@runfusion/fusion 0.23.0 → 0.25.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 +27921 -21003
- package/dist/client/assets/AgentDetailView-BwJaLqZh.css +1 -0
- package/dist/client/assets/AgentDetailView-ZbHEbYRT.js +18 -0
- package/dist/client/assets/AgentsView-B3jYk8Kt.js +29 -0
- package/dist/client/assets/{AgentsView-DSGQWObq.css → AgentsView-CV3vm7Qk.css} +1 -1
- package/dist/client/assets/ChatView-DhPkiEGs.js +1 -0
- package/dist/client/assets/ChatView-DwJAd5G1.css +1 -0
- package/dist/client/assets/{DevServerView-C9lzHrcT.js → DevServerView-DyGDEiBP.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-aVdFaV37.js → DirectoryPicker-D5UIeIl6.js} +1 -1
- package/dist/client/assets/{DocumentsView-DIpg3NSP.js → DocumentsView-DNHu1T8K.js} +1 -1
- package/dist/client/assets/{DocumentsView-BrhyOdeE.css → DocumentsView-gv4zG3aT.css} +1 -1
- package/dist/client/assets/EvalsView-CUNJ1TLc.css +1 -0
- package/dist/client/assets/EvalsView-CpRobtDi.js +1 -0
- package/dist/client/assets/{agentSkills-DDHJnrkn.css → ExperimentalAgentOnboardingModal-B-APN_lM.css} +1 -1
- package/dist/client/assets/ExperimentalAgentOnboardingModal-DOY_oZi7.js +499 -0
- package/dist/client/assets/InsightsView-B0J4mhzV.css +1 -0
- package/dist/client/assets/InsightsView-vp0RE8Mg.js +11 -0
- package/dist/client/assets/MemoryView-PSc5lGJt.js +2 -0
- package/dist/client/assets/MemoryView-zaXewZzi.css +1 -0
- package/dist/client/assets/NodesView-DMj6HGeC.js +14 -0
- package/dist/client/assets/NodesView-DT4pXowv.css +1 -0
- package/dist/client/assets/{PiExtensionsManager-Buopv-jb.js → PiExtensionsManager-DL_QcN56.js} +2 -2
- package/dist/client/assets/PluginManager-BtYKm8IT.js +1 -0
- package/dist/client/assets/PluginManager-DtRQXia5.css +1 -0
- package/dist/client/assets/{ResearchView-_BHXUv2j.js → ResearchView-BhWqfdV0.js} +1 -1
- package/dist/client/assets/SettingsModal-BAgB4_AR.js +31 -0
- package/dist/client/assets/SettingsModal-CUCyaAyE.js +1 -0
- package/dist/client/assets/SettingsModal-DzsLquBu.css +1 -0
- package/dist/client/assets/SetupWizardModal-BKscasuh.js +1 -0
- package/dist/client/assets/{SkillsView-hDpTBdFT.js → SkillsView-BdELqTy7.js} +1 -1
- package/dist/client/assets/TodoView-Cx9cVhq7.css +1 -0
- package/dist/client/assets/TodoView-DFNGBDNV.js +6 -0
- package/dist/client/assets/{folder-open-usZkXdq2.js → folder-open-k1xmUMyr.js} +1 -1
- package/dist/client/assets/index-Qq2JOOWx.css +1 -0
- package/dist/client/assets/index-TFYXEVpn.js +692 -0
- package/dist/client/assets/projectDetection-G3XuxD2X.js +1 -0
- package/dist/client/assets/{star-BAT_ObKE.js → star-ne32r3Y4.js} +1 -1
- package/dist/client/assets/{upload-BC2YKNEV.js → upload-MS-2Gx53.js} +1 -1
- package/dist/client/assets/{users-Dkd4rtrN.js → users-C519GSjH.js} +1 -1
- package/dist/client/index.html +12 -20
- package/dist/client/theme-data.css +106 -0
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/extension.js +15395 -9935
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +216 -0
- package/dist/plugins/fusion-plugin-cursor-runtime/manifest.json +6 -0
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +11 -0
- package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +30 -0
- package/dist/plugins/fusion-plugin-dependency-graph/manifest.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +3 -26
- package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +136684 -0
- package/dist/plugins/fusion-plugin-droid-runtime/manifest.json +13 -0
- package/dist/plugins/fusion-plugin-droid-runtime/mcp-schema-server.cjs +49 -0
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +11 -0
- package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +68 -71
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +137 -53
- package/dist/plugins/fusion-plugin-openclaw-runtime/mcp-schema-server.cjs +59 -0
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +155 -109
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/manifest.json +33 -0
- package/dist/plugins/fusion-plugin-reports/package.json +26 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/manifest.test.ts +51 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/review-panel.test.ts +166 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/settings.test.ts +157 -0
- package/dist/plugins/fusion-plugin-reports/src/index.ts +87 -0
- package/dist/plugins/fusion-plugin-reports/src/report-schema.ts +38 -0
- package/dist/plugins/fusion-plugin-reports/src/review-panel.ts +294 -0
- package/dist/plugins/fusion-plugin-reports/src/review-types.ts +75 -0
- package/dist/plugins/fusion-plugin-reports/src/settings.ts +105 -0
- package/dist/plugins/fusion-plugin-reports/src/store/__tests__/report-schema.test.ts +66 -0
- package/dist/plugins/fusion-plugin-reports/src/store/__tests__/report-store.test.ts +177 -0
- package/dist/plugins/fusion-plugin-reports/src/store/report-store.ts +341 -0
- package/dist/plugins/fusion-plugin-reports/src/store/report-types.ts +77 -0
- package/dist/plugins/fusion-plugin-roadmap/manifest.json +16 -0
- package/dist/plugins/fusion-plugin-roadmap/package.json +48 -0
- package/dist/plugins/fusion-plugin-roadmap/src/__tests__/api-client.test.ts +101 -0
- package/dist/plugins/fusion-plugin-roadmap/src/__tests__/index.test.ts +92 -0
- package/dist/plugins/fusion-plugin-roadmap/src/__tests__/roadmap-routes.test.ts +48 -0
- package/dist/plugins/fusion-plugin-roadmap/src/__tests__/roadmap-suggestions.test.ts +31 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/RoadmapsView.css +1299 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/RoadmapsView.tsx +2559 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/__tests__/RoadmapsView.test.tsx +1144 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/__tests__/useRoadmaps.test.ts +1756 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/api.ts +70 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/test-setup.ts +7 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/types.ts +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useConfirm.ts +8 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useRoadmaps.ts +1188 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard/useViewportMode.ts +20 -0
- package/dist/plugins/fusion-plugin-roadmap/src/dashboard-view.tsx +6 -0
- package/dist/plugins/fusion-plugin-roadmap/src/index.ts +74 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-routes.ts +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-schema.ts +41 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-suggestions.d.ts +15 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-suggestions.ts +15 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.d.ts +283 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.js +21 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/roadmap-types.ts +310 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.d.ts +5 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.js +361 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-routes.ts +408 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.d.ts +68 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.js +300 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/routes/roadmap-suggestions.ts +381 -0
- package/dist/plugins/fusion-plugin-roadmap/src/server/index.d.ts +3 -0
- package/dist/plugins/fusion-plugin-roadmap/src/server/index.ts +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-handoff.test.ts +445 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-ordering.test.ts +334 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/__tests__/roadmap-store.test.ts +1318 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-handoff.ts +163 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.d.ts +37 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.js +188 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-ordering.ts +311 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.d.ts +299 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.d.ts.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.js +765 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.js.map +1 -0
- package/dist/plugins/fusion-plugin-roadmap/src/store/roadmap-store.ts +1001 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/manifest.json +8 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +34 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/auth-state.test.ts +99 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/connection.test.ts +145 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/index.test.ts +216 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/__tests__/reply.test.ts +52 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/auth-state.ts +89 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/connection.ts +253 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/index.ts +262 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/qrcode.d.ts +1 -0
- package/dist/plugins/fusion-plugin-whatsapp-chat/src/reply.ts +37 -0
- package/package.json +2 -2
- package/skill/fusion/SKILL.md +2 -2
- package/skill/fusion/references/engine-tools.md +3 -0
- package/skill/fusion/references/extension-tools.md +39 -0
- package/skill/fusion/references/fusion-capabilities.md +3 -0
- package/dist/client/assets/AgentDetailView-C1XceMgi.js +0 -18
- package/dist/client/assets/AgentDetailView-CeO_1MK7.css +0 -1
- package/dist/client/assets/AgentsView-Deh125ss.js +0 -527
- package/dist/client/assets/ChatView-7D_RQDqT.js +0 -1
- package/dist/client/assets/InsightsView-AWo5o_81.css +0 -1
- package/dist/client/assets/InsightsView-jKjEFAx_.js +0 -11
- package/dist/client/assets/MemoryView-DiajLXby.css +0 -1
- package/dist/client/assets/MemoryView-nXlTqebk.js +0 -2
- package/dist/client/assets/NodesView-Di2SvOhg.js +0 -14
- package/dist/client/assets/NodesView-fXqDk9ur.css +0 -1
- package/dist/client/assets/PluginManager-B9-NbQ8f.js +0 -1
- package/dist/client/assets/PluginManager-C1DbPaar.css +0 -1
- package/dist/client/assets/RoadmapsView-DHWjUoc8.js +0 -6
- package/dist/client/assets/RoadmapsView-DdGlfuu-.css +0 -1
- package/dist/client/assets/SettingsModal-C89Ikhfm.js +0 -1
- package/dist/client/assets/SettingsModal-DHitIpsa.css +0 -1
- package/dist/client/assets/SettingsModal-DR_yirvK.js +0 -31
- package/dist/client/assets/SetupWizardModal-BtDMY9pa.js +0 -1
- package/dist/client/assets/agentSkills-B-w5wFHh.js +0 -1
- package/dist/client/assets/index-Bc6ZdGMz.css +0 -1
- package/dist/client/assets/index-D__RMku8.js +0 -694
- package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.css +0 -141
- package/dist/plugins/fusion-plugin-dependency-graph/src/DependencyGraphView.tsx +0 -428
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/DependencyGraphView.test.tsx +0 -261
- package/dist/plugins/fusion-plugin-dependency-graph/src/__tests__/storage.test.ts +0 -41
- package/dist/plugins/fusion-plugin-dependency-graph/src/index.ts +0 -25
- package/dist/plugins/fusion-plugin-dependency-graph/src/storage.ts +0 -22
|
@@ -1,694 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-C1XceMgi.js","assets/vendor-react-K0fH_qHe.js","assets/star-BAT_ObKE.js","assets/agentSkills-B-w5wFHh.js","assets/agentSkills-DDHJnrkn.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-CeO_1MK7.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-BtDMY9pa.js","assets/DirectoryPicker-aVdFaV37.js","assets/folder-open-usZkXdq2.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-DR_yirvK.js","assets/SettingsModal-C89Ikhfm.js","assets/SettingsModal-DHitIpsa.css","assets/users-Dkd4rtrN.js","assets/SettingsModal-BNSrO1M9.css","assets/AgentsView-Deh125ss.js","assets/upload-BC2YKNEV.js","assets/AgentsView-DSGQWObq.css","assets/DocumentsView-DIpg3NSP.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-jKjEFAx_.js","assets/InsightsView-AWo5o_81.css","assets/ResearchView-_BHXUv2j.js","assets/ResearchView-BzCcDAS4.css","assets/NodesView-Di2SvOhg.js","assets/NodesView-fXqDk9ur.css","assets/ChatView-7D_RQDqT.js","assets/RoadmapsView-DHWjUoc8.js","assets/RoadmapsView-DdGlfuu-.css","assets/SkillsView-hDpTBdFT.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-nXlTqebk.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-C9lzHrcT.js","assets/DevServerView-DlZpuAnj.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as i,j as t,R as ol,a as ha,g as Nf,c as _x}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"]'))a(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"&&a(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 a(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 Sf=(...e)=>e.filter((n,s,a)=>!!n&&n.trim()!==""&&a.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 Mx=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 Ax=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(n,s,a)=>a?a.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 Tu=e=>{const n=Ax(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 Xl={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 Px=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},Tx=i.createContext({}),Rx=()=>i.useContext(Tx),Ix=i.forwardRef(({color:e,size:n,strokeWidth:s,absoluteStrokeWidth:a,className:r="",children:o,iconNode:l,...c},d)=>{const{size:u=24,strokeWidth:m=2,absoluteStrokeWidth:h=!1,color:f="currentColor",className:p=""}=Rx()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...Xl,width:n??u??Xl.width,height:n??u??Xl.height,stroke:e??f,strokeWidth:g,className:Sf("lucide",p,r),...!o&&!Px(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,v])=>i.createElement(x,v)),...Array.isArray(o)?o:[o]])});/**
|
|
33
|
-
* @license lucide-react v1.7.0 - ISC
|
|
34
|
-
*
|
|
35
|
-
* This source code is licensed under the ISC license.
|
|
36
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
-
*/const Qe=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(Ix,{ref:o,iconNode:n,className:Sf(`lucide-${Mx(Tu(e))}`,`lucide-${e}`,a),...r}));return s.displayName=Tu(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 $x=[["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"}]],Ws=Qe("activity",$x);/**
|
|
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 Dx=[["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"}]],Lx=Qe("archive-restore",Dx);/**
|
|
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 Ox=[["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"}]],ao=Qe("archive",Ox);/**
|
|
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 Fx=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],ro=Qe("arrow-down",Fx);/**
|
|
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 zx=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],ka=Qe("arrow-left",zx);/**
|
|
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 Ux=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],oo=Qe("arrow-right",Ux);/**
|
|
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 Bx=[["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"}]],Cf=Qe("arrow-up-down",Bx);/**
|
|
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 Hx=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],fa=Qe("arrow-up",Hx);/**
|
|
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 qx=[["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"}]],Vx=Qe("book-open",qx);/**
|
|
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 Wx=[["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"}]],zn=Qe("bot",Wx);/**
|
|
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 Kx=[["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"}]],dd=Qe("box",Kx);/**
|
|
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 Gx=[["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"}]],Yr=Qe("brain",Gx);/**
|
|
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 Jx=[["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"}]],Ef=Qe("calendar",Jx);/**
|
|
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 Yx=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Qx=Qe("check-check",Yx);/**
|
|
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 Xx=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],os=Qe("check",Xx);/**
|
|
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 Zx=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],cn=Qe("chevron-down",Zx);/**
|
|
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 ev=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],Ml=Qe("chevron-left",ev);/**
|
|
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 tv=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],Un=Qe("chevron-right",tv);/**
|
|
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 nv=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],mi=Qe("chevron-up",nv);/**
|
|
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 sv=[["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=Qe("circle-alert",sv);/**
|
|
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 iv=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Gn=Qe("circle-check-big",iv);/**
|
|
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 av=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],Al=Qe("circle-dot",av);/**
|
|
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 rv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]],ov=Qe("circle-plus",rv);/**
|
|
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 lv=[["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"}]],ud=Qe("circle-question-mark",lv);/**
|
|
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 cv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],dv=Qe("circle-stop",cv);/**
|
|
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 uv=[["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"}]],lo=Qe("circle-x",uv);/**
|
|
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 mv=[["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"}]],hv=Qe("clipboard-list",mv);/**
|
|
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 pv=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],zi=Qe("clock",pv);/**
|
|
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 fv=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],_f=Qe("code",fv);/**
|
|
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 gv=[["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"}]],Ru=Qe("columns-3",gv);/**
|
|
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 bv=[["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"}]],ta=Qe("copy",bv);/**
|
|
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 xv=[["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"}]],Mf=Qe("cpu",xv);/**
|
|
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 vv=[["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"}]],yv=Qe("download",vv);/**
|
|
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 wv=[["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"}]],kv=Qe("ellipsis-vertical",wv);/**
|
|
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 jv=[["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"}]],md=Qe("ellipsis",jv);/**
|
|
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 Nv=[["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"}]],Af=Qe("external-link",Nv);/**
|
|
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 Sv=[["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"}]],Qd=Qe("eye-off",Sv);/**
|
|
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 Cv=[["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"}]],ur=Qe("eye",Cv);/**
|
|
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 Ev=[["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"}]],ci=Qe("file-code",Ev);/**
|
|
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 _v=[["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"}]],hd=Qe("file-diff",_v);/**
|
|
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 Mv=[["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"}]],Av=Qe("file-minus",Mv);/**
|
|
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 Pv=[["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"}]],Pf=Qe("file-pen",Pv);/**
|
|
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 Tv=[["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"}]],Rv=Qe("file-plus",Tv);/**
|
|
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 Iv=[["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"}]],$v=Qe("file-question-mark",Iv);/**
|
|
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 Dv=[["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"}]],na=Qe("file-text",Dv);/**
|
|
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 Lv=[["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"}]],Ov=Qe("file-type",Lv);/**
|
|
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 Fv=[["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"}]],Tf=Qe("file",Fv);/**
|
|
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 zv=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528",key:"1jaruq"}]],Uv=Qe("flag",zv);/**
|
|
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 Bv=[["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"}]],pd=Qe("folder-git-2",Bv);/**
|
|
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 Hv=[["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"}]],Iu=Qe("folder-root",Hv);/**
|
|
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 qv=[["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"}]],vs=Qe("folder",qv);/**
|
|
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 Vv=[["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"}]],ll=Qe("funnel",Vv);/**
|
|
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 Wv=[["path",{d:"M15 6a9 9 0 0 0-9 9V3",key:"1cii5b"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}]],zs=Qe("git-branch",Wv);/**
|
|
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 Kv=[["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"}]],co=Qe("git-commit-horizontal",Kv);/**
|
|
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 Gv=[["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"}]],Rf=Qe("git-merge",Gv);/**
|
|
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 Jv=[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]],Vs=Qe("git-pull-request",Jv);/**
|
|
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 Yv=[["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"}]],Pl=Qe("globe",Yv);/**
|
|
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 Qv=[["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"}]],Tl=Qe("grid-3x3",Qv);/**
|
|
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 Xv=[["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"}]],Rl=Qe("grip-vertical",Xv);/**
|
|
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 Zv=[["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"}]],ey=Qe("hard-drive",Zv);/**
|
|
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 ty=[["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"}]],ny=Qe("heart",ty);/**
|
|
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 sy=[["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"}]],Qr=Qe("history",sy);/**
|
|
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 iy=[["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"}]],Lr=Qe("inbox",iy);/**
|
|
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 ay=[["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"}]],If=Qe("key",ay);/**
|
|
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 ry=[["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"}]],oy=Qe("keyboard",ry);/**
|
|
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 ly=[["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"}]],ga=Qe("layers",ly);/**
|
|
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 cy=[["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"}]],sa=Qe("layout-grid",cy);/**
|
|
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 dy=[["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"}]],hi=Qe("lightbulb",dy);/**
|
|
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 uy=[["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"}]],Qa=Qe("link",uy);/**
|
|
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 my=[["path",{d:"M13 5h8",key:"a7qcls"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 19h8",key:"c3s6r1"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}]],fd=Qe("list-checks",my);/**
|
|
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 hy=[["path",{d:"M11 5h10",key:"1cz7ny"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 19h10",key:"11t30w"}],["path",{d:"M4 4h1v5",key:"10yrso"}],["path",{d:"M4 9h2",key:"r1h2o0"}],["path",{d:"M6.5 20H3.4c0-1 2.6-1.925 2.6-3.5a1.5 1.5 0 0 0-2.6-1.02",key:"xtkcd5"}]],py=Qe("list-ordered",hy);/**
|
|
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 fy=[["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"}]],gy=Qe("list-plus",fy);/**
|
|
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 by=[["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"}]],Il=Qe("list-tree",by);/**
|
|
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 xy=[["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"}]],gd=Qe("list",xy);/**
|
|
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 vy=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],xt=Qe("loader-circle",vy);/**
|
|
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 yy=[["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"}]],$l=Qe("lock",yy);/**
|
|
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 wy=[["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=Qe("mail",wy);/**
|
|
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 ky=[["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"}]],bd=Qe("map",ky);/**
|
|
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 jy=[["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"}]],Dl=Qe("maximize-2",jy);/**
|
|
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 Ny=[["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"}]],Sy=Qe("message-square-plus",Ny);/**
|
|
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 Cy=[["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"}]],Oi=Qe("message-square",Cy);/**
|
|
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 Ey=[["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"}]],uo=Qe("minimize-2",Ey);/**
|
|
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 _y=[["path",{d:"M5 12h14",key:"1ays0h"}]],My=Qe("minus",_y);/**
|
|
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 Ay=[["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"}]],Xa=Qe("monitor",Ay);/**
|
|
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 Py=[["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"}]],Ty=Qe("move",Py);/**
|
|
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 Ry=[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]],Iy=Qe("network",Ry);/**
|
|
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 $y=[["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"}]],xd=Qe("package",$y);/**
|
|
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 Dy=[["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"}]],$f=Qe("paperclip",Dy);/**
|
|
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 Ly=[["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"}]],di=Qe("pause",Ly);/**
|
|
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 Oy=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],Ss=Qe("pencil",Oy);/**
|
|
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 Fy=[["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"}]],ls=Qe("play",Fy);/**
|
|
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 zy=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],_n=Qe("plus",zy);/**
|
|
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 Uy=[["path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",key:"w46dr5"}]],By=Qe("puzzle",Uy);/**
|
|
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 Hy=[["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"}]],Df=Qe("radio",Hy);/**
|
|
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 qy=[["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"}]],hs=Qe("refresh-cw",qy);/**
|
|
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 Vy=[["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"}]],$u=Qe("rocket",Vy);/**
|
|
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 Wy=[["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"}]],Ky=Qe("rotate-ccw",Wy);/**
|
|
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 Gy=[["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"}]],Jy=Qe("rotate-cw",Gy);/**
|
|
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 Yy=[["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"}]],Lf=Qe("save",Yy);/**
|
|
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 Qy=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Li=Qe("search",Qy);/**
|
|
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 Xy=[["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"}]],pa=Qe("send",Xy);/**
|
|
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 Zy=[["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"}]],Xr=Qe("server",Zy);/**
|
|
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 ew=[["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"}]],qr=Qe("settings",ew);/**
|
|
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 tw=[["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"}]],nw=Qe("shield-alert",tw);/**
|
|
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 sw=[["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"}]],iw=Qe("shield",sw);/**
|
|
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 aw=[["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"}]],rw=Qe("skull",aw);/**
|
|
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 ow=[["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"}]],bs=Qe("sparkles",ow);/**
|
|
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 lw=[["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"}]],Xd=Qe("square-check-big",lw);/**
|
|
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 cw=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Si=Qe("square",cw);/**
|
|
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 dw=[["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"}]],Ms=Qe("target",dw);/**
|
|
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 uw=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Fi=Qe("terminal",uw);/**
|
|
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 mw=[["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"}]],cl=Qe("text-wrap",mw);/**
|
|
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 hw=[["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"}]],En=Qe("trash-2",hw);/**
|
|
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 pw=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],fw=Qe("trending-up",pw);/**
|
|
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 gw=[["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"}]],Ll=Qe("triangle-alert",gw);/**
|
|
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 bw=[["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"}]],Du=Qe("unlink",bw);/**
|
|
618
|
-
* @license lucide-react v1.7.0 - ISC
|
|
619
|
-
*
|
|
620
|
-
* This source code is licensed under the ISC license.
|
|
621
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
622
|
-
*/const xw=[["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"}]],$a=Qe("user",xw);/**
|
|
623
|
-
* @license lucide-react v1.7.0 - ISC
|
|
624
|
-
*
|
|
625
|
-
* This source code is licensed under the ISC license.
|
|
626
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
627
|
-
*/const vw=[["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"}]],Of=Qe("webhook",vw);/**
|
|
628
|
-
* @license lucide-react v1.7.0 - ISC
|
|
629
|
-
*
|
|
630
|
-
* This source code is licensed under the ISC license.
|
|
631
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
632
|
-
*/const yw=[["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"}]],dl=Qe("workflow",yw);/**
|
|
633
|
-
* @license lucide-react v1.7.0 - ISC
|
|
634
|
-
*
|
|
635
|
-
* This source code is licensed under the ISC license.
|
|
636
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
637
|
-
*/const ww=[["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"}]],Lu=Qe("wrench",ww);/**
|
|
638
|
-
* @license lucide-react v1.7.0 - ISC
|
|
639
|
-
*
|
|
640
|
-
* This source code is licensed under the ISC license.
|
|
641
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
642
|
-
*/const kw=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],nn=Qe("x",kw);/**
|
|
643
|
-
* @license lucide-react v1.7.0 - ISC
|
|
644
|
-
*
|
|
645
|
-
* This source code is licensed under the ISC license.
|
|
646
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
647
|
-
*/const jw=[["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"}]],us=Qe("zap",jw),vd="fusion:version-reload",yd="fusion:version-update";let Zd=!0;function Zl(e){Zd=e}function Nw(){try{if(sessionStorage.getItem(yd))return sessionStorage.removeItem(yd),!0}catch{}return!1}function eu(e){if(sessionStorage.getItem(vd)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(vd,"1"),!Zd){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function Sw(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 Cw(e){return Sw(e)?(eu(`chunk load error: ${e?.message??e}`),!0):!1}async function Ew(){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}}async function _w(){try{const e=new AbortController,n=setTimeout(()=>e.abort(),3e3),s=await fetch("/api/settings",{headers:{Accept:"application/json"},signal:e.signal});clearTimeout(n),s.ok&&(await s.json()).autoReloadOnVersionChange===!1&&(Zd=!1)}catch{}}const Mw=6e4;let Ou=0,ec=!1;async function tc(){if(!(ec||document.visibilityState!=="visible")&&!(Date.now()-Ou<Mw)){Ou=Date.now(),ec=!0;try{const e=await Ew();if(e&&e!=="8bdac36c5-0e3ff4bd"){try{sessionStorage.setItem(yd,"1")}catch{}eu(`build version changed: 8bdac36c5-0e3ff4bd -> ${e}`)}}finally{ec=!1}}}function Aw(){_w(),window.setTimeout(()=>sessionStorage.removeItem(vd),5e3),document.addEventListener("visibilitychange",()=>{tc()}),window.addEventListener("focus",()=>{tc()}),window.setTimeout(()=>void tc(),2e3)}class mo extends i.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),!Cw(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",a=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(Ll,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:a}),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 Es({children:e,onError:n}){return t.jsx(mo,{level:"page",onError:n,children:e})}function da({children:e,onError:n}){return t.jsx(mo,{level:"modal",onError:n,children:e})}function Pw({children:e,onError:n}){return t.jsx(mo,{level:"root",onError:n,children:e})}const Tw="modulepreload",Rw=function(e){return"/"+e},Fu={},Rn=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.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]"),d=c?.nonce||c?.getAttribute("nonce");r=l(s.map(u=>{if(u=Rw(u),u in Fu)return;Fu[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":Tw,m||(f.as="script"),f.crossOrigin="",f.href=u,d&&f.setAttribute("nonce",d),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 ${u}`)))})}))}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)})},tu="fn.authToken",zu="token",Iw="fn_token";let Wa,Uu=!1,ul=!1;const wd="fn:auth-token-recovery-required";function $w(){try{const e=window.localStorage.getItem(tu);return e&&e.length>0?e:void 0}catch{return}}function Ff(e){try{window.localStorage.setItem(tu,e)}catch{}}function Dw(){if(!(Uu||typeof window>"u")){Uu=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(zu);if(!n)return;Ff(n),e.searchParams.delete(zu);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Za(){if(Wa!==void 0)return Wa;const e=Dw();if(e)return Wa=e,e;const n=$w();if(n)return Wa=n,n}function Lw(e){Wa=e,ul=!1,Ff(e)}function Ow(){Wa=void 0,ul=!1;try{window.localStorage.removeItem(tu)}catch{}}function Bu(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function Fw(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function zw(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!Fw(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Bu(e.protocol)===Bu(n.protocol);return s&&a&&r}function Uw(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 _i(e){const n=Za();if(!n||typeof window>"u")return e;const s=Uw(e);return!s||!zw(s.parsed)?e:(s.parsed.searchParams.set(Iw,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Mi(e){const n=Za();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Bw(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Hw(){typeof window>"u"||ul||(ul=!0,window.dispatchEvent(new CustomEvent(wd)))}async function qw(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const a=await n.json();Bw(a)&&Hw()}catch{}}function Vw(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Za();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=Za(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const d=new URL(o,window.location.origin);return d.origin!==window.location.origin?!1:d.pathname.startsWith("/api/")||d.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,a);const c=new Headers(a?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...a,headers:c}).then(d=>(qw(d),d))}}class zf extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function Ww(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Cs(e){return`/api${e}`}async function R(e,n={}){const s=Cs(e),a=Za(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),Mi(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(),d=l.includes("application/json");if(l.includes("text/html")||Ww(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!d){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 zf(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function fO(){return R("/health")}function gO(){return R("/updates/check")}function Kw(e,n,s,a,r){const o=new URLSearchParams;e!==void 0&&o.set("limit",String(e)),n!==void 0&&o.set("offset",String(n)),s&&o.set("projectId",s),a&&o.set("q",a),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return R(`/tasks${l}`)}async function er(e,n){const a=Cs(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:Mi({"Content-Type":"application/json"})}),l=await o.json();if(o.ok)return l;if(r===2)throw new Error(l.error||"Request failed")}throw new Error("Request failed")}function ml(e,n){const{title:s,description:a,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:d,modelPresetId:u,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:N,source:E,branch:w,baseBranch:j}=e;return R(V("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:a,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:d,modelPresetId:u,modelProvider:m,modelId:h,validatorModelProvider:f,validatorModelId:p,planningModelProvider:g,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:N,source:E,branch:w,baseBranch:j})})}function Ci(e,n,s){return R(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Gw(e,n,s,a,r,o,l,c,d){return R(V("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Jw(e,n,s,a){return R(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Yw(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return R(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Qw(e,n){return R(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Xw(e,n){return R(V(`/tasks/${e}/retry`,n),{method:"POST"})}function Zw(e,n){return R(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function ek(e,n){return R(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Uf(e,n){return R(V(`/tasks/${e}/pause`,n),{method:"POST"})}function tk(e,n){return R(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function nk(e,n){return R(V(`/tasks/${e}/archive`,n),{method:"POST"})}function sk(e,n){return R(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function ik(e){return R(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function ak(e,n){return R(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function rk(e,n){return R(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function ok(e){return R(V("/config",e))}function Ol(e){return R(V("/settings",e))}function jo(e,n){return R(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function lk(e){return R(V("/update-check",e))}function bO(e){return R(V("/remote/settings",e))}function xO(e,n){return R(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function vO(e){return R(V("/remote/status",e))}function yO(e){return R(V("/remote/install-cloudflared",e),{method:"POST"})}function wO(e){return R(V("/remote/tunnel/start",e),{method:"POST"})}function kO(e){return R(V("/remote/tunnel/stop",e),{method:"POST"})}function jO(e){return R(V("/remote/tunnel/kill-external",e),{method:"POST"})}function NO(e){return R(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function SO(e,n){return R(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Bf(e,n,s){const a=new URLSearchParams;e&&a.set("format",e),a.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&a.set("ttlMs",String(s));const r=a.toString();return r?`?${r}`:""}function CO(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=Bf(null,s,a);return R(V(`/remote/url${r}`,n))}function EO(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=Bf(e,a,r);return R(V(`/remote/qr${o}`,s))}function _O(e){return R(V("/memory",e))}function MO(e,n){return R(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function AO(e){return R(V("/memory/files",e))}function PO(e,n){const s=`path=${encodeURIComponent(e)}`;return R(V(`/memory/file?${s}`,n))}function TO(e,n,s){return R(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function RO(e,n){let s,a=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:a=r}return R(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function IO(e){return R(V("/memory/dream",e),{method:"POST"})}function $O(e){return R(V("/memory/insights",e))}function DO(e,n){return R(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function LO(e){return R(V("/memory/extract",e),{method:"POST"})}function OO(e){return R(V("/memory/audit",e))}function FO(e){return R(V("/memory/stats",e))}function zO(e){return R(V("/memory/backend",e))}function UO(e){return R(V("/memory/install-qmd",e),{method:"POST"})}function BO(e,n){return R(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ja(){return R("/settings/global")}function $n(e){return R("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function HO(e){return R(V("/settings/scopes",e))}function qO(e){return R(V("/settings/pi-extensions",e))}function VO(e,n){return R(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function WO(e,n,s){return R(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function KO(){return R("/pi-settings")}async function GO(e){return R("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function JO(e){return R("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function YO(e){return R(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Fl(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Cs(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:Mi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function ck(e,n,s){return R(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Hu(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Cs(o),{headers:Mi()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),d=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,u=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:d,hasMore:u}}function dk(e,n,s,a){return R(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function uk(e,n,s){return R(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function mk(e,n){return R(V(`/tasks/${e}/documents`,n))}function hk(e,n,s){return R(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function QO(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 a=s.toString(),r=`/documents${a?`?${a}`:""}`;return R(V(r,n))}function XO(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return R(V(r,e))}function qu(e,n,s,a,r){return R(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function pk(e,n,s){return R(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function fk(e,n,s){return R(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function gk(e,n,s){return R(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function bk(e,n){return R(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function xk(e,n,s){return R(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function $s(){return R("/models")}function vk(){return R("/usage")}function yk(){return R("/providers/claude-cli/status")}function wk(){return R("/system/fn-binary/status")}function kk(){return R("/system/fn-binary/install",{method:"POST"})}function jk(){return R("/providers/droid-cli/status")}function Nk(){return R("/providers/llama-cpp/status")}async function ZO(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return R(`/providers/hermes/status${n}`)}async function eF(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await R(`/providers/hermes/profiles${n}`)).profiles??[]}async function tF(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return R(`/providers/openclaw/status${n}`)}async function nF(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),R(`/providers/paperclip/status?${n.toString()}`)}async function sF(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await R(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function iF(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await R(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function aF(e){return R("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function rF(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return R(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function oF(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 R(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function lF(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await R(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function cF(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return R(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Sk(e){return R("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Ck(e){return R("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Ek(e){return R("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function _k(){const n=(await R("/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(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function Mk(e){return R("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function dF(e,n){const s=n,a={...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 R(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function uF(e){return R(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function Ak(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return Mk({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 Zr(){return R("/auth/status")}function Pk(e){return R("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function Tk(e,n){return R("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function Rk(e){return R("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Ik(e){return R("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function $k(e,n){return R("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Dk(e){return R("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Lk(e,n,s,a){return R("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function Ok(e,n,s,a){return R(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Fk(e,n,s){return R("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function zk(e,n,s,a){return R(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function Uk(e){return R(V("/git/remotes",e))}function Bk(e){return R(V("/git/remotes/detailed",e))}function Hk(e,n,s){return R(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function qk(e,n){return R(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Vk(e,n,s){return R(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function Wk(e,n,s){return R(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Kk(e,n,s){return R(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Gk(e,n){return R(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function Jk(e,n){return(await R(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function No(e,n,s,a){return R(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Vu(e,n){return R(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Yk(e){return R(V("/terminal/sessions",e))}function oi(e){return R(V("/git/status",e))}function Qk(e,n){const s=e?`?limit=${e}`:"";return R(V(`/git/commits${s}`,n))}function hl(e,n){return R(V(`/git/commits/${e}/diff`,n))}function Xk(e){return R(V("/git/commits/ahead",e))}function Zk(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return R(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function wr(e){return R(V("/git/branches",e))}function ej(e,n,s){const a=`?limit=${n}`;return R(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function tj(e){return R(V("/git/worktrees",e))}function nj(e,n,s){return R(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function sj(e,n){return R(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Wu(e,n,s){const a=n?"?force=true":"";return R(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function ij(e,n){return R(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function aj(e){return R(V("/git/pull",e),{method:"POST"})}function rj(e){return R(V("/git/push",e),{method:"POST"})}function So(e){return R(V("/git/stashes",e))}function oj(e,n){return R(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function lj(e,n,s){return R(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function cj(e,n){return R(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function dj(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),R(V(`/git/diff/file?${a.toString()}`,s))}function Da(e){return R(V("/git/changes",e))}function Ku(e,n){return R(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function uj(e,n){return R(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Gu(e,n){return R(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function mj(e,n){return R(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function hj(e){return R(V("/workspaces",e))}function pj(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),R(`/files?${a.toString()}`)}function fj(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),R(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function gj(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),R(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function bj(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),R(`/files/search?${a.toString()}`)}function xj(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),R(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function vj(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),R(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function yj(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),R(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function wj(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),R(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Hf(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function kj(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function jj(e,n,s){return R(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Nj(e,n,s,a,r){return R(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function Ju(e,n,s,a){return R(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function Sj(e,n,s){return R(V(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Cj(e,n,s){return R(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Ej(e,n,s){return R(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function qf(e,n,s){return R(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function mF(e,n,s,a){return R(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function hF(e,n,s){return R(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function pF(e,n){return R(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function _j(e,n,s){return R(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Mj(e,n,s){return R(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Aj(e,n,s){return R(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const kd=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(kd))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Pj(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function mr(e,n,s={}){const a=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,d=null,u=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const x=Number.parseInt(g,10);return Number.isFinite(x)?d!==null&&x<=d?!1:(d=x,!0):!0},h=()=>{if(o)return;const p=Pj(e,d),g=new EventSource(_i(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))g.addEventListener(x,b=>{const y=b;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){u||(u=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=a){s.onFatalError?.("Connection lost");return}u=!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(),kd.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return kd.add(f),f}function Yu(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,a=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:a,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${a} (${l})`}}function tr(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",a=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:a,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:a,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function Tj(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 Rj(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>Tj(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Ij(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,a=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((u,m)=>({id:m+1,text:u,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(u=>u.id>r).slice(0,s),totalLines:o};const c=Math.max(o-a,0),d=Math.max(c-s,0);return{lines:l.slice(d,c),totalLines:o}}function Qu(e){return Array.isArray(e)?e.map(Yu):(e.candidates??[]).map(Yu)}async function $j(e){try{const n=await R(V("/dev-server/candidates",e));return Qu(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await R(V("/dev-server/detect",e));return Qu(s)}throw n}}function nu(e){return R(V("/dev-server/status",e)).then(tr)}async function fF(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 a=s.size>0?`?${s.toString()}`:"";try{const r=await R(V(`/dev-server/logs/history${a}`,n));return Rj(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await nu(n);return Ij(o.logs,e)}throw r}}function Dj(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return R(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(tr)}function Lj(e){return R(V("/dev-server/stop",e),{method:"POST"}).then(tr)}function Oj(e){return R(V("/dev-server/restart",e),{method:"POST"}).then(tr)}async function Fj(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await R(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return tr(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await R(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return tr(r)}throw a}}function gF(e){return Cs(V("/dev-server/logs/stream",e))}async function bF(e){try{return(await R(V("/devserver",e))).sessions??[]}catch{try{const n=await nu(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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function xF(e,n){try{return await R(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await nu(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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function vF(e,n){try{return await R(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Dj({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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function yF(e,n){try{return await R(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Lj(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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function wF(e,n){try{return await R(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Oj(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(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function kF(e,n,s){try{const a=await R(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await Fj({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function jF(e){try{return(await R(V("/devserver/detect",e))).candidates??[]}catch{try{return(await $j(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function NF(e,n){return Cs(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function ho(e,n,s=25e3){const a=setInterval(()=>{I1(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function zj(e,n){return Cs(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function Uj(e,n){return Cs(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function SF(e,n,s,a){const r=Uj(e,n),o=mr(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:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function Bj(e,n,s,a){const r=zj(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=mr(r,{onOpen:()=>{c(),o=ho(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function po(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const a=s.toString();return a?`${e}?${a}`:e}function Hj(e){return R(po("/routines",e))}function qj(e,n){return R(po("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Xu(e,n,s){return R(po(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function Vj(e,n){await R(po(`/routines/${e}`,n),{method:"DELETE"})}function Wj(e,n){return R(po(`/routines/${e}/trigger`,n),{method:"POST"})}function Zu(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 R(`/activity${s}`)}function Kj(e){const n=V("/activity",e);return R(n,{method:"DELETE"})}function fo(e){return R(V("/workflow-steps",e))}function em(e,n){return R(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function Gj(e,n,s){return R(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Jj(e,n){return R(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function tm(e,n){return R(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function Yj(e,n){return R(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Qj(){return R("/workflow-step-templates")}function Xj(){return R("/plugin-workflow-step-templates")}function Zj(e,n){return R(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function eo(e){return R(V("/scripts",e))}function eN(e,n,s){return R(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function tN(e,n){return R(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function Vf(e,n,s){return(await R(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Co={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 Wf(e){if(!(e instanceof Error))return Co.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Co.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Co.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Co.NETWORK}function nN(e,n){return R(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function sN(e,n,s){return R(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function iN(e,n){return Cs(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function aN(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=mr(iN(e,n),{onOpen:()=>{l(),r=ho(e,n)},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},subtasks:d=>{try{s.onSubtasks?.(JSON.parse(d.data))}catch(u){console.error("[subtasks] Failed to parse subtasks event:",u)}},error:d=>{try{const u=JSON.parse(d.data),m=typeof u=="string"&&u.length>0?u:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{l(),s.onError?.(d)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function rN(e,n,s,a){return R(V("/subtasks/create-tasks",a),{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 Kf(e,n,s){return R(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function oN(e,n,s){if(!n||n===s)return e;const a="/api",r=e.startsWith(a)?e.slice(a.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function zl(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=oN(e,s,a);return R(o,r)}function Na(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 a=s.size>0?`?${s.toString()}`:"";return R(`/agents${a}`)}function jd(e,n){return R(V(`/agents/${encodeURIComponent(e)}`,n))}function lN(e,n){return R(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function cN(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function CF(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Cs(V(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:Mi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function EF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function _F(e,n){return R(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function MF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function AF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function PF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function TF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function RF(e,n,s){const a=`path=${encodeURIComponent(n)}`;return R(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function IF(e,n,s,a){return R(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function dN(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function uN(e,n){return R(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $F(e,n,s){const a=new URLSearchParams;n!==void 0&&a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return R(`/agents/${encodeURIComponent(e)}/runs${r}`)}function DF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function LF(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function OF(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return R(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function FF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function mN(e){return R(V("/agents/stats",e))}function zF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function UF(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return R(`/agents/org-tree${a?`?${a}`:""}`)}function BF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function nm(e,n,s){return R(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function HF(e,n){return R(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function qF(){return R("/agents/companies")}function VF(e,n){return R(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function WF(e,n){return R(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function KF(e,n){return R(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function GF(e){return R(V("/backups",e))}function JF(e){return R(V("/backups",e),{method:"POST"})}function YF(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return R(a)}function QF(e,n,s){return R(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function sm(){return R("/projects/across-nodes")}function pl(){return R("/nodes")}function XF(){return R("/docker/nodes")}function ZF(e){return R(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function e3(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return R(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function t3(e){return R("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function hN(e){return R("/nodes",{method:"POST",body:JSON.stringify(e)})}function pN(e,n){return R(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function fN(e){return R(`/nodes/${encodeURIComponent(e)}/docker-config`)}function gN(e,n){return R(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function bN(e){return R(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function xN(e){return R(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function vN(e){const n=await R(`/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 n3(e,n,s,a){const r=s&&s!==a?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=Za();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return R(d)}function yN(e){return R("/projects",{method:"POST",body:JSON.stringify(e)})}function Gf(e){return R(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function im(e){return R(`/projects/${encodeURIComponent(e)}/health`)}function wN(e){return R(V("/executor/stats",e))}function kN(e){return R(V("/system-stats",e))}function jN(e){return R(V("/kill-vitest",e),{method:"POST"})}function am(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 R(`/activity-feed${s}`)}function NN(e){return R(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function SN(e){return R(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function s3(){return R("/global-concurrency")}function i3(e){return R("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function CN(e,n){return R(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Jf(e,n,s){const a=new URLSearchParams;n&&a.set("worktree",n),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return R(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function EN(e){return R(V("/missions",e))}function _N(e,n){return R(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function Yf(e,n){return R(V(`/missions/${encodeURIComponent(e)}`,n))}function MN(e,n,s){return R(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function AN(e,n){return R(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function PN(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return R(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function TN(e){return R(V("/missions/health",e))}function RN(e,n,s){return R(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function IN(e,n,s){return R(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $N(e,n){return R(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function DN(e,n,s){return R(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function LN(e,n,s){return R(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ON(e,n){return R(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function FN(e,n){return R(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function zN(e,n,s){return R(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function UN(e,n,s){return R(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function BN(e,n){return R(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function HN(e,n,s){return R(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function qN(e,n){return R(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function VN(e,n,s,a){return R(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function WN(e,n){return R(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function nc(e,n){return R(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function KN(e,n,s){return R(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function GN(e,n,s){return R(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function JN(e,n,s){return R(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function YN(e,n,s){return R(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function QN(e,n){return R(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function sc(e,n){return R(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function rm(e,n){return R(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function XN(e,n){return R(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function om(e,n){return R(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function ZN(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return R(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function e1(e,n){return R(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function t1(e,n){return R(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function n1(e,n){return R(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function s1(e,n){return R(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function i1(e,n,s){return R(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function a1(e,n,s){return R(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function r1(e,n,s,a){return R(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function o1(e,n,s){return R(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Qf(e,n,s){return R(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function l1(e,n,s){return R(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function c1(e,n,s,a){const r=Cs(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=mr(r,{onOpen:()=>{c(),o=ho(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function go(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function bo(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function d1(e,n){return R(go(e,"/start",n),{method:"POST"})}function u1(e,n,s,a){return R(go(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function m1(e,n,s,a){const r=Cs(go(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=mr(r,{onOpen:()=>{c(),o=ho(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function h1(e,n,s){return R(go(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function p1(e,n){return R(go(e,"/skip",n),{method:"POST"})}function f1(e,n){return R(bo(e,"/start",n),{method:"POST"})}function g1(e,n,s,a){return R(bo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function b1(e,n,s,a){const r=Cs(bo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=mr(r,{onOpen:()=>{c(),o=ho(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function x1(e,n,s){return R(bo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function v1(e,n){return R(bo(e,"/skip",n),{method:"POST"})}async function y1(e,n){try{return await R(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function a3(e){return R(V("/roadmaps",e))}function r3(e,n){return R(V("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function o3(e,n){return R(V(`/roadmaps/${encodeURIComponent(e)}`,n))}function l3(e,n,s){return R(V(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function c3(e,n){return R(V(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function d3(e,n,s){return R(V(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function u3(e,n,s){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function m3(e,n){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function h3(e,n,s){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function p3(e,n,s){return R(V(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function f3(e,n){return R(V(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function g3(e,n,s){return R(V(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function b3(e,n,s){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function x3(e,n,s,a){return R(V(`/roadmaps/features/${encodeURIComponent(e)}/move`,a),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function v3(e,n){return R(V(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function y3(e,n,s,a){return R(V(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,a),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function w3(e,n,s){return R(V(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function w1(e){return R(V("/todos",e))}function k1(e,n){const s={title:e};return R(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function j1(e,n,s){const a={title:n};return R(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function N1(e,n){return R(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function S1(e,n,s){const a={text:n};return R(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function C1(e,n,s){const a=n;return R(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function E1(e,n){return R(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _1(e,n,s){return R(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function nr(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function su(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const a=s.toString(),r=await fetch(Cs(`/ai-sessions${a?`?${a}`:""}`),{headers:Mi()});return r.ok?(await r.json()).sessions??[]:[]}async function M1(e){return R(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function A1(e){return R(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Ei(e){const n=await fetch(Cs(`/ai-sessions/${encodeURIComponent(e)}`),{headers:Mi()});return n.ok?n.json():null}async function P1(e,n){const s=await R(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function T1(e,n){return R(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function R1(e,n){return R(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Xf(e){await fetch(Cs(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:Mi()})}function I1(e,n){return R(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function $1(e,n,s){return R(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function D1(e,n){return R(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function L1(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 a=s.size>0?`?${s.toString()}`:"";return R(`/messages/inbox${a}`)}function O1(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 a=s.size>0?`?${s.toString()}`:"";return R(`/messages/outbox${a}`)}function Zf(e){return R(V("/messages/unread-count",e))}function F1(e,n){return R(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function z1(e,n){return R(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function U1(e){return R(V("/messages/read-all",e),{method:"POST"})}function B1(e,n){return R(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function H1(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return R(V(a,s))}function q1(e,n){return R(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function k3(e,n,s){const a=new URLSearchParams;a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return R(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function j3(e,n){return R(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function N3(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return R(`/agents/${encodeURIComponent(e)}/performance${r}`)}function S3(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.category&&a.set("category",n.category),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return R(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function C3(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function E3(e,n){return R(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function _3(e,n,s){return R(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function M3(e,n){return R(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function A3(e,n){return R(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function P3(e){return R(V("/plugins",e))}async function T3(e,n){return R(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function R3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function I3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function $3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function D3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function L3(e,n,s){return R(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function O3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function F3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function z3(e,n){return R(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function V1(e){return R(V("/plugins/ui-slots",e))}async function W1(e){return R(V("/plugins/dashboard-views",e))}async function U3(e){return R(V("/plugins/runtimes",e))}async function K1(e){return(await R(V("/skills/discovered",e))).skills}async function B3(e,n,s){return R(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function H3(e,n,s){const a=new URLSearchParams;e&&a.set("q",e),a.set("limit",String(n));const r=a.size>0?`?${a.toString()}`:"";return R(V(`/skills/catalog${r}`,s))}async function q3(e,n){return(await R(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function lm(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return R(`/chat/sessions${a?`?${a}`:""}`)}async function G1(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const a=e.modelProvider?.trim(),r=e.modelId?.trim();if(a&&!r||!a&&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),a&&r&&(o.set("modelProvider",a),o.set("modelId",r)),{session:(await R(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function J1(e,n){return R(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function Y1(e,n){return R(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function V3(e,n,s){return R(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function W3(e,n){return R(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ic(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return R(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Q1(e,n){return R(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function X1(e,n,s,a,r,o){const l=Cs(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1;const m=(h,f)=>{if(h)switch(h){case"thinking":try{s.onThinking?.(JSON.parse(f))}catch{s.onThinking?.(f)}break;case"text":try{s.onText?.(JSON.parse(f))}catch{s.onText?.(f)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(f))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(f))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(f))}catch{}break;case"done":u=!0;try{const p=JSON.parse(f);s.onDone?.({messageId:typeof p.messageId=="string"?p.messageId:"",...p.message&&typeof p.message=="object"?{message:p.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0;try{const p=JSON.parse(f);s.onError?.(p.message||p)}catch{s.onError?.(f||"Stream error")}break}};return(async()=>{try{const h=Array.isArray(a)&&a.length>0,f=h?(()=>{const E=new FormData;return E.append("content",n),a.forEach(w=>E.append("attachments",w)),E})():JSON.stringify({content:n}),p=await fetch(l,{method:"POST",headers:h?Mi():Mi({"Content-Type":"application/json"}),body:f,signal:c.signal});if(!p.ok){const E=await p.text();let w=`Request failed: ${p.status}`;try{w=JSON.parse(E).error||w}catch{}s.onError?.(w);return}if(!p.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const g=p.body.getReader(),x=new TextDecoder;let v="",b="",y=[];const S=(E,w=!1)=>{v+=E;const j=v.split(`
|
|
648
|
-
`);v=j.pop()||"",w&&v.length>0&&(j.push(v),v="");for(const _ of j){const D=_.endsWith("\r")?_.slice(0,-1):_;if(D.startsWith("event:"))b=D.slice(6).trim();else if(D.startsWith("data:")){const C=D.slice(5);y.push(C.startsWith(" ")?C.slice(1):C)}else if(D===""){const C=y.join(`
|
|
649
|
-
`);m(b,C),b="",y=[]}}if(w&&b&&y.length>0){const _=y.join(`
|
|
650
|
-
`);m(b,_),b="",y=[]}};for(;;){const{done:E,value:w}=await g.read();if(E){S(x.decode(),!0);break}S(x.decode(w,{stream:!0}))}const N=v.length>0||b.length>0||y.length>0;!u&&!d&&!N&&s.onError?.("Connection closed unexpectedly")}catch(h){if(h instanceof DOMException&&h.name==="AbortError"){d||s.onError?.("Connection aborted");return}if(d)return;s.onError?.(h instanceof Error?h.message:"Connection error")}})(),{close:()=>{d=!0,c.abort()},isConnected:()=>!d}}function K3(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 a=s.size>0?`?${s.toString()}`:"";return R(V(`/insights${a}`,n))}function G3(e,n){return R(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function J3(e,n){return R(V(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function Y3(e,n){return R(V(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function Q3(e="manual",n,s){return R(V("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function X3(e){return R(V("/insights/runs",e))}function Z3(e,n){return R(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function ez(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 a=s.size>0?`?${s.toString()}`:"";return R(V(`/research/runs${a}`,n))}function tz(e,n){return R(V("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function nz(e,n){return R(V(`/research/runs/${encodeURIComponent(e)}`,n))}function eg(e){if(e instanceof zf){const n=e.details?.code,s=typeof n=="string"?n:"INTERNAL_ERROR",a=typeof e.details?.setupHint=="string"?e.details.setupHint:void 0,r=typeof e.details?.retryable=="boolean"?e.details.retryable:void 0,o=e;throw o.researchCode=s,o.setupHint=a,o.retryable=r,o}throw e}async function sz(e,n){try{return await R(V(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){eg(s)}}async function iz(e,n){try{return await R(V(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){eg(s)}}function az(e,n,s){return R(V(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function rz(e,n,s){const a=n.findingId??"finding-1";return R(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/task`,s),{method:"POST",body:JSON.stringify({title:n.title,description:n.description,priority:n.priority,attachExport:n.attachExport})})}function oz(e,n,s){const a=n.findingId??"finding-1";return R(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}function Z1(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 eS({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:a}=Z1(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 ${a}`,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 tS(e){return e.charAt(0).toUpperCase()+e.slice(1)}function xa({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=tS(e);return t.jsxs("span",{className:`node-health-dot${a?" 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 cm=new Map,nS=6e4;function tg(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(!1),d=i.useRef(!1),u=i.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return i.useEffect(()=>{const m=e??"default";let h=!1;async function f(){const p=cm.get(m);if(p&&Date.now()<p.expiresAt){if(h||d.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const x=await V1(e);if(h||d.current)return;cm.set(m,{slots:x,expiresAt:Date.now()+nS}),s(x),c.current=!0}catch(x){if(h||d.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!d.current&&r(!1)}}return f(),()=>{h=!0}},[e]),i.useEffect(()=>{c.current=!1,d.current=!1},[e]),i.useEffect(()=>()=>{d.current=!0},[]),i.useMemo(()=>({slots:n,getSlotsForId:u,loading:a,error:o}),[n,u,a,o])}function dm({size:e,color:n,label:s="llama.cpp"}){return t.jsx(Mf,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const sS={sm:16,md:20,lg:24};function iS({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 um({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 wi({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 aS({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 mm({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 rS({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 ac({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 hm({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 pm({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 fm({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 rc({size:e,color:n,label:s="DeepSeek"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"deepseek-icon","aria-label":s,children:t.jsx("path",{d:"M4 12a8 8 0 1 1 12.7 6.4L12 16h4a4 4 0 1 0-1.6 3.2L12 22l7-1-1.2-3.6A10 10 0 1 0 2 12z",fill:n})})}function gm({size:e,color:n,label:s="Cloudflare"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cloudflare-icon","aria-label":s,children:t.jsx("path",{d:"M7 16.5h10.8a2.9 2.9 0 0 0 .3-5.8 4.9 4.9 0 0 0-9.3-1.6A3.6 3.6 0 0 0 7 16.5m-1.9 0h3.2a2.5 2.5 0 0 0 .2-5 3.4 3.4 0 0 0-3.4 3.4c0 .6 0 1 .2 1.6",fill:n})})}function kr({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 bm({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 oc({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 xm({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 lc({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 oS({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 lS({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 vm({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 cc({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 cS({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 ym({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 dc({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 wm({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 uc({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 km({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 dS({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 uS={anthropic:{component:iS,color:"var(--provider-anthropic)"},"claude-cli":{component:km,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:km,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:dS,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"llama-cpp":{component:dm,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:dm,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:um,color:"var(--provider-openai)"},"openai-codex":{component:um,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:wi,color:"var(--provider-gemini)"},gemini:{component:wi,color:"var(--provider-gemini)"},"google-antigravity":{component:wi,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:wi,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:wi,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:wi,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:wi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:wi,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:wi,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:wi,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:aS,color:"var(--text)"},github:{component:ym,color:"var(--text)"},"github-copilot":{component:ym,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:cS,color:"var(--provider-openrouter)"},minimax:{component:mm,color:"var(--provider-minimax)"},"minimax-cn":{component:mm,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:rS,color:"var(--provider-zai)"},kimi:{component:ac,color:"var(--provider-kimi)"},moonshot:{component:ac,color:"var(--provider-kimi)"},"kimi-coding":{component:ac,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:hm,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:hm,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:pm,color:"var(--text)"},grok:{component:pm,color:"var(--text)",label:"xAI"},opencode:{component:fm,color:"var(--provider-opencode)"},"opencode-go":{component:fm,color:"var(--provider-opencode)",label:"Opencode (Go)"},deepseek:{component:rc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deepseek-ai":{component:rc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deep-seek":{component:rc,color:"var(--provider-deepseek)",label:"DeepSeek"},cloudflare:{component:gm,color:"var(--provider-cloudflare)",label:"Cloudflare"},cloudflared:{component:gm,color:"var(--provider-cloudflare)",label:"Cloudflare"},qwen:{component:kr,color:"var(--provider-qwen)"},"qwen-ai":{component:kr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:kr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:kr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:kr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:bm,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:bm,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:oc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:oc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:oc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:xm,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:xm,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:lc,color:"var(--provider-azure)"},"azure-openai":{component:lc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:lc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:cc,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:cc,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:cc,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:oS,color:"var(--provider-cerebras)"},groq:{component:lS,color:"var(--provider-groq)"},vercel:{component:vm,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:vm,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:dc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:dc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:dc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:wm,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:wm,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:uc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:uc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:uc,color:"var(--provider-paperclip)",label:"Paperclip"}};function Jn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=uS[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=sS[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(Mf,{size:c})})}function ng({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await jk();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await Ck(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=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(xt,{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(Jn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(mS,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(jm,{status:a,authenticated:e}),c&&t.jsx(Nm,{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(Jn,{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"}),x,t.jsx(jm,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Nm,{action:c})]})}function mS({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&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 jm({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(xt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?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 Nm({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 Sm({actions:e}){return t.jsx(ng,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function hS({actions:e}){return t.jsx(ng,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function pS(){return t.jsx("p",{className:"onboarding-helper-text","data-testid":"droid-onboarding-setup-help",children:"Tip: Enable Droid CLI to reuse your Factory AI subscription without adding an API key."})}function fS({actions:e}){return t.jsxs("div",{className:"post-onboarding-recommendations__item","data-testid":"droid-post-onboarding-recommendation",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:"Enable Droid CLI"}),t.jsx("span",{children:"Use your local Droid CLI session as an AI provider in Fusion."})]}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>e?.openSettingsSection?.("authentication"),children:"Open Authentication"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>e?.openModelOnboarding?.(),children:"Open Onboarding"})]})}const gS=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:Sm},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:Sm},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:hS},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:pS},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:fS}];function bS(e){return gS.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function xS({slotId:e,pluginId:n}){return t.jsxs("section",{className:"plugin-slot-shell","data-plugin-slot":!0,"data-slot-id":e,"data-plugin-id":n,"data-plugin-slot-state":"missing-component",role:"status","aria-live":"polite",children:[t.jsx("p",{className:"plugin-slot-shell__title",children:"Plugin component unavailable"}),t.jsx("p",{className:"plugin-slot-shell__message",children:"The dashboard could not resolve this plugin surface from the static host registry."})]})}function Zi({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=tg(n);if(l||c||!e)return null;const d=o(e).filter(u=>s&&s.length>0?s.includes(u.pluginId):!0);return d.length===0?null:t.jsx(mo,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,m)=>{const h=`${u.pluginId}-${u.slot.slotId}-${m}`,f=bS(u);return f?t.jsx(f,{entry:u,actions:r},h):a?t.jsx(xS,{slotId:u.slot.slotId,pluginId:u.pluginId},h):null})})})}function vS(){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 Js(){const[e,n]=i.useState(vS);return i.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),a=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):a.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),a.addEventListener("change",r),()=>{s.removeEventListener("change",r),a.removeEventListener("change",r)}},[]),e}function hr(e){return e.replace(/\\/g,"/")}function iu(e){return e.replace(/[\\/]+$/g,"")}function au(e){const n=hr(iu(e));return n?n.split("/").filter(Boolean):[]}function ru(e){const n=hr(iu(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function sg(e,n){const s=au(e);return s.length===0?hr(e):s.slice(-2).join("/")}function yS(e){const n=hr(iu(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function wS(e,n){return!e||e==="."?n:[...au(e),n].join("/")}function kS(e){const n=au(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function lz(e){const n=hr(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 a=n.split("/").filter(Boolean);return a.map((r,o)=>({label:r,path:a.slice(0,o+1).join("/")}))}const jS=new Map;function ig(e,n){return`plugin:${e}:${n}`}function ag(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function Ga(e){return ag(e)!==null}function NS(e,n){return jS.get(ig(e,n))??null}function mc({viewId:e}){return t.jsxs("section",{className:"card plugin-dashboard-view-missing","data-testid":"plugin-view-unavailable",children:[t.jsxs("h2",{className:"plugin-dashboard-view-missing-title",children:[t.jsx(Ll,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function SS({viewId:e}){const n=ag(e);if(!n)return t.jsx(mc,{viewId:e});const s=NS(n.pluginId,n.viewId);return s?t.jsx(mo,{fallback:t.jsx(mc,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(s,{})})}):t.jsx(mc,{viewId:e})}const Vr=ig,CS={activity:Ws,bot:zn,brain:Yr,checksquare:Xd,clock:zi,filetext:na,folder:vs,gitbranch:zs,grid3x3:Tl,layoutgrid:sa,mail:ba,map:bd,messagesquare:Oi,monitor:Xa,search:Li,sparkles:bs,target:Ms,workflow:dl,zap:us};function ES(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function fl(e){return CS[ES(e)]??Tl}const Eo="__none__",rg={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function _S({projects:e,currentProject:n,onViewAll:s,onSelectProject:a}){const[r,o]=i.useState(!1),l=i.useRef(null);i.useEffect(()=>{if(!r)return;const d=u=>{l.current&&!l.current.contains(u.target)&&o(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[r]),i.useEffect(()=>{if(!r)return;const d=u=>{u.key==="Escape"&&o(!1)};return document.addEventListener("keydown",d),()=>document.removeEventListener("keydown",d)},[r]);const c=i.useCallback(d=>{a?.(d),o(!1)},[a]);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(d=>!d),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(cn,{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(d=>{const u=n?.id===d.id,m=rg[d.status]?.color;return t.jsxs("button",{className:`project-selector-item${u?" project-selector-item--current":""}`,onClick:()=>c(d),role:"option","aria-selected":u,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:d.name}),t.jsx("span",{className:"project-selector-path",children:sg(d.path)})]}),u&&t.jsx(os,{size:14,className:"project-selector-check"})]},d.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 Cm({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 MS({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,chatHasUnreadResponse:m=!1,onOpenSchedules:h,onOpenGitManager:f,onOpenNodes:p,showNodesButton:g,onOpenWorkflowSteps:x,onOpenScripts:v,onRunScript:b,onToggleTerminal:y,onOpenFiles:S,filesOpen:N,onOpenTodos:E,todosOpen:w,todosEnabled:j,globalPaused:_,enginePaused:D,onToggleGlobalPause:C,onToggleEnginePause:P,view:I="board",onChangeView:H,showSkillsTab:A,showAgentsTab:$,searchQuery:F="",onSearchChange:G,branchFilter:ee=null,baseBranchFilter:J=null,branchOptions:M=[],baseBranchOptions:T=[],onBranchFilterChange:L,onBaseBranchFilterChange:k,projects:K=[],currentProject:oe,onSelectProject:le,onViewAllProjects:we,projectId:ge,isElectron:Ue=!1,mobileNavEnabled:Z,availableNodes:Q=[],currentNode:X,onSelectNode:ie,isRemote:se=!1,experimentalFeatures:B,pluginDashboardViews:O=[],shellConnectionControl:ke}){const ae=Js(),te=ae==="mobile",Oe=te||ae==="tablet",He=te&&Z,[$e,Te]=i.useState(!1),[ue,ce]=i.useState(!1),[Ae,Ne]=i.useState(!1),[ye,Ce]=i.useState(!1),[fe,Pe]=i.useState(!1),[De,dt]=i.useState(!1),[pt,lt]=i.useState(!1),[vt,_e]=i.useState(!1),[Fe,bt]=i.useState(!1),[ht,Ee]=i.useState(!1),[me,Re]=i.useState(!1),[be,Ke]=i.useState({}),[pe,Xe]=i.useState(!1),[wt,gt]=i.useState(-1),[Tt,Zt]=i.useState(null),[Ot,Rt]=i.useState({}),[en,zt]=i.useState(!1),Qt=i.useRef(null),xn=i.useRef(null),Kt=i.useRef(null),Ut=i.useRef(null),fn=i.useRef(null),un=i.useRef(null),tn=i.useRef(!1),Vt=i.useRef(null),mn=i.useRef(null),xe=i.useRef(null),Le=i.useRef(null),Ve=i.useRef(null),at=i.useRef(null),Ge=i.useRef(null),Ft=i.useRef(null),_t=i.useRef(!1),qt=i.useMemo(()=>Q.filter(Y=>Y.type==="remote"),[Q]),St=qt.length>0,z=i.useMemo(()=>Object.entries(be).sort(([Y],[Ye])=>Y.localeCompare(Ye)),[be]),he=z.length>0,st=z.length+(he?1:0),It=i.useMemo(()=>Object.entries(Ot).sort(([Y],[Ye])=>Y.localeCompare(Ye)),[Ot]),ve=i.useMemo(()=>O.some(Y=>Y.pluginId==="fusion-plugin-roadmap"),[O]),ot=i.useMemo(()=>!!(B?.researchView||j||B?.insights||B?.roadmap&&!ve||A||B?.memoryView||B?.devServerView||!He||O.some(Y=>Y.view.placement!=="primary")),[B,j,A,He,O,ve]),Nt=i.useCallback(()=>{const Y=window.visualViewport;return Y&&Y.width>0&&Y.height>0?{width:Y.width,height:Y.height,offsetTop:Y.offsetTop,offsetLeft:Y.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Lt=i.useCallback(()=>{const Y=Ge.current;if(!Y)return;const Ye=Y.getBoundingClientRect(),Yt=Ft.current,{width:In,height:cs,offsetTop:gn,offsetLeft:Nn}=Nt(),ms=16,vn=16,bn=6,Pt=Yt?.offsetWidth||Math.max(Ye.width,260),Qn=Math.min(Pt,Math.max(In-ms*2,160)),es=Yt?.offsetHeight||280,W=Math.min(es,Math.max(cs-vn*2,160)),qe=Ye.top-gn,Je=Ye.bottom-gn,ut=Ye.right-Nn,Ct=cs-Je,Mt=qe,an=Ct<W&&Mt>Ct,An=Math.min(Math.max(ut-Qn,ms),In-ms-Qn)+Nn,Sn=an?Math.max(vn+gn,qe-W-bn+gn):Math.min(Je+bn+gn,cs+gn-vn-W);Zt({top:Sn,left:An,width:Qn})},[Nt]),$t=i.useCallback((Y,Ye)=>{b?.(Y,Ye),Re(!1),gt(-1)},[b]),Wt=i.useCallback(()=>{v?.(),Re(!1),gt(-1)},[v]),Gt=i.useCallback(Y=>{switch(Y.key){case"ArrowDown":Y.preventDefault(),st>0&>(Ye=>Ye<st-1?Ye+1:0);break;case"ArrowUp":Y.preventDefault(),st>0&>(Ye=>Ye>0?Ye-1:st-1);break;case"Enter":if(Y.preventDefault(),wt>=0)if(wt<z.length){const[Ye,Yt]=z[wt];$t(Ye,Yt)}else he&&wt===z.length&&Wt();break;case"Home":Y.preventDefault(),st>0&>(0);break;case"End":Y.preventDefault(),st>0&>(st-1);break}},[Wt,$t,wt,z,he,st]);i.useEffect(()=>{tn.current=fe},[fe]),i.useEffect(()=>{_t.current=me},[me]),i.useEffect(()=>{if(!fe||!Oe)return;let Y=!1;return zt(!0),eo(ge).then(Ye=>{Y||Rt(Ye)}).catch(()=>{Y||Rt({})}).finally(()=>{Y||zt(!1)}),()=>{Y=!0}},[fe,Oe,ge]),i.useEffect(()=>{if(!me||Oe)return;let Y=!1;return Xe(!0),eo(ge).then(Ye=>{Y||Ke(Ye)}).catch(()=>{Y||Ke({})}).finally(()=>{Y||Xe(!1)}),()=>{Y=!0}},[me,Oe,ge]),i.useEffect(()=>{if(!me)return;const Y=Ye=>{at.current&&!at.current.contains(Ye.target)&&Re(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[me]),i.useEffect(()=>{if(!me)return;const Y=Ye=>{Ye.key==="Escape"&&(Re(!1),Ge.current?.focus())};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[me]),i.useEffect(()=>{if(me){gt(-1);const Y=window.setTimeout(()=>Ft.current?.focus(),0);return()=>window.clearTimeout(Y)}Zt(null)},[me]),i.useEffect(()=>{if(!me)return;const Y=requestAnimationFrame(()=>{Lt()});return()=>cancelAnimationFrame(Y)},[me,pe,z.length,he,Lt]),i.useEffect(()=>{if(!me)return;const Y=()=>Lt();window.addEventListener("resize",Y),window.addEventListener("scroll",Y,!0);const Ye=window.visualViewport;return Ye&&(Ye.addEventListener("resize",Y),Ye.addEventListener("scroll",Y)),()=>{window.removeEventListener("resize",Y),window.removeEventListener("scroll",Y,!0),Ye&&(Ye.removeEventListener("resize",Y),Ye.removeEventListener("scroll",Y))}},[me,Lt]),i.useEffect(()=>{Oe&&(Re(!1),gt(-1))},[Oe]);const sn=$e||F.length>0,on=(ue||F.length>0)&&!Ae,Dn=(I==="board"||I==="list")&&!te&&G&&!Ae&&F.length===0,Jt=(I==="board"||I==="list")&&!te&&G,Hn=I==="board";i.useEffect(()=>{F===""&&Ne(!1)},[F]),i.useEffect(()=>{if(!ye)return;const Y=Ye=>{xn.current&&!xn.current.contains(Ye.target)&&Qt.current&&!Qt.current.contains(Ye.target)&&Ce(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[ye]),i.useEffect(()=>{if(!Fe)return;const Y=Ye=>{Ut.current&&!Ut.current.contains(Ye.target)&&Kt.current&&!Kt.current.contains(Ye.target)&&bt(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[Fe]),i.useEffect(()=>{if(!De)return;const Y=Ye=>{Vt.current&&!Vt.current.contains(Ye.target)&&dt(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[De]),i.useEffect(()=>{const Y=Ye=>{if(Ye.key==="Escape"){if(_e(!1),bt(!1),tn.current){Pe(!1);return}if(_t.current){Re(!1),Ge.current?.focus();return}Ce(!1),Te(!1),dt(!1),lt(!1)}};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[]),i.useEffect(()=>{if(!pt)return;const Y=Ye=>{mn.current&&!mn.current.contains(Ye.target)&<(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[pt]),i.useEffect(()=>{if(!ht)return;const Y=Ye=>{Ve.current&&!Ve.current.contains(Ye.target)&&Ee(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[ht]),i.useEffect(()=>{if(!ht)return;const Y=Ye=>{Ye.key==="Escape"&&Ee(!1)};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[ht]),i.useEffect(()=>{if(!vt)return;const Y=Ye=>{xe.current&&!xe.current.contains(Ye.target)&&Le.current&&!Le.current.contains(Ye.target)&&_e(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[vt]);const Yn=i.useCallback(()=>{Te(Y=>!Y)},[]),re=i.useCallback(()=>{ce(!0),Ne(!1)},[]),rt=i.useCallback(()=>{ce(!1),Ne(!0),G&&G("")},[G]),ct=i.useCallback(()=>{Ce(Y=>!Y)},[]),ft=i.useCallback(Y=>{Y&&Y(),Ce(!1),Pe(!1)},[]),it=i.useCallback(()=>{Te(!1),G&&G("")},[G]);return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header",children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),te&&K.length>=1&&le&&t.jsxs("div",{className:"mobile-project-switch",ref:mn,children:[t.jsx("button",{className:`mobile-project-switch-trigger${pt?" mobile-project-switch-trigger--open":""}`,onClick:()=>lt(Y=>!Y),title:"Switch project","aria-label":"Switch project","aria-expanded":pt,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(cn,{size:14,className:`mobile-project-switch-chevron${pt?" mobile-project-switch-chevron--open":""}`})}),pt&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:K.map(Y=>{const Ye=oe?.id===Y.id,Yt=rg[Y.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${Ye?" mobile-project-switch-item--current":""}`,onClick:()=>{le(Y),lt(!1)},role:"option","aria-selected":Ye,"data-testid":`mobile-project-switch-item-${Y.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Yt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:Y.name}),t.jsx("span",{className:"mobile-project-switch-path",children:sg(Y.path)})]}),Ye&&t.jsx(os,{size:14,className:"mobile-project-switch-check"})]},Y.id)})})]}),!Oe&&K.length>=1&&we&&t.jsx(_S,{projects:K,currentProject:oe??null,onViewAll:we,onSelectProject:le}),St&&t.jsxs("div",{className:`header-node-selector${te?" header-node-selector--mobile":""}`,ref:te?void 0:Vt,children:[t.jsx(eS,{node:X??null,showDetails:!te}),!te&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${De?" node-selector-trigger--open":""}`,onClick:()=>dt(Y=>!Y),title:"Switch node","aria-label":"Switch node","aria-expanded":De,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(Un,{size:12,className:`node-selector-chevron${De?" node-selector-chevron--open":""}`})}),De&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${se?"":" node-selector-option--active"}`,onClick:()=>{ie?.(null),dt(!1)},role:"option","aria-selected":!se,"data-testid":"node-option-local",children:[t.jsx(xa,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),qt.map(Y=>t.jsxs("button",{className:`node-selector-option${X?.id===Y.id?" node-selector-option--active":""}`,onClick:()=>{ie?.(Y),dt(!1)},role:"option","aria-selected":X?.id===Y.id,"data-testid":`node-option-${Y.id}`,children:[t.jsx(xa,{status:Y.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:Y.name}),t.jsx("span",{className:"node-selector-option-status",children:Y.status})]},Y.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ke,He&&H&&(I==="board"||I==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${I==="board"?" active":""}`,onClick:()=>H("board"),title:"Board view","aria-label":"Board view","aria-pressed":I==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(sa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${I==="list"?" active":""}`,onClick:()=>H("list"),title:"List view","aria-label":"List view","aria-pressed":I==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(gd,{size:16})})]}),G&&te&&(He||I==="board"||I==="list")&&!sn&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Yn,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Li,{size:16})}),Dn&&t.jsx("button",{className:"btn-icon",onClick:re,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Li,{size:16})}),te&&He&&o&&t.jsx("button",{className:"btn-icon",onClick:Y=>o(Y.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ws,{size:16})}),!He&&H&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${I==="board"?" active":""}`,onClick:()=>H("board"),title:"Board view","aria-label":"Board view","aria-pressed":I==="board",children:t.jsx(sa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${I==="list"?" active":""}`,onClick:()=>H("list"),title:"List view","aria-label":"List view","aria-pressed":I==="list",children:t.jsx(gd,{size:16})}),$&&t.jsx("button",{className:`view-toggle-btn${I==="agents"?" active":""}`,onClick:()=>H("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":I==="agents",children:t.jsx(zn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${I==="missions"?" active":""}`,onClick:()=>H("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":I==="missions",children:t.jsx(Ms,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${I==="chat"?" active":""}`,onClick:()=>H("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":I==="chat","data-testid":"header-chat-view-btn",children:[t.jsx(Oi,{size:16}),m&&I!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("button",{className:`view-toggle-btn${I==="documents"?" active":""}`,onClick:()=>H("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":I==="documents",children:t.jsx(na,{size:16})}),t.jsx("button",{className:`view-toggle-btn${I==="mailbox"?" active":""}`,onClick:()=>H("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":I==="mailbox",children:t.jsx(ba,{size:16})}),O.filter(Y=>Y.view.placement==="primary").sort((Y,Ye)=>(Y.view.order??Number.MAX_SAFE_INTEGER)-(Ye.view.order??Number.MAX_SAFE_INTEGER)).map(Y=>{const Ye=Vr(Y.pluginId,Y.view.viewId),Yt=fl(Y.view.icon);return t.jsx("button",{className:`view-toggle-btn${I===Ye?" active":""}`,onClick:()=>H(Ye),title:`${Y.view.label} view`,"aria-label":`${Y.view.label} view`,"aria-pressed":I===Ye,"data-testid":`view-toggle-plugin-${Y.pluginId}-${Y.view.viewId}`,children:t.jsx(Yt,{size:16})},`${Y.pluginId}:${Y.view.viewId}`)}),ot&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Le,className:`view-toggle-btn${["research","skills","roadmaps","insights","memory","dev-server","devserver"].includes(I)||j&&w||Ga(I)?" active":""}`,onClick:()=>_e(Y=>!Y),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":vt,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(cn,{size:12})}),vt&&t.jsxs("div",{ref:xe,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[B?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${I==="research"?" active":""}`,onClick:()=>{H("research"),_e(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Li,{size:14}),t.jsx("span",{children:"Research"})]}),B?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${I==="insights"?" active":""}`,onClick:()=>{H("insights"),_e(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(bs,{size:14}),t.jsx("span",{children:"Insights"})]}),B?.roadmap&&!ve&&t.jsx("button",{className:`view-toggle-overflow-item${I==="roadmaps"?" active":""}`,onClick:()=>{H("roadmaps"),_e(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:t.jsx("span",{children:"Roadmaps"})}),A&&t.jsxs("button",{className:`view-toggle-overflow-item${I==="skills"?" active":""}`,onClick:()=>{H("skills"),_e(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(us,{size:14}),t.jsx("span",{children:"Skills"})]}),B?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${I==="memory"?" active":""}`,onClick:()=>{H("memory"),_e(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Yr,{size:14}),t.jsx("span",{children:"Memory"})]}),B?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${I==="dev-server"||I==="devserver"?" active":""}`,onClick:()=>{H("devserver"),_e(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(Xa,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),j&&E&&t.jsxs("button",{className:`view-toggle-overflow-item${w?" active":""}`,onClick:()=>{E(),_e(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Xd,{size:14}),t.jsx("span",{children:"Todos"})]}),O.filter(Y=>Y.view.placement!=="primary").sort((Y,Ye)=>(Y.view.order??Number.MAX_SAFE_INTEGER)-(Ye.view.order??Number.MAX_SAFE_INTEGER)).map(Y=>{const Ye=Vr(Y.pluginId,Y.view.viewId),Yt=fl(Y.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${I===Ye?" active":""}`,onClick:()=>{H(Ye),_e(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${Y.pluginId}-${Y.view.viewId}`,children:[t.jsx(Yt,{size:14}),t.jsx("span",{children:Y.view.label})]},`${Y.pluginId}:${Y.view.viewId}`)})]})]})]}),!Oe&&o&&t.jsx("button",{className:"btn-icon",onClick:Y=>o(Y.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ws,{size:16})}),!Oe&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(Xa,{size:16})}),!Oe&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Qr,{size:16})}),!Oe&&!Ue&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(Cm,{size:16})}),!Oe&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&a?a:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(hi,{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})]}),!Oe&&t.jsxs("div",{className:"terminal-split-btn",ref:at,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:y,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Fi,{size:16})}),v&&b&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Ge,className:`btn-icon terminal-split-btn__chevron${me?" btn-icon--active":""}`,onClick:()=>Re(Y=>!Y),title:"Scripts","aria-haspopup":"listbox","aria-expanded":me,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(cn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${me?" rotate":""}`})}),me&&t.jsx("div",{ref:Ft,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:Gt,"data-testid":"quick-scripts-dropdown",style:Tt?{position:"fixed",top:`${Tt.top}px`,left:`${Tt.left}px`,width:`${Tt.width}px`,right:"auto"}:void 0,children:pe?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(xt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):z.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(Fi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:Wt,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:z.map(([Y,Ye],Yt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${wt===Yt?"highlighted":""}`,onClick:()=>$t(Y,Ye),role:"option","aria-selected":wt===Yt,"data-testid":`quick-script-item-${Y}`,children:[t.jsx(ls,{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:Y}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:Ye,children:Ye.length>50?`${Ye.slice(0,50)}...`:Ye})]})]},Y))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${he&&wt===z.length?"highlighted":""}`,onClick:Wt,"data-testid":"quick-scripts-manage",children:[t.jsx(qr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Oe&&S&&t.jsx("button",{className:`btn-icon${N?" btn-icon--active":""}`,onClick:S,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(vs,{size:16})}),!Oe&&f&&t.jsx("button",{className:"btn-icon",onClick:f,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(zs,{size:16})}),!Oe&&x&&t.jsx("button",{className:"btn-icon",onClick:x,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(dl,{size:16})}),!Oe&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Kt,className:"btn-icon",onClick:()=>bt(Y=>!Y),title:"More actions","aria-label":"More actions","aria-expanded":Fe,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(md,{size:16})}),Fe&&t.jsxs("div",{ref:Ut,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[p&&g!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{p(),bt(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Xr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{ft(h),bt(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(zi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Ve,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${_?" btn-icon--stopped":""}`,onClick:C,title:_?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:_?t.jsx(ls,{size:16}):t.jsx(Si,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${ht?" btn-icon--active":""}`,onClick:()=>Ee(Y=>!Y),title:"Engine options","aria-haspopup":"menu","aria-expanded":ht,"data-testid":"engine-control-chevron-btn",children:t.jsx(cn,{size:12})}),ht&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${D?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{P?.(),Ee(!1)},role:"menuitem",title:D?"Resume scheduling":"Pause triage",disabled:!!_,"data-testid":"engine-control-pause-triage-btn",children:[D?t.jsx(ls,{size:14}):t.jsx(di,{size:14}),t.jsx("span",{children:D?"Resume scheduling":"Pause triage"})]})})]}),!Oe&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(qr,{size:16})}),t.jsx(Zi,{slotId:"header-action",projectId:ge}),Oe&&!He&&t.jsx("button",{ref:Qt,className:"btn-icon compact-overflow-trigger",onClick:ct,title:"More header actions","aria-label":"More header actions","aria-expanded":ye,"aria-haspopup":"menu",children:t.jsx(md,{size:16})}),Oe&&!He&&ye&&t.jsxs("div",{ref:xn,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[K.length>=1&&we&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(we),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(Tl,{size:16}),t.jsx("span",{children:"Projects"})]}),S&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(S),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(vs,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>ft(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(hi,{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"})]}),f&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(f),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(zs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),p&&g!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(p),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Xr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!Ue&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(n),role:"menuitem",children:[t.jsx(Cm,{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:()=>ft(y),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Fi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>Pe(Y=>!Y),role:"menuitem","aria-expanded":fe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(Un,{size:14,className:`mobile-overflow-chevron${fe?" mobile-overflow-chevron--open":""}`})})]}),fe&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:en?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(xt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):It.length>0?t.jsxs(t.Fragment,{children:[It.map(([Y,Ye])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(Y,Ye),Ce(!1),Pe(!1)},role:"menuitem","data-testid":`overflow-script-item-${Y}`,children:[t.jsx(ls,{size:14}),t.jsx("span",{children:Y})]},Y)),v&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>ft(v),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(ci,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):v&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>ft(v),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(ci,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(h),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(zi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Qr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(ba,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:Y=>ft(()=>o(Y.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ws,{size:16}),t.jsx("span",{children:"View Usage"})]}),x&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(x),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(dl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>ft(e),role:"menuitem",children:[t.jsx(qr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Jt&&on&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{className:"header-search",children:[t.jsx(Li,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:Y=>G(Y.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:rt,"aria-label":"Close search",children:t.jsx(nn,{size:14})})]}),Hn&&t.jsxs("div",{className:"header-branch-filters","data-testid":"header-branch-filters-desktop",children:[t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Working branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:ee??"",onChange:Y=>L?.(Y.target.value||null),"data-testid":"working-branch-filter",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:Eo,children:"No working branch"}),M.map(Y=>t.jsx("option",{value:Y,children:Y},Y))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Target branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:J??"",onChange:Y=>k?.(Y.target.value||null),"data-testid":"target-branch-filter",children:[t.jsx("option",{value:"",children:"All target branches"}),t.jsx("option",{value:Eo,children:"No target branch"}),T.map(Y=>t.jsx("option",{value:Y,children:Y},Y))]})]})]})]}),G&&te&&sn&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{ref:fn,className:"header-search mobile-search-expanded",children:[t.jsx(Li,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:un,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:Y=>G(Y.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:it,"aria-label":"Close search",children:t.jsx(nn,{size:14})})]}),Hn&&t.jsxs("div",{className:"header-branch-filters","data-testid":"header-branch-filters-mobile",children:[t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Working branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:ee??"",onChange:Y=>L?.(Y.target.value||null),"data-testid":"working-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:Eo,children:"No working branch"}),M.map(Y=>t.jsx("option",{value:Y,children:Y},Y))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Target branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:J??"",onChange:Y=>k?.(Y.target.value||null),"data-testid":"target-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All target branches"}),t.jsx("option",{value:Eo,children:"No target branch"}),T.map(Y=>t.jsx("option",{value:Y,children:Y},Y))]})]})]})]})]})}const AS={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","fallback-used","memory-dreams-processed"],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,opencodeGoModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!0,showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,useDroidCli:void 0,useLlamaCpp: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,persistAgentToolOutput:!0,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,researchGlobalWebSearchProvider:"none",researchGlobalSearxngUrl:void 0,researchGlobalBraveApiKey:void 0,researchGlobalGoogleSearchApiKey:void 0,researchGlobalGoogleSearchCx:void 0,researchGlobalTavilyApiKey:void 0,researchGlobalGitHubEnabled:!1,researchGlobalLocalDocsEnabled:!0,researchGlobalMaxSearchResults:10,researchGlobalFetchTimeoutMs:3e4,researchGlobalUserAgent:"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:{}},PS={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,completionDocumentationMode:"off",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,preserveProgressOnStuckRequeue:!0,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,useAiMergeCommitSummary:!0,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,taskEvaluationEnabled:!1,taskEvaluationSchedule:"0 5 * * *",taskEvaluationProvider:void 0,taskEvaluationModelId:void 0,taskEvaluationFollowUpPolicy:"off",taskEvaluationRetention:void 0,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},TS=Object.freeze(Object.keys(AS)),RS=Object.freeze(Object.keys(PS));function cz(e){return TS.includes(e)}function dz(e){return RS.includes(e)}function Me(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function IS(e){return!!(e?.provider&&e?.modelId)}function ia(...e){for(const n of e)if(IS(n))return{provider:n.provider,modelId:n.modelId};return{}}function Ul(e){return ia({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function $S(e){return ia({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Ul(e))}function DS(e){return ia({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Ul(e))}function LS(e){return ia({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Ul(e))}function uz(e){return ia({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Ul(e))}function og(e,n){return ia({provider:e.modelProvider,modelId:e.modelId},$S(n))}function lg(e,n){return ia({provider:e.validatorModelProvider,modelId:e.validatorModelId},LS(n))}function cg(e,n){return ia({provider:e.planningModelProvider,modelId:e.planningModelId},DS(n))}const mz=["off","minimal","low","medium","high"],Xi=["triage","todo","in-progress","in-review","done","archived"],gl="triage";function ou(e){return typeof e=="string"&&Xi.includes(e)}function dg(e,n=gl){return ou(e)?e:n}const xo=["low","normal","high","urgent"],Rs="normal",OS=["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"],ds={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},FS={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"},Nd={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 zS(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 Em(e){return e==="urgent"?3:e==="high"?2:e==="low"?0:1}function _m(e,n){return Em(n)-Em(e)}function hc(e,n){const s=Number.parseInt(e.slice(e.lastIndexOf("-")+1),10),a=Number.parseInt(n.slice(n.lastIndexOf("-")+1),10);return Number.isFinite(s)&&Number.isFinite(a)&&s!==a?s-a:e.localeCompare(n)}function Mm(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function Am(e){return e==="merging"||e==="merging-pr"||e==="merging-fix"}function ug(e,n){return n==="todo"?[...e].sort((s,a)=>{const r=_m(s.priority,a.priority);return r!==0?r:s.createdAt!==a.createdAt?s.createdAt.localeCompare(a.createdAt):hc(s.id,a.id)}):[...e].sort((s,a)=>{if(n==="done"){const o=Mm(a)-Mm(s);return o!==0?o:hc(s.id,a.id)}if(n==="in-review"){const o=Am(s.status),l=Am(a.status);if(o!==l)return o?-1:1}const r=_m(s.priority,a.priority);return r!==0?r:hc(s.id,a.id)})}function US(e,n=1400){const s=i.useRef(null),[a,r]=i.useState(!1),o=i.useRef(null);return i.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]),a}function BS({isOpen:e,options:n,onConfirm:s,onCancel:a}){const r=i.useRef(null);return i.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),a())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,a]),!e||!n?null:t.jsx("div",{className:"modal-overlay open confirm-dialog-overlay",onClick:a,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:a,"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:a,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const mg=i.createContext(null);function HS({children:e}){const[n,s]=i.useState([]),a=i.useRef([]),r=i.useCallback(u=>{s(m=>{const h=u(m);return a.current=h,h})},[]),o=i.useCallback(u=>new Promise(m=>{r(h=>[...h,{options:u,resolve:m}])}),[r]),l=i.useCallback(u=>{const m=a.current[0];m&&(m.resolve(u),r(h=>h.slice(1)))},[r]),c=n[0]??null,d=i.useMemo(()=>({confirm:o}),[o]);return ol.createElement(mg.Provider,{value:d},e,ol.createElement(BS,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Ys(){const e=i.useContext(mg);return e||{confirm:async n=>!1}}function qS(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 hg({prInfo:e,issueInfo:n,onIssueRefresh:s}){return t.jsxs(t.Fragment,{children:[e&&t.jsxs("a",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,href:e.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(Vs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${qS(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(Al,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function _o(e,n){return`${e??"default"}:${n}`}class VS{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,a=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)a.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of a){const l=_o(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=_o(this.projectId,s),r=this.subscriptionsByTask.get(a)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(a,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const a=_o(this.projectId,s),r=this.subscriptionsByTask.get(a);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(a),this.badgeUpdates.delete(a),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 a=s.split(":").slice(1).join(":");this.unsubscribeTask(n,a)}}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 a=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(a+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(_i(a));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=_o(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:Pm(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:Pm(l,"issueInfo")?l.issueInfo??null:d?.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,a=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},a),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 ua=new VS;let WS=0;function Pm(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function pg(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${WS++}`);const s=i.useSyncExternalStore(o=>ua.subscribe(o),()=>ua.getSnapshot(),()=>ua.getSnapshot()),a=i.useCallback(o=>{ua.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{ua.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{ua.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{ua.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function bl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function KS({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=pg(o),u=!!(n||s);i.useEffect(()=>{if(!u||!r){d(e);return}return c(e),()=>{d(e)}},[u,r,o,c,e,d]);const m=l.get(`${o??"default"}:${e}`),h=bl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=bl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(hg,{prInfo:h,issueInfo:f})}const GS=i.memo(KS);GS.displayName="TaskCardBadge";const ei={data:new Map,pendingPromise:null,lastFetchTime:null},JS=5e3;function sl(e,n){return n?`${n}::${e}`:e}function YS(e,n){const s=ei.data.get(sl(e,n));if(!(!s||Date.now()-s.timestamp>JS))return s}function QS(e){const[n,s]=i.useState(!1),a=i.useRef(null),r=i.useCallback(async c=>{let u=null;for(let m=0;m<3;m++)try{return await Jk(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=Me(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(u)throw u;return{}},[e]),o=i.useCallback(async c=>{if(c.length===0)return;const u=Date.now()-5e3;if(c.every(f=>{const p=ei.data.get(sl(f,e));return p&&p.timestamp>u})&&ei.lastFetchTime&&ei.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),ei.pendingPromise){s(!0);try{await ei.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);ei.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))ei.data.set(sl(g,e),{result:x,timestamp:p});ei.lastFetchTime=p}catch{}finally{ei.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>ei.data.get(sl(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ei.lastFetchTime,getBatchData:l}}const Sd=new Map,XS=3e4;function fg(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function ZS(e,n,s,a){const r=fg(e,n,s,a),o=Sd.get(r);return o?Date.now()>o.expiresAt?(Sd.delete(r),null):o.stats:null}function e0(e,n,s,a,r){const o=fg(e,n,s,a);Sd.set(o,{stats:r,expiresAt:Date.now()+XS})}function t0(e,n,s,a,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,d=r.pollIntervalMs,[u,m]=i.useState(null),[h,f]=i.useState(!1);return i.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 x=g?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(N=!1){if(!N){const E=ZS(e,a,x,v);if(E){b||(m(E),f(!1));return}}f(!0);try{const E=await Jf(e,x,a);b||(m(E.stats),e0(e,a,x,v,E.stats))}catch{b||m(null)}finally{b||f(!1)}}y();let S;return d&&g&&(S=setInterval(()=>{y(!0)},d)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const n0=new Set(["failed","stuck-killed"]);function xl(e,n,s){if(e.column!=="in-progress"||e.status&&n0.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function s0(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function i0(e){return e==="done"||e==="skipped"}function a0(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function gg(e,n){const s=(e.steps??[]).map((d,u)=>({id:`step-${u}`,name:d.name,status:d.status,source:"step",phase:"pre-merge"})),a=new Map((e.workflowStepResults??[]).map(d=>[d.workflowStepId,d])),r=(e.enabledWorkflowSteps??[]).map(d=>{const u=a.get(d);return{id:`workflow-${d}`,name:a0(d,u,n),status:u?s0(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>i0(d.status)).length;return{total:l,completed:c,items:o}}function r0(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 bg(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",a=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||a.includes("[timing]")}).map(n=>{const a=`${n.action??""}
|
|
651
|
-
${n.outcome??""}`.match(/(\d+(?:\.\d+)?)ms\b/i),r=a?Number(a[1]):void 0;return{timestamp:n.timestamp,durationMs:Number.isFinite(r)?r:void 0,summary:r0(n)}})}function xg(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of bg(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}function va(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function vg(e,n){if(!e||e.length===0)return null;let s=0,a=0;for(const r of e){if(!r.startedAt)continue;const o=va(r.startedAt);if(o==null)continue;let l;if(r.completedAt){const c=va(r.completedAt);if(c==null||c<o)continue;l=c}else l=Math.max(o,n);s+=l-o,a+=1}return a>0?s:null}function yg(e,n,s){const a=va(e);if(a==null)return null;const r=va(n),o=r!=null&&r>=a?r:s;return Math.max(0,o-a)}const Cd=new Map;async function o0(e,n){const s=Cd.get(e);if(s)return s;try{const a=await Yf(e,n);return Cd.set(e,a.title),a.title}catch{return e}}const Tm=12;function l0(e){return e.length<=Tm?e:e.slice(0,Tm-3)+"..."}const Ed=new Map;async function c0(e,n){const s=Ed.get(e);if(s)return s;try{const a=await jd(e,n);return Ed.set(e,a.name),a.name}catch{return e}}function d0(e){return typeof e=="string"&&xo.includes(e)?e:Rs}function u0(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function wg(e){const n=e.sourceMetadata?.agentName;if(typeof n=="string"&&n.trim().length>0)return n.trim();if(typeof e.sourceAgentId=="string"&&e.sourceAgentId.trim().length>0)return e.sourceAgentId.trim()}function m0(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!wg(e)}const h0=new Set(["triage","todo"]),Rm=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),Im=new Set(["merging","merging-pr","merging-fix"]),p0={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},f0=new Set(["in-progress","in-review","done"]),g0=3e4;function b0(e){return e==="merging-fix"?"Merging fixes…":e}function x0(e){const n=va(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function $m(e,n){const s=va(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function Or(e,n){return yg(e.executionStartedAt,e.executionCompletedAt,n)}function v0(e){return e.column==="done"?x0(e):null}function kg(e,n){const s=va(e.updatedAt);return s==null?null:Math.max(0,n-s)}function y0(e,n){const s=Or(e,n);if(s!=null)return s;const a=kg(e,n),r=Fr(e,n);return r!=null?r+(a??0):a}function Fr(e,n){if(typeof e.timedExecutionMs=="number")return e.timedExecutionMs;const s=xg(e.log),a=vg(e.workflowStepResults,n);return s==null&&a==null?null:(s??0)+(a??0)}function Dm(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 Lm(e){if(!e)return null;const n=e.trim();return n.length>0?n:null}function w0(e){const n=Lm(e.branch),s=Lm(e.baseBranch),a=`fusion/${e.id.toLowerCase()}`,r=n&&(n===a||n.startsWith(`${a}-`))?null:n,o=s?.toLowerCase()==="main"?null:s;return{branch:r,baseBranch:o??null}}function Om(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 Fm(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),a=Object.keys(n);return s.length!==a.length?!1:s.every(r=>e[r]===n[r])}function k0(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function j0(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function N0(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function S0(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function C0(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(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function E0(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];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 _0(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function M0(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>{const r=n[a];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function A0(e,n){const s=e.task,a=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===a.id&&s.title===a.title&&s.description===a.description&&s.column===a.column&&s.columnMovedAt===a.columnMovedAt&&s.timedExecutionMs===a.timedExecutionMs&&s.updatedAt===a.updatedAt&&s.createdAt===a.createdAt&&s.status===a.status&&s.priority===a.priority&&s.executionMode===a.executionMode&&s.paused===a.paused&&s.error===a.error&&s.size===a.size&&s.blockedBy===a.blockedBy&&s.worktree===a.worktree&&s.branch===a.branch&&s.baseBranch===a.baseBranch&&s.breakIntoSubtasks===a.breakIntoSubtasks&&s.currentStep===a.currentStep&&s.modelProvider===a.modelProvider&&s.modelId===a.modelId&&s.validatorModelProvider===a.validatorModelProvider&&s.validatorModelId===a.validatorModelId&&s.planningModelProvider===a.planningModelProvider&&s.planningModelId===a.planningModelId&&s.reviewLevel===a.reviewLevel&&s.missionId===a.missionId&&s.assignedAgentId===a.assignedAgentId&&s.mergeRetries===a.mergeRetries&&s.sourceType===a.sourceType&&s.sourceAgentId===a.sourceAgentId&&s.sourceMetadata?.issueUrl===a.sourceMetadata?.issueUrl&&s.sourceMetadata?.agentName===a.sourceMetadata?.agentName&&_0(s.attachments,a.attachments)&&M0(s.comments,a.comments)&&j0(s.dependencies,a.dependencies)&&k0(s.steps,a.steps)&&N0(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&E0(s.workflowStepResults,a.workflowStepResults)&&Fm(s.prInfo,a.prInfo)&&Fm(s.issueInfo,a.issueInfo)}function P0({task:e,projectId:n,queued:s,onOpenDetail:a,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:d,onDeleteTask:u,onRetryTask:m,onOpenDetailWithTab:h,taskStuckTimeoutMs:f,onOpenMission:p,onMoveTask:g,lastFetchTimeMs:x,workflowStepNameLookup:v}){const[b,y]=i.useState(!1),[S,N]=i.useState(!1),[E,w]=i.useState(!1),[j,_]=i.useState(e.description||""),[D,C]=i.useState(!1),[P,I]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(ve=>ve.status==="done"||ve.status==="skipped")),[H,A]=i.useState(null),[$,F]=i.useState(null),[G,ee]=i.useState(!1),[J,M]=i.useState(!1),[T,L]=i.useState(()=>Date.now()),k=i.useRef(null),K=i.useRef(!1),oe=i.useRef(null),le=i.useRef(null),[we,ge]=i.useState(!1),{badgeUpdates:Ue,subscribeToBadge:Z,unsubscribeFromBadge:Q}=pg(n),{confirm:X}=Ys(),ie=i.useRef(null),se=i.useRef(!1),B=i.useCallback(ve=>ve instanceof Element?!!ve.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{_(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!G)return;const ve=ot=>{le.current&&!le.current.contains(ot.target)&&ee(!1)};return document.addEventListener("click",ve),()=>document.removeEventListener("click",ve)},[G]),i.useEffect(()=>{if(!e.missionId){A(null);return}const ve=Cd.get(e.missionId);if(ve){A(ve);return}let ot=!1;return o0(e.missionId,n).then(Nt=>{ot||A(Nt)}),()=>{ot=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){F(null);return}const ve=Ed.get(e.assignedAgentId);if(ve){F(ve);return}F(null);let ot=!1;return c0(e.assignedAgentId,n).then(Nt=>{ot||F(Nt)}),()=>{ot=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(E&&k.current){const ve=k.current;ve.focus(),ve.style.height="auto",ve.style.height=ve.scrollHeight+"px"}},[E]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){ge(!0);return}const ve=oe.current;if(!ve)return;const ot=new IntersectionObserver(([Nt])=>{ge(Nt?.isIntersecting??!0)},{rootMargin:"200px"});return ot.observe(ve),()=>ot.disconnect()},[E,e.id]);const O=i.useCallback(ve=>{ve.dataTransfer.setData("text/plain",e.id),ve.dataTransfer.effectAllowed="move",y(!0)},[e.id]),ke=i.useCallback(()=>{y(!1)},[]),ae=i.useCallback(ve=>ve.dataTransfer.types.includes("Files"),[]),te=i.useCallback(ve=>{ae(ve)&&(ve.preventDefault(),ve.stopPropagation(),ve.dataTransfer.dropEffect="copy",N(!0))},[ae]),Ie=i.useCallback(ve=>{ae(ve)&&(ve.preventDefault(),ve.stopPropagation(),N(!1))},[ae]),Oe=i.useCallback(async ve=>{if(!ae(ve))return;ve.preventDefault(),ve.stopPropagation(),N(!1);const ot=Array.from(ve.dataTransfer.files);for(const Nt of ot)try{await Fl(e.id,Nt,n),r(`Attached ${Nt.name} to ${e.id}`,"success")}catch(Lt){r(`Failed to attach ${Nt.name}: ${Me(Lt)}`,"error")}},[e.id,ae,r]),He=i.useCallback(()=>{E||a(e)},[e,a,E]),$e=i.useCallback(ve=>{if(K.current){K.current=!1;return}B(ve.target)||He()},[He,B]),Te=i.useCallback(ve=>{const ot=ve.touches[0];ot&&(ie.current={x:ot.clientX,y:ot.clientY,time:Date.now()},se.current=!1)},[]),ue=i.useCallback(ve=>{if(!ie.current)return;const ot=ve.touches[0];if(!ot)return;const Nt=Math.abs(ot.clientX-ie.current.x),Lt=Math.abs(ot.clientY-ie.current.y);(Nt>zm||Lt>zm)&&(se.current=!0)},[]),ce=i.useCallback(ve=>{if(B(ve.target)||!ie.current)return;const Nt=Date.now()-ie.current.time<T0,Lt=!se.current;Nt&&Lt&&(K.current=!0,He()),ie.current=null,se.current=!1},[He,B]),Ae=i.useCallback(async(ve,ot)=>{ve.stopPropagation();try{const Nt=await er(ot,n);a(Nt)}catch{r(`Failed to load dependency ${ot}`,"error")}},[a,r]),Ne=e.status==="failed",ye=e.paused===!0,Ce=!!(e.paused&&e.pausedByAgentId),fe=d0(e.priority),Pe=fe!==Rs,De=xl(e,f,x),dt=e.column==="triage"&&e.status==="awaiting-approval",pt=e.column==="archived",lt=!o&&!s&&!Ne&&!ye&&!De&&!dt&&(e.column==="in-progress"||Rm.has(e.status)),vt=!s&&!ye&&!E&&!pt,_e=h0.has(e.column)&&!lt&&!ye&&!s&&l,Fe=!!(e.prInfo||e.issueInfo),bt=e.sourceType==="github_import",ht=i.useMemo(()=>w0(e),[e.id,e.branch,e.baseBranch]),Ee=!!(ht.branch||ht.baseBranch),me=S0(e.sourceMetadata),Re=m0(e),be=wg(e),Ke=be?`Created by agent: ${be}`:"Created by agent",pe=!!(e.assignedAgentId&&$===null),Xe=i.useMemo(()=>{const ve=[];return e.modelProvider&&ve.push(e.modelProvider),e.validatorModelProvider&&!ve.includes(e.validatorModelProvider)&&ve.push(e.validatorModelProvider),e.planningModelProvider&&!ve.includes(e.planningModelProvider)&&ve.push(e.planningModelProvider),ve},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),wt=i.useMemo(()=>gg(e,v),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,v]),gt=wt.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const ve=e.status!=null&&Im.has(e.status);if(e.column==="in-progress"){const Nt=Or(e,Date.now()),Lt=$m(e,Date.now()),$t=Fr(e,Date.now());if(Nt==null&&Lt==null&&$t==null)return}if(!ve&&e.column==="in-review"){const Nt=Or(e,Date.now()),Lt=Fr(e,Date.now());if(Nt==null&&Lt==null)return}L(Date.now());const ot=window.setInterval(()=>{L(Date.now())},g0);return()=>window.clearInterval(ot)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const Tt=i.useMemo(()=>{if(!f0.has(e.column))return null;if(e.status!=null&&Im.has(e.status)){const Wt=y0(e,T);if(Wt!=null){const Gt=Om(Wt);if(Gt){const sn=kg(e,T),on=sn==null?null:Dm(sn),Dn=on?`Execution time ${Gt}. Merge phase ${on}`:`Execution time ${Gt}. Merging`;return{label:Gt,title:Dn,ariaLabel:Dn}}}}if(e.column==="in-progress"){const Wt=Or(e,T)??$m(e,T)??Fr(e,T);if(Wt==null)return null;const Gt=Dm(Wt);return Gt?{label:Gt,title:`In progress ${Gt}`,ariaLabel:`In progress ${Gt}`}:null}const ot=Or(e,T)??Fr(e,T);if(ot==null)return null;const Nt=Om(ot);if(!Nt)return null;const Lt=v0(e);if(Lt==null)return{label:Nt,title:`Execution time ${Nt}`,ariaLabel:`Execution time ${Nt}`};const $t=new Date(Lt).toLocaleString();return{label:Nt,title:`Execution time ${Nt}. Completed ${$t}`,ariaLabel:`Execution time ${Nt}. Completed ${$t}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,T]);i.useEffect(()=>{if(!Fe||!we){Q(e.id);return}return Z(e.id),()=>{Q(e.id)}},[Fe,we,Z,e.id,Q]);const Zt=Ue.get(`${n??"default"}:${e.id}`),Ot=e.column==="in-progress"||e.column==="in-review",Rt=i.useMemo(()=>e.steps.map(ve=>`${ve.name}:${ve.status}`).join("|"),[e.steps]),{stats:en}=t0(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:we,worktree:e.worktree,stepVersion:Ot?Rt:void 0,pollIntervalMs:Ot?3e4:void 0}),zt=i.useMemo(()=>YS(e.id,n),[e.id,n]),Qt=i.useMemo(()=>{const ve=Zt?.prInfo,ot=Zt?.timestamp,Nt=zt?.result?.prInfo,Lt=zt?.timestamp?new Date(zt.timestamp).toISOString():void 0,$t=e.prInfo,Wt=e.prInfo?.lastCheckedAt??e.updatedAt;let Gt=bl(ve,ot,$t,Wt);const sn=ot&&ot>=Wt?ot:Wt;return Nt&&Lt&&(!sn||Lt>sn)&&(Gt=Nt),Gt},[Zt,zt,e.prInfo,e.updatedAt]),xn=i.useMemo(()=>{const ve=Zt?.issueInfo,ot=Zt?.timestamp,Nt=zt?.result?.issueInfo,Lt=zt?.timestamp?new Date(zt.timestamp).toISOString():void 0,$t=e.issueInfo,Wt=e.issueInfo?.lastCheckedAt??e.updatedAt;let Gt=bl(ve,ot,$t,Wt);const sn=ot&&ot>=Wt?ot:Wt;return Nt&&Lt&&(!sn||Lt>sn)&&(Gt=Nt),Gt},[Zt,zt,e.issueInfo,e.updatedAt]),Kt=i.useCallback(ve=>{ve?.stopPropagation(),!(!_e||D)&&(w(!0),_(e.description||""))},[_e,D,e.description]),Ut=i.useCallback(()=>{w(!1),_(e.description||"")},[e.description]),fn=i.useCallback(()=>j!==(e.description||""),[j,e.description]),un=i.useCallback(async()=>{if(!(!l||D)){if(!fn()){Ut();return}C(!0);try{await l(e.id,{description:j.trim()||void 0}),r(`Updated ${e.id}`,"success"),w(!1)}catch(ve){r(`Failed to update ${e.id}: ${Me(ve)}`,"error")}finally{C(!1)}}},[l,e.id,j,D,fn,Ut,r]),tn=i.useCallback(ve=>{ve.key==="Enter"&&!ve.shiftKey?(ve.preventDefault(),un()):ve.key==="Escape"&&(ve.preventDefault(),Ut())},[un,Ut]),Vt=i.useCallback(()=>{setTimeout(()=>{const ve=document.activeElement;ve===k.current||ve?.closest(".card-editing-content")||(fn()?un():Ut())},0)},[fn,un,Ut]),mn=i.useCallback(ve=>{_e&&(ve.stopPropagation(),Kt(ve))},[_e,Kt]),xe=i.useCallback(ve=>{ve.stopPropagation(),Kt(ve)},[Kt]),Le=i.useCallback(ve=>{_(ve.target.value);const ot=ve.target;ot.style.height="auto",ot.style.height=ot.scrollHeight+"px"},[]),Ve=i.useCallback(ve=>{ve.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(ot=>{r(`Failed to archive ${e.id}: ${Me(ot)}`,"error")})},[r,c,e.id]),at=i.useCallback(ve=>{ve.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(ot=>{r(`Failed to unarchive ${e.id}: ${Me(ot)}`,"error")})},[r,d,e.id]),Ge=i.useCallback(async ve=>{if(ve.stopPropagation(),!(!u||!await X({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(Nt){const Lt=C0(Nt);if(!Lt||Lt.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Me(Nt)}`,"error");return}const $t=Lt.dependentIds.join(", ");if(!await X({title:"Force Delete Task",message:`${e.id} is a dependency of ${$t}.
|
|
652
|
-
|
|
653
|
-
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await u(e.id,{removeDependencyReferences:!0}),r(`Deleted ${e.id} after removing dependency references`,"success")}catch(Gt){r(`Failed to delete ${e.id}: ${Me(Gt)}`,"error")}}},[r,X,u,e.id]),Ft=i.useCallback(ve=>{ve.stopPropagation(),h?.(e,"changes")},[e,h]),_t=i.useCallback(ve=>{ve.stopPropagation(),I(ot=>!ot)},[]),qt=i.useCallback(ve=>{ve.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),St=i.useCallback(ve=>{ve.stopPropagation(),ee(ot=>!ot)},[]),z=i.useCallback(async(ve,ot)=>{if(ve.stopPropagation(),ee(!1),!!g)try{const Nt=e.steps.some(Wt=>Wt.status!=="pending"),Lt=(ot==="todo"||ot==="triage")&&Nt;let $t;if(Lt){if(await X({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))$t={preserveProgress:!0};else if(!await X({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await g(e.id,ot,$t),r(`Moved ${e.id} to ${ds[ot]}`,"success")}catch(Nt){r(`Failed to move ${e.id}: ${Me(Nt)}`,"error")}},[r,X,g,e.id,e.steps]),he=i.useCallback(async ve=>{if(ve.stopPropagation(),!(!m||J)){M(!0);try{await m(e.id)}catch(ot){r(`Failed to retry ${e.id}: ${Me(ot)}`,"error")}finally{M(!1)}}},[r,J,m,e.id]),st=`card${b?" dragging":""}${s?" queued":""}${lt?" agent-active":""}${Ne?" failed":""}${ye?" paused":""}${De?" stuck":""}${dt?" awaiting-approval":""}${S?" file-drop-target":""}${E?" card-editing":""}${D?" card-saving":""}`,It=(()=>{if(e.column==="in-progress"){const ve=en?.filesChanged,ot=ve==null||ve===0?e.modifiedFiles?.length:void 0,Nt=ve!=null&&ve>0?ve:ot;return Nt==null||Nt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ft,disabled:!h,children:[t.jsx(vs,{size:12}),t.jsxs("span",{children:[Nt," ",Nt===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const ve=en?.filesChanged,ot=ve==null||ve===0?e.modifiedFiles?.length:void 0,Nt=ve!=null&&ve>0?ve:ot;return Nt==null||Nt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ft,disabled:!h,children:[t.jsx(vs,{size:12}),t.jsxs("span",{children:[Nt," ",Nt===1?"file":"files"," changed"]})]})}if(e.column==="done"){const ve=en?.filesChanged,ot=e.mergeDetails?.filesChanged,Nt=ve??ot;if(Nt!=null&&Nt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ft,disabled:!h,children:[t.jsx(vs,{size:12}),t.jsxs("span",{children:[Nt," ",Nt===1?"file":"files"," changed"]})]});const Lt=e.modifiedFiles?.length;if(Lt!=null&&Lt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ft,disabled:!h,children:[t.jsx(vs,{size:12}),t.jsxs("span",{children:[Lt," ",Lt===1?"file":"files"," changed"]})]})}return null})();return E?t.jsx("div",{ref:oe,className:st,"data-id":e.id,onDoubleClick:mn,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:k,className:"card-edit-desc-textarea",placeholder:"Task description",value:j,onChange:Le,onKeyDown:tn,onBlur:Vt,disabled:D,rows:4}),D&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:oe,className:st,"data-id":e.id,draggable:vt,onDragStart:vt?O:void 0,onDragEnd:vt?ke:void 0,onDragOver:te,onDragLeave:Ie,onDrop:Oe,onClick:$e,onTouchStart:Te,onTouchMove:ue,onTouchEnd:ce,onDoubleClick:mn,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),ye&&t.jsx("span",{className:"card-status-badge paused",children:Ce?"paused by agent":"paused"}),!ye&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${dt?" awaiting-approval":""}${Rm.has(e.status)?" pulsing":""}${Ne?" failed":""}${De?" stuck":""}`,children:De?"Stuck":dt?"Awaiting Approval":b0(e.status)}),De&&(ye||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),Fe&&t.jsx(hg,{prInfo:Qt,issueInfo:xn}),Re&&t.jsxs("span",{className:"card-agent-created-badge",title:Ke,"aria-label":Ke,children:[t.jsx(zn,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:Ke}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),Pe&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${fe}`,children:fe}),e.executionMode==="fast"&&t.jsxs("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(us,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:qt,title:`Mission: ${H??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(Ms,{size:11}),l0(H??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[_e&&t.jsx("button",{className:"card-edit-btn",onClick:xe,title:"Edit task","aria-label":"Edit task",children:t.jsx(Ss,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:Ge,title:"Delete task","aria-label":"Delete task",children:t.jsx(En,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Ve,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:at,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:le,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:St,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":G,children:["Send back",t.jsx(cn,{size:10})]}),G&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Nd["in-progress"].filter(ve=>ve!=="in-review").map(ve=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ot=>z(ot,ve),children:ds[ve]},ve))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:le,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:St,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":G,children:["Move",t.jsx(cn,{size:10})]}),G&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:Nd["in-review"].map(ve=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:ot=>z(ot,ve),children:ve==="done"?"Done (no merge)":ds[ve]},ve))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Ne&&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:he,disabled:J,children:[t.jsx(Jy,{size:12}),J?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Bm(e.title,Um)||Bm(e.description,Um)||e.id}),Ee&&t.jsxs("div",{className:"card-branch-row","aria-label":"Branch metadata",children:[ht.branch&&t.jsxs("span",{className:"card-branch-chip",title:ht.branch,children:[t.jsx("span",{className:"card-branch-label",children:"Branch"}),t.jsx("span",{className:"card-branch-value",children:ht.branch})]}),ht.baseBranch&&t.jsxs("span",{className:"card-branch-chip",title:ht.baseBranch,children:[t.jsx("span",{className:"card-branch-label",children:"Base"}),t.jsx("span",{className:"card-branch-value",children:ht.baseBranch})]})]}),gt&&(()=>{const ve=wt.completed/wt.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:`${ve}%`,backgroundColor:p0[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[wt.completed,"/",wt.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:_t,"aria-expanded":P,"aria-label":P?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[wt.total," step",wt.total===1?"":"s"]}),t.jsx(cn,{size:14,className:`card-steps-toggle-icon${P?" expanded":""}`})]}),P&&t.jsx("div",{className:"card-steps-list",children:wt.items.map(ot=>{const Nt=ot.source==="workflow"&&ot.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${ot.status}${Nt?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${ot.status==="done"?" completed":""}`,children:ot.name}),ot.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${ot.phase}`,title:"Workflow check",children:"workflow"})]},ot.id)})})]})})(),(It||Tt||bt)&&t.jsxs("div",{className:"card-footer-row",children:[It,bt&&t.jsx("span",{className:"card-source-provenance",title:me?`Imported from GitHub: ${me}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Jn,{provider:"github",size:"sm"})}),Tt&&t.jsxs("span",{className:"card-time-indicator",title:Tt.title,"aria-label":Tt.ariaLabel,children:[t.jsx(zi,{size:12}),t.jsx("span",{children:Tt.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(ve=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:ot=>void Ae(ot,ve),title:`Click to view ${ve}`,children:[t.jsx(Qa,{size:12,style:{verticalAlign:"middle"}})," ",ve]},ve))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(ga,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(zi,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Xe.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Xe.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Xe.map(ve=>t.jsx(Jn,{provider:ve,size:"sm"},ve))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${pe?" card-agent-badge--loading":""}`,title:`Assigned to ${$??e.assignedAgentId}`,children:[t.jsx(zn,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:u0($??e.assignedAgentId,15)})]})]}),t.jsx(Zi,{slotId:"task-card-badge",projectId:n})]})}const zm=10,T0=300,Um=140;function Bm(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const to=i.memo(P0,A0);to.displayName="TaskCard";function R0({label:e,activeTasks:n,queuedTasks:s,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,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(hv,{size:14}):t.jsx(zs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(g=>t.jsx(to,{task:g,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id)),s.map(g=>t.jsx(to,{task:g,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p},g.id))]})}const jg=i.memo(R0);jg.displayName="WorktreeGroup";function Hm(e){return e.toLowerCase().replace(/[-_./]/g,"")}function I0(e,n){let s=0;for(let a=0;a<n.length&&s<e.length;a++)e[s]===n[a]&&s++;return s===e.length}function $0(e,n,s){const a=e.length,r=n.length;if(a===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<=a;c++){const d=new Array(r+1);d[0]=c;for(let u=1;u<=r;u++){const m=e[c-1]===n[u-1]?0:1;d[u]=Math.min(l[u]+1,d[u-1]+1,l[u-1]+m),c>=2&&u>=2&&e[c-1]===n[u-2]&&e[c-2]===n[u-1]&&(d[u]=Math.min(d[u],o[u-2]+1))}o=l,l=d}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function D0(e,n){const s=Hm(e),a=Hm(n);if(s.length===0||a.includes(s))return!0;const r=a.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&I0(s,o)||s.length>=4&&$0(s,o,1))return!0;return!1}function L0(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(a=>{const r=`${a.provider} ${a.id} ${a.name}`;return s.every(o=>D0(o,r))})}function ks({models:e,value:n,onChange:s,placeholder:a="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:d,favoriteModels:u=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:f="No change"}){const[p,g]=i.useState(!1),[x,v]=i.useState(""),[b,y]=i.useState(0),[S,N]=i.useState(null),[E,w]=i.useState(null),j=i.useRef(null),_=i.useRef(null),D=i.useRef(null),C=i.useRef(null),P=i.useRef(null),I=i.useMemo(()=>L0(e,x),[e,x]),H=i.useMemo(()=>I.reduce((X,ie)=>((X[ie.provider]??=[]).push(ie),X),{}),[I]),A=i.useMemo(()=>{const X=[];for(const ie of u){const se=ie.indexOf("/");if(se===-1)continue;const B=ie.slice(0,se),O=ie.slice(se+1),ke=I.find(ae=>ae.provider===B&&ae.id===O);ke&&X.push({model:ke,fullId:ie})}return X},[u,I]),$=i.useMemo(()=>{const X=Object.entries(H),ie=new Set(c);return X.sort(([se],[B])=>{const O=ie.has(se),ke=ie.has(B);if(O&&!ke)return-1;if(!O&&ke)return 1;if(O&&ke){const ae=c.indexOf(se),te=c.indexOf(B);if(ae!==te)return ae-te}return se.localeCompare(B)})},[H,c]),F=typeof h=="string"&&h.length>0,G=i.useMemo(()=>{if(!n||F&&n===h)return null;const X=n.indexOf("/");return X===-1?null:n.slice(0,X)},[F,h,n]),ee=i.useMemo(()=>{const X=[];return F&&X.push({type:"no-change",value:h,label:f}),X.push({type:"default",value:"",label:"Use default"}),X},[F,f,h]),J=i.useMemo(()=>{const X=[...ee];for(const{model:ie,fullId:se}of A)X.push({type:"favorite",value:se,label:ie.name,provider:ie.provider});return $.forEach(([ie,se])=>{X.push({type:"provider",value:`__group_${ie}`,label:ie,provider:ie}),se.forEach(B=>{X.push({type:"model",value:`${B.provider}/${B.id}`,label:B.name,provider:B.provider})})}),X},[A,$,ee]),M=i.useMemo(()=>{if(F&&n===h)return f;if(!n)return"Use default";const X=n.indexOf("/");if(X===-1)return n;const ie=n.slice(0,X),se=n.slice(X+1);return e.find(O=>O.provider===ie&&O.id===se)?.name||n},[F,f,h,n,e]),T=i.useMemo(()=>J.findIndex(X=>X.value===n),[J,n]),L=i.useCallback(()=>{const X=window.visualViewport;return X&&X.height>0&&X.width>0?{width:X.width,height:X.height,offsetTop:X.offsetTop,offsetLeft:X.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),k=i.useCallback(()=>{const{height:X}=L(),ie=typeof window.matchMedia=="function",se=ie?window.matchMedia("(max-width: 640px)").matches:!1,B=ie?window.matchMedia("(max-width: 768px)").matches:!1;return X<=0?320:se?Math.min(X*.6,360):B?Math.min(X*.7,420):320},[L]),K=i.useCallback(()=>{const X=_.current;if(!X)return;const ie=X.getBoundingClientRect(),{width:se,height:B,offsetTop:O,offsetLeft:ke}=L(),ae=16,te=16,Ie=4,Oe=k(),He=ie.bottom-O,$e=ie.top-O,Te=ie.left-ke,ue=B-He,ce=$e,Ae=Math.max(ue-te-Ie,160),Ne=Math.max(ce-te-Ie,160),ye=ue<Oe&&ce>ue,Ce=Math.max(Math.min(ye?Ne:Ae,Oe),160),fe=Math.min(ie.width,se-ae*2),Pe=Math.min(Math.max(Te,ae),se-ae-fe)+ke,De=ye?Math.max(te+O,$e-Ce-Ie+O):Math.min(He+Ie+O,B+O-te-Ce);N({top:De,left:Pe,width:fe,maxHeight:Ce})},[L,k]);i.useEffect(()=>{w(document.body)},[]);const oe=i.useRef(!1);i.useEffect(()=>{if(!p){oe.current=!1;return}if(oe.current||J.length===0)return;const X=J.findIndex((ie,se)=>se>=(T>=0?T:0)&&ie.type!=="provider");y(X>=0?X:0),oe.current=!0},[p,J,T]),i.useEffect(()=>{p&&oe.current&&(y(0),P.current&&(P.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;K();const X=requestAnimationFrame(()=>C.current?.focus());return()=>cancelAnimationFrame(X)},[p,K]),i.useEffect(()=>{if(!p)return;const X=()=>K();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const ie=window.visualViewport;return ie&&(ie.addEventListener("resize",X),ie.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),ie&&(ie.removeEventListener("resize",X),ie.removeEventListener("scroll",X))}},[p,K]),i.useEffect(()=>{if(!p)return;const X=ie=>{const se=ie.target,B=j.current?.contains(se),O=D.current?.contains(se);!B&&!O&&(g(!1),v(""))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[p]);const le=i.useCallback(X=>{switch(X.key){case"ArrowDown":if(X.preventDefault(),!p)g(!0);else{let ie=b;for(let se=1;se<=J.length;se++){const B=(b+se)%J.length;if(J[B]?.type!=="provider"){ie=B;break}}y(ie)}break;case"ArrowUp":if(X.preventDefault(),p){let ie=b;for(let se=1;se<=J.length;se++){const B=(b-se+J.length)%J.length;if(J[B]?.type!=="provider"){ie=B;break}}y(ie)}break;case"Enter":if(X.preventDefault(),p){const ie=J[b];ie&&ie.type!=="provider"&&ie.type!=="favorite"&&(s(ie.value),g(!1),v(""))}else g(!0);break;case"Escape":X.preventDefault(),g(!1),v("");break;case"Tab":p&&(g(!1),v(""));break}},[p,b,J,s]),we=i.useCallback(X=>{s(X),g(!1),v("")},[s]),ge=i.useCallback(()=>{v(""),C.current?.focus()},[]),Ue=i.useCallback(()=>{r||g(X=>!X)},[r]);i.useEffect(()=>{if(p&&P.current){const X=P.current.querySelector(`[data-index="${b}"]`);X&&typeof X.scrollIntoView=="function"&&X.scrollIntoView({block:"nearest"})}},[b,p]);const Z=x.length>0,Q=p&&S?t.jsxs("div",{ref:D,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:le,style:{top:`${S.top}px`,left:`${S.left}px`,width:`${S.width}px`,maxHeight:`${S.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:C,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:X=>v(X.target.value),onClick:X=>X.stopPropagation()}),Z&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:ge,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[I.length," model",I.length!==1?"s":""]}),t.jsxs("div",{ref:P,className:"model-combobox-list",children:[ee.map((X,ie)=>t.jsx("div",{"data-index":ie,className:`model-combobox-option ${b===ie?"model-combobox-option--highlighted":""} ${n===X.value?"model-combobox-option--selected":""}`,onClick:()=>we(X.value),onMouseEnter:()=>y(ie),role:"option","aria-selected":n===X.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:X.label})},`${X.type}-${X.value}`)),A.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),A.map(({model:X,fullId:ie},se)=>{const B=se+ee.length,O=b===B,ke=n===ie;return t.jsxs("div",{"data-index":B,className:`model-combobox-option model-combobox-option--favorite ${O?"model-combobox-option--highlighted":""} ${ke?"model-combobox-option--selected":""}`,onClick:()=>we(ie),onMouseEnter:()=>y(B),role:"option","aria-selected":ke,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Jn,{provider:X.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:X.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:X.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:ae=>{ae.stopPropagation(),m(ie)},title:"Remove from favorites","aria-label":`Remove ${X.name} from favorites`,children:"★"})]},ie)}),t.jsx("div",{className:"model-combobox-divider"})]}),$.map(([X,ie])=>{const se=J.findIndex(ke=>ke.value===`__group_${X}`),B=c.includes(X),O=ie.filter(ke=>{const ae=`${ke.provider}/${ke.id}`;return!u.includes(ae)});return O.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":se,children:[t.jsx(Jn,{provider:X,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:X}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${B?"model-combobox-optgroup-favorite--active":""}`,onClick:ke=>{ke.stopPropagation(),d(X)},title:B?"Remove from favorites":"Add to favorites","aria-label":B?`Remove ${X} from favorites`:`Add ${X} to favorites`,children:"★"})]}),O.map(ke=>{const ae=`${ke.provider}/${ke.id}`,te=J.findIndex($e=>$e.value===ae),Ie=b===te,Oe=n===ae,He=u.includes(ae);return t.jsxs("div",{"data-index":te,className:`model-combobox-option ${Ie?"model-combobox-option--highlighted":""} ${Oe?"model-combobox-option--selected":""}`,onClick:()=>we(ae),onMouseEnter:()=>y(te),role:"option","aria-selected":Oe,children:[t.jsx("span",{className:"model-combobox-option-text",children:ke.name}),t.jsx("span",{className:"model-combobox-option-id",children:ke.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${He?"model-combobox-option-favorite--active":""}`,onClick:$e=>{$e.stopPropagation(),m(ae)},title:He?"Remove from favorites":"Add to favorites","aria-label":He?`Remove ${ke.name} from favorites`:`Add ${ke.name} to favorites`,children:He?"★":"☆"})]},ae)})]},X)}),I.length===0&&Z&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:j,className:"model-combobox",onKeyDown:le,children:t.jsxs("button",{ref:_,type:"button",id:o,className:"model-combobox-trigger",onClick:Ue,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[G&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Jn,{provider:G,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:M||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),E&&Q?ha.createPortal(Q,E):null]})}function lu(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function ss(e,n){return typeof window>"u"?null:window.localStorage.getItem(lu(e,n))}function xs(e,n,s){typeof window>"u"||window.localStorage.setItem(lu(e,s),n)}function sr(e,n){typeof window>"u"||window.localStorage.removeItem(lu(e,n))}const O0=1e4,F0=1e3;function Bl(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const v=await pl();n(v)}catch(v){o(v instanceof Error?v.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let v=!1;async function b(){a(!0);try{const S=await pl();v||(n(S),o(null))}catch(S){v||o(S instanceof Error?S.message:"Failed to fetch nodes")}finally{v||a(!1)}}b();const y=()=>{if(document.visibilityState!=="visible")return;const S=Date.now();S-c.current<F0||(c.current=S,d())};return document.addEventListener("visibilitychange",y),()=>{v=!0,document.removeEventListener("visibilitychange",y)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},O0),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async v=>{const b=await hN(v);return n(y=>[...y,b]),b},[]),m=i.useCallback(async(v,b)=>{const y=await pN(v,b);return n(S=>S.map(N=>N.id===v?y:N)),y},[]),h=i.useCallback(async v=>{await xN(v),n(b=>b.filter(y=>y.id!==v))},[]),f=i.useCallback(async v=>{const b=await vN(v);n(y=>y.map(S=>S.id===v?{...S,status:b.status,updatedAt:b.checkedAt}:S))},[]),p=i.useCallback(v=>fN(v),[]),g=i.useCallback(async(v,b)=>{const y=await gN(v,b);return n(S=>S.map(N=>N.id===v?{...N,dockerConfig:y}:N)),y},[]),x=i.useCallback(async v=>{const b=await bN(v);return"persistedVersion"in b?b:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f,fetchDockerConfig:p,patchDockerConfig:g,fetchDockerDiff:x}}const jr="kb-quick-entry-text",z0=["image/png","image/jpeg","image/gif","image/webp"];function U0(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function pc(e,n){return e&&n?`${e}/${n}`:""}function fc(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 Ng({onCreate:e,addToast:n,tasks:s=[],availableModels:a,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:d,favoriteModels:u,onToggleFavorite:m,onToggleModelFavorite:h}){const[f,p]=i.useState(()=>typeof window<"u"&&ss(jr,l)||""),[g,x]=i.useState(!1),[v,b]=i.useState(!1),[y,S]=i.useState(!1),N=i.useRef(null),E=i.useRef(null),w=i.useRef(!1),j=i.useRef(l),[_,D]=i.useState([]),C=i.useRef([]),[P,I]=i.useState([]),[H,A]=i.useState(!1),[$,F]=i.useState(""),[G,ee]=i.useState(null),[J,M]=i.useState([]),[T,L]=i.useState(void 0),[k,K]=i.useState(!1),[oe,le]=i.useState(!1),[we,ge]=i.useState(!1),[Ue,Z]=i.useState(!1),[Q,X]=i.useState(!1),[ie,se]=i.useState(null),[B,O]=i.useState(void 0),[ke,ae]=i.useState(void 0),[te,Ie]=i.useState(void 0),[Oe,He]=i.useState(void 0),[$e,Te]=i.useState(void 0),[ue,ce]=i.useState(void 0),Ae=i.useRef(null),Ne=i.useRef(null),ye=i.useRef(null),Ce=i.useRef(null),fe=i.useRef(null),Pe=i.useRef(null),De=i.useRef(null),dt=i.useRef(null),[pt,lt]=i.useState(null),[vt,_e]=i.useState(null),[Fe,bt]=i.useState(null),[ht,Ee]=i.useState(null),me=i.useRef(null),Re=i.useRef(null),[be,Ke]=i.useState(null),[pe]=i.useState(()=>typeof document<"u"?document.body:null),[Xe,wt]=i.useState(!1),[gt,Tt]=i.useState(null),[Zt,Ot]=i.useState(a??[]),[Rt,en]=i.useState([]),[zt,Qt]=i.useState([]),[xn,Kt]=i.useState(null),[Ut,fn]=i.useState(void 0),[un,tn]=i.useState(!1),[Vt,mn]=i.useState(Rs),[xe,Le]=i.useState(void 0),[Ve,at]=i.useState(""),[Ge,Ft]=i.useState(""),{nodes:_t}=Bl(),[qt,St]=i.useState(!1),[z,he]=i.useState(!1),st=i.useRef(null),It=i.useRef(null),[ve,ot]=i.useState(null),Nt=d??Rt,Lt=u??zt,$t=!e;i.useEffect(()=>{if(a)Ot(a),wt(!1),Tt(null);else{let q=!1;return wt(!0),Tt(null),$s().then(Se=>{q||(Ot(Se.models),d||en(Se.favoriteProviders),u||Qt(Se.favoriteModels))}).catch(Se=>{q||Tt(Me(Se)||"Failed to load models")}).finally(()=>{q||wt(!1)}),Ol(l).then(Se=>{q||Kt(Se)}).catch(()=>{}),()=>{q=!0}}},[a,d,u,l]);const Wt=pc(B,ke),Gt=pc(te,Oe),sn=pc($e,ue),on=!!(B&&ke),Dn=!!(te&&Oe),Jt=!!($e&&ue),Hn=Number(on)+Number(Dn)+Number(Jt),Yn=Ut?xn?.modelPresets?.find(q=>q.id===Ut)?.name??"Models":Hn>0?`${Hn} model${Hn===1?"":"s"}`:"Models",re=i.useCallback((q,Se)=>{if(!q||!Se)return"Using default";const Ze=Zt.find(At=>At.provider===q&&At.id===Se);return Ze?`${Ze.provider}/${Ze.id}`:`${q}/${Se}`},[Zt]);i.useEffect(()=>{p(ss(jr,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&xs(jr,f,l)},[f,l]),i.useEffect(()=>{j.current!==l&&(j.current=l,M([]),L(void 0),ee(null),K(!1),lt(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{C.current=_},[_]),i.useEffect(()=>()=>{C.current.forEach(q=>URL.revokeObjectURL(q.previewUrl))},[]);const rt=i.useCallback(()=>{const q=N.current;if(!q)return;q.style.height="auto";const Se=Math.min(q.scrollHeight,200);q.style.height=`${Se}px`},[]);i.useEffect(()=>{v&&rt()},[f,v,rt]),i.useEffect(()=>{if(!g&&f===""&&N.current){const q=setTimeout(()=>{N.current?.focus()},0);return()=>clearTimeout(q)}},[g,f]),i.useEffect(()=>{H||F("")},[H]),i.useEffect(()=>{if(!qt)return;const q=Se=>{const Ze=Se.target,At=st.current?.contains(Ze),Et=It.current?.contains(Ze);!At&&!Et&&St(!1)};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[qt]),i.useEffect(()=>{if(!Q)return;const q=Se=>{const Ze=Se.target,At=Ae.current?.contains(Ze),Et=Ne.current?.contains(Ze),Cn=Ze instanceof Element&&Ze.closest?.(".model-combobox-dropdown--portal")!=null;!At&&!Et&&!Cn&&(X(!1),se(null))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[Q]),i.useEffect(()=>{if(!oe)return;const q=Se=>{const Ze=Se.target;fe.current?.contains(Ze)||Pe.current?.contains(Ze)||(le(!1),_e(null))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[oe]),i.useEffect(()=>{if(!k)return;const q=Se=>{const Ze=Se.target;ye.current?.contains(Ze)||Ce.current?.contains(Ze)||(K(!1),lt(null))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[k]),i.useEffect(()=>{if(!we)return;const q=Se=>{const Ze=Se.target;De.current?.contains(Ze)||dt.current?.contains(Ze)||(ge(!1),bt(null))};return document.addEventListener("mousedown",q),()=>document.removeEventListener("mousedown",q)},[we]);const ct=i.useCallback(()=>{_.forEach(q=>URL.revokeObjectURL(q.previewUrl)),D([]),E.current&&(E.current.value=""),p(""),I([]),ee(null),K(!1),lt(null),le(!1),_e(null),ge(!1),bt(null),O(void 0),ae(void 0),Ie(void 0),He(void 0),Te(void 0),ce(void 0),fn(void 0),tn(!1),mn(Rs),Le(void 0),at(""),Ft(""),A(!1),X(!1),Ee(null),se(null),St(!1),he(!1),b(!1),S(!1),w.current=!0,N.current&&(N.current.style.height="auto"),typeof window<"u"&&sr(jr,l)},[_,l]),ft=i.useCallback(q=>{if(!q||q.length===0)return;const Se=[];for(let Ze=0;Ze<q.length;Ze++){const At=q[Ze];z0.includes(At.type)&&Se.push({file:At,previewUrl:URL.createObjectURL(At)})}Se.length>0&&D(Ze=>[...Ze,...Se])},[]),it=i.useCallback(q=>{g||ft(q.clipboardData?.files)},[ft,g]),Y=i.useCallback(q=>{D(Se=>{const Ze=Se[q];return Ze&&URL.revokeObjectURL(Ze.previewUrl),Se.filter((At,Et)=>Et!==q)})},[]),Ye=i.useCallback(async()=>{const q=f.trim();if(!q||g||!e)return;const Se=f;x(!0),p("");try{const Ze=await e({description:q,column:"triage",dependencies:P.length?P:void 0,...G?{assignedAgentId:G}:{},modelPresetId:Ut,modelProvider:on?B:void 0,modelId:on?ke:void 0,validatorModelProvider:Dn?te:void 0,validatorModelId:Dn?Oe:void 0,planningModelProvider:Jt?$e:void 0,planningModelId:Jt?ue:void 0,...un?{executionMode:"fast"}:{},priority:Vt,nodeId:xe,branch:Ve.trim()===""?void 0:Ve.trim(),baseBranch:Ge.trim()===""?void 0:Ge.trim()});if(Ze&&_.length>0){const At=[];for(const Et of _)try{await Fl(Ze.id,Et.file,l)}catch{At.push(Et.file.name)}At.length>0&&n(`Failed to upload: ${At.join(", ")}`,"error")}ct()}catch(Ze){p(Se),n(Me(Ze)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,P,G,on,B,ke,Dn,te,Oe,Jt,$e,ue,_,l,n,ct,un,Vt,xe,Ve,Ge]),Yt=i.useCallback(q=>{if(q.key==="Enter"){if(q.shiftKey&&v)return;q.preventDefault(),Ye()}else if(q.key==="Escape"){if(q.preventDefault(),ie){se(null);return}if(Q){X(!1),Ee(null);return}if(H){A(!1);return}if(qt){St(!1);return}if(oe){le(!1),_e(null);return}if(we){ge(!1),bt(null);return}if(k){K(!1),lt(null);return}f.trim()&&(p(""),N.current&&(N.current.style.height="auto"),typeof window<"u"&&sr(jr,l)),b(!1),S(!1),N.current?.blur()}},[Ye,f,v,H,k,oe,Q,ie,qt,we,l,S]),In=i.useCallback(()=>{w.current&&(w.current=!1)},[]),cs=i.useCallback(()=>{c&&b(!0)},[c]),gn=i.useCallback(q=>{I(Se=>Se.includes(q)?Se.filter(Ze=>Ze!==q):[...Se,q])},[]),Nn=i.useCallback(()=>{const q=window.visualViewport;return q&&q.width>0&&q.height>0?{width:q.width,height:q.height,offsetTop:q.offsetTop,offsetLeft:q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ms=i.useCallback(()=>{const q=Ae.current;if(!q)return;const Se=q.getBoundingClientRect(),{width:Ze,height:At,offsetTop:Et,offsetLeft:Cn}=Nn(),rn=16,yn=16,kn=4,Ln=Ze<=768,is=Math.min(Ln?At*.6:At*.5,360),fs=Math.max(Se.width*1.35,320),On=Ln?Math.min(Ze-rn*2,360):fs,qn=Math.min(On,Math.max(Ze-rn*2,240)),wn=Se.top-Et,Xn=Se.bottom-Et,Vn=Se.left-Cn,as=At-Xn,Fn=wn,ys=Math.max(as-yn-kn,160),Wn=Math.max(Fn-yn-kn,160),ns=as<is&&Fn>as,js=Math.max(Math.min(ns?Wn:ys,is),160),Ds=Math.min(Math.max(Vn,rn),Ze-rn-qn)+Cn,qi=ns?Math.max(yn+Et,wn-js-kn+Et):Math.min(Xn+kn+Et,At+Et-yn-js);Ee({top:qi,left:Ds,width:qn,maxHeight:js})},[Nn]),vn=i.useCallback(()=>{const q=st.current?.querySelector(".refine-button");if(!q)return;const Se=q.getBoundingClientRect(),{width:Ze,height:At,offsetTop:Et,offsetLeft:Cn}=Nn(),rn=8,yn=12,kn=4,Ln=Math.min(200,Math.max(At-yn*2,160)),is=Math.min(200,Ze-rn*2),fs=Se.top-Et,On=Se.bottom-Et,qn=Se.left-Cn,wn=At-On,Xn=fs,Vn=wn<Ln&&Xn>wn,as=Math.min(Math.max(qn,rn),Ze-rn-is)+Cn,Fn=Vn?Math.max(yn+Et,fs-Ln-kn+Et):Math.min(On+kn+Et,At+Et-yn-Ln);ot({top:Fn,left:as})},[Nn]),bn=i.useCallback(()=>{const q=me.current;if(!q)return;const Se=q.getBoundingClientRect(),{width:Ze,height:At,offsetTop:Et,offsetLeft:Cn}=Nn(),rn=16,yn=16,kn=4,Ln=Ze<=768,is=Math.min(Ln?At*.6:At*.5,320),fs=Ln?Math.min(Ze-rn*2,360):Math.max(Se.width,280),On=Math.min(fs,Math.max(Ze-rn*2,240)),qn=Se.top-Et,wn=Se.bottom-Et,Xn=Se.left-Cn,Vn=At-wn,as=qn,Fn=Math.max(Vn-yn-kn,200),ys=Math.max(as-yn-kn,200),Wn=Vn<is&&as>Vn,ns=Math.max(Math.min(Wn?ys:Fn,is),200),js=Math.min(Math.max(Xn,rn),Ze-rn-On)+Cn,Ds=Wn?Math.max(yn+Et,qn-ns-kn+Et):Math.min(wn+kn+Et,At+Et-yn-ns);Ke({top:Ds,left:js,width:On,maxHeight:ns})},[Nn]),Pt=i.useCallback(()=>{const q=ye.current?.querySelector("button");if(!q)return;const Se=q.getBoundingClientRect(),{width:Ze,height:At,offsetTop:Et,offsetLeft:Cn}=Nn(),rn=16,yn=16,kn=4,Ln=Ze<=768,is=Math.min(Ln?At*.6:At*.5,320),fs=Ln?Math.min(Ze-rn*2,280):Math.max(Se.width,240),On=Math.min(fs,Math.max(Ze-rn*2,200)),qn=Se.top-Et,wn=Se.bottom-Et,Xn=Se.left-Cn,Vn=At-wn,as=qn,Fn=Math.max(Vn-yn-kn,160),ys=Math.max(as-yn-kn,160),Wn=Vn<is&&as>Vn,ns=Math.max(Math.min(Wn?ys:Fn,is),160),js=Math.min(Math.max(Xn,rn),Ze-rn-On)+Cn,Ds=Wn?Math.max(yn+Et,qn-ns-kn+Et):Math.min(wn+kn+Et,At+Et-yn-ns);lt({top:Ds,left:js,width:On,maxHeight:ns})},[Nn]),Qn=i.useCallback(()=>{const q=fe.current?.querySelector("button");if(!q)return;const Se=q.getBoundingClientRect(),{width:Ze,height:At,offsetTop:Et,offsetLeft:Cn}=Nn(),rn=16,yn=16,kn=4,Ln=Ze<=768,is=Math.min(Ln?At*.6:At*.5,320),fs=Ln?Math.min(Ze-rn*2,280):Math.max(Se.width,240),On=Math.min(fs,Math.max(Ze-rn*2,200)),qn=Se.top-Et,wn=Se.bottom-Et,Xn=Se.left-Cn,Vn=At-wn,as=qn,Fn=Math.max(Vn-yn-kn,160),ys=Math.max(as-yn-kn,160),Wn=Vn<is&&as>Vn,ns=Math.max(Math.min(Wn?ys:Fn,is),160),js=Math.min(Math.max(Xn,rn),Ze-rn-On)+Cn,Ds=Wn?Math.max(yn+Et,qn-ns-kn+Et):Math.min(wn+kn+Et,At+Et-yn-ns);_e({top:Ds,left:js,width:On,maxHeight:ns})},[Nn]),es=i.useCallback(()=>{const q=De.current?.querySelector("button");if(!q)return;const Se=q.getBoundingClientRect(),{width:Ze,height:At,offsetTop:Et,offsetLeft:Cn}=Nn(),rn=16,yn=16,kn=4,Ln=220,is=Math.min(Math.max(Se.width,200),Math.max(Ze-rn*2,200)),fs=Se.top-Et,On=Se.bottom-Et,qn=Se.left-Cn,wn=At-On,Xn=fs,Vn=Math.max(wn-yn-kn,160),as=Math.max(Xn-yn-kn,160),Fn=wn<Ln&&Xn>wn,ys=Math.max(Math.min(Fn?as:Vn,Ln),160),Wn=Math.min(Math.max(qn,rn),Ze-rn-is)+Cn,ns=Fn?Math.max(yn+Et,fs-ys-kn+Et):Math.min(On+kn+Et,At+Et-yn-ys);bt({top:ns,left:Wn,width:is,maxHeight:ys})},[Nn]);i.useEffect(()=>{if(!Q)return;const q=()=>ms();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",q),Se.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),Se&&(Se.removeEventListener("resize",q),Se.removeEventListener("scroll",q))}},[Q,ms]),i.useEffect(()=>{if(!qt)return;const q=()=>vn();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",q),Se.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),Se&&(Se.removeEventListener("resize",q),Se.removeEventListener("scroll",q))}},[qt,vn]),i.useEffect(()=>{if(!H)return;const q=()=>bn();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",q),Se.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),Se&&(Se.removeEventListener("resize",q),Se.removeEventListener("scroll",q))}},[H,bn]),i.useEffect(()=>{if(!k)return;const q=()=>Pt();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",q),Se.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),Se&&(Se.removeEventListener("resize",q),Se.removeEventListener("scroll",q))}},[k,Pt]),i.useEffect(()=>{if(!oe)return;const q=()=>Qn();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",q),Se.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),Se&&(Se.removeEventListener("resize",q),Se.removeEventListener("scroll",q))}},[oe,Qn]),i.useEffect(()=>{if(!we)return;const q=()=>es();window.addEventListener("resize",q),window.addEventListener("scroll",q,!0);const Se=window.visualViewport;return Se&&(Se.addEventListener("resize",q),Se.addEventListener("scroll",q)),()=>{window.removeEventListener("resize",q),window.removeEventListener("scroll",q,!0),Se&&(Se.removeEventListener("resize",q),Se.removeEventListener("scroll",q))}},[we,es]);const W=i.useCallback(q=>{const Se=fc(q);Te(Se.provider),ce(Se.modelId)},[]),qe=i.useCallback(q=>{const Se=fc(q);O(Se.provider),ae(Se.modelId)},[]),Je=i.useCallback(q=>{const Se=fc(q);Ie(Se.provider),He(Se.modelId)},[]),ut=i.useCallback(async q=>{if(m){m(q);return}const Se=Rt,At=Se.includes(q)?Se.filter(Et=>Et!==q):[q,...Se];en(At);try{await $n({favoriteProviders:At,favoriteModels:zt})}catch{en(Se)}},[Rt,zt,m]),Ct=i.useCallback(async q=>{if(h){h(q);return}const Se=zt,At=Se.includes(q)?Se.filter(Et=>Et!==q):[q,...Se];Qt(At);try{await $n({favoriteProviders:Rt,favoriteModels:At})}catch{Qt(Se)}},[zt,Rt,h]),Mt=i.useCallback(()=>{const q=f.trim();if(!q){n("Enter a description first","error");return}r?.(q),ct()},[f,r,n,ct]),an=i.useCallback(()=>{const q=f.trim();if(!q){n("Enter a description first","error");return}o?.(q),ct()},[f,o,n,ct]),An=i.useCallback(()=>{Ye()},[Ye]),Sn=i.useCallback(async q=>{const Se=f.trim();if(!(!Se||z)){St(!1),he(!0);try{const Ze=await Vf(Se,q,l);p(Ze),n("Description refined with AI","success"),N.current&&(N.current.style.height="auto",N.current.style.height=`${Math.min(N.current.scrollHeight,200)}px`)}catch(Ze){const At=Wf(Ze);n(At,"error")}finally{he(!1)}}},[f,z,n,l]),ps=(q,Se)=>q.length>Se?q.slice(0,Se)+"…":q,ts=i.useCallback(async()=>{if(a){Ot(a),Tt(null),wt(!1);return}wt(!0),Tt(null);try{const q=await $s();Ot(q.models),d||en(q.favoriteProviders),u||Qt(q.favoriteModels)}catch(q){Tt(Me(q)||"Failed to load models")}finally{wt(!1)}},[a,d,u]),Bs=i.useCallback(async()=>{if(J.length>0&&T===l){K(!0),Pt();return}Z(!0);try{const q=await Na(void 0,l);M(q),L(l),K(!0),Pt()}catch(q){const Se=Me(q);n(Se?`Failed to load agents: ${Se}`:"Failed to load agents","error"),K(!1)}finally{Z(!1)}},[J.length,T,l,n,Pt]),fi=(G?J.find(q=>q.id===G):void 0)?.name??G,de=xe?_t.find(q=>q.id===xe):void 0,We=y,mt=i.useCallback(()=>{S(q=>{const Se=!q;return b(Se),Se})},[]);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:N,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:q=>p(q.target.value),onKeyDown:Yt,onPaste:it,onFocus:cs,onBlur:In,disabled:g||$t,"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:mt,"aria-expanded":y,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:y?"Collapse":"Expand",children:y?t.jsx(mi,{size:14}):t.jsx(cn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!We,"aria-hidden":!We,children:[We&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Mt,onMouseDown:q=>q.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(hi,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:an,onMouseDown:q=>q.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(Il,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:st,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${z?"refine-button--loading":""}`,onClick:()=>{St(q=>{const Se=!q;return Se?vn():ot(null),Se})},disabled:!f.trim()||z,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(bs,{size:12,style:{verticalAlign:"middle"}}),z?"Refining...":"Refine"]}),qt&&pe&&ve&&ha.createPortal(t.jsxs("div",{ref:It,className:"refine-menu refine-menu--portal",onMouseDown:q=>q.preventDefault(),style:{position:"fixed",top:`${ve.top}px`,left:`${ve.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Sn("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:()=>Sn("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:()=>Sn("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:()=>Sn("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),pe)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:me,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{A(q=>{const Se=!q;return Se?(X(!1),Ee(null),se(null),K(!1),lt(null),le(!1),_e(null),ge(!1),bt(null),bn()):Ke(null),Se})},children:[t.jsx(Qa,{size:12,style:{verticalAlign:"middle"}}),P.length>0?`${P.length} deps`:"Deps"]})}),H&&pe&&be&&(()=>{const q=$.toLowerCase(),Se=(q?s.filter(Ze=>Ze.id.toLowerCase().includes(q)||Ze.title&&Ze.title.toLowerCase().includes(q)||Ze.description&&Ze.description.toLowerCase().includes(q)):[...s]).sort((Ze,At)=>{const Et=At.createdAt.localeCompare(Ze.createdAt);if(Et!==0)return Et;const Cn=parseInt(Ze.id.slice(Ze.id.lastIndexOf("-")+1),10)||0;return(parseInt(At.id.slice(At.id.lastIndexOf("-")+1),10)||0)-Cn});return ha.createPortal(t.jsxs("div",{ref:Re,className:"dep-dropdown dep-dropdown--portal",onMouseDown:Ze=>Ze.preventDefault(),style:{position:"fixed",top:`${be.top}px`,left:`${be.left}px`,width:`${be.width}px`,maxHeight:be.maxHeight?`${be.maxHeight}px`:void 0,overflowY:be.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:$,onChange:Ze=>F(Ze.target.value),onClick:Ze=>Ze.stopPropagation()}),Se.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Se.map(Ze=>t.jsxs("div",{className:`dep-dropdown-item${P.includes(Ze.id)?" selected":""}`,onMouseDown:At=>At.preventDefault(),onClick:()=>gn(Ze.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:Ze.id}),t.jsx("span",{className:"dep-dropdown-title",children:ps(Ze.title||Ze.description||Ze.id,60)})]},Ze.id))]}),pe)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>E.current?.click(),children:[t.jsx($f,{size:12,style:{verticalAlign:"middle"}}),_.length>0?`Attach (${_.length})`:"Attach"]}),t.jsxs("button",{ref:Ae,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{A(!1),K(!1),lt(null),le(!1),_e(null),ge(!1),bt(null),se(null),X(!0),ms()},children:[t.jsx(Yr,{size:12,style:{verticalAlign:"middle"}}),Yn]}),t.jsx("div",{className:"node-trigger-wrap",ref:fe,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{A(!1),K(!1),lt(null),X(!1),Ee(null),se(null),ge(!1),bt(null),le(q=>{const Se=!q;return Se?Qn():_e(null),Se})},children:[t.jsx(Xr,{size:12,style:{verticalAlign:"middle"}}),` ${de?.name??"Node"}`,de&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(xa,{status:de.status,showLabel:!0})})]})}),oe&&pe&&vt&&ha.createPortal(t.jsxs("div",{ref:Pe,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:q=>q.preventDefault(),style:{position:"fixed",top:`${vt.top}px`,left:`${vt.left}px`,width:`${vt.width}px`,maxHeight:vt.maxHeight?`${vt.maxHeight}px`:void 0,overflowY:vt.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${xe==null?" selected":""}`,onMouseDown:q=>q.preventDefault(),onClick:()=>{Le(void 0),le(!1),_e(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),_t.map(q=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${xe===q.id?" selected":""}`,onMouseDown:Se=>Se.preventDefault(),onClick:()=>{Le(q.id),le(!1),_e(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(xa,{status:q.status})}),t.jsx("span",{className:"node-picker-item-name",children:q.name}),t.jsx("span",{className:"node-picker-item-status",children:U0(q.status)})]},q.id))]}),pe),t.jsx("div",{className:"agent-trigger-wrap",ref:ye,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{k?(K(!1),lt(null)):(le(!1),_e(null),ge(!1),bt(null),Bs())},"data-testid":"quick-entry-agent-button",children:[t.jsx(zn,{size:12,style:{verticalAlign:"middle"}}),fi?` ${fi}`:" Agent"]})}),k&&pe&&pt&&ha.createPortal(t.jsxs("div",{ref:Ce,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:q=>q.preventDefault(),style:{position:"fixed",top:`${pt.top}px`,left:`${pt.left}px`,width:`${pt.width}px`,maxHeight:pt.maxHeight?`${pt.maxHeight}px`:void 0,overflowY:pt.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Ue&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Ue&&J.map(q=>t.jsxs("div",{className:`dep-dropdown-item${G===q.id?" selected":""}`,onMouseDown:Se=>Se.preventDefault(),onClick:()=>{ee(q.id===G?null:q.id),K(!1),lt(null)},children:[t.jsx(zn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:q.role}),t.jsx("span",{className:"dep-dropdown-title",children:q.name})]},q.id)),!Ue&&J.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),G&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:q=>q.preventDefault(),onClick:()=>{ee(null),K(!1),lt(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),pe),t.jsx("div",{className:"priority-trigger-wrap",ref:De,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{A(!1),K(!1),lt(null),le(!1),_e(null),X(!1),Ee(null),se(null),ge(q=>{const Se=!q;return Se?es():bt(null),Se})},children:[t.jsx(Uv,{size:12,style:{verticalAlign:"middle"}}),` ${Vt[0].toUpperCase()}${Vt.slice(1)}`]})}),we&&pe&&Fe&&ha.createPortal(t.jsxs("div",{ref:dt,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:q=>q.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 priority"}),xo.map(q=>{const Se=`${q[0].toUpperCase()}${q.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${Vt===q?" selected":""}`,"data-testid":`quick-entry-priority-option-${q}`,onMouseDown:Ze=>Ze.preventDefault(),onClick:()=>{mn(q),ge(!1),bt(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:Se})},q)})]}),pe),t.jsx("button",{type:"button",className:`btn btn-sm ${un?"btn-primary":""}`,onClick:()=>tn(q=>!q),onMouseDown:q=>q.preventDefault(),"aria-pressed":un,"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:An,onMouseDown:q=>q.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(Lf,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),We&&t.jsxs("div",{className:"quick-entry-branch-fields","data-testid":"quick-entry-branch-fields",children:[t.jsxs("label",{children:[t.jsx("span",{children:"Working branch"}),t.jsx("input",{className:"input",value:Ve,onChange:q=>at(q.target.value),placeholder:"e.g. feature/my-task","data-testid":"quick-entry-working-branch",disabled:g||$t})]}),t.jsxs("label",{children:[t.jsx("span",{children:"Merge target / base branch"}),t.jsx("input",{className:"input",value:Ge,onChange:q=>Ft(q.target.value),placeholder:"e.g. main","data-testid":"quick-entry-base-branch",disabled:g||$t})]})]}),_.length>0&&t.jsx("div",{className:"inline-create-previews",children:_.map((q,Se)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:q.previewUrl,alt:q.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Y(Se),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${Se}`,children:"×"})]},q.previewUrl))}),Q&&pe&&ht&&ha.createPortal(t.jsx("div",{ref:Ne,className:"model-nested-menu model-nested-menu--portal",onMouseDown:q=>q.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ht.top}px`,left:`${ht.left}px`,width:`${ht.width}px`,maxHeight:ht.maxHeight?`${ht.maxHeight}px`:void 0,overflowY:ht.maxHeight?"auto":void 0},children:ie===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Jt?"model-menu-item--active":""}`,onClick:()=>se("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(hi,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Jt?re($e,ue):"Using default"}),t.jsx(Un,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${on?"model-menu-item--active":""}`,onClick:()=>se("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(bs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:on?re(B,ke):"Using default"}),t.jsx(Un,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${Dn?"model-menu-item--active":""}`,onClick:()=>se("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Yr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:Dn?re(te,Oe):"Using default"}),t.jsx(Un,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]})]}):t.jsxs("div",{className:"model-submenu",children:[t.jsxs("button",{type:"button",className:"model-submenu-back",onClick:()=>se(null),"data-testid":"model-submenu-back",children:[t.jsx(cn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ie==="plan"&&"Plan Model",ie==="executor"&&"Executor Model",ie==="validator"&&"Reviewer Model"]}),t.jsx(ks,{models:Zt,value:ie==="plan"?sn:ie==="executor"?Wt:Gt,onChange:ie==="plan"?W:ie==="executor"?qe:Je,placeholder:"Using default",disabled:Xe,id:`model-${ie}-select`,label:`${ie} model`,favoriteProviders:Nt,onToggleFavorite:ut,favoriteModels:Lt,onToggleModelFavorite:Ct}),gt&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:gt}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:ts,children:"Retry"})]})]})}),pe)]}),t.jsx("input",{ref:E,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:q=>{ft(q.target.files),q.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function B0(e){return ru(e)||e}function H0(e){const n=new Map(e.map(l=>[l.id,l])),s=[],a=new Set,r=new Set;function o(l){if(a.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const d of c.dependencies||[])n.has(d)&&o(d);r.delete(l),a.add(l),s.push(l)}for(const l of e)o(l.id);return s}function q0(e,n,s){const a=e.filter(g=>g.worktree),r=e.filter(g=>!g.worktree),o=new Map;for(const g of a){const x=g.worktree,v=o.get(x)||[];v.push(g),o.set(x,v)}const l=new Map(n.map(g=>[g.id,g])),d=n.filter(g=>g.column==="todo").filter(g=>!g.paused&&(g.dependencies||[]).every(x=>{const v=l.get(x);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=H0(d).map(g=>l.get(g)).filter(g=>g!==void 0&&d.includes(g)),h=[],f=Array.from(o.keys());for(const g of f)h.push({label:B0(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 qm=100,gc=50,Vm=25;function V0({column:e,tasks:n,projectId:s,maxConcurrent:a,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:d,onNewTask:u,autoMerge:m,onToggleAutoMerge:h,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onArchiveAllDone:y,collapsed:S,onToggleCollapse:N,allTasks:E,availableModels:w,onPlanningMode:j,onSubtaskBreakdown:_,onOpenDetailWithTab:D,favoriteProviders:C,favoriteModels:P,onToggleFavorite:I,onToggleModelFavorite:H,isSearchActive:A,taskStuckTimeoutMs:$,onOpenMission:F,lastFetchTimeMs:G,workflowStepNameLookup:ee}){const[J,M]=i.useState(!1),[T,L]=i.useState(gc),[k,K]=i.useState(!1),[oe,le]=i.useState(!1),[we,ge]=i.useState(!1),[Ue,Z]=i.useState(!1),Q=i.useRef(null),X=US(n.length),{confirm:ie}=Ys();i.useEffect(()=>{if(!k)return;function Pe(dt){Q.current?.contains(dt.target)||K(!1)}function De(dt){dt.key==="Escape"&&K(!1)}return document.addEventListener("mousedown",Pe),document.addEventListener("keydown",De),()=>{document.removeEventListener("mousedown",Pe),document.removeEventListener("keydown",De)}},[k]);const se=e==="archived",B=se&&S,O=!se&&!A&&e!=="in-progress"&&n.length>qm;i.useEffect(()=>{L(Pe=>e==="in-progress"||se||n.length<=qm?gc:Math.min(Math.max(Pe,gc),n.length))},[e,se,n.length]);const ke=i.useCallback(Pe=>{se||(Pe.preventDefault(),Pe.dataTransfer.dropEffect="move",M(!0))},[se]),ae=i.useCallback(Pe=>{Pe.currentTarget.contains(Pe.relatedTarget)||M(!1)},[]),te=i.useCallback(async Pe=>{Pe.preventDefault(),M(!1);const De=Pe.dataTransfer.getData("text/plain");if(!De)return;const dt=n.find(pt=>pt.id===De);if(!(dt&&dt.column===e))try{const lt=(E?.find(Fe=>Fe.id===De)??dt)?.steps.some(Fe=>Fe.status!=="pending")??!1,vt=(e==="todo"||e==="triage")&<let _e;if(vt){if(await ie({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))_e={preserveProgress:!0};else if(!await ie({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(De,e,_e)}catch(pt){c(Me(pt),"error")}},[c,E,e,ie,r,n]),Ie=i.useMemo(()=>e!=="in-progress"?[]:q0(n,n,a),[e,n,a]),Oe=i.useMemo(()=>O?n.slice(0,T):n,[O,n,T]),He=Math.max(0,n.length-Oe.length),$e=i.useCallback(()=>{L(Pe=>Math.min(Pe+Vm,n.length))},[n.length]),Te=i.useCallback(async()=>{if(K(!1),!(n.length===0||!await ie({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){le(!0);try{const De=await Promise.allSettled(n.map(lt=>r(lt.id,"triage"))),dt=De.filter(lt=>lt.status==="rejected").length,pt=De.length-dt;dt===0?c(`Moved ${pt} task${pt===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${pt} of ${De.length} tasks; ${dt} failed`,"error")}finally{le(!1)}}},[n,r,c,ie]),ue=i.useMemo(()=>n.filter(Pe=>!Pe.paused&&!Pe.assignedAgentId),[n]),ce=ue.length,Ae=e==="todo"||e==="in-progress"||e==="in-review",Ne=oe||we||Ue,ye=i.useCallback(async()=>{if(!(!o||(K(!1),ce===0)||!await ie({title:"Stop All Tasks",message:`Stop all ${ce} ${ds[e].toLowerCase()} task${ce===1?"":"s"}?`,danger:!0}))){ge(!0);try{const De=await Promise.allSettled(ue.map(lt=>o(lt.id))),dt=De.filter(lt=>lt.status==="rejected").length,pt=De.length-dt;dt===0?c(`Stopped ${pt} task${pt===1?"":"s"}`,"success"):c(`Stopped ${pt} of ${De.length} tasks; ${dt} failed`,"error")}finally{ge(!1)}}},[o,ce,e,ue,c,ie]),Ce=i.useCallback(async()=>{if(K(!1),n.length===0||!await ie({title:"Move All to Todo",message:`Move all ${n.length} ${ds[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const De=n.some(pt=>pt.steps.some(lt=>lt.status!=="pending"));let dt=!1;if(De){if(await ie({title:"Preserve Progress?",message:"Some tasks have completed steps. Keep progress before moving to Todo?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))dt=!0;else if(!await ie({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}Z(!0);try{const pt=await Promise.allSettled(n.map(_e=>r(_e.id,"todo",dt?{preserveProgress:!0}:void 0))),lt=pt.filter(_e=>_e.status==="rejected").length,vt=pt.length-lt;lt===0?c(`Moved ${vt} task${vt===1?"":"s"} to Todo`,"success"):c(`Moved ${vt} of ${pt.length} tasks to Todo; ${lt} failed`,"error")}finally{Z(!1)}},[n,e,r,c,ie]),fe=i.useCallback(async()=>{if(!(!y||n.length===0||!await ie({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const De=await y();c(`Archived ${De.length} tasks`,"success")}catch(De){c(Me(De)||"Failed to archive tasks","error")}},[y,n.length,c,ie]);return t.jsxs("div",{className:`column${J?" drag-over":""}${se?" column-archived":""}${B?" column-collapsed":""}`,"data-column":e,onDragOver:ke,onDragLeave:ae,onDrop:te,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:ds[e]}),t.jsx("span",{className:`column-count${X?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),u&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:u,children:"+ New Task"}),e==="done"&&y&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:fe,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(ao,{})}),se&&N&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:N,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(cn,{size:16}):t.jsx(mi,{size:16})}),Ae&&t.jsxs("div",{className:"column-menu",ref:Q,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>K(Pe=>!Pe),"aria-haspopup":"menu","aria-expanded":k,"aria-label":`${ds[e]} column actions`,title:"Column actions",disabled:Ne,children:t.jsx(kv,{})}),k&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Te(),disabled:n.length===0||oe,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 ye(),disabled:ce===0||we||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":ce===0?"No manually pausable tasks":`Pause ${ce} active unassigned task${ce===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Ce(),disabled:n.length===0||Ue,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!B&&t.jsx("p",{className:"column-desc",children:FS[e]}),!B&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(Ng,{onCreate:d,addToast:c,tasks:E??[],availableModels:w,onPlanningMode:j,onSubtaskBreakdown:_,projectId:s,autoExpand:!1,favoriteProviders:C,favoriteModels:P,onToggleFavorite:I,onToggleModelFavorite:H}),e==="in-progress"?Ie.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Ie.map(Pe=>t.jsx(jg,{label:Pe.label,activeTasks:Pe.activeTasks,queuedTasks:Pe.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:D,taskStuckTimeoutMs:$,onOpenMission:F,lastFetchTimeMs:G,workflowStepNameLookup:ee},Pe.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[Oe.map(Pe=>t.jsx(to,{task:Pe,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:v,onDeleteTask:b,onOpenDetailWithTab:D,taskStuckTimeoutMs:$,onOpenMission:F,onMoveTask:r,lastFetchTimeMs:G,workflowStepNameLookup:ee},Pe.id)),O&&He>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:$e,children:["Load ",Math.min(Vm,He)," more (",He," remaining)"]})]}),t.jsx(Zi,{slotId:"board-column-footer",projectId:s})]})]})}const Sg=i.memo(V0);Sg.displayName="Column";function W0(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const Wm=new Map;function K0(e,n){if(e.size!==n.size)return!1;for(const[s,a]of e)if(n.get(s)!==a)return!1;return!0}function G0({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:d,autoMerge:u,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:v,onArchiveAllDone:b,onLoadArchivedTasks:y,searchQuery:S="",availableModels:N,onPlanningMode:E,onSubtaskBreakdown:w,onOpenDetailWithTab:j,favoriteProviders:_,favoriteModels:D,onToggleFavorite:C,onToggleModelFavorite:P,taskStuckTimeoutMs:I,onOpenMission:H,lastFetchTimeMs:A}){const[$,F]=i.useState(!0),G=i.useRef(!1),{fetchBatch:ee}=QS(n),J=i.useRef(null),[M,T]=i.useState(Wm),L=S.trim()!=="",k=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),K=i.useCallback(()=>{F(we=>{const ge=!we;return!ge&&!G.current&&y&&(G.current=!0,y()),ge})},[y]),oe=i.useMemo(()=>{const we={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};for(const Z of e){const Q=ou(Z.column)?Z.column:gl;(we[Q]??we[gl]).push(Z)}const ge=k.current,Ue={};for(const Z of Xi){const Q=ug(we[Z],Z);Ue[Z]=W0(ge[Z],Q)?ge[Z]:Q}return k.current=Ue,Ue},[e]);i.useEffect(()=>{let we=!1;return fo(n).then(ge=>{if(we)return;const Ue=new Map(ge.map(Z=>[Z.id,Z.name]));T(Z=>K0(Z,Ue)?Z:Ue)}).catch(()=>{we||T(ge=>ge.size===0?ge:Wm)}),()=>{we=!0}},[n]);const le=i.useMemo(()=>e.filter(we=>we.prInfo||we.issueInfo).map(we=>we.id),[e]);return i.useEffect(()=>{if(le.length!==0)return J.current&&clearTimeout(J.current),J.current=setTimeout(()=>{const we=[];for(let ge=0;ge<le.length;ge+=50)we.push(le.slice(ge,ge+50));we.forEach(ge=>{ee(ge)})},500),()=>{J.current&&clearTimeout(J.current)}},[le,ee]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:Xi.map(we=>t.jsx(Sg,{column:we,tasks:oe[we],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:v,allTasks:e,availableModels:N,onOpenDetailWithTab:j,favoriteProviders:_,favoriteModels:D,onToggleFavorite:C,onToggleModelFavorite:P,isSearchActive:L,taskStuckTimeoutMs:I,onOpenMission:H,lastFetchTimeMs:A,workflowStepNameLookup:M,...we==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:E,onSubtaskBreakdown:w}:{},...we==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...we==="done"?{onArchiveAllDone:b}:{},...we==="archived"?{collapsed:$,onToggleCollapse:K}:{}},we))})})}function Ti(e,n,s){i.useEffect(()=>{if(!n)return;const a=e.current;if(!a)return;if(typeof window<"u"&&("ontouchstart"in window||navigator.maxTouchPoints>0)&&window.innerWidth<=768){a.style.removeProperty("width"),a.style.removeProperty("height");return}try{const u=localStorage.getItem(s);if(u){const{width:m,height:h}=JSON.parse(u);typeof m=="number"&&m>0&&(a.style.width=`${m}px`),typeof h=="number"&&h>0&&(a.style.height=`${h}px`)}}catch{}if(typeof ResizeObserver>"u")return;let o=a.offsetWidth,l=a.offsetHeight,c=null;const d=new ResizeObserver(()=>{const u=a.offsetWidth,m=a.offsetHeight;u===o&&m===l||(o=u,l=m,c&&clearTimeout(c),c=setTimeout(()=>{try{localStorage.setItem(s,JSON.stringify({width:u,height:m}))}catch{}},200))});return d.observe(a),()=>{d.disconnect(),c&&clearTimeout(c)}},[e,n,s])}function J0(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Ja=0,Wr=null;function Y0(){if(typeof window>"u")return;if(Ja>0){Ja+=1;return}const e=document.documentElement,n=document.body;Wr={htmlOverflow:e.style.overflow,bodyPosition:n.style.position,bodyTop:n.style.top,bodyLeft:n.style.left,bodyRight:n.style.right,bodyWidth:n.style.width,bodyOverflow:n.style.overflow,scrollY:window.scrollY},e.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${Wr.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",Ja=1}function Q0(){if(typeof window>"u"||Ja===0||(Ja-=1,Ja>0||!Wr))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=Wr;e.style.overflow=s,n.style.position=a,n.style.top=r,n.style.left=o,n.style.right=l,n.style.width=c,n.style.overflow=d,Wr=null,window.scrollTo(0,0)}function pi(e){i.useEffect(()=>{if(!(!e||!J0()))return Y0(),()=>{Q0()}},[e])}function Ui(e){const n=i.useRef(!1),s=i.useCallback(r=>{n.current=r.target===r.currentTarget},[]),a=i.useCallback(r=>{const o=n.current&&r.target===r.currentTarget;n.current=!1,o&&e()},[e]);return{onMouseDown:s,onMouseUp:a}}function X0(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const Z0=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,eC=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,tC={};function Km(e,n){return(tC.jsx?eC:Z0).test(e)}const nC=/[ \t\n\f\r]/g;function sC(e){return typeof e=="object"?e.type==="text"?Gm(e.value):!1:Gm(e)}function Gm(e){return e.replace(nC,"")===""}class vo{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}vo.prototype.normal={};vo.prototype.property={};vo.prototype.space=void 0;function Cg(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new vo(s,a,n)}function _d(e){return e.toLowerCase()}class Us{constructor(n,s){this.attribute=s,this.property=n}}Us.prototype.attribute="";Us.prototype.booleanish=!1;Us.prototype.boolean=!1;Us.prototype.commaOrSpaceSeparated=!1;Us.prototype.commaSeparated=!1;Us.prototype.defined=!1;Us.prototype.mustUseProperty=!1;Us.prototype.number=!1;Us.prototype.overloadedBoolean=!1;Us.prototype.property="";Us.prototype.spaceSeparated=!1;Us.prototype.space=void 0;let iC=0;const ln=Sa(),gs=Sa(),Md=Sa(),yt=Sa(),Kn=Sa(),Ya=Sa(),qs=Sa();function Sa(){return 2**++iC}const Ad=Object.freeze(Object.defineProperty({__proto__:null,boolean:ln,booleanish:gs,commaOrSpaceSeparated:qs,commaSeparated:Ya,number:yt,overloadedBoolean:Md,spaceSeparated:Kn},Symbol.toStringTag,{value:"Module"})),bc=Object.keys(Ad);class cu extends Us{constructor(n,s,a,r){let o=-1;if(super(n,s),Jm(this,"space",r),typeof a=="number")for(;++o<bc.length;){const l=bc[o];Jm(this,bc[o],(a&Ad[l])===Ad[l])}}}cu.prototype.defined=!0;function Jm(e,n,s){s&&(e[n]=s)}function pr(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new cu(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[_d(a)]=a,s[_d(o.attribute)]=a}return new vo(n,s,e.space)}const Eg=pr({properties:{ariaActiveDescendant:null,ariaAtomic:gs,ariaAutoComplete:null,ariaBusy:gs,ariaChecked:gs,ariaColCount:yt,ariaColIndex:yt,ariaColSpan:yt,ariaControls:Kn,ariaCurrent:null,ariaDescribedBy:Kn,ariaDetails:null,ariaDisabled:gs,ariaDropEffect:Kn,ariaErrorMessage:null,ariaExpanded:gs,ariaFlowTo:Kn,ariaGrabbed:gs,ariaHasPopup:null,ariaHidden:gs,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Kn,ariaLevel:yt,ariaLive:null,ariaModal:gs,ariaMultiLine:gs,ariaMultiSelectable:gs,ariaOrientation:null,ariaOwns:Kn,ariaPlaceholder:null,ariaPosInSet:yt,ariaPressed:gs,ariaReadOnly:gs,ariaRelevant:null,ariaRequired:gs,ariaRoleDescription:Kn,ariaRowCount:yt,ariaRowIndex:yt,ariaRowSpan:yt,ariaSelected:gs,ariaSetSize:yt,ariaSort:null,ariaValueMax:yt,ariaValueMin:yt,ariaValueNow:yt,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function _g(e,n){return n in e?e[n]:n}function Mg(e,n){return _g(e,n.toLowerCase())}const aC=pr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:Ya,acceptCharset:Kn,accessKey:Kn,action:null,allow:null,allowFullScreen:ln,allowPaymentRequest:ln,allowUserMedia:ln,alt:null,as:null,async:ln,autoCapitalize:null,autoComplete:Kn,autoFocus:ln,autoPlay:ln,blocking:Kn,capture:null,charSet:null,checked:ln,cite:null,className:Kn,cols:yt,colSpan:null,content:null,contentEditable:gs,controls:ln,controlsList:Kn,coords:yt|Ya,crossOrigin:null,data:null,dateTime:null,decoding:null,default:ln,defer:ln,dir:null,dirName:null,disabled:ln,download:Md,draggable:gs,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:ln,formTarget:null,headers:Kn,height:yt,hidden:Md,high:yt,href:null,hrefLang:null,htmlFor:Kn,httpEquiv:Kn,id:null,imageSizes:null,imageSrcSet:null,inert:ln,inputMode:null,integrity:null,is:null,isMap:ln,itemId:null,itemProp:Kn,itemRef:Kn,itemScope:ln,itemType:Kn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:ln,low:yt,manifest:null,max:null,maxLength:yt,media:null,method:null,min:null,minLength:yt,multiple:ln,muted:ln,name:null,nonce:null,noModule:ln,noValidate:ln,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:ln,optimum:yt,pattern:null,ping:Kn,placeholder:null,playsInline:ln,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:ln,referrerPolicy:null,rel:Kn,required:ln,reversed:ln,rows:yt,rowSpan:yt,sandbox:Kn,scope:null,scoped:ln,seamless:ln,selected:ln,shadowRootClonable:ln,shadowRootDelegatesFocus:ln,shadowRootMode:null,shape:null,size:yt,sizes:null,slot:null,span:yt,spellCheck:gs,src:null,srcDoc:null,srcLang:null,srcSet:null,start:yt,step:null,style:null,tabIndex:yt,target:null,title:null,translate:null,type:null,typeMustMatch:ln,useMap:null,value:gs,width:yt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Kn,axis:null,background:null,bgColor:null,border:yt,borderColor:null,bottomMargin:yt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:ln,declare:ln,event:null,face:null,frame:null,frameBorder:null,hSpace:yt,leftMargin:yt,link:null,longDesc:null,lowSrc:null,marginHeight:yt,marginWidth:yt,noResize:ln,noHref:ln,noShade:ln,noWrap:ln,object:null,profile:null,prompt:null,rev:null,rightMargin:yt,rules:null,scheme:null,scrolling:gs,standby:null,summary:null,text:null,topMargin:yt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:yt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:ln,disableRemotePlayback:ln,prefix:null,property:null,results:yt,security:null,unselectable:null},space:"html",transform:Mg}),rC=pr({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:qs,accentHeight:yt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:yt,amplitude:yt,arabicForm:null,ascent:yt,attributeName:null,attributeType:null,azimuth:yt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:yt,by:null,calcMode:null,capHeight:yt,className:Kn,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:yt,diffuseConstant:yt,direction:null,display:null,dur:null,divisor:yt,dominantBaseline:null,download:ln,dx:null,dy:null,edgeMode:null,editable:null,elevation:yt,enableBackground:null,end:null,event:null,exponent:yt,externalResourcesRequired:null,fill:null,fillOpacity:yt,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:Ya,g2:Ya,glyphName:Ya,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:yt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:yt,horizOriginX:yt,horizOriginY:yt,id:null,ideographic:yt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:yt,k:yt,k1:yt,k2:yt,k3:yt,k4:yt,kernelMatrix:qs,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:yt,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:yt,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:yt,overlineThickness:yt,paintOrder:null,panose1:null,path:null,pathLength:yt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Kn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:yt,pointsAtY:yt,pointsAtZ:yt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:qs,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:qs,rev:qs,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:qs,requiredFeatures:qs,requiredFonts:qs,requiredFormats:qs,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:yt,specularExponent:yt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:yt,strikethroughThickness:yt,string:null,stroke:null,strokeDashArray:qs,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:yt,strokeOpacity:yt,strokeWidth:null,style:null,surfaceScale:yt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:qs,tabIndex:yt,tableValues:null,target:null,targetX:yt,targetY:yt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:qs,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:yt,underlineThickness:yt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:yt,values:null,vAlphabetic:yt,vMathematical:yt,vectorEffect:null,vHanging:yt,vIdeographic:yt,version:null,vertAdvY:yt,vertOriginX:yt,vertOriginY:yt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:yt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:_g}),Ag=pr({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()}}),Pg=pr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Mg}),Tg=pr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),oC={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"},lC=/[A-Z]/g,Ym=/-[a-z]/g,cC=/^data[-\w.:]+$/i;function dC(e,n){const s=_d(n);let a=n,r=Us;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&cC.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Ym,mC);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Ym.test(o)){let l=o.replace(lC,uC);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=cu}return new r(a,n)}function uC(e){return"-"+e.toLowerCase()}function mC(e){return e.charAt(1).toUpperCase()}const hC=Cg([Eg,aC,Ag,Pg,Tg],"html"),du=Cg([Eg,rC,Ag,Pg,Tg],"svg");function pC(e){return e.join(" ").trim()}var La={},xc,Qm;function fC(){if(Qm)return xc;Qm=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,a=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,d=`
|
|
654
|
-
`,u="/",m="*",h="",f="comment",p="declaration";function g(v,b){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];b=b||{};var y=1,S=1;function N(A){var $=A.match(n);$&&(y+=$.length);var F=A.lastIndexOf(d);S=~F?A.length-F:S+A.length}function E(){var A={line:y,column:S};return function($){return $.position=new w(A),D(),$}}function w(A){this.start=A,this.end={line:y,column:S},this.source=b.source}w.prototype.content=v;function j(A){var $=new Error(b.source+":"+y+":"+S+": "+A);if($.reason=A,$.filename=b.source,$.line=y,$.column=S,$.source=v,!b.silent)throw $}function _(A){var $=A.exec(v);if($){var F=$[0];return N(F),v=v.slice(F.length),$}}function D(){_(s)}function C(A){var $;for(A=A||[];$=P();)$!==!1&&A.push($);return A}function P(){var A=E();if(!(u!=v.charAt(0)||m!=v.charAt(1))){for(var $=2;h!=v.charAt($)&&(m!=v.charAt($)||u!=v.charAt($+1));)++$;if($+=2,h===v.charAt($-1))return j("End of comment missing");var F=v.slice(2,$-2);return S+=2,N(F),v=v.slice($),S+=2,A({type:f,comment:F})}}function I(){var A=E(),$=_(a);if($){if(P(),!_(r))return j("property missing ':'");var F=_(o),G=A({type:p,property:x($[0].replace(e,h)),value:F?x(F[0].replace(e,h)):h});return _(l),G}}function H(){var A=[];C(A);for(var $;$=I();)$!==!1&&(A.push($),C(A));return A}return D(),H()}function x(v){return v?v.replace(c,h):h}return xc=g,xc}var Xm;function gC(){if(Xm)return La;Xm=1;var e=La&&La.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(La,"__esModule",{value:!0}),La.default=s;const n=e(fC());function s(a,r){let o=null;if(!a||typeof a!="string")return o;const l=(0,n.default)(a),c=typeof r=="function";return l.forEach(d=>{if(d.type!=="declaration")return;const{property:u,value:m}=d;c?r(u,m,d):m&&(o=o||{},o[u]=m)}),o}return La}var Nr={},Zm;function bC(){if(Zm)return Nr;Zm=1,Object.defineProperty(Nr,"__esModule",{value:!0}),Nr.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,a=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(u){return!u||s.test(u)||e.test(u)},l=function(u,m){return m.toUpperCase()},c=function(u,m){return"".concat(m,"-")},d=function(u,m){return m===void 0&&(m={}),o(u)?u:(u=u.toLowerCase(),m.reactCompat?u=u.replace(r,c):u=u.replace(a,c),u.replace(n,l))};return Nr.camelCase=d,Nr}var Sr,eh;function xC(){if(eh)return Sr;eh=1;var e=Sr&&Sr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(gC()),s=bC();function a(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,d){c&&d&&(l[(0,s.camelCase)(c,o)]=d)}),l}return a.default=a,Sr=a,Sr}var vC=xC();const yC=Nf(vC),Rg=Ig("end"),uu=Ig("start");function Ig(e){return n;function n(s){const a=s&&s.position&&s.position[e]||{};if(typeof a.line=="number"&&a.line>0&&typeof a.column=="number"&&a.column>0)return{line:a.line,column:a.column,offset:typeof a.offset=="number"&&a.offset>-1?a.offset:void 0}}}function wC(e){const n=uu(e),s=Rg(e);if(n&&s)return{start:n,end:s}}function Kr(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?th(e.position):"start"in e||"end"in e?th(e):"line"in e||"column"in e?Pd(e):""}function Pd(e){return nh(e&&e.line)+":"+nh(e&&e.column)}function th(e){return Pd(e&&e.start)+"-"+Pd(e&&e.end)}function nh(e){return e&&typeof e=="number"?e:1}class Ts extends Error{constructor(n,s,a){super(),typeof s=="string"&&(a=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 a=="string"){const d=a.indexOf(":");d===-1?o.ruleId=a:(o.source=a.slice(0,d),o.ruleId=a.slice(d+1))}if(!o.place&&o.ancestors&&o.ancestors){const d=o.ancestors[o.ancestors.length-1];d&&(o.place=d.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=Kr(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}}Ts.prototype.file="";Ts.prototype.name="";Ts.prototype.reason="";Ts.prototype.message="";Ts.prototype.stack="";Ts.prototype.column=void 0;Ts.prototype.line=void 0;Ts.prototype.ancestors=void 0;Ts.prototype.cause=void 0;Ts.prototype.fatal=void 0;Ts.prototype.place=void 0;Ts.prototype.ruleId=void 0;Ts.prototype.source=void 0;const mu={}.hasOwnProperty,kC=new Map,jC=/[A-Z]/g,NC=new Set(["table","tbody","thead","tfoot","tr"]),SC=new Set(["td","th"]),$g="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function CC(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let a;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");a=IC(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");a=RC(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:a,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"?du:hC,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=Dg(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function Dg(e,n,s){if(n.type==="element")return EC(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return _C(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return AC(e,n,s);if(n.type==="mdxjsEsm")return MC(e,n);if(n.type==="root")return PC(e,n,s);if(n.type==="text")return TC(e,n)}function EC(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=du,e.schema=r),e.ancestors.push(n);const o=Og(e,n.tagName,!1),l=$C(e,n);let c=pu(e,n);return NC.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!sC(d):!0})),Lg(e,l,o,n),hu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function _C(e,n){if(n.data&&n.data.estree&&e.evaluater){const a=n.data.estree.body[0];return a.type,e.evaluater.evaluateExpression(a.expression)}no(e,n.position)}function MC(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);no(e,n.position)}function AC(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=du,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:Og(e,n.name,!0),l=DC(e,n),c=pu(e,n);return Lg(e,l,o,n),hu(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function PC(e,n,s){const a={};return hu(a,pu(e,n)),e.create(n,e.Fragment,a,s)}function TC(e,n){return n.value}function Lg(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function hu(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function RC(e,n,s){return a;function a(r,o,l,c){const u=Array.isArray(l.children)?s:n;return c?u(o,l,c):u(o,l)}}function IC(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=uu(a);return n(r,o,l,c,{columnNumber:d?d.column-1:void 0,fileName:e,lineNumber:d?d.line:void 0},void 0)}}function $C(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&mu.call(n.properties,r)){const o=LC(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&SC.has(n.tagName)?a=c:s[l]=c}}if(a){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=a}return s}function DC(e,n){const s={};for(const a of n.attributes)if(a.type==="mdxJsxExpressionAttribute")if(a.data&&a.data.estree&&e.evaluater){const o=a.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 no(e,n.position);else{const r=a.name;let o;if(a.value&&typeof a.value=="object")if(a.value.data&&a.value.data.estree&&e.evaluater){const c=a.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else no(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function pu(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:kC;for(;++a<n.children.length;){const o=n.children[a];let l;if(e.passKeys){const d=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(d){const u=r.get(d)||0;l=d+"-"+u,r.set(d,u+1)}}const c=Dg(e,o,l);c!==void 0&&s.push(c)}return s}function LC(e,n,s){const a=dC(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?X0(s):pC(s)),a.property==="style"){let r=typeof s=="object"?s:OC(e,String(s));return e.stylePropertyNameCase==="css"&&(r=FC(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?oC[a.property]||a.property:a.attribute,s]}}function OC(e,n){try{return yC(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Ts("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:a,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=$g+"#cannot-parse-style-attribute",r}}function Og(e,n,s){let a;if(!s)a={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=Km(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}a=l}else a=Km(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return mu.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);no(e)}function no(e,n){const s=new Ts("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=$g+"#cannot-handle-mdx-estrees-without-createevaluater",s}function FC(e){const n={};let s;for(s in e)mu.call(e,s)&&(n[zC(s)]=e[s]);return n}function zC(e){let n=e.replace(jC,UC);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function UC(e){return"-"+e.toLowerCase()}const vc={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"]},BC={};function fu(e,n){const s=BC,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return Fg(e,a,r)}function Fg(e,n,s){if(HC(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 sh(e.children,n,s)}return Array.isArray(e)?sh(e,n,s):""}function sh(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=Fg(e[r],n,s);return a.join("")}function HC(e){return!!(e&&typeof e=="object")}const ih=document.createElement("i");function gu(e){const n="&"+e+";";ih.innerHTML=n;const s=ih.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function Ks(e,n,s,a){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,a.length<1e4)l=Array.from(a),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<a.length;)l=a.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function si(e,n){return e.length>0?(Ks(e,e.length,0,n),e):n}const ah={}.hasOwnProperty;function zg(e){const n={};let s=-1;for(;++s<e.length;)qC(n,e[s]);return n}function qC(e,n){let s;for(s in n){const r=(ah.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){ah.call(r,l)||(r[l]=[]);const c=o[l];VC(r[l],Array.isArray(c)?c:c?[c]:[])}}}function VC(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);Ks(e,0,0,a)}function Ug(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 ui(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Is=aa(/[A-Za-z]/),As=aa(/[\dA-Za-z]/),WC=aa(/[#-'*+\--9=?A-Z^-~]/);function vl(e){return e!==null&&(e<32||e===127)}const Td=aa(/\d/),KC=aa(/[\dA-Fa-f]/),GC=aa(/[!-/:-@[-`{-~]/);function Ht(e){return e!==null&&e<-2}function Bn(e){return e!==null&&(e<0||e===32)}function pn(e){return e===-2||e===-1||e===32}const Hl=aa(/\p{P}|\p{S}/u),ya=aa(/\s/);function aa(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function fr(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&As(e.charCodeAt(s+1))&&As(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(a,s),encodeURIComponent(l)),a=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(a)}function jn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return pn(d)?(e.enter(s),c(d)):n(d)}function c(d){return pn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const JC={tokenize:YC};function YC(e){const n=e.attempt(this.parser.constructs.contentInitial,a,r);let s;return n;function a(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),jn(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const d=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=d),s=d,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return Ht(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const QC={tokenize:XC},rh={tokenize:ZC};function XC(e){const n=this,s=[];let a=0,r,o,l;return c;function c(S){if(a<s.length){const N=s[a];return n.containerState=N[1],e.attempt(N[0].continuation,d,u)(S)}return u(S)}function d(S){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&y();const N=n.events.length;let E=N,w;for(;E--;)if(n.events[E][0]==="exit"&&n.events[E][1].type==="chunkFlow"){w=n.events[E][1].end;break}b(a);let j=N;for(;j<n.events.length;)n.events[j][1].end={...w},j++;return Ks(n.events,E+1,0,n.events.slice(N)),n.events.length=j,u(S)}return c(S)}function u(S){if(a===s.length){if(!r)return f(S);if(r.currentConstruct&&r.currentConstruct.concrete)return g(S);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(rh,m,h)(S)}function m(S){return r&&y(),b(a),f(S)}function h(S){return n.parser.lazy[n.now().line]=a!==s.length,l=n.now().offset,g(S)}function f(S){return n.containerState={},e.attempt(rh,p,g)(S)}function p(S){return a++,s.push([n.currentConstruct,n.containerState]),f(S)}function g(S){if(S===null){r&&y(),b(0),e.consume(S);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),x(S)}function x(S){if(S===null){v(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return Ht(S)?(e.consume(S),v(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(S),x)}function v(S,N){const E=n.sliceStream(S);if(N&&E.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(E),n.parser.lazy[S.start.line]){let w=r.events.length;for(;w--;)if(r.events[w][1].start.offset<l&&(!r.events[w][1].end||r.events[w][1].end.offset>l))return;const j=n.events.length;let _=j,D,C;for(;_--;)if(n.events[_][0]==="exit"&&n.events[_][1].type==="chunkFlow"){if(D){C=n.events[_][1].end;break}D=!0}for(b(a),w=j;w<n.events.length;)n.events[w][1].end={...C},w++;Ks(n.events,_+1,0,n.events.slice(j)),n.events.length=w}}function b(S){let N=s.length;for(;N-- >S;){const E=s[N];n.containerState=E[1],E[0].exit.call(n,e)}s.length=S}function y(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function ZC(e,n,s){return jn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function ir(e){if(e===null||Bn(e)||ya(e))return 1;if(Hl(e))return 2}function ql(e,n,s){const a=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!a.includes(o)&&(n=o(n,s),a.push(o))}return n}const Rd={name:"attention",resolveAll:e2,tokenize:t2};function e2(e,n){let s=-1,a,r,o,l,c,d,u,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(a=s;a--;)if(e[a][0]==="exit"&&e[a][1].type==="attentionSequence"&&e[a][1]._open&&n.sliceSerialize(e[a][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[a][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[a][1].end.offset-e[a][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;d=e[a][1].end.offset-e[a][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[a][1].end},f={...e[s][1].start};oh(h,-d),oh(f,d),l={type:d>1?"strongSequence":"emphasisSequence",start:h,end:{...e[a][1].end}},c={type:d>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:f},o={type:d>1?"strongText":"emphasisText",start:{...e[a][1].end},end:{...e[s][1].start}},r={type:d>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[a][1].end={...l.start},e[s][1].start={...c.end},u=[],e[a][1].end.offset-e[a][1].start.offset&&(u=si(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=si(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=si(u,ql(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=si(u,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,u=si(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,Ks(e,a-1,s-a+3,u),s=a+u.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function t2(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=ir(a);let o;return l;function l(d){return o=d,e.enter("attentionSequence"),c(d)}function c(d){if(d===o)return e.consume(d),c;const u=e.exit("attentionSequence"),m=ir(d),h=!m||m===2&&r||s.includes(d),f=!r||r===2&&m||s.includes(a);return u._open=!!(o===42?h:h&&(r||!f)),u._close=!!(o===42?f:f&&(m||!h)),n(d)}}function oh(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const n2={name:"autolink",tokenize:s2};function s2(e,n,s){let a=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return Is(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||As(p)?(a=1,c(p)):u(p)}function c(p){return p===58?(e.consume(p),a=0,d):(p===43||p===45||p===46||As(p))&&a++<32?(e.consume(p),c):(a=0,u(p))}function d(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||vl(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):WC(p)?(e.consume(p),u):s(p)}function m(p){return As(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),a=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):f(p)}function f(p){if((p===45||As(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const yo={partial:!0,tokenize:i2};function i2(e,n,s){return a;function a(o){return pn(o)?jn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||Ht(o)?n(o):s(o)}}const Bg={continuation:{tokenize:r2},exit:o2,name:"blockQuote",tokenize:a2};function a2(e,n,s){const a=this;return r;function r(l){if(l===62){const c=a.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 pn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function r2(e,n,s){const a=this;return r;function r(l){return pn(l)?jn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(Bg,n,s)(l)}}function o2(e){e.exit("blockQuote")}const Hg={name:"characterEscape",tokenize:l2};function l2(e,n,s){return a;function a(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return GC(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const qg={name:"characterReference",tokenize:c2};function c2(e,n,s){const a=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),d}function d(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),u):(e.enter("characterReferenceValue"),o=31,l=As,m(h))}function u(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=KC,m):(e.enter("characterReferenceValue"),o=7,l=Td,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===As&&!gu(a.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 lh={partial:!0,tokenize:u2},ch={concrete:!0,name:"codeFenced",tokenize:d2};function d2(e,n,s){const a=this,r={partial:!0,tokenize:E};let o=0,l=0,c;return d;function d(w){return u(w)}function u(w){const j=a.events[a.events.length-1];return o=j&&j[1].type==="linePrefix"?j[2].sliceSerialize(j[1],!0).length:0,c=w,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(w)}function m(w){return w===c?(l++,e.consume(w),m):l<3?s(w):(e.exit("codeFencedFenceSequence"),pn(w)?jn(e,h,"whitespace")(w):h(w))}function h(w){return w===null||Ht(w)?(e.exit("codeFencedFence"),a.interrupt?n(w):e.check(lh,x,N)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||Ht(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):pn(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),jn(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),f)}function p(w){return w===null||Ht(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||Ht(w)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(w)):w===96&&w===c?s(w):(e.consume(w),g)}function x(w){return e.attempt(r,N,v)(w)}function v(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),b}function b(w){return o>0&&pn(w)?jn(e,y,"linePrefix",o+1)(w):y(w)}function y(w){return w===null||Ht(w)?e.check(lh,x,N)(w):(e.enter("codeFlowValue"),S(w))}function S(w){return w===null||Ht(w)?(e.exit("codeFlowValue"),y(w)):(e.consume(w),S)}function N(w){return e.exit("codeFenced"),n(w)}function E(w,j,_){let D=0;return C;function C($){return w.enter("lineEnding"),w.consume($),w.exit("lineEnding"),P}function P($){return w.enter("codeFencedFence"),pn($)?jn(w,I,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)($):I($)}function I($){return $===c?(w.enter("codeFencedFenceSequence"),H($)):_($)}function H($){return $===c?(D++,w.consume($),H):D>=l?(w.exit("codeFencedFenceSequence"),pn($)?jn(w,A,"whitespace")($):A($)):_($)}function A($){return $===null||Ht($)?(w.exit("codeFencedFence"),j($)):_($)}}}function u2(e,n,s){const a=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 a.parser.lazy[a.now().line]?s(l):n(l)}}const yc={name:"codeIndented",tokenize:h2},m2={partial:!0,tokenize:p2};function h2(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),jn(e,o,"linePrefix",5)(u)}function o(u){const m=a.events[a.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(u):s(u)}function l(u){return u===null?d(u):Ht(u)?e.attempt(m2,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||Ht(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function p2(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):Ht(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):jn(e,o,"linePrefix",5)(l)}function o(l){const c=a.events[a.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):Ht(l)?r(l):s(l)}}const f2={name:"codeText",previous:b2,resolve:g2,tokenize:x2};function g2(e){let n=e.length-4,s=3,a,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(a=s;++a<n;)if(e[a][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(a=s-1,n++;++a<=n;)r===void 0?a!==n&&e[a][1].type!=="lineEnding"&&(r=a):(a===n||e[a][1].type==="lineEnding")&&(e[r][1].type="codeTextData",a!==r+2&&(e[r][1].end=e[a-1][1].end,e.splice(r+2,a-r-2),n-=a-r-2,a=r+2),r=void 0);return e}function b2(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function x2(e,n,s){let a=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),a++,c):(e.exit("codeTextSequence"),d(h))}function d(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),d):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):Ht(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),d):(e.enter("codeTextData"),u(h))}function u(h){return h===null||h===32||h===96||Ht(h)?(e.exit("codeTextData"),d(h)):(e.consume(h),u)}function m(h){return h===96?(e.consume(h),r++,m):r===a?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",u(h))}}class v2{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 a=s??Number.POSITIVE_INFINITY;return a<this.left.length?this.left.slice(n,a):n>this.left.length?this.right.slice(this.right.length-a+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-a+this.left.length).reverse())}splice(n,s,a){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return a&&Cr(this.left,a),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),Cr(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Cr(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);Cr(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Cr(this.left,s.reverse())}}}function Cr(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 Vg(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new v2(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(a=m.get(s),s&&a[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(d=a[1]._tokenizer.events,o=0,o<d.length&&d[o][1].type==="lineEndingBlank"&&(o+=2),o<d.length&&d[o][1].type==="content"))for(;++o<d.length&&d[o][1].type!=="content";)d[o][1].type==="chunkText"&&(d[o][1]._isInFirstContentOfListItem=!0,o++);if(a[0]==="enter")a[1].contentType&&(Object.assign(n,y2(m,s)),s=n[s],u=!0);else if(a[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&&(a[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(a),m.splice(r,s-r+1,c))}}return Ks(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function y2(e,n){const s=e.get(n)[1],a=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=a.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,d=[],u={};let m,h,f=-1,p=s,g=0,x=0;const v=[x];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=a.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&&(x=f+1,v.push(x),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),f=v.length;f--;){const b=c.slice(v[f],v[f+1]),y=o.pop();d.push([y,y+b.length-1]),e.splice(y,2,b)}for(d.reverse(),f=-1;++f<d.length;)u[g+d[f][0]]=g+d[f][1],g+=d[f][1]-d[f][0]-1;return u}const w2={resolve:j2,tokenize:N2},k2={partial:!0,tokenize:S2};function j2(e){return Vg(e),e}function N2(e,n){let s;return a;function a(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):Ht(c)?e.check(k2,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 S2(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),jn(e,o,"linePrefix")}function o(l){if(l===null||Ht(l))return s(l);const c=a.events[a.events.length-1];return!a.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(a.parser.constructs.flow,s,n)(l)}}function Wg(e,n,s,a,r,o,l,c,d){const u=d||Number.POSITIVE_INFINITY;let m=0;return h;function h(b){return b===60?(e.enter(a),e.enter(r),e.enter(o),e.consume(b),e.exit(o),f):b===null||b===32||b===41||vl(b)?s(b):(e.enter(a),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),x(b))}function f(b){return b===62?(e.enter(o),e.consume(b),e.exit(o),e.exit(r),e.exit(a),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(b))}function p(b){return b===62?(e.exit("chunkString"),e.exit(c),f(b)):b===null||b===60||Ht(b)?s(b):(e.consume(b),b===92?g:p)}function g(b){return b===60||b===62||b===92?(e.consume(b),p):p(b)}function x(b){return!m&&(b===null||b===41||Bn(b))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(a),n(b)):m<u&&b===40?(e.consume(b),m++,x):b===41?(e.consume(b),m--,x):b===null||b===32||b===40||vl(b)?s(b):(e.consume(b),b===92?v:x)}function v(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function Kg(e,n,s,a,r,o){const l=this;let c=0,d;return u;function u(p){return e.enter(a),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&&!d||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(a),n):Ht(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||Ht(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!pn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function Gg(e,n,s,a,r,o){let l;return c;function c(f){return f===34||f===39||f===40?(e.enter(a),e.enter(r),e.consume(f),e.exit(r),l=f===40?41:f,d):s(f)}function d(f){return f===l?(e.enter(r),e.consume(f),e.exit(r),e.exit(a),n):(e.enter(o),u(f))}function u(f){return f===l?(e.exit(o),d(l)):f===null?s(f):Ht(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),jn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||Ht(f)?(e.exit("chunkString"),u(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 a;function a(r){return Ht(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):pn(r)?jn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const C2={name:"definition",tokenize:_2},E2={partial:!0,tokenize:M2};function _2(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return Kg.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=ui(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),d):s(p)}function d(p){return Bn(p)?Gr(e,u)(p):u(p)}function u(p){return Wg(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(E2,h,h)(p)}function h(p){return pn(p)?jn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||Ht(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function M2(e,n,s){return a;function a(c){return Bn(c)?Gr(e,r)(c):s(c)}function r(c){return Gg(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return pn(c)?jn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||Ht(c)?n(c):s(c)}}const A2={name:"hardBreakEscape",tokenize:P2};function P2(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return Ht(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const T2={name:"headingAtx",resolve:R2,tokenize:I2};function R2(e,n){let s=e.length-2,a=3,r,o;return e[a][1].type==="whitespace"&&(a+=2),s-2>a&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(a===s-1||s-4>a&&e[s-2][1].type==="whitespace")&&(s-=a+1===s?2:4),s>a&&(r={type:"atxHeadingText",start:e[a][1].start,end:e[s][1].end},o={type:"chunkText",start:e[a][1].start,end:e[s][1].end,contentType:"text"},Ks(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function I2(e,n,s){let a=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&&a++<6?(e.consume(m),l):m===null||Bn(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),d(m)):m===null||Ht(m)?(e.exit("atxHeading"),n(m)):pn(m)?jn(e,c,"whitespace")(m):(e.enter("atxHeadingText"),u(m))}function d(m){return m===35?(e.consume(m),d):(e.exit("atxHeadingSequence"),c(m))}function u(m){return m===null||m===35||Bn(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const $2=["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"],dh=["pre","script","style","textarea"],D2={concrete:!0,name:"htmlFlow",resolveTo:F2,tokenize:z2},L2={partial:!0,tokenize:B2},O2={partial:!0,tokenize:U2};function F2(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 z2(e,n,s){const a=this;let r,o,l,c,d;return u;function u(k){return m(k)}function m(k){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(k),h}function h(k){return k===33?(e.consume(k),f):k===47?(e.consume(k),o=!0,x):k===63?(e.consume(k),r=3,a.interrupt?n:M):Is(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function f(k){return k===45?(e.consume(k),r=2,p):k===91?(e.consume(k),r=5,c=0,g):Is(k)?(e.consume(k),r=4,a.interrupt?n:M):s(k)}function p(k){return k===45?(e.consume(k),a.interrupt?n:M):s(k)}function g(k){const K="CDATA[";return k===K.charCodeAt(c++)?(e.consume(k),c===K.length?a.interrupt?n:I:g):s(k)}function x(k){return Is(k)?(e.consume(k),l=String.fromCharCode(k),v):s(k)}function v(k){if(k===null||k===47||k===62||Bn(k)){const K=k===47,oe=l.toLowerCase();return!K&&!o&&dh.includes(oe)?(r=1,a.interrupt?n(k):I(k)):$2.includes(l.toLowerCase())?(r=6,K?(e.consume(k),b):a.interrupt?n(k):I(k)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(k):o?y(k):S(k))}return k===45||As(k)?(e.consume(k),l+=String.fromCharCode(k),v):s(k)}function b(k){return k===62?(e.consume(k),a.interrupt?n:I):s(k)}function y(k){return pn(k)?(e.consume(k),y):C(k)}function S(k){return k===47?(e.consume(k),C):k===58||k===95||Is(k)?(e.consume(k),N):pn(k)?(e.consume(k),S):C(k)}function N(k){return k===45||k===46||k===58||k===95||As(k)?(e.consume(k),N):E(k)}function E(k){return k===61?(e.consume(k),w):pn(k)?(e.consume(k),E):S(k)}function w(k){return k===null||k===60||k===61||k===62||k===96?s(k):k===34||k===39?(e.consume(k),d=k,j):pn(k)?(e.consume(k),w):_(k)}function j(k){return k===d?(e.consume(k),d=null,D):k===null||Ht(k)?s(k):(e.consume(k),j)}function _(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||Bn(k)?E(k):(e.consume(k),_)}function D(k){return k===47||k===62||pn(k)?S(k):s(k)}function C(k){return k===62?(e.consume(k),P):s(k)}function P(k){return k===null||Ht(k)?I(k):pn(k)?(e.consume(k),P):s(k)}function I(k){return k===45&&r===2?(e.consume(k),F):k===60&&r===1?(e.consume(k),G):k===62&&r===4?(e.consume(k),T):k===63&&r===3?(e.consume(k),M):k===93&&r===5?(e.consume(k),J):Ht(k)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(L2,L,H)(k)):k===null||Ht(k)?(e.exit("htmlFlowData"),H(k)):(e.consume(k),I)}function H(k){return e.check(O2,A,L)(k)}function A(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),$}function $(k){return k===null||Ht(k)?H(k):(e.enter("htmlFlowData"),I(k))}function F(k){return k===45?(e.consume(k),M):I(k)}function G(k){return k===47?(e.consume(k),l="",ee):I(k)}function ee(k){if(k===62){const K=l.toLowerCase();return dh.includes(K)?(e.consume(k),T):I(k)}return Is(k)&&l.length<8?(e.consume(k),l+=String.fromCharCode(k),ee):I(k)}function J(k){return k===93?(e.consume(k),M):I(k)}function M(k){return k===62?(e.consume(k),T):k===45&&r===2?(e.consume(k),M):I(k)}function T(k){return k===null||Ht(k)?(e.exit("htmlFlowData"),L(k)):(e.consume(k),T)}function L(k){return e.exit("htmlFlow"),n(k)}}function U2(e,n,s){const a=this;return r;function r(l){return Ht(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return a.parser.lazy[a.now().line]?s(l):n(l)}}function B2(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(yo,n,s)}}const H2={name:"htmlText",tokenize:q2};function q2(e,n,s){const a=this;let r,o,l;return c;function c(M){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(M),d}function d(M){return M===33?(e.consume(M),u):M===47?(e.consume(M),E):M===63?(e.consume(M),S):Is(M)?(e.consume(M),_):s(M)}function u(M){return M===45?(e.consume(M),m):M===91?(e.consume(M),o=0,g):Is(M)?(e.consume(M),y):s(M)}function m(M){return M===45?(e.consume(M),p):s(M)}function h(M){return M===null?s(M):M===45?(e.consume(M),f):Ht(M)?(l=h,G(M)):(e.consume(M),h)}function f(M){return M===45?(e.consume(M),p):h(M)}function p(M){return M===62?F(M):M===45?f(M):h(M)}function g(M){const T="CDATA[";return M===T.charCodeAt(o++)?(e.consume(M),o===T.length?x:g):s(M)}function x(M){return M===null?s(M):M===93?(e.consume(M),v):Ht(M)?(l=x,G(M)):(e.consume(M),x)}function v(M){return M===93?(e.consume(M),b):x(M)}function b(M){return M===62?F(M):M===93?(e.consume(M),b):x(M)}function y(M){return M===null||M===62?F(M):Ht(M)?(l=y,G(M)):(e.consume(M),y)}function S(M){return M===null?s(M):M===63?(e.consume(M),N):Ht(M)?(l=S,G(M)):(e.consume(M),S)}function N(M){return M===62?F(M):S(M)}function E(M){return Is(M)?(e.consume(M),w):s(M)}function w(M){return M===45||As(M)?(e.consume(M),w):j(M)}function j(M){return Ht(M)?(l=j,G(M)):pn(M)?(e.consume(M),j):F(M)}function _(M){return M===45||As(M)?(e.consume(M),_):M===47||M===62||Bn(M)?D(M):s(M)}function D(M){return M===47?(e.consume(M),F):M===58||M===95||Is(M)?(e.consume(M),C):Ht(M)?(l=D,G(M)):pn(M)?(e.consume(M),D):F(M)}function C(M){return M===45||M===46||M===58||M===95||As(M)?(e.consume(M),C):P(M)}function P(M){return M===61?(e.consume(M),I):Ht(M)?(l=P,G(M)):pn(M)?(e.consume(M),P):D(M)}function I(M){return M===null||M===60||M===61||M===62||M===96?s(M):M===34||M===39?(e.consume(M),r=M,H):Ht(M)?(l=I,G(M)):pn(M)?(e.consume(M),I):(e.consume(M),A)}function H(M){return M===r?(e.consume(M),r=void 0,$):M===null?s(M):Ht(M)?(l=H,G(M)):(e.consume(M),H)}function A(M){return M===null||M===34||M===39||M===60||M===61||M===96?s(M):M===47||M===62||Bn(M)?D(M):(e.consume(M),A)}function $(M){return M===47||M===62||Bn(M)?D(M):s(M)}function F(M){return M===62?(e.consume(M),e.exit("htmlTextData"),e.exit("htmlText"),n):s(M)}function G(M){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),ee}function ee(M){return pn(M)?jn(e,J,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):J(M)}function J(M){return e.enter("htmlTextData"),l(M)}}const bu={name:"labelEnd",resolveAll:G2,resolveTo:J2,tokenize:Y2},V2={tokenize:Q2},W2={tokenize:X2},K2={tokenize:Z2};function G2(e){let n=-1;const s=[];for(;++n<e.length;){const a=e[n][1];if(s.push(e[n]),a.type==="labelImage"||a.type==="labelLink"||a.type==="labelEnd"){const r=a.type==="labelImage"?4:2;a.type="data",n+=r}}return e.length!==s.length&&Ks(e,0,e.length,s),e}function J2(e,n){let s=e.length,a=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")){a=2;break}}else r.type==="labelEnd"&&(l=s);const d={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},u={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+a+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",d,n],["enter",u,n]],c=si(c,e.slice(o+1,o+a+3)),c=si(c,[["enter",m,n]]),c=si(c,ql(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=si(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=si(c,e.slice(l+1)),c=si(c,[["exit",d,n]]),Ks(e,o,e.length,c),e}function Y2(e,n,s){const a=this;let r=a.events.length,o,l;for(;r--;)if((a.events[r][1].type==="labelImage"||a.events[r][1].type==="labelLink")&&!a.events[r][1]._balanced){o=a.events[r][1];break}return c;function c(f){return o?o._inactive?h(f):(l=a.parser.defined.includes(ui(a.sliceSerialize({start:o.end,end:a.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(f),e.exit("labelMarker"),e.exit("labelEnd"),d):s(f)}function d(f){return f===40?e.attempt(V2,m,l?m:h)(f):f===91?e.attempt(W2,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(K2,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function Q2(e,n,s){return a;function a(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return Bn(h)?Gr(e,o)(h):o(h)}function o(h){return h===41?m(h):Wg(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Bn(h)?Gr(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?Gg(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return Bn(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 X2(e,n,s){const a=this;return r;function r(c){return Kg.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(ui(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function Z2(e,n,s){return a;function a(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 eE={name:"labelStartImage",resolveAll:bu.resolveAll,tokenize:tE};function tE(e,n,s){const a=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 a.parser.constructs?s(c):n(c)}}const nE={name:"labelStartLink",resolveAll:bu.resolveAll,tokenize:sE};function sE(e,n,s){const a=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 a.parser.constructs?s(l):n(l)}}const wc={name:"lineEnding",tokenize:iE};function iE(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),jn(e,n,"linePrefix")}}const il={name:"thematicBreak",tokenize:aE};function aE(e,n,s){let a=0,r;return o;function o(u){return e.enter("thematicBreak"),l(u)}function l(u){return r=u,c(u)}function c(u){return u===r?(e.enter("thematicBreakSequence"),d(u)):a>=3&&(u===null||Ht(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),pn(u)?jn(e,c,"whitespace")(u):c(u))}}const Os={continuation:{tokenize:cE},exit:uE,name:"list",tokenize:lE},rE={partial:!0,tokenize:mE},oE={partial:!0,tokenize:dE};function lE(e,n,s){const a=this,r=a.events[a.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=a.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!a.containerState.marker||p===a.containerState.marker:Td(p)){if(a.containerState.type||(a.containerState.type=g,e.enter(g,{_container:!0})),g==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(il,s,u)(p):u(p);if(!a.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),d(p)}return s(p)}function d(p){return Td(p)&&++l<10?(e.consume(p),d):(!a.interrupt||l<2)&&(a.containerState.marker?p===a.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),u(p)):s(p)}function u(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),a.containerState.marker=a.containerState.marker||p,e.check(yo,a.interrupt?s:m,e.attempt(rE,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return pn(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),f):s(p)}function f(p){return a.containerState.size=o+a.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function cE(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(yo,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,jn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!pn(c)?(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,l(c)):(a.containerState.furtherBlankLines=void 0,a.containerState.initialBlankLine=void 0,e.attempt(oE,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,jn(e,e.attempt(Os,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function dE(e,n,s){const a=this;return jn(e,r,"listItemIndent",a.containerState.size+1);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===a.containerState.size?n(o):s(o)}}function uE(e){e.exit(this.containerState.type)}function mE(e,n,s){const a=this;return jn(e,r,"listItemPrefixWhitespace",a.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=a.events[a.events.length-1];return!pn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const uh={name:"setextUnderline",resolveTo:hE,tokenize:pE};function hE(e,n){let s=e.length,a,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){a=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[a][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[a][1],n]),e[a][1].end={...e[o][1].end}):e[a][1]=l,e.push(["exit",l,n]),e}function pE(e,n,s){const a=this;let r;return o;function o(u){let m=a.events.length,h;for(;m--;)if(a.events[m][1].type!=="lineEnding"&&a.events[m][1].type!=="linePrefix"&&a.events[m][1].type!=="content"){h=a.events[m][1].type==="paragraph";break}return!a.parser.lazy[a.now().line]&&(a.interrupt||h)?(e.enter("setextHeadingLine"),r=u,l(u)):s(u)}function l(u){return e.enter("setextHeadingLineSequence"),c(u)}function c(u){return u===r?(e.consume(u),c):(e.exit("setextHeadingLineSequence"),pn(u)?jn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||Ht(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const fE={tokenize:gE};function gE(e){const n=this,s=e.attempt(yo,a,e.attempt(this.parser.constructs.flowInitial,r,jn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(w2,r)),"linePrefix")));return s;function a(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 bE={resolveAll:Yg()},xE=Jg("string"),vE=Jg("text");function Jg(e){return{resolveAll:Yg(e==="text"?yE:void 0),tokenize:n};function n(s){const a=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return u(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),d}function d(m){return u(m)?(s.exit("data"),o(m)):(s.consume(m),d)}function u(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(a,a.previous))return!0}return!1}}}function Yg(e){return n;function n(s,a){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,a):s}}function yE(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 a=e[s-1][1],r=n.sliceStream(a);let o=r.length,l=-1,c=0,d;for(;o--;){const u=r[o];if(typeof u=="string"){for(l=u.length;u.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(u===-2)d=!0,c++;else if(u!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const u={type:s===e.length||d||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:a.start._bufferIndex+l,_index:a.start._index+o,line:a.end.line,column:a.end.column-c,offset:a.end.offset-c},end:{...a.end}};a.end={...u.start},a.start.offset===a.end.offset?Object.assign(a,u):(e.splice(s,0,["enter",u,n],["exit",u,n]),s+=2)}s++}return e}const wE={42:Os,43:Os,45:Os,48:Os,49:Os,50:Os,51:Os,52:Os,53:Os,54:Os,55:Os,56:Os,57:Os,62:Bg},kE={91:C2},jE={[-2]:yc,[-1]:yc,32:yc},NE={35:T2,42:il,45:[uh,il],60:D2,61:uh,95:il,96:ch,126:ch},SE={38:qg,92:Hg},CE={[-5]:wc,[-4]:wc,[-3]:wc,33:eE,38:qg,42:Rd,60:[n2,H2],91:nE,92:[A2,Hg],93:bu,95:Rd,96:f2},EE={null:[Rd,bE]},_E={null:[42,95]},ME={null:[]},AE=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:_E,contentInitial:kE,disable:ME,document:wE,flow:NE,flowInitial:jE,insideSpan:EE,string:SE,text:CE},Symbol.toStringTag,{value:"Module"}));function PE(e,n,s){let a={_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 d={attempt:j(E),check:j(w),consume:y,enter:S,exit:N,interrupt:j(w,{interrupt:!0})},u={code:null,containerState:{},defineSkip:x,events:[],now:g,parser:e,previous:null,sliceSerialize:f,sliceStream:p,write:h};let m=n.tokenize.call(u,d);return n.resolveAll&&o.push(n),u;function h(P){return l=si(l,P),v(),l[l.length-1]!==null?[]:(_(n,0),u.events=ql(o,u.events,u),u.events)}function f(P,I){return RE(p(P),I)}function p(P){return TE(l,P)}function g(){const{_bufferIndex:P,_index:I,line:H,column:A,offset:$}=a;return{_bufferIndex:P,_index:I,line:H,column:A,offset:$}}function x(P){r[P.line]=P.column,C()}function v(){let P;for(;a._index<l.length;){const I=l[a._index];if(typeof I=="string")for(P=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===P&&a._bufferIndex<I.length;)b(I.charCodeAt(a._bufferIndex));else b(I)}}function b(P){m=m(P)}function y(P){Ht(P)?(a.line++,a.column=1,a.offset+=P===-3?2:1,C()):P!==-1&&(a.column++,a.offset++),a._bufferIndex<0?a._index++:(a._bufferIndex++,a._bufferIndex===l[a._index].length&&(a._bufferIndex=-1,a._index++)),u.previous=P}function S(P,I){const H=I||{};return H.type=P,H.start=g(),u.events.push(["enter",H,u]),c.push(H),H}function N(P){const I=c.pop();return I.end=g(),u.events.push(["exit",I,u]),I}function E(P,I){_(P,I.from)}function w(P,I){I.restore()}function j(P,I){return H;function H(A,$,F){let G,ee,J,M;return Array.isArray(A)?L(A):"tokenize"in A?L([A]):T(A);function T(le){return we;function we(ge){const Ue=ge!==null&&le[ge],Z=ge!==null&&le.null,Q=[...Array.isArray(Ue)?Ue:Ue?[Ue]:[],...Array.isArray(Z)?Z:Z?[Z]:[]];return L(Q)(ge)}}function L(le){return G=le,ee=0,le.length===0?F:k(le[ee])}function k(le){return we;function we(ge){return M=D(),J=le,le.partial||(u.currentConstruct=le),le.name&&u.parser.constructs.disable.null.includes(le.name)?oe():le.tokenize.call(I?Object.assign(Object.create(u),I):u,d,K,oe)(ge)}}function K(le){return P(J,M),$}function oe(le){return M.restore(),++ee<G.length?k(G[ee]):F}}}function _(P,I){P.resolveAll&&!o.includes(P)&&o.push(P),P.resolve&&Ks(u.events,I,u.events.length-I,P.resolve(u.events.slice(I),u)),P.resolveTo&&(u.events=P.resolveTo(u.events,u))}function D(){const P=g(),I=u.previous,H=u.currentConstruct,A=u.events.length,$=Array.from(c);return{from:A,restore:F};function F(){a=P,u.previous=I,u.currentConstruct=H,u.events.length=A,c=$,C()}}function C(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function TE(e,n){const s=n.start._index,a=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(a,o)];else{if(l=e.slice(s,r),a>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(a):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function RE(e,n){let s=-1;const a=[];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=`
|
|
655
|
-
`;break}case-3:{l=`\r
|
|
656
|
-
`;break}case-2:{l=n?" ":" ";break}case-1:{if(!n&&r)continue;l=" ";break}default:l=String.fromCharCode(o)}r=o===-2,a.push(l)}return a.join("")}function IE(e){const a={constructs:zg([AE,...(e||{}).extensions||[]]),content:r(JC),defined:[],document:r(QC),flow:r(fE),lazy:{},string:r(xE),text:r(vE)};return a;function r(o){return l;function l(c){return PE(a,o,c)}}}function $E(e){for(;!Vg(e););return e}const mh=/[\0\t\n\r]/g;function DE(){let e=1,n="",s=!0,a;return r;function r(o,l,c){const d=[];let u,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(mh.lastIndex=h,u=mh.exec(o),f=u&&u.index!==void 0?u.index:o.length,p=o.charCodeAt(f),!u){n=o.slice(h);break}if(p===10&&h===f&&a)d.push(-3),a=void 0;else switch(a&&(d.push(-5),a=void 0),h<f&&(d.push(o.slice(h,f)),e+=f-h),p){case 0:{d.push(65533),e++;break}case 9:{for(m=Math.ceil(e/4)*4,d.push(-2);e++<m;)d.push(-1);break}case 10:{d.push(-4),e=1;break}default:a=!0,e=1}h=f+1}return c&&(a&&d.push(-5),n&&d.push(n),d.push(null)),d}}const LE=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function OE(e){return e.replace(LE,FE)}function FE(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return Ug(s.slice(o?2:1),o?16:10)}return gu(s)||e}const Qg={}.hasOwnProperty;function zE(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),UE(s)($E(IE(s).document().write(DE()(e,n,!0))))}function UE(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(te),autolinkProtocol:D,autolinkEmail:D,atxHeading:o(B),blockQuote:o(Z),characterEscape:D,characterReference:D,codeFenced:o(Q),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(Q,l),codeText:o(X,l),codeTextData:D,data:D,codeFlowValue:D,definition:o(ie),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(se),hardBreakEscape:o(O),hardBreakTrailing:o(O),htmlFlow:o(ke,l),htmlFlowData:D,htmlText:o(ke,l),htmlTextData:D,image:o(ae),label:l,link:o(te),listItem:o(Oe),listItemValue:f,listOrdered:o(Ie,h),listUnordered:o(Ie),paragraph:o(He),reference:k,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(B),strong:o($e),thematicBreak:o(ue)},exit:{atxHeading:d(),atxHeadingSequence:E,autolink:d(),autolinkEmail:Ue,autolinkProtocol:ge,blockQuote:d(),characterEscapeValue:C,characterReferenceMarkerHexadecimal:oe,characterReferenceMarkerNumeric:oe,characterReferenceValue:le,characterReference:we,codeFenced:d(v),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:C,codeIndented:d(b),codeText:d($),codeTextData:C,data:C,definition:d(),definitionDestinationString:N,definitionLabelString:y,definitionTitleString:S,emphasis:d(),hardBreakEscape:d(I),hardBreakTrailing:d(I),htmlFlow:d(H),htmlFlowData:C,htmlText:d(A),htmlTextData:C,image:d(G),label:J,labelText:ee,lineEnding:P,link:d(F),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:K,resourceDestinationString:M,resourceTitleString:T,resource:L,setextHeading:d(_),setextHeadingLineSequence:j,setextHeadingText:w,strong:d(),thematicBreak:d()}};Xg(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(ce){let Ae={type:"root",children:[]};const Ne={stack:[Ae],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},ye=[];let Ce=-1;for(;++Ce<ce.length;)if(ce[Ce][1].type==="listOrdered"||ce[Ce][1].type==="listUnordered")if(ce[Ce][0]==="enter")ye.push(Ce);else{const fe=ye.pop();Ce=r(ce,fe,Ce)}for(Ce=-1;++Ce<ce.length;){const fe=n[ce[Ce][0]];Qg.call(fe,ce[Ce][1].type)&&fe[ce[Ce][1].type].call(Object.assign({sliceSerialize:ce[Ce][2].sliceSerialize},Ne),ce[Ce][1])}if(Ne.tokenStack.length>0){const fe=Ne.tokenStack[Ne.tokenStack.length-1];(fe[1]||hh).call(Ne,void 0,fe[0])}for(Ae.position={start:Ji(ce.length>0?ce[0][1].start:{line:1,column:1,offset:0}),end:Ji(ce.length>0?ce[ce.length-2][1].end:{line:1,column:1,offset:0})},Ce=-1;++Ce<n.transforms.length;)Ae=n.transforms[Ce](Ae)||Ae;return Ae}function r(ce,Ae,Ne){let ye=Ae-1,Ce=-1,fe=!1,Pe,De,dt,pt;for(;++ye<=Ne;){const lt=ce[ye];switch(lt[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{lt[0]==="enter"?Ce++:Ce--,pt=void 0;break}case"lineEndingBlank":{lt[0]==="enter"&&(Pe&&!pt&&!Ce&&!dt&&(dt=ye),pt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:pt=void 0}if(!Ce&<[0]==="enter"&<[1].type==="listItemPrefix"||Ce===-1&<[0]==="exit"&&(lt[1].type==="listUnordered"||lt[1].type==="listOrdered")){if(Pe){let vt=ye;for(De=void 0;vt--;){const _e=ce[vt];if(_e[1].type==="lineEnding"||_e[1].type==="lineEndingBlank"){if(_e[0]==="exit")continue;De&&(ce[De][1].type="lineEndingBlank",fe=!0),_e[1].type="lineEnding",De=vt}else if(!(_e[1].type==="linePrefix"||_e[1].type==="blockQuotePrefix"||_e[1].type==="blockQuotePrefixWhitespace"||_e[1].type==="blockQuoteMarker"||_e[1].type==="listItemIndent"))break}dt&&(!De||dt<De)&&(Pe._spread=!0),Pe.end=Object.assign({},De?ce[De][1].start:lt[1].end),ce.splice(De||ye,0,["exit",Pe,lt[2]]),ye++,Ne++}if(lt[1].type==="listItemPrefix"){const vt={type:"listItem",_spread:!1,start:Object.assign({},lt[1].start),end:void 0};Pe=vt,ce.splice(ye,0,["enter",vt,lt[2]]),ye++,Ne++,dt=void 0,pt=!0}}}return ce[Ae][1]._spread=fe,Ne}function o(ce,Ae){return Ne;function Ne(ye){c.call(this,ce(ye),ye),Ae&&Ae.call(this,ye)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(ce,Ae,Ne){this.stack[this.stack.length-1].children.push(ce),this.stack.push(ce),this.tokenStack.push([Ae,Ne||void 0]),ce.position={start:Ji(Ae.start),end:void 0}}function d(ce){return Ae;function Ae(Ne){ce&&ce.call(this,Ne),u.call(this,Ne)}}function u(ce,Ae){const Ne=this.stack.pop(),ye=this.tokenStack.pop();if(ye)ye[0].type!==ce.type&&(Ae?Ae.call(this,ce,ye[0]):(ye[1]||hh).call(this,ce,ye[0]));else throw new Error("Cannot close `"+ce.type+"` ("+Kr({start:ce.start,end:ce.end})+"): it’s not open");Ne.position.end=Ji(ce.end)}function m(){return fu(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(ce){if(this.data.expectingFirstListItemValue){const Ae=this.stack[this.stack.length-2];Ae.start=Number.parseInt(this.sliceSerialize(ce),10),this.data.expectingFirstListItemValue=void 0}}function p(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.lang=ce}function g(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.meta=ce}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function v(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.value=ce.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.value=ce.replace(/(\r?\n|\r)$/g,"")}function y(ce){const Ae=this.resume(),Ne=this.stack[this.stack.length-1];Ne.label=Ae,Ne.identifier=ui(this.sliceSerialize(ce)).toLowerCase()}function S(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.title=ce}function N(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.url=ce}function E(ce){const Ae=this.stack[this.stack.length-1];if(!Ae.depth){const Ne=this.sliceSerialize(ce).length;Ae.depth=Ne}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function j(ce){const Ae=this.stack[this.stack.length-1];Ae.depth=this.sliceSerialize(ce).codePointAt(0)===61?1:2}function _(){this.data.setextHeadingSlurpLineEnding=void 0}function D(ce){const Ne=this.stack[this.stack.length-1].children;let ye=Ne[Ne.length-1];(!ye||ye.type!=="text")&&(ye=Te(),ye.position={start:Ji(ce.start),end:void 0},Ne.push(ye)),this.stack.push(ye)}function C(ce){const Ae=this.stack.pop();Ae.value+=this.sliceSerialize(ce),Ae.position.end=Ji(ce.end)}function P(ce){const Ae=this.stack[this.stack.length-1];if(this.data.atHardBreak){const Ne=Ae.children[Ae.children.length-1];Ne.position.end=Ji(ce.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Ae.type)&&(D.call(this,ce),C.call(this,ce))}function I(){this.data.atHardBreak=!0}function H(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.value=ce}function A(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.value=ce}function $(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.value=ce}function F(){const ce=this.stack[this.stack.length-1];if(this.data.inReference){const Ae=this.data.referenceType||"shortcut";ce.type+="Reference",ce.referenceType=Ae,delete ce.url,delete ce.title}else delete ce.identifier,delete ce.label;this.data.referenceType=void 0}function G(){const ce=this.stack[this.stack.length-1];if(this.data.inReference){const Ae=this.data.referenceType||"shortcut";ce.type+="Reference",ce.referenceType=Ae,delete ce.url,delete ce.title}else delete ce.identifier,delete ce.label;this.data.referenceType=void 0}function ee(ce){const Ae=this.sliceSerialize(ce),Ne=this.stack[this.stack.length-2];Ne.label=OE(Ae),Ne.identifier=ui(Ae).toLowerCase()}function J(){const ce=this.stack[this.stack.length-1],Ae=this.resume(),Ne=this.stack[this.stack.length-1];if(this.data.inReference=!0,Ne.type==="link"){const ye=ce.children;Ne.children=ye}else Ne.alt=Ae}function M(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.url=ce}function T(){const ce=this.resume(),Ae=this.stack[this.stack.length-1];Ae.title=ce}function L(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function K(ce){const Ae=this.resume(),Ne=this.stack[this.stack.length-1];Ne.label=Ae,Ne.identifier=ui(this.sliceSerialize(ce)).toLowerCase(),this.data.referenceType="full"}function oe(ce){this.data.characterReferenceType=ce.type}function le(ce){const Ae=this.sliceSerialize(ce),Ne=this.data.characterReferenceType;let ye;Ne?(ye=Ug(Ae,Ne==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):ye=gu(Ae);const Ce=this.stack[this.stack.length-1];Ce.value+=ye}function we(ce){const Ae=this.stack.pop();Ae.position.end=Ji(ce.end)}function ge(ce){C.call(this,ce);const Ae=this.stack[this.stack.length-1];Ae.url=this.sliceSerialize(ce)}function Ue(ce){C.call(this,ce);const Ae=this.stack[this.stack.length-1];Ae.url="mailto:"+this.sliceSerialize(ce)}function Z(){return{type:"blockquote",children:[]}}function Q(){return{type:"code",lang:null,meta:null,value:""}}function X(){return{type:"inlineCode",value:""}}function ie(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function se(){return{type:"emphasis",children:[]}}function B(){return{type:"heading",depth:0,children:[]}}function O(){return{type:"break"}}function ke(){return{type:"html",value:""}}function ae(){return{type:"image",title:null,url:"",alt:null}}function te(){return{type:"link",title:null,url:"",children:[]}}function Ie(ce){return{type:"list",ordered:ce.type==="listOrdered",start:null,spread:ce._spread,children:[]}}function Oe(ce){return{type:"listItem",spread:ce._spread,checked:null,children:[]}}function He(){return{type:"paragraph",children:[]}}function $e(){return{type:"strong",children:[]}}function Te(){return{type:"text",value:""}}function ue(){return{type:"thematicBreak"}}}function Ji(e){return{line:e.line,column:e.column,offset:e.offset}}function Xg(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?Xg(e,a):BE(e,a)}}function BE(e,n){let s;for(s in n)if(Qg.call(n,s))switch(s){case"canContainEols":{const a=n[s];a&&e[s].push(...a);break}case"transforms":{const a=n[s];a&&e[s].push(...a);break}case"enter":case"exit":{const a=n[s];a&&Object.assign(e[s],a);break}}}function hh(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+Kr({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+Kr({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+Kr({start:n.start,end:n.end})+") is still open")}function HE(e){const n=this;n.parser=s;function s(a){return zE(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function qE(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 VE(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
657
|
-
`}]}function WE(e,n){const s=n.value?n.value+`
|
|
658
|
-
`:"",a={},r=n.lang?n.lang.split(/\s+/):[];r.length>0&&(a.className=["language-"+r[0]]);let o={type:"element",tagName:"code",properties:a,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 KE(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function GE(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function JE(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=fr(a.toLowerCase()),o=e.footnoteOrder.indexOf(a);let l,c=e.footnoteCounts.get(a);c===void 0?(c=0,e.footnoteOrder.push(a),l=e.footnoteOrder.length):l=o+1,c+=1,e.footnoteCounts.set(a,c);const d={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,d);const u={type:"element",tagName:"sup",properties:{},children:[d]};return e.patch(n,u),e.applyData(n,u)}function YE(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 QE(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function Zg(e,n){const s=n.referenceType;let a="]";if(s==="collapsed"?a+="[]":s==="full"&&(a+="["+(n.label||n.identifier)+"]"),n.type==="imageReference")return[{type:"text",value:"!["+n.alt+a}];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+=a:r.push({type:"text",value:a}),r}function XE(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Zg(e,n);const r={src:fr(a.url||""),alt:n.alt};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"img",properties:r,children:[]};return e.patch(n,o),e.applyData(n,o)}function ZE(e,n){const s={src:fr(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 a={type:"element",tagName:"img",properties:s,children:[]};return e.patch(n,a),e.applyData(n,a)}function e_(e,n){const s={type:"text",value:n.value.replace(/\r?\n|\r/g," ")};e.patch(n,s);const a={type:"element",tagName:"code",properties:{},children:[s]};return e.patch(n,a),e.applyData(n,a)}function t_(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return Zg(e,n);const r={href:fr(a.url||"")};a.title!==null&&a.title!==void 0&&(r.title=a.title);const o={type:"element",tagName:"a",properties:r,children:e.all(n)};return e.patch(n,o),e.applyData(n,o)}function n_(e,n){const s={href:fr(n.url)};n.title!==null&&n.title!==void 0&&(s.title=n.title);const a={type:"element",tagName:"a",properties:s,children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function s_(e,n,s){const a=e.all(n),r=s?i_(s):eb(n),o={},l=[];if(typeof n.checked=="boolean"){const m=a[0];let h;m&&m.type==="element"&&m.tagName==="p"?h=m:(h={type:"element",tagName:"p",properties:{},children:[]},a.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<a.length;){const m=a[c];(r||c!==0||m.type!=="element"||m.tagName!=="p")&&l.push({type:"text",value:`
|
|
659
|
-
`}),m.type==="element"&&m.tagName==="p"&&!r?l.push(...m.children):l.push(m)}const d=a[a.length-1];d&&(r||d.type!=="element"||d.tagName!=="p")&&l.push({type:"text",value:`
|
|
660
|
-
`});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function i_(e){let n=!1;if(e.type==="list"){n=e.spread||!1;const s=e.children;let a=-1;for(;!n&&++a<s.length;)n=eb(s[a])}return n}function eb(e){const n=e.spread;return n??e.children.length>1}function a_(e,n){const s={},a=e.all(n);let r=-1;for(typeof n.start=="number"&&n.start!==1&&(s.start=n.start);++r<a.length;){const l=a[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(a,!0)};return e.patch(n,o),e.applyData(n,o)}function r_(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function o_(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function l_(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function c_(e,n){const s=e.all(n),a=s.shift(),r=[];if(a){const l={type:"element",tagName:"thead",properties:{},children:e.wrap([a],!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=uu(n.children[1]),d=Rg(n.children[n.children.length-1]);c&&d&&(l.position={start:c,end:d}),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 d_(e,n,s){const a=s?s.children:void 0,o=(a?a.indexOf(n):1)===0?"th":"td",l=s&&s.type==="table"?s.align:void 0,c=l?l.length:n.children.length;let d=-1;const u=[];for(;++d<c;){const h=n.children[d],f={},p=l?l[d]: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)),u.push(g)}const m={type:"element",tagName:"tr",properties:{},children:e.wrap(u,!0)};return e.patch(n,m),e.applyData(n,m)}function u_(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const ph=9,fh=32;function m_(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(gh(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(gh(n.slice(r),r>0,!1)),o.join("")}function gh(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===ph||o===fh;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===ph||o===fh;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function h_(e,n){const s={type:"text",value:m_(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function p_(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const f_={blockquote:qE,break:VE,code:WE,delete:KE,emphasis:GE,footnoteReference:JE,heading:YE,html:QE,imageReference:XE,image:ZE,inlineCode:e_,linkReference:t_,link:n_,listItem:s_,list:a_,paragraph:r_,root:o_,strong:l_,table:c_,tableCell:u_,tableRow:d_,text:h_,thematicBreak:p_,toml:Mo,yaml:Mo,definition:Mo,footnoteDefinition:Mo};function Mo(){}const tb=-1,Vl=0,Jr=1,yl=2,xu=3,vu=4,yu=5,wu=6,nb=7,sb=8,bh=typeof self=="object"?self:globalThis,g_=(e,n)=>{const s=(r,o)=>(e.set(o,r),r),a=r=>{if(e.has(r))return e.get(r);const[o,l]=n[r];switch(o){case Vl:case tb:return s(l,r);case Jr:{const c=s([],r);for(const d of l)c.push(a(d));return c}case yl:{const c=s({},r);for(const[d,u]of l)c[a(d)]=a(u);return c}case xu:return s(new Date(l),r);case vu:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case yu:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case wu:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case nb:{const{name:c,message:d}=l;return s(new bh[c](d),r)}case sb: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 bh[o](l),r)};return a},xh=e=>g_(new Map,e)(0),Oa="",{toString:b_}={},{keys:x_}=Object,Er=e=>{const n=typeof e;if(n!=="object"||!e)return[Vl,n];const s=b_.call(e).slice(8,-1);switch(s){case"Array":return[Jr,Oa];case"Object":return[yl,Oa];case"Date":return[xu,Oa];case"RegExp":return[vu,Oa];case"Map":return[yu,Oa];case"Set":return[wu,Oa];case"DataView":return[Jr,s]}return s.includes("Array")?[Jr,s]:s.includes("Error")?[nb,s]:[yl,s]},Ao=([e,n])=>e===Vl&&(n==="function"||n==="symbol"),v_=(e,n,s,a)=>{const r=(l,c)=>{const d=a.push(l)-1;return s.set(c,d),d},o=l=>{if(s.has(l))return s.get(l);let[c,d]=Er(l);switch(c){case Vl:{let m=l;switch(d){case"bigint":c=sb,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([tb],l)}return r([c,m],l)}case Jr:{if(d){let f=l;return d==="DataView"?f=new Uint8Array(l.buffer):d==="ArrayBuffer"&&(f=new Uint8Array(l)),r([d,[...f]],l)}const m=[],h=r([c,m],l);for(const f of l)m.push(o(f));return h}case yl:{if(d)switch(d){case"BigInt":return r([d,l.toString()],l);case"Boolean":case"Number":case"String":return r([d,l.valueOf()],l)}if(n&&"toJSON"in l)return o(l.toJSON());const m=[],h=r([c,m],l);for(const f of x_(l))(e||!Ao(Er(l[f])))&&m.push([o(f),o(l[f])]);return h}case xu:return r([c,l.toISOString()],l);case vu:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case yu:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(Ao(Er(f))||Ao(Er(p))))&&m.push([o(f),o(p)]);return h}case wu:{const m=[],h=r([c,m],l);for(const f of l)(e||!Ao(Er(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},vh=(e,{json:n,lossy:s}={})=>{const a=[];return v_(!(n||s),!!n,new Map,a)(e),a},wl=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?xh(vh(e,n)):structuredClone(e):(e,n)=>xh(vh(e,n));function y_(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 w_(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function k_(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||y_,a=e.options.footnoteBackLabel||w_,r=e.options.footnoteLabel||"Footnotes",o=e.options.footnoteLabelTagName||"h2",l=e.options.footnoteLabelProperties||{className:["sr-only"]},c=[];let d=-1;for(;++d<e.footnoteOrder.length;){const u=e.footnoteById.get(e.footnoteOrder[d]);if(!u)continue;const m=e.all(u),h=String(u.identifier).toUpperCase(),f=fr(h.toLowerCase());let p=0;const g=[],x=e.footnoteCounts.get(h);for(;x!==void 0&&++p<=x;){g.length>0&&g.push({type:"text",value:" "});let y=typeof s=="string"?s:s(d,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 a=="string"?a:a(d,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 b={type:"element",tagName:"li",properties:{id:n+"fn-"+f},children:e.wrap(m,!0)};e.patch(u,b),c.push(b)}if(c.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:o,properties:{...wl(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
661
|
-
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
|
|
662
|
-
`}]}}const Wl=(function(e){if(e==null)return C_;if(typeof e=="function")return Kl(e);if(typeof e=="object")return Array.isArray(e)?j_(e):N_(e);if(typeof e=="string")return S_(e);throw new Error("Expected function, string, or object as test")});function j_(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Wl(e[s]);return Kl(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function N_(e){const n=e;return Kl(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function S_(e){return Kl(n);function n(s){return s&&s.type===e}}function Kl(e){return n;function n(s,a,r){return!!(E_(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function C_(){return!0}function E_(e){return e!==null&&typeof e=="object"&&"type"in e}const ib=[],__=!0,Id=!1,M_="skip";function ab(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=Wl(r),l=a?-1:1;c(e,void 0,[])();function c(d,u,m){const h=d&&typeof d=="object"?d:{};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 ("+(d.type+(p?"<"+p+">":""))+")"})}return f;function f(){let p=ib,g,x,v;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=A_(s(d,m)),p[0]===Id))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==M_)for(x=(a?b.children.length:-1)+l,v=m.concat(b);x>-1&&x<b.children.length;){const y=b.children[x];if(g=c(y,x,v)(),g[0]===Id)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function A_(e){return Array.isArray(e)?e:typeof e=="number"?[__,e]:e==null?ib:[e]}function ku(e,n,s,a){let r,o,l;typeof n=="function"&&typeof s!="function"?(o=void 0,l=n,r=s):(o=n,l=s,r=a),ab(e,o,c,r);function c(d,u){const m=u[u.length-1],h=m?m.children.indexOf(d):void 0;return l(d,h,m)}}const $d={}.hasOwnProperty,P_={};function T_(e,n){const s=n||P_,a=new Map,r=new Map,o=new Map,l={...f_,...s.handlers},c={all:u,applyData:I_,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:R_,wrap:D_};return ku(e,function(m){if(m.type==="definition"||m.type==="footnoteDefinition"){const h=m.type==="definition"?a:r,f=String(m.identifier).toUpperCase();h.has(f)||h.set(f,m)}}),c;function d(m,h){const f=m.type,p=c.handlers[f];if($d.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:x,...v}=m,b=wl(v);return b.children=c.all(m),b}return wl(m)}return(c.options.unknownHandler||$_)(c,m,h)}function u(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=yh(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=yh(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function R_(e,n){e.position&&(n.position=wC(e))}function I_(e,n){let s=n;if(e&&e.data){const a=e.data.hName,r=e.data.hChildren,o=e.data.hProperties;if(typeof a=="string")if(s.type==="element")s.tagName=a;else{const l="children"in s?s.children:[s];s={type:"element",tagName:a,properties:{},children:l}}s.type==="element"&&o&&Object.assign(s.properties,wl(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function $_(e,n){const s=n.data||{},a="value"in n&&!($d.call(s,"hProperties")||$d.call(s,"hChildren"))?{type:"text",value:n.value}:{type:"element",tagName:"div",properties:{},children:e.all(n)};return e.patch(n,a),e.applyData(n,a)}function D_(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
|
|
663
|
-
`});++a<e.length;)a&&s.push({type:"text",value:`
|
|
664
|
-
`}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
|
|
665
|
-
`}),s}function yh(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function wh(e,n){const s=T_(e,n),a=s.one(e,void 0),r=k_(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
666
|
-
`},r),o}function L_(e,n){return e&&"run"in e?async function(s,a){const r=wh(s,{file:a,...n});await e.run(r,a)}:function(s,a){return wh(s,{file:a,...e||n})}}function kh(e){if(e)throw e}var kc,jh;function O_(){if(jh)return kc;jh=1;var e=Object.prototype.hasOwnProperty,n=Object.prototype.toString,s=Object.defineProperty,a=Object.getOwnPropertyDescriptor,r=function(u){return typeof Array.isArray=="function"?Array.isArray(u):n.call(u)==="[object Array]"},o=function(u){if(!u||n.call(u)!=="[object Object]")return!1;var m=e.call(u,"constructor"),h=u.constructor&&u.constructor.prototype&&e.call(u.constructor.prototype,"isPrototypeOf");if(u.constructor&&!m&&!h)return!1;var f;for(f in u);return typeof f>"u"||e.call(u,f)},l=function(u,m){s&&m.name==="__proto__"?s(u,m.name,{enumerable:!0,configurable:!0,value:m.newValue,writable:!0}):u[m.name]=m.newValue},c=function(u,m){if(m==="__proto__")if(e.call(u,m)){if(a)return a(u,m).value}else return;return u[m]};return kc=function d(){var u,m,h,f,p,g,x=arguments[0],v=1,b=arguments.length,y=!1;for(typeof x=="boolean"&&(y=x,x=arguments[1]||{},v=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});v<b;++v)if(u=arguments[v],u!=null)for(m in u)h=c(x,m),f=c(u,m),x!==f&&(y&&f&&(o(f)||(p=r(f)))?(p?(p=!1,g=h&&r(h)?h:[]):g=h&&o(h)?h:{},l(x,{name:m,newValue:d(y,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},kc}var F_=O_();const jc=Nf(F_);function Dd(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 z_(){const e=[],n={run:s,use:a};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(d,...u){const m=e[++o];let h=-1;if(d){l(d);return}for(;++h<r.length;)(u[h]===null||u[h]===void 0)&&(u[h]=r[h]);r=u,m?U_(m,c)(...u):l(null,...u)}}function a(r){if(typeof r!="function")throw new TypeError("Expected `middelware` to be a function, not "+r);return e.push(r),n}}function U_(e,n){let s;return a;function a(...l){const c=e.length>l.length;let d;c&&l.push(r);try{d=e.apply(this,l)}catch(u){const m=u;if(c&&s)throw m;return r(m)}c||(d&&d.then&&typeof d.then=="function"?d.then(o,r):d instanceof Error?r(d):o(d))}function r(l,...c){s||(s=!0,n(l,...c))}function o(l){r(null,l)}}const Ni={basename:B_,dirname:H_,extname:q_,join:V_,sep:"/"};function B_(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');wo(e);let s=0,a=-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 a<0&&(o=!0,a=r+1);return a<0?"":e.slice(s,a)}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&&(a=r):(c=-1,a=l));return s===a?a=l:a<0&&(a=e.length),e.slice(s,a)}function H_(e){if(wo(e),e.length===0)return".";let n=-1,s=e.length,a;for(;--s;)if(e.codePointAt(s)===47){if(a){n=s;break}}else a||(a=!0);return n<0?e.codePointAt(0)===47?"/":".":n===1&&e.codePointAt(0)===47?"//":e.slice(0,n)}function q_(e){wo(e);let n=e.length,s=-1,a=0,r=-1,o=0,l;for(;n--;){const c=e.codePointAt(n);if(c===47){if(l){a=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===a+1?"":e.slice(r,s)}function V_(...e){let n=-1,s;for(;++n<e.length;)wo(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":W_(s)}function W_(e){wo(e);const n=e.codePointAt(0)===47;let s=K_(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function K_(e,n){let s="",a=0,r=-1,o=0,l=-1,c,d;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||a!==2||s.codePointAt(s.length-1)!==46||s.codePointAt(s.length-2)!==46){if(s.length>2){if(d=s.lastIndexOf("/"),d!==s.length-1){d<0?(s="",a=0):(s=s.slice(0,d),a=s.length-1-s.lastIndexOf("/")),r=l,o=0;continue}}else if(s.length>0){s="",a=0,r=l,o=0;continue}}n&&(s=s.length>0?s+"/..":"..",a=2)}else s.length>0?s+="/"+e.slice(r+1,l):s=e.slice(r+1,l),a=l-r-1;r=l,o=0}else c===46&&o>-1?o++:o=-1}return s}function wo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const G_={cwd:J_};function J_(){return"/"}function Ld(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function Y_(e){if(typeof e=="string")e=new URL(e);else if(!Ld(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 Q_(e)}function Q_(e){if(e.hostname!==""){const a=new TypeError('File URL host must be "localhost" or empty on darwin');throw a.code="ERR_INVALID_FILE_URL_HOST",a}const n=e.pathname;let s=-1;for(;++s<n.length;)if(n.codePointAt(s)===37&&n.codePointAt(s+1)===50){const a=n.codePointAt(s+2);if(a===70||a===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 Nc=["history","path","basename","stem","extname","dirname"];class rb{constructor(n){let s;n?Ld(n)?s={path:n}:typeof n=="string"||X_(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":G_.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<Nc.length;){const o=Nc[a];o in s&&s[o]!==void 0&&s[o]!==null&&(this[o]=o==="history"?[...s[o]]:s[o])}let r;for(r in s)Nc.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Ni.basename(this.path):void 0}set basename(n){Cc(n,"basename"),Sc(n,"basename"),this.path=Ni.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Ni.dirname(this.path):void 0}set dirname(n){Nh(this.basename,"dirname"),this.path=Ni.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Ni.extname(this.path):void 0}set extname(n){if(Sc(n,"extname"),Nh(this.dirname,"extname"),n){if(n.codePointAt(0)!==46)throw new Error("`extname` must start with `.`");if(n.includes(".",1))throw new Error("`extname` cannot contain multiple dots")}this.path=Ni.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){Ld(n)&&(n=Y_(n)),Cc(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){Cc(n,"stem"),Sc(n,"stem"),this.path=Ni.join(this.dirname||"",n+(this.extname||""))}fail(n,s,a){const r=this.message(n,s,a);throw r.fatal=!0,r}info(n,s,a){const r=this.message(n,s,a);return r.fatal=void 0,r}message(n,s,a){const r=new Ts(n,s,a);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 Sc(e,n){if(e&&e.includes(Ni.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Ni.sep+"`")}function Cc(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function Nh(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function X_(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const Z_=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),eM={}.hasOwnProperty;class ju extends Z_{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=z_()}copy(){const n=new ju;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(jc(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(Mc("data",this.frozen),this.namespace[n]=s,this):eM.call(this.namespace,n)&&this.namespace[n]||void 0:n?(Mc("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,...a]=this.attachers[this.freezeIndex];if(a[0]===!1)continue;a[0]===!0&&(a[0]=void 0);const r=s.call(n,...a);typeof r=="function"&&this.transformers.use(r)}return this.frozen=!0,this.freezeIndex=Number.POSITIVE_INFINITY,this}parse(n){this.freeze();const s=Po(n),a=this.parser||this.Parser;return Ec("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),Ec("process",this.parser||this.Parser),_c("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=Po(n),d=a.parse(c);a.run(d,c,function(m,h,f){if(m||!h||!f)return u(m);const p=h,g=a.stringify(p,f);sM(g)?f.value=g:f.result=g,u(m,f)});function u(m,h){m||!h?l(m):o?o(h):s(void 0,h)}}}processSync(n){let s=!1,a;return this.freeze(),Ec("processSync",this.parser||this.Parser),_c("processSync",this.compiler||this.Compiler),this.process(n,r),Ch("processSync","process",s),a;function r(o,l){s=!0,kh(o),a=l}}run(n,s,a){Sh(n),this.freeze();const r=this.transformers;return!a&&typeof s=="function"&&(a=s,s=void 0),a?o(void 0,a):new Promise(o);function o(l,c){const d=Po(s);r.run(n,d,u);function u(m,h,f){const p=h||n;m?c(m):l?l(p):a(void 0,p,f)}}}runSync(n,s){let a=!1,r;return this.run(n,s,o),Ch("runSync","run",a),r;function o(l,c){kh(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=Po(s),r=this.compiler||this.Compiler;return _c("stringify",r),Sh(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(Mc("use",this.frozen),n!=null)if(typeof n=="function")d(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(u){if(typeof u=="function")d(u,[]);else if(typeof u=="object")if(Array.isArray(u)){const[m,...h]=u;d(m,h)}else l(u);else throw new TypeError("Expected usable value, not `"+u+"`")}function l(u){if(!("plugins"in u)&&!("settings"in u))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(u.plugins),u.settings&&(r.settings=jc(!0,r.settings,u.settings))}function c(u){let m=-1;if(u!=null)if(Array.isArray(u))for(;++m<u.length;){const h=u[m];o(h)}else throw new TypeError("Expected a list of plugins, not `"+u+"`")}function d(u,m){let h=-1,f=-1;for(;++h<a.length;)if(a[h][0]===u){f=h;break}if(f===-1)a.push([u,...m]);else if(m.length>0){let[p,...g]=m;const x=a[f][1];Dd(x)&&Dd(p)&&(p=jc(!0,x,p)),a[f]=[u,p,...g]}}}}const tM=new ju().freeze();function Ec(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function _c(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function Mc(e,n){if(n)throw new Error("Cannot call `"+e+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function Sh(e){if(!Dd(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function Ch(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function Po(e){return nM(e)?e:new rb(e)}function nM(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function sM(e){return typeof e=="string"||iM(e)}function iM(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const aM="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Eh=[],_h={allowDangerousHtml:!0},rM=/^(https?|ircs?|mailto|xmpp)$/i,oM=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function Ai(e){const n=lM(e),s=cM(e);return dM(n.runSync(n.parse(s),s),e)}function lM(e){const n=e.rehypePlugins||Eh,s=e.remarkPlugins||Eh,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,..._h}:_h;return tM().use(HE).use(s).use(L_,a).use(n)}function cM(e){const n=e.children||"",s=new rb;return typeof n=="string"&&(s.value=n),s}function dM(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||uM;for(const m of oM)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+aM+m.id,void 0);return ku(e,u),CC(e,{Fragment:t.Fragment,components:r,ignoreInvalidStyle:!0,jsx:t.jsx,jsxs:t.jsxs,passKeys:!0,passNode:!0});function u(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 vc)if(Object.hasOwn(vc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=vc[p];(x===null||x.includes(m.tagName))&&(m.properties[p]=d(String(g||""),p,m))}}if(m.type==="element"){let p=s?!s.includes(m.tagName):o?o.includes(m.tagName):!1;if(!p&&a&&typeof h=="number"&&(p=!a(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 uM(e){const n=e.indexOf(":"),s=e.indexOf("?"),a=e.indexOf("#"),r=e.indexOf("/");return n===-1||r!==-1&&n>r||s!==-1&&n>s||a!==-1&&n>a||rM.test(e.slice(0,n))?e:""}function Mh(e,n){const s=String(e);if(typeof n!="string")throw new TypeError("Expected character");let a=0,r=s.indexOf(n);for(;r!==-1;)a++,r=s.indexOf(n,r+n.length);return a}function mM(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function hM(e,n,s){const r=Wl((s||{}).ignore||[]),o=pM(n);let l=-1;for(;++l<o.length;)ab(e,"text",c);function c(u,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 d(u,m)}function d(u,m){const h=m[m.length-1],f=o[l][0],p=o[l][1];let g=0;const v=h.children.indexOf(u);let b=!1,y=[];f.lastIndex=0;let S=f.exec(u.value);for(;S;){const N=S.index,E={index:S.index,input:S.input,stack:[...m,u]};let w=p(...S,E);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?f.lastIndex=N+1:(g!==N&&y.push({type:"text",value:u.value.slice(g,N)}),Array.isArray(w)?y.push(...w):w&&y.push(w),g=N+S[0].length,b=!0),!f.global)break;S=f.exec(u.value)}return b?(g<u.value.length&&y.push({type:"text",value:u.value.slice(g)}),h.children.splice(v,1,...y)):y=[u],v+y.length}}function pM(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 a=-1;for(;++a<s.length;){const r=s[a];n.push([fM(r[0]),gM(r[1])])}return n}function fM(e){return typeof e=="string"?new RegExp(mM(e),"g"):e}function gM(e){return typeof e=="function"?e:function(){return e}}const Ac="phrasing",Pc=["autolink","link","image","label"];function bM(){return{transforms:[NM],enter:{literalAutolink:vM,literalAutolinkEmail:Tc,literalAutolinkHttp:Tc,literalAutolinkWww:Tc},exit:{literalAutolink:jM,literalAutolinkEmail:kM,literalAutolinkHttp:yM,literalAutolinkWww:wM}}}function xM(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:Ac,notInConstruct:Pc},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:Ac,notInConstruct:Pc},{character:":",before:"[ps]",after:"\\/",inConstruct:Ac,notInConstruct:Pc}]}}function vM(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function Tc(e){this.config.enter.autolinkProtocol.call(this,e)}function yM(e){this.config.exit.autolinkProtocol.call(this,e)}function wM(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 kM(e){this.config.exit.autolinkEmail.call(this,e)}function jM(e){this.exit(e)}function NM(e){hM(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,SM],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,CM]],{ignore:["link","linkReference"]})}function SM(e,n,s,a,r){let o="";if(!ob(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!EM(s)))return!1;const l=_M(s+a);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 CM(e,n,s,a){return!ob(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function EM(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 _M(e){const n=/[!"&'),.:;<>?\]}]+$/.exec(e);if(!n)return[e,void 0];e=e.slice(0,n.index);let s=n[0],a=s.indexOf(")");const r=Mh(e,"(");let o=Mh(e,")");for(;a!==-1&&r>o;)e+=s.slice(0,a+1),s=s.slice(a+1),a=s.indexOf(")"),o++;return[e,s]}function ob(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||ya(s)||Hl(s))&&(!n||s!==47)}lb.peek=LM;function MM(){this.buffer()}function AM(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function PM(){this.buffer()}function TM(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function RM(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=ui(this.sliceSerialize(e)).toLowerCase(),s.label=n}function IM(e){this.exit(e)}function $M(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=ui(this.sliceSerialize(e)).toLowerCase(),s.label=n}function DM(e){this.exit(e)}function LM(){return"["}function lb(e,n,s,a){const r=s.createTracker(a);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 OM(){return{enter:{gfmFootnoteCallString:MM,gfmFootnoteCall:AM,gfmFootnoteDefinitionLabelString:PM,gfmFootnoteDefinition:TM},exit:{gfmFootnoteCallString:RM,gfmFootnoteCall:IM,gfmFootnoteDefinitionLabelString:$M,gfmFootnoteDefinition:DM}}}function FM(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:lb},unsafe:[{character:"[",inConstruct:["label","phrasing","reference"]}]};function s(a,r,o,l){const c=o.createTracker(l);let d=c.move("[^");const u=o.enter("footnoteDefinition"),m=o.enter("label");return d+=c.move(o.safe(o.associationId(a),{before:d,after:"]"})),m(),d+=c.move("]:"),a.children&&a.children.length>0&&(c.shift(4),d+=c.move((n?`
|
|
667
|
-
`:" ")+o.indentLines(o.containerFlow(a,c.current()),n?cb:zM))),u(),d}}function zM(e,n,s){return n===0?e:cb(e,n,s)}function cb(e,n,s){return(s?"":" ")+e}const UM=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];db.peek=WM;function BM(){return{canContainEols:["delete"],enter:{strikethrough:qM},exit:{strikethrough:VM}}}function HM(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:UM}],handlers:{delete:db}}}function qM(e){this.enter({type:"delete",children:[]},e)}function VM(e){this.exit(e)}function db(e,n,s,a){const r=s.createTracker(a),o=s.enter("strikethrough");let l=r.move("~~");return l+=s.containerPhrasing(e,{...r.current(),before:l,after:"~"}),l+=r.move("~~"),o(),l}function WM(){return"~"}function KM(e){return e.length}function GM(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||KM,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const x=[],v=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const y=JM(e[m][b]);if(s.alignDelimiters!==!1){const S=r(y);v[b]=S,(d[b]===void 0||S>d[b])&&(d[b]=S)}x.push(y)}l[m]=x,c[m]=v}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=Ah(a[h]);else{const x=Ah(a);for(;++h<u;)o[h]=x}h=-1;const f=[],p=[];for(;++h<u;){const x=o[h];let v="",b="";x===99?(v=":",b=":"):x===108?v=":":x===114&&(b=":");let y=s.alignDelimiters===!1?1:Math.max(1,d[h]-v.length-b.length);const S=v+"-".repeat(y)+b;s.alignDelimiters!==!1&&(y=v.length+y+b.length,y>d[h]&&(d[h]=y),p[h]=y),f[h]=S}l.splice(1,0,f),c.splice(1,0,p),m=-1;const g=[];for(;++m<l.length;){const x=l[m],v=c[m];h=-1;const b=[];for(;++h<u;){const y=x[h]||"";let S="",N="";if(s.alignDelimiters!==!1){const E=d[h]-(v[h]||0),w=o[h];w===114?S=" ".repeat(E):w===99?E%2?(S=" ".repeat(E/2+.5),N=" ".repeat(E/2-.5)):(S=" ".repeat(E/2),N=S):N=" ".repeat(E)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&y==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(y),s.alignDelimiters!==!1&&b.push(N),s.padding!==!1&&b.push(" "),(s.delimiterEnd!==!1||h!==u-1)&&b.push("|")}g.push(s.delimiterEnd===!1?b.join("").replace(/ +$/,""):b.join(""))}return g.join(`
|
|
668
|
-
`)}function JM(e){return e==null?"":String(e)}function Ah(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 YM(e,n,s,a){const r=s.enter("blockquote"),o=s.createTracker(a);o.move("> "),o.shift(2);const l=s.indentLines(s.containerFlow(e,o.current()),QM);return r(),l}function QM(e,n,s){return">"+(s?"":" ")+e}function XM(e,n){return Ph(e,n.inConstruct,!0)&&!Ph(e,n.notInConstruct,!1)}function Ph(e,n,s){if(typeof n=="string"&&(n=[n]),!n||n.length===0)return s;let a=-1;for(;++a<n.length;)if(e.includes(n[a]))return!0;return!1}function Th(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
669
|
-
`&&XM(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
|
|
670
|
-
`}function ZM(e,n){const s=String(e);let a=s.indexOf(n),r=a,o=0,l=0;if(typeof n!="string")throw new TypeError("Expected substring");for(;a!==-1;)a===r?++o>l&&(l=o):o=1,r=a+n.length,a=s.indexOf(n,r);return l}function eA(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 tA(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 nA(e,n,s,a){const r=tA(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(eA(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,sA);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(ZM(o,r)+1,3)),u=s.enter("codeFenced");let m=c.move(d);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:`
|
|
671
|
-
`,encode:["`"],...c.current()})),h()}return m+=c.move(`
|
|
672
|
-
`),o&&(m+=c.move(o+`
|
|
673
|
-
`)),m+=c.move(d),u(),m}function sA(e,n,s){return(s?"":" ")+e}function Nu(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 iA(e,n,s,a){const r=Nu(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("definition");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("[");return u+=d.move(s.safe(s.associationId(e),{before:u,after:"]",...d.current()})),u+=d.move("]: "),c(),!e.url||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":`
|
|
674
|
-
`,...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),l(),u}function aA(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 so(e){return"&#x"+e.toString(16).toUpperCase()+";"}function kl(e,n,s){const a=ir(e),r=ir(n);return a===void 0?r===void 0?s==="_"?{inside:!0,outside:!0}:{inside:!1,outside:!1}:r===1?{inside:!0,outside:!0}:{inside:!1,outside:!0}:a===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}}ub.peek=rA;function ub(e,n,s,a){const r=aA(s),o=s.enter("emphasis"),l=s.createTracker(a),c=l.move(r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),m=kl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=so(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=kl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+so(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function rA(e,n,s){return s.options.emphasis||"*"}function oA(e,n){let s=!1;return ku(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,Id}),!!((!e.depth||e.depth<3)&&fu(e)&&(n.options.setext||s))}function lA(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(oA(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
|
|
675
|
-
`,after:`
|
|
676
|
-
`});return h(),m(),f+`
|
|
677
|
-
`+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
|
|
678
|
-
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
|
|
679
|
-
`,...o.current()});return/^[\t ]/.test(u)&&(u=so(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}mb.peek=cA;function mb(e){return e.value||""}function cA(){return"<"}hb.peek=dA;function hb(e,n,s,a){const r=Nu(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const d=s.createTracker(a);let u=d.move("![");return u+=d.move(s.safe(e.alt,{before:u,after:"]",...d.current()})),u+=d.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),u+=d.move("<"),u+=d.move(s.safe(e.url,{before:u,after:">",...d.current()})),u+=d.move(">")):(c=s.enter("destinationRaw"),u+=d.move(s.safe(e.url,{before:u,after:e.title?" ":")",...d.current()}))),c(),e.title&&(c=s.enter(`title${o}`),u+=d.move(" "+r),u+=d.move(s.safe(e.title,{before:u,after:r,...d.current()})),u+=d.move(r),c()),u+=d.move(")"),l(),u}function dA(){return"!"}pb.peek=uA;function pb(e,n,s,a){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("![");const u=s.safe(e.alt,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function uA(){return"!"}fb.peek=mA;function fb(e,n,s){let a=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(a);)r+="`";for(/[^ \r\n]/.test(a)&&(/^[ \r\n]/.test(a)&&/[ \r\n]$/.test(a)||/^`|`$/.test(a))&&(a=" "+a+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let d;if(l.atBreak)for(;d=c.exec(a);){let u=d.index;a.charCodeAt(u)===10&&a.charCodeAt(u-1)===13&&u--,a=a.slice(0,u)+" "+a.slice(d.index+1)}}return r+a+r}function mA(){return"`"}function gb(e,n){const s=fu(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))}bb.peek=hA;function bb(e,n,s,a){const r=Nu(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(gb(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"),d=s.enter("label");let u=l.move("[");return u+=l.move(s.containerPhrasing(e,{before:u,after:"](",...l.current()})),u+=l.move("]("),d(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(d=s.enter("destinationLiteral"),u+=l.move("<"),u+=l.move(s.safe(e.url,{before:u,after:">",...l.current()})),u+=l.move(">")):(d=s.enter("destinationRaw"),u+=l.move(s.safe(e.url,{before:u,after:e.title?" ":")",...l.current()}))),d(),e.title&&(d=s.enter(`title${o}`),u+=l.move(" "+r),u+=l.move(s.safe(e.title,{before:u,after:r,...l.current()})),u+=l.move(r),d()),u+=l.move(")"),c(),u}function hA(e,n,s){return gb(e,s)?"<":"["}xb.peek=pA;function xb(e,n,s,a){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(a);let d=c.move("[");const u=s.containerPhrasing(e,{before:d,after:"]",...c.current()});d+=c.move(u+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:d,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!u||u!==h?d+=c.move(h+"]"):r==="shortcut"?d=d.slice(0,-1):d+=c.move("]"),d}function pA(){return"["}function Su(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 fA(e){const n=Su(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 gA(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 vb(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 bA(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?gA(s):Su(s);const c=e.ordered?l==="."?")":".":fA(s);let d=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&&(d=!0),vb(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"){d=!0;break}}}}d&&(l=c),s.bulletCurrent=l;const u=s.containerFlow(e,a);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),u}function xA(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 vA(e,n,s,a){const r=xA(s);let o=s.bulletCurrent||Su(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(a);c.move(o+" ".repeat(l-o.length)),c.shift(l);const d=s.enter("listItem"),u=s.indentLines(s.containerFlow(e,c.current()),m);return d(),u;function m(h,f,p){return f?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function yA(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const wA=Wl(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function kA(e,n,s,a){return(e.children.some(function(l){return wA(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function jA(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}yb.peek=NA;function yb(e,n,s,a){const r=jA(s),o=s.enter("strong"),l=s.createTracker(a),c=l.move(r+r);let d=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const u=d.charCodeAt(0),m=kl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=so(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=kl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+so(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function NA(e,n,s){return s.options.strong||"*"}function SA(e,n,s,a){return s.safe(e.value,a)}function CA(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 EA(e,n,s){const a=(vb(s)+(s.options.ruleSpaces?" ":"")).repeat(CA(s));return s.options.ruleSpaces?a.slice(0,-1):a}const wb={blockquote:YM,break:Th,code:nA,definition:iA,emphasis:ub,hardBreak:Th,heading:lA,html:mb,image:hb,imageReference:pb,inlineCode:fb,link:bb,linkReference:xb,list:bA,listItem:vA,paragraph:yA,root:kA,strong:yb,text:SA,thematicBreak:EA};function _A(){return{enter:{table:MA,tableData:Rh,tableHeader:Rh,tableRow:PA},exit:{codeText:TA,table:AA,tableData:Rc,tableHeader:Rc,tableRow:Rc}}}function MA(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 AA(e){this.exit(e),this.data.inTable=void 0}function PA(e){this.enter({type:"tableRow",children:[]},e)}function Rc(e){this.exit(e)}function Rh(e){this.enter({type:"tableCell",children:[]},e)}function TA(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,RA));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function RA(e,n){return n==="|"?n:e}function IA(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
680
|
-
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:f,table:l,tableCell:d,tableRow:c}};function l(p,g,x,v){return u(m(p,x,v),p.align)}function c(p,g,x,v){const b=h(p,x,v),y=u([b]);return y.slice(0,y.indexOf(`
|
|
681
|
-
`))}function d(p,g,x,v){const b=x.enter("tableCell"),y=x.enter("phrasing"),S=x.containerPhrasing(p,{...v,before:o,after:o});return y(),b(),S}function u(p,g){return GM(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const v=p.children;let b=-1;const y=[],S=g.enter("table");for(;++b<v.length;)y[b]=h(v[b],g,x);return S(),y}function h(p,g,x){const v=p.children;let b=-1;const y=[],S=g.enter("tableRow");for(;++b<v.length;)y[b]=d(v[b],p,g,x);return S(),y}function f(p,g,x){let v=wb.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function $A(){return{exit:{taskListCheckValueChecked:Ih,taskListCheckValueUnchecked:Ih,paragraph:LA}}}function DA(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:OA}}}function Ih(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function LA(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 a=s.children[0];if(a&&a.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&&(a.value=a.value.slice(1),a.value.length===0?s.children.shift():s.position&&a.position&&typeof a.position.start.offset=="number"&&(a.position.start.column++,a.position.start.offset++,s.position.start=Object.assign({},a.position.start)))}}this.exit(e)}function OA(e,n,s,a){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(a);o&&c.move(l);let d=wb.listItem(e,n,s,{...a,...c.current()});return o&&(d=d.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,u)),d;function u(m){return m+l}}function FA(){return[bM(),OM(),BM(),_A(),$A()]}function zA(e){return{extensions:[xM(),FM(e),HM(),IA(e),DA()]}}const UA={tokenize:KA,partial:!0},kb={tokenize:GA,partial:!0},jb={tokenize:JA,partial:!0},Nb={tokenize:YA,partial:!0},BA={tokenize:QA,partial:!0},Sb={name:"wwwAutolink",tokenize:VA,previous:Eb},Cb={name:"protocolAutolink",tokenize:WA,previous:_b},Bi={name:"emailAutolink",tokenize:qA,previous:Mb},Ri={};function HA(){return{text:Ri}}let ma=48;for(;ma<123;)Ri[ma]=Bi,ma++,ma===58?ma=65:ma===91&&(ma=97);Ri[43]=Bi;Ri[45]=Bi;Ri[46]=Bi;Ri[95]=Bi;Ri[72]=[Bi,Cb];Ri[104]=[Bi,Cb];Ri[87]=[Bi,Sb];Ri[119]=[Bi,Sb];function qA(e,n,s){const a=this;let r,o;return l;function l(h){return!Od(h)||!Mb.call(a,a.previous)||Cu(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Od(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(BA,m,u)(h):h===45||h===95||As(h)?(o=!0,e.consume(h),d):m(h)}function u(h){return e.consume(h),r=!0,d}function m(h){return o&&r&&Is(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function VA(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!Eb.call(a,a.previous)||Cu(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(UA,e.attempt(kb,e.attempt(jb,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function WA(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&_b.call(a,a.previous)&&!Cu(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Is(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const f=r.toLowerCase();if(f==="http"||f==="https")return e.consume(h),d}return s(h)}function d(h){return h===47?(e.consume(h),o?u:(o=!0,d)):s(h)}function u(h){return h===null||vl(h)||Bn(h)||ya(h)||Hl(h)?s(h):e.attempt(kb,e.attempt(jb,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function KA(e,n,s){let a=0;return r;function r(l){return(l===87||l===119)&&a<3?(a++,e.consume(l),r):l===46&&a===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function GA(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(Nb,d,c)(u):u===null||Bn(u)||ya(u)||u!==45&&Hl(u)?d(u):(o=!0,e.consume(u),l)}function c(u){return u===95?a=!0:(r=a,a=void 0),e.consume(u),l}function d(u){return r||a||!o?s(u):n(u)}}function JA(e,n){let s=0,a=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&a<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(Nb,n,o)(l):l===null||Bn(l)||ya(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function YA(e,n,s){return a;function a(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),a):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||Bn(c)||ya(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Bn(c)||ya(c)?n(c):a(c)}function o(c){return Is(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):Is(c)?(e.consume(c),l):s(c)}}function QA(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return As(o)?s(o):n(o)}}function Eb(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Bn(e)}function _b(e){return!Is(e)}function Mb(e){return!(e===47||Od(e))}function Od(e){return e===43||e===45||e===46||e===95||As(e)}function Cu(e){let n=e.length,s=!1;for(;n--;){const a=e[n][1];if((a.type==="labelLink"||a.type==="labelImage")&&!a._balanced){s=!0;break}if(a._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const XA={tokenize:rP,partial:!0};function ZA(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:sP,continuation:{tokenize:iP},exit:aP}},text:{91:{name:"gfmFootnoteCall",tokenize:nP},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:eP,resolveTo:tP}}}}function eP(e,n,s){const a=this;let r=a.events.length;const o=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let l;for(;r--;){const d=a.events[r][1];if(d.type==="labelImage"){l=d;break}if(d.type==="gfmFootnoteCall"||d.type==="labelLink"||d.type==="label"||d.type==="image"||d.type==="link")break}return c;function c(d){if(!l||!l._balanced)return s(d);const u=ui(a.sliceSerialize({start:l.end,end:a.now()}));return u.codePointAt(0)!==94||!o.includes(u.slice(1))?s(d):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(d),e.exit("gfmFootnoteCallLabelMarker"),n(d))}}function tP(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 a={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",a,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",a,n]];return e.splice(s,e.length-s+1,...c),e}function nP(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),d}function d(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",u)}function u(h){if(o>999||h===93&&!l||h===null||h===91||Bn(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(ui(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Bn(h)||(l=!0),o++,e.consume(h),h===92?m:u}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,u):u(h)}}function sP(e,n,s){const a=this,r=a.parser.gfmFootnotes||(a.parser.gfmFootnotes=[]);let o,l=0,c;return d;function d(g){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),u}function u(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||Bn(g))return s(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=ui(a.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Bn(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),jn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function iP(e,n,s){return e.check(yo,n,e.attempt(XA,n,s))}function aP(e){e.exit("gfmFootnoteDefinition")}function rP(e,n,s){const a=this;return jn(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=a.events[a.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function oP(e){let s=(e||{}).singleTilde;const a={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:a},insideSpan:{null:[a]},attentionMarkers:{null:[126]}};function r(l,c){let d=-1;for(;++d<l.length;)if(l[d][0]==="enter"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._close){let u=d;for(;u--;)if(l[u][0]==="exit"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._open&&l[d][1].end.offset-l[d][1].start.offset===l[u][1].end.offset-l[u][1].start.offset){l[d][1].type="strikethroughSequence",l[u][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[u][1].start),end:Object.assign({},l[d][1].end)},h={type:"strikethroughText",start:Object.assign({},l[u][1].end),end:Object.assign({},l[d][1].start)},f=[["enter",m,c],["enter",l[u][1],c],["exit",l[u][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&Ks(f,f.length,0,ql(p,l.slice(u+1,d),c)),Ks(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),Ks(l,u-1,d-u+3,f),d=u+f.length-2;break}}for(d=-1;++d<l.length;)l[d][1].type==="strikethroughSequenceTemporary"&&(l[d][1].type="data");return l}function o(l,c,d){const u=this.previous,m=this.events;let h=0;return f;function f(g){return u===126&&m[m.length-1][1].type!=="characterEscape"?d(g):(l.enter("strikethroughSequenceTemporary"),p(g))}function p(g){const x=ir(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const v=l.exit("strikethroughSequenceTemporary"),b=ir(g);return v._open=!b||b===2&&!!x,v._close=!x||x===2&&!!b,c(g)}}}class lP{constructor(){this.map=[]}add(n,s,a){cP(this,n,s,a)}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 a=[];for(;s>0;)s-=1,a.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];a.push(n.slice()),n.length=0;let r=a.pop();for(;r;){for(const o of r)n.push(o);r=a.pop()}this.map.length=0}}function cP(e,n,s,a){let r=0;if(!(s===0&&a.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...a);return}r+=1}e.map.push([n,s,a])}}function dP(e,n){let s=!1;const a=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&a.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=a.length-1;a[o]=a[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return a}function uP(){return{flow:{null:{name:"table",tokenize:mP,resolveAll:hP}}}}function mP(e,n,s){const a=this;let r=0,o=0,l;return c;function c(C){let P=a.events.length-1;for(;P>-1;){const A=a.events[P][1].type;if(A==="lineEnding"||A==="linePrefix")P--;else break}const I=P>-1?a.events[P][1].type:null,H=I==="tableHead"||I==="tableRow"?w:d;return H===w&&a.parser.lazy[a.now().line]?s(C):H(C)}function d(C){return e.enter("tableHead"),e.enter("tableRow"),u(C)}function u(C){return C===124||(l=!0,o+=1),m(C)}function m(C){return C===null?s(C):Ht(C)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(C),e.exit("lineEnding"),p):s(C):pn(C)?jn(e,m,"whitespace")(C):(o+=1,l&&(l=!1,r+=1),C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(C)))}function h(C){return C===null||C===124||Bn(C)?(e.exit("data"),m(C)):(e.consume(C),C===92?f:h)}function f(C){return C===92||C===124?(e.consume(C),h):h(C)}function p(C){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(C):(e.enter("tableDelimiterRow"),l=!1,pn(C)?jn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(C):g(C))}function g(C){return C===45||C===58?v(C):C===124?(l=!0,e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),x):E(C)}function x(C){return pn(C)?jn(e,v,"whitespace")(C):v(C)}function v(C){return C===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),b):C===45?(o+=1,b(C)):C===null||Ht(C)?N(C):E(C)}function b(C){return C===45?(e.enter("tableDelimiterFiller"),y(C)):E(C)}function y(C){return C===45?(e.consume(C),y):C===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(C),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(C))}function S(C){return pn(C)?jn(e,N,"whitespace")(C):N(C)}function N(C){return C===124?g(C):C===null||Ht(C)?!l||r!==o?E(C):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(C)):E(C)}function E(C){return s(C)}function w(C){return e.enter("tableRow"),j(C)}function j(C){return C===124?(e.enter("tableCellDivider"),e.consume(C),e.exit("tableCellDivider"),j):C===null||Ht(C)?(e.exit("tableRow"),n(C)):pn(C)?jn(e,j,"whitespace")(C):(e.enter("data"),_(C))}function _(C){return C===null||C===124||Bn(C)?(e.exit("data"),j(C)):(e.consume(C),C===92?D:_)}function D(C){return C===92||C===124?(e.consume(C),_):_(C)}}function hP(e,n){let s=-1,a=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,d=0,u,m,h;const f=new lP;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&($h(f,n,d,u,m),m=void 0,d=0),u={type:"table",start:Object.assign({},g.start),end:Object.assign({},g.end)},f.add(s,0,[["enter",u,n]])):g.type==="tableRow"||g.type==="tableDelimiterRow"?(a=!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")?(a=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=To(f,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):g.type==="tableCellDivider"&&(a?a=!1:(o[1]!==0&&(l[0]=l[1],h=To(f,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):g.type==="tableHead"?(c=!0,d=s):g.type==="tableRow"||g.type==="tableDelimiterRow"?(d=s,o[1]!==0?(l[0]=l[1],h=To(f,n,o,r,s,h)):l[1]!==0&&(h=To(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&$h(f,n,d,u,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=dP(n.events,s))}return e}function To(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Va(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=Va(n.events,s[1]);if(o={type:l,start:Object.assign({},d),end:Object.assign({},d)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const u=Va(n.events,s[2]),m=Va(n.events,s[3]),h={type:c,start:Object.assign({},u),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),a!==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,x=s[3]-s[2]-1;e.add(g,x,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},Va(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function $h(e,n,s,a,r){const o=[],l=Va(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),a.end=Object.assign({},l),o.push(["exit",a,n]),e.add(s+1,0,o)}function Va(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const pP={name:"tasklistCheck",tokenize:gP};function fP(){return{text:{91:pP}}}function gP(e,n,s){const a=this;return r;function r(d){return a.previous!==null||!a._gfmTasklistFirstContentOfListItem?s(d):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),o)}function o(d){return Bn(d)?(e.enter("taskListCheckValueUnchecked"),e.consume(d),e.exit("taskListCheckValueUnchecked"),l):d===88||d===120?(e.enter("taskListCheckValueChecked"),e.consume(d),e.exit("taskListCheckValueChecked"),l):s(d)}function l(d){return d===93?(e.enter("taskListCheckMarker"),e.consume(d),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(d)}function c(d){return Ht(d)?n(d):pn(d)?e.check({tokenize:bP},n,s)(d):s(d)}}function bP(e,n,s){return jn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function xP(e){return zg([HA(),ZA(),oP(e),uP(),fP()])}const vP={};function Pi(e){const n=this,s=e||vP,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(xP(s)),o.push(FA()),l.push(zA(s))}const yP=45e3,wP=3e3,kP=2e3,jP=1500,Dh="fusion:sse-client-id";let Fa=null;const ea=new Map;function Lh(){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 Ab(){if(!(typeof window>"u")){if(Fa)return Fa;try{const e=window.sessionStorage.getItem(Dh);if(e)return Fa=e,e;const n=Lh();return window.sessionStorage.setItem(Dh,n),Fa=n,n}catch{return Fa=Lh(),Fa}}}function Pb(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Tb(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function NP(e){const n=Ab();if(!n)return e;const s=Pb(e);return!s||!Tb(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Eu(e,n){const s=Ab();if(!s)return;const a=Pb(e);if(!a||!Tb(a.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=a.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),_i(`${r.pathname}${r.search}${r.hash}`)}function SP(e){if(typeof window>"u")return;const n=Eu(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 Gl(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Oh(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=Eu(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),jP):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function CP(e){Gl(e),Eu(e.url,"keepalive")&&(Oh(e),e.keepaliveTimer=window.setInterval(()=>{Oh(e)},kP))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ea.values()))if(!s.closed){if(Gl(s),SP(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const a of Array.from(ea.values()))a.subscribers.size!==0&&(a.closed=!1,_u(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function zr(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Rb(e)},yP)}function Rb(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Gl(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=ea.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=ea.get(e.url);s&&s===e&&e.subscribers.size>0&&_u(e)},wP)}}function _u(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(_i(NP(e.url)));e.es=n,CP(e),n.addEventListener("open",()=>{zr(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const a of e.subscribers)a.onOpen?.(),s&&a.onReconnect?.()}),n.addEventListener("error",s=>{for(const a of e.subscribers)a.onError?.(s);Rb(e)}),n.addEventListener("message",()=>zr(e)),n.addEventListener("heartbeat",()=>zr(e)),Ib(e),zr(e)}function Ib(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const a of s.events.keys())n.add(a);for(const s of n){if(e.nativeListeners.has(s))continue;const a=r=>{zr(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const d of c)d(o)}};e.nativeListeners.set(s,a),e.es.addEventListener(s,a)}}function EP(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Gl(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ea.delete(e.url)}function ai(e,n={}){let s=ea.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ea.set(e,s));const a={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 d=a.events.get(l);d||(d=new Set,a.events.set(l,d)),d.add(c)}s.subscribers.add(a);const r=!!s.es&&s.hasOpenedOnce;_u(s),Ib(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=ea.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&EP(l))}}const Fh=100;function $b(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState(!1),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(!1),p=i.useRef(null),g=i.useRef(!1),x=i.useRef(0),v=i.useRef(e),b=i.useRef(s),y=i.useRef(n),S=i.useRef(0);(v.current!==e||b.current!==s||y.current!==n)&&(v.current=e,b.current=s,y.current=n,x.current++,g.current=!0,r([]),l(!1),d(!1),m(null),f(!1),p.current&&(p.current(),p.current=null)),i.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const j=x.current,_=++S.current;g.current=!1;const D=e,C=s;async function P(){if(!D)return;l(!0),f(!1);try{const H=await Hu(D,C,{limit:Fh});if(g.current||x.current!==j||S.current!==_)return;r(H.entries),d(H.hasMore),m(H.total)}catch{if(g.current||x.current!==j||S.current!==_)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===j&&S.current===_&&l(!1)}const I=C?`?projectId=${encodeURIComponent(C)}`:"";p.current=ai(`/api/tasks/${D}/logs/stream${I}`,{events:{"agent:log":H=>{if(!(g.current||x.current!==j))try{const A=JSON.parse(H.data);r($=>[...$,A]),m($=>$!==null?$+1:null)}catch{}}}})}return P(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const E=i.useCallback(async()=>{if(!e||h)return;const j=x.current,_=a.length,D=e;f(!0);try{const C=await Hu(D,s,{limit:Fh,offset:_});if(g.current||x.current!==j)return;r(P=>[...C.entries,...P]),d(C.hasMore),m(C.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),w=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:w,loadMore:E,hasMore:c,total:u,loadingMore:h}}const zh="fn-agent-log-markdown",Uh="fn-agent-log-tool-output";function Bh(e,n){if(typeof window>"u")return n;try{const s=window.localStorage.getItem(e);return s===null?n:s==="true"}catch{return n}}function Hh(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function _P(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/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 qh={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})},Db=50,MP={triage:"Plan"};function Vh(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=Db}function Fd(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function AP(e){const n=new Map;return e.map(s=>{const a=Fd(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function Lb(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function Ic({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
|
|
682
|
-
`).length,o=n?"Hide output":`Show output${r>1?` (${r} lines)`:""}`;return t.jsxs("div",{className:"agent-log-tool-detail-wrapper",children:[t.jsxs("button",{type:"button",className:"agent-log-tool-detail-toggle",onClick:()=>s(l=>!l),"aria-expanded":n,"aria-controls":a,"data-testid":"tool-detail-toggle",children:[n?t.jsx(cn,{size:14}):t.jsx(Un,{size:14}),t.jsx("span",{children:o})]}),t.jsx("div",{id:a,className:n?"agent-log-tool-detail-content":"agent-log-tool-detail-content agent-log-tool-detail-content--collapsed","data-testid":"tool-detail-content",children:t.jsx("pre",{className:"agent-log-tool-detail",children:e})})]})}function PP(e,n){return e.agent?Lb(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function TP(e,n){const s=[];for(let a=0;a<e.length;a+=1){const{entry:r,hiddenToolBoundaryId:o}=e[a],l=n[a]??`${Fd(r)}|fallback`,c=a>0?e[a-1]:void 0,d=c?.entry,u=PP(r,d)||c!==void 0&&c.hiddenToolBoundaryId!==o;if(r.type==="text"||r.type==="thinking"){const m=[r];let h=a+1;for(;h<e.length;){const p=e[h],g=p.entry;if(g.type!==r.type||g.agent!==r.agent||p.hiddenToolBoundaryId!==o)break;m.push(g),h+=1}const f=n[h-1]??`${Fd(e[h-1].entry)}|fallback`;s.push({kind:r.type,entries:m,key:`${l}->${f}`,showBadge:u}),a=h-1;continue}s.push({kind:"single",entry:r,key:l,showBadge:u})}return s}function RP({entries:e,loading:n,executorModel:s,validatorModel:a,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:d=null}){const u=i.useRef(null),m=i.useRef(0),h=i.useRef(0),f=i.useRef(null),p=i.useRef(null),[g,x]=i.useState(()=>Bh(zh,!0)),[v,b]=i.useState(()=>Bh(Uh,!0)),[y,S]=i.useState(!1),[N,E]=i.useState(!1),[w,j]=i.useState(!0);i.useEffect(()=>{Hh(zh,g)},[g]),i.useEffect(()=>{Hh(Uh,v)},[v]);const _=i.useMemo(()=>{if(v)return e.map(T=>({entry:T,hiddenToolBoundaryId:0}));const J=[];let M=0;for(const T of e){if(Lb(T.type)){M+=1;continue}J.push({entry:T,hiddenToolBoundaryId:M})}return J},[e,v]),D=i.useMemo(()=>_.map(J=>J.entry),[_]),C=i.useMemo(()=>AP(D),[D]),P=i.useMemo(()=>TP(_,C),[_,C]);i.useLayoutEffect(()=>{const J=u.current;if(!J)return;const M=e.length,T=m.current,L=h.current||J.scrollHeight,k=C[0]??null,K=C[C.length-1]??null,oe=f.current!==k,le=p.current!==K;if(M>T)if(T===0)J.scrollTop=J.scrollHeight;else{const we=L-(J.scrollTop+J.clientHeight)<=Db,ge=le&&!oe,Ue=oe&&!le;if(ge&&we&&(J.scrollTop=J.scrollHeight),Ue){const Z=J.scrollHeight-L;Z>0&&(J.scrollTop+=Z)}}m.current=M,h.current=J.scrollHeight,f.current=k,p.current=K,j(Vh(J))},[e,C]);const I=i.useCallback(()=>{const J=u.current;J&&j(Vh(J))},[]),H=i.useCallback(()=>{const J=u.current;J&&(J.scrollTop=J.scrollHeight,j(!0))},[]),A=i.useCallback(J=>{J.key==="Escape"&&y&&S(!1)},[y]);i.useEffect(()=>{if(y)return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A)}},[y,A]);const $=s?.provider&&s?.modelId,F=a?.provider&&a?.modelId,G=r?.provider&&r?.modelId,ee=i.useMemo(()=>{const J=[];return $&&J.push({role:"Executor",provider:s.provider,modelId:s.modelId}),F&&J.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),G&&J.push({role:"Planning",provider:r.provider,modelId:r.modelId}),J},[$,s,F,a,G,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${y?" 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:[ee.map(J=>t.jsx(Jn,{provider:J.provider,size:"sm"},`${J.role}-${J.provider}-${J.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>E(J=>!J),"aria-label":N?"Collapse model details":"Expand model details","aria-expanded":N,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:N?t.jsx(cn,{size:14}):t.jsx(Un,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(J=>!J),"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:()=>b(J=>!J),"aria-label":v?"Hide tool output":"Show tool output","aria-pressed":v,"data-testid":"agent-log-tool-output-toggle",title:v?"Hide tool calls and results":"Show tool calls and results",children:v?"Tools: On":"Tools: Off"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>S(J=>!J),"aria-label":y?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:y?"Exit full screen":"Expand agent log to full screen",children:y?t.jsx(uo,{size:14}):t.jsx(Dl,{size:14})})]}),N&&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.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Jn,{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:"}),F?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Jn,{provider:a.provider,size:"sm"}),t.jsxs("span",{children:[a.provider,"/",a.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning:"}),G?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Jn,{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:u,className:"agent-log-viewer-scroll",onScroll:I,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",D.length," of ",d," entries",!v&&e.length!==D.length?` (${e.length-D.length} tool entries hidden)`:""]}),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(xt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),P.map(J=>{const M=J.kind==="single"?J.entry:J.entries[0],T=J.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:_P(M.timestamp)}):null,L=J.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",MP[M.agent]??M.agent,"]"]}),T]}):null;if(J.kind==="single"){const{entry:K}=J;if(K.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[L,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",K.text]}),K.detail?t.jsx(Ic,{detail:K.detail,type:"tool"}):null]},J.key);if(K.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[L,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",K.text]}),K.detail?t.jsx(Ic,{detail:K.detail,type:"tool_result"}):null]},J.key);if(K.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[L,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",K.text]}),K.detail?t.jsx(Ic,{detail:K.detail,type:"tool_error"}):null]},J.key)}const k=J.kind==="single"?M.text:J.entries.map(K=>K.text).join("");return J.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[L,g?t.jsx("div",{className:"markdown-body",children:t.jsx(Ai,{remarkPlugins:[Pi],components:qh,children:k})}):t.jsx("pre",{className:"agent-log-plain-block",children:k})]},J.key):t.jsxs("div",{className:"agent-log-text",children:[L,g?t.jsx("div",{className:"markdown-body",children:t.jsx(Ai,{remarkPlugins:[Pi],components:qh,children:k})}):t.jsx("pre",{className:"agent-log-plain-block",children:k})]},J.key)}),!w&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:H,"data-testid":"agent-log-return-to-live",children:[t.jsx(cn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function ar(e){return e??void 0}function Ro(e){return{provider:ar(e.modelProvider),modelId:ar(e.modelId)}}function Io(e){return{provider:ar(e.validatorModelProvider),modelId:ar(e.validatorModelId)}}function $o(e){return{provider:ar(e.planningModelProvider),modelId:ar(e.planningModelId)}}function IP(e,n){return og(e,n)}function $P(e,n){return lg(e,n)}function DP(e,n){return cg(e,n)}function $c(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 Dc(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function Lc(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function LP(e,n){const a={executor:"Executor",validator:"Reviewer",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${a} model set to default`:`${a} model set to ${n.provider}/${n.modelId}`}function OP({task:e,addToast:n,onTaskUpdated:s,settings:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(()=>Ro(e)),[v,b]=i.useState(()=>Ro(e)),[y,S]=i.useState(()=>Io(e)),[N,E]=i.useState(()=>Io(e)),[w,j]=i.useState(()=>$o(e)),[_,D]=i.useState(()=>$o(e)),[C,P]=i.useState(()=>e.thinkingLevel??null),[I,H]=i.useState(()=>e.thinkingLevel??null),[A,$]=i.useState(null),F=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),$s().then(se=>{o(se.models),c(se.favoriteProviders),u(se.favoriteModels)}).catch(se=>{p(se.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const G=i.useCallback(async se=>{const B=l,ke=B.includes(se)?B.filter(ae=>ae!==se):[se,...B];c(ke);try{await $n({favoriteProviders:ke,favoriteModels:d})}catch{c(B),n("Failed to update favorites","error")}},[l,d,n]),ee=i.useCallback(async se=>{const B=d,ke=B.includes(se)?B.filter(ae=>ae!==se):[se,...B];u(ke);try{await $n({favoriteProviders:l,favoriteModels:ke})}catch{u(B),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{F.current=e.id;const se=Ro(e),B=Io(e),O=$o(e);x(se),b(se),S(B),E(B),j(O),D(O);const ke=e.thinkingLevel??null;P(ke),H(ke),$(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const J=i.useMemo(()=>Dc(g),[g]),M=i.useMemo(()=>Dc(y),[y]),T=i.useMemo(()=>Dc(w),[w]),L=i.useMemo(()=>IP(e,a),[e,a]),k=i.useMemo(()=>$P(e,a),[e,a]),K=i.useMemo(()=>DP(e,a),[e,a]),oe=A!==null,le=i.useCallback(async(se,B)=>{const O=e.id,ke=v,ae=N,te=_;$(se);try{const Ie=s?se==="executor"?{modelProvider:B.provider??null,modelId:B.modelId??null}:se==="validator"?{validatorModelProvider:B.provider??null,validatorModelId:B.modelId??null}:{planningModelProvider:B.provider??null,planningModelId:B.modelId??null}:{modelProvider:(se==="executor"?B:v).provider??null,modelId:(se==="executor"?B:v).modelId??null,validatorModelProvider:(se==="validator"?B:N).provider??null,validatorModelId:(se==="validator"?B:N).modelId??null,planningModelProvider:(se==="planning"?B:_).provider??null,planningModelId:(se==="planning"?B:_).modelId??null},Oe=await Ci(O,Ie);if(F.current!==O)return;const He=Ro(Oe),$e=Io(Oe),Te=$o(Oe);b(He),x(He),E($e),S($e),D(Te),j(Te),s?.(Oe),n(LP(se,{executor:He,validator:$e,planning:Te}[se]),"success")}catch(Ie){if(F.current!==O)return;se==="executor"?x(ke):se==="validator"?S(ae):j(te),n(Me(Ie)||"Failed to save model settings","error")}finally{F.current===O&&$(null)}},[e.id,v,N,_,n,s]),we=i.useCallback(se=>{const B=$c(se);x(B),!Lc(B,v)&&le("executor",B)},[v,le]),ge=i.useCallback(se=>{const B=$c(se);S(B),!Lc(B,N)&&le("validator",B)},[N,le]),Ue=i.useCallback(se=>{const B=$c(se);j(B),!Lc(B,_)&&le("planning",B)},[_,le]),Z=i.useCallback(async se=>{const B=e.id,O=I,ke=se===""?null:se;P(ke),$("thinking");try{const ae=await Ci(B,{thinkingLevel:ke});if(F.current!==B)return;const te=ae.thinkingLevel??null;H(te),P(te),s?.(ae);const Ie=a?.defaultThinkingLevel??"off";n(te===null?`Thinking level set to default (${Ie})`:`Thinking level set to ${te}`,"success")}catch(ae){if(F.current!==B)return;P(O),n(Me(ae)||"Failed to save thinking level","error")}finally{F.current===B&&$(null)}},[e.id,I,a,n,s]),Q=!v.provider&&!v.modelId,X=!N.provider&&!N.modelId,ie=!_.provider&&!_.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),$s().then(se=>{o(se.models),c(se.favoriteProviders),u(se.favoriteModels)}).catch(se=>p(se.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:Q?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",L.provider&&L.modelId?` (${L.provider}/${L.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Jn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(ks,{id:"executorModel",label:"Executor Model",value:J,onChange:we,models:r,disabled:oe,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:G,favoriteModels:d,onToggleModelFavorite:ee}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Reviewer Model"}),t.jsx("div",{className:"model-selector-current",children:X?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",k.provider&&k.modelId?` (${k.provider}/${k.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[N.provider&&t.jsx(Jn,{provider:N.provider,size:"sm"}),N.provider,"/",N.modelId]})}),t.jsx(ks,{id:"validatorModel",label:"Reviewer Model",value:M,onChange:ge,models:r,disabled:oe,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:G,favoriteModels:d,onToggleModelFavorite:ee}),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:ie?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",K.provider&&K.modelId?` (${K.provider}/${K.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[_.provider&&t.jsx(Jn,{provider:_.provider,size:"sm"}),_.provider,"/",_.modelId]})}),t.jsx(ks,{id:"planningModel",label:"Planning Model",value:T,onChange:Ue,models:r,disabled:oe,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:G,favoriteModels:d,onToggleModelFavorite:ee}),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:I===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",a?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:I})}),t.jsxs("select",{id:"thinkingLevel",value:C??"",onChange:se=>Z(se.target.value),disabled:oe,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",a?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:Q&&X&&ie&&I===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const FP={open:t.jsx(Al,{size:16}),closed:t.jsx(lo,{size:16}),merged:t.jsx(Rf,{size:16})};function zP({taskId:e,projectId:n,prInfo:s,automationStatus:a,autoMerge:r=!1,isManualPrFlow:o=!1,prAuthAvailable:l,onPrCreated:c,onPrUpdated:d,addToast:u}){const[m,h]=i.useState(!1),[f,p]=i.useState(""),[g,x]=i.useState(""),[v,b]=i.useState(!1),[y,S]=i.useState(!1),[N,E]=i.useState(null),w=i.useCallback(async()=>{if(f.trim()){b(!0);try{const C=await Kk(e,{title:f.trim(),body:g.trim()||void 0},n);c(C),h(!1),p(""),x(""),u(`Created PR #${C.number}`,"success")}catch(C){u(Me(C)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),j=i.useCallback(async()=>{if(s){S(!0);try{const C=await Gk(e,n);E(C),d(C.prInfo),u("PR status refreshed","success")}catch(C){u(Me(C)||"Failed to refresh PR","error")}finally{S(!1)}}},[e,s,n,d,u]);if(!s)return a==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Vs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Vs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):m?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Vs,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:f,onChange:C=>p(C.target.value),disabled:v,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:g,onChange:C=>x(C.target.value),disabled:v,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>h(!1),disabled:v,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:!f.trim()||v,children:v?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Vs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>h(!0),disabled:!l,title:l?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(_n,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),o&&t.jsx("div",{className:"pr-hint pr-hint--subtle",children:"Use the footer action to run PR-first completion for this task."}),!l&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const _=FP[s.status]??t.jsx(Al,{size:16}),D=N?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(Vs,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:_}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:j,disabled:y,title:"Refresh PR status",children:t.jsx(hs,{size:14,style:{verticalAlign:"middle",opacity:y?.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})]}),a==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),a==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:D.length>0?`Waiting for: ${D.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(Oi,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Af,{size:14}),"View on GitHub"]})]})]})]})}const Wh=2e3;function UP(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function BP(e){return e==="agent"||e==="system"}function HP({task:e,onTaskUpdated:n,addToast:s,currentAuthor:a="user",projectId:r}){const[o,l]=i.useState(""),[c,d]=i.useState(null),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState(null),x=i.useMemo(()=>[...e.comments||[]].sort((j,_)=>new Date(_.createdAt).getTime()-new Date(j.createdAt).getTime()),[e.comments]),v=o.length>Wh;async function b(){const j=o.trim();if(j){f(!0);try{const _=await fk(e.id,j,r);l(""),n?.(_),s("Comment added","success")}catch(_){s(Me(_)||"Failed to add comment","error")}finally{f(!1)}}}async function y(j){const _=u.trim();if(_){f(!0);try{const D=await dk(e.id,j,_,r);d(null),m(""),n?.(D),s("Comment updated","success")}catch(D){s(Me(D)||"Failed to update comment","error")}finally{f(!1)}}}async function S(j){g(j);try{const _=await uk(e.id,j,r);n?.(_),s("Comment deleted","success")}catch(_){s(Me(_)||"Failed to delete comment","error")}finally{g(null)}}function N(j){j.key==="Enter"&&(j.ctrlKey||j.metaKey)&&(j.preventDefault(),b())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),x.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:x.map(j=>{const _=j.author===a,D=c===j.id,C=BP(j.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:[C?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:j.author}),t.jsx("span",{className:"detail-log-timestamp",children:UP(j)})]}),_&&!D?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(j.id),m(j.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(j.id),disabled:p===j.id,children:p===j.id?"Deleting…":"Delete"})]}):null]}),D?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:P=>m(P.target.value),rows:3,className:"comments-textarea"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void y(j.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:j.text})]},j.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:j=>l(j.target.value),onKeyDown:N,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," / ",Wh]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function qP(e){return e?e.slice(0,7):"Unknown"}function VP({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:qP(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"}),e.prInfo?.url?t.jsxs("a",{className:"detail-source-link detail-log-outcome",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",n.prNumber]}):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 Ob(e){return e.split(`
|
|
683
|
-
`).map((s,a)=>{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}
|
|
684
|
-
`},a):t.jsx(ol.Fragment,{children:`${s}
|
|
685
|
-
`},a)})}function WP(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function KP({isOpen:e,taskId:n,files:s,stats:a,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[d,u]=i.useState(null),[m,h]=i.useState(!0),f=i.useRef(null);Ti(f,e,"fusion:changes-diff-modal-size");const p=Ui(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(y=>y!==null&&y>0?y-1:y)},[]),x=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),g()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),x())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,x]),!e)return null;const v=d!==null?s[d]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(ci,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",a.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",a.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:d===null||d<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(Ml,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:d!==null?`${d+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:x,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(Un,{})})]}),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(cl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(hs,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(co,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,S)=>t.jsxs("button",{className:`changes-diff-file-item ${d===S?"selected":""}`,onClick:()=>u(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:WP(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:Ob(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(ci,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function Fb(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Oc(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(co,{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(ci,{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(a=>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:Fb("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function GP({taskId:e,worktree:n,projectId:s,column:a,mergeDetails:r,modifiedFiles:o}){const[l,c]=i.useState([]),[d,u]=i.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(new Set),[v,b]=i.useState(null),[y,S]=i.useState(!0),[N,E]=i.useState(!1),w=a==="done",j=w&&!!r?.commitSha,_=a==="in-progress"||a==="in-review"||j,D=i.useCallback(async()=>{if(!_){h(!1);return}try{h(!0),p(null);const A=await Jf(e,void 0,s),$=A.files.map(F=>({path:F.path,status:F.status,additions:F.additions,deletions:F.deletions,patch:F.patch}));c($),u(A.stats),$.length>0&&(x(new Set([$[0].path])),b(0))}catch(A){p(Me(A)||"Failed to load diff")}finally{h(!1)}},[e,s,_]);i.useEffect(()=>{D()},[D]);const C=A=>{x($=>{const F=new Set($);if(F.has(A))F.delete(A);else{F.add(A);const G=l.findIndex(ee=>ee.path===A);G!==-1&&b(G)}return F})},P=A=>{if(A<0||A>=l.length)return;const $=l[A].path;x(new Set([$])),b(A)},I=v!==null&&v>0,H=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(!w&&!n)return o&&o.length>0?Oc(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ci,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(w&&!j){if(o&&o.length>0)return Oc(o,!0,r);const A=r?.filesChanged,$=r?.insertions,F=r?.deletions,G=A!=null||$!=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(ci,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:G?`Merge summary: ${A??0} file${(A??0)===1?"":"s"} changed, +${$??0} additions, -${F??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?o&&o.length>0?Oc(o,w,r):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(ci,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:w?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[w&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(co,{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(ci,{size:16}),"Files Changed (",d.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",d.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",d.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:()=>I&&P(v-1),disabled:!I,title:"Previous file","aria-label":"Previous file",children:t.jsx(Ml,{})}),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:()=>H&&P(v+1),disabled:!H,title:"Next file","aria-label":"Next file",children:t.jsx(Un,{})})]}),t.jsx("button",{className:`btn btn-sm ${y?"btn-primary":""}`,onClick:()=>S(A=>!A),title:y?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(cl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:D,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>E(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(Dl,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(A=>{const $=g.has(A.path);return t.jsxs("div",{className:`changes-file-item ${$?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>C(A.path),children:[t.jsx("span",{className:"changes-file-toggle",children:$?t.jsx(cn,{size:14}):t.jsx(Un,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${A.status}`,title:A.status,children:Fb(A.status)}),t.jsx("span",{className:"changes-file-path",title:A.path,children:t.jsx("bdo",{dir:"ltr",children:A.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${A.additions} -${A.deletions}`,children:["+",A.additions," -",A.deletions]})]}),$&&A.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:Ob(A.patch)})})})]},A.path)})}),t.jsx(KP,{isOpen:N,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>E(!1),onRefresh:D})]})}function Kh(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function JP(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function hz(e,n){const s=JP(e),a=new Set(n.map(c=>c.id));if(!a.has(s))return s;const r=30;let o=s,l=1;for(;a.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function YP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Gh=["image/png","image/jpeg","image/gif","image/webp"];function QP(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function zb({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,branch:c,onBranchChange:d,baseBranch:u,onBaseBranchChange:m,nodeId:h,onNodeIdChange:f,nodeOptions:p,nodeOverrideDisabled:g=!1,nodeOverrideDisabledReason:x,priority:v,onPriorityChange:b,executorModel:y,onExecutorModelChange:S,validatorModel:N,onValidatorModelChange:E,planningModel:w,onPlanningModelChange:j,thinkingLevel:_,onThinkingLevelChange:D,presetMode:C,onPresetModeChange:P,selectedPresetId:I,onSelectedPresetIdChange:H,selectedWorkflowSteps:A,onWorkflowStepsChange:$,onDefaultOnApplied:F,pendingImages:G,onImagesChange:ee,tasks:J,projectId:M,disabled:T=!1,addToast:L,isActive:k=!0,onAutoSaveDescription:K,onPlanningMode:oe,onSubtaskBreakdown:le,onClose:we,renderBelowPrimary:ge,renderBelowModelConfiguration:Ue,hideDependencies:Z,autoExpandMoreOptionsOnSelection:Q=!0,reviewLevel:X,onReviewLevelChange:ie,executionMode:se,onExecutionModeChange:B}){const O=(Z?!1:o.length>0)||G.length>0||A.length>0||C!=="default"||(v??Rs)!==Rs||y!==""||N!==""||(w||"")!==""||(_||"")!==""||X!==void 0||se==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!=="",[ke,ae]=i.useState(!1),[te,Ie]=i.useState(Q?O:!1),[Oe,He]=i.useState(""),[$e,Te]=i.useState([]),[ue,ce]=i.useState([]),[Ae,Ne]=i.useState([]),[ye,Ce]=i.useState(!1),[fe,Pe]=i.useState(null),[De,dt]=i.useState([]),[pt,lt]=i.useState("idle"),[vt,_e]=i.useState(!1),[Fe,bt]=i.useState(!1),[ht,Ee]=i.useState(!1),me=i.useRef(null),Re=i.useRef(null),be=i.useRef(null),Ke=i.useRef(null),pe=i.useRef(null),Xe=i.useRef(null),wt=i.useRef(null),gt=i.useRef(!1),Tt=i.useRef(O),Zt=i.useRef(n.trim()),Ot=i.useRef(n.trim());i.useEffect(()=>{k&&(Ce(!0),$s().then(z=>{Te(z.models),ce(z.favoriteProviders),Ne(z.favoriteModels)}).catch(()=>{}).finally(()=>Ce(!1)),Ol(M).then(z=>Pe(z)).catch(()=>Pe(null)),fo(M).then(z=>dt(z.filter(he=>he.enabled))).catch(()=>dt([])))},[k,M]);const Rt=fe?.modelPresets||[],en=Rt.find(z=>z.id===I),zt=(Z?!1:o.length>0)||G.length>0||A.length>0||C!=="default"||(v??Rs)!==Rs||y!==""||N!==""||(w||"")!==""||(_||"")!==""||X!==void 0||se==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!=="";i.useEffect(()=>{if(e!=="create"||!k||!fe?.autoSelectModelPreset)return;const z=(fe.defaultPresetBySize,void 0);if(z){const he=Kh(z);H(z.id),P("preset"),S(he.executorValue),E(he.validatorValue)}},[k,fe,Rt,e]);const Qt=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!k||Qt.current||De.length===0)return;const z=De.filter(st=>st.defaultOn);if(z.length===0)return;Qt.current=!0;const he=z.map(st=>st.id);$(he),F?.(he)},[e,k,De]),i.useEffect(()=>{k||(Qt.current=!1)},[k]),i.useEffect(()=>{if(!Q){Tt.current=zt;return}zt&&!Tt.current&&Ie(!0),Tt.current=zt},[zt,Q]),i.useEffect(()=>{te||(ae(!1),He(""))},[te]),i.useEffect(()=>{e!=="edit"||!k||Ke.current&&(Ke.current.focus(),Ke.current.select())},[e,k]),i.useEffect(()=>{if(!ke)return;const z=he=>{Re.current&&!Re.current.contains(he.target)&&ae(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[ke]),i.useEffect(()=>{(e!=="edit"||T)&&Ee(!1)},[e,T]),i.useEffect(()=>{if(e!=="edit"){lt("idle");return}const z=n.trim();Zt.current=z,Ot.current=z,lt("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!K||!k)return;const z=n.trim(),he=Zt.current;if(z===he||z===Ot.current){Xe.current&&(clearTimeout(Xe.current),Xe.current=null),gt.current||lt("idle");return}return Xe.current&&clearTimeout(Xe.current),Xe.current=setTimeout(async()=>{if(!gt.current){gt.current=!0,lt("saving");try{await K(z),Ot.current=z,lt("saved"),wt.current&&clearTimeout(wt.current),wt.current=setTimeout(()=>{lt("idle"),wt.current=null},2e3)}catch{lt("idle")}finally{gt.current=!1,Xe.current=null}}},1500),()=>{Xe.current&&(clearTimeout(Xe.current),Xe.current=null)}},[e,n,K,k]),i.useEffect(()=>()=>{Xe.current&&clearTimeout(Xe.current),wt.current&&clearTimeout(wt.current)},[]),i.useEffect(()=>{if(!vt)return;const z=he=>{me.current&&!me.current.contains(he.target)&&_e(!1)};return document.addEventListener("mousedown",z),()=>document.removeEventListener("mousedown",z)},[vt]);const xn=i.useCallback(z=>{const he=z.clipboardData?.items;if(he)for(let st=0;st<he.length;st++){const It=he[st];if(It.type.startsWith("image/")){const ve=It.getAsFile();if(ve&&Gh.includes(ve.type)){z.preventDefault(),ee([...G,{file:ve,previewUrl:URL.createObjectURL(ve)}]);return}}}},[G,ee]),Kt=i.useCallback(z=>{z.preventDefault();const he=z.dataTransfer.files;for(let st=0;st<he.length;st++){const It=he[st];if(Gh.includes(It.type)){ee([...G,{file:It,previewUrl:URL.createObjectURL(It)}]);return}}},[G,ee]),Ut=i.useCallback(z=>{const he=G[z];he&&URL.revokeObjectURL(he.previewUrl),ee(G.filter((st,It)=>It!==z))},[G,ee]),fn=i.useCallback(z=>{l(o.includes(z)?o.filter(he=>he!==z):[...o,z])},[o,l]),un=(z,he)=>z.length>he?z.slice(0,he)+"…":z,tn=i.useCallback(z=>{s(z.target.value);const he=z.target;he.style.height="auto",he.style.height=he.scrollHeight+"px"},[s]),Vt=i.useCallback(()=>{Ee(z=>!z)},[]),mn=i.useCallback(z=>{!ht||z.key!=="Escape"||(z.preventDefault(),z.stopPropagation(),Ee(!1))},[ht]),xe=i.useCallback(async z=>{const he=n.trim();if(!(!he||Fe)){bt(!0);try{const st=await Vf(he,z,M);s(st),_e(!1),L("Description refined with AI","success"),be.current&&(be.current.style.height="auto",be.current.style.height=be.current.scrollHeight+"px")}catch(st){const It=Wf(st);L(It,"error")}finally{bt(!1)}}},[n,Fe,L,s,M]),Le=i.useCallback(async z=>{const he=ue,It=he.includes(z)?he.filter(ve=>ve!==z):[z,...he];ce(It);try{await $n({favoriteProviders:It,favoriteModels:Ae})}catch{ce(he)}},[ue,Ae]),Ve=i.useCallback(async z=>{const he=Ae,It=he.includes(z)?he.filter(ve=>ve!==z):[z,...he];Ne(It);try{await $n({favoriteProviders:ue,favoriteModels:It})}catch{Ne(he)}},[Ae,ue]),at=i.useCallback(z=>{if(z<=0)return;const he=[...A];[he[z-1],he[z]]=[he[z],he[z-1]],$(he)},[A,$]),Ge=i.useCallback(z=>{if(z>=A.length-1)return;const he=[...A];[he[z],he[z+1]]=[he[z+1],he[z]],$(he)},[A,$]),Ft=i.useCallback(z=>{$(A.filter(he=>he!==z))},[A,$]),_t=new Map;for(const z of De)_t.set(z.id,{name:z.name,description:z.description});const qt=J.filter(z=>!o.includes(z.id)).sort((z,he)=>{const st=he.createdAt.localeCompare(z.createdAt);if(st!==0)return st;const It=parseInt(z.id.slice(z.id.lastIndexOf("-")+1),10)||0;return(parseInt(he.id.slice(he.id.lastIndexOf("-")+1),10)||0)-It}),St=Oe?qt.filter(z=>z.id.toLowerCase().includes(Oe.toLowerCase())||z.title&&z.title.toLowerCase().includes(Oe.toLowerCase())||z.description&&z.description.toLowerCase().includes(Oe.toLowerCase())):qt;return t.jsxs("div",{className:"task-form",onDrop:Kt,onDragOver:z=>z.preventDefault(),onPaste:xn,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:Ke,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:z=>r(z.target.value),disabled:T})]}),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${pt==="idle"?"":" is-visible"}`,"aria-live":"polite",children:pt==="saving"?"Saving...":pt==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${ht?" description--fullscreen":""}`,ref:me,onKeyDown:mn,children:[ht&&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:Vt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(uo,{size:14})})]}),t.jsx("textarea",{ref:be,autoFocus:e==="create",id:"task-form-description",value:n,onChange:tn,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:T||Fe}),(()=>{const z=!!n.trim()&&!T;return t.jsxs(t.Fragment,{children:[!ht&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${z?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Vt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(Dl,{size:14})}),z&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Fe?"refine-button--loading":""}`,onClick:()=>_e(he=>!he),disabled:Fe,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(bs,{size:12,style:{verticalAlign:"middle"}}),Fe?"Refining...":"Refine"]})]})})(),vt&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:z=>z.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>xe("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:()=>xe("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:()=>xe("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:()=>xe("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"&&(oe||le)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[oe&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const z=n.trim();if(!z){L("Enter a description first","error");return}we?.(),oe(z)},disabled:T||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),le&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const z=n.trim();if(!z){L("Enter a description first","error");return}we?.(),le(z)},disabled:T||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),ge,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>Ie(z=>!z),"aria-expanded":te,"aria-controls":"task-form-more-options",disabled:T,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),te?t.jsx(mi,{size:14}):t.jsx(cn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${te?"":" collapsed"}`,"aria-hidden":!te,hidden:!te,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),G.length>0&&t.jsx("div",{className:"inline-create-previews",children:G.map((z,he)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:z.previewUrl,alt:z.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Ut(he),disabled:T,title:"Remove image",children:"×"})]},z.previewUrl))}),t.jsx("input",{ref:pe,type:"file",accept:"image/*",onChange:z=>{const he=z.target.files?.[0];he&&(ee([...G,{file:he,previewUrl:URL.createObjectURL(he)}]),z.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>pe.current?.click(),disabled:T,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),f&&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:h??"",onChange:z=>f(z.target.value||void 0),disabled:T||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(z=>t.jsxs("option",{value:z.id,children:[z.name," (",YP(z.status),")"]},z.id))]}),(()=>{const z=(p??[]).find(he=>he.id===h);return z?t.jsx("div",{className:"task-form-node-status",children:t.jsx(xa,{status:z.status,showLabel:!0})}):null})(),t.jsx("small",{children:x??"Task override takes priority over project default node routing."})]}),!Z&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:Re,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ae(z=>!z),disabled:T,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ke&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Oe,onChange:z=>He(z.target.value),onClick:z=>z.stopPropagation()}),St.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):St.map(z=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(z.id)?" selected":""}`,onClick:()=>fn(z.id),onMouseDown:he=>he.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:z.id}),t.jsx("span",{className:"dep-dropdown-title",children:un(z.title||z.description||z.id,30)})]},z.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(z=>t.jsxs("span",{className:"dep-chip",children:[z,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>fn(z),disabled:T,children:"×"})]},z))})]})}),(d||m)&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch Settings"}),d&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-working-branch",className:"model-select-label",children:"Working branch"}),t.jsx("input",{id:"task-working-branch",className:"input",value:c||"",onChange:z=>d(z.target.value),placeholder:"e.g. feature/my-task",disabled:T})]}),m&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-base-branch",className:"model-select-label",children:"Merge target / base branch"}),t.jsx("input",{id:"task-base-branch",className:"input",value:u||"",onChange:z=>m(z.target.value),placeholder:"e.g. main",disabled:T})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),b&&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:v??Rs,onChange:z=>b(z.target.value),disabled:T,children:xo.map(z=>t.jsx("option",{value:z,children:z[0].toUpperCase()+z.slice(1)},z))})]}),B&&se!==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:se,onChange:z=>B(z.target.value),disabled:T,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),ye?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):$e.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:C==="preset"?I:C,onChange:z=>{const he=z.target.value;if(he==="default"){P("default"),H(""),S(""),E("");return}if(he==="custom"){P("custom"),H("");return}const st=Rt.find(ve=>ve.id===he),It=Kh(st);P("preset"),H(he),S(It.executorValue),E(It.validatorValue)},disabled:T,children:[t.jsx("option",{value:"default",children:"Use default"}),Rt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,Rt.map(z=>t.jsx("option",{value:z.id,children:z.name},z.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),C==="preset"&&en?t.jsxs("small",{children:["Using preset: ",en.name]}):null,C==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>P("custom"),disabled:T,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(ks,{id:"executor-model",label:"Executor Model",value:y,onChange:z=>{P("custom"),H(""),S(z)},models:$e,disabled:T||C==="preset",favoriteProviders:ue,onToggleFavorite:Le,favoriteModels:Ae,onToggleModelFavorite:Ve})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(ks,{id:"validator-model",label:"Reviewer Model",value:N,onChange:z=>{P("custom"),H(""),E(z)},models:$e,disabled:T||C==="preset",favoriteProviders:ue,onToggleFavorite:Le,favoriteModels:Ae,onToggleModelFavorite:Ve})]}),j&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(ks,{id:"planning-model",label:"Planning Model",value:w||"",onChange:z=>{P("custom"),H(""),j(z)},models:$e,disabled:T||C==="preset",favoriteProviders:ue,onToggleFavorite:Le,favoriteModels:Ae,onToggleModelFavorite:Ve})]}),D&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:_||"",onChange:z=>D(z.target.value),disabled:T||C==="preset",children:[t.jsxs("option",{value:"",children:["Default (",fe?.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"})]})]}),ie&&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:X??"",onChange:z=>ie(z.target.value===""?void 0:parseInt(z.target.value,10)),disabled:T,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"})]})]})]})]}),Ue,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:De.length>0&&De.map(z=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${z.id}`,children:[t.jsx("input",{type:"checkbox",checked:A.includes(z.id),onChange:he=>{$(he.target.checked?[...A,z.id]:A.filter(st=>st!==z.id))},disabled:T}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[z.name,QP(z.phase||"pre-merge",z.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:z.description})]})]},z.id))})]}),A.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),A.map((z,he)=>{const st=_t.get(z);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${z}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:he+1}),t.jsx("span",{className:"workflow-step-order-name",children:st?.name||z}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>at(he),disabled:T||he===0,"data-testid":`workflow-step-move-up-${z}`,title:"Move up",children:t.jsx(mi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ge(he),disabled:T||he===A.length-1,"data-testid":`workflow-step-move-down-${z}`,title:"Move down",children:t.jsx(cn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ft(z),disabled:T,"data-testid":`workflow-step-remove-${z}`,title:"Remove",children:t.jsx(nn,{})})]})]},z)})]})]})]})]})}const Jh={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 XP(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function ZP(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 eT(e){return e?new Date(e).toLocaleString():null}function tT(e){const n=e.split(`
|
|
686
|
-
`);return n.length<=1?e:`${n.length} lines`}function Do(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function nT({entries:e,startedAt:n,stepId:s}){const a=i.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return i.useEffect(()=>{const l=a.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:a,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 sT({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[m,h]=i.useState({}),[f,p]=i.useState(null),[g,x]=i.useState([]),[v,b]=i.useState(!1),y=n.some(k=>k.status==="pending"),{entries:S}=$b(e,!!l&&y,o);i.useEffect(()=>{let k=!1;return fo(o).then(K=>{k||x(K.filter(oe=>oe.enabled))}).catch(()=>{k||x([])}),()=>{k=!0}},[o]);const N=a??[],E=i.useMemo(()=>g.map(k=>({id:k.id,name:k.name,description:k.description,phase:k.phase||"pre-merge"})),[g]),w=i.useMemo(()=>new Map(E.map(k=>[k.id,k])),[E]),j=k=>{u(K=>({...K,[k]:!K[k]}))},_=k=>{h(K=>{const oe=K[k]??"markdown";return{...K,[k]:oe==="markdown"?"plain":"markdown"}})},D=k=>{p(k)},C=()=>{p(null)};i.useEffect(()=>{if(!f)return;const k=K=>{K.key==="Escape"&&C()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[f]);const P=i.useCallback((k,K)=>{if(c){if(K){if(N.includes(k)){c(N);return}c([...N,k]);return}c(N.filter(oe=>oe!==k))}},[c,N]),I=i.useCallback(k=>{if(!c||k<=0)return;const K=[...N];[K[k-1],K[k]]=[K[k],K[k-1]],c(K)},[c,N]),H=i.useCallback(k=>{if(!c||k>=N.length-1)return;const K=[...N];[K[k],K[k+1]]=[K[k+1],K[k]],c(K)},[c,N]),A=i.useCallback(k=>{c&&c(N.filter(K=>K!==k))},[c,N]),$=n.length>0,F=N.length>0;i.useEffect(()=>{r||b(!1)},[r]);const G=i.useMemo(()=>N.map(k=>{const K=w.get(k);return{id:k,name:K?.name||k,description:K?.description||"Step definition not found.",phase:K?.phase||"pre-merge"}}),[N,w]),ee=()=>!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:E.map(k=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${k.id}`,children:[t.jsx("input",{type:"checkbox",checked:N.includes(k.id),onChange:K=>P(k.id,K.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,Do(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),N.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:"}),N.map((k,K)=>{const oe=w.get(k);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${k}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:K+1}),t.jsx("span",{className:"workflow-step-order-name",children:oe?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>I(K),disabled:K===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(mi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>H(K),disabled:K===N.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(cn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(k),"data-testid":`workflow-step-remove-${k}`,title:"Remove",children:t.jsx(nn,{})})]})]},k)})]})]}),J=()=>{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(!$)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const k=n.filter(ge=>ge.status==="passed").length,K=n.filter(ge=>ge.status==="failed").length,oe=n.filter(ge=>ge.status==="skipped").length,le=n.filter(ge=>ge.status==="pending").length,we=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&we.push(`${k} passed`),K>0&&we.push(`${K} failed`),oe>0&&we.push(`${oe} skipped`),le>0&&we.push(`${le} 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:we.join(" · ")}),n.map((ge,Ue)=>{const Z=ge.phase||"pre-merge",Q=d[ge.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ge.status}`,"data-testid":`workflow-result-item-${ge.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ge.workflowStepName,Do(Z,ge.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ge.status}`,"data-testid":`workflow-result-badge-${ge.workflowStepId}`,children:XP(ge.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ge.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",eT(ge.startedAt)]}),ge.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:ZP(ge.startedAt,ge.completedAt)})]}),ge.status==="pending"&&ge.startedAt?t.jsx(nT,{entries:S,startedAt:ge.startedAt,stepId:ge.workflowStepId}):ge.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",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>j(ge.workflowStepId),"data-testid":`workflow-result-toggle-${ge.workflowStepId}`,children:Q?"Hide output":"Show output"}),!Q&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ge.workflowStepId}`,children:tT(ge.output)}),Q&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>_(ge.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ge.workflowStepId}`,title:(m[ge.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ge.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>D(ge.workflowStepId),"data-testid":`workflow-result-expand-${ge.workflowStepId}`,title:"Expand output",children:t.jsx(Dl,{size:12})})]})]}),Q&&t.jsx("div",{className:`workflow-result-output${(m[ge.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ge.workflowStepId}`,children:(m[ge.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Ai,{remarkPlugins:[Pi],components:Jh,children:ge.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:ge.output})})]}):null]},`${ge.workflowStepId}-${Ue}`)})]})},M=r?t.jsx("button",{type:"button",className:"modal-edit-btn workflow-results-edit-toggle",onClick:()=>b(k=>!k),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(os,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Ss,{size:14}),"Edit"]})}):null,T=!s&&!$&&F,L=r&&$;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[T?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:[G.length," step",G.length===1?"":"s"]})]}),M]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:G.map(k=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${k.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[k.name,Do(k.phase,k.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:k.description})]},k.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),ee()]}):t.jsxs(t.Fragment,{children:[L&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),M]}),J(),ee()]}),f&&(()=>{const k=n.find(le=>le.workflowStepId===f);if(!k)return null;const K=m[k.workflowStepId]??"markdown",oe=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:le=>{le.target===le.currentTarget&&C()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:k.workflowStepName}),Do(oe,k.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>_(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:K==="markdown"?"Switch to plain text":"Switch to markdown",children:K==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:C,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(nn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${K==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:K==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Ai,{remarkPlugins:[Pi],components:Jh,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:k.output})})})]})})})()]})}function iT(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const aT=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function rT(e){return e!==void 0&&e!=="online"}function oT({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,h]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),pl().then(C=>{o(C)}).catch(C=>{u(Me(C)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(C=>[C.id,C])),[r]),v=i.useMemo(()=>[...r].sort((C,P)=>C.name.localeCompare(P.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",N=y?x.get(y):void 0,E=N?`${N.name} (${N.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",w=e.column==="in-progress"||aT.has(e.status),j=w||f||l,_=i.useCallback(async C=>{if(C===m)return;const P=e.id,I=m;h(C),p(!0);try{const H=await Ci(P,{nodeId:C||null});if(g.current!==P)return;h(H.nodeId??""),a?.(H),s(C?"Node override updated":"Node override cleared","success")}catch(H){if(g.current!==P)return;h(I),s(Me(H)||"Failed to update node override","error")}finally{g.current===P&&p(!1)}},[s,a,m,e.id]),D=i.useCallback(()=>{_("")},[_]);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:[N?t.jsx(xa,{status:N.status,compact:!0}):null,E,rT(N?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:iT(b?.unavailableNodePolicy)})]})]}),w&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),w?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:j,onChange:C=>{_(C.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(C=>t.jsxs("option",{value:C.id,title:`Status: ${C.status}`,children:[C.name," (",C.type,") — ",C.status]},C.id))]}),d?t.jsx("div",{className:"routing-tab__error",children:d}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",x.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:w||f,onClick:D,children:"Clear override"})]}):null]})]})}const lT=/^[a-zA-Z0-9_-]{1,64}$/,cT=200;function Yh(e){return e?new Date(e).toLocaleString():""}function dT(e,n=cT){return e.length<=n?e:e.substring(0,n)+"…"}function uT({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(""),[p,g]=i.useState(null),[x,v]=i.useState(""),[b,y]=i.useState(null),[S,N]=i.useState([]),[E,w]=i.useState(!1),[j,_]=i.useState(!1),[D,C]=i.useState(""),[P,I]=i.useState(""),[H,A]=i.useState(!1),[$,F]=i.useState(null),[G,ee]=i.useState(null),[J,M]=i.useState(!1),T=i.useCallback(async()=>{try{const Z=await mk(e,a);l(Z)}catch(Z){n(Me(Z)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{T()},[T]);async function L(Z){u===Z.key?(m(null),f(""),g(null),v(""),y(null),N([]),M(!1)):(m(Z.key),f(Z.content),g(null),v(""),y(null),N([]),M(!1))}async function k(Z){if(b===Z)y(null),N([]);else{y(Z),w(!0);try{const Q=await hk(e,Z,a);N(Q)}catch(Q){n(Me(Q)||"Failed to load revisions","error")}finally{w(!1)}}}function K(){u&&(g(u),v(h))}function oe(){g(null),v("")}async function le(){if(!(!p||!x.trim())){A(!0);try{await qu(e,p,x,{},a),g(null),v(""),await T();const Z=o.find(Q=>Q.key===p);Z&&f(Z.content),n("Document saved","success")}catch(Z){n(Me(Z)||"Failed to save document","error")}finally{A(!1)}}}async function we(){const Z=D.trim(),Q=P.trim();if(!Z){n("Document key is required","error");return}if(!lT.test(Z)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!Q){n("Content is required","error");return}A(!0);try{await qu(e,Z,Q,{},a),_(!1),C(""),I(""),await T(),n("Document created","success")}catch(X){n(Me(X)||"Failed to create document","error")}finally{A(!1)}}async function ge(Z){F(Z);try{await pk(e,Z,a),ee(null),F(null),u===Z&&(m(null),f("")),b===Z&&(y(null),N([])),await T(),n("Document deleted","success")}catch(Q){n(Me(Q)||"Failed to delete document","error")}finally{F(null)}}function Ue(Z){f(Z.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"}),j&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:D,onChange:Z=>C(Z.target.value),placeholder:"e.g., plan, notes, research",disabled:H}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:P,onChange:Z=>I(Z.target.value),rows:6,placeholder:"Enter document content…",disabled:H})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{_(!1),C(""),I("")},disabled:H,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void we(),disabled:H||!D.trim()||!P.trim(),children:H?"Creating…":"Create"})]})]}),o.length===0&&!j?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(Z=>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(na,{size:14}),t.jsx("span",{className:"task-document-key",children:Z.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",Z.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:Z.author}),t.jsx("span",{className:"task-document-timestamp",children:Yh(Z.updatedAt||Z.createdAt)})]})]}),u===Z.key&&p!==Z.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:()=>M(Q=>!Q),"aria-label":J?"Switch to plain text":"Switch to markdown","aria-pressed":J,title:J?"Switch to plain text":"Switch to markdown",children:J?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:J?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(Ai,{remarkPlugins:[Pi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===Z.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),E?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(Q=>Q.revision<Z.revision).sort((Q,X)=>X.revision-Q.revision).map(Q=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Ue(Q),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",Q.revision]}),t.jsx("span",{className:"revision-author",children:Q.author}),t.jsx("span",{className:"revision-timestamp",children:Yh(Q.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:dT(Q.content,100)})]},Q.id))})]})]}),p===Z.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:Q=>v(Q.target.value),rows:10,disabled:H}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:oe,disabled:H,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void le(),disabled:H||!x.trim(),children:H?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void L(Z),children:u===Z.key?t.jsxs(t.Fragment,{children:[t.jsx(mi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(cn,{size:14})," Expand"]})}),u===Z.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(Z.key),children:[t.jsx(Qr,{size:14})," History"]}),r&&p!==Z.key&&t.jsx("button",{className:"btn btn-sm",onClick:K,children:"Edit"}),r&&(G===Z.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 ge(Z.key),disabled:$===Z.key,children:$===Z.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>ee(null),disabled:$===Z.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>ee(Z.key),children:t.jsx(En,{size:14})}))]})]})]},Z.key))}),r&&!j&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>_(!0),children:[t.jsx(_n,{size:14})," New Document"]})]})}function Lo(e){return e.toLocaleString()}function Fc(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function _r(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),a=Math.round(n%60);return`${s}m ${a}s`}function mT(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 d=new Date(o.completedAt).getTime();if(Number.isNaN(d)||d<l)return null;c=d}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),a=vg(e,n)??0,r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:a,longestStep:r}}function hT({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=bg(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,x)=>g+(x.durationMs??0),0),c=xg(s?.log)??0,d=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(l,c),u=o.reduce((g,x)=>!g||(x.durationMs??0)>(g.durationMs??0)?x:g,void 0),m=mT(s?.workflowStepResults??[]),f=yg(s?.executionStartedAt,s?.executionCompletedAt,a)??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:d+m.totalDurationMs),p=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:r.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:_r(d)})]}),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:m.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:_r(m.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:_r(f)})]})]}),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:u?.durationMs?`${u.summary} (${_r(u.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:m.longestStep?`${m.longestStep.name} (${_r(m.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:p>0?`${Math.min((s?.currentStep??0)+1,p)} / ${p}`:"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 ${Fc(s.nextRecoveryAt)}`:"No scheduled recovery"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Self-heal counters"}),t.jsx("dd",{children:`stuck kills: ${s?.stuckKillCount??0}, post-review fixes: ${s?.postReviewFixCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime links"}),t.jsx("dd",{children:[s?.assignedAgentId?`agent ${s.assignedAgentId}`:null,s?.checkedOutBy?`checkout ${s.checkedOutBy}`:null,s?.blockedBy?`blocked by ${s.blockedBy}`:null,s?.sessionFile?"has session":null].filter(Boolean).join(", ")||"No runtime links"})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Token Usage"}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Lo(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Lo(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Lo(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),t.jsx("span",{className:"task-token-stats-panel__value",children:Lo(e.totalTokens)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"First used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:Fc(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:Fc(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const pT=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function fT(e,n){return og(e,n)}function gT(e,n){return lg(e,n)}function bT(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const a=s.text.match(/^Triage using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function xT(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=bT(n);return a||cg(e,s)}function vT(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--todo)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function yT(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/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 wT(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function kT(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(a=>typeof a=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Qh(e,n){return e.length>n?e.slice(0,n)+"…":e}function Xh(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function zc(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Uc(e){return e.trim()}function jT(e){const n=e.trim();return n.length>0?n:void 0}function $i(e){return typeof e=="string"&&xo.includes(e)?e:Rs}function Mr(e){return e==="fast"?"fast":"standard"}function NT(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function ST(e){const n=e?.findingLabel;if(typeof n=="string"&&n.length>0)return n;const s=e?.runId;return typeof s=="string"&&s.length>0?s:void 0}const CT=i.lazy(()=>Rn(()=>import("./AgentDetailView-C1XceMgi.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function ET(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:NT(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:ST(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const Bc=200,_T=new Set(["triage","todo"]);function Ub({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:m,addToast:h,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:x=!1,onRequestClose:v}){const[b,y]=i.useState(p),[S,N]=i.useState(()=>"prompt"in e?e:null),[E,w]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){N(e),w(!1);return}let ne=!1;return w(!0),N(null),er(e.id,n).then(ze=>{ne||(N(ze),w(!1))}).catch(()=>{ne||w(!1)}),()=>{ne=!0}},[e.id,n]);const j=S?{...S,...e,prompt:S.prompt,log:S.log}:{...e,prompt:""},_=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[D,C]=i.useState(null),[P,I]=i.useState(null),H=ET(j,{sourceAgentName:D?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{G(!1)},[e.id]);const[A,$]=i.useState("activity"),[F,G]=i.useState(!1),[ee,J]=i.useState(e.attachments||[]),[M,T]=i.useState(!1),[L,k]=i.useState(e.dependencies||[]),[K,oe]=i.useState(!1),[le,we]=i.useState(""),[ge,Ue]=i.useState(null),[Z,Q]=i.useState([]),[X,ie]=i.useState(!1),[se,B]=i.useState(!1),[O,ke]=i.useState(!1),[ae,te]=i.useState(!1),[Ie,Oe]=i.useState(!1),[He,$e]=i.useState(j.prompt||""),[Te,ue]=i.useState(""),[ce,Ae]=i.useState(!1),[Ne,ye]=i.useState(""),[Ce,fe]=i.useState(!1),[Pe,De]=i.useState(!1),[dt,pt]=i.useState(e.title||""),[lt,vt]=i.useState(e.description||""),[_e,Fe]=i.useState(e.dependencies||[]),[bt,ht]=i.useState(e.branch??""),[Ee,me]=i.useState(e.baseBranch??""),[Re,be]=i.useState(""),[Ke,pe]=i.useState(""),[Xe,wt]=i.useState(""),[gt,Tt]=i.useState(""),[Zt,Ot]=i.useState("default"),[Rt,en]=i.useState(void 0),[zt,Qt]=i.useState(Rs),[xn,Kt]=i.useState(e.nodeId),[Ut,fn]=i.useState(Mr(e.executionMode)),[un,tn]=i.useState(""),[Vt,mn]=i.useState(e.enabledWorkflowSteps||[]),[xe,Le]=i.useState(e.sourceIssue?.provider??""),[Ve,at]=i.useState(e.sourceIssue?.repository??""),[Ge,Ft]=i.useState(e.sourceIssue?.externalIssueId??""),[_t,qt]=i.useState(e.sourceIssue?.url??""),[St,z]=i.useState([]),[he,st]=i.useState(!1),[It,ve]=i.useState($i(e.priority)),[ot,Nt]=i.useState(!1),Lt=i.useRef(!1),[$t,Wt]=i.useState(!1),[Gt,sn]=i.useState(!1),[on,Dn]=i.useState(!1),Jt=i.useRef(null),Hn=i.useRef(null),Yn=i.useRef(null),{getSlotsForId:re}=tg(n),ct=re("task-detail-tab").map((ne,ze)=>({entry:ne,tabId:`plugin-${ne.pluginId}-${ze}`})),ft=typeof b=="string"&&b.startsWith("plugin-")?ct.find(ne=>ne.tabId===b)??null:null;i.useEffect(()=>(Lt.current=!0,()=>{Lt.current=!1}),[]);const[it,Y]=i.useState(void 0),[Ye,Yt]=i.useState([]),[In,cs]=i.useState(!1),[gn,Nn]=i.useState(e.enabledWorkflowSteps||[]),ms=e.column==="in-progress"||pT.has(e.status);i.useEffect(()=>{pt(e.title||""),vt(e.description||""),ht(e.branch??""),me(e.baseBranch??""),Le(e.sourceIssue?.provider??""),at(e.sourceIssue?.repository??""),Ft(e.sourceIssue?.externalIssueId??""),qt(e.sourceIssue?.url??""),fn(Mr(e.executionMode)),Dn(!1),De(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode]),i.useEffect(()=>{Nn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{ve($i(e.priority))},[e.id,e.priority]),i.useEffect(()=>{let ne=!1;return Ol(n).then(ze=>{ne||Y(ze)}).catch(()=>{}),()=>{ne=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let ne=!1;return cs(!0),Yj(e.id,n).then(ze=>{ne||Yt(ze)}).catch(ze=>{ne||h(`Failed to load workflow results: ${Me(ze)}`,"error")}).finally(()=>{ne||cs(!1)}),()=>{ne=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const ne=n?`?projectId=${encodeURIComponent(n)}`:"",ze=kt=>{try{const U=JSON.parse(kt.data);U.id===e.id&&Array.isArray(U.workflowStepResults)&&Yt(U.workflowStepResults)}catch{}};return ai(`/api/events${ne}`,{events:{"task:updated":ze}})},[b,e.id,n]),i.useEffect(()=>{K||we("")},[K]),i.useEffect(()=>{if(!e.assignedAgentId){Ue(null);return}const ne=Z.find(kt=>kt.id===e.assignedAgentId);if(ne){Ue(ne);return}let ze=!1;return jd(e.assignedAgentId,n).then(kt=>{ze||Ue(kt)}).catch(()=>{ze||Ue(null)}),()=>{ze=!0}},[e.assignedAgentId,n,Z]),i.useEffect(()=>{if(!e.sourceAgentId){C(null);return}const ne=Z.find(kt=>kt.id===e.sourceAgentId);if(ne){C(ne);return}let ze=!1;return Promise.resolve(jd(e.sourceAgentId,n)).then(kt=>{ze||C(kt??null)}).catch(()=>{ze||C(null)}),()=>{ze=!0}},[e.sourceAgentId,n,Z]),i.useEffect(()=>{ie(!1)},[e.id]),i.useEffect(()=>{if(!($t||Gt))return;const ze=kt=>{const U=kt.target,je=Jt.current?.contains(U),Be=Yn.current?.contains(U);!je&&$t&&Wt(!1),!Be&&Gt&&sn(!1)};return document.addEventListener("mousedown",ze),()=>document.removeEventListener("mousedown",ze)},[$t,Gt]),i.useEffect(()=>{if(!($t||Gt))return;const ze=kt=>{kt.key==="Escape"&&(kt.stopPropagation(),$t&&Wt(!1),Gt&&sn(!1))};return document.addEventListener("keydown",ze),()=>document.removeEventListener("keydown",ze)},[$t,Gt]),i.useEffect(()=>{Oe(!1),$e(j.prompt||""),ue("")},[e.id,j.prompt]);const vn=_T.has(e.column)&&!he,bn=i.useCallback(()=>{if(!vn)return;De(!0),pt(e.title||""),vt(e.description||""),Fe(e.dependencies||[]),ht(e.branch??""),me(e.baseBranch??"");const ne=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",ze=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",kt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";be(ne),pe(ze),wt(kt),Tt(e.thinkingLevel??""),Kt(e.nodeId),Ot(ne||ze||kt?"custom":"default"),tn(""),mn(e.enabledWorkflowSteps||[]),fn(Mr(e.executionMode)),Le(e.sourceIssue?.provider??""),at(e.sourceIssue?.repository??""),Ft(e.sourceIssue?.externalIssueId??""),qt(e.sourceIssue?.url??""),z([]),en(e.reviewLevel),Qt($i(e.priority))},[vn,e]),Pt=i.useCallback(()=>{De(!1),pt(e.title||""),vt(e.description||""),Fe(e.dependencies||[]),ht(e.branch??""),me(e.baseBranch??""),Kt(e.nodeId),Le(e.sourceIssue?.provider??""),at(e.sourceIssue?.repository??""),Ft(e.sourceIssue?.externalIssueId??""),qt(e.sourceIssue?.url??""),Qt($i(e.priority)),fn(Mr(e.executionMode)),St.forEach(ne=>URL.revokeObjectURL(ne.previewUrl)),z([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,St]),[Qn,es]=i.useState("idle"),W=i.useRef(null),qe=i.useRef(0),Je=i.useCallback(ne=>{const ze={},kt=dt.trim(),U=lt.trim();kt&&kt!==(e.title??"")&&(ze.title=kt),ne&&U&&U!==(e.description??"")&&(ze.description=U),Xh(_e,e.dependencies??[])||(ze.dependencies=_e),Xh(Vt,e.enabledWorkflowSteps??[])||(ze.enabledWorkflowSteps=Vt);const je=bt.trim()||null,Be=e.branch??null;je!==Be&&(ze.branch=je);const jt=Ee.trim()||null,hn=e.baseBranch??null;jt!==hn&&(ze.baseBranch=jt);const Xt=zc(Re),Pn=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";Re!==Pn&&(ze.modelProvider=Xt?.provider??null,ze.modelId=Xt?.modelId??null);const tt=zc(Ke),nt=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Ke!==nt&&(ze.validatorModelProvider=tt?.provider??null,ze.validatorModelId=tt?.modelId??null);const Dt=zc(Xe),Tn=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";Xe!==Tn&&(ze.planningModelProvider=Dt?.provider??null,ze.planningModelId=Dt?.modelId??null);const Xs=e.thinkingLevel??"";gt!==Xs&&(ze.thinkingLevel=gt!==""?gt:null),(e.nodeId??void 0)!==xn&&(ze.nodeId=xn??null),Rt!==e.reviewLevel&&(ze.reviewLevel=Rt),zt!==$i(e.priority)&&(ze.priority=zt),Ut!==Mr(e.executionMode)&&(ze.executionMode=Ut==="fast"?"fast":null);const Zs=Uc(xe),rs=Uc(Ve),Zn=Uc(Ge),dn=jT(_t);if(Zs.length===0&&rs.length===0&&Zn.length===0&&!dn)e.sourceIssue&&(ze.sourceIssue=null);else{if(!Zs||!rs||!Zn)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const Ls=Number.parseInt(Zn,10),Hs=e.sourceIssue?.issueNumber??Ls;if(!Number.isFinite(Hs)||Hs<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const vi={provider:Zs,repository:rs,externalIssueId:Zn,issueNumber:Hs,...dn?{url:dn}:{}},yi=e.sourceIssue;(!yi||yi.provider!==vi.provider||yi.repository!==vi.repository||yi.externalIssueId!==vi.externalIssueId||yi.issueNumber!==vi.issueNumber||(yi.url??void 0)!==vi.url)&&(ze.sourceIssue=vi)}return{updates:ze,error:null}},[Ee,bt,_e,lt,Ut,Re,xn,Xe,zt,Rt,Vt,Ge,xe,Ve,_t,gt,dt,Ke,e]),ut=i.useCallback(async ne=>{const{updates:ze,error:kt}=Je(ne);if(!ze)return es("error"),kt&&h(`Failed to update ${e.id}: ${kt}`,"error"),!1;if(Object.keys(ze).length===0)return!0;const U=++qe.current;st(!0),es("saving");try{const je=await Ci(e.id,ze,n);return U!==qe.current?void 0:(m?.(je),es("saved"),!0)}catch(je){return U===qe.current&&(es("error"),h(`Failed to update ${e.id}: ${Me(je)}`,"error")),!1}finally{Lt.current&&U===qe.current&&st(!1)}},[h,Je,m,n,e.id]),Ct=i.useCallback(async ne=>{await ut(!0)},[ut]),Mt=i.useCallback(async()=>{await ut(!0)&&(h(`Updated ${e.id}`,"success"),Lt.current&&De(!1))},[h,ut,e.id]);i.useEffect(()=>{if(Pe)return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{ut(!1)},700),()=>{W.current&&(clearTimeout(W.current),W.current=null)}},[Pe,dt,_e,bt,Ee,Re,Ke,Xe,gt,xn,Rt,zt,Ut,Vt,xe,Ve,Ge,_t,ut]);const an=i.useCallback(async ne=>{const ze=$i(ne),kt=$i(e.priority);if(ze===kt){ve(kt);return}const U=It;ve(ze),Nt(!0);try{const je=await Ci(e.id,{priority:ze},n);ve($i(je.priority)),m?.(je),h(`Priority updated to ${$i(je.priority)}`,"success")}catch(je){ve(U),h(`Failed to update ${e.id}: ${Me(je)}`,"error")}finally{Lt.current&&Nt(!1)}},[e.id,e.priority,n,It,m,h]),An=i.useCallback(ne=>{Pe&&(ne.key==="Escape"?(ne.preventDefault(),Pt()):ne.key==="Enter"&&(ne.ctrlKey||ne.metaKey)&&(ne.preventDefault(),Mt()))},[Pe,Pt,Mt]);i.useEffect(()=>{if(Pe)return document.addEventListener("keydown",An),()=>document.removeEventListener("keydown",An)},[Pe,An]);const Sn=i.useRef(null),{nodes:ps}=Bl(),{confirm:ts}=Ys(),{entries:Bs,loading:Hi,loadMore:fi,hasMore:de,total:We,loadingMore:mt}=$b(e.id,b==="logs"&&A==="agent-log",n),q=i.useCallback(()=>{v?.()},[v]);i.useEffect(()=>{if(x)return;const ne=ze=>{ze.key==="Escape"&&!Pe&&q()};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[x,q,Pe]);const Se=i.useCallback(async ne=>{try{const ze=e.steps.some(je=>je.status!=="pending"),kt=(ne==="todo"||ne==="triage")&&ze;let U;if(kt){if(await ts({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))U={preserveProgress:!0};else if(!await ts({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(e.id,ne,U),q(),h(`Moved to ${ds[ne]}`,"success")}catch(ze){h(Me(ze),"error")}},[e.id,e.steps,r,q,h,ts]),Ze=i.useCallback(async()=>{if(await ts({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),q(),h(`Deleted ${e.id}`,"info")}catch(ze){const kt=kT(ze);if(!kt||kt.dependentIds.length===0){h(Me(ze),"error");return}const U=kt.dependentIds.join(", ");if(!await ts({title:"Force Delete Task",message:`${e.id} is a dependency of ${U}.
|
|
687
|
-
|
|
688
|
-
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),q(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Be){h(Me(Be),"error")}}},[e.id,o,q,h,ts]),At=i.useCallback(async()=>{await ts({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(q(),h(`Merging ${e.id}...`,"info"),l(e.id).then(ze=>{const kt=ze.merged?`Merged ${e.id} (branch: ${ze.branch})`:`Closed ${e.id} (${ze.error||"no branch to merge"})`;h(kt,"success")}).catch(ze=>{h(Me(ze),"error")}))},[e.id,l,q,h,ts]),Et=i.useCallback(()=>{c&&(q(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(ne=>{h(Me(ne),"error")}))},[e.id,c,q,h]),Cn=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(q(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(ne=>{h(Me(ne),"error")}))},[e.id,d,q,h]),rn=i.useCallback(async()=>{if(!(!u||!await ts({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const ze=await u(e.id);q(),h(`Duplicated ${e.id} → ${ze.id}`,"success")}catch(ze){h(Me(ze),"error")}},[e.id,u,q,h,ts]),yn=i.useCallback(async()=>{try{e.paused?(await tk(e.id,n),h(`Unpaused ${e.id}`,"success")):(await Uf(e.id,n),h(`Paused ${e.id}`,"success")),q()}catch(ne){h(Me(ne),"error")}},[e.id,e.paused,q,h]),kn=i.useCallback(async()=>{try{await ak(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),q()}catch(ne){h(Me(ne),"error")}},[e.id,q,h]),Ln=i.useCallback(async()=>{if(await ts({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await rk(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),q()}catch(ze){h(Me(ze),"error")}},[e.id,q,h,ts]),is=i.useCallback(async()=>{if(await ts({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await bk(e.id,n),q(),h(`Replanning ${e.id}...`,"info")}catch(ze){h(Me(ze),"error")}},[e.id,n,q,h,ts]),fs=i.useCallback(()=>{Ae(!0),ye("")},[]),On=i.useCallback(()=>{Wt(!1),sn(!1)},[]),qn=i.useCallback(ne=>{On(),Se(ne)},[On]),wn=i.useCallback(ne=>{On(),ne()},[On]),Xn=i.useCallback(()=>{On(),At()},[On,At]),Vn=i.useCallback(()=>{Ae(!1),ye(""),fe(!1)},[]),as=i.useCallback(async()=>{if(!Ne.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Ne.length>2e3){h("Feedback must be 2000 characters or less","error");return}fe(!0);try{const ne=await xk(e.id,Ne.trim(),n);h(`Refinement task created: ${ne.id}`,"success"),q()}catch(ne){h(Me(ne),"error")}finally{fe(!1)}},[e.id,Ne,h,q]),Fn=i.useCallback(async ne=>{T(!0);try{const ze=await Fl(e.id,ne,n);J(kt=>[...kt,ze]),h("Screenshot attached","success")}catch(ze){h(Me(ze),"error")}finally{T(!1)}},[e.id,h]),ys=i.useCallback(async ne=>{const ze=ne.target.files?.[0];ze&&(await Fn(ze),Sn.current&&(Sn.current.value=""))},[Fn]);i.useEffect(()=>{const ne=ze=>{const kt=ze.clipboardData?.items;if(kt)for(let U=0;U<kt.length;U++){const je=kt[U];if(je.type.startsWith("image/")){const Be=je.getAsFile();if(Be){ze.preventDefault(),Fn(Be);return}}}};return document.addEventListener("paste",ne),()=>document.removeEventListener("paste",ne)},[Fn]);const Wn=i.useCallback(ne=>{ne.preventDefault()},[]),ns=i.useCallback(ne=>{ne.preventDefault();const ze=ne.dataTransfer.files;for(let kt=0;kt<ze.length;kt++){const U=ze[kt];if(U.type.startsWith("image/")){Fn(U);return}}},[Fn]),js=i.useCallback(async ne=>{try{await ck(e.id,ne,n),J(ze=>ze.filter(kt=>kt.filename!==ne)),h("Attachment deleted","info")}catch(ze){h(Me(ze),"error")}},[e.id,h]),Ds=i.useCallback(async ne=>{const ze=gn;Nn(ne);try{const kt=await Ci(e.id,{enabledWorkflowSteps:ne},n);h("Workflow steps updated","success"),m?.(kt)}catch(kt){Nn(ze),h(`Failed to update workflow steps: ${Me(kt)}`,"error")}},[e.id,n,gn,m,h]),qi=i.useCallback(async()=>{B(!0);try{const ne=await Na(void 0,n);Q(ne),ie(!0)}catch(ne){h(`Failed to load agents: ${Me(ne)}`,"error"),ie(!1)}finally{B(!1)}},[n,h]),br=i.useCallback(async ne=>{try{const ze=await nm(e.id,ne,n),kt=Z.find(U=>U.id===ne)??null;Ue(kt||(U=>U?.id===ne?U:null)),ie(!1),m?.(ze),h("Assigned agent updated","success")}catch(ze){h(`Failed to assign agent: ${Me(ze)}`,"error")}},[e.id,n,Z,m,h]),ri=i.useCallback(async()=>{try{const ne=await nm(e.id,null,n);Ue(null),ie(!1),m?.(ne),h("Agent unassigned","success")}catch(ne){h(`Failed to unassign agent: ${Me(ne)}`,"error")}},[e.id,n,m,h]),gi=i.useCallback(async ne=>{const ze=[...L,ne];k(ze);try{await Ci(e.id,{dependencies:ze},n)}catch(kt){k(L),h(Me(kt),"error")}},[e.id,L,h]),Vi=i.useCallback(async(ne,ze)=>{ne.stopPropagation();const kt=L.filter(U=>U!==ze);k(kt);try{await Ci(e.id,{dependencies:kt},n)}catch(U){k(L),h(Me(U),"error")}},[e.id,L,h]),Ii=i.useCallback(async ne=>{try{const ze=await er(ne,n);a(ze)}catch{h(`Failed to load dependency ${ne}`,"error")}},[a,h]),Ea=i.useCallback(async ne=>{ke(!0);try{await Ci(j.id,{prompt:ne},n),h("Spec updated","success"),S&&(S.prompt=ne)}catch(ze){throw h(Me(ze),"error"),ze}finally{ke(!1)}},[j,S,h]),_a=i.useCallback(async ne=>{te(!0);try{await gk(e.id,ne,n),h("AI revision requested. Task moved to planning.","success"),q()}catch(ze){const kt=Me(ze);kt.includes("done")||kt.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(kt,"error")}finally{te(!1)}},[e.id,h,q]),Ma=i.useCallback(()=>{Oe(!0),$e(j.prompt||""),ue("")},[j.prompt]),bi=i.useCallback(()=>{Oe(!1),$e(j.prompt||""),ue("")},[j.prompt]),Wi=i.useCallback(async()=>{if(He===(j.prompt||"")){bi();return}Oe(!1);try{await Ea(He)}catch(ne){throw Oe(!0),ne}},[He,j.prompt,Ea,bi]),oa=i.useCallback(async()=>{Te.trim()&&await _a(Te.trim())},[Te,_a]),Aa=i.useCallback(ne=>{ne.key==="Escape"?(ne.preventDefault(),bi()):ne.key==="Enter"&&(ne.ctrlKey||ne.metaKey)&&(ne.preventDefault(),Wi())},[bi,Wi]),Pa=s.filter(ne=>ne.id!==e.id&&!L.includes(ne.id)).sort((ne,ze)=>{const kt=ze.createdAt.localeCompare(ne.createdAt);if(kt!==0)return kt;const U=parseInt(ne.id.slice(ne.id.lastIndexOf("-")+1),10)||0;return(parseInt(ze.id.slice(ze.id.lastIndexOf("-")+1),10)||0)-U}),Ki=ge?.name??e.assignedAgentId??null,Qs=i.useMemo(()=>{const ne=[];return j.modelProvider&&ne.push(j.modelProvider),j.validatorModelProvider&&!ne.includes(j.validatorModelProvider)&&ne.push(j.validatorModelProvider),j.planningModelProvider&&!ne.includes(j.planningModelProvider)&&ne.push(j.planningModelProvider),ne},[j.modelProvider,j.validatorModelProvider,j.planningModelProvider]),Ta=Nd[e.column]||[],et=["todo","in-progress"],Bt=e.column==="in-review"?et:Ta,Mn=Bt[0],xi=Bt.slice(1),Ns=xi.length>0,Ra=i.useCallback(()=>{Wt(!1),Hn.current?.focus()},[]),xr=i.useCallback(ne=>{if(!Ns){Mn&&qn(Mn);return}const ze=ne.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(ne.target instanceof Element&&ne.target.closest(".detail-move-btn__arrow")||ze&&ne.clientX>0&&ne.clientX>=ze.getBoundingClientRect().left)){Wt(U=>!U),sn(!1);return}Mn&&qn(Mn)},[Ns,Mn,qn]),vr=i.useCallback(ne=>{!Ns||!(ne.key==="ArrowDown"||ne.altKey&&ne.key==="ArrowDown")||(ne.preventDefault(),Wt(!0),sn(!1))},[Ns]),la=i.useCallback(ne=>{ne.key==="Escape"&&(ne.preventDefault(),ne.stopPropagation(),Ra())},[Ra]);i.useEffect(()=>{if(!$t)return;Jt.current?.querySelector(".detail-move-menu-item")?.focus()},[$t]);const Yl={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},Ia=e.status?Yl[e.status]:void 0,Ql=it?.mergeStrategy??"direct",ko=it?.autoMerge??!1,yr=Ql==="pull-request"&&!ko;let ca="Merge & Close";return yr&&!Ia&&(e.prInfo?e.prInfo.status==="open"?ca="Check PR Status":e.prInfo.status==="merged"&&(ca="Finish & Close"):ca="Start PR Review"),t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:Wn,onDrop:ns,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:ds[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!Pe&&vn&&t.jsx("button",{className:"modal-edit-btn",onClick:bn,title:"Edit task","aria-label":"Edit task",children:t.jsx(Ss,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:q,"aria-label":"Back to task list",type:"button",children:[t.jsx(ka,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!x&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:q,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&A==="agent-log"&&!Pe?" detail-body--agent-log":""}`,children:[Pe?t.jsx("div",{className:"modal-edit-form",children:t.jsx(zb,{mode:"edit",title:dt,onTitleChange:pt,description:lt,onDescriptionChange:vt,dependencies:_e,onDependenciesChange:Fe,branch:bt,onBranchChange:ht,baseBranch:Ee,onBaseBranchChange:me,executorModel:Re,onExecutorModelChange:be,validatorModel:Ke,onValidatorModelChange:pe,planningModel:Xe,onPlanningModelChange:wt,thinkingLevel:gt,onThinkingLevelChange:Tt,presetMode:Zt,onPresetModeChange:Ot,selectedPresetId:un,onSelectedPresetIdChange:tn,selectedWorkflowSteps:Vt,onWorkflowStepsChange:mn,pendingImages:St,onImagesChange:z,tasks:s.filter(ne=>ne.id!==e.id),projectId:n,disabled:he,addToast:h,isActive:Pe,onAutoSaveDescription:Ct,reviewLevel:Rt,onReviewLevelChange:en,priority:zt,onPriorityChange:Qt,nodeId:xn,onNodeIdChange:Kt,nodeOptions:ps,nodeOverrideDisabled:ms,nodeOverrideDisabledReason:ms?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Ut,onExecutionModeChange:fn,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:xe,onChange:ne=>Le(ne.target.value),disabled:he,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Ve,onChange:ne=>at(ne.target.value),disabled:he,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:Ge,onChange:ne=>Ft(ne.target.value),disabled:he,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:_t,onChange:ne=>qt(ne.target.value),disabled:he,"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 ne=e.title||e.description||e.id,ze=!F&&ne.length>Bc;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:ze?ne.slice(0,Bc)+"…":ne}),ne.length>Bc&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>G(!F),children:F?"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("label",{className:`card-priority-badge card-priority-badge--${It} detail-priority-chip ${ot?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:It,onChange:ne=>{an(ne.target.value)},disabled:ot,"aria-label":"Task priority",children:xo.map(ne=>t.jsx("option",{value:ne,children:ne},ne))})]}),H&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(zs,{"aria-hidden":"true"}),t.jsxs("span",{children:[j.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",H.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>I(H.sourceAgentId),children:H.label}):H.label]}):t.jsxs(t.Fragment,{children:["Created via ",H.label]}),H.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Ii(H.parentTaskId),children:H.parentTaskId})]}),H.contextInfo?` (${H.contextInfo})`:""]})]}),(e.prInfo?.number||e.mergeDetails?.prNumber)&&t.jsxs("div",{className:"detail-provenance detail-pr-link-row",children:[t.jsx(zs,{"aria-hidden":"true"}),t.jsxs("span",{children:["PR"," ",e.prInfo?.url?t.jsxs("a",{className:"detail-provenance-link",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",e.prInfo.number]}):t.jsxs("span",{children:["#",e.prInfo?.number??e.mergeDetails?.prNumber]})]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!Pe&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>y("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>y("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:()=>y("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>y("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>y("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>y("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>y("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>y("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>y("routing"),children:"Routing"}),ct.map(({entry:ne,tabId:ze})=>t.jsx("button",{className:`detail-tab${b===ze?" detail-tab-active":""}`,onClick:()=>y(ze),children:ne.slot.label},`plugin-tab-${ne.pluginId}-${ze}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(sT,{taskId:e.id,results:Ye,loading:In,enabledWorkflowSteps:gn,canEdit:vn,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Ds})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(OP,{task:e,addToast:h,onTaskUpdated:m,settings:it})}):b==="logs"?t.jsxs("div",{className:`detail-section${A==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${A==="activity"?" log-subview-btn-active":""}`,onClick:()=>$("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${A==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>$("agent-log"),children:"Agent Log"})]}),A==="agent-log"?t.jsx(RP,{entries:Bs,loading:Hi,executorModel:fT(e,it),validatorModel:gT(e,it),planningModel:xT(e,Bs,it),hasMore:de,onLoadMore:fi,loadingMore:mt,totalCount:We}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),j.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",j.log.length," activity entries."]}):null,j.log&&j.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...j.log].reverse().map((ne,ze)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:yT(ne.timestamp)}),t.jsx("span",{className:"detail-log-action",children:ne.action})]}),ne.outcome&&t.jsx("div",{className:"detail-log-outcome",children:ne.outcome})]},ze))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(GP,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="comments"?t.jsx(HP,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(uT,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:vn}):ft?t.jsx("div",{className:"detail-section",children:t.jsx(Zi,{slotId:"task-detail-tab",projectId:n,pluginIds:[ft.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(hT,{tokenUsage:j.tokenUsage,loading:E,task:j})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(oT,{task:e,settings:it,addToast:h,onTaskUpdated:m})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(Ai,{remarkPlugins:[Pi],children:e.summary})})]}),t.jsx(VP,{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.provider.toLowerCase()==="github"&&t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub source issue",children:[t.jsx(zs,{"aria-hidden":"true"}),t.jsx("span",{children:"GitHub"})]}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-link--summary 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":on,"aria-label":on?"Collapse source issue details":"Expand source issue details",onClick:()=>Dn(ne=>!ne),children:t.jsx(Un,{size:16,className:on?"detail-source-chevron--expanded":void 0})})]}),on&&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:[Qs.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Qs.map(ne=>t.jsx(Jn,{provider:ne,size:"sm"},ne))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(zn,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Ki?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(zn,{size:14}),Ki,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void ri(),title:"Unassign agent",children:t.jsx(nn,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{X?ie(!1):qi()},children:"Assign Agent"}),X&&t.jsxs("div",{className:"agent-picker-dropdown",children:[se&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!se&&Z.map(ne=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===ne.id?" selected":""}`,onClick:()=>void br(ne.id),children:[t.jsx(zn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:ne.name}),t.jsx("span",{className:"agent-picker-role",children:ne.role})]},ne.id)),!se&&Z.length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),j.steps&&j.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:j.steps.map((ne,ze)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${ne.status}`,"data-tooltip":`${ne.name} (${ne.status})`,style:{backgroundColor:vT(ne.status)}},ze))}),t.jsxs("span",{className:"step-progress-label",children:[j.steps.filter(ne=>ne.status==="done").length,"/",j.steps.length," step",j.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Ie&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:Ma,children:"Edit"})}),Ie?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:He,onChange:ne=>$e(ne.target.value),onKeyDown:Aa,disabled:O,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:bi,disabled:O,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Wi(),disabled:He===(j.prompt||"")||O,children:O?"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:Te,onChange:ne=>ue(ne.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:ae,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[Te.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void oa(),disabled:!Te.trim()||ae,children:ae?"Requesting…":"Request AI Revision"})]})]})]}):E?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):j.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(Ai,{remarkPlugins:[Pi],children:j.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),ee.length>0?t.jsx("div",{className:"detail-attachments-grid",children:ee.map(ne=>{const ze=_i(`/api/tasks/${e.id}/attachments/${ne.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:ze,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:ze,alt:ne.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[ne.originalName," (",wT(ne.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>js(ne.filename),title:"Delete attachment",children:"×"})]},ne.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Sn,type:"file",accept:"image/*",onChange:ys}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Sn.current?.click(),disabled:M,children:M?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),L.length>0?t.jsx("ul",{className:"detail-dep-list",children:L.map(ne=>{const ze=s.find(U=>U.id===ne),kt=ze?.title||ze?.description||ne;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Ii(ne),onKeyDown:U=>{(U.key==="Enter"||U.key===" ")&&(U.preventDefault(),Ii(ne))},role:"link",tabIndex:0,title:`Click to view ${ne}`,children:[t.jsx("span",{className:"detail-dep-id",children:ne}),t.jsx("span",{className:"detail-dep-label",children:Qh(kt,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:U=>Vi(U,ne),title:`Remove dependency ${ne}`,children:"×"})]},ne)})}):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:()=>{K&&we(""),oe(ne=>!ne)},children:"Add Dependency"}),K&&(()=>{const ne=le.toLowerCase(),ze=ne?Pa.filter(kt=>kt.id.toLowerCase().includes(ne)||kt.title&&kt.title.toLowerCase().includes(ne)||kt.description&&kt.description.toLowerCase().includes(ne)):Pa;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:le,onChange:kt=>we(kt.target.value),onClick:kt=>kt.stopPropagation()}),ze.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ze.map(kt=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{gi(kt.id),oe(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:kt.id}),t.jsx("span",{className:"dep-dropdown-title",children:Qh(kt.title||kt.description||kt.id,30)})]},kt.id))]})})()]})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(zP,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:it?.autoMerge??!1,isManualPrFlow:yr,prAuthAvailable:f??!1,onPrCreated:ne=>{e.prInfo=ne},onPrUpdated:ne=>{e.prInfo=ne},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:Pe?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:Qn==="saving"?"Autosaving…":Qn==="saved"?"Saved":Qn==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:Pt,disabled:he,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Mt(),disabled:he,children:he?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&j.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:kn,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:Ln,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!_&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:Ze,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||_||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:Yn,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{sn(ne=>!ne),Wt(!1)},"aria-haspopup":"menu","aria-expanded":Gt,children:["Actions",t.jsx(cn,{size:12})]}),Gt&&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:()=>wn(Ze),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>wn(rn),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>wn(fs),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>wn(is),children:"Respecify"}),_&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>wn(Et),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:()=>wn(Cn),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>wn(yn),children:e.paused?"Unpause":"Pause"}),e.column!=="done"&&e.paused&&e.pausedByAgentId&&t.jsx("span",{className:"detail-actions-menu-item detail-actions-menu-note",role:"note",children:"Paused by agent"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:Jt,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:Hn,className:"btn btn-primary btn-sm detail-move-btn",onClick:xr,onKeyDown:vr,disabled:!Mn,"aria-label":Mn?`Move to ${ds[Mn]}`:void 0,"aria-haspopup":Ns?"menu":void 0,"aria-expanded":Ns?$t:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Mn?ds[Mn]:""]}),Ns&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(cn,{size:12})})]}),$t&&Ns&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:la,children:xi.map(ne=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>qn(ne),onKeyDown:la,children:ne==="in-progress"?"Back to In Progress":`Move to ${ds[ne]}`},ne))})]}),Ia?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Ia}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Xn,children:ca})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:Hn,className:"btn btn-primary btn-sm detail-move-btn",onClick:xr,onKeyDown:vr,disabled:!Mn,"aria-label":Mn?`Move to ${ds[Mn]}`:void 0,"aria-haspopup":Ns?"menu":void 0,"aria-expanded":Ns?$t:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Mn?ds[Mn]:""]}),Ns&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(cn,{size:12})})]}),$t&&Ns&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:la,children:xi.map(ne=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>qn(ne),onKeyDown:la,children:["Move to ",ds[ne]]},ne))})]})})]})}),ce&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:Vn,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:ne=>ne.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:Vn,"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:Ne,onChange:ne=>ye(ne.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:[Ne.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:as,disabled:!Ne.trim()||Ce,children:Ce?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:Vn,disabled:Ce,children:"Cancel"})})]})}),P&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(CT,{agentId:P,projectId:n,onClose:()=>I(null),addToast:h})})]})}function MT({onClose:e,...n}){const s=i.useRef(null);Ti(s,!0,"task-detail-modal-size"),pi(!0);const a=Ui(e);return t.jsx("div",{className:"modal-overlay open",...a,role:"dialog","aria-modal":"true",children:t.jsx("div",{className:"modal modal-lg task-detail-modal",ref:s,children:t.jsx(Ub,{...n,onRequestClose:e})})})}const Oo={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Zh=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function ep(e){return e==="merging-fix"?"Merging fixes…":e}const Bb=["title","status","column","dependencies","progress"],AT=["title","status","column"];function PT(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function TT(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function tp(e){try{const n=ss("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>Bb.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(AT)}function np(e){try{const n=ss("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function sp(e){try{const n=ss("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>Xi.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function ip(e){try{const n=ss("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function ap(e){try{const n=ss("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function rp(e){try{const s=ss("kb-dashboard-list-sidebar-width",e);if(!s)return 400;const a=Number(s);if(Number.isFinite(a)&&a>0)return a}catch{}return 400}const jl=280,zd=.65,Fo=16;function Ud(e){return Math.max(jl,e*zd)}function zo(e,n){const s=Ud(n);return Math.min(Math.max(e,jl),s)}function RT(e){return e.status==="executing"||e.column==="in-progress"}function op(e){const n=gg(e);return n.total===0||!RT(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function IT({tasks:e,onMoveTask:n,onRetryTask:s,onDeleteTask:a,onMergeTask:r,onResetTask:o,onDuplicateTask:l,onOpenDetail:c,addToast:d,globalPaused:u,onNewTask:m,onQuickCreate:h,availableModels:f,favoriteProviders:p=[],favoriteModels:g=[],onToggleFavorite:x,onToggleModelFavorite:v,onPlanningMode:b,onSubtaskBreakdown:y,onTasksUpdated:S,projectId:N,projectName:E,taskStuckTimeoutMs:w,searchQuery:j="",lastFetchTimeMs:_,prAuthAvailable:D}){const[C,P]=i.useState(null),[I,H]=i.useState("asc"),[A,$]=i.useState(null),[F,G]=i.useState(null),[ee,J]=i.useState(null),T=Js()==="mobile",{confirm:L}=Ys(),[k,K]=i.useState(()=>tp(N)),[oe,le]=i.useState(()=>np(N)),[we,ge]=i.useState(()=>sp(N));i.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-list-columns",JSON.stringify([...k]),N)},[N,k]),i.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-hide-done",oe.toString(),N)},[oe,N]),i.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-list-collapsed",JSON.stringify([...we]),N)},[we,N]);const[Ue,Z]=i.useState(!1),[Q,X]=i.useState(!1),[ie,se]=i.useState(()=>ip(N)),[B,O]=i.useState(()=>ap(N)),[ke,ae]=i.useState(null),[te,Ie]=i.useState(()=>rp(N)),Oe=i.useRef(null),He=i.useRef(null);i.useEffect(()=>{K(tp(N)),le(np(N)),ge(sp(N)),se(ip(N));const xe=ap(N);O(xe),ae(xe?e.find(Le=>Le.id===xe)??null:null),Ie(rp(N))},[N,e]),i.useEffect(()=>{typeof window<"u"&&xs("kb-dashboard-selected-tasks",JSON.stringify([...ie]),N)},[N,ie]),i.useEffect(()=>{if(!(typeof window>"u")){if(B){xs("kb-dashboard-list-selected-task",B,N);return}sr("kb-dashboard-list-selected-task",N)}},[N,B]),i.useEffect(()=>{if(!B){ae(null);return}const xe=e.find(Le=>Le.id===B);xe&&ae(Le=>!Le||Le.id!==B?xe:{...Le,...xe})},[B,e]),i.useEffect(()=>{if(T||typeof ResizeObserver>"u")return;const xe=Oe.current;if(!xe)return;const Le=()=>{const at=zo(te,xe.clientWidth);at!==te&&Ie(at)};Le();const Ve=new ResizeObserver(Le);return Ve.observe(xe),()=>Ve.disconnect()},[T,te]),i.useEffect(()=>{if(T||typeof ResizeObserver>"u")return;const xe=He.current,Le=Oe.current;if(!xe||!Le)return;let Ve=null,at=xe.offsetWidth;const Ge=new ResizeObserver(()=>{const Ft=zo(xe.offsetWidth,Le.clientWidth);Ft!==at&&(at=Ft,Ve&&clearTimeout(Ve),Ve=setTimeout(()=>{try{xs("kb-dashboard-list-sidebar-width",String(Ft),N)}catch{}},200))});return Ge.observe(xe),()=>{Ge.disconnect(),Ve&&clearTimeout(Ve)}},[T,N]);const $e=i.useCallback(()=>{X(xe=>(xe&&se(new Set),!xe))},[]),Te=i.useCallback(xe=>{se(Le=>{const Ve=new Set(Le);return Ve.has(xe)?Ve.delete(xe):Ve.add(xe),Ve})},[]),ue=i.useCallback(()=>{se(new Set)},[]),ce=i.useCallback(xe=>{K(Le=>{const Ve=new Set(Le);return Ve.has(xe)?Ve.size>1&&Ve.delete(xe):Ve.add(xe),Ve})},[]),Ae={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Ne=i.useCallback(xe=>{if(C===xe){H(Le=>Le==="asc"?"desc":"asc");return}P(xe),H("asc")},[C]),ye=i.useCallback(xe=>{J(Le=>Le===xe?null:xe)},[]),Ce=i.useCallback(xe=>{ge(Le=>{const Ve=new Set(Le);return Ve.has(xe)?Ve.delete(xe):Ve.add(xe),Ve})},[]),fe=i.useCallback(()=>{J(null)},[]),Pe=i.useMemo(()=>{let xe=j?e.filter(at=>at.id.toLowerCase().includes(j.toLowerCase())||at.title&&at.title.toLowerCase().includes(j.toLowerCase())||at.description.toLowerCase().includes(j.toLowerCase())):[...e];oe&&!ee&&(xe=xe.filter(at=>at.column!=="done"&&at.column!=="archived"));const Le=ee?xe.filter(at=>at.column===ee):xe,Ve={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};Le.forEach(at=>{const Ge=ou(at.column)?at.column:gl;Ve[Ge].push(at)});for(const at of Xi){if(!C){Ve[at]=ug(Ve[at],at);continue}Ve[at]=[...Ve[at]].sort((Ge,Ft)=>{let _t=0;switch(C){case"title":_t=(Ge.title||Ge.description).localeCompare(Ft.title||Ft.description);break;case"status":_t=(Ge.status||"").localeCompare(Ft.status||"");break;case"column":_t=Ge.column.localeCompare(Ft.column);break}return I==="asc"?_t:-_t})}return Ve},[e,j,C,I,oe,ee]),De=i.useMemo(()=>Object.values(Pe).reduce((xe,Le)=>xe+Le.length,0),[Pe]),dt=i.useMemo(()=>e.filter(xe=>xe.column==="done"||xe.column==="archived").length,[e]),pt=i.useMemo(()=>oe?dt:0,[oe,dt]),lt=i.useCallback(()=>{const xe=Object.values(Pe).flat().filter(Le=>Le.column!=="archived").map(Le=>Le.id);se(Le=>{if(xe.every(at=>Le.has(at))){const at=new Set(Le);return xe.forEach(Ge=>at.delete(Ge)),at}else return new Set([...Le,...xe])})},[Pe]),vt=i.useMemo(()=>{const xe=Object.values(Pe).flat().filter(Le=>Le.column!=="archived");return xe.length===0?!1:xe.every(Le=>ie.has(Le.id))},[Pe,ie]),_e=i.useMemo(()=>{const xe=Object.values(Pe).flat().filter(Ve=>Ve.column!=="archived");if(xe.length===0)return!1;const Le=xe.filter(Ve=>ie.has(Ve.id)).length;return Le>0&&Le<xe.length},[Pe,ie]),[Fe,bt]=i.useState("__no_change__"),[ht,Ee]=i.useState("__no_change__"),[me,Re]=i.useState("__no_change__"),[be,Ke]=i.useState([]),[pe,Xe]=i.useState(!1),wt=i.useMemo(()=>me&&me!=="__no_change__"?be.find(xe=>xe.id===me):void 0,[be,me]),[gt,Tt]=i.useState(!1);i.useEffect(()=>{if(ie.size===0)return;let xe=!1;return(async()=>{Xe(!0);try{const Ve=await pl();xe||Ke(Ve)}catch(Ve){console.error("Failed to fetch nodes for bulk edit",Ve),xe||Ke([])}finally{xe||Xe(!1)}})(),()=>{xe=!0}},[ie.size]);const Zt=i.useCallback(async()=>{if(ie.size===0)return;const xe=Array.from(ie).filter(Ve=>{const at=e.find(Ge=>Ge.id===Ve);return at&&at.column!=="archived"});if(xe.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Le={taskIds:xe};if(Fe!=="__no_change__")if(Fe==="")Le.modelProvider=null,Le.modelId=null;else{const Ve=Fe.indexOf("/");Ve!==-1&&(Le.modelProvider=Fe.slice(0,Ve),Le.modelId=Fe.slice(Ve+1))}if(ht!=="__no_change__")if(ht==="")Le.validatorModelProvider=null,Le.validatorModelId=null;else{const Ve=ht.indexOf("/");Ve!==-1&&(Le.validatorModelProvider=ht.slice(0,Ve),Le.validatorModelId=ht.slice(Ve+1))}if(me!=="__no_change__"&&(me===""?Le.nodeId=null:Le.nodeId=me),Object.keys(Le).length===1){d("No changes to apply","info");return}Tt(!0);try{const Ve=await Gw(Le.taskIds,Le.modelProvider,Le.modelId,Le.validatorModelProvider,Le.validatorModelId,void 0,void 0,Le.nodeId,N);S&&S(Ve.updated),d(`Updated ${xe.length} task${xe.length===1?"":"s"}`,"success"),ue(),bt("__no_change__"),Ee("__no_change__"),Re("__no_change__")}catch(Ve){d(Me(Ve)||"Failed to update models","error")}finally{Tt(!1)}},[ie,e,Fe,ht,me,N,d,ue,S]),Ot=i.useCallback(xe=>{if(T){c(xe,{origin:"list-mobile"});return}O(xe.id),ae(xe)},[T,c]),Rt=i.useRef(null),en=i.useRef(null);i.useEffect(()=>()=>{Rt.current&&clearTimeout(Rt.current)},[]);const zt=i.useCallback(xe=>{if(O(xe.id),ae(xe),"prompt"in xe){en.current=null,Rt.current&&(clearTimeout(Rt.current),Rt.current=null);return}en.current=xe.id,Rt.current&&clearTimeout(Rt.current),Rt.current=setTimeout(()=>{Rt.current=null,en.current===xe.id&&er(xe.id,N).then(Ve=>{en.current===Ve.id&&ae(at=>!at||at.id!==Ve.id?at:{...at,...Ve})}).catch(()=>{})},200)},[N]),Qt=i.useCallback((xe,Le)=>{if(Le.paused){xe.preventDefault();return}xe.dataTransfer.setData("text/plain",Le.id),xe.dataTransfer.effectAllowed="move",$(Le.id)},[]),xn=i.useCallback(()=>{$(null),G(null)},[]),Kt=i.useCallback(xe=>{if(T)return;xe.preventDefault();const Le=Oe.current;if(!Le)return;const Ve=Le.getBoundingClientRect(),at=Ft=>{const _t=Ft.clientX-Ve.left;Ie(zo(_t,Ve.width))},Ge=()=>{window.removeEventListener("mousemove",at),window.removeEventListener("mouseup",Ge)};window.addEventListener("mousemove",at),window.addEventListener("mouseup",Ge)},[T]),Ut=i.useCallback(xe=>{if(T)return;const Le=Oe.current?.clientWidth??0,Ve=te/zd+Fo,at=Math.max(Le,Ve),Ge=Ud(at);if(xe.key==="ArrowLeft"||xe.key==="ArrowRight"){xe.preventDefault();const Ft=xe.key==="ArrowLeft"?-Fo:Fo;Ie(_t=>zo(_t+Ft,at));return}if(xe.key==="Home"){xe.preventDefault(),Ie(jl);return}xe.key==="End"&&(xe.preventDefault(),Ie(Ge))},[T,te]),fn=i.useCallback((xe,Le)=>{xe.preventDefault(),xe.dataTransfer.dropEffect="move",G(Le)},[]),un=i.useCallback(()=>{G(null)},[]),tn=i.useCallback(async(xe,Le)=>{xe.preventDefault(),G(null);const Ve=xe.dataTransfer.getData("text/plain");if(Ve){if(Le==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Ge=e.find(qt=>qt.id===Ve)?.steps.some(qt=>qt.status!=="pending")??!1,Ft=(Le==="todo"||Le==="triage")&&Ge;let _t;if(Ft){if(await L({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))_t={preserveProgress:!0};else if(!await L({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(Ve,Le,_t)}catch(at){d(Me(at),"error")}}},[n,d,e,L]),Vt=xe=>!C||C!==xe?t.jsx(Cf,{size:14,className:"sort-icon"}):I==="asc"?t.jsx(fa,{size:14,className:"sort-icon active"}):t.jsx(ro,{size:14,className:"sort-icon active"}),mn=xe=>t.jsxs("div",{id:xe,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:Bb.map(Le=>{const Ve=k.has(Le),at=Ve&&k.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${at?" disabled":""}`,title:at?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:Ve,onChange:()=>ce(Le),disabled:at}),t.jsx("span",{children:Ae[Le]})]},Le)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>le(Le=>!Le),"aria-pressed":oe,title:oe?"Show done tasks":"Hide done tasks",children:[oe?t.jsx(ur,{size:14}):t.jsx(Qd,{size:14}),oe?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:Xi.map(Le=>{const Ve=e.filter(_t=>_t.column===Le).length,at=Le==="done"||Le==="archived",Ge=oe&&at?0:Ve,Ft=oe&&at&&Ve>0;return t.jsxs("div",{className:`list-drop-zone${F===Le?" drag-over":""}${ee===Le?" active":""}`,onClick:()=>ye(Le),onDragOver:_t=>fn(_t,Le),onDragLeave:un,onDrop:_t=>tn(_t,Le),"data-column":Le,children:[t.jsx("span",{className:`list-section-dot dot-${Le}`}),t.jsx("span",{className:"drop-zone-label",children:ds[Le]}),t.jsx("span",{className:"drop-zone-count",children:Ft?`${Ge} of ${Ve}`:Ve})]},Le)})})]});return t.jsxs("div",{className:"list-view",children:[T&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:$e,"aria-pressed":Q,children:Q?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>Z(xe=>!xe),"aria-expanded":Ue,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(Ru,{size:14}),"View options"]}),m?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:m,children:"+ New Task"}):null,t.jsx("div",{className:"list-stats",children:ee?`${De} of ${e.length} tasks in ${ds[ee]}`:`${De} of ${e.length} tasks`})]}),Ue?t.jsx("div",{className:"list-toolbar-mobile-options",children:mn("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:T?"":"list-split-layout","data-testid":T?void 0:"list-split-layout",ref:Oe,children:[t.jsxs("div",{className:T?"":"list-split-sidebar","data-testid":T?void 0:"list-split-sidebar",ref:He,style:T?void 0:{width:`${te}px`},children:[!T&&t.jsxs("aside",{className:"list-sidebar-controls","aria-label":"List controls",children:[t.jsxs("div",{className:"list-sidebar-controls__header",children:[t.jsxs("p",{className:"list-stats",children:[ee?`${De} of ${e.length} tasks in ${ds[ee]}`:`${De} of ${e.length} tasks`,pt>0&&!ee&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",pt," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:$e,"aria-pressed":Q,children:Q?"Done Editing":"Bulk Edit"}),m?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:m,children:"+ New Task"}):null]}),t.jsxs("div",{className:"list-sidebar-summary-chips",children:[ee?t.jsx("button",{className:"btn btn-sm",onClick:fe,"aria-label":"Clear column filter",children:`Filter: ${ds[ee]}`}):null,oe?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,Q?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,Q&&ie.size>0?t.jsx("button",{className:"btn btn-sm",onClick:ue,children:`${ie.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>Z(xe=>!xe),"aria-expanded":Ue,"aria-controls":"list-view-options-panel",children:[t.jsx(Ru,{size:14}),"View options"]}),Ue&&mn("list-view-options-panel"),Q&&ie.size>0&&f&&f.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(ks,{models:f,value:Fe,onChange:bt,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:v})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(ks,{models:f,value:ht,onChange:Ee,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:v})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:me,onChange:xe=>Re(xe.target.value),"aria-label":"Node Override",disabled:pe,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),be.map(xe=>t.jsx("option",{value:xe.id,children:`${TT(xe.status)} ${xe.name||xe.id} (${PT(xe.status)})`},xe.id))]}),wt?t.jsx(xa,{status:wt.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:Zt,disabled:gt||Fe==="__no_change__"&&ht==="__no_change__"&&me==="__no_change__",children:gt?"Applying...":"Apply"})]})]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Ng,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:y,projectId:N,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:v})}),De===0?t.jsx("div",{className:"list-empty",children:j?"No tasks match your filter":"No tasks yet"}):T?t.jsx("div",{className:"list-cards",children:Xi.map(xe=>{if(ee&&xe!==ee||oe&&(xe==="done"||xe==="archived")&&!ee)return null;const Le=Pe[xe],Ve=Le.length===0;if(j&&Ve)return null;const at=we.has(xe);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>Ce(xe),"aria-expanded":!at,role:"button",tabIndex:0,onKeyDown:Ge=>{(Ge.key==="Enter"||Ge.key===" ")&&(Ge.preventDefault(),Ce(xe))},children:[t.jsx(Un,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${xe}`}),t.jsx("span",{className:"list-section-title",children:ds[xe]}),t.jsx("span",{className:"list-section-count",children:Le.length})]}),!at&&t.jsx(t.Fragment,{children:Ve?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Le.map(Ge=>{const Ft=Ge.status==="failed",_t=Ge.paused===!0,qt=xl(Ge,w,_),St=!u&&!Ft&&!_t&&!qt&&(Ge.column==="in-progress"||Zh.has(Ge.status)),z=typeof Ge.status=="string"&&Ge.status.trim().length>0,he=!!(Ge.dependencies&&Ge.dependencies.length>0),st=op(Ge),It=st.hasProgress,ve=Q;return t.jsxs("div",{className:`list-card${St?" agent-active":""}${ve?" list-card--selectable":""}`,onClick:()=>Ot(Ge),"data-id":Ge.id,children:[ve&&t.jsx("label",{className:"list-card-checkbox",onClick:ot=>ot.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:ie.has(Ge.id),onChange:ot=>{ot.stopPropagation(),Te(Ge.id)},onClick:ot=>ot.stopPropagation(),disabled:Ge.column==="archived","aria-label":`Select ${Ge.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Ge.id}),Ge.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(us,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),_t&&Ge.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):qt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):z?t.jsx("span",{className:`list-status-badge list-status-badge--${Ge.column}${Ft?" failed":""}${St?" pulsing":""}`,children:ep(Ge.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Ge.title||Ge.description})}),(he||It)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[he&&t.jsxs("span",{className:"list-dep-badge",title:Ge.dependencies.join(", "),children:[t.jsx(Qa,{size:12})," ",Ge.dependencies.length]}),It&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${st.percent}%`,backgroundColor:Oo[Ge.column]}})}),t.jsx("span",{className:"list-progress-label",children:st.label})]})]})]},Ge.id)})})]},xe)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[Q&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:vt,ref:xe=>{xe&&(xe.indeterminate=_e)},onChange:lt,"aria-label":"Select all visible tasks"})}),k.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("title"),children:["Title ",Vt("title")]}),k.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("status"),children:["Status ",Vt("status")]}),k.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Ne("column"),children:["Column ",Vt("column")]}),k.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),k.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:Xi.map(xe=>{if(ee&&xe!==ee||oe&&(xe==="done"||xe==="archived")&&!ee)return null;const Le=Pe[xe],Ve=Le.length===0;if(j&&Ve)return null;const at=we.has(xe);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>Ce(xe),"aria-expanded":!at,children:t.jsxs("th",{colSpan:k.size+(Q?1:0),className:"list-section-cell",children:[t.jsx(Un,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${xe}`}),t.jsx("span",{className:"list-section-title",children:ds[xe]}),t.jsx("span",{className:"list-section-count",children:Le.length})]})}),!at&&t.jsx(t.Fragment,{children:Ve?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:k.size+(Q?1:0),className:"list-empty-cell",children:"No tasks"})}):Le.map(Ge=>{const Ft=Ge.status==="failed",_t=Ge.paused===!0,qt=xl(Ge,w,_),St=!u&&!Ft&&!_t&&!qt&&(Ge.column==="in-progress"||Zh.has(Ge.status)),z=A===Ge.id;return t.jsxs("tr",{className:`list-row${Ft?" failed":""}${_t?" paused":""}${qt?" stuck":""}${St?" agent-active":""}${z?" dragging":""}${B===Ge.id?" list-row--selected":""}`,onClick:()=>Ot(Ge),draggable:!_t,onDragStart:he=>Qt(he,Ge),onDragEnd:xn,"data-id":Ge.id,children:[Q&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:ie.has(Ge.id),onChange:he=>{he.stopPropagation(),Te(Ge.id)},onClick:he=>he.stopPropagation(),disabled:Ge.column==="archived","aria-label":`Select ${Ge.id}`})}),k.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[t.jsx("span",{className:"list-title-id",children:Ge.id}),t.jsxs("div",{className:"list-title-row",children:[Ge.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(us,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Ge.title||Ge.description})]})]})}),k.has("status")&&t.jsx("td",{className:"list-cell",children:_t&&Ge.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):qt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ge.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Ge.column}${Ft?" failed":""}${St?" pulsing":""}`,children:ep(Ge.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),k.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${Oo[Ge.column]}20`,color:Oo[Ge.column]},children:ds[Ge.column]})}),k.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Ge.dependencies&&Ge.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Ge.dependencies.join(", "),children:[t.jsx(Qa,{size:12})," ",Ge.dependencies.length]}):"-"}),k.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const he=op(Ge);return he.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:`${he.percent}%`,backgroundColor:Oo[Ge.column]}})}),t.jsx("span",{className:"list-progress-label",children:he.label})]}):"-"})()})]},Ge.id)})})]},xe)})})]})]}),!T&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:Kt,onKeyDown:Ut,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":jl,"aria-valuemax":Math.round(Ud(Oe.current?.clientWidth??te/zd+Fo)),"aria-valuenow":Math.round(te)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:ke?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(Ub,{task:ke,projectId:N,tasks:e,embedded:!0,onOpenDetail:zt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:xe=>{ae(Le=>!Le||Le.id!==xe.id?Le:{...Le,...xe})},addToast:d,prAuthAvailable:D})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const $T={active:{label:"Active",color:"var(--success)",icon:ls},paused:{label:"Paused",color:"var(--warning)",icon:di},errored:{label:"Error",color:"var(--color-error)",icon:Ps},initializing:{label:"Initializing",color:"var(--info)",icon:xt}};function DT(e){if(!e)return"Never";const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function LT(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),a=e.slice(-Math.floor(n/2)+2);return`${s}...${a}`}function OT(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,a=n.health;if(!s&&!a)return!0;if(!s||!a||s.activeTaskCount!==a.activeTaskCount||s.inFlightAgentCount!==a.inFlightAgentCount||s.totalTasksCompleted!==a.totalTasksCompleted||s.totalTasksFailed!==a.totalTasksFailed||s.status!==a.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 FT({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:d=!1}){const[u,m]=i.useState(!1),h=$T[e.status],f=h.icon,p=i.useCallback(()=>{s(e)},[s,e]),g=i.useCallback(N=>{N.stopPropagation(),a(e)},[a,e]),x=i.useCallback(N=>{N.stopPropagation(),r(e)},[r,e]),v=i.useCallback(N=>{if(N.stopPropagation(),!u){m(!0);return}o(e),m(!1)},[u,o,e]),b=e.status==="paused",y=e.status==="errored",S=e.status==="initializing";return t.jsxs("div",{className:`project-card ${d?"project-card-loading":""} ${y?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(vs,{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:LT(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(f,{size:12,className:S?"animate-spin":""}),t.jsx("span",{children:h.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:DT(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[b?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:x,disabled:d,title:"Resume project","aria-label":"Resume project",children:[t.jsx(ls,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:g,disabled:d||S,title:S?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(di,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:d,title:"Open project","aria-label":"Open project",children:[t.jsx(oo,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${u?"is-armed":""}`,onClick:v,disabled:d,title:u?"Confirm remove":"Remove project","aria-label":u?"Confirm remove project":"Remove project",children:[t.jsx(En,{size:14}),t.jsx("span",{children:u?"Confirm":""})]})]})]})]})}const zT=i.memo(FT,OT);function UT(){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(vs,{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(Ws,{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(Gn,{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 BT=1e4,lp=5;function HT(e){const[n,s]=i.useState({}),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(null),d=i.useRef(null),u=i.useRef(!1),m=i.useCallback(async()=>{if(e.length===0){s({}),u.current||(u.current=!0),r(!1);return}d.current&&d.current.abort(),d.current=new AbortController,!u.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=lp){const x=e.slice(g,g+lp),v=await Promise.allSettled(x.map(async b=>{try{return await im(b)}catch{return null}}));if(x.forEach((b,y)=>{const S=v[y];p[b]=S.status==="fulfilled"?S.value:null}),d.current?.signal.aborted)return}s(p),u.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),u.current=!0}finally{r(!1)}},[e]),h=i.useCallback(async f=>{try{const p=await im(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return i.useEffect(()=>(u.current=!1,m(),()=>{d.current&&d.current.abort()}),[m]),i.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},BT),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function qT({projects:e,loading:n=!1,onSelectProject:s,onAddProject:a,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[d,u]=i.useState("all"),[m,h]=i.useState(null),[f,p]=i.useState("activity"),[g,x]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const H=localStorage.getItem("kb-dashboard-recent-projects");if(H)try{const A=JSON.parse(H);b(A)}catch{}},[]);const[v,b]=i.useState([]),y=i.useMemo(()=>e.map(H=>H.id),[e]),{healthMap:S,loading:N}=HT(y),E=i.useMemo(()=>e.map(H=>({project:H,health:S[H.id]||null})),[e,S]),w=i.useMemo(()=>{let H=[...E];return d!=="all"&&(H=H.filter(({project:A})=>A.status===d)),m!==null&&(H=H.filter(({project:A})=>A.nodeId===m)),H},[E,d,m]),j=i.useMemo(()=>{const H=[...w];return H.sort((A,$)=>{let F=0;switch(f){case"name":F=A.project.name.localeCompare($.project.name);break;case"activity":{const G=A.project.lastActivityAt||A.health?.lastActivityAt||A.project.updatedAt,ee=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt;F=new Date(ee).getTime()-new Date(G).getTime();break}case"status":{const G={errored:0,initializing:1,paused:2,active:3};F=G[A.project.status]-G[$.project.status];break}}return g==="asc"?F:-F}),H},[w,f,g]),_=i.useMemo(()=>{const H=e.length,A=e.filter(T=>T.status==="active").length,$=e.filter(T=>T.status==="errored").length,F=new Set;e.forEach(T=>{T.nodeId&&F.add(T.nodeId)});const G=F.size||(H>0?1:0);let ee=0,J=0,M=0;return Object.values(S).forEach(T=>{T&&(ee+=T.activeTaskCount,J+=T.totalTasksCompleted,M+=T.inFlightAgentCount)}),{totalProjects:H,activeProjects:A,erroredProjects:$,totalNodes:G,totalActiveTasks:ee,totalCompletedTasks:J,totalInFlightAgents:M}},[e,S]),D=i.useMemo(()=>({all:e.length,active:e.filter(H=>H.status==="active").length,paused:e.filter(H=>H.status==="paused").length,errored:e.filter(H=>H.status==="errored").length}),[e]),C=i.useMemo(()=>{const H=new Map;return e.forEach(A=>{const $=A.nodeId,F=H.get($);if(F)F.count++;else{const ee=c.find(J=>J.id===$)?.name??A._sourceNodeName??"Local";H.set($,{name:ee,count:1})}}),Array.from(H.entries()).map(([A,{name:$,count:F}])=>({nodeId:A??null,name:$,count:F}))},[e,c]),P=i.useCallback(H=>{const A=[H.id,...v.filter($=>$!==H.id)].slice(0,3);b(A),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(A)),s(H)},[s,v]);return n||N&&e.length>0&&Object.keys(S).length===0?t.jsx(UT,{}):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(Lr,{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:a,children:[t.jsx(_n,{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(sa,{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(vs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.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(Ws,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.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(Gn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),_.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:_.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),_.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Xr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:_.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:a,children:[t.jsx(_n,{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 ${d==="all"?"active":""}`,onClick:()=>u("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:D.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:D.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:D.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${D.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:D.errored})]})]}),C.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Xr,{size:14}),t.jsxs("select",{value:m??"",onChange:H=>{h(H.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),C.map(({nodeId:H,name:A,count:$})=>t.jsxs("option",{value:H??"",children:[A," (",$,")"]},H??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(ll,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:H=>{const[A,$]=H.target.value.split("-");p(A),x($)},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(Cf,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:j.map(({project:H,health:A})=>{const $=c.find(G=>G.id===H.nodeId),F=$?void 0:H._sourceNodeName;return t.jsx(zT,{project:H,health:A,node:$,nodeNameFallback:F,onSelect:P,onPause:r,onResume:o,onRemove:l},H.id)})}),j.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(ll,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>u("all"),children:"Show All Projects"})]})]})}const Mu="kb-planning-last-description",Au="kb-subtask-last-description",Pu="kb-mission-last-goal";function VT(e,n){xs(Mu,e,n)}function WT(e){return ss(Mu,e)||""}function za(e){sr(Mu,e)}function KT(e,n){xs(Au,e,n)}function GT(e){return ss(Au,e)||""}function Hc(e){sr(Au,e)}function JT(e,n){xs(Pu,e,n)}function YT(e){return ss(Pu,e)||""}function Yi(e){sr(Pu,e)}function QT(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const a=s;if(n.id in a)return a[n.id]}return s}function XT(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(a=>a.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 ZT(e){let n=0;const s=[];for(const a of e){if(a.question){n+=1,s.push({...a,questionNumber:n});continue}a.thinkingOutput&&s.push({...a,questionNumber:null})}return s}function ii({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=ZT(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,d=!!o.thinkingOutput,u=s[l]??n,m=c?QT(o):void 0,h=o.question&&m!==void 0?XT(o.question,m):"",f=o.response&&typeof o.response=="object"&&!Array.isArray(o.response)?o.response:void 0,p=typeof f?._comment=="string"?f._comment.trim():"";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||"—"}),p&&t.jsxs("p",{className:"conversation-comment",children:["💬 ",p]})]}),d&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{a(g=>({...g,[l]:!u}))},"aria-expanded":u,children:[t.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"}),u?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),u&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const cp="fusion-tab-id";function eR(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ca(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(cp);if(e)return e;const n=eR();return window.sessionStorage.setItem(cp,n),n}function Jl(e){const n=i.useMemo(()=>Ca(),[]),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(!1);i.useEffect(()=>{if(!e){a(!1),o(null),c(!1);return}let u=!0;return c(!0),Promise.resolve(P1(e,n)).then(m=>{if(u){if(m.acquired){a(!1),o(null);return}a(!0),o(m.currentHolder)}}).catch(()=>{u&&(a(!1),o(null))}).finally(()=>{u&&c(!1)}),()=>{u=!1;try{const m=T1(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),i.useEffect(()=>{if(!e||typeof window>"u")return;const u=()=>{if(typeof navigator.sendBeacon!="function")return;const m=_i(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",u),()=>{window.removeEventListener("beforeunload",u)}},[e,n]),i.useEffect(()=>!e||typeof EventSource>"u"?void 0:ai("/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),a(!!(f&&f!==n))}catch{}}}}),[e,n]);const d=i.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(R1(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const tR="fusion:ai-session-sync",dp="fusion:ai-session-sync",nR=3e4,sR=6e4;function ki(){return Date.now()}function iR(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function up(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 aR{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=iR(),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:ki()})}broadcastUpdate(n){const s=n.timestamp??ki();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",a=n.timestamp??ki();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},a),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:a})}broadcastLock(n,s){const a=ki();this.applyTabOwnership(n,s,a),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:a})}broadcastUnlock(n,s){const a=ki();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=ki();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(tR),this.channel.onmessage=s=>{const a=up(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==dp||!s.newValue))try{const a=JSON.parse(s.newValue),r=up(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=ki();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},nR)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=ki();this.publish({type:"tab:inactive",tabId:a,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 a={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(dp,JSON.stringify(a))}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}}),a=[...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:a,heartbeats:r,timestamp:ki()});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,a=!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)),a&&this.emit()}applyTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(o&&a<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:a}),this.updateHeartbeat(s,a,!1);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:a}),r&&this.emit()}releaseTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||a<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:a}),r&&this.emit()}updateHeartbeat(n,s,a=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),a&&this.emit())}emit(){const n=ki(),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 a=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>sR;a.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:a};for(const r of this.listeners)r()}}const ji=new aR;function gr(){const e=i.useSyncExternalStore(c=>ji.subscribe(c),()=>ji.getSnapshot(),()=>ji.getSnapshot());i.useEffect(()=>{ji.requestSync()},[]);const n=i.useCallback(c=>{ji.broadcastUpdate(c)},[]),s=i.useCallback(c=>{ji.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{ji.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{ji.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{ji.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{ji.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function rR(e,n){return e&&n?`${e}/${n}`:""}function oR(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 lR=["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 cR({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){pi(e);const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,x]=i.useState([]),[v,b]=i.useState(null),[y,S]=i.useState(!1),N=i.useRef(!1),[E,w]=i.useState(""),[j,_]=i.useState(!0),[D,C]=i.useState(!1),[P,I]=i.useState(!1),[H,A]=i.useState(!1),$=i.useRef(null),F=i.useRef(null),G=i.useRef(null),ee=i.useRef(null),[J,M]=i.useState(o??null),T=i.useMemo(()=>Ca(),[]),{isLockedByOther:L,takeControl:k,isLoading:K}=Jl(e?J:null),{activeTabMap:oe,broadcastUpdate:le,broadcastCompleted:we,broadcastLock:ge,broadcastUnlock:Ue,broadcastHeartbeat:Z}=gr(),{confirm:Q}=Ys(),[X,ie]=i.useState(void 0),[se,B]=i.useState(void 0),[O,ke]=i.useState([]),[ae,te]=i.useState(!0),[Ie,Oe]=i.useState(null),[He,$e]=i.useState([]),[Te,ue]=i.useState([]),ce=rR(X,se);i.useEffect(()=>{(async()=>{try{te(!0);const Re=await $s();ke(Re.models),$e(Re.favoriteProviders),ue(Re.favoriteModels)}catch(Re){Oe(Me(Re)||"Failed to load models")}finally{te(!1)}})()},[]);const Ae=i.useCallback(me=>{$e(Re=>{const be=Re,pe=be.includes(me)?be.filter(Xe=>Xe!==me):[me,...be];return $n({favoriteProviders:pe,favoriteModels:Te}).catch(()=>{$e(be)}),pe})},[Te]),Ne=i.useCallback(me=>{ue(Re=>{const be=Re,pe=be.includes(me)?be.filter(Xe=>Xe!==me):[me,...be];return $n({favoriteProviders:He,favoriteModels:pe}).catch(()=>{ue(be)}),pe})},[He]),ye=i.useCallback((me,Re)=>{if(!me||!Re)return"Using default";const be=O.find(Ke=>Ke.provider===me&&Ke.id===Re);return be?`${be.provider}/${be.id}`:`${me}/${Re}`},[O]),Ce=i.useCallback(me=>{F.current?.close();const Re=c1(me,a,{onThinking:be=>{w(Ke=>Ke+be),le({sessionId:me,status:"generating",needsInput:!1,owningTabId:T,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:be=>{C(!1),I(!1),Yi(a),u({type:"question",sessionId:me,question:be}),w(""),S(!0),le({sessionId:me,status:"awaiting_input",needsInput:!0,owningTabId:T,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:be=>{C(!1),I(!1),Yi(a),u({type:"summary",sessionId:me,summary:be}),b(be),w(""),S(!0),le({sessionId:me,status:"complete",needsInput:!1,owningTabId:T,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:be=>{const Ke=be||"Session failed while contacting the AI.";C(!1),I(!1),h(null),u({type:"error",sessionId:me,errorMessage:Ke}),w(""),S(!0),G.current=me,le({sessionId:me,status:"error",needsInput:!1,owningTabId:T,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),we({sessionId:me,status:"error"})},onComplete:()=>{C(!1),I(!1),G.current=null,we({sessionId:me,status:"complete"})},onConnectionStateChange:be=>{C(be==="reconnecting")}});F.current=Re},[we,le,l,a,T]),fe=i.useCallback(async me=>{const Re=me??l;if(Re.trim()){h(null),w(""),p([]),x([]),C(!1),u({type:"loading"});try{const{sessionId:be}=await a1(Re.trim(),a,X&&se?{modelProvider:X,modelId:se}:void 0);G.current=be,M(be),Yi(a),Ce(be),p([])}catch(be){C(!1),h(Me(be)||"Failed to start interview session"),u({type:"initial"}),G.current=null,M(null)}}},[Ce,l,X,se,a]);i.useEffect(()=>{e&&d.type==="initial"&&$.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!N.current&&d.type==="initial"){const me=YT(a);me&&c(me)}},[e]),i.useEffect(()=>{if(e&&r&&!N.current&&d.type==="initial"){c(r);const me=setTimeout(()=>{N.current=!0,fe(r)},0);return()=>clearTimeout(me)}},[e,r,d.type,fe]),i.useEffect(()=>{e||(N.current=!1,C(!1),I(!1),M(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let me=!1;return Ei(o).then(Re=>{if(me||!Re)return;const be=nr(Re.conversationHistory);if(x(be),M(Re.id),p(be.map(Ke=>Ke.response).filter(Ke=>!!(Ke&&typeof Ke=="object"&&!Array.isArray(Ke)))),Re.status==="awaiting_input"&&Re.currentQuestion)try{Yi(a);const Ke=JSON.parse(Re.currentQuestion);G.current=Re.id,S(!0),u({type:"question",sessionId:Re.id,question:Ke})}catch{h("Failed to restore session question.")}else if(Re.status==="complete"&&Re.result)try{Yi(a);const Ke=JSON.parse(Re.result);G.current=Re.id,S(!0),b(Ke),u({type:"summary",sessionId:Re.id,summary:Ke})}catch{h("Failed to restore session result.")}else Re.status==="generating"?(G.current=Re.id,S(!0),Re.thinkingOutput&&w(Re.thinkingOutput),u({type:"loading"}),Ce(Re.id)):Re.status==="error"&&(G.current=Re.id,S(!0),h(null),u({type:"error",sessionId:Re.id,errorMessage:Re.error??"The session encountered an error."}))}).catch(()=>{me||h("Failed to resume session.")}),()=>{me=!0}},[Ce,e,o,d.type,a]),i.useEffect(()=>{if(!e){ee.current&&(Ue(ee.current,T),ee.current=null);return}if(J&&ee.current!==J){ee.current&&Ue(ee.current,T),ge(J,T),ee.current=J;return}!J&&ee.current&&(Ue(ee.current,T),ee.current=null)},[ge,Ue,e,J,T]),i.useEffect(()=>{if(!e||!J||ee.current!==J)return;Z(T);const me=setInterval(()=>{Z(T)},3e4);return()=>{clearInterval(me)}},[Z,e,J,T]),i.useEffect(()=>()=>{F.current?.close(),F.current=null,ee.current&&(Ue(ee.current,T),ee.current=null)},[Ue,T]),i.useEffect(()=>{if(!e)return;const me=Re=>{(d.type==="question"||d.type==="summary")&&(Re.preventDefault(),Re.returnValue=""),F.current?.close()};return window.addEventListener("beforeunload",me),()=>window.removeEventListener("beforeunload",me)},[e,d]);const Pe=i.useCallback(()=>{F.current?.close(),F.current=null,n()},[n]),De=i.useCallback(async()=>{if(l&&JT(l,a),!(y&&!await Q({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,d.type==="question"||d.type==="summary"||d.type==="error")try{await Qf(d.sessionId,a,T)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),w(""),C(!1),I(!1),S(!1),A(!1),ie(void 0),B(void 0),G.current=null,M(null),n()}},[l,y,d,n,a,T,Q]);i.useEffect(()=>{if(!e)return;const me=Re=>{Re.key==="Escape"&&De()};return document.addEventListener("keydown",me),()=>document.removeEventListener("keydown",me)},[e,De]);const dt=i.useCallback(async me=>{if(d.type!=="question")return;const{sessionId:Re}=d;h(null),p(be=>[...be,me]),x(be=>[...be,{question:d.question,response:me}]),u({type:"loading"}),w("");try{Ce(Re),await r1(Re,me,a,T),S(!0)}catch(be){F.current?.close(),F.current=null,h(Me(be)||"Failed to submit response"),u({type:"question",sessionId:Re,question:d.question})}},[d,a,T,Ce]),pt=i.useCallback(async()=>{if(d.type!=="error")return;const me=d.sessionId;h(null),I(!0),w(""),u({type:"loading"}),Ce(me);try{G.current=me,M(me),await o1(me,a,T)}catch(Re){let be=Re;if((Me(Re)||"").includes("not in an error state"))try{const pe=await Ei(me);if(!pe)throw new Error("Failed to refresh interview session.");const Xe=nr(pe.conversationHistory);if(x(Xe),p(Xe.map(wt=>wt.response).filter(wt=>!!(wt&&typeof wt=="object"&&!Array.isArray(wt)))),G.current=pe.id,M(pe.id),S(!0),pe.status==="generating")w(pe.thinkingOutput??""),u({type:"loading"}),F.current?.isConnected()||Ce(pe.id);else if(pe.status==="awaiting_input"){if(!pe.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");Yi(a);const wt=JSON.parse(pe.currentQuestion);u({type:"question",sessionId:pe.id,question:wt}),F.current?.isConnected()||Ce(pe.id)}else if(pe.status==="complete"){if(!pe.result)throw new Error("Interview session is complete but has no result.");Yi(a);const wt=JSON.parse(pe.result);b(wt),u({type:"summary",sessionId:pe.id,summary:wt})}else pe.status==="error"&&u({type:"error",sessionId:pe.id,errorMessage:pe.error??"Retry failed. Please try again."});C(!1);return}catch(pe){be=pe}F.current?.close(),F.current=null,u({type:"error",sessionId:me,errorMessage:Me(be)||"Retry failed. Please try again."}),C(!1)}finally{I(!1)}},[Ce,a,T,d]),lt=i.useCallback(async()=>{if(d.type==="summary"){h(null),A(!0);try{const me=await l1(d.sessionId,v||void 0,a);s(me),Yi(a),F.current?.close(),F.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),w(""),C(!1),I(!1),S(!1),A(!1),G.current=null,M(null),n()}catch(me){h(Me(me)||"Failed to create mission"),A(!1)}}},[d,v,s,n,a]),vt=()=>d.type==="question"?Math.min(f.length+1,6):6,_e=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Fe=J?oe.get(J):null,bt=Fe&&Fe.tabId!==T,ht=!!(bt&&!Fe.stale),Ee=L&&(!bt||Fe.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:me=>me.target===me.currentTarget&&De(),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(Ms,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[_e&&t.jsx("button",{className:"modal-send-to-background",onClick:Pe,title:"Send to background","aria-label":"Send to background",children:t.jsx(uo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:De,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),D&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ht&&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.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(bs,{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:$,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:me=>c(me.target.value),onKeyDown:me=>{me.key==="Enter"&&!me.shiftKey&&l.trim()&&(me.preventDefault(),fe())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:lR.map((me,Re)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(me),children:me.length>45?me.slice(0,45)+"...":me},Re))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",ae&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(ks,{id:"mission-interview-modal-model",label:"Planning Model",value:ce,onChange:me=>{const{provider:Re,modelId:be}=oR(me);ie(Re),B(be)},models:O,disabled:ae,favoriteProviders:He,onToggleFavorite:Ae,favoriteModels:Te,onToggleModelFavorite:Ne}),Ie&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Ie," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{te(!0);const me=await $s();ke(me.models),$e(me.favoriteProviders),ue(me.favoriteModels),Oe(null)}catch(me){Oe(Me(me)||"Failed to load models")}finally{te(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${X&&se?"model-badge-custom":"model-badge-default"}`,children:ye(X,se)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>fe(),disabled:!l.trim(),children:[t.jsx(Ms,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(xt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:E?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>_(!j),type:"button",children:j?"Hide thinking":"Show thinking"}),j&&E&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:E})})]})]}),d.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(ii,{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:d.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void pt(),disabled:P,children:[P?t.jsx(xt,{size:14,className:"spin"}):t.jsx(hs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:P?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:De,disabled:P,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(dR,{question:d.question,progress:vt(),historyEntries:g,onSubmit:dt}),d.type==="summary"&&v&&t.jsx(uR,{summary:v,historyEntries:g,onSummaryChange:b,onApprove:lt,onStartOver:()=>{u({type:"initial"}),S(!1),b(null),p([]),x([]),M(null),F.current?.close(),F.current=null},isCreating:H}),L&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx($l,{size:16}),t.jsx("span",{children:Ee?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ee&&t.jsx("button",{type:"button",onClick:()=>{k()},disabled:K,className:"btn btn-primary session-lock-take-control",children:K?"Taking control...":"Take Control"})]})})]})]})}):null}function dR({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{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(ii,{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(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),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:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.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(Gn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(nn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx(oo,{size:16,className:"icon-ml-4"})]})})]})}function uR({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((N,E)=>E))),[d,u]=i.useState(()=>{const N=new Set;return e.milestones.forEach((E,w)=>{E.slices.forEach((j,_)=>N.add(`${w}-${_}`))}),N}),m=N=>{c(E=>{const w=new Set(E);return w.has(N)?w.delete(N):w.add(N),w})},h=N=>{u(E=>{const w=new Set(E);return w.has(N)?w.delete(N):w.add(N),w})},f=(N,E)=>{const w=[...e.milestones];w[N]={...w[N],...E},s({...e,milestones:w})},p=(N,E,w)=>{const j=[...e.milestones],_=[...j[N].slices];_[E]={..._[E],...w},j[N]={...j[N],slices:_},s({...e,milestones:j})},g=(N,E,w,j)=>{const _=[...e.milestones],D=[..._[N].slices],C=[...D[E].features];C[w]={...C[w],...j},D[E]={...D[E],features:C},_[N]={..._[N],slices:D},s({...e,milestones:_})},x=N=>{const E=e.milestones.filter((w,j)=>j!==N);s({...e,milestones:E})},v=(N,E)=>{const w=[...e.milestones];w[N]={...w[N],slices:w[N].slices.filter((j,_)=>_!==E)},s({...e,milestones:w})},b=(N,E,w)=>{const j=[...e.milestones],_=[...j[N].slices];_[E]={..._[E],features:_[E].features.filter((D,C)=>C!==w)},j[N]={...j[N],slices:_},s({...e,milestones:j})},y=(N,E)=>{const w=[...e.milestones],j=[...w[N].slices];j[E]={...j[E],features:[...j[E].features,{title:"New feature",description:""}]},w[N]={...w[N],slices:j},s({...e,milestones:w})},S=e.milestones.reduce((N,E)=>N+E.slices.reduce((w,j)=>w+j.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(ii,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Gn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:N=>s({...e,missionTitle:N.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:N=>s({...e,missionDescription:N.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((N,E)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(E),children:[l.has(E)?t.jsx(cn,{size:16,className:"icon-text-secondary"}):t.jsx(Un,{size:16,className:"icon-text-secondary"}),t.jsx(ga,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:N.title,onChange:w=>f(E,{title:w.target.value}),onClick:w=>w.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:w=>{w.stopPropagation(),x(E)},title:"Remove milestone",children:t.jsx(En,{size:14,className:"icon-text-secondary"})})]}),l.has(E)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:N.description||"",onChange:w=>f(E,{description:w.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:N.verification||"",onChange:w=>f(E,{verification:w.target.value})})]}),N.slices.map((w,j)=>{const _=`${E}-${j}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(_),children:[d.has(_)?t.jsx(cn,{size:14,className:"icon-text-secondary"}):t.jsx(Un,{size:14,className:"icon-text-secondary"}),t.jsx(xd,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:D=>p(E,j,{title:D.target.value}),onClick:D=>D.stopPropagation()}),N.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:D=>{D.stopPropagation(),v(E,j)},title:"Remove slice",children:t.jsx(En,{size:12,className:"icon-text-secondary"})})]}),d.has(_)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:w.verification||"",onChange:D=>p(E,j,{verification:D.target.value})})]}),w.features.map((D,C)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(dd,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:D.title,onChange:P=>g(E,j,C,{title:P.target.value})}),D.description&&t.jsx("p",{className:"roadmap-feature-text",children:D.description}),D.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",D.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(E,j,C),title:"Remove feature",children:t.jsx(En,{size:12,className:"icon-text-secondary"})})]},C)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(E,j),children:[t.jsx(_n,{size:12}),"Add Feature"]})]})]},j)})]})]},E))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(ka,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}const mR=30,hR=16,pR=16;function fR(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let al=null;function Hb(){return al===null&&(al=window.visualViewport?.height??window.innerHeight),al}function gR(e){const n=Hb();e>n&&(al=e)}function bR(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 mp(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=bR(document.activeElement),s=e.offsetTop;n||gR(e.height);const a=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(a>0&&n)return{overlap:a,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=Hb(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=mR&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=hR&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=pR?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function ra({enabled:e=!0}={}){const[n,s]=i.useState(0),[a,r]=i.useState(null),[o,l]=i.useState(0),[c,d]=i.useState(!1);return i.useEffect(()=>{if(!e||!fR()){s(0),r(null),l(0),d(!1);return}const u=window.visualViewport;if(!u){s(0),r(null),l(0),d(!1);return}const m=()=>{const w=mp();s(w.overlap),r(w.vvHeight),l(w.vvOffsetTop),d(w.open)},h=()=>{const w=mp();s(w.overlap),r(w.vvHeight),d(w.open)},f=[],p=w=>{if(typeof window>"u")return;const j=window.setTimeout(()=>{typeof window>"u"||m()},w);f.push(j)};let g=null,x=0,v=-1,b=0;const y=()=>{g!==null&&typeof window<"u"&&(window.cancelAnimationFrame(g),g=null)},S=()=>{if(typeof window>"u")return;m();const w=window.visualViewport?.offsetTop??0;if(w===v?b+=1:(b=0,v=w),b>=2||performance.now()>x){g=null;return}g=window.requestAnimationFrame(S)},N=()=>{typeof window>"u"||(y(),x=performance.now()+1500,v=-1,b=0,g=window.requestAnimationFrame(S))},E=()=>{m(),p(50),p(200),p(500),p(1e3),p(1500),N()};return E(),u.addEventListener("resize",m),u.addEventListener("scroll",h),document.addEventListener("focusin",E),document.addEventListener("focusout",m),document.addEventListener("visibilitychange",E),window.addEventListener("pageshow",E),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",h),document.removeEventListener("focusin",E),document.removeEventListener("focusout",m),document.removeEventListener("visibilitychange",E),window.removeEventListener("pageshow",E);for(const w of f)clearTimeout(w);y(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function xR({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=Js();pi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=ra({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,v]=i.useState({type:"initial"}),[b,y]=i.useState(null),[S,N]=i.useState([]),[E,w]=i.useState([]),[j,_]=i.useState(null),[D,C]=i.useState(""),[P,I]=i.useState(!0),[H,A]=i.useState(!1),[$,F]=i.useState(!1),G=i.useRef(null),ee=i.useRef(null),J=i.useRef(null),M=i.useRef(null),[T,L]=i.useState(null),k=i.useMemo(()=>Ca(),[]);Jl(e?T:null);const{activeTabMap:K,broadcastUpdate:oe,broadcastCompleted:le,broadcastLock:we,broadcastUnlock:ge,broadcastHeartbeat:Ue}=gr(),Z=a==="milestone"?d1:f1,Q=a==="milestone"?u1:g1,X=a==="milestone"?m1:b1,ie=a==="milestone"?h1:x1,se=a==="milestone"?p1:v1,B=a==="milestone"?"Milestone":"Slice",O=a==="milestone"?"milestone_interview":"slice_interview",ke=i.useCallback(Ce=>{ee.current?.close();const fe=X(Ce,c,{onThinking:Pe=>{C(De=>De+Pe),oe({sessionId:Ce,status:"generating",needsInput:!1,owningTabId:k,type:O,title:o,projectId:c??null})},onQuestion:Pe=>{A(!1),ae(),v({type:"question",sessionId:Ce,question:Pe}),C(""),oe({sessionId:Ce,status:"awaiting_input",needsInput:!0,owningTabId:k,type:O,title:o,projectId:c??null})},onSummary:Pe=>{A(!1),ae(),v({type:"summary",sessionId:Ce,summary:Pe}),_(Pe),C(""),oe({sessionId:Ce,status:"complete",needsInput:!1,owningTabId:k,type:O,title:o,projectId:c??null})},onError:Pe=>{const De=Pe||"Session failed while contacting the AI.";A(!1),y(null),v({type:"error",sessionId:Ce,errorMessage:De}),C(""),J.current=Ce,oe({sessionId:Ce,status:"error",needsInput:!1,owningTabId:k,type:O,title:o,projectId:c??null}),le({sessionId:Ce,status:"error"})},onComplete:()=>{A(!1),J.current=null,le({sessionId:Ce,status:"complete"})},onConnectionStateChange:Pe=>{A(Pe==="reconnecting")}});ee.current=fe},[le,oe,X,O,c,k,o]),ae=()=>{_(null),N([]),w([]),C("")},te=i.useCallback(async()=>{y(null),ae(),A(!1),v({type:"loading"});try{const{sessionId:Ce}=await Z(r,c);J.current=Ce,L(Ce),ke(Ce)}catch(Ce){A(!1),y(Me(Ce)||`Failed to start ${B.toLowerCase()} interview`),v({type:"initial"}),J.current=null,L(null)}},[ke,c,Z,r,B]),Ie=i.useCallback(async()=>{y(null),F(!0);try{await se(r,c),s(),v({type:"applied"})}catch(Ce){y(Me(Ce)||`Failed to skip ${B.toLowerCase()} interview`),F(!1)}},[s,c,se,r,B]);i.useEffect(()=>{e&&x.type==="initial"&&G.current?.focus()},[e,x.type]),i.useEffect(()=>{if(!e||!d||x.type!=="initial")return;let Ce=!1;return Ei(d).then(fe=>{if(Ce||!fe)return;const Pe=nr(fe.conversationHistory);if(w(Pe),L(fe.id),N(Pe.map(De=>De.response).filter(De=>!!(De&&typeof De=="object"&&!Array.isArray(De)))),fe.status==="awaiting_input"&&fe.currentQuestion)try{const De=JSON.parse(fe.currentQuestion);J.current=fe.id,v({type:"question",sessionId:fe.id,question:De})}catch{y("Failed to restore session question.")}else if(fe.status==="complete"&&fe.result)try{const De=JSON.parse(fe.result);J.current=fe.id,_(De),v({type:"summary",sessionId:fe.id,summary:De})}catch{y("Failed to restore session result.")}else fe.status==="generating"?(J.current=fe.id,fe.thinkingOutput&&C(fe.thinkingOutput),v({type:"loading"}),ke(fe.id)):fe.status==="error"&&(J.current=fe.id,y(null),v({type:"error",sessionId:fe.id,errorMessage:fe.error??"The session encountered an error."}))}).catch(()=>{Ce||y("Failed to resume session.")}),()=>{Ce=!0}},[ke,e,d,x.type]),i.useEffect(()=>{e||(A(!1),L(null))},[e]),i.useEffect(()=>{if(!(!e||!T)){if(M.current!==T){M.current&&ge(M.current,k),we(T,k),M.current=T;return}!T&&M.current&&(ge(M.current,k),M.current=null)}},[we,ge,e,T,k]),i.useEffect(()=>{if(!e||!T||M.current!==T)return;Ue(k);const Ce=setInterval(()=>{Ue(k)},3e4);return()=>{clearInterval(Ce)}},[Ue,e,T,k]),i.useEffect(()=>()=>{ee.current?.close(),ee.current=null,M.current&&(ge(M.current,k),M.current=null)},[ge,k]);const Oe=i.useCallback(()=>{ee.current?.close(),ee.current=null,n()},[n]),He=i.useCallback(async()=>{ee.current?.close(),ee.current=null,ae(),v({type:"initial"}),y(null),J.current=null,L(null),n()},[n]),$e=i.useCallback(async Ce=>{if(x.type!=="question")return;const{sessionId:fe}=x;y(null),N(Pe=>[...Pe,Ce]),w(Pe=>[...Pe,{question:x.question,response:Ce}]),v({type:"loading"}),C("");try{ke(fe),await Q(fe,Ce,c,k)}catch(Pe){ee.current?.close(),ee.current=null,y(Me(Pe)||"Failed to submit response"),v({type:"question",sessionId:fe,question:x.question})}},[ke,c,Q,k,x]),Te=i.useCallback(async()=>{if(x.type==="summary"){y(null),F(!0);try{await ie(x.sessionId,j||void 0,c),s(),v({type:"applied"})}catch(Ce){y(Me(Ce)||"Failed to apply interview results"),F(!1)}}},[ie,j,s,c,x]),ue=()=>x.type==="question"?Math.min(S.length+1,6):6,ce=x.type==="loading"||x.type==="question"||x.type==="summary"||x.type==="error",Ae=T?K.get(T):null,ye=!!(Ae&&Ae.tabId!==k&&!Ae.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ce=>Ce.target===Ce.currentTarget&&He(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(bs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",B,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[ce&&t.jsx("button",{className:"modal-send-to-background",onClick:Oe,title:"Send to background","aria-label":"Send to background",children:t.jsx(uo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:He,"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[b&&t.jsx("div",{className:"form-error planning-error",children:b}),H&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ye&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),x.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(bs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",B," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",a,"'s scope, acceptance criteria, and verification methods. Each ",a," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void te(),children:[t.jsx(bs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void Ie(),disabled:$,children:[$?t.jsx(xt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:He,children:"Cancel"})]})]}),x.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(xt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:D?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>I(!P),type:"button",children:P?"Hide thinking":"Show thinking"}),P&&D&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:D})})]})]}),x.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[E.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{entries:E}),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:x.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:He,children:"Cancel"})})]})]})}),x.type==="question"&&t.jsx(vR,{question:x.question,progress:ue(),historyEntries:E,onSubmit:$e}),x.type==="summary"&&j&&t.jsx(yR,{summary:j,historyEntries:E,onSummaryChange:_,onApply:Te,onCancel:He,isApplying:$}),x.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(Gn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[B," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",a,"'s scope and verification have been ",x.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 vR({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{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(ii,{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(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),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:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const x=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:x})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.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(Gn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(nn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx(oo,{size:16,className:"icon-ml-4"})]})})]})}function yR({summary:e,historyEntries:n,onSummaryChange:s,onApply:a,onCancel:r,isApplying:o}){const[l,c]=i.useState(e),[d,u]=i.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(ii,{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:()=>u(!d),"aria-expanded":d,children:[d?t.jsx(cn,{size:16}):t.jsx(Un,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),d&&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:a,disabled:o,children:[o?t.jsx(xt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const hp=300,Uo=220,Bo=560,pp="fusion:mission-sidebar-width",Ar={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)"}},fp={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)"}},gp={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)"}},Ho={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)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"}},qo={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)"}},Vo={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)"}},bp={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)"}},wR=3;function kR(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function xp({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 vp(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const yp={title:"",description:"",status:"planning",autopilotEnabled:!1},qc={title:"",description:"",status:"planning",dependencies:[]},Vc={title:"",description:"",status:"pending"},Wc={title:"",description:"",acceptanceCriteria:"",status:"defined"},jR=3600*1e3;function Nl(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 a=Math.floor(s/(60*1e3));if(a<1)return"just now";if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function NR(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=jR,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 SR(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 CR(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 Kc(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 qb=["feature_triaged","feature_completed"],Vb=["slice_activated","slice_completed","milestone_completed"],Wb=["mission_started","mission_paused","mission_resumed","mission_completed"],Kb=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function wp(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Wb.includes(e);case"tasks":return qb.includes(e);case"slices":return Vb.includes(e);case"autopilot":return Kb.includes(e);default:return!0}}function ER(e){return e==="error"||e==="warning"?"mission-event__type--error":Wb.includes(e)?"mission-event__type--state":qb.includes(e)?"mission-event__type--task":Vb.includes(e)?"mission-event__type--slice":Kb.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function _R(e){return e.replace(/_/g," ")}function MR(e,n){return n?e==="watching"?`Watching since ${Nl(n)}`:`Last activation ${Nl(n)}`:null}function AR({isOpen:e,isInline:n=!1,onClose:s,addToast:a,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:d,milestoneSliceResumeSessionId:u,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=i.useState([]),[g,x]=i.useState(null),[v,b]=i.useState(!0),[y,S]=i.useState(!1),N=Js()==="mobile",[E,w]=i.useState(()=>{if(typeof window>"u")return hp;const U=window.localStorage.getItem(pp),je=U?Number(U):NaN;return Number.isFinite(je)?Math.max(Uo,Math.min(Bo,je)):hp}),j=i.useCallback(U=>{try{window.localStorage.setItem(pp,String(U))}catch{}},[]),_=i.useCallback(U=>{if(N)return;U.preventDefault(),U.stopPropagation();const je=U.currentTarget;typeof je.setPointerCapture=="function"&&je.setPointerCapture(U.pointerId);const Be=U.clientX,jt=E;let hn=jt;document.body.style.userSelect="none";const Xt=tt=>{const nt=tt.clientX-Be,Dt=Math.max(Uo,Math.min(Bo,jt+nt));hn=Dt,w(Dt)},Pn=tt=>{typeof je.releasePointerCapture=="function"&&je.releasePointerCapture(tt.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Xt),document.removeEventListener("pointerup",Pn),j(hn)};document.addEventListener("pointermove",Xt),document.addEventListener("pointerup",Pn)},[N,j,E]),D=i.useCallback(U=>{if(N||U.key!=="ArrowLeft"&&U.key!=="ArrowRight")return;U.preventDefault();const je=U.shiftKey?50:10,Be=U.key==="ArrowLeft"?-je:je,jt=Math.max(Uo,Math.min(Bo,E+Be));w(jt),j(jt)},[N,j,E]),[C,P]=i.useState(!1),[I,H]=i.useState(null),[A,$]=i.useState(yp),[F,G]=i.useState(!1),[ee,J]=i.useState(new Set),[M,T]=i.useState(new Set),[L,k]=i.useState(null),[K,oe]=i.useState(qc),[le,we]=i.useState(!1),[ge,Ue]=i.useState(null),[Z,Q]=i.useState(Vc),[X,ie]=i.useState(!1),[se,B]=i.useState(null),[O,ke]=i.useState(null),[ae,te]=i.useState(Wc),[Ie,Oe]=i.useState(!1),[He,$e]=i.useState(null),[Te,ue]=i.useState(null),[ce,Ae]=i.useState(""),[Ne,ye]=i.useState(!1),[Ce,fe]=i.useState([]),[Pe,De]=i.useState(void 0),dt=Pe??c,[pt,lt]=i.useState(null),[vt,_e]=i.useState(null),[Fe,bt]=i.useState(null);i.useEffect(()=>{h&&dt&&ye(!0)},[h,dt]),i.useEffect(()=>{if(!h||dt)return;let U=!1;return su(r).then(je=>{if(U)return;const Be=je.filter(jt=>jt.type==="mission_interview"&&(jt.status==="awaiting_input"||jt.status==="error"));fe(Be)}).catch(je=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",je)}),()=>{U=!0}},[h,r,dt]),i.useEffect(()=>{if(!h||!u)return;let U=!1;return Ei(u).then(je=>{if(!(U||!je))try{const Be=JSON.parse(je.inputPayload||"{}");Be.targetId&&Be.targetType&<({type:Be.targetType,id:Be.targetId,title:Be.targetTitle||je.title,resumeSessionId:u})}catch{lt({type:"milestone",id:"",title:je.title,resumeSessionId:u})}}).catch(je=>{U||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",je),m?.())}),()=>{U=!0}},[h,u,m]);const[ht,Ee]=i.useState(null),[me,Re]=i.useState(new Map),[be,Ke]=i.useState(null),[pe,Xe]=i.useState({title:"",assertion:"",status:"pending"}),[wt,gt]=i.useState(!1),[Tt,Zt]=i.useState(null),[Ot,Rt]=i.useState(new Map),[en,zt]=i.useState(new Set),[Qt,xn]=i.useState(new Set),[Kt,Ut]=i.useState(null),[fn,un]=i.useState(new Map),[tn,Vt]=i.useState(null),[mn,xe]=i.useState(null),[Le,Ve]=i.useState(!0),[at,Ge]=i.useState(new Set),[Ft,_t]=i.useState(new Map),[qt,St]=i.useState(null),[z,he]=i.useState(new Map),[st,It]=i.useState(null),[ve,ot]=i.useState(new Map),[Nt,Lt]=i.useState(new Map),[$t,Wt]=i.useState("structure"),[Gt,sn]=i.useState([]),on=i.useRef([]),Dn=i.useRef([]),Jt=i.useRef(null),Hn=i.useRef(null),Yn=i.useRef("structure"),re=i.useRef("all"),[rt,ct]=i.useState(!1),[ft,it]=i.useState(0),[Y,Ye]=i.useState("all"),[Yt,In]=i.useState(new Set),cs=i.useRef(null),gn=i.useRef(null);Dn.current=f,Jt.current=g,Hn.current=tn,Yn.current=$t,re.current=Y;const Nn=i.useCallback((U="auto")=>{const je=gn.current;if(je&&typeof je.scrollIntoView=="function"){je.scrollIntoView({block:"end",behavior:U});return}const Be=cs.current;Be&&(Be.scrollTop=Be.scrollHeight)},[]),ms=i.useCallback(()=>{const U=cs.current;return U?U.scrollHeight-U.scrollTop-U.clientHeight<=100:!0},[]),vn=i.useCallback(async U=>{if(U.length===0){Lt(new Map);return}const je=await TN(r);Lt(Be=>{const jt=new Map(Be);for(const[hn,Xt]of Object.entries(je))SR(Xt)&&jt.set(hn,Xt);return jt})},[r]),bn=i.useCallback(async()=>{try{b(!0);const U=await EN(r);p(U),vn(U)}catch(U){a(Me(U)||"Failed to load missions","error")}finally{b(!1)}},[a,r,vn]),Pt=i.useCallback(async U=>{try{S(!0);const je=await Yf(U,r);if(!je||!Array.isArray(je.milestones)){S(!1);return}if(x(je),je.milestones.length>0){const Be=je.milestones[0].id;Vt(Be),Ve(!0),J(new Set([Be])),nc(Be,r).then(jt=>{Re(hn=>{const Xt=new Map(hn);return Xt.set(Be,jt),Xt})}).catch(()=>{}),sc(Be,r).then(jt=>{un(hn=>{const Xt=new Map(hn);return Xt.set(Be,jt),Xt})}).catch(()=>{}),je.milestones[0].slices.length>0&&T(new Set([je.milestones[0].slices[0].id]))}else Vt(null),xe(null)}catch(je){a(Me(je)||"Failed to load mission details","error")}finally{S(!1)}},[a,r]);i.useEffect(()=>{if(!h||!tn){xe(null);return}let U=!1;return xe(null),rm(tn,r).then(je=>{if(!U){if(!Kc(je)){xe(null);return}xe(je),un(Be=>{const jt=new Map(Be);return jt.set(tn,je.rollup),jt})}}).catch(()=>{U||xe(null)}),()=>{U=!0}},[h,tn,r]),i.useEffect(()=>{Ve(!0)},[tn]);const Qn=i.useCallback(U=>{!U||U!==Hn.current||rm(U,r).then(je=>{Hn.current!==U||!Kc(je)||(xe(je),un(Be=>{const jt=new Map(Be);return jt.set(U,je.rollup),jt}))}).catch(()=>{})},[r]),es=i.useCallback(async(U,je)=>{const Be=je?.append??!1,jt=Be?on.current.length:0;Be||(ct(!0),In(new Set));try{const hn=await PN(U,{limit:50,offset:jt,eventType:void 0},r),Xt=hn.events.filter(Pn=>wp(Pn.eventType,Y));sn(Pn=>{if(!Be)return on.current=Xt,Xt;const tt=new Set(Pn.map(Dt=>Dt.id)),nt=[...Pn];for(const Dt of Xt)tt.has(Dt.id)||nt.push(Dt);return on.current=nt,nt}),it(hn.total),Be||requestAnimationFrame(()=>{Nn("auto")})}catch(hn){a(Me(hn)||"Failed to load mission activity","error")}finally{Be||ct(!1)}},[a,Y,r,Nn]);i.useEffect(()=>{on.current=Gt},[Gt]),i.useEffect(()=>{h&&(bn(),x(null),Vt(null),xe(null),sn([]),it(0),Wt("structure"),Ye("all"),In(new Set))},[h,bn]);const W=i.useRef(null);i.useEffect(()=>{h&&d&&W.current!==d&&f.length>0&&(W.current=d,Pt(d))},[h,d,f,Pt]),i.useEffect(()=>{h||(W.current=null)},[h]);const qe=i.useRef(!1);i.useEffect(()=>{!h||!n||N||v||qe.current||g||d||f.length!==0&&(qe.current=!0,Pt(f[0].id))},[h,n,N,v,f,g,d,Pt]),i.useEffect(()=>{h||(qe.current=!1)},[h]),i.useEffect(()=>{!h||!g||$t!=="activity"||es(g.id)},[$t,h,es,g,Y]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const U=new URLSearchParams;r&&U.set("projectId",r);const je=`/api/events${U.size>0?`?${U.toString()}`:""}`,Be=()=>{vn(Dn.current)},jt=rs=>{Be();const Zn=rs;if(Zn.data)try{const dn=JSON.parse(Zn.data);dn?.id&&p(Gi=>Gi.map(Ls=>Ls.id===dn.id?{...Ls,...dn}:Ls))}catch{}Jt.current&&Pt(Jt.current.id)},hn=rs=>{Be(),Jt.current&&Pt(Jt.current.id)},Xt=()=>{Be(),Jt.current&&Pt(Jt.current.id)},Pn=rs=>{Be(),Jt.current&&Pt(Jt.current.id)},tt=rs=>{const Zn=rs;if(Zn.data)try{const dn=JSON.parse(Zn.data);dn&&dn.featureId&&(ri(dn.featureId),gi(dn.featureId),dn.milestoneId&&Qn(dn.milestoneId))}catch{}},nt=rs=>{const Zn=rs;if(Zn.data)try{const dn=JSON.parse(Zn.data);dn&&dn.featureId&&(ri(dn.featureId),gi(dn.featureId),dn.milestoneId&&Qn(dn.milestoneId),Jt.current&&Pt(Jt.current.id))}catch{}},Dt=rs=>{const Zn=rs;if(Zn.data)try{const dn=JSON.parse(Zn.data);dn&&dn.milestoneId&&(Xn(dn.milestoneId),Qn(dn.milestoneId))}catch{}},Tn=rs=>{const Zn=rs;if(Zn.data)try{const dn=JSON.parse(Zn.data);dn&&dn.milestoneId&&(wn(dn.milestoneId),Xn(dn.milestoneId),Qn(dn.milestoneId))}catch{}};return ai(je,{events:{"mission:updated":jt,"slice:updated":hn,"feature:updated":Xt,"milestone:updated":Pn,"mission:event":rs=>{Be();const Zn=Jt.current;if(!Zn||Yn.current!=="activity")return;const dn=ms(),Gi=rs;if(Gi.data)try{const Ls=JSON.parse(Gi.data);if(!CR(Ls)||Ls.missionId!==Zn.id||!wp(Ls.eventType,re.current))return;sn(Hs=>{const vi=Hs.filter(yi=>yi.id!==Ls.id);return[Ls,...vi].slice(0,100)}),it(Hs=>Hs+1),dn&&requestAnimationFrame(()=>{const Hs=cs.current;Hs&&(Hs.scrollTop=0)})}catch{}},"validator-run:started":tt,"validator-run:completed":nt,"milestone:validation:updated":Dt,"assertion:created":Tn,"assertion:updated":Tn,"assertion:deleted":Tn,"assertion:linked":Tn,"assertion:unlinked":Tn,"fix-feature:created":rs=>{const Zn=rs;if(Zn.data)try{const dn=JSON.parse(Zn.data);if(dn&&dn.sourceFeatureId){ri(dn.sourceFeatureId);const Gi=dn?.feature?.sliceId,Ls=Jt.current;if(Gi&&Ls){const Hs=Ls.milestones.find(vi=>vi.slices.some(yi=>yi.id===Gi));Hs&&Qn(Hs.id)}Jt.current&&Pt(Jt.current.id)}}catch{}}}})},[h,ms,Pt,vn,r,Qn]);const Je=i.useCallback(U=>{H(U.id),P(!1),$({title:U.title,description:U.description||"",status:U.status,autopilotEnabled:U.autopilotEnabled??!1})},[]),ut=i.useCallback(()=>{H(null),P(!1),$(yp)},[]),Ct=i.useCallback(async()=>{if(!A.title.trim()){a("Mission title is required","error");return}try{if(G(!0),C)await _N({title:A.title.trim(),description:A.description.trim()||void 0,autopilotEnabled:A.autopilotEnabled},r),a("Mission created","success");else if(I){const U={title:A.title.trim(),description:A.description.trim()||void 0,status:A.status,autopilotEnabled:A.autopilotEnabled};A.autopilotEnabled&&(U.autoAdvance=!0),await MN(I,U,r),a("Mission updated","success"),g?.id===I&&await Pt(I)}await bn(),ut()}catch(U){a(Me(U)||"Failed to save mission","error")}finally{G(!1)}},[A,C,I,a,bn,Pt,g,ut,r]),Mt=i.useCallback(async U=>{try{await AN(U,r),a("Mission deleted","success"),g?.id===U&&x(null),await bn(),Ee(null)}catch(je){a(Me(je)||"Failed to delete mission","error")}},[a,bn,g,r]),an=i.useCallback(()=>{we(!0),k(null),oe(qc)},[]),An=i.useCallback(U=>{k(U.id),we(!1),oe({title:U.title,description:U.description||"",status:U.status,dependencies:U.dependencies})},[]),Sn=i.useCallback(()=>{k(null),we(!1),oe(qc)},[]),ps=i.useCallback(async()=>{if(!K.title.trim()){a("Milestone title is required","error");return}try{G(!0),le&&g?(await RN(g.id,{title:K.title.trim(),description:K.description.trim()||void 0,dependencies:K.dependencies},r),a("Milestone created","success")):L&&(await IN(L,{title:K.title.trim(),description:K.description.trim()||void 0,status:K.status,dependencies:K.dependencies},r),a("Milestone updated","success")),await Pt(g.id),Sn()}catch(U){a(Me(U)||"Failed to save milestone","error")}finally{G(!1)}},[K,le,L,g,a,Pt,Sn,A.title,r]),ts=i.useCallback(async U=>{try{await $N(U,r),a("Milestone deleted","success"),await Pt(g.id),Ee(null)}catch(je){a(Me(je)||"Failed to delete milestone","error")}},[a,Pt,g,r]),Bs=i.useCallback(U=>{Vt(U),Ve(!0),J(je=>{const Be=new Set(je);return!Be.has(U)?(Be.add(U),nc(U,r).then(hn=>{Re(Xt=>{const Pn=new Map(Xt);return Pn.set(U,hn),Pn})}).catch(()=>{}),sc(U,r).then(hn=>{un(Xt=>{const Pn=new Map(Xt);return Pn.set(U,hn),Pn})}).catch(()=>{})):Be.delete(U),Be})},[r]),Hi=i.useCallback(U=>{B(U),ie(!0),Ue(null),Q(Vc)},[]),fi=i.useCallback(U=>{Ue(U.id),ie(!1),Q({title:U.title,description:U.description||"",status:U.status})},[]),de=i.useCallback(()=>{Ue(null),ie(!1),B(null),Q(Vc)},[]),We=i.useCallback(async()=>{if(!Z.title.trim()){a("Slice title is required","error");return}try{G(!0),X&&se?(await DN(se,{title:Z.title.trim(),description:Z.description.trim()||void 0},r),a("Slice created","success")):ge&&(await LN(ge,{title:Z.title.trim(),description:Z.description.trim()||void 0,status:Z.status},r),a("Slice updated","success")),await Pt(g.id),de()}catch(U){a(Me(U)||"Failed to save slice","error")}finally{G(!1)}},[Z,X,ge,se,g,a,Pt,de,r]),mt=i.useCallback(async U=>{try{await ON(U,r),a("Slice deleted","success"),await Pt(g.id),Ee(null)}catch(je){a(Me(je)||"Failed to delete slice","error")}},[a,Pt,g,r]),q=i.useCallback(async U=>{try{await FN(U,r),a("Slice activated","success"),await Pt(g.id)}catch(je){a(Me(je)||"Failed to activate slice","error")}},[a,Pt,g,r]),Se=i.useCallback(U=>{T(je=>{const Be=new Set(je);return Be.has(U)?Be.delete(U):Be.add(U),Be})},[]),Ze=i.useCallback(U=>{$e(U),Oe(!0),ke(null),te(Wc)},[]),At=i.useCallback(U=>{ke(U.id),Oe(!1),te({title:U.title,description:U.description||"",acceptanceCriteria:U.acceptanceCriteria||"",status:U.status})},[]),Et=i.useCallback(()=>{ke(null),Oe(!1),$e(null),te(Wc)},[]),Cn=i.useCallback(async()=>{if(!ae.title.trim()){a("Feature title is required","error");return}try{G(!0),Ie&&He?(await zN(He,{title:ae.title.trim(),description:ae.description.trim()||void 0,acceptanceCriteria:ae.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):O&&(await UN(O,{title:ae.title.trim(),description:ae.description.trim()||void 0,acceptanceCriteria:ae.acceptanceCriteria.trim()||void 0,status:ae.status},r),a("Feature updated","success")),await Pt(g.id),Et()}catch(U){a(Me(U)||"Failed to save feature","error")}finally{G(!1)}},[ae,Ie,O,He,g,a,Pt,Et,r]),rn=i.useCallback(async U=>{try{await BN(U,r),a("Feature deleted","success"),await Pt(g.id),Ee(null)}catch(je){a(Me(je)||"Failed to delete feature","error")}},[a,Pt,g,r]),yn=i.useCallback(async()=>{if(!Te||!ce.trim()){a("Task ID is required","error");return}try{await HN(Te,ce.trim(),r),a("Feature linked to task","success"),await Pt(g.id),ue(null),Ae("")}catch(U){a(Me(U)||"Failed to link feature to task","error")}},[Te,ce,a,Pt,g,r]),kn=i.useCallback(async U=>{try{await qN(U,r),a("Feature unlinked from task","success"),await Pt(g.id)}catch(je){a(Me(je)||"Failed to unlink feature","error")}},[a,Pt,g,r]),Ln=i.useCallback(async U=>{try{G(!0),await VN(U,void 0,void 0,r),a("Feature triaged — task created","success"),await Pt(g.id)}catch(je){a(Me(je)||"Failed to triage feature","error")}finally{G(!1)}},[a,Pt,g,r]),is=i.useCallback(async U=>{bt(U);try{const je=await y1(U,r);_e({featureId:U,enrichedDescription:je.description})}catch{await Ln(U)}finally{bt(null)}},[Ln,r]),fs=i.useCallback(async()=>{vt&&(_e(null),await Ln(vt.featureId))},[Ln,vt]),On=i.useCallback(()=>{_e(null)},[]),qn=i.useCallback(async U=>{try{G(!0);const je=await WN(U,r);a(`Triaged ${je.count} feature${je.count!==1?"s":""}`,"success"),await Pt(g.id)}catch(je){a(Me(je)||"Failed to triage slice features","error")}finally{G(!1)}},[a,Pt,g,r]),wn=i.useCallback(async U=>{try{const je=await nc(U,r);Re(Be=>{const jt=new Map(Be);return jt.set(U,je),jt})}catch{}},[r]),Xn=i.useCallback(async U=>{try{const je=await sc(U,r);un(Be=>{const jt=new Map(Be);return jt.set(U,je),jt})}catch{}},[r]),Vn=i.useCallback(async U=>{if(!pe.title.trim()||!pe.assertion.trim()){a("Title and assertion text are required","error");return}try{G(!0),await KN(U,{title:pe.title.trim(),assertion:pe.assertion.trim(),status:pe.status},r),a("Assertion created","success"),await wn(U),await Xn(U),gt(!1),Xe({title:"",assertion:"",status:"pending"})}catch(je){a(Me(je)||"Failed to create assertion","error")}finally{G(!1)}},[pe,a,wn,Xn,r]),as=i.useCallback(U=>{Ke(U.id),Xe({title:U.title,assertion:U.assertion,status:U.status})},[]),Fn=i.useCallback(()=>{Ke(null),gt(!1),Xe({title:"",assertion:"",status:"pending"})},[]),ys=i.useCallback(async(U,je)=>{if(!pe.title.trim()||!pe.assertion.trim()){a("Title and assertion text are required","error");return}try{G(!0),await GN(U,{title:pe.title.trim(),assertion:pe.assertion.trim(),status:pe.status},r),a("Assertion updated","success"),await wn(je),await Xn(je),Fn()}catch(Be){a(Me(Be)||"Failed to update assertion","error")}finally{G(!1)}},[pe,a,wn,Xn,Fn,r]),Wn=i.useCallback(async U=>{try{const je=await QN(U,r);Rt(Be=>{const jt=new Map(Be);return jt.set(U,je),jt})}catch{}},[r]),ns=i.useCallback(async U=>{const je=Tt!==U;Zt(Be=>Be===U?null:U),je&&await Wn(U)},[Tt,Wn]),js=i.useCallback(U=>{Zt(U),Wn(U),requestAnimationFrame(()=>{const je=document.querySelector(`[data-mission-assertion-id="${U}"]`);je instanceof HTMLElement&&typeof je.scrollIntoView=="function"&&je.scrollIntoView({behavior:"smooth",block:"center"})})},[Wn]),Ds=i.useCallback(async(U,je)=>{try{zt(Be=>new Set(Be).add(je)),await JN(U,je,r),a("Feature linked to assertion","success"),await Wn(je),Ut(null)}catch(Be){a(Me(Be)||"Failed to link feature","error")}finally{zt(Be=>{const jt=new Set(Be);return jt.delete(je),jt})}},[a,Wn,r]),qi=i.useCallback(async(U,je)=>{const Be=`${U}-${je}`;try{xn(jt=>new Set(jt).add(Be)),await YN(U,je,r),a("Feature unlinked from assertion","success"),await Wn(je)}catch(jt){a(Me(jt)||"Failed to unlink feature","error")}finally{xn(jt=>{const hn=new Set(jt);return hn.delete(Be),hn})}},[a,Wn,r]),br=i.useCallback(async U=>{try{Ge(Be=>new Set(Be).add(U)),await XN(U,r),a("Validation triggered","success");const je=await om(U,r);_t(Be=>{const jt=new Map(Be);return jt.set(U,je),jt})}catch(je){a(Me(je)||"Failed to trigger validation","error")}finally{Ge(je=>{const Be=new Set(je);return Be.delete(U),Be})}},[a,r]),ri=i.useCallback(async U=>{try{const je=await om(U,r);_t(Be=>{const jt=new Map(Be);return jt.set(U,je),jt})}catch{}},[r]),gi=i.useCallback(async U=>{try{const je=await ZN(U,{limit:10},r);he(Be=>{const jt=new Map(Be);return jt.set(U,je),jt})}catch{}},[r]),Vi=i.useCallback(U=>{const je=Jt.current;if(je){for(const Be of je.milestones)for(const jt of Be.slices)if(jt.features.find(Xt=>Xt.id===U)){J(Xt=>{const Pn=new Set(Xt);return Pn.add(Be.id),Pn}),T(Xt=>{const Pn=new Set(Xt);return Pn.add(jt.id),Pn}),St(U),Vt(Be.id),ri(U),gi(U),requestAnimationFrame(()=>{const Xt=document.querySelector(`[data-mission-feature-id="${U}"]`);Xt instanceof HTMLElement&&typeof Xt.scrollIntoView=="function"&&Xt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[ri,gi]),Ii=i.useCallback(async U=>{try{const je=await e1(U,r);ot(Be=>{const jt=new Map(Be);return jt.set(U,je),jt})}catch{}},[r]),Ea=i.useCallback(async U=>{qt===U?St(null):(St(U),await ri(U),await gi(U))},[qt,ri,gi]),_a=i.useCallback(async U=>{st===U?It(null):(It(U),await Ii(U))},[st,Ii]),Ma=i.useCallback(async U=>{try{await t1(U,r),a("Mission resumed","success"),await Pt(U),bn()}catch(je){a(Me(je)||"Failed to resume mission","error")}},[a,Pt,bn,r]),bi=i.useCallback(async U=>{try{const Be=(await n1(U,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Be} task${Be!==1?"s":""} paused)`,"success"),await Pt(U),bn()}catch(je){a(Me(je)||"Failed to stop mission","error")}},[a,Pt,bn,r]),Wi=i.useCallback(async U=>{try{await s1(U,r),a("Mission started — first slice activated","success"),await Pt(U),bn()}catch(je){a(Me(je)||"Failed to start mission","error")}},[a,Pt,bn,r]),oa=i.useCallback(async(U,je)=>{try{await i1(U,{enabled:je},r),a(je?"Autopilot enabled":"Autopilot disabled","success"),await Pt(U),bn()}catch(Be){a(Me(Be)||"Failed to update autopilot","error")}},[a,Pt,bn,r]),Aa=i.useCallback(U=>{Wt("structure"),Vt(null),xe(null),sn([]),it(0),Ye("all"),In(new Set),Pt(U.id)},[Pt]),Pa=i.useCallback(()=>{x(null),Vt(null),xe(null),Wt("structure"),sn([]),it(0),Ye("all"),In(new Set),bn()},[bn]),Ki=Gt.length<ft,Qs=g?.autopilotState??"inactive",Ta=Qs==="watching"||Qs==="activating",et=MR(Qs,g?.lastAutopilotActivityAt),Bt=i.useMemo(()=>!mn||!tn||!Kc(mn)?null:mn.rollup.milestoneId===tn?mn:null,[tn,mn]),Mn=i.useMemo(()=>{const U=new Map;for(const je of Bt?.validationTelemetry.validationRounds??[]){const Be=U.get(je.featureId);(!Be||je.startedAt>Be.startedAt)&&U.set(je.featureId,je)}return U},[Bt]),xi=i.useCallback(()=>{!g||rt||!Ki||es(g.id,{append:!0})},[rt,Ki,es,g]),Ns=i.useCallback(U=>{In(je=>{const Be=new Set(je);return Be.has(U)?Be.delete(U):Be.add(U),Be})},[]),Ra=i.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),Ct())},[Ct]),xr=i.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),ps())},[ps]),vr=i.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),We())},[We]),la=i.useCallback(U=>{U.key==="Enter"&&!U.shiftKey&&(U.preventDefault(),Cn())},[Cn]),Yl=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const U=je=>{je.key==="Escape"&&s()};return document.addEventListener("keydown",U),()=>document.removeEventListener("keydown",U)},[h,s]),!h)return null;const Ia=()=>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:[Ta&&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:(Ar[g.status]||Ar.planning).bg,color:(Ar[g.status]||Ar.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:U=>oa(g.id,U.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(us,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(qo[Qs]||qo.inactive).bg,color:(qo[Qs]||qo.inactive).text},"data-testid":"autopilot-state-badge",children:[Ta&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Qs]})]}),et&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:et})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>bi(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Si,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ma(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(ls,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Wi(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(ls,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Je(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ee({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(En,{size:14})})]})]}),I===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:U=>$({...A,title:U.target.value}),onKeyDown:Ra,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:U=>$({...A,description:U.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:A.status,onChange:U=>$({...A,status:U.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:A.autopilotEnabled,onChange:U=>$({...A,autopilotEnabled:U.target.checked})}),t.jsx(us,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ct,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ut,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${$t==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Wt("structure"),role:"tab","aria-selected":$t==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${$t==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Wt("activity"),role:"tab","aria-selected":$t==="activity","data-testid":"mission-tab-activity",children:["Activity (",ft,")"]})]}),$t==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(U=>{const je=Bt?.rollup.milestoneId===U.id?Bt:null,Be=je?.rollup??fn.get(U.id),jt=je?.validationTelemetry.validationRounds??[],hn=je?.fixFeatures??[],Xt=bp[Be?.state??"not_started"]??bp.not_started,Pn=Be&&(Be.state==="blocked"||Be.state==="failed")?je?.validationTelemetry.validationRounds.find(tt=>tt.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Bs(U.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:ee.has(U.id)?t.jsx(cn,{size:16}):t.jsx(Un,{size:16})}),t.jsx(ga,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:U.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:fp[U.status].bg,color:fp[U.status].text},children:U.status}),t.jsxs("span",{className:"mission-milestone__count",children:[U.slices.length," slices"]}),t.jsx(xp,{state:kR(U.interviewState)}),Be&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Xt.bg,color:Xt.text},title:"Validation state",children:vp(Be.state)}),Be.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Be.passedAssertions??0} of ${Be.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Be.passedAssertions??0)/Be.totalAssertions*100}%`,backgroundColor:(Be.passedAssertions??0)===Be.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),U.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>lt({type:"milestone",id:U.id,title:U.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(na,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:tt=>tt.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Hi(U.id),title:"Add slice",children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>An(U),title:"Edit milestone",children:t.jsx(Ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ee({type:"milestone",id:U.id}),title:"Delete milestone",children:t.jsx(En,{size:14})})]})]}),ee.has(U.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(le||L===U.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:K.title,onChange:tt=>oe({...K,title:tt.target.value}),onKeyDown:xr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:tt=>oe({...K,description:tt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ps,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),L?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Sn,children:"Cancel"})]})]}),je&&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:[je.validationTelemetry.totalRuns," rounds",je.validationTelemetry.lastValidatorStatus?` · Last ${je.validationTelemetry.lastValidatorStatus}`:""]})]}),Pn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Pn]}),jt.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:()=>Ve(tt=>!tt),title:Le?"Hide validation rounds":"Show validation rounds",children:[Le?t.jsx(cn,{size:12}):t.jsx(Un,{size:12}),"Validation rounds (",jt.length,")"]}),Le&&t.jsx("div",{className:"mission-validation-rounds__list",children:jt.map(tt=>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--${tt.validatorStatus}`,children:tt.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:tt.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",tt.implementationAttempt," · reviewer #",tt.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),tt.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:tt.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>js(nt),title:`Jump to assertion ${nt}`,children:nt},`${tt.roundId}-${nt}`))}):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:"}),tt.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:tt.generatedFixFeatureIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Vi(nt),title:`Jump to fix feature ${nt}`,children:nt},`${tt.roundId}-${nt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),tt.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:tt.blockedReason})]},tt.roundId))})]}),hn.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:hn.map(tt=>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:()=>Vi(tt.id),title:`Jump to feature ${tt.id}`,children:tt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ho[tt.status].bg,color:Ho[tt.status].text},children:tt.status}),tt.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${tt.loopState}`,children:tt.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:()=>Vi(tt.sourceFeatureId),title:`Jump to source feature ${tt.sourceFeatureId}`,children:tt.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:tt.runId})]}),tt.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:tt.failedAssertionIds.map(nt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>js(nt),title:`Jump to assertion ${nt}`,children:nt},`${tt.id}-${nt}`))})]})]},tt.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[U.slices.map(tt=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Se(tt.id),children:[t.jsx("button",{className:"mission-slice__expand",children:M.has(tt.id)?t.jsx(cn,{size:16}):t.jsx(Un,{size:16})}),t.jsx(xd,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:tt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:gp[tt.status].bg,color:gp[tt.status].text},children:tt.status}),t.jsxs("span",{className:"mission-slice__count",children:[tt.features?.length||0," features"]}),t.jsx(xp,{state:tt.planState??"not_started"}),tt.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>lt({type:"slice",id:tt.id,title:tt.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(na,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:nt=>nt.stopPropagation(),children:[tt.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>q(tt.id),title:"Activate slice",children:t.jsx(ls,{size:14})}),tt.status==="active"&&tt.features?.some(nt=>nt.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>qn(tt.id),title:"Triage all features",disabled:F,children:F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(us,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ze(tt.id),title:"Add feature",children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>fi(tt),title:"Edit slice",children:t.jsx(Ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ee({type:"slice",id:tt.id}),title:"Delete slice",children:t.jsx(En,{size:14})})]})]}),M.has(tt.id)&&t.jsxs("div",{className:"mission-slice__body",children:[X&&se===U.id&&!ge&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:Z.title,onChange:nt=>Q({...Z,title:nt.target.value}),onKeyDown:vr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Z.description,onChange:nt=>Q({...Z,description:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:We,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:de,children:"Cancel"})]})]}),ge===tt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:Z.title,onChange:nt=>Q({...Z,title:nt.target.value}),onKeyDown:vr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Z.description,onChange:nt=>Q({...Z,description:nt.target.value}),rows:2}),t.jsxs("select",{value:Z.status,onChange:nt=>Q({...Z,status:nt.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:We,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:de,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[tt.features?.map(nt=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":nt.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Ea(nt.id),title:qt===nt.id?"Collapse details":"Expand to show run history",children:qt===nt.id?t.jsx(cn,{size:14}):t.jsx(Un,{size:14})}),t.jsx(dd,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:nt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Ho[nt.status].bg,color:Ho[nt.status].text},children:nt.status}),nt.loopState&&nt.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${nt.loopState}`,title:`Loop state: ${nt.loopState}`,children:[nt.loopState==="implementing"&&"⏳",nt.loopState==="validating"&&"🔄",nt.loopState==="needs_fix"&&"🔧",nt.loopState==="passed"&&"✅",nt.loopState==="blocked"&&"🚫"]}),nt.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Vi(nt.generatedFromFeatureId),title:`Generated from feature: ${nt.generatedFromFeatureId}`,children:"🔗 Fix"}),(nt.loopState==="validating"||nt.loopState==="needs_fix")&&(()=>{const Dt=Ft.get(nt.id),Tn=Mn.get(nt.id),Xs=Dt?.implementationAttemptCount??Tn?.implementationAttempt??nt.implementationAttemptCount??0,Zs=Dt?.retryBudgetRemaining??Math.max(0,wR-Xs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Xs," · ",Zs," ",Zs===1?"retry":"retries"," left"]})})(),nt.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>br(nt.id),title:"Validate feature",disabled:at.has(nt.id),children:at.has(nt.id)?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(bs,{size:14})}),nt.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(nt.taskId),title:"Click to view task",children:nt.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[nt.status==="defined"&&!nt.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>is(nt.id),title:"Triage — create task",disabled:F||Fe===nt.id,children:Fe===nt.id?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(us,{size:14})}),nt.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>kn(nt.id),title:"Unlink task",children:t.jsx(Du,{size:14})}):nt.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>ue(nt.id),title:"Link to task",children:t.jsx(Qa,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>At(nt),title:"Edit feature",children:t.jsx(Ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ee({type:"feature",id:nt.id}),title:"Delete feature",children:t.jsx(En,{size:14})})]})]}),nt.description&&t.jsx("p",{className:"mission-feature__description",children:nt.description}),nt.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",nt.acceptanceCriteria]}),vt?.featureId===nt.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:vt.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:fs,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:On,disabled:F,children:"Cancel"})]})]}),O===nt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ae.title,onChange:Dt=>te({...ae,title:Dt.target.value}),onKeyDown:la,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ae.description,onChange:Dt=>te({...ae,description:Dt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ae.acceptanceCriteria,onChange:Dt=>te({...ae,acceptanceCriteria:Dt.target.value}),rows:2}),t.jsxs("select",{value:ae.status,onChange:Dt=>te({...ae,status:Dt.target.value}),children:[t.jsx("option",{value:"defined",children:"Defined"}),t.jsx("option",{value:"triaged",children:"Triaged"}),t.jsx("option",{value:"in-progress",children:"In Progress"}),t.jsx("option",{value:"done",children:"Done"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Et,children:"Cancel"})]})]}),qt===nt.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"})}),(z.get(nt.id)??[]).map(Dt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>_a(Dt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Dt.status}`,title:Dt.status,children:Dt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Dt.startedAt).toLocaleString()}),Dt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Dt.completedAt).getTime()-new Date(Dt.startedAt).getTime())/1e3),"s"]}),Dt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Dt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:st===Dt.id?"Hide details":"Show details",children:st===Dt.id?t.jsx(cn,{size:12}):t.jsx(Un,{size:12})})]}),st===Dt.id&&ve.get(Dt.id)&&t.jsxs("div",{className:"mission-run__details",children:[Dt.summary&&t.jsx("p",{className:"mission-run__summary",children:Dt.summary}),Dt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Dt.blockedReason]}),ve.get(Dt.id)?.failures&&ve.get(Dt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),ve.get(Dt.id).failures.map(Tn=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Tn.message}),Tn.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Tn.expected]}),Tn.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Tn.actual]})]},Tn.id))]}),(!ve.get(Dt.id)?.failures||ve.get(Dt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Dt.id)),(!z.get(nt.id)||z.get(nt.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},nt.id)),Ie&&He===tt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:ae.title,onChange:nt=>te({...ae,title:nt.target.value}),onKeyDown:la,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:ae.description,onChange:nt=>te({...ae,description:nt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:ae.acceptanceCriteria,onChange:nt=>te({...ae,acceptanceCriteria:nt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Et,children:"Cancel"})]})]}),!Ie&&(!tt.features||tt.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(dd,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},tt.id)),U.slices.length===0&&!X&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(xd,{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"}),Be&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Xt.bg,color:Xt.text},children:vp(Be.state)}),Be&&Be.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Be.passedAssertions??0} of ${Be.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Be.passedAssertions??0)/Be.totalAssertions*100}%`,backgroundColor:(Be.passedAssertions??0)===Be.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{gt(!0),Ke(null),Xe({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(_n,{size:14})})]}),wt&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:pe.title,onChange:tt=>Xe({...pe,title:tt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:pe.assertion,onChange:tt=>Xe({...pe,assertion:tt.target.value}),rows:2}),t.jsxs("select",{value:pe.status,onChange:tt=>Xe({...pe,status:tt.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:()=>Vn(U.id),disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Fn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(me.get(U.id))?me.get(U.id):[]).map(tt=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":tt.id,children:[t.jsx("div",{className:"mission-assertion__header",children:be===tt.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:pe.title,onChange:nt=>Xe({...pe,title:nt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:pe.assertion,onChange:nt=>Xe({...pe,assertion:nt.target.value}),rows:2}),t.jsxs("select",{value:pe.status,onChange:nt=>Xe({...pe,status:nt.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:()=>ys(tt.id,U.id),disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Fn,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Vo[tt.status]??Vo.pending).bg,color:(Vo[tt.status]??Vo.pending).text},children:tt.status}),t.jsx("span",{className:"mission-assertion__title",children:tt.title}),(()=>{const Dt=Ot.get(tt.id)?.length??0;return Dt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Dt} linked feature${Dt!==1?"s":""}`,children:["(",Dt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ns(tt.id),title:"Toggle details",children:Tt===tt.id?t.jsx(cn,{size:14}):t.jsx(Un,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>as(tt),title:"Edit assertion",children:t.jsx(Ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ee({type:"assertion",id:tt.id}),title:"Delete assertion",children:t.jsx(En,{size:14})})]})}),Tt===tt.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:tt.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()=>{Tt!==tt.id&&await ns(tt.id),Ut(Kt===tt.id?null:tt.id)},title:"Link a feature",children:[t.jsx(Qa,{size:12}),"Link Feature"]})]}),Kt===tt.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const nt=new Set((Ot.get(tt.id)??[]).map(Tn=>Tn.id)),Dt=[];return g?.milestones.forEach(Tn=>Tn.slices.forEach(Xs=>Dt.push(...Xs.features.filter(Zs=>!nt.has(Zs.id))))),Dt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Dt.map(Tn=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Ds(Tn.id,tt.id),disabled:en.has(tt.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Tn.title}),en.has(tt.id)&&t.jsx(xt,{size:12,className:"spinner"})]},Tn.id))})()})}),(()=>{const nt=Ot.get(tt.id)??[];return nt.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):nt.map(Dt=>{const Tn=`${Dt.id}-${tt.id}`,Xs=Qt.has(Tn);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Dt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>qi(Dt.id,tt.id),disabled:Xs,title:"Unlink feature",children:Xs?t.jsx(xt,{size:12,className:"spinner"}):t.jsx(Du,{size:12})})]},Dt.id)})})()]})]})]},tt.id)),(!me.get(U.id)||me.get(U.id)?.length===0)&&!wt&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},U.id)}),g&&!le&&L===null&&t.jsxs("button",{className:"mission-add-btn",onClick:an,children:[t.jsx(_n,{size:16}),"Add Milestone"]}),le&&L===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:K.title,onChange:U=>oe({...K,title:U.target.value}),onKeyDown:xr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:K.description,onChange:U=>oe({...K,description:U.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ps,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Sn,children:"Cancel"})]})]}),g.milestones.length===0&&!le&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(ga,{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:Y,onChange:U=>Ye(U.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:[Gt.length," of ",ft]})]}),!rt&&Ki&&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:xi,"data-testid":"mission-activity-load-more",children:"Load more"})}),rt?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(xt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Gt.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ws,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:cs,className:"mission-events","data-testid":"mission-activity-events",children:[Gt.map(U=>{const je=!!(U.metadata&&Object.keys(U.metadata).length>0),Be=Yt.has(U.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${ER(U.eventType)}`,children:_R(U.eventType)}),t.jsx("span",{className:"mission-event__time",children:Nl(U.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:U.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(U.timestamp).toLocaleString()}),je&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Ns(U.id),"data-testid":`mission-event-metadata-${U.id}`,children:[Be?"Hide":"Show"," metadata"]}),Be&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(U.metadata,null,2)})]})]},U.id)}),t.jsx("div",{ref:gn})]})]})]}):null,Ql=()=>f.map(U=>{const je=U,Be=g?.id===je.id,jt=Ar[je.status]||{bg:"",text:""},hn=je.summary,Xt=Nt.get(je.id),Pn=NR(Xt),tt=!!(hn&&(hn.totalMilestones>0||hn.totalFeatures>0)),nt=Xt?.totalTasks??0,Dt=Xt?.tasksCompleted??0,Tn=Xt?.tasksFailed??0,Xs=Xt?.estimatedCompletionPercent??hn?.progressPercent??0,Zs=tt||nt>0||Tn>0||!!Xt?.lastActivityAt;return t.jsxs("div",{className:`mission-list__item ${Be?"mission-list__item--selected":""}`,onClick:()=>Aa(U),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(Ms,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:je.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[U.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(us,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Pn}`,"data-testid":`mission-health-badge-${je.id}`,"aria-label":`Mission health: ${Pn}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:jt.bg,color:jt.text},children:je.status})]}),je.description&&t.jsx("p",{className:"mission-list__item-description",children:je.description}),Zs&&t.jsxs("div",{className:"mission-list__item-summary",children:[tt&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[hn.completedMilestones,"/",hn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[hn.completedFeatures,"/",hn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${je.id}`,children:[Dt,"/",nt," tasks"]}),Tn>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:rs=>{rs.stopPropagation(),Aa(U)},"data-testid":`mission-failed-${je.id}`,title:"View mission failures",children:[Tn," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Pn}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Xs}%`}})})]}),Zs&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${je.id}`,children:["Activity ",Nl(Xt?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:rs=>rs.stopPropagation(),children:[je.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>bi(je.id),title:"Stop mission",children:t.jsx(Si,{size:14})}),je.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ma(je.id),title:"Resume mission",children:t.jsx(ls,{size:14})}),je.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Wi(je.id),title:"Start mission",children:t.jsx(ls,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Je(U),title:"Edit mission",children:t.jsx(Ss,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ee({type:"mission",id:je.id}),title:"Delete mission",children:t.jsx(En,{size:14})})]})]},je.id)}),ko=({hideBottomButtons:U=!1}={})=>{const je=N&&f.length>0&&!C,Be=!U&&!je;return t.jsxs("div",{className:"mission-list",children:[C&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:jt=>$({...A,title:jt.target.value}),onKeyDown:Ra,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:jt=>$({...A,description:jt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ct,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ut,children:"Cancel"})]})]}),je&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>ye(!0),children:[t.jsx(bs,{size:14}),"Plan New Mission"]})}),Ql(),I&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:jt=>$({...A,title:jt.target.value}),onKeyDown:Ra,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:jt=>$({...A,description:jt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:A.status,onChange:jt=>$({...A,status:jt.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:A.autopilotEnabled,onChange:jt=>$({...A,autopilotEnabled:jt.target.checked})}),t.jsx(us,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ct,disabled:F,children:[F?t.jsx(xt,{size:14,className:"spinner"}):t.jsx(os,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ut,children:"Cancel"})]})]}),f.length===0&&!C&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(Ms,{size:32}),t.jsx("h3",{className:"mission-manager__empty-title",children:"No missions yet"}),t.jsx("p",{className:"mission-manager__empty-body",children:"Missions are large initiatives that bundle milestones, slices, and features into a single plan. Plan a mission to break down a goal end-to-end and let agents work through it autopilot-style."}),t.jsxs("button",{className:"btn btn-sm btn-primary mission-manager__empty-cta",onClick:()=>ye(!0),children:[t.jsx(bs,{size:14}),"Plan New Mission"]})]}),!C&&t.jsxs("div",{className:"mission-list__footer",children:[Ce.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(Ps,{size:16}),t.jsx("span",{children:Ce.length===1?`Resume "${Ce[0].title}"?`:`${Ce.length} interview sessions pending`}),t.jsx("div",{className:"mission-list__resume-actions",children:Ce.map(jt=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{De(jt.id),ye(!0),fe([])},children:[jt.status==="error"?t.jsx(hs,{size:14}):t.jsx(bs,{size:14}),jt.status==="error"?"Retry":"Resume"]},jt.id))})]}),Be&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>ye(!0),children:[t.jsx(bs,{size:16}),"Plan New Mission"]})})]})]})},yr=()=>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 ",ht?.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()=>{ht&&(ht.type==="mission"?await Mt(ht.id):ht.type==="milestone"?await ts(ht.id):ht.type==="slice"?await mt(ht.id):ht.type==="feature"&&await rn(ht.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Ee(null),children:"Cancel"})]})]})}),ca=()=>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:ce,onChange:U=>Ae(U.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(U=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ae(U.id),children:[U.id,": ",U.title||"Untitled"]},U.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:yn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{ue(null),Ae("")},children:"Cancel"})]})]})}),ne=t.jsxs("div",{ref:Yl,className:`mission-manager mission-manager--desktop${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:Pa,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(Ml,{size:18})}),t.jsx(Ms,{size:18,className:"mission-manager__header-icon"}),t.jsxs("h2",{className:"mission-manager__title","data-testid":"mission-header-title",children:[t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--desktop",children:"Missions"}),t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--mobile",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(nn,{size:18})})]}),N?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(xt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(xt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Ia():ko(),ht&&yr(),Te&&ca()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:N?void 0:{width:`${E}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-header",children:t.jsxs("button",{className:"btn btn-sm btn-primary mission-manager__sidebar-cta",onClick:()=>ye(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(bs,{size:14}),"Plan New Mission"]})}),t.jsx("div",{className:"mission-manager__sidebar-list",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(xt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):ko({hideBottomButtons:!0})})]}),!N&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Uo,"aria-valuemax":Bo,"aria-valuenow":E,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:_,onKeyDown:D}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(xt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Ia():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(Ms,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),ht&&yr(),Te&&ca()]})]})]}),ze=t.jsx(cR,{isOpen:Ne,onClose:()=>ye(!1),onMissionCreated:()=>{bn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:dt}),kt=pt?t.jsx(xR,{isOpen:!0,onClose:()=>lt(null),onApplied:()=>{lt(null),g&&Pt(g.id)},targetType:pt.type,targetId:pt.id,targetTitle:pt.title,missionContext:g?.title,projectId:r,resumeSessionId:pt.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[ne,ze,kt]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:U=>U.target===U.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:ne}),ze,kt]})}const Wo=2e3;function kp({recipient:e,replyContext:n,agents:s=[],projectId:a,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[d,u]=i.useState(e?.id??""),[m,h]=i.useState(e?.type??"agent"),[f,p]=i.useState(""),[g,x]=i.useState(!1),[v,b]=i.useState(!1),[y,S]=i.useState(null),N=d.trim()!==""&&f.trim().length>0&&f.length<=Wo,E=i.useCallback(async()=>{if(!(!N||v)){b(!0),S(null);try{const j=m==="agent"?"user-to-agent":"system",_=g&&m==="agent",D=n||_?{...n?{replyTo:{messageId:n.messageId}}:{},..._?{wakeRecipient:!0}:{}}:void 0;await F1({toId:d.trim(),toType:m,content:f.trim(),type:j,...D?{metadata:D}:{}},a),r()}catch(j){const _=Me(j)||"Failed to send message";S(_),l?.(_,"error")}finally{b(!1)}}},[N,v,d,m,f,g,n,a,r,l]),w=i.useCallback(j=>{u(j),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(nn,{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:d,onChange:j=>w(j.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(j=>t.jsx("option",{value:j.id,children:j.name||j.id},j.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(zn,{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:j=>p(j.target.value),maxLength:Wo,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>Wo?"over-limit":"",children:[f.length,"/",Wo]})})]}),m==="agent"&&t.jsx("div",{className:"message-composer-field message-composer-field--wake",children:t.jsxs("label",{className:"message-composer-wake-label",children:[t.jsx("input",{type:"checkbox",checked:g,onChange:j=>x(j.target.checked),"data-testid":"message-composer-wake"}),t.jsxs("span",{children:["Wake recipient immediately",t.jsx("span",{className:"message-composer-wake-hint",children:"(overrides their messageResponseMode)"})]})]})}),y&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Ps,{size:14}),t.jsx("span",{children:y})]})]}),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:E,disabled:!N||v,"data-testid":"message-composer-send",children:v?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(pa,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function Ua(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/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 PR(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const a=s?.get(e)?.trim();return a?a===e?`Agent: ${e}`:`Agent: ${a} (${e})`:`Agent: ${e}`}return"System"}function TR(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 jp(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function RR(e,n){const s=[...e];s.some(o=>o.id===n.id)||s.push(n);const a=new Set([n.id]);let r=!0;for(;r;){r=!1;for(const o of s){const l=o.metadata?.replyTo?.messageId;a.has(o.id)&&l&&!a.has(l)&&(a.add(l),r=!0),l&&a.has(l)&&!a.has(o.id)&&(a.add(o.id),r=!0)}}return s.filter(o=>a.has(o.id)).sort((o,l)=>new Date(o.createdAt).getTime()-new Date(l.createdAt).getTime())}function IR({projectId:e,addToast:n,onUnreadCountChange:s}){const[a,r]=i.useState("inbox"),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(0),[h,f]=i.useState(!1),[p,g]=i.useState(null),[x,v]=i.useState([]),[b,y]=i.useState(!1),[S,N]=i.useState(null),[E,w]=i.useState(null),[j,_]=i.useState(null),[D,C]=i.useState("inbox"),[P,I]=i.useState(null),[H,A]=i.useState([]),$=i.useMemo(()=>new Map(H.map(O=>[O.id,O.name??""])),[H]),F=i.useCallback((O,ke)=>PR(O,ke,$),[$]),ee=Js()==="mobile",J=!ee,M=i.useCallback(async()=>{f(!0);try{const O=await L1({limit:50},e);l(O),m(O.unreadCount),s?.(O.unreadCount)}catch{}finally{f(!1)}},[e,s]),T=i.useCallback(async()=>{f(!0);try{const O=await O1({limit:50},e);d(O)}catch{}finally{f(!1)}},[e]),L=i.useCallback(async O=>{f(!0);try{const ke=await q1(O,e);I(ke)}catch{}finally{f(!1)}},[e]),k=i.useCallback(async()=>{try{const O=await Na(void 0,e);A(O)}catch{}},[e]),K=i.useCallback(async()=>{try{const O=await Zf(e);m(O.unreadCount),s?.(O.unreadCount)}catch{}},[e,s]);i.useEffect(()=>{a==="inbox"?M():a==="outbox"?T():a==="agents"&&k()},[a,M,T,k]),i.useEffect(()=>{j&&L(j)},[j,L]),i.useEffect(()=>{K()},[K]),i.useEffect(()=>{k()},[k]),i.useEffect(()=>{if(typeof EventSource>"u")return;const O=e?`?projectId=${encodeURIComponent(e)}`:"",ke=()=>{K(),a==="inbox"?M():a==="outbox"&&T(),j&&L(j)};return ai(`/api/events${O}`,{events:{"message:sent":ke,"message:received":ke,"message:read":ke,"message:deleted":ke}})},[e,a,j,K,M,T,L]);const oe=i.useCallback(async O=>{if(g(O),!O.read&&a==="inbox")try{const ke=await z1(O.id,e);ke&&l(te=>te&&{...te,messages:te.messages.map(Ie=>Ie.id===ke.id?ke:Ie),unreadCount:Math.max(0,te.unreadCount-1)});const ae=Math.max(0,u-1);m(ae),s?.(ae)}catch{}try{const ke=await H1(O.fromId,O.fromType,e);v(ke)}catch{v([O])}},[e,u,s,a]),le=i.useCallback(()=>{g(null),v([])},[]),we=i.useCallback(async()=>{try{const O=await U1(e);m(0),s?.(0),l(ke=>ke&&{...ke,messages:ke.messages.map(ae=>({...ae,read:!0})),unreadCount:0}),n?.(`Marked ${O.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),ge=i.useCallback(async O=>{try{await B1(O,e),g(null),v([]),a==="inbox"?M():a==="outbox"?T():j&&L(j),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,j,M,T,L,n]),Ue=i.useCallback(O=>{N({id:O.fromId,type:O.fromType}),w({messageId:O.id,preview:jp(O.content,120)}),y(!0)},[]),Z=i.useCallback(()=>{y(!1),N(null),w(null),n?.("Message sent","success"),a==="outbox"?T():a==="agents"&&j&&L(j),K()},[a,T,j,L,n,K]),Q=i.useCallback(()=>{N(a==="agents"&&j?{id:j,type:"agent"}:null),w(null),y(!0)},[a,j]),X=i.useCallback(()=>{y(!1),N(null),w(null)},[]),ie=()=>{if(!p||b)return null;const O=RR(x,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:le,"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:TR(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Ua(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>Ue(p),"data-testid":"mailbox-reply",children:[t.jsx(Oi,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ge(p.id),"data-testid":"mailbox-delete",children:[t.jsx(En,{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(zn,{size:14}):t.jsx($a,{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(zn,{size:14}):t.jsx($a,{size:14}),F(p.toId,p.toType)]})]})]}),O.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),O.map(ke=>{const ae=ke.metadata?.replyTo?.messageId,te=ae?O.find(Ie=>Ie.id===ae):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${ke.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:F(ke.fromId,ke.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Ua(ke.createdAt)})]}),ae&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${ke.id}`,children:["↪ Replying to ",te?jp(te.content,60):`message ${ae}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:ke.content})]},ke.id)})]}),O.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})]})]})},se=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Gc,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Lr,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(O=>t.jsxs("div",{className:`mailbox-item ${O.read?"":"unread"}`,onClick:()=>oe(O),"data-testid":`mailbox-item-${O.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:O.fromType==="agent"?t.jsx(zn,{size:16}):t.jsx($a,{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(O.fromId,O.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Ua(O.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[O.content.slice(0,80),O.content.length>80?"…":""]})]}),!O.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${O.id}`})]},O.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Gc,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(pa,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(O=>t.jsxs("div",{className:"mailbox-item",onClick:()=>oe(O),"data-testid":`mailbox-item-${O.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:O.toType==="agent"?t.jsx(zn,{size:16}):t.jsx($a,{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(O.toId,O.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Ua(O.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[O.content.slice(0,80),O.content.length>80?"…":""]})]})]},O.id))]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:H.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(zn,{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:j??"",onChange:O=>{_(O.target.value||null),C("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),H.map(O=>t.jsx("option",{value:O.id,children:O.name||O.id},O.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Q,"data-testid":"mailbox-compose-btn",children:[t.jsx(Oi,{size:14}),t.jsx("span",{children:"Compose"})]})]}),j&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${D==="inbox"?"active":""}`,onClick:()=>C("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(Lr,{size:12}),t.jsx("span",{children:"Inbox"}),P&&P.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:P.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${D==="outbox"?"active":""}`,onClick:()=>C("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(pa,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!j&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(zn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),j&&h&&!P&&t.jsx(Gc,{}),j&&P&&D==="inbox"&&P.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Lr,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),j&&P&&D==="outbox"&&P.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(pa,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),j&&P&&D==="inbox"&&P.inbox.map(O=>t.jsxs("div",{className:`mailbox-item ${O.read?"":"unread"}`,onClick:()=>oe(O),"data-testid":`mailbox-item-${O.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:O.fromType==="agent"?t.jsx(zn,{size:16}):t.jsx($a,{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(O.fromId,O.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Ua(O.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[O.content.slice(0,80),O.content.length>80?"…":""]})]})]},O.id)),j&&P&&D==="outbox"&&P.outbox.map(O=>t.jsxs("div",{className:"mailbox-item",onClick:()=>oe(O),"data-testid":`mailbox-item-${O.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:O.toType==="agent"?t.jsx(zn,{size:16}):t.jsx($a,{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(O.toId,O.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Ua(O.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[O.content.slice(0,80),O.content.length>80?"…":""]})]})]},O.id))]})]})})]}),B=()=>b?t.jsx(kp,{recipient:S,replyContext:E,agents:H,projectId:e,onSend:Z,onCancel:X,addToast:n}):p?ie():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(ba,{size:24}),t.jsx("p",{children:"Select a message to read"})]});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"}),u>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:u})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:Q,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Oi,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:we,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Qx,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?M():a==="outbox"?T():j&&L(j)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(xt,{size:14,className:"spin"}):t.jsx(hs,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(Lr,{size:14}),t.jsx("span",{children:"Inbox"}),u>0&&t.jsx("span",{className:"mailbox-tab-badge",children:u})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(pa,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(zn,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:J?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:se()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:B()})]}):t.jsxs(t.Fragment,{children:[ie(),b&&t.jsx(kp,{recipient:S,replyContext:E,agents:H,projectId:e,onSend:Z,onCancel:X,addToast:n}),!p&&!b&&se()]})})]})}function Gc(){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))})}const $R=640;function DR({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){pi(e);const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[x,v]=i.useState([]),[b,y]=i.useState(null),[S,N]=i.useState([]),[E,w]=i.useState(null),[j,_]=i.useState(null),[D,C]=i.useState(!1),[P,I]=i.useState([]),[H,A]=i.useState(!1),[$,F]=i.useState(""),G=i.useRef(!1),ee=i.useRef(null);Ti(ee,e,"fusion:github-modal-size");const J=Ui(n),[M,T]=i.useState(!1),[L,k]=i.useState("list"),K=i.useRef(null),oe=new Set;for(const fe of a){const Pe=fe.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);Pe&&oe.add(Pe[1]);const De=fe.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);De&&oe.add(De[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),v([]),y(null),N([]),w(null),g("issues"),_(null),C(!1),I([]),A(!0),F(""),K.current=null,G.current=!0,Uk().then(fe=>{if(G.current)if(I(fe),A(!1),fe.length===1){const Pe=fe[0];l(Pe.owner),d(Pe.repo),F(Pe.name)}else fe.length>1&&(l(""),d(""),F(""))}).catch(()=>{G.current&&A(!1)}),()=>{G.current=!1}},[e]);const le=i.useCallback(fe=>{if(F(fe),fe==="")l(""),d("");else{const Pe=P.find(De=>De.name===fe);Pe&&(l(Pe.owner),d(Pe.repo))}},[P]),we=i.useCallback(async()=>{if(!o.trim()||!c.trim()){_("Repository must be selected");return}f(!0),_(null),v([]),y(null);try{const fe=u.split(",").map(De=>De.trim()).filter(Boolean),Pe=await Lk(o.trim(),c.trim(),30,fe.length>0?fe:void 0);v(Pe),Pe.length===0&&_("No open issues found")}catch(fe){_(Me(fe)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),ge=i.useCallback(async()=>{if(!o.trim()||!c.trim()){_("Repository must be selected");return}f(!0),_(null),N([]),w(null);try{const fe=await Fk(o.trim(),c.trim(),30);N(fe),fe.length===0&&_("No open pull requests found")}catch(fe){_(Me(fe)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||D)return;const fe={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};K.current?.owner===fe.owner&&K.current?.repo===fe.repo&&K.current?.labels===fe.labels&&K.current?.tab===fe.tab||(K.current=fe,p==="issues"?we():ge())},[o,c,u,p,e,h,D,we,ge]),i.useEffect(()=>{if(!e)return;const fe=Pe=>{Pe.key==="Escape"&&n()};return document.addEventListener("keydown",fe),()=>document.removeEventListener("keydown",fe)},[e,n]),i.useEffect(()=>{if(!e)return;const fe=()=>{T(window.innerWidth<=$R)};return fe(),window.addEventListener("resize",fe),()=>window.removeEventListener("resize",fe)},[e]);const Ue=i.useCallback(fe=>{y(fe),M&&k("preview")},[M]),Z=i.useCallback(fe=>{w(fe),M&&k("preview")},[M]),Q=i.useCallback(()=>{k("list")},[]),X=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;C(!0),_(null);try{const fe=await Ok(o.trim(),c.trim(),b,r);s(fe),y(null),M&&L==="preview"&&k("list")}catch(fe){const Pe=Me(fe);Pe?.includes("already imported")?_(Pe):_(Pe||"Failed to import issue")}finally{C(!1)}}else{if(E===null)return;C(!0),_(null);try{const fe=await zk(o.trim(),c.trim(),E,r);s(fe),w(null),M&&L==="preview"&&k("list")}catch(fe){const Pe=Me(fe);Pe?.includes("already imported")?_(Pe):_(Pe||"Failed to import pull request")}finally{C(!1)}}},[p,b,E,o,c,s,M,L]),ie=x.find(fe=>fe.number===b),se=S.find(fe=>fe.number===E);if(!e)return null;const B=P.length>0,O=P.length===1,ke=x.filter(fe=>oe.has(fe.html_url)).length,ae=S.filter(fe=>oe.has(fe.html_url)).length,te=j==="No open issues found",Ie=j==="No open pull requests found",Oe=p==="issues"?te:Ie,He=!!j&&!te&&x.length===0&&!h,$e=!!j&&!Ie&&S.length===0&&!h,Te=p==="issues"?He:$e,ue=h||x.length>0||te||He,ce=h||S.length>0||Ie||$e,Ae=p==="issues"?ue:ce,Ne=!!j&&x.length>0&&!te,ye=!!j&&S.length>0&&!Ie,Ce=p==="issues"?Ne:ye;return t.jsx("div",{className:"modal-overlay open",...J,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:ee,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),w(null)},disabled:h||D,children:[t.jsx(Al,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||D,children:[t.jsx(Vs,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:H?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(xt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):B?O?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:P[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[P[0].owner,"/",P[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:$,onChange:fe=>le(fe.target.value),disabled:h||D,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),P.map(fe=>t.jsxs("option",{value:fe.name,children:[fe.name," (",fe.owner,"/",fe.repo,")"]},fe.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:u,onChange:fe=>m(fe.target.value),onKeyDown:fe=>fe.key==="Enter"&&we(),disabled:h||D||!B,"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"?we:ge,disabled:h||D||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(xt,{size:14,className:"spin"}):t.jsx(hs,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!H&&!B&&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"})]}),Ce&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:j}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${M?"mobile":""} ${L==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&x.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[x.length," issue",x.length===1?"":"s"]}),t.jsxs("span",{children:[ke," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[ae," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Ae&&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(xt,{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."})]})]}),Te&&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:j})]})}),Oe&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&x.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:x.map(fe=>{const Pe=oe.has(fe.html_url);return t.jsxs("div",{className:`issue-item ${b===fe.number?"selected":""} ${Pe?"imported":""}`,onClick:()=>!Pe&&Ue(fe.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===fe.number,onChange:()=>Ue(fe.number),disabled:Pe,"aria-label":`Select issue #${fe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",fe.number]}),t.jsx("span",{className:"issue-title",children:fe.title})]}),fe.labels.length>0&&t.jsx("span",{className:"issue-labels",children:fe.labels.map(De=>t.jsx("span",{className:"label-chip",children:De.name},De.name))})]}),Pe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},fe.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(fe=>{const Pe=oe.has(fe.html_url);return t.jsxs("div",{className:`issue-item ${E===fe.number?"selected":""} ${Pe?"imported":""}`,onClick:()=>!Pe&&Z(fe.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:E===fe.number,onChange:()=>Z(fe.number),disabled:Pe,"aria-label":`Select pull request #${fe.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",fe.number]}),t.jsx("span",{className:"issue-title",children:fe.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[fe.headBranch," → ",fe.baseBranch]})]}),Pe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},fe.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${M?"mobile":""} ${L==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[M&&t.jsxs("button",{className:"github-import-back-button",onClick:Q,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(ka,{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"&&ie?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",ie.number]}),t.jsx("div",{className:"preview-title",children:ie.title}),t.jsx("div",{className:"preview-body",children:ie.body?ie.body.slice(0,200)+(ie.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"&&se?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",se.number]}),t.jsx("div",{className:"preview-title",children:se.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",se.headBranch," → ",se.baseBranch]}),t.jsx("div",{className:"preview-body",children:se.body?se.body.slice(0,200)+(se.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:D,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:X,disabled:(p==="issues"?b===null:E===null)||D,children:D?t.jsx(xt,{size:14,className:"spin"}):"Import"})]})]})})}function ni({summary:e,children:n,className:s="",onToggle:a,defaultOpen:r=!1}){const[o,l]=i.useState(r);return t.jsxs("div",{className:`onboarding-disclosure ${s}`.trim(),children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>{const c=!o;l(c),a?.(c)},"aria-expanded":o,type:"button",children:[t.jsx(Un,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),o?t.jsx("div",{className:"onboarding-disclosure-content",children:n}):null]})}const LR=["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 OR(e,n){return e&&n?`${e}/${n}`:""}function FR(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 zR({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:a,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[d,u]=i.useState(""),[m,h]=i.useState({type:"initial"}),[f,p]=i.useState(null),[g,x]=i.useState([]),[v,b]=i.useState([]),[y,S]=i.useState(null),N=i.useRef(!1),E=i.useRef(!1),[w,j]=i.useState(""),[_,D]=i.useState(!0),[C,P]=i.useState(!1),[I,H]=i.useState(!1),[A,$]=i.useState(null),[F,G]=i.useState(0),ee=i.useRef(null),J=i.useRef(null),M=i.useRef(null),T=i.useRef(null),L=i.useRef(null),k=i.useRef(null),K=i.useRef(null),[oe,le]=i.useState(c??null),we=i.useMemo(()=>Ca(),[]),{isLockedByOther:ge,takeControl:Ue,isLoading:Z}=Jl(e?oe:null),{activeTabMap:Q,broadcastUpdate:X,broadcastCompleted:ie,broadcastLock:se,broadcastUnlock:B,broadcastHeartbeat:O}=gr(),[ke,ae]=i.useState(void 0),[te,Ie]=i.useState(void 0),[Oe,He]=i.useState("medium"),[$e,Te]=i.useState(""),[ue,ce]=i.useState([]),[Ae,Ne]=i.useState(!1),[ye,Ce]=i.useState(null),[fe,Pe]=i.useState([]),[De,dt]=i.useState([]),[pt,lt]=i.useState({}),vt=i.useRef(null),[_e,Fe]=i.useState([]),[bt,ht]=i.useState(!1),[Ee,me]=i.useState(c??null),[Re,be]=i.useState(!!c),[Ke,pe]=i.useState(null),[Xe,wt]=i.useState(!1),gt=i.useRef(!1),Tt=i.useRef(null),Zt=i.useRef(""),Ot=i.useRef(null),Rt=i.useRef(null);Ti(J,e,"fusion:planning-modal-size");const en=Js(),{keyboardOverlap:zt,viewportHeight:Qt,viewportOffsetTop:xn,keyboardOpen:Kt}=ra({enabled:en==="mobile"});pi(en==="mobile"&&e),i.useEffect(()=>{const re=J.current;re&&(Kt?(re.style.setProperty("--keyboard-overlap",`${zt}px`),re.style.setProperty("--vv-offset-top",`${xn}px`),Qt!==null?re.style.setProperty("--vv-height",`${Qt}px`):re.style.removeProperty("--vv-height")):(re.style.removeProperty("--keyboard-overlap"),re.style.removeProperty("--vv-offset-top"),re.style.removeProperty("--vv-height")))},[Kt,zt,xn,Qt]),i.useEffect(()=>{Zt.current=w},[w]),i.useEffect(()=>{const re=Tt.current;if(!re)return;re.scrollHeight-re.scrollTop-re.clientHeight<32&&(re.scrollTop=re.scrollHeight)},[w]),i.useEffect(()=>{if(m.type!=="loading"){$(null),G(0);return}const re=Date.now();$(re),G(0);const rt=setInterval(()=>{G(Math.max(0,Math.floor((Date.now()-re)/1e3)))},1e3);return()=>clearInterval(rt)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const re=T.current;if(!re)return;let rt=!1;const ft=setInterval(async()=>{try{const it=await Ei(re);if(rt||!it||T.current!==re)return;if(it.status==="awaiting_input"&&it.currentQuestion){const Y=JSON.parse(it.currentQuestion);h({type:"question",session:{sessionId:re,currentQuestion:Y,summary:null}}),j("")}else if(it.status==="complete"&&it.result){const Y=JSON.parse(it.result);h({type:"summary",session:{sessionId:re,currentQuestion:null,summary:Y},summary:Y}),S(Y),j("")}}catch{}},8e3);return()=>{rt=!0,clearInterval(ft)}},[m.type]);const Ut=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),j(""),P(!1),H(!1),ae(void 0),Ie(void 0),He("medium"),Te(""),T.current=null,le(null)},[]),fn=OR(ke,te),un=i.useCallback((re,rt)=>{if(!re||!rt)return pt.provider&&pt.modelId?`${pt.provider}/${pt.modelId}`:"Using default";const ct=ue.find(ft=>ft.provider===re&&ft.id===rt);return ct?`${ct.provider}/${ct.id}`:`${re}/${rt}`},[ue,pt.modelId,pt.provider]),tn=i.useCallback(async()=>{Ne(!0),Ce(null);try{const re=await $s();ce(re.models),Pe(re.favoriteProviders),dt(re.favoriteModels),lt({provider:re.resolvedPlanningProvider,modelId:re.resolvedPlanningModelId})}catch(re){Ce(Me(re)||"Failed to load models")}finally{Ne(!1)}},[]),Vt=i.useCallback(re=>{Pe(rt=>{const ct=rt,it=ct.includes(re)?ct.filter(Y=>Y!==re):[re,...ct];return $n({favoriteProviders:it,favoriteModels:De}).catch(()=>{Pe(ct)}),it})},[De]),mn=i.useCallback(re=>{dt(rt=>{const ct=rt,it=ct.includes(re)?ct.filter(Y=>Y!==re):[re,...ct];return $n({favoriteProviders:fe,favoriteModels:it}).catch(()=>{dt(ct)}),it})},[fe]),xe=i.useCallback(re=>{M.current?.close();const rt=()=>T.current!==re,ct=Bj(re,l,{onThinking:ft=>{rt()||(j(it=>it+ft),X({sessionId:re,status:"generating",needsInput:!1,owningTabId:we,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:ft=>{if(rt())return;P(!1),H(!1),za(l);const it=Zt.current.trim();it&&b(Y=>Y[Y.length-1]?.thinkingOutput===it?Y:[...Y,{thinkingOutput:it}]),h({type:"question",session:{sessionId:re,currentQuestion:ft,summary:null}}),j(""),X({sessionId:re,status:"awaiting_input",needsInput:!0,owningTabId:we,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:ft=>{if(rt())return;P(!1),H(!1),za(l);const it=Zt.current.trim();it&&b(Y=>Y[Y.length-1]?.thinkingOutput===it?Y:[...Y,{thinkingOutput:it}]),h({type:"summary",session:{sessionId:re,currentQuestion:null,summary:ft},summary:ft}),S(ft),j(""),X({sessionId:re,status:"complete",needsInput:!1,owningTabId:we,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:ft=>{const it=ft||"Session failed while contacting the AI.";P(!0),(async()=>{try{const Y=await Ei(re);if(Y&&(Y.status==="generating"||Y.status==="awaiting_input")){xe(re);return}}catch{}P(!1),H(!1),p(null),h(Y=>Y.type==="question"||Y.type==="summary"||Y.type==="error"?{type:"error",session:Y.session,errorMessage:it}:{type:"error",session:{sessionId:re,currentQuestion:null,summary:null},errorMessage:it}),j(""),T.current=re,X({sessionId:re,status:"error",needsInput:!1,owningTabId:we,type:"planning",title:d.trim()||void 0,projectId:l??null}),ie({sessionId:re,status:"error"})})()},onComplete:()=>{P(!1),H(!1),T.current=null,ie({sessionId:re,status:"complete"})},onConnectionStateChange:ft=>{P(ft==="reconnecting")}});M.current=ct},[ie,X,d,l,we]),Le=i.useCallback(async re=>{const rt=re??d;if(rt.trim()){p(null),j(""),b([]),x([]),P(!1),h({type:"loading"});try{const ct=ke&&te?{planningModelProvider:ke,planningModelId:te}:void 0,ft=$e.trim()?Number.parseInt($e,10):void 0,it=L.current,{sessionId:Y}=await Nj(rt.trim(),l,ct,{planningDepth:Oe,customQuestionCount:Number.isInteger(ft)?ft:void 0},it??void 0);L.current=null,T.current=Y,le(Y),me(Y),xe(Y),x([])}catch(ct){P(!1),p(Me(ct)||"Failed to start planning session"),h({type:"initial"}),T.current=null,le(null)}}},[xe,$e,d,Oe,te,ke,l]);i.useEffect(()=>{e&&m.type==="initial"&&ee.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&tn()},[e,tn]),i.useEffect(()=>{if(e&&o&&!N.current&&m.type==="initial"){u(o);const re=setTimeout(()=>{N.current=!0,Le(o)},0);return()=>clearTimeout(re)}else if(e&&!o&&!N.current&&!E.current&&m.type==="initial"){E.current=!0;const re=WT(l);re&&u(re)}},[e,o,m.type,Le,l]);const Ve=i.useCallback(async re=>{M.current?.close(),M.current=null,p(null),j(""),x([]),b([]),S(null),H(!1),h({type:"loading"});try{const rt=await Ei(re);if(!rt){me(null),be(!1),h({type:"initial"});return}T.current=re,le(re);const ct=nr(rt.conversationHistory);if(b(ct),x(ct.map(ft=>ft.response).filter(ft=>!!(ft&&typeof ft=="object"&&!Array.isArray(ft)))),rt.status==="draft"){let ft="",it,Y;try{const Ye=rt.inputPayload?JSON.parse(rt.inputPayload):null;Ye&&typeof Ye.initialPlan=="string"&&(ft=Ye.initialPlan),Ye&&typeof Ye.modelProvider=="string"&&typeof Ye.modelId=="string"&&(it=Ye.modelProvider,Y=Ye.modelId)}catch{}u(ft),ae(it),Ie(Y),L.current=re,Rt.current=ft?{sessionId:re,initialPlan:ft.trim(),modelProvider:it,modelId:Y}:null,h({type:"initial"})}else if(rt.status==="awaiting_input"&&rt.currentQuestion){za(l);const ft=JSON.parse(rt.currentQuestion);if(h({type:"question",session:{sessionId:re,currentQuestion:ft,summary:null}}),rt.thinkingOutput){const it=rt.thinkingOutput.trim();it&&b(Y=>Y[Y.length-1]?.thinkingOutput===it?Y:[...Y,{thinkingOutput:it}])}xe(re)}else if(rt.status==="complete"&&rt.result){za(l);const ft=JSON.parse(rt.result);h({type:"summary",session:{sessionId:re,currentQuestion:null,summary:ft},summary:ft}),S(ft)}else rt.status==="generating"?(h({type:"loading"}),rt.thinkingOutput&&j(rt.thinkingOutput),xe(re)):rt.status==="error"&&h({type:"error",session:{sessionId:re,currentQuestion:null,summary:null},errorMessage:rt.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[xe,l]);i.useEffect(()=>{!e||!c||T.current!==c&&K.current!==c&&(me(c),be(!0),Ve(c))},[e,c]),i.useEffect(()=>{e&&Ee&&(c&&c===Ee||Ve(Ee))},[e]);const at=i.useCallback(async()=>{ht(!0);try{const rt=(await su(l,{includeCompleted:!0,includeArchived:Xe})).filter(ct=>ct.type==="planning").sort((ct,ft)=>Date.parse(ft.updatedAt)-Date.parse(ct.updatedAt));Fe(rt)}catch{}finally{ht(!1)}},[l,Xe]);i.useEffect(()=>{e&&at()},[e,at]);const Ge=i.useRef(!1);i.useEffect(()=>{const re=Ge.current&&!bt;Ge.current=bt,re&&en==="mobile"&&(Re||c||Ee||_e.length>0||be(!0))},[en,Re,c,Ee,bt,_e.length]),i.useEffect(()=>{if(!e)return;const re=l?`?projectId=${encodeURIComponent(l)}`:"",rt=ft=>{try{const it=JSON.parse(ft.data);if(it.type!=="planning")return;Fe(Y=>{const Ye=Y.findIndex(In=>In.id===it.id);return(Ye>=0?[...Y.slice(0,Ye),it,...Y.slice(Ye+1)]:[it,...Y]).sort((In,cs)=>Date.parse(cs.updatedAt)-Date.parse(In.updatedAt))})}catch{}},ct=ft=>{try{const it=JSON.parse(ft.data);Fe(Y=>Y.filter(Ye=>Ye.id!==it))}catch{}};return ai(`/api/events${re}`,{events:{"ai_session:updated":rt,"ai_session:deleted":ct},onReconnect:()=>{at()}})},[e,l,at]);const Ft=i.useCallback(re=>{if(Ee===re){be(!0);return}me(re),be(!0),Ve(re)},[Ve,Ee]),_t=i.useCallback(()=>{M.current?.close(),M.current=null,L.current=null,k.current&&(clearTimeout(k.current),k.current=null),c&&(K.current=c),Ut(),me(null),be(!0)},[Ut,c]),qt=i.useCallback(()=>{be(!1)},[]),St=i.useCallback(async(re,rt)=>{const ct=rt.trim();if(!(!ct||Rt.current?.sessionId===re&&Rt.current.initialPlan===ct&&Rt.current.modelProvider===ke&&Rt.current.modelId===te))try{await $1(re,{initialPlan:ct,modelProvider:ke&&te?ke:void 0,modelId:ke&&te?te:void 0},l),Rt.current={sessionId:re,initialPlan:ct,modelProvider:ke,modelId:te}}catch{}},[te,ke,l]);i.useEffect(()=>{if(Ot.current&&(clearTimeout(Ot.current),Ot.current=null),!(!e||m.type!=="initial"||!Ee))return Ot.current=setTimeout(()=>{St(Ee,d)},500),()=>{Ot.current&&(clearTimeout(Ot.current),Ot.current=null)}},[d,e,Ee,St,m.type]),i.useEffect(()=>{Rt.current=null},[Ee]),i.useEffect(()=>()=>{Ot.current&&(clearTimeout(Ot.current),Ot.current=null)},[]);const z=i.useCallback(async re=>{const rt=ft=>ft==="generating"||ft==="awaiting_input",ct=_e.find(ft=>ft.id===re);if(ct&&rt(ct.status))try{await qf(re,l,we)}catch{}try{await Xf(re)}catch{}ie({sessionId:re,status:"complete",timestamp:Date.now()}),Fe(ft=>ft.filter(it=>it.id!==re)),Ee===re&&(M.current?.close(),M.current=null,Ut(),me(null),be(!1)),pe(null)},[ie,_e,l,Ut,Ee,we]),he=i.useCallback(async re=>{const ct=_e.find(ft=>ft.id===re)?.archived===!0;try{ct?await A1(re):await M1(re)}catch{return}Fe(ft=>!ct&&!Xe?ft.filter(it=>it.id!==re):ft.map(it=>it.id===re?{...it,archived:!ct}:it)),!ct&&Ee===re&&!Xe&&(M.current?.close(),M.current=null,Ut(),me(null),be(!1))},[_e,Ut,Ee,be,Xe]);i.useEffect(()=>{e||(N.current=!1,E.current=!1,P(!1),H(!1),le(null))},[e]),i.useEffect(()=>{if(!e){vt.current&&(B(vt.current,we),vt.current=null);return}if(oe&&vt.current!==oe){vt.current&&B(vt.current,we),se(oe,we),vt.current=oe;return}!oe&&vt.current&&(B(vt.current,we),vt.current=null)},[se,B,e,oe,we]),i.useEffect(()=>{if(!e||!oe||vt.current!==oe)return;O(we);const re=setInterval(()=>{O(we)},3e4);return()=>{clearInterval(re)}},[O,e,oe,we]),i.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),M.current?.close(),M.current=null,vt.current&&(B(vt.current,we),vt.current=null)},[B,we]),i.useEffect(()=>{if(!e)return;const re=()=>{M.current?.close(),M.current=null};return window.addEventListener("beforeunload",re),()=>window.removeEventListener("beforeunload",re)},[e]);const st=i.useCallback((re,rt)=>{Ot.current&&(clearTimeout(Ot.current),Ot.current=null),(async()=>{try{await St(re,rt),await D1(re,l)}catch{}})()},[l,St]),It=i.useCallback(()=>{if(en!=="mobile")return;const re=document.activeElement;re instanceof HTMLElement&&re.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[en]),ve=i.useCallback(()=>{d&&m.type==="initial"&&VT(d,l);const re=L.current;re&&d.trim()&&st(re,d),L.current=null,k.current&&(clearTimeout(k.current),k.current=null),M.current?.close(),M.current=null,P(!1),H(!1),It(),n()},[st,d,n,l,It,m.type]);i.useEffect(()=>{if(!e)return;const re=rt=>{rt.key==="Escape"&&ve()};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[e,ve]);const ot=i.useCallback(async re=>{if(m.type!=="question")return;const{session:rt}=m,ct=rt.sessionId,ft=rt.currentQuestion;if(!ft){p("No active question in session");return}p(null),x(it=>[...it,re]),b(it=>{const Y=Zt.current.trim();let Ye=it;return Y&&Ye[Ye.length-1]?.thinkingOutput!==Y&&(Ye=[...Ye,{thinkingOutput:Y}]),[...Ye,{question:ft,response:re}]}),h({type:"loading"}),j("");try{await Ju(ct,re,l,we)}catch(it){p(Me(it)||"Failed to submit response"),h({type:"question",session:rt})}},[l,we,m]),Nt=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:re,summary:rt}=m,ct=re.sessionId;T.current=ct,le(ct),p(null),H(!1),j(""),h({type:"loading"}),xe(ct);try{await Ju(ct,{refine:!0},l,we)}catch(ft){M.current?.close(),M.current=null,p(Me(ft)||"Failed to refine plan"),h({type:"summary",session:re,summary:y??rt})}},[xe,y,l,we,m]),Lt=i.useCallback(async()=>{const re=T.current;if(re){try{await Ej(re,l,we)}catch{}M.current?.close(),M.current=null,P(!1),H(!1),h({type:"error",session:{sessionId:re,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),j("")}},[l,we]),$t=i.useCallback(async()=>{if(m.type!=="error")return;const re=m.session;p(null),H(!0),j(""),h({type:"loading"}),xe(re.sessionId);try{T.current=re.sessionId,le(re.sessionId),await Cj(re.sessionId,l,we)}catch(rt){let ct=rt;if((Me(rt)||"").includes("not in an error state"))try{const it=await Ei(re.sessionId);if(!it)throw new Error("Failed to refresh planning session.");if(T.current=it.id,le(it.id),it.status==="generating")j(it.thinkingOutput??""),h({type:"loading"});else if(it.status==="awaiting_input"){if(!it.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const Y=JSON.parse(it.currentQuestion);if(za(l),h({type:"question",session:{sessionId:it.id,currentQuestion:Y,summary:null}}),it.thinkingOutput){const Ye=it.thinkingOutput.trim();Ye&&b(Yt=>Yt[Yt.length-1]?.thinkingOutput===Ye?Yt:[...Yt,{thinkingOutput:Ye}])}M.current?.isConnected()||xe(it.id)}else if(it.status==="complete"){if(!it.result)throw new Error("Planning session is complete but has no result.");const Y=JSON.parse(it.result);za(l),h({type:"summary",session:{sessionId:it.id,currentQuestion:null,summary:Y},summary:Y}),S(Y)}else it.status==="error"&&h({type:"error",session:{sessionId:it.id,currentQuestion:null,summary:null},errorMessage:it.error||"Retry failed. Please try again."});P(!1);return}catch(it){ct=it}M.current?.close(),M.current=null,h({type:"error",session:re,errorMessage:Me(ct)||"Retry failed. Please try again."}),P(!1)}finally{H(!1)}},[xe,l,we,m]),Wt=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const re=m.session.sessionId,rt=await _j(re,y??void 0,l);s(rt),me(null),Fe(ct=>ct.filter(ft=>ft.id!==re)),ie({sessionId:re,status:"complete",timestamp:Date.now()}),ve()}catch(re){p(Me(re)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[ie,y,m,l,s,ve]),Gt=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const re=await Mj(m.session.sessionId,y??void 0,l);le(re.sessionId),h({type:"breakdown",sessionId:re.sessionId,subtasks:re.subtasks,dirty:!1})}catch(re){p(Me(re)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),sn=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const re=m.sessionId,rt=await Aj(re,m.subtasks,l);a(rt.tasks),Fe(ct=>ct.filter(ft=>ft.id!==re)),ie({sessionId:re,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),j(""),ae(void 0),Ie(void 0),He("medium"),Te(""),T.current=null,le(null),me(null),ve()}catch(re){p(Me(re)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[ie,ve,m,a,l]),on=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const re=m.session.sessionId;p(null),h({type:"loading"});try{const rt=await Sj(re,l,we);x(rt.history.map(ct=>ct.response&&typeof ct.response=="object"&&!Array.isArray(ct.response)?ct.response:{[ct.question.id]:ct.response})),b(rt.history.map(ct=>({question:ct.question,response:ct.response&&typeof ct.response=="object"&&!Array.isArray(ct.response)?ct.response:{[ct.question.id]:ct.response},thinkingOutput:ct.thinkingOutput}))),j(""),h({type:"question",session:{...m.session,currentQuestion:rt.currentQuestion,summary:null}})}catch(rt){p(Me(rt)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,we,m]),Dn=()=>m.type==="question"?Math.min(g.length+1,3):3,Jt=oe?Q.get(oe):null,Hn=Jt&&Jt.tabId!==we,Yn=ge&&(!Hn||Jt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:re=>{gt.current=re.target===re.currentTarget},onClick:re=>{re.target===re.currentTarget&>.current&&ve(),gt.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:J,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[Re&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:qt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(Ml,{size:18})}),t.jsx(hi,{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:ve,"aria-label":"Close",children:t.jsx(nn,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${Re?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(VR,{sessions:_e,loading:bt,selectedSessionId:Ee,pendingDeleteId:Ke,showArchived:Xe,onToggleShowArchived:()=>wt(re=>!re),onArchive:re=>void he(re),onSelectSession:Ft,onNewSession:_t,onRequestDelete:pe,onConfirmDelete:re=>void z(re),onCancelDelete:()=>pe(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),C&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),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(bs,{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:ee,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:d,onChange:re=>{const rt=re.target.value;u(rt),!(L.current||rt.trim().length===0)&&(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{if(L.current)return;const ct=rt.trim();if(!ct)return;jj(ct,l,ke&&te?{planningModelProvider:ke,planningModelId:te}:void 0).then(it=>{L.current=it.sessionId,Fe(Y=>Y.some(Yt=>Yt.id===it.sessionId)?Y:[{id:it.sessionId,type:"planning",status:"draft",title:it.title,preview:ct.length>80?`${ct.slice(0,79).trimEnd()}…`:ct,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...Y].sort((Yt,In)=>Date.parse(In.updatedAt)-Date.parse(Yt.updatedAt))),me(it.sessionId)}).catch(()=>{})},300))},onKeyDown:re=>{re.key==="Enter"&&!re.shiftKey&&d.trim()&&(re.preventDefault(),Le())},onBlur:()=>{const re=L.current;re&&d.trim()&&st(re,d)}})]}),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:LR.map((re,rt)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(re),children:re.length>40?re.slice(0,40)+"...":re},rt))})]}),t.jsx(ni,{summary:"Advanced planning settings",className:"planning-advanced-disclosure",children:t.jsxs("div",{className:"planning-advanced-content",children:[t.jsxs("div",{className:"planning-advanced-section planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Ae&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx("p",{className:"planning-advanced-blurb",children:"Selects which model runs the planning interview and writes the final draft."}),t.jsx(ks,{id:"planning-modal-model",label:"Planning Model",value:fn,onChange:re=>{const{provider:rt,modelId:ct}=FR(re);ae(rt),Ie(ct)},models:ue,disabled:Ae,favoriteProviders:fe,onToggleFavorite:Vt,favoriteModels:De,onToggleModelFavorite:mn}),ye&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ye," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{tn()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ke&&te?"model-badge-custom":"model-badge-default"}`,children:un(ke,te)})})]}),t.jsxs("div",{className:"planning-advanced-section planning-depth-selector",children:[t.jsx("p",{className:"planning-advanced-blurb",children:"Plan size sets default interview depth. Questions lets you override with an exact count."}),t.jsxs("div",{className:"planning-depth-controls-row",children:[t.jsx("div",{className:"planning-depth-chip-group",role:"group","aria-label":"Planning depth",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(re=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${Oe===re.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>He(re.value),"aria-pressed":Oe===re.value,children:re.label},re.value))}),t.jsxs("label",{className:"planning-depth-question-count",htmlFor:"planning-depth-questions",children:[t.jsx("span",{children:"Questions"}),t.jsx("input",{id:"planning-depth-questions",className:"input planning-depth-question-input",type:"number",min:1,max:20,value:$e,onChange:re=>Te(re.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Le(),disabled:!d.trim(),children:[t.jsx(hi,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(xt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:w?"AI is thinking...":"Generating next question..."}),A&&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:()=>D(!_),type:"button",children:_?"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(dv,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),_&&w&&t.jsx("div",{className:"planning-thinking-output",ref:Tt,children:t.jsx("pre",{children:w})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{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 $t(),disabled:I,children:[I?t.jsx(xt,{size:14,className:"spin"}):t.jsx(hs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:I?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:ve,disabled:I,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(xt,{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(UR,{question:m.session.currentQuestion,progress:Dn(),historyEntries:v,onSubmit:ot,onBack:g.length>0?on:void 0})}),m.type==="summary"&&y&&t.jsx(BR,{summary:y,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:Wt,onBreakIntoTasks:Gt,onRefine:()=>{Nt()},isLoading:!1}),m.type==="breakdown"&&t.jsx(qR,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:re=>h({...m,subtasks:re,dirty:!0}),onCreateTasks:sn,onBack:()=>{const rt={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:rt,summary:y})}})]}),ge&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx($l,{size:16}),t.jsx("span",{children:Yn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Yn&&t.jsx("button",{type:"button",onClick:()=>{Ue()},disabled:Z,className:"btn btn-primary session-lock-take-control",children:Z?"Taking control...":"Take Control"})]})})]})]})}):null}function UR({question:e,progress:n,historyEntries:s,onSubmit:a,onBack:r}){const[o,l]=i.useState({}),[c,d]=i.useState(""),[u,m]=i.useState(""),h=i.useCallback(()=>{let p;e.type==="text"?p={[e.id]:c}:e.type==="confirm"?p={[e.id]:o[e.id]===!0}:p=o;const g=u.trim();g.length>0&&(p={...p,_comment:g}),a(p)},[u,e,o,c,a]);i.useEffect(()=>{l({}),d(""),m("")},[e.id]);const f=()=>{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(ii,{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(p=>t.jsx("div",{className:`planning-progress-step ${p<=n?"active":""}`},p))}),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:p=>d(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&c.trim()&&(p.preventDefault(),h())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(p=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:p.id,checked:o[e.id]===p.id,onChange:()=>l({[e.id]:p.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(p=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:p.id,checked:g.includes(p.id),onChange:x=>{const v=x.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:v})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.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(Gn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(nn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:u,onChange:p=>m(p.target.value)})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(ka,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:h,disabled:!f(),children:["Continue",t.jsx(oo,{size:16,className:"icon-ml-4"})]})]})]})}function BR({summary:e,historyEntries:n,onSummaryChange:s,tasks:a,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[d,u]=i.useState(!1),[m,h]=i.useState(e.suggestedDependencies),f=p=>{const g=m.includes(p)?m.filter(x=>x!==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(ni,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(ii,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Gn,{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:()=>u(!d),children:d?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${d?"expanded":""}`,rows:d?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)"})]})]}),a.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:a.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(ka,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:16,className:"icon-mr-8"}),"Create Single Task"]})}),t.jsx("button",{className:"btn btn-primary",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Il,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Np(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.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),a.add(o),!1};return e.some(o=>r(o.id))}function HR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function qR({subtasks:e,dirty:n,isLoading:s,onUpdateSubtasks:a,onCreateTasks:r,onBack:o}){const[l,c]=i.useState(null),[d,u]=i.useState(null),[m,h]=i.useState(null),f=i.useRef([]),p=i.useMemo(()=>e.length===0||e.some(j=>!j.title.trim())?!0:Np(e),[e]),g=i.useCallback((j,_)=>{a(e.map(D=>D.id===j?{...D,..._}:D))},[e,a]),x=i.useCallback(()=>{a([...e,HR(e.length+1)])},[e,a]),v=i.useCallback(j=>{a(e.filter(_=>_.id!==j).map(_=>({..._,dependsOn:_.dependsOn.filter(D=>D!==j)})))},[e,a]),b=i.useCallback((j,_)=>{if(_<0||_>=e.length)return;const D=[...e],[C]=D.splice(j,1);D.splice(_,0,C),a(D)},[e,a]),y=i.useCallback(j=>_=>{c(j),_.dataTransfer.setData("text/plain",j),_.dataTransfer.effectAllowed="move"},[]),S=i.useCallback(()=>{c(null),u(null),h(null)},[]),N=i.useCallback(j=>_=>{if(_.preventDefault(),j===l)return;const D=_.currentTarget.getBoundingClientRect(),C=D.top+D.height/2,P=_.clientY<C?"before":"after";u(j),h(P)},[l]),E=i.useCallback(j=>_=>{_.preventDefault();const D=_.dataTransfer.getData("text/plain");if(!D||D===j){S();return}const C=e.findIndex($=>$.id===D),P=e.findIndex($=>$.id===j);if(C===-1||P===-1){S();return}const I=[...e],[H]=I.splice(C,1);let A=P;m==="after"&&C<P&&A--,m==="after"&&A++,I.splice(A,0,H),a(I),S()},[e,m,a,S]),w=i.useCallback(j=>{const _=j.currentTarget.getBoundingClientRect(),D=j.clientX,C=j.clientY;(D<_.left||D>_.right||C<_.top||C>_.bottom)&&(u(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(Il,{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((j,_)=>{const D=l===j.id,C=d===j.id,P=["task-detail-section","subtask-item",D?"subtask-item-dragging":"",C?"subtask-item-drop-target":"",C&&m==="before"?"subtask-item-drop-before":"",C&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:P,"data-testid":`subtask-item-${_}`,draggable:!s,onDragStart:y(j.id),onDragEnd:S,onDragOver:N(j.id),onDrop:E(j.id),onDragLeave:w,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(Rl,{size:16}),t.jsx("strong",{children:j.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(_,_-1),disabled:s||_===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(fa,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(_,_+1),disabled:s||_===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(ro,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>v(j.id),disabled:s,children:[t.jsx(En,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:I=>{f.current[_]=I},value:j.title,onChange:I=>g(j.id,{title:I.target.value}),onKeyDown:I=>{I.key==="Enter"&&(I.preventDefault(),_<e.length-1&&f.current[_+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:j.description,onChange:I=>g(j.id,{description:I.target.value}),disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:j.suggestedSize,onChange:I=>g(j.id,{suggestedSize:I.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,_).filter(I=>I.id!==j.id).map(I=>{const H=j.dependsOn.includes(I.id);return t.jsxs("label",{className:`planning-dep-chip ${H?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:H,onChange:()=>{const A=H?j.dependsOn.filter($=>$!==I.id):[...j.dependsOn,I.id];g(j.id,{dependsOn:A})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:I.id}),t.jsx("span",{className:"planning-dep-title",children:I.title||"Untitled"})]},I.id)}),_===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),_>0&&e.slice(0,_).filter(I=>I.id!==j.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},j.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(_n,{size:16,className:"icon-mr-6"})," Add subtask"]}),Np(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(ka,{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(xt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function VR({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:a,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:d,onRequestDelete:u,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:d,type:"button",children:[t.jsx(Sy,{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=a===f.id,x=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${x?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(WR,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.status==="draft"&&(!f.title||f.title==="New planning session")?f.preview??"New planning session":f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(KR,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:GR(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:b=>{b.stopPropagation(),l(f.id)},"aria-label":x?"Unarchive session":"Archive session",title:x?"Unarchive session":"Archive session",children:x?t.jsx(Lx,{size:14}):t.jsx(ao,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:b=>{b.stopPropagation(),u(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(En,{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 WR({status:e}){switch(e){case"generating":return t.jsx(xt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(ud,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Gn,{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(zi,{size:14,className:"planning-sidebar-status-icon"})}}function KR({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 GR(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 a=Math.floor(s/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/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 JR(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Sp(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.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),a.add(o),!1};return e.some(o=>r(o.id))}function YR({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=Js();pi(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=ra({enabled:c==="mobile"}),f=h?{"--keyboard-overlap":`${d}px`,"--vv-offset-top":`${m}px`,...u!==null?{"--vv-height":`${u}px`}:{}}:{},[p,g]=i.useState({type:"initial"}),[x,v]=i.useState([]),[b,y]=i.useState([]),[S,N]=i.useState(""),[E,w]=i.useState(!0),[j,_]=i.useState(!1),[D,C]=i.useState(!1),[P,I]=i.useState(s),[H,A]=i.useState(null),[$,F]=i.useState(!1),[G,ee]=i.useState(null),[J,M]=i.useState(null),[T,L]=i.useState(null),k=i.useRef(null),K=i.useRef([]),oe=i.useRef(!1),le=i.useRef(null),we=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,ge=i.useMemo(()=>Ca(),[]),{isLockedByOther:Ue,takeControl:Z,isLoading:Q}=Jl(e?we:null),{activeTabMap:X,broadcastUpdate:ie,broadcastCompleted:se,broadcastLock:B,broadcastUnlock:O,broadcastHeartbeat:ke}=gr(),ae=i.useMemo(()=>x.length===0||x.some(Ee=>!Ee.title.trim())?!0:Sp(x),[x]),te=p.type==="generating"||p.type==="editing"||p.type==="error",Ie=we?X.get(we):null,{confirm:Oe}=Ys(),He=Ie&&Ie.tabId!==ge,$e=!!(He&&!Ie.stale),Te=Ue&&(!He||Ie.stale),ue=i.useCallback(()=>{P&&KT(P,o),k.current?.close(),k.current=null,g({type:"initial"}),v([]),y([]),N(""),w(!0),_(!1),C(!1),A(null),F(!1),oe.current=!1},[P,o]),ce=i.useCallback(()=>{k.current?.close(),k.current=null,n()},[n]),Ae=i.useCallback(async()=>{if(!(($||p.type==="editing"||p.type==="creating")&&!await Oe({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(we)try{await Kf(we,o,ge)}catch{}ue(),n()}},[$,n,ue,we,ge,p.type,o,Oe]),Ne=i.useCallback(Ee=>{k.current?.close(),k.current=aN(Ee,o,{onThinking:me=>{N(Re=>Re+me),ie({sessionId:Ee,status:"generating",needsInput:!1,owningTabId:ge,type:"subtask",title:P.trim()||void 0,projectId:o??null})},onSubtasks:me=>{_(!1),C(!1),Hc(o),v(me),g({type:"editing",sessionId:Ee}),F(!1),ie({sessionId:Ee,status:"awaiting_input",needsInput:!0,owningTabId:ge,type:"subtask",title:P.trim()||void 0,projectId:o??null})},onError:me=>{const Re=me||"Session failed while contacting the AI.";_(!1),C(!1),A(null),g({type:"error",sessionId:Ee,errorMessage:Re}),ie({sessionId:Ee,status:"error",needsInput:!1,owningTabId:ge,type:"subtask",title:P.trim()||void 0,projectId:o??null}),se({sessionId:Ee,status:"error"})},onComplete:()=>{se({sessionId:Ee,status:"complete"})},onConnectionStateChange:me=>{_(me==="reconnecting")}})},[se,ie,P,o,ge]),ye=i.useCallback(async()=>{if(P.trim()){A(null),y([]),N(""),_(!1);try{const{sessionId:Ee}=await nN(P.trim(),o);g({type:"generating",sessionId:Ee}),Ne(Ee)}catch(Ee){A(Me(Ee)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[Ne,P,o]);i.useEffect(()=>{if(!e){ue();return}if(e&&s&&!oe.current)I(s),oe.current=!0,ye();else if(e&&!s&&!oe.current){const Ee=GT(o);Ee&&I(Ee)}},[e,s,ye,ue]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const Ee=await Ei(l);if(!Ee)return;const me=nr(Ee.conversationHistory);if(y(me),Ee.status==="generating"||Ee.status==="awaiting_input")N(Ee.thinkingOutput??""),g({type:"generating",sessionId:l}),Ne(l);else if(Ee.status==="complete"&&Ee.result){Hc(o);const Re=JSON.parse(Ee.result);v(Re),g({type:"editing",sessionId:l})}else Ee.status==="error"&&(A(null),g({type:"error",sessionId:l,errorMessage:Ee.error??"Session encountered an error"}))}catch(Ee){A(Me(Ee)||"Failed to resume session")}})()},[Ne,e,l,p.type,o]),i.useEffect(()=>{if(!e){le.current&&(O(le.current,ge),le.current=null);return}if(we&&le.current!==we){le.current&&O(le.current,ge),B(we,ge),le.current=we;return}!we&&le.current&&(O(le.current,ge),le.current=null)},[B,O,e,we,ge]),i.useEffect(()=>{if(!e||!we||le.current!==we)return;ke(ge);const Ee=setInterval(()=>{ke(ge)},3e4);return()=>{clearInterval(Ee)}},[ke,e,we,ge]),i.useEffect(()=>()=>{k.current?.close(),le.current&&(O(le.current,ge),le.current=null)},[O,ge]),i.useEffect(()=>{if(!e)return;const Ee=me=>{me.key==="Escape"&&(me.preventDefault(),Ae())};return document.addEventListener("keydown",Ee),()=>document.removeEventListener("keydown",Ee)},[e,Ae]);const Ce=i.useCallback((Ee,me)=>{v(Re=>Re.map(be=>be.id===Ee?{...be,...me}:be)),F(!0)},[]),fe=i.useCallback(()=>{v(Ee=>[...Ee,JR(Ee.length+1)]),F(!0)},[]),Pe=i.useCallback(Ee=>{v(me=>me.filter(Re=>Re.id!==Ee).map(Re=>({...Re,dependsOn:Re.dependsOn.filter(be=>be!==Ee)}))),F(!0)},[]),De=i.useCallback(Ee=>me=>{ee(Ee),me.dataTransfer.setData("text/plain",Ee),me.dataTransfer.effectAllowed="move"},[]),dt=i.useCallback(()=>{ee(null),M(null),L(null)},[]),pt=i.useCallback(Ee=>me=>{if(me.preventDefault(),Ee===G)return;const Re=me.currentTarget.getBoundingClientRect(),be=Re.top+Re.height/2,Ke=me.clientY<be?"before":"after";M(Ee),L(Ke)},[G]),lt=i.useCallback(Ee=>me=>{me.preventDefault();const Re=me.dataTransfer.getData("text/plain");if(!Re||Re===Ee){ee(null),M(null),L(null);return}v(be=>{const Ke=be.findIndex(Tt=>Tt.id===Re),pe=be.findIndex(Tt=>Tt.id===Ee);if(Ke===-1||pe===-1)return be;const Xe=[...be],[wt]=Xe.splice(Ke,1);let gt=pe;return T==="after"&&Ke<pe&>--,T==="after"&>++,Xe.splice(gt,0,wt),Xe}),F(!0),ee(null),M(null),L(null)},[T]),vt=i.useCallback(Ee=>{const me=Ee.currentTarget.getBoundingClientRect(),Re=Ee.clientX,be=Ee.clientY;(Re<me.left||Re>me.right||be<me.top||be>me.bottom)&&(M(null),L(null))},[]),_e=i.useCallback((Ee,me)=>{me<0||me>=x.length||(v(Re=>{const be=[...Re],[Ke]=be.splice(Ee,1);return be.splice(me,0,Ke),be}),F(!0))},[x.length]),Fe=i.useCallback(Ee=>{K.current[Ee+1]?.focus()},[]),bt=i.useCallback(async()=>{if(!(!we||ae)){A(null),g({type:"creating",sessionId:we});try{const Ee=await rN(we,x,r,o);a(Ee.tasks),ue(),n()}catch(Ee){A(Me(Ee)||"Failed to create tasks"),g({type:"editing",sessionId:we})}}},[ae,n,a,r,o,ue,we,x]),ht=i.useCallback(async()=>{if(p.type!=="error")return;const Ee=p.sessionId;A(null),C(!0),N(""),g({type:"generating",sessionId:Ee}),Ne(Ee);try{await sN(Ee,o,ge)}catch(me){let Re=me;if((Me(me)||"").includes("not in an error state"))try{const Ke=await Ei(Ee);if(!Ke)throw new Error("Failed to refresh subtask session.");if(y(nr(Ke.conversationHistory)),Ke.status==="generating"||Ke.status==="awaiting_input")N(Ke.thinkingOutput??""),g({type:"generating",sessionId:Ke.id}),k.current?.isConnected()||Ne(Ke.id);else if(Ke.status==="complete"){if(!Ke.result)throw new Error("Subtask session is complete but has no result.");Hc(o);const pe=JSON.parse(Ke.result);v(pe),g({type:"editing",sessionId:Ke.id}),F(!1)}else Ke.status==="error"&&g({type:"error",sessionId:Ke.id,errorMessage:Ke.error??"Retry failed. Please try again."});_(!1);return}catch(Ke){Re=Ke}k.current?.close(),k.current=null,g({type:"error",sessionId:Ee,errorMessage:Me(Re)||"Retry failed. Please try again."}),_(!1)}finally{C(!1)}},[Ne,o,ge,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ee=>Ee.target===Ee.currentTarget&&void Ae(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",style:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Il,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[te&&t.jsx("button",{className:"modal-send-to-background",onClick:ce,title:"Send to background","aria-label":"Send to background",children:t.jsx(uo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void Ae(),"aria-label":"Close",children:t.jsx(nn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[H&&t.jsx("div",{className:"form-error planning-error",children:H}),j&&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."}),p.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:P})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(xt,{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:()=>w(!E),type:"button",children:E?"Hide thinking":"Show thinking"}),E&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),p.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(ii,{entries:b,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:p.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ht(),disabled:D,children:[D?t.jsx(xt,{size:14,className:"spin"}):t.jsx(hs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:D?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void Ae(),disabled:D,children:"Cancel"})]})]})]})}),(p.type==="editing"||p.type==="creating")&&t.jsxs("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(ii,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Gn,{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:[x.map((Ee,me)=>{const Re=G===Ee.id,be=J===Ee.id,Ke=["task-detail-section","subtask-item",Re?"subtask-item-dragging":"",be?"subtask-item-drop-target":"",be&&T==="before"?"subtask-item-drop-before":"",be&&T==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:Ke,"data-testid":`subtask-item-${me}`,draggable:p.type!=="creating",onDragStart:De(Ee.id),onDragEnd:dt,onDragOver:pt(Ee.id),onDrop:lt(Ee.id),onDragLeave:vt,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(Rl,{size:16}),t.jsx("strong",{children:Ee.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(me,me-1),disabled:p.type==="creating"||me===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(fa,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_e(me,me+1),disabled:p.type==="creating"||me===x.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(ro,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>Pe(Ee.id),disabled:p.type==="creating",children:[t.jsx(En,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:pe=>{K.current[me]=pe},value:Ee.title,onChange:pe=>Ce(Ee.id,{title:pe.target.value}),onKeyDown:pe=>{pe.key==="Enter"&&(pe.preventDefault(),Fe(me))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:Ee.description,onChange:pe=>Ce(Ee.id,{description:pe.target.value}),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:Ee.suggestedSize,onChange:pe=>Ce(Ee.id,{suggestedSize:pe.target.value}),disabled:p.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:[x.slice(0,me).filter(pe=>pe.id!==Ee.id).map(pe=>{const Xe=Ee.dependsOn.includes(pe.id);return t.jsxs("label",{className:`planning-dep-chip ${Xe?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Xe,onChange:()=>{const wt=Xe?Ee.dependsOn.filter(gt=>gt!==pe.id):[...Ee.dependsOn,pe.id];Ce(Ee.id,{dependsOn:wt})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:pe.id}),t.jsx("span",{className:"planning-dep-title",children:pe.title||"Untitled"})]},pe.id)}),me===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),me>0&&x.slice(0,me).filter(pe=>pe.id!==Ee.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},Ee.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:fe,disabled:p.type==="creating",children:[t.jsx(_n,{size:16,className:"icon-mr-6"})," Add subtask"]}),Sp(x)&&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 Ae(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void bt(),disabled:p.type==="creating"||ae,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),Ue&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx($l,{size:16}),t.jsx("span",{children:Te?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Te&&t.jsx("button",{type:"button",onClick:()=>{Z()},disabled:Q,className:"btn btn-primary session-lock-take-control",children:Q?"Taking control...":"Take Control"})]})})]})]})}):null}const QR=5,XR=1e3,ZR=45e3;function Ko(){return{scrollback:null,connected:null,data:[]}}function eI(e,n){const[s,a]=i.useState("disconnected"),r=i.useRef(0),o=i.useRef(e),l=i.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const d=i.useRef(null),u=i.useRef(0),m=i.useRef(null),h=i.useRef(null),f=i.useRef(!1),p=i.useRef(new Set),g=i.useRef(new Set),x=i.useRef(new Set),v=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(Ko()),S=i.useCallback(A=>{p.current.add(A);const $=y.current;return $.data.length>0&&($.data.forEach(F=>A(F)),$.data=[]),()=>p.current.delete(A)},[]),N=i.useCallback(A=>(g.current.add(A),()=>g.current.delete(A)),[]),E=i.useCallback(A=>{x.current.add(A);const $=y.current;return $.connected&&(A($.connected),$.connected=null),()=>x.current.delete(A)},[]),w=i.useCallback(A=>{v.current.add(A);const $=y.current;return $.scrollback&&(A($.scrollback),$.scrollback=null),()=>v.current.delete(A)},[]),j=i.useCallback(A=>(b.current.add(A),()=>b.current.delete(A)),[]),_=i.useCallback(A=>{const $=d.current;$?.readyState===WebSocket.OPEN&&$.send(JSON.stringify({type:"input",data:A}))},[]),D=i.useCallback((A,$)=>{const F=d.current;F?.readyState===WebSocket.OPEN&&F.send(JSON.stringify({type:"resize",cols:A,rows:$}))},[]),C=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Ko()},[]),P=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Ko()},[]),I=i.useCallback(()=>{if(!e){a("disconnected");return}if(d.current?.readyState===WebSocket.OPEN)return;d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),f.current=!1,a("connecting");const A=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 G=new WebSocket(_i(F));d.current=G,G.onopen=()=>{if(r.current!==A){G.close();return}y.current=Ko(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===A&&G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"ping"}))},ZR)},G.onmessage=ee=>{if(r.current===A)try{const J=JSON.parse(ee.data),M=y.current;switch(J.type){case"data":J.data&&(p.current.size===0&&M.data.push(J.data),p.current.forEach(T=>T(J.data)));break;case"scrollback":J.data&&(M.scrollback=J.data,v.current.forEach(T=>T(J.data)));break;case"connected":J.shell&&J.cwd&&(M.connected={shell:J.shell,cwd:J.cwd},x.current.forEach(T=>T({shell:J.shell,cwd:J.cwd})));break;case"exit":J.exitCode!==void 0&&g.current.forEach(T=>T(J.exitCode));break;case"ping":G.readyState===WebSocket.OPEN&&G.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},G.onclose=ee=>{if(r.current!==A)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(ee.code===4e3||ee.code===4004){a("disconnected"),ee.code===4004&&b.current.forEach(T=>T());return}if(u.current++,u.current>QR){a("disconnected");return}const J=XR*Math.pow(2,u.current-1);a("reconnecting");const M=r.current;m.current=setTimeout(()=>{r.current===M&&(f.current||I())},Math.min(J,16e3))},G.onerror=()=>{}},[e,n]),H=i.useCallback(()=>{u.current=0,P(),I()},[P,I]);return i.useEffect(()=>(c&&(C(),u.current=0,a("disconnected")),e?I():a("disconnected"),P),[e,n,c,I,P,C]),{connectionStatus:s,sendInput:_,resize:D,onData:S,onExit:N,onConnect:E,onScrollback:w,reconnect:H,onSessionInvalid:j}}const Gb="kb-terminal-tabs",tI=15e3,nI=15e3;function Cp(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Ep(e){if(typeof window>"u")return[];try{const n=ss(Gb,e);if(n)return JSON.parse(n)}catch{}return[]}function Jc(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function _p(e,n,s){let a;const r=new Promise((o,l)=>{a=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(a))}function sI(e){const[n,s]=i.useState(()=>Ep(e)),[a,r]=i.useState(!1),[o,l]=i.useState(!0),[c,d]=i.useState(null),[u,m]=i.useState(0),h=i.useRef(0);i.useEffect(()=>{h.current+=1,s(Ep(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{xs(Gb,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let E=!1;const w=h.current;return(async()=>{if(!E)try{const _=await _p(Yk(e),tI,"listTerminalSessions");if(E||w!==h.current)return;const D=new Set(_.map(C=>C.id));l(!0),s(C=>{if(E||w!==h.current)return C;const I=C.map($=>({...$,_verified:D.has($.sessionId)})).filter($=>$._verified);if(I.length===0)return[];const H=I.map(({_verified:$,...F})=>F);return H.find($=>$.isActive)?H:H.map(($,F)=>({...$,isActive:F===0}))}),r(!0)}catch(_){if(E||w!==h.current)return;const D=Jc(_);D||console.warn("Failed to validate terminal sessions with server:",_),l(!D),r(!0)}})(),()=>{E=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const E=h.current,w=setTimeout(()=>{_p(No(void 0,void 0,void 0,e),nI,"createTerminalSession").then(j=>{if(E!==h.current)return;const _={id:Cp(),sessionId:j.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(D=>D.length>0?D:[...D.map(P=>({...P,isActive:!1})),_]),d(null)}).catch(j=>{if(E!==h.current)return;Jc(j)||console.error(j);const _=j instanceof Error?j.message:typeof j=="string"?j:"Failed to create terminal session";d(_)})},0);return()=>clearTimeout(w)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const E=await No(void 0,void 0,void 0,e),w={id:Cp(),sessionId:E.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(j=>[...j.map(D=>({...D,isActive:!1})),w]),w},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(E=>{s(w=>{const j=w.find(P=>P.id===E);if(!j)return w;Vu(j.sessionId,e).catch(P=>{console.warn(`Failed to kill terminal session ${j.sessionId}:`,P)});const _=w.findIndex(P=>P.id===E),D=j.isActive,C=w.filter(P=>P.id!==E);if(C.length===0)return[];if(D){const P=Math.min(_,C.length-1);return C.map((I,H)=>({...I,isActive:H===P}))}return C})},[]),x=i.useCallback(E=>{s(w=>{let j=!1;const _=w.map(D=>D.id===E?(j=!0,{...D,isActive:!0}):{...D,isActive:!1});return j?_:w})},[]),v=i.useCallback((E,w)=>{s(j=>j.map(_=>_.id===E?{..._,title:w}:_))},[]),b=i.useCallback(async()=>{s(j=>{const _=j.find(D=>D.isActive);return _&&Vu(_.sessionId,e).catch(D=>{console.warn(`Failed to kill old session ${_.sessionId}:`,D)}),j});const E=n.find(j=>j.isActive);if(!E)return;const w=await No(void 0,void 0,void 0,e);s(j=>j.map(_=>_.id===E.id?{..._,sessionId:w.sessionId}:_))},[n]),y=i.useCallback(async()=>{const E=n.find(w=>w.isActive);if(E)try{const w=await No(void 0,void 0,void 0,e);s(j=>j.map(_=>_.id===E.id?{..._,sessionId:w.sessionId}:_)),d(null)}catch(w){Jc(w)||console.error(w);const j=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";d(j)}},[n]),S=n.find(E=>E.isActive)??null,N=i.useCallback(()=>{d(null),h.current+=1,m(E=>E+1)},[]);return{tabs:n,activeTab:S,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:v,restartActiveTab:b,retryBootstrap:N,replaceActiveTabSession:y}}const iI=1e4,aI=[500,1500,3e3],Jb="kb-terminal-font-size",Ur=14,rI=8,oI=32,lI='"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 cI(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 dI(e){return`\x1B${e}`}const uI=[{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 Br(e){return Math.min(oI,Math.max(rI,e))}function mI(){if(typeof window>"u")return Ur;try{const e=window.localStorage.getItem(Jb);if(!e)return Ur;const n=Number.parseInt(e,10);return Number.isFinite(n)?Br(n):Ur}catch{return Ur}}function hI(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 pI(e){return new Promise(n=>setTimeout(n,e))}async function fI(e,n=aI){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!hI(r))throw r;s===void 0&&(s=r);const o=n[a];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${a+1}/${n.length+1}). Retrying in ${o}ms...`,l),await pI(o)}throw s??new Error("Dynamic import failed")}function Mp(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function gI(){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 a=bI()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let Yc=null;function bI(){return Yc===null&&(Yc=window.innerHeight),Yc}function xI({isOpen:e,onClose:n,initialCommand:s,projectId:a}){const[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(0),[g,x]=i.useState(0),[v,b]=i.useState(null),[y,S]=i.useState(()=>mI()),[N,E]=i.useState(!1),[w,j]=i.useState(null),_=i.useRef(null),D=i.useRef(null),C=i.useRef(!1);Ti(D,e,"fusion:terminal-modal-size");const P=i.useRef(null),I=i.useRef(null),H=i.useRef(!1),A=i.useRef(!1),$=i.useRef(null),F=i.useRef(()=>{}),G=i.useRef(null),ee=i.useRef(0),J=i.useRef(y),M=i.useRef(null),T=i.useRef(a);ee.current=g,J.current=y;const L=i.useCallback(_e=>{if(_e&&A.current!==_e)return;const Fe=I.current,bt=P.current,ht=$.current;if(!(!Fe||!bt)&&!(_e&&A.current!==_e))try{Fe.fit(),ht&&ht(bt.cols,bt.rows)}catch{}},[]);i.useEffect(()=>{e&&p(_e=>_e+1)},[e]),i.useEffect(()=>{if(!e||!Mp())return;const _e=window.visualViewport;if(!_e)return;const Fe=()=>{const bt=gI();x(bt),b(_e.height),bt>0&&D.current?.scrollIntoView&&D.current.scrollIntoView({block:"end",behavior:"smooth"}),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const ht=typeof A.current=="string"?A.current:void 0;M.current=requestAnimationFrame(()=>{M.current=null,L(ht)})};return Fe(),_e.addEventListener("resize",Fe),_e.addEventListener("scroll",Fe),()=>{_e.removeEventListener("resize",Fe),_e.removeEventListener("scroll",Fe),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),x(0),b(null)}},[L,e]),i.useEffect(()=>{if(!e)return;const _e=D.current;if(!_e||typeof ResizeObserver>"u")return;let Fe=null;const bt=new ResizeObserver(()=>{Fe!==null&&cancelAnimationFrame(Fe),Fe=requestAnimationFrame(()=>{Fe=null;const ht=typeof A.current=="string"?A.current:void 0;L(ht)})});return bt.observe(_e),()=>{bt.disconnect(),Fe!==null&&cancelAnimationFrame(Fe)}},[L,e]);const{tabs:k,activeTab:K,isReady:oe,bootstrapError:le,createTab:we,closeTab:ge,setActiveTab:Ue,updateTabTitle:Z,restartActiveTab:Q,retryBootstrap:X,replaceActiveTabSession:ie}=sI(a),{connectionStatus:se,sendInput:B,resize:O,onData:ke,onConnect:ae,onExit:te,onScrollback:Ie,reconnect:Oe,onSessionInvalid:He}=eI(K?.sessionId??null,a);$.current=O,F.current=B,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(Jb,String(y))}catch{}},[y]);const $e=i.useCallback(()=>{const _e=P.current;if(_e)try{I.current?.fit(),O(_e.cols,_e.rows)}catch{}},[O]);i.useEffect(()=>{if(!e||!oe)return;const _e=K?.sessionId;if(!_e)return;const Fe=T.current!==a;if(Fe&&(T.current=a),A.current===_e&&P.current&&!Fe)return;P.current&&(A.current!==_e||Fe)&&(P.current.dispose(),P.current=null,I.current=null,A.current=!1,G.current&&(window.removeEventListener("resize",G.current),G.current=null),u(!1),h(null));let bt=!0,ht;return(async()=>{const me=fI(()=>Promise.all([Rn(()=>import("./vendor-xterm-DzcZoU0P.js").then(pe=>pe.x),__vite__mapDeps([5,1,6])),Rn(()=>import("./addon-fit-C7jRorKK.js").then(pe=>pe.a),__vite__mapDeps([8,1])),Rn(()=>import("./addon-web-links-CkJwd4cQ.js").then(pe=>pe.a),__vite__mapDeps([9,1]))])),Re=new Promise((pe,Xe)=>{ht=setTimeout(()=>{Xe(new Error("xterm initialization timed out"))},iI)});let be,Ke;try{const[{Terminal:pe},{FitAddon:Xe},{WebLinksAddon:wt}]=await Promise.race([me,Re]);if(!bt||!_.current||P.current)return;be=new pe({cursorBlink:!0,cursorStyle:"block",fontSize:J.current,fontFamily:lI,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}),Ke=new Xe,be.loadAddon(Ke);const gt=new wt;if(be.loadAddon(gt),!Mp())try{const{WebglAddon:Ot}=await Rn(async()=>{const{WebglAddon:en}=await import("./addon-webgl-BjvOw43o.js").then(zt=>zt.a);return{WebglAddon:en}},__vite__mapDeps([10,1])),Rt=new Ot;Rt.onContextLoss(()=>{Rt.dispose()}),be.loadAddon(Rt)}catch{}be.open(_.current),ht&&clearTimeout(ht);const Tt=_.current?.querySelector(".xterm-helper-textarea");if(Tt&&Tt.focus(),_.current)try{_.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{Ke.fit();const Ot=_.current?.querySelector(".xterm-helper-textarea");Ot&&Ot.focus()},50),P.current=be,I.current=Ke,A.current=_e,ee.current>0&&(M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),M.current=requestAnimationFrame(()=>{M.current=null,L(_e)})),be.onData(Ot=>{A.current===_e&&F.current(Ot)});const Zt=()=>{if(A.current===_e&&I.current&&P.current)try{I.current.fit();const{cols:Ot,rows:Rt}=P.current;$.current?.(Ot,Rt)}catch{}};window.addEventListener("resize",Zt),G.current&&window.removeEventListener("resize",G.current),G.current=Zt,u(!0),h(null)}catch(pe){if(ht&&clearTimeout(ht),!bt)return;const Xe=pe instanceof Error?pe.message:"xterm initialization failed";h(Xe)}})(),()=>{bt=!1,ht&&clearTimeout(ht)}},[L,e,oe,K?.sessionId,a]),i.useEffect(()=>{e||(P.current&&(P.current.dispose(),P.current=null),I.current=null,A.current=!1,G.current&&(window.removeEventListener("resize",G.current),G.current=null),u(!1),h(null),H.current=!1,o(null),c(null),E(!1),j(null))},[e]),i.useEffect(()=>{if(!d||!P.current||!K)return;const _e=K.sessionId,Fe=Re=>{A.current===_e&&P.current?.write(Re)},bt=ke(Re=>{Fe(Re)}),ht=Ie(Re=>{Fe(Re)}),Ee=ae(Re=>{Z(K.id,ru(Re.shell)||Re.shell)}),me=te(Re=>{A.current===_e&&(c(Re),P.current?.write(`\r
|
|
689
|
-
\x1B[33m[Process exited with code ${Re}]\x1B[0m\r
|
|
690
|
-
`))});return()=>{bt(),ht(),Ee(),me()}},[d,K?.sessionId,K?.id,K,se,ke,Ie,ae,te,Z]),i.useEffect(()=>{se==="connected"&&s&&H.current!==s&&K&&(H.current=s,setTimeout(()=>{B(s+`
|
|
691
|
-
`)},500))},[se,s,B,K,f]),i.useEffect(()=>{if(!d||!P.current)return;P.current.options.fontSize=y,M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const _e=requestAnimationFrame(()=>{M.current=null,$e()});return M.current=_e,()=>{M.current===_e&&(cancelAnimationFrame(_e),M.current=null)}},[y,d,$e]),i.useEffect(()=>{if(!e)return;const _e=Fe=>{if(!(!Fe.ctrlKey&&!Fe.metaKey)){if(Fe.code==="Equal"||Fe.code==="NumpadAdd"){Fe.preventDefault(),S(bt=>Br(bt+1));return}if(Fe.code==="Minus"||Fe.code==="NumpadSubtract"){Fe.preventDefault(),S(bt=>Br(bt-1));return}if(Fe.code==="Digit0"||Fe.code==="Numpad0"){Fe.preventDefault(),S(Ur);return}}};return window.addEventListener("keydown",_e),()=>window.removeEventListener("keydown",_e)},[e,$e]),i.useEffect(()=>{if(!e)return;const _e=Fe=>{Fe.key==="Escape"&&n()};return document.addEventListener("keydown",_e),()=>document.removeEventListener("keydown",_e)},[e,n]),i.useEffect(()=>{se==="connected"&&P.current&&setTimeout(()=>{if(!P.current||!_.current)return;const _e=_.current.querySelector(".xterm-helper-textarea");_e&&_e.focus();try{_.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[se]);const Te=i.useCallback(()=>{if(!_.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;P.current?.focus();const Fe=_.current.querySelector(".xterm-helper-textarea");if(!Fe)return;Fe.autocapitalize="off",Fe.autocomplete="off",Fe.autocorrect="off",Fe.spellcheck=!1,Fe.setAttribute("inputmode","text");try{Fe.focus({preventScroll:!0})}catch{Fe.focus()}const bt=Fe.value.length;Fe.setSelectionRange(bt,bt)},[]);i.useEffect(()=>He(()=>{P.current?.clear(),c(null),H.current=!1,P.current&&(P.current.dispose(),P.current=null),I.current=null,A.current=!1,G.current&&(window.removeEventListener("resize",G.current),G.current=null),u(!1),h(null),ie().catch(Fe=>{console.error("Failed to replace invalid terminal session:",Fe)})}),[He,ie]);const ue=i.useCallback(_e=>{_e.target===_e.currentTarget&&(C.current=!0)},[]),ce=i.useCallback(_e=>{C.current&&_e.target===_e.currentTarget&&n(),C.current=!1},[n]),Ae=i.useCallback(()=>{P.current?.clear()},[]),Ne=i.useCallback(async()=>{P.current?.clear(),c(null),H.current=!1;try{await Q()}catch(_e){o(Me(_e)||"Failed to restart terminal session")}},[Q]),ye=i.useCallback(()=>{P.current&&(P.current.dispose(),P.current=null),I.current=null,A.current=!1,G.current&&(window.removeEventListener("resize",G.current),G.current=null),h(null),u(!1)},[]),Ce=i.useCallback(()=>{window.location.reload()},[]),fe=i.useCallback(()=>{S(_e=>Br(_e+1))},[]),Pe=i.useCallback(()=>{S(_e=>Br(_e-1))},[]),De=i.useCallback(_e=>{j(Fe=>Fe===_e?null:_e)},[]),dt=i.useCallback(_e=>{if(w==="ctrl"){B(cI(_e)),j(null);return}if(w==="alt"){B(dI(_e)),j(null);return}B(_e)},[B,w]),pt=i.useCallback(_e=>{B(_e),j(null)},[B]);if(!e)return null;const lt=()=>{switch(se){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}},vt=!oe||!K&&!le;return t.jsx("div",{className:"modal-overlay open",onMouseDown:ue,onMouseUp:ce,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:D,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[k.map(_e=>t.jsxs("div",{className:`terminal-tab ${_e.isActive?"terminal-tab--active":""}`,onClick:()=>Ue(_e.id),title:_e.title,role:"tab","aria-selected":_e.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:_e.title}),k.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Fe=>{Fe.stopPropagation(),ge(_e.id)},title:"Close tab",children:"×"})]},_e.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:we,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Fi,{size:16}),lt()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[se==="disconnected"&&K&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Oe,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(hs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Ne,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(hs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Ae,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(En,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>E(_e=>!_e),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":N,children:[t.jsx(oy,{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(nn,{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:[vt&&!le&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),le&&!K&&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: ",le]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:X,"data-testid":"terminal-retry-btn",children:[t.jsx(hs,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ce,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(hs,{size:14}),"Refresh page"]})]})]})}),m&&K&&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:ye,"data-testid":"terminal-reinit-btn",children:[t.jsx(hs,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ce,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(hs,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:_,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Te,onTouchStart:Te},K?.sessionId)]}),N&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>De("ctrl"),"aria-pressed":w==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>De("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>pt("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>pt(" "),children:"Tab"})]}),uI.map(_e=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>dt(_e.key),title:_e.description,children:_e.label},_e.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${se}`,children:[se==="connected"&&"Connected",se==="connecting"&&"Connecting...",se==="reconnecting"&&"Reconnecting...",se==="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:Pe,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(My,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:fe,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(_n,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Pr={name:"",command:""};function Ap(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function vI(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function yI({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){pi(e);const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[h,f]=i.useState(null),[p,g]=i.useState(Pr),[x,v]=i.useState(!1),[b,y]=i.useState(null),[S,N]=i.useState(null),E=Ui(n),w=i.useCallback(async()=>{try{d(!0);const F=await eo(a);l(F)}catch(F){s(Me(F)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&w()},[e,w]);const j=i.useCallback(()=>{m(!0),f(null),g(Pr),N(null)},[]),_=i.useCallback((F,G)=>{f(F),m(!1),g({name:F,command:G}),N(null)},[]),D=i.useCallback(()=>{f(null),m(!1),g(Pr),N(null)},[]),C=i.useCallback(F=>{g(G=>({...G,name:F})),F&&!Ap(F)?N("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):N(null)},[]),P=i.useCallback(async()=>{const F=p.name.trim(),G=p.command.trim();if(!F){s("Script name is required","error");return}if(!Ap(F)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!G){s("Script command is required","error");return}v(!0);try{await eN(F,G,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(Pr),N(null),await w()}catch(ee){const J=Me(ee);J?.includes("already exists")?s("A script with this name already exists","error"):s(J||"Failed to save script","error")}finally{v(!1)}},[p,h,s,w,a]),I=i.useCallback(async F=>{try{await tN(F,a),s("Script deleted","success"),y(null),h===F&&(f(null),g(Pr)),await w()}catch(G){s(Me(G)||"Failed to delete script","error")}},[h,s,w,a]),H=i.useCallback((F,G)=>{r&&r(F,G)},[r]);if(!e)return null;const A=u||h!==null,$=Object.entries(o).map(([F,G])=>({name:F,command:G}));return t.jsx("div",{className:"modal-overlay open",...E,"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(Fi,{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(xt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):A?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=>C(F.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:F=>g(G=>({...G,command:F.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:D,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:P,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:$.length===0?"No scripts defined":`${$.length} script${$.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:j,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(_n,{size:14}),"Add Script"]})]}),$.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(Fi,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:$.map(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:vI(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:()=>H(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(ls,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>_(F.name,F.command),title:"Edit","aria-label":`Edit ${F.name}`,"data-testid":`edit-script-${F.name}`,children:t.jsx(_n,{size:14,style:{transform:"rotate(45deg)"}})}),b===F.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>I(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(En,{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(nn,{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(En,{size:14})})]})]})},F.name))})]})})]})})}function wI(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState("."),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(0),p=i.useCallback(()=>{f(x=>x+1)},[]),g=i.useCallback(x=>{l(x),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let x=!1;async function v(){d(!0),m(null);try{const b=await pj(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(Me(b)||"Failed to load files"),r([]))}finally{x||d(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function kI(e,n,s,a){const[r,o]=i.useState(""),[l,c]=i.useState(""),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(null),v=i.useCallback(S=>{o(S),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let S=!1;async function N(){h(!0),x(null);try{const E=await fj(e,n,a);S||(o(E.content),c(E.content),u(E.mtime))}catch(E){S||(x(Me(E)||"Failed to load file"),o(""),c(""),u(null))}finally{S||h(!1)}}return N(),()=>{S=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await gj(e,n,r,a);c(r),u(S.mtime)}catch(S){throw x(Me(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const jI=1e4;function NI(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function SI(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function CI(e){const[n,s]=i.useState("Project Root"),[a,r]=i.useState([]),[o,l]=i.useState(!0),[c,d]=i.useState(null);return i.useEffect(()=>{let u=!1;async function m(){try{const f=await hj(e);if(u)return;s(NI(f.project)),r(f.tasks.map(SI)),d(null)}catch(f){u||d(Me(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},jI);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function EI(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function _I(e){return e?new Date(e).toLocaleDateString():""}function Pp(e,n){return wS(e,n)}const Tr={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Qc={type:null,entry:null,entryFullPath:""},MI=200,AI=500,Tp=10;function PI({x:e,y:n,entry:s,onAction:a,onClose:r}){const o=i.useRef(null),[l,c]=i.useState({x:e,y:n});i.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,x=f?.offsetLeft??0,v=f?.offsetTop??0,b=8;let y=e-x,S=n-v;y+h.width>p-b&&(y=p-b-h.width),S+h.height>g-b&&(S=g-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+x,y:S+v})},[e,n]),i.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:ta,disabled:!1},{id:"move",label:"Move",icon:Ty,disabled:!1},{id:"rename",label:"Rename",icon:Ss,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:ao,disabled:!1}]:[{id:"download",label:"Download",icon:yv,disabled:!1}],{id:"divider",label:"",icon:ta,disabled:!0},{id:"delete",label:"Delete",icon:En,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:u.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:()=>a(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 TI({type:e,entry:n,entryFullPath:s,onConfirm:a,onCancel:r,loading:o,error:l}){const c=i.useRef(null),d=e==="rename"?n.name:"",[u,m]=i.useState(d);i.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),i.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"&&u.trim()&&a(u.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:()=>a(""),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:u,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:()=>a(u.trim()),disabled:o||!u.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function RI({entries:e,currentPath:n,onSelectFile:s,onNavigate:a,loading:r,error:o,onRetry:l,workspace:c,onRefresh:d,projectId:u}){const[m,h]=i.useState(Tr),[f,p]=i.useState(Qc),[g,x]=i.useState(!1),[v,b]=i.useState(null),[y,S]=i.useState(!1),[N,E]=i.useState(null),w=i.useRef(null),j=i.useRef(null),_=i.useRef(null),D=i.useRef(!1),C=i.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),j.current!==null&&(window.clearTimeout(j.current),j.current=null)},[]),P=i.useCallback(()=>{C(),_.current=null,S(!1),E(null)},[C]);i.useEffect(()=>()=>{C()},[C]);const I=i.useCallback((T,L,k,K)=>{h({visible:!0,x:T,y:L,entry:k,entryFullPath:K})},[]),H=i.useCallback((T,L,k)=>{if(T.touches.length!==1)return;const K=T.touches[0];K&&(P(),_.current={x:K.clientX,y:K.clientY},j.current=window.setTimeout(()=>{S(!0),E(k)},MI),w.current=window.setTimeout(()=>{const oe=_.current;oe&&(D.current=!0,S(!1),E(null),C(),I(oe.x,oe.y,L,k))},AI))},[P,C,I]),A=i.useCallback(T=>{const L=_.current,k=T.touches[0];!L||!k||(Math.abs(k.clientX-L.x)>Tp||Math.abs(k.clientY-L.y)>Tp)&&P()},[P]),$=i.useCallback(()=>{P()},[P]);i.useEffect(()=>{if(!m.visible)return;const T=document.querySelector(".file-browser-list"),L=()=>{D.current=!1,P(),h(Tr)};return T?.addEventListener("scroll",L),()=>T?.removeEventListener("scroll",L)},[P,m.visible]),i.useEffect(()=>{if(!m.visible)return;const T=L=>{L.key==="Escape"&&(D.current=!1,h(Tr))};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[m.visible]);const F=i.useCallback((T,L)=>{T.preventDefault(),T.stopPropagation(),P(),D.current=!1,I(T.clientX,T.clientY,L,Pp(n,L.name))},[P,n,I]),G=i.useCallback(T=>{if(!m.entry)return;D.current=!1;const L=m.entry,k=m.entryFullPath;if(h(Tr),T==="download"){if(!c)return;const K=Hf(c,k,u);window.open(_i(K),"_blank");return}if(T==="download-zip"){if(!c)return;const K=kj(c,k,u);window.open(_i(K),"_blank");return}p({type:T,entry:L,entryFullPath:k}),b(null)},[m,c,u]),ee=i.useCallback(async T=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await xj(c,f.entryFullPath,T,u);break;case"move":await vj(c,f.entryFullPath,T,u);break;case"rename":await wj(c,f.entryFullPath,T,u);break;case"delete":await yj(c,f.entryFullPath,u);break}p(Qc),d?.()}catch(L){b(Me(L)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),J=i.useCallback(()=>{p(Qc),b(null)},[]),M=i.useCallback((T,L)=>{if(D.current){D.current=!1;return}m.visible||(T.type==="directory"?a(L):s(L))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(xt,{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:()=>{a(kS(n))},children:[t.jsx(Un,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":hr(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(T=>{const L=Pp(n,T.name),k=y&&N===L;return t.jsxs("div",{className:`file-node file-node--${T.type} ${k?"file-node--long-pressing":""}`,onClick:()=>M(T,L),onContextMenu:K=>F(K,T),onTouchStart:K=>H(K,T,L),onTouchMove:A,onTouchEnd:$,onTouchCancel:$,children:[t.jsx("div",{className:"file-node-icon",children:T.type==="directory"?t.jsx(vs,{size:16}):t.jsx(Tf,{size:16})}),t.jsx("div",{className:"file-node-name",children:T.name}),T.type==="file"&&T.size!==void 0&&t.jsx("div",{className:"file-node-size",children:EI(T.size)}),T.mtime&&t.jsx("div",{className:"file-node-time",children:_I(T.mtime)})]},T.name)})}),m.visible&&m.entry&&t.jsx(PI,{x:m.x,y:m.y,entry:m.entry,onAction:G,onClose:()=>{D.current=!1,h(Tr)}}),f.type&&f.entry&&t.jsx(TI,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:ee,onCancel:J,loading:g,error:v})]})}function II(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function $I({content:e,onChange:n,readOnly:s,filePath:a,showLineNumbers:r=!1}){const[o,l]=i.useState(!1),[c,d]=i.useState(!0),u=i.useRef(null),m=II(a),h=m&&(s?!0:o),f=r&&!s&&!h,p=i.useMemo(()=>f?e.split(`
|
|
692
|
-
`).length:0,[e,f]),g=i.useCallback(()=>{l(!1)},[]),x=i.useCallback(()=>{l(!0)},[]),v=i.useCallback(()=>{d(y=>!y)},[]),b=i.useCallback(y=>{u.current&&(u.current.scrollTop=y.currentTarget.scrollTop)},[]);return t.jsxs("div",{className:"file-editor-container",children:[m?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 ${h?"":"btn-primary"}`,onClick:g,disabled:!h,"aria-label":"Edit mode",children:[t.jsx(Pf,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:x,disabled:h,"aria-label":"Preview mode",children:[t.jsx(ur,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:v,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(cl,{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 ${c?"btn-primary":""}`,onClick:v,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(cl,{size:14})})]}),h?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(Ai,{remarkPlugins:[Pi],children:e})}):t.jsxs("div",{className:`file-editor-textarea-shell ${f?"file-editor-textarea-shell--line-numbers":""}`,children:[f&&t.jsx("div",{className:"file-editor-line-numbers",ref:u,"aria-hidden":"true",children:Array.from({length:p},(y,S)=>t.jsx("div",{className:"file-editor-line-number",children:S+1},`line-${S+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${c?"file-editor-textarea--wrap":""}`,value:e,onChange:y=>n(y.target.value),onScroll:b,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function DI(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function LI({currentWorkspace:e,projectName:n,workspaces:s,onSelect:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>e==="project"?n||"Project Root":s.find(d=>d.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(Iu,{size:14}):t.jsx(pd,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(cn,{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:()=>{a("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Iu,{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:()=>{a(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(pd,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:DI(c.title)})]},c.id))]})]})]})}const OI=768,FI=280,Go=180,Jo=500,Rp="fusion:file-browser-sidebar-width",Ip="kb-files-line-numbers",Yb=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),zI=new Set([...Yb,".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 Xc(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return zI.has(n)}function UI(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Yb.has(n)}function BI({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=CI(a),l=i.useRef(null);Ti(l,!0,"fusion:files-modal-size");const c=Ui(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,x]=i.useState("list"),[v,b]=i.useState(FI),[y,S]=i.useState(!1),{entries:N,currentPath:E,setPath:w,loading:j,error:_,refresh:D}=wI(d,!0,a),{content:C,setContent:P,originalContent:I,loading:H,saving:A,error:$,save:F,hasChanges:G,mtime:ee}=kI(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const Q=()=>{p(window.innerWidth<=OI)};return Q(),window.addEventListener("resize",Q),()=>window.removeEventListener("resize",Q)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const Q=localStorage.getItem(Rp);if(!Q)return;const X=Number.parseInt(Q,10);if(!Number.isNaN(X)){const ie=Math.max(Go,Math.min(Jo,X));b(ie)}}catch{}},[]),i.useEffect(()=>{const Q=ss(Ip,a);S(Q==="true")},[a]),i.useEffect(()=>{const Q=X=>{X.key==="Escape"&&n(),(X.metaKey||X.ctrlKey)&&X.key==="s"&&(X.preventDefault(),G&&!A&&F())};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[n,G,A,F]);const J=i.useCallback(Q=>{h(Q),f&&x("editor")},[f]),M=i.useCallback(()=>{x("list")},[]),T=i.useCallback(()=>{P(I)},[I,P]),L=i.useCallback(Q=>{u(Q),h(null),x("list"),s?.(Q)},[s]),k=i.useCallback(Q=>{try{localStorage.setItem(Rp,String(Q))}catch{}},[]),K=i.useCallback(Q=>{if(f)return;Q.preventDefault(),Q.stopPropagation();const X=Q.currentTarget;typeof X.setPointerCapture=="function"&&X.setPointerCapture(Q.pointerId);const ie=Q.clientX,se=v;let B=se;document.body.style.userSelect="none";const O=ae=>{const te=ae.clientX-ie,Ie=Math.max(Go,Math.min(Jo,se+te));B=Ie,b(Ie)},ke=ae=>{typeof X.releasePointerCapture=="function"&&X.releasePointerCapture(ae.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",O),document.removeEventListener("pointerup",ke),k(B)};document.addEventListener("pointermove",O),document.addEventListener("pointerup",ke)},[f,k,v]),oe=i.useCallback(Q=>{if(f)return;const X=20;if(Q.key!=="ArrowLeft"&&Q.key!=="ArrowRight")return;Q.preventDefault();const ie=Q.key==="ArrowLeft"?-X:X,se=Math.max(Go,Math.min(Jo,v+ie));b(se),k(se)},[f,k,v]),le=i.useCallback(()=>{S(Q=>{const X=!Q;return xs(Ip,String(X),a),X})},[a]),ge=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(Q=>Q.id===d)?.id??d,[d,o])}`,Ue=i.useMemo(()=>!m||!UI(m)?null:Hf(d,m,a),[m,d,a]),Z=Q=>{const X=new Blob([Q]).size;return X<1024?`${X} B`:`${(X/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(vs,{size:18}),t.jsx("span",{children:ge}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsxs("button",{className:`btn btn-sm file-browser-line-numbers-toggle ${y?"btn-primary":""}`,onClick:le,"aria-label":"Toggle line numbers","aria-pressed":y,title:"Toggle line numbers",children:[t.jsx(py,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx(LI,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:L}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(nn,{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(RI,{entries:N,currentPath:E,onSelectFile:J,onNavigate:w,loading:j,error:_,onRetry:D,workspace:d,onRefresh:D,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Go,"aria-valuemax":Jo,"aria-valuenow":v,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:K,onKeyDown:oe}),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:M,"aria-label":"Back to file list",children:[t.jsx(ka,{size:16}),t.jsx("span",{children:"Back"})]}),m,Xc(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Ov,{size:12}),"Binary file — read only"]}),ee&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(ee).toLocaleString()]}),H&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!Ue&&G&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:T,disabled:A,children:[t.jsx(Ky,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void F(),disabled:A,children:[t.jsx(Lf,{size:14}),A?"Saving...":"Save"]})]})})]}),$&&!Ue&&t.jsx("div",{className:"file-browser-error-banner",children:$}),Ue?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:Ue,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx($I,{content:C,onChange:P,filePath:m,readOnly:Xc(m),showLineNumbers:y&&!Xc(m)})}),!Ue&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:Z(C)}),G&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(vs,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function HI(e){const{items:n,...s}=e;return s}function $p(e){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?`${e}-${crypto.randomUUID()}`:`${e}-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function qI(e={}){const{projectId:n,addToast:s}=e,[a,r]=i.useState([]),[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(null),[p,g]=i.useState([]),x=i.useRef(h);x.current=h,i.useEffect(()=>{let _=!1;async function D(){d(!0),m(null);try{const C=await w1(n);if(_)return;g(C),r(C.map(HI));const P=x.current&&C.some(I=>I.id===x.current)?x.current:C[0]?.id??null;f(P),l(P?C.find(I=>I.id===P)?.items??[]:[])}catch(C){if(_)return;g([]),r([]),l([]),f(null),m(C instanceof Error?C.message:"Failed to load todo lists")}finally{_||d(!1)}}return D(),()=>{_=!0}},[n]),i.useEffect(()=>{if(!h){l([]);return}const _=p.find(D=>D.id===h);l(_?.items??[])},[p,h]);const v=i.useCallback(async _=>{const D=a,C=p,P=new Date().toISOString(),I={id:$p("temp-list"),projectId:n??"",title:_,createdAt:P,updatedAt:P};m(null),r(H=>[...H,I]),g(H=>[...H,{...I,items:[]}]);try{const H=await k1(_,n);r(A=>A.map($=>$.id===I.id?H:$)),g(A=>A.map($=>$.id===I.id?{...H,items:[]}:$)),x.current||f(H.id)}catch(H){r(D),g(C),m(H instanceof Error?H.message:"Failed to create list"),s?.("Failed to create todo list","error")}},[s,p,a,n]),b=i.useCallback(async(_,D)=>{const C=a,P=p;m(null),r(I=>I.map(H=>H.id===_?{...H,title:D}:H)),g(I=>I.map(H=>H.id===_?{...H,title:D}:H));try{const I=await j1(_,D,n);r(H=>H.map(A=>A.id===_?I:A)),g(H=>H.map(A=>A.id===_?{...I,items:A.items}:A))}catch(I){r(C),g(P),m(I instanceof Error?I.message:"Failed to rename list"),s?.("Failed to rename todo list","error")}},[s,p,a,n]),y=i.useCallback(async _=>{const D=a,C=p,P=x.current,I=P===_?a.find(H=>H.id!==_)?.id??null:P;m(null),r(H=>H.filter(A=>A.id!==_)),g(H=>H.filter(A=>A.id!==_)),P===_&&f(I);try{await N1(_,n)}catch(H){r(D),g(C),f(P),m(H instanceof Error?H.message:"Failed to delete list"),s?.("Failed to delete todo list","error")}},[s,p,a,n]),S=i.useCallback(async _=>{const D=x.current;if(!D)return;const C=o,P=p,I=new Date().toISOString(),H=o.reduce(($,F)=>Math.max($,F.sortOrder),-1),A={id:$p("temp-item"),listId:D,text:_,completed:!1,completedAt:null,createdAt:I,updatedAt:I,sortOrder:H+1};m(null),l($=>[...$,A]),g($=>$.map(F=>F.id===D?{...F,items:[...F.items,A]}:F));try{const $=await S1(D,_,n);l(F=>F.map(G=>G.id===A.id?$:G)),g(F=>F.map(G=>G.id===D?{...G,items:G.items.map(ee=>ee.id===A.id?$:ee)}:G))}catch($){l(C),g(P),m($ instanceof Error?$.message:"Failed to create item"),s?.("Failed to create todo item","error")}},[s,o,p,n]),N=i.useCallback(async(_,D)=>{const C=o.find($=>$.id===_);if(!C)return;const P=o,I=p,H=D.completed??C.completed,A={...C,...D,completed:H,completedAt:H?C.completedAt??new Date().toISOString():null,updatedAt:new Date().toISOString()};m(null),l($=>$.map(F=>F.id===_?A:F)),g($=>$.map(F=>F.id===A.listId?{...F,items:F.items.map(G=>G.id===_?A:G)}:F));try{const $=await C1(_,D,n);l(F=>F.map(G=>G.id===_?$:G)),g(F=>F.map(G=>G.id===$.listId?{...G,items:G.items.map(ee=>ee.id===_?$:ee)}:G))}catch($){l(P),g(I),m($ instanceof Error?$.message:"Failed to update item"),s?.("Failed to update todo item","error")}},[s,o,p,n]),E=i.useCallback(async _=>{const D=o.find(C=>C.id===_);D&&await N(_,{completed:!D.completed})},[o,N]),w=i.useCallback(async _=>{const D=o,C=p;m(null),l(P=>P.filter(I=>I.id!==_)),g(P=>P.map(I=>({...I,items:I.items.filter(H=>H.id!==_)})));try{await E1(_,n)}catch(P){l(D),g(C),m(P instanceof Error?P.message:"Failed to delete item"),s?.("Failed to delete todo item","error")}},[s,o,p,n]),j=i.useCallback(async _=>{const D=x.current;if(!D)return;const C=o,P=p,I=new Map(o.map(A=>[A.id,A])),H=_.map((A,$)=>{const F=I.get(A);return F?{...F,sortOrder:$}:null}).filter(A=>A!==null);m(null),l(H),g(A=>A.map($=>$.id===D?{...$,items:H}:$));try{await _1(D,_,n)}catch(A){l(C),g(P),m(A instanceof Error?A.message:"Failed to reorder items"),s?.("Failed to reorder todo items","error")}},[s,o,p,n]);return{lists:a,items:o,loading:c,error:u,selectedListId:h,setSelectedListId:f,createList:v,renameList:b,deleteList:y,createItem:S,updateItem:N,toggleItem:E,deleteItem:w,reorderItems:j}}function VI(e){return[...e].sort((n,s)=>n.sortOrder-s.sortOrder)}function Qb({projectId:e,addToast:n,onPlanningMode:s,onTaskCreated:a}){const{lists:r,items:o,loading:l,error:c,selectedListId:d,setSelectedListId:u,createList:m,renameList:h,deleteList:f,createItem:p,updateItem:g,toggleItem:x,deleteItem:v,reorderItems:b}=qI({projectId:e,addToast:(ue,ce)=>{if(ce==="success"||ce==="error"||ce==="info"||ce===void 0){n(ue,ce);return}n(ue,"info")}}),[y,S]=i.useState(null),[N,E]=i.useState(""),[w,j]=i.useState(null),[_,D]=i.useState(""),[C,P]=i.useState(""),[I,H]=i.useState(!1),[A,$]=i.useState(""),[F,G]=i.useState([]),[ee,J]=i.useState(!1),[M,T]=i.useState(!1),[L,k]=i.useState(null),K=i.useRef(null),{confirm:oe}=Ys(),le=i.useMemo(()=>r.find(ue=>ue.id===d)??null,[r,d]),we=i.useMemo(()=>VI(o.filter(ue=>ue.listId===d)),[o,d]);function ge(){S(null),E(""),P(""),H(!1)}function Ue(){j(null),D(""),$("")}function Z(ue){ge(),Ue(),u(ue)}const Q=i.useCallback(async()=>{J(!0);try{const ue=await Na(void 0,e);G(ue),T(!0)}catch(ue){n(`Failed to load agents: ${Me(ue)}`,"error"),T(!1),k(null)}finally{J(!1)}},[e,n]);i.useEffect(()=>{S(null),E(""),P(""),H(!1),j(null),D(""),$(""),T(!1),k(null)},[d]),i.useEffect(()=>{if(!M)return;const ue=ce=>{K.current&&!K.current.contains(ce.target)&&(T(!1),k(null))};return document.addEventListener("mousedown",ue),()=>{document.removeEventListener("mousedown",ue)}},[M]);function X(ue){Ue(),S(ue.id),E(ue.title),H(!1)}async function ie(){if(!y)return;const ue=N.trim();if(!ue){S(null),E("");return}await h(y,ue),S(null),E("")}function se(){S(null),E("")}function B(ue){ge(),j(ue.id),D(ue.text)}async function O(){if(!w)return;const ue=_.trim();if(!ue){j(null),D("");return}await g(w,{text:ue}),j(null),D("")}function ke(){j(null),D("")}async function ae(){const ue=C.trim();ue&&(await m(ue),P(""),H(!1))}async function te(){if(!d)return;const ue=A.trim();ue&&(await p(ue),$(""))}async function Ie(ue){await oe({title:"Delete List",message:"Delete this list and all its items?",danger:!0})&&await f(ue)}async function Oe(ue){await v(ue)}async function He(ue,ce){const Ae=we.map(Ce=>Ce.id),Ne=Ae.findIndex(Ce=>Ce===ue);if(Ne<0)return;const ye=ce==="up"?Ne-1:Ne+1;ye<0||ye>=Ae.length||([Ae[Ne],Ae[ye]]=[Ae[ye],Ae[Ne]],await b(Ae))}const $e=i.useCallback(async ue=>{try{const ce={description:ue.text,column:"triage",source:{sourceType:"dashboard_ui"}},Ae=await ml(ce,e);a?.(Ae),n(`Created ${Ae.id} from todo`,"success")}catch(ce){n(`Failed to create task: ${Me(ce)}`,"error")}},[e,n,a]),Te=i.useCallback(async(ue,ce)=>{try{const Ae={description:ue.text,column:"triage",assignedAgentId:ce,source:{sourceType:"dashboard_ui"}},Ne=await ml(Ae,e);a?.(Ne);const Ce=F.find(fe=>fe.id===ce)?.name??ce;n(`Created ${Ne.id} and assigned to ${Ce}`,"success"),T(!1),k(null)}catch(Ae){n(`Failed to create and assign task: ${Me(Ae)}`,"error")}},[e,n,F,a]);return l?t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-loading",children:[t.jsx(xt,{className:"todo-loading-icon","aria-hidden":"true"}),t.jsx("p",{children:"Loading todos..."})]})}):t.jsx("div",{className:"todo-view",children:t.jsxs("div",{className:"todo-view-layout",children:[t.jsxs("aside",{className:"todo-view-sidebar","aria-label":"Todo lists sidebar",children:[t.jsxs("div",{className:"todo-sidebar-header",children:[t.jsx("h3",{className:"todo-sidebar-title",children:"Lists"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-add-list-btn",onClick:()=>{Ue(),H(!0),S(null)},"aria-label":"Add list","data-testid":"add-list-button",children:t.jsx(_n,{})})]}),I&&t.jsxs("div",{className:"todo-list-item",children:[t.jsx("input",{className:"input todo-inline-edit-input",placeholder:"New list title",value:C,onChange:ue=>P(ue.target.value),onKeyDown:ue=>{ue.key==="Enter"&&ae(),ue.key==="Escape"&&(P(""),H(!1))},autoFocus:!0,"data-testid":"new-list-input"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ae()},"aria-label":"Save list",children:t.jsx(os,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{P(""),H(!1)},"aria-label":"Cancel list",children:t.jsx(nn,{})})]}),r.length===0&&!I?t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(fd,{"aria-hidden":"true"}),t.jsx("p",{children:"No todo lists yet. Create one to get started."}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{Ue(),H(!0)},children:"Create List"})]}):t.jsx("div",{className:"todo-list-items",role:"list","aria-label":"Todo lists",children:r.map(ue=>{const ce=ue.id===d,Ae=ue.id===y;return t.jsx("div",{className:`todo-list-item${ce?" todo-list-item--active":""}`,role:"listitem",children:Ae?t.jsxs(t.Fragment,{children:[t.jsx("input",{className:"input todo-inline-edit-input",value:N,onChange:Ne=>E(Ne.target.value),onKeyDown:Ne=>{Ne.key==="Enter"&&ie(),Ne.key==="Escape"&&se()},autoFocus:!0,"data-testid":`rename-list-input-${ue.id}`}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{ie()},"aria-label":"Save list rename",children:t.jsx(os,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:se,"aria-label":"Cancel list rename",children:t.jsx(nn,{})})]}):t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"todo-list-select-btn",onClick:()=>Z(ue.id),"aria-label":`Select list ${ue.title}`,"aria-current":ce?"true":void 0,"data-testid":`todo-list-${ue.id}`,children:t.jsx("span",{className:"todo-list-item-name",children:ue.title})}),t.jsxs("div",{className:"todo-list-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{X(ue)},"aria-label":`Rename ${ue.title}`,"data-testid":`rename-list-button-${ue.id}`,children:t.jsx(Ss,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{Ie(ue.id)},"aria-label":`Delete ${ue.title}`,"data-testid":`delete-list-button-${ue.id}`,children:t.jsx(En,{})})]})]})},ue.id)})})]}),t.jsxs("section",{className:"todo-view-main","aria-label":"Todo items",children:[c&&t.jsxs("div",{className:"todo-error-banner",role:"alert",children:[t.jsx("span",{className:"todo-error-message",children:c}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>window.location.reload(),children:"Retry"})]}),le?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"todo-items-header",children:t.jsx("h3",{children:le.title})}),t.jsxs("div",{className:"todo-add-item-row",children:[t.jsx("input",{className:"input",placeholder:"Add a todo item",value:A,onChange:ue=>$(ue.target.value),onKeyDown:ue=>{ue.key==="Enter"&&te(),ue.key==="Escape"&&$("")},"data-testid":"new-item-input"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>{te()},children:"Add"})]}),we.length===0?t.jsx("div",{className:"todo-empty-state",children:t.jsx("p",{children:"No items in this list. Add one above."})}):t.jsx("div",{className:"todo-items-list",children:we.map((ue,ce)=>{const Ae=ue.id===w;return t.jsxs("div",{className:"todo-item","data-testid":`todo-item-${ue.id}`,children:[t.jsxs("div",{className:"todo-item-main-row",children:[t.jsx("input",{type:"checkbox",checked:ue.completed,onChange:()=>{x(ue.id)},className:"todo-item-checkbox","aria-label":`Toggle ${ue.text}`,"data-testid":`toggle-item-${ue.id}`}),Ae?t.jsx("input",{className:"input todo-inline-edit-input",value:_,onChange:Ne=>D(Ne.target.value),onKeyDown:Ne=>{Ne.key==="Enter"&&O(),Ne.key==="Escape"&&ke()},autoFocus:!0,"data-testid":`edit-item-input-${ue.id}`}):t.jsx("button",{type:"button",className:`todo-item-text${ue.completed?" todo-item-text--completed":""}`,onClick:()=>B(ue),children:ue.text})]}),t.jsx("div",{className:"todo-item-actions","data-testid":`todo-item-actions-${ue.id}`,children:Ae?t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{O()},"aria-label":"Save item edit",children:t.jsx(os,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:ke,"aria-label":"Cancel item edit",children:t.jsx(nn,{})})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"todo-item-reorder-btns",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{He(ue.id,"up")},disabled:ce===0,"aria-label":`Move ${ue.text} up`,"data-testid":`move-up-${ue.id}`,children:t.jsx(mi,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-item-reorder-btn",onClick:()=>{He(ue.id,"down")},disabled:ce===we.length-1,"aria-label":`Move ${ue.text} down`,"data-testid":`move-down-${ue.id}`,children:t.jsx(cn,{})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{s?.(ue.text)},"aria-label":`Start planning from ${ue.text}`,"data-testid":`planning-from-${ue.id}`,children:t.jsx(hi,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{$e(ue)},"aria-label":`Create task from ${ue.text}`,"data-testid":`create-task-from-${ue.id}`,children:t.jsx(ov,{})}),t.jsxs("div",{className:"todo-agent-picker-trigger",ref:L===ue.id?K:void 0,children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>{k(ue.id),Q()},"aria-label":`Assign ${ue.text} to agent`,"data-testid":`assign-agent-for-${ue.id}`,children:t.jsx(zn,{})}),M&&L===ue.id&&t.jsx("div",{className:"todo-agent-picker-dropdown",onMouseDown:Ne=>{Ne.preventDefault()},children:ee?t.jsx("div",{className:"todo-agent-picker-loading",children:"Loading agents..."}):F.length>0?F.map(Ne=>t.jsxs("button",{type:"button",className:"todo-agent-picker-item",onClick:()=>{Te(ue,Ne.id)},children:[t.jsx(zn,{}),t.jsx("span",{children:Ne.name}),t.jsx("span",{className:"todo-agent-picker-role",children:Ne.role})]},Ne.id)):t.jsx("div",{className:"todo-agent-picker-empty",children:"No agents available"})})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon todo-icon-btn",onClick:()=>B(ue),"aria-label":`Edit ${ue.text}`,"data-testid":`edit-item-${ue.id}`,children:t.jsx(Ss,{})}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon btn-danger todo-icon-btn",onClick:()=>{Oe(ue.id)},"aria-label":`Delete ${ue.text}`,"data-testid":`delete-item-${ue.id}`,children:t.jsx(En,{})})]})})]},ue.id)})})]}):t.jsxs("div",{className:"todo-empty-state",children:[t.jsx(fd,{"aria-hidden":"true"}),t.jsx("p",{children:"Select a list from the sidebar"})]})]})]})})}const Xb=Object.freeze(Object.defineProperty({__proto__:null,TodoView:Qb},Symbol.toStringTag,{value:"Module"}));function WI({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Ui(e),l=Js()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=ra({enabled:l});pi(l);const h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{};return i.useEffect(()=>{const f=p=>{p.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:h,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(fd,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:"Todos"}),t.jsx("p",{children:"Manage reusable todo lists for your project."})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(nn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(Qb,{projectId:n,addToast:s,onPlanningMode:a,onClose:e})})]})})}function KI(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[a,r]=i.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await vk();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:Me(m)||"Failed to fetch usage data"}))}},[]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),i.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const d=i.useCallback(()=>c(!0),[c]);return{providers:a.providers,loading:a.loading,error:a.error,lastUpdated:a.lastUpdated,refresh:d}}function GI(e){const n=new Date(e),s=new Date,a=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return a;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"})} ${a}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${a}`}function JI(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Zb="kb-usage-hidden-windows",ex="kb-usage-modal-size",tx="kb-usage-provider-order";function Dp(e){const n=ss(ex,e);if(!n)return null;try{const s=JSON.parse(n);if(s&&typeof s.width=="number"&&typeof s.height=="number"&&s.width>0&&s.height>0)return{width:s.width,height:s.height}}catch{}return null}function Lp(e){const n=ss(Zb,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((a,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(a[r]=l)}return a},{})}catch{return{}}}function YI(e,n){xs(Zb,JSON.stringify(e),n)}function Op(e){const n=ss(tx,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function Fp(e,n){xs(tx,JSON.stringify(e),n)}function nx(e,n,s){return s[e]?.includes(n)??!1}function QI({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=JI(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`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?u=`resets in ${y}d ${S}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`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",x=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(ur,{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:d}),t.jsxs("span",{className:"usage-window-reset-group",children:[u&&t.jsx("span",{className:"usage-window-reset",children:u}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:GI(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Ll,{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(fw,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function XI(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 ZI({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:x,onMoveUp:v,onMoveDown:b}){const y=s[e.name]?.length??0,S=()=>{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${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(Jn,{provider:XI(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),y>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 (",y,")"]})]}),t.jsxs("div",{className:"usage-provider-actions",children:[p&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":`Reorder ${e.name}`,children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:v,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(mi,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!x,"aria-label":`Move ${e.name} down`,children:t.jsx(cn,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(Rl,{size:16})})]})]}),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((N,E)=>{const w=nx(e.name,N.label,s);return t.jsx(QI,{window:N,viewMode:n,isHidden:w,onToggleHidden:()=>a(e.name,N.label)},`${e.name}-${N.label}-${E}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function e4(){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 t4({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=KI({autoRefresh:e}),[u,m]=i.useState(!1),[h,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[x,v]=i.useState("used"),[b,y]=i.useState(()=>Lp(s)),[S,N]=i.useState(()=>Op(s)),[E,w]=i.useState(null),[j,_]=i.useState(null),[D,C]=i.useState(null),P=i.useRef(null),I=i.useRef(null),H=i.useRef(e),A=i.useRef(!1),[$,F]=i.useState(()=>Dp(s));i.useEffect(()=>{F(Dp(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const ae=I.current;if(!ae||typeof ResizeObserver>"u")return;let te=null;const Ie=new ResizeObserver(Oe=>{const He=Oe[0];if(!He)return;const{width:$e,height:Te}=He.contentRect;$e<=0||Te<=0||(te&&clearTimeout(te),te=setTimeout(()=>{xs(ex,JSON.stringify({width:Math.round($e),height:Math.round(Te)}),s)},250))});return Ie.observe(ae),()=>{te&&clearTimeout(te),Ie.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(A.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(A.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const ae=window.matchMedia?.("(pointer: coarse)"),te=()=>{f(window.innerWidth>=769),g(ae?.matches??!1)};return te(),window.addEventListener("resize",te),ae?.addEventListener?.("change",te),()=>{window.removeEventListener("resize",te),ae?.removeEventListener?.("change",te)}},[]),i.useEffect(()=>{!H.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),H.current=e},[e,c,d]),i.useEffect(()=>{const ae=ss("kb-usage-view-mode",s);if(ae==="used"||ae==="remaining"){v(ae);return}v("used")},[s]);const G=i.useCallback(ae=>{v(ae),xs("kb-usage-view-mode",ae,s)},[s]);i.useEffect(()=>{y(Lp(s)),N(Op(s))},[s]),i.useEffect(()=>{YI(b,s)},[b,s]);const ee=i.useCallback((ae,te)=>{y(Ie=>{if(nx(ae,te,Ie)){const Oe=(Ie[ae]??[]).filter(He=>He!==te);if(Oe.length===0){const{[ae]:He,...$e}=Ie;return $e}return{...Ie,[ae]:Oe}}return{...Ie,[ae]:[...Ie[ae]??[],te]}})},[]),J=i.useCallback(ae=>{y(te=>{if(!te[ae])return te;const{[ae]:Ie,...Oe}=te;return Oe})},[]),M=i.useCallback(ae=>{if(S.length===0)return ae;const te=new Map(ae.map(Oe=>[Oe.name,Oe])),Ie=[];for(const Oe of S){const He=te.get(Oe);He&&(Ie.push(He),te.delete(Oe))}return[...Ie,...te.values()]},[S]),T=i.useCallback((ae,te)=>{ae.dataTransfer.effectAllowed="move",ae.dataTransfer.setData("text/plain",te),w(te)},[]),L=i.useCallback((ae,te)=>{if(!E||E===te)return;ae.preventDefault(),ae.dataTransfer.dropEffect="move";const{top:Ie,height:Oe}=ae.currentTarget.getBoundingClientRect(),He=Ie+Oe/2,$e=ae.clientY<He?"before":"after";_(te),C($e)},[E]),k=i.useCallback((ae,te)=>{ae.preventDefault();const Ie=E??ae.dataTransfer.getData("text/plain");if(!Ie||Ie===te){_(null),C(null);return}const He=M(r).map(ue=>ue.name).filter(ue=>ue!==Ie),$e=He.indexOf(te);if($e<0){_(null),C(null);return}const Te=D==="after"?$e+1:$e;He.splice(Te,0,Ie),Fp(He,s),N(He),_(null),C(null)},[E,D,s,r,M]),K=i.useCallback(()=>{w(null),_(null),C(null)},[]),oe=i.useCallback((ae,te)=>{const Ie=M(r).map(ue=>ue.name),Oe=Ie.indexOf(ae),He=Oe+te;if(Oe<0||He<0||He>=Ie.length)return;const $e=[...Ie],[Te]=$e.splice(Oe,1);$e.splice(He,0,Te),Fp($e,s),N($e)},[s,r,M]),le=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const ae=te=>{te.key==="Escape"&&n()};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[e,n]);const we=i.useCallback(ae=>{ae.target===ae.currentTarget&&n()},[n]);if(!e)return null;const ge=!!(a&&h),Ue=8,Z=12,X=$?.width??420,ie=ge?Math.min((a?.bottom??0)+Ue,window.innerHeight-Z):void 0,se=ge?Math.max(8,(a?.right??0)-X):void 0,B=h&&$?{width:$.width,height:$.height}:{},O=M(r),ke=t.jsxs("div",{ref:I,className:`usage-modal${ge?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:ge?{position:"fixed",top:ie,left:se,...B}:B,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ws,{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 ${x==="used"?"active":""}`,onClick:()=>G("used"),"aria-pressed":x==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${x==="remaining"?"active":""}`,onClick:()=>G("remaining"),"aria-pressed":x==="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(nn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:P,children:(o||!A.current&&!l)&&r.length===0?t.jsx(e4,{}):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:le,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:O.map((ae,te)=>t.jsx(ZI,{provider:ae,viewMode:x,hiddenWindows:b,onToggleWindow:ee,onShowAllHidden:J,isDragging:E===ae.name,isDragOver:j===ae.name,dragOverPosition:j===ae.name?D:null,onDragStart:Ie=>T(Ie,ae.name),onDragOver:Ie=>L(Ie,ae.name),onDragLeave:()=>{j===ae.name&&(_(null),C(null))},onDrop:Ie=>k(Ie,ae.name),onDragEnd:K,isTouchReorderMode:p,canMoveUp:te>0,canMoveDown:te<O.length-1,onMoveUp:()=>oe(ae.name,-1),onMoveDown:()=>oe(ae.name,1)},ae.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:le,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(hs,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return ge?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),ke]}):t.jsx("div",{className:"modal-overlay open",onClick:we,"data-testid":"usage-modal-overlay",children:ke})}function sx(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),a=n%60;if(s<60)return a>0?`${s}m ${a}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function Sl(e){const n=Date.now(),s=new Date(e).getTime(),a=n-s;if(a<0){const r=Math.abs(a);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 a<6e4?"just now":a<36e5?`${Math.floor(a/6e4)}m ago`:a<864e5?`${Math.floor(a/36e5)}h ago`:`${Math.floor(a/864e5)}d ago`}const n4={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},ix={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},s4={cron:Ef,webhook:Of,api:_f,manual:us},i4={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},a4={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function r4({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(Gn,{size:12}):t.jsx(lo,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:sx(n)})]})}function o4({result:e,index:n}){const[s,a]=i.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:()=>a(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${Sl(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Gn,{size:12}):t.jsx(lo,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Sl(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:ix[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:sx(r)}),s?t.jsx(mi,{size:12}):t.jsx(cn,{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 l4({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=Ys(),m=i.useCallback(async()=>{await u({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,u]),h=n4[e.trigger.type],f=s4[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}),ix[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(Pl,{size:10}):t.jsx(vs,{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:()=>a(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(xt,{className:"spinner"}):t.jsx(ls,{})}),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(di,{}):t.jsx(ls,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Ss,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(En,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ga,{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(zi,{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:i4[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:a4[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:Sl(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:Sl(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(r4,{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:()=>d(g=>!g),"aria-expanded":c,children:[c?t.jsx(mi,{size:12}):t.jsx(cn,{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,x)=>t.jsx(o4,{result:g,index:x},`${g.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function c4({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Fi,{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(gy,{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(bs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Zc(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function d4(e){return e==="command"?{id:Zc(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Zc(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Zc(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function u4({step:e,onSave:n,onCancel:s}){const[a,r]=i.useState(e.name),[o,l]=i.useState(e.type),[c,d]=i.useState(e.command??""),[u,m]=i.useState(e.prompt??""),[h,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[x,v]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[S,N]=i.useState(e.taskColumn??"triage"),[E,w]=i.useState(e.timeoutMs),[j,_]=i.useState(e.continueOnFailure??!1),[D,C]=i.useState({}),[P,I]=i.useState([]),[H,A]=i.useState(!1),[$,F]=i.useState(null);i.useEffect(()=>{let T=!1;return A(!0),F(null),$s().then(L=>{T||I(L.models)}).catch(L=>{T||F(L instanceof Error?L.message:"Failed to load models")}).finally(()=>{T||A(!1)}),()=>{T=!0}},[]);const G=i.useCallback(()=>{const T={};return a.trim()||(T.name="Step name is required"),o==="command"&&!c.trim()&&(T.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(T.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(T.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(T.modelProvider="Both model provider and model ID must be set together"),E!==void 0&&E<1e3&&(T.timeoutMs="Timeout must be at least 1 second (1000ms)"),C(T),Object.keys(T).length===0},[a,o,c,u,b,h,p,E]),ee=h&&p?`${h}/${p}`:"",J=i.useCallback(T=>{if(!T)f(""),g("");else{const L=T.indexOf("/");L!==-1&&(f(T.slice(0,L)),g(T.slice(L+1)))}},[]),M=i.useCallback(()=>{if(!G())return;const T={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:E||void 0,continueOnFailure:j};o!=="ai-prompt"&&delete T.prompt,o!=="create-task"&&(delete T.taskTitle,delete T.taskDescription,delete T.taskColumn),n(T)},[G,n,e,a,o,c,u,x,b,S,h,p,E,j]);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:a,onChange:T=>r(T.target.value),"aria-invalid":!!D.name}),D.name&&t.jsx("small",{className:"field-error",children:D.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:T=>l(T.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:T=>d(T.target.value),rows:2,"aria-invalid":!!D.command}),D.command&&t.jsx("small",{className:"field-error",children:D.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:T=>m(T.target.value),rows:3,"aria-invalid":!!D.prompt}),D.prompt&&t.jsx("small",{className:"field-error",children:D.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(ks,{id:`step-model-${e.id}`,label:"Model",models:P,value:ee,onChange:J,placeholder:"Use default",disabled:H}),$&&t.jsx("small",{className:"field-error",children:$}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange:T=>v(T.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:T=>y(T.target.value),rows:4,"aria-invalid":!!D.taskDescription}),D.taskDescription&&t.jsx("small",{className:"field-error",children:D.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:T=>N(T.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(ks,{id:`step-task-model-${e.id}`,label:"Model",models:P,value:ee,onChange:J,placeholder:"Use default",disabled:H}),$&&t.jsx("small",{className:"field-error",children:$}),D.modelProvider&&t.jsx("small",{className:"field-error",children:D.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:E??"",onChange:T=>w(T.target.value?Number(T.target.value):void 0),"aria-invalid":!!D.timeoutMs}),D.timeoutMs&&t.jsx("small",{className:"field-error",children:D.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:j,onChange:T=>_(T.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:M,children:"Save Step"})]})]})}function m4({steps:e,onChange:n,onEditingChange:s}){const[a,r]=i.useState(null);i.useEffect(()=>{s?.(a!==null)},[a,s]);const o=i.useCallback(u=>{const m=d4(u);n([...e,m]),r(m.id)},[e,n]),l=i.useCallback(u=>{n(e.filter(m=>m.id!==u)),a===u&&r(null)},[e,n,a]),c=i.useCallback((u,m)=>{const h=e.findIndex(g=>g.id===u);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]),d=i.useCallback(u=>{n(e.map(m=>m.id===u.id?u: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((u,m)=>t.jsx("div",{className:"step-card",children:a===u.id?t.jsx(u4,{step:u,onSave:d,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(Rl,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(c4,{type:u.type}),t.jsx("span",{className:"step-card-name",children:u.name}),u.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(u.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(mi,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(cn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Ss,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(En,{})})]})]})},u.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(_n,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(_n,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(_n,{size:14}),"Add Create Task Step"]})]})]})}const ax={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},h4={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function p4(e){const n=e.trim();for(const[s,a]of Object.entries(ax))if(a===n)return s;return"custom"}function f4(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function g4(e,n,s,a,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:a||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function b4(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 x4=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],v4=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function zp(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Up({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?b4(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,x]=i.useState(c.cronExpression),[v,b]=i.useState(()=>c.triggerType!=="cron"?"custom":p4(c.cronExpression)),[y,S]=i.useState(c.webhookPath),[N,E]=i.useState(c.webhookSecret),[w,j]=i.useState(c.endpoint),[_,D]=i.useState(e?.executionPolicy??"queue"),[C,P]=i.useState(e?.catchUpPolicy??"run_one"),[I,H]=i.useState(e?.enabled??!0),A=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,$=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[F,G]=i.useState(e?.steps&&e.steps.length>0&&!A&&!$?"advanced":"simple"),[ee,J]=i.useState(()=>A?"ai-prompt":$?"create-task":"command"),[M,T]=i.useState(e?.command??""),[L,k]=i.useState(e?.steps??[]),[K,oe]=i.useState(!1),[le,we]=i.useState(e?.timeoutMs??3e5),[ge,Ue]=i.useState(A?e.steps?.[0]?.prompt??"":""),[Z,Q]=i.useState($?e.steps?.[0]?.taskTitle??"":""),[X,ie]=i.useState($?e.steps?.[0]?.taskDescription??"":""),[se,B]=i.useState($?e.steps?.[0]?.taskColumn??"triage":"triage"),[O,ke]=i.useState(A||$?e.steps?.[0]?.modelProvider??"":""),[ae,te]=i.useState(A||$?e.steps?.[0]?.modelId??"":""),[Ie,Oe]=i.useState([]),[He,$e]=i.useState(!1),[Te,ue]=i.useState(null),[ce,Ae]=i.useState(a??"global"),[Ne,ye]=i.useState({}),[Ce,fe]=i.useState(!1),Pe=i.useRef(!0);i.useEffect(()=>()=>{Pe.current=!1},[]),i.useEffect(()=>{a&&Ae(a)},[a]),i.useEffect(()=>{let pe=!1;return $e(!0),ue(null),$s().then(Xe=>{pe||Oe(Xe.models)}).catch(Xe=>{pe||ue(Xe instanceof Error?Xe.message:"Failed to load models")}).finally(()=>{pe||$e(!1)}),()=>{pe=!0}},[]);const De=O&&ae?`${O}/${ae}`:"",dt=i.useCallback(pe=>{if(!pe){ke(""),te("");return}const Xe=pe.indexOf("/");Xe!==-1&&(ke(pe.slice(0,Xe)),te(pe.slice(Xe+1)))},[]),pt=i.useCallback(()=>{const pe={};if(d.trim()||(pe.name="Name is required"),ce==="project"&&!r&&(pe.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?f4(g)||(pe.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):pe.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(pe.webhookPath="Webhook path is required"),f==="api"&&!w.trim()&&(pe.endpoint="API endpoint is required"),F==="simple")ee==="command"&&!M.trim()&&(pe.command="Command is required"),ee==="ai-prompt"&&!ge.trim()&&(pe.prompt="Prompt is required"),ee==="create-task"&&!X.trim()&&(pe.taskDescription="Task description is required"),(O.trim()&&!ae.trim()||!O.trim()&&ae.trim())&&(pe.model="Both model provider and model ID must be set, or both must be empty");else{L.length===0&&(pe.steps="At least one step is required"),K&&(pe.stepsEditing="Please save or cancel all step edits before saving the routine");const Xe=[];L.forEach((wt,gt)=>{wt.name?.trim()||Xe.push(`Step ${gt+1}: Name is required`),wt.type==="command"&&!wt.command?.trim()&&Xe.push(`Step ${gt+1}: Command is required`),wt.type==="ai-prompt"&&!wt.prompt?.trim()&&Xe.push(`Step ${gt+1}: Prompt is required`),wt.type==="create-task"&&!wt.taskDescription?.trim()&&Xe.push(`Step ${gt+1}: Task description is required`)}),Xe.length>0&&(pe.steps=Xe.join("; "))}return le<1e3&&(pe.timeoutMs="Timeout must be at least 1 second (1000ms)"),ye(pe),Object.keys(pe).length===0},[d,f,g,v,y,w,ce,r,F,ee,M,ge,X,O,ae,L,K,le]),lt=i.useCallback(async pe=>{if(pe.preventDefault(),!!pt()){fe(!0);try{let Xe=e?.scope??ce??(r?"project":"global");Xe==="project"&&!r&&(Xe="global");const wt=g4(f,g,y,N,w);let gt,Tt;F==="simple"?ee==="command"?gt=M.trim()||void 0:ee==="ai-prompt"?Tt=[{id:zp(),type:"ai-prompt",name:d.trim(),prompt:ge.trim(),modelProvider:O.trim()||void 0,modelId:ae.trim()||void 0}]:Tt=[{id:zp(),type:"create-task",name:d.trim(),taskTitle:Z.trim()||void 0,taskDescription:X.trim(),taskColumn:se,modelProvider:O.trim()||void 0,modelId:ae.trim()||void 0}]:Tt=L;const Zt={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:wt,command:gt,steps:Tt,timeoutMs:le,executionPolicy:_,catchUpPolicy:C,enabled:I,scope:Xe};await n(Zt)}finally{Pe.current&&fe(!1)}}},[pt,n,d,m,f,g,y,N,w,F,ee,M,ge,O,ae,Z,X,se,L,le,_,C,I,ce,r,e?.scope,e?.agentId]),vt="routine-name-error",_e="routine-cron-error",Fe="routine-webhook-error",bt="routine-endpoint-error",ht="routine-command-error",Ee="routine-prompt-error",me="routine-task-description-error",Re="routine-model-error",be="routine-timeout-error",Ke=i.useCallback(pe=>{b(pe),pe!=="custom"&&x(ax[pe])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:lt,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:d,onChange:pe=>u(pe.target.value),"aria-invalid":!!Ne.name,"aria-describedby":Ne.name?vt:void 0}),Ne.name&&t.jsx("small",{id:vt,className:"field-error",children:Ne.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:pe=>h(pe.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${ce==="global"?" active":""}`,onClick:()=>{Ae("global"),o?.("global")},role:"radio","aria-checked":ce==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(Pl,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${ce==="project"?" active":""}`,onClick:()=>{Ae("project"),o?.("project")},role:"radio","aria-checked":ce==="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(vs,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":ce==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Ne.scope&&t.jsx("small",{className:"field-error",children:Ne.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(Ef,{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(Of,{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(_f,{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(us,{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:pe=>Ke(pe.target.value),children:Object.entries(h4).map(([pe,Xe])=>t.jsx("option",{value:pe,children:Xe},pe))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:pe=>x(pe.target.value),disabled:v!=="custom","aria-invalid":!!Ne.cronExpression,"aria-describedby":Ne.cronExpression?_e:void 0}),Ne.cronExpression?t.jsx("small",{id:_e,className:"field-error",children:Ne.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:pe=>S(pe.target.value),"aria-invalid":!!Ne.webhookPath,"aria-describedby":Ne.webhookPath?Fe:void 0}),Ne.webhookPath?t.jsx("small",{id:Fe,className:"field-error",children:Ne.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:N,onChange:pe=>E(pe.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:w,onChange:pe=>j(pe.target.value),"aria-invalid":!!Ne.endpoint,"aria-describedby":Ne.endpoint?bt:void 0}),Ne.endpoint?t.jsx("small",{id:bt,className:"field-error",children:Ne.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:()=>G("simple"),role:"radio","aria-checked":F==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${F==="advanced"?" active":""}`,onClick:()=>G("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${ee==="command"?" active":""}`,onClick:()=>J("command"),role:"radio","aria-checked":ee==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ee==="ai-prompt"?" active":""}`,onClick:()=>J("ai-prompt"),role:"radio","aria-checked":ee==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ee==="create-task"?" active":""}`,onClick:()=>J("create-task"),role:"radio","aria-checked":ee==="create-task",children:"Create Task"})]})]}),ee==="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:M,onChange:pe=>T(pe.target.value),"aria-invalid":!!Ne.command,"aria-describedby":Ne.command?ht:void 0}),Ne.command?t.jsx("small",{id:ht,className:"field-error",children:Ne.command}):t.jsx("small",{children:"Shell command to execute."})]}):ee==="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:ge,onChange:pe=>Ue(pe.target.value),rows:3,"aria-invalid":!!Ne.prompt,"aria-describedby":Ne.prompt?Ee:void 0}),Ne.prompt?t.jsx("small",{id:Ee,className:"field-error",children:Ne.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(ks,{id:"routine-model",label:"Model",models:Ie,value:De,onChange:dt,placeholder:"Use default",disabled:He}),Te&&t.jsx("small",{className:"field-error",children:Te}),Ne.model&&t.jsx("small",{id:Re,className:"field-error",children:Ne.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:Z,onChange:pe=>Q(pe.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:X,onChange:pe=>ie(pe.target.value),rows:4,"aria-invalid":!!Ne.taskDescription,"aria-describedby":Ne.taskDescription?me:void 0}),Ne.taskDescription?t.jsx("small",{id:me,className:"field-error",children:Ne.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:se,onChange:pe=>B(pe.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(ks,{id:"routine-task-model",label:"Executor Model",models:Ie,value:De,onChange:dt,placeholder:"Use default",disabled:He}),Te&&t.jsx("small",{className:"field-error",children:Te}),Ne.model&&t.jsx("small",{id:Re,className:"field-error",children:Ne.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(m4,{steps:L,onChange:k,onEditingChange:oe}),Ne.steps&&t.jsx("small",{className:"field-error",children:Ne.steps}),Ne.stepsEditing&&t.jsx("small",{className:"field-error",children:Ne.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:le,onChange:pe=>we(Number(pe.target.value)),"aria-invalid":!!Ne.timeoutMs,"aria-describedby":Ne.timeoutMs?be:void 0}),Ne.timeoutMs?t.jsx("small",{id:be,className:"field-error",children:Ne.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:_,onChange:pe=>D(pe.target.value),children:x4.map(pe=>t.jsx("option",{value:pe.value,children:pe.label},pe.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:C,onChange:pe=>P(pe.target.value),children:v4.map(pe=>t.jsx("option",{value:pe.value,children:pe.label},pe.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:I,onChange:pe=>H(pe.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:Ce,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ce,children:Ce?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const y4=3e4;function w4({onClose:e,addToast:n,projectId:s}){const[a,r]=i.useState(()=>s?"project":"global"),[o,l]=i.useState([]),[c,d]=i.useState("list"),[u,m]=i.useState(),[h,f]=i.useState(null),[p,g]=i.useState({}),x=i.useRef(null);Ti(x,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const A=await Hj(v);l(A),g($=>{const F={...$};for(const G of A){const ee=F[G.id];if(!ee||!G.lastRunResult)continue;const J=G.lastRunResult;J.success===ee.success&&(J.output||"")===ee.output&&(J.error||"")===(ee.error||"")&&delete F[G.id]}return F})}catch(A){n(Me(A)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const A=setInterval(()=>{b()},y4);return()=>clearInterval(A)},[b]),i.useEffect(()=>{const A=$=>{$.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e,c]);const y=Ui(e),S=i.useCallback(async A=>{try{await qj(A,v),n("Routine created","success"),d("list"),await b()}catch($){n(Me($)||"Failed to create routine","error")}},[n,b,v]),N=i.useCallback(A=>{m(A),d("edit")},[]),E=i.useCallback(async A=>{if(u)try{await Xu(u.id,A,v),n("Routine updated","success"),d("list"),m(void 0),await b()}catch($){n(Me($)||"Failed to update routine","error")}},[u,n,b,v]),w=i.useCallback(async A=>{try{await Vj(A.id,v),n(`Deleted "${A.name}"`,"success"),await b()}catch($){n(Me($)||"Failed to delete routine","error")}},[n,b,v]),j=i.useCallback(async A=>{f(A.id);try{const{result:$}=await Wj(A.id,v);g(F=>({...F,[A.id]:{output:$.output||"",error:$.error,success:$.success}})),$.success?n(`"${A.name}" completed successfully`,"success"):n(`"${A.name}" failed: ${$.error||"Unknown error"}`,"error"),await b()}catch($){n(Me($)||"Failed to run routine","error")}finally{f(null)}},[n,b,v]),_=i.useCallback(async A=>{try{await Xu(A.id,{enabled:!A.enabled},v),n(`"${A.name}" ${A.enabled?"disabled":"enabled"}`,"success"),await b()}catch($){n(Me($)||"Failed to toggle routine","error")}},[n,b,v]),D=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const C=i.useCallback(A=>{r(A),d("list"),m(void 0),g({})},[]),P=()=>c==="create"?t.jsx(Up,{onSubmit:S,onCancel:D,scope:a,projectId:s}):c==="edit"&&u?t.jsx(Up,{routine:u,onSubmit:E,onCancel:D,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(us,{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:()=>d("create"),children:[t.jsx(_n,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(A=>t.jsx(l4,{routine:A,onEdit:N,onDelete:w,onRun:j,onToggle:_,running:h===A.id,lastRunOutput:p[A.id]??null},A.id))}),I=()=>P(),H=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(us,{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(nn,{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${a==="global"?" active":""}`,onClick:()=>C("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(Pl,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>C("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(vs,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(us,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:H&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(_n,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:I()})]})})}const k4=3e4,Bd=new Map,ed=new Map;function Bp(e){return e??"default"}function Hp(e){const n=Bd.get(e);return n?Date.now()>=n.expiresAt?(Bd.delete(e),null):n:null}function j4(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),a=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:a}}async function N4(e){const n=ed.get(e);if(n)return n;const s=Zr().then(({providers:a,ghCli:r})=>{const l={...j4(a,r),ghCli:r,expiresAt:Date.now()+k4};return Bd.set(e,l),l}).finally(()=>{ed.delete(e)});return ed.set(e,s),s}function rx(e){const n=Bp(e),s=Hp(n),[a,r]=i.useState(s?.hasAiProvider??!1),[o,l]=i.useState(s?.hasGithub??!1),[,c]=i.useState(s?.ghCli),[d,u]=i.useState(s==null),m=i.useRef(!!s);return i.useEffect(()=>{let h=!1;const f=Bp(e),p=Hp(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const v=await N4(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function ox({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:a}){if(e&&n)return null;const r=a?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:a,children:t.jsx(nn,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${a?" 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${a?" 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 S4({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=Ys(),u=Js();pi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=ra({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,v]=i.useState(""),[b,y]=i.useState([]),[S,N]=i.useState(""),[E,w]=i.useState(""),[j,_]=i.useState([]),[D,C]=i.useState(!1),[P,I]=i.useState(""),[H,A]=i.useState(""),[$,F]=i.useState(""),[G,ee]=i.useState(""),[J,M]=i.useState(""),[T,L]=i.useState("default"),[k,K]=i.useState(!1),[oe,le]=i.useState([]),[we,ge]=i.useState(!1),[Ue,Z]=i.useState(void 0),[Q,X]=i.useState(Rs),[ie,se]=i.useState(void 0),[B,O]=i.useState(null),[ke,ae]=i.useState([]),[te,Ie]=i.useState(!1),[Oe,He]=i.useState(!1),$e=i.useRef(null),[Te,ue]=i.useState(!1),[ce,Ae]=i.useState(""),Ne=i.useRef(null),{hasAiProvider:ye,hasGithub:Ce,loading:fe}=rx(s),{nodes:Pe}=Bl(),De=i.useCallback(be=>{ge(!0),le(be)},[]),dt=i.useCallback(()=>{ge(!1)},[]),pt=i.useCallback(async()=>{if(ke.length>0){Ie(!0);return}He(!0);try{const be=await Na(void 0,s);ae(be),Ie(!0)}catch(be){const Ke=Me(be);o(Ke?`Failed to load agents: ${Ke}`:"Failed to load agents","error"),Ie(!1)}finally{He(!1)}},[ke.length,s,o]);i.useEffect(()=>{if(!te)return;const be=Ke=>{$e.current&&!$e.current.contains(Ke.target)&&Ie(!1)};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[te]),i.useEffect(()=>{if(!Te)return;const be=Ke=>{Ne.current&&!Ne.current.contains(Ke.target)&&(ue(!1),Ae(""))};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[Te]);const lt=a.filter(be=>!b.includes(be.id)).sort((be,Ke)=>{const pe=Ke.createdAt.localeCompare(be.createdAt);if(pe!==0)return pe;const Xe=parseInt(be.id.slice(be.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ke.id.slice(Ke.id.lastIndexOf("-")+1),10)||0)-Xe}),vt=ce?lt.filter(be=>be.id.toLowerCase().includes(ce.toLowerCase())||be.title&&be.title.toLowerCase().includes(ce.toLowerCase())||be.description&&be.description.toLowerCase().includes(ce.toLowerCase())):lt,_e=(be,Ke)=>be.length>Ke?be.slice(0,Ke)+"…":be;i.useEffect(()=>{const be=x.trim()!==""||b.length>0||j.length>0||P!==""||H!==""||$!==""||G!==""||oe.length>0||B!==null||Ue!==void 0||Q!==Rs||ie!==void 0||S!==""||E!=="";K(be)},[x,b,j,P,H,$,G,oe,B,Ue,Q,ie,S,E]);const Fe=i.useCallback(async()=>{k&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(j.forEach(be=>URL.revokeObjectURL(be.previewUrl)),_([]),v(""),y([]),I(""),A(""),F(""),ee(""),M(""),L("default"),le([]),ge(!1),O(null),Ie(!1),Z(void 0),X(Rs),se(void 0),N(""),w(""),K(!1),n())},[k,n,j,d]),bt=i.useCallback(async()=>{const be=x.trim();if(!(!be||D)){C(!0);try{const Ke=P.indexOf("/"),pe=H.indexOf("/"),Xe=$.indexOf("/"),wt=await r({title:void 0,description:be,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:we?oe.length>0?oe:[]:void 0,...B?{assignedAgentId:B}:{},modelPresetId:T==="preset"&&J||void 0,modelProvider:P&&Ke!==-1?P.slice(0,Ke):void 0,modelId:P&&Ke!==-1?P.slice(Ke+1):void 0,validatorModelProvider:H&&pe!==-1?H.slice(0,pe):void 0,validatorModelId:H&&pe!==-1?H.slice(pe+1):void 0,planningModelProvider:$&&Xe!==-1?$.slice(0,Xe):void 0,planningModelId:$&&Xe!==-1?$.slice(Xe+1):void 0,thinkingLevel:G!==""?G:void 0,reviewLevel:Ue,priority:Q,nodeId:ie,branch:S.trim()===""?void 0:S.trim(),baseBranch:E.trim()===""?void 0:E.trim()});if(j.length>0){const gt=[];for(const Tt of j)try{await Fl(wt.id,Tt.file,s)}catch{gt.push(Tt.file.name)}gt.length>0&&o(`Failed to upload: ${gt.join(", ")}`,"error")}j.forEach(gt=>URL.revokeObjectURL(gt.previewUrl)),_([]),v(""),y([]),I(""),A(""),F(""),ee(""),M(""),L("default"),le([]),ge(!1),O(null),Ie(!1),Z(void 0),X(Rs),se(void 0),N(""),w(""),o(`Created ${wt.id}`,"success"),n()}catch(Ke){o(Me(Ke)||"Failed to create task","error")}finally{C(!1)}}},[x,b,j,P,H,$,G,D,r,o,n,s,T,J,oe,we,B,Ue,Q,ie,S,E]),ht=i.useCallback(be=>{be.key==="Escape"&&(be.preventDefault(),Fe())},[Fe]),me=(B?ke.find(be=>be.id===B):void 0)?.name??B,Re=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:Ne,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ue(be=>!be),disabled:D,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),Te&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ce,onChange:be=>Ae(be.target.value),onClick:be=>be.stopPropagation()}),vt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):vt.map(be=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(be.id)?" selected":""}`,onClick:()=>{y(b.includes(be.id)?b.filter(Ke=>Ke!==be.id):[...b,be.id]),ue(!1),Ae("")},onMouseDown:Ke=>Ke.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:be.id}),t.jsx("span",{className:"dep-dropdown-title",children:_e(be.title||be.description||be.id,30)})]},be.id))]})]}),b.length>0&&t.jsx("div",{className:"selected-deps",children:b.map(be=>t.jsxs("span",{className:"dep-chip",children:[be,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>y(b.filter(Ke=>Ke!==be)),disabled:D,children:"×"})]},be))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:$e,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{te?Ie(!1):pt()},disabled:D,"data-testid":"new-task-agent-button",children:[t.jsx(zn,{size:12,style:{verticalAlign:"middle"}}),me?` ${me}`:" Assign agent"]}),te&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:be=>be.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Oe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Oe&&ke.map(be=>t.jsxs("div",{className:`dep-dropdown-item${B===be.id?" selected":""}`,onMouseDown:Ke=>Ke.preventDefault(),onClick:()=>{O(be.id===B?null:be.id),Ie(!1)},"data-testid":`agent-option-${be.id}`,children:[t.jsx(zn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:be.role}),t.jsx("span",{className:"dep-dropdown-title",children:be.name})]},be.id)),!Oe&&ke.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),B&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:be=>be.preventDefault(),onClick:()=>{O(null),Ie(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Fe,onKeyDown:ht,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:be=>be.stopPropagation(),style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Fe,disabled:D,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!fe&&t.jsx(ox,{hasAiProvider:ye,hasGithub:Ce}),t.jsx(zb,{mode:"create",description:x,onDescriptionChange:v,dependencies:b,onDependenciesChange:y,executorModel:P,onExecutorModelChange:I,validatorModel:H,onValidatorModelChange:A,presetMode:T,onPresetModeChange:L,selectedPresetId:J,onSelectedPresetIdChange:M,selectedWorkflowSteps:oe,onWorkflowStepsChange:De,onDefaultOnApplied:dt,pendingImages:j,onImagesChange:_,tasks:a,projectId:s,disabled:D,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Fe,planningModel:$,onPlanningModelChange:F,thinkingLevel:G,onThinkingLevelChange:ee,reviewLevel:Ue,onReviewLevelChange:Z,priority:Q,onPriorityChange:X,branch:S,onBranchChange:N,baseBranch:E,onBaseBranchChange:w,nodeId:ie,onNodeIdChange:se,nodeOptions:Pe,renderBelowPrimary:Re,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Fe,disabled:D,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:bt,disabled:!x.trim()||D,children:D?"Creating...":"Create Task"})]})]})}):null}function li(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function qp(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function C4(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function E4(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function _4(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function M4(e,n){if(e===null||!Number.isFinite(e)||e<0)return"normal";const s=n>0?e/n:e;return s>=80?"critical":s>=50?"warning":"normal"}function Yo(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function A4(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function P4({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,m]=i.useState(!0),[h,f]=i.useState(90),[p,g]=i.useState(!1),[x,v]=i.useState(!1),[b,y]=i.useState(null),[S,N]=i.useState(null),[E,w]=i.useState(null),j=i.useCallback(async Z=>{l(!0);try{const Q=await kN(s);r(Q),d(null),w(Date.now()),Z?.preserveKillResult||y(null)}catch(Q){d(Q instanceof Error?Q.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;j();const Z=window.setInterval(()=>{j()},5e3);return()=>{window.clearInterval(Z)}},[e,j]),i.useEffect(()=>{if(!e)return;(async()=>{try{const Q=await ja();m(Q.vitestAutoKillEnabled??!0),f(Q.vitestKillThresholdPct??90),N(null)}catch(Q){N(Q instanceof Error?Q.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const Z=Q=>{Q.key==="Escape"&&n()};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[e,n]);const _=i.useMemo(()=>{if(!a)return[];const Z=a.systemStats,Q=Yo(C4(Z.heapUsed,Z.heapLimit)),X=Yo(E4(Z.rss,Z.systemTotalMem));return[{label:"RSS",value:li(Z.rss),detail:qp(Z.rss,Z.systemTotalMem),className:X},{label:"Heap Used",value:li(Z.heapUsed),detail:`of ${li(Z.heapTotal)}`,className:Q},{label:"Heap Limit",value:li(Z.heapLimit),detail:"V8 limit"},{label:"External",value:li(Z.external)},{label:"Array Buffers",value:li(Z.arrayBuffers)}]},[a]),D=i.useCallback(async Z=>{m(Z);try{await $n({vitestAutoKillEnabled:Z}),N(null)}catch(Q){N(Q instanceof Error?Q.message:"Failed to save vitest settings")}},[]),C=i.useCallback(async Z=>{const Q=Math.min(99,Math.max(50,Number.isFinite(Z)?Math.round(Z):90));f(Q);try{await $n({vitestKillThresholdPct:Q}),N(null)}catch(X){N(X instanceof Error?X.message:"Failed to save vitest settings")}},[]),P=i.useCallback(async()=>{if(!p){if(!x){v(!0);return}g(!0);try{const Z=await jN(s);y(Z),v(!1),await j({preserveKillResult:!0})}catch(Z){d(Z instanceof Error?Z.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,j,s]);if(!e)return null;const I=a?.systemStats,H=o&&!!a,A=E?`Updated ${new Date(E).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",$=a?.taskStats,F=I?I.systemTotalMem-I.systemFreeMem:0,G=I?_4(F,I.systemTotalMem):"normal",ee=I?Yo(G):"",J=I&&Number.isFinite(I.systemTotalMem)&&I.systemTotalMem>0?Math.max(0,Math.min(100,F/I.systemTotalMem*100)):0,M=I?`System memory used: ${J.toFixed(1)}% (${li(F)} of ${li(I.systemTotalMem)})`:"System memory usage unavailable",T=a?.vitestProcessCount,L=M4(I?.cpuPercent??null,I?.cpuCount??0),k=Yo(L),K=I?.cpuPercent??null,oe=K===null?0:Math.max(0,Math.min(100,K)),le=K===null?"Sampling…":`${K.toFixed(1)}%`,we=K===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${K.toFixed(1)}%`,ge=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",Ue=A4(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:Z=>{Z.target===Z.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(Xa,{}),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:A})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void j(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(hs,{size:16,className:H?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(nn,{})})]})]}),o&&!a&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!a&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),a&&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:_.map(Z=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:Z.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${Z.className}`.trim(),children:Z.value}),Z.detail?t.jsx("span",{className:"system-stats-modal__detail",children:Z.detail}):null]})]},Z.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 system-stats-modal__row--cpu-used",children:[t.jsx("dt",{children:"App CPU"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${k}`.trim(),children:le}),t.jsx("span",{className:"system-stats-modal__detail",children:K===null?"First sample pending":"process usage"})]}),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--${L}`,role:"progressbar","aria-valuenow":Math.round(oe),"aria-valuemin":0,"aria-valuemax":100,"aria-label":we,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${L}`,style:{width:`${oe}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:I?.loadAvg.map(Z=>Z.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:I?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:I?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:I?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:I?.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 ${ee}`.trim(),children:I?li(F):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:I?`${qp(F,I.systemTotalMem)} of ${li(I.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--${G}`,role:"progressbar","aria-valuenow":Math.round(J),"aria-valuemin":0,"aria-valuemax":100,"aria-label":M,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${G}`,style:{width:`${J}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:I?li(I.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:$?.total??0})]}),Object.entries($?.byColumn??{}).map(([Z,Q])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:Z}),t.jsx("dd",{children:Q})]},Z))]})]}),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:$?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:$?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:$?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:$?.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(nw,{}),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??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void P(),disabled:p||T===0,children:[t.jsx(rw,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:u,onChange:Z=>{D(Z.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:Z=>{const Q=Number.parseInt(Z.target.value,10);C(Number.isNaN(Q)?90:Q)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:Z=>{const Q=Number.parseInt(Z.target.value,10);C(Number.isNaN(Q)?90:Q)},onBlur:()=>{C(h)}})]})]}),b&&t.jsxs("p",{className:ge,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",Ue]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const T4=5e3;function R4(e={}){const{projectId:n,type:s,limit:a=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),x=i.useRef(void 0),v=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await am({limit:a,projectId:n,type:s}):S=(await Zu({limit:a,type:s,projectId:n})).map(E=>({...E,projectId:n??"",projectName:""})),c(S),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(x.current)try{u(!0);let S;o?S=await am({limit:a,projectId:n,type:s,since:x.current}):S=(await Zu({limit:a,type:s,since:x.current,projectId:n})).map(E=>({...E,projectId:n??"",projectName:""})),c(N=>[...N,...S]),p(S.length===a),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},T4),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:m,refresh:v,clear:y,hasMore:f,loadMore:b}}const td={"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"},I4={"task:created":t.jsx(_n,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(oo,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(hs,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(nn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Gn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(lo,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(qr,{size:14,className:"activity-icon settings"})};function $4(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/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 D4({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[m,h]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{h(r||"all")},[r]);const g=d==="all"?void 0:d,x=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:N,hasMore:E}=R4({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),w=b.map(P=>({id:P.id,timestamp:P.timestamp,type:P.type,taskId:P.taskId,taskTitle:P.taskTitle,details:P.details,metadata:P.metadata,projectId:P.projectId,projectName:P.projectName})),j=async()=>{try{await Kj(),N(),p(!1)}catch{p(!1)}},_=P=>{a&&a(P)},D=P=>{h(P),l?.(P==="all"?void 0:P)};i.useEffect(()=>{if(!e)return;const P=I=>{I.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[e,n,f]);const C=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:P=>{P.target===P.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(Qr,{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(vs,{size:14}),t.jsxs("select",{value:m,onChange:P=>D(P.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(P=>t.jsx("option",{value:P.id,children:P.name},P.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(ll,{size:14}),t.jsxs("select",{value:d,onChange:P=>u(P.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(td).map(([P,I])=>t.jsx("option",{value:P,children:I},P))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>N(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(xt,{size:14,className:"spin"}):t.jsx(hs,{size:14})}),w.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(En,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),C&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(P=>P.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",td[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Ps,{size:16}),t.jsx("span",{children:S})]}),w.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Qr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:C?"No activity matches the current filters":"No activity recorded yet"}),C&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:w.map(P=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:I4[P.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:td[P.type]}),t.jsx("span",{className:"activity-log-entry-time",children:$4(P.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[P.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>_(P.taskId),"data-testid":"activity-task-link",children:P.taskId}),P.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:P.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:P.details})]}),P.metadata&&Object.keys(P.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof P.metadata.from=="string"&&typeof P.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[P.metadata.from," → ",P.metadata.to]}),typeof P.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${P.metadata.merged?"success":"error"}`,children:P.metadata.merged?"Merged":"Not merged"})]})]})]},P.id))}),E&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:N,"data-testid":"activity-load-more",children:"Load More"}),y&&w.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(xt,{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:j,children:"Clear Log"})]})]})})]})}):null}const Rr=[{id:"status",label:"Status",icon:Df},{id:"changes",label:"Changes",icon:hd},{id:"commits",label:"Commits",icon:co},{id:"branches",label:"Branches",icon:zs},{id:"worktrees",label:"Worktrees",icon:ey},{id:"stashes",label:"Stashes",icon:ao},{id:"remotes",label:"Remotes",icon:Rf}];function Vp({status:e}){switch(e){case"added":case"untracked":return t.jsx(Rv,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Pf,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Av,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(na,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx($v,{size:14,className:"gm-file-icon"})}}function Wp({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 L4(e){return i.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function rr(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const a=new Date().getTime()-n.getTime(),r=Math.floor(a/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 O4({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=Ys(),l=Js();pi(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=ra({enabled:l==="mobile"}),h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{},f=i.useCallback(()=>{if(l==="mobile"){const z=document.activeElement;z instanceof HTMLElement&&z.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[x,v]=i.useState(!1),[b,y]=i.useState(null),S=i.useRef(null);Ti(S,e,"fusion:git-modal-size");const N=Ui(f),E=L4(a),[w,j]=i.useState(null),[_,D]=i.useState([]),[C,P]=i.useState(new Set),[I,H]=i.useState(""),[A,$]=i.useState(!1),[F,G]=i.useState(null),[ee,J]=i.useState(!1),[M,T]=i.useState(null),[L,k]=i.useState(null),K=i.useRef(0),[oe,le]=i.useState([]),[we,ge]=i.useState(null),[Ue,Z]=i.useState(null),[Q,X]=i.useState(!1),[ie,se]=i.useState(20),[B,O]=i.useState(""),[ke,ae]=i.useState([]),[te,Ie]=i.useState(""),[Oe,He]=i.useState(""),[$e,Te]=i.useState(""),[ue,ce]=i.useState(null),[Ae,Ne]=i.useState([]),[ye,Ce]=i.useState(!1),[fe,Pe]=i.useState(null),[De,dt]=i.useState(null),[pt,lt]=i.useState(!1),[vt,_e]=i.useState([]),[Fe,bt]=i.useState([]),[ht,Ee]=i.useState(""),[me,Re]=i.useState(null),[be,Ke]=i.useState(null),[pe,Xe]=i.useState(null),wt=i.useCallback(async()=>{if(e){v(!0),y(null);try{switch(p){case"status":{const z=await oi(r);j(z);break}case"changes":{const[z,he]=await Promise.all([oi(r),Da(r)]);j(z),D(he),P(new Set),k(null),G(null),T(null);break}case"commits":{const z=await Qk(ie,r);le(z);break}case"branches":{const[z,he]=await Promise.all([wr(r),oi(r)]);ae(z),j(he);break}case"worktrees":{const z=await tj(r);_e(z);break}case"stashes":{const z=await So(r);bt(z);break}case"remotes":{const z=await oi(r);j(z);break}}}catch(z){y(Me(z)||"Failed to fetch git data"),a(Me(z)||"Failed to fetch git data","error")}finally{v(!1)}}},[p,e,ie,a,r]);i.useEffect(()=>{e&&wt()},[wt,e]),i.useEffect(()=>{if(!e)return;const z=he=>{if(he.key==="Escape"){f();return}if((he.key==="ArrowUp"||he.key==="ArrowDown")&&he.altKey){he.preventDefault();const st=Rr.findIndex(It=>It.id===p);he.key==="ArrowUp"&&st>0?g(Rr[st-1].id):he.key==="ArrowDown"&&st<Rr.length-1&&g(Rr[st+1].id)}};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[e,f,p]);const gt=i.useCallback(async z=>{try{await Ku(z,r),a(`Staged ${z.length} file(s)`,"success");const he=await Da(r);D(he),P(new Set),k(null),G(null),T(null)}catch(he){a(Me(he)||"Failed to stage files","error")}},[a,r]),Tt=i.useCallback(async z=>{try{await uj(z,r),a(`Unstaged ${z.length} file(s)`,"success");const he=await Da(r);D(he),P(new Set),k(null),G(null),T(null)}catch(he){a(Me(he)||"Failed to unstage files","error")}},[a,r]),Zt=i.useCallback(async z=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${z.length} file(s)? This cannot be undone.`,danger:!0}))try{await mj(z,r),a(`Discarded changes to ${z.length} file(s)`,"success");const[st,It]=await Promise.all([Da(r),oi(r)]);D(st),j(It),P(new Set),k(null),G(null),T(null)}catch(st){a(Me(st)||"Failed to discard changes","error")}},[a,r,o]),Ot=i.useCallback(async z=>{if(z.preventDefault(),!!I.trim()){$(!0);try{const he=await Gu(I.trim(),r);a(`Committed: ${he.hash}`,"success"),H("");const[st,It]=await Promise.all([Da(r),oi(r)]);D(st),j(It),k(null),G(null),T(null)}catch(he){a(Me(he)||"Failed to commit","error")}finally{$(!1)}}},[I,a,r]),Rt=i.useCallback(async()=>{if(I.trim()){$(!0);try{const z=_.filter(ve=>!ve.staged).map(ve=>ve.file);z.length>0&&await Ku(z,r);const he=await Gu(I.trim(),r);a(`Committed: ${he.hash}`,"success"),H("");const[st,It]=await Promise.all([Da(r),oi(r)]);D(st),j(It),k(null),G(null),T(null)}catch(z){a(Me(z)||"Failed to commit","error")}finally{$(!1)}}},[I,_,a,r]),en=i.useCallback(async(z,he)=>{k({file:z,staged:he}),J(!0),T(null);const st=K.current+1;K.current=st;try{const It=await dj(z,he,r);if(K.current!==st)return;G(It)}catch(It){if(K.current!==st)return;const ve=Me(It)||"Failed to load file diff";G(null),T(ve),a(ve,"error")}finally{K.current===st&&J(!1)}},[a,r]),zt=i.useCallback(z=>{P(he=>{const st=new Set(he);return st.has(z)?st.delete(z):st.add(z),st})},[]),Qt=i.useCallback(async z=>{if(we===z){ge(null),Z(null);return}ge(z),X(!0);try{const he=await hl(z,r);Z(he)}catch(he){a(Me(he)||"Failed to load diff","error"),Z(null)}finally{X(!1)}},[we,a,r]),xn=i.useCallback(()=>{se(z=>Math.min(z+20,100))},[]),Kt=i.useMemo(()=>{if(!B.trim())return oe;const z=B.toLowerCase();return oe.filter(he=>he.message.toLowerCase().includes(z)||he.author.toLowerCase().includes(z)||he.shortHash.toLowerCase().includes(z))},[oe,B]),Ut=i.useCallback(async z=>{if(z.preventDefault(),!!te.trim()){v(!0);try{await nj(te.trim(),Oe.trim()||void 0,r),a(`Created branch ${te}`,"success"),Ie(""),He("");const he=await wr(r);ae(he)}catch(he){a(Me(he)||"Failed to create branch","error")}finally{v(!1)}}},[te,Oe,a,r]),fn=i.useCallback(async z=>{v(!0);try{await sj(z,r),a(`Switched to ${z}`,"success");const[he,st]=await Promise.all([oi(r),wr(r)]);j(he),ae(st)}catch(he){a(Me(he)||"Failed to checkout branch","error")}finally{v(!1)}},[a,r]),un=i.useCallback(async z=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${z}"?`,danger:!0})){v(!0);try{await Wu(z,void 0,r),a(`Deleted branch ${z}`,"success");const st=await wr(r);ae(st)}catch(st){if(Me(st).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Wu(z,!0,r),a(`Force deleted branch ${z}`,"success");const ve=await wr(r);ae(ve)}catch(ve){a(Me(ve)||"Failed to delete branch","error")}}else a(Me(st)||"Failed to delete branch","error")}finally{v(!1)}}},[a,r,o]),tn=i.useMemo(()=>{if(!$e.trim())return ke;const z=$e.toLowerCase();return ke.filter(he=>he.name.toLowerCase().includes(z))},[ke,$e]),Vt=i.useCallback(async z=>{if(ue===z){ce(null),Ne([]),Pe(null),dt(null);return}ce(z),Ne([]),Pe(null),dt(null),Ce(!0);try{const he=await ej(z,10,r);Ne(he)}catch{Ne([])}finally{Ce(!1)}},[ue,r]),mn=i.useCallback(async z=>{if(fe===z){Pe(null),dt(null);return}Pe(z),dt(null),lt(!0);try{const he=await hl(z,r);dt(he)}catch{dt(null)}finally{lt(!1)}},[fe,r]),xe=i.useCallback(()=>{ce(null),Ne([]),Pe(null),dt(null)},[]),Le=i.useCallback(async z=>{z.preventDefault(),Re("create");try{await oj(ht.trim()||void 0,r),a("Changes stashed","success"),Ee("");const he=await So(r);bt(he)}catch(he){a(Me(he)||"Failed to stash changes","error")}finally{Re(null)}},[ht,a,r]),Ve=i.useCallback(async(z,he=!1)=>{Re(`apply-${z}`);try{await lj(z,he,r),a(he?"Stash popped":"Stash applied","success");const st=await So(r);bt(st)}catch(st){a(Me(st)||"Failed to apply stash","error")}finally{Re(null)}},[a,r]),at=i.useCallback(async z=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${z}}? This cannot be undone.`,danger:!0})){Re(`drop-${z}`);try{await cj(z,r),a("Stash dropped","success");const st=await So(r);bt(st)}catch(st){a(Me(st)||"Failed to drop stash","error")}finally{Re(null)}}},[a,r,o]),Ge=i.useCallback(async()=>{Ke("fetch");try{const z=await ij(void 0,r);Xe(z),a(z.message||"Fetch completed",z.fetched?"success":"info");const he=await oi(r);j(he)}catch(z){a(Me(z)||"Fetch failed","error")}finally{Ke(null)}},[a,r]),Ft=i.useCallback(async()=>{Ke("pull");try{const z=await aj(r);Xe(z),z.conflict?a("Merge conflict detected. Resolve manually.","error"):a(z.message||"Pull completed","success");const he=await oi(r);j(he)}catch(z){a(Me(z)||"Pull failed","error")}finally{Ke(null)}},[a,r]),_t=i.useCallback(async()=>{Ke("push");try{const z=await rj(r);Xe(z),a(z.message||"Push completed","success");const he=await oi(r);j(he)}catch(z){a(Me(z)||"Push failed","error")}finally{Ke(null)}},[a,r]),qt=i.useMemo(()=>_.filter(z=>z.staged),[_]),St=i.useMemo(()=>_.filter(z=>!z.staged),[_]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...N,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:S,style:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(pd,{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:wt,disabled:x,title:"Refresh",children:t.jsx(hs,{size:14,className:x?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(nn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Rr.map(z=>{const he=z.icon;return t.jsxs("button",{role:"tab","aria-selected":p===z.id,className:`gm-nav-item${p===z.id?" active":""}`,onClick:()=>g(z.id),children:[t.jsx(he,{size:16}),t.jsx("span",{className:"gm-nav-label",children:z.label})]},z.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[x&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(xt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!x&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Ps,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:wt,children:"Retry"})]}),p==="status"&&!x&&w&&t.jsx(F4,{status:w,copyToClipboard:E}),p==="changes"&&!x&&t.jsx(z4,{status:w,stagedFiles:qt,unstagedFiles:St,selectedFiles:C,toggleFileSelection:zt,onStageFiles:gt,onUnstageFiles:Tt,onDiscardChanges:Zt,onSelectDiffFile:en,selectedDiffTarget:L,changeDiff:F,loadingChangeDiff:ee,changeDiffError:M,commitMessage:I,setCommitMessage:H,onCommit:Ot,onStageAllAndCommit:Rt,committing:A}),p==="commits"&&!x&&t.jsx(U4,{commits:Kt,commitSearch:B,setCommitSearch:O,selectedCommit:we,commitDiff:Ue,loadingDiff:Q,onCommitClick:Qt,onLoadMore:xn,canLoadMore:oe.length>=ie&&ie<100,copyToClipboard:E}),p==="branches"&&!x&&t.jsx(B4,{branches:tn,branchSearch:$e,setBranchSearch:Te,newBranchName:te,setNewBranchName:Ie,branchBase:Oe,setBranchBase:He,onCreateBranch:Ut,onCheckoutBranch:fn,onDeleteBranch:un,loading:x,allBranches:ke,selectedBranch:ue,branchCommits:Ae,loadingBranchCommits:ye,expandedBranchCommit:fe,branchCommitDiff:De,loadingBranchCommitDiff:pt,onSelectBranch:Vt,onBranchCommitClick:mn,onCloseBranchDetails:xe}),p==="worktrees"&&!x&&t.jsx(H4,{worktrees:vt}),p==="stashes"&&!x&&t.jsx(q4,{stashes:Fe,stashMessage:ht,setStashMessage:Ee,onCreateStash:Le,onApplyStash:Ve,onDropStash:at,stashLoading:me}),p==="remotes"&&!x&&t.jsx(V4,{status:w,remoteLoading:be,lastRemoteResult:pe,onFetch:Ge,onPull:Ft,onPush:_t,addToast:a,projectId:r,copyToClipboard:E})]})]})]})}):null}function F4({status:e,copyToClipboard:n}){return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Repository Status"})}),t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Branch"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(zs,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(ta,{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(Gn,{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(fa,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(ro,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Gn,{size:12}),"Up to date"]})]})]})]})]})}function z4({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:x,onStageAllAndCommit:v,committing:b}){const y=s.filter(N=>a.has(`unstaged:${N.file}`)),S=n.filter(N=>a.has(`staged:${N.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(zs,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-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(N=>N.file)),title:"Stage selected",children:[t.jsx(_n,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(N=>N.file)),title:"Discard selected",children:t.jsx(lo,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(N=>N.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(N=>{const E=u?.file===N.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${E?" active":""}`,onClick:()=>d(N.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),d(N.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${N.file}`),onChange:()=>r(`unstaged:${N.file}`)})}),t.jsx(Vp,{status:N.status}),t.jsx("span",{className:"gm-file-name",title:N.file,children:t.jsx("bdo",{dir:"ltr",children:N.file})}),t.jsx(Wp,{status:N.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([N.file])},title:"Stage file",children:t.jsx(_n,{size:12})})]},`unstaged:${N.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(N=>N.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(N=>N.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(N=>{const E=u?.file===N.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${E?" active":""}`,onClick:()=>d(N.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),d(N.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${N.file}`),onChange:()=>r(`staged:${N.file}`)})}),t.jsx(Vp,{status:N.status}),t.jsx("span",{className:"gm-file-name",title:N.file,children:t.jsx("bdo",{dir:"ltr",children:N.file})}),t.jsx(Wp,{status:N.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([N.file])},title:"Unstage file",children:t.jsx(nn,{size:12})})]},`staged:${N.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(hd,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{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(hd,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:N=>g(N.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(xt,{size:14,className:"spin"}):t.jsx(pa,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function U4({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:a,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:d,copyToClipboard:u}){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(Li,{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:rr(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:()=>u(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(ta,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[m.body&&t.jsx("div",{className:"gm-commit-message-full",children:m.body}),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))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function B4({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:x,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:N}){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(Li,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:E=>s(E.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:E=>r(E.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:E=>l(E.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(E=>t.jsx("option",{value:E.name,children:E.name},E.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx(_n,{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(E=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${E.isCurrent?" current":""}${f===E.name?" selected":""}`,onClick:()=>y(E.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[E.isCurrent&&t.jsx(os,{size:14,className:"gm-current-icon"}),E.name]}),E.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",E.remote]}),E.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:rr(E.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!E.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),d(E.name)},disabled:m,title:"Checkout",children:t.jsx(zs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),u(E.name)},disabled:m,title:"Delete",children:t.jsx(En,{size:14})})]})})]}),f===E.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(co,{size:14}),"Commits on ",E.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:N,title:"Close","data-testid":"close-branch-details",children:t.jsx(nn,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(w=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(w.hash),"data-testid":`branch-commit-${w.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:w.shortHash}),t.jsx("span",{className:"gm-commit-message",title:w.message,children:w.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:w.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:rr(w.date)}),w.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===w.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[(w.body||w.message)&&t.jsx("div",{className:"gm-commit-message-full",children:w.body||w.message}),v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},w.hash))})]})]},E.name))})]})}function H4({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:ru(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(zs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function q4({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,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:a,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(xt,{size:14,className:"spin"}):t.jsx(ao,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(zs,{size:12}),c.branch]}),t.jsx("span",{children:rr(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(xt,{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(xt,{size:14,className:"spin"}):t.jsx(En,{size:14})})]})]},c.index))})]})}function V4({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=ye=>{try{return new URL(ye).hostname}catch{return ye.replace(/^git@/,"").split(":")[0]||ye}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[v,b]=i.useState(""),[y,S]=i.useState(""),[N,E]=i.useState(null),[w,j]=i.useState(""),[_,D]=i.useState(""),[C,P]=i.useState(!1),[I,H]=i.useState([]),[A,$]=i.useState(!1),[F,G]=i.useState(null),[ee,J]=i.useState([]),[M,T]=i.useState(!1),[L,k]=i.useState(null),K=i.useRef(0),oe=m.find(ye=>ye.name===F),[le,we]=i.useState(null),[ge,Ue]=i.useState(null),[Z,Q]=i.useState(!1),[X,ie]=i.useState(null),[se,B]=i.useState(null),[O,ke]=i.useState(!1);i.useEffect(()=>{ae()},[]),i.useEffect(()=>{e&&e.ahead>0?te():e&&e.ahead===0&&H([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!F&&G(m[0].name)},[m]),i.useEffect(()=>{F?Ie(F):(J([]),k(null))},[F]),i.useEffect(()=>{!F||!s||Ie(F)},[F,s]),i.useEffect(()=>{F&&!m.find(ye=>ye.name===F)&&G(m.length>0?m[0].name:null)},[m,F]);const ae=async()=>{p(!0);try{const ye=await Bk(c);h(ye)}catch(ye){l(Me(ye)||"Failed to load remotes","error")}finally{p(!1)}},te=async()=>{$(!0);try{const ye=await Xk(c);H(ye)}catch{H([])}finally{$(!1)}},Ie=async ye=>{const Ce=K.current+1;K.current=Ce,T(!0),k(null);try{const fe=await Zk(ye,void 0,10,c);if(K.current!==Ce)return;J(fe)}catch(fe){if(K.current!==Ce)return;k(Me(fe)||"Failed to load remote commits"),J([])}finally{K.current===Ce&&T(!1)}},Oe=Ys(),He=async ye=>{if(ye.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await Hk(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),P(!1),await ae()}catch(Ce){l(Me(Ce)||"Failed to add remote","error")}finally{x(null)}}},$e=async ye=>{if(await Oe.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${ye}'?`,danger:!0})){x(`remove-${ye}`);try{await qk(ye,c),l(`Remote '${ye}' removed`,"success"),await ae()}catch(fe){l(Me(fe)||"Failed to remove remote","error")}finally{x(null)}}},Te=async ye=>{if(_.trim()){x(`rename-${ye}`);try{await Vk(ye,_.trim(),c),l(`Remote renamed to '${_.trim()}'`,"success"),E(null),D(""),await ae()}catch(Ce){l(Me(Ce)||"Failed to rename remote","error")}finally{x(null)}}},ue=async ye=>{if(w.trim()){x(`url-${ye}`);try{await Wk(ye,w.trim(),c),l("Remote URL updated","success"),E(null),j(""),await ae()}catch(Ce){l(Me(Ce)||"Failed to update remote URL","error")}finally{x(null)}}},ce=i.useCallback(async(ye,Ce)=>{if(Ce==="ahead"){if(le===ye){we(null),Ue(null);return}we(ye),Ue(null),Q(!0);try{const fe=await hl(ye);Ue(fe)}catch{Ue(null)}finally{Q(!1)}}else{if(X===ye){ie(null),B(null);return}ie(ye),B(null),ke(!0);try{const fe=await hl(ye);B(fe)}catch{B(null)}finally{ke(!1)}}},[le,X]),Ae=ye=>{E(`url-${ye.name}`),j(ye.pushUrl||ye.fetchUrl)},Ne=ye=>{E(`name-${ye.name}`),D(ye.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>P(!C),disabled:g!==null,title:C?"Cancel":"Add Remote",children:C?t.jsx(nn,{size:14}):t.jsx(_n,{size:14})})]}),C&&t.jsxs("form",{className:"gm-remote-form",onSubmit:He,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:ye=>b(ye.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:ye=>S(ye.target.value),disabled:g==="add",className:"input 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(xt,{size:12,className:"spin"}):t.jsx(_n,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(ye=>t.jsxs("div",{className:`gm-remote-selector-item${F===ye.name?" selected":""}`,onClick:()=>G(ye.name),role:"button",tabIndex:0,onKeyDown:Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),G(ye.name))},children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[t.jsx("span",{className:"gm-remote-selector-name-text",children:ye.name}),ye.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:ye.fetchUrl,children:u(ye.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:Ce=>{Ce.stopPropagation(),$e(ye.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(En,{size:14})})]},ye.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[F&&oe?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("span",{className:"status-dot status-dot--online","aria-hidden":"true"}),t.jsx(fa,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx("span",{className:"status-dot status-dot--pending","aria-hidden":"true"}),t.jsx(ro,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:a,disabled:n!==null||f,children:[n==="fetch"?t.jsx(xt,{size:14,className:"spin"}):t.jsx(hs,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||f,children:[n==="pull"?t.jsx(xt,{size:14,className:"spin"}):t.jsx(Vs,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(xt,{size:14,className:"spin"}):t.jsx(fa,{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:"}),N===`url-${F}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:w,onChange:ye=>j(ye.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>ue(F),disabled:g===`url-${F}`,children:g===`url-${F}`?t.jsx(xt,{size:12,className:"spin"}):t.jsx(os,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{E(null),j("")},title:"Cancel",children:t.jsx(nn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:oe.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:oe.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(oe.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(ta,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ae(oe),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Ss,{size:14})})]})]})]}),oe.pushUrl&&oe.pushUrl!==oe.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:oe.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:oe.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(oe.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(ta,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:N===`name-${F}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:_,onChange:ye=>D(ye.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Te(F),disabled:g===`rename-${F}`,children:g===`rename-${F}`?t.jsx(xt,{size:12,className:"spin"}):t.jsx(os,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{E(null),D("")},title:"Cancel",children:t.jsx(nn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ne(oe),disabled:g!==null,title:"Edit remote name",children:t.jsx(Ss,{size:14})})})]}),e&&e.ahead>0&&t.jsxs("div",{className:"gm-remote-section","data-testid":"commits-to-push",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(fa,{size:14}),"Commits to Push (",e.ahead,")"]})}),A?t.jsxs("div",{className:"gm-loading",children:[t.jsx(xt,{size:14,className:"spin"}),"Loading..."]}):I.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:I.map(ye=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ce(ye.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),ce(ye.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:ye.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ye.message,children:ye.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ye.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:rr(ye.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:le===ye.hash?t.jsx(cn,{size:14}):t.jsx(Un,{size:14})})]}),le===ye.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Z?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading diff..."]}):ge?t.jsxs(t.Fragment,{children:[(ye.body||ye.message)&&t.jsx("div",{className:"gm-commit-message-full",children:ye.body||ye.message}),ge.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ge.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ge.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},ye.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(Df,{size:14}),"Recent commits on ",F]})}),M?t.jsxs("div",{className:"gm-loading",children:[t.jsx(xt,{size:14,className:"spin"}),"Loading commits..."]}):L?t.jsxs("div",{className:"gm-error",children:[t.jsx(Ps,{size:14}),L]}):ee.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:ee.map(ye=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ce(ye.hash,"remote"),role:"button",tabIndex:0,onKeyDown:Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),ce(ye.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:ye.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:ye.message,children:ye.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:ye.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:rr(ye.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:X===ye.hash?t.jsx(cn,{size:14}):t.jsx(Un,{size:14})})]}),X===ye.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:O?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(xt,{size:16,className:"spin"}),"Loading diff..."]}):se?t.jsxs(t.Fragment,{children:[(ye.body||ye.message)&&t.jsx("div",{className:"gm-commit-message-full",children:ye.body||ye.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"})})]},ye.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 Ba={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function W4(e,n){return e&&n?`${e}/${n}`:""}function K4(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 Kp(e){switch(e){case"file-text":return na;case"check-circle":return Gn;case"shield":return iw;case"zap":return us;case"eye":return ur;case"globe":return Pl;case"layout-grid":return sa;case"puzzle":return By;default:return Gn}}function Gp(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 G4({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState({}),[m,h]=i.useState(!0),[f,p]=i.useState(!0),[g,x]=i.useState("my-steps"),[v,b]=i.useState(null),[y,S]=i.useState(!1),[N,E]=i.useState(!1),[w,j]=i.useState(Ba),[_,D]=i.useState(!1),[C,P]=i.useState(!1),[I,H]=i.useState(null),[A,$]=i.useState(null),[F,G]=i.useState({}),[ee,J]=i.useState([]),M=i.useRef(null);Ti(M,e,"fusion:workflow-steps-modal-size");const T=i.useCallback(async()=>{try{h(!0);const B=await fo(a);o(B)}catch(B){s(Me(B)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),L=i.useCallback(async()=>{try{const B=await eo(a);G(B||{})}catch{}},[a]),k=i.useCallback(async()=>{try{const B=await $s();J(B.models||[])}catch{}},[]),K=i.useCallback(async()=>{try{p(!0);const[B,O]=await Promise.all([Qj(),Xj()]);c(B.templates);const ke=Object.fromEntries(O.templates.map(({pluginId:ae,template:te})=>[te.id,ae]));u(ke)}catch(B){s(Me(B)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(T(),K(),L(),k())},[e,T,K,L,k]);const oe=i.useCallback(()=>{E(!0),S(!1),b(null),j(Ba)},[]),le=i.useCallback(()=>{E(!1),S(!0),b(null),j(Ba)},[]),we=i.useCallback(B=>{b(B.id),S(!1),j({name:B.name,description:B.description,mode:B.mode||"prompt",phase:B.phase||"pre-merge",prompt:B.prompt,scriptName:B.scriptName||"",enabled:B.enabled,defaultOn:B.defaultOn||!1,modelProvider:B.modelProvider||"",modelId:B.modelId||""})},[]),ge=i.useCallback(()=>{b(null),S(!1),E(!1),j(Ba)},[]),Ue=i.useCallback(async()=>{if(!w.name.trim()||!w.description.trim()){s("Name and description are required","error");return}D(!0);try{const B=w.mode==="prompt"&&w.modelProvider&&w.modelId?{modelProvider:w.modelProvider,modelId:w.modelId}:w.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(y){const O={name:w.name.trim(),description:w.description.trim(),mode:w.mode,phase:w.phase,prompt:w.mode==="prompt"&&w.prompt.trim()||void 0,scriptName:w.mode==="script"?w.scriptName.trim():void 0,enabled:w.enabled,defaultOn:w.defaultOn||void 0,...B};await em(O,a),s("Workflow step created","success")}else v&&(await Gj(v,{name:w.name.trim(),description:w.description.trim(),mode:w.mode,phase:w.phase,prompt:w.mode==="prompt"?w.prompt:"",scriptName:w.mode==="script"?w.scriptName.trim():void 0,enabled:w.enabled,defaultOn:w.defaultOn,...B},a),s("Workflow step updated","success"));S(!1),b(null),j(Ba),await T()}catch(B){s(Me(B)||"Failed to save workflow step","error")}finally{D(!1)}},[w,y,v,s,T]),Z=i.useCallback(async B=>{try{await Jj(B,a),s("Workflow step deleted","success"),H(null),v===B&&(b(null),j(Ba)),await T()}catch(O){s(Me(O)||"Failed to delete workflow step","error")}},[v,s,T]),Q=i.useCallback(async()=>{if(!(!v&&!y)&&w.mode==="prompt"){if(y){if(!w.name.trim()||!w.description.trim()){s("Name and description are required before refining","error");return}D(!0);try{const B=w.modelProvider&&w.modelId?{modelProvider:w.modelProvider,modelId:w.modelId}:{},O={name:w.name.trim(),description:w.description.trim(),mode:"prompt",prompt:w.prompt.trim()||void 0,enabled:w.enabled,defaultOn:w.defaultOn||void 0,...B},ke=await em(O,a);S(!1),b(ke.id),P(!0);const ae=await tm(ke.id,a);j(te=>({...te,prompt:ae.prompt})),s("Prompt refined with AI","success"),await T()}catch(B){s(Me(B)||"Failed to refine prompt","error")}finally{D(!1),P(!1)}return}if(v){P(!0);try{const B=await tm(v,a);j(O=>({...O,prompt:B.prompt})),s("Prompt refined with AI","success"),await T()}catch(B){s(Me(B)||"Failed to refine prompt","error")}finally{P(!1)}}}},[v,y,w,s,T]),X=i.useCallback(async B=>{$(B.id);try{await Zj(B.id,a),s(`Added ${B.name} workflow step`,"success"),await T(),x("my-steps"),E(!1)}catch(O){const ke=Me(O);ke?.includes("already exists")?s(`A workflow step named '${B.name}' already exists`,"error"):s(ke||"Failed to add workflow step from template","error")}finally{$(null)}},[s,T]),ie=Ui(n);if(!e)return null;const se=y||v!==null;return t.jsx("div",{className:"modal-overlay open",...ie,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:M,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:m?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!se&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>x("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Vx,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>x("templates"),"data-testid":"tab-templates",children:[t.jsx(sa,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!se&&!N&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(B=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${B.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:B.name}),t.jsx("span",{className:`wfm-badge ${B.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:B.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(B.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(B.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(B.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(B.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),B.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:B.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>we(B),title:"Edit","aria-label":`Edit ${B.name}`,children:t.jsx(Ss,{size:14})}),I===B.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>Z(B.id),title:"Confirm delete","aria-label":`Confirm delete ${B.name}`,children:t.jsx(os,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>H(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(nn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>H(B.id),title:"Delete","aria-label":`Delete ${B.name}`,children:t.jsx(En,{size:14})})]})]})},B.id))})]}),g==="templates"&&!se&&!N&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(xt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(B=>{const O=Kp(B.icon),ke=Gp(B.category),ae=A===B.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${B.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(O,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:B.name}),t.jsx("span",{className:ke,children:B.category}),d[B.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[B.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:B.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>X(B),disabled:ae,"data-testid":`add-template-${B.id}`,children:ae?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(_n,{size:12}),"Add"]})})]})]})},B.id)})})}),N&&!se&&t.jsxs("div",{className:"wfm-create-chooser","data-testid":"workflow-step-create-chooser",children:[t.jsx("h3",{className:"wfm-form-title",children:"How would you like to create this workflow step?"}),t.jsx("p",{className:"wfm-create-chooser-hint",children:"Start from a built-in template or create a fully custom workflow step."}),t.jsxs("button",{className:"btn wfm-create-custom-btn",onClick:le,"data-testid":"create-custom-step",children:[t.jsx(_n,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(xt,{size:24,className:"spin wfm-spinner"}),"Loading built-in templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"create-chooser-no-templates",children:"No built-in templates are available right now. You can still create a custom step."}):t.jsx("div",{className:"wfm-template-list","data-testid":"create-chooser-templates",children:l.map(B=>{const O=Kp(B.icon),ke=Gp(B.category),ae=A===B.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${B.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(O,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:B.name}),t.jsx("span",{className:ke,children:B.category}),d[B.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[B.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:B.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>X(B),disabled:ae,"data-testid":`chooser-add-template-${B.id}`,children:ae?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(_n,{size:12}),"Add template"]})})]})]})},B.id)})})]}),se&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:y?"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:w.name,onChange:B=>j(O=>({...O,name:B.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:w.description,onChange:B=>j(O=>({...O,description:B.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${w.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Oi,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${w.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Fi,{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 ${w.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${w.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>j(B=>({...B,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:w.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),w.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:Q,disabled:!w.description.trim()||C,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[C?t.jsx(xt,{size:12,className:"spin"}):t.jsx(bs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:w.prompt,onChange:B=>j(O=>({...O,prompt:B.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),w.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"}),w.modelProvider&&w.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>j(B=>({...B,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(nn,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:w.modelProvider&&w.modelId?`Using ${w.modelProvider}/${w.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(ks,{models:ee,value:W4(w.modelProvider,w.modelId),onChange:B=>{const O=K4(B);j(ke=>({...ke,modelProvider:O.provider,modelId:O.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),w.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(F).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:w.scriptName,onChange:B=>j(O=>({...O,scriptName:B.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(F).map(([B,O])=>t.jsxs("option",{value:B,children:[B," (",O,")"]},B))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:w.enabled,onChange:B=>j(O=>({...O,enabled:B.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:w.defaultOn,onChange:B=>j(O=>({...O,defaultOn:B.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:ge,disabled:_,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Ue,disabled:_||!w.name.trim()||!w.description.trim()||w.mode==="script"&&!w.scriptName.trim(),"data-testid":"save-workflow-step",children:_?"Saving...":y?"Create":"Save"})]})]})]})]})}),!se&&!N&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:oe,"data-testid":"add-workflow-step",children:[t.jsx(_n,{size:14}),"Add Workflow Step"]})})]})})}const J4=36e5,Y4=3e5,nd=[{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 Q4(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 X4(e){return typeof e!="number"||!Number.isFinite(e)?J4:Math.max(Y4,Math.round(e))}function pz(e){if(nd.some(s=>s.value===e))return[...nd];const n={value:e,label:`${Q4(e)} (custom)`};return[...nd,n].sort((s,a)=>s.value-a.value)}const Z4=4,e$=5*6e4;function t$(e){const n=X4(e?.heartbeatIntervalMs);return Math.max(n*Z4,e$)}function Jp(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),a=n%60;return s>0&&a>0?`${s}h ${a}m`:s>0?`${s}h`:`${a}m`}function n$(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 s$(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=n$(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Ws,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(di,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ws,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(di,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(zn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=new Date(s).getTime(),u=Date.now()-d,m=t$(o);if(u>m){const h=`No heartbeat for ${Jp(u)} (threshold: ${Jp(m)})`;return{label:"Unresponsive",icon:t.jsx(Ws,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:h}}return{label:"Healthy",icon:t.jsx(ny,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function Hd({agent:e,size:n=36,className:s}){const[a,r]=i.useState(!1);i.useEffect(()=>{r(!1)},[e.imageUrl]);const o=i.useMemo(()=>{if(!e.imageUrl)return;const l=encodeURIComponent(e.updatedAt??""),c=e.imageUrl.includes("?")?"&":"?";return`${e.imageUrl}${c}t=${l}`},[e.imageUrl,e.updatedAt]);return t.jsx("span",{className:`agent-avatar${s?` ${s}`:""}`,style:{width:`${n}px`,height:`${n}px`},"aria-label":`${e.name} avatar`,children:o&&!a?t.jsx("img",{src:o,alt:`${e.name} avatar`,onError:()=>r(!0)}):e.icon?.trim()?t.jsx("span",{className:"agent-avatar-emoji",style:{fontSize:`calc(${n}px * 0.58)`},"aria-hidden":"true",children:e.icon}):t.jsx(zn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const i$="https://github.com/Runfusion/Fusion/issues/new";function a$(e,n){const s=`[Agent Error] ${n.surface}${n.agentName?` - ${n.agentName}`:""}`,a=["## Agent Error Report","",`- Surface: ${n.surface}`,`- Agent ID: ${n.agentId??"unknown"}`,`- Agent Name: ${n.agentName??"unknown"}`,`- Agent State: ${n.agentState??"unknown"}`,`- Run ID: ${n.runId??"n/a"}`,`- Task ID: ${n.taskId??"n/a"}`,`- Timestamp: ${n.timestamp??new Date().toISOString()}`,"","## Error","```text",e,"```"],r=new URLSearchParams({title:s,body:a.join(`
|
|
693
|
-
`)});return`${i$}?${r.toString()}`}function r$({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>a$(s,a),[s,a]);return e?t.jsx("div",{className:"modal-overlay open",onClick:c=>c.target===c.currentTarget&&n(),role:"dialog","aria-modal":"true","aria-label":"Agent error details",children:t.jsxs("div",{className:"modal agent-error-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Ps,{size:16}),"Agent Error Details"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"agent-error-modal__content",children:t.jsx("pre",{className:"agent-error-modal__error",children:s})}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>{navigator.clipboard.writeText(s).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},"aria-label":r?"Copied error to clipboard":"Copy error to clipboard",children:[r?t.jsx(os,{size:14}):t.jsx(ta,{size:14}),r?"Copied":"Copy"]}),t.jsxs("a",{className:"btn btn-sm btn-warning",href:l,target:"_blank",rel:"noreferrer",onClick:c=>{c.preventDefault(),window.open(l,"_blank","noopener,noreferrer")},children:[t.jsx(Af,{size:14}),"Report on GitHub"]})]})]})}):null}function o$({errorText:e,issueContext:n,summaryPrefix:s="Error"}){const[a,r]=i.useState(!1);return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"agent-error-indicator",onClick:()=>r(!0),"aria-label":"Open error details",children:[t.jsx(Ps,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(r$,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const Qo=[{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 l$({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(""),[f,p]=i.useState("custom"),[g,x]=i.useState("all"),[v,b]=i.useState(()=>{if(typeof window>"u")return"list";const L=ss("fn-agent-view",a);return L==="board"||L==="list"?L:"list"});i.useEffect(()=>{const L=ss("fn-agent-view",a);if(L==="board"||L==="list"){b(L);return}b("list")},[a]),i.useEffect(()=>{xs("fn-agent-view",v,a)},[a,v]);const[y,S]=i.useState(null),N=i.useRef(null),[E,w]=i.useState(new Set),[j,_]=i.useState(new Map),{confirm:D}=Ys(),C=i.useMemo(()=>j.size===0?r:r.map(L=>{const k=j.get(L.id);return k?{...L,state:k}:L}),[r,j]),P=i.useMemo(()=>g!=="all"?C:[...C].sort((L,k)=>{const K=L.state==="paused"?1:0,oe=k.state==="paused"?1:0;return K!==oe?K-oe:(k.updatedAt??"").localeCompare(L.updatedAt??"")}),[C,g]),I=i.useCallback(async()=>{c(!0);try{const k=await Na(g!=="all"?{state:g}:void 0,a);o(k)}catch(L){s(`Failed to load agents: ${Me(L)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&I()},[e,I]),i.useEffect(()=>{if(!e)return;const L=setInterval(()=>{I()},3e4);return()=>{clearInterval(L)}},[e,I]);const H=async()=>{if(m.trim())try{await lN({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),I()}catch(L){s(`Failed to create agent: ${Me(L)}`,"error")}},A=async(L,k)=>{if(!E.has(L)){w(K=>new Set(K).add(L)),_(K=>{const oe=new Map(K);return oe.set(L,k),oe});try{await dN(L,k,a),s(`Agent state updated to ${k}`,"success"),await I(),_(K=>{const oe=new Map(K);return oe.delete(L),oe})}catch(K){_(oe=>{const le=new Map(oe);return le.delete(L),le}),s(`Failed to update state: ${Me(K)}`,"error")}finally{w(K=>{const oe=new Set(K);return oe.delete(L),oe})}}},$=async(L,k)=>{if(await D({title:"Delete Agent",message:`Delete agent "${k}"? This cannot be undone.`,danger:!0}))try{await uN(L,a),s(`Agent "${k}" deleted`,"success"),I()}catch(oe){s(`Failed to delete agent: ${Me(oe)}`,"error")}},F=async(L,k)=>{const K=r.find(oe=>oe.id===L);if(K){if(K.role===k){S(null);return}try{await cN(L,{role:k},a),s(`Agent role updated to ${Qo.find(oe=>oe.value===k)?.label??k}`,"success"),S(null),I()}catch(oe){s(`Failed to update role: ${Me(oe)}`,"error")}}},G=(L,k)=>{L.key==="Escape"&&S(null)},ee=L=>Qo.find(k=>k.value===L)?.label??L,J=L=>s$(L),M=L=>L.color==="var(--state-active-text)"?"active":L.color==="var(--state-paused-text)"?"paused":L.color==="var(--state-error-text)"?"error":"muted",T=(L,k)=>L.state==="error"?{title:void 0,label:"Error"}:{title:k.reason??k.label,label:k.stateDerived?null:k.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:L=>L.target===L.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(zn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(sa,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(gd,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void I(),title:"Refresh",disabled:l,children:t.jsx(hs,{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(ll,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:L=>x(L.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.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>u(!d),children:[t.jsx(_n,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:L=>h(L.target.value),onKeyDown:L=>L.key==="Enter"&&H(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:L=>p(L.target.value),children:Qo.map(L=>t.jsxs("option",{value:L.value,children:[L.icon," ",L.label]},L.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void H(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:P.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(zn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?P.map(L=>{const k=J(L),K=T(L,k),oe=M(k);return t.jsxs("div",{className:"agent-board-card","data-state":L.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(Hd,{agent:L,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":L.state,children:L.state}),t.jsx("span",{className:"agent-board-health","data-health":oe,title:K.title,children:k.icon})]}),t.jsx("div",{className:"agent-board-name",title:L.name,children:L.name}),t.jsx("div",{className:"agent-board-id",children:L.id}),t.jsxs("div",{className:"agent-board-actions",children:[L.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"active"),disabled:E.has(L.id),title:"Activate",children:t.jsx(ls,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(L.id,L.name),title:"Delete",children:t.jsx(En,{size:14})})]}),L.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Pause",children:t.jsx(di,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Stop",children:t.jsx(Si,{size:14})})]}),L.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"active"),disabled:E.has(L.id),title:"Resume",children:t.jsx(ls,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(L.id,L.name),title:"Delete",children:t.jsx(En,{size:14})})]}),L.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Pause",children:t.jsx(di,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Stop",children:t.jsx(Si,{size:14})})]}),L.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"active"),disabled:E.has(L.id),title:"Retry",children:t.jsx(ls,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Stop",children:t.jsx(Si,{size:14})})]})]})]},L.id)}):P.map(L=>{const k=J(L),K=T(L,k),oe=M(k);return t.jsxs("div",{className:"agent-card","data-state":L.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===L.id?t.jsx("select",{ref:N,className:"select agent-role-select",value:L.role,onChange:le=>void F(L.id,le.target.value),onKeyDown:le=>G(le,L.id),onBlur:()=>S(null),autoFocus:!0,children:Qo.map(le=>t.jsxs("option",{value:le.value,children:[le.icon," ",le.label]},le.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S(L.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:le=>{(le.key==="Enter"||le.key===" ")&&S(L.id)},children:t.jsx(Hd,{agent:L,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:L.name}),t.jsx("span",{className:"agent-id text-secondary",children:L.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":L.state,children:L.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":oe,title:K.title,children:[k.icon,K.label?` ${K.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:ee(L.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[L.state==="error"&&L.lastError?t.jsx(o$,{errorText:L.lastError,issueContext:{surface:"AgentListModal list",agentId:L.id,agentName:L.name,agentState:L.state,taskId:L.taskId}}):null,L.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:L.taskId})]}),L.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(L.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[L.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"active"),disabled:E.has(L.id),title:"Activate",children:[t.jsx(ls,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(L.id,L.name),title:"Delete",children:[t.jsx(En,{size:14})," Delete"]})]}),L.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Pause",children:[t.jsx(di,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]}),L.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"active"),disabled:E.has(L.id),title:"Resume",children:[t.jsx(ls,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(L.id,L.name),title:"Delete",children:[t.jsx(En,{size:14})," Delete"]})]}),L.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Pause",children:[t.jsx(di,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]}),L.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A(L.id,"active"),disabled:E.has(L.id),title:"Retry",children:[t.jsx(ls,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A(L.id,"paused"),disabled:E.has(L.id),title:"Stop",children:[t.jsx(Si,{size:14})," Stop"]})]})]})]},L.id)})})]})]})}):null}function c$({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await yk();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await Sk(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(xt,{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(Jn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(d$,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(Yp,{status:a,authenticated:e}),c&&t.jsx(Qp,{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(Jn,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),x,t.jsx(Yp,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Qp,{action:c})]})}function d$({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&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 Yp({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(xt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?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 Qp({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 u$({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!0);i.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const d=i.useCallback(async()=>{const x=await Nk();return c.current&&r(x),x},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async x=>{l(x?"enabling":"disabling");try{const v=await Ek(x);n?.(v.enabled),await d()}finally{c.current&&l(null)}},[n,d]),m=i.useCallback(async()=>{l("testing");try{await d()}finally{c.current&&l(null)}},[d]),h=a?.enabled??e,f=a?.server.available??!1,p=a?a.server.available?`Server reachable at ${a.server.url}`:`Server unavailable: ${a.server.reason??"not reachable"}`:"Probing llama.cpp server…",g=t.jsxs("div",{className:"auth-provider-cli-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void m(),disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),h?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!f,children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli llama-cpp-provider-card llama-cpp-provider-card--compact${h?" auth-provider-card--authenticated":""}`,"data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Jn,{provider:"llama-cpp",size:"sm"}),t.jsx("strong",{children:"llama.cpp — via HTTP server"})]}),g]}),t.jsx("small",{className:`auth-hint llama-cpp-status${a?.ready?" llama-cpp-status--ok":""}`,children:p})]}):t.jsxs("div",{className:"onboarding-provider-card llama-cpp-provider-card llama-cpp-provider-card--full","data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Jn,{provider:"llama-cpp",size:"md"}),t.jsx("strong",{children:"llama.cpp — via HTTP server"})]}),t.jsx("small",{className:`llama-cpp-status${a?.ready?" llama-cpp-status--ok":""}`,children:p}),g]})}function m$(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"),a=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(a);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function sd({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=m$(e),o=i.useRef(null),l=i.useCallback(()=>{a(!0),setTimeout(()=>a(!1),2e3)},[]),c=i.useCallback(async()=>{const d=r??e;try{await navigator.clipboard.writeText(d),l()}catch{}},[r,e,l]);return i.useEffect(()=>{const d=o.current===null&&r!==null;if(o.current=r,!d)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((d,u,m)=>t.jsxs("span",{children:[d,u<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(os,{size:12}):t.jsx(ta,{size:12})})]})]},u))}):e})}function h$({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){return t.jsxs("div",{className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{className:"form-input oauth-manual-code__input",value:e,onChange:u=>n(u.target.value),placeholder:r,rows:3,spellCheck:!1,disabled:l}),t.jsx("div",{className:"oauth-manual-code__actions",children:t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:l,children:c})}),o&&t.jsx("p",{className:"oauth-manual-code__help",children:o})]})}const p$=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"]),f$=/^[a-z][a-z0-9-]*$/,Xp=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function Zp(){return{id:"",name:"",reasoning:!1}}function g$({initialConfig:e,onSave:n,onCancel:s,saving:a=!1,error:r}){const o=!!e,[l,c]=i.useState(e?.id??""),[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.baseUrl??""),[f,p]=i.useState(e?.api??"openai-completions"),[g,x]=i.useState(e?.apiKey??""),[v,b]=i.useState(e?.models?.length?e.models:[Zp()]),[y,S]=i.useState(null),N=v.length>1,E=i.useMemo(()=>y??r??null,[y,r]);function w(C,P){b(I=>I.map((H,A)=>A===C?{...H,...P}:H))}function j(C){b(P=>P.length<=1?P:P.filter((I,H)=>H!==C))}function _(){if(!l.trim())return"Provider ID is required.";if(!f$.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&p$.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const C=new URL(m.trim());if(C.protocol!=="http:"&&C.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return Xp.includes(f)?v.length===0?"At least one model is required.":v.some(C=>!C.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function D(C){C.preventDefault();const P=_();S(P),!P&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(I=>({id:I.id.trim(),name:I.name?.trim()||void 0,reasoning:!!I.reasoning,contextWindow:I.contextWindow,maxTokens:I.maxTokens}))})}return t.jsxs("form",{onSubmit:D,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:C=>c(C.target.value),disabled:o||a})]}),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:d,onChange:C=>u(C.target.value),disabled:a})]}),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:C=>h(C.target.value),disabled:a})]}),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:C=>p(C.target.value),disabled:a,children:Xp.map(C=>t.jsx("option",{value:C,children:C},C))})]}),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:C=>x(C.target.value),disabled:a})]}),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((C,P)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${P+1}`,placeholder:"Model ID",value:C.id,onChange:I=>w(P,{id:I.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${P+1}`,placeholder:"Display name",value:C.name??"",onChange:I=>w(P,{name:I.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!C.reasoning,onChange:I=>w(P,{reasoning:I.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${P+1}`,placeholder:"Context window",type:"number",value:C.contextWindow??"",onChange:I=>w(P,{contextWindow:I.target.value?Number(I.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${P+1}`,placeholder:"Max tokens",type:"number",value:C.maxTokens??"",onChange:I=>w(P,{maxTokens:I.target.value?Number(I.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>j(P),disabled:a||!N,"aria-label":`Remove model ${P+1}`,children:"×"})]},`${P}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(C=>[...C,Zp()]),disabled:a,children:"+ Add model"})]}),E?t.jsx("div",{className:"form-error",children:E}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:a,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:a,children:a?"Saving...":"Save Provider"})]})]})}const b$=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function x$(e){return!b$.has(e)}function ef(e){return e.filter(n=>x$(n.id))}const wa="fusion_model_onboarding_state",or=[],lr=[],Cl=!1,El=!1,cr={},v$=void 0,Qi=["ai-setup","github","project-setup","first-task"],y$={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Gs(){if(typeof window>"u")return null;try{const e=localStorage.getItem(wa);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?w$(n):null}catch{return null}}function w$(e){const n=e.postOnboardingDismissedAt??v$;return{...e,completedSteps:e.completedSteps??or,skippedSteps:e.skippedSteps??lr,dismissed:e.dismissed??Cl,completed:e.completed??El,stepData:e.stepData??cr,...n?{postOnboardingDismissedAt:n}:{}}}function Xo(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:or,skippedSteps:lr,dismissed:Cl,completed:El,stepData:cr};try{localStorage.setItem(wa,JSON.stringify(s))}catch{}return}try{const s=Gs(),a=new Date().toISOString(),r=n.completed??El;let o=n.dismissed??Cl;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??or,c=n.skippedSteps??s?.skippedSteps??lr,d={...s?.stepData??cr};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(d[m]={...d[m]??{},...h});const u={currentStep:e,updatedAt:a,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:d};localStorage.setItem(wa,JSON.stringify(u))}catch{}}}function k$(e){if(!(typeof window>"u"))try{const n=Gs(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:or,skippedSteps:[e],dismissed:Cl,completed:El,stepData:cr};localStorage.setItem(wa,JSON.stringify(o));return}const a=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:a,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(wa,JSON.stringify(r))}catch{}}function tf(){if(!(typeof window>"u"))try{const e=Gs(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:or,skippedSteps:lr,dismissed:!1,completed:!0,stepData:cr};localStorage.setItem(wa,JSON.stringify(s))}catch{}}function dr(){const e=Gs();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function j$(){if(!(typeof window>"u"))try{const e=Gs(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:or,skippedSteps:lr,dismissed:!1,completed:!1,stepData:cr,postOnboardingDismissedAt:n};localStorage.setItem(wa,JSON.stringify(s))}catch{}}function lx(){const e=Gs();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function N$(){const e=Gs();return!e||dr()?!1:e.currentStep!=="complete"}function S$(){const e=Gs();if(!e||dr()||e.currentStep==="complete")return null;const n=e.currentStep,s=y$[n]??_$(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function C$(){const e=Gs();return e?e.skippedSteps:lr}function E$(e){const n=Gs();return!n||!n.stepData?null:n.stepData[e]??null}function _$(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const cx="fusion_onboarding_events",nf="fusion_onboarding_session_id",M$=200,A$=50;function ti(e,n={}){if(!(typeof window>"u"))try{const s=T$(),a=$$(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:P$()},o=I$([...s,r]);R$(o)}catch{}}function P$(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(nf);if(e)return e;const n=sf();return sessionStorage.setItem(nf,n),n}catch{return sf()}}function sf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function T$(){try{const e=localStorage.getItem(cx);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(D$):[]}catch{return[]}}function R$(e){try{localStorage.setItem(cx,JSON.stringify(e))}catch{}}function I$(e){const n=[...e];for(;n.length>M$;)n.splice(0,A$);return n}function $$(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function D$(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 L$=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}))??[]}),O$={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"}}},dx={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:"..."}},F$={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},af={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 qd(e){if(af[e])return af[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 id=["anthropic","openai","google","gemini","ollama"],z$=["anthropic","claude-cli","droid-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],U$={anthropic:"anthropic","claude-cli":"claude-cli","droid-cli":"droid-cli","llama-cpp":"llama-cpp","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},B$={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Vd(e){return U$[e]??e}function rf(e){const n=Vd(e),s=z$.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function of(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=rf(e.id),a=rf(n.id);if(s!==a)return s-a;const r=Vd(e.id),o=Vd(n.id);if(r!==o)return r.localeCompare(o);const l=B$[r];if(l){const d=l.indexOf(e.id),u=l.indexOf(n.id);if(d!==u)return(d===-1?Number.POSITIVE_INFINITY:d)-(u===-1?Number.POSITIVE_INFINITY:u)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function H$(e,n){const s=n.trim();if(!s)return"API key is required";const a=dx[e]??F$;return a.pattern.test(s)?null:`${qd(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const ux={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"},q$={description:"AI provider — connect to start using AI models",apiKeyInfo:ux};function Wd(e){return O$[e]??q$}function V$(e){return Wd(e.id).apiKeyInfo??ux}function W$({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 a=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:a}),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 K$({provider:e,apiKeyInfo:n,inputValue:s,isSaving:a,error:r,success:o,isConnected:l,onInputChange:c,onSave:d,onClear:u}){const m=`onboarding-apikey-input-${e.id}`,h=a||!s.trim(),f=dx[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:()=>u(e.id),disabled:a,children:a?"Removing…":"Remove Key"}),t.jsx(ni,{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:x=>c(e.id,x.target.value),onKeyDown:x=>{x.key==="Enter"&&d(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>d(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:a?"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(ni,{summary:"Advanced setup details",children:g})]})}const G$=150;function J$({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=Gs(),u=d?.currentStep,m=u==="complete"?"ai-setup":Qi.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??C$(),[p,g]=i.useState(!0),[x,v]=i.useState(m),[b,y]=i.useState(h),[S,N]=i.useState(f),[E,w]=i.useState(!1),[j,_]=i.useState(""),[D,C]=i.useState(!1),[P,I]=i.useState(null),[H,A]=i.useState(null),[$,F]=i.useState([]),[G,ee]=i.useState(void 0),[J,M]=i.useState(!0),[T,L]=i.useState(null),[k,K]=i.useState({}),[oe,le]=i.useState({}),[we,ge]=i.useState({}),[Ue,Z]=i.useState(null),[Q,X]=i.useState([]),[ie,se]=i.useState(""),[B,O]=i.useState(!1),[ke,ae]=i.useState({}),[te,Ie]=i.useState({}),[Oe,He]=i.useState({}),[$e,Te]=i.useState([]),[ue,ce]=i.useState(!1),[Ae,Ne]=i.useState(!1),[ye,Ce]=i.useState(),fe=i.useRef({}),Pe=i.useRef(null),De=i.useRef(null),dt=i.useRef(null),[pt,lt]=i.useState({}),[vt,_e]=i.useState(()=>Gs()?.stepData?.github?.skipped===!0),Fe=i.useRef(0),bt=i.useRef(l),ht=i.useRef(!1),Ee=d?.currentStep,me=!!d&&d.currentStep!=="complete";Ti(De,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const W=Pe.current;W&&(W.scrollTop=0)},[x]);const[Re,be]=i.useState(()=>Gs()?.stepData?.["ai-setup"]?.skippedProviders??{}),Ke=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],pe=Ke.findIndex(W=>W.key===x),Xe=x==="complete"?Ke.length:pe;i.useEffect(()=>{x!=="complete"&&Xo(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),i.useEffect(()=>{ht.current||(ht.current=!0,ti("onboarding:wizard-opened",{source:me?"resume":"initial",resumedFromStep:Ee}))},[me,Ee]),i.useEffect(()=>{const W=bt.current!=null,qe=l!=null;!W&&qe&&w(!0),qe||w(!1),bt.current=l},[l]);const wt=i.useRef(m);i.useEffect(()=>{if(wt.current==="ai-setup"&&x!=="ai-setup"&&!$.some(qe=>qe.id!=="github"&&qe.authenticated)){const qe={};for(const Je of $)Je.id!=="github"&&!Je.authenticated&&!Re[Je.id]&&(qe[Je.id]=!0);if(Object.keys(qe).length>0){const Je={...Re,...qe};be(Je),Xo(x,{stepData:{"ai-setup":{skippedProviders:Je}}})}}wt.current=x},[x,$,Re]);const gt=i.useCallback(async()=>{try{const{providers:W,ghCli:qe}=await Zr(),Je=ef(W);F(Je),ee(qe),K(ut=>{const Ct={};for(const[Mt,an]of Object.entries(ut)){const An=Je.find(Sn=>Sn.id===Mt);An&&!An.authenticated&&An.loginInProgress&&(Ct[Mt]=an)}return Object.keys(Ct).length===Object.keys(ut).length?ut:Ct}),lt(ut=>{let Ct=!1;const Mt={...ut};for(const[an,An]of Object.entries(ut)){if(An!=="pending")continue;Je.find(ps=>ps.id===an)?.loginInProgress||(delete Mt[an],Ct=!0)}return Ct?Mt:ut}),be(ut=>{const Ct={...ut};for(const Mt of Je)Mt.authenticated&&Ct[Mt.id]&&delete Ct[Mt.id];return Object.keys(Ct).length===Object.keys(ut).length?ut:Ct})}catch{}},[]),Tt=i.useCallback(async()=>{try{const W=await _k();Te((W.providers??[]).map(L$))}catch{}},[]),Zt=i.useCallback(async W=>{Ne(!0),Ce(void 0);try{await Ak(W),await Tt(),await $s().then(qe=>X(qe.models??[])),ce(!1)}catch(qe){Ce(Me(qe)||"Failed to create custom provider")}finally{Ne(!1)}},[Tt]),Ot=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&Tt(),Ot.current&>(),Ot.current=x!=="ai-setup"},[x,gt,Tt]),i.useEffect(()=>{if(!$.some(Je=>Je.loginInProgress))return;const qe=setInterval(()=>{gt()},2e3);return()=>clearInterval(qe)},[$,gt]);const Rt=$.find(W=>W.id==="github"),en=!!Rt,zt=Rt?.authenticated??!1,Qt=Rt?.loginInProgress??!1,xn=G?.authenticated??!1,Kt=zt||xn,Ut=!zt&&xn,fn=i.useCallback(W=>{if(W.authenticated)return"connected";const qe=pt?.[W.id];return qe==="timeout"||qe==="failed"?"retry":Re[W.id]?"skipped":"not-connected"},[pt,Re]);function un({status:W}){const qe={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:Je,className:ut}=qe[W];return t.jsx("span",{"data-testid":"provider-status-badge",className:ut,"data-status":W,children:Je})}const tn=i.useCallback(()=>{if(Kt)return"connected";const W=pt.github;return W==="pending"?"pending":W==="failed"||W==="timeout"?"failed":vt?"skipped":"not-connected"},[Kt,pt,vt]);function Vt({status:W}){const qe={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:Je,className:ut}=qe[W];return t.jsx("span",{"data-testid":"github-status-badge",className:ut,"data-status":W,children:Je})}const mn=i.useCallback(async()=>{try{const W=await $s();X(W.models)}catch{}},[]),xe=i.useCallback(async()=>{try{const W=await ja();if(W.defaultProvider&&W.defaultModelId){const qe=`${W.defaultProvider}/${W.defaultModelId}`;se(qe)}}catch{}},[]);i.useEffect(()=>{Promise.all([gt(),mn(),xe()]).finally(()=>M(!1))},[gt,mn,xe]),i.useEffect(()=>{const W=E$("ai-setup");if(W?.loginOutcomes){const qe=W.loginOutcomes,Je={};for(const[ut,Ct]of Object.entries(qe))Ct!=="pending"&&(Je[ut]=Ct);Object.keys(Je).length>0&<(Je)}},[]);const Le=i.useCallback((W,qe)=>{Xo(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[W]:qe}}}})},[x,b]);i.useEffect(()=>{const W=Object.entries(pt).filter(([qe,Je])=>Je!=="pending");for(const[qe,Je]of W)Le(qe,Je)},[pt,Le]),i.useEffect(()=>()=>{dt.current&&clearInterval(dt.current),Object.values(fe.current).forEach(clearTimeout),fe.current={}},[]);const Ve=i.useCallback(W=>{_e(W),Xo(x,{completedSteps:b,stepData:{github:{skipped:W}}})},[x,b]),at=i.useCallback(W=>W==="complete"?-1:Qi.indexOf(W),[]),Ge=i.useCallback(()=>{y(qe=>[...new Set([...qe,x])]),N(qe=>qe.filter(Je=>Je!==x)),ti("onboarding:step-completed",{step:x}),x==="github"&&!zt&&Ve(!1);const W=at(x);W>=0&&W<Qi.length-1&&v(Qi[W+1])},[x,zt,Ve,at]),Ft=i.useCallback(()=>{N(qe=>[...new Set([...qe,x])]),k$(x),ti("onboarding:step-skipped",{step:x}),x==="github"&&!zt&&Ve(!0);const W=at(x);W>=0&&W<Qi.length-1&&v(Qi[W+1])},[x,zt,Ve,at]),_t=i.useCallback(()=>{const W=x;y(Je=>Je.filter(ut=>ut!==W)),N(Je=>Je.filter(ut=>ut!==W)),W==="github"&&!zt&&Ve(!1);const qe=at(x);qe>0&&v(Qi[qe-1])},[x,zt,Ve,at]),qt=i.useCallback(()=>{Ft()},[Ft]),St=i.useCallback(async W=>{lt(Je=>{const ut=Je[W];if(ut&&ut!=="pending"){const{[W]:Ct,...Mt}=Je;return Mt}return Je});const qe=()=>{K(Je=>{if(!(W in Je))return Je;const ut={...Je};return delete ut[W],ut}),le(Je=>{if(!(W in Je))return Je;const ut={...Je};return delete ut[W],ut}),ge(Je=>{if(!(W in Je))return Je;const ut={...Je};return delete ut[W],ut})};qe(),lt(Je=>({...Je,[W]:"pending"})),L(W),Fe.current=0;try{const{url:Je,instructions:ut,manualCode:Ct}=await Pk(W);ut?.trim()&&K(Mt=>({...Mt,[W]:ut})),Ct&&le(Mt=>({...Mt,[W]:Ct})),window.open(_i(Je),"_blank"),dt.current=setInterval(async()=>{if(Fe.current++,Fe.current>=G$){dt.current&&(clearInterval(dt.current),dt.current=null),L(null),F(Mt=>Mt.map(an=>an.id===W?{...an,loginInProgress:!1}:an)),lt(Mt=>({...Mt,[W]:"timeout"})),qe(),n("Login timed out. Please try again.","warning");return}try{const{providers:Mt,ghCli:an}=await Zr(),An=ef(Mt);F(An),ee(an);const Sn=An.find(ps=>ps.id===W);if(Sn?.authenticated){dt.current&&(clearInterval(dt.current),dt.current=null),L(null),lt(ps=>({...ps,[W]:"success"})),qe(),W==="github"&&Ve(!1),n("Login successful","success");return}Sn?.loginInProgress||(dt.current&&(clearInterval(dt.current),dt.current=null),L(null),lt(ps=>({...ps,[W]:"failed"})),qe(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(Je){Je instanceof Error&&Je.message.includes("already in progress")||Je&&typeof Je=="object"&&"status"in Je&&Je.status===409?(n("Login already in progress. Cancel it to retry.","warning"),lt(Ct=>({...Ct,[W]:"pending"})),gt()):(n(Je instanceof Error?Je.message:"Login failed","error"),lt(Ct=>({...Ct,[W]:"failed"}))),L(null),qe()}},[n,gt,Ve]),z=i.useCallback(async W=>{const qe=we[W]?.trim();if(!qe){n("Paste the full redirect URL or authorization code first.","warning");return}Z(W);try{(await Tk(W,qe)).submitted?(ge(ut=>{if(!(W in ut))return ut;const Ct={...ut};return delete Ct[W],Ct}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(Je){n(Me(Je)||"Failed to submit authorization code","error")}finally{Z(null)}},[n,we]),he=i.useCallback(async W=>{dt.current&&(clearInterval(dt.current),dt.current=null),L(W),Fe.current=0,F(qe=>qe.map(Je=>Je.id===W?{...Je,loginInProgress:!1}:Je)),lt(qe=>({...qe,[W]:"cancelled"}));try{await Ik(W),await gt().catch(()=>{}),n("Login cancelled","success")}catch(qe){n(Me(qe)||"Failed to cancel login","error")}finally{L(null),K(qe=>{if(!(W in qe))return qe;const Je={...qe};return delete Je[W],Je}),le(qe=>{if(!(W in qe))return qe;const Je={...qe};return delete Je[W],Je}),ge(qe=>{if(!(W in qe))return qe;const Je={...qe};return delete Je[W],Je}),Z(qe=>qe===W?null:qe)}},[n,gt]),st=i.useCallback((W,qe)=>{ae(ut=>({...ut,[W]:qe}));const Je=fe.current[W];Je&&(clearTimeout(Je),delete fe.current[W]),Ie(ut=>{if(!ut[W])return ut;const Ct={...ut};return delete Ct[W],Ct}),He(ut=>{if(!ut[W])return ut;const Ct={...ut};return delete Ct[W],Ct})},[]),It=i.useCallback(()=>{const W=Pe.current;if(!W)return;const qe=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:qe?"auto":"smooth"});return}}catch{}W.scrollTop=0},[]),ve=i.useCallback(async(W,qe)=>{const Je=(qe??ke[W]??"").trim(),ut=H$(W,Je);if(ut){Ie(Mt=>({...Mt,[W]:ut}));return}const Ct=fe.current[W];Ct&&(clearTimeout(Ct),delete fe.current[W]),L(W),Ie(Mt=>{const an={...Mt};return delete an[W],an}),He(Mt=>{if(!Mt[W])return Mt;const an={...Mt};return delete an[W],an});try{await $k(W,Je),await gt(),It(),ae(Mt=>{const an={...Mt};return delete an[W],an}),Ie(Mt=>{if(!Mt[W])return Mt;const an={...Mt};return delete an[W],an}),He(Mt=>({...Mt,[W]:"✓ Key saved"})),fe.current[W]=setTimeout(()=>{He(Mt=>{if(!Mt[W])return Mt;const an={...Mt};return delete an[W],an}),delete fe.current[W]},3e3),n("API key saved","success")}catch(Mt){const an=Mt instanceof TypeError&&Mt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Mt instanceof Error?Mt.message:"Failed to save API key";Ie(An=>({...An,[W]:an})),He(An=>{if(!An[W])return An;const Sn={...An};return delete Sn[W],Sn}),n(an,"error")}finally{L(null)}},[ke,n,gt,It]),ot=i.useCallback(async W=>{L(W);try{await Dk(W),await gt(),n("API key removed","success")}catch(qe){n(qe instanceof Error?qe.message:"Failed to clear API key","error")}finally{L(null)}},[n,gt]),Nt=i.useCallback(async W=>{L(W);try{await Rk(W),await gt(),n("Logged out","success")}catch(qe){n(qe instanceof Error?qe.message:"Logout failed","error")}finally{L(null)}},[n,gt]),Lt=i.useCallback(W=>{se(W)},[]),$t=i.useCallback(async()=>{try{const W={modelOnboardingComplete:!0};if(ie){const qe=ie.indexOf("/"),Je=qe!==-1?ie.slice(0,qe):void 0,ut=qe!==-1?ie.slice(qe+1):ie,Ct=Q.find(Mt=>Mt.id===ut);Ct?(W.defaultProvider=Ct.provider,W.defaultModelId=Ct.id):Je&&ut&&(W.defaultProvider=Je,W.defaultModelId=ut)}await $n(W),tf()}catch{}},[ie,Q,$n,tf]),Wt=i.useCallback(async()=>{const W=[...new Set([...b,"first-task"])];O(!0);try{await $t(),ti("onboarding:completed",{completedSteps:W,skippedSteps:S}),y(W),N(qe=>qe.filter(Je=>Je!=="first-task")),v("complete")}finally{O(!1)}},[$t,b,S]),Gt=i.useCallback(async()=>{if(!s)return;const W=j.trim();if(!W){I("Please enter a task description.");return}I(null),C(!0);let qe=!1;try{const Je=await ml({description:W,source:{sourceType:"dashboard_ui"}},s);A(Je),w(!0),ti("onboarding:first-task-created",{taskId:Je?.id}),n("Task created","success"),qe=!0}catch(Je){const ut=Je instanceof Error?Je.message:"Something went wrong creating your task. Please try again.";I(ut),n(ut,"error")}finally{C(!1)}qe&&$t()},[s,j,n,$t]),sn=i.useCallback(async()=>{O(!0);try{await $t()}finally{O(!1)}ti("onboarding:open-new-task",{}),r?.()},[$t,r]),on=i.useCallback(async()=>{if(Kt){O(!0);try{await $t()}finally{O(!1)}g(!1),e(),ti("onboarding:open-github-import",{}),o?.()}},[$t,Kt,e,o]),Dn=i.useCallback(async()=>{ti("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),O(!0);try{await $n({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,S,e]),Jt=i.useCallback(()=>{ti("onboarding:finished",{}),g(!1),e()},[e]),Hn=i.useCallback(()=>{const W=l??H;W&&($t(),c?.(W),e())},[l,H,$t,c,e]),Yn=i.useCallback(()=>{$t(),e()},[$t,e]);if(!p)return null;const re=tn(),rt=$.filter(W=>W.id!=="github"),ct=[...rt].sort(of),ft=ct.some(W=>!W.type||W.type==="oauth"),it=ct.some(W=>W.type==="api_key"),Y=rt.filter(W=>W.authenticated),Ye=Y.length>0,Yt=!!s,In=x==="github"&&!Ye,cs=(()=>{if(!ie)return"";const W=ie.indexOf("/"),qe=W===-1?void 0:ie.slice(0,W),Je=W===-1?ie:ie.slice(W+1),ut=Q.find(Ct=>Ct.id===Je&&(!qe||Ct.provider===qe));return ut?.name?ut.name:qe?`${qd(qe)} ${Je}`:ie})(),gn=[];if(Yt?gn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):gn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Ye){const W=qd(Y[0]?.id??"");gn.push({label:"AI Provider",status:"connected",detail:`${W} connected — AI agents can work on tasks`})}else rt.length>0&&rt.some(W=>Re[W.id])?gn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):gn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Kt?gn.push({label:"GitHub",status:"connected",detail:Ut?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!en||vt?gn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):gn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),cs&&gn.push({label:"Default Model",status:"connected",detail:cs});const Nn=l??H,ms=Nn?.description?.split(`
|
|
694
|
-
`)[0]?.trim()||Nn?.title||"",vn=new Set(id),bn=ct.filter(W=>vn.has(W.id)).sort((W,qe)=>{const Je=id.indexOf(W.id),ut=id.indexOf(qe.id);return Je!==ut?Je-ut:of(W,qe)}),Pt=ct.filter(W=>W.authenticated&&!vn.has(W.id)),Qn=ct.filter(W=>!W.authenticated&&!vn.has(W.id)),es=W=>{const qe=pt[W.id]==="timeout"||pt[W.id]==="failed"||pt[W.id]==="cancelled",Je=W.loginInProgress&&!qe;if(W.id==="llama-cpp"&&W.type==="cli")return t.jsx(u$,{authenticated:W.authenticated,onToggled:()=>{gt()}},W.id);if(W.id==="claude-cli"&&W.type==="cli")return t.jsx(c$,{authenticated:W.authenticated,onToggled:()=>{gt()}},W.id);if(W.type==="api_key"){const ut=Wd(W.id),Ct=V$(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(Jn,{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(If,{size:14,className:"onboarding-provider-key-icon"}),W.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:ut.description}),t.jsx(un,{status:fn(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(K$,{provider:W,apiKeyInfo:Ct,inputValue:ke[W.id]??"",isSaving:T===W.id,error:te[W.id],success:Oe[W.id],isConnected:W.authenticated,onInputChange:st,onSave:ve,onClear:ot})})]},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(Jn,{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:Wd(W.id).description}),t.jsx(un,{status:fn(W)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:T===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 he(W.id),children:"Cancel"})]}):Je?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 he(W.id),children:"Cancel"})]}):W.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt(W.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>St(W.id),children:"Login"})}),(T===W.id||Je)&&k[W.id]&&t.jsx(sd,{instructions:k[W.id],"data-testid":`onboarding-login-instructions-${W.id}`}),(T===W.id||Je)&&oe[W.id]&&t.jsx(h$,{value:we[W.id]??"",onChange:ut=>ge(Ct=>({...Ct,[W.id]:ut})),onSubmit:()=>void z(W.id),prompt:oe[W.id].prompt,placeholder:oe[W.id].placeholder,helpText:oe[W.id].helpText,disabled:Ue===W.id,submitLabel:Ue===W.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${W.id}`}),pt[W.id]==="timeout"&&T!==W.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),pt[W.id]==="failed"&&T!==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:De,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(us,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(Vs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx($u,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx($u,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Gn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Dn,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(nn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Ke.map((W,qe)=>{const Je=Xe>qe,ut=b.includes(W.key)&&Je,Ct=S.includes(W.key)&&!b.includes(W.key)&&Je,Mt=ut||Ct;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[qe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${qe<=Xe?"done":""}`}),Mt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===W.key?"active":""} ${ut?"done":""} ${Ct?"skipped":""}`,onClick:()=>v(W.key),"aria-label":`Go back to ${W.label}`,title:`Review ${W.label}`,children:[t.jsx("span",{className:"step-number",children:ut?t.jsx(Gn,{size:14}):Ct?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):qe+1}),t.jsx("span",{className:"step-label",children:W.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===W.key?"active":""} ${ut?"done":""} ${Ct?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:ut?t.jsx(Gn,{size:14}):Ct?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):qe+1}),t.jsx("span",{className:"step-label",children:W.label})]})]},W.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Pe,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),t.jsx("p",{className:"onboarding-helper-text",children:"Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features."}),!J&&$.length>0&&(()=>{const W=$.filter(Mt=>Mt.id!=="github"&&Mt.authenticated).length,qe=$.filter(Mt=>Mt.id!=="github").length,Je=Object.keys(Re).filter(Mt=>!$.find(an=>an.id===Mt)?.authenticated).length;if(qe===0)return null;let ut="onboarding-provider-summary",Ct="";return W>0?(ut+=" onboarding-provider-summary--connected",Ct=`✓ ${W} of ${qe} provider${qe!==1?"s":""} connected`):Je>0?(ut+=" onboarding-provider-summary--skipped",Ct=`${Je} provider${Je!==1?"s":""} skipped`):(ut+=" onboarding-provider-summary--none",Ct="No providers connected yet"),t.jsx("div",{className:ut,"data-testid":"provider-summary",children:Ct})})(),t.jsx(Zi,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(ni,{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."})}),$.length>0&&!$.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."}),J?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(xt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):$.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.jsx(Zi,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{gt()}}}),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"}),bn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:bn.map(W=>es(W))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),Pt.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:Pt.map(W=>es(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(ni,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),Q.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(ks,{models:Q,value:ie,onChange:Lt,placeholder:"Select a default model…",label:"Default model"})}),ie&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Q.find(W=>W.id===ie)?.name??ie]})})]}),t.jsx(ni,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Qn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Qn.map(W=>es(W))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),$e.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:$e.map(W=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Jn,{provider:W.id,size:"sm"}),t.jsx("span",{children:W.name||W.id})]},W.id))}):null,ue?t.jsx(g$,{onSave:Zt,onCancel:()=>{ce(!1),Ce(void 0)},saving:Ae,error:ye}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ce(!0),children:"Add custom provider"})]})}),ft&&t.jsx(ni,{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."})}),it&&t.jsx(ni,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})}),t.jsx(Zi,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Kt?t.jsx("p",{className:"model-onboarding-description",children:Ut?"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."}),!Kt&&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"})]})}),In&&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(ni,{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."})}),en?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(Vs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Vt,{status:re})})]}),zt&&(T==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:"Disconnect"}))]}),(re==="not-connected"||re==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[T==="github"||Qt?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 he("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>St("github"),children:[t.jsx(Vs,{size:16}),"Connect"]}),(T==="github"||Qt)&&k.github&&t.jsx(sd,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]}),re==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Ut?"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."}),re==="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:()=>St("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:qt,children:"Skip for now"})]})]}),re==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),re==="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:()=>St("github"),children:"Connect anyway"})})]}),re==="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(Jn,{provider:"github",size:"lg"})}),Ut?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:Ut?"Continue with gh CLI auth →":"Continue without GitHub →"}),Ut&&(T==="github"||Qt?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(xt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>St("github"),children:[t.jsx(Jn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Ut&&(T==="github"||Qt)&&k.github&&t.jsx(sd,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),Yt?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:a,"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(ni,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),E&&Nn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Gn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:Nn.id}),ms&&t.jsx("p",{className:"onboarding-task-created__description",children:ms}),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:Hn,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Yn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Yt?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:j,onChange:W=>{_(W.target.value),I(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:Gt,disabled:D,"data-testid":"onboarding-first-task-submit",children:D?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),P&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:P}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(W$,{items:gn}),Yt&&t.jsxs(t.Fragment,{children:[t.jsx(ni,{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:sn,disabled:B,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(_n,{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${Kt?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:on,disabled:B||!Kt,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Vs,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!Kt&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Gn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Dn,disabled:B,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ft,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ge,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:_t,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ft,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:Ge,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:_t,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Ge,disabled:!Yt,children:"Next →"})]}),x==="first-task"&&!E&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:_t,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Wt,disabled:B,children:B?t.jsxs(t.Fragment,{children:[t.jsx(xt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Jt,children:[t.jsx(Gn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function mx({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 Y$=i.lazy(()=>Rn(()=>import("./SetupWizardModal-BtDMY9pa.js"),__vite__mapDeps([11,1,12,13,14,5,6,15])).then(e=>({default:e.SetupWizardModal}))),Q$=i.lazy(()=>Rn(()=>import("./SettingsModal-DR_yirvK.js"),__vite__mapDeps([16,1,17,18,19,2,5,6,20])).then(e=>({default:e.SettingsModal})));function X$(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Rn(()=>import("./SettingsModal-DR_yirvK.js"),__vite__mapDeps([16,1,17,18,19,2,5,6,20]))},{timeout:1500})}function Z$({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[x,v]=i.useState(null),b=c.detailTask?(()=>{const j=n.find(_=>_.id===c.detailTask?.id);return j?"prompt"in c.detailTask?{...c.detailTask,...j,prompt:c.detailTask.prompt,log:c.detailTask.log}:j:c.detailTask})():null,y=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),N=i.useCallback(()=>{c.openGitHubImport()},[c]),E=i.useCallback(j=>{v(null),c.closeModelOnboarding(),c.openDetailTask(j)},[c]),w=i.useCallback(async j=>{const _=await u.handleModalCreate(j);return c.modelOnboardingOpen&&v(_),_},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{X$()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(da,{children:t.jsx(MT,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,mobileHeaderMode:c.detailTaskOrigin==="list-mobile"?"back":"close",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(da,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Q$,{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(DR,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(da,{children:t.jsx(zR,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:u.handlePlanningTaskCreated,onTasksCreated:u.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(da,{children:t.jsx(YR,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(xI,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(yI,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(BI,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(WI,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(t4,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(P4,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(w4,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(da,{children:t.jsx(S4,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:w,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(D4,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:j=>{const _=n.find(D=>D.id===j);_&&c.openDetailTask(_)}}),t.jsx(da,{children:t.jsx(O4,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(da,{children:t.jsx(G4,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(l$,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(Y$,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(J$,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:N,firstCreatedTask:x,onViewTask:E}),t.jsx(mx,{toasts:o,onRemove:l})]})}function eD({errorMessage:e,isRetrying:n,onRetry:s,onManageConnection:a}){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.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"}),a&&t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Manage Connection"})]})]})}const Kd=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function tD(e,n){if(n==="ready")return"done";const s=Kd.findIndex(r=>r.id===n),a=Kd.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function nD({stage:e}){const[n]=i.useState(()=>Nw());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:Kd.map(s=>{const a=tD(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${a}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:a==="done"?"✓":a==="active"?t.jsx(xt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const sD=5e3;function iD(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function aD(e,n,s){let a=0,r=0,o=0,l=0,c=0;for(const d of e){switch(d.column){case"in-progress":a++,xl(d,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}d.blockedBy&&d.blockedBy.length>0&&r++}return{runningTaskCount:a,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function rD(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const v=await wN(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;u(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},sD),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=aD(e,s,a),g=iD(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const oD={planning:hi,subtask:ga,mission_interview:Ms,milestone_interview:Ms,slice_interview:Ms},lD={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function cD({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=Ys(),[l,c]=i.useState(!1),[d,u]=i.useState(new Set),m=i.useRef(null),h=i.useRef(new Map),f=i.useRef(null),{activeTabMap:p}=gr(),g=i.useMemo(()=>Ca(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const N=p.get(S.id),E=[S.status,S.updatedAt,N?.tabId??S.lockedByTab??"",N?.stale?"stale":"fresh"].join("|"),w=h.current.get(S.id);w&&w!==E&&b.add(S.id),y.set(S.id,E)}if(h.current=y,b.size!==0)return u(b),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{u(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const x=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(xt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(ud,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=oD[b.type],S=b.status==="generating",N=b.status==="awaiting_input",E=b.status==="error",w=p.get(b.id),j=w?.tabId??b.lockedByTab??null,_=!!(j&&j!==g&&!w?.stale),D=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${D?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:D?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:D?"translateY(-1px)":void 0},onClick:async()=>{_&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[E?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:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[E?"Failed":lD[b.type],S&&" — generating...",N&&!_&&" — needs input",N&&_&&" — active in another tab"]})]}),S&&t.jsx(xt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),N&&!_&&t.jsx(ud,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),N&&_&&t.jsx($l,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:C=>{C.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(nn,{size:12})})]},b.id)})})]})]})}function dD(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),a=n-s,r=Math.floor(a/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 uD(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:ls};case"paused":return{label:"Paused",color:"var(--triage)",icon:di};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:us}}}function mD({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:a,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:d,currentProjectPath:u,onOpenProjectDirectory:m,keyboardOpen:h}){if(h)return null;const{stats:f,loading:p,error:g}=rD(e,n,s,d),[x,v]=i.useState(!1),b=i.useMemo(()=>uD(f.executorState),[f.executorState]),y=i.useMemo(()=>dD(f.lastActivityAt),[f.lastActivityAt]),S=b.icon;return g?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(Ll,{size:14}),g]})}):p&&f.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 ${f.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[a&&a.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(cD,{sessions:a,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:f.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 ${f.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:f.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:f.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),f.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:f.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 ${f.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 ${f.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:f.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:f.inReviewCount})]}),u&&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${x?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>v(N=>!N),"aria-label":x?"Hide project directory":"Show project directory","aria-expanded":x,"data-testid":"executor-project-path-toggle",title:x?"Hide project directory":"Show project directory",children:t.jsx(vs,{size:12,"aria-hidden":"true"})}),x&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:u,"data-testid":"executor-project-path-link",children:u})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(zi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:y})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(S,{size:12,style:{color:b.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:b.color},children:b.label})]})]})}const hD={planning:hi,subtask:ga,mission_interview:Ms,milestone_interview:Ms,slice_interview:Ms},pD={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},hx="fusion:session-banner-dismissed";function Hr(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function fD(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(hx);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n)){const o=typeof r=="number"?r:Hr(r);s.set(a,o)}return s}catch{return new Map}}function gD(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(hx,JSON.stringify(n))}catch{}}const Di=fD();function bD({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{gD(Di),o(g=>g+1)};i.useEffect(()=>{if(Di.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let x=!1;for(const[v,b]of Di){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Di.delete(v),x=!0;continue}Hr(y.updatedAt)>b&&(Di.delete(v),x=!0)}x&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const x=Di.get(g.id);return x===void 0?!0:Hr(g.updatedAt)>x}),[e,r]);if(c.length===0)return null;const d=c.filter(g=>g.status==="awaiting_input").length,u=c.filter(g=>g.status==="error").length;let m="";d>0&&u>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input, ${u} failed`:d>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input`:u>0&&(m=`${u} AI session${u===1?"":"s"} failed`);const h=g=>{Di.set(g.id,Math.max(Hr(g.updatedAt),Date.now())),l()},f=g=>{Di.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)Di.set(x.id,Math.max(Hr(x.updatedAt),g));l(),a()};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(nn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const x=hD[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(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":pD[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(nn,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const px="fusion:cli-binary-banner-dismissed";function xD(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(px)==="1"}catch{return!1}}function vD(){if(!(typeof window>"u"))try{window.localStorage.setItem(px,"1")}catch{}}function yD({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>xD()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let y=!1;return wk().then(S=>{y||s(S)}).catch(()=>{}),()=>{y=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const y=await kk();s({binary:y.binary,expectedVersion:y.expectedVersion,state:y.state,install:y.install}),y.installResult.success||d(y.installResult.permissionsHint||y.installResult.stderr||`Install failed (exit ${y.installResult.exitCode??"n/a"})`)}catch(y){d(y instanceof Error?y.message:String(y))}finally{l(!1)}},[]),m=i.useCallback(()=>{vD(),r(!0)},[]);if(a||!n||n.state==="installed"||n.state==="skipped")return null;const h=n.state==="version-mismatch",f=n.binary.version,p=n.expectedVersion,g=h?"Update the Fusion CLI":"Install the Fusion CLI",x=h?t.jsxs(t.Fragment,{children:["Your installed ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," but this dashboard expects"," ",t.jsxs("strong",{children:["v",p]}),". Update to stay in sync."]}):t.jsxs(t.Fragment,{children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),v=h?"Update with npm":"Install with npm",b=h?"Updating…":"Installing…";return t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:g}),t.jsx("div",{className:"cli-binary-banner__text",children:x}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?b:v}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(nn,{size:16})})]})}function wD({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(nn,{size:16,"aria-hidden":"true"})})]})}function kD({onResume:e}){const n=S$();if(!n)return null;const s=n.completedSteps.length,a=Qi.length,r=s>0?`${s} of ${a} 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(bs,{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:()=>{ti("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(ls,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function jD({onOpenSettings:e,onOpenModelOnboarding:n}){const s=dr(),a=lx(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,N]=await Promise.all([Zr(),ja()]);if(b)return;const E=S.providers??[],w=E.find(P=>P.id==="github"),_=!E.some(P=>P.id!=="github"&&P.authenticated),D=!N.defaultProvider&&!N.defaultModelId,C=w?!w.authenticated:!1;h({needsAiProvider:_,needsDefaultModel:D,needsGitHub:C})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{j$(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),x=i.useCallback(()=>{e("authentication")},[e]),v=i.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:us}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:If}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:Vs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,g,p]);return!s||a||d||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(hi,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsx("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:t.jsx(y,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})}),t.jsx(Zi,{slotId:"post-onboarding-recommendation",renderPlaceholder:!1,actions:{openSettingsSection:e,openModelOnboarding:n}})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(nn,{size:16,"aria-hidden":!0})})]})}function ND({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 ad(e){return e>99?"99+":String(e)}function SD({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,chatHasUnreadResponse:m=!1,onOpenGitManager:h,onOpenWorkflowSteps:f,onOpenSchedules:p,onOpenScripts:g,onToggleTerminal:x,onOpenFiles:v,onOpenTodos:b,todosOpen:y=!1,onOpenGitHubImport:S,onOpenPlanning:N,onResumePlanning:E,activePlanningSessionCount:w=0,onOpenUsage:j,onRunScript:_,projectId:D,onViewAllProjects:C,showSkillsTab:P,experimentalFeatures:I,onOpenNodes:H,pluginDashboardViews:A=[]}){const $=Js(),[F,G]=i.useState(!1),[ee,J]=i.useState(!1),[M,T]=i.useState({}),[L,k]=i.useState(!1),K=i.useMemo(()=>Object.entries(M).sort(([Te],[ue])=>Te.localeCompare(ue)),[M]);i.useEffect(()=>{if(!ee)return;let Te=!1;return k(!0),eo(D).then(ue=>{Te||T(ue)}).catch(()=>{Te||T({})}).finally(()=>{Te||k(!1)}),()=>{Te=!0}},[ee,D]);const oe=i.useCallback(()=>G(!1),[]),le=i.useCallback(Te=>{oe(),Te?.()},[oe]);if(i.useEffect(()=>{if(!F)return;const Te=ue=>{ue.key==="Escape"&&G(!1)};return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[F]),$!=="mobile"||a||r)return null;const we=w>0&&E?E:N,ge=A.some(Te=>Te.pluginId==="fusion-plugin-roadmap"),Ue=!!I?.roadmap&&!ge,Z=!!P,Q=!!I?.todoView,X=Ue&&(!Z||e==="roadmaps"),ie=Z&&(!Ue||e!=="roadmaps"),se=Z&&!ie,B=Te=>Te.pluginId==="fusion-plugin-dependency-graph"&&Te.view.viewId==="graph",O=A.filter(Te=>Te.view.placement==="primary").sort((Te,ue)=>(Te.view.order??Number.MAX_SAFE_INTEGER)-(ue.view.order??Number.MAX_SAFE_INTEGER)),ke=A.find(B)??null,Ie=(ke?[ke,...O.filter(Te=>!B(Te))]:O).slice(0,1),Oe=new Set(Ie.map(Te=>`${Te.pluginId}:${Te.view.viewId}`)),He=A.filter(Te=>!Oe.has(`${Te.pluginId}:${Te.view.viewId}`)).sort((Te,ue)=>(Te.view.order??Number.MAX_SAFE_INTEGER)-(ue.view.order??Number.MAX_SAFE_INTEGER)),$e=e==="documents"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||y&&Q||e==="roadmaps"&&!X||e==="skills"&&!ie||Ga(e)&&!Ie.some(Te=>Vr(Te.pluginId,Te.view.viewId)===e);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(sa,{}),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(zn,{}),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(Ms,{}),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.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Oi,{}),m&&e!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Unread chat response"})]}),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"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:ad(u)})]}),ie&&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(us,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),X&&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(bd,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),Ie.map(Te=>{const ue=Vr(Te.pluginId,Te.view.viewId),ce=fl(Te.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===ue?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${Te.pluginId}-${Te.view.viewId}`,role:"tab","aria-selected":e===ue,onClick:()=>n(ue),children:[t.jsx(ce,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:Te.view.label})]},`${Te.pluginId}:${Te.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${$e?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>G(Te=>!Te),children:[t.jsx(md,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),F&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:oe}),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:()=>le(d),children:[t.jsx(ba,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:ad(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>le(l),children:[t.jsx(Ws,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>le(c),children:[t.jsx(Xa,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>le(h),children:[t.jsx(zs,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>le(x),children:[t.jsx(Fi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>J(Te=>!Te),"aria-expanded":ee,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(Un,{size:14,className:`mobile-more-chevron${ee?" mobile-more-chevron--open":""}`})})]}),ee&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:L?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(xt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):K.length>0?t.jsxs(t.Fragment,{children:[K.map(([Te,ue])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${Te}`,onClick:()=>{_&&_(Te,ue),oe(),J(!1)},children:[t.jsx(ls,{}),t.jsx("span",{children:Te})]},Te)),g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{oe(),J(!1),g()},children:[t.jsx(ci,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{oe(),J(!1),g()},children:[t.jsx(ci,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>le(v),children:[t.jsx(vs,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>le(we),children:[t.jsx(hi,{}),t.jsx("span",{children:"Planning"}),w>0&&t.jsx("span",{className:"mobile-more-item-badge",children:ad(w)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>le(f),children:[t.jsx(dl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>le(p),children:[t.jsx(zi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>le(S),children:[t.jsx(ND,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>le(j),children:[t.jsx(Ws,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>le(C),children:[t.jsx(Tl,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>le(()=>n("documents")),children:[t.jsx(na,{}),t.jsx("span",{children:"Documents"})]}),se&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>le(()=>n("skills")),children:[t.jsx(us,{}),t.jsx("span",{children:"Skills"})]}),Ue&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>le(()=>n("roadmaps")),children:[t.jsx(bd,{}),t.jsx("span",{children:"Roadmaps"})]}),I?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>le(()=>n("research")),children:[t.jsx(Li,{}),t.jsx("span",{children:"Research"})]}),I?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>le(()=>n("insights")),children:[t.jsx(bs,{}),t.jsx("span",{children:"Insights"})]}),I?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>le(()=>n("memory")),children:[t.jsx(Yr,{}),t.jsx("span",{children:"Memory"})]}),I?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{le(()=>n("dev-server"))},children:[t.jsx(Xa,{}),t.jsx("span",{children:"Dev Server"})]}),I?.nodesView&&H&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>le(H),children:[t.jsx(Iy,{}),t.jsx("span",{children:"Nodes"})]}),Q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>le(()=>b?.()),children:[t.jsx(Xd,{}),t.jsx("span",{children:"Todos"})]}),He.map(Te=>{const ue=Vr(Te.pluginId,Te.view.viewId),ce=fl(Te.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${Te.pluginId}-${Te.view.viewId}`,onClick:()=>le(()=>n(ue)),children:[t.jsx(ce,{}),t.jsx("span",{children:Te.view.label})]},`${Te.pluginId}:${Te.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>le(o),children:[t.jsx(qr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function CD({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below"}){const l=i.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(d=>d.name.toLowerCase().includes(c)):e},[e,n]);return a?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,d)=>t.jsxs("button",{type:"button",className:`agent-mention-item${d===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:u=>u.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":d===s,children:[t.jsx(Hd,{agent:c,size:20}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}function ED(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:a,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:c,onDone:d,onError:u,onFallbackSession:m}=e;let h="",f="",p=[],g,x=null,v=null;const b=()=>{x=null,a(h)},y=()=>{v=null,r(f)},S=()=>{x!==null&&(cancelAnimationFrame(x),x=null),v!==null&&(cancelAnimationFrame(v),v=null)};return l.current=S,{handlers:{onThinking:E=>{f+=E,v===null&&(v=requestAnimationFrame(y))},onText:E=>{h+=E,x===null&&(x=requestAnimationFrame(b))},onToolStart:E=>{p=[...p,{toolName:E.toolName,args:E.args,isError:!1,status:"running"}],o(p)},onToolEnd:E=>{const w=[...p];for(let j=w.length-1;j>=0;j--){const _=w[j];if(_?.toolName===E.toolName&&_.status==="running"){w[j]={..._,status:"completed",isError:E.isError,result:E.result},p=w,o(w);return}}p=[...w,{toolName:E.toolName,isError:E.isError,result:E.result,status:"completed"}],o(p)},onFallback:E=>{g=E,m?.(E,n),c?.(`Primary model unavailable. Switched to fallback ${E.fallbackModel}.`,"warning")},onDone:E=>{S(),d({messageId:E.messageId,message:E.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:E=>{S(),u(E,s)}},cancelFlushes:S}}const Ka="__fn_agent__";function fx(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Zo(e,n,s){const a=typeof e=="string"?e.trim():"",r=fx(n,s),o=a||(r.modelProvider&&r.modelId?Ka:"");return o?{agentId:o,...r}:null}function el(e,n,s){const a=fx(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function _D(e){const n=typeof e=="string"?e.trim():"",s=n.indexOf("/");return!n||s<=0||s>=n.length-1?{}:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function MD(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(a=>{if(!a||typeof a!="object")return null;const r=a,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(a=>a!==null);return s.length>0?s:void 0}function AD(e){const n=e?.fallback;if(!n||typeof n!="object")return;const s=n,a=typeof s.primaryModel=="string"?s.primaryModel:"",r=typeof s.fallbackModel=="string"?s.fallbackModel:"",o=s.triggerPoint;if(!(!a||!r||o!=="session-creation"&&o!=="prompt-time"))return{primaryModel:a,fallbackModel:r,triggerPoint:o}}function tl(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:MD(e.metadata),fallbackInfo:AD(e.metadata),createdAt:e.createdAt}}function PD(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,x]=i.useState(""),[v,b]=i.useState(""),[y,S]=i.useState([]),[N,E]=i.useState(""),w=i.useRef(null),j=i.useRef(!1),_=i.useRef(null),D=i.useRef(""),C=i.useRef(f);C.current=f;const P=i.useRef(null),I=i.useRef(""),H=i.useRef(null),A=i.useRef(s);A.current=s;const $=i.useRef(0),F=3,G=i.useRef(!1);i.useEffect(()=>{D.current=N},[N]);const ee=i.useCallback(async()=>{c(!0);try{const Q=await lm(e);o(Q.sessions)}catch(Q){console.error("[useQuickChat] Failed to refresh sessions:",Q)}finally{c(!1)}},[e]),J=i.useCallback(async Q=>{const X={agentId:Q.agentId};return Q.modelProvider&&Q.modelId&&(X.modelProvider=Q.modelProvider,X.modelId=Q.modelId),(await J1(X,e)).session},[e]),M=i.useCallback(async(Q,X,ie)=>{const se=Zo(Q,X,ie);if(!se)return;const B=el(se.agentId,se.modelProvider,se.modelId);c(!0);try{const{session:O}=await G1({agentId:se.agentId,modelProvider:se.modelProvider,modelId:se.modelId},e);if(O)a(O),I.current=B,O.isGenerating&&(p(!0),x(""));else{const ke=await J(se);a(ke),I.current=B}$.current=0}catch(O){console.error("[useQuickChat] Failed to initialize session:",O),$.current+=1,$.current<=F&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[e,n,J]),T=i.useCallback(async()=>{if(s){h(!0);try{const Q=await ic(s.id,{limit:50},e);u(Q.messages.map(tl))}catch(Q){console.error("[useQuickChat] Failed to load messages:",Q)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?T():u([])},[s,T]),i.useEffect(()=>{if(!f||w.current||!s)return;const Q=setInterval(async()=>{if(!C.current||w.current||!s){clearInterval(Q);return}try{if(!(await Y1(s.id,e)).session.isGenerating){clearInterval(Q);const ie=await ic(s.id,{limit:50},e);u(ie.messages.map(tl)),x(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(Q)},[f,s,e]);const L=i.useCallback(async()=>{if(s){h(!0);try{const Q=await ic(s.id,{limit:50},e);u(Q.messages.map(tl))}catch(Q){console.error("[useQuickChat] Failed to reload messages:",Q)}finally{h(!1)}}},[s,e]),k=i.useCallback(()=>{_.current?.(),_.current=null,D.current="",E(""),x(""),b(""),S([]),p(!1)},[]),K=i.useCallback(async(Q,X,ie)=>{const se=Zo(Q,X,ie);if(!se)return;const B=el(se.agentId,se.modelProvider,se.modelId);H.current=se;const O=B===I.current&&A.current;if(O||(w.current&&(w.current.close(),w.current=null),k()),O){await L();return}a(null),u([]),I.current=B,await M(se.agentId,se.modelProvider,se.modelId)},[M,L,k]),oe=i.useCallback(async Q=>{const X=Zo(Q.agentId,Q.modelProvider??void 0,Q.modelId??void 0);X&&(H.current=X,I.current=el(X.agentId,X.modelProvider,X.modelId),w.current&&(w.current.close(),w.current=null),k(),a(Q))},[k]),le=i.useCallback(async(Q,X)=>{await K(Ka,Q,X)},[K]),we=i.useCallback(async(Q,X,ie)=>{const B=Zo(Q??"",X,ie)??H.current;if(!B)return;H.current=B;const O=el(B.agentId,B.modelProvider,B.modelId);G.current=!0,$.current=0,w.current&&(w.current.close(),w.current=null),k(),u([]),a(null),c(!0);try{const ke=await J(B);a(ke),I.current=O;const ae=await lm(e);o(ae.sessions)}catch(ke){console.error("[useQuickChat] Failed to start a fresh session:",ke),n?.("Failed to start a new chat","error")}finally{G.current=!1,c(!1)}},[n,J,e,k]),ge=i.useCallback(()=>{s&&(j.current=!0,_.current?.(),_.current=null,w.current?.close(),w.current=null,Q1(s.id,e).catch(()=>{}),p(!1),x(""),b(""),S([]))},[s,e]),Ue=i.useCallback(()=>{D.current="",E("")},[]),Z=i.useCallback((Q,X)=>{if(!s||!Q.trim()&&(!X||X.length===0))return Promise.resolve();if(f)return X&&X.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(D.current=Q,E(Q),n?.("Still waiting for previous response — message queued","warning"),Promise.resolve());const ie=new Promise((se,B)=>{P.current={resolve:se,reject:B},j.current=!1,w.current&&(w.current.close(),w.current=null);const O=`temp-${Date.now()}`,ke={id:O,sessionId:s.id,role:"user",content:Q,createdAt:new Date().toISOString()};u(te=>[...te,ke]),x(""),b(""),S([]),p(!0);const{handlers:ae}=ED({sessionId:s.id,tempUserMessageId:O,setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:_,addToast:n,onFallbackSession:(te,Ie)=>{const Oe=_D(te.fallbackModel);o(He=>He.map($e=>$e.id===Ie?{...$e,...Oe}:$e)),a(He=>He&&He.id===Ie?{...He,...Oe}:He)},onDone:({messageId:te,message:Ie,accumulated:Oe})=>{const He=Ie?tl(Ie):{id:te||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:Oe.text,thinkingOutput:Oe.thinking||void 0,toolCalls:Oe.toolCalls.length>0?Oe.toolCalls:void 0,fallbackInfo:Oe.fallbackInfo,createdAt:new Date().toISOString()};u(Te=>[...Te,He]),x(""),b(""),S([]),p(!1),w.current=null,P.current?.resolve(),P.current=null;const $e=D.current.trim();$e&&(D.current="",E(""),Z($e))},onError:te=>{if(x(""),b(""),S([]),p(!1),w.current=null,console.error("[useQuickChat] Stream error:",te),n?.(typeof te=="string"&&te.trim()?te:"Failed to get response","error"),P.current?.reject(new Error(typeof te=="string"?te:"Failed to get response")),P.current=null,!j.current){const Ie=D.current.trim();Ie&&(D.current="",E(""),Z(Ie))}L()}});w.current=X1(s.id,Q,ae,X,e)});return ie.catch(()=>{}),ie},[s,f,e,n,L]);return i.useEffect(()=>()=>{w.current&&(w.current.close(),w.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:N,sendMessage:Z,stopStreaming:ge,clearPendingMessage:Ue,switchSession:K,selectSession:oe,startModelChat:le,startFreshSession:we,refreshSessions:ee,loadMessages:T,reloadMessages:L,skipNextSessionInitRef:G}),[s,r,l,d,m,f,g,v,y,N,Z,ge,Ue,K,oe,le,we,ee,T,L])}function TD(e,n){const[s,a]=i.useState([]),[r,o]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback(async p=>{c(!0);try{const g=n?.filterState,x=g&&g!=="all"?{state:g}:void 0,v=n?.showSystemAgents??!1,b=await Na({...x,...p,includeEphemeral:p?.includeEphemeral??v},e),y=Array.from(new Map(b.map(S=>[S.id,S])).values());a(y)}catch(g){console.error("Failed to load agents:",g)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=i.useCallback(async()=>{try{const p=await mN(e);o(p)}catch(p){console.error("Failed to load agent stats:",p)}},[e]);i.useEffect(()=>{d(),u()},[d,u]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=()=>{d(),u()};return ai(`/api/events${p}`,{events:{"agent:created":g,"agent:updated":g,"agent:deleted":g,"agent:stateChanged":g}})},[e,d,u]);const m=i.useCallback(async()=>{await Promise.all([d(),u()])},[d,u]),h=n?.showSystemAgents??!1,f=s.filter(p=>p.state!=="active"&&p.state!=="running"?!1:h||!zS(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function RD({visible:e,position:n,files:s,selectedIndex:a,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 d=yS(l.path),u=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===a?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===a,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Tf,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:u}),d&&t.jsx("span",{className:"file-mention-popup-item-path",children:d})]})]},l.path)})})]}):null}const ID=200;function $D(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,m]=i.useState([]),[h,f]=i.useState(!1),[p,g]=i.useState(0),x=i.useRef(null),v=i.useRef(null);i.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=i.useCallback((w,j)=>{if(j<0||j>w.length){r(!1);return}const _=D=>/[a-zA-Z0-9/_.-]/.test(D);for(let D=j-1;D>=0;D--){if(w[D]==="#")if(D===0){const C=w.slice(D+1,j);d(D),l(C),g(0),r(!0);return}else{const C=w[D-1];if(/[\s,.;:!?'"()[\]{}]/.test(C)){const P=w.slice(D+1,j);d(D),l(P),g(0),r(!0);return}r(!1);return}if(!_(w[D])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async w=>{if(!w.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const j=await bj(w,s,n);m(j.files),g(0)}catch(j){j.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},ID),()=>{x.current&&clearTimeout(x.current)}},[o,a,S]);const N=i.useCallback((w,j)=>{if(!a||c<0)return j;const _=j.slice(0,c),D=j.slice(c+1),C=D.match(/[\s]|$/),P=C?C.index:D.length,I=D.slice(P);return`${_}#${w.path}${I}`},[a,c]),E=i.useCallback((w,j)=>{if(!a||u.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),g(_=>Math.min(_+1,u.length-1)),!0;case"ArrowUp":return w.preventDefault(),g(_=>Math.max(_-1,0)),!0;case"Enter":case"Tab":return u[p]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:N,dismissMention:y,handleKeyDown:E}}function DD(e){return`${e.name?.trim()||e.id} (${e.role})`}function Ir(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 LD(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 rl(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function OD(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,a])=>{const r=typeof a=="string"?a:(()=>{try{return JSON.stringify(a)}catch{return String(a)}})();return`${s}=${rl(r,50)}`}).join(", ")}function FD(e){if(e===void 0)return null;if(typeof e=="string")return rl(e,200);try{return rl(JSON.stringify(e),200)}catch{return rl(String(e),200)}}function gx(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",x=f.status==="completed"&&f.isError,v=OD(f.args),b=FD(f.result),y=g?v:b?`result: ${b}`:v?`args: ${v}`:null,S=n?null:y,N=g?"running":x?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${x?" 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}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:N})]}),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})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${x?" 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:b})]})]})]},`${f.toolName}-${p}`)},a=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:a,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Lu,{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))),d=c.slice(0,5),u=Math.max(0,c.length-d.length),m=u>0?`${d.join(", ")}, +${u} more`:d.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:a,"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(Lu,{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 bx={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 lf(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",a=n[2]??"",r=n.index+s.length;return{filter:a,start:r,end:e.length}}function zD(e,n){const s=e.slice(0,n),a=/(^|[\s])@([\w-]*)$/.exec(s);if(!a)return null;const r=a[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const nl={width:320,height:400},UD=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"]),BD=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function HD(e){return e.type.startsWith("image/")}function qD(e){if(UD.has(e.type))return!0;const n=e.name.toLowerCase();return BD.some(s=>n.endsWith(s))}const Ha={width:280,height:260},_s=768,qa=8;function VD(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const N=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return N&&parseFloat(N)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const N=`fusion-quick-chat-position-${e||"default"}`;try{const E=localStorage.getItem(N);if(E){const w=JSON.parse(E);if(typeof w.x=="number"&&typeof w.y=="number"&&!isNaN(w.x)&&!isNaN(w.y))return w}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=i.useRef(r),m=i.useRef(null),h=i.useRef(null),f=n??i.useRef(!1);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback(N=>{if(typeof window>"u")return N;const E=48,w=window.innerWidth<=768?4:8,j=window.innerWidth<=768?44:0,_=window.innerWidth>768?s():0,D=window.innerWidth-E-w,C=window.innerHeight-E-w-j-_;return{x:Math.max(w,Math.min(D,N.x)),y:Math.max(w,Math.min(C,N.y))}},[s]),g=i.useCallback(N=>{if(typeof window>"u")return;const E=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(E,JSON.stringify(N))}catch{}},[e]),x=i.useCallback(()=>{if(!d.current)return;const N=h.current,E=m.current;N&&E!==null&&typeof N.releasePointerCapture=="function"&&N.releasePointerCapture(E),d.current=null,m.current=null,h.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y)},[g]),v=i.useCallback(N=>{if(!d.current||m.current!==null&&N.pointerId!==m.current)return;const E=N.clientX-d.current.pointerX,w=N.clientY-d.current.pointerY;if((Math.abs(E)>=5||Math.abs(w)>=5)&&(f.current=!0),!f.current)return;const j=d.current.x-E,_=d.current.y-w,D=p({x:j,y:_});u.current=D,o(D)},[p]),b=i.useCallback(N=>{m.current!==null&&N.pointerId!==m.current||x()},[x]),y=i.useCallback(N=>{m.current!==null&&N.pointerId!==m.current||x()},[x]),S=i.useCallback(N=>{if(N.button!==0&&N.pointerType==="mouse")return;const E=N.currentTarget;N.preventDefault(),typeof E.setPointerCapture=="function"&&E.setPointerCapture(N.pointerId);const w=u.current;d.current={x:w.x,y:w.y,pointerX:N.clientX,pointerY:N.clientY},m.current=N.pointerId,h.current=E,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",v,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",y)},[y,v,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y),document.body.style.userSelect=""},[y,v,b]),{position:r,isDragging:l,handlePointerDown:S}}function WD(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>_s,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const x=Math.max(Ha.width,window.innerWidth-p-qa),v=Math.max(Ha.height,window.innerHeight-g-qa);return{width:Math.max(Ha.width,Math.min(x,f.width)),height:Math.max(Ha.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=_s)return nl;try{const f=localStorage.getItem(a);if(!f)return nl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?nl:{width:p.width,height:p.height}}catch{return nl}},[a]),[c,d]=i.useState(l),[u,m]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const h=i.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 x={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-x.pointerX,N=y.clientY-x.pointerY;let E=x.width,w=x.height,j=x.anchorRight,_=x.anchorBottom;if(p.includes("w")&&(E=x.width-S),p.includes("e")){const A=S;E=x.width+A,j=x.anchorRight-A}if(p.includes("n")&&(w=x.height-N),p.includes("s")){const A=N;w=x.height+A,_=x.anchorBottom-A}const D=n+j,C=s+_,P=o({width:E,height:w},D,C),I=Math.max(qa-n,Math.min(window.innerWidth-n-Ha.width-qa,j)),H=Math.max(qa-s,Math.min(window.innerHeight-s-Ha.height-qa,_));d(P),m({right:I,bottom:H})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const cf=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,onToggleRender:r}){const o=n.role==="user",l=i.useMemo(()=>{if(!o)return null;const d=n.content,u=/@([\w-]+)/g,m=[];let h=0,f=u.exec(d);for(;f;){const[p,g=""]=f,x=f.index;x>h&&m.push(d.slice(h,x));const v=g.replace(/_/g," ").toLowerCase(),b=a.get(v);b?m.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",b.name.replace(/\s+/g,"_")]},`${b.id}-${x}`)):m.push(p),h=x+p.length,f=u.exec(d)}return h<d.length&&m.push(d.slice(h)),m.length===0?d:m},[o,n.content,a]),c=i.useMemo(()=>o?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Ai,{remarkPlugins:[Pi],components:bx,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(Qd,{size:14}):t.jsx(ur,{size:14})})]}),gx(n.toolCalls,!0)]})});function KD({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d}){const{agents:u}=TD(e),[m,h]=i.useState(!1),f=a!==void 0,p=f?a:m,g=f?de=>{r?.(typeof de=="function"?de(p):de)}:h;ra({enabled:p});const x=Js(),[v,b]=i.useState("agent"),[y,S]=i.useState(""),[N,E]=i.useState(!1),[w,j]=i.useState("model"),[_,D]=i.useState(""),[C,P]=i.useState(""),[I,H]=i.useState([]),[A,$]=i.useState(!1),[F,G]=i.useState(""),[ee,J]=i.useState(""),[M,T]=i.useState(""),[L,k]=i.useState([]),[K,oe]=i.useState(!1),[le,we]=i.useState(!1),[ge,Ue]=i.useState(""),[Z,Q]=i.useState(0),[X,ie]=i.useState(""),[se,B]=i.useState(!1),[O,ke]=i.useState(0),[ae,te]=i.useState(-1),[Ie,Oe]=i.useState(()=>new Set),[He,$e]=i.useState(!1),[Te,ue]=i.useState([]),[ce,Ae]=i.useState(!1),[Ne,ye]=i.useState(!1),[,Ce]=i.useState(!1),[fe,Pe]=i.useState({top:0,left:0}),De=$D({projectId:e}),dt=i.useCallback(de=>{if(!de||!De.mentionActive)return;const We=de.getBoundingClientRect();Pe({top:We.top-260,left:We.left+8})},[De.mentionActive]),pt=i.useRef(!1),lt=i.useRef(!1),vt=i.useRef(""),_e=i.useRef(0),Fe=i.useRef(null),bt=i.useRef(null),ht=i.useRef(0),{position:Ee,isDragging:me,handlePointerDown:Re}=VD(e,pt),be=Ee.y+60,{panelSize:Ke,anchorOffset:pe,handleResizeStart:Xe}=WD(e,Ee.x,be),wt=typeof window<"u"&&window.innerWidth>_s,{activeSession:gt,messages:Tt,isStreaming:Zt,streamingText:Ot,streamingThinking:Rt,streamingToolCalls:en,sessions:zt,sessionsLoading:Qt,messagesLoading:xn,sendMessage:Kt,stopStreaming:Ut,pendingMessage:fn,clearPendingMessage:un,switchSession:tn,selectSession:Vt,startModelChat:mn,startFreshSession:xe,refreshSessions:Le,skipNextSessionInitRef:Ve}=PD(e,n),at=i.useRef(null),Ge=i.useRef(null),Ft=i.useRef(null),_t=i.useRef(null),qt=i.useRef(null),St=i.useRef([]),z=i.useRef(!1),he=i.useRef(!1),st=i.useRef(!1),It=i.useRef(null),ve=i.useRef(!1),ot=i.useRef(!1);i.useEffect(()=>{if(!p||typeof window>"u"||typeof document>"u"||window.innerWidth>_s)return;const de=window.scrollY,We=document.documentElement,mt=document.body,q={htmlOverflow:We.style.overflow,bodyOverflow:mt.style.overflow};return window.scrollTo(0,0),We.style.overflow="hidden",mt.style.overflow="hidden",()=>{We.style.overflow=q.htmlOverflow,mt.style.overflow=q.bodyOverflow,window.scrollTo(0,de)}},[p]),i.useLayoutEffect(()=>{if(!p||typeof window>"u"||!window.visualViewport)return;const de=at.current;if(!de)return;const We=window.visualViewport,mt=()=>{ve.current||(de.style.setProperty("--vv-height",`${We.height}px`),de.style.setProperty("--vv-offset-top",`${We.offsetTop||0}px`))};return mt(),We.addEventListener("resize",mt),We.addEventListener("scroll",mt),()=>{We.removeEventListener("resize",mt),We.removeEventListener("scroll",mt)}},[p]);const Nt=F||ee,Lt=i.useMemo(()=>Ir(Nt),[Nt]),$t=i.useMemo(()=>v==="model"&>?.modelProvider&>?.modelId?`${gt.modelProvider}/${gt.modelId}`:Nt,[gt?.modelId,gt?.modelProvider,v,Nt]),Wt=i.useMemo(()=>Ir($t),[$t]),Gt=i.useMemo(()=>I.find(de=>`${de.provider}/${de.id}`===$t)??null,[$t,I]),sn=i.useMemo(()=>LD(Gt,Wt),[Gt,Wt]),on=i.useMemo(()=>v==="model"?Lt?`${Ka}::${Lt.modelProvider}/${Lt.modelId}`:"":y?`${y}::`:"",[v,y,Lt]),Jt=!(v==="agent"?!!y:!!Lt)||!gt;i.useEffect(()=>{if(u.length===0){S(""),b("model");return}u.some(We=>We.id===y)||S(u[0]?.id??"")},[u,y]),i.useEffect(()=>{!p||lt.current||(lt.current=!0,$(!0),$s().then(de=>{const We=de.models??[];if(H(We),F||We.length===0)return;const mt=de.defaultProvider,q=de.defaultModelId;if(mt&&q){const Ze=`${mt}/${q}`;if(We.some(Et=>`${Et.provider}/${Et.id}`===Ze)){J(Ze),G(Ze),b("model");return}}J("");const Se=We[0];Se&&G(`${Se.provider}/${Se.id}`)}).catch(de=>{console.error("[QuickChatFAB] Failed to load models:",de),H([]),J("")}).finally(()=>{$(!1)}))},[p,u.length,F]),i.useEffect(()=>{!p||!e||(oe(!0),K1(e).then(de=>{k(de)}).catch(()=>{k([])}).finally(()=>{oe(!1)}))},[p,e]),i.useEffect(()=>{p&&Le()},[p,Le]),i.useEffect(()=>{if(!p){vt.current="";return}if(!on){vt.current="";return}if(Ve.current){vt.current=on;return}const de=on===vt.current&&!gt&&!Qt;if(!(on===vt.current&&!de)){if(vt.current=on,v==="model"&&Lt){mn(Lt.modelProvider,Lt.modelId);return}v==="agent"&&y&&tn(y)}},[p,v,Lt,y,on,gt,Qt,mn,tn,Ve]),i.useEffect(()=>{p||(B(!1),ie(""),te(-1),we(!1),Ue(""),Q(0),St.current.forEach(de=>{de.previewUrl&&URL.revokeObjectURL(de.previewUrl)}),ue([]))},[p]),i.useEffect(()=>{St.current=Te},[Te]),i.useEffect(()=>{if(!p){z.current=!1;return}typeof window>"u"||(z.current=window.innerWidth<=_s)},[p]),i.useEffect(()=>{if(!p||Jt||!z.current)return;const de=_t.current;if(!de)return;const We=document.activeElement,mt=We?at.current?.contains(We):!1,q=We===document.body,Se=We===It.current;if(!mt&&!q&&!Se){z.current=!1;return}if(Se){de.focus({preventScroll:!0}),z.current=!1;return}const Ze=requestAnimationFrame(()=>{de.focus(),z.current=!1});return()=>cancelAnimationFrame(Ze)},[p,Jt]),i.useEffect(()=>()=>{St.current.forEach(de=>{de.previewUrl&&URL.revokeObjectURL(de.previewUrl)})},[]);const Hn=i.useCallback(()=>{E(!0),j("model"),D(u[0]?.id??""),P(F||ee||"")},[u,ee,F]),Yn=i.useMemo(()=>u.find(de=>de.id===y)??null,[u,y]),re=i.useMemo(()=>{const de=ge.trim().toLowerCase();return(de?L.filter(mt=>mt.name.toLowerCase().includes(de)):L).slice(0,10)},[L,ge]),rt=i.useMemo(()=>{const de=X.trim().toLowerCase();return de?u.filter(We=>We.name.toLowerCase().includes(de)):u},[u,X]),ct=i.useMemo(()=>{const de=new Map;for(const We of u)de.set(We.name.toLowerCase(),We);return de},[u]);i.useEffect(()=>{Q(0)},[re]),i.useEffect(()=>{ke(0)},[X,se]),i.useEffect(()=>()=>{Fe.current!==null&&(window.clearTimeout(Fe.current),Fe.current=null),bt.current!==null&&(window.clearTimeout(bt.current),bt.current=null)},[]),i.useEffect(()=>{if(!p)return;const de=mt=>{const q=mt.target;at.current?.contains(q)||Ge.current?.contains(q)||q.closest(".model-combobox-dropdown--portal")||g(!1)},We=mt=>{mt.key==="Escape"&&g(!1)};return document.addEventListener("mousedown",de),document.addEventListener("keydown",We),()=>{document.removeEventListener("mousedown",de),document.removeEventListener("keydown",We)}},[p,g]);const ft=i.useCallback(()=>{const de=Ft.current;if(!de)return;const mt=de.scrollTop+de.clientHeight>=de.scrollHeight-50;ye(!mt),ot.current=!mt},[]),it=i.useCallback(()=>{const de=Ft.current;de&&(de.scrollTop=de.scrollHeight,ye(!1),ot.current=!1)},[]);i.useEffect(()=>{p&&(ot.current||it())},[Tt,Ot,Rt,Zt,p,it]);const Y=i.useMemo(()=>{const de=new Map(u.map(mt=>[mt.id,mt.name?.trim()||mt.id])),We=new Map(I.map(mt=>[`${mt.provider}/${mt.id}`,mt.name?.trim()||""]));return zt.map((mt,q)=>{const Se=mt.title?.trim()||`Session ${q+1}`;let Ze=null;if(mt.agentId&&mt.agentId!==Ka)Ze=de.get(mt.agentId)||mt.agentId;else if(mt.modelProvider&&mt.modelId){const At=`${mt.modelProvider}/${mt.modelId}`,Et=We.get(At);Ze=Et?`${Et} [${At}]`:At}return{id:mt.id,label:Ze?`${Se} — ${Ze}`:Se}})},[u,I,zt]),Ye=i.useMemo(()=>v==="agent"?Yn?`Message ${Yn.name||Yn.id}`:"Select an agent to start chatting":sn?`Message ${sn}`:"Select a model to start chatting",[v,Yn,sn]),Yt=i.useCallback(de=>{const We=zt.find(mt=>mt.id===de);We&&(We.modelProvider&&We.modelId?(b("model"),G(`${We.modelProvider}/${We.modelId}`)):(b("agent"),S(We.agentId)),Vt(We))},[Vt,zt]),In=i.useCallback(async()=>{if(!Qt){if(w==="agent"){if(!_)return;b("agent"),S(_),await xe(_)}else{const de=Ir(C||F||ee);if(!de)return;b("model"),G(`${de.modelProvider}/${de.modelId}`),await xe(Ka,de.modelProvider,de.modelId)}await Le(),E(!1),j("model")}},[ee,_,w,C,Le,F,Qt,xe]),cs=fn.length>50?`${fn.slice(0,50)}…`:fn,gn=i.useCallback(de=>{if(!de||de.length===0)return;const We=[];for(let mt=0;mt<de.length;mt+=1){const q=de[mt];qD(q)&&We.push({file:q,previewUrl:HD(q)?URL.createObjectURL(q):""})}We.length>0&&ue(mt=>[...mt,...We])},[]),Nn=i.useCallback(de=>{ue(We=>{const mt=We[de];return mt?.previewUrl&&URL.revokeObjectURL(mt.previewUrl),We.filter((q,Se)=>Se!==de)})},[]),ms=i.useCallback(de=>{gn(de.clipboardData?.files)},[gn]),vn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>_s)return;const de=_t.current;!de||de.disabled||de.focus({preventScroll:!0})},[]),bn=i.useCallback(()=>{typeof window>"u"||window.innerWidth>_s||(st.current=!0)},[]),Pt=i.useCallback(async()=>{const de=M.trim(),We=St.current;if(!(!de&&We.length===0)&&!Jt){if(T(""),B(!1),ie(""),te(-1),de==="/help"){$e(!0),vn(),st.current=!1;return}if(de==="/clear"){Ut(),un(),We.forEach(mt=>{mt.previewUrl&&URL.revokeObjectURL(mt.previewUrl)}),ue(mt=>mt.filter(q=>!We.includes(q)));try{if(v==="model"){const mt=Ir(Nt);if(!mt)return;await xe(Ka,mt.modelProvider,mt.modelId)}else y&&await xe(y)}catch{n("Failed to clear conversation","error")}finally{vn(),st.current=!1}return}try{$e(!1),await Kt(de,We.map(mt=>mt.file)),We.forEach(mt=>{mt.previewUrl&&URL.revokeObjectURL(mt.previewUrl)}),ue(mt=>mt.filter(q=>!We.includes(q)))}catch{}finally{vn(),st.current=!1}}},[n,v,un,vn,Jt,M,Nt,y,Kt,xe,Ut]),Qn=i.useCallback(de=>{de.preventDefault(),ht.current+=1,Ae(!0)},[]),es=i.useCallback(de=>{de.preventDefault(),de.dataTransfer.dropEffect="copy",Ae(!0)},[]),W=i.useCallback(de=>{de.preventDefault(),ht.current=Math.max(0,ht.current-1),ht.current===0&&Ae(!1)},[]),qe=i.useCallback(de=>{de.preventDefault(),ht.current=0,Ae(!1),gn(de.dataTransfer?.files)},[gn]),Je=i.useCallback((de,We)=>{const mt=zD(de,We);if(mt){B(!0),ie(mt.filter),te(mt.start);return}B(!1),ie(""),te(-1)},[]),ut=i.useCallback(de=>{T(We=>{const mt=lf(We);if(!mt)return We;const q=`/skill:${de.name} `,Se=We.slice(0,mt.start)+q+We.slice(mt.end);return window.requestAnimationFrame(()=>{_t.current&&_t.current.focus()}),Se}),we(!1),Ue(""),Q(0)},[]),Ct=i.useCallback(de=>{const We=_t.current;if(!We||ae<0)return;const mt=We.selectionStart??_e.current,q=We.selectionEnd??mt,Se=Math.max(mt,q),Ze=Math.min(ae,Se),Et=`${`@${de.name.replace(/\s+/g,"_")}`} `,Cn=M.slice(0,Ze)+Et+M.slice(Se),rn=Ze+Et.length;T(Cn),B(!1),ie(""),ke(0),te(-1),window.requestAnimationFrame(()=>{_t.current&&(_t.current.focus(),_t.current.setSelectionRange(rn,rn))})},[ae,M]),Mt=i.useCallback(de=>{const We=de.target.value,mt=de.target.selectionStart??We.length;_e.current=mt,T(We),He&&We.trim().length>0&&$e(!1),Je(We,mt);const q=lf(We);q?(we(!0),Ue(q.filter)):(we(!1),Ue("")),De.detectMention(We,mt),Ce(De.mentionActive),De.mentionActive&&dt(de.target)},[He,Je,De,dt]),an=i.useCallback(()=>{if(st.current){window.requestAnimationFrame(()=>{vn()});return}typeof window<"u"&&window.innerWidth<=_s&&at.current&&(ve.current=!0,at.current.style.removeProperty("--vv-height"),at.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{ve.current=!1},450)),Fe.current!==null&&window.clearTimeout(Fe.current),Fe.current=window.setTimeout(()=>{B(!1),ie(""),te(-1),Ce(!1),De.dismissMention(),Fe.current=null},120),bt.current!==null&&window.clearTimeout(bt.current),bt.current=window.setTimeout(()=>{we(!1),bt.current=null},120)},[De,vn]),An=i.useCallback(()=>{ve.current=!1,Fe.current!==null&&(window.clearTimeout(Fe.current),Fe.current=null),bt.current!==null&&(window.clearTimeout(bt.current),bt.current=null)},[]),Sn=i.useCallback(de=>{const We=de.currentTarget,mt=We.selectionStart??We.value.length;_e.current=mt,Je(We.value,mt),De.detectMention(We.value,mt),Ce(De.mentionActive),De.mentionActive&&dt(We)},[Je,De,dt]),ps=i.useCallback(de=>{de.key!=="Escape"&&Sn(de)},[Sn]),ts=i.useCallback(de=>{Oe(We=>{const mt=new Set(We);return mt.has(de)?mt.delete(de):mt.add(de),mt})},[]),Bs=i.useCallback((de,We=!1)=>We?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:de}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Ai,{remarkPlugins:[Pi],components:bx,children:de})}),[]),Hi=i.useCallback(de=>{if(_e.current=de.currentTarget.selectionStart??_e.current,De.mentionActive&&De.files.length>0){if(De.handleKeyDown(de,M),de.key==="Enter"||de.key==="Tab"){const We=De.files[De.selectedIndex];if(We){const mt=De.selectFile(We,M);T(mt),De.dismissMention(),Ce(!1)}}return}if(se&&de.key==="ArrowDown"){de.preventDefault(),rt.length>0&&ke(We=>(We+1)%rt.length);return}if(se&&de.key==="ArrowUp"){de.preventDefault(),rt.length>0&&ke(We=>We===0?rt.length-1:We-1);return}if(se&&de.key==="Enter"){de.preventDefault();const We=rt[O]??rt[0];We&&Ct(We);return}if(se&&de.key==="Escape"){de.preventDefault(),de.stopPropagation(),B(!1),ie(""),te(-1);return}if(le&&re.length>0&&de.key==="ArrowDown"){de.preventDefault(),Q(We=>(We+1)%re.length);return}if(le&&re.length>0&&de.key==="ArrowUp"){de.preventDefault(),Q(We=>We===0?re.length-1:We-1);return}if(le&&(de.key==="Enter"||de.key==="Tab")){de.preventDefault();const We=re[Z]??re[0];We&&ut(We);return}if(le&&de.key==="Escape"){de.preventDefault(),we(!1),Ue("");return}de.key!=="Enter"||de.shiftKey||(de.preventDefault(),Pt())},[se,rt,O,Ct,Pt,De,M,le,re,Z,ut]),fi=i.useCallback(()=>{if(pt.current){pt.current=!1;return}if(p){g(!1);return}typeof window<"u"&&window.innerWidth<=_s&&It.current?.focus({preventScroll:!0}),g(!0)},[p,g]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:It,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Ge,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":me?"true":"false",style:{right:Ee.x,bottom:Ee.y},onPointerDown:Re,onClick:fi,children:t.jsx(Oi,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:at,"data-testid":"quick-chat-panel",style:{...wt?{right:Ee.x+pe.right,bottom:be+pe.bottom,width:Ke.width,height:Ke.height}:{}},children:[wt&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Xe,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:Xe,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:Xe,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:Xe,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:Xe,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:Xe,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:Xe,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:Xe,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),v==="model"&&sn&&(()=>{const de=Gt?.provider??Wt?.modelProvider??"";return x==="mobile"&&sn.length>12&&de?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:sn,"aria-label":sn,children:t.jsx(Jn,{provider:de,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:sn,children:sn})})()]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:Hn,disabled:Qt,children:t.jsx(_n,{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(nn,{size:16})})]})]}),t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:[t.jsx("label",{htmlFor:"quick-chat-session-select",className:"visually-hidden",children:"Select session"}),t.jsxs("select",{id:"quick-chat-session-select",value:gt?.id??"",onChange:de=>Yt(de.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Qt?"Loading sessions…":"Select a session"}),Y.map(de=>t.jsx("option",{value:de.id,children:de.label},de.id))]})]}),N&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${w==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>j("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${w==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>j("agent"),children:"Agent"})]}),w==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:_,onChange:de=>D(de.target.value),"data-testid":"quick-chat-new-agent-select",children:u.map(de=>t.jsx("option",{value:de.id,children:DD(de)},de.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(ks,{id:"quick-chat-new-model-select",models:I,value:C,onChange:P,label:"Select model override",placeholder:A?"Loading models…":"Select a model",disabled:A||I.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:d})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{E(!1),j("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void In(),disabled:Qt||(w==="agent"?!_:!Ir(C||F||ee)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Ft,"data-testid":"quick-chat-messages",onScroll:ft,children:Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Zt?t.jsxs(t.Fragment,{children:[Tt.map(de=>t.jsx(cf,{message:de,forcePlain:de.role!=="user"&&Ie.has(de.id),mentionAgentsByName:ct,onToggleRender:ts},de.id)),He&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Bs("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")}),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:[Ot?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Bs(Ot,Ie.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Ie.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Ie.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>ts("__streaming__"),children:Ie.has("__streaming__")?t.jsx(Qd,{size:14}):t.jsx(ur,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Rt?"Thinking…":"Connecting…"}),gx(en,!0),Rt&&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:Rt})]})]})]}):xn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Tt.length===0&&!Ot&&!Rt&&!Zt&&!He?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Tt.map(de=>t.jsx(cf,{message:de,forcePlain:de.role!=="user"&&Ie.has(de.id),mentionAgentsByName:ct,onToggleRender:ts},de.id)),He&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Bs("Available commands:\n- `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),Ne&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:it,children:[t.jsx(cn,{size:14}),"Latest"]}),Te.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Te.map((de,We)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${We}`,children:[de.previewUrl?t.jsx("img",{src:de.previewUrl,alt:de.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:de.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${We}`,"aria-label":`Remove ${de.file.name}`,onClick:()=>Nn(We),children:"×"})]},`${de.file.name}-${We}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${ce?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Qn,onDragOver:es,onDragLeave:W,onDrop:qe,children:[t.jsx("input",{ref:qt,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:de=>{gn(de.target.files),de.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:()=>qt.current?.click(),children:t.jsx($f,{size:16})}),t.jsx("input",{ref:_t,type:"text",value:M,onChange:Mt,onKeyDown:Hi,onKeyUp:ps,onClick:Sn,onBlur:an,onFocus:An,onPaste:ms,onTouchStart:de=>{typeof window>"u"||window.innerWidth>_s||document.activeElement!==de.currentTarget&&(de.preventDefault(),de.currentTarget.focus({preventScroll:!0}))},placeholder:Ye,disabled:Jt,"data-testid":"quick-chat-input"}),Zt?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:de=>{typeof window>"u"||window.innerWidth>_s||(de.preventDefault(),de.pointerType&&de.pointerType!=="mouse"&&(he.current=!0,Ut()))},onTouchStart:de=>{typeof window>"u"||window.innerWidth>_s||(de.preventDefault(),he.current=!0,Ut())},onMouseDown:de=>{typeof window>"u"||window.innerWidth>_s||de.preventDefault()},onClick:()=>{if(he.current){he.current=!1;return}Ut()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Si,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:de=>{typeof window>"u"||window.innerWidth>_s||(de.preventDefault(),de.pointerType&&de.pointerType!=="mouse"&&(he.current=!0,bn(),vn(),Pt()))},onTouchStart:de=>{typeof window>"u"||window.innerWidth>_s||(de.preventDefault(),he.current=!0,bn(),vn(),Pt())},onMouseDown:de=>{typeof window>"u"||window.innerWidth>_s||de.preventDefault()},onClick:()=>{if(he.current){he.current=!1;return}Pt()},disabled:Jt||M.trim().length===0&&Te.length===0,"data-testid":"quick-chat-send",children:t.jsx(pa,{size:16})})]}),t.jsx(CD,{agents:u,filter:X,highlightedIndex:O,visible:se,onSelect:Ct,position:"above"}),t.jsx(RD,{visible:De.mentionActive&&!se,position:fe,files:De.files,selectedIndex:De.selectedIndex,onSelect:de=>{const We=De.selectFile(de,M);T(We),De.dismissMention(),Ce(!1),_t.current?.focus()},loading:De.loading}),le&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:K?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):re.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:ge?"No skills found":"No skills available"}):re.map((de,We)=>t.jsxs("button",{type:"button",role:"option","aria-selected":We===Z,className:`chat-skill-menu-item${We===Z?" chat-skill-menu-item--highlighted":""}`,onMouseDown:mt=>mt.preventDefault(),onMouseEnter:()=>Q(We),onClick:()=>ut(de),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:de.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:de.relativePath,children:de.relativePath})]},de.id))}),fn&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${cs}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:un,children:"×"})]})]})})]})]})}function $r(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function df(e){return e.status==="generating"||e.status==="awaiting_input"}function Dr(e){return e==="complete"||e==="error"}function GD(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=gr(),u=i.useCallback(()=>{su(e).then(p=>{const g=p.filter(v=>{const b=$r(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of g)x.set(v.id,$r(v.updatedAt));a.current=x,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);i.useEffect(()=>{d(),u()},[u,d]),i.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const x=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=a.current.get(v.sessionId)??0;if(b<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!Dr(v.status)&&r.current.delete(v.sessionId),Dr(v.status)){x.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,b);continue}const N=x.get(v.sessionId),E=v.type??N?.type,w=v.title??N?.title;if(!N&&(!E||!w))continue;const j={id:v.sessionId,type:E??"planning",status:v.status,title:w??"AI Session",projectId:v.projectId??N?.projectId??e??null,lockedByTab:v.owningTabId??N?.lockedByTab??null,updatedAt:v.updatedAt??N?.updatedAt??new Date(b).toISOString()},_=x.get(v.sessionId);(!_||_.status!==j.status||_.title!==j.title||_.type!==j.type||_.projectId!==j.projectId||_.lockedByTab!==j.lockedByTab||_.updatedAt!==j.updatedAt)&&(x.set(v.sessionId,j),a.current.set(v.sessionId,b),g=!0)}return g?[...x.values()].sort((v,b)=>$r(b.updatedAt)-$r(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const b=JSON.parse(v.data),y=$r(b.updatedAt)||Date.now();s(S=>{const N=a.current.get(b.id)??0;if(y<N)return S;const E=r.current.get(b.id);if(E!==void 0&&y<=E)return S;if(E!==void 0&&y>E&&!Dr(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),Dr(b.status))return S.filter(j=>j.id!==b.id);const w=S.findIndex(j=>j.id===b.id);if(w>=0){const j=[...S];return j[w]=b,j}return df(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),Dr(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(N=>N.id!==b))}catch{}};return ai(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":x},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,v=Ca();let b=!1;if(x==="planning")try{await qf(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await Kf(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await Qf(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await Xf(p)}catch{}s(S=>S.filter(N=>N.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>df(p)),[n]),f=i.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:u}}const _l="fusion:hide-session-banners",Gd="fusion:session-banner-pref-changed";function JD(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(_l)==="1"}catch{return!1}}function YD(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===_l&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Gd,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Gd,s)}}function fz(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(_l,"1"):window.localStorage.removeItem(_l),window.dispatchEvent(new Event(Gd))}catch{}}function QD(){return i.useSyncExternalStore(YD,JD,()=>!1)}function ws(e){return{...e,column:dg(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function uf(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function XD(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 rd(e,n){if(uf(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return XD(e,n);const a=uf(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:a>0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function ZD(e){const n=e?.projectId,s=e?.searchQuery,a=e?.sseEnabled??!0,[r,o]=i.useState([]),[l,c]=i.useState(!1),d=i.useRef(l);d.current=l;const u=i.useRef(r),m=i.useRef(0),h=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),x=i.useRef(0),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=i.useCallback(async ee=>{const J=++m.current,M=n,T=ee?.searchQueryOverride??f.current,L=ee?.includeArchivedOverride??d.current;try{const k=await Kw(void 0,void 0,M,T,L);if(m.current!==J||n!==M)return;o(k.map(ws)),g.current=Date.now()}catch{if(m.current!==J||n!==M)return;if(ee?.clearOnError){o([]);return}o(k=>k)}},[n]);p.current=y;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),N=i.useRef(s);i.useEffect(()=>{if(s===void 0&&N.current===void 0)return;N.current=s;const ee=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(ee)},[s]),i.useEffect(()=>{y({clearOnError:!0});const ee=()=>{if(document.visibilityState!=="visible")return;const J=Date.now();J-h.current<b||(h.current=J,y())};return document.addEventListener("visibilitychange",ee),()=>{document.removeEventListener("visibilitychange",ee)}},[y]),i.useEffect(()=>{if(a===!1)return;const ee=x.current,J=n?`?projectId=${encodeURIComponent(n)}`:"",M=()=>x.current!==ee;let T=!0;const L=ge=>{if(M())return;const Ue=ws(JSON.parse(ge.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(Z=>{const Q=Z.findIndex(B=>B.id===Ue.id);if(Q===-1)return[...Z,Ue];const X=Z[Q],ie=rd(X,Ue);if(ie===X)return Z;const se=[...Z];return se[Q]=ie,se}),g.current=Date.now()},k=ge=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ue,to:Z}=JSON.parse(ge.data),Q=ws(Ue);o(X=>X.map(ie=>ie.id===Q.id?{...Q,column:dg(Z,Q.column)}:ie)),g.current=Date.now()},K=ge=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ue=ws(JSON.parse(ge.data));o(Z=>Z.map(Q=>Q.id!==Ue.id?Q:rd(Q,Ue))),g.current=Date.now()},oe=ge=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ue=ws(JSON.parse(ge.data));o(Z=>Z.filter(Q=>Q.id!==Ue.id))},le=ge=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ue}=JSON.parse(ge.data),Z=ws(Ue);o(Q=>Q.map(X=>X.id===Z.id?{...Z,column:"done"}:X))},we=ai(`/api/events${J}`,{events:{"task:created":L,"task:moved":k,"task:updated":K,"task:deleted":oe,"task:merged":le},onReconnect:()=>{T&&(M()||p.current())}});return()=>{T=!1,we()}},[n,a]);const E=i.useCallback(async ee=>{const J=ws(await ml(ee,n));return o(M=>M.some(T=>T.id===J.id)?M:[...M,J]),J},[n]),w=i.useCallback(async(ee,J,M)=>ws(await Jw(ee,J,n,M)),[n]),j=i.useCallback(async ee=>ws(await Uf(ee,n)),[n]),_=i.useCallback(async(ee,J)=>ws(await Yw(ee,n,J)),[n]),D=i.useCallback(async ee=>Qw(ee,n),[n]),C=i.useCallback(async ee=>ws(await Xw(ee,n)),[n]),P=i.useCallback(async ee=>ws(await Zw(ee,n)),[n]),I=i.useCallback(async ee=>{const J=ws(await ek(ee,n));return o(M=>M.some(T=>T.id===J.id)?M:[...M,J]),J},[n]),H=i.useCallback(async(ee,J)=>{const M=u.current.find(L=>L.id===ee),T=M?{...M,...J,updatedAt:new Date().toISOString()}:void 0;T&&o(L=>L.map(k=>k.id===ee?T:k));try{const L=ws(await Ci(ee,J,n));return o(k=>k.map(K=>K.id===ee?L:K)),L}catch(L){throw M&&o(k=>k.map(K=>K.id===ee?M:K)),L}},[n]),A=i.useCallback(async ee=>{const J=ws(await nk(ee,n));return o(M=>M.map(T=>T.id===ee?J:T)),J},[n]),$=i.useCallback(async ee=>{const J=ws(await sk(ee,n));return o(M=>M.map(T=>T.id===ee?J:T)),J},[n]),F=i.useCallback(async()=>{const J=(await ik(n)).map(ws);return o(M=>M.map(T=>J.find(k=>k.id===T.id)||T)),J},[n]),G=i.useCallback(ee=>{if(ee.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const J=ee.map(ws);o(M=>{let T=M;for(const L of J){const k=T.findIndex(le=>le.id===L.id);if(k===-1){T===M&&(T=[...M]),T.push(L);continue}const K=T[k],oe=rd(K,L);oe!==K&&(T===M&&(T=[...M]),T[k]=oe)}return T}),g.current=Date.now()},[]);return{tasks:r,createTask:E,moveTask:w,pauseTask:j,deleteTask:_,mergeTask:D,retryTask:C,resetTask:P,duplicateTask:I,updateTask:H,archiveTask:A,unarchiveTask:$,archiveAllDone:F,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:G,lastFetchTimeMs:g.current}}const eL=5e3,tL=1e3;function nL(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const f=await sm();n(f)}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const x=performance.now();try{const v=await sm(),b=Math.round(performance.now()-x);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${b}ms (${v.length} projects)`),f||(n(v),o(null))}catch(v){const b=Math.round(performance.now()-x);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${v instanceof Error?v.message:String(v)}`),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<tL||(c.current=x,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},eL),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await yN(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await CN(f,p);return n(x=>x.map(v=>v.id===f?g:v)),g},[]),h=i.useCallback(async f=>{await Gf(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h}}const sL="kb-dashboard-current-project";function iL(e){return e??"local"}function aL(e,n={}){const{nodeId:s=null}=n,[a,r]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useRef(!1),u=i.useRef(null),m=iL(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await ja();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const v=u.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(sL);if(b){const y=JSON.parse(b);y?.id&&e.some(N=>N.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await $n({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(x=>x.id===a.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,$n({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,m]);const h=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[m]:p.id};u.current=g,$n({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,$n({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const xx=i.createContext(null);function rL({children:e}){const[n,s]=i.useState([]),a=i.useRef(0),r=i.useRef(new Map),o=i.useCallback(c=>{const d=r.current.get(c);d!==void 0&&(clearTimeout(d),r.current.delete(c)),s(u=>u.filter(m=>m.id!==c))},[]),l=i.useCallback((c,d="info")=>{const u=a.current++;s(h=>[...h,{id:u,message:c,type:d}]);const m=setTimeout(()=>o(u),4e3);r.current.set(u,m)},[o]);return i.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),ol.createElement(xx.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function oL(){const e=i.useContext(xx);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const vx="kb-dashboard-theme-mode",yx="kb-dashboard-color-theme",wx="kb-dashboard-font-scale-pct",Jd=100,lL=85,cL=125,kx=[...OS],Yd="theme-data",od="theme-data.css";function dL(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${od}`:e.replace(/\/[^/]+$/,`/${od}`):`/${od}`}const Fs=typeof window<"u",uL=Fs?i.useLayoutEffect:i.useEffect;function jx(e){return e==="dark"||e==="light"||e==="system"}function mf(){if(!Fs)return"dark";try{const e=localStorage.getItem(vx);if(jx(e))return e}catch{}return"dark"}function hf(){if(!Fs)return"default";try{const e=localStorage.getItem(yx);if(e&&kx.includes(e))return e}catch{}return"default"}function pf(e){if(Fs)try{localStorage.setItem(vx,e)}catch{}}function ff(e){if(Fs)try{localStorage.setItem(yx,e)}catch{}}function io(e){return typeof e!="number"||!Number.isFinite(e)?Jd:Math.min(cL,Math.max(lL,Math.round(e)))}function gf(){if(!Fs)return Jd;try{const e=Number(localStorage.getItem(wx));return io(e)}catch{return Jd}}function bf(e){if(Fs)try{localStorage.setItem(wx,String(io(e)))}catch{}}function mL(e,n){return e==="system"?n?"dark":"light":e}function hL(e,n,s,a){if(!Fs)return;const r=mL(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${io(s)}%`}function xf(){if(!Fs)return;const e=dL(),n=document.getElementById(Yd);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=Yd,document.head.appendChild(s)}function vf(){if(!Fs)return;const e=document.getElementById(Yd);e&&e.remove()}function pL(){const[e,n]=i.useState(()=>mf()),[s,a]=i.useState(()=>hf()),[r,o]=i.useState(()=>gf()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Fs?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=i.useRef(e),h=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),x=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Fs||!l)return;let S=!1;return ja().then(N=>{if(!S&&(jx(N.themeMode)&&!p.current&&(m.current!==N.themeMode&&(m.current=N.themeMode,n(N.themeMode)),mf()!==N.themeMode&&pf(N.themeMode)),N.colorTheme&&kx.includes(N.colorTheme)&&!g.current&&(h.current!==N.colorTheme&&(h.current=N.colorTheme,a(N.colorTheme)),hf()!==N.colorTheme&&ff(N.colorTheme)),!x.current)){const E=io(N.dashboardFontScalePct);f.current!==E&&(f.current=E,o(E)),gf()!==E&&bf(E)}}).catch(N=>{console.warn("[useTheme] Failed to hydrate theme from global settings",N)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Fs)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),N=E=>{u(E.matches)};return S.addEventListener("change",N),()=>S.removeEventListener("change",N)},[]),uL(()=>{hL(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Fs||l||(s!=="default"?xf():vf())},[s,l]);const v=i.useCallback(S=>{p.current=!0,m.current=S,n(S),pf(S),$n({themeMode:S}).catch(N=>{console.warn("[useTheme] Failed to persist themeMode to global settings",N)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),ff(S),S!=="default"?xf():vf(),$n({colorTheme:S}).catch(N=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",N)})},[]),y=i.useCallback(S=>{const N=io(S);x.current=!0,f.current=N,o(N),bf(N),$n({dashboardFontScalePct:N}).catch(E=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",E)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function fL(e){const{planningSessions:n}=e,[s,a]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(void 0),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,x]=i.useState(void 0),[v,b]=i.useState(null),[y,S]=i.useState("definition"),[N,E]=i.useState(null),[w,j]=i.useState(!1),[_,D]=i.useState(void 0),[C,P]=i.useState(!1),[I,H]=i.useState(!1),[A,$]=i.useState(!1),[F,G]=i.useState(null),[ee,J]=i.useState(!1),[M,T]=i.useState(!1),[L,k]=i.useState(void 0),[K,oe]=i.useState(!1),[le,we]=i.useState(!1),[ge,Ue]=i.useState("project"),[Z,Q]=i.useState(!1),[X,ie]=i.useState(!1),[se,B]=i.useState(!1),[O,ke]=i.useState(!1),[ae,te]=i.useState(!1),[Ie,Oe]=i.useState(!1),[He,$e]=i.useState(!1),Te=!!(v||w||s||r||m||M||K||le||Z||X||se||ae||O||A||ee||C||I||Ie||He),ue=i.useCallback(()=>a(!0),[]),ce=i.useCallback(()=>a(!1),[]),Ae=i.useCallback(()=>o(!0),[]),Ne=i.useCallback(St=>{c(St),o(!0)},[]),ye=i.useCallback(()=>{const St=n[0];St&&(u(St.id),o(!0))},[n]),Ce=i.useCallback(St=>{u(St),o(!0)},[]),fe=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),Pe=i.useCallback(St=>{p(St),h(!0)},[]),De=i.useCallback(St=>{x(St),h(!0)},[]),dt=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),pt=i.useCallback((St,z="definition",he)=>{b(St),S(z),E(he?.origin??null)},[]),lt=i.useCallback(St=>{b(St),S("changes"),E(null)},[]),vt=i.useCallback(St=>{b(z=>z&&{...z,...St})},[]),_e=i.useCallback(()=>{b(null),E(null)},[]),Fe=i.useCallback(St=>{D(St),j(!0)},[]),bt=i.useCallback(()=>{j(!1),D(void 0)},[]),ht=i.useCallback(()=>P(!0),[]),Ee=i.useCallback(()=>P(!1),[]),me=i.useCallback(()=>H(!0),[]),Re=i.useCallback(()=>H(!1),[]),be=i.useCallback(St=>{G(St??null),$(!0)},[]),Ke=i.useCallback(()=>{$(!1),G(null)},[]),pe=i.useCallback(()=>J(!0),[]),Xe=i.useCallback(()=>J(!1),[]),wt=i.useCallback(()=>{T(St=>!St)},[]),gt=i.useCallback(()=>{T(!1),k(void 0)},[]),Tt=i.useCallback(()=>oe(!0),[]),Zt=i.useCallback(()=>oe(!1),[]),Ot=i.useCallback(()=>we(!0),[]),Rt=i.useCallback(()=>we(!1),[]),en=i.useCallback(St=>{Ue(St)},[]),zt=i.useCallback(()=>Q(!0),[]),Qt=i.useCallback(()=>Q(!1),[]),xn=i.useCallback(()=>ie(!0),[]),Kt=i.useCallback(()=>ie(!1),[]),Ut=i.useCallback(()=>B(!0),[]),fn=i.useCallback(()=>B(!1),[]),un=i.useCallback(()=>ke(!0),[]),tn=i.useCallback(()=>ke(!1),[]),Vt=i.useCallback(()=>te(!0),[]),mn=i.useCallback(()=>te(!1),[]),xe=i.useCallback(async(St,z)=>{te(!1),k(z),T(!0)},[]),Le=i.useCallback(()=>Oe(!0),[]),Ve=i.useCallback(()=>Oe(!1),[]),at=i.useCallback(()=>$e(!0),[]),Ge=i.useCallback(()=>$e(!1),[]),Ft=i.useCallback((St,z)=>{z(`Created ${St.id} from planning mode`,"success"),o(!1),c(null)},[]),_t=i.useCallback((St,z)=>{const he=St.map(st=>st.id).join(", ");z(`Created ${he} from planning mode`,"success"),o(!1),c(null)},[]),qt=i.useCallback((St,z)=>{const he=St.map(st=>st.id).join(", ");z(`Created ${he} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,detailTaskOrigin:N,settingsOpen:w,settingsInitialSection:_,schedulesOpen:C,githubImportOpen:I,usageOpen:A,usageAnchorRect:F,systemStatsOpen:ee,terminalOpen:M,terminalInitialCommand:L,filesOpen:K,todosOpen:le,fileBrowserWorkspace:ge,activityLogOpen:Z,gitManagerOpen:X,workflowStepsOpen:se,agentsOpen:O,scriptsOpen:ae,setupWizardOpen:Ie,modelOnboardingOpen:He,anyModalOpen:Te,openNewTask:ue,closeNewTask:ce,openPlanning:Ae,openPlanningWithInitialPlan:Ne,resumePlanning:ye,openPlanningWithSession:Ce,closePlanning:fe,openSubtaskBreakdown:Pe,openSubtaskWithSession:De,closeSubtask:dt,openDetailTask:pt,openDetailWithChangesTab:lt,updateDetailTask:vt,closeDetailTask:_e,openSettings:Fe,closeSettings:bt,openSchedules:ht,closeSchedules:Ee,openGitHubImport:me,closeGitHubImport:Re,openUsage:be,closeUsage:Ke,openSystemStats:pe,closeSystemStats:Xe,toggleTerminal:wt,closeTerminal:gt,openFiles:Tt,closeFiles:Zt,openTodos:Ot,closeTodos:Rt,setFileWorkspace:en,openActivityLog:zt,closeActivityLog:Qt,openGitManager:xn,closeGitManager:Kt,openWorkflowSteps:Ut,closeWorkflowSteps:fn,openAgents:un,closeAgents:tn,openScripts:Vt,closeScripts:mn,runScript:xe,openSetupWizard:Le,closeSetupWizard:Ve,openModelOnboarding:at,closeModelOnboarding:Ge,onPlanningTaskCreated:Ft,onPlanningTasksCreated:_t,onSubtaskTasksCreated:qt}}function gL(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(!1),[x,v]=i.useState(!1),[b,y]=i.useState(!1),[S,N]=i.useState({}),[E,w]=i.useState(!1),[j,_]=i.useState(!1),[D,C]=i.useState(!1),[P,I]=i.useState(!1),[H,A]=i.useState(!1),[$,F]=i.useState(!0),G=i.useCallback(async()=>{const[k,K]=await Promise.allSettled([ok(e),Ol(e)]);if(k.status==="fulfilled"&&(s(k.value.maxConcurrent),r(k.value.rootDir)),K.status==="fulfilled"){const oe=K.value;l(!!oe.autoMerge),d(!!oe.globalPause),m(!!oe.enginePaused),v(!!oe.prAuthAvailable),f(oe.taskStuckTimeoutMs),g(oe.showQuickChatFAB===!0),N(oe.experimentalFeatures??{});const le=oe.experimentalFeatures??{};w(le.insights===!0),_(le.roadmap===!0),C(le.memoryView===!0),I(le.devServerView===!0||le.devServer===!0),A(le.todoView===!0);const we=oe.autoReloadOnVersionChange!==!1;F(we),Zl(we)}y(!0)},[e]);i.useEffect(()=>{y(!1),N({}),w(!1),_(!1),C(!1),I(!1),A(!1),G()},[G]);const ee=i.useCallback(async()=>{const k=!o;l(k);try{await jo({autoMerge:k},e)}catch{l(!k)}},[o,e]),J=i.useCallback(async()=>{const k=!c;d(k);try{await jo({globalPause:k,globalPauseReason:k?"manual":void 0},e)}catch{d(!k)}},[c,e]),M=i.useCallback(async()=>{const k=!u;m(k);try{await jo({enginePaused:k},e)}catch{m(!k)}},[u,e]),T=i.useCallback(async()=>{const k=!p;g(k);try{await jo({showQuickChatFAB:k},e)}catch{g(!k)}},[p,e]),L=i.useCallback(async()=>{const k=!$;F(k),Zl(k);try{await $n({autoReloadOnVersionChange:k})}catch{F(!k),Zl(!k)}},[$]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,settingsLoaded:b,experimentalFeatures:S,insightsEnabled:E,roadmapEnabled:j,memoryEnabled:D,devServerEnabled:P,todosEnabled:H,autoReloadOnVersionChange:$,toggleAutoMerge:ee,toggleGlobalPause:J,toggleEnginePause:M,toggleShowQuickChatFAB:T,toggleAutoReloadOnVersionChange:L,refresh:G}}function bL(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(null);return i.useEffect(()=>{const f=new URLSearchParams(window.location.search),p=f.get("project"),g=f.get("task");if(!g||a)return;if(p){const v=s.find(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(u.current)return;u.current=!0,er(g,p??n).then(v=>{c(v),m.current=g}).catch(()=>{l(`Task ${g} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(m.current){const f=new URLSearchParams(window.location.search);f.delete("task");const p=f.toString(),g=window.history.state??{};window.history.replaceState(g,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}d()},[d])}}function xL(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{$s().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,a(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,a(()=>p);try{await $n({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,a(()=>h),g}},[]),u=i.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 $n({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function vL({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:a}){const r=i.useRef(!1),o=i.useRef(n);o.current=n,i.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Zr().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return ja().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!dr()?l=!0:!u&&!dr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ti("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ti("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const yf="kb-update-banner-dismissed";function yL(){const[e,n]=i.useState(!0),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1);i.useEffect(()=>{const h=sessionStorage.getItem(yf)==="true";u(h);let f=!1;return lk().then(p=>{f||p.disabled||(a(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=i.useCallback(()=>{u(!0),sessionStorage.setItem(yf,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const wL=["board","list","agents","missions","chat","documents","research","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function kL(e){return e!==null&&wL.includes(e)}function wf(e){return e!==null&&(kL(e)||Ga(e))}function jL(e){return e==="devserver"?"dev-server":e}function NL(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:a,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:d,setThemeMode:u}=e,[m,h]=i.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[f,p]=i.useState(()=>{const b=ss("kb-dashboard-task-view");return wf(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=ss("kb-dashboard-task-view",r?.id);if(wf(b)){const y=!g.current&&b==="devserver";p(y?"devserver":jL(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{xs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{n||a||r&&m==="overview"&&h("project")},[n,a,r,m]),i.useEffect(()=>{if(n||a||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,a,r,l,c]);const x=i.useCallback(b=>{p(b)},[]),v=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),S=b[(y+1)%b.length];u(S)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function SL(e){const{enabled:n}=e,s=i.useRef([]),a=i.useRef(!1),r=i.useRef(n);r.current=n;const o=i.useCallback(c=>{if(!r.current||a.current)return;const d=s.current[s.current.length-1];if(d){const h=d.type==="modal"?d.close:d.revert,f=c.type==="modal"?c.close:c.revert;if(h===f)return}s.current.push(c);const u=s.current.length,m=typeof window<"u"&&window.history.state?window.history.state:{};window.history.pushState({...m,navIndex:u},"")},[]),l=i.useCallback(c=>{if(!r.current||s.current.length===0)return;s.current[s.current.length-1]=c;const d=s.current.length,u=typeof window<"u"&&window.history.state?window.history.state:{};window.history.replaceState({...u,navIndex:d},"")},[]);return i.useEffect(()=>{if(typeof window>"u")return;const c=d=>{if(!r.current)return;const u=d.state?.navIndex??0,m=s.current.length;if(u>=m)return;const h=m-u;if(!(h<=0)){a.current=!0;try{for(let f=0;f<h;f++){const p=s.current.pop();p&&(p.type==="modal"?p.close():p.revert())}}finally{a.current=!1}}};return window.addEventListener("popstate",c),()=>{window.removeEventListener("popstate",c)}},[]),{pushNav:o,replaceCurrent:l}}const ld=new Map,CL=6e4;function EL(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),[c,d]=i.useState(0),u=i.useRef(!1),m=i.useCallback(()=>{const h=e??"default";ld.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=ld.get(h);if(g&&Date.now()<g.expiresAt){if(f)return;s(g.views),r(!1);return}u.current||r(!0),l(null);try{const x=await W1(e);if(f)return;ld.set(h,{views:x,expiresAt:Date.now()+CL}),s(x)}catch(x){if(f)return;l(x instanceof Error?x.message:"Failed to fetch plugin dashboard views")}finally{f||(r(!1),u.current=!0)}}return p(),()=>{f=!0}},[e,c]),i.useMemo(()=>({views:n,loading:a,error:o,refetch:m}),[n,a,o,m])}function _L({taskView:e}){return t.jsx(SS,{viewId:e})}function ML(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=i.useCallback(_=>{n(_),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),x=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{m()},[m]),b=i.useCallback(_=>{h(),n(_),a("project"),d(`Project ${_.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),S=i.useCallback(async _=>{try{await NN(_.id),d(`Project ${_.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${_.name}`,"error")}},[d,o]),N=i.useCallback(async _=>{try{await SN(_.id),d(`Project ${_.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${_.name}`,"error")}},[d,o]),E=i.useCallback(async _=>{try{await Gf(_.id),d(`Project ${_.name} removed`,"success"),r?.id===_.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${_.name}`,"error")}},[r,s,a,d,o]),w=i.useCallback(async _=>{try{await l(_)}catch{d("Failed to update favorites","error")}},[l,d]),j=i.useCallback(async _=>{try{await c(_)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:N,handleRemoveProject:E,handleToggleFavorite:w,handleToggleModelFavorite:j}}function AL(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:a,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=i.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=i.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=i.useCallback(p=>{s([p]),a(p,l)},[l,s,a]),m=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=i.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=i.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:d,handlePlanningTaskCreated:u,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}async function PL(e){return zl("/health",{nodeId:e})}async function TL(e){return zl("/projects",{nodeId:e})}async function RL(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),zl(`/tasks?${a.toString()}`,{nodeId:e})}async function IL(e,n){return zl(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function gz(e){return R(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function bz(e){return R(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function xz(e){return R(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function vz(e){return R(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function $L(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),x=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,h(!0),p(null);try{const y=[PL(e),TL(e)];s&&(y.push(RL(e,s,a)),y.push(IL(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const N=S[0],E=S[1];if(N.status==="rejected"){p(`Failed to fetch node health: ${N.reason}`),h(!1);return}if(u(N.value),E.status==="rejected"){p(`Failed to fetch projects: ${E.reason}`),h(!1);return}if(o(E.value),s&&S[2]){const w=S[2];if(w.status==="rejected"){p(`Failed to fetch tasks: ${w.reason}`),h(!1);return}w.status==="fulfilled"&&c(w.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(x(),()=>{g.current?.abort()}),[x]);const v=i.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:v}}function DL(e){const[n,s]=i.useState(!1),[a,r]=i.useState(null);return i.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return ai(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:a}}const LL="fusion-dashboard-current-node",Nx=i.createContext(null);function OL({children:e}){const[n,s]=i.useState(null),[a,r]=i.useState(!0),o=i.useRef(!1),l=i.useRef(void 0);i.useEffect(()=>{let m=!1;async function h(){try{const f=await ja();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(LL);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await $n({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,$n({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,$n({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,$n({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(Nx.Provider,{value:u,children:e})}function FL(){const e=i.useContext(Nx);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const Sx={host:"web",activeProfileId:null,profiles:[]},Cx=i.createContext({shellApi:null,state:Sx,ready:!0,openConnectionManagerSignal:0});function zL({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(Sx),[r,o]=i.useState(!n),[l,c]=i.useState(0);return i.useEffect(()=>{if(!n)return;let d=!1;n.getState().then(h=>{d||(a(h),o(!0))});const u=n.subscribe(h=>{a(h)}),m=()=>{c(h=>h+1)};return window.addEventListener("shell:open-connection-manager",m),()=>{d=!0,u(),window.removeEventListener("shell:open-connection-manager",m)}},[n]),t.jsx(Cx.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function UL(){return i.useContext(Cx)}function BL(){return UL()}function HL(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function qL({open:e,shellApi:n,shellState:s,onComplete:a}){const[r,o]=i.useState(s.desktopMode??"remote"),[l,c]=i.useState("Remote Server"),[d,u]=i.useState(""),[m,h]=i.useState(""),[f,p]=i.useState(null),[g,x]=i.useState(!1),[v,b]=i.useState(!1),y=s.host==="desktop-shell";i.useEffect(()=>{y&&o(s.desktopMode??"remote")},[y,s.desktopMode]);const S=i.useMemo(()=>y&&r==="local"?!0:d.trim().length>0,[y,r,d]);return e?t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-onboarding-modal",children:[t.jsx("div",{className:"modal-header",children:t.jsx("h2",{children:"Welcome to Fusion"})}),t.jsxs("div",{className:"native-shell-onboarding-body",children:[t.jsx("p",{children:"Fusion helps you plan, run, and review AI-assisted engineering work."}),y&&t.jsxs("div",{className:"native-shell-onboarding-mode-row",children:[t.jsx("button",{type:"button",className:`btn ${r==="local"?"btn-primary":""}`,onClick:()=>o("local"),children:"Local Fusion"}),t.jsx("button",{type:"button",className:`btn ${r==="remote"?"btn-primary":""}`,onClick:()=>o("remote"),children:"Remote Server"})]}),(!y||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null),x(!0);try{const N=await n.startQrScan();u(N.serverUrl),h(N.authToken??"")}catch(N){p(N.message)}finally{x(!1)}},disabled:g,children:g?"Scanning…":"Scan QR"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:"Profile name"}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:l,onChange:N=>c(N.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:d,onChange:N=>u(N.target.value),placeholder:"https://your-fusion-host"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:m,onChange:N=>h(N.target.value)})]}),f&&t.jsx("p",{className:"form-error",role:"alert",children:f})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",disabled:!S||v,onClick:async()=>{p(null),b(!0);try{if(y&&r==="local"){await n.setDesktopMode("local"),a();return}const N=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(y&&await n.setDesktopMode("remote"),await n.setActiveProfile(N.id),typeof window<"u"&&s.host!=="web"){window.location.href=HL(N.serverUrl,N.authToken??null);return}a()}catch(N){p(N.message)}finally{b(!1)}},children:v?"Saving…":"Continue"})})]})}):null}function VL({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(b=>b.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState(null),[c,d]=i.useState({}),[u,m]=i.useState(null);if(!e)return null;const h=o==="__new__",f=h?null:s.profiles.find(b=>b.id===o)??r,p=c.name??f?.name??"",g=c.serverUrl??f?.serverUrl??"",x=c.authToken??f?.authToken??"",v=async()=>{m(null);try{const b=new URL(g.trim());if(!/^https?:$/.test(b.protocol))throw new Error("Server URL must use http or https");const y=await n.saveProfile({id:h?void 0:o??f?.id,name:p||"Remote Server",serverUrl:g,authToken:x||null});await n.setActiveProfile(y.id),l(y.id),d({})}catch(b){m(b.message)}};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":"Connection Manager",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Connection Manager"}),t.jsx("button",{type:"button",className:"modal-close",onClick:a,"aria-label":"Close",children:"×"})]}),s.host==="desktop-shell"&&t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:`btn ${s.desktopMode==="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("local"),children:"Local"}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:"Remote"})]}),t.jsx("div",{className:"native-shell-connection-manager__profiles",children:s.profiles.map(b=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:b.name}),t.jsx("div",{className:"settings-muted",children:b.serverUrl})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Edit ${b.name}`,onClick:()=>{l(b.id),d(b)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${b.name}`,onClick:()=>void n.setActiveProfile(b.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${b.name}`,onClick:()=>void n.deleteProfile(b.id),children:"Delete"})]})]},b.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),m(null)},children:"Add connection"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void n.startQrScan(),children:"Scan QR"})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:"Name"}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:p,onChange:b=>d(y=>({...y,name:b.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-connection-manager-url",className:"input",value:g,onChange:b=>d(y=>({...y,serverUrl:b.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-connection-manager-token",className:"input",type:"password",value:x??"",onChange:b=>d(y=>({...y,authToken:b.target.value}))}),u&&t.jsx("p",{className:"form-error",role:"alert",children:u})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Close"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void v(),disabled:!g.trim(),children:"Save"})]})]})})}function WL({state:e,onManage:n}){const s=e.profiles.find(r=>r.id===e.activeProfileId)??null,a=e.host==="desktop-shell"&&e.desktopMode==="local"?"Local Fusion":s?.name??"Disconnected";return t.jsxs("button",{type:"button",className:"btn native-shell-status",onClick:n,"data-testid":"native-shell-status-btn",children:[t.jsx("span",{className:`status-dot ${s||e.desktopMode==="local"?"status-dot--online":"status-dot--error"}`,"aria-hidden":"true"}),t.jsx("span",{className:"native-shell-status__label",children:a})]})}function KL({open:e}){const[n,s]=i.useState(""),a=i.useRef(null);i.useEffect(()=>{e&&a.current?.focus()},[e]);const r=i.useCallback(()=>{const l=n.trim();l&&(Lw(l),window.location.reload())},[n]),o=i.useCallback(()=>{Ow(),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:a,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 GL=200,JL=i.lazy(()=>Rn(()=>import("./AgentsView-Deh125ss.js"),__vite__mapDeps([21,1,3,4,22,13,5,6,23])).then(e=>({default:e.AgentsView}))),YL=i.lazy(()=>Rn(()=>import("./DocumentsView-DIpg3NSP.js"),__vite__mapDeps([24,1,5,6,25])).then(e=>({default:e.DocumentsView}))),QL=i.lazy(()=>Rn(()=>import("./InsightsView-jKjEFAx_.js"),__vite__mapDeps([26,1,19,5,6,27])).then(e=>({default:e.InsightsView}))),XL=i.lazy(()=>Rn(()=>import("./ResearchView-_BHXUv2j.js"),__vite__mapDeps([28,1,5,6,29])).then(e=>({default:e.ResearchView}))),ZL=i.lazy(()=>Rn(()=>import("./NodesView-Di2SvOhg.js"),__vite__mapDeps([30,1,22,5,6,31])).then(e=>({default:e.NodesView}))),eO=i.lazy(()=>Rn(()=>import("./ChatView-7D_RQDqT.js"),__vite__mapDeps([32,1,5,6])).then(e=>({default:e.ChatView}))),tO=i.lazy(()=>Rn(()=>import("./RoadmapsView-DHWjUoc8.js"),__vite__mapDeps([33,1,5,6,34])).then(e=>({default:e.RoadmapsView}))),nO=i.lazy(()=>Rn(()=>import("./SkillsView-hDpTBdFT.js"),__vite__mapDeps([35,1,5,6,36])).then(e=>({default:e.SkillsView}))),sO=i.lazy(()=>Rn(()=>import("./MemoryView-nXlTqebk.js"),__vite__mapDeps([37,1,17,18,5,6,38])).then(e=>({default:e.MemoryView}))),iO=i.lazy(()=>Rn(()=>import("./DevServerView-C9lzHrcT.js"),__vite__mapDeps([39,1,5,6,40])).then(e=>({default:e.DevServerView})));i.lazy(()=>Rn(()=>Promise.resolve().then(()=>Xb),void 0).then(e=>({default:e.TodoView})));function aO(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Rn(()=>import("./AgentsView-Deh125ss.js"),__vite__mapDeps([21,1,3,4,22,13,5,6,23])),Rn(()=>import("./DocumentsView-DIpg3NSP.js"),__vite__mapDeps([24,1,5,6,25])),Rn(()=>import("./InsightsView-jKjEFAx_.js"),__vite__mapDeps([26,1,19,5,6,27])),Rn(()=>import("./ResearchView-_BHXUv2j.js"),__vite__mapDeps([28,1,5,6,29])),Rn(()=>import("./NodesView-Di2SvOhg.js"),__vite__mapDeps([30,1,22,5,6,31])),Rn(()=>import("./ChatView-7D_RQDqT.js"),__vite__mapDeps([32,1,5,6])),Rn(()=>import("./RoadmapsView-DHWjUoc8.js"),__vite__mapDeps([33,1,5,6,34])),Rn(()=>import("./SkillsView-hDpTBdFT.js"),__vite__mapDeps([35,1,5,6,36])),Rn(()=>import("./MemoryView-nXlTqebk.js"),__vite__mapDeps([37,1,17,18,5,6,38])),Rn(()=>import("./DevServerView-C9lzHrcT.js"),__vite__mapDeps([39,1,5,6,40])),Rn(()=>Promise.resolve().then(()=>Xb),void 0)})}const cd="kb-setup-warning-dismissed",rO="kb-chat-active-session",kf="__none__";function oO(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function lO(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function cO(){const{toasts:e,addToast:n,removeToast:s}=oL(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=BL(),c=typeof window<"u"&&!!window.electronAPI;i.useEffect(()=>{aO()},[]);const{projects:d,loading:u,error:m,refresh:h}=nL(),{nodes:f}=Bl(),{currentNode:p,currentNodeId:g,isRemote:x,setCurrentNode:v,clearCurrentNode:b}=FL(),{currentProject:y,setCurrentProject:S,clearCurrentProject:N,loading:E}=aL(d,{nodeId:g}),{hasAiProvider:w,hasGithub:j,loading:_,hasWarnings:D}=rx(y?.id),{updateAvailable:C,latestVersion:P,currentVersion:I,dismissed:H,dismiss:A}=yL();i.useEffect(()=>{if(g&&!p&&f.length>0){const et=f.find(Bt=>Bt.id===g);if(et){v(et);return}}g&&f.length>0&&(f.some(Bt=>Bt.id===g)||b())},[g,p,f,v,b]);const[$,F]=i.useState(""),[G,ee]=i.useState(null),[J,M]=i.useState(null),T=$L(g,{projectId:y?.id,searchQuery:$||void 0});DL(g);const L=x&&T.projects.length>0?T.projects:d,{themeMode:k,colorTheme:K,dashboardFontScalePct:oe,setThemeMode:le,setColorTheme:we,setDashboardFontScalePct:ge}=pL(),{sessions:Ue,generating:Z,needsInput:Q,planningSessions:X,dismissSession:ie}=GD(y?.id),se=Ue.filter(et=>et.status==="awaiting_input"||et.status==="error"),B=QD(),O=fL({projectId:y?.id,planningSessions:X}),ae=Js()==="mobile",{pushNav:te,replaceCurrent:Ie}=SL({enabled:!0}),{viewMode:Oe,setViewMode:He,taskView:$e,handleChangeTaskView:Te}=NL({projectsLoading:u,projectsError:m,currentProjectLoading:E,currentProject:y,projectsLength:d.length,setupWizardOpen:O.setupWizardOpen,openSetupWizard:O.openSetupWizard,themeMode:k,setThemeMode:le}),{views:ue}=EL(y?.id),ce=i.useCallback(et=>{et==="missions"&&(Ve(void 0),Ge(void 0),_t(void 0));const Bt=$e;Te(et),Bt!==et&&te({type:"view",revert:()=>Te(Bt)})},[Te,$e,te]),Ae=$e==="board"||$e==="list",{tasks:Ne,createTask:ye,moveTask:Ce,pauseTask:fe,deleteTask:Pe,mergeTask:De,retryTask:dt,resetTask:pt,updateTask:lt,duplicateTask:vt,archiveTask:_e,unarchiveTask:Fe,archiveAllDone:bt,loadArchivedTasks:ht,ingestCreatedTasks:Ee,lastFetchTimeMs:me}=ZD({...y?{projectId:y.id}:{},searchQuery:$||void 0,sseEnabled:Ae}),Re=x&&T.tasks.length>0?T.tasks:Ne,[be,Ke]=i.useState(!1),[pe,Xe]=i.useState(0),wt=i.useRef(performance.now()),gt=i.useRef(!1),Tt=i.useRef(!1),Zt=i.useMemo(()=>u?"projects":E?"project":"tasks",[u,E]);i.useEffect(()=>{if(!u&&!gt.current){gt.current=!0;const et=`projects loaded at ${Math.round(performance.now()-wt.current)}ms from mount`;console.log(`[App] ${et}`)}if(!E&&!Tt.current){Tt.current=!0;const et=`current-project resolved at ${Math.round(performance.now()-wt.current)}ms from mount`;console.log(`[App] ${et}`)}},[u,E]),i.useEffect(()=>{if(be||u||E)return;const et=performance.now(),Bt=window.setTimeout(()=>{const Mn=`dashboard ready at ${Math.round(performance.now()-wt.current)}ms from mount (settle delay=${Math.round(performance.now()-et)}ms)`;console.log(`[App] ${Mn}`),Ke(!0)},GL);return()=>{window.clearTimeout(Bt)}},[be,u,E]);const{keyboardOpen:Ot}=ra({enabled:ae}),Rt=ae&&Ot&&!O.anyModalOpen;pi(Rt);const[en,zt]=i.useState(0),[Qt,xn]=i.useState(!1),Kt=i.useCallback(()=>{Zf(y?.id).then(et=>{zt(et.unreadCount)}).catch(et=>{console.warn("[App] Failed to fetch mailbox unread count:",et)})},[y?.id]);i.useEffect(()=>{Kt();const et=new URLSearchParams;y?.id&&et.set("projectId",y.id);const Bt=et.size>0?`?${et.toString()}`:"";return ai(`/api/events${Bt}`,{events:{"message:sent":Kt,"message:received":Kt,"message:read":Kt,"message:deleted":Kt}})},[y?.id,Kt]),i.useEffect(()=>{$e==="chat"&&xn(!1)},[$e]),i.useEffect(()=>{const et=new URLSearchParams;y?.id&&et.set("projectId",y.id);const Bt=et.size>0?`?${et.toString()}`:"";return ai(`/api/events${Bt}`,{events:{"chat:message:added":Mn=>{try{const xi=JSON.parse(Mn.data),Ns=ss(rO,y?.id);if(!Ns||xi.role!=="assistant"||$e==="chat"||xi.sessionId!==Ns||xi.projectId&&y?.id&&xi.projectId!==y.id)return;xn(!0)}catch{}}}})},[y?.id,$e]);const Ut=i.useMemo(()=>Array.from(new Set(Re.map(et=>et.branch?.trim()).filter(et=>!!(et&&et.length>0)))).sort((et,Bt)=>et.localeCompare(Bt)),[Re]),fn=i.useMemo(()=>Array.from(new Set(Re.map(et=>et.baseBranch?.trim()).filter(et=>!!(et&&et.length>0)))).sort((et,Bt)=>et.localeCompare(Bt)),[Re]),un=i.useMemo(()=>Re.filter(et=>{const Bt=et.branch?.trim()??null,Mn=et.baseBranch?.trim()??null;if(G===kf){if(Bt)return!1}else if(G&&Bt!==G)return!1;if(J===kf){if(Mn)return!1}else if(J&&Mn!==J)return!1;return!0}),[Re,G,J]),[tn,Vt]=i.useState(!1),[mn,xe]=i.useState(!1),[Le,Ve]=i.useState(void 0),[at,Ge]=i.useState(void 0),[Ft,_t]=i.useState(void 0),[qt,St]=i.useState(!1),[z,he]=i.useState(!1),[st,It]=i.useState(()=>ss(cd,y?.id)==="true");i.useEffect(()=>{It(ss(cd,y?.id)==="true")},[y?.id]),i.useEffect(()=>{const et=()=>{he(!0)};return window.addEventListener(wd,et),()=>{window.removeEventListener(wd,et)}},[]);const ve=i.useCallback(()=>{xs(cd,"true",y?.id),It(!0)},[y?.id]),{maxConcurrent:ot,autoMerge:Nt,globalPaused:Lt,enginePaused:$t,taskStuckTimeoutMs:Wt,showQuickChatFAB:Gt,prAuthAvailable:sn,settingsLoaded:on,experimentalFeatures:Dn,insightsEnabled:Jt,roadmapEnabled:Hn,memoryEnabled:Yn,devServerEnabled:re,todosEnabled:rt,toggleAutoMerge:ct,toggleGlobalPause:ft,toggleEnginePause:it,refresh:Y}=gL(y?.id),Ye=Dn.skillsView===!0,Yt=Dn.nodesView===!0,In=Dn.researchView===!0,cs=Dn.agentOnboarding===!0,gn=!0,Nn=i.useCallback(()=>{O.closeSettings(),Xe(et=>et+1),Y()},[O,Y]);i.useEffect(()=>{on&&(Ga($e)||($e==="skills"&&!Ye&&Te("board"),$e==="insights"&&!Jt&&Te("board"),$e==="roadmaps"&&!Hn&&Te("board"),$e==="memory"&&!Yn&&Te("board"),($e==="devserver"||$e==="dev-server")&&!re&&Te("board"),$e==="research"&&!In&&Te("board")))},[$e,on,Ye,Jt,Hn,Te,gn,Yn,re,In]),i.useEffect(()=>{tn&&!Yt&&Vt(!1)},[tn,Yt]);const{availableModels:ms,favoriteProviders:vn,favoriteModels:bn,toggleFavoriteProvider:Pt,toggleFavoriteModel:Qn}=xL();vL({projectId:y?.id,setupWizardOpen:O.setupWizardOpen,openModelOnboarding:O.openModelOnboarding,openSettings:O.openSettings});const{handleSelectProject:es,handleViewAllProjects:W,handleAddProject:qe,handleSetupComplete:Je,handleModelOnboardingComplete:ut,handlePauseProject:Ct,handleResumeProject:Mt,handleRemoveProject:an,handleToggleFavorite:An,handleToggleModelFavorite:Sn}=ML({setCurrentProject:S,clearCurrentProject:N,setViewMode:He,currentProject:y,refreshProjects:h,toggleFavoriteProvider:Pt,toggleFavoriteModel:Qn,addToast:n,openSettings:O.openSettings,openSetupWizard:O.openSetupWizard,closeSetupWizard:O.closeSetupWizard,closeModelOnboarding:O.closeModelOnboarding}),{handleDetailClose:ps}=bL({projectId:y?.id,projects:d,projectsLoading:u,currentProject:y,setCurrentProject:S,addToast:n,openTaskDetail:O.openDetailTask,closeTaskDetail:O.closeDetailTask}),ts=i.useCallback(async({insightId:et,title:Bt,description:Mn})=>{await ye({title:Bt,description:Mn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:et}}})},[ye]),{handleBoardQuickCreate:Bs,handleModalCreate:Hi,handlePlanningTaskCreated:fi,handlePlanningTasksCreated:de,handleSubtaskTasksCreated:We,handleGitHubImport:mt}=AL({createTask:ye,ingestCreatedTasks:Ee,onPlanningTaskCreated:O.onPlanningTaskCreated,onPlanningTasksCreated:O.onPlanningTasksCreated,onSubtaskTasksCreated:O.onSubtaskTasksCreated,addToast:n}),q=i.useCallback((et,Bt)=>{Bt==="changes"?O.openDetailWithChangesTab(et):O.openDetailTask(et,Bt),te({type:"modal",close:O.closeDetailTask})},[O,te]),Se=i.useCallback(async et=>{try{const Bt=await er(et,y?.id);O.openDetailTask(Bt,"logs"),te({type:"modal",close:O.closeDetailTask})}catch(Bt){n(`Failed to open task logs: ${Bt.message}`,"error")}},[O,y?.id,n,te]),[Ze,At]=i.useState([]);i.useEffect(()=>{let et=!1;return fo(y?.id).then(Bt=>{et||At(Bt)}).catch(()=>{et||At([])}),()=>{et=!0}},[y?.id]);const Et=i.useMemo(()=>new Map(Ze.map(et=>[et.id,et.name])),[Ze]);i.useCallback(()=>{Yt&&Vt(et=>!et)},[Yt]);const Cn=i.useCallback(()=>{Yt&&(tn?Vt(!1):(Vt(!0),te({type:"view",revert:()=>Vt(!1)})))},[Yt,tn,te]),rn=i.useCallback((et,Bt,Mn)=>{O.openDetailTask(et,Bt,Mn),te({type:"modal",close:O.closeDetailTask})},[O,te]),yn=i.useCallback(et=>{O.openSettings(et),te({type:"modal",close:Nn})},[O,te,Nn]),kn=i.useCallback(()=>{O.openNewTask(),te({type:"modal",close:O.closeNewTask})},[O,te]),Ln=i.useCallback(()=>{O.openPlanning(),te({type:"modal",close:O.closePlanning})},[O,te]),is=i.useCallback(et=>{O.openPlanningWithInitialPlan(et),te({type:"modal",close:O.closePlanning})},[O,te]),fs=i.useCallback(()=>{O.resumePlanning(),te({type:"modal",close:O.closePlanning})},[O,te]),On=i.useCallback(et=>{O.openSubtaskBreakdown(et),te({type:"modal",close:O.closeSubtask})},[O,te]),qn=i.useCallback(()=>{O.openGitHubImport(),te({type:"modal",close:O.closeGitHubImport})},[O,te]),wn=i.useCallback(()=>{O.terminalOpen?O.toggleTerminal():(O.toggleTerminal(),te({type:"modal",close:O.closeTerminal}))},[O,te]),Xn=i.useCallback(()=>{O.openFiles(),te({type:"modal",close:O.closeFiles})},[O,te]),Vn=i.useCallback(()=>{O.openTodos(),te({type:"modal",close:O.closeTodos})},[O,te]),as=i.useCallback(()=>{O.openActivityLog(),te({type:"modal",close:O.closeActivityLog})},[O,te]),Fn=i.useCallback(()=>{O.openGitManager(),te({type:"modal",close:O.closeGitManager})},[O,te]),ys=i.useCallback(()=>{O.openSystemStats(),te({type:"modal",close:O.closeSystemStats})},[O,te]),Wn=i.useCallback(()=>{O.openSchedules(),te({type:"modal",close:O.closeSchedules})},[O,te]),ns=i.useCallback(()=>{O.openScripts(),te({type:"modal",close:O.closeScripts})},[O,te]),js=i.useCallback(()=>{O.openWorkflowSteps(),te({type:"modal",close:O.closeWorkflowSteps})},[O,te]),Ds=i.useCallback(et=>{O.openUsage(et),te({type:"modal",close:O.closeUsage})},[O,te]),qi=i.useCallback(async(et,Bt)=>{await O.runScript(et,Bt),Ie({type:"modal",close:O.closeTerminal})},[O,Ie]),br=i.useCallback(()=>{O.closeSettings(),O.openModelOnboarding(),Ie({type:"modal",close:O.closeModelOnboarding})},[O,Ie]),ri=i.useCallback(()=>{O.setFileWorkspace("project"),O.openFiles()},[O]),gi=i.useCallback(async()=>{xe(!0);try{await h()}finally{xe(!1)}},[h]),Vi=i.useCallback(et=>{Ge(et),Ve(void 0),Te("missions")},[Te]),Ii=i.useCallback(et=>{et.type==="planning"?O.openPlanningWithSession(et.id):et.type==="subtask"?O.openSubtaskWithSession(et.id):et.type==="mission_interview"?(Ge(void 0),Ve(et.id),_t(void 0),Te("missions")):(et.type==="milestone_interview"||et.type==="slice_interview")&&(Ve(void 0),Ge(void 0),_t(et.id),Te("missions"))},[Te,O]),Ea=i.useCallback(()=>{},[]),_a=i.useCallback(()=>{},[]),[Ma,bi]=i.useState(!1),[Wi,oa]=i.useState(!1),Aa=lO(r,o,Ma);i.useEffect(()=>{!a||l===0||oa(!0)},[a,l]),i.useEffect(()=>{r.host==="desktop-shell"&&r.desktopMode==="local"&&(r.localServer?.status!=="ready"||!r.localServer.port||window.location.port!==String(r.localServer.port)&&(window.location.href=`http://localhost:${r.localServer.port}`))},[r]),i.useEffect(()=>{if(r.host!=="desktop-shell"||r.desktopMode!=="remote")return;const et=r.profiles.find(Mn=>Mn.id===r.activeProfileId);if(!et||typeof window>"u")return;const Bt=oO(et.serverUrl,et.authToken??null);window.location.href!==Bt&&(window.location.href=Bt)},[r]);const Pa=!u&&!E&&d.length===0&&!y&&!!m,Ki=()=>Pa?t.jsx(eD,{errorMessage:m??"Failed to fetch projects",isRetrying:mn,onRetry:gi,onManageConnection:a?()=>{a.openConnectionManager()}:void 0}):tn?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(ZL,{addToast:n,onClose:()=>Vt(!1)})})})}):Oe==="overview"?t.jsx(Es,{children:t.jsx(qT,{projects:d,loading:u,onSelectProject:es,onAddProject:qe,onPauseProject:Ct,onResumeProject:Mt,onRemoveProject:an,nodes:f})}):Ga($e)?t.jsx(Es,{children:t.jsx(_L,{taskView:$e,context:{projectId:y?.id,tasks:x&&T.tasks.length>0?T.tasks:Ne,workflowSteps:Ze,openTaskDetail:(et,Bt)=>rn(et,Bt),renderTaskCard:et=>t.jsx(to,{task:et,projectId:y?.id,onOpenDetail:Bt=>rn(Bt),addToast:n,workflowStepNameLookup:Et})}})}):$e==="skills"?!on||!Ye?null:t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(nO,{addToast:n,projectId:y?.id,onClose:()=>Te("board")})})}):$e==="chat"?t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(eO,{addToast:n,projectId:y?.id})})}):$e==="mailbox"?t.jsx(Es,{children:t.jsx(IR,{projectId:y?.id,addToast:n,onUnreadCountChange:zt})}):$e==="roadmaps"?!on||!Hn?null:t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(tO,{addToast:n,projectId:y?.id})})}):$e==="missions"?t.jsx(Es,{children:t.jsx(AR,{isInline:!0,isOpen:!0,onClose:()=>{Ge(void 0),Ve(void 0),_t(void 0),Te("board")},addToast:n,projectId:y?.id,onSelectTask:et=>{const Bt=Ne.find(Mn=>Mn.id===et);Bt&&rn(Bt)},availableTasks:Ne.map(et=>({id:et.id,title:et.title})),resumeSessionId:Le,targetMissionId:at,milestoneSliceResumeSessionId:Ft,onMilestoneSliceResumeFetchError:()=>_t(void 0)})}):$e==="agents"&&gn?t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(JL,{addToast:n,projectId:y?.id,onOpenTaskLogs:Se,agentOnboardingEnabled:cs})})}):$e==="documents"?t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(YL,{projectId:y?.id,addToast:n,onOpenDetail:rn})})}):$e==="insights"?!on||!Jt?null:t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(QL,{projectId:y?.id,addToast:n,onClose:()=>Te("board"),onCreateTask:ts})})}):$e==="research"?!on||!In?null:t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(XL,{projectId:y?.id,addToast:n,onOpenSettings:et=>O.openSettings(et),readinessVersion:pe})})}):$e==="memory"?!on||!Yn?null:t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(sO,{addToast:n,projectId:y?.id})})}):$e==="devserver"||$e==="dev-server"?!on||!re?null:t.jsx(Es,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(iO,{addToast:n,projectId:y?.id})})}):$e==="board"?t.jsx(Es,{children:t.jsx(G0,{tasks:un,projectId:y?.id,maxConcurrent:ot,onMoveTask:Ce,onPauseTask:fe,onOpenDetail:rn,addToast:n,onQuickCreate:Bs,onNewTask:kn,onPlanningMode:is,onSubtaskBreakdown:On,autoMerge:Nt,onToggleAutoMerge:ct,globalPaused:Lt,onUpdateTask:lt,onRetryTask:dt,onArchiveTask:_e,onUnarchiveTask:Fe,onDeleteTask:Pe,onArchiveAllDone:bt,onLoadArchivedTasks:ht,searchQuery:$,availableModels:ms,onOpenDetailWithTab:q,favoriteProviders:vn,favoriteModels:bn,onToggleFavorite:An,onToggleModelFavorite:Sn,taskStuckTimeoutMs:Wt,onOpenMission:Vi,lastFetchTimeMs:me})}):t.jsx(Es,{children:t.jsx(IT,{tasks:x&&T.tasks.length>0?T.tasks:Ne,projectId:y?.id,onMoveTask:Ce,onRetryTask:dt,onDeleteTask:Pe,onMergeTask:De,onResetTask:pt,onDuplicateTask:vt,onOpenDetail:(et,Bt)=>rn(et,void 0,Bt),addToast:n,globalPaused:Lt,onNewTask:kn,onQuickCreate:Bs,onPlanningMode:is,onSubtaskBreakdown:On,availableModels:ms,favoriteProviders:vn,favoriteModels:bn,onToggleFavorite:An,onToggleModelFavorite:Sn,taskStuckTimeoutMs:Wt,searchQuery:$,lastFetchTimeMs:me,prAuthAvailable:sn})});if(!be)return t.jsxs(t.Fragment,{children:[t.jsx(nD,{stage:Zt}),t.jsx(mx,{toasts:e,onRemove:s})]});const Qs=!O.modelOnboardingOpen&&N$(),Ta=!O.modelOnboardingOpen&&!Qs&&dr()&&!lx();return t.jsxs(t.Fragment,{children:[t.jsx(MS,{isElectron:c,onOpenSettings:yn,onOpenGitHubImport:qn,onOpenPlanning:Ln,onResumePlanning:fs,activePlanningSessionCount:X.length,onOpenUsage:Ds,onOpenActivityLog:as,onOpenSystemStats:ys,onOpenMailbox:()=>ce("mailbox"),mailboxUnreadCount:en,chatHasUnreadResponse:Qt,onOpenSchedules:Wn,onOpenGitManager:Fn,onOpenNodes:Cn,showNodesButton:Yt,onOpenWorkflowSteps:js,onOpenScripts:ns,onRunScript:qi,onToggleTerminal:wn,onOpenFiles:Xn,filesOpen:O.filesOpen,onOpenTodos:Vn,todosOpen:O.todosOpen,todosEnabled:rt,globalPaused:Lt,enginePaused:$t,onToggleGlobalPause:ft,onToggleEnginePause:it,view:$e,onChangeView:Oe==="project"&&y?ce:void 0,showSkillsTab:Ye,showAgentsTab:gn,searchQuery:$,onSearchChange:F,branchFilter:G,baseBranchFilter:J,branchOptions:Ut,baseBranchOptions:fn,onBranchFilterChange:ee,onBaseBranchFilterChange:M,projects:L,currentProject:y,onSelectProject:es,onViewAllProjects:W,projectId:y?.id,mobileNavEnabled:ae,availableNodes:f,currentNode:p,onSelectNode:et=>{et===null?b():v(et)},isRemote:x,experimentalFeatures:{insights:Jt,roadmap:Hn,memoryView:Yn,devServer:re,devServerView:re,researchView:In},pluginDashboardViews:ue,shellConnectionControl:a&&r.host!=="web"?t.jsx(WL,{state:r,onManage:()=>oa(!0)}):void 0}),Oe==="project"&&y&&!tn&&$e!=="missions"&&!O.isPlanningOpen&&!B&&t.jsx(bD,{sessions:se,onResumeSession:Ii,onDismissSession:Ea,onDismissAll:_a}),Oe==="project"&&y&&t.jsx(yD,{onOpenSettings:()=>O.openSettings("general")}),Oe==="project"&&y&&Qs&&t.jsx(kD,{onResume:O.openModelOnboarding}),Oe==="project"&&y&&Ta&&t.jsx(jD,{onOpenModelOnboarding:O.openModelOnboarding,onOpenSettings:et=>O.openSettings(et)}),Oe==="project"&&y&&C&&P&&I&&!H&&t.jsx(wD,{latestVersion:P,currentVersion:I,onDismiss:A}),Oe==="project"&&y&&!_&&D&&!st&&t.jsx(ox,{hasAiProvider:w,hasGithub:j,onDismiss:ve}),t.jsx("div",{className:`project-content${Oe==="project"&&y?" project-content--with-footer":""}${ae&&!Rt?" project-content--with-mobile-nav":""}`,children:Ki()}),Oe==="project"&&y&&!tn&&t.jsx(mD,{tasks:x&&T.tasks.length>0?T.tasks:Ne,projectId:y.id,taskStuckTimeoutMs:Wt,backgroundSessions:Ue,backgroundGenerating:Z,backgroundNeedsInput:Q,onOpenBackgroundSession:Ii,onDismissBackgroundSession:ie,lastFetchTimeMs:me,currentProjectPath:y.path,onOpenProjectDirectory:ri,keyboardOpen:Rt}),t.jsx(SD,{view:$e,onChangeView:Oe==="project"&&y?ce:()=>{},footerVisible:Oe==="project"&&!!y,modalOpen:O.anyModalOpen,keyboardOpen:Rt,onOpenSettings:yn,onOpenActivityLog:as,onOpenSystemStats:ys,onOpenMailbox:()=>ce("mailbox"),onOpenNodes:Cn,mailboxUnreadCount:en,chatHasUnreadResponse:Qt,onOpenGitManager:Fn,onOpenWorkflowSteps:js,onOpenSchedules:Wn,onOpenScripts:ns,onToggleTerminal:wn,onOpenFiles:Xn,onOpenTodos:Vn,todosOpen:O.todosOpen,onOpenGitHubImport:qn,onOpenPlanning:Ln,onResumePlanning:fs,activePlanningSessionCount:X.length,onOpenUsage:()=>Ds(null),onViewAllProjects:W,onRunScript:qi,projectId:y?.id,showSkillsTab:Ye,experimentalFeatures:{insights:Jt,roadmap:Hn,memoryView:Yn,devServer:re,devServerView:re,todoView:rt,researchView:In,nodesView:Yt},pluginDashboardViews:ue}),Oe==="project"&&y&&$e!=="chat"&&$e!=="mailbox"&&$e!=="insights"&&$e!=="devserver"&&$e!=="dev-server"&&!Ga($e)&&t.jsx(KD,{projectId:y.id,addToast:n,showFAB:Gt,open:qt,onOpenChange:St,favoriteProviders:vn,favoriteModels:bn,onToggleFavorite:An,onToggleModelFavorite:Sn}),t.jsx(Z$,{projectId:y?.id,tasks:Ne,projects:d,currentProject:y,addToast:n,toasts:e,removeToast:s,modalManager:O,projectActions:{handleAddProject:qe,handleSetupComplete:Je,handleModelOnboardingComplete:ut},taskHandlers:{handleModalCreate:Hi,handlePlanningTaskCreated:fi,handlePlanningTasksCreated:de,handleSubtaskTasksCreated:We,handleGitHubImport:mt},taskOperations:{moveTask:Ce,deleteTask:Pe,mergeTask:De,retryTask:dt,resetTask:pt,duplicateTask:vt},deepLink:{handleDetailClose:ps},settings:{prAuthAvailable:sn,themeMode:k,colorTheme:K,dashboardFontScalePct:oe,setThemeMode:le,setColorTheme:we,setDashboardFontScalePct:ge},onSettingsClose:Nn,onReopenOnboarding:br}),t.jsx(KL,{open:z}),a&&t.jsxs(t.Fragment,{children:[t.jsx(qL,{open:Aa,shellApi:a,shellState:r,onComplete:()=>bi(!0)}),t.jsx(VL,{open:Wi,shellApi:a,shellState:r,onClose:()=>oa(!1)})]})]})}function dO(){return t.jsx(rL,{children:t.jsx(zL,{children:t.jsx(OL,{children:t.jsx(HS,{children:t.jsx(cO,{})})})})})}function Ex(e){e.postMessage({type:"SKIP_WAITING"})}function jf(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&Ex(e)})}function uO(){if(!("serviceWorker"in navigator))return;let e=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{e||(e=!0,eu("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(n=>{console.log("SW registered:",n.scope),n.waiting&&navigator.serviceWorker.controller&&Ex(n.waiting),n.installing&&jf(n.installing),n.addEventListener("updatefound",()=>{const s=n.installing;s&&jf(s)})}).catch(n=>{console.log("SW registration failed:",n)})}Vw();Aw();_x.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(Pw,{children:t.jsx(dO,{})})}));uO();export{ls as $,Ws as A,zn as B,Gn as C,Ys as D,xs as E,na as F,Pl as G,Ol as H,jo as I,Me as J,zS as K,xt as L,UF as M,gd as N,Iy as O,Jn as P,_n as Q,hs as R,Li as S,Ll as T,ll as U,uo as V,pz as W,nn as X,o$ as Y,us as Z,nd as _,cn as a,Bl as a$,di as a0,En as a1,Rn as a2,s$ as a3,cN as a4,Y4 as a5,Q4 as a6,dN as a7,OF as a8,uN as a9,oz as aA,rz as aB,az as aC,iz as aD,sz as aE,tz as aF,zf as aG,Kw as aH,Zr as aI,xz as aJ,gz as aK,bz as aL,vz as aM,Xr as aN,dd as aO,iw as aP,qr as aQ,Si as aR,Jy as aS,yv as aT,Ss as aU,Lf as aV,Ky as aW,XF as aX,ZF as aY,e3 as aZ,t3 as a_,QO as aa,XO as ab,fj as ac,Qd as ad,ur as ae,ka as af,Ai as ag,Pi as ah,mi as ai,K3 as aj,X3 as ak,Q3 as al,G3 as am,Z3 as an,J3 as ao,Y3 as ap,bs as aq,ao as ar,Ps as as,fw as at,hi as au,Af as av,zi as aw,Lx as ax,ez as ay,nz as az,Un as b,vF as b$,nL as b0,lm as b1,ic as b2,sr as b3,J1 as b4,V3 as b5,W3 as b6,Q1 as b7,ED as b8,X1 as b9,w3 as bA,v3 as bB,os as bC,Rl as bD,ta as bE,H3 as bF,B3 as bG,q3 as bH,PO as bI,AO as bJ,MO as bK,TO as bL,UO as bM,BO as bN,OO as bO,$O as bP,DO as bQ,LO as bR,IO as bS,RO as bT,_O as bU,FO as bV,$I as bW,xF as bX,bF as bY,NF as bZ,gF as b_,$D as ba,ra as bb,K1 as bc,Ml as bd,$f as be,CD as bf,RD as bg,pa as bh,Tf as bi,Lu as bj,Oi as bk,a3 as bl,o3 as bm,r3 as bn,l3 as bo,c3 as bp,d3 as bq,u3 as br,m3 as bs,h3 as bt,p3 as bu,f3 as bv,g3 as bw,b3 as bx,x3 as by,y3 as bz,Qe as c,QF as c$,yF as c0,wF as c1,kF as c2,Fj as c3,jF as c4,nu as c5,Dj as c6,Lj as c7,Oj as c8,$j as c9,Mk as cA,uF as cB,ni as cC,Ti as cD,QD as cE,wI as cF,HO as cG,s3 as cH,fO as cI,gO as cJ,ef as cK,GF as cL,bO as cM,vO as cN,EO as cO,CO as cP,Bk as cQ,Pk as cR,_i as cS,Tk as cT,Ik as cU,Rk as cV,$k as cW,Dk as cX,WO as cY,JF as cZ,YF as c_,fF as ca,Dl as cb,nw as cc,Xa as cd,Za as ce,yN as cf,Lw as cg,Ow as ch,wk as ci,kk as cj,D3 as ck,eF as cl,ZO as cm,L3 as cn,tF as co,cF as cp,rF as cq,nF as cr,oF as cs,sF as ct,lF as cu,iF as cv,aF as cw,Vx as cx,_k as cy,dF as cz,KF as d,_F as d$,Ui as d0,cz as d1,dz as d2,i3 as d3,yO as d4,ud as d5,vs as d6,RI as d7,c$ as d8,u$ as d9,jd as dA,Hu as dB,$F as dC,LF as dD,fd as dE,zs as dF,ny as dG,M3 as dH,zF as dI,lo as dJ,RP as dK,DF as dL,HF as dM,BF as dN,Pf as dO,RF as dP,TF as dQ,CF as dR,EF as dS,J4 as dT,FF as dU,AF as dV,MF as dW,gj as dX,PF as dY,IF as dZ,A3 as d_,Zi as da,sd as db,h$ as dc,kO as dd,xO as de,jO as df,wO as dg,NO as dh,SO as di,xa as dj,fz as dk,DS as dl,Ul as dm,uz as dn,Kh as dp,mz as dq,hz as dr,zO as ds,k3 as dt,N3 as du,E3 as dv,S3 as dw,j3 as dx,C3 as dy,_3 as dz,VF as e,P3 as e0,O3 as e1,xd as e2,z3 as e3,I3 as e4,R3 as e5,$3 as e6,T3 as e7,F3 as e8,n3 as e9,lz as ea,KO as eb,qO as ec,VO as ed,By as ee,JO as ef,YO as eg,GO as eh,er as f,WF as g,SF as h,ii as i,pF as j,mF as k,hF as l,$s as m,Na as n,$n as o,Hd as p,U3 as q,X4 as r,ai as s,ks as t,pi as u,lN as v,qF as w,Js as x,TD as y,ss as z};
|