@runfusion/fusion 0.26.0 → 0.27.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 +11036 -1992
- package/dist/client/assets/AgentDetailView-B7QRcHJH.css +1 -0
- package/dist/client/assets/AgentDetailView-DwLmRXTY.js +18 -0
- package/dist/client/assets/{AgentsView-D6Zi5zfP.js → AgentsView-D-N6aA0P.js} +12 -7
- package/dist/client/assets/ChatView-DnCdKu8Z.js +1 -0
- package/dist/client/assets/{DevServerView--_WBvIDQ.js → DevServerView-BiA1nYtt.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-xedtR-Rd.js → DirectoryPicker-DvBviDG6.js} +1 -1
- package/dist/client/assets/{DocumentsView-Bg2oaZks.js → DocumentsView-BWXOxpuq.js} +1 -1
- package/dist/client/assets/{EvalsView-B3uOCXfr.js → EvalsView-CJFbtL7i.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-Bx6yXVS5.js → ExperimentalAgentOnboardingModal-DuGIPd0B.js} +1 -1
- package/dist/client/assets/InsightsView-BBpRiolN.js +11 -0
- package/dist/client/assets/{MemoryView-xcN_eouf.js → MemoryView-48LuNkKk.js} +2 -2
- package/dist/client/assets/NodesView-CGQWSNZM.js +14 -0
- package/dist/client/assets/{PiExtensionsManager-Cc8aAZXg.js → PiExtensionsManager-i-7UL2oh.js} +2 -2
- package/dist/client/assets/PluginManager-DoSAykD6.js +1 -0
- package/dist/client/assets/{ResearchView-CERNf7sJ.js → ResearchView-XZuRtOxE.js} +1 -1
- package/dist/client/assets/{SettingsModal-Cis-4Lot.css → SettingsModal-Ci0_sqbU.css} +1 -1
- package/dist/client/assets/{SettingsModal-B1r0yASu.js → SettingsModal-CmeF8CN4.js} +1 -1
- package/dist/client/assets/SettingsModal-DBcjf9Bu.js +31 -0
- package/dist/client/assets/SettingsModal-DWKgRxBA.css +1 -0
- package/dist/client/assets/{SetupWizardModal-D1q548_L.js → SetupWizardModal-CgtvpMX9.js} +1 -1
- package/dist/client/assets/{SkillsView-ClLM6u6p.js → SkillsView-DErYRumF.js} +1 -1
- package/dist/client/assets/{StashRecoveryView-ze0pEZ5U.js → StashRecoveryView-QJrNS4Vg.js} +1 -1
- package/dist/client/assets/{TodoView-CTmIfy2M.js → TodoView-BD9NRwq0.js} +2 -2
- package/dist/client/assets/{dashboard-view-CyWN-d02.js → dashboard-view-BWGH_fAq.js} +1 -1
- package/dist/client/assets/dashboard-view-BoTzlP8b.css +1 -0
- package/dist/client/assets/dashboard-view-Ws9_ZnKu.js +21 -0
- package/dist/client/assets/{folder-open-BZuKESeq.js → folder-open-CHSlllzf.js} +1 -1
- package/dist/client/assets/index-DCovGm5b.css +1 -0
- package/dist/client/assets/index-bEwSVl7B.js +692 -0
- package/dist/client/assets/{star-D75YKEq-.js → star-BgVwWAPz.js} +1 -1
- package/dist/client/assets/{upload-BYYTgWFj.js → upload-CAzycxr9.js} +1 -1
- package/dist/client/assets/{users-RS90Aii3.js → users-CZnxCCCJ.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/droid-cli/src/__tests__/index.test.ts +228 -0
- package/dist/extension.js +5517 -1193
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/pi-claude-cli/src/__tests__/provider.test.ts +36 -22
- package/dist/pi-claude-cli/src/provider.ts +7 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/manifest.json +19 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +20 -2
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/TestRunnerPanel.test.tsx +99 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/config-flow.test.ts +91 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/dashboard-view.test.tsx +40 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/dashboard-views.test.ts +46 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/draft-store.test.ts +50 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/fixtures/exec-mock.ts +80 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/fixtures/fixtures.test.ts +40 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/fixtures/registry.ts +82 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/generator.test.ts +54 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/manage-view.test.tsx +98 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/manifest.test.ts +21 -5
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/registration.test.ts +29 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/run-routes.test.ts +98 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/runner.test.ts +55 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/runtime-availability.test.ts +61 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/validation.test.ts +30 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/wizard-routes.test.ts +61 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/__tests__/workflow-integration.test.ts +19 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/dashboard-view.css +43 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/dashboard-view.tsx +49 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/generation/generator.ts +95 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/generation/redact.ts +9 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/generation/runner.ts +79 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/generation/types.ts +31 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/index.ts +46 -2
- package/dist/plugins/fusion-plugin-cli-printing-press/src/manage/EditDraftModal.tsx +75 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/manage/useDrafts.ts +73 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/manage-view.css +79 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/manage-view.tsx +122 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/routes/wizard-routes.ts +272 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/run/TestRunnerPanel.css +70 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/run/TestRunnerPanel.tsx +98 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/run/useRunGeneratedCli.ts +37 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/runtime/__tests__/executor-runtime-env.test.ts +191 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/runtime/executor-runtime-env.ts +75 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/storage/draft-store.ts +85 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/store/__tests__/cli-press-store.test.ts +128 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/store/__tests__/credentials.test.ts +62 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/store/cli-press-store.ts +427 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/store/cli-press-types.ts +110 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/store/credentials.ts +95 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/wizard/steps.tsx +55 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/wizard/types.ts +33 -0
- package/dist/plugins/fusion-plugin-cli-printing-press/src/wizard/validation.ts +63 -0
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/manifest.json +10 -0
- package/dist/plugins/fusion-plugin-reports/package.json +18 -2
- package/dist/plugins/fusion-plugin-reports/src/__tests__/approval.test.ts +164 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/manifest.test.ts +14 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/routes-approval.test.ts +109 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/scaffold.test.ts +60 -0
- package/dist/plugins/fusion-plugin-reports/src/__tests__/share-blocks.test.ts +83 -0
- package/dist/plugins/fusion-plugin-reports/src/aggregation.ts +23 -0
- package/dist/plugins/fusion-plugin-reports/src/approval.ts +97 -0
- package/dist/plugins/fusion-plugin-reports/src/cadence.ts +23 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/ReportsView.css +82 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/ReportsView.tsx +24 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportComparisonDrawer.test.tsx +12 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportDetailPanel.test.tsx +12 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportFiltersBar.test.tsx +14 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/ReportsView.test.tsx +27 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/api.test.ts +19 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/useReportSectionDiff.test.ts +11 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/__tests__/useReports.test.ts +13 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/api.ts +85 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportApprovalPanel.css +59 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportApprovalPanel.tsx +58 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportComparisonDrawer.tsx +21 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportDetailPanel.tsx +29 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportEmptyState.tsx +3 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportFiltersBar.tsx +19 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ReportListItem.tsx +8 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ShareBlocksPanel.css +29 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/ShareBlocksPanel.tsx +43 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/__tests__/ReportApprovalPanel.test.tsx +38 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/components/__tests__/ShareBlocksPanel.test.tsx +24 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/test-setup.ts +18 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/types.ts +22 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/useReportPreview.ts +44 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/useReportSectionDiff.ts +59 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/useReports.ts +71 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard/useViewportMode.ts +13 -0
- package/dist/plugins/fusion-plugin-reports/src/dashboard-view.tsx +6 -0
- package/dist/plugins/fusion-plugin-reports/src/index.ts +48 -2
- package/dist/plugins/fusion-plugin-reports/src/pipeline.ts +58 -0
- package/dist/plugins/fusion-plugin-reports/src/render/__tests__/escape.test.ts +20 -0
- package/dist/plugins/fusion-plugin-reports/src/render/__tests__/html-template.test.ts +110 -0
- package/dist/plugins/fusion-plugin-reports/src/render/__tests__/standalone-html.test.ts +66 -0
- package/dist/plugins/fusion-plugin-reports/src/render/escape.ts +12 -0
- package/dist/plugins/fusion-plugin-reports/src/render/html-styles.ts +40 -0
- package/dist/plugins/fusion-plugin-reports/src/render/html-template.ts +137 -0
- package/dist/plugins/fusion-plugin-reports/src/render/index.ts +4 -0
- package/dist/plugins/fusion-plugin-reports/src/render/standalone-html.ts +75 -0
- package/dist/plugins/fusion-plugin-reports/src/report-schema.ts +31 -0
- package/dist/plugins/fusion-plugin-reports/src/routes/__tests__/report-export-routes.test.ts +104 -0
- package/dist/plugins/fusion-plugin-reports/src/routes/report-approval-routes.ts +98 -0
- package/dist/plugins/fusion-plugin-reports/src/routes/report-export-routes.ts +77 -0
- package/dist/plugins/fusion-plugin-reports/src/routes/report-list-routes.ts +72 -0
- package/dist/plugins/fusion-plugin-reports/src/runs-store.ts +69 -0
- package/dist/plugins/fusion-plugin-reports/src/share-blocks.ts +82 -0
- package/dist/plugins/fusion-plugin-reports/src/store/report-store.ts +51 -2
- package/dist/plugins/fusion-plugin-reports/src/store/report-types.ts +6 -1
- package/dist/plugins/fusion-plugin-roadmap/bundled.js +1528 -29391
- package/dist/plugins/fusion-plugin-roadmap/manifest.json +1 -1
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/skill/fusion/references/engine-tools.md +1 -1
- package/skill/fusion/references/extension-tools.md +3 -3
- package/skill/fusion/references/fusion-capabilities.md +1 -1
- package/dist/client/assets/AgentDetailView-BwJaLqZh.css +0 -1
- package/dist/client/assets/AgentDetailView-Cv-vgOj3.js +0 -18
- package/dist/client/assets/ChatView-CAHjY9uO.js +0 -1
- package/dist/client/assets/InsightsView-Q1zvtF4F.js +0 -11
- package/dist/client/assets/NodesView-RxXg58_Q.js +0 -14
- package/dist/client/assets/PluginManager-BEkyBajl.js +0 -1
- package/dist/client/assets/SettingsModal-BLsac7CJ.js +0 -31
- package/dist/client/assets/SettingsModal-BNSrO1M9.css +0 -1
- package/dist/client/assets/dashboard-view-4xAN3yO5.js +0 -21
- package/dist/client/assets/dashboard-view-BkTMSZYn.css +0 -1
- package/dist/client/assets/index-Bdw6llW6.js +0 -692
- package/dist/client/assets/index-CZGlyJuS.css +0 -1
- package/dist/plugins/fusion-plugin-roadmap/bundled.css +0 -1093
|
@@ -0,0 +1,692 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-DwLmRXTY.js","assets/vendor-react-K0fH_qHe.js","assets/star-BgVwWAPz.js","assets/ExperimentalAgentOnboardingModal-DuGIPd0B.js","assets/ExperimentalAgentOnboardingModal-B-APN_lM.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-B7QRcHJH.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-BD9NRwq0.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-CgtvpMX9.js","assets/DirectoryPicker-DvBviDG6.js","assets/folder-open-CHSlllzf.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-DBcjf9Bu.js","assets/SettingsModal-CmeF8CN4.js","assets/SettingsModal-Ci0_sqbU.css","assets/users-CZnxCCCJ.js","assets/SettingsModal-DWKgRxBA.css","assets/dashboard-view-Ws9_ZnKu.js","assets/createLucideIcon-BazL2hk5.js","assets/dashboard-view-BoTzlP8b.css","assets/dashboard-view-BWGH_fAq.js","assets/dashboard-view-DdGlfuu-.css","assets/AgentsView-D-N6aA0P.js","assets/upload-CAzycxr9.js","assets/AgentsView-CV3vm7Qk.css","assets/DocumentsView-BWXOxpuq.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-BBpRiolN.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-XZuRtOxE.js","assets/ResearchView-BEI4ZSGs.css","assets/EvalsView-CJFbtL7i.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-CGQWSNZM.js","assets/NodesView-DT4pXowv.css","assets/ChatView-DnCdKu8Z.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-DErYRumF.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-48LuNkKk.js","assets/MemoryView-zaXewZzi.css","assets/DevServerView-BiA1nYtt.js","assets/DevServerView-DlZpuAnj.css","assets/StashRecoveryView-QJrNS4Vg.js","assets/StashRecoveryView-B_8WIQEo.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as i,j as t,R as Ol,a as Ra,g as Bg,c as cy}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 Ug=(...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 dy=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 uy=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 Cm=e=>{const n=uy(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 Ic={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 my=e=>{for(const n in e)if(n.startsWith("aria-")||n==="role"||n==="title")return!0;return!1},hy=i.createContext({}),py=()=>i.useContext(hy),fy=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=""}=py()??{},g=a??h?Number(s??m)*24/Number(n??u):s??m;return i.createElement("svg",{ref:d,...Ic,width:n??u??Ic.width,height:n??u??Ic.height,stroke:e??f,strokeWidth:g,className:Ug("lucide",p,r),...!o&&!my(c)&&{"aria-hidden":"true"},...c},[...l.map(([x,y])=>i.createElement(x,y)),...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 et=(e,n)=>{const s=i.forwardRef(({className:a,...r},o)=>i.createElement(fy,{ref:o,iconNode:n,className:Ug(`lucide-${dy(Cm(e))}`,`lucide-${e}`,a),...r}));return s.displayName=Cm(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 gy=[["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"}]],Ys=et("activity",gy);/**
|
|
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 by=[["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"}]],xy=et("archive-restore",by);/**
|
|
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 vy=[["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"}]],To=et("archive",vy);/**
|
|
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 yy=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Po=et("arrow-down",yy);/**
|
|
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 wy=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],Ua=et("arrow-left",wy);/**
|
|
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 ky=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],$o=et("arrow-right",ky);/**
|
|
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 jy=[["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"}]],Hg=et("arrow-up-down",jy);/**
|
|
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 Ny=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Ta=et("arrow-up",Ny);/**
|
|
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 Sy=[["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"}]],Cy=et("book-open",Sy);/**
|
|
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 Ey=[["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=et("bot",Ey);/**
|
|
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 _y=[["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"}]],Gd=et("box",_y);/**
|
|
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 My=[["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"}]],No=et("brain",My);/**
|
|
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 Ay=[["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"}]],qg=et("calendar",Ay);/**
|
|
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 Ry=[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]],Em=et("check-check",Ry);/**
|
|
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 Iy=[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]],js=et("check",Iy);/**
|
|
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 Ty=[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]],pn=et("chevron-down",Ty);/**
|
|
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 Py=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],lc=et("chevron-left",Py);/**
|
|
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 $y=[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]],On=et("chevron-right",$y);/**
|
|
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 Dy=[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]],Pi=et("chevron-up",Dy);/**
|
|
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 Ly=[["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"}]],Ws=et("circle-alert",Ly);/**
|
|
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 Oy=[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]],Gn=et("circle-check-big",Oy);/**
|
|
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 Fy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]],cc=et("circle-dot",Fy);/**
|
|
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 zy=[["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"}]],Jd=et("circle-question-mark",zy);/**
|
|
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 By=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],Uy=et("circle-stop",By);/**
|
|
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 Hy=[["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"}]],Do=et("circle-x",Hy);/**
|
|
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 qy=[["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"}]],Vy=et("clipboard-list",qy);/**
|
|
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 Wy=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 6v6l4 2",key:"mmk7yg"}]],Ji=et("clock",Wy);/**
|
|
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 Ky=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],Vg=et("code",Ky);/**
|
|
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 Gy=[["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"}]],_m=et("columns-3",Gy);/**
|
|
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 Jy=[["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"}]],da=et("copy",Jy);/**
|
|
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 Yy=[["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"}]],Wg=et("cpu",Yy);/**
|
|
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 Qy=[["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"}]],Xy=et("download",Qy);/**
|
|
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 Zy=[["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"}]],ew=et("ellipsis-vertical",Zy);/**
|
|
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 tw=[["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"}]],Yd=et("ellipsis",tw);/**
|
|
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 nw=[["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"}]],Kg=et("external-link",nw);/**
|
|
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 sw=[["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"}]],Pu=et("eye-off",sw);/**
|
|
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 iw=[["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"}]],Ir=et("eye",iw);/**
|
|
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 aw=[["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"}]],xi=et("file-code",aw);/**
|
|
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 rw=[["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"}]],Qd=et("file-diff",rw);/**
|
|
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 ow=[["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"}]],lw=et("file-minus",ow);/**
|
|
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 cw=[["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"}]],Gg=et("file-pen",cw);/**
|
|
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 dw=[["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"}]],uw=et("file-plus",dw);/**
|
|
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 mw=[["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"}]],hw=et("file-question-mark",mw);/**
|
|
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 pw=[["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"}]],ua=et("file-text",pw);/**
|
|
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 fw=[["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"}]],gw=et("file-type",fw);/**
|
|
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 bw=[["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"}]],Jg=et("file",bw);/**
|
|
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 xw=[["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"}]],vw=et("flag",xw);/**
|
|
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 yw=[["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"}]],Xd=et("folder-git-2",yw);/**
|
|
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 ww=[["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"}]],Mm=et("folder-root",ww);/**
|
|
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 kw=[["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"}]],Es=et("folder",kw);/**
|
|
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 jw=[["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"}]],Fl=et("funnel",jw);/**
|
|
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 Nw=[["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"}]],Fs=et("git-branch",Nw);/**
|
|
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 Sw=[["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"}]],br=et("git-commit-horizontal",Sw);/**
|
|
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 Cw=[["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"}]],Yg=et("git-merge",Cw);/**
|
|
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 Ew=[["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"}]],si=et("git-pull-request",Ew);/**
|
|
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 _w=[["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"}]],dc=et("globe",_w);/**
|
|
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 Mw=[["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"}]],uc=et("grid-3x3",Mw);/**
|
|
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 Aw=[["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"}]],mc=et("grip-vertical",Aw);/**
|
|
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 Rw=[["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"}]],Iw=et("hard-drive",Rw);/**
|
|
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 Tw=[["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"}]],Pw=et("heart",Tw);/**
|
|
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 $w=[["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"}]],Pa=et("history",$w);/**
|
|
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 Dw=[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]],ra=et("inbox",Dw);/**
|
|
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 Lw=[["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"}]],Qg=et("key",Lw);/**
|
|
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 Ow=[["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"}]],Fw=et("keyboard",Ow);/**
|
|
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 zw=[["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"}]],$a=et("layers",zw);/**
|
|
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 Bw=[["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"}]],ma=et("layout-grid",Bw);/**
|
|
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 Uw=[["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"}]],$i=et("lightbulb",Uw);/**
|
|
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 Hw=[["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"}]],xr=et("link",Hw);/**
|
|
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 qw=[["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"}]],Vw=et("list-checks",qw);/**
|
|
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 Ww=[["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"}]],Kw=et("list-ordered",Ww);/**
|
|
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 Gw=[["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"}]],Jw=et("list-plus",Gw);/**
|
|
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 Yw=[["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"}]],hc=et("list-tree",Yw);/**
|
|
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 Qw=[["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"}]],Zd=et("list",Qw);/**
|
|
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 Xw=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]],jt=et("loader-circle",Xw);/**
|
|
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 Zw=[["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"}]],pc=et("lock",Zw);/**
|
|
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 ek=[["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"}]],Da=et("mail",ek);/**
|
|
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 tk=[["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"}]],nk=et("map",tk);/**
|
|
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 sk=[["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"}]],fc=et("maximize-2",sk);/**
|
|
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 ik=[["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"}]],ak=et("message-square-plus",ik);/**
|
|
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 rk=[["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"}]],Ki=et("message-square",rk);/**
|
|
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 ok=[["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"}]],Lo=et("minimize-2",ok);/**
|
|
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 lk=[["path",{d:"M5 12h14",key:"1ays0h"}]],ck=et("minus",lk);/**
|
|
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 dk=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]],vr=et("monitor",dk);/**
|
|
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 uk=[["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"}]],mk=et("move",uk);/**
|
|
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 hk=[["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"}]],pk=et("network",hk);/**
|
|
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 fk=[["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"}]],eu=et("package",fk);/**
|
|
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 gk=[["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"}]],Xg=et("paperclip",gk);/**
|
|
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 bk=[["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"}]],vi=et("pause",bk);/**
|
|
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 xk=[["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"}]],qs=et("pencil",xk);/**
|
|
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 vk=[["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"}]],is=et("play",vk);/**
|
|
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 yk=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]],Mn=et("plus",yk);/**
|
|
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 wk=[["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"}]],kk=et("puzzle",wk);/**
|
|
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 jk=[["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"}]],Zg=et("radio",jk);/**
|
|
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 Nk=[["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"}]],bs=et("refresh-cw",Nk);/**
|
|
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 Sk=[["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"}]],Am=et("rocket",Sk);/**
|
|
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 Ck=[["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"}]],Ek=et("rotate-ccw",Ck);/**
|
|
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 _k=[["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"}]],Mk=et("rotate-cw",_k);/**
|
|
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 Ak=[["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"}]],eb=et("save",Ak);/**
|
|
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 Rk=[["path",{d:"m21 21-4.34-4.34",key:"14j7rj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]],Wi=et("search",Rk);/**
|
|
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 Ik=[["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"}]],Ia=et("send",Ik);/**
|
|
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 Tk=[["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"}]],So=et("server",Tk);/**
|
|
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 Pk=[["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"}]],xo=et("settings",Pk);/**
|
|
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 $k=[["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"}]],Dk=et("shield-alert",$k);/**
|
|
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 Lk=[["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"}]],Ok=et("shield",Lk);/**
|
|
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 Fk=[["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"}]],zk=et("skull",Fk);/**
|
|
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 Bk=[["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"}]],gs=et("sparkles",Bk);/**
|
|
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 Uk=[["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"}]],$u=et("square-check-big",Uk);/**
|
|
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 Hk=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]],Ii=et("square",Hk);/**
|
|
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 qk=[["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"}]],Rs=et("target",qk);/**
|
|
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 Vk=[["path",{d:"M12 19h8",key:"baeox8"}],["path",{d:"m4 17 6-6-6-6",key:"1yngyt"}]],Gi=et("terminal",Vk);/**
|
|
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 Wk=[["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"}]],zl=et("text-wrap",Wk);/**
|
|
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 Kk=[["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"}]],_n=et("trash-2",Kk);/**
|
|
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 Gk=[["path",{d:"M16 7h6v6",key:"box55l"}],["path",{d:"m22 7-8.5 8.5-5-5L2 17",key:"1t1m79"}]],Jk=et("trending-up",Gk);/**
|
|
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 Yk=[["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"}]],Oo=et("triangle-alert",Yk);/**
|
|
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 Qk=[["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"}]],Rm=et("unlink",Qk);/**
|
|
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 Xk=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]],Ea=et("user",Xk);/**
|
|
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 Zk=[["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"}]],tb=et("webhook",Zk);/**
|
|
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 ej=[["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"}]],Bl=et("workflow",ej);/**
|
|
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 tj=[["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"}]],Im=et("wrench",tj);/**
|
|
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 nj=[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]],un=et("x",nj);/**
|
|
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 sj=[["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"}]],as=et("zap",sj),tu="fusion:version-reload",nu="fusion:version-update";let Du=!0;function Tc(e){Du=e}function ij(){try{if(sessionStorage.getItem(nu))return sessionStorage.removeItem(nu),!0}catch{}return!1}function Lu(e){if(sessionStorage.getItem(tu)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(tu,"1"),!Du){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function aj(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|Unable to preload (?:CSS|module) for/i.test(n)}function rj(e){return aj(e)?(Lu(`chunk load error: ${e?.message??e}`),!0):!1}async function oj(){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 lj(){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&&(Du=!1)}catch{}}const cj=6e4;let Tm=0,Pc=!1;async function $c(){if(!(Pc||document.visibilityState!=="visible")&&!(Date.now()-Tm<cj)){Tm=Date.now(),Pc=!0;try{const e=await oj();if(e&&e!=="296392357-520c09a1"){try{sessionStorage.setItem(nu,"1")}catch{}Lu(`build version changed: 296392357-520c09a1 -> ${e}`)}}finally{Pc=!1}}}function dj(){lj(),window.setTimeout(()=>sessionStorage.removeItem(tu),5e3),document.addEventListener("visibilitychange",()=>{$c()}),window.addEventListener("focus",()=>{$c()}),window.setTimeout(()=>void $c(),2e3)}class Fo 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),!rj(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(Oo,{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 $s({children:e,onError:n}){return t.jsx(Fo,{level:"page",onError:n,children:e})}function _a({children:e,onError:n}){return t.jsx(Fo,{level:"modal",onError:n,children:e})}function uj({children:e,onError:n}){return t.jsx(Fo,{level:"root",onError:n,children:e})}const mj="modulepreload",hj=function(e){return"/"+e},Pm={},Sn=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=hj(u),u in Pm)return;Pm[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":mj,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)})},Ou="fn.authToken",$m="token",pj="fn_token";let mr,Dm=!1,Ul=!1;const su="fn:auth-token-recovery-required";function fj(){try{const e=window.localStorage.getItem(Ou);return e&&e.length>0?e:void 0}catch{return}}function nb(e){try{window.localStorage.setItem(Ou,e)}catch{}}function gj(){if(!(Dm||typeof window>"u")){Dm=!0;try{const e=new URL(window.location.href),n=e.searchParams.get($m);if(!n)return;nb(n),e.searchParams.delete($m);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function yr(){if(mr!==void 0)return mr;const e=gj();if(e)return mr=e,e;const n=fj();if(n)return mr=n,n}function bj(e){mr=e,Ul=!1,nb(e)}function xj(){mr=void 0,Ul=!1;try{window.localStorage.removeItem(Ou)}catch{}}function Lm(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function vj(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function yj(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!vj(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Lm(e.protocol)===Lm(n.protocol);return s&&a&&r}function wj(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 Di(e){const n=yr();if(!n||typeof window>"u")return e;const s=wj(e);return!s||!yj(s.parsed)?e:(s.parsed.searchParams.set(pj,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function wi(e){const n=yr();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function kj(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function jj(){typeof window>"u"||Ul||(Ul=!0,window.dispatchEvent(new CustomEvent(su)))}async function Nj(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();kj(a)&&jj()}catch{}}function Sj(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,yr();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=yr(),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=>(Nj(d),d))}}class sb extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function Cj(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Ts(e){return`/api${e}`}async function T(e,n={}){const s=Ts(e),a=yr(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),wi(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")||Cj(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 sb(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function Kz(){return T("/health")}function Gz(){return T("/updates/check")}function Ej(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 T(`/tasks${l}`)}async function La(e,n){const a=Ts(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:wi({"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 ib(e,n,s){const{title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:x,planningModelId:y,thinkingLevel:b,summarize:v,reviewLevel:S,executionMode:j,priority:C,source:w,nodeId:N,branch:R,baseBranch:z,githubTracking:E}=e;return Ho(V("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:x,planningModelId:y,thinkingLevel:b,summarize:v,reviewLevel:S,executionMode:j,priority:C,source:w,nodeId:N,branch:R,baseBranch:z,githubTracking:E})})}function Hs(e,n,s){return T(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function _j(e,n,s,a,r,o,l,c,d){return T(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 Mj(e,n,s,a){return T(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Aj(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return T(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Rj(e,n){return T(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Ij(e,n){return T(V(`/tasks/${e}/retry`,n),{method:"POST"})}function Tj(e,n){return T(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Pj(e,n){return T(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function ab(e,n){return T(V(`/tasks/${e}/pause`,n),{method:"POST"})}function $j(e,n){return T(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Dj(e,n){return T(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Lj(e,n){return T(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Oj(e){return T(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Fj(e,n){return T(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function zj(e,n){return T(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Bj(e){return T(V("/config",e))}function gc(e){return T(V("/settings",e))}function Xo(e,n){return T(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Uj(e){return T(V("/update-check",e))}function Jz(e){return T(V("/remote/settings",e))}function Yz(e,n){return T(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Qz(e){return T(V("/remote/status",e))}function Xz(e){return T(V("/remote/install-cloudflared",e),{method:"POST"})}function Zz(e){return T(V("/remote/tunnel/start",e),{method:"POST"})}function e3(e){return T(V("/remote/tunnel/stop",e),{method:"POST"})}function t3(e){return T(V("/remote/tunnel/kill-external",e),{method:"POST"})}function n3(e){return T(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function s3(e,n){return T(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function rb(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 i3(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=rb(null,s,a);return T(V(`/remote/url${r}`,n))}function a3(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=rb(e,a,r);return T(V(`/remote/qr${o}`,s))}function r3(e){return T(V("/memory",e))}function o3(e,n){return T(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function l3(e){return T(V("/memory/files",e))}function c3(e,n){const s=`path=${encodeURIComponent(e)}`;return T(V(`/memory/file?${s}`,n))}function d3(e,n,s){return T(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function u3(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 T(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function m3(e){return T(V("/memory/dream",e),{method:"POST"})}function h3(e){return T(V("/memory/insights",e))}function p3(e,n){return T(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function f3(e){return T(V("/memory/extract",e),{method:"POST"})}function g3(e){return T(V("/memory/audit",e))}function b3(e){return T(V("/memory/stats",e))}function x3(e){return T(V("/memory/backend",e))}function v3(e){return T(V("/memory/install-qmd",e),{method:"POST"})}function y3(e,n){return T(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Yi(){return T("/settings/global")}function Dn(e){return T("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function w3(e){return T(V("/settings/scopes",e))}function k3(e){return T(V("/settings/pi-extensions",e))}function j3(e,n){return T(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function N3(e,n,s){return T(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function S3(){return T("/pi-settings")}async function C3(e){return T("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function E3(e){return T("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function _3(e){return T(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function bc(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ts(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:wi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Hj(e,n,s){return T(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Om(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(Ts(o),{headers:wi()});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 qj(e,n,s,a){return T(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function Vj(e,n,s){return T(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Wj(e,n){return T(V(`/tasks/${e}/documents`,n))}function Kj(e,n,s){return T(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function M3(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 T(V(r,n))}function A3(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return T(V(r,e))}function Fm(e,n,s,a,r){return T(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function Gj(e,n,s){return T(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Jj(e,n,s){return T(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Yj(e,n,s){return T(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Qj(e,n){return T(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Xj(e,n,s){return T(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ks(){return T("/models")}function Zj(){return T("/usage")}function eN(){return T("/providers/claude-cli/status")}function tN(){return T("/system/fn-binary/status")}function nN(){return T("/system/fn-binary/install",{method:"POST"})}function sN(){return T("/providers/droid-cli/status")}function iN(){return T("/providers/cursor-cli/status")}function aN(){return T("/providers/llama-cpp/status")}async function R3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/hermes/status${n}`)}async function I3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await T(`/providers/hermes/profiles${n}`)).profiles??[]}async function T3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return T(`/providers/openclaw/status${n}`)}async function P3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),T(`/providers/paperclip/status?${n.toString()}`)}async function $3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await T(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function D3(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await T(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function L3(e){return T("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function O3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return T(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function F3(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 T(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function z3(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await T(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function B3(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return T(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function rN(e){return T("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function oN(e){return T("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function lN(e){return T("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function cN(e){return T("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function dN(){const n=(await T("/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 uN(e){return T("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function U3(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 T(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function H3(e){return T(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function mN(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return uN({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 Co(){return T("/auth/status")}function hN(e){return T("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function pN(e,n){return T("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function fN(e){return T("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function gN(e){return T("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function bN(e,n){return T("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function xN(e){return T("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function vN(e,n,s,a){return T("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function yN(e,n,s,a){return T(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function wN(e,n,s){return T("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function kN(e,n,s,a){return T(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function jN(e){return T(V("/git/remotes",e))}function NN(e){return T(V("/git/remotes/detailed",e))}function SN(e,n,s){return T(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function CN(e,n){return T(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function EN(e,n,s){return T(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function _N(e,n,s){return T(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function MN(e,n,s){return T(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function AN(e,n){return T(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function RN(e,n){return(await T(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Zo(e,n,s,a){return T(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function zm(e,n){return T(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function IN(e){return T(V("/terminal/sessions",e))}function gi(e){return T(V("/git/status",e))}function TN(e,n){const s=e?`?limit=${e}`:"";return T(V(`/git/commits${s}`,n))}function Hl(e,n){return T(V(`/git/commits/${e}/diff`,n))}function PN(e){return T(V("/git/commits/ahead",e))}function $N(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return T(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function qr(e){return T(V("/git/branches",e))}function DN(e,n,s){const a=`?limit=${n}`;return T(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function LN(e){return T(V("/git/worktrees",e))}function ON(e,n,s){return T(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function FN(e,n){return T(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Bm(e,n,s){const a=n?"?force=true":"";return T(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function zN(e,n){return T(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function BN(e,n){const s=typeof e=="string"?void 0:e;return T(V("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function UN(e){return T(V("/git/push",e),{method:"POST"})}function el(e){return T(V("/git/stashes",e))}function HN(e,n){return T(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function qN(e,n,s){return T(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function VN(e,n){return T(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function WN(e,n){return T(V(`/git/stashes/${e}/diff`,n))}function KN(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),T(V(`/git/diff/file?${a.toString()}`,s))}function nr(e){return T(V("/git/changes",e))}function Um(e,n){return T(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function GN(e,n){return T(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Hm(e,n){return T(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function JN(e,n){return T(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function YN(e){return T(V("/workspaces",e))}function QN(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),T(`/files?${a.toString()}`)}function XN(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function ZN(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function eS(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),T(`/files/search?${a.toString()}`)}function tS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function nS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function sS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),T(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function iS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),T(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function ob(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function aS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function rS(e,n,s){return T(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function oS(e,n,s,a,r){return T(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 qm(e,n,s,a){return T(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function lS(e,n,s){return T(V(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function cS(e,n,s){return T(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dS(e,n,s){return T(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function lb(e,n,s){return T(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function q3(e,n,s,a){return T(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function V3(e,n,s){return T(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function W3(e,n){return T(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function uS(e,n,s){return T(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function mS(e,n,s){return T(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function hS(e,n,s){return T(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const iu=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(iu))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function pS(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Tr(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=pS(e,d),g=new EventSource(Di(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=x=>{const y=x;m(y)&&n.onMessage?.(y)};for(const[x,y]of Object.entries(n.events??{}))g.addEventListener(x,b=>{const v=b;m(v)&&y(v)});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 y=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},y)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),iu.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return iu.add(f),f}function Vm(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 wr(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 fS(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 gS(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>fS(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function bS(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 Wm(e){return Array.isArray(e)?e.map(Vm):(e.candidates??[]).map(Vm)}async function xS(e){try{const n=await T(V("/dev-server/candidates",e));return Wm(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await T(V("/dev-server/detect",e));return Wm(s)}throw n}}function Fu(e){return T(V("/dev-server/status",e)).then(wr)}async function K3(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 T(V(`/dev-server/logs/history${a}`,n));return gS(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Fu(n);return bS(o.logs,e)}throw r}}function vS(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return T(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(wr)}function yS(e){return T(V("/dev-server/stop",e),{method:"POST"}).then(wr)}function wS(e){return T(V("/dev-server/restart",e),{method:"POST"}).then(wr)}async function kS(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await T(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return wr(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await T(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return wr(r)}throw a}}function G3(e){return Ts(V("/dev-server/logs/stream",e))}async function J3(e){try{return(await T(V("/devserver",e))).sessions??[]}catch{try{const n=await Fu(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 Y3(e,n){try{return await T(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Fu(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 Q3(e,n){try{return await T(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await vS({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 X3(e,n){try{return await T(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await yS(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 Z3(e,n){try{return await T(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await wS(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 e6(e,n,s){try{const a=await T(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 kS({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function t6(e){try{return(await T(V("/devserver/detect",e))).candidates??[]}catch{try{return(await xS(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function n6(e,n){return Ts(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function zo(e,n,s=25e3){const a=setInterval(()=>{f0(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function jS(e,n){return Ts(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function NS(e,n){return Ts(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function s6(e,n,s,a){const r=NS(e,n),o=Tr(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 SS(e,n,s,a){const r=jS(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Tr(r,{onOpen:()=>{c(),o=zo(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 Bo(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 CS(e){return T(Bo("/routines",e))}function ES(e,n){return T(Bo("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Km(e,n,s){return T(Bo(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function _S(e,n){await T(Bo(`/routines/${e}`,n),{method:"DELETE"})}function MS(e,n){return T(Bo(`/routines/${e}/trigger`,n),{method:"POST"})}function Gm(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 T(`/activity${s}`)}function AS(e){const n=V("/activity",e);return T(n,{method:"DELETE"})}function Uo(e){return T(V("/workflow-steps",e))}function Jm(e,n){return T(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function RS(e,n,s){return T(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function IS(e,n){return T(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Ym(e,n){return T(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function TS(e,n){return T(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function PS(){return T("/workflow-step-templates")}function $S(){return T("/plugin-workflow-step-templates")}function DS(e,n){return T(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Eo(e){return T(V("/scripts",e))}function LS(e,n,s){return T(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function OS(e,n){return T(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function cb(e,n,s){return(await T(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const tl={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 db(e){if(!(e instanceof Error))return tl.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?tl.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?tl.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:tl.NETWORK}function FS(e,n){return T(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function zS(e,n,s){return T(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function BS(e,n){return Ts(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function US(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Tr(BS(e,n),{onOpen:()=>{l(),r=zo(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 HS(e,n,s,a,r){return T(V("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,...r?.branch!==void 0?{branch:r.branch}:{},...r?.baseBranch!==void 0?{baseBranch:r.baseBranch}:{},...r?.branchSelection?{branchSelection:r.branchSelection}:{},...r?.branchAssignment?{branchAssignment:r.branchAssignment}:{},subtasks:n.map(o=>({tempId:o.id,title:o.title,description:o.description,size:o.suggestedSize,dependsOn:o.dependsOn}))})})}function ub(e,n,s){return T(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 qS(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 Ho(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=qS(e,s,a);return T(o,r)}function Pr(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 T(`/agents${a}`)}function au(e,n){return T(V(`/agents/${encodeURIComponent(e)}`,n))}function VS(e,n){return T(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function WS(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function i6(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ts(V(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:wi(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function a6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function r6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function o6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function l6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function c6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function d6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function u6(e,n,s){const a=`path=${encodeURIComponent(n)}`;return T(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function m6(e,n,s,a){return T(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function KS(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function GS(e,n){return T(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function h6(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 T(`/agents/${encodeURIComponent(e)}/runs${r}`)}function p6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function f6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function g6(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return T(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function b6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function JS(e){return T(V("/agents/stats",e))}function x6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function v6(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return T(`/agents/org-tree${a?`?${a}`:""}`)}function y6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Qm(e,n,s){return T(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function mb(e){return{reviewState:{source:e.mode,summary:e.summary??void 0,items:e.items.map(n=>({id:n.itemId,body:n.body,author:{login:n.author},createdAt:n.createdAt??new Date(0).toISOString(),updatedAt:n.updatedAt??void 0,path:n.filePath,threadId:n.threadId,htmlUrl:n.url,state:n.reviewState??void 0,isResolved:n.isResolved})),addressing:[],lastRefreshedAt:e.fetchedAt??void 0,refreshStatus:"ready",refreshSource:"initial-load"},automationStatus:null}}async function YS(e,n){const s=await T(V(`/tasks/${encodeURIComponent(e)}/review`,n));return mb(s)}async function QS(e,n){const s=await T(V(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return mb(s)}function XS(e,n,s){return T(V(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function w6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function k6(){return T("/agents/companies")}function j6(e,n){return T(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function N6(e,n){return T(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function S6(e,n){return T(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function C6(e){return T(V("/backups",e))}function E6(e){return T(V("/backups",e),{method:"POST"})}function _6(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return T(a)}function M6(e,n,s){return T(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function ZS(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function Xm(){return T("/projects/across-nodes")}function ql(){return T("/nodes")}function A6(){return T("/docker/nodes")}function R6(e){return T(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function I6(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return T(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function T6(e){return T("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function e1(e){return T("/nodes",{method:"POST",body:JSON.stringify(e)})}function t1(e){return T("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function n1(e,n){return T(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function s1(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config`)}function i1(e,n){return T(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function a1(e){return T(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function Zm(e){return T(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function r1(e){const n=await T(`/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()}}async function P6(){return T("/mesh/state")}function $6(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=yr();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return T(d)}function o1(e){return T("/projects",{method:"POST",body:JSON.stringify(e)})}function hb(e){return T(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function l1(e,n,s){return T(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function eh(e){return T(`/projects/${encodeURIComponent(e)}/health`)}function c1(e){return T(V("/executor/stats",e))}function d1(e){return T(V("/system-stats",e))}function u1(e){return T(V("/kill-vitest",e),{method:"POST"})}function th(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 T(`/activity-feed${s}`)}function m1(e){return T(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function h1(e){return T(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function D6(){return T("/global-concurrency")}function L6(e){return T("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function p1(e,n){return T(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function pb(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 T(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function f1(e,n){return T(V(`/tasks/${encodeURIComponent(e)}/commit-associations`,n))}function g1(e){return T(V("/missions",e))}function b1(e,n){return T(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function fb(e,n){return T(V(`/missions/${encodeURIComponent(e)}`,n))}function x1(e,n,s){return T(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function v1(e,n){return T(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function y1(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 T(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function w1(e){return T(V("/missions/health",e))}function k1(e,n,s){return T(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function j1(e,n,s){return T(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function N1(e,n){return T(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function S1(e,n,s){return T(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function C1(e,n,s){return T(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function E1(e,n){return T(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _1(e,n){return T(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function M1(e,n,s){return T(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function A1(e,n,s){return T(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function R1(e,n){return T(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function I1(e,n,s){return T(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function T1(e,n){return T(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function P1(e,n,s,a,r){return T(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function $1(e,n,s){return T(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify({})})}function Dc(e,n){return T(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function D1(e,n,s){return T(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function L1(e,n,s){return T(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function O1(e,n,s){return T(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function F1(e,n,s){return T(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function z1(e,n){return T(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Lc(e,n){return T(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function nh(e,n){return T(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function B1(e,n){return T(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function sh(e,n){return T(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function U1(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 T(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function H1(e,n){return T(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function q1(e,n){return T(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function V1(e,n){return T(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function W1(e,n){return T(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function K1(e,n,s){return T(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function G1(e,n,s){return T(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function J1(e,n,s,a){return T(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function Y1(e,n,s){return T(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function gb(e,n,s){return T(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Q1(e,n,s,a){return T(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function X1(e,n,s,a){const r=Ts(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Tr(r,{onOpen:()=>{c(),o=zo(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 qo(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Vo(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function Z1(e,n){return T(qo(e,"/start",n),{method:"POST"})}function e0(e,n,s,a){return T(qo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function t0(e,n,s,a){const r=Ts(qo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Tr(r,{onOpen:()=>{c(),o=zo(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 n0(e,n,s){return T(qo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function s0(e,n){return T(qo(e,"/skip",n),{method:"POST"})}function i0(e,n){return T(Vo(e,"/start",n),{method:"POST"})}function a0(e,n,s,a){return T(Vo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function r0(e,n,s,a){const r=Ts(Vo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Tr(r,{onOpen:()=>{c(),o=zo(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 o0(e,n,s){return T(Vo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function l0(e,n){return T(Vo(e,"/skip",n),{method:"POST"})}async function c0(e,n){try{return await T(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function O6(e){return T(V("/todos",e))}function F6(e,n){const s={title:e};return T(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function z6(e,n,s){const a={title:n};return T(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function B6(e,n){return T(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function U6(e,n,s){const a={text:n};return T(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function H6(e,n,s){const a=n;return T(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function q6(e,n){return T(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function V6(e,n,s){return T(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function kr(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function zu(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(Ts(`/ai-sessions${a?`?${a}`:""}`),{headers:wi()});return r.ok?(await r.json()).sessions??[]:[]}async function d0(e){return T(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function u0(e){return T(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Ti(e){const n=await fetch(Ts(`/ai-sessions/${encodeURIComponent(e)}`),{headers:wi()});return n.ok?n.json():null}async function m0(e,n){const s=await T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function h0(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function p0(e,n){return T(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function bb(e){await fetch(Ts(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:wi()})}function f0(e,n){return T(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function g0(e,n,s){return T(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function b0(e,n){return T(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function x0(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 T(`/messages/inbox${a}`)}function v0(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 T(`/messages/outbox${a}`)}function xb(e){return T(V("/messages/unread-count",e))}function y0(e,n){return T(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function w0(e,n){return T(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function k0(e){return T(V("/messages/read-all",e),{method:"POST"})}function j0(e,n){return T(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function N0(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return T(V(a,s))}function S0(e,n){return T(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function C0(e){return T(V("/agents/mailbox/all",e))}function nl(e,n){const s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return T(`/approvals${a}`)}function ih(e,n){return T(V(`/approvals/${encodeURIComponent(e)}`,n))}function E0(e,n,s){return T(V(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function W6(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 T(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function K6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function G6(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return T(`/agents/${encodeURIComponent(e)}/performance${r}`)}function J6(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 T(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function Y6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function Q6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function X6(e,n,s){return T(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function Z6(e,n){return T(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function e5(e,n){return T(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function t5(e){return T(V("/plugins",e))}async function n5(e,n){return T(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function s5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function i5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function a5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function r5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function o5(e,n,s){return T(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function l5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function c5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function d5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function u5(e,n,s){return T(V(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function m5(e,n){return T(V(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function _0(e){return T(V("/plugins/ui-slots",e))}async function M0(e){return T(V("/plugins/dashboard-views",e))}async function h5(e){return T(V("/plugins/runtimes",e))}async function A0(e){return(await T(V("/skills/discovered",e))).skills}async function p5(e,n,s){return T(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function f5(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 T(V(`/skills/catalog${r}`,s))}async function g5(e,n){return(await T(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function ah(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return T(`/chat/sessions${a?`?${a}`:""}`)}async function R0(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 T(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function I0(e,n){return T(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function T0(e,n){return T(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function b5(e,n,s){return T(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function x5(e,n){return T(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Vr(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 T(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function v5(e={},n){const s=new URLSearchParams;n&&s.set("projectId",n),e.status&&s.set("status",e.status),e.agentId&&s.set("agentId",e.agentId);const a=s.toString();return T(`/chat/rooms${a?`?${a}`:""}`)}function y5(e,n){const s={...e,...n?{projectId:n}:{}};return T(V("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function w5(e,n){return T(V(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function k5(e,n){return T(V(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function j5(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 T(V(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function N5(e,n,s){return T(V(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function P0(e,n){return T(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function $0(e,n,s,a,r,o){const l=Ts(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1,m=!1;const h=Math.max(1e3,6e4);let f=null;const p=()=>{f&&(clearTimeout(f),f=null)},g=()=>{m||(m=!0,p())},x=(y,b)=>{if(y)switch(g(),y){case"thinking":try{s.onThinking?.(JSON.parse(b))}catch{s.onThinking?.(b)}break;case"text":try{s.onText?.(JSON.parse(b))}catch{s.onText?.(b)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(b))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(b))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(b))}catch{}break;case"done":u=!0;try{const v=JSON.parse(b);s.onDone?.({messageId:typeof v.messageId=="string"?v.messageId:"",...v.message&&typeof v.message=="object"?{message:v.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0;try{const v=JSON.parse(b);s.onError?.(v.message||v)}catch{s.onError?.(b||"Stream error")}break}};return(async()=>{try{const y=Array.isArray(a)&&a.length>0,b=y?(()=>{const E=new FormData;return E.append("content",n),a.forEach(I=>E.append("attachments",I)),E})():JSON.stringify({content:n}),v=await fetch(l,{method:"POST",headers:y?wi():wi({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!v.ok){const E=await v.text();let I=`Request failed: ${v.status}`;try{I=JSON.parse(E).error||I}catch{}s.onError?.(I);return}if(!v.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),f=setTimeout(()=>{u||d||m||(u=!0,s.onError?.("Timed out waiting for first response event"),c.abort())},h);const S=v.body.getReader(),j=new TextDecoder;let C="",w="",N=[];const R=(E,I=!1)=>{C+=E;const O=C.split(`
|
|
643
|
+
`);C=O.pop()||"",I&&C.length>0&&(O.push(C),C="");for(const U of O){const A=U.endsWith("\r")?U.slice(0,-1):U;if(A.startsWith("event:"))w=A.slice(6).trim();else if(A.startsWith("data:")){const D=A.slice(5);N.push(D.startsWith(" ")?D.slice(1):D)}else if(A===""){const D=N.join(`
|
|
644
|
+
`);x(w,D),w="",N=[]}}if(I&&w&&N.length>0){const U=N.join(`
|
|
645
|
+
`);x(w,U),w="",N=[]}};for(;;){const{done:E,value:I}=await S.read();if(E){R(j.decode(),!0);break}R(j.decode(I,{stream:!0}))}const z=C.length>0||w.length>0||N.length>0;!u&&!d&&!z&&s.onError?.("Connection closed unexpectedly"),p()}catch(y){if(y instanceof DOMException&&y.name==="AbortError"){!d&&!u&&s.onError?.("Connection aborted"),p();return}if(d){p();return}p(),s.onError?.(y instanceof Error?y.message:"Connection error")}})(),{close:()=>{d=!0,p(),c.abort()},isConnected:()=>!d}}function D0(e,n,s,a){const r=Ts(V(`/chat/sessions/${encodeURIComponent(e)}/stream`,s)),o=new AbortController;let l=!1,c=!1;const d=(u,m)=>{if(u)switch(u){case"thinking":try{n.onThinking?.(JSON.parse(m))}catch{n.onThinking?.(m)}break;case"text":try{n.onText?.(JSON.parse(m))}catch{n.onText?.(m)}break;case"tool_start":try{n.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{n.onToolEnd?.(JSON.parse(m))}catch{}break;case"fallback":try{n.onFallback?.(JSON.parse(m))}catch{}break;case"done":c=!0;try{const h=JSON.parse(m);n.onDone?.({messageId:typeof h.messageId=="string"?h.messageId:"",...h.message&&typeof h.message=="object"?{message:h.message}:{}})}catch{n.onDone?.({messageId:""})}break;case"error":c=!0;try{const h=JSON.parse(m);n.onError?.(h.message||h)}catch{n.onError?.(m||"Stream error")}break}};return(async()=>{try{const u=new Headers(wi());typeof a?.lastEventId=="number"&&u.set("Last-Event-ID",String(a.lastEventId));const m=await fetch(r,{method:"GET",headers:u,signal:o.signal});if(!m.ok){const v=await m.text();let S=`Request failed: ${m.status}`;try{S=JSON.parse(v).error||S}catch{}n.onError?.(S);return}if(!m.body){n.onError?.("No response body");return}n.onConnectionStateChange?.("connected");const h=m.body.getReader(),f=new TextDecoder;let p="",g="",x=[];const y=(v,S=!1)=>{p+=v;const j=p.split(`
|
|
646
|
+
`);p=j.pop()||"",S&&p.length>0&&(j.push(p),p="");for(const C of j){const w=C.endsWith("\r")?C.slice(0,-1):C;if(w.startsWith("event:"))g=w.slice(6).trim();else if(w.startsWith("data:")){const N=w.slice(5);x.push(N.startsWith(" ")?N.slice(1):N)}else if(w===""){const N=x.join(`
|
|
647
|
+
`);d(g,N),g="",x=[]}}if(S&&g&&x.length>0){const C=x.join(`
|
|
648
|
+
`);d(g,C),g="",x=[]}};for(;;){const{done:v,value:S}=await h.read();if(v){y(f.decode(),!0);break}y(f.decode(S,{stream:!0}))}const b=p.length>0||g.length>0||x.length>0;if(!c&&!l&&!b)return}catch(u){if(u instanceof DOMException&&u.name==="AbortError"){!l&&!c&&n.onError?.("Connection aborted");return}if(l)return;n.onError?.(u instanceof Error?u.message:"Connection error")}})(),{close:()=>{l=!0,o.abort()},isConnected:()=>!l}}function S5(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 T(V(`/insights${a}`,n))}function C5(e,n){return T(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function E5(e,n){return T(V(`/insights/${encodeURIComponent(e)}/archive`,n),{method:"POST"})}function _5(e,n){return T(V(`/insights/${encodeURIComponent(e)}/unarchive`,n),{method:"POST"})}function M5(e="manual",n,s,a,r){const o={trigger:e,inputMetadata:n};return a&&(o.modelProvider=a),r&&(o.modelId=r),T(V("/insights/run",s),{method:"POST",body:JSON.stringify(o)})}function A5(e){return T(V("/insights/runs",e))}function R5(e,n){return T(V(`/insights/runs/${encodeURIComponent(e)}`,n))}function I5(e,n){return T(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function T5(e={},n){const s=new URLSearchParams;e.q&&s.set("q",e.q),e.runId&&s.set("runId",e.runId),e.scoreMin!==void 0&&s.set("scoreMin",String(e.scoreMin)),e.scoreMax!==void 0&&s.set("scoreMax",String(e.scoreMax)),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 T(V(`/evals${a}`,n))}function P5(e,n){return T(V(`/evals/${encodeURIComponent(e)}`,n))}function $5(e){return T(V("/evals/runs",e))}function D5(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 T(V(`/research/runs${a}`,n))}function L5(e,n){return T(V("/research/runs",n),{method:"POST",body:JSON.stringify(e)})}function O5(e,n){return T(V(`/research/runs/${encodeURIComponent(e)}`,n))}function vb(e){if(e instanceof sb){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 F5(e,n){try{return await T(V(`/research/runs/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}catch(s){vb(s)}}async function z5(e,n){try{return await T(V(`/research/runs/${encodeURIComponent(e)}/retry`,n),{method:"POST"})}catch(s){vb(s)}}function B5(e,n,s){return T(V(`/research/runs/${encodeURIComponent(e)}/export?format=${encodeURIComponent(n)}`,s))}function U5(e,n,s){const a=n.findingId??"finding-1";return T(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 H5(e,n,s){const a=n.findingId??"finding-1";return T(V(`/research/runs/${encodeURIComponent(e)}/findings/${encodeURIComponent(a)}/tasks/${encodeURIComponent(n.taskId)}/enrich`,s),{method:"POST",body:JSON.stringify({attachExport:n.attachExport})})}async function L0(e){return Ho("/health",{nodeId:e})}async function O0(e){return Ho("/projects",{nodeId:e})}async function F0(e,n,s){const a=new URLSearchParams({projectId:n});return s&&s.trim()&&a.set("q",s.trim()),Ho(`/tasks?${a.toString()}`,{nodeId:e})}async function z0(e,n){return Ho(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function q5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function V5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function W5(e){return T(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function K5(e){return T(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}async function B0(e,n){return Promise.all(n.map(({projectId:s,path:a})=>l1(s,e,a)))}function U0(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 H0({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}=U0(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 q0(e){return e.charAt(0).toUpperCase()+e.slice(1)}function Oa({status:e,showLabel:n=!1,className:s,compact:a=!1}){const r=q0(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 rh=new Map,V0=6e4;function yb(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=rh.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 _0(e);if(h||d.current)return;rh.set(m,{slots:x,expiresAt:Date.now()+V0}),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 oh({size:e,color:n,label:s="llama.cpp"}){return t.jsx(Wg,{size:e,color:n,"aria-label":s,"data-testid":"llama-cpp-icon"})}const W0={sm:16,md:20,lg:24};function K0({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 lh({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 _i({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 G0({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 ch({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 J0({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 Oc({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 dh({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 uh({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 mh({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 Fc({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 hh({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 Wr({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 ph({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 zc({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 fh({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 Bc({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 Y0({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 Q0({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 gh({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 Uc({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 X0({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 bh({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 Hc({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 xh({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 qc({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 vh({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 Z0({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"})]})}function eC({size:e,color:n,label:s="Cursor — via Cursor 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":"cursor-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:"M10.8 7.2a3.6 3.6 0 1 0 0 5.6",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 tC={anthropic:{component:K0,color:"var(--provider-anthropic)"},"claude-cli":{component:vh,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:vh,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"droid-cli":{component:Z0,color:"var(--provider-openai)",label:"Factory AI — via Droid CLI"},"cursor-cli":{component:eC,color:"var(--provider-cursor-cli)",label:"Cursor — via Cursor CLI"},"llama-cpp":{component:oh,color:"var(--provider-ollama)",label:"llama.cpp"},"llama-server":{component:oh,color:"var(--provider-ollama)",label:"llama.cpp"},openai:{component:lh,color:"var(--provider-openai)"},"openai-codex":{component:lh,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:_i,color:"var(--provider-gemini)"},gemini:{component:_i,color:"var(--provider-gemini)"},"google-antigravity":{component:_i,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:_i,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:_i,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:_i,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:_i,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:_i,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:_i,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:_i,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:G0,color:"var(--text)"},github:{component:bh,color:"var(--text)"},"github-copilot":{component:bh,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:X0,color:"var(--provider-openrouter)"},minimax:{component:ch,color:"var(--provider-minimax)"},"minimax-cn":{component:ch,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:J0,color:"var(--provider-zai)"},kimi:{component:Oc,color:"var(--provider-kimi)"},moonshot:{component:Oc,color:"var(--provider-kimi)"},"kimi-coding":{component:Oc,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:dh,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:dh,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:uh,color:"var(--text)"},grok:{component:uh,color:"var(--text)",label:"xAI"},opencode:{component:mh,color:"var(--provider-opencode)"},"opencode-go":{component:mh,color:"var(--provider-opencode)",label:"Opencode (Go)"},deepseek:{component:Fc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deepseek-ai":{component:Fc,color:"var(--provider-deepseek)",label:"DeepSeek"},"deep-seek":{component:Fc,color:"var(--provider-deepseek)",label:"DeepSeek"},cloudflare:{component:hh,color:"var(--provider-cloudflare)",label:"Cloudflare"},cloudflared:{component:hh,color:"var(--provider-cloudflare)",label:"Cloudflare"},qwen:{component:Wr,color:"var(--provider-qwen)"},"qwen-ai":{component:Wr,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Wr,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Wr,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Wr,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:ph,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:ph,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:zc,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:zc,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:zc,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:fh,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:fh,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:Bc,color:"var(--provider-azure)"},"azure-openai":{component:Bc,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:Bc,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:Uc,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:Uc,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:Uc,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Y0,color:"var(--provider-cerebras)"},groq:{component:Q0,color:"var(--provider-groq)"},vercel:{component:gh,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:gh,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:Hc,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:Hc,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:Hc,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:xh,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:xh,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:qc,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:qc,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:qc,color:"var(--provider-paperclip)",label:"Paperclip"}};function Fn({provider:e,size:n="sm"}){const s=e.toLowerCase(),a=tC[s],r=a?.component,o=a?.color??"var(--text-muted)",l=a?.label,c=W0[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(Wg,{size:c})})}function wb({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 sN();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 v=await oN(b);u.current&&d({kind:v.enabled?"enabled":"disabled",restartRequired:v.restartRequired}),n?.(v.enabled),await m()}catch(v){u.current&&d({kind:"error",message:v instanceof Error?v.message:String(v)})}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."]}),y=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(jt,{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(Fn,{provider:"droid-cli",size:"sm"}),t.jsx("strong",{children:"Factory AI — via Droid CLI"}),t.jsx(nC,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:y})]}),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(yh,{status:a,authenticated:e}),c&&t.jsx(wh,{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(Fn,{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(yh,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:y}),c&&t.jsx(wh,{action:c})]})}function nC({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 yh({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(jt,{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 wh({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 kh({actions:e}){return t.jsx(wb,{compact:!0,authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function sC({actions:e}){return t.jsx(wb,{authenticated:!1,onToggled:()=>{e?.refreshAuthProviders?.()}})}function iC(){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 aC({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 rC=[{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-provider-card",componentPath:"./components/settings-provider-card.js",component:kh},{pluginId:"fusion-plugin-droid-runtime",slotId:"settings-integration-card",componentPath:"./components/settings-integration-card.js",component:kh},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-provider-card",componentPath:"./components/onboarding-provider-card.js",component:sC},{pluginId:"fusion-plugin-droid-runtime",slotId:"onboarding-setup-help",componentPath:"./components/onboarding-setup-help.js",component:iC},{pluginId:"fusion-plugin-droid-runtime",slotId:"post-onboarding-recommendation",componentPath:"./components/post-onboarding-recommendation.js",component:aC}];function oC(e){return rC.find(s=>s.pluginId===e.pluginId&&s.slotId===e.slot.slotId&&s.componentPath===e.slot.componentPath)?.component??null}function lC({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 la({slotId:e,projectId:n,pluginIds:s,renderPlaceholder:a=!0,actions:r}){const{getSlotsForId:o,loading:l,error:c}=yb(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(Fo,{level:"page",children:t.jsx(t.Fragment,{children:d.map((u,m)=>{const h=`${u.pluginId}-${u.slot.slotId}-${m}`,f=oC(u);return f?t.jsx(f,{entry:u,actions:r},h):a?t.jsx(lC,{slotId:u.slot.slotId,pluginId:u.pluginId},h):null})})})}function cC(){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 ri(){const[e,n]=i.useState(cC);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 $r(e){return e.replace(/\\/g,"/")}function Bu(e){return e.replace(/[\\/]+$/g,"")}function Uu(e){const n=$r(Bu(e));return n?n.split("/").filter(Boolean):[]}function Hu(e){const n=$r(Bu(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function kb(e,n){const s=Uu(e);return s.length===0?$r(e):s.slice(-2).join("/")}function dC(e){const n=$r(Bu(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function uC(e,n){return!e||e==="."?n:[...Uu(e),n].join("/")}function mC(e){const n=Uu(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function G5(e){const n=$r(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 qu=new Map;function Wo(e,n){return`plugin:${e}:${n}`}function jb(e){const n=/^plugin:([^:]+):(.+)$/u.exec(e);return n?{pluginId:n[1],viewId:n[2]}:null}function pr(e){return jb(e)!==null}function sl(e,n,s){qu.set(Wo(e,n),s)}function hC(e,n){return qu.get(Wo(e,n))??null}function Nb(e,n){return qu.has(Wo(e,n))}function Vc({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(Oo,{}),"Plugin view unavailable"]}),t.jsxs("p",{className:"plugin-dashboard-view-missing-description",children:["No host registration found for ",t.jsx("code",{children:e}),"."]})]})}function pC({viewId:e,context:n}){const s=jb(e);if(!s)return t.jsx(Vc,{viewId:e});const a=hC(s.pluginId,s.viewId);return a?t.jsx(Fo,{fallback:t.jsx(Vc,{viewId:e}),children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a,{context:n})})}):t.jsx(Vc,{viewId:e})}const vo=Wo,fC={activity:Ys,bot:zn,brain:No,checksquare:$u,clock:Ji,filetext:ua,folder:Es,gitbranch:Fs,grid3x3:uc,layoutgrid:ma,mail:Da,map:nk,messagesquare:Ki,monitor:vr,search:Wi,sparkles:gs,target:Rs,workflow:Bl,zap:as};function gC(e){return(e??"").trim().toLowerCase().replace(/[-_\s]/g,"")}function Vl(e){return fC[gC(e)]??uc}const il="__fusion:no-branch__",Sb={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function bC({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(pn,{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=Sb[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:kb(d.path)})]}),u&&t.jsx(js,{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 jh({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 xC({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:a,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,stashOrphanCount:f=0,onOpenSchedules:p,onOpenGitManager:g,onOpenNodes:x,showNodesButton:y,onOpenWorkflowSteps:b,onOpenScripts:v,onRunScript:S,onToggleTerminal:j,onOpenFiles:C,filesOpen:w,onOpenTodos:N,todosOpen:R,todosEnabled:z,globalPaused:E,enginePaused:I,onToggleGlobalPause:O,onToggleEnginePause:U,view:A="board",onChangeView:D,showSkillsTab:K,showAgentsTab:Z,searchQuery:ne="",onSearchChange:F,branchFilter:M="",baseBranchFilter:P="",branchOptions:$=[],baseBranchOptions:k=[],onBranchFilterChange:J,onBaseBranchFilterChange:ce,projects:je=[],currentProject:He,onSelectProject:xe,onViewAllProjects:Ne,projectId:Y,shellHost:ie={kind:"browser"},mobileNavEnabled:ee,availableNodes:oe=[],currentNode:W,onSelectNode:L,isRemote:pe=!1,experimentalFeatures:fe,pluginDashboardViews:B=[],shellConnectionControl:ve}){const Fe=ri(),ae=Fe==="mobile",Pe=ae||Fe==="tablet",nt=ae&&ee,[Be,de]=i.useState(!1),[Ie,$e]=i.useState(!1),[st,Ue]=i.useState(!1),[me,re]=i.useState(!1),[_e,xt]=i.useState(!1),[dt,Qe]=i.useState(!1),[vt,Ae]=i.useState(!1),[Je,ct]=i.useState(!1),[Nt,yt]=i.useState(!1),[Se,G]=i.useState(!1),[ge,pt]=i.useState(!1),[ke,tt]=i.useState({}),[Rt,Re]=i.useState(!1),[be,at]=i.useState(-1),[ot,gt]=i.useState(null),[St,Lt]=i.useState({}),[Yt,tn]=i.useState(!1),mn=i.useRef(null),Qt=i.useRef(null),yn=i.useRef(null),Gt=i.useRef(null),on=i.useRef(null),sn=i.useRef(null),ln=i.useRef(!1),Wt=i.useRef(null),ye=i.useRef(null),Le=i.useRef(null),Ke=i.useRef(null),ut=i.useRef(null),Ve=i.useRef(null),Pt=i.useRef(null),Ot=i.useRef(null),bt=i.useRef(!1),Dt=i.useMemo(()=>oe.filter(le=>le.type==="remote"),[oe]),Ft=Dt.length>0,Ht=i.useMemo(()=>Object.entries(ke).sort(([le],[lt])=>le.localeCompare(lt)),[ke]),rn=Ht.length>0,Xt=Ht.length+(rn?1:0),an=i.useMemo(()=>Object.entries(St).sort(([le],[lt])=>le.localeCompare(lt)),[St]),Me=i.useMemo(()=>!!(D||fe?.researchView||z||fe?.insights||K||fe?.memoryView||fe?.devServerView||!nt||B.some(le=>le.view.placement!=="primary")),[D,fe,z,K,nt,B]),it=i.useCallback(()=>{const le=window.visualViewport;return le&&le.width>0&&le.height>0?{width:le.width,height:le.height,offsetTop:le.offsetTop,offsetLeft:le.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),kt=i.useCallback(()=>{const le=Pt.current;if(!le)return;const lt=le.getBoundingClientRect(),nn=Ot.current,{width:Rn,height:Hn,offsetTop:wn,offsetLeft:rs}=it(),_s=16,bn=16,Ut=6,xs=nn?.offsetWidth||Math.max(lt.width,260),xn=Math.min(xs,Math.max(Rn-_s*2,160)),Xn=nn?.offsetHeight||280,$n=Math.min(Xn,Math.max(Hn-bn*2,160)),vs=lt.top-wn,ms=lt.bottom-wn,hs=lt.right-rs,Jn=Hn-ms,ps=vs,Ns=Jn<$n&&ps>Jn,Yn=Math.min(Math.max(hs-xn,_s),Rn-_s-xn)+rs,ys=Ns?Math.max(bn+wn,vs-$n-Ut+wn):Math.min(ms+Ut+wn,Hn+wn-bn-$n);gt({top:ys,left:Yn,width:xn})},[it]),$t=i.useCallback((le,lt)=>{S?.(le,lt),pt(!1),at(-1)},[S]),se=i.useCallback(()=>{v?.(),pt(!1),at(-1)},[v]),te=i.useCallback(le=>{switch(le.key){case"ArrowDown":le.preventDefault(),Xt>0&&at(lt=>lt<Xt-1?lt+1:0);break;case"ArrowUp":le.preventDefault(),Xt>0&&at(lt=>lt>0?lt-1:Xt-1);break;case"Enter":if(le.preventDefault(),be>=0)if(be<Ht.length){const[lt,nn]=Ht[be];$t(lt,nn)}else rn&&be===Ht.length&&se();break;case"Home":le.preventDefault(),Xt>0&&at(0);break;case"End":le.preventDefault(),Xt>0&&at(Xt-1);break}},[se,$t,be,Ht,rn,Xt]);i.useEffect(()=>{ln.current=_e},[_e]),i.useEffect(()=>{bt.current=ge},[ge]),i.useEffect(()=>{if(!_e||!Pe)return;let le=!1;return tn(!0),Eo(Y).then(lt=>{le||Lt(lt)}).catch(()=>{le||Lt({})}).finally(()=>{le||tn(!1)}),()=>{le=!0}},[_e,Pe,Y]),i.useEffect(()=>{if(!ge||Pe)return;let le=!1;return Re(!0),Eo(Y).then(lt=>{le||tt(lt)}).catch(()=>{le||tt({})}).finally(()=>{le||Re(!1)}),()=>{le=!0}},[ge,Pe,Y]),i.useEffect(()=>{if(!ge)return;const le=lt=>{Ve.current&&!Ve.current.contains(lt.target)&&pt(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[ge]),i.useEffect(()=>{if(!ge)return;const le=lt=>{lt.key==="Escape"&&(pt(!1),Pt.current?.focus())};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[ge]),i.useEffect(()=>{if(ge){at(-1);const le=window.setTimeout(()=>Ot.current?.focus(),0);return()=>window.clearTimeout(le)}gt(null)},[ge]),i.useEffect(()=>{if(!ge)return;const le=requestAnimationFrame(()=>{kt()});return()=>cancelAnimationFrame(le)},[ge,Rt,Ht.length,rn,kt]),i.useEffect(()=>{if(!ge)return;const le=()=>kt();window.addEventListener("resize",le),window.addEventListener("scroll",le,!0);const lt=window.visualViewport;return lt&&(lt.addEventListener("resize",le),lt.addEventListener("scroll",le)),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0),lt&&(lt.removeEventListener("resize",le),lt.removeEventListener("scroll",le))}},[ge,kt]),i.useEffect(()=>{Pe&&(pt(!1),at(-1))},[Pe]);const De=Be||ne.length>0,ft=(Ie||ne.length>0)&&!st,qt=(A==="board"||A==="list")&&!ae&&F&&!st&&ne.length===0,zt=(A==="board"||A==="list")&&!ae&&F,Pn=A==="board";i.useEffect(()=>{ne===""&&Ue(!1)},[ne]),i.useEffect(()=>{if(!me)return;const le=lt=>{Qt.current&&!Qt.current.contains(lt.target)&&mn.current&&!mn.current.contains(lt.target)&&re(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[me]),i.useEffect(()=>{if(!Nt)return;const le=lt=>{Gt.current&&!Gt.current.contains(lt.target)&&yn.current&&!yn.current.contains(lt.target)&&yt(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Nt]),i.useEffect(()=>{if(!dt)return;const le=lt=>{Wt.current&&!Wt.current.contains(lt.target)&&Qe(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[dt]),i.useEffect(()=>{const le=lt=>{if(lt.key==="Escape"){if(ct(!1),yt(!1),ln.current){xt(!1);return}if(bt.current){pt(!1),Pt.current?.focus();return}re(!1),de(!1),Qe(!1),Ae(!1)}};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[]),i.useEffect(()=>{if(!vt)return;const le=lt=>{ye.current&&!ye.current.contains(lt.target)&&Ae(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[vt]),i.useEffect(()=>{if(!Se)return;const le=lt=>{ut.current&&!ut.current.contains(lt.target)&&G(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Se]),i.useEffect(()=>{if(!Se)return;const le=lt=>{lt.key==="Escape"&&G(!1)};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[Se]),i.useEffect(()=>{if(!Je)return;const le=lt=>{Le.current&&!Le.current.contains(lt.target)&&Ke.current&&!Ke.current.contains(lt.target)&&ct(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Je]);const he=i.useCallback(()=>{de(le=>!le)},[]),mt=i.useCallback(()=>{$e(!0),Ue(!1)},[]),ht=i.useCallback(()=>{$e(!1),Ue(!0),F&&F("")},[F]),wt=i.useCallback(()=>{re(le=>!le)},[]),Xe=i.useCallback(le=>{le&&le(),re(!1),xt(!1)},[]),Et=i.useCallback(()=>{de(!1),F&&F("")},[F]),Zt=ie.kind==="desktop-shell";return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header","data-shell-kind":ie.kind,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"})]}),ae&&je.length>=1&&xe&&t.jsxs("div",{className:"mobile-project-switch",ref:ye,children:[t.jsx("button",{className:`mobile-project-switch-trigger${vt?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ae(le=>!le),title:"Switch project","aria-label":"Switch project","aria-expanded":vt,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(pn,{size:14,className:`mobile-project-switch-chevron${vt?" mobile-project-switch-chevron--open":""}`})}),vt&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:je.map(le=>{const lt=He?.id===le.id,nn=Sb[le.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${lt?" mobile-project-switch-item--current":""}`,onClick:()=>{xe(le),Ae(!1)},role:"option","aria-selected":lt,"data-testid":`mobile-project-switch-item-${le.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:nn||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:le.name}),t.jsx("span",{className:"mobile-project-switch-path",children:kb(le.path)})]}),lt&&t.jsx(js,{size:14,className:"mobile-project-switch-check"})]},le.id)})})]}),!Pe&&je.length>=1&&Ne&&t.jsx(bC,{projects:je,currentProject:He??null,onViewAll:Ne,onSelectProject:xe}),Ft&&t.jsxs("div",{className:`header-node-selector${ae?" header-node-selector--mobile":""}`,ref:ae?void 0:Wt,children:[t.jsx(H0,{node:W??null,showDetails:!ae}),!ae&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${dt?" node-selector-trigger--open":""}`,onClick:()=>Qe(le=>!le),title:"Switch node","aria-label":"Switch node","aria-expanded":dt,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(On,{size:12,className:`node-selector-chevron${dt?" node-selector-chevron--open":""}`})}),dt&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${pe?"":" node-selector-option--active"}`,onClick:()=>{L?.(null),Qe(!1)},role:"option","aria-selected":!pe,"data-testid":"node-option-local",children:[t.jsx(Oa,{status:"online",compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Dt.map(le=>t.jsxs("button",{className:`node-selector-option${W?.id===le.id?" node-selector-option--active":""}`,onClick:()=>{L?.(le),Qe(!1)},role:"option","aria-selected":W?.id===le.id,"data-testid":`node-option-${le.id}`,children:[t.jsx(Oa,{status:le.status,compact:!0}),t.jsx("span",{className:"node-selector-option-label",children:le.name}),t.jsx("span",{className:"node-selector-option-status",children:le.status})]},le.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ve,nt&&D&&(A==="board"||A==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${A==="board"?" active":""}`,onClick:()=>D("board"),title:"Board view","aria-label":"Board view","aria-pressed":A==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(ma,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="list"?" active":""}`,onClick:()=>D("list"),title:"List view","aria-label":"List view","aria-pressed":A==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Zd,{size:16})})]}),F&&ae&&(nt||A==="board"||A==="list")&&!De&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:he,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Wi,{size:16})}),qt&&t.jsx("button",{className:"btn-icon",onClick:mt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Wi,{size:16})}),ae&&nt&&o&&t.jsx("button",{className:"btn-icon",onClick:le=>o(le.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ys,{size:16})}),!nt&&D&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${A==="board"?" active":""}`,onClick:()=>D("board"),title:"Board view","aria-label":"Board view","aria-pressed":A==="board",children:t.jsx(ma,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="list"?" active":""}`,onClick:()=>D("list"),title:"List view","aria-label":"List view","aria-pressed":A==="list",children:t.jsx(Zd,{size:16})}),Z&&t.jsx("button",{className:`view-toggle-btn${A==="agents"?" active":""}`,onClick:()=>D("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":A==="agents",children:t.jsx(zn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${A==="missions"?" active":""}`,onClick:()=>D("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":A==="missions",children:t.jsx(Rs,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${A==="chat"?" active":""}`,onClick:()=>D("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":A==="chat","data-testid":"header-chat-view-btn",children:[t.jsx(Ki,{size:16}),h&&A!=="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${A==="documents"?" active":""}`,onClick:()=>D("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":A==="documents",children:t.jsx(ua,{size:16})}),t.jsxs("button",{className:`view-toggle-btn${A==="mailbox"?" active":""}`,onClick:()=>D("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":A==="mailbox",children:[t.jsx(Da,{size:16}),m>0&&A!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending header-chat-unread-dot","aria-label":"Pending approvals"})]}),B.filter(le=>le.view.placement==="primary").sort((le,lt)=>(le.view.order??Number.MAX_SAFE_INTEGER)-(lt.view.order??Number.MAX_SAFE_INTEGER)).map(le=>{const lt=vo(le.pluginId,le.view.viewId),nn=Vl(le.view.icon);return t.jsx("button",{className:`view-toggle-btn${A===lt||A==="graph"&&le.pluginId==="fusion-plugin-dependency-graph"&&le.view.viewId==="graph"?" active":""}`,onClick:()=>D(le.pluginId==="fusion-plugin-dependency-graph"&&le.view.viewId==="graph"?"graph":lt),title:`${le.view.label} view`,"aria-label":`${le.view.label} view`,"aria-pressed":A===lt,"data-testid":`view-toggle-plugin-${le.pluginId}-${le.view.viewId}`,children:t.jsx(nn,{size:16})},`${le.pluginId}:${le.view.viewId}`)}),Me&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:Ke,className:`view-toggle-btn${["research","skills","insights","memory","dev-server","devserver","graph","stash-recovery"].includes(A)||fe?.evalsView&&A==="evals"||z&&R||pr(A)?" active":""}`,onClick:()=>ct(le=>!le),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Je,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(pn,{size:12})}),Je&&t.jsxs("div",{ref:Le,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[fe?.evalsView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="evals"?" active":""}`,onClick:()=>{D("evals"),ct(!1)},role:"menuitem","data-testid":"view-overflow-evals",children:[t.jsx(Rs,{size:14}),t.jsx("span",{children:"Evals"})]}),t.jsxs("button",{className:`view-toggle-overflow-item${A==="stash-recovery"?" active":""}`,onClick:()=>{D("stash-recovery"),ct(!1)},role:"menuitem","data-testid":"view-overflow-stash-recovery",children:[t.jsx(Pa,{size:14}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"btn-badge",children:f}):null]}),fe?.researchView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="research"?" active":""}`,onClick:()=>{D("research"),ct(!1)},role:"menuitem","data-testid":"view-overflow-research",children:[t.jsx(Wi,{size:14}),t.jsx("span",{children:"Research"})]}),fe?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="insights"?" active":""}`,onClick:()=>{D("insights"),ct(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(gs,{size:14}),t.jsx("span",{children:"Insights"})]}),K&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="skills"?" active":""}`,onClick:()=>{D("skills"),ct(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(as,{size:14}),t.jsx("span",{children:"Skills"})]}),fe?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="memory"?" active":""}`,onClick:()=>{D("memory"),ct(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(No,{size:14}),t.jsx("span",{children:"Memory"})]}),fe?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${A==="dev-server"||A==="devserver"?" active":""}`,onClick:()=>{D("devserver"),ct(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(vr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),z&&N&&t.jsxs("button",{className:`view-toggle-overflow-item${R?" active":""}`,onClick:()=>{N(),ct(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx($u,{size:14}),t.jsx("span",{children:"Todos"})]}),B.filter(le=>le.view.placement!=="primary").sort((le,lt)=>(le.view.order??Number.MAX_SAFE_INTEGER)-(lt.view.order??Number.MAX_SAFE_INTEGER)).map(le=>{const lt=vo(le.pluginId,le.view.viewId),nn=Vl(le.view.icon);return t.jsxs("button",{className:`view-toggle-overflow-item${A===lt||A==="graph"&&le.pluginId==="fusion-plugin-dependency-graph"&&le.view.viewId==="graph"?" active":""}`,onClick:()=>{D(le.pluginId==="fusion-plugin-dependency-graph"&&le.view.viewId==="graph"?"graph":lt),ct(!1)},role:"menuitem","data-testid":`view-overflow-plugin-${le.pluginId}-${le.view.viewId}`,children:[t.jsx(nn,{size:14}),t.jsx("span",{children:le.view.label})]},`${le.pluginId}:${le.view.viewId}`)})]})]})]}),!Pe&&o&&t.jsx("button",{className:"btn-icon",onClick:le=>o(le.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ys,{size:16})}),!Pe&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(vr,{size:16})}),!Pe&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Pa,{size:16})}),!Pe&&!Zt&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(jh,{size:16})}),!Pe&&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($i,{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})]}),!Pe&&t.jsxs("div",{className:"terminal-split-btn",ref:Ve,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:j,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Gi,{size:16})}),v&&S&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Pt,className:`btn-icon terminal-split-btn__chevron${ge?" btn-icon--active":""}`,onClick:()=>pt(le=>!le),title:"Scripts","aria-haspopup":"listbox","aria-expanded":ge,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(pn,{size:12,className:`quick-scripts-dropdown__trigger-chevron${ge?" rotate":""}`})}),ge&&t.jsx("div",{ref:Ot,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:te,"data-testid":"quick-scripts-dropdown",style:ot?{position:"fixed",top:`${ot.top}px`,left:`${ot.left}px`,width:`${ot.width}px`,right:"auto"}:void 0,children:Rt?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Ht.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(Gi,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:se,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Ht.map(([le,lt],nn)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${be===nn?"highlighted":""}`,onClick:()=>$t(le,lt),role:"option","aria-selected":be===nn,"data-testid":`quick-script-item-${le}`,children:[t.jsx(is,{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:le}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:lt,children:lt.length>50?`${lt.slice(0,50)}...`:lt})]})]},le))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${rn&&be===Ht.length?"highlighted":""}`,onClick:se,"data-testid":"quick-scripts-manage",children:[t.jsx(xo,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!Pe&&C&&t.jsx("button",{className:`btn-icon${w?" btn-icon--active":""}`,onClick:C,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(Es,{size:16})}),!Pe&&g&&t.jsx("button",{className:"btn-icon",onClick:g,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Fs,{size:16})}),!Pe&&b&&t.jsx("button",{className:"btn-icon",onClick:b,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Bl,{size:16})}),!Pe&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:yn,className:"btn-icon",onClick:()=>yt(le=>!le),title:"More actions","aria-label":"More actions","aria-expanded":Nt,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(Yd,{size:16})}),Nt&&t.jsxs("div",{ref:Gt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[x&&y!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{x(),yt(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(So,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Xe(p),yt(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(Ji,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:ut,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${E?" btn-icon--stopped":""}`,onClick:O,title:E?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:E?t.jsx(is,{size:16}):t.jsx(Ii,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Se?" btn-icon--active":""}`,onClick:()=>G(le=>!le),title:"Engine options","aria-haspopup":"menu","aria-expanded":Se,"data-testid":"engine-control-chevron-btn",children:t.jsx(pn,{size:12})}),Se&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${I?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{U?.(),G(!1)},role:"menuitem",title:I?"Resume scheduling":"Pause triage",disabled:!!E,"data-testid":"engine-control-pause-triage-btn",children:[I?t.jsx(is,{size:14}):t.jsx(vi,{size:14}),t.jsx("span",{children:I?"Resume scheduling":"Pause triage"})]})})]}),!Pe&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(xo,{size:16})}),t.jsx(la,{slotId:"header-action",projectId:Y}),Pe&&!nt&&t.jsx("button",{ref:mn,className:"btn-icon compact-overflow-trigger",onClick:wt,title:"More header actions","aria-label":"More header actions","aria-expanded":me,"aria-haspopup":"menu",children:t.jsx(Yd,{size:16})}),Pe&&!nt&&me&&t.jsxs("div",{ref:Qt,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[je.length>=1&&Ne&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(Ne),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(uc,{size:16}),t.jsx("span",{children:"Projects"})]}),C&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(C),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(Es,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Xe(r>0&&a?a:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx($i,{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"})]}),g&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(g),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Fs,{size:16}),t.jsx("span",{children:"Git Manager"})]}),x&&y!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(x),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(So,{size:16}),t.jsx("span",{children:"Nodes"})]}),!Zt&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(n),role:"menuitem",children:[t.jsx(jh,{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:()=>Xe(j),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Gi,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>xt(le=>!le),role:"menuitem","aria-expanded":_e,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(On,{size:14,className:`mobile-overflow-chevron${_e?" mobile-overflow-chevron--open":""}`})})]}),_e&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Yt?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(jt,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):an.length>0?t.jsxs(t.Fragment,{children:[an.map(([le,lt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{S&&S(le,lt),re(!1),xt(!1)},role:"menuitem","data-testid":`overflow-script-item-${le}`,children:[t.jsx(is,{size:14}),t.jsx("span",{children:le})]},le)),v&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Xe(v),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(xi,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):v&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Xe(v),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(xi,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(p),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(Ji,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Pa,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),d&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(d),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Da,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]}),m>0&&t.jsx("span",{className:"header-badge","data-testid":"overflow-mailbox-approval-badge",children:m})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:le=>Xe(()=>o(le.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ys,{size:16}),t.jsx("span",{children:"View Usage"})]}),b&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(b),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Bl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Xe(e),role:"menuitem",children:[t.jsx(xo,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),zt&&ft&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{className:"header-search",children:[t.jsx(Wi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:ne,onChange:le=>F(le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:ht,"aria-label":"Close search",children:t.jsx(un,{size:14})})]}),Pn&&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:M,onChange:le=>J?.(le.target.value),"data-testid":"working-branch-filter",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:il,children:"No working branch"}),$.map(le=>t.jsx("option",{value:le,children:le},le))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:P,onChange:le=>ce?.(le.target.value),"data-testid":"target-branch-filter",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:il,children:"No base branch"}),k.map(le=>t.jsx("option",{value:le,children:le},le))]})]})]})]}),F&&ae&&De&&t.jsxs("div",{className:"header-floating-search",children:[t.jsxs("div",{ref:on,className:"header-search mobile-search-expanded",children:[t.jsx(Wi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:sn,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:ne,onChange:le=>F(le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Et,"aria-label":"Close search",children:t.jsx(un,{size:14})})]}),Pn&&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:M,onChange:le=>J?.(le.target.value),"data-testid":"working-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All working branches"}),t.jsx("option",{value:il,children:"No working branch"}),$.map(le=>t.jsx("option",{value:le,children:le},le))]})]}),t.jsxs("label",{className:"header-branch-filter-label",children:[t.jsx("span",{children:"Base branch"}),t.jsxs("select",{className:"header-branch-filter-select",value:P,onChange:le=>ce?.(le.target.value),"data-testid":"target-branch-filter-mobile",children:[t.jsx("option",{value:"",children:"All base branches"}),t.jsx("option",{value:il,children:"No base branch"}),k.map(le=>t.jsx("option",{value:le,children:le},le))]})]})]})]})]})}const vC={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","message:agent-to-user","message:agent-to-agent","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,githubTrackingDefaultRepo:void 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,persistAgentThinkingLog:!1,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:"builtin",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:{}},yC={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,mergerAutostashMaxAgeHours:24,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,agentProvisioning:{},specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:6e5,staleHighFanoutBlockerAgeThresholdMs:7200*1e3,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,githubTrackingEnabledByDefault:!1,githubTrackingDefaultRepo:void 0,githubAuthMode:"gh-cli",githubAuthToken:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",memoryBackupEnabled:!1,memoryBackupSchedule:"0 3 * * *",memoryBackupRetention:14,memoryBackupDir:".fusion/backups/memory",memoryBackupScope:"all",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}},evalSettings:{enabled:!1,intervalMs:864e5,evaluatorProvider:void 0,evaluatorModelId:void 0,followUpPolicy:"suggest-only",retentionDays:30},researchEnabled:!0,researchMaxConcurrentRuns:3,researchDefaultTimeout:3e5,researchMaxSourcesPerRun:20,researchMaxSynthesisRounds:2},wC=Object.freeze(Object.keys(vC)),kC=Object.freeze(Object.keys(yC));function J5(e){return wC.includes(e)}function Y5(e){return kC.includes(e)}function Ee(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function jC(e){return!!(e?.provider&&e?.modelId)}function ha(...e){for(const n of e)if(jC(n))return{provider:n.provider,modelId:n.modelId};return{}}function xc(e){return ha({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function NC(e){return ha({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},xc(e))}function SC(e){return ha({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},xc(e))}function CC(e){return ha({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},xc(e))}function Q5(e){return ha({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},xc(e))}function Cb(e,n){return ha({provider:e.modelProvider,modelId:e.modelId},NC(n))}function Eb(e,n){return ha({provider:e.validatorModelProvider,modelId:e.validatorModelId},CC(n))}function _b(e,n){return ha({provider:e.planningModelProvider,modelId:e.planningModelId},SC(n))}const X5=["off","minimal","low","medium","high"],oa=["triage","todo","in-progress","in-review","done","archived"],Wl="triage";function Vu(e){return typeof e=="string"&&oa.includes(e)}function Mb(e,n=Wl){return Vu(e)?e:n}const pa=["low","normal","high","urgent"],Ds="normal",Wu=5,Ab=7200*1e3,EC=["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"],vc=/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,ds={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},_C={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"},ru={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 MC(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 Nh(e){return e==="urgent"?3:e==="high"?2:e==="low"?0:1}function Sh(e,n){return Nh(n)-Nh(e)}function Wc(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 Ch(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=Date.parse(n);return Number.isFinite(s)?s:0}function Eh(e){return e==="merging"||e==="merging-pr"||e==="merging-fix"}function Rb(e,n){return n==="todo"?[...e].sort((s,a)=>{const r=Sh(s.priority,a.priority);return r!==0?r:s.createdAt!==a.createdAt?s.createdAt.localeCompare(a.createdAt):Wc(s.id,a.id)}):[...e].sort((s,a)=>{if(n==="done"){const o=Ch(a)-Ch(s);return o!==0?o:Wc(s.id,a.id)}if(n==="in-review"){const o=Eh(s.status),l=Eh(a.status);if(o!==l)return o?-1:1}const r=Sh(s.priority,a.priority);return r!==0?r:Wc(s.id,a.id)})}function AC(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 RC({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 Ib=i.createContext(null);function IC({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(Ib.Provider,{value:d},e,Ol.createElement(RC,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function pi(){const e=i.useContext(Ib);return e||{confirm:async n=>!1}}function TC(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 Tb({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(si,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("a",{className:`card-github-badge ${TC(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,href:n.url,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(cc,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function al(e,n){return`${e??"default"}:${n}`}class PC{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=al(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const a=al(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=al(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(Di(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=al(this.projectId,l.taskId),d=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:_h(l,"prInfo")?l.prInfo??null:d?.prInfo,issueInfo:_h(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 Ma=new PC;let $C=0;function _h(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Pb(e){const n=i.useRef(null);n.current===null&&(n.current=`badge-hook-${$C++}`);const s=i.useSyncExternalStore(o=>Ma.subscribe(o),()=>Ma.getSnapshot(),()=>Ma.getSnapshot()),a=i.useCallback(o=>{Ma.subscribeTask(n.current,o)},[]),r=i.useCallback(o=>{Ma.unsubscribeTask(n.current,o)},[]);return i.useEffect(()=>{Ma.setProjectId(e??null)},[e]),i.useEffect(()=>()=>{Ma.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:a,unsubscribeFromBadge:r}}function Kl(e,n,s,a){return e===void 0||!n?s:!a||n>=a?e??void 0:s}function DC({taskId:e,prInfo:n,issueInfo:s,updatedAt:a,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:d}=Pb(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=Kl(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??a),f=Kl(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??a);return!h&&!f?null:t.jsx(Tb,{prInfo:h,issueInfo:f})}const LC=i.memo(DC);LC.displayName="TaskCardBadge";const li={data:new Map,pendingPromise:null,lastFetchTime:null},OC=5e3;function Pl(e,n){return n?`${n}::${e}`:e}function FC(e,n){const s=li.data.get(Pl(e,n));if(!(!s||Date.now()-s.timestamp>OC))return s}function zC(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 RN(c,e)}catch(h){u=h instanceof Error?h:new Error(String(h));const f=Ee(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=li.data.get(Pl(f,e));return p&&p.timestamp>u})&&li.lastFetchTime&&li.lastFetchTime>u)return;if(a.current&&(clearTimeout(a.current),a.current=null),li.pendingPromise){s(!0);try{await li.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);li.pendingPromise=h;try{const f=await h,p=Date.now();for(const[g,x]of Object.entries(f))li.data.set(Pl(g,e),{result:x,timestamp:p});li.lastFetchTime=p}catch{}finally{li.pendingPromise=null,s(!1)}},[r,e]),l=i.useCallback(c=>li.data.get(Pl(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:li.lastFetchTime,getBatchData:l}}const ou=new Map,BC=3e4;function $b(e,n,s,a){return`${e}:${n??""}:${s??""}:${a??""}`}function UC(e,n,s,a){const r=$b(e,n,s,a),o=ou.get(r);return o?Date.now()>o.expiresAt?(ou.delete(r),null):o.stats:null}function HC(e,n,s,a,r){const o=$b(e,n,s,a);ou.set(o,{stats:r,expiresAt:Date.now()+BC})}function qC(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,y=c!==void 0?String(c):void 0;let b=!1;async function v(j=!1){if(!j){const C=UC(e,a,x,y);if(C){b||(m(C),f(!1));return}}f(!0);try{const C=await pb(e,x,a);b||(m(C.stats),HC(e,a,x,y,C.stats))}catch{b||m(null)}finally{b||f(!1)}}v();let S;return d&&g&&(S=setInterval(()=>{v(!0)},d)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,a,o,l,c,d]),{stats:u,loading:h}}const VC=new Set(["failed","stuck-killed"]);function Gl(e,n,s){if(e.column!=="in-progress"||e.status&&VC.has(e.status)||!n||n<=0)return!1;const a=new Date(e.updatedAt).getTime();return(s??Date.now())-a>n}function WC(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function KC(e){return e==="done"||e==="skipped"}function GC(e,n,s){const a=s?.get(e)?.trim();if(a)return a;const r=n?.workflowStepName?.trim();return r||e}function Db(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:GC(d,u,n),status:u?WC(u.status):"pending",source:"workflow",phase:u?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(d=>KC(d.status)).length;return{total:l,completed:c,items:o}}function JC(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 Lb(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??""}
|
|
649
|
+
${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:JC(n)}})}function Ob(e){if(!e||e.length===0)return null;let n=0,s=0;for(const a of Lb(e))typeof a.durationMs=="number"&&(n+=a.durationMs,s+=1);return s>0?n:null}function Fa(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Fb(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=Fa(r.startedAt);if(o==null)continue;let l;if(r.completedAt){const c=Fa(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 zb(e,n,s){const a=Fa(e);if(a==null)return null;const r=Fa(n),o=r!=null&&r>=a?r:s;return Math.max(0,o-a)}function Ku(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}const lu=new Map;async function YC(e,n){const s=lu.get(e);if(s)return s;try{const a=await fb(e,n);return lu.set(e,a.title),a.title}catch{return e}}const Mh=12;function QC(e){return e.length<=Mh?e:e.slice(0,Mh-3)+"..."}const cu=new Map;async function XC(e,n){const s=cu.get(e);if(s)return s;try{const a=await au(e,n);return cu.set(e,a.name),a.name}catch{return e}}function ZC(e){return typeof e=="string"&&pa.includes(e)?e:Ds}function eE(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}function Bb(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 tE(e){return e.sourceType==="agent_heartbeat"||e.sourceType==="automation"||!!Bb(e)}const nE=new Set(["triage","todo"]),Ah=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),Rh=new Set(["merging","merging-pr","merging-fix"]),sE={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},iE=new Set(["in-progress","in-review","done"]),aE=3e4;function rE(e){return e==="merging-fix"?"Merging fixes…":e}function oE(e){const n=Fa(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function Ih(e,n){const s=Fa(e.columnMovedAt??e.updatedAt);return s==null?null:Math.max(0,n-s)}function uo(e,n){return zb(e.executionStartedAt,e.executionCompletedAt,n)}function lE(e){return e.column==="done"?oE(e):null}function Ub(e,n){const s=Fa(e.updatedAt);return s==null?null:Math.max(0,n-s)}function cE(e,n){const s=uo(e,n);if(s!=null)return s;const a=Ub(e,n),r=mo(e,n);return r!=null?r+(a??0):a}function mo(e,n){if(typeof e.timedExecutionMs=="number")return e.timedExecutionMs;const s=Ob(e.log),a=Fb(e.workflowStepResults,n);return s==null&&a==null?null:(s??0)+(a??0)}function Th(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 Ph(e){if(!e)return null;const n=e.trim();return n.length>0?n:null}function dE(e){const n=Ph(e.branch),s=Ph(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 $h(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 Dh(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 uE(e,n){return e.length!==n.length?!1:e.every((s,a)=>s.name===n[a]?.name&&s.status===n[a]?.status)}function Kc(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function mE(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,a)=>s===n[a])}function hE(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function pE(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 fE(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 gE(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 bE(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&&e.disableDrag===n.disableDrag&&e.fanout?.totalCount===n.fanout?.totalCount&&e.fanout?.activeTodoCount===n.fanout?.activeTodoCount&&e.fanout?.isHighFanout===n.fanout?.isHighFanout&&e.fanout?.escalation?.blockingAgeMs===n.fanout?.escalation?.blockingAgeMs&&Kc(e.fanout?.dependentIds??[],n.fanout?.dependentIds??[])&&Kc(e.fanout?.staleBlockedByDependentIds??[],n.fanout?.staleBlockedByDependentIds??[])&&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&&fE(s.attachments,a.attachments)&&gE(s.comments,a.comments)&&Kc(s.dependencies,a.dependencies)&&uE(s.steps,a.steps)&&mE(s.enabledWorkflowSteps,a.enabledWorkflowSteps)&&pE(s.workflowStepResults,a.workflowStepResults)&&Dh(s.prInfo,a.prInfo)&&Dh(s.issueInfo,a.issueInfo)}function xE({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:y,disableDrag:b,fanout:v}){const[S,j]=i.useState(!1),[C,w]=i.useState(!1),[N,R]=i.useState(!1),[z,E]=i.useState(e.description||""),[I,O]=i.useState(!1),[U,A]=i.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(Me=>Me.status==="done"||Me.status==="skipped")),[D,K]=i.useState(null),[Z,ne]=i.useState(null),[F,M]=i.useState(!1),[P,$]=i.useState(!1),[k,J]=i.useState(()=>Date.now()),ce=i.useRef(null),je=i.useRef(!1),He=i.useRef(null),xe=i.useRef(null),[Ne,Y]=i.useState(!1),{badgeUpdates:ie,subscribeToBadge:ee,unsubscribeFromBadge:oe}=Pb(n),{confirm:W}=pi(),L=i.useRef(null),pe=i.useRef(!1),fe=i.useCallback(Me=>Me instanceof Element?!!Me.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);i.useEffect(()=>{E(e.description||"")},[e.id,e.description]),i.useEffect(()=>{if(!F)return;const Me=it=>{xe.current&&!xe.current.contains(it.target)&&M(!1)};return document.addEventListener("click",Me),()=>document.removeEventListener("click",Me)},[F]),i.useEffect(()=>{if(!e.missionId){K(null);return}const Me=lu.get(e.missionId);if(Me){K(Me);return}let it=!1;return YC(e.missionId,n).then(kt=>{it||K(kt)}),()=>{it=!0}},[e.missionId,n]),i.useEffect(()=>{if(!e.assignedAgentId){ne(null);return}const Me=cu.get(e.assignedAgentId);if(Me){ne(Me);return}ne(null);let it=!1;return XC(e.assignedAgentId,n).then(kt=>{it||ne(kt)}),()=>{it=!0}},[e.assignedAgentId,n]),i.useEffect(()=>{if(N&&ce.current){const Me=ce.current;Me.focus(),Me.style.height="auto",Me.style.height=Me.scrollHeight+"px"}},[N]),i.useEffect(()=>{if(typeof IntersectionObserver>"u"){Y(!0);return}const Me=He.current;if(!Me)return;const it=new IntersectionObserver(([kt])=>{Y(kt?.isIntersecting??!0)},{rootMargin:"200px"});return it.observe(Me),()=>it.disconnect()},[N,e.id]);const B=i.useCallback(Me=>{Me.dataTransfer.setData("text/plain",e.id),Me.dataTransfer.effectAllowed="move",j(!0)},[e.id]),ve=i.useCallback(()=>{j(!1)},[]),Fe=i.useCallback(Me=>Me.dataTransfer.types.includes("Files"),[]),ae=i.useCallback(Me=>{Fe(Me)&&(Me.preventDefault(),Me.stopPropagation(),Me.dataTransfer.dropEffect="copy",w(!0))},[Fe]),qe=i.useCallback(Me=>{Fe(Me)&&(Me.preventDefault(),Me.stopPropagation(),w(!1))},[Fe]),Pe=i.useCallback(async Me=>{if(!Fe(Me))return;Me.preventDefault(),Me.stopPropagation(),w(!1);const it=Array.from(Me.dataTransfer.files);for(const kt of it)try{await bc(e.id,kt,n),r(`Attached ${kt.name} to ${e.id}`,"success")}catch($t){r(`Failed to attach ${kt.name}: ${Ee($t)}`,"error")}},[e.id,Fe,r]),nt=i.useCallback(()=>{N||a(e)},[e,a,N]),Be=i.useCallback(Me=>{if(je.current){je.current=!1;return}fe(Me.target)||nt()},[nt,fe]),de=i.useCallback(Me=>{const it=Me.touches[0];it&&(L.current={x:it.clientX,y:it.clientY,time:Date.now()},pe.current=!1)},[]),Ie=i.useCallback(Me=>{if(!L.current)return;const it=Me.touches[0];if(!it)return;const kt=Math.abs(it.clientX-L.current.x),$t=Math.abs(it.clientY-L.current.y);(kt>Lh||$t>Lh)&&(pe.current=!0)},[]),$e=i.useCallback(Me=>{if(fe(Me.target)||!L.current)return;const kt=Date.now()-L.current.time<vE,$t=!pe.current;kt&&$t&&(je.current=!0,nt()),L.current=null,pe.current=!1},[nt,fe]),st=i.useCallback(async(Me,it)=>{Me.stopPropagation();try{const kt=await La(it,n);a(kt)}catch{r(`Failed to load dependency ${it}`,"error")}},[a,r]),Ue=e.status==="failed",me=e.paused===!0,re=!!(e.paused&&e.pausedByAgentId),_e=ZC(e.priority),xt=_e!==Ds,dt=Gl(e,f,x),Qe=e.column==="triage"&&e.status==="awaiting-approval",vt=e.column==="archived",Ae=!o&&!s&&!Ue&&!me&&!dt&&!Qe&&(e.column==="in-progress"||Ah.has(e.status)),Je=!b&&!s&&!me&&!N&&!vt,ct=nE.has(e.column)&&!Ae&&!me&&!s&&l,Nt=!!(e.prInfo||e.issueInfo),yt=e.sourceType==="github_import",Se=i.useMemo(()=>dE(e),[e.id,e.branch,e.baseBranch]),G=!!(Se.branch||Se.baseBranch),ge=hE(e.sourceMetadata),pt=tE(e),ke=Bb(e),tt=ke?`Created by agent: ${ke}`:"Created by agent",Rt=!!(e.assignedAgentId&&Z===null),Re=i.useMemo(()=>{const Me=[];return e.modelProvider&&Me.push(e.modelProvider),e.validatorModelProvider&&!Me.includes(e.validatorModelProvider)&&Me.push(e.validatorModelProvider),e.planningModelProvider&&!Me.includes(e.planningModelProvider)&&Me.push(e.planningModelProvider),Me},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),be=i.useMemo(()=>Db(e,y),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,y]),at=be.total>0&&(e.status==="executing"||e.column==="in-progress");i.useEffect(()=>{if(e.column!=="in-progress"&&e.column!=="in-review")return;const Me=e.status!=null&&Rh.has(e.status);if(e.column==="in-progress"){const kt=uo(e,Date.now()),$t=Ih(e,Date.now()),se=mo(e,Date.now());if(kt==null&&$t==null&&se==null)return}if(!Me&&e.column==="in-review"){const kt=uo(e,Date.now()),$t=mo(e,Date.now());if(kt==null&&$t==null)return}J(Date.now());const it=window.setInterval(()=>{J(Date.now())},aE);return()=>window.clearInterval(it)},[e.column,e.status,e.columnMovedAt,e.updatedAt,e.workflowStepResults,e.timedExecutionMs,e.executionStartedAt,e.executionCompletedAt]);const ot=i.useMemo(()=>{if(!iE.has(e.column))return null;if(e.status!=null&&Rh.has(e.status)){const te=cE(e,k);if(te!=null){const De=$h(te);if(De){const ft=Ub(e,k),qt=ft==null?null:Th(ft),zt=qt?`Execution time ${De}. Merge phase ${qt}`:`Execution time ${De}. Merging`;return{label:De,title:zt,ariaLabel:zt}}}}if(e.column==="in-progress"){const te=uo(e,k)??Ih(e,k)??mo(e,k);if(te==null)return null;const De=Th(te);return De?{label:De,title:`In progress ${De}`,ariaLabel:`In progress ${De}`}:null}const it=uo(e,k)??mo(e,k);if(it==null)return null;const kt=$h(it);if(!kt)return null;const $t=lE(e);if($t==null)return{label:kt,title:`Execution time ${kt}`,ariaLabel:`Execution time ${kt}`};const se=new Date($t).toLocaleString();return{label:kt,title:`Execution time ${kt}. Completed ${se}`,ariaLabel:`Execution time ${kt}. Completed ${se}`}},[e.column,e.status,e.columnMovedAt,e.timedExecutionMs,e.updatedAt,e.workflowStepResults,e.log,e.executionStartedAt,e.executionCompletedAt,k]);i.useEffect(()=>{if(!Nt||!Ne){oe(e.id);return}return ee(e.id),()=>{oe(e.id)}},[Nt,Ne,ee,e.id,oe]);const gt=ie.get(`${n??"default"}:${e.id}`),St=e.column==="in-progress"||e.column==="in-review",Lt=i.useMemo(()=>e.steps.map(Me=>`${Me.name}:${Me.status}`).join("|"),[e.steps]),{stats:Yt}=qC(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:Ne,worktree:e.worktree,stepVersion:St?Lt:void 0,pollIntervalMs:St?3e4:void 0}),tn=i.useMemo(()=>FC(e.id,n),[e.id,n]),mn=i.useMemo(()=>{const Me=gt?.prInfo,it=gt?.timestamp,kt=tn?.result?.prInfo,$t=tn?.timestamp?new Date(tn.timestamp).toISOString():void 0,se=e.prInfo,te=e.prInfo?.lastCheckedAt??e.updatedAt;let De=Kl(Me,it,se,te);const ft=it&&it>=te?it:te;return kt&&$t&&(!ft||$t>ft)&&(De=kt),De},[gt,tn,e.prInfo,e.updatedAt]),Qt=i.useMemo(()=>{const Me=gt?.issueInfo,it=gt?.timestamp,kt=tn?.result?.issueInfo,$t=tn?.timestamp?new Date(tn.timestamp).toISOString():void 0,se=e.issueInfo,te=e.issueInfo?.lastCheckedAt??e.updatedAt;let De=Kl(Me,it,se,te);const ft=it&&it>=te?it:te;return kt&&$t&&(!ft||$t>ft)&&(De=kt),De},[gt,tn,e.issueInfo,e.updatedAt]),yn=i.useCallback(Me=>{Me?.stopPropagation(),!(!ct||I)&&(R(!0),E(e.description||""))},[ct,I,e.description]),Gt=i.useCallback(()=>{R(!1),E(e.description||"")},[e.description]),on=i.useCallback(()=>z!==(e.description||""),[z,e.description]),sn=i.useCallback(async()=>{if(!(!l||I)){if(!on()){Gt();return}O(!0);try{await l(e.id,{description:z.trim()||void 0}),r(`Updated ${e.id}`,"success"),R(!1)}catch(Me){r(`Failed to update ${e.id}: ${Ee(Me)}`,"error")}finally{O(!1)}}},[l,e.id,z,I,on,Gt,r]),ln=i.useCallback(Me=>{Me.key==="Enter"&&!Me.shiftKey?(Me.preventDefault(),sn()):Me.key==="Escape"&&(Me.preventDefault(),Gt())},[sn,Gt]),Wt=i.useCallback(()=>{setTimeout(()=>{const Me=document.activeElement;Me===ce.current||Me?.closest(".card-editing-content")||(on()?sn():Gt())},0)},[on,sn,Gt]),ye=i.useCallback(Me=>{ct&&(Me.stopPropagation(),yn(Me))},[ct,yn]),Le=i.useCallback(Me=>{Me.stopPropagation(),yn(Me)},[yn]),Ke=i.useCallback(Me=>{E(Me.target.value);const it=Me.target;it.style.height="auto",it.style.height=it.scrollHeight+"px"},[]),ut=i.useCallback(Me=>{Me.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(it=>{r(`Failed to archive ${e.id}: ${Ee(it)}`,"error")})},[r,c,e.id]),Ve=i.useCallback(Me=>{Me.stopPropagation(),d&&d(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(it=>{r(`Failed to unarchive ${e.id}: ${Ee(it)}`,"error")})},[r,d,e.id]),Pt=i.useCallback(async Me=>{if(Me.stopPropagation(),!(!u||!await W({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0})))try{await u(e.id),r(`Deleted ${e.id}`,"success")}catch(kt){const $t=Ku(kt);if(!$t||$t.dependentIds.length===0){r(`Failed to delete ${e.id}: ${Ee(kt)}`,"error");return}const se=$t.dependentIds.join(", ");if(!await W({title:"Force Delete Task",message:`${e.id} is a dependency of ${se}.
|
|
650
|
+
|
|
651
|
+
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(De){r(`Failed to delete ${e.id}: ${Ee(De)}`,"error")}}},[r,W,u,e.id]),Ot=i.useCallback(Me=>{Me.stopPropagation(),h?.(e,"changes")},[e,h]),bt=i.useCallback(Me=>{Me.stopPropagation(),A(it=>!it)},[]),Dt=i.useCallback(Me=>{Me.stopPropagation(),e.missionId&&p&&p(e.missionId)},[e.missionId,p]),Ft=i.useCallback(Me=>{Me.stopPropagation(),M(it=>!it)},[]),Ht=i.useCallback(async(Me,it)=>{if(Me.stopPropagation(),M(!1),!!g)try{const kt=e.steps.some(te=>te.status!=="pending"),$t=(it==="todo"||it==="triage")&&kt;let se;if($t){if(await W({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))se={preserveProgress:!0};else if(!await W({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,it,se),r(`Moved ${e.id} to ${ds[it]}`,"success")}catch(kt){r(`Failed to move ${e.id}: ${Ee(kt)}`,"error")}},[r,W,g,e.id,e.steps]),rn=i.useCallback(async Me=>{if(Me.stopPropagation(),!(!m||P)){$(!0);try{await m(e.id)}catch(it){r(`Failed to retry ${e.id}: ${Ee(it)}`,"error")}finally{$(!1)}}},[r,P,m,e.id]),Xt=`card${S?" dragging":""}${s?" queued":""}${Ae?" agent-active":""}${Ue?" failed":""}${me?" paused":""}${dt?" stuck":""}${Qe?" awaiting-approval":""}${C?" file-drop-target":""}${N?" card-editing":""}${I?" card-saving":""}`,an=(()=>{if(e.column==="in-progress"){const Me=Yt?.filesChanged,it=Me==null||Me===0?e.modifiedFiles?.length:void 0,kt=Me!=null&&Me>0?Me:it;return kt==null||kt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ot,disabled:!h,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:[kt," ",kt===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const Me=Yt?.filesChanged,it=Me==null||Me===0?e.modifiedFiles?.length:void 0,kt=Me!=null&&Me>0?Me:it;return kt==null||kt===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ot,disabled:!h,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:[kt," ",kt===1?"file":"files"," changed"]})]})}if(e.column==="done"){const Me=Yt?.filesChanged,it=e.mergeDetails?.filesChanged,kt=Me??it;if(kt!=null&&kt>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ot,disabled:!h,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:[kt," ",kt===1?"file":"files"," changed"]})]});const $t=e.modifiedFiles?.length;if($t!=null&&$t>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Ot,disabled:!h,children:[t.jsx(Es,{size:12}),t.jsxs("span",{children:[$t," ",$t===1?"file":"files"," changed"]})]})}return null})();return N?t.jsx("div",{ref:He,className:Xt,"data-id":e.id,"data-column":e.column,onDoubleClick:ye,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:ce,className:"card-edit-desc-textarea",placeholder:"Task description",value:z,onChange:Ke,onKeyDown:ln,onBlur:Wt,disabled:I,rows:4}),I&&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:He,className:Xt,"data-id":e.id,"data-column":e.column,draggable:Je,onDragStart:Je?B:void 0,onDragEnd:Je?ve:void 0,onDragOver:ae,onDragLeave:qe,onDrop:Pe,onClick:Be,onTouchStart:de,onTouchMove:Ie,onTouchEnd:$e,onDoubleClick:ye,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),me&&t.jsx("span",{className:"card-status-badge paused",children:re?"paused by agent":"paused"}),!me&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${Qe?" awaiting-approval":""}${Ah.has(e.status)?" pulsing":""}${Ue?" failed":""}${dt?" stuck":""}`,children:dt?"Stuck":Qe?"Awaiting Approval":rE(e.status)}),dt&&(me||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),Nt&&t.jsx(Tb,{prInfo:mn,issueInfo:Qt}),pt&&t.jsxs("span",{className:"card-agent-created-badge",title:tt,"aria-label":tt,children:[t.jsx(zn,{size:11,"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:tt}),t.jsx("span",{"aria-hidden":"true",children:"Agent"})]}),xt&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${_e}`,children:_e}),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(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:Dt,title:`Mission: ${D??e.missionId}`,role:p?"button":void 0,tabIndex:p?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(Rs,{size:11}),QC(D??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[ct&&t.jsx("button",{className:"card-edit-btn",onClick:Le,title:"Edit task","aria-label":"Edit task",children:t.jsx(qs,{size:12})}),e.column==="triage"&&u&&t.jsx("button",{className:"card-delete-btn",onClick:Pt,title:"Delete task","aria-label":"Delete task",children:t.jsx(_n,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:ut,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&d&&t.jsx("button",{className:"card-unarchive-btn",onClick:Ve,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&g&&t.jsxs("div",{className:"card-send-back",ref:xe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Ft,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":F,children:["Send back",t.jsx(pn,{size:10})]}),F&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:ru["in-progress"].filter(Me=>Me!=="in-review").map(Me=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:it=>Ht(it,Me),children:ds[Me]},Me))})]}),e.column==="in-review"&&g&&t.jsxs("div",{className:"card-send-back",ref:xe,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:Ft,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":F,children:["Move",t.jsx(pn,{size:10})]}),F&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:ru["in-review"].map(Me=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:it=>Ht(it,Me),children:Me==="done"?"Done (no merge)":ds[Me]},Me))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),Ue&&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:rn,disabled:P,children:[t.jsx(Mk,{size:12}),P?"Retrying…":"Retry"]})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Fh(e.title,Oh)||Fh(e.description,Oh)||e.id}),G&&t.jsxs("div",{className:"card-branch-row","aria-label":"Branch metadata",children:[Se.branch&&t.jsxs("span",{className:"card-branch-chip",title:Se.branch,children:[t.jsx("span",{className:"card-branch-label",children:"Branch"}),t.jsx("span",{className:"card-branch-value",children:Se.branch})]}),Se.baseBranch&&t.jsxs("span",{className:"card-branch-chip",title:Se.baseBranch,children:[t.jsx("span",{className:"card-branch-label",children:"Base"}),t.jsx("span",{className:"card-branch-value",children:Se.baseBranch})]})]}),at&&(()=>{const Me=be.completed/be.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:`${Me}%`,backgroundColor:sE[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[be.completed,"/",be.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:bt,"aria-expanded":U,"aria-label":U?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[be.total," step",be.total===1?"":"s"]}),t.jsx(pn,{size:14,className:`card-steps-toggle-icon${U?" expanded":""}`})]}),U&&t.jsx("div",{className:"card-steps-list",children:be.items.map(it=>{const kt=it.source==="workflow"&&it.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${it.status}${kt?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${it.status==="done"?" completed":""}`,children:it.name}),it.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${it.phase}`,title:"Workflow check",children:"workflow"})]},it.id)})})]})})(),(an||ot||yt)&&t.jsxs("div",{className:"card-footer-row",children:[an,yt&&t.jsx("span",{className:"card-source-provenance",title:ge?`Imported from GitHub: ${ge}`:"Imported from GitHub","aria-label":"Imported from GitHub",children:t.jsx(Fn,{provider:"github",size:"sm"})}),ot&&t.jsxs("span",{className:"card-time-indicator",title:ot.title,"aria-label":ot.ariaLabel,children:[t.jsx(Ji,{size:12}),t.jsx("span",{children:ot.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy||v&&v.totalCount>0)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(Me=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:it=>void st(it,Me),title:`Click to view ${Me}`,children:[t.jsx(xr,{size:12,style:{verticalAlign:"middle"}})," ",Me]},Me))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx($a,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),v&&v.totalCount>0&&t.jsxs("span",{className:`card-fanout-badge${v.staleBlockedByDependentIds.length>0?" card-fanout-badge--stale":""}${v.isHighFanout?" card-fanout-badge--high-impact":""}${v.escalation?" card-fanout-badge--escalated":""}`,"data-tooltip":`Blocking ${v.totalCount} active task(s); ${v.activeTodoCount} waiting in todo${v.isHighFanout?` (high fan-out threshold: ${Wu})`:""}${v.escalation?` · escalated after ${Math.floor(v.escalation.blockingAgeMs/6e4)}m in blocking column`:""}`,children:[t.jsx(Fs,{size:12,style:{verticalAlign:"middle"}}),t.jsxs("span",{children:[v.escalation?"Escalated":v.isHighFanout?"High fan-out":"Blocks"," ",t.jsx("span",{className:"card-fanout-count",children:v.totalCount}),v.isHighFanout?` (${v.activeTodoCount} todo)`:"",v.staleBlockedByDependentIds.length>0?` (${v.staleBlockedByDependentIds.length} stale)`:""]})]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(Ji,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Re.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Re.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Re.map(Me=>t.jsx(Fn,{provider:Me,size:"sm"},Me))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${Rt?" card-agent-badge--loading":""}`,title:`Assigned to ${Z??e.assignedAgentId}`,children:[t.jsx(zn,{size:11}),t.jsx("span",{className:"card-agent-badge-text","aria-hidden":"true",children:eE(Z??e.assignedAgentId,15)}),t.jsxs("span",{className:"visually-hidden",children:["Assigned to ",Z??e.assignedAgentId]})]})]}),t.jsx(la,{slotId:"task-card-badge",projectId:n})]})}const Lh=10,vE=300,Oh=140;function Fh(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const _o=i.memo(xE,bE);_o.displayName="TaskCard";function yE({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,blockerFanoutMap:g}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(Vy,{size:14}):t.jsx(Fs,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(x=>t.jsx(_o,{task:x,projectId:a,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p,fanout:g?.get(x.id)},x.id)),s.map(x=>t.jsx(_o,{task:x,projectId:a,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onRetryTask:d,onOpenDetailWithTab:u,taskStuckTimeoutMs:m,onOpenMission:h,lastFetchTimeMs:f,workflowStepNameLookup:p,fanout:g?.get(x.id)},x.id))]})}const Hb=i.memo(yE);Hb.displayName="WorktreeGroup";function zh(e){return e.toLowerCase().replace(/[-_./]/g,"")}function wE(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 kE(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 jE(e,n){const s=zh(e),a=zh(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&&wE(s,o)||s.length>=4&&kE(s,o,1))return!0;return!1}function NE(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=>jE(o,r))})}function Is({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,y]=i.useState(""),[b,v]=i.useState(0),[S,j]=i.useState(null),[C,w]=i.useState(null),N=i.useRef(null),R=i.useRef(null),z=i.useRef(null),E=i.useRef(null),I=i.useRef(null),O=i.useMemo(()=>NE(e,x),[e,x]),U=i.useMemo(()=>O.reduce((ee,oe)=>((ee[oe.provider]??=[]).push(oe),ee),{}),[O]),A=i.useMemo(()=>{const ee=[];for(const oe of u){const W=oe.indexOf("/");if(W===-1)continue;const L=oe.slice(0,W),pe=oe.slice(W+1),fe=O.find(B=>B.provider===L&&B.id===pe);fe&&ee.push({model:fe,fullId:oe})}return ee},[u,O]),D=i.useMemo(()=>{const ee=Object.entries(U),oe=new Set(c);return ee.sort(([W],[L])=>{const pe=oe.has(W),fe=oe.has(L);if(pe&&!fe)return-1;if(!pe&&fe)return 1;if(pe&&fe){const B=c.indexOf(W),ve=c.indexOf(L);if(B!==ve)return B-ve}return W.localeCompare(L)})},[U,c]),K=typeof h=="string"&&h.length>0,Z=i.useMemo(()=>{if(!n||K&&n===h)return null;const ee=n.indexOf("/");return ee===-1?null:n.slice(0,ee)},[K,h,n]),ne=i.useMemo(()=>{const ee=[];return K&&ee.push({type:"no-change",value:h,label:f}),ee.push({type:"default",value:"",label:"Use default"}),ee},[K,f,h]),F=i.useMemo(()=>{const ee=[...ne];for(const{model:oe,fullId:W}of A)ee.push({type:"favorite",value:W,label:oe.name,provider:oe.provider});return D.forEach(([oe,W])=>{ee.push({type:"provider",value:`__group_${oe}`,label:oe,provider:oe}),W.forEach(L=>{ee.push({type:"model",value:`${L.provider}/${L.id}`,label:L.name,provider:L.provider})})}),ee},[A,D,ne]),M=i.useMemo(()=>{if(K&&n===h)return f;if(!n)return"Use default";const ee=n.indexOf("/");if(ee===-1)return n;const oe=n.slice(0,ee),W=n.slice(ee+1);return e.find(pe=>pe.provider===oe&&pe.id===W)?.name||n},[K,f,h,n,e]),P=i.useMemo(()=>F.findIndex(ee=>ee.value===n),[F,n]),$=i.useCallback(()=>{const ee=window.visualViewport;return ee&&ee.height>0&&ee.width>0?{width:ee.width,height:ee.height,offsetTop:ee.offsetTop,offsetLeft:ee.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),k=i.useCallback(()=>{const{height:ee}=$(),oe=typeof window.matchMedia=="function",W=oe?window.matchMedia("(max-width: 640px)").matches:!1,L=oe?window.matchMedia("(max-width: 768px)").matches:!1;return ee<=0?320:W?Math.min(ee*.6,360):L?Math.min(ee*.7,420):320},[$]),J=i.useCallback(()=>{const ee=R.current;if(!ee)return;const oe=ee.getBoundingClientRect(),{width:W,height:L,offsetTop:pe,offsetLeft:fe}=$(),B=16,ve=16,Fe=4,ae=k(),qe=oe.bottom-pe,Pe=oe.top-pe,nt=oe.left-fe,Be=L-qe,de=Pe,Ie=Math.max(Be-ve-Fe,160),$e=Math.max(de-ve-Fe,160),st=Be<ae&&de>Be,Ue=Math.max(Math.min(st?$e:Ie,ae),160),me=Math.min(oe.width,W-B*2),re=Math.min(Math.max(nt,B),W-B-me)+fe,_e=st?Math.max(ve+pe,Pe-Ue-Fe+pe):Math.min(qe+Fe+pe,L+pe-ve-Ue);j({top:_e,left:re,width:me,maxHeight:Ue})},[$,k]);i.useEffect(()=>{w(document.body)},[]);const ce=i.useRef(!1);i.useEffect(()=>{if(!p){ce.current=!1;return}if(ce.current||F.length===0)return;const ee=F.findIndex((oe,W)=>W>=(P>=0?P:0)&&oe.type!=="provider");v(ee>=0?ee:0),ce.current=!0},[p,F,P]),i.useEffect(()=>{p&&ce.current&&(v(0),I.current&&(I.current.scrollTop=0))},[x,p]),i.useEffect(()=>{if(!p)return;J();const ee=requestAnimationFrame(()=>E.current?.focus());return()=>cancelAnimationFrame(ee)},[p,J]),i.useEffect(()=>{if(!p)return;const ee=()=>J();window.addEventListener("resize",ee),window.addEventListener("scroll",ee,!0);const oe=window.visualViewport;return oe&&(oe.addEventListener("resize",ee),oe.addEventListener("scroll",ee)),()=>{window.removeEventListener("resize",ee),window.removeEventListener("scroll",ee,!0),oe&&(oe.removeEventListener("resize",ee),oe.removeEventListener("scroll",ee))}},[p,J]),i.useEffect(()=>{if(!p)return;const ee=oe=>{const W=oe.target,L=N.current?.contains(W),pe=z.current?.contains(W);!L&&!pe&&(g(!1),y(""))};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[p]);const je=i.useCallback(ee=>{switch(ee.key){case"ArrowDown":if(ee.preventDefault(),!p)g(!0);else{let oe=b;for(let W=1;W<=F.length;W++){const L=(b+W)%F.length;if(F[L]?.type!=="provider"){oe=L;break}}v(oe)}break;case"ArrowUp":if(ee.preventDefault(),p){let oe=b;for(let W=1;W<=F.length;W++){const L=(b-W+F.length)%F.length;if(F[L]?.type!=="provider"){oe=L;break}}v(oe)}break;case"Enter":if(ee.preventDefault(),p){const oe=F[b];oe&&oe.type!=="provider"&&oe.type!=="favorite"&&(s(oe.value),g(!1),y(""))}else g(!0);break;case"Escape":ee.preventDefault(),g(!1),y("");break;case"Tab":p&&(g(!1),y(""));break}},[p,b,F,s]),He=i.useCallback(ee=>{s(ee),g(!1),y("")},[s]),xe=i.useCallback(()=>{y(""),E.current?.focus()},[]),Ne=i.useCallback(()=>{r||g(ee=>!ee)},[r]);i.useEffect(()=>{if(p&&I.current){const ee=I.current.querySelector(`[data-index="${b}"]`);ee&&typeof ee.scrollIntoView=="function"&&ee.scrollIntoView({block:"nearest"})}},[b,p]);const Y=x.length>0,ie=p&&S?t.jsxs("div",{ref:z,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:je,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:E,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:x,onChange:ee=>y(ee.target.value),onClick:ee=>ee.stopPropagation()}),Y&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:xe,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[O.length," model",O.length!==1?"s":""]}),t.jsxs("div",{ref:I,className:"model-combobox-list",children:[ne.map((ee,oe)=>t.jsx("div",{"data-index":oe,className:`model-combobox-option ${b===oe?"model-combobox-option--highlighted":""} ${n===ee.value?"model-combobox-option--selected":""}`,onClick:()=>He(ee.value),onMouseEnter:()=>v(oe),role:"option","aria-selected":n===ee.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:ee.label})},`${ee.type}-${ee.value}`)),A.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),A.map(({model:ee,fullId:oe},W)=>{const L=W+ne.length,pe=b===L,fe=n===oe;return t.jsxs("div",{"data-index":L,className:`model-combobox-option model-combobox-option--favorite ${pe?"model-combobox-option--highlighted":""} ${fe?"model-combobox-option--selected":""}`,onClick:()=>He(oe),onMouseEnter:()=>v(L),role:"option","aria-selected":fe,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Fn,{provider:ee.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:ee.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:ee.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:B=>{B.stopPropagation(),m(oe)},title:"Remove from favorites","aria-label":`Remove ${ee.name} from favorites`,children:"★"})]},oe)}),t.jsx("div",{className:"model-combobox-divider"})]}),D.map(([ee,oe])=>{const W=F.findIndex(fe=>fe.value===`__group_${ee}`),L=c.includes(ee),pe=oe.filter(fe=>{const B=`${fe.provider}/${fe.id}`;return!u.includes(B)});return pe.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":W,children:[t.jsx(Fn,{provider:ee,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:ee}),d&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${L?"model-combobox-optgroup-favorite--active":""}`,onClick:fe=>{fe.stopPropagation(),d(ee)},title:L?"Remove from favorites":"Add to favorites","aria-label":L?`Remove ${ee} from favorites`:`Add ${ee} to favorites`,children:"★"})]}),pe.map(fe=>{const B=`${fe.provider}/${fe.id}`,ve=F.findIndex(Pe=>Pe.value===B),Fe=b===ve,ae=n===B,qe=u.includes(B);return t.jsxs("div",{"data-index":ve,className:`model-combobox-option ${Fe?"model-combobox-option--highlighted":""} ${ae?"model-combobox-option--selected":""}`,onClick:()=>He(B),onMouseEnter:()=>v(ve),role:"option","aria-selected":ae,children:[t.jsx("span",{className:"model-combobox-option-text",children:fe.name}),t.jsx("span",{className:"model-combobox-option-id",children:fe.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${qe?"model-combobox-option-favorite--active":""}`,onClick:Pe=>{Pe.stopPropagation(),m(B)},title:qe?"Remove from favorites":"Add to favorites","aria-label":qe?`Remove ${fe.name} from favorites`:`Add ${fe.name} to favorites`,children:qe?"★":"☆"})]},B)})]},ee)}),O.length===0&&Y&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",x,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:N,className:"model-combobox",onKeyDown:je,children:t.jsxs("button",{ref:R,type:"button",id:o,className:"model-combobox-trigger",onClick:Ne,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[Z&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Fn,{provider:Z,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:M||a}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),C&&ie?Ra.createPortal(ie,C):null]})}function Gu(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Bn(e,n){if(typeof window>"u")return null;const s=window.localStorage?.getItem;return typeof s!="function"?null:s.call(window.localStorage,Gu(e,n))}function us(e,n,s){if(typeof window>"u")return;const a=window.localStorage?.setItem;typeof a=="function"&&a.call(window.localStorage,Gu(e,s),n)}function jr(e,n){if(typeof window>"u")return;const s=window.localStorage?.removeItem;typeof s=="function"&&s.call(window.localStorage,Gu(e,n))}const SE=1e4,CE=1e3;function yc(){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 b=await ql();n(b)}catch(b){o(b instanceof Error?b.message:"Failed to fetch nodes")}},[]);i.useEffect(()=>{let b=!1;async function v(){a(!0);try{const j=await ql();b||(n(j),o(null))}catch(j){b||o(j instanceof Error?j.message:"Failed to fetch nodes")}finally{b||a(!1)}}v();const S=()=>{if(document.visibilityState!=="visible")return;const j=Date.now();j-c.current<CE||(c.current=j,d())};return document.addEventListener("visibilitychange",S),()=>{b=!0,document.removeEventListener("visibilitychange",S)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},SE),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async b=>{const{projectMappings:v,...S}=b,j=await e1(S);if(v.length>0)try{await B0(j.id,v)}catch(C){const w=C instanceof Error?C.message:"Failed to persist project mappings";let N="";try{await Zm(j.id)}catch(R){N=R instanceof Error?R.message:"Failed to unregister node after mapping failure"}throw await d(),N?new Error(`${w}. Cleanup also failed: ${N}`):new Error(w)}return await d(),j},[d]),m=i.useCallback(async(b,v)=>{const S=await n1(b,v);return n(j=>j.map(C=>C.id===b?S:C)),S},[]),h=i.useCallback(async b=>{await Zm(b),n(v=>v.filter(S=>S.id!==b))},[]),f=i.useCallback(async b=>{const v=await r1(b);n(S=>S.map(j=>j.id===b?{...j,status:v.status,updatedAt:v.checkedAt}:j))},[]),p=i.useCallback(b=>s1(b),[]),g=i.useCallback(async(b,v)=>{const S=await i1(b,v);return n(j=>j.map(C=>C.id===b?{...C,dockerConfig:S}:C)),S},[]),x=i.useCallback(async b=>{const v=await a1(b);return"persistedVersion"in v?v:{persistedVersion:0,deployedVersion:null,needsRecreate:!1}},[]),y=i.useCallback(async b=>t1(b),[]);return{nodes:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h,healthCheck:f,fetchDockerConfig:p,patchDockerConfig:g,fetchDockerDiff:x,discoverRemoteProjects:y}}const Kr="kb-quick-entry-text",EE=["image/png","image/jpeg","image/gif","image/webp"];function _E(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function Gc(e,n){return e&&n?`${e}/${n}`:""}function Jc(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 qb({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"&&Bn(Kr,l)||""),[g,x]=i.useState(!1),[y,b]=i.useState(!1),[v,S]=i.useState(!1),j=i.useRef(null),C=i.useRef(null),w=i.useRef(!1),N=i.useRef(l),[R,z]=i.useState([]),E=i.useRef([]),[I,O]=i.useState([]),[U,A]=i.useState(!1),[D,K]=i.useState(""),[Z,ne]=i.useState(null),[F,M]=i.useState([]),[P,$]=i.useState(void 0),[k,J]=i.useState(!1),[ce,je]=i.useState(!1),[He,xe]=i.useState(!1),[Ne,Y]=i.useState(!1),[ie,ee]=i.useState(!1),[oe,W]=i.useState(null),[L,pe]=i.useState(void 0),[fe,B]=i.useState(void 0),[ve,Fe]=i.useState(void 0),[ae,qe]=i.useState(void 0),[Pe,nt]=i.useState(void 0),[Be,de]=i.useState(void 0),Ie=i.useRef(null),$e=i.useRef(null),st=i.useRef(null),Ue=i.useRef(null),me=i.useRef(null),re=i.useRef(null),_e=i.useRef(null),xt=i.useRef(null),[dt,Qe]=i.useState(null),[vt,Ae]=i.useState(null),[Je,ct]=i.useState(null),[Nt,yt]=i.useState(null),Se=i.useRef(null),G=i.useRef(null),[ge,pt]=i.useState(null),[ke]=i.useState(()=>typeof document<"u"?document.body:null),[tt,Rt]=i.useState(!1),[Re,be]=i.useState(null),[at,ot]=i.useState(a??[]),[gt,St]=i.useState([]),[Lt,Yt]=i.useState([]),[tn,mn]=i.useState(null),[Qt,yn]=i.useState(void 0),[Gt,on]=i.useState(!1),[sn,ln]=i.useState(Ds),[Wt,ye]=i.useState(void 0),{nodes:Le}=yc(),[Ke,ut]=i.useState(!1),[Ve,Pt]=i.useState(!1),Ot=i.useRef(null),bt=i.useRef(null),[Dt,Ft]=i.useState(null),Ht=d??gt,rn=u??Lt,Xt=!e;i.useEffect(()=>{if(a)ot(a),Rt(!1),be(null);else{let X=!1;return Rt(!0),be(null),Ks().then(_=>{X||(ot(_.models),d||St(_.favoriteProviders),u||Yt(_.favoriteModels))}).catch(_=>{X||be(Ee(_)||"Failed to load models")}).finally(()=>{X||Rt(!1)}),gc(l).then(_=>{X||mn(_)}).catch(()=>{}),()=>{X=!0}}},[a,d,u,l]);const an=Gc(L,fe),Me=Gc(ve,ae),it=Gc(Pe,Be),kt=!!(L&&fe),$t=!!(ve&&ae),se=!!(Pe&&Be),te=Number(kt)+Number($t)+Number(se),De=Qt?tn?.modelPresets?.find(X=>X.id===Qt)?.name??"Models":te>0?`${te} model${te===1?"":"s"}`:"Models",ft=i.useCallback((X,_)=>{if(!X||!_)return"Using default";const ue=at.find(Ce=>Ce.provider===X&&Ce.id===_);return ue?`${ue.provider}/${ue.id}`:`${X}/${_}`},[at]);i.useEffect(()=>{p(Bn(Kr,l)||"")},[l]),i.useEffect(()=>{typeof window<"u"&&us(Kr,f,l)},[f,l]),i.useEffect(()=>{N.current!==l&&(N.current=l,M([]),$(void 0),ne(null),J(!1),Qe(null))},[l]),i.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),i.useEffect(()=>{E.current=R},[R]),i.useEffect(()=>()=>{E.current.forEach(X=>URL.revokeObjectURL(X.previewUrl))},[]);const qt=i.useCallback(()=>{const X=j.current;if(!X)return;X.style.height="auto";const _=Math.min(X.scrollHeight,200);X.style.height=`${_}px`},[]);i.useEffect(()=>{y&&qt()},[f,y,qt]),i.useEffect(()=>{if(!g&&f===""&&j.current){const X=setTimeout(()=>{j.current?.focus()},0);return()=>clearTimeout(X)}},[g,f]),i.useEffect(()=>{U||K("")},[U]),i.useEffect(()=>{if(!Ke)return;const X=_=>{const ue=_.target,Ce=Ot.current?.contains(ue),We=bt.current?.contains(ue);!Ce&&!We&&ut(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[Ke]),i.useEffect(()=>{if(!ie)return;const X=_=>{const ue=_.target,Ce=Ie.current?.contains(ue),We=$e.current?.contains(ue),At=ue instanceof Element&&ue.closest?.(".model-combobox-dropdown--portal")!=null;!Ce&&!We&&!At&&(ee(!1),W(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[ie]),i.useEffect(()=>{if(!ce)return;const X=_=>{const ue=_.target;me.current?.contains(ue)||re.current?.contains(ue)||(je(!1),Ae(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[ce]),i.useEffect(()=>{if(!k)return;const X=_=>{const ue=_.target;st.current?.contains(ue)||Ue.current?.contains(ue)||(J(!1),Qe(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[k]),i.useEffect(()=>{if(!He)return;const X=_=>{const ue=_.target;_e.current?.contains(ue)||xt.current?.contains(ue)||(xe(!1),ct(null))};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[He]);const zt=i.useCallback(()=>{R.forEach(X=>URL.revokeObjectURL(X.previewUrl)),z([]),C.current&&(C.current.value=""),p(""),O([]),ne(null),J(!1),Qe(null),je(!1),Ae(null),xe(!1),ct(null),pe(void 0),B(void 0),Fe(void 0),qe(void 0),nt(void 0),de(void 0),yn(void 0),on(!1),ln(Ds),ye(void 0),A(!1),ee(!1),yt(null),W(null),ut(!1),Pt(!1),b(!1),S(!1),w.current=!0,j.current&&(j.current.style.height="auto"),typeof window<"u"&&jr(Kr,l)},[R,l]),Pn=i.useCallback(X=>{if(!X||X.length===0)return;const _=[];for(let ue=0;ue<X.length;ue++){const Ce=X[ue];EE.includes(Ce.type)&&_.push({file:Ce,previewUrl:URL.createObjectURL(Ce)})}_.length>0&&z(ue=>[...ue,..._])},[]),he=i.useCallback(X=>{g||Pn(X.clipboardData?.files)},[Pn,g]),mt=i.useCallback(X=>{z(_=>{const ue=_[X];return ue&&URL.revokeObjectURL(ue.previewUrl),_.filter((Ce,We)=>We!==X)})},[]),ht=i.useCallback(async()=>{const X=f.trim();if(!X||g||!e)return;const _=f;x(!0),p("");try{const ue=await e({description:X,column:"triage",dependencies:I.length?I:void 0,...Z?{assignedAgentId:Z}:{},modelPresetId:Qt,modelProvider:kt?L:void 0,modelId:kt?fe:void 0,validatorModelProvider:$t?ve:void 0,validatorModelId:$t?ae:void 0,planningModelProvider:se?Pe:void 0,planningModelId:se?Be:void 0,...Gt?{executionMode:"fast"}:{},priority:sn,nodeId:Wt});if(ue&&R.length>0){const Ce=[];for(const We of R)try{await bc(ue.id,We.file,l)}catch{Ce.push(We.file.name)}Ce.length>0&&n(`Failed to upload: ${Ce.join(", ")}`,"error")}zt()}catch(ue){p(_),n(Ee(ue)||"Failed to create task","error")}finally{x(!1)}},[f,g,e,I,Z,kt,L,fe,$t,ve,ae,se,Pe,Be,R,l,n,zt,Gt,sn,Wt]),wt=i.useCallback(X=>{if(X.key==="Enter"){if(X.shiftKey&&y)return;X.preventDefault(),ht()}else if(X.key==="Escape"){if(X.preventDefault(),oe){W(null);return}if(ie){ee(!1),yt(null);return}if(U){A(!1);return}if(Ke){ut(!1);return}if(ce){je(!1),Ae(null);return}if(He){xe(!1),ct(null);return}if(k){J(!1),Qe(null);return}f.trim()&&(p(""),j.current&&(j.current.style.height="auto"),typeof window<"u"&&jr(Kr,l)),b(!1),S(!1),j.current?.blur()}},[ht,f,y,U,k,ce,ie,oe,Ke,He,l,S]),Xe=i.useCallback(()=>{w.current&&(w.current=!1)},[]),Et=i.useCallback(()=>{c&&b(!0)},[c]),Zt=i.useCallback(X=>{O(_=>_.includes(X)?_.filter(ue=>ue!==X):[..._,X])},[]),le=i.useCallback(()=>{const X=window.visualViewport;return X&&X.width>0&&X.height>0?{width:X.width,height:X.height,offsetTop:X.offsetTop,offsetLeft:X.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),lt=i.useCallback(()=>{const X=Ie.current;if(!X)return;const _=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=ue<=768,Kt=Math.min(It?Ce*.6:Ce*.5,360),fn=Math.max(_.width*1.35,320),An=It?Math.min(ue-q*2,360):fn,jn=Math.min(An,Math.max(ue-q*2,240)),En=_.top-We,ts=_.bottom-We,Ln=_.left-At,os=Ce-ts,fs=En,ns=Math.max(os-we-Oe,160),Zn=Math.max(fs-we-Oe,160),es=os<Kt&&fs>os,Ss=Math.max(Math.min(es?Zn:ns,Kt),160),ls=Math.min(Math.max(Ln,q),ue-q-jn)+At,ss=es?Math.max(we+We,En-Ss-Oe+We):Math.min(ts+Oe+We,Ce+We-we-Ss);yt({top:ss,left:ls,width:jn,maxHeight:Ss})},[le]),nn=i.useCallback(()=>{const X=Ot.current?.querySelector(".refine-button");if(!X)return;const _=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=8,we=12,Oe=4,It=Math.min(200,Math.max(Ce-we*2,160)),Kt=Math.min(200,ue-q*2),fn=_.top-We,An=_.bottom-We,jn=_.left-At,En=Ce-An,ts=fn,Ln=En<It&&ts>En,os=Math.min(Math.max(jn,q),ue-q-Kt)+At,fs=Ln?Math.max(we+We,fn-It-Oe+We):Math.min(An+Oe+We,Ce+We-we-It);Ft({top:fs,left:os})},[le]),Rn=i.useCallback(()=>{const X=Se.current;if(!X)return;const _=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=ue<=768,Kt=Math.min(It?Ce*.6:Ce*.5,320),fn=It?Math.min(ue-q*2,360):Math.max(_.width,280),An=Math.min(fn,Math.max(ue-q*2,240)),jn=_.top-We,En=_.bottom-We,ts=_.left-At,Ln=Ce-En,os=jn,fs=Math.max(Ln-we-Oe,200),ns=Math.max(os-we-Oe,200),Zn=Ln<Kt&&os>Ln,es=Math.max(Math.min(Zn?ns:fs,Kt),200),Ss=Math.min(Math.max(ts,q),ue-q-An)+At,ls=Zn?Math.max(we+We,jn-es-Oe+We):Math.min(En+Oe+We,Ce+We-we-es);pt({top:ls,left:Ss,width:An,maxHeight:es})},[le]),Hn=i.useCallback(()=>{const X=st.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=ue<=768,Kt=Math.min(It?Ce*.6:Ce*.5,320),fn=It?Math.min(ue-q*2,280):Math.max(_.width,240),An=Math.min(fn,Math.max(ue-q*2,200)),jn=_.top-We,En=_.bottom-We,ts=_.left-At,Ln=Ce-En,os=jn,fs=Math.max(Ln-we-Oe,160),ns=Math.max(os-we-Oe,160),Zn=Ln<Kt&&os>Ln,es=Math.max(Math.min(Zn?ns:fs,Kt),160),Ss=Math.min(Math.max(ts,q),ue-q-An)+At,ls=Zn?Math.max(we+We,jn-es-Oe+We):Math.min(En+Oe+We,Ce+We-we-es);Qe({top:ls,left:Ss,width:An,maxHeight:es})},[le]),wn=i.useCallback(()=>{const X=me.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=ue<=768,Kt=Math.min(It?Ce*.6:Ce*.5,320),fn=It?Math.min(ue-q*2,280):Math.max(_.width,240),An=Math.min(fn,Math.max(ue-q*2,200)),jn=_.top-We,En=_.bottom-We,ts=_.left-At,Ln=Ce-En,os=jn,fs=Math.max(Ln-we-Oe,160),ns=Math.max(os-we-Oe,160),Zn=Ln<Kt&&os>Ln,es=Math.max(Math.min(Zn?ns:fs,Kt),160),Ss=Math.min(Math.max(ts,q),ue-q-An)+At,ls=Zn?Math.max(we+We,jn-es-Oe+We):Math.min(En+Oe+We,Ce+We-we-es);Ae({top:ls,left:Ss,width:An,maxHeight:es})},[le]),rs=i.useCallback(()=>{const X=_e.current?.querySelector("button");if(!X)return;const _=X.getBoundingClientRect(),{width:ue,height:Ce,offsetTop:We,offsetLeft:At}=le(),q=16,we=16,Oe=4,It=220,Kt=Math.min(Math.max(_.width,200),Math.max(ue-q*2,200)),fn=_.top-We,An=_.bottom-We,jn=_.left-At,En=Ce-An,ts=fn,Ln=Math.max(En-we-Oe,160),os=Math.max(ts-we-Oe,160),fs=En<It&&ts>En,ns=Math.max(Math.min(fs?os:Ln,It),160),Zn=Math.min(Math.max(jn,q),ue-q-Kt)+At,es=fs?Math.max(we+We,fn-ns-Oe+We):Math.min(An+Oe+We,Ce+We-we-ns);ct({top:es,left:Zn,width:Kt,maxHeight:ns})},[le]);i.useEffect(()=>{if(!ie)return;const X=()=>lt();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[ie,lt]),i.useEffect(()=>{if(!Ke)return;const X=()=>nn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[Ke,nn]),i.useEffect(()=>{if(!U)return;const X=()=>Rn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[U,Rn]),i.useEffect(()=>{if(!k)return;const X=()=>Hn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[k,Hn]),i.useEffect(()=>{if(!ce)return;const X=()=>wn();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[ce,wn]),i.useEffect(()=>{if(!He)return;const X=()=>rs();window.addEventListener("resize",X),window.addEventListener("scroll",X,!0);const _=window.visualViewport;return _&&(_.addEventListener("resize",X),_.addEventListener("scroll",X)),()=>{window.removeEventListener("resize",X),window.removeEventListener("scroll",X,!0),_&&(_.removeEventListener("resize",X),_.removeEventListener("scroll",X))}},[He,rs]);const _s=i.useCallback(X=>{const _=Jc(X);nt(_.provider),de(_.modelId)},[]),bn=i.useCallback(X=>{const _=Jc(X);pe(_.provider),B(_.modelId)},[]),Ut=i.useCallback(X=>{const _=Jc(X);Fe(_.provider),qe(_.modelId)},[]),xs=i.useCallback(async X=>{if(m){m(X);return}const _=gt,Ce=_.includes(X)?_.filter(We=>We!==X):[X,..._];St(Ce);try{await Dn({favoriteProviders:Ce,favoriteModels:Lt})}catch{St(_)}},[gt,Lt,m]),xn=i.useCallback(async X=>{if(h){h(X);return}const _=Lt,Ce=_.includes(X)?_.filter(We=>We!==X):[X,..._];Yt(Ce);try{await Dn({favoriteProviders:gt,favoriteModels:Ce})}catch{Yt(_)}},[Lt,gt,h]),Xn=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}r?.(X),zt()},[f,r,n,zt]),$n=i.useCallback(()=>{const X=f.trim();if(!X){n("Enter a description first","error");return}o?.(X),zt()},[f,o,n,zt]),vs=i.useCallback(()=>{ht()},[ht]),ms=i.useCallback(async X=>{const _=f.trim();if(!(!_||Ve)){ut(!1),Pt(!0);try{const ue=await cb(_,X,l);p(ue),n("Description refined with AI","success"),j.current&&(j.current.style.height="auto",j.current.style.height=`${Math.min(j.current.scrollHeight,200)}px`)}catch(ue){const Ce=db(ue);n(Ce,"error")}finally{Pt(!1)}}},[f,Ve,n,l]),hs=(X,_)=>X.length>_?X.slice(0,_)+"…":X,Jn=i.useCallback(async()=>{if(a){ot(a),be(null),Rt(!1);return}Rt(!0),be(null);try{const X=await Ks();ot(X.models),d||St(X.favoriteProviders),u||Yt(X.favoriteModels)}catch(X){be(Ee(X)||"Failed to load models")}finally{Rt(!1)}},[a,d,u]),ps=i.useCallback(async()=>{if(F.length>0&&P===l){J(!0),Hn();return}Y(!0);try{const X=await Pr(void 0,l);M(X),$(l),J(!0),Hn()}catch(X){const _=Ee(X);n(_?`Failed to load agents: ${_}`:"Failed to load agents","error"),J(!1)}finally{Y(!1)}},[F.length,P,l,n,Hn]),Yn=(Z?F.find(X=>X.id===Z):void 0)?.name??Z,ys=Wt?Le.find(X=>X.id===Wt):void 0,ws=v,Ms=i.useCallback(()=>{S(X=>{const _=!X;return b(_),_})},[]);return t.jsxs("div",{className:`quick-entry-box ${v?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:j,className:`quick-entry-input ${y?"quick-entry-input--expanded":""}`,placeholder:g?"Creating...":"Add a task...",value:f,onChange:X=>p(X.target.value),onKeyDown:wt,onPaste:he,onFocus:Et,onBlur:Xe,disabled:g||Xt,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":v})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:Ms,"aria-expanded":v,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:v?"Collapse":"Expand",children:v?t.jsx(Pi,{size:14}):t.jsx(pn,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!ws,"aria-hidden":!ws,children:[ws&&!g&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:Xn,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx($i,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:$n,onMouseDown:X=>X.preventDefault(),disabled:!f.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(hc,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Ot,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Ve?"refine-button--loading":""}`,onClick:()=>{ut(X=>{const _=!X;return _?nn():Ft(null),_})},disabled:!f.trim()||Ve,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(gs,{size:12,style:{verticalAlign:"middle"}}),Ve?"Refining...":"Refine"]}),Ke&&ke&&Dt&&Ra.createPortal(t.jsxs("div",{ref:bt,className:"refine-menu refine-menu--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${Dt.top}px`,left:`${Dt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>ms("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:()=>ms("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:()=>ms("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:()=>ms("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"})]})]}),ke)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:Se,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{A(X=>{const _=!X;return _?(ee(!1),yt(null),W(null),J(!1),Qe(null),je(!1),Ae(null),xe(!1),ct(null),Rn()):pt(null),_})},children:[t.jsx(xr,{size:12,style:{verticalAlign:"middle"}}),I.length>0?`${I.length} deps`:"Deps"]})}),U&&ke&&ge&&(()=>{const X=D.toLowerCase(),_=(X?s.filter(ue=>ue.id.toLowerCase().includes(X)||ue.title&&ue.title.toLowerCase().includes(X)||ue.description&&ue.description.toLowerCase().includes(X)):[...s]).sort((ue,Ce)=>{const We=Ce.createdAt.localeCompare(ue.createdAt);if(We!==0)return We;const At=parseInt(ue.id.slice(ue.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ce.id.slice(Ce.id.lastIndexOf("-")+1),10)||0)-At});return Ra.createPortal(t.jsxs("div",{ref:G,className:"dep-dropdown dep-dropdown--portal",onMouseDown:ue=>ue.preventDefault(),style:{position:"fixed",top:`${ge.top}px`,left:`${ge.left}px`,width:`${ge.width}px`,maxHeight:ge.maxHeight?`${ge.maxHeight}px`:void 0,overflowY:ge.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:D,onChange:ue=>K(ue.target.value),onClick:ue=>ue.stopPropagation()}),_.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):_.map(ue=>t.jsxs("div",{className:`dep-dropdown-item${I.includes(ue.id)?" selected":""}`,onMouseDown:Ce=>Ce.preventDefault(),onClick:()=>Zt(ue.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:ue.id}),t.jsx("span",{className:"dep-dropdown-title",children:hs(ue.title||ue.description||ue.id,60)})]},ue.id))]}),ke)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>C.current?.click(),children:[t.jsx(Xg,{size:12,style:{verticalAlign:"middle"}}),R.length>0?`Attach (${R.length})`:"Attach"]}),t.jsxs("button",{ref:Ie,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{A(!1),J(!1),Qe(null),je(!1),Ae(null),xe(!1),ct(null),W(null),ee(!0),lt()},children:[t.jsx(No,{size:12,style:{verticalAlign:"middle"}}),De]}),t.jsx("div",{className:"node-trigger-wrap",ref:me,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-node-button",onClick:()=>{A(!1),J(!1),Qe(null),ee(!1),yt(null),W(null),xe(!1),ct(null),je(X=>{const _=!X;return _?wn():Ae(null),_})},children:[t.jsx(So,{size:12,style:{verticalAlign:"middle"}}),` ${ys?.name??"Node"}`,ys&&t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Oa,{status:ys.status,showLabel:!0})})]})}),ce&&ke&&vt&&Ra.createPortal(t.jsxs("div",{ref:re,className:"dep-dropdown node-picker-dropdown node-picker-dropdown--portal",onMouseDown:X=>X.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${Wt==null?" selected":""}`,onMouseDown:X=>X.preventDefault(),onClick:()=>{ye(void 0),je(!1),Ae(null)},children:t.jsx("span",{className:"node-picker-item-name",children:"Project default / local"})}),Le.map(X=>t.jsxs("div",{className:`dep-dropdown-item node-picker-item${Wt===X.id?" selected":""}`,onMouseDown:_=>_.preventDefault(),onClick:()=>{ye(X.id),je(!1),Ae(null)},children:[t.jsx("span",{className:"quick-entry-node-status",children:t.jsx(Oa,{status:X.status})}),t.jsx("span",{className:"node-picker-item-name",children:X.name}),t.jsx("span",{className:"node-picker-item-status",children:_E(X.status)})]},X.id))]}),ke),t.jsx("div",{className:"agent-trigger-wrap",ref:st,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{k?(J(!1),Qe(null)):(je(!1),Ae(null),xe(!1),ct(null),ps())},"data-testid":"quick-entry-agent-button",children:[t.jsx(zn,{size:12,style:{verticalAlign:"middle"}}),Yn?` ${Yn}`:" Agent"]})}),k&&ke&&dt&&Ra.createPortal(t.jsxs("div",{ref:Ue,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${dt.top}px`,left:`${dt.left}px`,width:`${dt.width}px`,maxHeight:dt.maxHeight?`${dt.maxHeight}px`:void 0,overflowY:dt.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Ne&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Ne&&F.map(X=>t.jsxs("div",{className:`dep-dropdown-item${Z===X.id?" selected":""}`,onMouseDown:_=>_.preventDefault(),onClick:()=>{ne(X.id===Z?null:X.id),J(!1),Qe(null)},children:[t.jsx(zn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:X.role}),t.jsx("span",{className:"dep-dropdown-title",children:X.name})]},X.id)),!Ne&&F.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),Z&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:X=>X.preventDefault(),onClick:()=>{ne(null),J(!1),Qe(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),ke),t.jsx("div",{className:"priority-trigger-wrap",ref:_e,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-priority-button",onClick:()=>{A(!1),J(!1),Qe(null),je(!1),Ae(null),ee(!1),yt(null),W(null),xe(X=>{const _=!X;return _?rs():ct(null),_})},children:[t.jsx(vw,{size:12,style:{verticalAlign:"middle"}}),` ${sn[0].toUpperCase()}${sn.slice(1)}`]})}),He&&ke&&Je&&Ra.createPortal(t.jsxs("div",{ref:xt,className:"dep-dropdown priority-picker-dropdown priority-picker-dropdown--portal",onMouseDown:X=>X.preventDefault(),style:{position:"fixed",top:`${Je.top}px`,left:`${Je.left}px`,width:`${Je.width}px`,maxHeight:Je.maxHeight?`${Je.maxHeight}px`:void 0,overflowY:Je.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select priority"}),pa.map(X=>{const _=`${X[0].toUpperCase()}${X.slice(1)}`;return t.jsx("div",{className:`dep-dropdown-item${sn===X?" selected":""}`,"data-testid":`quick-entry-priority-option-${X}`,onMouseDown:ue=>ue.preventDefault(),onClick:()=>{ln(X),xe(!1),ct(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:_})},X)})]}),ke),t.jsx("button",{type:"button",className:`btn btn-sm ${Gt?"btn-primary":""}`,onClick:()=>on(X=>!X),onMouseDown:X=>X.preventDefault(),"aria-pressed":Gt,"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:vs,onMouseDown:X=>X.preventDefault(),disabled:!f.trim()||g,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(eb,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),R.length>0&&t.jsx("div",{className:"inline-create-previews",children:R.map((X,_)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:X.previewUrl,alt:X.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>mt(_),disabled:g,title:"Remove image","data-testid":`quick-entry-preview-remove-${_}`,children:"×"})]},X.previewUrl))}),ie&&ke&&Nt&&Ra.createPortal(t.jsx("div",{ref:$e,className:"model-nested-menu model-nested-menu--portal",onMouseDown:X=>X.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${Nt.top}px`,left:`${Nt.left}px`,width:`${Nt.width}px`,maxHeight:Nt.maxHeight?`${Nt.maxHeight}px`:void 0,overflowY:Nt.maxHeight?"auto":void 0},children:oe===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${se?"model-menu-item--active":""}`,onClick:()=>W("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx($i,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:se?ft(Pe,Be):"Using default"}),t.jsx(On,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${kt?"model-menu-item--active":""}`,onClick:()=>W("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(gs,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:kt?ft(L,fe):"Using default"}),t.jsx(On,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${$t?"model-menu-item--active":""}`,onClick:()=>W("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(No,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Reviewer"]}),t.jsx("span",{className:"model-menu-item-value",children:$t?ft(ve,ae):"Using default"}),t.jsx(On,{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:()=>W(null),"data-testid":"model-submenu-back",children:[t.jsx(pn,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[oe==="plan"&&"Plan Model",oe==="executor"&&"Executor Model",oe==="validator"&&"Reviewer Model"]}),t.jsx(Is,{models:at,value:oe==="plan"?it:oe==="executor"?an:Me,onChange:oe==="plan"?_s:oe==="executor"?bn:Ut,placeholder:"Using default",disabled:tt,id:`model-${oe}-select`,label:`${oe} model`,favoriteProviders:Ht,onToggleFavorite:xs,favoriteModels:rn,onToggleModelFavorite:xn}),Re&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Re}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:Jn,children:"Retry"})]})]})}),ke)]}),t.jsx("input",{ref:C,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:X=>{Pn(X.target.files),X.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function ME(e){return Hu(e)||e}function AE(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 RE(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,y=o.get(x)||[];y.push(g),o.set(x,y)}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 y=l.get(x);return y&&(y.column==="done"||y.column==="in-review"||y.column==="archived")})),m=AE(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:ME(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 Bh=100,Yc=50,Uh=25;function IE({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:y,onDeleteTask:b,onArchiveAllDone:v,collapsed:S,onToggleCollapse:j,allTasks:C,availableModels:w,onPlanningMode:N,onSubtaskBreakdown:R,onOpenDetailWithTab:z,favoriteProviders:E,favoriteModels:I,onToggleFavorite:O,onToggleModelFavorite:U,isSearchActive:A,taskStuckTimeoutMs:D,onOpenMission:K,lastFetchTimeMs:Z,workflowStepNameLookup:ne,blockerFanoutMap:F}){const[M,P]=i.useState(!1),[$,k]=i.useState(Yc),[J,ce]=i.useState(!1),[je,He]=i.useState(!1),[xe,Ne]=i.useState(!1),[Y,ie]=i.useState(!1),ee=i.useRef(null),oe=AC(n.length),{confirm:W}=pi();i.useEffect(()=>{if(!J)return;function _e(dt){ee.current?.contains(dt.target)||ce(!1)}function xt(dt){dt.key==="Escape"&&ce(!1)}return document.addEventListener("mousedown",_e),document.addEventListener("keydown",xt),()=>{document.removeEventListener("mousedown",_e),document.removeEventListener("keydown",xt)}},[J]);const L=e==="archived",pe=L&&S,fe=!L&&!A&&e!=="in-progress"&&n.length>Bh;i.useEffect(()=>{k(_e=>e==="in-progress"||L||n.length<=Bh?Yc:Math.min(Math.max(_e,Yc),n.length))},[e,L,n.length]);const B=i.useCallback(_e=>{L||(_e.preventDefault(),_e.dataTransfer.dropEffect="move",P(!0))},[L]),ve=i.useCallback(_e=>{_e.currentTarget.contains(_e.relatedTarget)||P(!1)},[]),Fe=i.useCallback(async _e=>{_e.preventDefault(),P(!1);const xt=_e.dataTransfer.getData("text/plain");if(!xt)return;const dt=n.find(Qe=>Qe.id===xt);if(!(dt&&dt.column===e))try{const vt=(C?.find(ct=>ct.id===xt)??dt)?.steps.some(ct=>ct.status!=="pending")??!1,Ae=(e==="todo"||e==="triage")&&vt;let Je;if(Ae){if(await W({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Je={preserveProgress:!0};else if(!await W({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(xt,e,Je)}catch(Qe){c(Ee(Qe),"error")}},[c,C,e,W,r,n]),ae=i.useMemo(()=>e!=="in-progress"?[]:RE(n,n,a),[e,n,a]),qe=i.useMemo(()=>fe?n.slice(0,$):n,[fe,n,$]),Pe=Math.max(0,n.length-qe.length),nt=i.useCallback(()=>{k(_e=>Math.min(_e+Uh,n.length))},[n.length]),Be=i.useCallback(async()=>{if(ce(!1),!(n.length===0||!await W({title:"Replan All Tasks",message:`Move all ${n.length} todo task${n.length===1?"":"s"} back to planning to be replanned?`}))){He(!0);try{const xt=await Promise.allSettled(n.map(vt=>r(vt.id,"triage"))),dt=xt.filter(vt=>vt.status==="rejected").length,Qe=xt.length-dt;dt===0?c(`Moved ${Qe} task${Qe===1?"":"s"} to planning for replanning`,"success"):c(`Moved ${Qe} of ${xt.length} tasks; ${dt} failed`,"error")}finally{He(!1)}}},[n,r,c,W]),de=i.useMemo(()=>n.filter(_e=>!_e.paused&&!_e.assignedAgentId),[n]),Ie=de.length,$e=e==="todo"||e==="in-progress"||e==="in-review",st=je||xe||Y,Ue=i.useCallback(async()=>{if(!(!o||(ce(!1),Ie===0)||!await W({title:"Stop All Tasks",message:`Stop all ${Ie} ${ds[e].toLowerCase()} task${Ie===1?"":"s"}?`,danger:!0}))){Ne(!0);try{const xt=await Promise.allSettled(de.map(vt=>o(vt.id))),dt=xt.filter(vt=>vt.status==="rejected").length,Qe=xt.length-dt;dt===0?c(`Stopped ${Qe} task${Qe===1?"":"s"}`,"success"):c(`Stopped ${Qe} of ${xt.length} tasks; ${dt} failed`,"error")}finally{Ne(!1)}}},[o,Ie,e,de,c,W]),me=i.useCallback(async()=>{if(ce(!1),n.length===0||!await W({title:"Move All to Todo",message:`Move all ${n.length} ${ds[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`}))return;const xt=n.some(Qe=>Qe.steps.some(vt=>vt.status!=="pending"));let dt=!1;if(xt){if(await W({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 W({title:"Reset Progress?",message:"Reset step progress for tasks before moving to Todo?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}ie(!0);try{const Qe=await Promise.allSettled(n.map(Je=>r(Je.id,"todo",dt?{preserveProgress:!0}:void 0))),vt=Qe.filter(Je=>Je.status==="rejected").length,Ae=Qe.length-vt;vt===0?c(`Moved ${Ae} task${Ae===1?"":"s"} to Todo`,"success"):c(`Moved ${Ae} of ${Qe.length} tasks to Todo; ${vt} failed`,"error")}finally{ie(!1)}},[n,e,r,c,W]),re=i.useCallback(async()=>{if(!(!v||n.length===0||!await W({title:"Archive All Done",message:`Archive all ${n.length} done tasks?`,danger:!0})))try{const xt=await v();c(`Archived ${xt.length} tasks`,"success")}catch(xt){c(Ee(xt)||"Failed to archive tasks","error")}},[v,n.length,c,W]);return t.jsxs("div",{className:`column${M?" drag-over":""}${L?" column-archived":""}${pe?" column-collapsed":""}`,"data-column":e,onDragOver:B,onDragLeave:ve,onDrop:Fe,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${oe?" 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"&&v&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:re,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(To,{})}),L&&j&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:j,title:S?"Expand archived tasks":"Collapse archived tasks","aria-label":S?"Expand archived tasks":"Collapse archived tasks",children:S?t.jsx(pn,{size:16}):t.jsx(Pi,{size:16})}),$e&&t.jsxs("div",{className:"column-menu",ref:ee,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ce(_e=>!_e),"aria-haspopup":"menu","aria-expanded":J,"aria-label":`${ds[e]} column actions`,title:"Column actions",disabled:st,children:t.jsx(ew,{})}),J&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void Be(),disabled:n.length===0||je,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 Ue(),disabled:Ie===0||xe||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":Ie===0?"No manually pausable tasks":`Pause ${Ie} active unassigned task${Ie===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void me(),disabled:n.length===0||Y,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!pe&&t.jsx("p",{className:"column-desc",children:_C[e]}),!pe&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&d&&t.jsx(qb,{onCreate:d,addToast:c,tasks:C??[],availableModels:w,onPlanningMode:N,onSubtaskBreakdown:R,projectId:s,autoExpand:!1,favoriteProviders:E,favoriteModels:I,onToggleFavorite:O,onToggleModelFavorite:U}),e==="in-progress"?ae.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):ae.map(_e=>t.jsx(Hb,{label:_e.label,activeTasks:_e.activeTasks,queuedTasks:_e.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onOpenDetailWithTab:z,taskStuckTimeoutMs:D,onOpenMission:K,lastFetchTimeMs:Z,workflowStepNameLookup:ne,blockerFanoutMap:F},_e.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[qe.map(_e=>t.jsx(_o,{task:_e,projectId:s,onOpenDetail:l,addToast:c,globalPaused:f,onUpdateTask:p,onRetryTask:g,onArchiveTask:x,onUnarchiveTask:y,onDeleteTask:b,onOpenDetailWithTab:z,taskStuckTimeoutMs:D,onOpenMission:K,onMoveTask:r,lastFetchTimeMs:Z,workflowStepNameLookup:ne,fanout:F?.get(_e.id)},_e.id)),fe&&Pe>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:nt,children:["Load ",Math.min(Uh,Pe)," more (",Pe," remaining)"]})]}),t.jsx(la,{slotId:"board-column-footer",projectId:s})]})]})}const Vb=i.memo(IE);Vb.displayName="Column";const TE=new Set(["in-progress","in-review"]),PE=new Set(["triage","todo","in-progress","in-review"]);function $E(e,n){return!e||e.column==="done"||e.column==="archived"||e.column==="in-review"&&e.paused===!0||e.column==="in-review"&&e.status==="failed"&&(e.mergeRetries??0)>=n}function DE(e,n){const s=Date.parse(e.columnMovedAt??e.updatedAt);return Number.isFinite(s)?Math.max(0,n-s):0}function LE(e,n,s={}){const a=s.nowMs??Date.now(),r=s.highFanoutTodoThreshold??Wu,o=s.staleHighFanoutAgeThresholdMs??Ab,l=new Map(e.map(m=>[m.id,m])),c=new Map,d=m=>{let h=c.get(m);return h||(h={dependentIds:[],blockedByDependentIds:[],activeCount:0,activeTodoCount:0},c.set(m,h)),h};for(const m of e){const h=PE.has(m.column),f=m.column==="todo";for(const p of m.dependencies??[]){if(!p)continue;const g=d(p);g.dependentIds.push(m.id),h&&(g.activeCount+=1),f&&(g.activeTodoCount+=1)}if(m.blockedBy){const p=d(m.blockedBy);p.dependentIds.push(m.id),p.blockedByDependentIds.push(m.id),h&&(p.activeCount+=1),f&&(p.activeTodoCount+=1)}}const u=new Map;for(const[m,h]of c){const f=l.get(m),p=$E(f,n)?[...h.blockedByDependentIds]:[],g=h.activeTodoCount>=r,x=f?DE(f,a):0,y=f?.column,b=y!==void 0&&g&&TE.has(y)&&x>=o;u.set(m,{totalCount:h.activeCount,activeTodoCount:h.activeTodoCount,dependentIds:h.dependentIds,staleBlockedByDependentIds:p,isHighFanout:g,escalation:b?{blockerId:m,activeTodoCount:h.activeTodoCount,totalActiveCount:h.activeCount,blockingAgeMs:x}:void 0})}return u}const OE=3;function Ju(e,n={}){return LE(e,OE,{staleHighFanoutAgeThresholdMs:n.staleHighFanoutAgeThresholdMs})}function FE(e,n={}){return i.useMemo(()=>Ju(e,n),[e,n.staleHighFanoutAgeThresholdMs])}function zE(e,n){return e.length!==n.length?!1:e.every((s,a)=>s===n[a])}const Hh=new Map;function BE(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 UE({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:y,onArchiveAllDone:b,onLoadArchivedTasks:v,searchQuery:S="",availableModels:j,onPlanningMode:C,onSubtaskBreakdown:w,onOpenDetailWithTab:N,favoriteProviders:R,favoriteModels:z,onToggleFavorite:E,onToggleModelFavorite:I,taskStuckTimeoutMs:O,onOpenMission:U,staleHighFanoutBlockerAgeThresholdMs:A,lastFetchTimeMs:D}){const[K,Z]=i.useState(!0),ne=i.useRef(!1),{fetchBatch:F}=zC(n),M=i.useRef(null),[P,$]=i.useState(Hh),k=FE(e,{staleHighFanoutAgeThresholdMs:A}),J=S.trim()!=="",ce=i.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),je=i.useCallback(()=>{Z(Ne=>{const Y=!Ne;return!Y&&!ne.current&&v&&(ne.current=!0,v()),Y})},[v]),He=i.useMemo(()=>{const Ne={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};for(const ee of e){const oe=Vu(ee.column)?ee.column:Wl;(Ne[oe]??Ne[Wl]).push(ee)}const Y=ce.current,ie={};for(const ee of oa){const oe=Rb(Ne[ee],ee);ie[ee]=zE(Y[ee],oe)?Y[ee]:oe}return ce.current=ie,ie},[e]);i.useEffect(()=>{let Ne=!1;return Uo(n).then(Y=>{if(Ne)return;const ie=new Map(Y.map(ee=>[ee.id,ee.name]));$(ee=>BE(ee,ie)?ee:ie)}).catch(()=>{Ne||$(Y=>Y.size===0?Y:Hh)}),()=>{Ne=!0}},[n]);const xe=i.useMemo(()=>e.filter(Ne=>Ne.prInfo||Ne.issueInfo).map(Ne=>Ne.id),[e]);return i.useEffect(()=>{if(xe.length!==0)return M.current&&clearTimeout(M.current),M.current=setTimeout(()=>{const Ne=[];for(let Y=0;Y<xe.length;Y+=50)Ne.push(xe.slice(Y,Y+50));Ne.forEach(Y=>{F(Y)})},500),()=>{M.current&&clearTimeout(M.current)}},[xe,F]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:oa.map(Ne=>t.jsx(Vb,{column:Ne,tasks:He[Ne],projectId:n,maxConcurrent:s,onMoveTask:a,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:f,onRetryTask:p,onArchiveTask:g,onUnarchiveTask:x,onDeleteTask:y,allTasks:e,availableModels:j,onOpenDetailWithTab:N,favoriteProviders:R,favoriteModels:z,onToggleFavorite:E,onToggleModelFavorite:I,isSearchActive:J,taskStuckTimeoutMs:O,onOpenMission:U,lastFetchTimeMs:D,workflowStepNameLookup:P,blockerFanoutMap:k,...Ne==="triage"?{onQuickCreate:c,onNewTask:d,onPlanningMode:C,onSubtaskBreakdown:w}:{},...Ne==="in-review"?{autoMerge:u,onToggleAutoMerge:m}:{},...Ne==="done"?{onArchiveAllDone:b}:{},...Ne==="archived"?{collapsed:K,onToggleCollapse:je}:{}},Ne))})})}function Li(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 HE(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let fr=0,yo=null;function qE(){if(typeof window>"u")return;if(fr>0){fr+=1;return}const e=document.documentElement,n=document.body;yo={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=`-${yo.scrollY}px`,n.style.left="0",n.style.right="0",n.style.width="100%",n.style.overflow="hidden",fr=1}function VE(){if(typeof window>"u"||fr===0||(fr-=1,fr>0||!yo))return;const e=document.documentElement,n=document.body,{htmlOverflow:s,bodyPosition:a,bodyTop:r,bodyLeft:o,bodyRight:l,bodyWidth:c,bodyOverflow:d,scrollY:u}=yo;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,yo=null,window.scrollTo(0,0)}function Ni(e){i.useEffect(()=>{if(!(!e||!HE()))return qE(),()=>{VE()}},[e])}function Qi(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 WE(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const KE=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,GE=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,JE={};function qh(e,n){return(JE.jsx?GE:KE).test(e)}const YE=/[ \t\n\f\r]/g;function QE(e){return typeof e=="object"?e.type==="text"?Vh(e.value):!1:Vh(e)}function Vh(e){return e.replace(YE,"")===""}class Ko{constructor(n,s,a){this.normal=s,this.property=n,a&&(this.space=a)}}Ko.prototype.normal={};Ko.prototype.property={};Ko.prototype.space=void 0;function Wb(e,n){const s={},a={};for(const r of e)Object.assign(s,r.property),Object.assign(a,r.normal);return new Ko(s,a,n)}function du(e){return e.toLowerCase()}class Xs{constructor(n,s){this.attribute=s,this.property=n}}Xs.prototype.attribute="";Xs.prototype.booleanish=!1;Xs.prototype.boolean=!1;Xs.prototype.commaOrSpaceSeparated=!1;Xs.prototype.commaSeparated=!1;Xs.prototype.defined=!1;Xs.prototype.mustUseProperty=!1;Xs.prototype.number=!1;Xs.prototype.overloadedBoolean=!1;Xs.prototype.property="";Xs.prototype.spaceSeparated=!1;Xs.prototype.space=void 0;let XE=0;const hn=Ha(),ks=Ha(),uu=Ha(),Mt=Ha(),Kn=Ha(),gr=Ha(),ni=Ha();function Ha(){return 2**++XE}const mu=Object.freeze(Object.defineProperty({__proto__:null,boolean:hn,booleanish:ks,commaOrSpaceSeparated:ni,commaSeparated:gr,number:Mt,overloadedBoolean:uu,spaceSeparated:Kn},Symbol.toStringTag,{value:"Module"})),Qc=Object.keys(mu);class Yu extends Xs{constructor(n,s,a,r){let o=-1;if(super(n,s),Wh(this,"space",r),typeof a=="number")for(;++o<Qc.length;){const l=Qc[o];Wh(this,Qc[o],(a&mu[l])===mu[l])}}}Yu.prototype.defined=!0;function Wh(e,n,s){s&&(e[n]=s)}function Dr(e){const n={},s={};for(const[a,r]of Object.entries(e.properties)){const o=new Yu(a,e.transform(e.attributes||{},a),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(a)&&(o.mustUseProperty=!0),n[a]=o,s[du(a)]=a,s[du(o.attribute)]=a}return new Ko(n,s,e.space)}const Kb=Dr({properties:{ariaActiveDescendant:null,ariaAtomic:ks,ariaAutoComplete:null,ariaBusy:ks,ariaChecked:ks,ariaColCount:Mt,ariaColIndex:Mt,ariaColSpan:Mt,ariaControls:Kn,ariaCurrent:null,ariaDescribedBy:Kn,ariaDetails:null,ariaDisabled:ks,ariaDropEffect:Kn,ariaErrorMessage:null,ariaExpanded:ks,ariaFlowTo:Kn,ariaGrabbed:ks,ariaHasPopup:null,ariaHidden:ks,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Kn,ariaLevel:Mt,ariaLive:null,ariaModal:ks,ariaMultiLine:ks,ariaMultiSelectable:ks,ariaOrientation:null,ariaOwns:Kn,ariaPlaceholder:null,ariaPosInSet:Mt,ariaPressed:ks,ariaReadOnly:ks,ariaRelevant:null,ariaRequired:ks,ariaRoleDescription:Kn,ariaRowCount:Mt,ariaRowIndex:Mt,ariaRowSpan:Mt,ariaSelected:ks,ariaSetSize:Mt,ariaSort:null,ariaValueMax:Mt,ariaValueMin:Mt,ariaValueNow:Mt,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Gb(e,n){return n in e?e[n]:n}function Jb(e,n){return Gb(e,n.toLowerCase())}const ZE=Dr({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:gr,acceptCharset:Kn,accessKey:Kn,action:null,allow:null,allowFullScreen:hn,allowPaymentRequest:hn,allowUserMedia:hn,alt:null,as:null,async:hn,autoCapitalize:null,autoComplete:Kn,autoFocus:hn,autoPlay:hn,blocking:Kn,capture:null,charSet:null,checked:hn,cite:null,className:Kn,cols:Mt,colSpan:null,content:null,contentEditable:ks,controls:hn,controlsList:Kn,coords:Mt|gr,crossOrigin:null,data:null,dateTime:null,decoding:null,default:hn,defer:hn,dir:null,dirName:null,disabled:hn,download:uu,draggable:ks,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:hn,formTarget:null,headers:Kn,height:Mt,hidden:uu,high:Mt,href:null,hrefLang:null,htmlFor:Kn,httpEquiv:Kn,id:null,imageSizes:null,imageSrcSet:null,inert:hn,inputMode:null,integrity:null,is:null,isMap:hn,itemId:null,itemProp:Kn,itemRef:Kn,itemScope:hn,itemType:Kn,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:hn,low:Mt,manifest:null,max:null,maxLength:Mt,media:null,method:null,min:null,minLength:Mt,multiple:hn,muted:hn,name:null,nonce:null,noModule:hn,noValidate:hn,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:hn,optimum:Mt,pattern:null,ping:Kn,placeholder:null,playsInline:hn,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:hn,referrerPolicy:null,rel:Kn,required:hn,reversed:hn,rows:Mt,rowSpan:Mt,sandbox:Kn,scope:null,scoped:hn,seamless:hn,selected:hn,shadowRootClonable:hn,shadowRootDelegatesFocus:hn,shadowRootMode:null,shape:null,size:Mt,sizes:null,slot:null,span:Mt,spellCheck:ks,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Mt,step:null,style:null,tabIndex:Mt,target:null,title:null,translate:null,type:null,typeMustMatch:hn,useMap:null,value:ks,width:Mt,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Kn,axis:null,background:null,bgColor:null,border:Mt,borderColor:null,bottomMargin:Mt,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:hn,declare:hn,event:null,face:null,frame:null,frameBorder:null,hSpace:Mt,leftMargin:Mt,link:null,longDesc:null,lowSrc:null,marginHeight:Mt,marginWidth:Mt,noResize:hn,noHref:hn,noShade:hn,noWrap:hn,object:null,profile:null,prompt:null,rev:null,rightMargin:Mt,rules:null,scheme:null,scrolling:ks,standby:null,summary:null,text:null,topMargin:Mt,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Mt,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:hn,disableRemotePlayback:hn,prefix:null,property:null,results:Mt,security:null,unselectable:null},space:"html",transform:Jb}),e2=Dr({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:ni,accentHeight:Mt,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Mt,amplitude:Mt,arabicForm:null,ascent:Mt,attributeName:null,attributeType:null,azimuth:Mt,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Mt,by:null,calcMode:null,capHeight:Mt,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:Mt,diffuseConstant:Mt,direction:null,display:null,dur:null,divisor:Mt,dominantBaseline:null,download:hn,dx:null,dy:null,edgeMode:null,editable:null,elevation:Mt,enableBackground:null,end:null,event:null,exponent:Mt,externalResourcesRequired:null,fill:null,fillOpacity:Mt,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:gr,g2:gr,glyphName:gr,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Mt,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Mt,horizOriginX:Mt,horizOriginY:Mt,id:null,ideographic:Mt,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Mt,k:Mt,k1:Mt,k2:Mt,k3:Mt,k4:Mt,kernelMatrix:ni,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Mt,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:Mt,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:Mt,overlineThickness:Mt,paintOrder:null,panose1:null,path:null,pathLength:Mt,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Kn,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Mt,pointsAtY:Mt,pointsAtZ:Mt,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:ni,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:ni,rev:ni,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:ni,requiredFeatures:ni,requiredFonts:ni,requiredFormats:ni,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:Mt,specularExponent:Mt,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Mt,strikethroughThickness:Mt,string:null,stroke:null,strokeDashArray:ni,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Mt,strokeOpacity:Mt,strokeWidth:null,style:null,surfaceScale:Mt,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:ni,tabIndex:Mt,tableValues:null,target:null,targetX:Mt,targetY:Mt,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:ni,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Mt,underlineThickness:Mt,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Mt,values:null,vAlphabetic:Mt,vMathematical:Mt,vectorEffect:null,vHanging:Mt,vIdeographic:Mt,version:null,vertAdvY:Mt,vertOriginX:Mt,vertOriginY:Mt,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Mt,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Gb}),Yb=Dr({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()}}),Qb=Dr({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Jb}),Xb=Dr({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),t2={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"},n2=/[A-Z]/g,Kh=/-[a-z]/g,s2=/^data[-\w.:]+$/i;function i2(e,n){const s=du(n);let a=n,r=Xs;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&s2.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(Kh,r2);a="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!Kh.test(o)){let l=o.replace(n2,a2);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=Yu}return new r(a,n)}function a2(e){return"-"+e.toLowerCase()}function r2(e){return e.charAt(1).toUpperCase()}const o2=Wb([Kb,ZE,Yb,Qb,Xb],"html"),Qu=Wb([Kb,e2,Yb,Qb,Xb],"svg");function l2(e){return e.join(" ").trim()}var sr={},Xc,Gh;function c2(){if(Gh)return Xc;Gh=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=`
|
|
652
|
+
`,u="/",m="*",h="",f="comment",p="declaration";function g(y,b){if(typeof y!="string")throw new TypeError("First argument must be a string");if(!y)return[];b=b||{};var v=1,S=1;function j(A){var D=A.match(n);D&&(v+=D.length);var K=A.lastIndexOf(d);S=~K?A.length-K:S+A.length}function C(){var A={line:v,column:S};return function(D){return D.position=new w(A),z(),D}}function w(A){this.start=A,this.end={line:v,column:S},this.source=b.source}w.prototype.content=y;function N(A){var D=new Error(b.source+":"+v+":"+S+": "+A);if(D.reason=A,D.filename=b.source,D.line=v,D.column=S,D.source=y,!b.silent)throw D}function R(A){var D=A.exec(y);if(D){var K=D[0];return j(K),y=y.slice(K.length),D}}function z(){R(s)}function E(A){var D;for(A=A||[];D=I();)D!==!1&&A.push(D);return A}function I(){var A=C();if(!(u!=y.charAt(0)||m!=y.charAt(1))){for(var D=2;h!=y.charAt(D)&&(m!=y.charAt(D)||u!=y.charAt(D+1));)++D;if(D+=2,h===y.charAt(D-1))return N("End of comment missing");var K=y.slice(2,D-2);return S+=2,j(K),y=y.slice(D),S+=2,A({type:f,comment:K})}}function O(){var A=C(),D=R(a);if(D){if(I(),!R(r))return N("property missing ':'");var K=R(o),Z=A({type:p,property:x(D[0].replace(e,h)),value:K?x(K[0].replace(e,h)):h});return R(l),Z}}function U(){var A=[];E(A);for(var D;D=O();)D!==!1&&(A.push(D),E(A));return A}return z(),U()}function x(y){return y?y.replace(c,h):h}return Xc=g,Xc}var Jh;function d2(){if(Jh)return sr;Jh=1;var e=sr&&sr.__importDefault||function(a){return a&&a.__esModule?a:{default:a}};Object.defineProperty(sr,"__esModule",{value:!0}),sr.default=s;const n=e(c2());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 sr}var Gr={},Yh;function u2(){if(Yh)return Gr;Yh=1,Object.defineProperty(Gr,"__esModule",{value:!0}),Gr.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 Gr.camelCase=d,Gr}var Jr,Qh;function m2(){if(Qh)return Jr;Qh=1;var e=Jr&&Jr.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(d2()),s=u2();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,Jr=a,Jr}var h2=m2();const p2=Bg(h2),Zb=ex("end"),Xu=ex("start");function ex(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 f2(e){const n=Xu(e),s=Zb(e);if(n&&s)return{start:n,end:s}}function wo(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?Xh(e.position):"start"in e||"end"in e?Xh(e):"line"in e||"column"in e?hu(e):""}function hu(e){return Zh(e&&e.line)+":"+Zh(e&&e.column)}function Xh(e){return hu(e&&e.start)+"-"+hu(e&&e.end)}function Zh(e){return e&&typeof e=="number"?e:1}class Bs 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=wo(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}}Bs.prototype.file="";Bs.prototype.name="";Bs.prototype.reason="";Bs.prototype.message="";Bs.prototype.stack="";Bs.prototype.column=void 0;Bs.prototype.line=void 0;Bs.prototype.ancestors=void 0;Bs.prototype.cause=void 0;Bs.prototype.fatal=void 0;Bs.prototype.place=void 0;Bs.prototype.ruleId=void 0;Bs.prototype.source=void 0;const Zu={}.hasOwnProperty,g2=new Map,b2=/[A-Z]/g,x2=new Set(["table","tbody","thead","tfoot","tr"]),v2=new Set(["td","th"]),tx="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function y2(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=_2(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=E2(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"?Qu:o2,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=nx(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function nx(e,n,s){if(n.type==="element")return w2(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return k2(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return N2(e,n,s);if(n.type==="mdxjsEsm")return j2(e,n);if(n.type==="root")return S2(e,n,s);if(n.type==="text")return C2(e,n)}function w2(e,n,s){const a=e.schema;let r=a;n.tagName.toLowerCase()==="svg"&&a.space==="html"&&(r=Qu,e.schema=r),e.ancestors.push(n);const o=ix(e,n.tagName,!1),l=M2(e,n);let c=tm(e,n);return x2.has(n.tagName)&&(c=c.filter(function(d){return typeof d=="string"?!QE(d):!0})),sx(e,l,o,n),em(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function k2(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)}Mo(e,n.position)}function j2(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);Mo(e,n.position)}function N2(e,n,s){const a=e.schema;let r=a;n.name==="svg"&&a.space==="html"&&(r=Qu,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:ix(e,n.name,!0),l=A2(e,n),c=tm(e,n);return sx(e,l,o,n),em(l,c),e.ancestors.pop(),e.schema=a,e.create(n,o,l,s)}function S2(e,n,s){const a={};return em(a,tm(e,n)),e.create(n,e.Fragment,a,s)}function C2(e,n){return n.value}function sx(e,n,s,a){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=a)}function em(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function E2(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 _2(e,n){return s;function s(a,r,o,l){const c=Array.isArray(o.children),d=Xu(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 M2(e,n){const s={};let a,r;for(r in n.properties)if(r!=="children"&&Zu.call(n.properties,r)){const o=R2(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&v2.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 A2(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 Mo(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 Mo(e,n.position);else o=a.value===null?!0:a.value;s[r]=o}return s}function tm(e,n){const s=[];let a=-1;const r=e.passKeys?new Map:g2;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=nx(e,o,l);c!==void 0&&s.push(c)}return s}function R2(e,n,s){const a=i2(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=a.commaSeparated?WE(s):l2(s)),a.property==="style"){let r=typeof s=="object"?s:I2(e,String(s));return e.stylePropertyNameCase==="css"&&(r=T2(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&a.space?t2[a.property]||a.property:a.attribute,s]}}function I2(e,n){try{return p2(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const a=s,r=new Bs("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=tx+"#cannot-parse-style-attribute",r}}function ix(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=qh(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=qh(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(a.type==="Literal"){const r=a.value;return Zu.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(a);Mo(e)}function Mo(e,n){const s=new Bs("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=tx+"#cannot-handle-mdx-estrees-without-createevaluater",s}function T2(e){const n={};let s;for(s in e)Zu.call(e,s)&&(n[P2(s)]=e[s]);return n}function P2(e){let n=e.replace(b2,$2);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function $2(e){return"-"+e.toLowerCase()}const Zc={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"]},D2={};function nm(e,n){const s=D2,a=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return ax(e,a,r)}function ax(e,n,s){if(L2(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 ep(e.children,n,s)}return Array.isArray(e)?ep(e,n,s):""}function ep(e,n,s){const a=[];let r=-1;for(;++r<e.length;)a[r]=ax(e[r],n,s);return a.join("")}function L2(e){return!!(e&&typeof e=="object")}const tp=document.createElement("i");function sm(e){const n="&"+e+";";tp.innerHTML=n;const s=tp.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function ii(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 ui(e,n){return e.length>0?(ii(e,e.length,0,n),e):n}const np={}.hasOwnProperty;function rx(e){const n={};let s=-1;for(;++s<e.length;)O2(n,e[s]);return n}function O2(e,n){let s;for(s in n){const r=(np.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){np.call(r,l)||(r[l]=[]);const c=o[l];F2(r[l],Array.isArray(c)?c:c?[c]:[])}}}function F2(e,n){let s=-1;const a=[];for(;++s<n.length;)(n[s].add==="after"?e:a).push(n[s]);ii(e,0,0,a)}function ox(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 yi(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const Vs=fa(/[A-Za-z]/),zs=fa(/[\dA-Za-z]/),z2=fa(/[#-'*+\--9=?A-Z^-~]/);function Jl(e){return e!==null&&(e<32||e===127)}const pu=fa(/\d/),B2=fa(/[\dA-Fa-f]/),U2=fa(/[!-/:-@[-`{-~]/);function en(e){return e!==null&&e<-2}function Un(e){return e!==null&&(e<0||e===32)}function vn(e){return e===-2||e===-1||e===32}const wc=fa(/\p{P}|\p{S}/u),za=fa(/\s/);function fa(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function Lr(e){const n=[];let s=-1,a=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&zs(e.charCodeAt(s+1))&&zs(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 Cn(e,n,s,a){const r=a?a-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(d){return vn(d)?(e.enter(s),c(d)):n(d)}function c(d){return vn(d)&&o++<r?(e.consume(d),c):(e.exit(s),n(d))}}const H2={tokenize:q2};function q2(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"),Cn(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 en(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const V2={tokenize:W2},sp={tokenize:K2};function W2(e){const n=this,s=[];let a=0,r,o,l;return c;function c(S){if(a<s.length){const j=s[a];return n.containerState=j[1],e.attempt(j[0].continuation,d,u)(S)}return u(S)}function d(S){if(a++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&v();const j=n.events.length;let C=j,w;for(;C--;)if(n.events[C][0]==="exit"&&n.events[C][1].type==="chunkFlow"){w=n.events[C][1].end;break}b(a);let N=j;for(;N<n.events.length;)n.events[N][1].end={...w},N++;return ii(n.events,C+1,0,n.events.slice(j)),n.events.length=N,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(sp,m,h)(S)}function m(S){return r&&v(),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(sp,p,g)(S)}function p(S){return a++,s.push([n.currentConstruct,n.containerState]),f(S)}function g(S){if(S===null){r&&v(),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){y(e.exit("chunkFlow"),!0),b(0),e.consume(S);return}return en(S)?(e.consume(S),y(e.exit("chunkFlow")),a=0,n.interrupt=void 0,c):(e.consume(S),x)}function y(S,j){const C=n.sliceStream(S);if(j&&C.push(null),S.previous=o,o&&(o.next=S),o=S,r.defineSkip(S.start),r.write(C),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 N=n.events.length;let R=N,z,E;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){if(z){E=n.events[R][1].end;break}z=!0}for(b(a),w=N;w<n.events.length;)n.events[w][1].end={...E},w++;ii(n.events,R+1,0,n.events.slice(N)),n.events.length=w}}function b(S){let j=s.length;for(;j-- >S;){const C=s[j];n.containerState=C[1],C[0].exit.call(n,e)}s.length=S}function v(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function K2(e,n,s){return Cn(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Nr(e){if(e===null||Un(e)||za(e))return 1;if(wc(e))return 2}function kc(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 fu={name:"attention",resolveAll:G2,tokenize:J2};function G2(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};ip(h,-d),ip(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=ui(u,[["enter",e[a][1],n],["exit",e[a][1],n]])),u=ui(u,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),u=ui(u,kc(n.parser.constructs.insideSpan.null,e.slice(a+1,s),n)),u=ui(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=ui(u,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,ii(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 J2(e,n){const s=this.parser.constructs.attentionMarkers.null,a=this.previous,r=Nr(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=Nr(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 ip(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const Y2={name:"autolink",tokenize:Q2};function Q2(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 Vs(p)?(e.consume(p),l):p===64?s(p):u(p)}function l(p){return p===43||p===45||p===46||zs(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||zs(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||Jl(p)?s(p):(e.consume(p),d)}function u(p){return p===64?(e.consume(p),m):z2(p)?(e.consume(p),u):s(p)}function m(p){return zs(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||zs(p))&&a++<63){const g=p===45?f:h;return e.consume(p),g}return s(p)}}const Go={partial:!0,tokenize:X2};function X2(e,n,s){return a;function a(o){return vn(o)?Cn(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||en(o)?n(o):s(o)}}const lx={continuation:{tokenize:e_},exit:t_,name:"blockQuote",tokenize:Z2};function Z2(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 vn(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function e_(e,n,s){const a=this;return r;function r(l){return vn(l)?Cn(e,o,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(lx,n,s)(l)}}function t_(e){e.exit("blockQuote")}const cx={name:"characterEscape",tokenize:n_};function n_(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 U2(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const dx={name:"characterReference",tokenize:s_};function s_(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=zs,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=B2,m):(e.enter("characterReferenceValue"),o=7,l=pu,m(h))}function m(h){if(h===59&&r){const f=e.exit("characterReferenceValue");return l===zs&&!sm(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 ap={partial:!0,tokenize:a_},rp={concrete:!0,name:"codeFenced",tokenize:i_};function i_(e,n,s){const a=this,r={partial:!0,tokenize:C};let o=0,l=0,c;return d;function d(w){return u(w)}function u(w){const N=a.events[a.events.length-1];return o=N&&N[1].type==="linePrefix"?N[2].sliceSerialize(N[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"),vn(w)?Cn(e,h,"whitespace")(w):h(w))}function h(w){return w===null||en(w)?(e.exit("codeFencedFence"),a.interrupt?n(w):e.check(ap,x,j)(w)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),f(w))}function f(w){return w===null||en(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(w)):vn(w)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Cn(e,p,"whitespace")(w)):w===96&&w===c?s(w):(e.consume(w),f)}function p(w){return w===null||en(w)?h(w):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),g(w))}function g(w){return w===null||en(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,j,y)(w)}function y(w){return e.enter("lineEnding"),e.consume(w),e.exit("lineEnding"),b}function b(w){return o>0&&vn(w)?Cn(e,v,"linePrefix",o+1)(w):v(w)}function v(w){return w===null||en(w)?e.check(ap,x,j)(w):(e.enter("codeFlowValue"),S(w))}function S(w){return w===null||en(w)?(e.exit("codeFlowValue"),v(w)):(e.consume(w),S)}function j(w){return e.exit("codeFenced"),n(w)}function C(w,N,R){let z=0;return E;function E(D){return w.enter("lineEnding"),w.consume(D),w.exit("lineEnding"),I}function I(D){return w.enter("codeFencedFence"),vn(D)?Cn(w,O,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(D):O(D)}function O(D){return D===c?(w.enter("codeFencedFenceSequence"),U(D)):R(D)}function U(D){return D===c?(z++,w.consume(D),U):z>=l?(w.exit("codeFencedFenceSequence"),vn(D)?Cn(w,A,"whitespace")(D):A(D)):R(D)}function A(D){return D===null||en(D)?(w.exit("codeFencedFence"),N(D)):R(D)}}}function a_(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 ed={name:"codeIndented",tokenize:o_},r_={partial:!0,tokenize:l_};function o_(e,n,s){const a=this;return r;function r(u){return e.enter("codeIndented"),Cn(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):en(u)?e.attempt(r_,l,d)(u):(e.enter("codeFlowValue"),c(u))}function c(u){return u===null||en(u)?(e.exit("codeFlowValue"),l(u)):(e.consume(u),c)}function d(u){return e.exit("codeIndented"),n(u)}}function l_(e,n,s){const a=this;return r;function r(l){return a.parser.lazy[a.now().line]?s(l):en(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Cn(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):en(l)?r(l):s(l)}}const c_={name:"codeText",previous:u_,resolve:d_,tokenize:m_};function d_(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 u_(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function m_(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)):en(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||en(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 h_{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&&Yr(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),Yr(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),Yr(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);Yr(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);Yr(this.left,s.reverse())}}}function Yr(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 ux(e){const n={};let s=-1,a,r,o,l,c,d,u;const m=new h_(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,p_(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 ii(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!u}function p_(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 y=[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,y.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):y.pop(),f=y.length;f--;){const b=c.slice(y[f],y[f+1]),v=o.pop();d.push([v,v+b.length-1]),e.splice(v,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 f_={resolve:b_,tokenize:x_},g_={partial:!0,tokenize:v_};function b_(e){return ux(e),e}function x_(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):en(c)?e.check(g_,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 v_(e,n,s){const a=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Cn(e,o,"linePrefix")}function o(l){if(l===null||en(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 mx(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||Jl(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||en(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||Un(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||Jl(b)?s(b):(e.consume(b),b===92?y:x)}function y(b){return b===40||b===41||b===92?(e.consume(b),x):x(b)}}function hx(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):en(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||en(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),d||(d=!vn(p)),p===92?f:h)}function f(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function px(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):en(f)?(e.enter("lineEnding"),e.consume(f),e.exit("lineEnding"),Cn(e,u,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(f))}function m(f){return f===l||f===null||en(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 ko(e,n){let s;return a;function a(r){return en(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,a):vn(r)?Cn(e,a,s?"linePrefix":"lineSuffix")(r):n(r)}}const y_={name:"definition",tokenize:k_},w_={partial:!0,tokenize:j_};function k_(e,n,s){const a=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return hx.call(a,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=yi(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 Un(p)?ko(e,u)(p):u(p)}function u(p){return mx(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(w_,h,h)(p)}function h(p){return vn(p)?Cn(e,f,"whitespace")(p):f(p)}function f(p){return p===null||en(p)?(e.exit("definition"),a.parser.defined.push(r),n(p)):s(p)}}function j_(e,n,s){return a;function a(c){return Un(c)?ko(e,r)(c):s(c)}function r(c){return px(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return vn(c)?Cn(e,l,"whitespace")(c):l(c)}function l(c){return c===null||en(c)?n(c):s(c)}}const N_={name:"hardBreakEscape",tokenize:S_};function S_(e,n,s){return a;function a(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return en(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const C_={name:"headingAtx",resolve:E_,tokenize:__};function E_(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"},ii(e,a,s-a+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function __(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||Un(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),d(m)):m===null||en(m)?(e.exit("atxHeading"),n(m)):vn(m)?Cn(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||Un(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),u)}}const M_=["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"],op=["pre","script","style","textarea"],A_={concrete:!0,name:"htmlFlow",resolveTo:T_,tokenize:P_},R_={partial:!0,tokenize:D_},I_={partial:!0,tokenize:$_};function T_(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 P_(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):Vs(k)?(e.consume(k),l=String.fromCharCode(k),y):s(k)}function f(k){return k===45?(e.consume(k),r=2,p):k===91?(e.consume(k),r=5,c=0,g):Vs(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 J="CDATA[";return k===J.charCodeAt(c++)?(e.consume(k),c===J.length?a.interrupt?n:O:g):s(k)}function x(k){return Vs(k)?(e.consume(k),l=String.fromCharCode(k),y):s(k)}function y(k){if(k===null||k===47||k===62||Un(k)){const J=k===47,ce=l.toLowerCase();return!J&&!o&&op.includes(ce)?(r=1,a.interrupt?n(k):O(k)):M_.includes(l.toLowerCase())?(r=6,J?(e.consume(k),b):a.interrupt?n(k):O(k)):(r=7,a.interrupt&&!a.parser.lazy[a.now().line]?s(k):o?v(k):S(k))}return k===45||zs(k)?(e.consume(k),l+=String.fromCharCode(k),y):s(k)}function b(k){return k===62?(e.consume(k),a.interrupt?n:O):s(k)}function v(k){return vn(k)?(e.consume(k),v):E(k)}function S(k){return k===47?(e.consume(k),E):k===58||k===95||Vs(k)?(e.consume(k),j):vn(k)?(e.consume(k),S):E(k)}function j(k){return k===45||k===46||k===58||k===95||zs(k)?(e.consume(k),j):C(k)}function C(k){return k===61?(e.consume(k),w):vn(k)?(e.consume(k),C):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,N):vn(k)?(e.consume(k),w):R(k)}function N(k){return k===d?(e.consume(k),d=null,z):k===null||en(k)?s(k):(e.consume(k),N)}function R(k){return k===null||k===34||k===39||k===47||k===60||k===61||k===62||k===96||Un(k)?C(k):(e.consume(k),R)}function z(k){return k===47||k===62||vn(k)?S(k):s(k)}function E(k){return k===62?(e.consume(k),I):s(k)}function I(k){return k===null||en(k)?O(k):vn(k)?(e.consume(k),I):s(k)}function O(k){return k===45&&r===2?(e.consume(k),K):k===60&&r===1?(e.consume(k),Z):k===62&&r===4?(e.consume(k),P):k===63&&r===3?(e.consume(k),M):k===93&&r===5?(e.consume(k),F):en(k)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(R_,$,U)(k)):k===null||en(k)?(e.exit("htmlFlowData"),U(k)):(e.consume(k),O)}function U(k){return e.check(I_,A,$)(k)}function A(k){return e.enter("lineEnding"),e.consume(k),e.exit("lineEnding"),D}function D(k){return k===null||en(k)?U(k):(e.enter("htmlFlowData"),O(k))}function K(k){return k===45?(e.consume(k),M):O(k)}function Z(k){return k===47?(e.consume(k),l="",ne):O(k)}function ne(k){if(k===62){const J=l.toLowerCase();return op.includes(J)?(e.consume(k),P):O(k)}return Vs(k)&&l.length<8?(e.consume(k),l+=String.fromCharCode(k),ne):O(k)}function F(k){return k===93?(e.consume(k),M):O(k)}function M(k){return k===62?(e.consume(k),P):k===45&&r===2?(e.consume(k),M):O(k)}function P(k){return k===null||en(k)?(e.exit("htmlFlowData"),$(k)):(e.consume(k),P)}function $(k){return e.exit("htmlFlow"),n(k)}}function $_(e,n,s){const a=this;return r;function r(l){return en(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 D_(e,n,s){return a;function a(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(Go,n,s)}}const L_={name:"htmlText",tokenize:O_};function O_(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),C):M===63?(e.consume(M),S):Vs(M)?(e.consume(M),R):s(M)}function u(M){return M===45?(e.consume(M),m):M===91?(e.consume(M),o=0,g):Vs(M)?(e.consume(M),v):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):en(M)?(l=h,Z(M)):(e.consume(M),h)}function f(M){return M===45?(e.consume(M),p):h(M)}function p(M){return M===62?K(M):M===45?f(M):h(M)}function g(M){const P="CDATA[";return M===P.charCodeAt(o++)?(e.consume(M),o===P.length?x:g):s(M)}function x(M){return M===null?s(M):M===93?(e.consume(M),y):en(M)?(l=x,Z(M)):(e.consume(M),x)}function y(M){return M===93?(e.consume(M),b):x(M)}function b(M){return M===62?K(M):M===93?(e.consume(M),b):x(M)}function v(M){return M===null||M===62?K(M):en(M)?(l=v,Z(M)):(e.consume(M),v)}function S(M){return M===null?s(M):M===63?(e.consume(M),j):en(M)?(l=S,Z(M)):(e.consume(M),S)}function j(M){return M===62?K(M):S(M)}function C(M){return Vs(M)?(e.consume(M),w):s(M)}function w(M){return M===45||zs(M)?(e.consume(M),w):N(M)}function N(M){return en(M)?(l=N,Z(M)):vn(M)?(e.consume(M),N):K(M)}function R(M){return M===45||zs(M)?(e.consume(M),R):M===47||M===62||Un(M)?z(M):s(M)}function z(M){return M===47?(e.consume(M),K):M===58||M===95||Vs(M)?(e.consume(M),E):en(M)?(l=z,Z(M)):vn(M)?(e.consume(M),z):K(M)}function E(M){return M===45||M===46||M===58||M===95||zs(M)?(e.consume(M),E):I(M)}function I(M){return M===61?(e.consume(M),O):en(M)?(l=I,Z(M)):vn(M)?(e.consume(M),I):z(M)}function O(M){return M===null||M===60||M===61||M===62||M===96?s(M):M===34||M===39?(e.consume(M),r=M,U):en(M)?(l=O,Z(M)):vn(M)?(e.consume(M),O):(e.consume(M),A)}function U(M){return M===r?(e.consume(M),r=void 0,D):M===null?s(M):en(M)?(l=U,Z(M)):(e.consume(M),U)}function A(M){return M===null||M===34||M===39||M===60||M===61||M===96?s(M):M===47||M===62||Un(M)?z(M):(e.consume(M),A)}function D(M){return M===47||M===62||Un(M)?z(M):s(M)}function K(M){return M===62?(e.consume(M),e.exit("htmlTextData"),e.exit("htmlText"),n):s(M)}function Z(M){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(M),e.exit("lineEnding"),ne}function ne(M){return vn(M)?Cn(e,F,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(M):F(M)}function F(M){return e.enter("htmlTextData"),l(M)}}const im={name:"labelEnd",resolveAll:U_,resolveTo:H_,tokenize:q_},F_={tokenize:V_},z_={tokenize:W_},B_={tokenize:K_};function U_(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&&ii(e,0,e.length,s),e}function H_(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=ui(c,e.slice(o+1,o+a+3)),c=ui(c,[["enter",m,n]]),c=ui(c,kc(n.parser.constructs.insideSpan.null,e.slice(o+a+4,l-3),n)),c=ui(c,[["exit",m,n],e[l-2],e[l-1],["exit",u,n]]),c=ui(c,e.slice(l+1)),c=ui(c,[["exit",d,n]]),ii(e,o,e.length,c),e}function q_(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(yi(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(F_,m,l?m:h)(f):f===91?e.attempt(z_,m,l?u:h)(f):l?m(f):h(f)}function u(f){return e.attempt(B_,m,h)(f)}function m(f){return n(f)}function h(f){return o._balanced=!0,s(f)}}function V_(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 Un(h)?ko(e,o)(h):o(h)}function o(h){return h===41?m(h):mx(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Un(h)?ko(e,d)(h):m(h)}function c(h){return s(h)}function d(h){return h===34||h===39||h===40?px(e,u,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function u(h){return Un(h)?ko(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 W_(e,n,s){const a=this;return r;function r(c){return hx.call(a,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return a.parser.defined.includes(yi(a.sliceSerialize(a.events[a.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function K_(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 G_={name:"labelStartImage",resolveAll:im.resolveAll,tokenize:J_};function J_(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 Y_={name:"labelStartLink",resolveAll:im.resolveAll,tokenize:Q_};function Q_(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 td={name:"lineEnding",tokenize:X_};function X_(e,n){return s;function s(a){return e.enter("lineEnding"),e.consume(a),e.exit("lineEnding"),Cn(e,n,"linePrefix")}}const $l={name:"thematicBreak",tokenize:Z_};function Z_(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||en(u))?(e.exit("thematicBreak"),n(u)):s(u)}function d(u){return u===r?(e.consume(u),a++,d):(e.exit("thematicBreakSequence"),vn(u)?Cn(e,c,"whitespace")(u):c(u))}}const Js={continuation:{tokenize:sM},exit:aM,name:"list",tokenize:nM},eM={partial:!0,tokenize:rM},tM={partial:!0,tokenize:iM};function nM(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:pu(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($l,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 pu(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(Go,a.interrupt?s:m,e.attempt(eM,f,h))}function m(p){return a.containerState.initialBlankLine=!0,o++,f(p)}function h(p){return vn(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 sM(e,n,s){const a=this;return a.containerState._closeFlow=void 0,e.check(Go,r,o);function r(c){return a.containerState.furtherBlankLines=a.containerState.furtherBlankLines||a.containerState.initialBlankLine,Cn(e,n,"listItemIndent",a.containerState.size+1)(c)}function o(c){return a.containerState.furtherBlankLines||!vn(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(tM,n,l)(c))}function l(c){return a.containerState._closeFlow=!0,a.interrupt=void 0,Cn(e,e.attempt(Js,n,s),"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function iM(e,n,s){const a=this;return Cn(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 aM(e){e.exit(this.containerState.type)}function rM(e,n,s){const a=this;return Cn(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!vn(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const lp={name:"setextUnderline",resolveTo:oM,tokenize:lM};function oM(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 lM(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"),vn(u)?Cn(e,d,"lineSuffix")(u):d(u))}function d(u){return u===null||en(u)?(e.exit("setextHeadingLine"),n(u)):s(u)}}const cM={tokenize:dM};function dM(e){const n=this,s=e.attempt(Go,a,e.attempt(this.parser.constructs.flowInitial,r,Cn(e,e.attempt(this.parser.constructs.flow,r,e.attempt(f_,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 uM={resolveAll:gx()},mM=fx("string"),hM=fx("text");function fx(e){return{resolveAll:gx(e==="text"?pM: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 gx(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 pM(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 fM={42:Js,43:Js,45:Js,48:Js,49:Js,50:Js,51:Js,52:Js,53:Js,54:Js,55:Js,56:Js,57:Js,62:lx},gM={91:y_},bM={[-2]:ed,[-1]:ed,32:ed},xM={35:C_,42:$l,45:[lp,$l],60:A_,61:lp,95:$l,96:rp,126:rp},vM={38:dx,92:cx},yM={[-5]:td,[-4]:td,[-3]:td,33:G_,38:dx,42:fu,60:[Y2,L_],91:Y_,92:[N_,cx],93:im,95:fu,96:c_},wM={null:[fu,uM]},kM={null:[42,95]},jM={null:[]},NM=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:kM,contentInitial:gM,disable:jM,document:fM,flow:xM,flowInitial:bM,insideSpan:wM,string:vM,text:yM},Symbol.toStringTag,{value:"Module"}));function SM(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:N(C),check:N(w),consume:v,enter:S,exit:j,interrupt:N(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(I){return l=ui(l,I),y(),l[l.length-1]!==null?[]:(R(n,0),u.events=kc(o,u.events,u),u.events)}function f(I,O){return EM(p(I),O)}function p(I){return CM(l,I)}function g(){const{_bufferIndex:I,_index:O,line:U,column:A,offset:D}=a;return{_bufferIndex:I,_index:O,line:U,column:A,offset:D}}function x(I){r[I.line]=I.column,E()}function y(){let I;for(;a._index<l.length;){const O=l[a._index];if(typeof O=="string")for(I=a._index,a._bufferIndex<0&&(a._bufferIndex=0);a._index===I&&a._bufferIndex<O.length;)b(O.charCodeAt(a._bufferIndex));else b(O)}}function b(I){m=m(I)}function v(I){en(I)?(a.line++,a.column=1,a.offset+=I===-3?2:1,E()):I!==-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=I}function S(I,O){const U=O||{};return U.type=I,U.start=g(),u.events.push(["enter",U,u]),c.push(U),U}function j(I){const O=c.pop();return O.end=g(),u.events.push(["exit",O,u]),O}function C(I,O){R(I,O.from)}function w(I,O){O.restore()}function N(I,O){return U;function U(A,D,K){let Z,ne,F,M;return Array.isArray(A)?$(A):"tokenize"in A?$([A]):P(A);function P(je){return He;function He(xe){const Ne=xe!==null&&je[xe],Y=xe!==null&&je.null,ie=[...Array.isArray(Ne)?Ne:Ne?[Ne]:[],...Array.isArray(Y)?Y:Y?[Y]:[]];return $(ie)(xe)}}function $(je){return Z=je,ne=0,je.length===0?K:k(je[ne])}function k(je){return He;function He(xe){return M=z(),F=je,je.partial||(u.currentConstruct=je),je.name&&u.parser.constructs.disable.null.includes(je.name)?ce():je.tokenize.call(O?Object.assign(Object.create(u),O):u,d,J,ce)(xe)}}function J(je){return I(F,M),D}function ce(je){return M.restore(),++ne<Z.length?k(Z[ne]):K}}}function R(I,O){I.resolveAll&&!o.includes(I)&&o.push(I),I.resolve&&ii(u.events,O,u.events.length-O,I.resolve(u.events.slice(O),u)),I.resolveTo&&(u.events=I.resolveTo(u.events,u))}function z(){const I=g(),O=u.previous,U=u.currentConstruct,A=u.events.length,D=Array.from(c);return{from:A,restore:K};function K(){a=I,u.previous=O,u.currentConstruct=U,u.events.length=A,c=D,E()}}function E(){a.line in r&&a.column<2&&(a.column=r[a.line],a.offset+=r[a.line]-1)}}function CM(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 EM(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=`
|
|
653
|
+
`;break}case-3:{l=`\r
|
|
654
|
+
`;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 _M(e){const a={constructs:rx([NM,...(e||{}).extensions||[]]),content:r(H2),defined:[],document:r(V2),flow:r(cM),lazy:{},string:r(mM),text:r(hM)};return a;function r(o){return l;function l(c){return SM(a,o,c)}}}function MM(e){for(;!ux(e););return e}const cp=/[\0\t\n\r]/g;function AM(){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(cp.lastIndex=h,u=cp.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 RM=/\\([!-/:-@[-`{-~])|&(#(?:\d{1,7}|x[\da-f]{1,6})|[\da-z]{1,31});/gi;function IM(e){return e.replace(RM,TM)}function TM(e,n,s){if(n)return n;if(s.charCodeAt(0)===35){const r=s.charCodeAt(1),o=r===120||r===88;return ox(s.slice(o?2:1),o?16:10)}return sm(s)||e}const bx={}.hasOwnProperty;function PM(e,n,s){return n&&typeof n=="object"&&(s=n,n=void 0),$M(s)(MM(_M(s).document().write(AM()(e,n,!0))))}function $M(e){const n={transforms:[],canContainEols:["emphasis","fragment","heading","paragraph","strong"],enter:{autolink:o(ve),autolinkProtocol:z,autolinkEmail:z,atxHeading:o(L),blockQuote:o(Y),characterEscape:z,characterReference:z,codeFenced:o(ie),codeFencedFenceInfo:l,codeFencedFenceMeta:l,codeIndented:o(ie,l),codeText:o(ee,l),codeTextData:z,data:z,codeFlowValue:z,definition:o(oe),definitionDestinationString:l,definitionLabelString:l,definitionTitleString:l,emphasis:o(W),hardBreakEscape:o(pe),hardBreakTrailing:o(pe),htmlFlow:o(fe,l),htmlFlowData:z,htmlText:o(fe,l),htmlTextData:z,image:o(B),label:l,link:o(ve),listItem:o(ae),listItemValue:f,listOrdered:o(Fe,h),listUnordered:o(Fe),paragraph:o(qe),reference:k,referenceString:l,resourceDestinationString:l,resourceTitleString:l,setextHeading:o(L),strong:o(Pe),thematicBreak:o(Be)},exit:{atxHeading:d(),atxHeadingSequence:C,autolink:d(),autolinkEmail:Ne,autolinkProtocol:xe,blockQuote:d(),characterEscapeValue:E,characterReferenceMarkerHexadecimal:ce,characterReferenceMarkerNumeric:ce,characterReferenceValue:je,characterReference:He,codeFenced:d(y),codeFencedFence:x,codeFencedFenceInfo:p,codeFencedFenceMeta:g,codeFlowValue:E,codeIndented:d(b),codeText:d(D),codeTextData:E,data:E,definition:d(),definitionDestinationString:j,definitionLabelString:v,definitionTitleString:S,emphasis:d(),hardBreakEscape:d(O),hardBreakTrailing:d(O),htmlFlow:d(U),htmlFlowData:E,htmlText:d(A),htmlTextData:E,image:d(Z),label:F,labelText:ne,lineEnding:I,link:d(K),listItem:d(),listOrdered:d(),listUnordered:d(),paragraph:d(),referenceString:J,resourceDestinationString:M,resourceTitleString:P,resource:$,setextHeading:d(R),setextHeadingLineSequence:N,setextHeadingText:w,strong:d(),thematicBreak:d()}};xx(n,(e||{}).mdastExtensions||[]);const s={};return a;function a(de){let Ie={type:"root",children:[]};const $e={stack:[Ie],tokenStack:[],config:n,enter:c,exit:u,buffer:l,resume:m,data:s},st=[];let Ue=-1;for(;++Ue<de.length;)if(de[Ue][1].type==="listOrdered"||de[Ue][1].type==="listUnordered")if(de[Ue][0]==="enter")st.push(Ue);else{const me=st.pop();Ue=r(de,me,Ue)}for(Ue=-1;++Ue<de.length;){const me=n[de[Ue][0]];bx.call(me,de[Ue][1].type)&&me[de[Ue][1].type].call(Object.assign({sliceSerialize:de[Ue][2].sliceSerialize},$e),de[Ue][1])}if($e.tokenStack.length>0){const me=$e.tokenStack[$e.tokenStack.length-1];(me[1]||dp).call($e,void 0,me[0])}for(Ie.position={start:sa(de.length>0?de[0][1].start:{line:1,column:1,offset:0}),end:sa(de.length>0?de[de.length-2][1].end:{line:1,column:1,offset:0})},Ue=-1;++Ue<n.transforms.length;)Ie=n.transforms[Ue](Ie)||Ie;return Ie}function r(de,Ie,$e){let st=Ie-1,Ue=-1,me=!1,re,_e,xt,dt;for(;++st<=$e;){const Qe=de[st];switch(Qe[1].type){case"listUnordered":case"listOrdered":case"blockQuote":{Qe[0]==="enter"?Ue++:Ue--,dt=void 0;break}case"lineEndingBlank":{Qe[0]==="enter"&&(re&&!dt&&!Ue&&!xt&&(xt=st),dt=void 0);break}case"linePrefix":case"listItemValue":case"listItemMarker":case"listItemPrefix":case"listItemPrefixWhitespace":break;default:dt=void 0}if(!Ue&&Qe[0]==="enter"&&Qe[1].type==="listItemPrefix"||Ue===-1&&Qe[0]==="exit"&&(Qe[1].type==="listUnordered"||Qe[1].type==="listOrdered")){if(re){let vt=st;for(_e=void 0;vt--;){const Ae=de[vt];if(Ae[1].type==="lineEnding"||Ae[1].type==="lineEndingBlank"){if(Ae[0]==="exit")continue;_e&&(de[_e][1].type="lineEndingBlank",me=!0),Ae[1].type="lineEnding",_e=vt}else if(!(Ae[1].type==="linePrefix"||Ae[1].type==="blockQuotePrefix"||Ae[1].type==="blockQuotePrefixWhitespace"||Ae[1].type==="blockQuoteMarker"||Ae[1].type==="listItemIndent"))break}xt&&(!_e||xt<_e)&&(re._spread=!0),re.end=Object.assign({},_e?de[_e][1].start:Qe[1].end),de.splice(_e||st,0,["exit",re,Qe[2]]),st++,$e++}if(Qe[1].type==="listItemPrefix"){const vt={type:"listItem",_spread:!1,start:Object.assign({},Qe[1].start),end:void 0};re=vt,de.splice(st,0,["enter",vt,Qe[2]]),st++,$e++,xt=void 0,dt=!0}}}return de[Ie][1]._spread=me,$e}function o(de,Ie){return $e;function $e(st){c.call(this,de(st),st),Ie&&Ie.call(this,st)}}function l(){this.stack.push({type:"fragment",children:[]})}function c(de,Ie,$e){this.stack[this.stack.length-1].children.push(de),this.stack.push(de),this.tokenStack.push([Ie,$e||void 0]),de.position={start:sa(Ie.start),end:void 0}}function d(de){return Ie;function Ie($e){de&&de.call(this,$e),u.call(this,$e)}}function u(de,Ie){const $e=this.stack.pop(),st=this.tokenStack.pop();if(st)st[0].type!==de.type&&(Ie?Ie.call(this,de,st[0]):(st[1]||dp).call(this,de,st[0]));else throw new Error("Cannot close `"+de.type+"` ("+wo({start:de.start,end:de.end})+"): it’s not open");$e.position.end=sa(de.end)}function m(){return nm(this.stack.pop())}function h(){this.data.expectingFirstListItemValue=!0}function f(de){if(this.data.expectingFirstListItemValue){const Ie=this.stack[this.stack.length-2];Ie.start=Number.parseInt(this.sliceSerialize(de),10),this.data.expectingFirstListItemValue=void 0}}function p(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.lang=de}function g(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.meta=de}function x(){this.data.flowCodeInside||(this.buffer(),this.data.flowCodeInside=!0)}function y(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de.replace(/^(\r?\n|\r)|(\r?\n|\r)$/g,""),this.data.flowCodeInside=void 0}function b(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de.replace(/(\r?\n|\r)$/g,"")}function v(de){const Ie=this.resume(),$e=this.stack[this.stack.length-1];$e.label=Ie,$e.identifier=yi(this.sliceSerialize(de)).toLowerCase()}function S(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.title=de}function j(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.url=de}function C(de){const Ie=this.stack[this.stack.length-1];if(!Ie.depth){const $e=this.sliceSerialize(de).length;Ie.depth=$e}}function w(){this.data.setextHeadingSlurpLineEnding=!0}function N(de){const Ie=this.stack[this.stack.length-1];Ie.depth=this.sliceSerialize(de).codePointAt(0)===61?1:2}function R(){this.data.setextHeadingSlurpLineEnding=void 0}function z(de){const $e=this.stack[this.stack.length-1].children;let st=$e[$e.length-1];(!st||st.type!=="text")&&(st=nt(),st.position={start:sa(de.start),end:void 0},$e.push(st)),this.stack.push(st)}function E(de){const Ie=this.stack.pop();Ie.value+=this.sliceSerialize(de),Ie.position.end=sa(de.end)}function I(de){const Ie=this.stack[this.stack.length-1];if(this.data.atHardBreak){const $e=Ie.children[Ie.children.length-1];$e.position.end=sa(de.end),this.data.atHardBreak=void 0;return}!this.data.setextHeadingSlurpLineEnding&&n.canContainEols.includes(Ie.type)&&(z.call(this,de),E.call(this,de))}function O(){this.data.atHardBreak=!0}function U(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de}function A(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de}function D(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.value=de}function K(){const de=this.stack[this.stack.length-1];if(this.data.inReference){const Ie=this.data.referenceType||"shortcut";de.type+="Reference",de.referenceType=Ie,delete de.url,delete de.title}else delete de.identifier,delete de.label;this.data.referenceType=void 0}function Z(){const de=this.stack[this.stack.length-1];if(this.data.inReference){const Ie=this.data.referenceType||"shortcut";de.type+="Reference",de.referenceType=Ie,delete de.url,delete de.title}else delete de.identifier,delete de.label;this.data.referenceType=void 0}function ne(de){const Ie=this.sliceSerialize(de),$e=this.stack[this.stack.length-2];$e.label=IM(Ie),$e.identifier=yi(Ie).toLowerCase()}function F(){const de=this.stack[this.stack.length-1],Ie=this.resume(),$e=this.stack[this.stack.length-1];if(this.data.inReference=!0,$e.type==="link"){const st=de.children;$e.children=st}else $e.alt=Ie}function M(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.url=de}function P(){const de=this.resume(),Ie=this.stack[this.stack.length-1];Ie.title=de}function $(){this.data.inReference=void 0}function k(){this.data.referenceType="collapsed"}function J(de){const Ie=this.resume(),$e=this.stack[this.stack.length-1];$e.label=Ie,$e.identifier=yi(this.sliceSerialize(de)).toLowerCase(),this.data.referenceType="full"}function ce(de){this.data.characterReferenceType=de.type}function je(de){const Ie=this.sliceSerialize(de),$e=this.data.characterReferenceType;let st;$e?(st=ox(Ie,$e==="characterReferenceMarkerNumeric"?10:16),this.data.characterReferenceType=void 0):st=sm(Ie);const Ue=this.stack[this.stack.length-1];Ue.value+=st}function He(de){const Ie=this.stack.pop();Ie.position.end=sa(de.end)}function xe(de){E.call(this,de);const Ie=this.stack[this.stack.length-1];Ie.url=this.sliceSerialize(de)}function Ne(de){E.call(this,de);const Ie=this.stack[this.stack.length-1];Ie.url="mailto:"+this.sliceSerialize(de)}function Y(){return{type:"blockquote",children:[]}}function ie(){return{type:"code",lang:null,meta:null,value:""}}function ee(){return{type:"inlineCode",value:""}}function oe(){return{type:"definition",identifier:"",label:null,title:null,url:""}}function W(){return{type:"emphasis",children:[]}}function L(){return{type:"heading",depth:0,children:[]}}function pe(){return{type:"break"}}function fe(){return{type:"html",value:""}}function B(){return{type:"image",title:null,url:"",alt:null}}function ve(){return{type:"link",title:null,url:"",children:[]}}function Fe(de){return{type:"list",ordered:de.type==="listOrdered",start:null,spread:de._spread,children:[]}}function ae(de){return{type:"listItem",spread:de._spread,checked:null,children:[]}}function qe(){return{type:"paragraph",children:[]}}function Pe(){return{type:"strong",children:[]}}function nt(){return{type:"text",value:""}}function Be(){return{type:"thematicBreak"}}}function sa(e){return{line:e.line,column:e.column,offset:e.offset}}function xx(e,n){let s=-1;for(;++s<n.length;){const a=n[s];Array.isArray(a)?xx(e,a):DM(e,a)}}function DM(e,n){let s;for(s in n)if(bx.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 dp(e,n){throw e?new Error("Cannot close `"+e.type+"` ("+wo({start:e.start,end:e.end})+"): a different token (`"+n.type+"`, "+wo({start:n.start,end:n.end})+") is open"):new Error("Cannot close document, a token (`"+n.type+"`, "+wo({start:n.start,end:n.end})+") is still open")}function LM(e){const n=this;n.parser=s;function s(a){return PM(a,{...n.data("settings"),...e,extensions:n.data("micromarkExtensions")||[],mdastExtensions:n.data("fromMarkdownExtensions")||[]})}}function OM(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 FM(e,n){const s={type:"element",tagName:"br",properties:{},children:[]};return e.patch(n,s),[e.applyData(n,s),{type:"text",value:`
|
|
655
|
+
`}]}function zM(e,n){const s=n.value?n.value+`
|
|
656
|
+
`:"",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 BM(e,n){const s={type:"element",tagName:"del",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function UM(e,n){const s={type:"element",tagName:"em",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function HM(e,n){const s=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",a=String(n.identifier).toUpperCase(),r=Lr(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 qM(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 VM(e,n){if(e.options.allowDangerousHtml){const s={type:"raw",value:n.value};return e.patch(n,s),e.applyData(n,s)}}function vx(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 WM(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return vx(e,n);const r={src:Lr(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 KM(e,n){const s={src:Lr(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 GM(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 JM(e,n){const s=String(n.identifier).toUpperCase(),a=e.definitionById.get(s);if(!a)return vx(e,n);const r={href:Lr(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 YM(e,n){const s={href:Lr(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 QM(e,n,s){const a=e.all(n),r=s?XM(s):yx(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:`
|
|
657
|
+
`}),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:`
|
|
658
|
+
`});const u={type:"element",tagName:"li",properties:o,children:l};return e.patch(n,u),e.applyData(n,u)}function XM(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=yx(s[a])}return n}function yx(e){const n=e.spread;return n??e.children.length>1}function ZM(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 eA(e,n){const s={type:"element",tagName:"p",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function tA(e,n){const s={type:"root",children:e.wrap(e.all(n))};return e.patch(n,s),e.applyData(n,s)}function nA(e,n){const s={type:"element",tagName:"strong",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}function sA(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=Xu(n.children[1]),d=Zb(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 iA(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 aA(e,n){const s={type:"element",tagName:"td",properties:{},children:e.all(n)};return e.patch(n,s),e.applyData(n,s)}const up=9,mp=32;function rA(e){const n=String(e),s=/\r?\n|\r/g;let a=s.exec(n),r=0;const o=[];for(;a;)o.push(hp(n.slice(r,a.index),r>0,!0),a[0]),r=a.index+a[0].length,a=s.exec(n);return o.push(hp(n.slice(r),r>0,!1)),o.join("")}function hp(e,n,s){let a=0,r=e.length;if(n){let o=e.codePointAt(a);for(;o===up||o===mp;)a++,o=e.codePointAt(a)}if(s){let o=e.codePointAt(r-1);for(;o===up||o===mp;)r--,o=e.codePointAt(r-1)}return r>a?e.slice(a,r):""}function oA(e,n){const s={type:"text",value:rA(String(n.value))};return e.patch(n,s),e.applyData(n,s)}function lA(e,n){const s={type:"element",tagName:"hr",properties:{},children:[]};return e.patch(n,s),e.applyData(n,s)}const cA={blockquote:OM,break:FM,code:zM,delete:BM,emphasis:UM,footnoteReference:HM,heading:qM,html:VM,imageReference:WM,image:KM,inlineCode:GM,linkReference:JM,link:YM,listItem:QM,list:ZM,paragraph:eA,root:tA,strong:nA,table:sA,tableCell:aA,tableRow:iA,text:oA,thematicBreak:lA,toml:rl,yaml:rl,definition:rl,footnoteDefinition:rl};function rl(){}const wx=-1,jc=0,jo=1,Yl=2,am=3,rm=4,om=5,lm=6,kx=7,jx=8,pp=typeof self=="object"?self:globalThis,dA=(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 jc:case wx:return s(l,r);case jo:{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 am:return s(new Date(l),r);case rm:{const{source:c,flags:d}=l;return s(new RegExp(c,d),r)}case om:{const c=s(new Map,r);for(const[d,u]of l)c.set(a(d),a(u));return c}case lm:{const c=s(new Set,r);for(const d of l)c.add(a(d));return c}case kx:{const{name:c,message:d}=l;return s(new pp[c](d),r)}case jx: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 pp[o](l),r)};return a},fp=e=>dA(new Map,e)(0),ir="",{toString:uA}={},{keys:mA}=Object,Qr=e=>{const n=typeof e;if(n!=="object"||!e)return[jc,n];const s=uA.call(e).slice(8,-1);switch(s){case"Array":return[jo,ir];case"Object":return[Yl,ir];case"Date":return[am,ir];case"RegExp":return[rm,ir];case"Map":return[om,ir];case"Set":return[lm,ir];case"DataView":return[jo,s]}return s.includes("Array")?[jo,s]:s.includes("Error")?[kx,s]:[Yl,s]},ol=([e,n])=>e===jc&&(n==="function"||n==="symbol"),hA=(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]=Qr(l);switch(c){case jc:{let m=l;switch(d){case"bigint":c=jx,m=l.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+d);m=null;break;case"undefined":return r([wx],l)}return r([c,m],l)}case jo:{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 mA(l))(e||!ol(Qr(l[f])))&&m.push([o(f),o(l[f])]);return h}case am:return r([c,l.toISOString()],l);case rm:{const{source:m,flags:h}=l;return r([c,{source:m,flags:h}],l)}case om:{const m=[],h=r([c,m],l);for(const[f,p]of l)(e||!(ol(Qr(f))||ol(Qr(p))))&&m.push([o(f),o(p)]);return h}case lm:{const m=[],h=r([c,m],l);for(const f of l)(e||!ol(Qr(f)))&&m.push(o(f));return h}}const{message:u}=l;return r([c,{name:d,message:u}],l)};return o},gp=(e,{json:n,lossy:s}={})=>{const a=[];return hA(!(n||s),!!n,new Map,a)(e),a},Ql=typeof structuredClone=="function"?(e,n)=>n&&("json"in n||"lossy"in n)?fp(gp(e,n)):structuredClone(e):(e,n)=>fp(gp(e,n));function pA(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 fA(e,n){return"Back to reference "+(e+1)+(n>1?"-"+n:"")}function gA(e){const n=typeof e.options.clobberPrefix=="string"?e.options.clobberPrefix:"user-content-",s=e.options.footnoteBackContent||pA,a=e.options.footnoteBackLabel||fA,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=Lr(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 v=typeof s=="string"?s:s(d,p);typeof v=="string"&&(v={type:"text",value:v}),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(v)?v:[v]})}const y=m[m.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const v=y.children[y.children.length-1];v&&v.type==="text"?v.value+=" ":y.children.push({type:"text",value:" "}),y.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:{...Ql(l),id:"footnote-label"},children:[{type:"text",value:r}]},{type:"text",value:`
|
|
659
|
+
`},{type:"element",tagName:"ol",properties:{},children:e.wrap(c,!0)},{type:"text",value:`
|
|
660
|
+
`}]}}const Nc=(function(e){if(e==null)return yA;if(typeof e=="function")return Sc(e);if(typeof e=="object")return Array.isArray(e)?bA(e):xA(e);if(typeof e=="string")return vA(e);throw new Error("Expected function, string, or object as test")});function bA(e){const n=[];let s=-1;for(;++s<e.length;)n[s]=Nc(e[s]);return Sc(a);function a(...r){let o=-1;for(;++o<n.length;)if(n[o].apply(this,r))return!0;return!1}}function xA(e){const n=e;return Sc(s);function s(a){const r=a;let o;for(o in e)if(r[o]!==n[o])return!1;return!0}}function vA(e){return Sc(n);function n(s){return s&&s.type===e}}function Sc(e){return n;function n(s,a,r){return!!(wA(s)&&e.call(this,s,typeof a=="number"?a:void 0,r||void 0))}}function yA(){return!0}function wA(e){return e!==null&&typeof e=="object"&&"type"in e}const Nx=[],kA=!0,gu=!1,jA="skip";function Sx(e,n,s,a){let r;typeof n=="function"&&typeof s!="function"?(a=s,s=n):r=n;const o=Nc(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=Nx,g,x,y;if((!n||o(d,u,m[m.length-1]||void 0))&&(p=NA(s(d,m)),p[0]===gu))return p;if("children"in d&&d.children){const b=d;if(b.children&&p[0]!==jA)for(x=(a?b.children.length:-1)+l,y=m.concat(b);x>-1&&x<b.children.length;){const v=b.children[x];if(g=c(v,x,y)(),g[0]===gu)return g;x=typeof g[1]=="number"?g[1]:x+l}}return p}}}function NA(e){return Array.isArray(e)?e:typeof e=="number"?[kA,e]:e==null?Nx:[e]}function cm(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),Sx(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 bu={}.hasOwnProperty,SA={};function CA(e,n){const s=n||SA,a=new Map,r=new Map,o=new Map,l={...cA,...s.handlers},c={all:u,applyData:_A,definitionById:a,footnoteById:r,footnoteCounts:o,footnoteOrder:[],handlers:l,one:d,options:s,patch:EA,wrap:AA};return cm(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(bu.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,...y}=m,b=Ql(y);return b.children=c.all(m),b}return Ql(m)}return(c.options.unknownHandler||MA)(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=bp(g.value)),!Array.isArray(g)&&g.type==="element")){const x=g.children[0];x&&x.type==="text"&&(x.value=bp(x.value))}Array.isArray(g)?h.push(...g):h.push(g)}}}return h}}function EA(e,n){e.position&&(n.position=f2(e))}function _A(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,Ql(o)),"children"in s&&s.children&&r!==null&&r!==void 0&&(s.children=r)}return s}function MA(e,n){const s=n.data||{},a="value"in n&&!(bu.call(s,"hProperties")||bu.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 AA(e,n){const s=[];let a=-1;for(n&&s.push({type:"text",value:`
|
|
661
|
+
`});++a<e.length;)a&&s.push({type:"text",value:`
|
|
662
|
+
`}),s.push(e[a]);return n&&e.length>0&&s.push({type:"text",value:`
|
|
663
|
+
`}),s}function bp(e){let n=0,s=e.charCodeAt(n);for(;s===9||s===32;)n++,s=e.charCodeAt(n);return e.slice(n)}function xp(e,n){const s=CA(e,n),a=s.one(e,void 0),r=gA(s),o=Array.isArray(a)?{type:"root",children:a}:a||{type:"root",children:[]};return r&&o.children.push({type:"text",value:`
|
|
664
|
+
`},r),o}function RA(e,n){return e&&"run"in e?async function(s,a){const r=xp(s,{file:a,...n});await e.run(r,a)}:function(s,a){return xp(s,{file:a,...e||n})}}function vp(e){if(e)throw e}var nd,yp;function IA(){if(yp)return nd;yp=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 nd=function d(){var u,m,h,f,p,g,x=arguments[0],y=1,b=arguments.length,v=!1;for(typeof x=="boolean"&&(v=x,x=arguments[1]||{},y=2),(x==null||typeof x!="object"&&typeof x!="function")&&(x={});y<b;++y)if(u=arguments[y],u!=null)for(m in u)h=c(x,m),f=c(u,m),x!==f&&(v&&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(v,g,f)})):typeof f<"u"&&l(x,{name:m,newValue:f}));return x},nd}var TA=IA();const sd=Bg(TA);function xu(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 PA(){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?$A(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 $A(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 Ri={basename:DA,dirname:LA,extname:OA,join:FA,sep:"/"};function DA(e,n){if(n!==void 0&&typeof n!="string")throw new TypeError('"ext" argument must be a string');Jo(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 LA(e){if(Jo(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 OA(e){Jo(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 FA(...e){let n=-1,s;for(;++n<e.length;)Jo(e[n]),e[n]&&(s=s===void 0?e[n]:s+"/"+e[n]);return s===void 0?".":zA(s)}function zA(e){Jo(e);const n=e.codePointAt(0)===47;let s=BA(e,!n);return s.length===0&&!n&&(s="."),s.length>0&&e.codePointAt(e.length-1)===47&&(s+="/"),n?"/"+s:s}function BA(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 Jo(e){if(typeof e!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(e))}const UA={cwd:HA};function HA(){return"/"}function vu(e){return!!(e!==null&&typeof e=="object"&&"href"in e&&e.href&&"protocol"in e&&e.protocol&&e.auth===void 0)}function qA(e){if(typeof e=="string")e=new URL(e);else if(!vu(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 VA(e)}function VA(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 id=["history","path","basename","stem","extname","dirname"];class Cx{constructor(n){let s;n?vu(n)?s={path:n}:typeof n=="string"||WA(n)?s={value:n}:s=n:s={},this.cwd="cwd"in s?"":UA.cwd(),this.data={},this.history=[],this.messages=[],this.value,this.map,this.result,this.stored;let a=-1;for(;++a<id.length;){const o=id[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)id.includes(r)||(this[r]=s[r])}get basename(){return typeof this.path=="string"?Ri.basename(this.path):void 0}set basename(n){rd(n,"basename"),ad(n,"basename"),this.path=Ri.join(this.dirname||"",n)}get dirname(){return typeof this.path=="string"?Ri.dirname(this.path):void 0}set dirname(n){wp(this.basename,"dirname"),this.path=Ri.join(n||"",this.basename)}get extname(){return typeof this.path=="string"?Ri.extname(this.path):void 0}set extname(n){if(ad(n,"extname"),wp(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=Ri.join(this.dirname,this.stem+(n||""))}get path(){return this.history[this.history.length-1]}set path(n){vu(n)&&(n=qA(n)),rd(n,"path"),this.path!==n&&this.history.push(n)}get stem(){return typeof this.path=="string"?Ri.basename(this.path,this.extname):void 0}set stem(n){rd(n,"stem"),ad(n,"stem"),this.path=Ri.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 Bs(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 ad(e,n){if(e&&e.includes(Ri.sep))throw new Error("`"+n+"` cannot be a path: did not expect `"+Ri.sep+"`")}function rd(e,n){if(!e)throw new Error("`"+n+"` cannot be empty")}function wp(e,n){if(!e)throw new Error("Setting `"+n+"` requires `path` to be set too")}function WA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const KA=(function(e){const a=this.constructor.prototype,r=a[e],o=function(){return r.apply(o,arguments)};return Object.setPrototypeOf(o,a),o}),GA={}.hasOwnProperty;class dm extends KA{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=PA()}copy(){const n=new dm;let s=-1;for(;++s<this.attachers.length;){const a=this.attachers[s];n.use(...a)}return n.data(sd(!0,{},this.namespace)),n}data(n,s){return typeof n=="string"?arguments.length===2?(cd("data",this.frozen),this.namespace[n]=s,this):GA.call(this.namespace,n)&&this.namespace[n]||void 0:n?(cd("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=ll(n),a=this.parser||this.Parser;return od("parse",a),a(String(s),s)}process(n,s){const a=this;return this.freeze(),od("process",this.parser||this.Parser),ld("process",this.compiler||this.Compiler),s?r(void 0,s):new Promise(r);function r(o,l){const c=ll(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);QA(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(),od("processSync",this.parser||this.Parser),ld("processSync",this.compiler||this.Compiler),this.process(n,r),jp("processSync","process",s),a;function r(o,l){s=!0,vp(o),a=l}}run(n,s,a){kp(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=ll(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),jp("runSync","run",a),r;function o(l,c){vp(l),r=c,a=!0}}stringify(n,s){this.freeze();const a=ll(s),r=this.compiler||this.Compiler;return ld("stringify",r),kp(n),r(n,a)}use(n,...s){const a=this.attachers,r=this.namespace;if(cd("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=sd(!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];xu(x)&&xu(p)&&(p=sd(!0,x,p)),a[f]=[u,p,...g]}}}}const JA=new dm().freeze();function od(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `parser`")}function ld(e,n){if(typeof n!="function")throw new TypeError("Cannot `"+e+"` without `compiler`")}function cd(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 kp(e){if(!xu(e)||typeof e.type!="string")throw new TypeError("Expected node, got `"+e+"`")}function jp(e,n,s){if(!s)throw new Error("`"+e+"` finished async. Use `"+n+"` instead")}function ll(e){return YA(e)?e:new Cx(e)}function YA(e){return!!(e&&typeof e=="object"&&"message"in e&&"messages"in e)}function QA(e){return typeof e=="string"||XA(e)}function XA(e){return!!(e&&typeof e=="object"&&"byteLength"in e&&"byteOffset"in e)}const ZA="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",Np=[],Sp={allowDangerousHtml:!0},eR=/^(https?|ircs?|mailto|xmpp)$/i,tR=[{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 ki(e){const n=nR(e),s=sR(e);return iR(n.runSync(n.parse(s),s),e)}function nR(e){const n=e.rehypePlugins||Np,s=e.remarkPlugins||Np,a=e.remarkRehypeOptions?{...e.remarkRehypeOptions,...Sp}:Sp;return JA().use(LM).use(s).use(RA,a).use(n)}function sR(e){const n=e.children||"",s=new Cx;return typeof n=="string"&&(s.value=n),s}function iR(e,n){const s=n.allowedElements,a=n.allowElement,r=n.components,o=n.disallowedElements,l=n.skipHtml,c=n.unwrapDisallowed,d=n.urlTransform||aR;for(const m of tR)Object.hasOwn(n,m.from)&&(""+m.from+(m.to?"use `"+m.to+"` instead":"remove it")+ZA+m.id,void 0);return cm(e,u),y2(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 Zc)if(Object.hasOwn(Zc,p)&&Object.hasOwn(m.properties,p)){const g=m.properties[p],x=Zc[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 aR(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||eR.test(e.slice(0,n))?e:""}function Cp(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 rR(e){if(typeof e!="string")throw new TypeError("Expected a string");return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&").replace(/-/g,"\\x2d")}function oR(e,n,s){const r=Nc((s||{}).ignore||[]),o=lR(n);let l=-1;for(;++l<o.length;)Sx(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 y=h.children.indexOf(u);let b=!1,v=[];f.lastIndex=0;let S=f.exec(u.value);for(;S;){const j=S.index,C={index:S.index,input:S.input,stack:[...m,u]};let w=p(...S,C);if(typeof w=="string"&&(w=w.length>0?{type:"text",value:w}:void 0),w===!1?f.lastIndex=j+1:(g!==j&&v.push({type:"text",value:u.value.slice(g,j)}),Array.isArray(w)?v.push(...w):w&&v.push(w),g=j+S[0].length,b=!0),!f.global)break;S=f.exec(u.value)}return b?(g<u.value.length&&v.push({type:"text",value:u.value.slice(g)}),h.children.splice(y,1,...v)):v=[u],y+v.length}}function lR(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([cR(r[0]),dR(r[1])])}return n}function cR(e){return typeof e=="string"?new RegExp(rR(e),"g"):e}function dR(e){return typeof e=="function"?e:function(){return e}}const dd="phrasing",ud=["autolink","link","image","label"];function uR(){return{transforms:[xR],enter:{literalAutolink:hR,literalAutolinkEmail:md,literalAutolinkHttp:md,literalAutolinkWww:md},exit:{literalAutolink:bR,literalAutolinkEmail:gR,literalAutolinkHttp:pR,literalAutolinkWww:fR}}}function mR(){return{unsafe:[{character:"@",before:"[+\\-.\\w]",after:"[\\-.\\w]",inConstruct:dd,notInConstruct:ud},{character:".",before:"[Ww]",after:"[\\-.\\w]",inConstruct:dd,notInConstruct:ud},{character:":",before:"[ps]",after:"\\/",inConstruct:dd,notInConstruct:ud}]}}function hR(e){this.enter({type:"link",title:null,url:"",children:[]},e)}function md(e){this.config.enter.autolinkProtocol.call(this,e)}function pR(e){this.config.exit.autolinkProtocol.call(this,e)}function fR(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 gR(e){this.config.exit.autolinkEmail.call(this,e)}function bR(e){this.exit(e)}function xR(e){oR(e,[[/(https?:\/\/|www(?=\.))([-.\w]+)([^ \t\r\n]*)/gi,vR],[/(?<=^|\s|\p{P}|\p{S})([-.\w+]+)@([-\w]+(?:\.[-\w]+)+)/gu,yR]],{ignore:["link","linkReference"]})}function vR(e,n,s,a,r){let o="";if(!Ex(r)||(/^w/i.test(n)&&(s=n+s,n="",o="http://"),!wR(s)))return!1;const l=kR(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 yR(e,n,s,a){return!Ex(a,!0)||/[-\d_]$/.test(s)?!1:{type:"link",title:null,url:"mailto:"+n+"@"+s,children:[{type:"text",value:n+"@"+s}]}}function wR(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 kR(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=Cp(e,"(");let o=Cp(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 Ex(e,n){const s=e.input.charCodeAt(e.index-1);return(e.index===0||za(s)||wc(s))&&(!n||s!==47)}_x.peek=RR;function jR(){this.buffer()}function NR(e){this.enter({type:"footnoteReference",identifier:"",label:""},e)}function SR(){this.buffer()}function CR(e){this.enter({type:"footnoteDefinition",identifier:"",label:"",children:[]},e)}function ER(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=yi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function _R(e){this.exit(e)}function MR(e){const n=this.resume(),s=this.stack[this.stack.length-1];s.type,s.identifier=yi(this.sliceSerialize(e)).toLowerCase(),s.label=n}function AR(e){this.exit(e)}function RR(){return"["}function _x(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 IR(){return{enter:{gfmFootnoteCallString:jR,gfmFootnoteCall:NR,gfmFootnoteDefinitionLabelString:SR,gfmFootnoteDefinition:CR},exit:{gfmFootnoteCallString:ER,gfmFootnoteCall:_R,gfmFootnoteDefinitionLabelString:MR,gfmFootnoteDefinition:AR}}}function TR(e){let n=!1;return e&&e.firstLineBlank&&(n=!0),{handlers:{footnoteDefinition:s,footnoteReference:_x},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?`
|
|
665
|
+
`:" ")+o.indentLines(o.containerFlow(a,c.current()),n?Mx:PR))),u(),d}}function PR(e,n,s){return n===0?e:Mx(e,n,s)}function Mx(e,n,s){return(s?"":" ")+e}const $R=["autolink","destinationLiteral","destinationRaw","reference","titleQuote","titleApostrophe"];Ax.peek=zR;function DR(){return{canContainEols:["delete"],enter:{strikethrough:OR},exit:{strikethrough:FR}}}function LR(){return{unsafe:[{character:"~",inConstruct:"phrasing",notInConstruct:$R}],handlers:{delete:Ax}}}function OR(e){this.enter({type:"delete",children:[]},e)}function FR(e){this.exit(e)}function Ax(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 zR(){return"~"}function BR(e){return e.length}function UR(e,n){const s=n||{},a=(s.align||[]).concat(),r=s.stringLength||BR,o=[],l=[],c=[],d=[];let u=0,m=-1;for(;++m<e.length;){const x=[],y=[];let b=-1;for(e[m].length>u&&(u=e[m].length);++b<e[m].length;){const v=HR(e[m][b]);if(s.alignDelimiters!==!1){const S=r(v);y[b]=S,(d[b]===void 0||S>d[b])&&(d[b]=S)}x.push(v)}l[m]=x,c[m]=y}let h=-1;if(typeof a=="object"&&"length"in a)for(;++h<u;)o[h]=Ep(a[h]);else{const x=Ep(a);for(;++h<u;)o[h]=x}h=-1;const f=[],p=[];for(;++h<u;){const x=o[h];let y="",b="";x===99?(y=":",b=":"):x===108?y=":":x===114&&(b=":");let v=s.alignDelimiters===!1?1:Math.max(1,d[h]-y.length-b.length);const S=y+"-".repeat(v)+b;s.alignDelimiters!==!1&&(v=y.length+v+b.length,v>d[h]&&(d[h]=v),p[h]=v),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],y=c[m];h=-1;const b=[];for(;++h<u;){const v=x[h]||"";let S="",j="";if(s.alignDelimiters!==!1){const C=d[h]-(y[h]||0),w=o[h];w===114?S=" ".repeat(C):w===99?C%2?(S=" ".repeat(C/2+.5),j=" ".repeat(C/2-.5)):(S=" ".repeat(C/2),j=S):j=" ".repeat(C)}s.delimiterStart!==!1&&!h&&b.push("|"),s.padding!==!1&&!(s.alignDelimiters===!1&&v==="")&&(s.delimiterStart!==!1||h)&&b.push(" "),s.alignDelimiters!==!1&&b.push(S),b.push(v),s.alignDelimiters!==!1&&b.push(j),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(`
|
|
666
|
+
`)}function HR(e){return e==null?"":String(e)}function Ep(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 qR(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()),VR);return r(),l}function VR(e,n,s){return">"+(s?"":" ")+e}function WR(e,n){return _p(e,n.inConstruct,!0)&&!_p(e,n.notInConstruct,!1)}function _p(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 Mp(e,n,s,a){let r=-1;for(;++r<s.unsafe.length;)if(s.unsafe[r].character===`
|
|
667
|
+
`&&WR(s.stack,s.unsafe[r]))return/[ \t]/.test(a.before)?"":" ";return`\\
|
|
668
|
+
`}function KR(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 GR(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 JR(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 YR(e,n,s,a){const r=JR(s),o=e.value||"",l=r==="`"?"GraveAccent":"Tilde";if(GR(e,s)){const h=s.enter("codeIndented"),f=s.indentLines(o,QR);return h(),f}const c=s.createTracker(a),d=r.repeat(Math.max(KR(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:`
|
|
669
|
+
`,encode:["`"],...c.current()})),h()}return m+=c.move(`
|
|
670
|
+
`),o&&(m+=c.move(o+`
|
|
671
|
+
`)),m+=c.move(d),u(),m}function QR(e,n,s){return(s?"":" ")+e}function um(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 XR(e,n,s,a){const r=um(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?" ":`
|
|
672
|
+
`,...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 ZR(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 Ao(e){return"&#x"+e.toString(16).toUpperCase()+";"}function Xl(e,n,s){const a=Nr(e),r=Nr(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}}Rx.peek=eI;function Rx(e,n,s,a){const r=ZR(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=Xl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Ao(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Xl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Ao(h));const p=l.move(r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function eI(e,n,s){return s.options.emphasis||"*"}function tI(e,n){let s=!1;return cm(e,function(a){if("value"in a&&/\r?\n|\r/.test(a.value)||a.type==="break")return s=!0,gu}),!!((!e.depth||e.depth<3)&&nm(e)&&(n.options.setext||s))}function nI(e,n,s,a){const r=Math.max(Math.min(6,e.depth||1),1),o=s.createTracker(a);if(tI(e,s)){const m=s.enter("headingSetext"),h=s.enter("phrasing"),f=s.containerPhrasing(e,{...o.current(),before:`
|
|
673
|
+
`,after:`
|
|
674
|
+
`});return h(),m(),f+`
|
|
675
|
+
`+(r===1?"=":"-").repeat(f.length-(Math.max(f.lastIndexOf("\r"),f.lastIndexOf(`
|
|
676
|
+
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),d=s.enter("phrasing");o.move(l+" ");let u=s.containerPhrasing(e,{before:"# ",after:`
|
|
677
|
+
`,...o.current()});return/^[\t ]/.test(u)&&(u=Ao(u.charCodeAt(0))+u.slice(1)),u=u?l+" "+u:l,s.options.closeAtx&&(u+=" "+l),d(),c(),u}Ix.peek=sI;function Ix(e){return e.value||""}function sI(){return"<"}Tx.peek=iI;function Tx(e,n,s,a){const r=um(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 iI(){return"!"}Px.peek=aI;function Px(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 aI(){return"!"}$x.peek=rI;function $x(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 rI(){return"`"}function Dx(e,n){const s=nm(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))}Lx.peek=oI;function Lx(e,n,s,a){const r=um(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(a);let c,d;if(Dx(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 oI(e,n,s){return Dx(e,s)?"<":"["}Ox.peek=lI;function Ox(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 lI(){return"["}function mm(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 cI(e){const n=mm(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 dI(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 Fx(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 uI(e,n,s,a){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?dI(s):mm(s);const c=e.ordered?l==="."?")":".":cI(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),Fx(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 mI(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 hI(e,n,s,a){const r=mI(s);let o=s.bulletCurrent||mm(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 pI(e,n,s,a){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,a);return o(),r(),l}const fI=Nc(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function gI(e,n,s,a){return(e.children.some(function(l){return fI(l)})?s.containerPhrasing:s.containerFlow).call(s,e,a)}function bI(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}zx.peek=xI;function zx(e,n,s,a){const r=bI(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=Xl(a.before.charCodeAt(a.before.length-1),u,r);m.inside&&(d=Ao(u)+d.slice(1));const h=d.charCodeAt(d.length-1),f=Xl(a.after.charCodeAt(0),h,r);f.inside&&(d=d.slice(0,-1)+Ao(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:f.outside,before:m.outside},c+d+p}function xI(e,n,s){return s.options.strong||"*"}function vI(e,n,s,a){return s.safe(e.value,a)}function yI(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 wI(e,n,s){const a=(Fx(s)+(s.options.ruleSpaces?" ":"")).repeat(yI(s));return s.options.ruleSpaces?a.slice(0,-1):a}const Bx={blockquote:qR,break:Mp,code:YR,definition:XR,emphasis:Rx,hardBreak:Mp,heading:nI,html:Ix,image:Tx,imageReference:Px,inlineCode:$x,link:Lx,linkReference:Ox,list:uI,listItem:hI,paragraph:pI,root:gI,strong:zx,text:vI,thematicBreak:wI};function kI(){return{enter:{table:jI,tableData:Ap,tableHeader:Ap,tableRow:SI},exit:{codeText:CI,table:NI,tableData:hd,tableHeader:hd,tableRow:hd}}}function jI(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 NI(e){this.exit(e),this.data.inTable=void 0}function SI(e){this.enter({type:"tableRow",children:[]},e)}function hd(e){this.exit(e)}function Ap(e){this.enter({type:"tableCell",children:[]},e)}function CI(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,EI));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function EI(e,n){return n==="|"?n:e}function _I(e){const n=e||{},s=n.tableCellPadding,a=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
678
|
+
`,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,y){return u(m(p,x,y),p.align)}function c(p,g,x,y){const b=h(p,x,y),v=u([b]);return v.slice(0,v.indexOf(`
|
|
679
|
+
`))}function d(p,g,x,y){const b=x.enter("tableCell"),v=x.enter("phrasing"),S=x.containerPhrasing(p,{...y,before:o,after:o});return v(),b(),S}function u(p,g){return UR(p,{align:g,alignDelimiters:a,padding:s,stringLength:r})}function m(p,g,x){const y=p.children;let b=-1;const v=[],S=g.enter("table");for(;++b<y.length;)v[b]=h(y[b],g,x);return S(),v}function h(p,g,x){const y=p.children;let b=-1;const v=[],S=g.enter("tableRow");for(;++b<y.length;)v[b]=d(y[b],p,g,x);return S(),v}function f(p,g,x){let y=Bx.inlineCode(p,g,x);return x.stack.includes("tableCell")&&(y=y.replace(/\|/g,"\\$&")),y}}function MI(){return{exit:{taskListCheckValueChecked:Rp,taskListCheckValueUnchecked:Rp,paragraph:RI}}}function AI(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:II}}}function Rp(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function RI(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 II(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=Bx.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 TI(){return[uR(),IR(),DR(),kI(),MI()]}function PI(e){return{extensions:[mR(),TR(e),LR(),_I(e),AI()]}}const $I={tokenize:BI,partial:!0},Ux={tokenize:UI,partial:!0},Hx={tokenize:HI,partial:!0},qx={tokenize:qI,partial:!0},DI={tokenize:VI,partial:!0},Vx={name:"wwwAutolink",tokenize:FI,previous:Kx},Wx={name:"protocolAutolink",tokenize:zI,previous:Gx},Xi={name:"emailAutolink",tokenize:OI,previous:Jx},Oi={};function LI(){return{text:Oi}}let Aa=48;for(;Aa<123;)Oi[Aa]=Xi,Aa++,Aa===58?Aa=65:Aa===91&&(Aa=97);Oi[43]=Xi;Oi[45]=Xi;Oi[46]=Xi;Oi[95]=Xi;Oi[72]=[Xi,Wx];Oi[104]=[Xi,Wx];Oi[87]=[Xi,Vx];Oi[119]=[Xi,Vx];function OI(e,n,s){const a=this;let r,o;return l;function l(h){return!yu(h)||!Jx.call(a,a.previous)||hm(a.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return yu(h)?(e.consume(h),c):h===64?(e.consume(h),d):s(h)}function d(h){return h===46?e.check(DI,m,u)(h):h===45||h===95||zs(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&&Vs(a.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function FI(e,n,s){const a=this;return r;function r(l){return l!==87&&l!==119||!Kx.call(a,a.previous)||hm(a.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check($I,e.attempt(Ux,e.attempt(Hx,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function zI(e,n,s){const a=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Gx.call(a,a.previous)&&!hm(a.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(Vs(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||Jl(h)||Un(h)||za(h)||wc(h)?s(h):e.attempt(Ux,e.attempt(Hx,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function BI(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 UI(e,n,s){let a,r,o;return l;function l(u){return u===46||u===95?e.check(qx,d,c)(u):u===null||Un(u)||za(u)||u!==45&&wc(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 HI(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(qx,n,o)(l):l===null||Un(l)||za(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&a++,e.consume(l),r}}function qI(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||Un(c)||za(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Un(c)||za(c)?n(c):a(c)}function o(c){return Vs(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),a):Vs(c)?(e.consume(c),l):s(c)}}function VI(e,n,s){return a;function a(o){return e.consume(o),r}function r(o){return zs(o)?s(o):n(o)}}function Kx(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Un(e)}function Gx(e){return!Vs(e)}function Jx(e){return!(e===47||yu(e))}function yu(e){return e===43||e===45||e===46||e===95||zs(e)}function hm(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 WI={tokenize:eT,partial:!0};function KI(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:QI,continuation:{tokenize:XI},exit:ZI}},text:{91:{name:"gfmFootnoteCall",tokenize:YI},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:GI,resolveTo:JI}}}}function GI(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=yi(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 JI(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 YI(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||Un(h))return s(h);if(h===93){e.exit("chunkString");const f=e.exit("gfmFootnoteCallString");return r.includes(yi(a.sliceSerialize(f)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Un(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 QI(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||Un(g))return s(g);if(g===93){e.exit("chunkString");const x=e.exit("gfmFootnoteDefinitionLabelString");return o=yi(a.sliceSerialize(x)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(g),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),f}return Un(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),Cn(e,p,"gfmFootnoteDefinitionWhitespace")):s(g)}function p(g){return n(g)}}function XI(e,n,s){return e.check(Go,n,e.attempt(WI,n,s))}function ZI(e){e.exit("gfmFootnoteDefinition")}function eT(e,n,s){const a=this;return Cn(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 tT(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&&ii(f,f.length,0,kc(p,l.slice(u+1,d),c)),ii(f,f.length,0,[["exit",h,c],["enter",l[d][1],c],["exit",l[d][1],c],["exit",m,c]]),ii(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=Nr(u);if(g===126)return h>1?d(g):(l.consume(g),h++,p);if(h<2&&!s)return d(g);const y=l.exit("strikethroughSequenceTemporary"),b=Nr(g);return y._open=!b||b===2&&!!x,y._close=!x||x===2&&!!b,c(g)}}}class nT{constructor(){this.map=[]}add(n,s,a){sT(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 sT(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 iT(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 aT(){return{flow:{null:{name:"table",tokenize:rT,resolveAll:oT}}}}function rT(e,n,s){const a=this;let r=0,o=0,l;return c;function c(E){let I=a.events.length-1;for(;I>-1;){const A=a.events[I][1].type;if(A==="lineEnding"||A==="linePrefix")I--;else break}const O=I>-1?a.events[I][1].type:null,U=O==="tableHead"||O==="tableRow"?w:d;return U===w&&a.parser.lazy[a.now().line]?s(E):U(E)}function d(E){return e.enter("tableHead"),e.enter("tableRow"),u(E)}function u(E){return E===124||(l=!0,o+=1),m(E)}function m(E){return E===null?s(E):en(E)?o>1?(o=0,a.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),p):s(E):vn(E)?Cn(e,m,"whitespace")(E):(o+=1,l&&(l=!1,r+=1),E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(E)))}function h(E){return E===null||E===124||Un(E)?(e.exit("data"),m(E)):(e.consume(E),E===92?f:h)}function f(E){return E===92||E===124?(e.consume(E),h):h(E)}function p(E){return a.interrupt=!1,a.parser.lazy[a.now().line]?s(E):(e.enter("tableDelimiterRow"),l=!1,vn(E)?Cn(e,g,"linePrefix",a.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(E):g(E))}function g(E){return E===45||E===58?y(E):E===124?(l=!0,e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),x):C(E)}function x(E){return vn(E)?Cn(e,y,"whitespace")(E):y(E)}function y(E){return E===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),b):E===45?(o+=1,b(E)):E===null||en(E)?j(E):C(E)}function b(E){return E===45?(e.enter("tableDelimiterFiller"),v(E)):C(E)}function v(E){return E===45?(e.consume(E),v):E===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(E),e.exit("tableDelimiterMarker"),S):(e.exit("tableDelimiterFiller"),S(E))}function S(E){return vn(E)?Cn(e,j,"whitespace")(E):j(E)}function j(E){return E===124?g(E):E===null||en(E)?!l||r!==o?C(E):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(E)):C(E)}function C(E){return s(E)}function w(E){return e.enter("tableRow"),N(E)}function N(E){return E===124?(e.enter("tableCellDivider"),e.consume(E),e.exit("tableCellDivider"),N):E===null||en(E)?(e.exit("tableRow"),n(E)):vn(E)?Cn(e,N,"whitespace")(E):(e.enter("data"),R(E))}function R(E){return E===null||E===124||Un(E)?(e.exit("data"),N(E)):(e.consume(E),E===92?z:R)}function z(E){return E===92||E===124?(e.consume(E),R):R(E)}}function oT(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 nT;for(;++s<e.length;){const p=e[s],g=p[1];p[0]==="enter"?g.type==="tableHead"?(c=!1,d!==0&&(Ip(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=cl(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=cl(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=cl(f,n,o,r,s,h)):l[1]!==0&&(h=cl(f,n,l,r,s,h)),r=0):r&&(g.type==="data"||g.type==="tableDelimiterMarker"||g.type==="tableDelimiterFiller")&&(l[3]=s)}for(d!==0&&Ip(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=iT(n.events,s))}return e}function cl(e,n,s,a,r,o){const l=a===1?"tableHeader":a===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},ur(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const d=ur(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=ur(n.events,s[2]),m=ur(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({},ur(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Ip(e,n,s,a,r){const o=[],l=ur(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 ur(e,n){const s=e[n],a=s[0]==="enter"?"start":"end";return s[1][a]}const lT={name:"tasklistCheck",tokenize:dT};function cT(){return{text:{91:lT}}}function dT(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 Un(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 en(d)?n(d):vn(d)?e.check({tokenize:uT},n,s)(d):s(d)}}function uT(e,n,s){return Cn(e,a,"whitespace");function a(r){return r===null?s(r):n(r)}}function mT(e){return rx([LI(),KI(),tT(e),aT(),cT()])}const hT={};function ji(e){const n=this,s=e||hT,a=n.data(),r=a.micromarkExtensions||(a.micromarkExtensions=[]),o=a.fromMarkdownExtensions||(a.fromMarkdownExtensions=[]),l=a.toMarkdownExtensions||(a.toMarkdownExtensions=[]);r.push(mT(s)),o.push(TI()),l.push(PI(s))}const pT=45e3,fT=3e3,gT=2e3,bT=1500,Tp="fusion:sse-client-id";let ar=null;const ca=new Map;function Pp(){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 Yx(){if(!(typeof window>"u")){if(ar)return ar;try{const e=window.sessionStorage.getItem(Tp);if(e)return ar=e,e;const n=Pp();return window.sessionStorage.setItem(Tp,n),ar=n,n}catch{return ar=Pp(),ar}}}function Qx(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function Xx(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function xT(e){const n=Yx();if(!n)return e;const s=Qx(e);return!s||!Xx(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function pm(e,n){const s=Yx();if(!s)return;const a=Qx(e);if(!a||!Xx(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),Di(`${r.pathname}${r.search}${r.hash}`)}function vT(e){if(typeof window>"u")return;const n=pm(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 Cc(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function $p(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=pm(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,a=s?window.setTimeout(()=>s.abort(),bT):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{a!==null&&window.clearTimeout(a)})}function yT(e){Cc(e),pm(e.url,"keepalive")&&($p(e),e.keepaliveTimer=window.setInterval(()=>{$p(e)},gT))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ca.values()))if(!s.closed){if(Cc(s),vT(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(ca.values()))a.subscribers.size!==0&&(a.closed=!1,fm(a))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function ho(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Zx(e)},pT)}function Zx(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),Cc(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=ca.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=ca.get(e.url);s&&s===e&&e.subscribers.size>0&&fm(e)},fT)}}function fm(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Di(xT(e.url)));e.es=n,yT(e),n.addEventListener("open",()=>{ho(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);Zx(e)}),n.addEventListener("message",()=>ho(e)),n.addEventListener("heartbeat",()=>ho(e)),ev(e),ho(e)}function ev(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=>{ho(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 wT(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),Cc(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ca.delete(e.url)}function hi(e,n={}){let s=ca.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ca.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;fm(s),ev(s),r&&queueMicrotask(()=>{s.subscribers.has(a)&&a.onOpen?.()});let o=!0;return()=>{if(!o)return;o=!1;const l=ca.get(e);l&&(l.subscribers.delete(a),l.subscribers.size===0&&wT(l))}}const Dp=100;function tv(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),y=i.useRef(e),b=i.useRef(s),v=i.useRef(n),S=i.useRef(0);(y.current!==e||b.current!==s||v.current!==n)&&(y.current=e,b.current=s,v.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 N=x.current,R=++S.current;g.current=!1;const z=e,E=s;async function I(){if(!z)return;l(!0),f(!1);try{const U=await Om(z,E,{limit:Dp});if(g.current||x.current!==N||S.current!==R)return;r(U.entries),d(U.hasMore),m(U.total)}catch{if(g.current||x.current!==N||S.current!==R)return;r([]),d(!1),m(null)}finally{!g.current&&x.current===N&&S.current===R&&l(!1)}const O=E?`?projectId=${encodeURIComponent(E)}`:"";p.current=hi(`/api/tasks/${z}/logs/stream${O}`,{events:{"agent:log":U=>{if(!(g.current||x.current!==N))try{const A=JSON.parse(U.data);r(D=>[...D,A]),m(D=>D!==null?D+1:null)}catch{}}}})}return I(),()=>{g.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const C=i.useCallback(async()=>{if(!e||h)return;const N=x.current,R=a.length,z=e;f(!0);try{const E=await Om(z,s,{limit:Dp,offset:R});if(g.current||x.current!==N)return;r(I=>[...E.entries,...I]),d(E.hasMore),m(E.total)}catch{}finally{f(!1)}},[e,s,a.length,h]),w=i.useCallback(()=>r([]),[]);return{entries:a,loading:o,clear:w,loadMore:C,hasMore:c,total:u,loadingMore:h}}const Lp="fn-agent-log-markdown",Op="fn-agent-log-tool-output";function Fp(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 zp(e,n){if(!(typeof window>"u"))try{window.localStorage.setItem(e,n?"true":"false")}catch{}}function kT(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 Bp={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})},nv=50,jT={triage:"Plan"};function Up(e){return e.scrollHeight-(e.scrollTop+e.clientHeight)<=nv}function wu(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function NT(e){const n=new Map;return e.map(s=>{const a=wu(s),r=n.get(a)??0;return n.set(a,r+1),`${a}|${r}`})}function sv(e){return e==="tool"||e==="tool_result"||e==="tool_error"}function pd({detail:e}){const[n,s]=i.useState(!1),a=i.useId(),r=e.split(`
|
|
680
|
+
`).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(pn,{size:14}):t.jsx(On,{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 ST(e,n){return e.agent?sv(e.type)?!0:!n||n.agent!==e.agent||n.type!==e.type:!1}function CT(e,n){const s=[];for(let a=0;a<e.length;a+=1){const{entry:r,hiddenToolBoundaryId:o}=e[a],l=n[a]??`${wu(r)}|fallback`,c=a>0?e[a-1]:void 0,d=c?.entry,u=ST(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]??`${wu(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 ET({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(()=>Fp(Lp,!0)),[y,b]=i.useState(()=>Fp(Op,!0)),[v,S]=i.useState(!1),[j,C]=i.useState(!1),[w,N]=i.useState(!0);i.useEffect(()=>{zp(Lp,g)},[g]),i.useEffect(()=>{zp(Op,y)},[y]);const R=i.useMemo(()=>{if(y)return e.map(P=>({entry:P,hiddenToolBoundaryId:0}));const F=[];let M=0;for(const P of e){if(sv(P.type)){M+=1;continue}F.push({entry:P,hiddenToolBoundaryId:M})}return F},[e,y]),z=i.useMemo(()=>R.map(F=>F.entry),[R]),E=i.useMemo(()=>NT(z),[z]),I=i.useMemo(()=>CT(R,E),[R,E]);i.useLayoutEffect(()=>{const F=u.current;if(!F)return;const M=e.length,P=m.current,$=h.current||F.scrollHeight,k=E[0]??null,J=E[E.length-1]??null,ce=f.current!==k,je=p.current!==J;if(M>P)if(P===0)F.scrollTop=F.scrollHeight;else{const He=$-(F.scrollTop+F.clientHeight)<=nv,xe=je&&!ce,Ne=ce&&!je;if(xe&&He&&(F.scrollTop=F.scrollHeight),Ne){const Y=F.scrollHeight-$;Y>0&&(F.scrollTop+=Y)}}m.current=M,h.current=F.scrollHeight,f.current=k,p.current=J,N(Up(F))},[e,E]);const O=i.useCallback(()=>{const F=u.current;F&&N(Up(F))},[]),U=i.useCallback(()=>{const F=u.current;F&&(F.scrollTop=F.scrollHeight,N(!0))},[]),A=i.useCallback(F=>{F.key==="Escape"&&v&&S(!1)},[v]);i.useEffect(()=>{if(v)return document.addEventListener("keydown",A),()=>{document.removeEventListener("keydown",A)}},[v,A]);const D=s?.provider&&s?.modelId,K=a?.provider&&a?.modelId,Z=r?.provider&&r?.modelId,ne=i.useMemo(()=>{const F=[];return D&&F.push({role:"Executor",provider:s.provider,modelId:s.modelId}),K&&F.push({role:"Reviewer",provider:a.provider,modelId:a.modelId}),Z&&F.push({role:"Planning",provider:r.provider,modelId:r.modelId}),F},[D,s,K,a,Z,r]);return n&&e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})}):e.length===0?t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})}):t.jsxs("div",{className:`agent-log-viewer agent-log-viewer--streaming${v?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[ne.map(F=>t.jsx(Fn,{provider:F.provider,size:"sm"},`${F.role}-${F.provider}-${F.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>C(F=>!F),"aria-label":j?"Collapse model details":"Expand model details","aria-expanded":j,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:j?t.jsx(pn,{size:14}):t.jsx(On,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>x(F=>!F),"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(F=>!F),"aria-label":y?"Hide tool output":"Show tool output","aria-pressed":y,"data-testid":"agent-log-tool-output-toggle",title:y?"Hide tool calls and results":"Show tool calls and results",children:y?"Tools: On":"Tools: Off"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>S(F=>!F),"aria-label":v?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:v?"Exit full screen":"Expand agent log to full screen",children:v?t.jsx(Lo,{size:14}):t.jsx(fc,{size:14})})]}),j&&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:"}),D?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{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:"}),K?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{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:"}),Z?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Fn,{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:O,children:[d!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",z.length," of ",d," entries",!y&&e.length!==z.length?` (${e.length-z.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(jt,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})}),I.map(F=>{const M=F.kind==="single"?F.entry:F.entries[0],P=F.showBadge?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:kT(M.timestamp)}):null,$=F.showBadge?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",jT[M.agent]??M.agent,"]"]}),P]}):null;if(F.kind==="single"){const{entry:J}=F;if(J.type==="tool")return t.jsxs("div",{className:"agent-log-tool",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["⚡ ",J.text]}),J.detail?t.jsx(pd,{detail:J.detail,type:"tool"}):null]},F.key);if(J.type==="tool_result")return t.jsxs("div",{className:"agent-log-tool-result",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✓ ",J.text]}),J.detail?t.jsx(pd,{detail:J.detail,type:"tool_result"}):null]},F.key);if(J.type==="tool_error")return t.jsxs("div",{className:"agent-log-tool-error",children:[$,t.jsxs("div",{className:"agent-log-tool-title",children:["✗ ",J.text]}),J.detail?t.jsx(pd,{detail:J.detail,type:"tool_error"}):null]},F.key)}const k=F.kind==="single"?M.text:F.entries.map(J=>J.text).join("");return F.kind==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],components:Bp,children:k})}):t.jsx("pre",{className:"agent-log-plain-block",children:k})]},F.key):t.jsxs("div",{className:"agent-log-text",children:[$,g?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],components:Bp,children:k})}):t.jsx("pre",{className:"agent-log-plain-block",children:k})]},F.key)}),!w&&t.jsxs("button",{type:"button",className:"agent-log-return-to-live",onClick:U,"data-testid":"agent-log-return-to-live",children:[t.jsx(pn,{size:12}),t.jsx("span",{children:"Live"})]})]})]})}function Sr(e){return e??void 0}function dl(e){return{provider:Sr(e.modelProvider),modelId:Sr(e.modelId)}}function ul(e){return{provider:Sr(e.validatorModelProvider),modelId:Sr(e.validatorModelId)}}function ml(e){return{provider:Sr(e.planningModelProvider),modelId:Sr(e.planningModelId)}}function _T(e,n){return Cb(e,n)}function MT(e,n){return Eb(e,n)}function AT(e,n){return _b(e,n)}function fd(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 gd(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function bd(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function RT(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 IT({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(()=>dl(e)),[y,b]=i.useState(()=>dl(e)),[v,S]=i.useState(()=>ul(e)),[j,C]=i.useState(()=>ul(e)),[w,N]=i.useState(()=>ml(e)),[R,z]=i.useState(()=>ml(e)),[E,I]=i.useState(()=>e.thinkingLevel??null),[O,U]=i.useState(()=>e.thinkingLevel??null),[A,D]=i.useState(null),K=i.useRef(e.id);i.useEffect(()=>{h(!0),p(null),Ks().then(W=>{o(W.models),c(W.favoriteProviders),u(W.favoriteModels)}).catch(W=>{p(W.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const Z=i.useCallback(async W=>{const L=l,fe=L.includes(W)?L.filter(B=>B!==W):[W,...L];c(fe);try{await Dn({favoriteProviders:fe,favoriteModels:d})}catch{c(L),n("Failed to update favorites","error")}},[l,d,n]),ne=i.useCallback(async W=>{const L=d,fe=L.includes(W)?L.filter(B=>B!==W):[W,...L];u(fe);try{await Dn({favoriteProviders:l,favoriteModels:fe})}catch{u(L),n("Failed to update model favorites","error")}},[d,l,n]);i.useEffect(()=>{K.current=e.id;const W=dl(e),L=ul(e),pe=ml(e);x(W),b(W),S(L),C(L),N(pe),z(pe);const fe=e.thinkingLevel??null;I(fe),U(fe),D(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const F=i.useMemo(()=>gd(g),[g]),M=i.useMemo(()=>gd(v),[v]),P=i.useMemo(()=>gd(w),[w]),$=i.useMemo(()=>_T(e,a),[e,a]),k=i.useMemo(()=>MT(e,a),[e,a]),J=i.useMemo(()=>AT(e,a),[e,a]),ce=A!==null,je=i.useCallback(async(W,L)=>{const pe=e.id,fe=y,B=j,ve=R;D(W);try{const Fe=s?W==="executor"?{modelProvider:L.provider??null,modelId:L.modelId??null}:W==="validator"?{validatorModelProvider:L.provider??null,validatorModelId:L.modelId??null}:{planningModelProvider:L.provider??null,planningModelId:L.modelId??null}:{modelProvider:(W==="executor"?L:y).provider??null,modelId:(W==="executor"?L:y).modelId??null,validatorModelProvider:(W==="validator"?L:j).provider??null,validatorModelId:(W==="validator"?L:j).modelId??null,planningModelProvider:(W==="planning"?L:R).provider??null,planningModelId:(W==="planning"?L:R).modelId??null},ae=await Hs(pe,Fe);if(K.current!==pe)return;const qe=dl(ae),Pe=ul(ae),nt=ml(ae);b(qe),x(qe),C(Pe),S(Pe),z(nt),N(nt),s?.(ae),n(RT(W,{executor:qe,validator:Pe,planning:nt}[W]),"success")}catch(Fe){if(K.current!==pe)return;W==="executor"?x(fe):W==="validator"?S(B):N(ve),n(Ee(Fe)||"Failed to save model settings","error")}finally{K.current===pe&&D(null)}},[e.id,y,j,R,n,s]),He=i.useCallback(W=>{const L=fd(W);x(L),!bd(L,y)&&je("executor",L)},[y,je]),xe=i.useCallback(W=>{const L=fd(W);S(L),!bd(L,j)&&je("validator",L)},[j,je]),Ne=i.useCallback(W=>{const L=fd(W);N(L),!bd(L,R)&&je("planning",L)},[R,je]),Y=i.useCallback(async W=>{const L=e.id,pe=O,fe=W===""?null:W;I(fe),D("thinking");try{const B=await Hs(L,{thinkingLevel:fe});if(K.current!==L)return;const ve=B.thinkingLevel??null;U(ve),I(ve),s?.(B);const Fe=a?.defaultThinkingLevel??"off";n(ve===null?`Thinking level set to default (${Fe})`:`Thinking level set to ${ve}`,"success")}catch(B){if(K.current!==L)return;I(pe),n(Ee(B)||"Failed to save thinking level","error")}finally{K.current===L&&D(null)}},[e.id,O,a,n,s]),ie=!y.provider&&!y.modelId,ee=!j.provider&&!j.modelId,oe=!R.provider&&!R.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),Ks().then(W=>{o(W.models),c(W.favoriteProviders),u(W.favoriteModels)}).catch(W=>p(W.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:ie?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",$.provider&&$.modelId?` (${$.provider}/${$.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[y.provider&&t.jsx(Fn,{provider:y.provider,size:"sm"}),y.provider,"/",y.modelId]})}),t.jsx(Is,{id:"executorModel",label:"Executor Model",value:F,onChange:He,models:r,disabled:ce,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:Z,favoriteModels:d,onToggleModelFavorite:ne}),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:ee?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:[j.provider&&t.jsx(Fn,{provider:j.provider,size:"sm"}),j.provider,"/",j.modelId]})}),t.jsx(Is,{id:"validatorModel",label:"Reviewer Model",value:M,onChange:xe,models:r,disabled:ce,placeholder:"Select reviewer model…",favoriteProviders:l,onToggleFavorite:Z,favoriteModels:d,onToggleModelFavorite:ne}),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:oe?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",J.provider&&J.modelId?` (${J.provider}/${J.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[R.provider&&t.jsx(Fn,{provider:R.provider,size:"sm"}),R.provider,"/",R.modelId]})}),t.jsx(Is,{id:"planningModel",label:"Planning Model",value:P,onChange:Ne,models:r,disabled:ce,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:Z,favoriteModels:d,onToggleModelFavorite:ne}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:O===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",a?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:O})}),t.jsxs("select",{id:"thinkingLevel",value:E??"",onChange:W=>Y(W.target.value),disabled:ce,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:ie&&ee&&oe&&O===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const TT={open:t.jsx(cc,{size:16}),closed:t.jsx(Do,{size:16}),merged:t.jsx(Yg,{size:16})};function PT({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(""),[y,b]=i.useState(!1),[v,S]=i.useState(!1),[j,C]=i.useState(null),w=i.useCallback(async()=>{if(f.trim()){b(!0);try{const E=await MN(e,{title:f.trim(),body:g.trim()||void 0},n);c(E),h(!1),p(""),x(""),u(`Created PR #${E.number}`,"success")}catch(E){u(Ee(E)||"Failed to create PR","error")}finally{b(!1)}}},[e,f,g,n,c,u]),N=i.useCallback(async()=>{if(s){S(!0);try{const E=await AN(e,n);C(E),d(E.prInfo),u("PR status refreshed","success")}catch(E){u(Ee(E)||"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(si,{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(si,{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(si,{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:E=>p(E.target.value),disabled:y,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:g,onChange:E=>x(E.target.value),disabled:y,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>h(!1),disabled:y,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:w,disabled:!f.trim()||y,children:y?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(si,{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(Mn,{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 R=TT[s.status]??t.jsx(cc,{size:16}),z=j?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(si,{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:R}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:N,disabled:v,title:"Refresh PR status",children:t.jsx(bs,{size:14,style:{verticalAlign:"middle",opacity:v?.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:z.length>0?`Waiting for: ${z.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(Ki,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(Kg,{size:14}),"View on GitHub"]})]})]})]})}const Hp=2e3;function $T(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function DT(e){return e==="agent"||e==="system"}function LT({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((N,R)=>new Date(R.createdAt).getTime()-new Date(N.createdAt).getTime()),[e.comments]),y=o.length>Hp;async function b(){const N=o.trim();if(N){f(!0);try{const R=await Jj(e.id,N,r);l(""),n?.(R),s("Comment added","success")}catch(R){s(Ee(R)||"Failed to add comment","error")}finally{f(!1)}}}async function v(N){const R=u.trim();if(R){f(!0);try{const z=await qj(e.id,N,R,r);d(null),m(""),n?.(z),s("Comment updated","success")}catch(z){s(Ee(z)||"Failed to update comment","error")}finally{f(!1)}}}async function S(N){g(N);try{const R=await Vj(e.id,N,r);n?.(R),s("Comment deleted","success")}catch(R){s(Ee(R)||"Failed to delete comment","error")}finally{g(null)}}function j(N){N.key==="Enter"&&(N.ctrlKey||N.metaKey)&&(N.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(N=>{const R=N.author===a,z=c===N.id,E=DT(N.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[E?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:N.author}),t.jsx("span",{className:"detail-log-timestamp",children:$T(N)})]}),R&&!z?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{d(N.id),m(N.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void S(N.id),disabled:p===N.id,children:p===N.id?"Deleting…":"Delete"})]}):null]}),z?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:u,onChange:I=>m(I.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 v(N.id),disabled:h||!u.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:N.text})]},N.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:N=>l(N.target.value),onKeyDown:j,rows:3,placeholder:"Add a comment",className:"comments-textarea"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${y?" comments-char-count--over":""}`,children:[o.length," / ",Hp]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void b(),disabled:h||!o.trim()||y,children:h?"Posting…":"Add Comment"})]})]})]})}const qp="Failed to load review data.",OT="No reviewer feedback yet — this task has not produced reviewer-agent feedback in direct mode.";function Xr(e){return e?new Date(e).toLocaleString():"Never"}function FT(e){return e==="manual"?"Manual":e==="auto"?"Background":"Initial load"}function zT(e){const n=new Map(e.addressing.map(o=>[o.itemId,o])),s=e.items.map(o=>{const l=n.get(o.id);return{id:o.id,summary:o.summary??o.body.slice(0,120),body:o.body,path:o.path,createdAt:o.createdAt,status:l?.status??"queued",addressing:l,item:o}}),a=new Set(s.map(o=>o.id)),r=e.addressing.filter(o=>!a.has(o.itemId)&&o.snapshot).map(o=>({id:o.itemId,summary:o.snapshot?.summary??o.itemId,body:o.snapshot?.body??o.snapshot?.summary??o.itemId,path:o.snapshot?.filePath,createdAt:o.selectedAt,status:o.status,addressing:o}));return[...s,...r]}function BT({task:e,projectId:n,onTaskUpdated:s,addToast:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,x]=i.useState(null),[y,b]=i.useState(e.reviewState??null),v=r.length>0&&!d,S=y?.source==="pull-request",j=i.useMemo(()=>y?zT(y):[],[y]);i.useEffect(()=>{let O=!1;return h(!0),p(null),YS(e.id,n).then(U=>{O||(b(U.reviewState),x(U.emptyMessage??null))}).catch(()=>{O||p(qp)}).finally(()=>{O||h(!1)}),()=>{O=!0}},[e.id,n]);const C=i.useMemo(()=>y?y.source==="pull-request"?`${y.summary?.reviewDecision??"REVIEW_REQUIRED"} · ${j.length} review item(s)`:`${y.summary?.summary??"reviewer-agent"} · ${j.length} review item(s)`:"No review feedback captured yet.",[y,j.length]),w=y?y.source==="pull-request"?y.summary?.reviewDecision:y.summary?.verdict:void 0,N=l?"refreshing":y?.refreshStatus??"ready",R=N==="error"?"status-dot status-dot--error":N==="refreshing"?"status-dot status-dot--pending":"status-dot status-dot--online",z=O=>o(U=>U.includes(O)?U.filter(A=>A!==O):[...U,O]),E=async()=>{try{p(null),c(!0);const O=await QS(e.id,n);if(b(O.reviewState),s?.({...e,reviewState:O.reviewState,prInfo:O.prInfo??e.prInfo}),O.reviewState.refreshStatus==="error"){const U=O.reviewState.refreshError??"Failed to refresh review data.";p(U),a(U,"error");return}a("Review refreshed","success")}catch(O){const U=O instanceof Error?O.message:qp;p(U),a(U,"error")}finally{c(!1)}},I=async()=>{try{if(!y)return;p(null),u(!0);const O=j.filter(A=>r.includes(A.id)).map(A=>{if(!A.item)return{id:A.id,source:y.source==="pull-request"?"pr-review":"reviewer-agent",threadId:A.addressing?.snapshot?.threadId,filePath:A.addressing?.snapshot?.filePath,lineNumber:A.addressing?.snapshot?.lineNumber,author:A.addressing?.snapshot?.authorLogin,summary:A.summary,body:A.body,url:A.addressing?.snapshot?.url};const D=A.item;return{id:A.item.id,source:y.source==="pull-request"?"pr-review":"reviewer-agent",threadId:typeof D.threadId=="string"?D.threadId:void 0,filePath:A.item.path,lineNumber:typeof D.line=="number"?D.line:void 0,author:A.item.author?.login,summary:A.item.summary??A.item.body.slice(0,120),body:A.item.body,url:typeof D.url=="string"?D.url:void 0}}),U=await XS(e.id,O,n);b(U.reviewState),s?.({...U.task,reviewState:U.reviewState}),o([]),a("Same-task AI revision started from selected review feedback","success")}catch(O){const U=O instanceof Error?O.message:"Failed to queue revision";p(U),a(U,"error")}finally{u(!1)}};return t.jsxs("div",{className:"task-review-tab",children:[t.jsxs("div",{className:"task-review-tab__header",children:[t.jsxs("div",{className:"task-review-tab__summary-wrap",children:[t.jsx("p",{className:"task-review-tab__summary",children:C}),w?t.jsx("span",{className:`task-review-tab__decision task-review-tab__decision--${w}`,children:w}):null]}),t.jsxs("div",{className:"task-review-tab__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:E,disabled:l||m,children:l?"Refreshing…":"Refresh"}),t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!v,onClick:I,children:d?"Queueing…":"Request revision"})]})]}),t.jsxs("div",{className:"task-review-tab__meta task-review-tab__refresh-meta","aria-live":"polite",children:[t.jsx("span",{className:R,"aria-hidden":"true"}),t.jsxs("span",{children:[N==="error"?"Refresh failed":N==="refreshing"?"Refreshing":"Up to date"," · Last refreshed: ",Xr(y?.lastRefreshedAt)," · ",FT(y?.refreshSource)]})]}),m?t.jsx("div",{className:"task-review-tab__meta",children:"Loading review data…"}):null,!m&&f?t.jsx("div",{className:"task-review-tab__error",children:f}):null,!m&&!f&&!S&&j.length===0?t.jsx("div",{className:"task-review-tab__empty",children:g??OT}):null,!m&&!f&&j.length>0?t.jsx("ul",{className:"task-review-tab__list",children:j.map(O=>t.jsx("li",{className:"task-review-tab__item card",children:t.jsxs("label",{className:"task-review-tab__direct-item task-review-tab__direct-item--selectable",children:[t.jsxs("div",{className:"task-review-tab__summary-wrap",children:[t.jsx("input",{type:"checkbox",checked:r.includes(O.id),onChange:()=>z(O.id)}),t.jsxs("span",{className:"task-review-tab__item-summary",children:[O.path?`${O.path}: `:"",O.summary]}),t.jsx("span",{className:`task-review-tab__status task-review-tab__status--${O.status}`,children:O.status})]}),t.jsx("div",{className:"task-review-tab__meta",children:Xr(O.createdAt)}),O.addressing?t.jsxs("div",{className:"task-review-tab__meta",children:["Selected: ",Xr(O.addressing.selectedAt),O.addressing.startedAt?` · Started: ${Xr(O.addressing.startedAt)}`:"",O.addressing.completedAt?` · Completed: ${Xr(O.addressing.completedAt)}`:"",O.addressing.error?` · Error: ${O.addressing.error}`:""]}):null,t.jsx("pre",{className:"task-review-tab__body",children:O.body})]})},O.id))}):null,S&&!m&&!f&&j.length===0?t.jsx("div",{className:"task-review-tab__empty",children:"No review items yet."}):null]})}function UT(e){return e?e.slice(0,7):"Unknown"}function HT({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:UT(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 iv(e){return e.split(`
|
|
681
|
+
`).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}
|
|
682
|
+
`},a):t.jsx(Ol.Fragment,{children:`${s}
|
|
683
|
+
`},a)})}function qT(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function VT({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);Li(f,e,"fusion:changes-diff-modal-size");const p=Qi(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(v=>v!==null&&v>0?v-1:v)},[]),x=i.useCallback(()=>{u(v=>v!==null&&v<s.length-1?v+1:v)},[]);if(i.useEffect(()=>{if(!e)return;const v=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",v),()=>document.removeEventListener("keydown",v)},[e,l,g,x]),!e)return null;const y=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(xi,{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(lc,{})}),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(On,{})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(v=>!v),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(zl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(bs,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(un,{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(br,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((v,S)=>t.jsxs("button",{className:`changes-diff-file-item ${d===S?"selected":""}`,onClick:()=>u(S),title:v.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${v.status}`,children:qT(v.status)}),t.jsx("span",{className:"changes-diff-file-path",title:v.path,children:t.jsx("bdo",{dir:"ltr",children:v.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",v.additions," -",v.deletions]})]},v.path))})]}),t.jsx("div",{className:"changes-diff-content",children:y?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:y.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",y.additions," -",y.deletions]})]}),y.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:iv(y.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(xi,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function av(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function xd(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(br,{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(xi,{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:av("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function WT({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([]),[y,b]=i.useState(null),[v,S]=i.useState(new Set),[j,C]=i.useState(null),[w,N]=i.useState(!0),[R,z]=i.useState(!1),E=a==="done",I=E&&!!r?.commitSha,O=a==="in-progress"||a==="in-review"||I,U=i.useCallback(async()=>{if(!O&&!E){h(!1);return}try{h(!0),p(null);const F=await f1(e,s);if(b(F.lineageId),x(F.associations),!O){c([]),u({filesChanged:0,additions:0,deletions:0});return}const M=await pb(e,void 0,s),P=M.files.map($=>({path:$.path,status:$.status,additions:$.additions,deletions:$.deletions,patch:$.patch}));c(P),u(M.stats),P.length>0&&(S(new Set([P[0].path])),C(0))}catch(F){p(Ee(F)||"Failed to load task changes")}finally{h(!1)}},[e,s,O,E]);i.useEffect(()=>{U()},[U]);const A=F=>{S(M=>{const P=new Set(M);if(P.has(F))P.delete(F);else{P.add(F);const $=l.findIndex(k=>k.path===F);$!==-1&&C($)}return P})},D=F=>{if(F<0||F>=l.length)return;const M=l[F].path;S(new Set([M])),C(F)},K=j!==null&&j>0,Z=j!==null&&j<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(Ws,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!E&&!n)return o&&o.length>0?xd(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(xi,{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(E&&!I){if(o&&o.length>0)return xd(o,!0,r);const F=r?.filesChanged,M=r?.insertions,P=r?.deletions,$=F!=null||M!=null||P!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(xi,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:$?`Merge summary: ${F??0} file${(F??0)===1?"":"s"} changed, +${M??0} additions, -${P??0} deletions.`:"No merge commit was recorded for this task."})]})})}const ne=()=>t.jsxs("section",{className:"task-lineage-associations","aria-label":"Task commit associations",children:[t.jsxs("div",{className:"task-lineage-associations-header",children:[t.jsxs("h4",{children:[t.jsx(br,{size:16}),"Lineage commit associations"]}),y&&t.jsx("code",{className:"task-lineage-id",children:y})]}),g.length===0?t.jsx("p",{className:"task-lineage-associations-empty",children:"No associated commits recorded yet."}):t.jsx("div",{className:"task-lineage-associations-list",children:g.map(F=>{const M=F.matchedBy.replace(/-/g," ");return t.jsxs("article",{className:`task-lineage-association task-lineage-association--${F.confidence}`,children:[t.jsxs("div",{className:"task-lineage-association-main",children:[t.jsx("code",{className:"task-lineage-sha",children:F.commitSha.slice(0,7)}),t.jsx("span",{className:"task-lineage-subject",children:F.commitSubject})]}),t.jsxs("div",{className:"task-lineage-association-meta",children:[t.jsx("span",{children:new Date(F.authoredAt).toLocaleString()}),t.jsxs("span",{children:["Confidence: ",F.confidence]}),t.jsxs("span",{children:["Match: ",M]}),t.jsxs("span",{children:["Task snapshot: ",F.taskIdSnapshot]})]}),F.note&&t.jsx("p",{className:"task-lineage-note",children:F.note})]},`${F.commitSha}-${F.matchedBy}`)})})]});return l.length===0?o&&o.length>0?xd(o,E,r):t.jsxs("div",{className:"detail-section task-changes-tab",children:[ne(),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(xi,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:E?"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:[ne(),E&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(br,{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(xi,{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:()=>K&&D(j-1),disabled:!K,title:"Previous file","aria-label":"Previous file",children:t.jsx(lc,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:j!==null?`${j+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>Z&&D(j+1),disabled:!Z,title:"Next file","aria-label":"Next file",children:t.jsx(On,{})})]}),t.jsx("button",{className:`btn btn-sm ${w?"btn-primary":""}`,onClick:()=>N(F=>!F),title:w?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(zl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:U,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>z(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(fc,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(F=>{const M=v.has(F.path);return t.jsxs("div",{className:`changes-file-item ${M?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>A(F.path),children:[t.jsx("span",{className:"changes-file-toggle",children:M?t.jsx(pn,{size:14}):t.jsx(On,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${F.status}`,title:F.status,children:av(F.status)}),t.jsx("span",{className:"changes-file-path",title:F.path,children:t.jsx("bdo",{dir:"ltr",children:F.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${F.additions} -${F.deletions}`,children:["+",F.additions," -",F.deletions]})]}),M&&F.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${w?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:iv(F.patch)})})})]},F.path)})}),t.jsx(VT,{isOpen:R,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>z(!1),onRefresh:U})]})}function Vp(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function KT(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function Z5(e,n){const s=KT(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 Wp(e){const n=e?.trim()??"";return vc.test(n)?n:""}function rv(e,n){const s=Wp(e?.githubTrackingDefaultRepo);return s||Wp(n?.githubTrackingDefaultRepo)}function GT(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const Kp=["image/png","image/jpeg","image/gif","image/webp"];function JT(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 ov({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:y,onPriorityChange:b,executorModel:v,onExecutorModelChange:S,validatorModel:j,onValidatorModelChange:C,planningModel:w,onPlanningModelChange:N,thinkingLevel:R,onThinkingLevelChange:z,presetMode:E,onPresetModeChange:I,selectedPresetId:O,onSelectedPresetIdChange:U,selectedWorkflowSteps:A,onWorkflowStepsChange:D,onDefaultOnApplied:K,pendingImages:Z,onImagesChange:ne,tasks:F,projectId:M,disabled:P=!1,addToast:$,isActive:k=!0,onAutoSaveDescription:J,onPlanningMode:ce,onSubtaskBreakdown:je,onClose:He,renderBelowPrimary:xe,renderBelowModelConfiguration:Ne,hideDependencies:Y,autoExpandMoreOptionsOnSelection:ie=!0,reviewLevel:ee,onReviewLevelChange:oe,executionMode:W,onExecutionModeChange:L,githubTrackingEnabled:pe,onGithubTrackingEnabledChange:fe,githubRepoOverride:B,onGithubRepoOverrideChange:ve}){const Fe=(Y?!1:o.length>0)||Z.length>0||A.length>0||E!=="default"||(y??Ds)!==Ds||v!==""||j!==""||(w||"")!==""||(R||"")!==""||ee!==void 0||W==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||pe===!0||(B||"")!=="",[ae,qe]=i.useState(!1),[Pe,nt]=i.useState(ie?Fe:!1),[Be,de]=i.useState(""),[Ie,$e]=i.useState([]),[st,Ue]=i.useState([]),[me,re]=i.useState([]),[_e,xt]=i.useState(!1),[dt,Qe]=i.useState(null),[vt,Ae]=i.useState(null),[Je,ct]=i.useState([]),[Nt,yt]=i.useState("idle"),[Se,G]=i.useState(!1),[ge,pt]=i.useState(!1),[ke,tt]=i.useState(!1),Rt=i.useRef(null),Re=i.useRef(null),be=i.useRef(null),at=i.useRef(null),ot=i.useRef(null),gt=i.useRef(null),St=i.useRef(null),Lt=i.useRef(!1),Yt=i.useRef(Fe),tn=i.useRef(n.trim()),mn=i.useRef(n.trim());i.useEffect(()=>{k&&(xt(!0),Ks().then(se=>{$e(se.models),Ue(se.favoriteProviders),re(se.favoriteModels)}).catch(()=>{}).finally(()=>xt(!1)),gc(M).then(se=>Qe(se)).catch(()=>Qe(null)),Uo(M).then(se=>ct(se.filter(te=>te.enabled))).catch(()=>ct([])),Yi().then(se=>Ae(se)).catch(()=>Ae(null)))},[k,M]);const Qt=dt?.modelPresets||[],yn=Qt.find(se=>se.id===O),Gt=rv(dt,vt),on=(B||"").trim(),sn=on.length>0&&!vc.test(on),ln=(Y?!1:o.length>0)||Z.length>0||A.length>0||E!=="default"||(y??Ds)!==Ds||v!==""||j!==""||(w||"")!==""||(R||"")!==""||ee!==void 0||W==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||pe===!0||(B||"")!=="";i.useEffect(()=>{if(e!=="create"||!k||!dt?.autoSelectModelPreset)return;const se=(dt.defaultPresetBySize,void 0);if(se){const te=Vp(se);U(se.id),I("preset"),S(te.executorValue),C(te.validatorValue)}},[k,dt,Qt,e]);const Wt=i.useRef(!1),ye=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!k||Wt.current||Je.length===0)return;const se=Je.filter(De=>De.defaultOn);if(se.length===0)return;Wt.current=!0;const te=se.map(De=>De.id);D(te),K?.(te)},[e,k,Je]),i.useEffect(()=>{k||(Wt.current=!1)},[k]),i.useEffect(()=>{e!=="create"||!k||fe&&(ye.current||dt&&(fe(dt.githubTrackingEnabledByDefault??!1),ye.current=!0))},[e,k,dt,fe]),i.useEffect(()=>{k||(ye.current=!1)},[k]),i.useEffect(()=>{if(!ie){Yt.current=ln;return}ln&&!Yt.current&&nt(!0),Yt.current=ln},[ln,ie]),i.useEffect(()=>{Pe||(qe(!1),de(""))},[Pe]),i.useEffect(()=>{e!=="edit"||!k||at.current&&(at.current.focus(),at.current.select())},[e,k]),i.useEffect(()=>{if(!ae)return;const se=te=>{Re.current&&!Re.current.contains(te.target)&&qe(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[ae]),i.useEffect(()=>{(e!=="edit"||P)&&tt(!1)},[e,P]),i.useEffect(()=>{if(e!=="edit"){yt("idle");return}const se=n.trim();tn.current=se,mn.current=se,yt("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!J||!k)return;const se=n.trim(),te=tn.current;if(se===te||se===mn.current){gt.current&&(clearTimeout(gt.current),gt.current=null),Lt.current||yt("idle");return}return gt.current&&clearTimeout(gt.current),gt.current=setTimeout(async()=>{if(!Lt.current){Lt.current=!0,yt("saving");try{await J(se),mn.current=se,yt("saved"),St.current&&clearTimeout(St.current),St.current=setTimeout(()=>{yt("idle"),St.current=null},2e3)}catch{yt("idle")}finally{Lt.current=!1,gt.current=null}}},1500),()=>{gt.current&&(clearTimeout(gt.current),gt.current=null)}},[e,n,J,k]),i.useEffect(()=>()=>{gt.current&&clearTimeout(gt.current),St.current&&clearTimeout(St.current)},[]),i.useEffect(()=>{if(!Se)return;const se=te=>{Rt.current&&!Rt.current.contains(te.target)&&G(!1)};return document.addEventListener("mousedown",se),()=>document.removeEventListener("mousedown",se)},[Se]);const Le=i.useCallback(se=>{const te=se.clipboardData?.items;if(te)for(let De=0;De<te.length;De++){const ft=te[De];if(ft.type.startsWith("image/")){const qt=ft.getAsFile();if(qt&&Kp.includes(qt.type)){se.preventDefault(),ne([...Z,{file:qt,previewUrl:URL.createObjectURL(qt)}]);return}}}},[Z,ne]),Ke=i.useCallback(se=>{se.preventDefault();const te=se.dataTransfer.files;for(let De=0;De<te.length;De++){const ft=te[De];if(Kp.includes(ft.type)){ne([...Z,{file:ft,previewUrl:URL.createObjectURL(ft)}]);return}}},[Z,ne]),ut=i.useCallback(se=>{const te=Z[se];te&&URL.revokeObjectURL(te.previewUrl),ne(Z.filter((De,ft)=>ft!==se))},[Z,ne]),Ve=i.useCallback(se=>{l(o.includes(se)?o.filter(te=>te!==se):[...o,se])},[o,l]),Pt=(se,te)=>se.length>te?se.slice(0,te)+"…":se,Ot=i.useCallback(se=>{s(se.target.value);const te=se.target;te.style.height="auto",te.style.height=te.scrollHeight+"px"},[s]),bt=i.useCallback(()=>{tt(se=>!se)},[]),Dt=i.useCallback(se=>{!ke||se.key!=="Escape"||(se.preventDefault(),se.stopPropagation(),tt(!1))},[ke]),Ft=i.useCallback(async se=>{const te=n.trim();if(!(!te||ge)){pt(!0);try{const De=await cb(te,se,M);s(De),G(!1),$("Description refined with AI","success"),be.current&&(be.current.style.height="auto",be.current.style.height=be.current.scrollHeight+"px")}catch(De){const ft=db(De);$(ft,"error")}finally{pt(!1)}}},[n,ge,$,s,M]),Ht=i.useCallback(async se=>{const te=st,ft=te.includes(se)?te.filter(qt=>qt!==se):[se,...te];Ue(ft);try{await Dn({favoriteProviders:ft,favoriteModels:me})}catch{Ue(te)}},[st,me]),rn=i.useCallback(async se=>{const te=me,ft=te.includes(se)?te.filter(qt=>qt!==se):[se,...te];re(ft);try{await Dn({favoriteProviders:st,favoriteModels:ft})}catch{re(te)}},[me,st]),Xt=i.useCallback(se=>{if(se<=0)return;const te=[...A];[te[se-1],te[se]]=[te[se],te[se-1]],D(te)},[A,D]),an=i.useCallback(se=>{if(se>=A.length-1)return;const te=[...A];[te[se],te[se+1]]=[te[se+1],te[se]],D(te)},[A,D]),Me=i.useCallback(se=>{D(A.filter(te=>te!==se))},[A,D]),it=new Map;for(const se of Je)it.set(se.id,{name:se.name,description:se.description});const kt=F.filter(se=>!o.includes(se.id)).sort((se,te)=>{const De=te.createdAt.localeCompare(se.createdAt);if(De!==0)return De;const ft=parseInt(se.id.slice(se.id.lastIndexOf("-")+1),10)||0;return(parseInt(te.id.slice(te.id.lastIndexOf("-")+1),10)||0)-ft}),$t=Be?kt.filter(se=>se.id.toLowerCase().includes(Be.toLowerCase())||se.title&&se.title.toLowerCase().includes(Be.toLowerCase())||se.description&&se.description.toLowerCase().includes(Be.toLowerCase())):kt;return t.jsxs("div",{className:"task-form",onDrop:Ke,onDragOver:se=>se.preventDefault(),onPaste:Le,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:at,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:se=>r(se.target.value),disabled:P})]}),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${Nt==="idle"?"":" is-visible"}`,"aria-live":"polite",children:Nt==="saving"?"Saving...":Nt==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${ke?" description--fullscreen":""}`,ref:Rt,onKeyDown:Dt,children:[ke&&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:bt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(Lo,{size:14})})]}),t.jsx("textarea",{ref:be,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Ot,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:P||ge}),(()=>{const se=!!n.trim()&&!P;return t.jsxs(t.Fragment,{children:[!ke&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${se?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:bt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(fc,{size:14})}),se&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${ge?"refine-button--loading":""}`,onClick:()=>G(te=>!te),disabled:ge,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(gs,{size:12,style:{verticalAlign:"middle"}}),ge?"Refining...":"Refine"]})]})})(),Se&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:se=>se.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ft("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:()=>Ft("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:()=>Ft("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:()=>Ft("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"&&(ce||je)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[ce&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const se=n.trim();if(!se){$("Enter a description first","error");return}He?.(),ce(se)},disabled:P||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),je&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const se=n.trim();if(!se){$("Enter a description first","error");return}He?.(),je(se)},disabled:P||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),xe,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>nt(se=>!se),"aria-expanded":Pe,"aria-controls":"task-form-more-options",disabled:P,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),Pe?t.jsx(Pi,{size:14}):t.jsx(pn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${Pe?"":" collapsed"}`,"aria-hidden":!Pe,hidden:!Pe,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),Z.length>0&&t.jsx("div",{className:"inline-create-previews",children:Z.map((se,te)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:se.previewUrl,alt:se.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ut(te),disabled:P,title:"Remove image",children:"×"})]},se.previewUrl))}),t.jsx("input",{ref:ot,type:"file",accept:"image/*",onChange:se=>{const te=se.target.files?.[0];te&&(ne([...Z,{file:te,previewUrl:URL.createObjectURL(te)}]),se.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>ot.current?.click(),disabled:P,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:se=>f(se.target.value||void 0),disabled:P||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(se=>t.jsxs("option",{value:se.id,children:[se.name," (",GT(se.status),")"]},se.id))]}),(()=>{const se=(p??[]).find(te=>te.id===h);return se?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Oa,{status:se.status,showLabel:!0})}):null})(),t.jsx("small",{children:x??"Task override takes priority over project default node routing."})]}),!Y&&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:()=>qe(se=>!se),disabled:P,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ae&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Be,onChange:se=>de(se.target.value),onClick:se=>se.stopPropagation()}),$t.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):$t.map(se=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(se.id)?" selected":""}`,onClick:()=>Ve(se.id),onMouseDown:te=>te.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:se.id}),t.jsx("span",{className:"dep-dropdown-title",children:Pt(se.title||se.description||se.id,30)})]},se.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(se=>t.jsxs("span",{className:"dep-chip",children:[se,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Ve(se),disabled:P,children:"×"})]},se))})]})}),(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:se=>d(se.target.value),placeholder:"e.g. feature/my-task",disabled:P})]}),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:se=>m(se.target.value),placeholder:"e.g. main",disabled:P})]})]}),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:y??Ds,onChange:se=>b(se.target.value),disabled:P,children:pa.map(se=>t.jsx("option",{value:se,children:se[0].toUpperCase()+se.slice(1)},se))})]}),L&&W!==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:W,onChange:se=>L(se.target.value),disabled:P,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),_e?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Ie.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:E==="preset"?O:E,onChange:se=>{const te=se.target.value;if(te==="default"){I("default"),U(""),S(""),C("");return}if(te==="custom"){I("custom"),U("");return}const De=Qt.find(qt=>qt.id===te),ft=Vp(De);I("preset"),U(te),S(ft.executorValue),C(ft.validatorValue)},disabled:P,children:[t.jsx("option",{value:"default",children:"Use default"}),Qt.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,Qt.map(se=>t.jsx("option",{value:se.id,children:se.name},se.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),E==="preset"&&yn?t.jsxs("small",{children:["Using preset: ",yn.name]}):null,E==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>I("custom"),disabled:P,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(Is,{id:"executor-model",label:"Executor Model",value:v,onChange:se=>{I("custom"),U(""),S(se)},models:Ie,disabled:P||E==="preset",favoriteProviders:st,onToggleFavorite:Ht,favoriteModels:me,onToggleModelFavorite:rn})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(Is,{id:"validator-model",label:"Reviewer Model",value:j,onChange:se=>{I("custom"),U(""),C(se)},models:Ie,disabled:P||E==="preset",favoriteProviders:st,onToggleFavorite:Ht,favoriteModels:me,onToggleModelFavorite:rn})]}),N&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(Is,{id:"planning-model",label:"Planning Model",value:w||"",onChange:se=>{I("custom"),U(""),N(se)},models:Ie,disabled:P||E==="preset",favoriteProviders:st,onToggleFavorite:Ht,favoriteModels:me,onToggleModelFavorite:rn})]}),z&&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:R||"",onChange:se=>z(se.target.value),disabled:P||E==="preset",children:[t.jsxs("option",{value:"",children:["Default (",dt?.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"})]})]}),oe&&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:ee??"",onChange:se=>oe(se.target.value===""?void 0:parseInt(se.target.value,10)),disabled:P,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"})]})]})]})]}),Ne,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:Je.length>0&&Je.map(se=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${se.id}`,children:[t.jsx("input",{type:"checkbox",checked:A.includes(se.id),onChange:te=>{D(te.target.checked?[...A,se.id]:A.filter(De=>De!==se.id))},disabled:P}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[se.name,JT(se.phase||"pre-merge",se.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:se.description})]})]},se.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((se,te)=>{const De=it.get(se);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${se}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:te+1}),t.jsx("span",{className:"workflow-step-order-name",children:De?.name||se}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Xt(te),disabled:P||te===0,"data-testid":`workflow-step-move-up-${se}`,title:"Move up",children:t.jsx(Pi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>an(te),disabled:P||te===A.length-1,"data-testid":`workflow-step-move-down-${se}`,title:"Move down",children:t.jsx(pn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Me(se),disabled:P,"data-testid":`workflow-step-remove-${se}`,title:"Remove",children:t.jsx(un,{})})]})]},se)})]})]}),(fe||ve)&&t.jsxs("div",{className:"form-group","data-testid":"task-form-github-tracking",children:[t.jsx("label",{children:"GitHub Tracking"}),fe&&t.jsxs("label",{className:"checkbox-label",htmlFor:"task-github-tracking-enabled",children:[t.jsx("input",{id:"task-github-tracking-enabled",type:"checkbox",checked:pe===!0,onChange:se=>{ye.current=!0,fe(se.target.checked)},disabled:P}),"Enable GitHub issue tracking for this task"]}),ve&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-github-repo-override",className:"model-select-label",children:"Repository (owner/repo)"}),t.jsx("input",{id:"task-github-repo-override",className:"input",value:B||"",onChange:se=>ve(se.target.value),placeholder:Gt||"owner/repo",disabled:P}),sn?t.jsx("div",{className:"form-error",children:"Repository must be in owner/repo format."}):null]})]})]})]})}const Gp={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 YT(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function QT(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 XT(e){return e?new Date(e).toLocaleString():null}function ZT(e){const n=e.split(`
|
|
684
|
+
`);return n.length<=1?e:`${n.length} lines`}function hl(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 eP({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 tP({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([]),[y,b]=i.useState(!1),v=n.some(k=>k.status==="pending"),{entries:S}=tv(e,!!l&&v,o);i.useEffect(()=>{let k=!1;return Uo(o).then(J=>{k||x(J.filter(ce=>ce.enabled))}).catch(()=>{k||x([])}),()=>{k=!0}},[o]);const j=a??[],C=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(C.map(k=>[k.id,k])),[C]),N=k=>{u(J=>({...J,[k]:!J[k]}))},R=k=>{h(J=>{const ce=J[k]??"markdown";return{...J,[k]:ce==="markdown"?"plain":"markdown"}})},z=k=>{p(k)},E=()=>{p(null)};i.useEffect(()=>{if(!f)return;const k=J=>{J.key==="Escape"&&E()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[f]);const I=i.useCallback((k,J)=>{if(c){if(J){if(j.includes(k)){c(j);return}c([...j,k]);return}c(j.filter(ce=>ce!==k))}},[c,j]),O=i.useCallback(k=>{if(!c||k<=0)return;const J=[...j];[J[k-1],J[k]]=[J[k],J[k-1]],c(J)},[c,j]),U=i.useCallback(k=>{if(!c||k>=j.length-1)return;const J=[...j];[J[k],J[k+1]]=[J[k+1],J[k]],c(J)},[c,j]),A=i.useCallback(k=>{c&&c(j.filter(J=>J!==k))},[c,j]),D=n.length>0,K=j.length>0;i.useEffect(()=>{r||b(!1)},[r]);const Z=i.useMemo(()=>j.map(k=>{const J=w.get(k);return{id:k,name:J?.name||k,description:J?.description||"Step definition not found.",phase:J?.phase||"pre-merge"}}),[j,w]),ne=()=>!r||!y||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:C.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:j.includes(k.id),onChange:J=>I(k.id,J.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,hl(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),j.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),j.map((k,J)=>{const ce=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:J+1}),t.jsx("span",{className:"workflow-step-order-name",children:ce?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>O(J),disabled:J===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(Pi,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(J),disabled:J===j.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(pn,{})}),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(un,{})})]})]},k)})]})]}),F=()=>{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(!D)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(xe=>xe.status==="passed").length,J=n.filter(xe=>xe.status==="failed").length,ce=n.filter(xe=>xe.status==="skipped").length,je=n.filter(xe=>xe.status==="pending").length,He=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&He.push(`${k} passed`),J>0&&He.push(`${J} failed`),ce>0&&He.push(`${ce} skipped`),je>0&&He.push(`${je} 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:He.join(" · ")}),n.map((xe,Ne)=>{const Y=xe.phase||"pre-merge",ie=d[xe.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${xe.status}`,"data-testid":`workflow-result-item-${xe.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[xe.workflowStepName,hl(Y,xe.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${xe.status}`,"data-testid":`workflow-result-badge-${xe.workflowStepId}`,children:YT(xe.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[xe.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",XT(xe.startedAt)]}),xe.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:QT(xe.startedAt,xe.completedAt)})]}),xe.status==="pending"&&xe.startedAt?t.jsx(eP,{entries:S,startedAt:xe.startedAt,stepId:xe.workflowStepId}):xe.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:()=>N(xe.workflowStepId),"data-testid":`workflow-result-toggle-${xe.workflowStepId}`,children:ie?"Hide output":"Show output"}),!ie&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${xe.workflowStepId}`,children:ZT(xe.output)}),ie&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(xe.workflowStepId),"data-testid":`workflow-result-mode-toggle-${xe.workflowStepId}`,title:(m[xe.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[xe.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>z(xe.workflowStepId),"data-testid":`workflow-result-expand-${xe.workflowStepId}`,title:"Expand output",children:t.jsx(fc,{size:12})})]})]}),ie&&t.jsx("div",{className:`workflow-result-output${(m[xe.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${xe.workflowStepId}`,children:(m[xe.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],components:Gp,children:xe.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:xe.output})})]}):null]},`${xe.workflowStepId}-${Ne}`)})]})},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":y?"Done editing workflow steps":"Edit workflow steps",title:y?"Done":"Edit",children:y?t.jsxs(t.Fragment,{children:[t.jsx(js,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(qs,{size:14}),"Edit"]})}):null,P=!s&&!D&&K,$=r&&D;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[P?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:[Z.length," step",Z.length===1?"":"s"]})]}),M]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Z.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,hl(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."}),ne()]}):t.jsxs(t.Fragment,{children:[$&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),M]}),F(),ne()]}),f&&(()=>{const k=n.find(je=>je.workflowStepId===f);if(!k)return null;const J=m[k.workflowStepId]??"markdown",ce=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:je=>{je.target===je.currentTarget&&E()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:k.workflowStepName}),hl(ce,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:()=>R(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:J==="markdown"?"Switch to plain text":"Switch to markdown",children:J==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(un,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${J==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:J==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],components:Gp,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:k.output})})})]})})})()]})}function nP(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const sP=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function iP(e){return e!==void 0&&e!=="online"}function aP({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),ql().then(E=>{o(E)}).catch(E=>{u(Ee(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const x=i.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),y=i.useMemo(()=>[...r].sort((E,I)=>E.name.localeCompare(I.name)),[r]),b=n,v=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",j=v?x.get(v):void 0,C=j?`${j.name} (${j.type})`:v?`${v} (node unavailable or unknown)`:"Local (no routing configured)",w=e.column==="in-progress"||sP.has(e.status),N=w||f||l,R=i.useCallback(async E=>{if(E===m)return;const I=e.id,O=m;h(E),p(!0);try{const U=await Hs(I,{nodeId:E||null});if(g.current!==I)return;h(U.nodeId??""),a?.(U),s(E?"Node override updated":"Node override cleared","success")}catch(U){if(g.current!==I)return;h(O),s(Ee(U)||"Failed to update node override","error")}finally{g.current===I&&p(!1)}},[s,a,m,e.id]),z=i.useCallback(()=>{R("")},[R]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(Oa,{status:j.status,compact:!0}):null,C,iP(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:nP(b?.unavailableNodePolicy)})]})]}),w&&v?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:N,onChange:E=>{R(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),y.map(E=>t.jsxs("option",{value:E.id,title:`Status: ${E.status}`,children:[E.name," (",E.type,") — ",E.status]},E.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:z,children:"Clear override"})]}):null]})]})}const rP=/^[a-zA-Z0-9_-]{1,64}$/,oP=200;function Jp(e){return e?new Date(e).toLocaleString():""}function lP(e,n=oP){return e.length<=n?e:e.substring(0,n)+"…"}function cP({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,y]=i.useState(""),[b,v]=i.useState(null),[S,j]=i.useState([]),[C,w]=i.useState(!1),[N,R]=i.useState(!1),[z,E]=i.useState(""),[I,O]=i.useState(""),[U,A]=i.useState(!1),[D,K]=i.useState(null),[Z,ne]=i.useState(null),[F,M]=i.useState(!1),P=i.useCallback(async()=>{try{const Y=await Wj(e,a);l(Y)}catch(Y){n(Ee(Y)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{P()},[P]);async function $(Y){u===Y.key?(m(null),f(""),g(null),y(""),v(null),j([]),M(!1)):(m(Y.key),f(Y.content),g(null),y(""),v(null),j([]),M(!1))}async function k(Y){if(b===Y)v(null),j([]);else{v(Y),w(!0);try{const ie=await Kj(e,Y,a);j(ie)}catch(ie){n(Ee(ie)||"Failed to load revisions","error")}finally{w(!1)}}}function J(){u&&(g(u),y(h))}function ce(){g(null),y("")}async function je(){if(!(!p||!x.trim())){A(!0);try{await Fm(e,p,x,{},a),g(null),y(""),await P();const Y=o.find(ie=>ie.key===p);Y&&f(Y.content),n("Document saved","success")}catch(Y){n(Ee(Y)||"Failed to save document","error")}finally{A(!1)}}}async function He(){const Y=z.trim(),ie=I.trim();if(!Y){n("Document key is required","error");return}if(!rP.test(Y)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!ie){n("Content is required","error");return}A(!0);try{await Fm(e,Y,ie,{},a),R(!1),E(""),O(""),await P(),n("Document created","success")}catch(ee){n(Ee(ee)||"Failed to create document","error")}finally{A(!1)}}async function xe(Y){K(Y);try{await Gj(e,Y,a),ne(null),K(null),u===Y&&(m(null),f("")),b===Y&&(v(null),j([])),await P(),n("Document deleted","success")}catch(ie){n(Ee(ie)||"Failed to delete document","error")}finally{K(null)}}function Ne(Y){f(Y.content),g(null),y("")}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"}),N&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:z,onChange:Y=>E(Y.target.value),placeholder:"e.g., plan, notes, research",disabled:U}),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:I,onChange:Y=>O(Y.target.value),rows:6,placeholder:"Enter document content…",disabled:U})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(!1),E(""),O("")},disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void He(),disabled:U||!z.trim()||!I.trim(),children:U?"Creating…":"Create"})]})]}),o.length===0&&!N?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(Y=>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(ua,{size:14}),t.jsx("span",{className:"task-document-key",children:Y.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",Y.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:Y.author}),t.jsx("span",{className:"task-document-timestamp",children:Jp(Y.updatedAt||Y.createdAt)})]})]}),u===Y.key&&p!==Y.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(ie=>!ie),"aria-label":F?"Switch to plain text":"Switch to markdown","aria-pressed":F,title:F?"Switch to plain text":"Switch to markdown",children:F?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:F?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===Y.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),C?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(ie=>ie.revision<Y.revision).sort((ie,ee)=>ee.revision-ie.revision).map(ie=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>Ne(ie),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ie.revision]}),t.jsx("span",{className:"revision-author",children:ie.author}),t.jsx("span",{className:"revision-timestamp",children:Jp(ie.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:lP(ie.content,100)})]},ie.id))})]})]}),p===Y.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:x,onChange:ie=>y(ie.target.value),rows:10,disabled:U}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ce,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void je(),disabled:U||!x.trim(),children:U?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(Y),children:u===Y.key?t.jsxs(t.Fragment,{children:[t.jsx(Pi,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(pn,{size:14})," Expand"]})}),u===Y.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(Y.key),children:[t.jsx(Pa,{size:14})," History"]}),r&&p!==Y.key&&t.jsx("button",{className:"btn btn-sm",onClick:J,children:"Edit"}),r&&(Z===Y.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 xe(Y.key),disabled:D===Y.key,children:D===Y.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>ne(null),disabled:D===Y.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>ne(Y.key),children:t.jsx(_n,{size:14})}))]})]})]},Y.key))}),r&&!N&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>R(!0),children:[t.jsx(Mn,{size:14})," New Document"]})]})}function pl(e){return e.toLocaleString()}function vd(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function Zr(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 dP(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=Fb(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 uP({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=Lb(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,x)=>g+(x.durationMs??0),0),c=Ob(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=dP(s?.workflowStepResults??[]),f=zb(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:Zr(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:Zr(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:Zr(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} (${Zr(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} (${Zr(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 ${vd(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:pl(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:pl(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:pl(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:pl(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:vd(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:vd(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const gm=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function mP(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const a=s.text.match(/^Executor using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function hP(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const a=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function lv(e){const n=e?.runtimeConfig??void 0,s=typeof n?.model=="string"?n.model.trim():"";if(s){const o=s.indexOf("/");if(o>0&&o<s.length-1)return{provider:s.slice(0,o),modelId:s.slice(o+1)}}const a=typeof n?.modelProvider=="string"?n.modelProvider.trim():"",r=typeof n?.modelId=="string"?n.modelId.trim():"";return{provider:a||void 0,modelId:r||void 0}}function pP(e,n,s,a){const r=mP(n);if(r)return r;if(gm.has(e.status??"")||e.column==="in-progress"){const o=lv(s);if(o.provider&&o.modelId)return o}return Cb(e,a)}function fP(e,n,s,a){const r=hP(n);if(r)return r;if(gm.has(e.status??"")||e.column==="in-progress"){const o=lv(s);if(o.provider&&o.modelId)return o}return Eb(e,a)}function gP(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 bP(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=gP(n);return a||_b(e,s)}function xP(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 yd(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(void 0,{month:"short",day:"numeric"})}function vP(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wd(e,n){return e.length>n?e.slice(0,n)+"…":e}function Yp(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function kd(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function jd(e){return e.trim()}function yP(e){const n=e.trim();return n.length>0?n:void 0}function Ui(e){return typeof e=="string"&&pa.includes(e)?e:Ds}function Hi(e){return e==="fast"?"fast":"standard"}function wP(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function kP(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 jP=i.lazy(()=>Sn(()=>import("./AgentDetailView-DwLmRXTY.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function NP(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:wP(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:kP(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 Nd=200,SP=new Set(["triage","todo"]),CP=new Set(["triage","todo","in-progress","in-review"]);function cv({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:y}){const[b,v]=i.useState(p),[S,j]=i.useState(()=>"prompt"in e?e:null),[C,w]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){j(e),w(!1);return}let Q=!1;return w(!0),j(null),La(e.id,n).then(Te=>{Q||(j(Te),w(!1))}).catch(()=>{Q||w(!1)}),()=>{Q=!0}},[e.id,n]);const N=S?{...S,...e,prompt:S.prompt,log:S.log}:{...e,prompt:""},R=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[z,E]=i.useState(null),[I,O]=i.useState(null),U=NP(N,{sourceAgentName:z?.name});i.useEffect(()=>{v(p)},[p]),i.useEffect(()=>{Z(!1)},[e.id]);const[A,D]=i.useState("activity"),[K,Z]=i.useState(!1),[ne,F]=i.useState(e.attachments||[]),[M,P]=i.useState(!1),[$,k]=i.useState(e.dependencies||[]),[J,ce]=i.useState(!1),[je,He]=i.useState(""),[xe,Ne]=i.useState(null),[Y,ie]=i.useState([]),[ee,oe]=i.useState(!1),[W,L]=i.useState(!1),[pe,fe]=i.useState(!1),[B,ve]=i.useState(!1),[Fe,ae]=i.useState(!1),[qe,Pe]=i.useState(N.prompt||""),[nt,Be]=i.useState(""),[de,Ie]=i.useState(!1),[$e,st]=i.useState(""),[Ue,me]=i.useState(!1),[re,_e]=i.useState(!1),[xt,dt]=i.useState(e.title||""),[Qe,vt]=i.useState(e.description||""),[Ae,Je]=i.useState(e.dependencies||[]),[ct,Nt]=i.useState(e.branch??""),[yt,Se]=i.useState(e.baseBranch??""),[G,ge]=i.useState(""),[pt,ke]=i.useState(""),[tt,Rt]=i.useState(""),[Re,be]=i.useState(""),[at,ot]=i.useState("default"),[gt,St]=i.useState(void 0),[Lt,Yt]=i.useState(Ds),[tn,mn]=i.useState(e.nodeId),[Qt,yn]=i.useState(Hi(e.executionMode)),[Gt,on]=i.useState(""),[sn,ln]=i.useState(e.enabledWorkflowSteps||[]),[Wt,ye]=i.useState(e.sourceIssue?.provider??""),[Le,Ke]=i.useState(e.sourceIssue?.repository??""),[ut,Ve]=i.useState(e.sourceIssue?.externalIssueId??""),[Pt,Ot]=i.useState(e.sourceIssue?.url??""),[bt,Dt]=i.useState([]),[Ft,Ht]=i.useState(!1),[rn,Xt]=i.useState(Ui(e.priority)),[an,Me]=i.useState(!1),[it,kt]=i.useState(Hi(e.executionMode)),[$t,se]=i.useState(!1),te=i.useRef(!1),[De,ft]=i.useState(!1),[qt,zt]=i.useState(!1),[Pn,he]=i.useState(!1),[mt,ht]=i.useState(!1),[wt,Xe]=i.useState(e.githubTracking?.repoOverride??""),[Et,Zt]=i.useState(null),[le,lt]=i.useState(null),[nn,Rn]=i.useState(!1),Hn=i.useRef(null),wn=i.useRef(null),rs=i.useRef(null),{getSlotsForId:_s}=yb(n),Ut=_s("task-detail-tab").map((Q,Te)=>({entry:Q,tabId:`plugin-${Q.pluginId}-${Te}`})),xs=typeof b=="string"&&b.startsWith("plugin-")?Ut.find(Q=>Q.tabId===b)??null:null;i.useEffect(()=>(te.current=!0,()=>{te.current=!1}),[]);const[xn,Xn]=i.useState(void 0),[$n,vs]=i.useState(null),[ms,hs]=i.useState([]),[Jn,ps]=i.useState(!1),[Ns,Yn]=i.useState(e.enabledWorkflowSteps||[]),ys=e.column==="in-progress"||gm.has(e.status);i.useEffect(()=>{dt(e.title||""),vt(e.description||""),Nt(e.branch??""),Se(e.baseBranch??""),ye(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),Ve(e.sourceIssue?.externalIssueId??""),Ot(e.sourceIssue?.url??""),yn(Hi(e.executionMode)),he(!1),ht(!1),Xe(e.githubTracking?.repoOverride??""),Zt(null),lt(null),_e(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,e.githubTracking]),i.useEffect(()=>{Yn(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Xt(Ui(e.priority))},[e.id,e.priority]),i.useEffect(()=>{kt(Hi(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{Et!==null&&e.githubTracking?.enabled===!0===Et&&Zt(null)},[Et,e.githubTracking?.enabled]),i.useEffect(()=>{let Q=!1;return gc(n).then(Te=>{Q||Xn(Te)}).catch(()=>{}),Yi().then(Te=>{Q||vs(Te)}).catch(()=>{Q||vs(null)}),()=>{Q=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let Q=!1;return ps(!0),TS(e.id,n).then(Te=>{Q||hs(Te)}).catch(Te=>{Q||h(`Failed to load workflow results: ${Ee(Te)}`,"error")}).finally(()=>{Q||ps(!1)}),()=>{Q=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const Q=n?`?projectId=${encodeURIComponent(n)}`:"",Te=_t=>{try{const Jt=JSON.parse(_t.data);Jt.id===e.id&&Array.isArray(Jt.workflowStepResults)&&hs(Jt.workflowStepResults)}catch{}};return hi(`/api/events${Q}`,{events:{"task:updated":Te}})},[b,e.id,n]),i.useEffect(()=>{J||He("")},[J]),i.useEffect(()=>{if(!e.assignedAgentId){Ne(null);return}const Q=Y.find(_t=>_t.id===e.assignedAgentId);if(Q){Ne(Q);return}let Te=!1;return au(e.assignedAgentId,n).then(_t=>{Te||Ne(_t)}).catch(()=>{Te||Ne(null)}),()=>{Te=!0}},[e.assignedAgentId,n,Y]),i.useEffect(()=>{if(!e.sourceAgentId){E(null);return}const Q=Y.find(_t=>_t.id===e.sourceAgentId);if(Q){E(Q);return}let Te=!1;return Promise.resolve(au(e.sourceAgentId,n)).then(_t=>{Te||E(_t??null)}).catch(()=>{Te||E(null)}),()=>{Te=!0}},[e.sourceAgentId,n,Y]),i.useEffect(()=>{oe(!1)},[e.id]),i.useEffect(()=>{if(!(De||qt))return;const Te=_t=>{const Jt=_t.target,Qn=Hn.current?.contains(Jt),Bi=rs.current?.contains(Jt);!Qn&&De&&ft(!1),!Bi&&qt&&zt(!1)};return document.addEventListener("mousedown",Te),()=>document.removeEventListener("mousedown",Te)},[De,qt]),i.useEffect(()=>{if(!(De||qt))return;const Te=_t=>{_t.key==="Escape"&&(_t.stopPropagation(),De&&ft(!1),qt&&zt(!1))};return document.addEventListener("keydown",Te),()=>document.removeEventListener("keydown",Te)},[De,qt]),i.useEffect(()=>{ae(!1),Pe(N.prompt||""),Be("")},[e.id,N.prompt]);const ws=SP.has(e.column)&&!Ft,Ms=CP.has(e.column)&&!Ft,X=Et??e.githubTracking?.enabled===!0,_=e.githubTracking?.issue,ue=Ms||X||!!_,Ce=_?"Linked":X?"Enabled":"Disabled",We=rv(xn??null,$n),At=wt.trim(),q=i.useCallback(async()=>{if(!Ms||nn)return;const Q=!X;Zt(Q),Rn(!0);try{const Te=await Hs(e.id,{githubTracking:{enabled:Q}},n);m?.(Te)}catch(Te){Zt(e.githubTracking?.enabled===!0),h(`Failed to update ${e.id}: ${Ee(Te)}`,"error")}finally{te.current&&Rn(!1)}},[h,Ms,X,nn,m,n,e.githubTracking?.enabled,e.id]),we=i.useCallback(async()=>{if(!(!Ms||nn)){if(At.length>0&&!vc.test(At)){lt("Repository override must be in owner/repo format");return}lt(null),Rn(!0);try{const Q=await Hs(e.id,{githubTracking:{repoOverride:At.length>0?At:null}},n);m?.(Q)}catch(Q){h(`Failed to update ${e.id}: ${Ee(Q)}`,"error")}finally{te.current&&Rn(!1)}}},[h,Ms,At,nn,m,n,e.id]),Oe=i.useCallback(async()=>{if(!(!X||_||nn)){Rn(!0);try{const Q=await Hs(e.id,{githubTracking:{enabled:!0}},n);m?.(Q),h("Requested GitHub tracking issue creation","info")}catch(Q){h(`Failed to update ${e.id}: ${Ee(Q)}`,"error")}finally{te.current&&Rn(!1)}}},[h,_,X,nn,m,n,e.id]),It=i.useCallback(()=>{if(!ws)return;_e(!0),dt(e.title||""),vt(e.description||""),Je(e.dependencies||[]),Nt(e.branch??""),Se(e.baseBranch??"");const Q=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",Te=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",_t=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";ge(Q),ke(Te),Rt(_t),be(e.thinkingLevel??""),mn(e.nodeId),ot(Q||Te||_t?"custom":"default"),on(""),ln(e.enabledWorkflowSteps||[]),yn(Hi(e.executionMode)),ye(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),Ve(e.sourceIssue?.externalIssueId??""),Ot(e.sourceIssue?.url??""),Dt([]),St(e.reviewLevel),Yt(Ui(e.priority))},[ws,e]),Kt=i.useCallback(()=>{_e(!1),dt(e.title||""),vt(e.description||""),Je(e.dependencies||[]),Nt(e.branch??""),Se(e.baseBranch??""),mn(e.nodeId),ye(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),Ve(e.sourceIssue?.externalIssueId??""),Ot(e.sourceIssue?.url??""),Yt(Ui(e.priority)),yn(Hi(e.executionMode)),bt.forEach(Q=>URL.revokeObjectURL(Q.previewUrl)),Dt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,bt]),[fn,An]=i.useState("idle"),jn=i.useRef(null),En=i.useRef(0),ts=i.useCallback(Q=>{const Te={},_t=xt.trim(),Jt=Qe.trim();_t&&_t!==(e.title??"")&&(Te.title=_t),Q&&Jt&&Jt!==(e.description??"")&&(Te.description=Jt),Yp(Ae,e.dependencies??[])||(Te.dependencies=Ae),Yp(sn,e.enabledWorkflowSteps??[])||(Te.enabledWorkflowSteps=sn);const Qn=ct.trim()||null,Bi=e.branch??null;Qn!==Bi&&(Te.branch=Qn);const km=yt.trim()||null,sy=e.baseBranch??null;km!==sy&&(Te.baseBranch=km);const jm=kd(G),iy=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";G!==iy&&(Te.modelProvider=jm?.provider??null,Te.modelId=jm?.modelId??null);const Nm=kd(pt),ay=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";pt!==ay&&(Te.validatorModelProvider=Nm?.provider??null,Te.validatorModelId=Nm?.modelId??null);const Sm=kd(tt),ry=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";tt!==ry&&(Te.planningModelProvider=Sm?.provider??null,Te.planningModelId=Sm?.modelId??null);const oy=e.thinkingLevel??"";Re!==oy&&(Te.thinkingLevel=Re!==""?Re:null),(e.nodeId??void 0)!==tn&&(Te.nodeId=tn??null),gt!==e.reviewLevel&&(Te.reviewLevel=gt),Lt!==Ui(e.priority)&&(Te.priority=Lt),Qt!==Hi(e.executionMode)&&(Te.executionMode=Qt==="fast"?"fast":null);const _c=jd(Wt),Mc=jd(Le),Qo=jd(ut),Ac=yP(Pt);if(_c.length===0&&Mc.length===0&&Qo.length===0&&!Ac)e.sourceIssue&&(Te.sourceIssue=null);else{if(!_c||!Mc||!Qo)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const ly=Number.parseInt(Qo,10),Rc=e.sourceIssue?.issueNumber??ly;if(!Number.isFinite(Rc)||Rc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const er={provider:_c,repository:Mc,externalIssueId:Qo,issueNumber:Rc,...Ac?{url:Ac}:{}},tr=e.sourceIssue;(!tr||tr.provider!==er.provider||tr.repository!==er.repository||tr.externalIssueId!==er.externalIssueId||tr.issueNumber!==er.issueNumber||(tr.url??void 0)!==er.url)&&(Te.sourceIssue=er)}return{updates:Te,error:null}},[yt,ct,Ae,Qe,Qt,G,tn,tt,Lt,gt,sn,ut,Wt,Le,Pt,Re,xt,pt,e]),Ln=i.useCallback(async Q=>{const{updates:Te,error:_t}=ts(Q);if(!Te)return An("error"),_t&&h(`Failed to update ${e.id}: ${_t}`,"error"),!1;if(Object.keys(Te).length===0)return!0;const Jt=++En.current;Ht(!0),An("saving");try{const Qn=await Hs(e.id,Te,n);return Jt!==En.current?void 0:(m?.(Qn),An("saved"),!0)}catch(Qn){return Jt===En.current&&(An("error"),h(`Failed to update ${e.id}: ${Ee(Qn)}`,"error")),!1}finally{te.current&&Jt===En.current&&Ht(!1)}},[h,ts,m,n,e.id]),os=i.useCallback(async Q=>{await Ln(!0)},[Ln]),fs=i.useCallback(async()=>{await Ln(!0)&&(h(`Updated ${e.id}`,"success"),te.current&&_e(!1))},[h,Ln,e.id]);i.useEffect(()=>{if(re)return jn.current&&clearTimeout(jn.current),jn.current=setTimeout(()=>{Ln(!1)},700),()=>{jn.current&&(clearTimeout(jn.current),jn.current=null)}},[re,xt,Ae,ct,yt,G,pt,tt,Re,tn,gt,Lt,Qt,sn,Wt,Le,ut,Pt,Ln]);const ns=i.useCallback(async Q=>{const Te=Ui(Q),_t=Ui(e.priority);if(Te===_t){Xt(_t);return}const Jt=rn;Xt(Te),Me(!0);try{const Qn=await Hs(e.id,{priority:Te},n);Xt(Ui(Qn.priority)),m?.(Qn),h(`Priority updated to ${Ui(Qn.priority)}`,"success")}catch(Qn){Xt(Jt),h(`Failed to update ${e.id}: ${Ee(Qn)}`,"error")}finally{te.current&&Me(!1)}},[e.id,e.priority,n,rn,m,h]),Zn=i.useCallback(async()=>{const Te=Hi(e.executionMode)==="fast"?"standard":"fast",_t=it;kt(Te),se(!0);try{const Jt=await Hs(e.id,{executionMode:Te==="fast"?"fast":null},n),Qn=Hi(Jt.executionMode);kt(Qn),m?.(Jt),h(`Execution mode updated to ${Qn}`,"success")}catch(Jt){kt(_t),h(`Failed to update ${e.id}: ${Ee(Jt)}`,"error")}finally{te.current&&se(!1)}},[e.id,e.executionMode,n,it,m,h]),es=i.useCallback(Q=>{re&&(Q.key==="Escape"?(Q.preventDefault(),Kt()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),fs()))},[re,Kt,fs]);i.useEffect(()=>{if(re)return document.addEventListener("keydown",es),()=>document.removeEventListener("keydown",es)},[re,es]);const Ss=i.useRef(null),{nodes:ls}=yc(),{confirm:ss}=pi(),Zs=i.useCallback(async()=>{if(!(!ws||!_||nn||!await ss({title:"Unlink GitHub issue?",message:"This stops Fusion from syncing with the linked GitHub issue. The issue itself will not be modified.",confirmLabel:"Unlink",danger:!0}))){Rn(!0);try{const Te=await Hs(e.id,{githubTracking:{issue:null}},n);m?.(Te),h("GitHub issue unlinked","success")}catch(Te){h(`Failed to update ${e.id}: ${Ee(Te)}`,"error")}finally{te.current&&Rn(!1)}}},[h,ws,ss,_,nn,m,n,e.id]),{entries:Si,loading:ga,loadMore:Va,hasMore:Wa,total:Ka,loadingMore:oi}=tv(e.id,b==="logs"&&A==="agent-log",n),gn=i.useCallback(()=>{y?.()},[y]);i.useEffect(()=>{if(x)return;const Q=Te=>{Te.key==="Escape"&&!re&&gn()};return document.addEventListener("keydown",Q),()=>document.removeEventListener("keydown",Q)},[x,gn,re]);const Fi=i.useCallback(async Q=>{try{const Te=e.steps.some(Qn=>Qn.status!=="pending"),_t=(Q==="todo"||Q==="triage")&&Te;let Jt;if(_t){if(await ss({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Jt={preserveProgress:!0};else if(!await ss({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,Q,Jt),gn(),h(`Moved to ${ds[Q]}`,"success")}catch(Te){h(Ee(Te),"error")}},[e.id,e.steps,r,gn,h,ss]),ea=i.useCallback(async()=>{if(await ss({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),gn(),h(`Deleted ${e.id}`,"info")}catch(Te){const _t=Ku(Te);if(!_t||_t.dependentIds.length===0){h(Ee(Te),"error");return}const Jt=_t.dependentIds.join(", ");if(!await ss({title:"Force Delete Task",message:`${e.id} is a dependency of ${Jt}.
|
|
685
|
+
|
|
686
|
+
Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),gn(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Bi){h(Ee(Bi),"error")}}},[e.id,o,gn,h,ss]),ba=i.useCallback(async()=>{await ss({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(gn(),h(`Merging ${e.id}...`,"info"),l(e.id).then(Te=>{const _t=Te.merged?`Merged ${e.id} (branch: ${Te.branch})`:`Closed ${e.id} (${Te.error||"no branch to merge"})`;h(_t,"success")}).catch(Te=>{h(Ee(Te),"error")}))},[e.id,l,gn,h,ss]),Ga=i.useCallback(()=>{c&&(gn(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(Q=>{h(Ee(Q),"error")}))},[e.id,c,gn,h]),xa=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(gn(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(Q=>{h(Ee(Q),"error")}))},[e.id,d,gn,h]),va=i.useCallback(async()=>{if(!(!u||!await ss({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const Te=await u(e.id);gn(),h(`Duplicated ${e.id} → ${Te.id}`,"success")}catch(Te){h(Ee(Te),"error")}},[e.id,u,gn,h,ss]),ya=i.useCallback(async()=>{try{e.paused?(await $j(e.id,n),h(`Unpaused ${e.id}`,"success")):(await ab(e.id,n),h(`Paused ${e.id}`,"success")),gn()}catch(Q){h(Ee(Q),"error")}},[e.id,e.paused,gn,h]),Ja=i.useCallback(async()=>{try{await Fj(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),gn()}catch(Q){h(Ee(Q),"error")}},[e.id,gn,h]),wa=i.useCallback(async()=>{if(await ss({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await zj(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),gn()}catch(Te){h(Ee(Te),"error")}},[e.id,gn,h,ss]),Fr=i.useCallback(async()=>{if(await ss({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await Qj(e.id,n),gn(),h(`Replanning ${e.id}...`,"info")}catch(Te){h(Ee(Te),"error")}},[e.id,n,gn,h,ss]),ka=i.useCallback(()=>{Ie(!0),st("")},[]),Us=i.useCallback(()=>{ft(!1),zt(!1)},[]),Ci=i.useCallback(Q=>{Us(),Fi(Q)},[Us]),ei=i.useCallback(Q=>{Us(),Q()},[Us]),ta=i.useCallback(()=>{Us(),ba()},[Us,ba]),ja=i.useCallback(()=>{Ie(!1),st(""),me(!1)},[]),zr=i.useCallback(async()=>{if(!$e.trim()){h("Please enter feedback describing what needs refinement","error");return}if($e.length>2e3){h("Feedback must be 2000 characters or less","error");return}me(!0);try{const Q=await Xj(e.id,$e.trim(),n);h(`Refinement task created: ${Q.id}`,"success"),gn()}catch(Q){h(Ee(Q),"error")}finally{me(!1)}},[e.id,$e,h,gn]),Ei=i.useCallback(async Q=>{P(!0);try{const Te=await bc(e.id,Q,n);F(_t=>[..._t,Te]),h("Screenshot attached","success")}catch(Te){h(Ee(Te),"error")}finally{P(!1)}},[e.id,h]),Na=i.useCallback(async Q=>{const Te=Q.target.files?.[0];Te&&(await Ei(Te),Ss.current&&(Ss.current.value=""))},[Ei]);i.useEffect(()=>{const Q=Te=>{const _t=Te.clipboardData?.items;if(_t)for(let Jt=0;Jt<_t.length;Jt++){const Qn=_t[Jt];if(Qn.type.startsWith("image/")){const Bi=Qn.getAsFile();if(Bi){Te.preventDefault(),Ei(Bi);return}}}};return document.addEventListener("paste",Q),()=>document.removeEventListener("paste",Q)},[Ei]);const Sa=i.useCallback(Q=>{Q.preventDefault()},[]),zi=i.useCallback(Q=>{Q.preventDefault();const Te=Q.dataTransfer.files;for(let _t=0;_t<Te.length;_t++){const Jt=Te[_t];if(Jt.type.startsWith("image/")){Ei(Jt);return}}},[Ei]),Ya=i.useCallback(async Q=>{try{await Hj(e.id,Q,n),F(Te=>Te.filter(_t=>_t.filename!==Q)),h("Attachment deleted","info")}catch(Te){h(Ee(Te),"error")}},[e.id,h]),Br=i.useCallback(async Q=>{const Te=Ns;Yn(Q);try{const _t=await Hs(e.id,{enabledWorkflowSteps:Q},n);h("Workflow steps updated","success"),m?.(_t)}catch(_t){Yn(Te),h(`Failed to update workflow steps: ${Ee(_t)}`,"error")}},[e.id,n,Ns,m,h]),Qa=i.useCallback(async()=>{L(!0);try{const Q=await Pr(void 0,n);ie(Q),oe(!0)}catch(Q){h(`Failed to load agents: ${Ee(Q)}`,"error"),oe(!1)}finally{L(!1)}},[n,h]),Xa=i.useCallback(async Q=>{try{const Te=await Qm(e.id,Q,n),_t=Y.find(Jt=>Jt.id===Q)??null;Ne(_t||(Jt=>Jt?.id===Q?Jt:null)),oe(!1),m?.(Te),h("Assigned agent updated","success")}catch(Te){h(`Failed to assign agent: ${Ee(Te)}`,"error")}},[e.id,n,Y,m,h]),Za=i.useCallback(async()=>{try{const Q=await Qm(e.id,null,n);Ne(null),oe(!1),m?.(Q),h("Agent unassigned","success")}catch(Q){h(`Failed to unassign agent: ${Ee(Q)}`,"error")}},[e.id,n,m,h]),Ur=i.useCallback(async Q=>{const Te=[...$,Q];k(Te);try{await Hs(e.id,{dependencies:Te},n)}catch(_t){k($),h(Ee(_t),"error")}},[e.id,$,h]),Ye=i.useCallback(async(Q,Te)=>{Q.stopPropagation();const _t=$.filter(Jt=>Jt!==Te);k(_t);try{await Hs(e.id,{dependencies:_t},n)}catch(Jt){k($),h(Ee(Jt),"error")}},[e.id,$,h]),Tt=i.useCallback(async Q=>{try{const Te=await La(Q,n);a(Te)}catch{h(`Failed to load dependency ${Q}`,"error")}},[a,h]),cn=i.useCallback(async Q=>{fe(!0);try{await Hs(N.id,{prompt:Q},n),h("Spec updated","success"),S&&(S.prompt=Q)}catch(Te){throw h(Ee(Te),"error"),Te}finally{fe(!1)}},[N,S,h]),cs=i.useCallback(async Q=>{ve(!0);try{await Yj(e.id,Q,n),h("AI revision requested. Task moved to planning.","success"),gn()}catch(Te){const _t=Ee(Te);_t.includes("done")||_t.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(_t,"error")}finally{ve(!1)}},[e.id,h,gn]),qn=i.useCallback(()=>{ae(!0),Pe(N.prompt||""),Be("")},[N.prompt]),Cs=i.useCallback(()=>{ae(!1),Pe(N.prompt||""),Be("")},[N.prompt]),na=i.useCallback(async()=>{if(qe===(N.prompt||"")){Cs();return}ae(!1);try{await cn(qe)}catch(Q){throw ae(!0),Q}},[qe,N.prompt,cn,Cs]),H=i.useCallback(async()=>{nt.trim()&&await cs(nt.trim())},[nt,cs]),ze=i.useCallback(Q=>{Q.key==="Escape"?(Q.preventDefault(),Cs()):Q.key==="Enter"&&(Q.ctrlKey||Q.metaKey)&&(Q.preventDefault(),na())},[Cs,na]),Ge=s.filter(Q=>Q.id!==e.id&&!$.includes(Q.id)).sort((Q,Te)=>{const _t=Te.createdAt.localeCompare(Q.createdAt);if(_t!==0)return _t;const Jt=parseInt(Q.id.slice(Q.id.lastIndexOf("-")+1),10)||0;return(parseInt(Te.id.slice(Te.id.lastIndexOf("-")+1),10)||0)-Jt}),Nn=i.useMemo(()=>Ju(s),[s]).get(e.id),Vt=i.useMemo(()=>{if(!Nn)return[];const Q=new Set(Nn.staleBlockedByDependentIds);return Nn.dependentIds.map(Te=>{const _t=s.find(Jt=>Jt.id===Te);return{id:Te,label:_t?.title||_t?.description||Te,stale:Q.has(Te)}})},[Nn,s]),kn=xe?.name??e.assignedAgentId??null,Ze=i.useMemo(()=>{const Q=[];return N.modelProvider&&Q.push(N.modelProvider),N.validatorModelProvider&&!Q.includes(N.validatorModelProvider)&&Q.push(N.validatorModelProvider),N.planningModelProvider&&!Q.includes(N.planningModelProvider)&&Q.push(N.planningModelProvider),Q},[N.modelProvider,N.validatorModelProvider,N.planningModelProvider]),rt=ru[e.column]||[],Bt=["todo","in-progress"],In=e.column==="in-review"?Bt:rt,Vn=In[0],ti=In.slice(1),Tn=ti.length>0,Wn=i.useCallback(()=>{ft(!1),wn.current?.focus()},[]),dn=i.useCallback(Q=>{if(!Tn){Vn&&Ci(Vn);return}const Te=Q.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(Q.target instanceof Element&&Q.target.closest(".detail-move-btn__arrow")||Te&&Q.clientX>0&&Q.clientX>=Te.getBoundingClientRect().left)){ft(Jt=>!Jt),zt(!1);return}Vn&&Ci(Vn)},[Tn,Vn,Ci]),Gs=i.useCallback(Q=>{!Tn||!(Q.key==="ArrowDown"||Q.altKey&&Q.key==="ArrowDown")||(Q.preventDefault(),ft(!0),zt(!1))},[Tn]),Ps=i.useCallback(Q=>{Q.key==="Escape"&&(Q.preventDefault(),Q.stopPropagation(),Wn())},[Wn]);i.useEffect(()=>{if(!De)return;Hn.current?.querySelector(".detail-move-menu-item")?.focus()},[De]);const fi={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},Ca=e.status?fi[e.status]:void 0,Hr=xn?.mergeStrategy??"direct",ny=xn?.autoMerge??!1,wm=Hr==="pull-request"&&!ny;let Yo="Merge & Close";return wm&&!Ca&&(e.prInfo?e.prInfo.status==="open"?Yo="Check PR Status":e.prInfo.status==="merged"&&(Yo="Finish & Close"):Yo="Start PR Review"),t.jsxs("div",{className:x?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:Sa,onDrop:zi,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:[!re&&ws&&t.jsx("button",{className:"modal-edit-btn",onClick:It,title:"Edit task","aria-label":"Edit task",children:t.jsx(qs,{size:14})}),!x&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:gn,"aria-label":"Back to task list",type:"button",children:[t.jsx(Ua,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!x&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:gn,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&A==="agent-log"&&!re?" detail-body--agent-log":""}`,children:[re?t.jsx("div",{className:"modal-edit-form",children:t.jsx(ov,{mode:"edit",title:xt,onTitleChange:dt,description:Qe,onDescriptionChange:vt,dependencies:Ae,onDependenciesChange:Je,branch:ct,onBranchChange:Nt,baseBranch:yt,onBaseBranchChange:Se,executorModel:G,onExecutorModelChange:ge,validatorModel:pt,onValidatorModelChange:ke,planningModel:tt,onPlanningModelChange:Rt,thinkingLevel:Re,onThinkingLevelChange:be,presetMode:at,onPresetModeChange:ot,selectedPresetId:Gt,onSelectedPresetIdChange:on,selectedWorkflowSteps:sn,onWorkflowStepsChange:ln,pendingImages:bt,onImagesChange:Dt,tasks:s.filter(Q=>Q.id!==e.id),projectId:n,disabled:Ft,addToast:h,isActive:re,onAutoSaveDescription:os,reviewLevel:gt,onReviewLevelChange:St,priority:Lt,onPriorityChange:Yt,nodeId:tn,onNodeIdChange:mn,nodeOptions:ls,nodeOverrideDisabled:ys,nodeOverrideDisabledReason:ys?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:Qt,onExecutionModeChange:yn,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:Wt,onChange:Q=>ye(Q.target.value),disabled:Ft,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Le,onChange:Q=>Ke(Q.target.value),disabled:Ft,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:ut,onChange:Q=>Ve(Q.target.value),disabled:Ft,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:Pt,onChange:Q=>Ot(Q.target.value),disabled:Ft,"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 Q=e.title||e.description||e.id,Te=!K&&Q.length>Nd;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:Te?Q.slice(0,Nd)+"…":Q}),Q.length>Nd&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>Z(!K),children:K?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:[t.jsxs("div",{className:"detail-meta-inline-controls","data-testid":"detail-meta-inline-controls",children:[t.jsxs("label",{className:`card-priority-badge card-priority-badge--${rn} detail-priority-chip ${an?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:rn,onChange:Q=>{ns(Q.target.value)},disabled:an,"aria-label":"Task priority",children:pa.map(Q=>t.jsx("option",{value:Q,children:Q},Q))})]}),t.jsxs("button",{type:"button",className:`btn btn-sm detail-execution-mode-toggle ${it==="fast"?"detail-execution-mode-toggle--fast":""} ${$t?"detail-execution-mode-toggle--saving":""}`,onClick:()=>{Zn()},disabled:$t,"aria-label":`Execution mode: ${it}`,"aria-pressed":it==="fast",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{children:it==="fast"?"Fast":"Standard"})]})]}),U&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Fs,{"aria-hidden":"true"}),t.jsxs("span",{children:[N.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",U.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>O(U.sourceAgentId),children:U.label}):U.label]}):t.jsxs(t.Fragment,{children:["Created via ",U.label]}),U.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Tt(U.parentTaskId),children:U.parentTaskId})]}),U.contextInfo?` (${U.contextInfo})`:""]})]}),(e.prInfo?.number||e.mergeDetails?.prNumber)&&t.jsxs("div",{className:"detail-provenance detail-pr-link-row",children:[t.jsx(Fs,{"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]})]})]}),t.jsxs("div",{className:"detail-timestamps","aria-label":"Task timestamps",children:[t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Created"})," ",t.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toLocaleString(),children:yd(e.createdAt)})]}),t.jsx("span",{className:"detail-timestamp-separator","aria-hidden":"true",children:"·"}),t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Updated"})," ",t.jsx("time",{dateTime:e.updatedAt,title:new Date(e.updatedAt).toLocaleString(),children:yd(e.updatedAt)})]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!re&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>v("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>v("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>v("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="review"?" detail-tab-active":""}`,onClick:()=>v("review"),children:"Review"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>v("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>v("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>v("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>v("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>v("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>v("routing"),children:"Routing"}),Ut.map(({entry:Q,tabId:Te})=>t.jsx("button",{className:`detail-tab${b===Te?" detail-tab-active":""}`,onClick:()=>v(Te),children:Q.slot.label},`plugin-tab-${Q.pluginId}-${Te}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(tP,{taskId:e.id,results:ms,loading:Jn,enabledWorkflowSteps:Ns,canEdit:ws,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Br})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(IT,{task:e,addToast:h,onTaskUpdated:m,settings:xn})}):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:()=>D("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${A==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>D("agent-log"),children:"Agent Log"})]}),A==="agent-log"?t.jsx(ET,{entries:Si,loading:ga,executorModel:pP(e,Si,xe,xn),validatorModel:fP(e,Si,xe,xn),planningModel:bP(e,Si,xn),hasMore:Wa,onLoadMore:Va,loadingMore:oi,totalCount:Ka}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),N.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",N.log.length," activity entries."]}):null,N.log&&N.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...N.log].reverse().map((Q,Te)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:yd(Q.timestamp)}),t.jsx("span",{className:"detail-log-action",children:Q.action})]}),Q.outcome&&t.jsx("div",{className:"detail-log-outcome",children:Q.outcome})]},Te))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(WT,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="review"?t.jsx(BT,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="comments"?t.jsx(LT,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx(cP,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:ws}):xs?t.jsx("div",{className:"detail-section",children:t.jsx(la,{slotId:"task-detail-tab",projectId:n,pluginIds:[xs.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(uP,{tokenUsage:N.tokenUsage,loading:C,task:N})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(aP,{task:e,settings:xn,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(ki,{remarkPlugins:[ji],children:e.summary})})]}),t.jsx(HT,{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(Fs,{"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":Pn,"aria-label":Pn?"Collapse source issue details":"Expand source issue details",onClick:()=>he(Q=>!Q),children:t.jsx(On,{size:16,className:Pn?"detail-source-chevron--expanded":void 0})})]}),Pn&&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)"})})]})]})]}),ue&&t.jsxs("div",{className:"detail-section detail-github-tracking-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:"GitHub tracking"}),t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub tracking status",children:[t.jsx(Fs,{"aria-hidden":"true"}),t.jsx("span",{children:Ce})]}),!_&&t.jsx("span",{className:"detail-source-empty",children:X?"Issue not yet created":"Tracking is currently disabled"})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":mt,"aria-label":mt?"Collapse GitHub tracking details":"Expand GitHub tracking details",onClick:()=>ht(Q=>!Q),children:t.jsx(On,{size:16,className:mt?"detail-source-chevron--expanded":void 0})})]}),mt&&t.jsxs("div",{className:"detail-github-tracking-content",children:[_&&t.jsxs("dl",{className:"detail-source-grid detail-github-tracking-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Issue"}),t.jsx("dd",{children:_.url?t.jsx("a",{className:"detail-source-link",href:_.url,target:"_blank",rel:"noopener noreferrer",children:`${_.owner}/${_.repo}#${_.number}`}):t.jsx("span",{children:`${_.owner}/${_.repo}#${_.number}`})})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"State"}),t.jsx("dd",{children:t.jsx("span",{className:`detail-github-issue-state ${e.issueInfo?.state==="closed"?"detail-github-issue-state--closed":"detail-github-issue-state--open"}`,children:e.issueInfo?.state??"open"})})]})]}),t.jsxs("div",{className:"detail-github-tracking-controls",children:[!_&&X&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Oe(),disabled:nn,children:"Create tracking issue"}),Ms&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"checkbox-label",htmlFor:"detail-github-tracking-toggle",children:[t.jsx("input",{id:"detail-github-tracking-toggle",type:"checkbox",checked:X,disabled:nn,onChange:()=>void q()}),"Enable GitHub tracking"]}),t.jsxs("div",{className:"detail-github-tracking-repo-row",children:[t.jsx("input",{className:"input",value:wt,onChange:Q=>{Xe(Q.target.value),lt(null)},placeholder:We||"owner/repo"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void we(),disabled:nn,children:"Save"})]}),le&&t.jsx("small",{className:"detail-github-tracking-error",children:le}),_&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Zs(),disabled:nn,children:"Unlink GitHub issue"})]})]})]})]}),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:[Ze.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:Ze.map(Q=>t.jsx(Fn,{provider:Q,size:"sm"},Q))}),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:[kn?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(zn,{size:14}),kn,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void Za(),title:"Unassign agent",children:t.jsx(un,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{ee?oe(!1):Qa()},children:"Assign Agent"}),ee&&t.jsxs("div",{className:"agent-picker-dropdown",children:[W&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!W&&Y.map(Q=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===Q.id?" selected":""}`,onClick:()=>void Xa(Q.id),children:[t.jsx(zn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:Q.name}),t.jsx("span",{className:"agent-picker-role",children:Q.role})]},Q.id)),!W&&Y.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"}),N.steps&&N.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:N.steps.map((Q,Te)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${Q.status}`,"data-tooltip":`${Q.name} (${Q.status})`,style:{backgroundColor:xP(Q.status)}},Te))}),t.jsxs("span",{className:"step-progress-label",children:[N.steps.filter(Q=>Q.status==="done").length,"/",N.steps.length," step",N.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!Fe&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:qn,children:"Edit"})}),Fe?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:qe,onChange:Q=>Pe(Q.target.value),onKeyDown:ze,disabled:pe,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:Cs,disabled:pe,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void na(),disabled:qe===(N.prompt||"")||pe,children:pe?"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:nt,onChange:Q=>Be(Q.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:B,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[nt.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void H(),disabled:!nt.trim()||B,children:B?"Requesting…":"Request AI Revision"})]})]})]}):C?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):N.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],children:N.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"}),ne.length>0?t.jsx("div",{className:"detail-attachments-grid",children:ne.map(Q=>{const Te=Di(`/api/tasks/${e.id}/attachments/${Q.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:Te,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:Te,alt:Q.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[Q.originalName," (",vP(Q.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>Ya(Q.filename),title:"Delete attachment",children:"×"})]},Q.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:Ss,type:"file",accept:"image/*",onChange:Na}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Ss.current?.click(),disabled:M,children:M?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(Q=>{const Te=s.find(Jt=>Jt.id===Q),_t=Te?.title||Te?.description||Q;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Tt(Q),onKeyDown:Jt=>{(Jt.key==="Enter"||Jt.key===" ")&&(Jt.preventDefault(),Tt(Q))},role:"link",tabIndex:0,title:`Click to view ${Q}`,children:[t.jsx("span",{className:"detail-dep-id",children:Q}),t.jsx("span",{className:"detail-dep-label",children:wd(_t,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Jt=>Ye(Jt,Q),title:`Remove dependency ${Q}`,children:"×"})]},Q)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{J&&He(""),ce(Q=>!Q)},children:"Add Dependency"}),J&&(()=>{const Q=je.toLowerCase(),Te=Q?Ge.filter(_t=>_t.id.toLowerCase().includes(Q)||_t.title&&_t.title.toLowerCase().includes(Q)||_t.description&&_t.description.toLowerCase().includes(Q)):Ge;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:je,onChange:_t=>He(_t.target.value),onClick:_t=>_t.stopPropagation()}),Te.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Te.map(_t=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{Ur(_t.id),ce(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:_t.id}),t.jsx("span",{className:"dep-dropdown-title",children:wd(_t.title||_t.description||_t.id,30)})]},_t.id))]})})()]})]}),t.jsxs("div",{className:"detail-deps detail-blocking",children:[t.jsx("h4",{children:"Blocking"}),Vt.length>0?t.jsx("ul",{className:"detail-dep-list",children:Vt.map(Q=>t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Tt(Q.id),onKeyDown:Te=>{(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),Tt(Q.id))},role:"link",tabIndex:0,title:`Click to view ${Q.id}`,children:[t.jsx("span",{className:"detail-dep-id",children:Q.id}),t.jsx("span",{className:"detail-dep-label",children:wd(Q.label,40)})]}),Q.stale&&t.jsx("span",{className:"detail-blocking-item--stale",title:"Stale blockedBy edge: self-healing clearStaleBlockedBy should clear this automatically",children:"(stale)"})]},Q.id))}):t.jsx("div",{className:"detail-empty-inline",children:"(no downstream tasks blocked)"})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(PT,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:xn?.autoMerge??!1,isManualPrFlow:wm,prAuthAvailable:f??!1,onPrCreated:Q=>{e.prInfo=Q},onPrUpdated:Q=>{e.prInfo=Q},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:re?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:fn==="saving"?"Autosaving…":fn==="saved"?"Saved":fn==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:Kt,disabled:Ft,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void fs(),disabled:Ft,children:Ft?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&N.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ja,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:wa,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!R&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:ea,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||R||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:rs,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{zt(Q=>!Q),ft(!1)},"aria-haspopup":"menu","aria-expanded":qt,children:["Actions",t.jsx(pn,{size:12})]}),qt&&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:()=>ei(ea),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(va),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(ka),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(Fr),children:"Respecify"}),R&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(Ga),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:()=>ei(xa),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>ei(ya),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:Hn,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:wn,className:"btn btn-primary btn-sm detail-move-btn",onClick:dn,onKeyDown:Gs,disabled:!Vn,"aria-label":Vn?`Move to ${ds[Vn]}`:void 0,"aria-haspopup":Tn?"menu":void 0,"aria-expanded":Tn?De:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Vn?ds[Vn]:""]}),Tn&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(pn,{size:12})})]}),De&&Tn&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Ps,children:ti.map(Q=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ci(Q),onKeyDown:Ps,children:Q==="in-progress"?"Back to In Progress":`Move to ${ds[Q]}`},Q))})]}),Ca?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:Ca}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ta,children:Yo})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:wn,className:"btn btn-primary btn-sm detail-move-btn",onClick:dn,onKeyDown:Gs,disabled:!Vn,"aria-label":Vn?`Move to ${ds[Vn]}`:void 0,"aria-haspopup":Tn?"menu":void 0,"aria-expanded":Tn?De:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Vn?ds[Vn]:""]}),Tn&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(pn,{size:12})})]}),De&&Tn&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:Ps,children:ti.map(Q=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>Ci(Q),onKeyDown:Ps,children:["Move to ",ds[Q]]},Q))})]})})]})}),de&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:ja,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:Q=>Q.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:ja,"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:$e,onChange:Q=>st(Q.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:[$e.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:zr,disabled:!$e.trim()||Ue,children:Ue?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:ja,disabled:Ue,children:"Cancel"})})]})}),I&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(jP,{agentId:I,projectId:n,onClose:()=>O(null),addToast:h})})]})}function EP({onClose:e,...n}){const s=i.useRef(null);Li(s,!0,"task-detail-modal-size"),Ni(!0);const a=Qi(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(cv,{...n,onRequestClose:e})})})}const fl={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Qp=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function Xp(e){return e==="merging-fix"?"Merging fixes…":e}const dv=["title","status","column","dependencies","progress"],_P=["title","status","column"];function MP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function AP(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function Zp(e){try{const n=Bn("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>dv.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(_P)}function ef(e){try{const n=Bn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function tf(e){try{const n=Bn("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>oa.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function nf(e){try{const n=Bn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function sf(e){try{const n=Bn("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function af(e){try{const s=Bn("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 Zl=280,ku=.65,gl=16;function ju(e){return Math.max(Zl,e*ku)}function bl(e,n){const s=ju(n);return Math.min(Math.max(e,Zl),s)}function RP(e){return e.status==="executing"||e.column==="in-progress"}function rf(e){const n=Db(e);return n.total===0||!RP(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function IP({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:y,onPlanningMode:b,onSubtaskBreakdown:v,onTasksUpdated:S,projectId:j,projectName:C,taskStuckTimeoutMs:w,searchQuery:N="",lastFetchTimeMs:R,prAuthAvailable:z}){const[E,I]=i.useState(null),[O,U]=i.useState("asc"),[A,D]=i.useState(null),[K,Z]=i.useState(null),[ne,F]=i.useState(null),P=ri()==="mobile",{confirm:$}=pi(),[k,J]=i.useState(()=>Zp(j)),[ce,je]=i.useState(()=>ef(j)),[He,xe]=i.useState(()=>tf(j));i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-columns",JSON.stringify([...k]),j)},[j,k]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-hide-done",ce.toString(),j)},[ce,j]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-list-collapsed",JSON.stringify([...He]),j)},[He,j]);const[Ne,Y]=i.useState(!1),[ie,ee]=i.useState(!1),[oe,W]=i.useState(()=>nf(j)),[L,pe]=i.useState(()=>sf(j)),[fe,B]=i.useState(null),[ve,Fe]=i.useState(()=>af(j)),ae=i.useRef(null),qe=i.useRef(null);i.useEffect(()=>{J(Zp(j)),je(ef(j)),xe(tf(j)),W(nf(j));const ye=sf(j);pe(ye),B(ye?e.find(Le=>Le.id===ye)??null:null),Fe(af(j))},[j,e]),i.useEffect(()=>{typeof window<"u"&&us("kb-dashboard-selected-tasks",JSON.stringify([...oe]),j)},[j,oe]),i.useEffect(()=>{if(!(typeof window>"u")){if(L){us("kb-dashboard-list-selected-task",L,j);return}jr("kb-dashboard-list-selected-task",j)}},[j,L]),i.useEffect(()=>{if(!L){B(null);return}const ye=e.find(Le=>Le.id===L);ye&&B(Le=>!Le||Le.id!==L?ye:{...Le,...ye})},[L,e]),i.useEffect(()=>{if(P||typeof ResizeObserver>"u")return;const ye=ae.current;if(!ye)return;const Le=()=>{const ut=bl(ve,ye.clientWidth);ut!==ve&&Fe(ut)};Le();const Ke=new ResizeObserver(Le);return Ke.observe(ye),()=>Ke.disconnect()},[P,ve]),i.useEffect(()=>{if(P||typeof ResizeObserver>"u")return;const ye=qe.current,Le=ae.current;if(!ye||!Le)return;let Ke=null,ut=ye.offsetWidth;const Ve=new ResizeObserver(()=>{const Pt=bl(ye.offsetWidth,Le.clientWidth);Pt!==ut&&(ut=Pt,Ke&&clearTimeout(Ke),Ke=setTimeout(()=>{try{us("kb-dashboard-list-sidebar-width",String(Pt),j)}catch{}},200))});return Ve.observe(ye),()=>{Ve.disconnect(),Ke&&clearTimeout(Ke)}},[P,j]);const Pe=i.useCallback(()=>{ee(ye=>(ye&&W(new Set),!ye))},[]),nt=i.useCallback(ye=>{W(Le=>{const Ke=new Set(Le);return Ke.has(ye)?Ke.delete(ye):Ke.add(ye),Ke})},[]),Be=i.useCallback(()=>{W(new Set)},[]),de=i.useCallback(ye=>{J(Le=>{const Ke=new Set(Le);return Ke.has(ye)?Ke.size>1&&Ke.delete(ye):Ke.add(ye),Ke})},[]),Ie={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},$e=i.useCallback(ye=>{if(E===ye){U(Le=>Le==="asc"?"desc":"asc");return}I(ye),U("asc")},[E]),st=i.useCallback(ye=>{F(Le=>Le===ye?null:ye)},[]),Ue=i.useCallback(ye=>{xe(Le=>{const Ke=new Set(Le);return Ke.has(ye)?Ke.delete(ye):Ke.add(ye),Ke})},[]),me=i.useCallback(()=>{F(null)},[]),re=i.useMemo(()=>{let ye=N?e.filter(ut=>ut.id.toLowerCase().includes(N.toLowerCase())||ut.title&&ut.title.toLowerCase().includes(N.toLowerCase())||ut.description.toLowerCase().includes(N.toLowerCase())):[...e];ce&&!ne&&(ye=ye.filter(ut=>ut.column!=="done"&&ut.column!=="archived"));const Le=ne?ye.filter(ut=>ut.column===ne):ye,Ke={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};Le.forEach(ut=>{const Ve=Vu(ut.column)?ut.column:Wl;Ke[Ve].push(ut)});for(const ut of oa){if(!E){Ke[ut]=Rb(Ke[ut],ut);continue}Ke[ut]=[...Ke[ut]].sort((Ve,Pt)=>{let Ot=0;switch(E){case"title":Ot=(Ve.title||Ve.description).localeCompare(Pt.title||Pt.description);break;case"status":Ot=(Ve.status||"").localeCompare(Pt.status||"");break;case"column":Ot=Ve.column.localeCompare(Pt.column);break}return O==="asc"?Ot:-Ot})}return Ke},[e,N,E,O,ce,ne]),_e=i.useMemo(()=>Object.values(re).reduce((ye,Le)=>ye+Le.length,0),[re]),xt=i.useMemo(()=>e.filter(ye=>ye.column==="done"||ye.column==="archived").length,[e]),dt=i.useMemo(()=>ce?xt:0,[ce,xt]),Qe=i.useCallback(()=>{const ye=Object.values(re).flat().filter(Le=>Le.column!=="archived").map(Le=>Le.id);W(Le=>{if(ye.every(ut=>Le.has(ut))){const ut=new Set(Le);return ye.forEach(Ve=>ut.delete(Ve)),ut}else return new Set([...Le,...ye])})},[re]),vt=i.useMemo(()=>{const ye=Object.values(re).flat().filter(Le=>Le.column!=="archived");return ye.length===0?!1:ye.every(Le=>oe.has(Le.id))},[re,oe]),Ae=i.useMemo(()=>{const ye=Object.values(re).flat().filter(Ke=>Ke.column!=="archived");if(ye.length===0)return!1;const Le=ye.filter(Ke=>oe.has(Ke.id)).length;return Le>0&&Le<ye.length},[re,oe]),[Je,ct]=i.useState("__no_change__"),[Nt,yt]=i.useState("__no_change__"),[Se,G]=i.useState("__no_change__"),[ge,pt]=i.useState([]),[ke,tt]=i.useState(!1),Rt=i.useMemo(()=>Se&&Se!=="__no_change__"?ge.find(ye=>ye.id===Se):void 0,[ge,Se]),[Re,be]=i.useState(!1);i.useEffect(()=>{if(oe.size===0)return;let ye=!1;return(async()=>{tt(!0);try{const Ke=await ql();ye||pt(Ke)}catch(Ke){console.error("Failed to fetch nodes for bulk edit",Ke),ye||pt([])}finally{ye||tt(!1)}})(),()=>{ye=!0}},[oe.size]);const at=i.useCallback(async()=>{if(oe.size===0)return;const ye=Array.from(oe).map(bt=>e.find(Dt=>Dt.id===bt)).filter(bt=>!!bt),Le=ye.filter(bt=>bt.column==="archived"),Ke=ye.filter(bt=>bt.column!=="archived");if(Ke.length===0){d("No selected tasks can be deleted (archived tasks are excluded)","error");return}if(!await $({title:"Delete Selected Tasks",message:`Delete ${Ke.length} selected task${Ke.length===1?"":"s"}?`,confirmLabel:"Delete",cancelLabel:"Cancel",danger:!0}))return;be(!0);const Ve=[],Pt=[],Ot=Le.map(bt=>bt.id);try{for(const bt of Ke)try{await a(bt.id),Ve.push(bt.id)}catch(Dt){const Ft=Ku(Dt);if(!Ft){Pt.push(bt.id);continue}if(!await $({title:"Force Delete Task",message:`Task ${bt.id} has dependents: ${Ft.dependentIds.join(", ")}. Remove dependency references and force delete?`,confirmLabel:"Force Delete",cancelLabel:"Skip",danger:!0})){Pt.push(bt.id);continue}try{await a(bt.id,{removeDependencyReferences:!0}),Ve.push(bt.id)}catch{Pt.push(bt.id)}}}finally{be(!1)}Ve.length>0&&W(bt=>{const Dt=new Set(bt);for(const Ft of Ve)Dt.delete(Ft);return Dt}),d(`Deleted ${Ve.length} task${Ve.length===1?"":"s"} · ${Ot.length} archived skipped · ${Pt.length} failed`,Pt.length>0?"error":"success")},[d,$,a,oe,e]),ot=i.useCallback(async()=>{if(oe.size===0)return;const ye=Array.from(oe).filter(Ke=>{const ut=e.find(Ve=>Ve.id===Ke);return ut&&ut.column!=="archived"});if(ye.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Le={taskIds:ye};if(Je!=="__no_change__")if(Je==="")Le.modelProvider=null,Le.modelId=null;else{const Ke=Je.indexOf("/");Ke!==-1&&(Le.modelProvider=Je.slice(0,Ke),Le.modelId=Je.slice(Ke+1))}if(Nt!=="__no_change__")if(Nt==="")Le.validatorModelProvider=null,Le.validatorModelId=null;else{const Ke=Nt.indexOf("/");Ke!==-1&&(Le.validatorModelProvider=Nt.slice(0,Ke),Le.validatorModelId=Nt.slice(Ke+1))}if(Se!=="__no_change__"&&(Se===""?Le.nodeId=null:Le.nodeId=Se),Object.keys(Le).length===1){d("No changes to apply","info");return}be(!0);try{const Ke=await _j(Le.taskIds,Le.modelProvider,Le.modelId,Le.validatorModelProvider,Le.validatorModelId,void 0,void 0,Le.nodeId,j);S&&S(Ke.updated),d(`Updated ${ye.length} task${ye.length===1?"":"s"}`,"success"),Be(),ct("__no_change__"),yt("__no_change__"),G("__no_change__")}catch(Ke){d(Ee(Ke)||"Failed to update models","error")}finally{be(!1)}},[oe,e,Je,Nt,Se,j,d,Be,S]),gt=i.useCallback(ye=>{if(P){c(ye,{origin:"list-mobile"});return}pe(ye.id),B(ye)},[P,c]),St=i.useRef(null),Lt=i.useRef(null);i.useEffect(()=>()=>{St.current&&clearTimeout(St.current)},[]);const Yt=i.useCallback(ye=>{if(pe(ye.id),B(ye),"prompt"in ye){Lt.current=null,St.current&&(clearTimeout(St.current),St.current=null);return}Lt.current=ye.id,St.current&&clearTimeout(St.current),St.current=setTimeout(()=>{St.current=null,Lt.current===ye.id&&La(ye.id,j).then(Ke=>{Lt.current===Ke.id&&B(ut=>!ut||ut.id!==Ke.id?ut:{...ut,...Ke})}).catch(()=>{})},200)},[j]),tn=i.useCallback((ye,Le)=>{if(Le.paused){ye.preventDefault();return}ye.dataTransfer.setData("text/plain",Le.id),ye.dataTransfer.effectAllowed="move",D(Le.id)},[]),mn=i.useCallback(()=>{D(null),Z(null)},[]),Qt=i.useCallback(ye=>{if(P)return;ye.preventDefault();const Le=ae.current;if(!Le)return;const Ke=Le.getBoundingClientRect(),ut=Pt=>{const Ot=Pt.clientX-Ke.left;Fe(bl(Ot,Ke.width))},Ve=()=>{window.removeEventListener("mousemove",ut),window.removeEventListener("mouseup",Ve)};window.addEventListener("mousemove",ut),window.addEventListener("mouseup",Ve)},[P]),yn=i.useCallback(ye=>{if(P)return;const Le=ae.current?.clientWidth??0,Ke=ve/ku+gl,ut=Math.max(Le,Ke),Ve=ju(ut);if(ye.key==="ArrowLeft"||ye.key==="ArrowRight"){ye.preventDefault();const Pt=ye.key==="ArrowLeft"?-gl:gl;Fe(Ot=>bl(Ot+Pt,ut));return}if(ye.key==="Home"){ye.preventDefault(),Fe(Zl);return}ye.key==="End"&&(ye.preventDefault(),Fe(Ve))},[P,ve]),Gt=i.useCallback((ye,Le)=>{ye.preventDefault(),ye.dataTransfer.dropEffect="move",Z(Le)},[]),on=i.useCallback(()=>{Z(null)},[]),sn=i.useCallback(async(ye,Le)=>{ye.preventDefault(),Z(null);const Ke=ye.dataTransfer.getData("text/plain");if(Ke){if(Le==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const Ve=e.find(bt=>bt.id===Ke)?.steps.some(bt=>bt.status!=="pending")??!1,Pt=(Le==="todo"||Le==="triage")&&Ve;let Ot;if(Pt){if(await $({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Ot={preserveProgress:!0};else if(!await $({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(Ke,Le,Ot)}catch(ut){d(Ee(ut),"error")}}},[n,d,e,$]),ln=ye=>!E||E!==ye?t.jsx(Hg,{size:14,className:"sort-icon"}):O==="asc"?t.jsx(Ta,{size:14,className:"sort-icon active"}):t.jsx(Po,{size:14,className:"sort-icon active"}),Wt=ye=>t.jsxs("div",{id:ye,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:dv.map(Le=>{const Ke=k.has(Le),ut=Ke&&k.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${ut?" disabled":""}`,title:ut?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:Ke,onChange:()=>de(Le),disabled:ut}),t.jsx("span",{children:Ie[Le]})]},Le)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>je(Le=>!Le),"aria-pressed":ce,title:ce?"Show done tasks":"Hide done tasks",children:[ce?t.jsx(Ir,{size:14}):t.jsx(Pu,{size:14}),ce?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:oa.map(Le=>{const Ke=e.filter(Ot=>Ot.column===Le).length,ut=Le==="done"||Le==="archived",Ve=ce&&ut?0:Ke,Pt=ce&&ut&&Ke>0;return t.jsxs("div",{className:`list-drop-zone${K===Le?" drag-over":""}${ne===Le?" active":""}`,onClick:()=>st(Le),onDragOver:Ot=>Gt(Ot,Le),onDragLeave:on,onDrop:Ot=>sn(Ot,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:Pt?`${Ve} of ${Ke}`:Ke})]},Le)})})]});return t.jsxs("div",{className:"list-view",children:[P&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:Pe,"aria-pressed":ie,children:ie?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>Y(ye=>!ye),"aria-expanded":Ne,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(_m,{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:ne?`${_e} of ${e.length} tasks in ${ds[ne]}`:`${_e} of ${e.length} tasks`})]}),Ne?t.jsx("div",{className:"list-toolbar-mobile-options",children:Wt("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:P?"":"list-split-layout","data-testid":P?void 0:"list-split-layout",ref:ae,children:[t.jsxs("div",{className:P?"":"list-split-sidebar","data-testid":P?void 0:"list-split-sidebar",ref:qe,style:P?void 0:{width:`${ve}px`},children:[!P&&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:[ne?`${_e} of ${e.length} tasks in ${ds[ne]}`:`${_e} of ${e.length} tasks`,dt>0&&!ne&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",dt," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Pe,"aria-pressed":ie,children:ie?"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:[ne?t.jsx("button",{className:"btn btn-sm",onClick:me,"aria-label":"Clear column filter",children:`Filter: ${ds[ne]}`}):null,ce?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,ie?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,ie&&oe.size>0?t.jsx("button",{className:"btn btn-sm",onClick:Be,children:`${oe.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>Y(ye=>!ye),"aria-expanded":Ne,"aria-controls":"list-view-options-panel",children:[t.jsx(_m,{size:14}),"View options"]}),Ne&&Wt("list-view-options-panel"),ie&&oe.size>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"bulk-edit-toolbar",children:t.jsxs("button",{className:"btn btn-danger btn-sm",onClick:at,disabled:Re,children:[t.jsx(_n,{size:14}),"Delete selected"]})}),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(Is,{models:f,value:Je,onChange:ct,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:y})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(Is,{models:f,value:Nt,onChange:yt,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:x,favoriteModels:g,onToggleModelFavorite:y})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:Se,onChange:ye=>G(ye.target.value),"aria-label":"Node Override",disabled:ke,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),ge.map(ye=>t.jsx("option",{value:ye.id,children:`${AP(ye.status)} ${ye.name||ye.id} (${MP(ye.status)})`},ye.id))]}),Rt?t.jsx(Oa,{status:Rt.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:ot,disabled:Re||Je==="__no_change__"&&Nt==="__no_change__"&&Se==="__no_change__",children:Re?"Applying...":"Apply"})]}):null]}):null]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(qb,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:v,projectId:j,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:x,onToggleModelFavorite:y})}),_e===0?t.jsx("div",{className:"list-empty",children:N?"No tasks match your filter":"No tasks yet"}):P?t.jsx("div",{className:"list-cards",children:oa.map(ye=>{if(ne&&ye!==ne||ce&&(ye==="done"||ye==="archived")&&!ne)return null;const Le=re[ye],Ke=Le.length===0;if(N&&Ke)return null;const ut=He.has(ye);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${ut?" list-section-header--collapsed":""}`,onClick:()=>Ue(ye),"aria-expanded":!ut,role:"button",tabIndex:0,onKeyDown:Ve=>{(Ve.key==="Enter"||Ve.key===" ")&&(Ve.preventDefault(),Ue(ye))},children:[t.jsx(On,{size:14,className:`list-section-chevron${ut?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ye}`}),t.jsx("span",{className:"list-section-title",children:ds[ye]}),t.jsx("span",{className:"list-section-count",children:Le.length})]}),!ut&&t.jsx(t.Fragment,{children:Ke?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Le.map(Ve=>{const Pt=Ve.status==="failed",Ot=Ve.paused===!0,bt=Gl(Ve,w,R),Dt=!u&&!Pt&&!Ot&&!bt&&(Ve.column==="in-progress"||Qp.has(Ve.status)),Ft=typeof Ve.status=="string"&&Ve.status.trim().length>0,Ht=!!(Ve.dependencies&&Ve.dependencies.length>0),rn=rf(Ve),Xt=rn.hasProgress,an=ie;return t.jsxs("div",{className:`list-card${Dt?" agent-active":""}${an?" list-card--selectable":""}`,onClick:()=>gt(Ve),"data-id":Ve.id,children:[an&&t.jsx("label",{className:"list-card-checkbox",onClick:Me=>Me.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:oe.has(Ve.id),onChange:Me=>{Me.stopPropagation(),nt(Ve.id)},onClick:Me=>Me.stopPropagation(),disabled:Ve.column==="archived","aria-label":`Select ${Ve.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:Ve.id}),Ve.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),Ot&&Ve.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):bt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ft?t.jsx("span",{className:`list-status-badge list-status-badge--${Ve.column}${Pt?" failed":""}${Dt?" pulsing":""}`,children:Xp(Ve.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:Ve.title||Ve.description})}),(Ht||Xt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Ht&&t.jsxs("span",{className:"list-dep-badge",title:Ve.dependencies.join(", "),children:[t.jsx(xr,{size:12})," ",Ve.dependencies.length]}),Xt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${rn.percent}%`,backgroundColor:fl[Ve.column]}})}),t.jsx("span",{className:"list-progress-label",children:rn.label})]})]})]},Ve.id)})})]},ye)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[ie&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:vt,ref:ye=>{ye&&(ye.indeterminate=Ae)},onChange:Qe,"aria-label":"Select all visible tasks"})}),k.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>$e("title"),children:["Title ",ln("title")]}),k.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>$e("status"),children:["Status ",ln("status")]}),k.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>$e("column"),children:["Column ",ln("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:oa.map(ye=>{if(ne&&ye!==ne||ce&&(ye==="done"||ye==="archived")&&!ne)return null;const Le=re[ye],Ke=Le.length===0;if(N&&Ke)return null;const ut=He.has(ye);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${ut?" list-section-header--collapsed":""}`,onClick:()=>Ue(ye),"aria-expanded":!ut,children:t.jsxs("th",{colSpan:k.size+(ie?1:0),className:"list-section-cell",children:[t.jsx(On,{size:14,className:`list-section-chevron${ut?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ye}`}),t.jsx("span",{className:"list-section-title",children:ds[ye]}),t.jsx("span",{className:"list-section-count",children:Le.length})]})}),!ut&&t.jsx(t.Fragment,{children:Ke?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:k.size+(ie?1:0),className:"list-empty-cell",children:"No tasks"})}):Le.map(Ve=>{const Pt=Ve.status==="failed",Ot=Ve.paused===!0,bt=Gl(Ve,w,R),Dt=!u&&!Pt&&!Ot&&!bt&&(Ve.column==="in-progress"||Qp.has(Ve.status)),Ft=A===Ve.id;return t.jsxs("tr",{className:`list-row${Pt?" failed":""}${Ot?" paused":""}${bt?" stuck":""}${Dt?" agent-active":""}${Ft?" dragging":""}${L===Ve.id?" list-row--selected":""}`,onClick:()=>gt(Ve),draggable:!Ot,onDragStart:Ht=>tn(Ht,Ve),onDragEnd:mn,"data-id":Ve.id,children:[ie&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:oe.has(Ve.id),onChange:Ht=>{Ht.stopPropagation(),nt(Ve.id)},onClick:Ht=>Ht.stopPropagation(),disabled:Ve.column==="archived","aria-label":`Select ${Ve.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:Ve.id}),t.jsxs("div",{className:"list-title-row",children:[Ve.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(as,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:Ve.title||Ve.description})]})]})}),k.has("status")&&t.jsx("td",{className:"list-cell",children:Ot&&Ve.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):bt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):Ve.status?t.jsx("span",{className:`list-status-badge list-status-badge--${Ve.column}${Pt?" failed":""}${Dt?" pulsing":""}`,children:Xp(Ve.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:`${fl[Ve.column]}20`,color:fl[Ve.column]},children:ds[Ve.column]})}),k.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:Ve.dependencies&&Ve.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:Ve.dependencies.join(", "),children:[t.jsx(xr,{size:12})," ",Ve.dependencies.length]}):"-"}),k.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ht=rf(Ve);return Ht.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:`${Ht.percent}%`,backgroundColor:fl[Ve.column]}})}),t.jsx("span",{className:"list-progress-label",children:Ht.label})]}):"-"})()})]},Ve.id)})})]},ye)})})]})]}),!P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:Qt,onKeyDown:yn,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":Zl,"aria-valuemax":Math.round(ju(ae.current?.clientWidth??ve/ku+gl)),"aria-valuenow":Math.round(ve)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:fe?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(cv,{task:fe,projectId:j,tasks:e,embedded:!0,onOpenDetail:Yt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:ye=>{B(Le=>!Le||Le.id!==ye.id?Le:{...Le,...ye})},addToast:d,prAuthAvailable:z})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const TP={active:{label:"Active",color:"var(--color-success)",icon:is},paused:{label:"Paused",color:"var(--color-warning)",icon:vi},errored:{label:"Error",color:"var(--color-error)",icon:Ws},initializing:{label:"Initializing",color:"var(--color-warning)",icon:jt}};function PP(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 of(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 $P(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.availabilityMappings??[],o=n.availabilityMappings??[];return r.length!==o.length?!1:r.every((l,c)=>{const d=o[c];return!!d&&l.nodeId===d.nodeId&&l.path===d.path&&l.displayName===d.displayName&&l.available===d.available})}function DP({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,availabilityMappings:l=[],isLoading:c=!1}){const[d,u]=i.useState(!1),m=TP[e.status],h=m.icon,f=i.useCallback(()=>{s(e)},[s,e]),p=i.useCallback(S=>{S.stopPropagation(),a(e)},[a,e]),g=i.useCallback(S=>{S.stopPropagation(),r(e)},[r,e]),x=i.useCallback(S=>{if(S.stopPropagation(),!d){u(!0);return}o(e),u(!1)},[d,o,e]),y=e.status==="paused",b=e.status==="errored",v=e.status==="initializing";return t.jsxs("div",{className:`project-card ${c?"project-card-loading":""} ${b?"project-card-errored":""}`,onClick:f,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(Es,{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.length>0&&t.jsxs("div",{className:"project-card-availability","aria-label":"Project node availability",children:[l.slice(0,3).map(S=>t.jsxs("div",{className:"project-card-availability__row",title:`${S.displayName} → ${S.path}`,children:[t.jsx("span",{className:"project-card-availability__node",children:S.displayName}),t.jsx("span",{className:"project-card-availability__arrow",children:"→"}),t.jsx("code",{className:"project-card-availability__path",children:of(S.path,28)})]},`${S.nodeId}-${S.path}`)),l.length>3&&t.jsxs("span",{className:"project-card-availability__more",children:["+",l.length-3," more"]})]}),t.jsx("span",{className:"project-card-path",title:e.path,children:of(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:m.color,borderColor:m.color},children:[t.jsx(h,{size:12,className:v?"animate-spin":""}),t.jsx("span",{children:m.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:PP(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[y?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:g,disabled:c,title:"Resume project","aria-label":"Resume project",children:[t.jsx(is,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:p,disabled:c||v,title:v?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(vi,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:f,disabled:c,title:"Open project","aria-label":"Open project",children:[t.jsx($o,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:x,disabled:c,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(_n,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const LP=i.memo(DP,$P);function lf(e){return typeof e=="string"&&e.trim().length>0}function po(e){return(e.nodeMappings??[]).filter(s=>lf(s.nodeId)&&lf(s.path)).map(s=>({nodeId:s.nodeId,nodeName:s.nodeName,path:s.path,available:s.available!==!1}))}function OP(e,n){return po(e).filter(s=>s.nodeId===n.id&&s.available)}function FP(e,n){return OP(e,n).length>0}function zP(e,n){return e.filter(s=>FP(s,n))}function e8(e,n){return zP(e,n).length}function cf(e,n,s,a){const r=s.find(o=>o.id===e);return r?.name?r.name:n?.nodeName?n.nodeName:a._sourceNodeName?a._sourceNodeName:e}function BP(){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(Es,{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(Ys,{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(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__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 UP=1e4,df=5;function HP(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+=df){const x=e.slice(g,g+df),y=await Promise.allSettled(x.map(async b=>{try{return await eh(b)}catch{return null}}));if(x.forEach((b,v)=>{const S=y[v];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 eh(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()},UP),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function qP({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 U=localStorage.getItem("kb-dashboard-recent-projects");if(U)try{const A=JSON.parse(U);b(A)}catch{}},[]);const[y,b]=i.useState([]),v=i.useMemo(()=>e.map(U=>U.id),[e]),{healthMap:S,loading:j}=HP(v),C=i.useMemo(()=>e.map(U=>({project:U,health:S[U.id]||null})),[e,S]),w=i.useMemo(()=>{let U=[...C];return d!=="all"&&(U=U.filter(({project:A})=>A.status===d)),m!==null&&(U=U.filter(({project:A})=>po(A).some(D=>D.available&&D.nodeId===m))),U},[C,d,m]),N=i.useMemo(()=>{const U=[...w];return U.sort((A,D)=>{let K=0;switch(f){case"name":K=A.project.name.localeCompare(D.project.name);break;case"activity":{const Z=A.project.lastActivityAt||A.health?.lastActivityAt||A.project.updatedAt,ne=D.project.lastActivityAt||D.health?.lastActivityAt||D.project.updatedAt;K=new Date(ne).getTime()-new Date(Z).getTime();break}case"status":{const Z={errored:0,initializing:1,paused:2,active:3};K=Z[A.project.status]-Z[D.project.status];break}}return g==="asc"?K:-K}),U},[w,f,g]),R=i.useMemo(()=>{const U=e.length,A=e.filter(P=>P.status==="active").length,D=e.filter(P=>P.status==="errored").length,K=new Set;e.forEach(P=>{po(P).forEach($=>{$.available&&K.add($.nodeId)})});const Z=K.size;let ne=0,F=0,M=0;return Object.values(S).forEach(P=>{P&&(ne+=P.activeTaskCount,F+=P.totalTasksCompleted,M+=P.inFlightAgentCount)}),{totalProjects:U,activeProjects:A,erroredProjects:D,totalNodes:Z,totalActiveTasks:ne,totalCompletedTasks:F,totalInFlightAgents:M}},[e,S]),z=i.useMemo(()=>({all:e.length,active:e.filter(U=>U.status==="active").length,paused:e.filter(U=>U.status==="paused").length,errored:e.filter(U=>U.status==="errored").length}),[e]),E=i.useMemo(()=>{const U=new Map;return e.forEach(A=>{po(A).filter(D=>D.available).forEach(D=>{const K=D.nodeId,Z=U.get(K),ne=cf(K,D,c,A);Z?Z.count+=1:U.set(K,{name:ne,count:1})})}),Array.from(U.entries()).map(([A,{name:D,count:K}])=>({nodeId:A,name:D,count:K}))},[e,c]),I=i.useCallback(U=>{const A=[U.id,...y.filter(D=>D!==U.id)].slice(0,3);b(A),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(A)),s(U)},[s,y]);return n||j&&e.length>0&&Object.keys(S).length===0?t.jsx(BP,{}):e.length===0?t.jsx("div",{className:"project-overview project-overview--empty",children:t.jsxs("div",{className:"project-empty-state",children:[t.jsx("div",{className:"project-empty-state__icon",children:t.jsx(ra,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:a,children:[t.jsx(Mn,{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(ma,{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(Es,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.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(Ys,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.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:R.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),R.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",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:R.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),R.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(So,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.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(Mn,{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:z.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:z.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:z.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${z.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:z.errored})]})]}),E.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(So,{size:14}),t.jsxs("select",{value:m??"",onChange:U=>{h(U.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:U,name:A,count:D})=>t.jsxs("option",{value:U??"",children:[A," (",D,")"]},U??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Fl,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:U=>{const[A,D]=U.target.value.split("-");p(A),x(D)},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(Hg,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:N.map(({project:U,health:A})=>{const D=po(U).filter(K=>K.available).map(K=>({...K,displayName:cf(K.nodeId,K,c,U)}));return t.jsx(LP,{project:U,health:A,availabilityMappings:D,onSelect:I,onPause:r,onResume:o,onRemove:l},U.id)})}),N.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Fl,{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 bm="kb-planning-last-description",xm="kb-subtask-last-description",vm="kb-mission-last-goal";function VP(e,n){us(bm,e,n)}function WP(e){return Bn(bm,e)||""}function rr(e){jr(bm,e)}function KP(e,n){us(xm,e,n)}function GP(e){return Bn(xm,e)||""}function Sd(e){jr(xm,e)}function JP(e,n){us(vm,e,n)}function YP(e){return Bn(vm,e)||""}function ia(e){jr(vm,e)}function QP(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 XP(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 ZP(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 mi({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=ZP(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?QP(o):void 0,h=o.question&&m!==void 0?XP(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 uf="fusion-tab-id";function e$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function qa(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(uf);if(e)return e;const n=e$();return window.sessionStorage.setItem(uf,n),n}function Ec(e){const n=i.useMemo(()=>qa(),[]),[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(m0(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=h0(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=Di(`/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:hi("/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(p0(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const t$="fusion:ai-session-sync",mf="fusion:ai-session-sync",n$=3e4,s$=6e4;function Mi(){return Date.now()}function i$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function hf(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 a${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=i$(),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:Mi()})}broadcastUpdate(n){const s=n.timestamp??Mi();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??Mi();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=Mi();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=Mi();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=Mi();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(t$),this.channel.onmessage=s=>{const a=hf(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==mf||!s.newValue))try{const a=JSON.parse(s.newValue),r=hf(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Mi();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},n$)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=Mi();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(mf,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:Mi()});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=Mi(),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>s$;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 Ai=new a$;function Or(){const e=i.useSyncExternalStore(c=>Ai.subscribe(c),()=>Ai.getSnapshot(),()=>Ai.getSnapshot());i.useEffect(()=>{Ai.requestSync()},[]);const n=i.useCallback(c=>{Ai.broadcastUpdate(c)},[]),s=i.useCallback(c=>{Ai.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{Ai.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{Ai.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{Ai.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{Ai.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function r$(e,n){return e&&n?`${e}/${n}`:""}function o$(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 l$=["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 c$({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){Ni(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([]),[y,b]=i.useState(null),[v,S]=i.useState(!1),j=i.useRef(!1),[C,w]=i.useState(""),[N,R]=i.useState(!0),[z,E]=i.useState(!1),[I,O]=i.useState(!1),[U,A]=i.useState(!1),D=i.useRef(null),K=i.useRef(null),Z=i.useRef(null),ne=i.useRef(null),[F,M]=i.useState(o??null),P=i.useMemo(()=>qa(),[]),{isLockedByOther:$,takeControl:k,isLoading:J}=Ec(e?F:null),{activeTabMap:ce,broadcastUpdate:je,broadcastCompleted:He,broadcastLock:xe,broadcastUnlock:Ne,broadcastHeartbeat:Y}=Or(),{confirm:ie}=pi(),[ee,oe]=i.useState(void 0),[W,L]=i.useState(void 0),[pe,fe]=i.useState([]),[B,ve]=i.useState(!0),[Fe,ae]=i.useState(null),[qe,Pe]=i.useState([]),[nt,Be]=i.useState([]),de=r$(ee,W);i.useEffect(()=>{(async()=>{try{ve(!0);const G=await Ks();fe(G.models),Pe(G.favoriteProviders),Be(G.favoriteModels)}catch(G){ae(Ee(G)||"Failed to load models")}finally{ve(!1)}})()},[]);const Ie=i.useCallback(Se=>{Pe(G=>{const ge=G,ke=ge.includes(Se)?ge.filter(tt=>tt!==Se):[Se,...ge];return Dn({favoriteProviders:ke,favoriteModels:nt}).catch(()=>{Pe(ge)}),ke})},[nt]),$e=i.useCallback(Se=>{Be(G=>{const ge=G,ke=ge.includes(Se)?ge.filter(tt=>tt!==Se):[Se,...ge];return Dn({favoriteProviders:qe,favoriteModels:ke}).catch(()=>{Be(ge)}),ke})},[qe]),st=i.useCallback((Se,G)=>{if(!Se||!G)return"Using default";const ge=pe.find(pt=>pt.provider===Se&&pt.id===G);return ge?`${ge.provider}/${ge.id}`:`${Se}/${G}`},[pe]),Ue=i.useCallback(Se=>{K.current?.close();const G=X1(Se,a,{onThinking:ge=>{w(pt=>pt+ge),je({sessionId:Se,status:"generating",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:ge=>{E(!1),O(!1),ia(a),u({type:"question",sessionId:Se,question:ge}),w(""),S(!0),je({sessionId:Se,status:"awaiting_input",needsInput:!0,owningTabId:P,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:ge=>{E(!1),O(!1),ia(a),u({type:"summary",sessionId:Se,summary:ge}),b(ge),w(""),S(!0),je({sessionId:Se,status:"complete",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:ge=>{const pt=ge||"Session failed while contacting the AI.";E(!1),O(!1),h(null),u({type:"error",sessionId:Se,errorMessage:pt}),w(""),S(!0),Z.current=Se,je({sessionId:Se,status:"error",needsInput:!1,owningTabId:P,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),He({sessionId:Se,status:"error"})},onComplete:()=>{E(!1),O(!1),Z.current=null,He({sessionId:Se,status:"complete"})},onConnectionStateChange:ge=>{E(ge==="reconnecting")}});K.current=G},[He,je,l,a,P]),me=i.useCallback(async Se=>{const G=Se??l;if(G.trim()){h(null),w(""),p([]),x([]),E(!1),u({type:"loading"});try{const{sessionId:ge}=await G1(G.trim(),a,ee&&W?{modelProvider:ee,modelId:W}:void 0);Z.current=ge,M(ge),ia(a),Ue(ge),p([])}catch(ge){E(!1),h(Ee(ge)||"Failed to start interview session"),u({type:"initial"}),Z.current=null,M(null)}}},[Ue,l,ee,W,a]);i.useEffect(()=>{e&&d.type==="initial"&&D.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!j.current&&d.type==="initial"){const Se=YP(a);Se&&c(Se)}},[e]),i.useEffect(()=>{if(e&&r&&!j.current&&d.type==="initial"){c(r);const Se=setTimeout(()=>{j.current=!0,me(r)},0);return()=>clearTimeout(Se)}},[e,r,d.type,me]),i.useEffect(()=>{e||(j.current=!1,E(!1),O(!1),M(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let Se=!1;return Ti(o).then(G=>{if(Se||!G)return;const ge=kr(G.conversationHistory);if(x(ge),M(G.id),p(ge.map(pt=>pt.response).filter(pt=>!!(pt&&typeof pt=="object"&&!Array.isArray(pt)))),G.status==="awaiting_input"&&G.currentQuestion)try{ia(a);const pt=JSON.parse(G.currentQuestion);Z.current=G.id,S(!0),u({type:"question",sessionId:G.id,question:pt})}catch{h("Failed to restore session question.")}else if(G.status==="complete"&&G.result)try{ia(a);const pt=JSON.parse(G.result);Z.current=G.id,S(!0),b(pt),u({type:"summary",sessionId:G.id,summary:pt})}catch{h("Failed to restore session result.")}else G.status==="generating"?(Z.current=G.id,S(!0),G.thinkingOutput&&w(G.thinkingOutput),u({type:"loading"}),Ue(G.id)):G.status==="error"&&(Z.current=G.id,S(!0),h(null),u({type:"error",sessionId:G.id,errorMessage:G.error??"The session encountered an error."}))}).catch(()=>{Se||h("Failed to resume session.")}),()=>{Se=!0}},[Ue,e,o,d.type,a]),i.useEffect(()=>{if(!e){ne.current&&(Ne(ne.current,P),ne.current=null);return}if(F&&ne.current!==F){ne.current&&Ne(ne.current,P),xe(F,P),ne.current=F;return}!F&&ne.current&&(Ne(ne.current,P),ne.current=null)},[xe,Ne,e,F,P]),i.useEffect(()=>{if(!e||!F||ne.current!==F)return;Y(P);const Se=setInterval(()=>{Y(P)},3e4);return()=>{clearInterval(Se)}},[Y,e,F,P]),i.useEffect(()=>()=>{K.current?.close(),K.current=null,ne.current&&(Ne(ne.current,P),ne.current=null)},[Ne,P]),i.useEffect(()=>{if(!e)return;const Se=G=>{(d.type==="question"||d.type==="summary")&&(G.preventDefault(),G.returnValue=""),K.current?.close()};return window.addEventListener("beforeunload",Se),()=>window.removeEventListener("beforeunload",Se)},[e,d]);const re=i.useCallback(()=>{K.current?.close(),K.current=null,n()},[n]),_e=i.useCallback(async()=>{if(l&&JP(l,a),!(v&&!await ie({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(K.current?.close(),K.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await gb(d.sessionId,a,P)}catch{}c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),w(""),E(!1),O(!1),S(!1),A(!1),oe(void 0),L(void 0),Z.current=null,M(null),n()}},[l,v,d,n,a,P,ie]);i.useEffect(()=>{if(!e)return;const Se=G=>{G.key==="Escape"&&_e()};return document.addEventListener("keydown",Se),()=>document.removeEventListener("keydown",Se)},[e,_e]);const xt=i.useCallback(async Se=>{if(d.type!=="question")return;const{sessionId:G}=d;h(null),p(ge=>[...ge,Se]),x(ge=>[...ge,{question:d.question,response:Se}]),u({type:"loading"}),w("");try{Ue(G),await J1(G,Se,a,P),S(!0)}catch(ge){K.current?.close(),K.current=null,h(Ee(ge)||"Failed to submit response"),u({type:"question",sessionId:G,question:d.question})}},[d,a,P,Ue]),dt=i.useCallback(async()=>{if(d.type!=="error")return;const Se=d.sessionId;h(null),O(!0),w(""),u({type:"loading"}),Ue(Se);try{Z.current=Se,M(Se),await Y1(Se,a,P)}catch(G){let ge=G;if((Ee(G)||"").includes("not in an error state"))try{const ke=await Ti(Se);if(!ke)throw new Error("Failed to refresh interview session.");const tt=kr(ke.conversationHistory);if(x(tt),p(tt.map(Rt=>Rt.response).filter(Rt=>!!(Rt&&typeof Rt=="object"&&!Array.isArray(Rt)))),Z.current=ke.id,M(ke.id),S(!0),ke.status==="generating")w(ke.thinkingOutput??""),u({type:"loading"}),K.current?.isConnected()||Ue(ke.id);else if(ke.status==="awaiting_input"){if(!ke.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ia(a);const Rt=JSON.parse(ke.currentQuestion);u({type:"question",sessionId:ke.id,question:Rt}),K.current?.isConnected()||Ue(ke.id)}else if(ke.status==="complete"){if(!ke.result)throw new Error("Interview session is complete but has no result.");ia(a);const Rt=JSON.parse(ke.result);b(Rt),u({type:"summary",sessionId:ke.id,summary:Rt})}else ke.status==="error"&&u({type:"error",sessionId:ke.id,errorMessage:ke.error??"Retry failed. Please try again."});E(!1);return}catch(ke){ge=ke}K.current?.close(),K.current=null,u({type:"error",sessionId:Se,errorMessage:Ee(ge)||"Retry failed. Please try again."}),E(!1)}finally{O(!1)}},[Ue,a,P,d]),Qe=i.useCallback(async()=>{if(d.type==="summary"){h(null),A(!0);try{const Se=await Q1(d.sessionId,y||void 0,a);s(Se),ia(a),K.current?.close(),K.current=null,c(""),u({type:"initial"}),h(null),p([]),x([]),b(null),w(""),E(!1),O(!1),S(!1),A(!1),Z.current=null,M(null),n()}catch(Se){h(Ee(Se)||"Failed to create mission"),A(!1)}}},[d,y,s,n,a]),vt=()=>d.type==="question"?Math.min(f.length+1,6):6,Ae=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Je=F?ce.get(F):null,ct=Je&&Je.tabId!==P,Nt=!!(ct&&!Je.stale),yt=$&&(!ct||Je.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Se=>Se.target===Se.currentTarget&&_e(),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(Rs,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ae&&t.jsx("button",{className:"modal-send-to-background",onClick:re,title:"Send to background","aria-label":"Send to background",children:t.jsx(Lo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:_e,"aria-label":"Close",children:t.jsx(un,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),z&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Nt&&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(gs,{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:D,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:Se=>c(Se.target.value),onKeyDown:Se=>{Se.key==="Enter"&&!Se.shiftKey&&l.trim()&&(Se.preventDefault(),me())}})]}),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:l$.map((Se,G)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Se),children:Se.length>45?Se.slice(0,45)+"...":Se},G))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",B&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(Is,{id:"mission-interview-modal-model",label:"Planning Model",value:de,onChange:Se=>{const{provider:G,modelId:ge}=o$(Se);oe(G),L(ge)},models:pe,disabled:B,favoriteProviders:qe,onToggleFavorite:Ie,favoriteModels:nt,onToggleModelFavorite:$e}),Fe&&t.jsxs("div",{className:"form-hint form-hint-error",children:[Fe," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{ve(!0);const Se=await Ks();fe(Se.models),Pe(Se.favoriteProviders),Be(Se.favoriteModels),ae(null)}catch(Se){ae(Ee(Se)||"Failed to load models")}finally{ve(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${ee&&W?"model-badge-custom":"model-badge-default"}`,children:st(ee,W)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>me(),disabled:!l.trim(),children:[t.jsx(Rs,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:C?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>R(!N),type:"button",children:N?"Hide thinking":"Show thinking"}),N&&C&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:C})})]})]}),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(mi,{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 dt(),disabled:I,children:[I?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:I?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:_e,disabled:I,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(d$,{question:d.question,progress:vt(),historyEntries:g,onSubmit:xt}),d.type==="summary"&&y&&t.jsx(u$,{summary:y,historyEntries:g,onSummaryChange:b,onApprove:Qe,onStartOver:()=>{u({type:"initial"}),S(!1),b(null),p([]),x([]),M(null),K.current?.close(),K.current=null},isCreating:U}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(pc,{size:16}),t.jsx("span",{children:yt?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),yt&&t.jsx("button",{type:"button",onClick:()=>{k()},disabled:J,className:"btn btn-primary session-lock-take-control",children:J?"Taking control...":"Take Control"})]})})]})]})}):null}function d$({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(mi,{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(y=>y!==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(un,{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($o,{size:16,className:"icon-ml-4"})]})})]})}function u$({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((j,C)=>C))),[d,u]=i.useState(()=>{const j=new Set;return e.milestones.forEach((C,w)=>{C.slices.forEach((N,R)=>j.add(`${w}-${R}`))}),j}),m=j=>{c(C=>{const w=new Set(C);return w.has(j)?w.delete(j):w.add(j),w})},h=j=>{u(C=>{const w=new Set(C);return w.has(j)?w.delete(j):w.add(j),w})},f=(j,C)=>{const w=[...e.milestones];w[j]={...w[j],...C},s({...e,milestones:w})},p=(j,C,w)=>{const N=[...e.milestones],R=[...N[j].slices];R[C]={...R[C],...w},N[j]={...N[j],slices:R},s({...e,milestones:N})},g=(j,C,w,N)=>{const R=[...e.milestones],z=[...R[j].slices],E=[...z[C].features];E[w]={...E[w],...N},z[C]={...z[C],features:E},R[j]={...R[j],slices:z},s({...e,milestones:R})},x=j=>{const C=e.milestones.filter((w,N)=>N!==j);s({...e,milestones:C})},y=(j,C)=>{const w=[...e.milestones];w[j]={...w[j],slices:w[j].slices.filter((N,R)=>R!==C)},s({...e,milestones:w})},b=(j,C,w)=>{const N=[...e.milestones],R=[...N[j].slices];R[C]={...R[C],features:R[C].features.filter((z,E)=>E!==w)},N[j]={...N[j],slices:R},s({...e,milestones:N})},v=(j,C)=>{const w=[...e.milestones],N=[...w[j].slices];N[C]={...N[C],features:[...N[C].features,{title:"New feature",description:""}]},w[j]={...w[j],slices:N},s({...e,milestones:w})},S=e.milestones.reduce((j,C)=>j+C.slices.reduce((w,N)=>w+N.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(mi,{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:j=>s({...e,missionTitle:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:j=>s({...e,missionDescription:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((j,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(C),children:[l.has(C)?t.jsx(pn,{size:16,className:"icon-text-secondary"}):t.jsx(On,{size:16,className:"icon-text-secondary"}),t.jsx($a,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:w=>f(C,{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(C)},title:"Remove milestone",children:t.jsx(_n,{size:14,className:"icon-text-secondary"})})]}),l.has(C)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:j.description||"",onChange:w=>f(C,{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:j.verification||"",onChange:w=>f(C,{verification:w.target.value})})]}),j.slices.map((w,N)=>{const R=`${C}-${N}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(R),children:[d.has(R)?t.jsx(pn,{size:14,className:"icon-text-secondary"}):t.jsx(On,{size:14,className:"icon-text-secondary"}),t.jsx(eu,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:w.title,onChange:z=>p(C,N,{title:z.target.value}),onClick:z=>z.stopPropagation()}),j.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:z=>{z.stopPropagation(),y(C,N)},title:"Remove slice",children:t.jsx(_n,{size:12,className:"icon-text-secondary"})})]}),d.has(R)&&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:z=>p(C,N,{verification:z.target.value})})]}),w.features.map((z,E)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Gd,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:z.title,onChange:I=>g(C,N,E,{title:I.target.value})}),z.description&&t.jsx("p",{className:"roadmap-feature-text",children:z.description}),z.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",z.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(C,N,E),title:"Remove feature",children:t.jsx(_n,{size:12,className:"icon-text-secondary"})})]},E)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>v(C,N),children:[t.jsx(Mn,{size:12}),"Add Feature"]})]})]},N)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ua,{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(jt,{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 m$=30,h$=16,p$=16;function f$(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Dl=null;function uv(){return Dl===null&&(Dl=window.visualViewport?.height??window.innerHeight),Dl}function g$(e){const n=uv();e>n&&(Dl=e)}function b$(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 pf(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=b$(document.activeElement),s=e.offsetTop;n||g$(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=uv(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=m$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=h$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=p$?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function Zi({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||!f$()){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=pf();s(w.overlap),r(w.vvHeight),l(w.vvOffsetTop),d(w.open)},h=()=>{const w=pf();s(w.overlap),r(w.vvHeight),d(w.open)},f=[],p=w=>{if(typeof window>"u")return;const N=window.setTimeout(()=>{typeof window>"u"||m()},w);f.push(N)};let g=null,x=0,y=-1,b=0;const v=()=>{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===y?b+=1:(b=0,y=w),b>=2||performance.now()>x){g=null;return}g=window.requestAnimationFrame(S)},j=()=>{typeof window>"u"||(v(),x=performance.now()+1500,y=-1,b=0,g=window.requestAnimationFrame(S))},C=()=>{m(),p(50),p(200),p(500),p(1e3),p(1500),j()};return C(),u.addEventListener("resize",m),u.addEventListener("scroll",h),document.addEventListener("focusin",C),document.addEventListener("focusout",m),document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",C),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",h),document.removeEventListener("focusin",C),document.removeEventListener("focusout",m),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",C);for(const w of f)clearTimeout(w);v(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function x$({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=ri();Ni(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Zi({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,y]=i.useState({type:"initial"}),[b,v]=i.useState(null),[S,j]=i.useState([]),[C,w]=i.useState([]),[N,R]=i.useState(null),[z,E]=i.useState(""),[I,O]=i.useState(!0),[U,A]=i.useState(!1),[D,K]=i.useState(!1),Z=i.useRef(null),ne=i.useRef(null),F=i.useRef(null),M=i.useRef(null),[P,$]=i.useState(null),k=i.useMemo(()=>qa(),[]);Ec(e?P:null);const{activeTabMap:J,broadcastUpdate:ce,broadcastCompleted:je,broadcastLock:He,broadcastUnlock:xe,broadcastHeartbeat:Ne}=Or(),Y=a==="milestone"?Z1:i0,ie=a==="milestone"?e0:a0,ee=a==="milestone"?t0:r0,oe=a==="milestone"?n0:o0,W=a==="milestone"?s0:l0,L=a==="milestone"?"Milestone":"Slice",pe=a==="milestone"?"milestone_interview":"slice_interview",fe=i.useCallback(Ue=>{ne.current?.close();const me=ee(Ue,c,{onThinking:re=>{E(_e=>_e+re),ce({sessionId:Ue,status:"generating",needsInput:!1,owningTabId:k,type:pe,title:o,projectId:c??null})},onQuestion:re=>{A(!1),B(),y({type:"question",sessionId:Ue,question:re}),E(""),ce({sessionId:Ue,status:"awaiting_input",needsInput:!0,owningTabId:k,type:pe,title:o,projectId:c??null})},onSummary:re=>{A(!1),B(),y({type:"summary",sessionId:Ue,summary:re}),R(re),E(""),ce({sessionId:Ue,status:"complete",needsInput:!1,owningTabId:k,type:pe,title:o,projectId:c??null})},onError:re=>{const _e=re||"Session failed while contacting the AI.";A(!1),v(null),y({type:"error",sessionId:Ue,errorMessage:_e}),E(""),F.current=Ue,ce({sessionId:Ue,status:"error",needsInput:!1,owningTabId:k,type:pe,title:o,projectId:c??null}),je({sessionId:Ue,status:"error"})},onComplete:()=>{A(!1),F.current=null,je({sessionId:Ue,status:"complete"})},onConnectionStateChange:re=>{A(re==="reconnecting")}});ne.current=me},[je,ce,ee,pe,c,k,o]),B=()=>{R(null),j([]),w([]),E("")},ve=i.useCallback(async()=>{v(null),B(),A(!1),y({type:"loading"});try{const{sessionId:Ue}=await Y(r,c);F.current=Ue,$(Ue),fe(Ue)}catch(Ue){A(!1),v(Ee(Ue)||`Failed to start ${L.toLowerCase()} interview`),y({type:"initial"}),F.current=null,$(null)}},[fe,c,Y,r,L]),Fe=i.useCallback(async()=>{v(null),K(!0);try{await W(r,c),s(),y({type:"applied"})}catch(Ue){v(Ee(Ue)||`Failed to skip ${L.toLowerCase()} interview`),K(!1)}},[s,c,W,r,L]);i.useEffect(()=>{e&&x.type==="initial"&&Z.current?.focus()},[e,x.type]),i.useEffect(()=>{if(!e||!d||x.type!=="initial")return;let Ue=!1;return Ti(d).then(me=>{if(Ue||!me)return;const re=kr(me.conversationHistory);if(w(re),$(me.id),j(re.map(_e=>_e.response).filter(_e=>!!(_e&&typeof _e=="object"&&!Array.isArray(_e)))),me.status==="awaiting_input"&&me.currentQuestion)try{const _e=JSON.parse(me.currentQuestion);F.current=me.id,y({type:"question",sessionId:me.id,question:_e})}catch{v("Failed to restore session question.")}else if(me.status==="complete"&&me.result)try{const _e=JSON.parse(me.result);F.current=me.id,R(_e),y({type:"summary",sessionId:me.id,summary:_e})}catch{v("Failed to restore session result.")}else me.status==="generating"?(F.current=me.id,me.thinkingOutput&&E(me.thinkingOutput),y({type:"loading"}),fe(me.id)):me.status==="error"&&(F.current=me.id,v(null),y({type:"error",sessionId:me.id,errorMessage:me.error??"The session encountered an error."}))}).catch(()=>{Ue||v("Failed to resume session.")}),()=>{Ue=!0}},[fe,e,d,x.type]),i.useEffect(()=>{e||(A(!1),$(null))},[e]),i.useEffect(()=>{if(!(!e||!P)){if(M.current!==P){M.current&&xe(M.current,k),He(P,k),M.current=P;return}!P&&M.current&&(xe(M.current,k),M.current=null)}},[He,xe,e,P,k]),i.useEffect(()=>{if(!e||!P||M.current!==P)return;Ne(k);const Ue=setInterval(()=>{Ne(k)},3e4);return()=>{clearInterval(Ue)}},[Ne,e,P,k]),i.useEffect(()=>()=>{ne.current?.close(),ne.current=null,M.current&&(xe(M.current,k),M.current=null)},[xe,k]);const ae=i.useCallback(()=>{ne.current?.close(),ne.current=null,n()},[n]),qe=i.useCallback(async()=>{ne.current?.close(),ne.current=null,B(),y({type:"initial"}),v(null),F.current=null,$(null),n()},[n]),Pe=i.useCallback(async Ue=>{if(x.type!=="question")return;const{sessionId:me}=x;v(null),j(re=>[...re,Ue]),w(re=>[...re,{question:x.question,response:Ue}]),y({type:"loading"}),E("");try{fe(me),await ie(me,Ue,c,k)}catch(re){ne.current?.close(),ne.current=null,v(Ee(re)||"Failed to submit response"),y({type:"question",sessionId:me,question:x.question})}},[fe,c,ie,k,x]),nt=i.useCallback(async()=>{if(x.type==="summary"){v(null),K(!0);try{await oe(x.sessionId,N||void 0,c),s(),y({type:"applied"})}catch(Ue){v(Ee(Ue)||"Failed to apply interview results"),K(!1)}}},[oe,N,s,c,x]),Be=()=>x.type==="question"?Math.min(S.length+1,6):6,de=x.type==="loading"||x.type==="question"||x.type==="summary"||x.type==="error",Ie=P?J.get(P):null,st=!!(Ie&&Ie.tabId!==k&&!Ie.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ue=>Ue.target===Ue.currentTarget&&qe(),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(gs,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",L,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[de&&t.jsx("button",{className:"modal-send-to-background",onClick:ae,title:"Send to background","aria-label":"Send to background",children:t.jsx(Lo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:qe,"aria-label":"Close",children:t.jsx(un,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[b&&t.jsx("div",{className:"form-error planning-error",children:b}),U&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),st&&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(gs,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",L," 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 ve(),children:[t.jsx(gs,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void Fe(),disabled:D,children:[D?t.jsx(jt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:qe,children:"Cancel"})]})]}),x.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:z?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>O(!I),type:"button",children:I?"Hide thinking":"Show thinking"}),I&&z&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:z})})]})]}),x.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[C.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:C}),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:qe,children:"Cancel"})})]})]})}),x.type==="question"&&t.jsx(v$,{question:x.question,progress:Be(),historyEntries:C,onSubmit:Pe}),x.type==="summary"&&N&&t.jsx(y$,{summary:N,historyEntries:C,onSummaryChange:R,onApply:nt,onCancel:qe,isApplying:D}),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:[L," 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 v$({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(mi,{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(y=>y!==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(un,{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($o,{size:16,className:"icon-ml-4"})]})})]})}function y$({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(mi,{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(pn,{size:16}):t.jsx(On,{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(jt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const ff=300,xl=220,vl=560,gf="fusion:mission-sidebar-width",eo={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)"}},bf={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)"}},xf={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)"}},yl={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)"}},wl={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)"}},kl={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)"}},vf={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)"}},w$=3,k$=new Set(["generating","awaiting_input","error"]);function j$(e){switch(e){case"generating":return"Generating plan";case"awaiting_input":return"Awaiting input";case"error":return"Needs retry";default:return e}}function yf(e){return e==="error"?"Retry interview":"Resume interview"}function N$(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function wf({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 kf(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const jf={title:"",description:"",status:"planning",autopilotEnabled:!1},Cd={title:"",description:"",status:"planning",dependencies:[]},Ed={title:"",description:"",status:"pending"},_d={title:"",description:"",acceptanceCriteria:"",status:"defined"},S$=3600*1e3;function ec(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 C$(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=S$,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 E$(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 _$(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 Md(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 mv=["feature_triaged","feature_completed"],hv=["slice_activated","slice_completed","milestone_completed"],pv=["mission_started","mission_paused","mission_resumed","mission_completed"],fv=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Nf(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return pv.includes(e);case"tasks":return mv.includes(e);case"slices":return hv.includes(e);case"autopilot":return fv.includes(e);default:return!0}}function M$(e){return e==="error"||e==="warning"?"mission-event__type--error":pv.includes(e)?"mission-event__type--state":mv.includes(e)?"mission-event__type--task":hv.includes(e)?"mission-event__type--slice":fv.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function A$(e){return e.replace(/_/g," ")}function R$(e,n){return n?e==="watching"?`Watching since ${ec(n)}`:`Last activation ${ec(n)}`:null}function I$({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),[y,b]=i.useState(!0),[v,S]=i.useState(!1),j=ri()==="mobile",[C,w]=i.useState(()=>{if(typeof window>"u")return ff;const H=window.localStorage.getItem(gf),ze=H?Number(H):NaN;return Number.isFinite(ze)?Math.max(xl,Math.min(vl,ze)):ff}),N=i.useCallback(H=>{try{window.localStorage.setItem(gf,String(H))}catch{}},[]),R=i.useCallback(H=>{if(j)return;H.preventDefault(),H.stopPropagation();const ze=H.currentTarget;typeof ze.setPointerCapture=="function"&&ze.setPointerCapture(H.pointerId);const Ge=H.clientX,Ct=C;let Nn=Ct;document.body.style.userSelect="none";const Vt=Ze=>{const rt=Ze.clientX-Ge,Bt=Math.max(xl,Math.min(vl,Ct+rt));Nn=Bt,w(Bt)},kn=Ze=>{typeof ze.releasePointerCapture=="function"&&ze.releasePointerCapture(Ze.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Vt),document.removeEventListener("pointerup",kn),N(Nn)};document.addEventListener("pointermove",Vt),document.addEventListener("pointerup",kn)},[j,N,C]),z=i.useCallback(H=>{if(j||H.key!=="ArrowLeft"&&H.key!=="ArrowRight")return;H.preventDefault();const ze=H.shiftKey?50:10,Ge=H.key==="ArrowLeft"?-ze:ze,Ct=Math.max(xl,Math.min(vl,C+Ge));w(Ct),N(Ct)},[j,N,C]),[E,I]=i.useState(!1),[O,U]=i.useState(null),[A,D]=i.useState(jf),[K,Z]=i.useState(!1),[ne,F]=i.useState(new Set),[M,P]=i.useState(new Set),[$,k]=i.useState(null),[J,ce]=i.useState(Cd),[je,He]=i.useState(!1),[xe,Ne]=i.useState(null),[Y,ie]=i.useState(Ed),[ee,oe]=i.useState(!1),[W,L]=i.useState(null),[pe,fe]=i.useState(null),[B,ve]=i.useState(_d),[Fe,ae]=i.useState(!1),[qe,Pe]=i.useState(null),[nt,Be]=i.useState(null),[de,Ie]=i.useState(""),[$e,st]=i.useState(!1),[Ue,me]=i.useState([]),[re,_e]=i.useState(void 0),xt=i.useRef(null),dt=re??(c&&xt.current===c?void 0:c),[Qe,vt]=i.useState(null),[Ae,Je]=i.useState(null),[ct,Nt]=i.useState(null);i.useEffect(()=>{h&&dt&&st(!0)},[h,dt]),i.useEffect(()=>{c&&xt.current!==c&&(xt.current=null)},[c]),i.useEffect(()=>{if(!h)return;let H=!1;return zu(r).then(ze=>{if(H)return;const Ge=ze.filter(Ct=>Ct.type!=="mission_interview"||!k$.has(Ct.status)?!1:r?Ct.projectId===r:Ct.projectId==null);me(Ge)}).catch(ze=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",ze)}),()=>{H=!0}},[h,r,dt]),i.useEffect(()=>{if(!h||!u)return;let H=!1;return Ti(u).then(ze=>{if(!(H||!ze))try{const Ge=JSON.parse(ze.inputPayload||"{}");Ge.targetId&&Ge.targetType&&vt({type:Ge.targetType,id:Ge.targetId,title:Ge.targetTitle||ze.title,resumeSessionId:u})}catch{vt({type:"milestone",id:"",title:ze.title,resumeSessionId:u})}}).catch(ze=>{H||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",ze),m?.())}),()=>{H=!0}},[h,u,m]);const[yt,Se]=i.useState(null),[G,ge]=i.useState(new Map),[pt,ke]=i.useState(null),[tt,Rt]=i.useState({title:"",assertion:"",status:"pending"}),[Re,be]=i.useState(!1),[at,ot]=i.useState(null),[gt,St]=i.useState(new Map),[Lt,Yt]=i.useState(new Set),[tn,mn]=i.useState(new Set),[Qt,yn]=i.useState(null),[Gt,on]=i.useState(new Map),[sn,ln]=i.useState(null),[Wt,ye]=i.useState(null),[Le,Ke]=i.useState(!0),[ut,Ve]=i.useState(new Set),[Pt,Ot]=i.useState(new Map),[bt,Dt]=i.useState(null),[Ft,Ht]=i.useState(new Map),[rn,Xt]=i.useState(null),[an,Me]=i.useState(new Map),[it,kt]=i.useState(new Map),[$t,se]=i.useState("structure"),[te,De]=i.useState([]),ft=i.useRef([]),qt=i.useRef([]),zt=i.useRef(null),Pn=i.useRef(null),he=i.useRef("structure"),mt=i.useRef("all"),[ht,wt]=i.useState(!1),[Xe,Et]=i.useState(0),[Zt,le]=i.useState("all"),[lt,nn]=i.useState(new Set),Rn=i.useRef(null),Hn=i.useRef(null);qt.current=f,zt.current=g,Pn.current=sn,he.current=$t,mt.current=Zt;const wn=i.useCallback((H="auto")=>{const ze=Hn.current;if(ze&&typeof ze.scrollIntoView=="function"){ze.scrollIntoView({block:"end",behavior:H});return}const Ge=Rn.current;Ge&&(Ge.scrollTop=Ge.scrollHeight)},[]),rs=i.useCallback(()=>{const H=Rn.current;return H?H.scrollHeight-H.scrollTop-H.clientHeight<=100:!0},[]),_s=i.useCallback(async H=>{if(H.length===0){kt(new Map);return}const ze=await w1(r);kt(Ge=>{const Ct=new Map(Ge);for(const[Nn,Vt]of Object.entries(ze))E$(Vt)&&Ct.set(Nn,Vt);return Ct})},[r]),bn=i.useCallback(async()=>{try{b(!0);const H=await g1(r);p(H),_s(H)}catch(H){a(Ee(H)||"Failed to load missions","error")}finally{b(!1)}},[a,r,_s]),Ut=i.useCallback(async H=>{try{S(!0);const ze=await fb(H,r);if(!ze||!Array.isArray(ze.milestones)){S(!1);return}if(x(ze),ze.milestones.length>0){const Ge=ze.milestones[0].id;ln(Ge),Ke(!0),F(new Set([Ge])),Dc(Ge,r).then(Ct=>{ge(Nn=>{const Vt=new Map(Nn);return Vt.set(Ge,Ct),Vt})}).catch(()=>{}),Lc(Ge,r).then(Ct=>{on(Nn=>{const Vt=new Map(Nn);return Vt.set(Ge,Ct),Vt})}).catch(()=>{}),ze.milestones[0].slices.length>0&&P(new Set([ze.milestones[0].slices[0].id]))}else ln(null),ye(null)}catch(ze){a(Ee(ze)||"Failed to load mission details","error")}finally{S(!1)}},[a,r]);i.useEffect(()=>{if(!h||!sn){ye(null);return}let H=!1;return ye(null),nh(sn,r).then(ze=>{if(!H){if(!Md(ze)){ye(null);return}ye(ze),on(Ge=>{const Ct=new Map(Ge);return Ct.set(sn,ze.rollup),Ct})}}).catch(()=>{H||ye(null)}),()=>{H=!0}},[h,sn,r]),i.useEffect(()=>{Ke(!0)},[sn]);const xs=i.useCallback(H=>{!H||H!==Pn.current||nh(H,r).then(ze=>{Pn.current!==H||!Md(ze)||(ye(ze),on(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze.rollup),Ct}))}).catch(()=>{})},[r]),xn=i.useCallback(async(H,ze)=>{const Ge=ze?.append??!1,Ct=Ge?ft.current.length:0;Ge||(wt(!0),nn(new Set));try{const Nn=await y1(H,{limit:50,offset:Ct,eventType:void 0},r),Vt=Nn.events.filter(kn=>Nf(kn.eventType,Zt));De(kn=>{if(!Ge)return ft.current=Vt,Vt;const Ze=new Set(kn.map(Bt=>Bt.id)),rt=[...kn];for(const Bt of Vt)Ze.has(Bt.id)||rt.push(Bt);return ft.current=rt,rt}),Et(Nn.total),Ge||requestAnimationFrame(()=>{wn("auto")})}catch(Nn){a(Ee(Nn)||"Failed to load mission activity","error")}finally{Ge||wt(!1)}},[a,Zt,r,wn]);i.useEffect(()=>{ft.current=te},[te]),i.useEffect(()=>{h&&(bn(),x(null),ln(null),ye(null),De([]),Et(0),se("structure"),le("all"),nn(new Set))},[h,bn]);const Xn=i.useRef(null);i.useEffect(()=>{h&&d&&Xn.current!==d&&f.length>0&&(Xn.current=d,Ut(d))},[h,d,f,Ut]),i.useEffect(()=>{h||(Xn.current=null)},[h]);const $n=i.useRef(!1);i.useEffect(()=>{!h||!n||j||y||$n.current||g||d||f.length!==0&&($n.current=!0,Ut(f[0].id))},[h,n,j,y,f,g,d,Ut]),i.useEffect(()=>{h||($n.current=!1)},[h]),i.useEffect(()=>{!h||!g||$t!=="activity"||xn(g.id)},[$t,h,xn,g,Zt]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const H=new URLSearchParams;r&&H.set("projectId",r);const ze=`/api/events${H.size>0?`?${H.toString()}`:""}`,Ge=()=>{_s(qt.current)},Ct=Tn=>{Ge();const Wn=Tn;if(Wn.data)try{const dn=JSON.parse(Wn.data);dn?.id&&p(Gs=>Gs.map(Ps=>Ps.id===dn.id?{...Ps,...dn}:Ps))}catch{}zt.current&&Ut(zt.current.id)},Nn=Tn=>{Ge(),zt.current&&Ut(zt.current.id)},Vt=()=>{Ge(),zt.current&&Ut(zt.current.id)},kn=Tn=>{Ge(),zt.current&&Ut(zt.current.id)},Ze=Tn=>{const Wn=Tn;if(Wn.data)try{const dn=JSON.parse(Wn.data);dn&&dn.featureId&&(oi(dn.featureId),gn(dn.featureId),dn.milestoneId&&xs(dn.milestoneId))}catch{}},rt=Tn=>{const Wn=Tn;if(Wn.data)try{const dn=JSON.parse(Wn.data);dn&&dn.featureId&&(oi(dn.featureId),gn(dn.featureId),dn.milestoneId&&xs(dn.milestoneId),zt.current&&Ut(zt.current.id))}catch{}},Bt=Tn=>{const Wn=Tn;if(Wn.data)try{const dn=JSON.parse(Wn.data);dn&&dn.milestoneId&&(Zn(dn.milestoneId),xs(dn.milestoneId))}catch{}},In=Tn=>{const Wn=Tn;if(Wn.data)try{const dn=JSON.parse(Wn.data);dn&&dn.milestoneId&&(ns(dn.milestoneId),Zn(dn.milestoneId),xs(dn.milestoneId))}catch{}};return hi(ze,{events:{"mission:updated":Ct,"slice:updated":Nn,"feature:updated":Vt,"milestone:updated":kn,"mission:event":Tn=>{Ge();const Wn=zt.current;if(!Wn||he.current!=="activity")return;const dn=rs(),Gs=Tn;if(Gs.data)try{const Ps=JSON.parse(Gs.data);if(!_$(Ps)||Ps.missionId!==Wn.id||!Nf(Ps.eventType,mt.current))return;De(fi=>{const Ca=fi.filter(Hr=>Hr.id!==Ps.id);return[Ps,...Ca].slice(0,100)}),Et(fi=>fi+1),dn&&requestAnimationFrame(()=>{const fi=Rn.current;fi&&(fi.scrollTop=0)})}catch{}},"validator-run:started":Ze,"validator-run:completed":rt,"milestone:validation:updated":Bt,"assertion:created":In,"assertion:updated":In,"assertion:deleted":In,"assertion:linked":In,"assertion:unlinked":In,"fix-feature:created":Tn=>{const Wn=Tn;if(Wn.data)try{const dn=JSON.parse(Wn.data);if(dn&&dn.sourceFeatureId){oi(dn.sourceFeatureId);const Gs=dn?.feature?.sliceId,Ps=zt.current;if(Gs&&Ps){const fi=Ps.milestones.find(Ca=>Ca.slices.some(Hr=>Hr.id===Gs));fi&&xs(fi.id)}zt.current&&Ut(zt.current.id)}}catch{}}}})},[h,rs,Ut,_s,r,xs]);const vs=i.useCallback(H=>{U(H.id),I(!1),D({title:H.title,description:H.description||"",status:H.status,autopilotEnabled:H.autopilotEnabled??!1})},[]),ms=i.useCallback(()=>{U(null),I(!1),D(jf)},[]),hs=i.useCallback(async()=>{if(!A.title.trim()){a("Mission title is required","error");return}try{if(Z(!0),E)await b1({title:A.title.trim(),description:A.description.trim()||void 0,autopilotEnabled:A.autopilotEnabled},r),a("Mission created","success");else if(O){const H={title:A.title.trim(),description:A.description.trim()||void 0,status:A.status,autopilotEnabled:A.autopilotEnabled};A.autopilotEnabled&&(H.autoAdvance=!0),await x1(O,H,r),a("Mission updated","success"),g?.id===O&&await Ut(O)}await bn(),ms()}catch(H){a(Ee(H)||"Failed to save mission","error")}finally{Z(!1)}},[A,E,O,a,bn,Ut,g,ms,r]),Jn=i.useCallback(async H=>{try{await v1(H,r),a("Mission deleted","success"),g?.id===H&&x(null),await bn(),Se(null)}catch(ze){a(Ee(ze)||"Failed to delete mission","error")}},[a,bn,g,r]),ps=i.useCallback(()=>{He(!0),k(null),ce(Cd)},[]),Ns=i.useCallback(H=>{k(H.id),He(!1),ce({title:H.title,description:H.description||"",status:H.status,dependencies:H.dependencies})},[]),Yn=i.useCallback(()=>{k(null),He(!1),ce(Cd)},[]),ys=i.useCallback(async()=>{if(!J.title.trim()){a("Milestone title is required","error");return}try{Z(!0),je&&g?(await k1(g.id,{title:J.title.trim(),description:J.description.trim()||void 0,dependencies:J.dependencies},r),a("Milestone created","success")):$&&(await j1($,{title:J.title.trim(),description:J.description.trim()||void 0,status:J.status,dependencies:J.dependencies},r),a("Milestone updated","success")),await Ut(g.id),Yn()}catch(H){a(Ee(H)||"Failed to save milestone","error")}finally{Z(!1)}},[J,je,$,g,a,Ut,Yn,A.title,r]),ws=i.useCallback(async H=>{try{await N1(H,r),a("Milestone deleted","success"),await Ut(g.id),Se(null)}catch(ze){a(Ee(ze)||"Failed to delete milestone","error")}},[a,Ut,g,r]),Ms=i.useCallback(H=>{ln(H),Ke(!0),F(ze=>{const Ge=new Set(ze);return!Ge.has(H)?(Ge.add(H),Dc(H,r).then(Nn=>{ge(Vt=>{const kn=new Map(Vt);return kn.set(H,Nn),kn})}).catch(()=>{}),Lc(H,r).then(Nn=>{on(Vt=>{const kn=new Map(Vt);return kn.set(H,Nn),kn})}).catch(()=>{})):Ge.delete(H),Ge})},[r]),X=i.useCallback(H=>{L(H),oe(!0),Ne(null),ie(Ed)},[]),_=i.useCallback(H=>{Ne(H.id),oe(!1),ie({title:H.title,description:H.description||"",status:H.status})},[]),ue=i.useCallback(()=>{Ne(null),oe(!1),L(null),ie(Ed)},[]),Ce=i.useCallback(async()=>{if(!Y.title.trim()){a("Slice title is required","error");return}try{Z(!0),ee&&W?(await S1(W,{title:Y.title.trim(),description:Y.description.trim()||void 0},r),a("Slice created","success")):xe&&(await C1(xe,{title:Y.title.trim(),description:Y.description.trim()||void 0,status:Y.status},r),a("Slice updated","success")),await Ut(g.id),ue()}catch(H){a(Ee(H)||"Failed to save slice","error")}finally{Z(!1)}},[Y,ee,xe,W,g,a,Ut,ue,r]),We=i.useCallback(async H=>{try{await E1(H,r),a("Slice deleted","success"),await Ut(g.id),Se(null)}catch(ze){a(Ee(ze)||"Failed to delete slice","error")}},[a,Ut,g,r]),At=i.useCallback(async H=>{try{await _1(H,r),a("Slice activated","success"),await Ut(g.id)}catch(ze){a(Ee(ze)||"Failed to activate slice","error")}},[a,Ut,g,r]),q=i.useCallback(H=>{P(ze=>{const Ge=new Set(ze);return Ge.has(H)?Ge.delete(H):Ge.add(H),Ge})},[]),we=i.useCallback(H=>{Pe(H),ae(!0),fe(null),ve(_d)},[]),Oe=i.useCallback(H=>{fe(H.id),ae(!1),ve({title:H.title,description:H.description||"",acceptanceCriteria:H.acceptanceCriteria||"",status:H.status})},[]),It=i.useCallback(()=>{fe(null),ae(!1),Pe(null),ve(_d)},[]),Kt=i.useCallback(async()=>{if(!B.title.trim()){a("Feature title is required","error");return}try{Z(!0),Fe&&qe?(await M1(qe,{title:B.title.trim(),description:B.description.trim()||void 0,acceptanceCriteria:B.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):pe&&(await A1(pe,{title:B.title.trim(),description:B.description.trim()||void 0,acceptanceCriteria:B.acceptanceCriteria.trim()||void 0,status:B.status},r),a("Feature updated","success")),await Ut(g.id),It()}catch(H){a(Ee(H)||"Failed to save feature","error")}finally{Z(!1)}},[B,Fe,pe,qe,g,a,Ut,It,r]),fn=i.useCallback(async H=>{try{await R1(H,r),a("Feature deleted","success"),await Ut(g.id),Se(null)}catch(ze){a(Ee(ze)||"Failed to delete feature","error")}},[a,Ut,g,r]),An=i.useCallback(async()=>{if(!nt||!de.trim()){a("Task ID is required","error");return}try{await I1(nt,de.trim(),r),a("Feature linked to task","success"),await Ut(g.id),Be(null),Ie("")}catch(H){a(Ee(H)||"Failed to link feature to task","error")}},[nt,de,a,Ut,g,r]),jn=i.useCallback(async H=>{try{await T1(H,r),a("Feature unlinked from task","success"),await Ut(g.id)}catch(ze){a(Ee(ze)||"Failed to unlink feature","error")}},[a,Ut,g,r]),En=i.useCallback(async H=>{try{Z(!0),await P1(H,void 0,void 0,r),a("Feature triaged — task created","success"),await Ut(g.id)}catch(ze){a(Ee(ze)||"Failed to triage feature","error")}finally{Z(!1)}},[a,Ut,g,r]),ts=i.useCallback(async H=>{Nt(H);try{const ze=await c0(H,r);Je({featureId:H,enrichedDescription:ze.description})}catch{await En(H)}finally{Nt(null)}},[En,r]),Ln=i.useCallback(async()=>{Ae&&(Je(null),await En(Ae.featureId))},[En,Ae]),os=i.useCallback(()=>{Je(null)},[]),fs=i.useCallback(async H=>{try{Z(!0);const ze=await $1(H,r);a(`Triaged ${ze.count} feature${ze.count!==1?"s":""}`,"success"),await Ut(g.id)}catch(ze){a(Ee(ze)||"Failed to triage slice features","error")}finally{Z(!1)}},[a,Ut,g,r]),ns=i.useCallback(async H=>{try{const ze=await Dc(H,r);ge(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),Zn=i.useCallback(async H=>{try{const ze=await Lc(H,r);on(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),es=i.useCallback(async H=>{if(!tt.title.trim()||!tt.assertion.trim()){a("Title and assertion text are required","error");return}try{Z(!0),await D1(H,{title:tt.title.trim(),assertion:tt.assertion.trim(),status:tt.status},r),a("Assertion created","success"),await ns(H),await Zn(H),be(!1),Rt({title:"",assertion:"",status:"pending"})}catch(ze){a(Ee(ze)||"Failed to create assertion","error")}finally{Z(!1)}},[tt,a,ns,Zn,r]),Ss=i.useCallback(H=>{ke(H.id),Rt({title:H.title,assertion:H.assertion,status:H.status})},[]),ls=i.useCallback(()=>{ke(null),be(!1),Rt({title:"",assertion:"",status:"pending"})},[]),ss=i.useCallback(async(H,ze)=>{if(!tt.title.trim()||!tt.assertion.trim()){a("Title and assertion text are required","error");return}try{Z(!0),await L1(H,{title:tt.title.trim(),assertion:tt.assertion.trim(),status:tt.status},r),a("Assertion updated","success"),await ns(ze),await Zn(ze),ls()}catch(Ge){a(Ee(Ge)||"Failed to update assertion","error")}finally{Z(!1)}},[tt,a,ns,Zn,ls,r]),Zs=i.useCallback(async H=>{try{const ze=await z1(H,r);St(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),Si=i.useCallback(async H=>{const ze=at!==H;ot(Ge=>Ge===H?null:H),ze&&await Zs(H)},[at,Zs]),ga=i.useCallback(H=>{ot(H),Zs(H),requestAnimationFrame(()=>{const ze=document.querySelector(`[data-mission-assertion-id="${H}"]`);ze instanceof HTMLElement&&typeof ze.scrollIntoView=="function"&&ze.scrollIntoView({behavior:"smooth",block:"center"})})},[Zs]),Va=i.useCallback(async(H,ze)=>{try{Yt(Ge=>new Set(Ge).add(ze)),await O1(H,ze,r),a("Feature linked to assertion","success"),await Zs(ze),yn(null)}catch(Ge){a(Ee(Ge)||"Failed to link feature","error")}finally{Yt(Ge=>{const Ct=new Set(Ge);return Ct.delete(ze),Ct})}},[a,Zs,r]),Wa=i.useCallback(async(H,ze)=>{const Ge=`${H}-${ze}`;try{mn(Ct=>new Set(Ct).add(Ge)),await F1(H,ze,r),a("Feature unlinked from assertion","success"),await Zs(ze)}catch(Ct){a(Ee(Ct)||"Failed to unlink feature","error")}finally{mn(Ct=>{const Nn=new Set(Ct);return Nn.delete(Ge),Nn})}},[a,Zs,r]),Ka=i.useCallback(async H=>{try{Ve(Ge=>new Set(Ge).add(H)),await B1(H,r),a("Validation triggered","success");const ze=await sh(H,r);Ot(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch(ze){a(Ee(ze)||"Failed to trigger validation","error")}finally{Ve(ze=>{const Ge=new Set(ze);return Ge.delete(H),Ge})}},[a,r]),oi=i.useCallback(async H=>{try{const ze=await sh(H,r);Ot(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),gn=i.useCallback(async H=>{try{const ze=await U1(H,{limit:10},r);Ht(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),Fi=i.useCallback(H=>{const ze=zt.current;if(ze){for(const Ge of ze.milestones)for(const Ct of Ge.slices)if(Ct.features.find(Vt=>Vt.id===H)){F(Vt=>{const kn=new Set(Vt);return kn.add(Ge.id),kn}),P(Vt=>{const kn=new Set(Vt);return kn.add(Ct.id),kn}),Dt(H),ln(Ge.id),oi(H),gn(H),requestAnimationFrame(()=>{const Vt=document.querySelector(`[data-mission-feature-id="${H}"]`);Vt instanceof HTMLElement&&typeof Vt.scrollIntoView=="function"&&Vt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[oi,gn]),ea=i.useCallback(async H=>{try{const ze=await H1(H,r);Me(Ge=>{const Ct=new Map(Ge);return Ct.set(H,ze),Ct})}catch{}},[r]),ba=i.useCallback(async H=>{bt===H?Dt(null):(Dt(H),await oi(H),await gn(H))},[bt,oi,gn]),Ga=i.useCallback(async H=>{rn===H?Xt(null):(Xt(H),await ea(H))},[rn,ea]),xa=i.useCallback(async H=>{try{await q1(H,r),a("Mission resumed","success"),await Ut(H),bn()}catch(ze){a(Ee(ze)||"Failed to resume mission","error")}},[a,Ut,bn,r]),va=i.useCallback(async H=>{try{const Ge=(await V1(H,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Ge} task${Ge!==1?"s":""} paused)`,"success"),await Ut(H),bn()}catch(ze){a(Ee(ze)||"Failed to stop mission","error")}},[a,Ut,bn,r]),ya=i.useCallback(async H=>{try{await W1(H,r),a("Mission started — first slice activated","success"),await Ut(H),bn()}catch(ze){a(Ee(ze)||"Failed to start mission","error")}},[a,Ut,bn,r]),Ja=i.useCallback(async(H,ze)=>{try{await K1(H,{enabled:ze},r),a(ze?"Autopilot enabled":"Autopilot disabled","success"),await Ut(H),bn()}catch(Ge){a(Ee(Ge)||"Failed to update autopilot","error")}},[a,Ut,bn,r]),wa=i.useCallback(H=>{se("structure"),ln(null),ye(null),De([]),Et(0),le("all"),nn(new Set),Ut(H.id)},[Ut]),Fr=i.useCallback(()=>{x(null),ln(null),ye(null),se("structure"),De([]),Et(0),le("all"),nn(new Set),bn()},[bn]),ka=te.length<Xe,Us=g?.autopilotState??"inactive",Ci=Us==="watching"||Us==="activating",ei=R$(Us,g?.lastAutopilotActivityAt),ta=i.useMemo(()=>!Wt||!sn||!Md(Wt)?null:Wt.rollup.milestoneId===sn?Wt:null,[sn,Wt]),ja=i.useMemo(()=>{const H=new Map;for(const ze of ta?.validationTelemetry.validationRounds??[]){const Ge=H.get(ze.featureId);(!Ge||ze.startedAt>Ge.startedAt)&&H.set(ze.featureId,ze)}return H},[ta]),zr=i.useCallback(()=>{!g||ht||!ka||xn(g.id,{append:!0})},[ht,ka,xn,g]),Ei=i.useCallback(H=>{nn(ze=>{const Ge=new Set(ze);return Ge.has(H)?Ge.delete(H):Ge.add(H),Ge})},[]),Na=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),hs())},[hs]),Sa=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),ys())},[ys]),zi=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Ce())},[Ce]),Ya=i.useCallback(H=>{H.key==="Enter"&&!H.shiftKey&&(H.preventDefault(),Kt())},[Kt]),Br=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const H=ze=>{ze.key==="Escape"&&s()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[h,s]),!h)return null;const Qa=()=>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:[Ci&&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:(eo[g.status]||eo.planning).bg,color:(eo[g.status]||eo.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:H=>Ja(g.id,H.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(as,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(wl[Us]||wl.inactive).bg,color:(wl[Us]||wl.inactive).text},"data-testid":"autopilot-state-badge",children:[Ci&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Us]})]}),ei&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:ei})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>va(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(Ii,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xa(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(is,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ya(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vs(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(_n,{size:14})})]})]}),O===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:H=>D({...A,title:H.target.value}),onKeyDown:Na,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:H=>D({...A,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:A.status,onChange:H=>D({...A,status:H.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:H=>D({...A,autopilotEnabled:H.target.checked})}),t.jsx(as,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:hs,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ms,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:()=>se("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:()=>se("activity"),role:"tab","aria-selected":$t==="activity","data-testid":"mission-tab-activity",children:["Activity (",Xe,")"]})]}),$t==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(H=>{const ze=ta?.rollup.milestoneId===H.id?ta:null,Ge=ze?.rollup??Gt.get(H.id),Ct=ze?.validationTelemetry.validationRounds??[],Nn=ze?.fixFeatures??[],Vt=vf[Ge?.state??"not_started"]??vf.not_started,kn=Ge&&(Ge.state==="blocked"||Ge.state==="failed")?ze?.validationTelemetry.validationRounds.find(Ze=>Ze.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Ms(H.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:ne.has(H.id)?t.jsx(pn,{size:16}):t.jsx(On,{size:16})}),t.jsx($a,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:H.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:bf[H.status].bg,color:bf[H.status].text},children:H.status}),t.jsxs("span",{className:"mission-milestone__count",children:[H.slices.length," slices"]}),t.jsx(wf,{state:N$(H.interviewState)}),Ge&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},title:"Validation state",children:kf(Ge.state)}),Ge.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),H.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>vt({type:"milestone",id:H.id,title:H.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(ua,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Ze=>Ze.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>X(H.id),title:"Add slice",children:t.jsx(Mn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ns(H),title:"Edit milestone",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"milestone",id:H.id}),title:"Delete milestone",children:t.jsx(_n,{size:14})})]})]}),ne.has(H.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(je||$===H.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:Ze=>ce({...J,title:Ze.target.value}),onKeyDown:Sa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:Ze=>ce({...J,description:Ze.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ys,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),$?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),ze&&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:[ze.validationTelemetry.totalRuns," rounds",ze.validationTelemetry.lastValidatorStatus?` · Last ${ze.validationTelemetry.lastValidatorStatus}`:""]})]}),kn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",kn]}),Ct.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:()=>Ke(Ze=>!Ze),title:Le?"Hide validation rounds":"Show validation rounds",children:[Le?t.jsx(pn,{size:12}):t.jsx(On,{size:12}),"Validation rounds (",Ct.length,")"]}),Le&&t.jsx("div",{className:"mission-validation-rounds__list",children:Ct.map(Ze=>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--${Ze.validatorStatus}`,children:Ze.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Ze.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Ze.implementationAttempt," · reviewer #",Ze.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Ze.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.failedAssertionIds.map(rt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ga(rt),title:`Jump to assertion ${rt}`,children:rt},`${Ze.roundId}-${rt}`))}):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:"}),Ze.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Ze.generatedFixFeatureIds.map(rt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Fi(rt),title:`Jump to fix feature ${rt}`,children:rt},`${Ze.roundId}-${rt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Ze.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Ze.blockedReason})]},Ze.roundId))})]}),Nn.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:Nn.map(Ze=>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:()=>Fi(Ze.id),title:`Jump to feature ${Ze.id}`,children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:yl[Ze.status].bg,color:yl[Ze.status].text},children:Ze.status}),Ze.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Ze.loopState}`,children:Ze.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:()=>Fi(Ze.sourceFeatureId),title:`Jump to source feature ${Ze.sourceFeatureId}`,children:Ze.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Ze.runId})]}),Ze.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:Ze.failedAssertionIds.map(rt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ga(rt),title:`Jump to assertion ${rt}`,children:rt},`${Ze.id}-${rt}`))})]})]},Ze.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[H.slices.map(Ze=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>q(Ze.id),children:[t.jsx("button",{className:"mission-slice__expand",children:M.has(Ze.id)?t.jsx(pn,{size:16}):t.jsx(On,{size:16})}),t.jsx(eu,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Ze.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:xf[Ze.status].bg,color:xf[Ze.status].text},children:Ze.status}),t.jsxs("span",{className:"mission-slice__count",children:[Ze.features?.length||0," features"]}),t.jsx(wf,{state:Ze.planState??"not_started"}),Ze.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>vt({type:"slice",id:Ze.id,title:Ze.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(ua,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:rt=>rt.stopPropagation(),children:[Ze.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>At(Ze.id),title:"Activate slice",children:t.jsx(is,{size:14})}),Ze.status==="active"&&Ze.features?.some(rt=>rt.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>fs(Ze.id),title:"Triage all features",disabled:K,children:K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(as,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>we(Ze.id),title:"Add feature",children:t.jsx(Mn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>_(Ze),title:"Edit slice",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"slice",id:Ze.id}),title:"Delete slice",children:t.jsx(_n,{size:14})})]})]}),M.has(Ze.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ee&&W===H.id&&!xe&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:Y.title,onChange:rt=>ie({...Y,title:rt.target.value}),onKeyDown:zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:rt=>ie({...Y,description:rt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Ce,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ue,children:"Cancel"})]})]}),xe===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:Y.title,onChange:rt=>ie({...Y,title:rt.target.value}),onKeyDown:zi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:Y.description,onChange:rt=>ie({...Y,description:rt.target.value}),rows:2}),t.jsxs("select",{value:Y.status,onChange:rt=>ie({...Y,status:rt.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:Ce,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ue,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Ze.features?.map(rt=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":rt.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>ba(rt.id),title:bt===rt.id?"Collapse details":"Expand to show run history",children:bt===rt.id?t.jsx(pn,{size:14}):t.jsx(On,{size:14})}),t.jsx(Gd,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:rt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:yl[rt.status].bg,color:yl[rt.status].text},children:rt.status}),rt.loopState&&rt.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${rt.loopState}`,title:`Loop state: ${rt.loopState}`,children:[rt.loopState==="implementing"&&"⏳",rt.loopState==="validating"&&"🔄",rt.loopState==="needs_fix"&&"🔧",rt.loopState==="passed"&&"✅",rt.loopState==="blocked"&&"🚫"]}),rt.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Fi(rt.generatedFromFeatureId),title:`Generated from feature: ${rt.generatedFromFeatureId}`,children:"🔗 Fix"}),(rt.loopState==="validating"||rt.loopState==="needs_fix")&&(()=>{const Bt=Pt.get(rt.id),In=ja.get(rt.id),Vn=Bt?.implementationAttemptCount??In?.implementationAttempt??rt.implementationAttemptCount??0,ti=Bt?.retryBudgetRemaining??Math.max(0,w$-Vn);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",Vn," · ",ti," ",ti===1?"retry":"retries"," left"]})})(),rt.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Ka(rt.id),title:"Validate feature",disabled:ut.has(rt.id),children:ut.has(rt.id)?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(gs,{size:14})}),rt.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(rt.taskId),title:"Click to view task",children:rt.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[rt.status==="defined"&&!rt.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ts(rt.id),title:"Triage — create task",disabled:K||ct===rt.id,children:ct===rt.id?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(as,{size:14})}),rt.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>jn(rt.id),title:"Unlink task",children:t.jsx(Rm,{size:14})}):rt.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>Be(rt.id),title:"Link to task",children:t.jsx(xr,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>Oe(rt),title:"Edit feature",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"feature",id:rt.id}),title:"Delete feature",children:t.jsx(_n,{size:14})})]})]}),rt.description&&t.jsx("p",{className:"mission-feature__description",children:rt.description}),rt.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",rt.acceptanceCriteria]}),Ae?.featureId===rt.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:Ae.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:Ln,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:os,disabled:K,children:"Cancel"})]})]}),pe===rt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:B.title,onChange:Bt=>ve({...B,title:Bt.target.value}),onKeyDown:Ya,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:B.description,onChange:Bt=>ve({...B,description:Bt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:B.acceptanceCriteria,onChange:Bt=>ve({...B,acceptanceCriteria:Bt.target.value}),rows:2}),t.jsxs("select",{value:B.status,onChange:Bt=>ve({...B,status:Bt.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:Kt,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:It,children:"Cancel"})]})]}),bt===rt.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"})}),(Ft.get(rt.id)??[]).map(Bt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Ga(Bt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Bt.status}`,title:Bt.status,children:Bt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Bt.startedAt).toLocaleString()}),Bt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Bt.completedAt).getTime()-new Date(Bt.startedAt).getTime())/1e3),"s"]}),Bt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Bt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:rn===Bt.id?"Hide details":"Show details",children:rn===Bt.id?t.jsx(pn,{size:12}):t.jsx(On,{size:12})})]}),rn===Bt.id&&an.get(Bt.id)&&t.jsxs("div",{className:"mission-run__details",children:[Bt.summary&&t.jsx("p",{className:"mission-run__summary",children:Bt.summary}),Bt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Bt.blockedReason]}),an.get(Bt.id)?.failures&&an.get(Bt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),an.get(Bt.id).failures.map(In=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:In.message}),In.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",In.expected]}),In.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",In.actual]})]},In.id))]}),(!an.get(Bt.id)?.failures||an.get(Bt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Bt.id)),(!Ft.get(rt.id)||Ft.get(rt.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},rt.id)),Fe&&qe===Ze.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:B.title,onChange:rt=>ve({...B,title:rt.target.value}),onKeyDown:Ya,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:B.description,onChange:rt=>ve({...B,description:rt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:B.acceptanceCriteria,onChange:rt=>ve({...B,acceptanceCriteria:rt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Kt,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:It,children:"Cancel"})]})]}),!Fe&&(!Ze.features||Ze.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Gd,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Ze.id)),H.slices.length===0&&!ee&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(eu,{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"}),Ge&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},children:kf(Ge.state)}),Ge&&Ge.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{be(!0),ke(null),Rt({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Mn,{size:14})})]}),Re&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:tt.title,onChange:Ze=>Rt({...tt,title:Ze.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:tt.assertion,onChange:Ze=>Rt({...tt,assertion:Ze.target.value}),rows:2}),t.jsxs("select",{value:tt.status,onChange:Ze=>Rt({...tt,status:Ze.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:()=>es(H.id),disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ls,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(G.get(H.id))?G.get(H.id):[]).map(Ze=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Ze.id,children:[t.jsx("div",{className:"mission-assertion__header",children:pt===Ze.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:tt.title,onChange:rt=>Rt({...tt,title:rt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:tt.assertion,onChange:rt=>Rt({...tt,assertion:rt.target.value}),rows:2}),t.jsxs("select",{value:tt.status,onChange:rt=>Rt({...tt,status:rt.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:()=>ss(Ze.id,H.id),disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ls,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(kl[Ze.status]??kl.pending).bg,color:(kl[Ze.status]??kl.pending).text},children:Ze.status}),t.jsx("span",{className:"mission-assertion__title",children:Ze.title}),(()=>{const Bt=gt.get(Ze.id)?.length??0;return Bt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Bt} linked feature${Bt!==1?"s":""}`,children:["(",Bt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Si(Ze.id),title:"Toggle details",children:at===Ze.id?t.jsx(pn,{size:14}):t.jsx(On,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ss(Ze),title:"Edit assertion",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"assertion",id:Ze.id}),title:"Delete assertion",children:t.jsx(_n,{size:14})})]})}),at===Ze.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Ze.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()=>{at!==Ze.id&&await Si(Ze.id),yn(Qt===Ze.id?null:Ze.id)},title:"Link a feature",children:[t.jsx(xr,{size:12}),"Link Feature"]})]}),Qt===Ze.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const rt=new Set((gt.get(Ze.id)??[]).map(In=>In.id)),Bt=[];return g?.milestones.forEach(In=>In.slices.forEach(Vn=>Bt.push(...Vn.features.filter(ti=>!rt.has(ti.id))))),Bt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Bt.map(In=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Va(In.id,Ze.id),disabled:Lt.has(Ze.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:In.title}),Lt.has(Ze.id)&&t.jsx(jt,{size:12,className:"spinner"})]},In.id))})()})}),(()=>{const rt=gt.get(Ze.id)??[];return rt.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):rt.map(Bt=>{const In=`${Bt.id}-${Ze.id}`,Vn=tn.has(In);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Bt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Wa(Bt.id,Ze.id),disabled:Vn,title:"Unlink feature",children:Vn?t.jsx(jt,{size:12,className:"spinner"}):t.jsx(Rm,{size:12})})]},Bt.id)})})()]})]})]},Ze.id)),(!G.get(H.id)||G.get(H.id)?.length===0)&&!Re&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},H.id)}),g&&!je&&$===null&&t.jsxs("button",{className:"mission-add-btn",onClick:ps,children:[t.jsx(Mn,{size:16}),"Add Milestone"]}),je&&$===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:J.title,onChange:H=>ce({...J,title:H.target.value}),onKeyDown:Sa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:J.description,onChange:H=>ce({...J,description:H.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:ys,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),g.milestones.length===0&&!je&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx($a,{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:Zt,onChange:H=>le(H.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:[te.length," of ",Xe]})]}),!ht&&ka&&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:zr,"data-testid":"mission-activity-load-more",children:"Load more"})}),ht?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(jt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):te.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ys,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:Rn,className:"mission-events","data-testid":"mission-activity-events",children:[te.map(H=>{const ze=!!(H.metadata&&Object.keys(H.metadata).length>0),Ge=lt.has(H.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${M$(H.eventType)}`,children:A$(H.eventType)}),t.jsx("span",{className:"mission-event__time",children:ec(H.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:H.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(H.timestamp).toLocaleString()}),ze&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Ei(H.id),"data-testid":`mission-event-metadata-${H.id}`,children:[Ge?"Hide":"Show"," metadata"]}),Ge&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(H.metadata,null,2)})]})]},H.id)}),t.jsx("div",{ref:Hn})]})]})]}):null,Xa=H=>{_e(H),st(!0)},Za=()=>{xt.current=dt??null,_e(void 0),st(!1)},Ur=()=>Ue.map(H=>{const ze=H.status==="error",Ge=H.status==="generating";return t.jsxs("div",{className:"mission-list__item mission-list__item--interview",onClick:()=>Xa(H.id),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(gs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:H.title||"Mission interview"})]}),t.jsx("div",{className:"mission-list__item-tags",children:t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--${H.status}`,children:j$(H.status)})}),t.jsx("p",{className:"mission-list__item-description",children:Ge?"Generating mission hierarchy from interview context.":ze?"Interview hit an error. Retry from this list item.":"Interview is waiting for your next response."})]}),t.jsx("div",{className:"mission-list__item-actions",onClick:Ct=>Ct.stopPropagation(),children:t.jsx("button",{className:`mission-icon-btn ${ze?"mission-icon-btn--danger":"mission-icon-btn--success"}`,onClick:()=>Xa(H.id),title:yf(H.status),"aria-label":yf(H.status),children:Ge?t.jsx(jt,{size:14,className:"spinner"}):ze?t.jsx(bs,{size:14}):t.jsx(gs,{size:14})})})]},H.id)}),Ye=(H,ze)=>H.map(Ge=>{const Ct=Ge,Nn=g?.id===Ct.id,Vt=eo[Ct.status]||{bg:"",text:""},kn=Ct.summary,Ze=it.get(Ct.id),rt=C$(Ze),Bt=!!(kn&&(kn.totalMilestones>0||kn.totalFeatures>0)),In=Ze?.totalTasks??0,Vn=Ze?.tasksCompleted??0,ti=Ze?.tasksFailed??0,Tn=Ze?.estimatedCompletionPercent??kn?.progressPercent??0,Wn=Bt||In>0||ti>0||!!Ze?.lastActivityAt,dn=ze?.interviewStyle===!0;return t.jsxs("div",{className:`mission-list__item ${Nn?"mission-list__item--selected":""} ${dn?"mission-list__item--interview":""}`,onClick:()=>wa(Ge),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(Rs,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:Ct.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[Ge.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(as,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${rt}`,"data-testid":`mission-health-badge-${Ct.id}`,"aria-label":`Mission health: ${rt}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},children:Ct.status}),dn&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--awaiting_input",children:"Interview in progress"})]}),dn?t.jsx("p",{className:"mission-list__item-description",children:"Mission interview is still in progress. Open this mission to continue planning."}):Ct.description?t.jsx("p",{className:"mission-list__item-description",children:Ct.description}):null,Wn&&t.jsxs("div",{className:"mission-list__item-summary",children:[Bt&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[kn.completedMilestones,"/",kn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[kn.completedFeatures,"/",kn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${Ct.id}`,children:[Vn,"/",In," tasks"]}),ti>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:Gs=>{Gs.stopPropagation(),wa(Ge)},"data-testid":`mission-failed-${Ct.id}`,title:"View mission failures",children:[ti," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${rt}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${Tn}%`}})})]}),Wn&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${Ct.id}`,children:["Activity ",ec(Ze?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:Gs=>Gs.stopPropagation(),children:[Ct.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>va(Ct.id),title:"Stop mission",children:t.jsx(Ii,{size:14})}),Ct.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xa(Ct.id),title:"Resume mission",children:t.jsx(is,{size:14})}),Ct.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>ya(Ct.id),title:"Start mission",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>vs(Ge),title:"Edit mission",children:t.jsx(qs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Se({type:"mission",id:Ct.id}),title:"Delete mission",children:t.jsx(_n,{size:14})})]})]},Ct.id)}),Tt=({hideBottomButtons:H=!1}={})=>{const ze=f.filter(Vt=>Vt.interviewState==="in_progress"),Ge=f.filter(Vt=>Vt.interviewState!=="in_progress"),Ct=j&&f.length>0&&!E,Nn=!H&&!Ct;return t.jsxs("div",{className:"mission-list",children:[E&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:Vt=>D({...A,title:Vt.target.value}),onKeyDown:Na,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:Vt=>D({...A,description:Vt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:hs,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ms,children:"Cancel"})]})]}),Ct&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>st(!0),children:[t.jsx(gs,{size:14}),"Plan New Mission"]})}),Ye(ze,{interviewStyle:!0}),Ye(Ge),Ur(),O&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:A.title,onChange:Vt=>D({...A,title:Vt.target.value}),onKeyDown:Na,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:A.description,onChange:Vt=>D({...A,description:Vt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:A.status,onChange:Vt=>D({...A,status:Vt.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:Vt=>D({...A,autopilotEnabled:Vt.target.checked})}),t.jsx(as,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:hs,disabled:K,children:[K?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(js,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ms,children:"Cancel"})]})]}),f.length===0&&!E&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(Rs,{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:()=>st(!0),children:[t.jsx(gs,{size:14}),"Plan New Mission"]})]}),!E&&t.jsx("div",{className:"mission-list__footer",children:Nn&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>st(!0),children:[t.jsx(gs,{size:16}),"Plan New Mission"]})})})]})},cn=()=>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 ",yt?.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()=>{yt&&(yt.type==="mission"?await Jn(yt.id):yt.type==="milestone"?await ws(yt.id):yt.type==="slice"?await We(yt.id):yt.type==="feature"&&await fn(yt.id))},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Se(null),children:"Cancel"})]})]})}),cs=()=>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:de,onChange:H=>Ie(H.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(H=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ie(H.id),children:[H.id,": ",H.title||"Untitled"]},H.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:An,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{Be(null),Ie("")},children:"Cancel"})]})]})}),qn=t.jsxs("div",{ref:Br,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:Fr,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(lc,{size:18})}),t.jsx(Rs,{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(un,{size:18})})]}),j?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Qa():Tt(),yt&&cn(),nt&&cs()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:j?void 0:{width:`${C}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-list",children:y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):Tt({hideBottomButtons:!0})}),t.jsx("div",{className:"mission-manager__sidebar-footer","data-testid":"mission-sidebar-footer",children:t.jsxs("button",{className:"btn btn-primary mission-manager__sidebar-cta",onClick:()=>st(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(gs,{size:14}),"Plan New Mission"]})})]}),!j&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":xl,"aria-valuemax":vl,"aria-valuenow":C,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:R,onKeyDown:z}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?Qa():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(Rs,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),yt&&cn(),nt&&cs()]})]})]}),Cs=t.jsx(c$,{isOpen:$e,onClose:Za,onMissionCreated:()=>{bn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:dt}),na=Qe?t.jsx(x$,{isOpen:!0,onClose:()=>vt(null),onApplied:()=>{vt(null),g&&Ut(g.id)},targetType:Qe.type,targetId:Qe.id,targetTitle:Qe.title,missionContext:g?.title,projectId:r,resumeSessionId:Qe.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[qn,Cs,na]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:H=>H.target===H.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:qn}),Cs,na]})}const T$={pre:({children:e,...n})=>t.jsx("pre",{...n,className:"mailbox-markdown-pre",children:e}),table:({children:e,...n})=>t.jsx("table",{...n,className:"mailbox-markdown-table",children:e}),a:({children:e,...n})=>t.jsx("a",{...n,target:"_blank",rel:"noopener noreferrer",children:e})},Sf=i.memo(function({content:n,className:s,testId:a}){const r=s?`mailbox-markdown ${s}`:"mailbox-markdown";return t.jsx("div",{className:r,"data-testid":a,children:t.jsx(ki,{remarkPlugins:[ji],components:T$,children:n})})}),jl=2e3;function Cf({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),[y,b]=i.useState(!1),[v,S]=i.useState(null),j=i.useRef(null),C=i.useMemo(()=>s.find(U=>U.id===d),[s,d]),w=i.useMemo(()=>e?s.find(U=>U.id===e.id):void 0,[s,e]),N=m==="agent",R=N&&C?.runtimeConfig?.messageResponseMode==="immediate",z=N&&(g||R),E=d.trim()!==""&&f.trim().length>0&&f.length<=jl,I=i.useCallback(async()=>{if(!(!E||y)){b(!0),S(null);try{const U=m==="agent"?"user-to-agent":"system",A=n?{replyTo:{messageId:n.messageId}}:void 0,D=z;await y0({toId:d.trim(),toType:m,content:f.trim(),type:U,...A?{metadata:A}:{},...D?{wakeImmediately:!0}:{}},a),r()}catch(U){const A=Ee(U)||"Failed to send message";S(A),l?.(A,"error")}finally{b(!1)}}},[E,y,d,m,f,z,n,a,r,l]),O=i.useCallback(U=>{u(U),h("agent")},[]);return i.useEffect(()=>{n&&j.current?.focus()},[n]),i.useEffect(()=>{if(!n||typeof window>"u"||window.visualViewport==null)return;const U=()=>{j.current?.scrollIntoView({block:"center",behavior:"auto"})};return window.visualViewport.addEventListener("resize",U),()=>{window.visualViewport?.removeEventListener("resize",U)}},[n]),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(un,{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:U=>O(U.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(U=>t.jsx("option",{value:U.id,children:U.name||U.id},U.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}),w?.name||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",ref:j,className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:U=>p(U.target.value),maxLength:jl,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>jl?"over-limit":"",children:[f.length,"/",jl]})})]}),N&&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:z,disabled:R,onChange:U=>x(U.target.checked),"data-testid":"message-composer-wake"}),t.jsxs("span",{children:["Wake agent immediately",t.jsx("span",{className:"message-composer-wake-hint","data-testid":"message-composer-wake-hint",children:R?"(agent is already set to immediate response mode)":"(one-off override for this message only)"})]})]})}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Ws,{size:14}),t.jsx("span",{children:v})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:I,disabled:!E||y,"data-testid":"message-composer-send",children:y?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Ia,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}const Ls="__all_agents__",tc=280,Nu=.65,Ad=16,Ef=320;function Su(e){return Math.max(tc,e*Nu)}function Rd(e,n){const s=Su(n);return Math.min(Math.max(e,tc),s)}function _f(e){try{const n=Bn("kb-dashboard-mailbox-sidebar-width",e);if(!n)return Ef;const s=Number(n);if(Number.isFinite(s)&&s>0)return s}catch{}return Ef}function qi(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 P$(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 $$(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 Mf(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function Af(){if(typeof window>"u")return null;const n=new URLSearchParams(window.location.search).get("mailbox-message");return n||(/^#message-(.+)$/.exec(window.location.hash)?.[1]??null)}function to(e){return`mailbox-list-message-${e}`}function Id(e){return`mailbox-detail-message-${e}`}function D$(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 L$({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,y]=i.useState([]),[b,v]=i.useState(!1),[S,j]=i.useState(null),[C,w]=i.useState(null),[N,R]=i.useState(null),[z,E]=i.useState("inbox"),[I,O]=i.useState(null),[U,A]=i.useState(null),[D,K]=i.useState([]),[Z,ne]=i.useState("pending"),[F,M]=i.useState([]),[P,$]=i.useState(0),[k,J]=i.useState(null),[ce,je]=i.useState(""),[He,xe]=i.useState(!1),Ne=i.useMemo(()=>new Map(D.map(G=>[G.id,G.name??""])),[D]),Y=i.useCallback((G,ge)=>P$(G,ge,Ne),[Ne]),ee=ri()==="mobile",oe=!ee,[W,L]=i.useState(()=>_f(e)),pe=i.useRef(null),{keyboardOverlap:fe,viewportHeight:B,viewportOffsetTop:ve,keyboardOpen:Fe}=Zi({enabled:ee}),ae=i.useMemo(()=>{if(Fe)return{"--keyboard-overlap":`${fe}px`,"--vv-offset-top":`${ve}px`,...B!=null?{"--vv-height":`${B}px`}:{}}},[Fe,fe,B,ve]);i.useEffect(()=>{L(_f(e))},[e]),i.useEffect(()=>{if(!oe)return;const G=pe.current?.clientWidth;G&&L(ge=>Rd(ge,G))},[oe]),i.useEffect(()=>{if(oe)try{us("kb-dashboard-mailbox-sidebar-width",String(W),e)}catch{}},[oe,e,W]);const qe=i.useCallback(G=>{if(!oe)return;G.preventDefault();const ge=pe.current;if(!ge)return;const pt=ge.getBoundingClientRect(),ke=Rt=>{const Re=Rt.clientX-pt.left;L(Rd(Re,pt.width))},tt=()=>{window.removeEventListener("mousemove",ke),window.removeEventListener("mouseup",tt)};window.addEventListener("mousemove",ke),window.addEventListener("mouseup",tt)},[oe]),Pe=i.useCallback(G=>{if(!oe)return;const ge=pe.current?.clientWidth??0,pt=W/Nu+Ad,ke=Math.max(ge,pt),tt=Su(ke);if(G.key==="ArrowLeft"||G.key==="ArrowRight"){G.preventDefault();const Rt=G.key==="ArrowLeft"?-Ad:Ad;L(Re=>Rd(Re+Rt,ke));return}if(G.key==="Home"){G.preventDefault(),L(tc);return}G.key==="End"&&(G.preventDefault(),L(tt))},[oe,W]),nt=i.useCallback(async()=>{f(!0);try{const G=await x0({limit:50},e);l(G),m(G.unreadCount),s?.(G.unreadCount)}catch{}finally{f(!1)}},[e,s]),Be=i.useCallback(async()=>{f(!0);try{const G=await v0({limit:50},e);d(G)}catch{}finally{f(!1)}},[e]),de=i.useCallback(async G=>{f(!0);try{const ge=await S0(G,e);O(ge)}catch{}finally{f(!1)}},[e]),Ie=i.useCallback(async()=>{f(!0);try{const G=await C0(e);A(G)}catch{}finally{f(!1)}},[e]),$e=i.useCallback(async()=>{try{const G=await Pr(void 0,e);K(G)}catch{}},[e]),st=i.useCallback(async()=>{try{const G=await xb(e);m(G.unreadCount),s?.(G.unreadCount)}catch{}},[e,s]),Ue=i.useCallback(async G=>{f(!0);try{const ge=await nl({status:G==="pending"?"pending":void 0,limit:100},e);if(G==="pending")M(ge.requests);else{const[pt,ke,tt]=await Promise.all([nl({status:"approved",limit:100},e),nl({status:"denied",limit:100},e),nl({status:"completed",limit:100},e)]);M([...pt.requests,...ke.requests,...tt.requests].sort((Rt,Re)=>Re.updatedAt.localeCompare(Rt.updatedAt)))}$(ge.pendingCount)}catch{}finally{f(!1)}},[e]);i.useEffect(()=>{a==="inbox"?nt():a==="outbox"?Be():a==="agents"?$e():a==="approvals"&&Ue(Z)},[a,nt,Be,$e,Ue,Z]),i.useEffect(()=>{if(N){if(N===Ls){Ie();return}de(N)}},[N,de,Ie]),i.useEffect(()=>{st()},[st]),i.useEffect(()=>{$e()},[$e]),i.useEffect(()=>{if(typeof EventSource>"u")return;const G=e?`?projectId=${encodeURIComponent(e)}`:"",ge=()=>{st(),a==="inbox"?nt():a==="outbox"?Be():a==="approvals"&&Ue(Z),N===Ls?Ie():N&&de(N)};return hi(`/api/events${G}`,{events:{"message:sent":ge,"message:received":ge,"message:read":ge,"message:deleted":ge,"approval:requested":ge,"approval:updated":ge,"approval:decided":ge}})},[e,a,N,st,nt,Be,de,Ie,Ue,Z]);const me=i.useCallback(async G=>{if(g(G),!G.read&&a==="inbox")try{const ge=await w0(G.id,e);ge&&l(ke=>ke&&{...ke,messages:ke.messages.map(tt=>tt.id===ge.id?ge:tt),unreadCount:Math.max(0,ke.unreadCount-1)});const pt=Math.max(0,u-1);m(pt),s?.(pt)}catch{}try{const ge=await N0(G.fromId,G.fromType,e);y(ge)}catch{y([G])}},[e,u,s,a]);i.useEffect(()=>{const G=Af();if(!G)return;const ge=[...o?.messages??[],...c?.messages??[],...I?.inbox??[],...I?.outbox??[],...U?.messages??[],...x].find(pt=>pt.id===G);ge&&me(ge)},[o,c,I,U,x,me]),i.useEffect(()=>{const G=Af();if(!G)return;const ge=document.getElementById(Id(G));if(!ge)return;ge.scrollIntoView({behavior:"smooth",block:"center"}),ge.classList.add("mailbox-message-highlight");const pt=window.setTimeout(()=>{ge.classList.remove("mailbox-message-highlight")},2e3);return()=>{window.clearTimeout(pt)}},[p,x]);const re=i.useCallback(()=>{g(null),y([])},[]),_e=i.useCallback(async()=>{try{const G=await k0(e);m(0),s?.(0),l(ge=>ge&&{...ge,messages:ge.messages.map(pt=>({...pt,read:!0})),unreadCount:0}),n?.(`Marked ${G.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),xt=i.useCallback(async G=>{try{await j0(G,e),g(null),y([]),a==="inbox"?nt():a==="outbox"?Be():N===Ls?Ie():N&&de(N),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,N,nt,Be,de,Ie,n]),dt=i.useCallback(G=>{j({id:G.fromId,type:G.fromType}),w({messageId:G.id,preview:Mf(G.content,120)}),v(!0)},[]),Qe=i.useCallback(()=>{v(!1),j(null),w(null),n?.("Message sent","success"),a==="outbox"?Be():a==="agents"&&N===Ls?Ie():a==="agents"&&N&&de(N),st()},[a,Be,N,de,Ie,n,st]),vt=i.useCallback(()=>{j(a==="agents"&&N&&N!==Ls?{id:N,type:"agent"}:null),w(null),v(!0)},[a,N]),Ae=i.useCallback(()=>{v(!1),j(null),w(null)},[]),Je=i.useCallback(async G=>{try{const ge=await ih(G.id,e);J(ge),je("")}catch{n?.("Failed to load approval request","error")}},[e,n]),ct=i.useCallback(async G=>{if(!(!k||He)){xe(G);try{await E0(k.id,{decision:G,comment:ce||void 0},e),await Ue(Z);const ge=await ih(k.id,e);J(ge),je(""),n?.(`Request ${G==="approve"?"approved":"denied"}`,"success")}catch{n?.("Failed to submit decision","error")}finally{xe(!1)}}},[k,He,ce,e,Ue,Z,n]),Nt=()=>{if(!p||b)return null;const G=D$(x,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",id:Id(p.id),children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:re,"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:$$(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:qi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>dt(p),"data-testid":"mailbox-reply",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>xt(p.id),"data-testid":"mailbox-delete",children:[t.jsx(_n,{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(Ea,{size:14}),Y(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(Ea,{size:14}),Y(p.toId,p.toType)]})]})]}),G.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),G.map(ge=>{const pt=ge.metadata?.replyTo?.messageId,ke=pt?G.find(tt=>tt.id===pt):void 0;return t.jsxs("div",{id:Id(ge.id),className:`mailbox-conversation-msg ${ge.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:Y(ge.fromId,ge.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:qi(ge.createdAt)})]}),pt&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":`mailbox-reply-context-${ge.id}`,children:["↪ Replying to ",ke?Mf(ke.content,60):`message ${pt}`]}),t.jsx(Sf,{content:ge.content,className:"mailbox-conversation-msg-body"})]},ge.id)})]}),G.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx(Sf,{content:p.content,className:"mailbox-message-body",testId:"mailbox-message-body"})]})]})},yt=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Nl,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(G=>t.jsxs("div",{id:to(G.id),className:`mailbox-item ${G.read?"":"unread"}`,onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.fromType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:Y(G.fromId,G.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]}),!G.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${G.id}`})]},G.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Nl,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Ia,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(G=>t.jsxs("div",{id:to(G.id),className:"mailbox-item",onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.toType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",Y(G.toId,G.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]})]},G.id))]}),a==="approvals"&&t.jsxs("div",{className:"mailbox-approvals","data-testid":"mailbox-approvals",children:[t.jsxs("div",{className:"mailbox-approval-filters","data-testid":"mailbox-approval-filters",children:[t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Z==="pending"?"active":""}`,onClick:()=>{ne("pending"),J(null)},"data-testid":"mailbox-approval-filter-pending",children:"Pending"}),t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Z==="history"?"active":""}`,onClick:()=>{ne("history"),J(null)},"data-testid":"mailbox-approval-filter-history",children:"History"})]}),t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-approval-list",children:[F.length===0&&!h&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-approval-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:Z==="pending"?"No pending approvals":"No historical approvals"})]}),F.map(G=>t.jsxs("div",{className:"mailbox-item mailbox-approval-item",onClick:()=>void Je(G),"data-testid":`mailbox-approval-item-${G.id}`,children:[t.jsx("div",{className:`status-dot mailbox-approval-status-dot mailbox-approval-status-dot--${G.status}`}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-from",children:[G.agentId," · ",G.actionCategory]}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsx("div",{className:"mailbox-item-preview",children:G.actionSummary})]}),t.jsx("span",{className:`mailbox-approval-status mailbox-approval-status--${G.status}`,children:G.status})]},G.id))]})]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:D.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:N??"",onChange:G=>{R(G.target.value||null),E("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),t.jsx("option",{value:Ls,children:"All agents"}),D.map(G=>t.jsx("option",{value:G.id,children:G.name||G.id},G.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:vt,"data-testid":"mailbox-compose-btn",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Compose"})]})]}),N&&N!==Ls&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${z==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(ra,{size:12}),t.jsx("span",{children:"Inbox"}),I&&I.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:I.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${z==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Ia,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!N&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(zn,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),N===Ls&&h&&!U&&t.jsx(Nl,{}),N===Ls&&U&&U.messages.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:"No agent-to-agent messages"})]}),N===Ls&&U&&U.messages.map(G=>t.jsxs("div",{id:to(G.id),className:`mailbox-item ${G.read?"":"unread"}`,onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.fromType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:Y(G.fromId,G.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-participants","data-testid":`mailbox-item-participants-${G.id}`,children:[t.jsxs("span",{children:["From: ",Y(G.fromId,G.fromType)]}),t.jsxs("span",{children:["To: ",Y(G.toId,G.toType)]})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]})]},G.id)),N&&N!==Ls&&h&&!I&&t.jsx(Nl,{}),N&&N!==Ls&&I&&z==="inbox"&&I.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ra,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),N&&N!==Ls&&I&&z==="outbox"&&I.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Ia,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),N&&N!==Ls&&I&&z==="inbox"&&I.inbox.map(G=>t.jsxs("div",{id:to(G.id),className:`mailbox-item ${G.read?"":"unread"}`,onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.fromType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:Y(G.fromId,G.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]})]},G.id)),N&&N!==Ls&&I&&z==="outbox"&&I.outbox.map(G=>t.jsxs("div",{id:to(G.id),className:"mailbox-item",onClick:()=>me(G),"data-testid":`mailbox-item-${G.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:G.toType==="agent"?t.jsx(zn,{size:16}):t.jsx(Ea,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",Y(G.toId,G.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:qi(G.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[G.content.slice(0,80),G.content.length>80?"…":""]})]})]},G.id))]})]})})]}),Se=()=>b?t.jsx(Cf,{recipient:S,replyContext:C,agents:D,projectId:e,onSend:Qe,onCancel:Ae,addToast:n}):p?Nt():a==="approvals"&&k?t.jsxs("div",{className:"mailbox-message-detail mailbox-approval-detail","data-testid":"mailbox-approval-detail",children:[ee&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>J(null),"data-testid":"mailbox-approval-back-to-list",children:"← Back"}),t.jsx("div",{className:"mailbox-message-detail-header",children:t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:k.actionCategory}),t.jsx("span",{className:"mailbox-message-time",children:k.status})]})}),t.jsxs("div",{className:"mailbox-message-body",children:[t.jsx("strong",{children:k.actionSummary}),t.jsxs("p",{children:["Requester: ",k.requester.actorName," (",k.agentId,")"]}),k.taskId&&t.jsxs("p",{children:["Task: ",k.taskId]}),t.jsxs("p",{children:["Requested: ",qi(k.createdAt)]})]}),t.jsx("div",{className:"mailbox-conversation","data-testid":"mailbox-approval-history",children:k.history.map(G=>t.jsxs("div",{className:"mailbox-conversation-msg",children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:G.eventType}),t.jsx("span",{children:G.actor.actorName})]}),G.note&&t.jsx("div",{className:"mailbox-item-preview",children:G.note})]},G.id))}),k.status==="pending"&&t.jsxs("div",{className:"mailbox-approval-decision","data-testid":"mailbox-approval-decision",children:[t.jsx("textarea",{className:"message-composer-textarea mailbox-approval-comment",value:ce,onChange:G=>je(G.target.value),placeholder:"Optional comment","data-testid":"mailbox-approval-comment"}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>void ct("deny"),disabled:He!==!1,"data-testid":"mailbox-approval-deny",children:"Deny"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void ct("approve"),disabled:He!==!1,"data-testid":"mailbox-approval-approve",children:"Approve"})]})]})]}):t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(Da,{size:24}),t.jsx("p",{children:"Select a message to read"})]});return t.jsxs("div",{className:"mailbox-view",style:ae,"data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(Da,{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:vt,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Ki,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:_e,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Em,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?nt():a==="outbox"?Be():a==="approvals"?Ue(Z):N===Ls?Ie():N&&de(N)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{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(ra,{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(Ia,{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),J(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(zn,{size:14}),t.jsx("span",{children:"Agents"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="approvals"?"active":""}`,onClick:()=>{r("approvals"),g(null),J(null)},"data-testid":"mailbox-tab-approvals",children:[t.jsx(Em,{size:14}),t.jsx("span",{children:"Approvals"}),P>0&&t.jsx("span",{className:"mailbox-tab-badge","data-testid":"mailbox-approvals-pending-badge",children:P})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:oe?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",ref:pe,children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",style:{width:`${W}px`},children:yt()}),t.jsx("div",{className:"mailbox-split-resize-handle","data-testid":"mailbox-split-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize message list pane",tabIndex:0,"aria-valuemin":tc,"aria-valuemax":Math.round(Su(pe.current?.clientWidth??W/Nu)),"aria-valuenow":Math.round(W),onMouseDown:qe,onKeyDown:Pe}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Se()})]}):t.jsxs(t.Fragment,{children:[Nt(),a==="approvals"&&k&&Se(),b&&t.jsx(Cf,{recipient:S,replyContext:C,agents:D,projectId:e,onSend:Qe,onCancel:Ae,addToast:n}),!p&&!k&&!b&&yt()]})})]})}function Nl(){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 O$=640;function F$({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){Ni(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,y]=i.useState([]),[b,v]=i.useState(null),[S,j]=i.useState([]),[C,w]=i.useState(null),[N,R]=i.useState(null),[z,E]=i.useState(!1),[I,O]=i.useState([]),[U,A]=i.useState(!1),[D,K]=i.useState(""),Z=i.useRef(!1),ne=i.useRef(null);Li(ne,e,"fusion:github-modal-size");const F=Qi(n),[M,P]=i.useState(!1),[$,k]=i.useState("list"),J=i.useRef(null),ce=new Set;for(const me of a){const re=me.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);re&&ce.add(re[1]);const _e=me.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);_e&&ce.add(_e[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),y([]),v(null),j([]),w(null),g("issues"),R(null),E(!1),O([]),A(!0),K(""),J.current=null,Z.current=!0,jN().then(me=>{if(Z.current)if(O(me),A(!1),me.length===1){const re=me[0];l(re.owner),d(re.repo),K(re.name)}else me.length>1&&(l(""),d(""),K(""))}).catch(()=>{Z.current&&A(!1)}),()=>{Z.current=!1}},[e]);const je=i.useCallback(me=>{if(K(me),me==="")l(""),d("");else{const re=I.find(_e=>_e.name===me);re&&(l(re.owner),d(re.repo))}},[I]),He=i.useCallback(async()=>{if(!o.trim()||!c.trim()){R("Repository must be selected");return}f(!0),R(null),y([]),v(null);try{const me=u.split(",").map(_e=>_e.trim()).filter(Boolean),re=await vN(o.trim(),c.trim(),30,me.length>0?me:void 0);y(re),re.length===0&&R("No open issues found")}catch(me){R(Ee(me)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),xe=i.useCallback(async()=>{if(!o.trim()||!c.trim()){R("Repository must be selected");return}f(!0),R(null),j([]),w(null);try{const me=await wN(o.trim(),c.trim(),30);j(me),me.length===0&&R("No open pull requests found")}catch(me){R(Ee(me)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||z)return;const me={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};J.current?.owner===me.owner&&J.current?.repo===me.repo&&J.current?.labels===me.labels&&J.current?.tab===me.tab||(J.current=me,p==="issues"?He():xe())},[o,c,u,p,e,h,z,He,xe]),i.useEffect(()=>{if(!e)return;const me=re=>{re.key==="Escape"&&n()};return document.addEventListener("keydown",me),()=>document.removeEventListener("keydown",me)},[e,n]),i.useEffect(()=>{if(!e)return;const me=()=>{P(window.innerWidth<=O$)};return me(),window.addEventListener("resize",me),()=>window.removeEventListener("resize",me)},[e]);const Ne=i.useCallback(me=>{v(me),M&&k("preview")},[M]),Y=i.useCallback(me=>{w(me),M&&k("preview")},[M]),ie=i.useCallback(()=>{k("list")},[]),ee=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;E(!0),R(null);try{const me=await yN(o.trim(),c.trim(),b,r);s(me),v(null),M&&$==="preview"&&k("list")}catch(me){const re=Ee(me);re?.includes("already imported")?R(re):R(re||"Failed to import issue")}finally{E(!1)}}else{if(C===null)return;E(!0),R(null);try{const me=await kN(o.trim(),c.trim(),C,r);s(me),w(null),M&&$==="preview"&&k("list")}catch(me){const re=Ee(me);re?.includes("already imported")?R(re):R(re||"Failed to import pull request")}finally{E(!1)}}},[p,b,C,o,c,s,M,$]),oe=x.find(me=>me.number===b),W=S.find(me=>me.number===C);if(!e)return null;const L=I.length>0,pe=I.length===1,fe=x.filter(me=>ce.has(me.html_url)).length,B=S.filter(me=>ce.has(me.html_url)).length,ve=N==="No open issues found",Fe=N==="No open pull requests found",ae=p==="issues"?ve:Fe,qe=!!N&&!ve&&x.length===0&&!h,Pe=!!N&&!Fe&&S.length===0&&!h,nt=p==="issues"?qe:Pe,Be=h||x.length>0||ve||qe,de=h||S.length>0||Fe||Pe,Ie=p==="issues"?Be:de,$e=!!N&&x.length>0&&!ve,st=!!N&&S.length>0&&!Fe,Ue=p==="issues"?$e:st;return t.jsx("div",{className:"modal-overlay open",...F,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:ne,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||z,children:[t.jsx(cc,{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"),v(null)},disabled:h||z,children:[t.jsx(si,{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:U?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(jt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):L?pe?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:I[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[I[0].owner,"/",I[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:D,onChange:me=>je(me.target.value),disabled:h||z,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),I.map(me=>t.jsxs("option",{value:me.name,children:[me.name," (",me.owner,"/",me.repo,")"]},me.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:me=>m(me.target.value),onKeyDown:me=>me.key==="Enter"&&He(),disabled:h||z||!L,"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"?He:xe,disabled:h||z||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!U&&!L&&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"})]}),Ue&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:N}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${M?"mobile":""} ${$==="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:[fe," 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:[B," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Ie&&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(jt,{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."})]})]}),nt&&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:N})]})}),ae&&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(me=>{const re=ce.has(me.html_url);return t.jsxs("div",{className:`issue-item ${b===me.number?"selected":""} ${re?"imported":""}`,onClick:()=>!re&&Ne(me.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===me.number,onChange:()=>Ne(me.number),disabled:re,"aria-label":`Select issue #${me.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",me.number]}),t.jsx("span",{className:"issue-title",children:me.title})]}),me.labels.length>0&&t.jsx("span",{className:"issue-labels",children:me.labels.map(_e=>t.jsx("span",{className:"label-chip",children:_e.name},_e.name))})]}),re&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},me.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(me=>{const re=ce.has(me.html_url);return t.jsxs("div",{className:`issue-item ${C===me.number?"selected":""} ${re?"imported":""}`,onClick:()=>!re&&Y(me.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===me.number,onChange:()=>Y(me.number),disabled:re,"aria-label":`Select pull request #${me.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",me.number]}),t.jsx("span",{className:"issue-title",children:me.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[me.headBranch," → ",me.baseBranch]})]}),re&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},me.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${M?"mobile":""} ${$==="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:ie,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ua,{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"&&oe?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",oe.number]}),t.jsx("div",{className:"preview-title",children:oe.title}),t.jsx("div",{className:"preview-body",children:oe.body?oe.body.slice(0,200)+(oe.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"&&W?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",W.number]}),t.jsx("div",{className:"preview-title",children:W.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",W.headBranch," → ",W.baseBranch]}),t.jsx("div",{className:"preview-body",children:W.body?W.body.slice(0,200)+(W.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:z,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:ee,disabled:(p==="issues"?b===null:C===null)||z,children:z?t.jsx(jt,{size:14,className:"spin"}):"Import"})]})]})})}function di({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(On,{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 z$=["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 Ro(e){return e&&pa.includes(e)?e:Ds}function Td(e){return{...e,priority:Ro(e.priority)}}function B$(e,n){return e&&n?`${e}/${n}`:""}function U$(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 H$({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([]),[y,b]=i.useState([]),[v,S]=i.useState(null),j=i.useRef(!1),C=i.useRef(!1),[w,N]=i.useState(""),[R,z]=i.useState(!0),[E,I]=i.useState(!1),[O,U]=i.useState(!1),[A,D]=i.useState(null),[K,Z]=i.useState(0),ne=i.useRef(null),F=i.useRef(null),M=i.useRef(null),P=i.useRef(null),$=i.useRef(null),k=i.useRef(null),J=i.useRef(null),[ce,je]=i.useState(c??null),He=i.useMemo(()=>qa(),[]),{isLockedByOther:xe,takeControl:Ne,isLoading:Y}=Ec(e?ce:null),{activeTabMap:ie,broadcastUpdate:ee,broadcastCompleted:oe,broadcastLock:W,broadcastUnlock:L,broadcastHeartbeat:pe}=Or(),[fe,B]=i.useState(void 0),[ve,Fe]=i.useState(void 0),[ae,qe]=i.useState("medium"),[Pe,nt]=i.useState(""),[Be,de]=i.useState([]),[Ie,$e]=i.useState(!1),[st,Ue]=i.useState(null),[me,re]=i.useState([]),[_e,xt]=i.useState([]),[dt,Qe]=i.useState({}),vt=i.useRef(null),[Ae,Je]=i.useState([]),[ct,Nt]=i.useState(!1),[yt,Se]=i.useState(c??null),[G,ge]=i.useState(!!c),[pt,ke]=i.useState(null),[tt,Rt]=i.useState(!1),Re=i.useRef(!1),be=i.useRef(null),at=i.useRef(""),ot=i.useRef(null),gt=i.useRef(null);Li(F,e,"fusion:planning-modal-size");const St=ri(),{keyboardOverlap:Lt,viewportHeight:Yt,viewportOffsetTop:tn,keyboardOpen:mn}=Zi({enabled:St==="mobile"});Ni(St==="mobile"&&e),i.useEffect(()=>{const he=F.current;he&&(mn?(he.style.setProperty("--keyboard-overlap",`${Lt}px`),he.style.setProperty("--vv-offset-top",`${tn}px`),Yt!==null?he.style.setProperty("--vv-height",`${Yt}px`):he.style.removeProperty("--vv-height")):(he.style.removeProperty("--keyboard-overlap"),he.style.removeProperty("--vv-offset-top"),he.style.removeProperty("--vv-height")))},[mn,Lt,tn,Yt]),i.useEffect(()=>{at.current=w},[w]),i.useEffect(()=>{const he=be.current;if(!he)return;he.scrollHeight-he.scrollTop-he.clientHeight<32&&(he.scrollTop=he.scrollHeight)},[w]),i.useEffect(()=>{if(m.type!=="loading"){D(null),Z(0);return}const he=Date.now();D(he),Z(0);const mt=setInterval(()=>{Z(Math.max(0,Math.floor((Date.now()-he)/1e3)))},1e3);return()=>clearInterval(mt)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const he=P.current;if(!he)return;let mt=!1;const wt=setInterval(async()=>{try{const Xe=await Ti(he);if(mt||!Xe||P.current!==he)return;if(Xe.status==="awaiting_input"&&Xe.currentQuestion){const Et=JSON.parse(Xe.currentQuestion);h({type:"question",session:{sessionId:he,currentQuestion:Et,summary:null}}),N("")}else if(Xe.status==="complete"&&Xe.result){const Et=Td(JSON.parse(Xe.result));h({type:"summary",session:{sessionId:he,currentQuestion:null,summary:Et},summary:Et}),S(Et),N("")}}catch{}},8e3);return()=>{mt=!0,clearInterval(wt)}},[m.type]);const Qt=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),N(""),I(!1),U(!1),B(void 0),Fe(void 0),qe("medium"),nt(""),P.current=null,je(null)},[]),yn=B$(fe,ve),Gt=i.useCallback((he,mt)=>{if(!he||!mt)return dt.provider&&dt.modelId?`${dt.provider}/${dt.modelId}`:"Using default";const ht=Be.find(wt=>wt.provider===he&&wt.id===mt);return ht?`${ht.provider}/${ht.id}`:`${he}/${mt}`},[Be,dt.modelId,dt.provider]),on=i.useCallback(async()=>{$e(!0),Ue(null);try{const he=await Ks();de(he.models),re(he.favoriteProviders),xt(he.favoriteModels),Qe({provider:he.resolvedPlanningProvider,modelId:he.resolvedPlanningModelId})}catch(he){Ue(Ee(he)||"Failed to load models")}finally{$e(!1)}},[]),sn=i.useCallback(he=>{re(mt=>{const ht=mt,Xe=ht.includes(he)?ht.filter(Et=>Et!==he):[he,...ht];return Dn({favoriteProviders:Xe,favoriteModels:_e}).catch(()=>{re(ht)}),Xe})},[_e]),ln=i.useCallback(he=>{xt(mt=>{const ht=mt,Xe=ht.includes(he)?ht.filter(Et=>Et!==he):[he,...ht];return Dn({favoriteProviders:me,favoriteModels:Xe}).catch(()=>{xt(ht)}),Xe})},[me]),Wt=i.useCallback(he=>{M.current?.close();const mt=()=>P.current!==he,ht=SS(he,l,{onThinking:wt=>{mt()||(N(Xe=>Xe+wt),ee({sessionId:he,status:"generating",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:wt=>{if(mt())return;I(!1),U(!1),rr(l);const Xe=at.current.trim();Xe&&b(Et=>Et[Et.length-1]?.thinkingOutput===Xe?Et:[...Et,{thinkingOutput:Xe}]),h({type:"question",session:{sessionId:he,currentQuestion:wt,summary:null}}),N(""),ee({sessionId:he,status:"awaiting_input",needsInput:!0,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:wt=>{if(mt())return;I(!1),U(!1),rr(l);const Xe=at.current.trim();Xe&&b(Et=>Et[Et.length-1]?.thinkingOutput===Xe?Et:[...Et,{thinkingOutput:Xe}]),h({type:"summary",session:{sessionId:he,currentQuestion:null,summary:wt},summary:wt}),S(wt),N(""),ee({sessionId:he,status:"complete",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:wt=>{const Xe=wt||"Session failed while contacting the AI.";I(!0),(async()=>{try{const Et=await Ti(he);if(Et&&(Et.status==="generating"||Et.status==="awaiting_input")){Wt(he);return}}catch{}I(!1),U(!1),p(null),h(Et=>Et.type==="question"||Et.type==="summary"||Et.type==="error"?{type:"error",session:Et.session,errorMessage:Xe}:{type:"error",session:{sessionId:he,currentQuestion:null,summary:null},errorMessage:Xe}),N(""),P.current=he,ee({sessionId:he,status:"error",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null}),oe({sessionId:he,status:"error"})})()},onComplete:()=>{I(!1),U(!1),P.current=null,oe({sessionId:he,status:"complete"})},onConnectionStateChange:wt=>{I(wt==="reconnecting")}});M.current=ht},[oe,ee,d,l,He]),ye=i.useCallback(async he=>{const mt=he??d;if(mt.trim()){p(null),N(""),b([]),x([]),I(!1),h({type:"loading"});try{const ht=fe&&ve?{planningModelProvider:fe,planningModelId:ve}:void 0,wt=Pe.trim()?Number.parseInt(Pe,10):void 0,Xe=$.current,{sessionId:Et}=await oS(mt.trim(),l,ht,{planningDepth:ae,customQuestionCount:Number.isInteger(wt)?wt:void 0},Xe??void 0);$.current=null,P.current=Et,je(Et),Se(Et),Wt(Et),x([])}catch(ht){I(!1),p(Ee(ht)||"Failed to start planning session"),h({type:"initial"}),P.current=null,je(null)}}},[Wt,Pe,d,ae,ve,fe,l]);i.useEffect(()=>{e&&m.type==="initial"&&ne.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&on()},[e,on]),i.useEffect(()=>{if(e&&o&&!j.current&&m.type==="initial"){u(o);const he=setTimeout(()=>{j.current=!0,ye(o)},0);return()=>clearTimeout(he)}else if(e&&!o&&!j.current&&!C.current&&m.type==="initial"){C.current=!0;const he=WP(l);he&&u(he)}},[e,o,m.type,ye,l]);const Le=i.useCallback(async he=>{M.current?.close(),M.current=null,p(null),N(""),x([]),b([]),S(null),U(!1),h({type:"loading"});try{const mt=await Ti(he);if(!mt){Se(null),ge(!1),h({type:"initial"});return}P.current=he,je(he);const ht=kr(mt.conversationHistory);if(b(ht),x(ht.map(wt=>wt.response).filter(wt=>!!(wt&&typeof wt=="object"&&!Array.isArray(wt)))),mt.status==="draft"){let wt="",Xe,Et;try{const Zt=mt.inputPayload?JSON.parse(mt.inputPayload):null;Zt&&typeof Zt.initialPlan=="string"&&(wt=Zt.initialPlan),Zt&&typeof Zt.modelProvider=="string"&&typeof Zt.modelId=="string"&&(Xe=Zt.modelProvider,Et=Zt.modelId)}catch{}u(wt),B(Xe),Fe(Et),$.current=he,gt.current=wt?{sessionId:he,initialPlan:wt.trim(),modelProvider:Xe,modelId:Et}:null,h({type:"initial"})}else if(mt.status==="awaiting_input"&&mt.currentQuestion){rr(l);const wt=JSON.parse(mt.currentQuestion);if(h({type:"question",session:{sessionId:he,currentQuestion:wt,summary:null}}),mt.thinkingOutput){const Xe=mt.thinkingOutput.trim();Xe&&b(Et=>Et[Et.length-1]?.thinkingOutput===Xe?Et:[...Et,{thinkingOutput:Xe}])}Wt(he)}else if(mt.status==="complete"&&mt.result){rr(l);const wt=Td(JSON.parse(mt.result));h({type:"summary",session:{sessionId:he,currentQuestion:null,summary:wt},summary:wt}),S(wt)}else mt.status==="generating"?(h({type:"loading"}),mt.thinkingOutput&&N(mt.thinkingOutput),Wt(he)):mt.status==="error"&&h({type:"error",session:{sessionId:he,currentQuestion:null,summary:null},errorMessage:mt.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[Wt,l]);i.useEffect(()=>{!e||!c||P.current!==c&&J.current!==c&&(Se(c),ge(!0),Le(c))},[e,c]),i.useEffect(()=>{e&&yt&&(c&&c===yt||Le(yt))},[e]);const Ke=i.useCallback(async()=>{Nt(!0);try{const mt=(await zu(l,{includeCompleted:!0,includeArchived:tt})).filter(ht=>ht.type==="planning").sort((ht,wt)=>Date.parse(wt.updatedAt)-Date.parse(ht.updatedAt));Je(mt)}catch{}finally{Nt(!1)}},[l,tt]);i.useEffect(()=>{e&&Ke()},[e,Ke]);const ut=i.useRef(!1);i.useEffect(()=>{const he=ut.current&&!ct;ut.current=ct,he&&St==="mobile"&&(G||c||yt||Ae.length>0||ge(!0))},[St,G,c,yt,ct,Ae.length]),i.useEffect(()=>{if(!e)return;const he=l?`?projectId=${encodeURIComponent(l)}`:"",mt=wt=>{try{const Xe=JSON.parse(wt.data);if(Xe.type!=="planning")return;Je(Et=>{const Zt=Et.findIndex(lt=>lt.id===Xe.id);return(Zt>=0?[...Et.slice(0,Zt),Xe,...Et.slice(Zt+1)]:[Xe,...Et]).sort((lt,nn)=>Date.parse(nn.updatedAt)-Date.parse(lt.updatedAt))})}catch{}},ht=wt=>{try{const Xe=JSON.parse(wt.data);Je(Et=>Et.filter(Zt=>Zt.id!==Xe))}catch{}};return hi(`/api/events${he}`,{events:{"ai_session:updated":mt,"ai_session:deleted":ht},onReconnect:()=>{Ke()}})},[e,l,Ke]);const Ve=i.useCallback(he=>{if(yt===he){ge(!0);return}Se(he),ge(!0),Le(he)},[Le,yt]),Pt=i.useCallback(()=>{M.current?.close(),M.current=null,$.current=null,k.current&&(clearTimeout(k.current),k.current=null),c&&(J.current=c),Qt(),Se(null),ge(!0)},[Qt,c]),Ot=i.useCallback(()=>{ge(!1)},[]),bt=i.useCallback(async(he,mt)=>{const ht=mt.trim();if(!(!ht||gt.current?.sessionId===he&>.current.initialPlan===ht&>.current.modelProvider===fe&>.current.modelId===ve))try{await g0(he,{initialPlan:ht,modelProvider:fe&&ve?fe:void 0,modelId:fe&&ve?ve:void 0},l),gt.current={sessionId:he,initialPlan:ht,modelProvider:fe,modelId:ve}}catch{}},[ve,fe,l]);i.useEffect(()=>{if(ot.current&&(clearTimeout(ot.current),ot.current=null),!(!e||m.type!=="initial"||!yt))return ot.current=setTimeout(()=>{bt(yt,d)},500),()=>{ot.current&&(clearTimeout(ot.current),ot.current=null)}},[d,e,yt,bt,m.type]),i.useEffect(()=>{gt.current=null},[yt]),i.useEffect(()=>()=>{ot.current&&(clearTimeout(ot.current),ot.current=null)},[]);const Dt=i.useCallback(async he=>{const mt=wt=>wt==="generating"||wt==="awaiting_input",ht=Ae.find(wt=>wt.id===he);if(ht&&mt(ht.status))try{await lb(he,l,He)}catch{}try{await bb(he)}catch{}oe({sessionId:he,status:"complete",timestamp:Date.now()}),Je(wt=>wt.filter(Xe=>Xe.id!==he)),yt===he&&(M.current?.close(),M.current=null,Qt(),Se(null),ge(!1)),ke(null)},[oe,Ae,l,Qt,yt,He]),Ft=i.useCallback(async he=>{const ht=Ae.find(wt=>wt.id===he)?.archived===!0;try{ht?await u0(he):await d0(he)}catch{return}Je(wt=>!ht&&!tt?wt.filter(Xe=>Xe.id!==he):wt.map(Xe=>Xe.id===he?{...Xe,archived:!ht}:Xe)),!ht&&yt===he&&!tt&&(M.current?.close(),M.current=null,Qt(),Se(null),ge(!1))},[Ae,Qt,yt,ge,tt]);i.useEffect(()=>{e||(j.current=!1,C.current=!1,I(!1),U(!1),je(null))},[e]),i.useEffect(()=>{if(!e){vt.current&&(L(vt.current,He),vt.current=null);return}if(ce&&vt.current!==ce){vt.current&&L(vt.current,He),W(ce,He),vt.current=ce;return}!ce&&vt.current&&(L(vt.current,He),vt.current=null)},[W,L,e,ce,He]),i.useEffect(()=>{if(!e||!ce||vt.current!==ce)return;pe(He);const he=setInterval(()=>{pe(He)},3e4);return()=>{clearInterval(he)}},[pe,e,ce,He]),i.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),M.current?.close(),M.current=null,vt.current&&(L(vt.current,He),vt.current=null)},[L,He]),i.useEffect(()=>{if(!e)return;const he=()=>{M.current?.close(),M.current=null};return window.addEventListener("beforeunload",he),()=>window.removeEventListener("beforeunload",he)},[e]);const Ht=i.useCallback((he,mt)=>{ot.current&&(clearTimeout(ot.current),ot.current=null),(async()=>{try{await bt(he,mt),await b0(he,l)}catch{}})()},[l,bt]),rn=i.useCallback(()=>{if(St!=="mobile")return;const he=document.activeElement;he instanceof HTMLElement&&he.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[St]),Xt=i.useCallback(()=>{d&&m.type==="initial"&&VP(d,l);const he=$.current;he&&d.trim()&&Ht(he,d),$.current=null,k.current&&(clearTimeout(k.current),k.current=null),M.current?.close(),M.current=null,I(!1),U(!1),rn(),n()},[Ht,d,n,l,rn,m.type]);i.useEffect(()=>{if(!e)return;const he=mt=>{mt.key==="Escape"&&Xt()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,Xt]);const an=i.useCallback(async he=>{if(m.type!=="question")return;const{session:mt}=m,ht=mt.sessionId,wt=mt.currentQuestion;if(!wt){p("No active question in session");return}p(null),x(Xe=>[...Xe,he]),b(Xe=>{const Et=at.current.trim();let Zt=Xe;return Et&&Zt[Zt.length-1]?.thinkingOutput!==Et&&(Zt=[...Zt,{thinkingOutput:Et}]),[...Zt,{question:wt,response:he}]}),h({type:"loading"}),N("");try{await qm(ht,he,l,He)}catch(Xe){p(Ee(Xe)||"Failed to submit response"),h({type:"question",session:mt})}},[l,He,m]),Me=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:he,summary:mt}=m,ht=he.sessionId;P.current=ht,je(ht),p(null),U(!1),N(""),h({type:"loading"}),Wt(ht);try{await qm(ht,{refine:!0},l,He)}catch(wt){M.current?.close(),M.current=null,p(Ee(wt)||"Failed to refine plan"),h({type:"summary",session:he,summary:v??mt})}},[Wt,v,l,He,m]),it=i.useCallback(async()=>{const he=P.current;if(he){try{await dS(he,l,He)}catch{}M.current?.close(),M.current=null,I(!1),U(!1),h({type:"error",session:{sessionId:he,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),N("")}},[l,He]),kt=i.useCallback(async()=>{if(m.type!=="error")return;const he=m.session;p(null),U(!0),N(""),h({type:"loading"}),Wt(he.sessionId);try{P.current=he.sessionId,je(he.sessionId),await cS(he.sessionId,l,He)}catch(mt){let ht=mt;if((Ee(mt)||"").includes("not in an error state"))try{const Xe=await Ti(he.sessionId);if(!Xe)throw new Error("Failed to refresh planning session.");if(P.current=Xe.id,je(Xe.id),Xe.status==="generating")N(Xe.thinkingOutput??""),h({type:"loading"});else if(Xe.status==="awaiting_input"){if(!Xe.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const Et=JSON.parse(Xe.currentQuestion);if(rr(l),h({type:"question",session:{sessionId:Xe.id,currentQuestion:Et,summary:null}}),Xe.thinkingOutput){const Zt=Xe.thinkingOutput.trim();Zt&&b(le=>le[le.length-1]?.thinkingOutput===Zt?le:[...le,{thinkingOutput:Zt}])}M.current?.isConnected()||Wt(Xe.id)}else if(Xe.status==="complete"){if(!Xe.result)throw new Error("Planning session is complete but has no result.");const Et=Td(JSON.parse(Xe.result));rr(l),h({type:"summary",session:{sessionId:Xe.id,currentQuestion:null,summary:Et},summary:Et}),S(Et)}else Xe.status==="error"&&h({type:"error",session:{sessionId:Xe.id,currentQuestion:null,summary:null},errorMessage:Xe.error||"Retry failed. Please try again."});I(!1);return}catch(Xe){ht=Xe}M.current?.close(),M.current=null,h({type:"error",session:he,errorMessage:Ee(ht)||"Retry failed. Please try again."}),I(!1)}finally{U(!1)}},[Wt,l,He,m]),$t=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const he=m.session.sessionId,mt=await uS(he,v??void 0,l);s(mt),Se(null),Je(ht=>ht.filter(wt=>wt.id!==he)),oe({sessionId:he,status:"complete",timestamp:Date.now()}),Xt()}catch(he){p(Ee(he)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[oe,v,m,l,s,Xt]),se=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const he=await mS(m.session.sessionId,v??void 0,l);je(he.sessionId),h({type:"breakdown",sessionId:he.sessionId,subtasks:he.subtasks.map(mt=>({...mt,priority:Ro(mt.priority)})),dirty:!1})}catch(he){p(Ee(he)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[v,m,l]),te=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const he=m.sessionId,mt=await hS(he,m.subtasks.map(ht=>({...ht,priority:Ro(ht.priority)})),l);a(mt.tasks),Je(ht=>ht.filter(wt=>wt.id!==he)),oe({sessionId:he,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),x([]),b([]),S(null),N(""),B(void 0),Fe(void 0),qe("medium"),nt(""),P.current=null,je(null),Se(null),Xt()}catch(he){p(Ee(he)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,subtasks:m.subtasks,dirty:m.dirty})}}},[oe,Xt,m,a,l]),De=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const he=m.session.sessionId;p(null),h({type:"loading"});try{const mt=await lS(he,l,He);x(mt.history.map(ht=>ht.response&&typeof ht.response=="object"&&!Array.isArray(ht.response)?ht.response:{[ht.question.id]:ht.response})),b(mt.history.map(ht=>({question:ht.question,response:ht.response&&typeof ht.response=="object"&&!Array.isArray(ht.response)?ht.response:{[ht.question.id]:ht.response},thinkingOutput:ht.thinkingOutput}))),N(""),h({type:"question",session:{...m.session,currentQuestion:mt.currentQuestion,summary:null}})}catch(mt){p(Ee(mt)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,He,m]),ft=()=>m.type==="question"?Math.min(g.length+1,3):3,qt=ce?ie.get(ce):null,zt=qt&&qt.tabId!==He,Pn=xe&&(!zt||qt.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:he=>{Re.current=he.target===he.currentTarget},onClick:he=>{he.target===he.currentTarget&&Re.current&&Xt(),Re.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:F,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[G&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Ot,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(lc,{size:18})}),t.jsx($i,{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:Xt,"aria-label":"Close",children:t.jsx(un,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${G?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(G$,{sessions:Ae,loading:ct,selectedSessionId:yt,pendingDeleteId:pt,showArchived:tt,onToggleShowArchived:()=>Rt(he=>!he),onArchive:he=>void Ft(he),onSelectSession:Ve,onNewSession:Pt,onRequestDelete:ke,onConfirmDelete:he=>void Dt(he),onCancelDelete:()=>ke(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),E&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),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(gs,{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:ne,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:he=>{const mt=he.target.value;u(mt),!($.current||mt.trim().length===0)&&(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{if($.current)return;const ht=mt.trim();if(!ht)return;rS(ht,l,fe&&ve?{planningModelProvider:fe,planningModelId:ve}:void 0).then(Xe=>{$.current=Xe.sessionId,Je(Et=>Et.some(le=>le.id===Xe.sessionId)?Et:[{id:Xe.sessionId,type:"planning",status:"draft",title:Xe.title,preview:ht.length>80?`${ht.slice(0,79).trimEnd()}…`:ht,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...Et].sort((le,lt)=>Date.parse(lt.updatedAt)-Date.parse(le.updatedAt))),Se(Xe.sessionId)}).catch(()=>{})},300))},onKeyDown:he=>{he.key==="Enter"&&!he.shiftKey&&d.trim()&&(he.preventDefault(),ye())},onBlur:()=>{const he=$.current;he&&d.trim()&&Ht(he,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:z$.map((he,mt)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(he),children:he.length>40?he.slice(0,40)+"...":he},mt))})]}),t.jsx(di,{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",Ie&&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(Is,{id:"planning-modal-model",label:"Planning Model",value:yn,onChange:he=>{const{provider:mt,modelId:ht}=U$(he);B(mt),Fe(ht)},models:Be,disabled:Ie,favoriteProviders:me,onToggleFavorite:sn,favoriteModels:_e,onToggleModelFavorite:ln}),st&&t.jsxs("div",{className:"form-hint form-hint-error",children:[st," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{on()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${fe&&ve?"model-badge-custom":"model-badge-default"}`,children:Gt(fe,ve)})})]}),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(he=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${ae===he.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>qe(he.value),"aria-pressed":ae===he.value,children:he.label},he.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:Pe,onChange:he=>nt(he.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ye(),disabled:!d.trim(),children:[t.jsx($i,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{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… (",K,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>z(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void it(),children:[t.jsx(Uy,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),R&&w&&t.jsx("div",{className:"planning-thinking-output",ref:be,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:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:y}),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 kt(),disabled:O,children:[O?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:O?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Xt,disabled:O,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{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(q$,{question:m.session.currentQuestion,progress:ft(),historyEntries:y,onSubmit:an,onBack:g.length>0?De:void 0})}),m.type==="summary"&&v&&t.jsx(V$,{summary:v,historyEntries:y,onSummaryChange:S,tasks:r,onCreateTask:$t,onBreakIntoTasks:se,onRefine:()=>{Me()},isLoading:!1}),m.type==="breakdown"&&t.jsx(K$,{subtasks:m.subtasks,dirty:m.dirty,isLoading:!1,onUpdateSubtasks:he=>h({...m,subtasks:he,dirty:!0}),onCreateTasks:te,onBack:()=>{const mt={sessionId:m.sessionId,currentQuestion:null,summary:v??null};v&&h({type:"summary",session:mt,summary:v})}})]}),xe&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(pc,{size:16}),t.jsx("span",{children:Pn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Pn&&t.jsx("button",{type:"button",onClick:()=>{Ne()},disabled:Y,className:"btn btn-primary session-lock-take-control",children:Y?"Taking control...":"Take Control"})]})})]})]})}):null}function q$({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(mi,{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 y=x.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:y})}}),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(un,{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(Ua,{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($o,{size:16,className:"icon-ml-4"})]})]})]})}function V$({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=Ro(e.priority),p=g=>{const x=m.includes(g)?m.filter(y=>y!==g):[...m,g];h(x),s({...e,suggestedDependencies:x})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(di,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(mi,{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:g=>s({...e,description:g.target.value})})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-size",children:"Suggested Size"}),t.jsxs("select",{id:"planning-summary-size",className:"planning-size-select",value:e.suggestedSize,onChange:g=>s({...e,suggestedSize:g.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)"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-priority",children:"Priority"}),t.jsx("select",{id:"planning-summary-priority",className:"planning-size-select",value:f,onChange:g=>s({...e,priority:g.target.value}),disabled:c,children:pa.map(g=>t.jsx("option",{value:g,children:g[0].toUpperCase()+g.slice(1)},g))})]})]}),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(g=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(g.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(g.id),onChange:()=>p(g.id)}),t.jsx("span",{className:"planning-dep-id",children:g.id}),t.jsx("span",{className:"planning-dep-title",children:g.title||g.description.slice(0,30)})]},g.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((g,x)=>t.jsx("li",{children:g},x))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Ua,{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(jt,{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(jt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(hc,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Rf(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 W$(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",priority:Ds,dependsOn:[]}}function K$({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(N=>!N.title.trim())?!0:Rf(e),[e]),g=i.useCallback((N,R)=>{a(e.map(z=>z.id===N?{...z,...R}:z))},[e,a]),x=i.useCallback(()=>{a([...e,W$(e.length+1)])},[e,a]),y=i.useCallback(N=>{a(e.filter(R=>R.id!==N).map(R=>({...R,dependsOn:R.dependsOn.filter(z=>z!==N)})))},[e,a]),b=i.useCallback((N,R)=>{if(R<0||R>=e.length)return;const z=[...e],[E]=z.splice(N,1);z.splice(R,0,E),a(z)},[e,a]),v=i.useCallback(N=>R=>{c(N),R.dataTransfer.setData("text/plain",N),R.dataTransfer.effectAllowed="move"},[]),S=i.useCallback(()=>{c(null),u(null),h(null)},[]),j=i.useCallback(N=>R=>{if(R.preventDefault(),N===l)return;const z=R.currentTarget.getBoundingClientRect(),E=z.top+z.height/2,I=R.clientY<E?"before":"after";u(N),h(I)},[l]),C=i.useCallback(N=>R=>{R.preventDefault();const z=R.dataTransfer.getData("text/plain");if(!z||z===N){S();return}const E=e.findIndex(D=>D.id===z),I=e.findIndex(D=>D.id===N);if(E===-1||I===-1){S();return}const O=[...e],[U]=O.splice(E,1);let A=I;m==="after"&&E<I&&A--,m==="after"&&A++,O.splice(A,0,U),a(O),S()},[e,m,a,S]),w=i.useCallback(N=>{const R=N.currentTarget.getBoundingClientRect(),z=N.clientX,E=N.clientY;(z<R.left||z>R.right||E<R.top||E>R.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(hc,{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, priorities, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((N,R)=>{const z=l===N.id,E=d===N.id,I=["task-detail-section","subtask-item",z?"subtask-item-dragging":"",E?"subtask-item-drop-target":"",E&&m==="before"?"subtask-item-drop-before":"",E&&m==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:I,"data-testid":`subtask-item-${R}`,draggable:!s,onDragStart:v(N.id),onDragEnd:S,onDragOver:j(N.id),onDrop:C(N.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(mc,{size:16}),t.jsx("strong",{children:N.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(R,R-1),disabled:s||R===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Ta,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>b(R,R+1),disabled:s||R===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Po,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>y(N.id),disabled:s,children:[t.jsx(_n,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:O=>{f.current[R]=O},value:N.title,onChange:O=>g(N.id,{title:O.target.value}),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),R<e.length-1&&f.current[R+1]?.focus())},disabled:s})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:N.description,onChange:O=>g(N.id,{description:O.target.value}),disabled:s})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${N.id}-size`,children:"Size"}),t.jsxs("select",{id:`${N.id}-size`,className:"planning-size-select",value:N.suggestedSize,onChange:O=>g(N.id,{suggestedSize:O.target.value}),disabled:s,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${N.id}-priority`,children:"Priority"}),t.jsx("select",{id:`${N.id}-priority`,className:"planning-size-select",value:Ro(N.priority),onChange:O=>g(N.id,{priority:O.target.value}),disabled:s,children:pa.map(O=>t.jsx("option",{value:O,children:O[0].toUpperCase()+O.slice(1)},O))})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,R).filter(O=>O.id!==N.id).map(O=>{const U=N.dependsOn.includes(O.id);return t.jsxs("label",{className:`planning-dep-chip ${U?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:U,onChange:()=>{const A=U?N.dependsOn.filter(D=>D!==O.id):[...N.dependsOn,O.id];g(N.id,{dependsOn:A})},disabled:s}),t.jsx("span",{className:"planning-dep-id",children:O.id}),t.jsx("span",{className:"planning-dep-title",children:O.title||"Untitled"})]},O.id)}),R===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),R>0&&e.slice(0,R).filter(O=>O.id!==N.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},N.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:x,disabled:s,children:[t.jsx(Mn,{size:16,className:"icon-mr-6"})," Add subtask"]}),Rf(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(Ua,{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(jt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function G$({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(ak,{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,y=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(J$,{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(Y$,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:Q$(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:[y&&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(xy,{size:14}):t.jsx(To,{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(_n,{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 J$({status:e}){switch(e){case"generating":return t.jsx(jt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(Jd,{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(Ws,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(Ji,{size:14,className:"planning-sidebar-status-icon"})}}function Y$({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 Q$(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 X$(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function If(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 Z$({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=ri();Ni(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=Zi({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,y]=i.useState([]),[b,v]=i.useState([]),[S,j]=i.useState(""),[C,w]=i.useState(!0),[N,R]=i.useState(!1),[z,E]=i.useState(!1),[I,O]=i.useState(s),[U,A]=i.useState(null),[D,K]=i.useState(!1),[Z,ne]=i.useState("project-default"),[F,M]=i.useState(""),[P,$]=i.useState(""),[k,J]=i.useState("shared"),[ce,je]=i.useState(null),[He,xe]=i.useState(null),[Ne,Y]=i.useState(null),ie=i.useRef(null),ee=i.useRef([]),oe=i.useRef(!1),W=i.useRef(null),L=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,pe=i.useMemo(()=>qa(),[]),{isLockedByOther:fe,takeControl:B,isLoading:ve}=Ec(e?L:null),{activeTabMap:Fe,broadcastUpdate:ae,broadcastCompleted:qe,broadcastLock:Pe,broadcastUnlock:nt,broadcastHeartbeat:Be}=Or(),de=i.useMemo(()=>x.length===0||x.some(Re=>!Re.title.trim())||(Z==="existing"||Z==="custom-new")&&!F.trim()?!0:If(x),[Z,F,x]),Ie=p.type==="generating"||p.type==="editing"||p.type==="error",$e=L?Fe.get(L):null,{confirm:st}=pi(),Ue=$e&&$e.tabId!==pe,me=!!(Ue&&!$e.stale),re=fe&&(!Ue||$e.stale),_e=i.useCallback(()=>{I&&KP(I,o),ie.current?.close(),ie.current=null,g({type:"initial"}),y([]),v([]),j(""),w(!0),R(!1),E(!1),A(null),K(!1),ne("project-default"),M(""),$(""),J("shared"),oe.current=!1},[I,o]),xt=i.useCallback(()=>{ie.current?.close(),ie.current=null,n()},[n]),dt=i.useCallback(async()=>{if(!((D||p.type==="editing"||p.type==="creating")&&!await st({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(L)try{await ub(L,o,pe)}catch{}_e(),n()}},[D,n,_e,L,pe,p.type,o,st]),Qe=i.useCallback(Re=>{ie.current?.close(),ie.current=US(Re,o,{onThinking:be=>{j(at=>at+be),ae({sessionId:Re,status:"generating",needsInput:!1,owningTabId:pe,type:"subtask",title:I.trim()||void 0,projectId:o??null})},onSubtasks:be=>{R(!1),E(!1),Sd(o),y(be),g({type:"editing",sessionId:Re}),K(!1),ae({sessionId:Re,status:"awaiting_input",needsInput:!0,owningTabId:pe,type:"subtask",title:I.trim()||void 0,projectId:o??null})},onError:be=>{const at=be||"Session failed while contacting the AI.";R(!1),E(!1),A(null),g({type:"error",sessionId:Re,errorMessage:at}),ae({sessionId:Re,status:"error",needsInput:!1,owningTabId:pe,type:"subtask",title:I.trim()||void 0,projectId:o??null}),qe({sessionId:Re,status:"error"})},onComplete:()=>{qe({sessionId:Re,status:"complete"})},onConnectionStateChange:be=>{R(be==="reconnecting")}})},[qe,ae,I,o,pe]),vt=i.useCallback(async()=>{if(I.trim()){A(null),v([]),j(""),R(!1);try{const{sessionId:Re}=await FS(I.trim(),o);g({type:"generating",sessionId:Re}),Qe(Re)}catch(Re){A(Ee(Re)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[Qe,I,o]);i.useEffect(()=>{if(!e){_e();return}if(e&&s&&!oe.current)O(s),oe.current=!0,vt();else if(e&&!s&&!oe.current){const Re=GP(o);Re&&O(Re)}},[e,s,vt,_e]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const Re=await Ti(l);if(!Re)return;const be=kr(Re.conversationHistory);if(v(be),Re.status==="generating"||Re.status==="awaiting_input")j(Re.thinkingOutput??""),g({type:"generating",sessionId:l}),Qe(l);else if(Re.status==="complete"&&Re.result){Sd(o);const at=JSON.parse(Re.result);y(at),g({type:"editing",sessionId:l})}else Re.status==="error"&&(A(null),g({type:"error",sessionId:l,errorMessage:Re.error??"Session encountered an error"}))}catch(Re){A(Ee(Re)||"Failed to resume session")}})()},[Qe,e,l,p.type,o]),i.useEffect(()=>{if(!e){W.current&&(nt(W.current,pe),W.current=null);return}if(L&&W.current!==L){W.current&&nt(W.current,pe),Pe(L,pe),W.current=L;return}!L&&W.current&&(nt(W.current,pe),W.current=null)},[Pe,nt,e,L,pe]),i.useEffect(()=>{if(!e||!L||W.current!==L)return;Be(pe);const Re=setInterval(()=>{Be(pe)},3e4);return()=>{clearInterval(Re)}},[Be,e,L,pe]),i.useEffect(()=>()=>{ie.current?.close(),W.current&&(nt(W.current,pe),W.current=null)},[nt,pe]),i.useEffect(()=>{if(!e)return;const Re=be=>{be.key==="Escape"&&(be.preventDefault(),dt())};return document.addEventListener("keydown",Re),()=>document.removeEventListener("keydown",Re)},[e,dt]);const Ae=i.useCallback((Re,be)=>{y(at=>at.map(ot=>ot.id===Re?{...ot,...be}:ot)),K(!0)},[]),Je=i.useCallback(()=>{y(Re=>[...Re,X$(Re.length+1)]),K(!0)},[]),ct=i.useCallback(Re=>{y(be=>be.filter(at=>at.id!==Re).map(at=>({...at,dependsOn:at.dependsOn.filter(ot=>ot!==Re)}))),K(!0)},[]),Nt=i.useCallback(Re=>be=>{je(Re),be.dataTransfer.setData("text/plain",Re),be.dataTransfer.effectAllowed="move"},[]),yt=i.useCallback(()=>{je(null),xe(null),Y(null)},[]),Se=i.useCallback(Re=>be=>{if(be.preventDefault(),Re===ce)return;const at=be.currentTarget.getBoundingClientRect(),ot=at.top+at.height/2,gt=be.clientY<ot?"before":"after";xe(Re),Y(gt)},[ce]),G=i.useCallback(Re=>be=>{be.preventDefault();const at=be.dataTransfer.getData("text/plain");if(!at||at===Re){je(null),xe(null),Y(null);return}y(ot=>{const gt=ot.findIndex(mn=>mn.id===at),St=ot.findIndex(mn=>mn.id===Re);if(gt===-1||St===-1)return ot;const Lt=[...ot],[Yt]=Lt.splice(gt,1);let tn=St;return Ne==="after"&><St&&tn--,Ne==="after"&&tn++,Lt.splice(tn,0,Yt),Lt}),K(!0),je(null),xe(null),Y(null)},[Ne]),ge=i.useCallback(Re=>{const be=Re.currentTarget.getBoundingClientRect(),at=Re.clientX,ot=Re.clientY;(at<be.left||at>be.right||ot<be.top||ot>be.bottom)&&(xe(null),Y(null))},[]),pt=i.useCallback((Re,be)=>{be<0||be>=x.length||(y(at=>{const ot=[...at],[gt]=ot.splice(Re,1);return ot.splice(be,0,gt),ot}),K(!0))},[x.length]),ke=i.useCallback(Re=>{ee.current[Re+1]?.focus()},[]),tt=i.useCallback(async()=>{if(!(!L||de)){A(null),g({type:"creating",sessionId:L});try{const Re=await HS(L,x,r,o,{branchSelection:{mode:Z,...Z==="existing"||Z==="custom-new"?{branchName:F}:{},...P.trim()?{baseBranch:P.trim()}:{}},branchAssignment:{mode:k}});a(Re.tasks),_e(),n()}catch(Re){A(Ee(Re)||"Failed to create tasks"),g({type:"editing",sessionId:L})}}},[P,k,Z,F,de,n,a,r,o,_e,L,x]),Rt=i.useCallback(async()=>{if(p.type!=="error")return;const Re=p.sessionId;A(null),E(!0),j(""),g({type:"generating",sessionId:Re}),Qe(Re);try{await zS(Re,o,pe)}catch(be){let at=be;if((Ee(be)||"").includes("not in an error state"))try{const gt=await Ti(Re);if(!gt)throw new Error("Failed to refresh subtask session.");if(v(kr(gt.conversationHistory)),gt.status==="generating"||gt.status==="awaiting_input")j(gt.thinkingOutput??""),g({type:"generating",sessionId:gt.id}),ie.current?.isConnected()||Qe(gt.id);else if(gt.status==="complete"){if(!gt.result)throw new Error("Subtask session is complete but has no result.");Sd(o);const St=JSON.parse(gt.result);y(St),g({type:"editing",sessionId:gt.id}),K(!1)}else gt.status==="error"&&g({type:"error",sessionId:gt.id,errorMessage:gt.error??"Retry failed. Please try again."});R(!1);return}catch(gt){at=gt}ie.current?.close(),ie.current=null,g({type:"error",sessionId:Re,errorMessage:Ee(at)||"Retry failed. Please try again."}),R(!1)}finally{E(!1)}},[Qe,o,pe,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:Re=>Re.target===Re.currentTarget&&void dt(),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(hc,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ie&&t.jsx("button",{className:"modal-send-to-background",onClick:xt,title:"Send to background","aria-label":"Send to background",children:t.jsx(Lo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void dt(),"aria-label":"Close",children:t.jsx(un,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[U&&t.jsx("div",{className:"form-error planning-error",children:U}),N&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),me&&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:I})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(mi,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(jt,{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(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&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(mi,{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 Rt(),disabled:z,children:[z?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),t.jsx("span",{className:"icon-ml-6",children:z?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void dt(),disabled:z,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(mi,{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:[t.jsxs("div",{className:"task-detail-section",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch strategy"}),t.jsxs("select",{value:Z,onChange:Re=>ne(Re.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"project-default",children:"Use project/default branch"}),t.jsx("option",{value:"auto-new",children:"Create auto-named branch per task"}),t.jsx("option",{value:"existing",children:"Use existing branch"}),t.jsx("option",{value:"custom-new",children:"Create custom new branch"})]})]}),(Z==="existing"||Z==="custom-new")&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch name"}),t.jsx("input",{value:F,onChange:Re=>M(Re.target.value),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Merge target / base branch (optional)"}),t.jsx("input",{value:P,onChange:Re=>$(Re.target.value),disabled:p.type==="creating",placeholder:"main"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Planning branch mode"}),t.jsxs("select",{value:k,onChange:Re=>J(Re.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"shared",children:"Shared branch for all subtasks"}),t.jsx("option",{value:"per-task-derived",children:"Per-task branch derived from planning branch"})]})]})]}),x.map((Re,be)=>{const at=ce===Re.id,ot=He===Re.id,gt=["task-detail-section","subtask-item",at?"subtask-item-dragging":"",ot?"subtask-item-drop-target":"",ot&&Ne==="before"?"subtask-item-drop-before":"",ot&&Ne==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:gt,"data-testid":`subtask-item-${be}`,draggable:p.type!=="creating",onDragStart:Nt(Re.id),onDragEnd:yt,onDragOver:Se(Re.id),onDrop:G(Re.id),onDragLeave:ge,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(mc,{size:16}),t.jsx("strong",{children:Re.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>pt(be,be-1),disabled:p.type==="creating"||be===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(Ta,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>pt(be,be+1),disabled:p.type==="creating"||be===x.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Po,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>ct(Re.id),disabled:p.type==="creating",children:[t.jsx(_n,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:St=>{ee.current[be]=St},value:Re.title,onChange:St=>Ae(Re.id,{title:St.target.value}),onKeyDown:St=>{St.key==="Enter"&&(St.preventDefault(),ke(be))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:Re.description,onChange:St=>Ae(Re.id,{description:St.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:Re.suggestedSize,onChange:St=>Ae(Re.id,{suggestedSize:St.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,be).filter(St=>St.id!==Re.id).map(St=>{const Lt=Re.dependsOn.includes(St.id);return t.jsxs("label",{className:`planning-dep-chip ${Lt?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Lt,onChange:()=>{const Yt=Lt?Re.dependsOn.filter(tn=>tn!==St.id):[...Re.dependsOn,St.id];Ae(Re.id,{dependsOn:Yt})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:St.id}),t.jsx("span",{className:"planning-dep-title",children:St.title||"Untitled"})]},St.id)}),be===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),be>0&&x.slice(0,be).filter(St=>St.id!==Re.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},Re.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Je,disabled:p.type==="creating",children:[t.jsx(Mn,{size:16,className:"icon-mr-6"})," Add subtask"]}),If(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 dt(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void tt(),disabled:p.type==="creating"||de,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),fe&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(pc,{size:16}),t.jsx("span",{children:re?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),re&&t.jsx("button",{type:"button",onClick:()=>{B()},disabled:ve,className:"btn btn-primary session-lock-take-control",children:ve?"Taking control...":"Take Control"})]})})]})]})}):null}const e4=5,t4=1e3,n4=45e3;function Sl(){return{scrollback:null,connected:null,data:[]}}function s4(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),y=i.useRef(new Set),b=i.useRef(new Set),v=i.useRef(Sl()),S=i.useCallback(A=>{p.current.add(A);const D=v.current;return D.data.length>0&&(D.data.forEach(K=>A(K)),D.data=[]),()=>p.current.delete(A)},[]),j=i.useCallback(A=>(g.current.add(A),()=>g.current.delete(A)),[]),C=i.useCallback(A=>{x.current.add(A);const D=v.current;return D.connected&&(A(D.connected),D.connected=null),()=>x.current.delete(A)},[]),w=i.useCallback(A=>{y.current.add(A);const D=v.current;return D.scrollback&&(A(D.scrollback),D.scrollback=null),()=>y.current.delete(A)},[]),N=i.useCallback(A=>(b.current.add(A),()=>b.current.delete(A)),[]),R=i.useCallback(A=>{const D=d.current;D?.readyState===WebSocket.OPEN&&D.send(JSON.stringify({type:"input",data:A}))},[]),z=i.useCallback((A,D)=>{const K=d.current;K?.readyState===WebSocket.OPEN&&K.send(JSON.stringify({type:"resize",cols:A,rows:D}))},[]),E=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),v.current=Sl()},[]),I=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),v.current=Sl()},[]),O=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 K=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(K+=`&projectId=${encodeURIComponent(n)}`);const Z=new WebSocket(Di(K));d.current=Z,Z.onopen=()=>{if(r.current!==A){Z.close();return}v.current=Sl(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===A&&Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"ping"}))},n4)},Z.onmessage=ne=>{if(r.current===A)try{const F=JSON.parse(ne.data),M=v.current;switch(F.type){case"data":F.data&&(p.current.size===0&&M.data.push(F.data),p.current.forEach(P=>P(F.data)));break;case"scrollback":F.data&&(M.scrollback=F.data,y.current.forEach(P=>P(F.data)));break;case"connected":F.shell&&F.cwd&&(M.connected={shell:F.shell,cwd:F.cwd},x.current.forEach(P=>P({shell:F.shell,cwd:F.cwd})));break;case"exit":F.exitCode!==void 0&&g.current.forEach(P=>P(F.exitCode));break;case"ping":Z.readyState===WebSocket.OPEN&&Z.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},Z.onclose=ne=>{if(r.current!==A)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(ne.code===4e3||ne.code===4004){a("disconnected"),ne.code===4004&&b.current.forEach(P=>P());return}if(u.current++,u.current>e4){a("disconnected");return}const F=t4*Math.pow(2,u.current-1);a("reconnecting");const M=r.current;m.current=setTimeout(()=>{r.current===M&&(f.current||O())},Math.min(F,16e3))},Z.onerror=()=>{}},[e,n]),U=i.useCallback(()=>{u.current=0,I(),O()},[I,O]);return i.useEffect(()=>(c&&(E(),u.current=0,a("disconnected")),e?O():a("disconnected"),I),[e,n,c,O,I,E]),{connectionStatus:s,sendInput:R,resize:z,onData:S,onExit:j,onConnect:C,onScrollback:w,reconnect:U,onSessionInvalid:N}}const gv="kb-terminal-tabs",i4=15e3,a4=15e3;function Tf(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Pf(e){if(typeof window>"u")return[];try{const n=Bn(gv,e);if(n)return JSON.parse(n)}catch{}return[]}function Pd(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function $f(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 r4(e){const[n,s]=i.useState(()=>Pf(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(Pf(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{us(gv,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let C=!1;const w=h.current;return(async()=>{if(!C)try{const R=await $f(IN(e),i4,"listTerminalSessions");if(C||w!==h.current)return;const z=new Set(R.map(E=>E.id));l(!0),s(E=>{if(C||w!==h.current)return E;const O=E.map(D=>({...D,_verified:z.has(D.sessionId)})).filter(D=>D._verified);if(O.length===0)return[];const U=O.map(({_verified:D,...K})=>K);return U.find(D=>D.isActive)?U:U.map((D,K)=>({...D,isActive:K===0}))}),r(!0)}catch(R){if(C||w!==h.current)return;const z=Pd(R);z||console.warn("Failed to validate terminal sessions with server:",R),l(!z),r(!0)}})(),()=>{C=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const C=h.current,w=setTimeout(()=>{$f(Zo(void 0,void 0,void 0,e),a4,"createTerminalSession").then(N=>{if(C!==h.current)return;const R={id:Tf(),sessionId:N.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(z=>z.length>0?z:[...z.map(I=>({...I,isActive:!1})),R]),d(null)}).catch(N=>{if(C!==h.current)return;Pd(N)||console.error(N);const R=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";d(R)})},0);return()=>clearTimeout(w)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const C=await Zo(void 0,void 0,void 0,e),w={id:Tf(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(N=>[...N.map(z=>({...z,isActive:!1})),w]),w},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(C=>{s(w=>{const N=w.find(I=>I.id===C);if(!N)return w;zm(N.sessionId,e).catch(I=>{console.warn(`Failed to kill terminal session ${N.sessionId}:`,I)});const R=w.findIndex(I=>I.id===C),z=N.isActive,E=w.filter(I=>I.id!==C);if(E.length===0)return[];if(z){const I=Math.min(R,E.length-1);return E.map((O,U)=>({...O,isActive:U===I}))}return E})},[]),x=i.useCallback(C=>{s(w=>{let N=!1;const R=w.map(z=>z.id===C?(N=!0,{...z,isActive:!0}):{...z,isActive:!1});return N?R:w})},[]),y=i.useCallback((C,w)=>{s(N=>N.map(R=>R.id===C?{...R,title:w}:R))},[]),b=i.useCallback(async()=>{s(N=>{const R=N.find(z=>z.isActive);return R&&zm(R.sessionId,e).catch(z=>{console.warn(`Failed to kill old session ${R.sessionId}:`,z)}),N});const C=n.find(N=>N.isActive);if(!C)return;const w=await Zo(void 0,void 0,void 0,e);s(N=>N.map(R=>R.id===C.id?{...R,sessionId:w.sessionId}:R))},[n]),v=i.useCallback(async()=>{const C=n.find(w=>w.isActive);if(C)try{const w=await Zo(void 0,void 0,void 0,e);s(N=>N.map(R=>R.id===C.id?{...R,sessionId:w.sessionId}:R)),d(null)}catch(w){Pd(w)||console.error(w);const N=w instanceof Error?w.message:typeof w=="string"?w:"Failed to create terminal session";d(N)}},[n]),S=n.find(C=>C.isActive)??null,j=i.useCallback(()=>{d(null),h.current+=1,m(C=>C+1)},[]);return{tabs:n,activeTab:S,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:x,updateTabTitle:y,restartActiveTab:b,retryBootstrap:j,replaceActiveTabSession:v}}const o4=1e4,l4=[500,1500,3e3],bv="kb-terminal-font-size",fo=14,c4=8,d4=32,u4='"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 m4(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 h4(e){return`\x1B${e}`}const p4=[{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 go(e){return Math.min(d4,Math.max(c4,e))}function f4(){if(typeof window>"u")return fo;try{const e=window.localStorage.getItem(bv);if(!e)return fo;const n=Number.parseInt(e,10);return Number.isFinite(n)?go(n):fo}catch{return fo}}function g4(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 b4(e){return new Promise(n=>setTimeout(n,e))}async function x4(e,n=l4){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!g4(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 b4(o)}throw s??new Error("Dynamic import failed")}function Df(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function v4(){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=y4()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let $d=null;function y4(){return $d===null&&($d=window.innerHeight),$d}function w4({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),[y,b]=i.useState(null),[v,S]=i.useState(()=>f4()),[j,C]=i.useState(!1),[w,N]=i.useState(null),R=i.useRef(null),z=i.useRef(null),E=i.useRef(!1);Li(z,e,"fusion:terminal-modal-size");const I=i.useRef(null),O=i.useRef(null),U=i.useRef(!1),A=i.useRef(!1),D=i.useRef(null),K=i.useRef(()=>{}),Z=i.useRef(null),ne=i.useRef(0),F=i.useRef(v),M=i.useRef(null),P=i.useRef(a);ne.current=g,F.current=v;const $=i.useCallback(Ae=>{if(Ae&&A.current!==Ae)return;const Je=O.current,ct=I.current,Nt=D.current;if(!(!Je||!ct)&&!(Ae&&A.current!==Ae))try{Je.fit(),Nt&&Nt(ct.cols,ct.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Ae=>Ae+1)},[e]),i.useEffect(()=>{if(!e||!Df())return;const Ae=window.visualViewport;if(!Ae)return;const Je=()=>{const ct=v4();x(ct),b(Ae.height),ct>0&&z.current?.scrollIntoView&&z.current.scrollIntoView({block:"end",behavior:"smooth"}),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const Nt=typeof A.current=="string"?A.current:void 0;M.current=requestAnimationFrame(()=>{M.current=null,$(Nt)})};return Je(),Ae.addEventListener("resize",Je),Ae.addEventListener("scroll",Je),()=>{Ae.removeEventListener("resize",Je),Ae.removeEventListener("scroll",Je),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),x(0),b(null)}},[$,e]),i.useEffect(()=>{if(!e)return;const Ae=z.current;if(!Ae||typeof ResizeObserver>"u")return;let Je=null;const ct=new ResizeObserver(()=>{Je!==null&&cancelAnimationFrame(Je),Je=requestAnimationFrame(()=>{Je=null;const Nt=typeof A.current=="string"?A.current:void 0;$(Nt)})});return ct.observe(Ae),()=>{ct.disconnect(),Je!==null&&cancelAnimationFrame(Je)}},[$,e]);const{tabs:k,activeTab:J,isReady:ce,bootstrapError:je,createTab:He,closeTab:xe,setActiveTab:Ne,updateTabTitle:Y,restartActiveTab:ie,retryBootstrap:ee,replaceActiveTabSession:oe}=r4(a),{connectionStatus:W,sendInput:L,resize:pe,onData:fe,onConnect:B,onExit:ve,onScrollback:Fe,reconnect:ae,onSessionInvalid:qe}=s4(J?.sessionId??null,a);D.current=pe,K.current=L,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(bv,String(v))}catch{}},[v]);const Pe=i.useCallback(()=>{const Ae=I.current;if(Ae)try{O.current?.fit(),pe(Ae.cols,Ae.rows)}catch{}},[pe]);i.useEffect(()=>{if(!e||!ce)return;const Ae=J?.sessionId;if(!Ae)return;const Je=P.current!==a;if(Je&&(P.current=a),A.current===Ae&&I.current&&!Je)return;I.current&&(A.current!==Ae||Je)&&(I.current.dispose(),I.current=null,O.current=null,A.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),u(!1),h(null));let ct=!0,Nt;return(async()=>{const Se=x4(()=>Promise.all([Sn(()=>import("./vendor-xterm-DzcZoU0P.js").then(ke=>ke.x),__vite__mapDeps([5,1,6])),Sn(()=>import("./addon-fit-C7jRorKK.js").then(ke=>ke.a),__vite__mapDeps([8,1])),Sn(()=>import("./addon-web-links-CkJwd4cQ.js").then(ke=>ke.a),__vite__mapDeps([9,1]))])),G=new Promise((ke,tt)=>{Nt=setTimeout(()=>{tt(new Error("xterm initialization timed out"))},o4)});let ge,pt;try{const[{Terminal:ke},{FitAddon:tt},{WebLinksAddon:Rt}]=await Promise.race([Se,G]);if(!ct||!R.current||I.current)return;ge=new ke({cursorBlink:!0,cursorStyle:"block",fontSize:F.current,fontFamily:u4,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}),pt=new tt,ge.loadAddon(pt);const Re=new Rt;if(ge.loadAddon(Re),!Df())try{const{WebglAddon:ot}=await Sn(async()=>{const{WebglAddon:St}=await import("./addon-webgl-BjvOw43o.js").then(Lt=>Lt.a);return{WebglAddon:St}},__vite__mapDeps([10,1])),gt=new ot;gt.onContextLoss(()=>{gt.dispose()}),ge.loadAddon(gt)}catch{}ge.open(R.current),Nt&&clearTimeout(Nt);const be=R.current?.querySelector(".xterm-helper-textarea");if(be&&be.focus(),R.current)try{R.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{pt.fit();const ot=R.current?.querySelector(".xterm-helper-textarea");ot&&ot.focus()},50),I.current=ge,O.current=pt,A.current=Ae,ne.current>0&&(M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),M.current=requestAnimationFrame(()=>{M.current=null,$(Ae)})),ge.onData(ot=>{A.current===Ae&&K.current(ot)});const at=()=>{if(A.current===Ae&&O.current&&I.current)try{O.current.fit();const{cols:ot,rows:gt}=I.current;D.current?.(ot,gt)}catch{}};window.addEventListener("resize",at),Z.current&&window.removeEventListener("resize",Z.current),Z.current=at,u(!0),h(null)}catch(ke){if(Nt&&clearTimeout(Nt),!ct)return;const tt=ke instanceof Error?ke.message:"xterm initialization failed";h(tt)}})(),()=>{ct=!1,Nt&&clearTimeout(Nt)}},[$,e,ce,J?.sessionId,a]),i.useEffect(()=>{e||(I.current&&(I.current.dispose(),I.current=null),O.current=null,A.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),u(!1),h(null),U.current=!1,o(null),c(null),C(!1),N(null))},[e]),i.useEffect(()=>{if(!d||!I.current||!J)return;const Ae=J.sessionId,Je=G=>{A.current===Ae&&I.current?.write(G)},ct=fe(G=>{Je(G)}),Nt=Fe(G=>{Je(G)}),yt=B(G=>{Y(J.id,Hu(G.shell)||G.shell)}),Se=ve(G=>{A.current===Ae&&(c(G),I.current?.write(`\r
|
|
687
|
+
\x1B[33m[Process exited with code ${G}]\x1B[0m\r
|
|
688
|
+
`))});return()=>{ct(),Nt(),yt(),Se()}},[d,J?.sessionId,J?.id,J,W,fe,Fe,B,ve,Y]),i.useEffect(()=>{W==="connected"&&s&&U.current!==s&&J&&(U.current=s,setTimeout(()=>{L(s+`
|
|
689
|
+
`)},500))},[W,s,L,J,f]),i.useEffect(()=>{if(!d||!I.current)return;I.current.options.fontSize=v,M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const Ae=requestAnimationFrame(()=>{M.current=null,Pe()});return M.current=Ae,()=>{M.current===Ae&&(cancelAnimationFrame(Ae),M.current=null)}},[v,d,Pe]),i.useEffect(()=>{if(!e)return;const Ae=Je=>{if(!(!Je.ctrlKey&&!Je.metaKey)){if(Je.code==="Equal"||Je.code==="NumpadAdd"){Je.preventDefault(),S(ct=>go(ct+1));return}if(Je.code==="Minus"||Je.code==="NumpadSubtract"){Je.preventDefault(),S(ct=>go(ct-1));return}if(Je.code==="Digit0"||Je.code==="Numpad0"){Je.preventDefault(),S(fo);return}}};return window.addEventListener("keydown",Ae),()=>window.removeEventListener("keydown",Ae)},[e,Pe]),i.useEffect(()=>{if(!e)return;const Ae=Je=>{Je.key==="Escape"&&n()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[e,n]),i.useEffect(()=>{W==="connected"&&I.current&&setTimeout(()=>{if(!I.current||!R.current)return;const Ae=R.current.querySelector(".xterm-helper-textarea");Ae&&Ae.focus();try{R.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[W]);const nt=i.useCallback(()=>{if(!R.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;I.current?.focus();const Je=R.current.querySelector(".xterm-helper-textarea");if(!Je)return;Je.autocapitalize="off",Je.autocomplete="off",Je.autocorrect="off",Je.spellcheck=!1,Je.setAttribute("inputmode","text");try{Je.focus({preventScroll:!0})}catch{Je.focus()}const ct=Je.value.length;Je.setSelectionRange(ct,ct)},[]);i.useEffect(()=>qe(()=>{I.current?.clear(),c(null),U.current=!1,I.current&&(I.current.dispose(),I.current=null),O.current=null,A.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),u(!1),h(null),oe().catch(Je=>{console.error("Failed to replace invalid terminal session:",Je)})}),[qe,oe]);const Be=i.useCallback(Ae=>{Ae.target===Ae.currentTarget&&(E.current=!0)},[]),de=i.useCallback(Ae=>{E.current&&Ae.target===Ae.currentTarget&&n(),E.current=!1},[n]),Ie=i.useCallback(()=>{I.current?.clear()},[]),$e=i.useCallback(async()=>{I.current?.clear(),c(null),U.current=!1;try{await ie()}catch(Ae){o(Ee(Ae)||"Failed to restart terminal session")}},[ie]),st=i.useCallback(()=>{I.current&&(I.current.dispose(),I.current=null),O.current=null,A.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),h(null),u(!1)},[]),Ue=i.useCallback(()=>{window.location.reload()},[]),me=i.useCallback(()=>{S(Ae=>go(Ae+1))},[]),re=i.useCallback(()=>{S(Ae=>go(Ae-1))},[]),_e=i.useCallback(Ae=>{N(Je=>Je===Ae?null:Ae)},[]),xt=i.useCallback(Ae=>{if(w==="ctrl"){L(m4(Ae)),N(null);return}if(w==="alt"){L(h4(Ae)),N(null);return}L(Ae)},[L,w]),dt=i.useCallback(Ae=>{L(Ae),N(null)},[L]);if(!e)return null;const Qe=()=>{switch(W){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=!ce||!J&&!je;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Be,onMouseUp:de,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:z,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":y?`${y}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(Ae=>t.jsxs("div",{className:`terminal-tab ${Ae.isActive?"terminal-tab--active":""}`,onClick:()=>Ne(Ae.id),title:Ae.title,role:"tab","aria-selected":Ae.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ae.title}),k.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Je=>{Je.stopPropagation(),xe(Ae.id)},title:"Close tab",children:"×"})]},Ae.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:He,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Gi,{size:16}),Qe()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[W==="disconnected"&&J&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:ae,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(bs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:$e,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(bs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Ie,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(_n,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>C(Ae=>!Ae),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":j,children:[t.jsx(Fw,{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(un,{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&&!je&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),je&&!J&&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: ",je]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ee,"data-testid":"terminal-retry-btn",children:[t.jsx(bs,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ue,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(bs,{size:14}),"Refresh page"]})]})]})}),m&&J&&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:st,"data-testid":"terminal-reinit-btn",children:[t.jsx(bs,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ue,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(bs,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:R,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:nt,onTouchStart:nt},J?.sessionId)]}),j&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${w==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>_e("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:()=>_e("alt"),"aria-pressed":w==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>dt("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>dt(" "),children:"Tab"})]}),p4.map(Ae=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>xt(Ae.key),title:Ae.description,children:Ae.label},Ae.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${W}`,children:[W==="connected"&&"Connected",W==="connecting"&&"Connecting...",W==="reconnecting"&&"Reconnecting...",W==="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:re,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(ck,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[v,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:me,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(Mn,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const no={name:"",command:""};function Lf(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function k4(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function j4({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){Ni(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(no),[x,y]=i.useState(!1),[b,v]=i.useState(null),[S,j]=i.useState(null),C=Qi(n),w=i.useCallback(async()=>{try{d(!0);const K=await Eo(a);l(K)}catch(K){s(Ee(K)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&w()},[e,w]);const N=i.useCallback(()=>{m(!0),f(null),g(no),j(null)},[]),R=i.useCallback((K,Z)=>{f(K),m(!1),g({name:K,command:Z}),j(null)},[]),z=i.useCallback(()=>{f(null),m(!1),g(no),j(null)},[]),E=i.useCallback(K=>{g(Z=>({...Z,name:K})),K&&!Lf(K)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),I=i.useCallback(async()=>{const K=p.name.trim(),Z=p.command.trim();if(!K){s("Script name is required","error");return}if(!Lf(K)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!Z){s("Script command is required","error");return}y(!0);try{await LS(K,Z,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(no),j(null),await w()}catch(ne){const F=Ee(ne);F?.includes("already exists")?s("A script with this name already exists","error"):s(F||"Failed to save script","error")}finally{y(!1)}},[p,h,s,w,a]),O=i.useCallback(async K=>{try{await OS(K,a),s("Script deleted","success"),v(null),h===K&&(f(null),g(no)),await w()}catch(Z){s(Ee(Z)||"Failed to delete script","error")}},[h,s,w,a]),U=i.useCallback((K,Z)=>{r&&r(K,Z)},[r]);if(!e)return null;const A=u||h!==null,D=Object.entries(o).map(([K,Z])=>({name:K,command:Z}));return t.jsx("div",{className:"modal-overlay open",...C,"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(Gi,{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(jt,{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:K=>E(K.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:K=>g(Z=>({...Z,command:K.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:z,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:I,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(jt,{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:D.length===0?"No scripts defined":`${D.length} script${D.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:N,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Mn,{size:14}),"Add Script"]})]}),D.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(Gi,{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:D.map(K=>t.jsx("div",{className:"script-card","data-testid":`script-${K.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:K.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:K.command,children:k4(K.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:()=>U(K.name,K.command),title:"Run script","aria-label":`Run ${K.name}`,"data-testid":`run-script-${K.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(is,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>R(K.name,K.command),title:"Edit","aria-label":`Edit ${K.name}`,"data-testid":`edit-script-${K.name}`,children:t.jsx(Mn,{size:14,style:{transform:"rotate(45deg)"}})}),b===K.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>O(K.name),title:"Confirm delete","aria-label":`Confirm delete ${K.name}`,"data-testid":`confirm-delete-script-${K.name}`,style:{color:"var(--color-error)"},children:t.jsx(_n,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>v(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${K.name}`,children:t.jsx(un,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>v(K.name),title:"Delete","aria-label":`Delete ${K.name}`,"data-testid":`delete-script-${K.name}`,children:t.jsx(_n,{size:14})})]})]})},K.name))})]})})]})})}function N4(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 y(){d(!0),m(null);try{const b=await QN(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(Ee(b)||"Failed to load files"),r([]))}finally{x||d(!1)}}return y(),()=>{x=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function S4(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),y=i.useCallback(S=>{o(S),x(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),x(null);return}let S=!1;async function j(){h(!0),x(null);try{const C=await XN(e,n,a);S||(o(C.content),c(C.content),u(C.mtime))}catch(C){S||(x(Ee(C)||"Failed to load file"),o(""),c(""),u(null))}finally{S||h(!1)}}return j(),()=>{S=!0}},[e,n,s,a]);const b=r!==l,v=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await ZN(e,n,r,a);c(r),u(S.mtime)}catch(S){throw x(Ee(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:y,originalContent:l,loading:m,saving:f,error:g,save:v,hasChanges:b,mtime:d}}const C4=1e4;function E4(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function _4(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function M4(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 YN(e);if(u)return;s(E4(f.project)),r(f.tasks.map(_4)),d(null)}catch(f){u||d(Ee(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},C4);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function A4(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function R4(e){return e?new Date(e).toLocaleDateString():""}function Of(e,n){return uC(e,n)}const so={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Dd={type:null,entry:null,entryFullPath:""},I4=200,T4=500,Ff=10;function P4({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,y=f?.offsetTop??0,b=8;let v=e-x,S=n-y;v+h.width>p-b&&(v=p-b-h.width),S+h.height>g-b&&(S=g-b-h.height),v<b&&(v=b),S<b&&(S=b),c({x:v+x,y:S+y})},[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:da,disabled:!1},{id:"move",label:"Move",icon:mk,disabled:!1},{id:"rename",label:"Rename",icon:qs,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:To,disabled:!1}]:[{id:"download",label:"Download",icon:Xy,disabled:!1}],{id:"divider",label:"",icon:da,disabled:!0},{id:"delete",label:"Delete",icon:_n,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 $4({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 D4({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(so),[f,p]=i.useState(Dd),[g,x]=i.useState(!1),[y,b]=i.useState(null),[v,S]=i.useState(!1),[j,C]=i.useState(null),w=i.useRef(null),N=i.useRef(null),R=i.useRef(null),z=i.useRef(!1),E=i.useCallback(()=>{w.current!==null&&(window.clearTimeout(w.current),w.current=null),N.current!==null&&(window.clearTimeout(N.current),N.current=null)},[]),I=i.useCallback(()=>{E(),R.current=null,S(!1),C(null)},[E]);i.useEffect(()=>()=>{E()},[E]);const O=i.useCallback((P,$,k,J)=>{h({visible:!0,x:P,y:$,entry:k,entryFullPath:J})},[]),U=i.useCallback((P,$,k)=>{if(P.touches.length!==1)return;const J=P.touches[0];J&&(I(),R.current={x:J.clientX,y:J.clientY},N.current=window.setTimeout(()=>{S(!0),C(k)},I4),w.current=window.setTimeout(()=>{const ce=R.current;ce&&(z.current=!0,S(!1),C(null),E(),O(ce.x,ce.y,$,k))},T4))},[I,E,O]),A=i.useCallback(P=>{const $=R.current,k=P.touches[0];!$||!k||(Math.abs(k.clientX-$.x)>Ff||Math.abs(k.clientY-$.y)>Ff)&&I()},[I]),D=i.useCallback(()=>{I()},[I]);i.useEffect(()=>{if(!m.visible)return;const P=document.querySelector(".file-browser-list"),$=()=>{z.current=!1,I(),h(so)};return P?.addEventListener("scroll",$),()=>P?.removeEventListener("scroll",$)},[I,m.visible]),i.useEffect(()=>{if(!m.visible)return;const P=$=>{$.key==="Escape"&&(z.current=!1,h(so))};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[m.visible]);const K=i.useCallback((P,$)=>{P.preventDefault(),P.stopPropagation(),I(),z.current=!1,O(P.clientX,P.clientY,$,Of(n,$.name))},[I,n,O]),Z=i.useCallback(P=>{if(!m.entry)return;z.current=!1;const $=m.entry,k=m.entryFullPath;if(h(so),P==="download"){if(!c)return;const J=ob(c,k,u);window.open(Di(J),"_blank");return}if(P==="download-zip"){if(!c)return;const J=aS(c,k,u);window.open(Di(J),"_blank");return}p({type:P,entry:$,entryFullPath:k}),b(null)},[m,c,u]),ne=i.useCallback(async P=>{if(!(!f.type||!f.entry||!c)){x(!0),b(null);try{switch(f.type){case"copy":await tS(c,f.entryFullPath,P,u);break;case"move":await nS(c,f.entryFullPath,P,u);break;case"rename":await iS(c,f.entryFullPath,P,u);break;case"delete":await sS(c,f.entryFullPath,u);break}p(Dd),d?.()}catch($){b(Ee($)||"Operation failed")}finally{x(!1)}}},[f,c,d,u]),F=i.useCallback(()=>{p(Dd),b(null)},[]),M=i.useCallback((P,$)=>{if(z.current){z.current=!1;return}m.visible||(P.type==="directory"?a($):s($))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(jt,{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(mC(n))},children:[t.jsx(On,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":$r(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(P=>{const $=Of(n,P.name),k=v&&j===$;return t.jsxs("div",{className:`file-node file-node--${P.type} ${k?"file-node--long-pressing":""}`,onClick:()=>M(P,$),onContextMenu:J=>K(J,P),onTouchStart:J=>U(J,P,$),onTouchMove:A,onTouchEnd:D,onTouchCancel:D,children:[t.jsx("div",{className:"file-node-icon",children:P.type==="directory"?t.jsx(Es,{size:16}):t.jsx(Jg,{size:16})}),t.jsx("div",{className:"file-node-name",children:P.name}),P.type==="file"&&P.size!==void 0&&t.jsx("div",{className:"file-node-size",children:A4(P.size)}),P.mtime&&t.jsx("div",{className:"file-node-time",children:R4(P.mtime)})]},P.name)})}),m.visible&&m.entry&&t.jsx(P4,{x:m.x,y:m.y,entry:m.entry,onAction:Z,onClose:()=>{z.current=!1,h(so)}}),f.type&&f.entry&&t.jsx($4,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:ne,onCancel:F,loading:g,error:y})]})}function L4(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function O4({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=L4(a),h=m&&(s?!0:o),f=r&&!s&&!h,p=i.useMemo(()=>f?e.split(`
|
|
690
|
+
`).length:0,[e,f]),g=i.useCallback(()=>{l(!1)},[]),x=i.useCallback(()=>{l(!0)},[]),y=i.useCallback(()=>{d(v=>!v)},[]),b=i.useCallback(v=>{u.current&&(u.current.scrollTop=v.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(Gg,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:x,disabled:h,"aria-label":"Preview mode",children:[t.jsx(Ir,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${c?"btn-primary":""}`,onClick:y,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(zl,{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:y,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(zl,{size:14})})]}),h?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(ki,{remarkPlugins:[ji],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},(v,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:v=>n(v.target.value),onScroll:b,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function F4(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function z4({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(Mm,{size:14}):t.jsx(Xd,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(pn,{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(Mm,{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(Xd,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:F4(c.title)})]},c.id))]})]})]})}const B4=768,U4=280,Cl=180,El=500,zf="fusion:file-browser-sidebar-width",Bf="kb-files-line-numbers",xv=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),H4=new Set([...xv,".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 Ld(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return H4.has(n)}function q4(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return xv.has(n)}function V4({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:a}){const{projectName:r,workspaces:o}=M4(a),l=i.useRef(null);Li(l,!0,"fusion:files-modal-size");const c=Qi(n),[d,u]=i.useState(e),[m,h]=i.useState(null),[f,p]=i.useState(!1),[g,x]=i.useState("list"),[y,b]=i.useState(U4),[v,S]=i.useState(!1),{entries:j,currentPath:C,setPath:w,loading:N,error:R,refresh:z}=N4(d,!0,a),{content:E,setContent:I,originalContent:O,loading:U,saving:A,error:D,save:K,hasChanges:Z,mtime:ne}=S4(d,m,!0,a);i.useEffect(()=>{u(e)},[e]),i.useEffect(()=>{const ie=()=>{p(window.innerWidth<=B4)};return ie(),window.addEventListener("resize",ie),()=>window.removeEventListener("resize",ie)},[]),i.useEffect(()=>{m||x("list")},[m]),i.useEffect(()=>{try{const ie=localStorage.getItem(zf);if(!ie)return;const ee=Number.parseInt(ie,10);if(!Number.isNaN(ee)){const oe=Math.max(Cl,Math.min(El,ee));b(oe)}}catch{}},[]),i.useEffect(()=>{const ie=Bn(Bf,a);S(ie==="true")},[a]),i.useEffect(()=>{const ie=ee=>{ee.key==="Escape"&&n(),(ee.metaKey||ee.ctrlKey)&&ee.key==="s"&&(ee.preventDefault(),Z&&!A&&K())};return document.addEventListener("keydown",ie),()=>document.removeEventListener("keydown",ie)},[n,Z,A,K]);const F=i.useCallback(ie=>{h(ie),f&&x("editor")},[f]),M=i.useCallback(()=>{x("list")},[]),P=i.useCallback(()=>{I(O)},[O,I]),$=i.useCallback(ie=>{u(ie),h(null),x("list"),s?.(ie)},[s]),k=i.useCallback(ie=>{try{localStorage.setItem(zf,String(ie))}catch{}},[]),J=i.useCallback(ie=>{if(f)return;ie.preventDefault(),ie.stopPropagation();const ee=ie.currentTarget;typeof ee.setPointerCapture=="function"&&ee.setPointerCapture(ie.pointerId);const oe=ie.clientX,W=y;let L=W;document.body.style.userSelect="none";const pe=B=>{const ve=B.clientX-oe,Fe=Math.max(Cl,Math.min(El,W+ve));L=Fe,b(Fe)},fe=B=>{typeof ee.releasePointerCapture=="function"&&ee.releasePointerCapture(B.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",pe),document.removeEventListener("pointerup",fe),k(L)};document.addEventListener("pointermove",pe),document.addEventListener("pointerup",fe)},[f,k,y]),ce=i.useCallback(ie=>{if(f)return;const ee=20;if(ie.key!=="ArrowLeft"&&ie.key!=="ArrowRight")return;ie.preventDefault();const oe=ie.key==="ArrowLeft"?-ee:ee,W=Math.max(Cl,Math.min(El,y+oe));b(W),k(W)},[f,k,y]),je=i.useCallback(()=>{S(ie=>{const ee=!ie;return us(Bf,String(ee),a),ee})},[a]),xe=`Files — ${i.useMemo(()=>d==="project"?"Project":o.find(ie=>ie.id===d)?.id??d,[d,o])}`,Ne=i.useMemo(()=>!m||!q4(m)?null:ob(d,m,a),[m,d,a]),Y=ie=>{const ee=new Blob([ie]).size;return ee<1024?`${ee} B`:`${(ee/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(Es,{size:18}),t.jsx("span",{children:xe}),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 ${v?"btn-primary":""}`,onClick:je,"aria-label":"Toggle line numbers","aria-pressed":v,title:"Toggle line numbers",children:[t.jsx(Kw,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx(z4,{currentWorkspace:d,projectName:r,workspaces:o,onSelect:$}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(un,{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:`${y}px`},children:t.jsx(D4,{entries:j,currentPath:C,onSelectFile:F,onNavigate:w,loading:N,error:R,onRetry:z,workspace:d,onRefresh:z,projectId:a})}),!f&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Cl,"aria-valuemax":El,"aria-valuenow":y,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:J,onKeyDown:ce}),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(Ua,{size:16}),t.jsx("span",{children:"Back"})]}),m,Ld(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(gw,{size:12}),"Binary file — read only"]}),ne&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(ne).toLocaleString()]}),U&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!Ne&&Z&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:P,disabled:A,children:[t.jsx(Ek,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void K(),disabled:A,children:[t.jsx(eb,{size:14}),A?"Saving...":"Save"]})]})})]}),D&&!Ne&&t.jsx("div",{className:"file-browser-error-banner",children:D}),Ne?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:Ne,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(O4,{content:E,onChange:I,filePath:m,readOnly:Ld(m),showLineNumbers:v&&!Ld(m)})}),!Ne&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:Y(E)}),Z&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Es,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const W4=i.lazy(()=>Sn(()=>import("./TodoView-BD9NRwq0.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function K4({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=Qi(e),l=ri()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Zi({enabled:l});Ni(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(Vw,{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(un,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(W4,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&m})})})]})})}function G4(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 Zj();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:Ee(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 J4(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 Y4(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const vv="kb-usage-hidden-windows",yv="kb-usage-modal-size",wv="kb-usage-provider-order";function Uf(e){const n=Bn(yv,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 Hf(e){const n=Bn(vv,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 Q4(e,n){us(vv,JSON.stringify(e),n)}function qf(e){const n=Bn(wv,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function Vf(e,n){us(wv,JSON.stringify(e),n)}function kv(e,n,s){return s[e]?.includes(n)??!1}function X4({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=Y4(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 y=new Date(e.resetAt).getTime()-Date.now();if(y>0){const b=Math.floor(y/36e5),v=Math.floor(b/24),S=b%24;v>0&&S>0?u=`resets in ${v}d ${S}h`:v>0?u=`resets in ${v}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(y/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(Ir,{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:J4(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Oo,{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(Jk,{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 Z4(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 eD({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:y,onMoveDown:b}){const v=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(Fn,{provider:Z4(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),v>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 (",v,")"]})]}),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:y,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(Pi,{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(pn,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(mc,{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((j,C)=>{const w=kv(e.name,j.label,s);return t.jsx(X4,{window:j,viewMode:n,isHidden:w,onToggleHidden:()=>a(e.name,j.label)},`${e.name}-${j.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function tD(){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 nD({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=G4({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,y]=i.useState("used"),[b,v]=i.useState(()=>Hf(s)),[S,j]=i.useState(()=>qf(s)),[C,w]=i.useState(null),[N,R]=i.useState(null),[z,E]=i.useState(null),I=i.useRef(null),O=i.useRef(null),U=i.useRef(e),A=i.useRef(!1),[D,K]=i.useState(()=>Uf(s));i.useEffect(()=>{K(Uf(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const B=O.current;if(!B||typeof ResizeObserver>"u")return;let ve=null;const Fe=new ResizeObserver(ae=>{const qe=ae[0];if(!qe)return;const{width:Pe,height:nt}=qe.contentRect;Pe<=0||nt<=0||(ve&&clearTimeout(ve),ve=setTimeout(()=>{us(yv,JSON.stringify({width:Math.round(Pe),height:Math.round(nt)}),s)},250))});return Fe.observe(B),()=>{ve&&clearTimeout(ve),Fe.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 B=window.matchMedia?.("(pointer: coarse)"),ve=()=>{f(window.innerWidth>=769),g(B?.matches??!1)};return ve(),window.addEventListener("resize",ve),B?.addEventListener?.("change",ve),()=>{window.removeEventListener("resize",ve),B?.removeEventListener?.("change",ve)}},[]),i.useEffect(()=>{!U.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),U.current=e},[e,c,d]),i.useEffect(()=>{const B=Bn("kb-usage-view-mode",s);if(B==="used"||B==="remaining"){y(B);return}y("used")},[s]);const Z=i.useCallback(B=>{y(B),us("kb-usage-view-mode",B,s)},[s]);i.useEffect(()=>{v(Hf(s)),j(qf(s))},[s]),i.useEffect(()=>{Q4(b,s)},[b,s]);const ne=i.useCallback((B,ve)=>{v(Fe=>{if(kv(B,ve,Fe)){const ae=(Fe[B]??[]).filter(qe=>qe!==ve);if(ae.length===0){const{[B]:qe,...Pe}=Fe;return Pe}return{...Fe,[B]:ae}}return{...Fe,[B]:[...Fe[B]??[],ve]}})},[]),F=i.useCallback(B=>{v(ve=>{if(!ve[B])return ve;const{[B]:Fe,...ae}=ve;return ae})},[]),M=i.useCallback(B=>{if(S.length===0)return B;const ve=new Map(B.map(ae=>[ae.name,ae])),Fe=[];for(const ae of S){const qe=ve.get(ae);qe&&(Fe.push(qe),ve.delete(ae))}return[...Fe,...ve.values()]},[S]),P=i.useCallback((B,ve)=>{B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",ve),w(ve)},[]),$=i.useCallback((B,ve)=>{if(!C||C===ve)return;B.preventDefault(),B.dataTransfer.dropEffect="move";const{top:Fe,height:ae}=B.currentTarget.getBoundingClientRect(),qe=Fe+ae/2,Pe=B.clientY<qe?"before":"after";R(ve),E(Pe)},[C]),k=i.useCallback((B,ve)=>{B.preventDefault();const Fe=C??B.dataTransfer.getData("text/plain");if(!Fe||Fe===ve){R(null),E(null);return}const qe=M(r).map(Be=>Be.name).filter(Be=>Be!==Fe),Pe=qe.indexOf(ve);if(Pe<0){R(null),E(null);return}const nt=z==="after"?Pe+1:Pe;qe.splice(nt,0,Fe),Vf(qe,s),j(qe),R(null),E(null)},[C,z,s,r,M]),J=i.useCallback(()=>{w(null),R(null),E(null)},[]),ce=i.useCallback((B,ve)=>{const Fe=M(r).map(Be=>Be.name),ae=Fe.indexOf(B),qe=ae+ve;if(ae<0||qe<0||qe>=Fe.length)return;const Pe=[...Fe],[nt]=Pe.splice(ae,1);Pe.splice(qe,0,nt),Vf(Pe,s),j(Pe)},[s,r,M]),je=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const B=ve=>{ve.key==="Escape"&&n()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n]);const He=i.useCallback(B=>{B.target===B.currentTarget&&n()},[n]);if(!e)return null;const xe=!!(a&&h),Ne=8,Y=12,ee=D?.width??420,oe=xe?Math.min((a?.bottom??0)+Ne,window.innerHeight-Y):void 0,W=xe?Math.max(8,(a?.right??0)-ee):void 0,L=h&&D?{width:D.width,height:D.height}:{},pe=M(r),fe=t.jsxs("div",{ref:O,className:`usage-modal${xe?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:xe?{position:"fixed",top:oe,left:W,...L}:L,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ys,{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:()=>Z("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:()=>Z("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(un,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:I,children:(o||!A.current&&!l)&&r.length===0?t.jsx(tD,{}):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:je,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:pe.map((B,ve)=>t.jsx(eD,{provider:B,viewMode:x,hiddenWindows:b,onToggleWindow:ne,onShowAllHidden:F,isDragging:C===B.name,isDragOver:N===B.name,dragOverPosition:N===B.name?z:null,onDragStart:Fe=>P(Fe,B.name),onDragOver:Fe=>$(Fe,B.name),onDragLeave:()=>{N===B.name&&(R(null),E(null))},onDrop:Fe=>k(Fe,B.name),onDragEnd:J,isTouchReorderMode:p,canMoveUp:ve>0,canMoveDown:ve<pe.length-1,onMoveUp:()=>ce(B.name,-1),onMoveDown:()=>ce(B.name,1)},B.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:je,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(bs,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return xe?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),fe]}):t.jsx("div",{className:"modal-overlay open",onClick:He,"data-testid":"usage-modal-overlay",children:fe})}function jv(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 nc(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 sD={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Nv={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},iD={cron:qg,webhook:tb,api:Vg,manual:as},aD={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},rD={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function oD({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(Do,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:jv(n)})]})}function lD({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"} ${nc(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Gn,{size:12}):t.jsx(Do,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:nc(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Nv[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:jv(r)}),s?t.jsx(Pi,{size:12}):t.jsx(pn,{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 cD({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=pi(),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=sD[e.trigger.type],f=iD[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}),Nv[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(dc,{size:10}):t.jsx(Es,{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(jt,{className:"spinner"}):t.jsx(is,{})}),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(vi,{}):t.jsx(is,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(qs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(_n,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx($a,{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(Ji,{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:aD[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:rD[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:nc(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:nc(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(oD,{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(Pi,{size:12}):t.jsx(pn,{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(lD,{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 dD({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Gi,{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(Jw,{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(gs,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Od(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function uD(e){return e==="command"?{id:Od(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Od(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Od(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function mD({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,y]=i.useState(e.taskTitle??""),[b,v]=i.useState(e.taskDescription??""),[S,j]=i.useState(e.taskColumn??"triage"),[C,w]=i.useState(e.timeoutMs),[N,R]=i.useState(e.continueOnFailure??!1),[z,E]=i.useState({}),[I,O]=i.useState([]),[U,A]=i.useState(!1),[D,K]=i.useState(null);i.useEffect(()=>{let P=!1;return A(!0),K(null),Ks().then($=>{P||O($.models)}).catch($=>{P||K($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{P||A(!1)}),()=>{P=!0}},[]);const Z=i.useCallback(()=>{const P={};return a.trim()||(P.name="Step name is required"),o==="command"&&!c.trim()&&(P.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(P.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(P.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(P.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(P.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(P),Object.keys(P).length===0},[a,o,c,u,b,h,p,C]),ne=h&&p?`${h}/${p}`:"",F=i.useCallback(P=>{if(!P)f(""),g("");else{const $=P.indexOf("/");$!==-1&&(f(P.slice(0,$)),g(P.slice($+1)))}},[]),M=i.useCallback(()=>{if(!Z())return;const P={...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:C||void 0,continueOnFailure:N};o!=="ai-prompt"&&delete P.prompt,o!=="create-task"&&(delete P.taskTitle,delete P.taskDescription,delete P.taskColumn),n(P)},[Z,n,e,a,o,c,u,x,b,S,h,p,C,N]);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:P=>r(P.target.value),"aria-invalid":!!z.name}),z.name&&t.jsx("small",{className:"field-error",children:z.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:P=>l(P.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:P=>d(P.target.value),rows:2,"aria-invalid":!!z.command}),z.command&&t.jsx("small",{className:"field-error",children:z.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:P=>m(P.target.value),rows:3,"aria-invalid":!!z.prompt}),z.prompt&&t.jsx("small",{className:"field-error",children:z.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(Is,{id:`step-model-${e.id}`,label:"Model",models:I,value:ne,onChange:F,placeholder:"Use default",disabled:U}),D&&t.jsx("small",{className:"field-error",children:D}),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:P=>y(P.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:P=>v(P.target.value),rows:4,"aria-invalid":!!z.taskDescription}),z.taskDescription&&t.jsx("small",{className:"field-error",children:z.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:P=>j(P.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(Is,{id:`step-task-model-${e.id}`,label:"Model",models:I,value:ne,onChange:F,placeholder:"Use default",disabled:U}),D&&t.jsx("small",{className:"field-error",children:D}),z.modelProvider&&t.jsx("small",{className:"field-error",children:z.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:P=>w(P.target.value?Number(P.target.value):void 0),"aria-invalid":!!z.timeoutMs}),z.timeoutMs&&t.jsx("small",{className:"field-error",children:z.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:N,onChange:P=>R(P.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 hD({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=uD(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(mD,{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(mc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(dD,{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(Pi,{})}),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(pn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(qs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(_n,{})})]})]})},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(Mn,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Mn,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Mn,{size:14}),"Add Create Task Step"]})]})]})}const Sv={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},pD={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function fD(e){const n=e.trim();for(const[s,a]of Object.entries(Sv))if(a===n)return s;return"custom"}function gD(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function bD(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 xD(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 vD=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],yD=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Wf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function Kf({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?xD(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),[y,b]=i.useState(()=>c.triggerType!=="cron"?"custom":fD(c.cronExpression)),[v,S]=i.useState(c.webhookPath),[j,C]=i.useState(c.webhookSecret),[w,N]=i.useState(c.endpoint),[R,z]=i.useState(e?.executionPolicy??"queue"),[E,I]=i.useState(e?.catchUpPolicy??"run_one"),[O,U]=i.useState(e?.enabled??!0),A=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,D=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[K,Z]=i.useState(e?.steps&&e.steps.length>0&&!A&&!D?"advanced":"simple"),[ne,F]=i.useState(()=>A?"ai-prompt":D?"create-task":"command"),[M,P]=i.useState(e?.command??""),[$,k]=i.useState(e?.steps??[]),[J,ce]=i.useState(!1),[je,He]=i.useState(e?.timeoutMs??3e5),[xe,Ne]=i.useState(A?e.steps?.[0]?.prompt??"":""),[Y,ie]=i.useState(D?e.steps?.[0]?.taskTitle??"":""),[ee,oe]=i.useState(D?e.steps?.[0]?.taskDescription??"":""),[W,L]=i.useState(D?e.steps?.[0]?.taskColumn??"triage":"triage"),[pe,fe]=i.useState(A||D?e.steps?.[0]?.modelProvider??"":""),[B,ve]=i.useState(A||D?e.steps?.[0]?.modelId??"":""),[Fe,ae]=i.useState([]),[qe,Pe]=i.useState(!1),[nt,Be]=i.useState(null),[de,Ie]=i.useState(a??"global"),[$e,st]=i.useState({}),[Ue,me]=i.useState(!1),re=i.useRef(!0);i.useEffect(()=>()=>{re.current=!1},[]),i.useEffect(()=>{a&&Ie(a)},[a]),i.useEffect(()=>{let ke=!1;return Pe(!0),Be(null),Ks().then(tt=>{ke||ae(tt.models)}).catch(tt=>{ke||Be(tt instanceof Error?tt.message:"Failed to load models")}).finally(()=>{ke||Pe(!1)}),()=>{ke=!0}},[]);const _e=pe&&B?`${pe}/${B}`:"",xt=i.useCallback(ke=>{if(!ke){fe(""),ve("");return}const tt=ke.indexOf("/");tt!==-1&&(fe(ke.slice(0,tt)),ve(ke.slice(tt+1)))},[]),dt=i.useCallback(()=>{const ke={};if(d.trim()||(ke.name="Name is required"),de==="project"&&!r&&(ke.scope="Project-specific entries require an active project."),f==="cron"&&y==="custom"&&(g.trim()?gD(g)||(ke.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):ke.cronExpression="Cron expression is required"),f==="webhook"&&!v.trim()&&(ke.webhookPath="Webhook path is required"),f==="api"&&!w.trim()&&(ke.endpoint="API endpoint is required"),K==="simple")ne==="command"&&!M.trim()&&(ke.command="Command is required"),ne==="ai-prompt"&&!xe.trim()&&(ke.prompt="Prompt is required"),ne==="create-task"&&!ee.trim()&&(ke.taskDescription="Task description is required"),(pe.trim()&&!B.trim()||!pe.trim()&&B.trim())&&(ke.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(ke.steps="At least one step is required"),J&&(ke.stepsEditing="Please save or cancel all step edits before saving the routine");const tt=[];$.forEach((Rt,Re)=>{Rt.name?.trim()||tt.push(`Step ${Re+1}: Name is required`),Rt.type==="command"&&!Rt.command?.trim()&&tt.push(`Step ${Re+1}: Command is required`),Rt.type==="ai-prompt"&&!Rt.prompt?.trim()&&tt.push(`Step ${Re+1}: Prompt is required`),Rt.type==="create-task"&&!Rt.taskDescription?.trim()&&tt.push(`Step ${Re+1}: Task description is required`)}),tt.length>0&&(ke.steps=tt.join("; "))}return je<1e3&&(ke.timeoutMs="Timeout must be at least 1 second (1000ms)"),st(ke),Object.keys(ke).length===0},[d,f,g,y,v,w,de,r,K,ne,M,xe,ee,pe,B,$,J,je]),Qe=i.useCallback(async ke=>{if(ke.preventDefault(),!!dt()){me(!0);try{let tt=e?.scope??de??(r?"project":"global");tt==="project"&&!r&&(tt="global");const Rt=bD(f,g,v,j,w);let Re,be;K==="simple"?ne==="command"?Re=M.trim()||void 0:ne==="ai-prompt"?be=[{id:Wf(),type:"ai-prompt",name:d.trim(),prompt:xe.trim(),modelProvider:pe.trim()||void 0,modelId:B.trim()||void 0}]:be=[{id:Wf(),type:"create-task",name:d.trim(),taskTitle:Y.trim()||void 0,taskDescription:ee.trim(),taskColumn:W,modelProvider:pe.trim()||void 0,modelId:B.trim()||void 0}]:be=$;const at={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:Rt,command:Re,steps:be,timeoutMs:je,executionPolicy:R,catchUpPolicy:E,enabled:O,scope:tt};await n(at)}finally{re.current&&me(!1)}}},[dt,n,d,m,f,g,v,j,w,K,ne,M,xe,pe,B,Y,ee,W,$,je,R,E,O,de,r,e?.scope,e?.agentId]),vt="routine-name-error",Ae="routine-cron-error",Je="routine-webhook-error",ct="routine-endpoint-error",Nt="routine-command-error",yt="routine-prompt-error",Se="routine-task-description-error",G="routine-model-error",ge="routine-timeout-error",pt=i.useCallback(ke=>{b(ke),ke!=="custom"&&x(Sv[ke])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:Qe,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:ke=>u(ke.target.value),"aria-invalid":!!$e.name,"aria-describedby":$e.name?vt:void 0}),$e.name&&t.jsx("small",{id:vt,className:"field-error",children:$e.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:ke=>h(ke.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${de==="global"?" active":""}`,onClick:()=>{Ie("global"),o?.("global")},role:"radio","aria-checked":de==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(dc,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${de==="project"?" active":""}`,onClick:()=>{Ie("project"),o?.("project")},role:"radio","aria-checked":de==="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(Es,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":de==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),$e.scope&&t.jsx("small",{className:"field-error",children:$e.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(qg,{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(tb,{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(Vg,{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(as,{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:y,onChange:ke=>pt(ke.target.value),children:Object.entries(pD).map(([ke,tt])=>t.jsx("option",{value:ke,children:tt},ke))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:ke=>x(ke.target.value),disabled:y!=="custom","aria-invalid":!!$e.cronExpression,"aria-describedby":$e.cronExpression?Ae:void 0}),$e.cronExpression?t.jsx("small",{id:Ae,className:"field-error",children:$e.cronExpression}):t.jsx("small",{children:y==="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:v,onChange:ke=>S(ke.target.value),"aria-invalid":!!$e.webhookPath,"aria-describedby":$e.webhookPath?Je:void 0}),$e.webhookPath?t.jsx("small",{id:Je,className:"field-error",children:$e.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:j,onChange:ke=>C(ke.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:ke=>N(ke.target.value),"aria-invalid":!!$e.endpoint,"aria-describedby":$e.endpoint?ct:void 0}),$e.endpoint?t.jsx("small",{id:ct,className:"field-error",children:$e.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${K==="simple"?" active":""}`,onClick:()=>Z("simple"),role:"radio","aria-checked":K==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${K==="advanced"?" active":""}`,onClick:()=>Z("advanced"),role:"radio","aria-checked":K==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:K==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),K==="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${ne==="command"?" active":""}`,onClick:()=>F("command"),role:"radio","aria-checked":ne==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ne==="ai-prompt"?" active":""}`,onClick:()=>F("ai-prompt"),role:"radio","aria-checked":ne==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${ne==="create-task"?" active":""}`,onClick:()=>F("create-task"),role:"radio","aria-checked":ne==="create-task",children:"Create Task"})]})]}),ne==="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:ke=>P(ke.target.value),"aria-invalid":!!$e.command,"aria-describedby":$e.command?Nt:void 0}),$e.command?t.jsx("small",{id:Nt,className:"field-error",children:$e.command}):t.jsx("small",{children:"Shell command to execute."})]}):ne==="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:xe,onChange:ke=>Ne(ke.target.value),rows:3,"aria-invalid":!!$e.prompt,"aria-describedby":$e.prompt?yt:void 0}),$e.prompt?t.jsx("small",{id:yt,className:"field-error",children:$e.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(Is,{id:"routine-model",label:"Model",models:Fe,value:_e,onChange:xt,placeholder:"Use default",disabled:qe}),nt&&t.jsx("small",{className:"field-error",children:nt}),$e.model&&t.jsx("small",{id:G,className:"field-error",children:$e.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:Y,onChange:ke=>ie(ke.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:ee,onChange:ke=>oe(ke.target.value),rows:4,"aria-invalid":!!$e.taskDescription,"aria-describedby":$e.taskDescription?Se:void 0}),$e.taskDescription?t.jsx("small",{id:Se,className:"field-error",children:$e.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:W,onChange:ke=>L(ke.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(Is,{id:"routine-task-model",label:"Executor Model",models:Fe,value:_e,onChange:xt,placeholder:"Use default",disabled:qe}),nt&&t.jsx("small",{className:"field-error",children:nt}),$e.model&&t.jsx("small",{id:G,className:"field-error",children:$e.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(hD,{steps:$,onChange:k,onEditingChange:ce}),$e.steps&&t.jsx("small",{className:"field-error",children:$e.steps}),$e.stepsEditing&&t.jsx("small",{className:"field-error",children:$e.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:je,onChange:ke=>He(Number(ke.target.value)),"aria-invalid":!!$e.timeoutMs,"aria-describedby":$e.timeoutMs?ge:void 0}),$e.timeoutMs?t.jsx("small",{id:ge,className:"field-error",children:$e.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:R,onChange:ke=>z(ke.target.value),children:vD.map(ke=>t.jsx("option",{value:ke.value,children:ke.label},ke.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:E,onChange:ke=>I(ke.target.value),children:yD.map(ke=>t.jsx("option",{value:ke.value,children:ke.label},ke.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:O,onChange:ke=>U(ke.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:Ue,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ue,children:Ue?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const wD=3e4;function kD({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);Li(x,!0,"fusion:automation-modal-size");const y=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const A=await CS(y);l(A),g(D=>{const K={...D};for(const Z of A){const ne=K[Z.id];if(!ne||!Z.lastRunResult)continue;const F=Z.lastRunResult;F.success===ne.success&&(F.output||"")===ne.output&&(F.error||"")===(ne.error||"")&&delete K[Z.id]}return K})}catch(A){n(Ee(A)||"Failed to load routines","error")}},[n,y]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const A=setInterval(()=>{b()},wD);return()=>clearInterval(A)},[b]),i.useEffect(()=>{const A=D=>{D.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e,c]);const v=Qi(e),S=i.useCallback(async A=>{try{await ES(A,y),n("Routine created","success"),d("list"),await b()}catch(D){n(Ee(D)||"Failed to create routine","error")}},[n,b,y]),j=i.useCallback(A=>{m(A),d("edit")},[]),C=i.useCallback(async A=>{if(u)try{await Km(u.id,A,y),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(D){n(Ee(D)||"Failed to update routine","error")}},[u,n,b,y]),w=i.useCallback(async A=>{try{await _S(A.id,y),n(`Deleted "${A.name}"`,"success"),await b()}catch(D){n(Ee(D)||"Failed to delete routine","error")}},[n,b,y]),N=i.useCallback(async A=>{f(A.id);try{const{result:D}=await MS(A.id,y);g(K=>({...K,[A.id]:{output:D.output||"",error:D.error,success:D.success}})),D.success?n(`"${A.name}" completed successfully`,"success"):n(`"${A.name}" failed: ${D.error||"Unknown error"}`,"error"),await b()}catch(D){n(Ee(D)||"Failed to run routine","error")}finally{f(null)}},[n,b,y]),R=i.useCallback(async A=>{try{await Km(A.id,{enabled:!A.enabled},y),n(`"${A.name}" ${A.enabled?"disabled":"enabled"}`,"success"),await b()}catch(D){n(Ee(D)||"Failed to toggle routine","error")}},[n,b,y]),z=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const E=i.useCallback(A=>{r(A),d("list"),m(void 0),g({})},[]),I=()=>c==="create"?t.jsx(Kf,{onSubmit:S,onCancel:z,scope:a,projectId:s}):c==="edit"&&u?t.jsx(Kf,{routine:u,onSubmit:C,onCancel:z,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(as,{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(Mn,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(A=>t.jsx(cD,{routine:A,onEdit:j,onDelete:w,onRun:N,onToggle:R,running:h===A.id,lastRunOutput:p[A.id]??null},A.id))}),O=()=>I(),U=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...v,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(as,{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(un,{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:()=>E("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(dc,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>E("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(Es,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(as,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:U&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx(Mn,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:O()})]})})}const jD=3e4,Cu=new Map,Fd=new Map;function Gf(e){return e??"default"}function Jf(e){const n=Cu.get(e);return n?Date.now()>=n.expiresAt?(Cu.delete(e),null):n:null}function ND(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 SD(e){const n=Fd.get(e);if(n)return n;const s=Co().then(({providers:a,ghCli:r})=>{const l={...ND(a,r),ghCli:r,expiresAt:Date.now()+jD};return Cu.set(e,l),l}).finally(()=>{Fd.delete(e)});return Fd.set(e,s),s}function Cv(e){const n=Gf(e),s=Jf(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=Gf(e),p=Jf(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 y=await SD(f);if(h)return;r(y.hasAiProvider),l(y.hasGithub),c(y.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 Ev({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(un,{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 CD({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=pi(),u=ri();Ni(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=Zi({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[x,y]=i.useState(""),[b,v]=i.useState([]),[S,j]=i.useState(""),[C,w]=i.useState(""),[N,R]=i.useState([]),[z,E]=i.useState(!1),[I,O]=i.useState(""),[U,A]=i.useState(""),[D,K]=i.useState(""),[Z,ne]=i.useState(""),[F,M]=i.useState(""),[P,$]=i.useState("default"),[k,J]=i.useState(!1),[ce,je]=i.useState([]),[He,xe]=i.useState(!1),[Ne,Y]=i.useState(void 0),[ie,ee]=i.useState(Ds),[oe,W]=i.useState(void 0),[L,pe]=i.useState(!1),[fe,B]=i.useState(""),[ve,Fe]=i.useState(null),[ae,qe]=i.useState([]),[Pe,nt]=i.useState(!1),[Be,de]=i.useState(!1),Ie=i.useRef(null),[$e,st]=i.useState(!1),[Ue,me]=i.useState(""),re=i.useRef(null),{hasAiProvider:_e,hasGithub:xt,loading:dt}=Cv(s),{nodes:Qe}=yc(),vt=i.useCallback(be=>{xe(!0),je(be)},[]),Ae=i.useCallback(()=>{xe(!1)},[]),Je=i.useCallback(async()=>{if(ae.length>0){nt(!0);return}de(!0);try{const be=await Pr(void 0,s);qe(be),nt(!0)}catch(be){const at=Ee(be);o(at?`Failed to load agents: ${at}`:"Failed to load agents","error"),nt(!1)}finally{de(!1)}},[ae.length,s,o]);i.useEffect(()=>{if(!Pe)return;const be=at=>{Ie.current&&!Ie.current.contains(at.target)&&nt(!1)};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[Pe]),i.useEffect(()=>{if(!$e)return;const be=at=>{re.current&&!re.current.contains(at.target)&&(st(!1),me(""))};return document.addEventListener("mousedown",be),()=>document.removeEventListener("mousedown",be)},[$e]);const ct=a.filter(be=>!b.includes(be.id)).sort((be,at)=>{const ot=at.createdAt.localeCompare(be.createdAt);if(ot!==0)return ot;const gt=parseInt(be.id.slice(be.id.lastIndexOf("-")+1),10)||0;return(parseInt(at.id.slice(at.id.lastIndexOf("-")+1),10)||0)-gt}),Nt=Ue?ct.filter(be=>be.id.toLowerCase().includes(Ue.toLowerCase())||be.title&&be.title.toLowerCase().includes(Ue.toLowerCase())||be.description&&be.description.toLowerCase().includes(Ue.toLowerCase())):ct,yt=(be,at)=>be.length>at?be.slice(0,at)+"…":be,Se=fe.trim(),G=Se.length>0&&!vc.test(Se);i.useEffect(()=>{const be=x.trim()!==""||b.length>0||N.length>0||I!==""||U!==""||D!==""||Z!==""||ce.length>0||ve!==null||Ne!==void 0||ie!==Ds||oe!==void 0||S!==""||C!==""||L||Se!=="";J(be)},[x,b,N,I,U,D,Z,ce,ve,Ne,ie,oe,S,C,L,Se]);const ge=i.useCallback(async()=>{k&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(N.forEach(be=>URL.revokeObjectURL(be.previewUrl)),R([]),y(""),v([]),O(""),A(""),K(""),ne(""),M(""),$("default"),je([]),xe(!1),Fe(null),nt(!1),Y(void 0),ee(Ds),W(void 0),j(""),w(""),J(!1),pe(!1),B(""),n())},[k,n,N,d]),pt=i.useCallback(async()=>{const be=x.trim();if(!(!be||z||G)){E(!0);try{const at=I.indexOf("/"),ot=U.indexOf("/"),gt=D.indexOf("/"),St=await r({title:void 0,description:be,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:He?ce.length>0?ce:[]:void 0,...ve?{assignedAgentId:ve}:{},modelPresetId:P==="preset"&&F||void 0,modelProvider:I&&at!==-1?I.slice(0,at):void 0,modelId:I&&at!==-1?I.slice(at+1):void 0,validatorModelProvider:U&&ot!==-1?U.slice(0,ot):void 0,validatorModelId:U&&ot!==-1?U.slice(ot+1):void 0,planningModelProvider:D&>!==-1?D.slice(0,gt):void 0,planningModelId:D&>!==-1?D.slice(gt+1):void 0,thinkingLevel:Z!==""?Z:void 0,reviewLevel:Ne,priority:ie,nodeId:oe,branch:S.trim()===""?void 0:S.trim(),baseBranch:C.trim()===""?void 0:C.trim(),...L||Se!==""?{githubTracking:{enabled:L,...Se!==""?{repoOverride:Se}:{}}}:{}});if(N.length>0){const Lt=[];for(const Yt of N)try{await bc(St.id,Yt.file,s)}catch{Lt.push(Yt.file.name)}Lt.length>0&&o(`Failed to upload: ${Lt.join(", ")}`,"error")}N.forEach(Lt=>URL.revokeObjectURL(Lt.previewUrl)),R([]),y(""),v([]),O(""),A(""),K(""),ne(""),M(""),$("default"),je([]),xe(!1),Fe(null),nt(!1),Y(void 0),ee(Ds),W(void 0),j(""),w(""),o(`Created ${St.id}`,"success"),n()}catch(at){o(Ee(at)||"Failed to create task","error")}finally{E(!1)}}},[x,b,N,I,U,D,Z,z,r,o,n,s,P,F,ce,He,ve,Ne,ie,oe,S,C]),ke=i.useCallback(be=>{be.key==="Escape"&&(be.preventDefault(),ge())},[ge]),Rt=(ve?ae.find(be=>be.id===ve):void 0)?.name??ve,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:re,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>st(be=>!be),disabled:z,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),$e&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ue,onChange:be=>me(be.target.value),onClick:be=>be.stopPropagation()}),Nt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Nt.map(be=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(be.id)?" selected":""}`,onClick:()=>{v(b.includes(be.id)?b.filter(at=>at!==be.id):[...b,be.id]),st(!1),me("")},onMouseDown:at=>at.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:be.id}),t.jsx("span",{className:"dep-dropdown-title",children:yt(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:()=>v(b.filter(at=>at!==be)),disabled:z,children:"×"})]},be))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:Ie,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{Pe?nt(!1):Je()},disabled:z,"data-testid":"new-task-agent-button",children:[t.jsx(zn,{size:12,style:{verticalAlign:"middle"}}),Rt?` ${Rt}`:" Assign agent"]}),Pe&&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"}),Be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Be&&ae.map(be=>t.jsxs("div",{className:`dep-dropdown-item${ve===be.id?" selected":""}`,onMouseDown:at=>at.preventDefault(),onClick:()=>{Fe(be.id===ve?null:be.id),nt(!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)),!Be&&ae.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),ve&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:be=>be.preventDefault(),onClick:()=>{Fe(null),nt(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:ge,onKeyDown:ke,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:ge,disabled:z,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!dt&&t.jsx(Ev,{hasAiProvider:_e,hasGithub:xt}),t.jsx(ov,{mode:"create",description:x,onDescriptionChange:y,dependencies:b,onDependenciesChange:v,executorModel:I,onExecutorModelChange:O,validatorModel:U,onValidatorModelChange:A,presetMode:P,onPresetModeChange:$,selectedPresetId:F,onSelectedPresetIdChange:M,selectedWorkflowSteps:ce,onWorkflowStepsChange:vt,onDefaultOnApplied:Ae,pendingImages:N,onImagesChange:R,tasks:a,projectId:s,disabled:z,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:ge,planningModel:D,onPlanningModelChange:K,thinkingLevel:Z,onThinkingLevelChange:ne,reviewLevel:Ne,onReviewLevelChange:Y,priority:ie,onPriorityChange:ee,branch:S,onBranchChange:j,baseBranch:C,onBaseBranchChange:w,nodeId:oe,onNodeIdChange:W,nodeOptions:Qe,githubTrackingEnabled:L,onGithubTrackingEnabledChange:pe,githubRepoOverride:fe,onGithubRepoOverrideChange:B,renderBelowPrimary:Re,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ge,disabled:z,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:pt,disabled:!x.trim()||z||G,children:z?"Creating...":"Create Task"})]})]})}):null}function bi(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 Yf(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function ED(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function _D(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function MD(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function AD(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 _l(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function RD(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function ID({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,y]=i.useState(!1),[b,v]=i.useState(null),[S,j]=i.useState(null),[C,w]=i.useState(null),N=i.useCallback(async Y=>{l(!0);try{const ie=await d1(s);r(ie),d(null),w(Date.now()),Y?.preserveKillResult||v(null)}catch(ie){d(ie instanceof Error?ie.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;N();const Y=window.setInterval(()=>{N()},5e3);return()=>{window.clearInterval(Y)}},[e,N]),i.useEffect(()=>{if(!e)return;(async()=>{try{const ie=await Yi();m(ie.vitestAutoKillEnabled??!0),f(ie.vitestKillThresholdPct??90),j(null)}catch(ie){j(ie instanceof Error?ie.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const Y=ie=>{ie.key==="Escape"&&n()};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[e,n]);const R=i.useMemo(()=>{if(!a)return[];const Y=a.systemStats,ie=_l(ED(Y.heapUsed,Y.heapLimit)),ee=_l(_D(Y.rss,Y.systemTotalMem));return[{label:"RSS",value:bi(Y.rss),detail:Yf(Y.rss,Y.systemTotalMem),className:ee},{label:"Heap Used",value:bi(Y.heapUsed),detail:`of ${bi(Y.heapTotal)}`,className:ie},{label:"Heap Limit",value:bi(Y.heapLimit),detail:"V8 limit"},{label:"External",value:bi(Y.external)},{label:"Array Buffers",value:bi(Y.arrayBuffers)}]},[a]),z=i.useCallback(async Y=>{m(Y);try{await Dn({vitestAutoKillEnabled:Y}),j(null)}catch(ie){j(ie instanceof Error?ie.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async Y=>{const ie=Math.min(99,Math.max(50,Number.isFinite(Y)?Math.round(Y):90));f(ie);try{await Dn({vitestKillThresholdPct:ie}),j(null)}catch(ee){j(ee instanceof Error?ee.message:"Failed to save vitest settings")}},[]),I=i.useCallback(async()=>{if(!p){if(!x){y(!0);return}g(!0);try{const Y=await u1(s);v(Y),y(!1),await N({preserveKillResult:!0})}catch(Y){d(Y instanceof Error?Y.message:"Failed to kill vitest processes")}finally{g(!1)}}},[x,p,N,s]);if(!e)return null;const O=a?.systemStats,U=o&&!!a,A=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",D=a?.taskStats,K=O?O.systemTotalMem-O.systemFreeMem:0,Z=O?MD(K,O.systemTotalMem):"normal",ne=O?_l(Z):"",F=O&&Number.isFinite(O.systemTotalMem)&&O.systemTotalMem>0?Math.max(0,Math.min(100,K/O.systemTotalMem*100)):0,M=O?`System memory used: ${F.toFixed(1)}% (${bi(K)} of ${bi(O.systemTotalMem)})`:"System memory usage unavailable",P=a?.vitestProcessCount,$=AD(O?.cpuPercent??null,O?.cpuCount??0),k=_l($),J=O?.cpuPercent??null,ce=J===null?0:Math.max(0,Math.min(100,J)),je=J===null?"Sampling…":`${J.toFixed(1)}%`,He=J===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${J.toFixed(1)}%`,xe=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":"",Ne=RD(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:Y=>{Y.target===Y.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(vr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:A})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void N(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(bs,{size:16,className:U?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(un,{})})]})]}),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:R.map(Y=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:Y.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${Y.className}`.trim(),children:Y.value}),Y.detail?t.jsx("span",{className:"system-stats-modal__detail",children:Y.detail}):null]})]},Y.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:je}),t.jsx("span",{className:"system-stats-modal__detail",children:J===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--${$}`,role:"progressbar","aria-valuenow":Math.round(ce),"aria-valuemin":0,"aria-valuemax":100,"aria-label":He,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${$}`,style:{width:`${ce}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:O?.loadAvg.map(Y=>Y.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:O?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:O?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:O?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:O?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row 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 ${ne}`.trim(),children:O?bi(K):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:O?`${Yf(K,O.systemTotalMem)} of ${bi(O.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--${Z}`,role:"progressbar","aria-valuenow":Math.round(F),"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--${Z}`,style:{width:`${F}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:O?bi(O.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:D?.total??0})]}),Object.entries(D?.byColumn??{}).map(([Y,ie])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:Y}),t.jsx("dd",{children:ie})]},Y))]})]}),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:D?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:D?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:D?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:D?.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(Dk,{}),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:P??"—"})]})}),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 I(),disabled:p||P===0,children:[t.jsx(zk,{}),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:Y=>{z(Y.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:Y=>{const ie=Number.parseInt(Y.target.value,10);E(Number.isNaN(ie)?90:ie)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:Y=>{const ie=Number.parseInt(Y.target.value,10);E(Number.isNaN(ie)?90:ie)},onBlur:()=>{E(h)}})]})]}),b&&t.jsxs("p",{className:xe,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",Ne]}),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 TD=5e3;function PD(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),y=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await th({limit:a,projectId:n,type:s}):S=(await Gm({limit:a,type:s,projectId:n})).map(C=>({...C,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 th({limit:a,projectId:n,type:s,since:x.current}):S=(await Gm({limit:a,type:s,since:x.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(j=>[...j,...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]),v=i.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return i.useEffect(()=>{y()},[y]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{y()},TD),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,y]),{entries:l,loading:d,error:m,refresh:y,clear:v,hasMore:f,loadMore:b}}const zd={"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"},$D={"task:created":t.jsx(Mn,{size:14,className:"activity-icon created"}),"task:moved":t.jsx($o,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(bs,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(un,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Gn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Do,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(xo,{size:14,className:"activity-icon settings"})};function DD(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 LD({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,y=!c&&o.length>0,{entries:b,loading:v,error:S,refresh:j,hasMore:C}=PD({projectId:x,type:g,limit:100,autoRefresh:e,useCentralFeed:y}),w=b.map(I=>({id:I.id,timestamp:I.timestamp,type:I.type,taskId:I.taskId,taskTitle:I.taskTitle,details:I.details,metadata:I.metadata,projectId:I.projectId,projectName:I.projectName})),N=async()=>{try{await AS(),j(),p(!1)}catch{p(!1)}},R=I=>{a&&a(I)},z=I=>{h(I),l?.(I==="all"?void 0:I)};i.useEffect(()=>{if(!e)return;const I=O=>{O.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[e,n,f]);const E=d!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:I=>{I.target===I.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(Pa,{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(Es,{size:14}),t.jsxs("select",{value:m,onChange:I=>z(I.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(I=>t.jsx("option",{value:I.id,children:I.name},I.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Fl,{size:14}),t.jsxs("select",{value:d,onChange:I=>u(I.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(zd).map(([I,O])=>t.jsx("option",{value:I,children:O},I))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:v?t.jsx(jt,{size:14,className:"spin"}):t.jsx(bs,{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(_n,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(I=>I.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",zd[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(Ws,{size:16}),t.jsx("span",{children:S})]}),w.length===0&&!v&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Pa,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:w.map(I=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:$D[I.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:zd[I.type]}),t.jsx("span",{className:"activity-log-entry-time",children:DD(I.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[I.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>R(I.taskId),"data-testid":"activity-task-link",children:I.taskId}),I.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:I.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:I.details})]}),I.metadata&&Object.keys(I.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof I.metadata.from=="string"&&typeof I.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[I.metadata.from," → ",I.metadata.to]}),typeof I.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${I.metadata.merged?"success":"error"}`,children:I.metadata.merged?"Merged":"Not merged"})]})]})]},I.id))}),C&&!v&&t.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),v&&w.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(jt,{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:N,children:"Clear Log"})]})]})})]})}):null}const io=[{id:"status",label:"Status",icon:Zg},{id:"changes",label:"Changes",icon:Qd},{id:"commits",label:"Commits",icon:br},{id:"branches",label:"Branches",icon:Fs},{id:"worktrees",label:"Worktrees",icon:Iw},{id:"stashes",label:"Stashes",icon:To},{id:"remotes",label:"Remotes",icon:Yg}];function Qf({status:e}){switch(e){case"added":case"untracked":return t.jsx(uw,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Gg,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(lw,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(ua,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(hw,{size:14,className:"gm-file-icon"})}}function Xf({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 OD(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 Cr(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 FD({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=pi(),l=ri();Ni(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=Zi({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 te=document.activeElement;te instanceof HTMLElement&&te.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[x,y]=i.useState(!1),[b,v]=i.useState(null),S=i.useRef(null);Li(S,e,"fusion:git-modal-size");const j=Qi(f),C=OD(a),[w,N]=i.useState(null),[R,z]=i.useState([]),[E,I]=i.useState(new Set),[O,U]=i.useState(""),[A,D]=i.useState(!1),[K,Z]=i.useState(null),[ne,F]=i.useState(!1),[M,P]=i.useState(null),[$,k]=i.useState(null),J=i.useRef(0),[ce,je]=i.useState([]),[He,xe]=i.useState(null),[Ne,Y]=i.useState(null),[ie,ee]=i.useState(!1),[oe,W]=i.useState(20),[L,pe]=i.useState(""),[fe,B]=i.useState([]),[ve,Fe]=i.useState(""),[ae,qe]=i.useState(""),[Pe,nt]=i.useState(""),[Be,de]=i.useState(null),[Ie,$e]=i.useState([]),[st,Ue]=i.useState(!1),[me,re]=i.useState(null),[_e,xt]=i.useState(null),[dt,Qe]=i.useState(!1),[vt,Ae]=i.useState([]),[Je,ct]=i.useState([]),[Nt,yt]=i.useState(""),[Se,G]=i.useState(null),[ge,pt]=i.useState(null),[ke,tt]=i.useState(null),[Rt,Re]=i.useState(!1),[be,at]=i.useState(null),ot=i.useRef(0),[gt,St]=i.useState(null),[Lt,Yt]=i.useState(null),tn=i.useCallback(async()=>{if(e){y(!0),v(null);try{switch(p){case"status":{const te=await gi(r);N(te);break}case"changes":{const[te,De]=await Promise.all([gi(r),nr(r)]);N(te),z(De),I(new Set),k(null),Z(null),P(null);break}case"commits":{const te=await TN(oe,r);je(te);break}case"branches":{const[te,De]=await Promise.all([qr(r),gi(r)]);B(te),N(De);break}case"worktrees":{const te=await LN(r);Ae(te);break}case"stashes":{const te=await el(r);ct(te),pt(null),tt(null),at(null),ot.current+=1;break}case"remotes":{const te=await gi(r);N(te);break}}}catch(te){v(Ee(te)||"Failed to fetch git data"),a(Ee(te)||"Failed to fetch git data","error")}finally{y(!1)}}},[p,e,oe,a,r]);i.useEffect(()=>{e&&tn()},[tn,e]),i.useEffect(()=>{if(!e)return;const te=De=>{if(De.key==="Escape"){f();return}if((De.key==="ArrowUp"||De.key==="ArrowDown")&&De.altKey){De.preventDefault();const ft=io.findIndex(qt=>qt.id===p);De.key==="ArrowUp"&&ft>0?g(io[ft-1].id):De.key==="ArrowDown"&&ft<io.length-1&&g(io[ft+1].id)}};return document.addEventListener("keydown",te),()=>document.removeEventListener("keydown",te)},[e,f,p]);const mn=i.useCallback(async te=>{try{await Um(te,r),a(`Staged ${te.length} file(s)`,"success");const De=await nr(r);z(De),I(new Set),k(null),Z(null),P(null)}catch(De){a(Ee(De)||"Failed to stage files","error")}},[a,r]),Qt=i.useCallback(async te=>{try{await GN(te,r),a(`Unstaged ${te.length} file(s)`,"success");const De=await nr(r);z(De),I(new Set),k(null),Z(null),P(null)}catch(De){a(Ee(De)||"Failed to unstage files","error")}},[a,r]),yn=i.useCallback(async te=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${te.length} file(s)? This cannot be undone.`,danger:!0}))try{await JN(te,r),a(`Discarded changes to ${te.length} file(s)`,"success");const[ft,qt]=await Promise.all([nr(r),gi(r)]);z(ft),N(qt),I(new Set),k(null),Z(null),P(null)}catch(ft){a(Ee(ft)||"Failed to discard changes","error")}},[a,r,o]),Gt=i.useCallback(async te=>{if(te.preventDefault(),!!O.trim()){D(!0);try{const De=await Hm(O.trim(),r);a(`Committed: ${De.hash}`,"success"),U("");const[ft,qt]=await Promise.all([nr(r),gi(r)]);z(ft),N(qt),k(null),Z(null),P(null)}catch(De){a(Ee(De)||"Failed to commit","error")}finally{D(!1)}}},[O,a,r]),on=i.useCallback(async()=>{if(O.trim()){D(!0);try{const te=R.filter(zt=>!zt.staged).map(zt=>zt.file);te.length>0&&await Um(te,r);const De=await Hm(O.trim(),r);a(`Committed: ${De.hash}`,"success"),U("");const[ft,qt]=await Promise.all([nr(r),gi(r)]);z(ft),N(qt),k(null),Z(null),P(null)}catch(te){a(Ee(te)||"Failed to commit","error")}finally{D(!1)}}},[O,R,a,r]),sn=i.useCallback(async(te,De)=>{k({file:te,staged:De}),F(!0),P(null);const ft=J.current+1;J.current=ft;try{const qt=await KN(te,De,r);if(J.current!==ft)return;Z(qt)}catch(qt){if(J.current!==ft)return;const zt=Ee(qt)||"Failed to load file diff";Z(null),P(zt),a(zt,"error")}finally{J.current===ft&&F(!1)}},[a,r]),ln=i.useCallback(te=>{I(De=>{const ft=new Set(De);return ft.has(te)?ft.delete(te):ft.add(te),ft})},[]),Wt=i.useCallback(async te=>{if(He===te){xe(null),Y(null);return}xe(te),ee(!0);try{const De=await Hl(te,r);Y(De)}catch(De){a(Ee(De)||"Failed to load diff","error"),Y(null)}finally{ee(!1)}},[He,a,r]),ye=i.useCallback(()=>{W(te=>Math.min(te+20,100))},[]),Le=i.useMemo(()=>{if(!L.trim())return ce;const te=L.toLowerCase();return ce.filter(De=>De.message.toLowerCase().includes(te)||De.author.toLowerCase().includes(te)||De.shortHash.toLowerCase().includes(te))},[ce,L]),Ke=i.useCallback(async te=>{if(te.preventDefault(),!!ve.trim()){y(!0);try{await ON(ve.trim(),ae.trim()||void 0,r),a(`Created branch ${ve}`,"success"),Fe(""),qe("");const De=await qr(r);B(De)}catch(De){a(Ee(De)||"Failed to create branch","error")}finally{y(!1)}}},[ve,ae,a,r]),ut=i.useCallback(async te=>{y(!0);try{await FN(te,r),a(`Switched to ${te}`,"success");const[De,ft]=await Promise.all([gi(r),qr(r)]);N(De),B(ft)}catch(De){a(Ee(De)||"Failed to checkout branch","error")}finally{y(!1)}},[a,r]),Ve=i.useCallback(async te=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${te}"?`,danger:!0})){y(!0);try{await Bm(te,void 0,r),a(`Deleted branch ${te}`,"success");const ft=await qr(r);B(ft)}catch(ft){if(Ee(ft).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Bm(te,!0,r),a(`Force deleted branch ${te}`,"success");const zt=await qr(r);B(zt)}catch(zt){a(Ee(zt)||"Failed to delete branch","error")}}else a(Ee(ft)||"Failed to delete branch","error")}finally{y(!1)}}},[a,r,o]),Pt=i.useMemo(()=>{if(!Pe.trim())return fe;const te=Pe.toLowerCase();return fe.filter(De=>De.name.toLowerCase().includes(te))},[fe,Pe]),Ot=i.useCallback(async te=>{if(Be===te){de(null),$e([]),re(null),xt(null);return}de(te),$e([]),re(null),xt(null),Ue(!0);try{const De=await DN(te,10,r);$e(De)}catch{$e([])}finally{Ue(!1)}},[Be,r]),bt=i.useCallback(async te=>{if(me===te){re(null),xt(null);return}re(te),xt(null),Qe(!0);try{const De=await Hl(te,r);xt(De)}catch{xt(null)}finally{Qe(!1)}},[me,r]),Dt=i.useCallback(()=>{de(null),$e([]),re(null),xt(null)},[]),Ft=i.useCallback(()=>{ot.current+=1,pt(null),tt(null),at(null),Re(!1)},[]),Ht=i.useCallback(async te=>{te.preventDefault(),G("create"),Ft();try{await HN(Nt.trim()||void 0,r),a("Changes stashed","success"),yt("");const De=await el(r);ct(De)}catch(De){a(Ee(De)||"Failed to stash changes","error")}finally{G(null)}},[Nt,a,r,Ft]),rn=i.useCallback(async(te,De=!1)=>{G(`apply-${te}`),Ft();try{await qN(te,De,r),a(De?"Stash popped":"Stash applied","success");const ft=await el(r);ct(ft)}catch(ft){a(Ee(ft)||"Failed to apply stash","error")}finally{G(null)}},[a,r,Ft]),Xt=i.useCallback(async te=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${te}}? This cannot be undone.`,danger:!0})){G(`drop-${te}`),Ft();try{await VN(te,r),a("Stash dropped","success");const ft=await el(r);ct(ft)}catch(ft){a(Ee(ft)||"Failed to drop stash","error")}finally{G(null)}}},[a,r,o,Ft]),an=i.useCallback(async te=>{if(ge===te){Ft();return}const De=ot.current+1;ot.current=De,pt(te),tt(null),at(null),Re(!0);try{const ft=await WN(te,r);if(ot.current!==De)return;tt(ft)}catch(ft){if(ot.current!==De)return;tt(null),at(Ee(ft)||"Failed to load stash diff")}finally{ot.current===De&&Re(!1)}},[ge,r,Ft]),Me=i.useCallback(async()=>{St("fetch");try{const te=await zN(void 0,r);Yt(te),a(te.message||"Fetch completed",te.fetched?"success":"info");const De=await gi(r);N(De)}catch(te){a(Ee(te)||"Fetch failed","error")}finally{St(null)}},[a,r]),it=i.useCallback(async te=>{St("pull");try{const De=await BN(te,r);if(Yt(De),De.conflict)a("Merge conflict detected. Resolve manually.","error");else{const qt=te?.rebase?"Pull --rebase completed":"Pull completed";a(De.message||qt,"success")}const ft=await gi(r);N(ft)}catch(De){a(Ee(De)||"Pull failed","error")}finally{St(null)}},[a,r]),kt=i.useCallback(async()=>{St("push");try{const te=await UN(r);Yt(te),a(te.message||"Push completed","success");const De=await gi(r);N(De)}catch(te){a(Ee(te)||"Push failed","error")}finally{St(null)}},[a,r]),$t=i.useMemo(()=>R.filter(te=>te.staged),[R]),se=i.useMemo(()=>R.filter(te=>!te.staged),[R]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...j,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(Xd,{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:tn,disabled:x,title:"Refresh",children:t.jsx(bs,{size:14,className:x?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(un,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:io.map(te=>{const De=te.icon;return t.jsxs("button",{role:"tab","aria-selected":p===te.id,className:`gm-nav-item${p===te.id?" active":""}`,onClick:()=>g(te.id),children:[t.jsx(De,{size:16}),t.jsx("span",{className:"gm-nav-label",children:te.label})]},te.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[x&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!x&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Ws,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:tn,children:"Retry"})]}),p==="status"&&!x&&w&&t.jsx(zD,{status:w,copyToClipboard:C}),p==="changes"&&!x&&t.jsx(BD,{status:w,stagedFiles:$t,unstagedFiles:se,selectedFiles:E,toggleFileSelection:ln,onStageFiles:mn,onUnstageFiles:Qt,onDiscardChanges:yn,onSelectDiffFile:sn,selectedDiffTarget:$,changeDiff:K,loadingChangeDiff:ne,changeDiffError:M,commitMessage:O,setCommitMessage:U,onCommit:Gt,onStageAllAndCommit:on,committing:A}),p==="commits"&&!x&&t.jsx(UD,{commits:Le,commitSearch:L,setCommitSearch:pe,selectedCommit:He,commitDiff:Ne,loadingDiff:ie,onCommitClick:Wt,onLoadMore:ye,canLoadMore:ce.length>=oe&&oe<100,copyToClipboard:C}),p==="branches"&&!x&&t.jsx(HD,{branches:Pt,branchSearch:Pe,setBranchSearch:nt,newBranchName:ve,setNewBranchName:Fe,branchBase:ae,setBranchBase:qe,onCreateBranch:Ke,onCheckoutBranch:ut,onDeleteBranch:Ve,loading:x,allBranches:fe,selectedBranch:Be,branchCommits:Ie,loadingBranchCommits:st,expandedBranchCommit:me,branchCommitDiff:_e,loadingBranchCommitDiff:dt,onSelectBranch:Ot,onBranchCommitClick:bt,onCloseBranchDetails:Dt}),p==="worktrees"&&!x&&t.jsx(qD,{worktrees:vt}),p==="stashes"&&!x&&t.jsx(VD,{stashes:Je,stashMessage:Nt,setStashMessage:yt,onCreateStash:Ht,onApplyStash:rn,onDropStash:Xt,onToggleStashDiff:an,stashLoading:Se,expandedStashIndex:ge,stashDiff:ke,loadingStashDiff:Rt,stashDiffError:be}),p==="remotes"&&!x&&t.jsx(WD,{status:w,remoteLoading:gt,lastRemoteResult:Lt,onFetch:Me,onPull:it,onPush:kt,addToast:a,projectId:r,copyToClipboard:C})]})]})]})}):null}function zD({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(Fs,{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(da,{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(Ws,{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(Ta,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Po,{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 BD({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:y,committing:b}){const v=s.filter(j=>a.has(`unstaged:${j.file}`)),S=n.filter(j=>a.has(`staged:${j.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Fs,{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:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(v.map(j=>j.file)),title:"Stage selected",children:[t.jsx(Mn,{size:12})," Stage (",v.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(v.map(j=>j.file)),title:"Discard selected",children:t.jsx(Do,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-unstaged","data-testid":"gm-file-list-unstaged",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(j=>{const C=u?.file===j.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>d(j.file,!1),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),d(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(Qf,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(Xf,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),o([j.file])},title:"Stage file",children:t.jsx(Mn,{size:12})})]},`unstaged:${j.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-staged","data-testid":"gm-file-list-staged",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(j=>{const C=u?.file===j.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>d(j.file,!0),role:"button",tabIndex:0,onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),d(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:w=>w.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(Qf,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(Xf,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:w=>{w.stopPropagation(),l([j.file])},title:"Unstage file",children:t.jsx(un,{size:12})})]},`staged:${j.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(Qd,{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(jt,{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(Qd,{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:j=>g(j.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Ia,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:y,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function UD({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(Wi,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:m=>s(m.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):e.map((m,h)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),h<e.length-1&&t.jsx("div",{className:"gm-commit-line"})]}),t.jsxs("div",{className:"gm-commit-body",children:[t.jsxs("button",{className:"gm-commit-header",onClick:()=>l(m.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:m.shortHash}),t.jsx("span",{className:"gm-commit-message",title:m.message,children:m.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:m.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Cr(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(da,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{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 HD({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:y,loadingBranchCommitDiff:b,onSelectBranch:v,onBranchCommitClick:S,onCloseBranchDetails:j}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Wi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:C=>s(C.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:C=>r(C.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(C=>t.jsx("option",{value:C.name,children:C.name},C.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx(Mn,{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(C=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${C.isCurrent?" current":""}${f===C.name?" selected":""}`,onClick:()=>v(C.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[C.isCurrent&&t.jsx(js,{size:14,className:"gm-current-icon"}),C.name]}),C.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",C.remote]}),C.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Cr(C.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!C.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:w=>{w.stopPropagation(),d(C.name)},disabled:m,title:"Checkout",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:w=>{w.stopPropagation(),u(C.name)},disabled:m,title:"Delete",children:t.jsx(_n,{size:14})})]})})]}),f===C.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(br,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:t.jsx(un,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(jt,{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:Cr(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(jt,{size:16,className:"spin"}),"Loading diff..."]}):y?t.jsxs(t.Fragment,{children:[(w.body||w.message)&&t.jsx("div",{className:"gm-commit-message-full",children:w.body||w.message}),y.stat&&t.jsx("pre",{className:"gm-diff-stat",children:y.stat}),t.jsx("pre",{className:"gm-diff-patch",children:y.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},w.hash))})]})]},C.name))})]})}function qD({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:Hu(n.path)||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Fs,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function VD({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:c,expandedStashIndex:d,stashDiff:u,loadingStashDiff:m,stashDiffError:h}){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:f=>s(f.target.value),disabled:c!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:c!==null,children:[c==="create"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(To,{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(f=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-header",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${f.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:f.message}),t.jsxs("div",{className:"gm-stash-meta",children:[f.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Fs,{size:12}),f.branch]}),t.jsx("span",{children:Cr(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:c!==null,children:d===f.index?"Hide":"View"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:c!==null,title:"Apply stash (keep)",children:c===`apply-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:c!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:c!==null,title:"Drop stash",children:c===`drop-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):t.jsx(_n,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:m?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading stash diff…"]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):u?t.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&t.jsx("pre",{className:"gm-diff-stat",children:u.stat}),t.jsx("pre",{className:"gm-diff-patch",children:u.patch})]}):null})]},f.index))})]})}function WD({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=re=>{try{return new URL(re).hostname}catch{return re.replace(/^git@/,"").split(":")[0]||re}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,x]=i.useState(null),[y,b]=i.useState(""),[v,S]=i.useState(""),[j,C]=i.useState(null),[w,N]=i.useState(""),[R,z]=i.useState(""),[E,I]=i.useState(!1),[O,U]=i.useState(!1),A=i.useRef(null),[D,K]=i.useState([]),[Z,ne]=i.useState(!1),[F,M]=i.useState(null),[P,$]=i.useState([]),[k,J]=i.useState(!1),[ce,je]=i.useState(null),He=i.useRef(0),xe=m.find(re=>re.name===F);i.useEffect(()=>{(n!==null||f)&&U(!1)},[n,f]),i.useEffect(()=>{if(!O)return;const re=xt=>{A.current?.contains(xt.target)||U(!1)},_e=xt=>{xt.key==="Escape"&&U(!1)};return document.addEventListener("mousedown",re),document.addEventListener("keydown",_e),()=>{document.removeEventListener("mousedown",re),document.removeEventListener("keydown",_e)}},[O]);const[Ne,Y]=i.useState(null),[ie,ee]=i.useState(null),[oe,W]=i.useState(!1),[L,pe]=i.useState(null),[fe,B]=i.useState(null),[ve,Fe]=i.useState(!1);i.useEffect(()=>{ae()},[]),i.useEffect(()=>{e&&e.ahead>0?qe():e&&e.ahead===0&&K([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!F&&M(m[0].name)},[m]),i.useEffect(()=>{F?Pe(F):($([]),je(null))},[F]),i.useEffect(()=>{!F||!s||Pe(F)},[F,s]),i.useEffect(()=>{F&&!m.find(re=>re.name===F)&&M(m.length>0?m[0].name:null)},[m,F]);const ae=async()=>{p(!0);try{const re=await NN(c);h(re)}catch(re){l(Ee(re)||"Failed to load remotes","error")}finally{p(!1)}},qe=async()=>{ne(!0);try{const re=await PN(c);K(re)}catch{K([])}finally{ne(!1)}},Pe=async re=>{const _e=He.current+1;He.current=_e,J(!0),je(null);try{const xt=await $N(re,void 0,10,c);if(He.current!==_e)return;$(xt)}catch(xt){if(He.current!==_e)return;je(Ee(xt)||"Failed to load remote commits"),$([])}finally{He.current===_e&&J(!1)}},nt=pi(),Be=async re=>{if(re.preventDefault(),!(!y.trim()||!v.trim())){x("add");try{await SN(y.trim(),v.trim(),c),l(`Remote '${y}' added successfully`,"success"),b(""),S(""),I(!1),await ae()}catch(_e){l(Ee(_e)||"Failed to add remote","error")}finally{x(null)}}},de=async re=>{if(await nt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${re}'?`,danger:!0})){x(`remove-${re}`);try{await CN(re,c),l(`Remote '${re}' removed`,"success"),await ae()}catch(xt){l(Ee(xt)||"Failed to remove remote","error")}finally{x(null)}}},Ie=async re=>{if(R.trim()){x(`rename-${re}`);try{await EN(re,R.trim(),c),l(`Remote renamed to '${R.trim()}'`,"success"),C(null),z(""),await ae()}catch(_e){l(Ee(_e)||"Failed to rename remote","error")}finally{x(null)}}},$e=async re=>{if(w.trim()){x(`url-${re}`);try{await _N(re,w.trim(),c),l("Remote URL updated","success"),C(null),N(""),await ae()}catch(_e){l(Ee(_e)||"Failed to update remote URL","error")}finally{x(null)}}},st=i.useCallback(async(re,_e)=>{if(_e==="ahead"){if(Ne===re){Y(null),ee(null);return}Y(re),ee(null),W(!0);try{const xt=await Hl(re);ee(xt)}catch{ee(null)}finally{W(!1)}}else{if(L===re){pe(null),B(null);return}pe(re),B(null),Fe(!0);try{const xt=await Hl(re);B(xt)}catch{B(null)}finally{Fe(!1)}}},[Ne,L]),Ue=re=>{C(`url-${re.name}`),N(re.pushUrl||re.fetchUrl)},me=re=>{C(`name-${re.name}`),z(re.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:()=>I(!E),disabled:g!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(un,{size:14}):t.jsx(Mn,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Be,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:y,onChange:re=>b(re.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:v,onChange:re=>S(re.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!y.trim()||!v.trim()||g==="add",children:[g==="add"?t.jsx(jt,{size:12,className:"spin"}):t.jsx(Mn,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(re=>t.jsxs("div",{className:`gm-remote-selector-item${F===re.name?" selected":""}`,onClick:()=>M(re.name),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),M(re.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:re.name}),re.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:re.fetchUrl,children:u(re.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:_e=>{_e.stopPropagation(),de(re.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(_n,{size:14})})]},re.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[F&&xe?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(Ta,{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(Po,{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(jt,{size:14,className:"spin"}):t.jsx(bs,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:A,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{U(!1),r({rebase:!1})},disabled:n!==null||f,children:[n==="pull"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(si,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>U(re=>!re),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":O,children:t.jsx(pn,{size:14})}),O?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":"Pull options menu",children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!1})},children:"Pull"}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!0})},children:"Pull --rebase"})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Ta,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${F}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:w,onChange:re=>N(re.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>$e(F),disabled:g===`url-${F}`,children:g===`url-${F}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(js,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),N("")},title:"Cancel",children:t.jsx(un,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:xe.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:xe.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(xe.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(da,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ue(xe),disabled:g!==null,title:"Edit remote URL",children:t.jsx(qs,{size:14})})]})]})]}),xe.pushUrl&&xe.pushUrl!==xe.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:xe.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:xe.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(xe.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(da,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${F}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:R,onChange:re=>z(re.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ie(F),disabled:g===`rename-${F}`,children:g===`rename-${F}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(js,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),z("")},title:"Cancel",children:t.jsx(un,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>me(xe),disabled:g!==null,title:"Edit remote name",children:t.jsx(qs,{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(Ta,{size:14}),"Commits to Push (",e.ahead,")"]})}),Z?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading..."]}):D.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:D.map(re=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>st(re.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),st(re.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:re.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:re.message,children:re.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:re.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Cr(re.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Ne===re.hash?t.jsx(pn,{size:14}):t.jsx(On,{size:14})})]}),Ne===re.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:oe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):ie?t.jsxs(t.Fragment,{children:[(re.body||re.message)&&t.jsx("div",{className:"gm-commit-message-full",children:re.body||re.message}),ie.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ie.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ie.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},re.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(Zg,{size:14}),"Recent commits on ",F]})}),k?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading commits..."]}):ce?t.jsxs("div",{className:"gm-error",children:[t.jsx(Ws,{size:14}),ce]}):P.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:P.map(re=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>st(re.hash,"remote"),role:"button",tabIndex:0,onKeyDown:_e=>{(_e.key==="Enter"||_e.key===" ")&&(_e.preventDefault(),st(re.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:re.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:re.message,children:re.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:re.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Cr(re.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:L===re.hash?t.jsx(pn,{size:14}):t.jsx(On,{size:14})})]}),L===re.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ve?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):fe?t.jsxs(t.Fragment,{children:[(re.body||re.message)&&t.jsx("div",{className:"gm-commit-message-full",children:re.body||re.message}),fe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:fe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:fe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},re.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 or={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function KD(e,n){return e&&n?`${e}/${n}`:""}function GD(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 Zf(e){switch(e){case"file-text":return ua;case"check-circle":return Gn;case"shield":return Ok;case"zap":return as;case"eye":return Ir;case"globe":return dc;case"layout-grid":return ma;case"puzzle":return kk;default:return Gn}}function eg(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 JD({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"),[y,b]=i.useState(null),[v,S]=i.useState(!1),[j,C]=i.useState(!1),[w,N]=i.useState(or),[R,z]=i.useState(!1),[E,I]=i.useState(!1),[O,U]=i.useState(null),[A,D]=i.useState(null),[K,Z]=i.useState({}),[ne,F]=i.useState([]),M=i.useRef(null);Li(M,e,"fusion:workflow-steps-modal-size");const P=i.useCallback(async()=>{try{h(!0);const L=await Uo(a);o(L)}catch(L){s(Ee(L)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),$=i.useCallback(async()=>{try{const L=await Eo(a);Z(L||{})}catch{}},[a]),k=i.useCallback(async()=>{try{const L=await Ks();F(L.models||[])}catch{}},[]),J=i.useCallback(async()=>{try{p(!0);const[L,pe]=await Promise.all([PS(),$S()]);c(L.templates);const fe=Object.fromEntries(pe.templates.map(({pluginId:B,template:ve})=>[ve.id,B]));u(fe)}catch(L){s(Ee(L)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(P(),J(),$(),k())},[e,P,J,$,k]);const ce=i.useCallback(()=>{C(!0),S(!1),b(null),N(or)},[]),je=i.useCallback(()=>{C(!1),S(!0),b(null),N(or)},[]),He=i.useCallback(L=>{b(L.id),S(!1),N({name:L.name,description:L.description,mode:L.mode||"prompt",phase:L.phase||"pre-merge",prompt:L.prompt,scriptName:L.scriptName||"",enabled:L.enabled,defaultOn:L.defaultOn||!1,modelProvider:L.modelProvider||"",modelId:L.modelId||""})},[]),xe=i.useCallback(()=>{b(null),S(!1),C(!1),N(or)},[]),Ne=i.useCallback(async()=>{if(!w.name.trim()||!w.description.trim()){s("Name and description are required","error");return}z(!0);try{const L=w.mode==="prompt"&&w.modelProvider&&w.modelId?{modelProvider:w.modelProvider,modelId:w.modelId}:w.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const pe={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,...L};await Jm(pe,a),s("Workflow step created","success")}else y&&(await RS(y,{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,...L},a),s("Workflow step updated","success"));S(!1),b(null),N(or),await P()}catch(L){s(Ee(L)||"Failed to save workflow step","error")}finally{z(!1)}},[w,v,y,s,P]),Y=i.useCallback(async L=>{try{await IS(L,a),s("Workflow step deleted","success"),U(null),y===L&&(b(null),N(or)),await P()}catch(pe){s(Ee(pe)||"Failed to delete workflow step","error")}},[y,s,P]),ie=i.useCallback(async()=>{if(!(!y&&!v)&&w.mode==="prompt"){if(v){if(!w.name.trim()||!w.description.trim()){s("Name and description are required before refining","error");return}z(!0);try{const L=w.modelProvider&&w.modelId?{modelProvider:w.modelProvider,modelId:w.modelId}:{},pe={name:w.name.trim(),description:w.description.trim(),mode:"prompt",prompt:w.prompt.trim()||void 0,enabled:w.enabled,defaultOn:w.defaultOn||void 0,...L},fe=await Jm(pe,a);S(!1),b(fe.id),I(!0);const B=await Ym(fe.id,a);N(ve=>({...ve,prompt:B.prompt})),s("Prompt refined with AI","success"),await P()}catch(L){s(Ee(L)||"Failed to refine prompt","error")}finally{z(!1),I(!1)}return}if(y){I(!0);try{const L=await Ym(y,a);N(pe=>({...pe,prompt:L.prompt})),s("Prompt refined with AI","success"),await P()}catch(L){s(Ee(L)||"Failed to refine prompt","error")}finally{I(!1)}}}},[y,v,w,s,P]),ee=i.useCallback(async L=>{D(L.id);try{await DS(L.id,a),s(`Added ${L.name} workflow step`,"success"),await P(),x("my-steps"),C(!1)}catch(pe){const fe=Ee(pe);fe?.includes("already exists")?s(`A workflow step named '${L.name}' already exists`,"error"):s(fe||"Failed to add workflow step from template","error")}finally{D(null)}},[s,P]),oe=Qi(n);if(!e)return null;const W=v||y!==null;return t.jsx("div",{className:"modal-overlay open",...oe,"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:[!W&&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(Cy,{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(ma,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!W&&!j&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(L=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${L.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:L.name}),t.jsx("span",{className:`wfm-badge ${L.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:L.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(L.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(L.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(L.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(L.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),L.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:L.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>He(L),title:"Edit","aria-label":`Edit ${L.name}`,children:t.jsx(qs,{size:14})}),O===L.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>Y(L.id),title:"Confirm delete","aria-label":`Confirm delete ${L.name}`,children:t.jsx(js,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>U(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(un,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>U(L.id),title:"Delete","aria-label":`Delete ${L.name}`,children:t.jsx(_n,{size:14})})]})]})},L.id))})]}),g==="templates"&&!W&&!j&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(L=>{const pe=Zf(L.icon),fe=eg(L.category),B=A===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(pe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:fe,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ee(L),disabled:B,"data-testid":`add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Mn,{size:12}),"Add"]})})]})]})},L.id)})})}),j&&!W&&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:je,"data-testid":"create-custom-step",children:[t.jsx(Mn,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(jt,{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(L=>{const pe=Zf(L.icon),fe=eg(L.category),B=A===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(pe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:fe,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ee(L),disabled:B,"data-testid":`chooser-add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Mn,{size:12}),"Add template"]})})]})]})},L.id)})})]}),W&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:w.name,onChange:L=>N(pe=>({...pe,name:L.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:w.description,onChange:L=>N(pe=>({...pe,description:L.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${w.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Ki,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${w.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Gi,{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:()=>N(L=>({...L,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:()=>N(L=>({...L,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:ie,disabled:!w.description.trim()||E,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[E?t.jsx(jt,{size:12,className:"spin"}):t.jsx(gs,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:w.prompt,onChange:L=>N(pe=>({...pe,prompt:L.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:()=>N(L=>({...L,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(un,{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(Is,{models:ne,value:KD(w.modelProvider,w.modelId),onChange:L=>{const pe=GD(L);N(fe=>({...fe,modelProvider:pe.provider,modelId:pe.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(K).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:L=>N(pe=>({...pe,scriptName:L.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(K).map(([L,pe])=>t.jsxs("option",{value:L,children:[L," (",pe,")"]},L))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:w.enabled,onChange:L=>N(pe=>({...pe,enabled:L.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:w.defaultOn,onChange:L=>N(pe=>({...pe,defaultOn:L.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:xe,disabled:R,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Ne,disabled:R||!w.name.trim()||!w.description.trim()||w.mode==="script"&&!w.scriptName.trim(),"data-testid":"save-workflow-step",children:R?"Saving...":v?"Create":"Save"})]})]})]})]})}),!W&&!j&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:ce,"data-testid":"add-workflow-step",children:[t.jsx(Mn,{size:14}),"Add Workflow Step"]})})]})})}const YD=36e5,QD=3e5,Bd=[{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 XD(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 ZD(e){return typeof e!="number"||!Number.isFinite(e)?YD:Math.max(QD,Math.round(e))}function t8(e){if(Bd.some(s=>s.value===e))return[...Bd];const n={value:e,label:`${XD(e)} (custom)`};return[...Bd,n].sort((s,a)=>s.value-a.value)}const eL=4,tL=5*6e4;function nL(e){const n=ZD(e?.heartbeatIntervalMs);return Math.max(n*eL,tL)}function tg(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 sL(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 iL(e){const s=e.metadata?.heartbeatTimerRepair;if(!s||typeof s!="object")return{};const a=s;return{repairedAt:typeof a.repairedAt=="string"?a.repairedAt:void 0,staleAtRepair:typeof a.staleAtRepair=="boolean"?a.staleAtRepair:void 0,staleRepairReason:typeof a.staleRepairReason=="string"?a.staleRepairReason:void 0}}function aL(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=sL(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Ys,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(vi,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ys,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(vi,{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=iL(e);if(d.staleAtRepair&&d.repairedAt){const f=Date.parse(d.repairedAt),p=Date.parse(s);if(Number.isFinite(f)&&Number.isFinite(p)&&p<f)return{label:"Unresponsive",icon:t.jsx(Ys,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:d.staleRepairReason??"Heartbeat scheduler repaired a missing timer; waiting for recovery heartbeat"}}const u=new Date(s).getTime(),m=Date.now()-u,h=nL(o);if(m>h){const f=`No heartbeat for ${tg(m)} (threshold: ${tg(h)})`;return{label:"Unresponsive",icon:t.jsx(Ys,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:f}}return{label:"Healthy",icon:t.jsx(Pw,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function sc({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 rL="https://github.com/Runfusion/Fusion/issues/new";function oL(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(`
|
|
691
|
+
`)});return`${rL}?${r.toString()}`}function lL({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>oL(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(Ws,{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(js,{size:14}):t.jsx(da,{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(Kg,{size:14}),"Report on GitHub"]})]})]})}):null}function cL({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(Ws,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(lL,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const Ml=[{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 dL({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"),[y,b]=i.useState(()=>{if(typeof window>"u")return"list";const $=Bn("fn-agent-view",a);return $==="board"||$==="list"?$:"list"});i.useEffect(()=>{const $=Bn("fn-agent-view",a);if($==="board"||$==="list"){b($);return}b("list")},[a]),i.useEffect(()=>{us("fn-agent-view",y,a)},[a,y]);const[v,S]=i.useState(null),j=i.useRef(null),[C,w]=i.useState(new Set),[N,R]=i.useState(new Map),{confirm:z}=pi(),E=i.useMemo(()=>N.size===0?r:r.map($=>{const k=N.get($.id);return k?{...$,state:k}:$}),[r,N]),I=i.useMemo(()=>g!=="all"?E:[...E].sort(($,k)=>{const J=$.state==="paused"?1:0,ce=k.state==="paused"?1:0;return J!==ce?J-ce:(k.updatedAt??"").localeCompare($.updatedAt??"")}),[E,g]),O=i.useCallback(async()=>{c(!0);try{const k=await Pr(g!=="all"?{state:g}:void 0,a);o(k)}catch($){s(`Failed to load agents: ${Ee($)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&O()},[e,O]),i.useEffect(()=>{if(!e)return;const $=setInterval(()=>{O()},3e4);return()=>{clearInterval($)}},[e,O]);const U=async()=>{if(m.trim())try{await VS({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),O()}catch($){s(`Failed to create agent: ${Ee($)}`,"error")}},A=async($,k)=>{if(!C.has($)){w(J=>new Set(J).add($)),R(J=>{const ce=new Map(J);return ce.set($,k),ce});try{await KS($,k,a),s(`Agent state updated to ${k}`,"success"),await O(),R(J=>{const ce=new Map(J);return ce.delete($),ce})}catch(J){R(ce=>{const je=new Map(ce);return je.delete($),je}),s(`Failed to update state: ${Ee(J)}`,"error")}finally{w(J=>{const ce=new Set(J);return ce.delete($),ce})}}},D=async($,k)=>{if(await z({title:"Delete Agent",message:`Delete agent "${k}"? This cannot be undone.`,danger:!0}))try{await GS($,a),s(`Agent "${k}" deleted`,"success"),O()}catch(ce){s(`Failed to delete agent: ${Ee(ce)}`,"error")}},K=async($,k)=>{const J=r.find(ce=>ce.id===$);if(J){if(J.role===k){S(null);return}try{await WS($,{role:k},a),s(`Agent role updated to ${Ml.find(ce=>ce.value===k)?.label??k}`,"success"),S(null),O()}catch(ce){s(`Failed to update role: ${Ee(ce)}`,"error")}}},Z=($,k)=>{$.key==="Escape"&&S(null)},ne=$=>Ml.find(k=>k.value===$)?.label??$,F=$=>aL($),M=$=>$.color==="var(--state-active-text)"?"active":$.color==="var(--state-paused-text)"?"paused":$.color==="var(--state-error-text)"?"error":"muted",P=($,k)=>$.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:$=>$.target===$.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${y==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":y==="board",children:t.jsx(ma,{size:16})}),t.jsx("button",{className:`view-toggle-btn${y==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":y==="list",children:t.jsx(Zd,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void O(),title:"Refresh",disabled:l,children:t.jsx(bs,{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(Fl,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:$=>x($.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(Mn,{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:$=>h($.target.value),onKeyDown:$=>$.key==="Enter"&&U(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:$=>p($.target.value),children:Ml.map($=>t.jsxs("option",{value:$.value,children:[$.icon," ",$.label]},$.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void U(),children:"Create"})]}),t.jsx("div",{className:y==="board"?"agent-board":"agent-list",children:I.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"})]}):y==="board"?I.map($=>{const k=F($),J=P($,k),ce=M(k);return t.jsxs("div",{className:"agent-board-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(sc,{agent:$,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":$.state,children:$.state}),t.jsx("span",{className:"agent-board-health","data-health":ce,title:J.title,children:k.icon})]}),t.jsx("div",{className:"agent-board-name",title:$.name,children:$.name}),t.jsx("div",{className:"agent-board-id",children:$.id}),t.jsxs("div",{className:"agent-board-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Activate",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D($.id,$.name),title:"Delete",children:t.jsx(_n,{size:14})})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(vi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Ii,{size:14})})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Resume",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void D($.id,$.name),title:"Delete",children:t.jsx(_n,{size:14})})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(vi,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Ii,{size:14})})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Retry",children:t.jsx(is,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx(Ii,{size:14})})]})]})]},$.id)}):I.map($=>{const k=F($),J=P($,k),ce=M(k);return t.jsxs("div",{className:"agent-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[v===$.id?t.jsx("select",{ref:j,className:"select agent-role-select",value:$.role,onChange:je=>void K($.id,je.target.value),onKeyDown:je=>Z(je,$.id),onBlur:()=>S(null),autoFocus:!0,children:Ml.map(je=>t.jsxs("option",{value:je.value,children:[je.icon," ",je.label]},je.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S($.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:je=>{(je.key==="Enter"||je.key===" ")&&S($.id)},children:t.jsx(sc,{agent:$,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:$.name}),t.jsx("span",{className:"agent-id text-secondary",children:$.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":$.state,children:$.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":ce,title:J.title,children:[k.icon,J.label?` ${J.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:ne($.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[$.state==="error"&&$.lastError?t.jsx(cL,{errorText:$.lastError,issueContext:{surface:"AgentListModal list",agentId:$.id,agentName:$.name,agentState:$.state,taskId:$.taskId}}):null,$.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:$.taskId})]}),$.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date($.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Activate",children:[t.jsx(is,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D($.id,$.name),title:"Delete",children:[t.jsx(_n,{size:14})," Delete"]})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(vi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Ii,{size:14})," Stop"]})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Resume",children:[t.jsx(is,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void D($.id,$.name),title:"Delete",children:[t.jsx(_n,{size:14})," Delete"]})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(vi,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Ii,{size:14})," Stop"]})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Retry",children:[t.jsx(is,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx(Ii,{size:14})," Stop"]})]})]})]},$.id)})})]})]})}):null}function uL({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 eN();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 v=await rN(b);u.current&&d({kind:v.enabled?"enabled":"disabled",restartRequired:v.restartRequired}),n?.(v.enabled),await m()}catch(v){u.current&&d({kind:"error",message:v instanceof Error?v.message:String(v)})}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."]}),y=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(jt,{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(Fn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(mL,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:y})]}),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(ng,{status:a,authenticated:e}),c&&t.jsx(sg,{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(Fn,{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(ng,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:y}),c&&t.jsx(sg,{action:c})]})}function mL({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 ng({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(jt,{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 sg({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 hL({authenticated:e,compact:n=!1,onToggled:s}){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()=>{try{const g=await iN();return c.current&&r(g),g}catch{return null}},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async g=>{l(g?"enabling":"disabling");try{const x=await lN(g);s?.(x.enabled),await d()}finally{c.current&&l(null)}},[s,d]),m=a?.enabled??e,h=a?.binary.available??!1,f=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("testing"),d().finally(()=>{c.current&&l(null)})},disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"})," Testing…"]}):"Test"}),m?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||!h,children:o==="enabling"?"Enabling…":"Enable"})]}),p=a?a.binary.available?m?`Connected${a.binary.version?` — ${a.binary.version}`:""}`:"Detected. Click Enable to route calls through Cursor CLI.":a.binary.reason??"`cursor-agent` not found on PATH":"Probing local CLI…";return n?t.jsxs("div",{className:`cursor-cli-provider-card auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(Fn,{provider:"cursor-cli",size:"sm"}),t.jsx("strong",{children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:`auth-status-badge ${m?"authenticated":"not-authenticated"}`,children:m?"✓ Active":"✗ Not connected"})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:f})]}),t.jsx("small",{className:"settings-muted",children:p})]}):t.jsxs("div",{className:`cursor-cli-provider-card onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(Fn,{provider:"cursor-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:"onboarding-provider-card__description",children:"Route AI calls through your local Cursor agent runtime."}),t.jsx("small",{className:"settings-muted",children:p})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:f})]})}function pL({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 aN();return c.current&&r(x),x},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async x=>{l(x?"enabling":"disabling");try{const y=await cN(x);n?.(y.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(jt,{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(Fn,{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(Fn,{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 fL(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 Ud({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=fL(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(js,{size:12}):t.jsx(da,{size:12})})]})]},u))}):e})}function gL({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){const u=i.useRef(null),m=i.useRef(null),[h,f]=i.useState(!1),p=i.useCallback(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return!1;const y=window.matchMedia("(max-width: 768px)").matches,b=window.matchMedia("(pointer: coarse)").matches;return y||b},[]),g=i.useCallback(()=>typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",[]),x=i.useCallback(()=>{if(!p())return;const y=m.current??u.current;if(!y||typeof y.scrollIntoView!="function")return;const b=g();requestAnimationFrame(()=>{y.scrollIntoView({block:"center",behavior:b,inline:"nearest"}),window.setTimeout(()=>{y.scrollIntoView({block:"center",behavior:b,inline:"nearest"})},120)})},[g,p]);return i.useEffect(()=>{if(!h||!p())return;x();const y=window.visualViewport;if(!y)return;const b=()=>{document.activeElement===m.current&&x()};return y.addEventListener("resize",b),y.addEventListener("scroll",b),()=>{y.removeEventListener("resize",b),y.removeEventListener("scroll",b)}},[h,x,p]),t.jsxs("div",{ref:u,className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{ref:m,className:"form-input oauth-manual-code__input",value:e,onChange:y=>n(y.target.value),onFocus:()=>{f(!0),x()},onBlur:()=>f(!1),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 bL=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"]),xL=/^[a-z][a-z0-9-]*$/,ig=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function ag(){return{id:"",name:"",reasoning:!1}}function vL({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??""),[y,b]=i.useState(e?.models?.length?e.models:[ag()]),[v,S]=i.useState(null),j=y.length>1,C=i.useMemo(()=>v??r??null,[v,r]);function w(E,I){b(O=>O.map((U,A)=>A===E?{...U,...I}:U))}function N(E){b(I=>I.length<=1?I:I.filter((O,U)=>U!==E))}function R(){if(!l.trim())return"Provider ID is required.";if(!xL.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&bL.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const E=new URL(m.trim());if(E.protocol!=="http:"&&E.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return ig.includes(f)?y.length===0?"At least one model is required.":y.some(E=>!E.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function z(E){E.preventDefault();const I=R();S(I),!I&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:y.map(O=>({id:O.id.trim(),name:O.name?.trim()||void 0,reasoning:!!O.reasoning,contextWindow:O.contextWindow,maxTokens:O.maxTokens}))})}return t.jsxs("form",{onSubmit:z,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:E=>c(E.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:E=>u(E.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:E=>h(E.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:E=>p(E.target.value),disabled:a,children:ig.map(E=>t.jsx("option",{value:E,children:E},E))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:E=>x(E.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:y.map((E,I)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${I+1}`,placeholder:"Model ID",value:E.id,onChange:O=>w(I,{id:O.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${I+1}`,placeholder:"Display name",value:E.name??"",onChange:O=>w(I,{name:O.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!E.reasoning,onChange:O=>w(I,{reasoning:O.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${I+1}`,placeholder:"Context window",type:"number",value:E.contextWindow??"",onChange:O=>w(I,{contextWindow:O.target.value?Number(O.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${I+1}`,placeholder:"Max tokens",type:"number",value:E.maxTokens??"",onChange:O=>w(I,{maxTokens:O.target.value?Number(O.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>N(I),disabled:a||!j,"aria-label":`Remove model ${I+1}`,children:"×"})]},`${I}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(E=>[...E,ag()]),disabled:a,children:"+ Add model"})]}),C?t.jsx("div",{className:"form-error",children:C}):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 yL=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function wL(e){return!yL.has(e)}function rg(e){return e.filter(n=>wL(n.id))}const _v={host:"web",activeProfileId:null,profiles:[]},Mv=i.createContext({shellApi:null,state:_v,ready:!0,openConnectionManagerSignal:0});function kL({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(_v),[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(Mv.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function jL(){return i.useContext(Mv)}const NL={host:"web",activeProfileId:null,profiles:[]};function SL(e){if(!e)return NL;const n=Array.isArray(e.profiles)?e.profiles.filter(a=>!!(a&&a.id&&a.serverUrl)):[],s=e.activeProfileId&&n.some(a=>a.id===e.activeProfileId)?e.activeProfileId:null;return{...e,activeProfileId:s,profiles:n}}function ym(e){return new Error(`${e} is only available in native shell mode`)}async function CL(e,n){if(!e)throw ym("Saving connection profiles");return e.saveProfile(n)}async function EL(e,n){if(!e)throw ym("Deleting connection profiles");await e.deleteProfile(n)}async function _L(e,n){if(!e)throw ym("Switching connection profiles");return e.setActiveProfile(n)}function Av(){const e=jL(),n=i.useMemo(()=>SL(e.state),[e.state]),s=i.useCallback(o=>CL(e.shellApi,o),[e.shellApi]),a=i.useCallback(o=>EL(e.shellApi,o),[e.shellApi]),r=i.useCallback(o=>_L(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:a,setActiveProfile:r}}const Ba="fusion_model_onboarding_state",Er=[],_r=[],ic=!1,ac=!1,Mr={},ML=void 0,aa=["ai-setup","github","project-setup","first-task"],AL={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function ai(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Ba);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?RL(n):null}catch{return null}}function RL(e){const n=e.postOnboardingDismissedAt??ML;return{...e,completedSteps:e.completedSteps??Er,skippedSteps:e.skippedSteps??_r,dismissed:e.dismissed??ic,completed:e.completed??ac,stepData:e.stepData??Mr,...n?{postOnboardingDismissedAt:n}:{}}}function Al(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Er,skippedSteps:_r,dismissed:ic,completed:ac,stepData:Mr};try{localStorage.setItem(Ba,JSON.stringify(s))}catch{}return}try{const s=ai(),a=new Date().toISOString(),r=n.completed??ac;let o=n.dismissed??ic;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Er,c=n.skippedSteps??s?.skippedSteps??_r,d={...s?.stepData??Mr};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(Ba,JSON.stringify(u))}catch{}}}function IL(e){if(!(typeof window>"u"))try{const n=ai(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Er,skippedSteps:[e],dismissed:ic,completed:ac,stepData:Mr};localStorage.setItem(Ba,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(Ba,JSON.stringify(r))}catch{}}function og(){if(!(typeof window>"u"))try{const e=ai(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Er,skippedSteps:_r,dismissed:!1,completed:!0,stepData:Mr};localStorage.setItem(Ba,JSON.stringify(s))}catch{}}function Ar(){const e=ai();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function TL(){if(!(typeof window>"u"))try{const e=ai(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Er,skippedSteps:_r,dismissed:!1,completed:!1,stepData:Mr,postOnboardingDismissedAt:n};localStorage.setItem(Ba,JSON.stringify(s))}catch{}}function Rv(){const e=ai();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function PL(){const e=ai();return!e||Ar()?!1:e.currentStep!=="complete"}function $L(){const e=ai();if(!e||Ar()||e.currentStep==="complete")return null;const n=e.currentStep,s=AL[n]??OL(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function DL(){const e=ai();return e?e.skippedSteps:_r}function LL(e){const n=ai();return!n||!n.stepData?null:n.stepData[e]??null}function OL(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Iv="fusion_onboarding_events",lg="fusion_onboarding_session_id",FL=200,zL=50;function ci(e,n={}){if(!(typeof window>"u"))try{const s=UL(),a=VL(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:BL()},o=qL([...s,r]);HL(o)}catch{}}function BL(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(lg);if(e)return e;const n=cg();return sessionStorage.setItem(lg,n),n}catch{return cg()}}function cg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function UL(){try{const e=localStorage.getItem(Iv);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(WL):[]}catch{return[]}}function HL(e){try{localStorage.setItem(Iv,JSON.stringify(e))}catch{}}function qL(e){const n=[...e];for(;n.length>FL;)n.splice(0,zL);return n}function VL(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function WL(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 KL=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}))??[]}),GL={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"}}},Tv={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:"..."}},JL={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},dg={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 Eu(e){if(dg[e])return dg[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 Hd=["anthropic","openai","google","gemini","ollama"],YL=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],QL={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"},XL={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function _u(e){return QL[e]??e}function ug(e){const n=_u(e),s=YL.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function mg(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=ug(e.id),a=ug(n.id);if(s!==a)return s-a;const r=_u(e.id),o=_u(n.id);if(r!==o)return r.localeCompare(o);const l=XL[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 ZL(e,n){const s=n.trim();if(!s)return"API key is required";const a=Tv[e]??JL;return a.pattern.test(s)?null:`${Eu(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const Pv={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"},eO={description:"AI provider — connect to start using AI models",apiKeyInfo:Pv};function Mu(e){return GL[e]??eO}function tO(e){return Mu(e.id).apiKeyInfo??Pv}function nO({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 sO({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=Tv[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(di,{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(di,{summary:"Advanced setup details",children:g})]})}const iO=150;function aO({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const d=ai(),u=d?.currentStep,m=u==="complete"?"ai-setup":aa.includes(u)?u:"ai-setup",h=d?.completedSteps??[],f=d?.skippedSteps??DL(),[p,g]=i.useState(!0),[x,y]=i.useState(m),[b,v]=i.useState(h),[S,j]=i.useState(f),[C,w]=i.useState(!1),[N,R]=i.useState(""),[z,E]=i.useState(!1),[I,O]=i.useState(null),[U,A]=i.useState(null),[D,K]=i.useState([]),[Z,ne]=i.useState(void 0),[F,M]=i.useState(!0),[P,$]=i.useState(null),[k,J]=i.useState({}),[ce,je]=i.useState({}),[He,xe]=i.useState({}),[Ne,Y]=i.useState(null),[ie,ee]=i.useState([]),[oe,W]=i.useState(""),[L,pe]=i.useState(!1),[fe,B]=i.useState({}),[ve,Fe]=i.useState({}),[ae,qe]=i.useState({}),[Pe,nt]=i.useState([]),[Be,de]=i.useState(!1),[Ie,$e]=i.useState(!1),[st,Ue]=i.useState(),[me,re]=i.useState("Remote Server"),[_e,xt]=i.useState(""),[dt,Qe]=i.useState(""),[vt,Ae]=i.useState(!1),[Je,ct]=i.useState(null),Nt=i.useRef({}),yt=i.useRef(null),Se=i.useRef(null),G=i.useRef(null),[ge,pt]=i.useState({}),[ke,tt]=i.useState(()=>ai()?.stepData?.github?.skipped===!0),Rt=i.useRef(0),Re=i.useRef(l),{shellApi:be,state:at}=Av(),ot=i.useRef(!1),gt=d?.currentStep,St=!!d&&d.currentStep!=="complete";Li(Se,p,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const _=yt.current;_&&(_.scrollTop=0)},[x]);const[Lt,Yt]=i.useState(()=>ai()?.stepData?.["ai-setup"]?.skippedProviders??{}),tn=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],mn=tn.findIndex(_=>_.key===x),Qt=x==="complete"?tn.length:mn;i.useEffect(()=>{x!=="complete"&&Al(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),i.useEffect(()=>{ot.current||(ot.current=!0,ci("onboarding:wizard-opened",{source:St?"resume":"initial",resumedFromStep:gt}))},[St,gt]),i.useEffect(()=>{const _=Re.current!=null,ue=l!=null;!_&&ue&&w(!0),ue||w(!1),Re.current=l},[l]);const yn=i.useRef(m);i.useEffect(()=>{if(yn.current==="ai-setup"&&x!=="ai-setup"&&!D.some(ue=>ue.id!=="github"&&ue.authenticated)){const ue={};for(const Ce of D)Ce.id!=="github"&&!Ce.authenticated&&!Lt[Ce.id]&&(ue[Ce.id]=!0);if(Object.keys(ue).length>0){const Ce={...Lt,...ue};Yt(Ce),Al(x,{stepData:{"ai-setup":{skippedProviders:Ce}}})}}yn.current=x},[x,D,Lt]);const Gt=i.useCallback(async()=>{try{const{providers:_,ghCli:ue}=await Co(),Ce=rg(_);K(Ce),ne(ue),J(We=>{const At={};for(const[q,we]of Object.entries(We)){const Oe=Ce.find(It=>It.id===q);Oe&&!Oe.authenticated&&Oe.loginInProgress&&(At[q]=we)}return Object.keys(At).length===Object.keys(We).length?We:At}),pt(We=>{let At=!1;const q={...We};for(const[we,Oe]of Object.entries(We)){if(Oe!=="pending")continue;Ce.find(Kt=>Kt.id===we)?.loginInProgress||(delete q[we],At=!0)}return At?q:We}),Yt(We=>{const At={...We};for(const q of Ce)q.authenticated&&At[q.id]&&delete At[q.id];return Object.keys(At).length===Object.keys(We).length?We:At})}catch{}},[]),on=i.useCallback(async()=>{try{const _=await dN();nt((_.providers??[]).map(KL))}catch{}},[]),sn=i.useCallback(async _=>{$e(!0),Ue(void 0);try{await mN(_),await on(),await Ks().then(ue=>ee(ue.models??[])),de(!1)}catch(ue){Ue(Ee(ue)||"Failed to create custom provider")}finally{$e(!1)}},[on]),ln=i.useRef(!1);i.useEffect(()=>{x==="ai-setup"&&on(),ln.current&&Gt(),ln.current=x!=="ai-setup"},[x,Gt,on]),i.useEffect(()=>{if(!D.some(Ce=>Ce.loginInProgress))return;const ue=setInterval(()=>{Gt()},2e3);return()=>clearInterval(ue)},[D,Gt]);const Wt=D.find(_=>_.id==="github"),ye=!!Wt,Le=Wt?.authenticated??!1,Ke=Wt?.loginInProgress??!1,ut=Z?.authenticated??!1,Ve=Le||ut,Pt=!Le&&ut,Ot=i.useCallback(_=>{if(_.authenticated)return"connected";const ue=ge?.[_.id];return ue==="timeout"||ue==="failed"?"retry":Lt[_.id]?"skipped":"not-connected"},[ge,Lt]);function bt({status:_}){const ue={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:Ce,className:We}=ue[_];return t.jsx("span",{"data-testid":"provider-status-badge",className:We,"data-status":_,children:Ce})}const Dt=i.useCallback(()=>{if(Ve)return"connected";const _=ge.github;return _==="pending"?"pending":_==="failed"||_==="timeout"?"failed":ke?"skipped":"not-connected"},[Ve,ge,ke]);function Ft({status:_}){const ue={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:Ce,className:We}=ue[_];return t.jsx("span",{"data-testid":"github-status-badge",className:We,"data-status":_,children:Ce})}const Ht=i.useCallback(async()=>{try{const _=await Ks();ee(_.models)}catch{}},[]),rn=i.useCallback(async()=>{try{const _=await Yi();if(_.defaultProvider&&_.defaultModelId){const ue=`${_.defaultProvider}/${_.defaultModelId}`;W(ue)}}catch{}},[]);i.useEffect(()=>{Promise.all([Gt(),Ht(),rn()]).finally(()=>M(!1))},[Gt,Ht,rn]),i.useEffect(()=>{const _=LL("ai-setup");if(_?.loginOutcomes){const ue=_.loginOutcomes,Ce={};for(const[We,At]of Object.entries(ue))At!=="pending"&&(Ce[We]=At);Object.keys(Ce).length>0&&pt(Ce)}},[]);const Xt=i.useCallback((_,ue)=>{Al(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[_]:ue}}}})},[x,b]);i.useEffect(()=>{const _=Object.entries(ge).filter(([ue,Ce])=>Ce!=="pending");for(const[ue,Ce]of _)Xt(ue,Ce)},[ge,Xt]),i.useEffect(()=>()=>{G.current&&clearInterval(G.current),Object.values(Nt.current).forEach(clearTimeout),Nt.current={}},[]);const an=i.useCallback(_=>{tt(_),Al(x,{completedSteps:b,stepData:{github:{skipped:_}}})},[x,b]),Me=i.useCallback(_=>_==="complete"?-1:aa.indexOf(_),[]),it=i.useCallback(()=>{v(ue=>[...new Set([...ue,x])]),j(ue=>ue.filter(Ce=>Ce!==x)),ci("onboarding:step-completed",{step:x}),x==="github"&&!Le&&an(!1);const _=Me(x);_>=0&&_<aa.length-1&&y(aa[_+1])},[x,Le,an,Me]),kt=i.useCallback(()=>{j(ue=>[...new Set([...ue,x])]),IL(x),ci("onboarding:step-skipped",{step:x}),x==="github"&&!Le&&an(!0);const _=Me(x);_>=0&&_<aa.length-1&&y(aa[_+1])},[x,Le,an,Me]),$t=i.useCallback(()=>{const _=x;v(Ce=>Ce.filter(We=>We!==_)),j(Ce=>Ce.filter(We=>We!==_)),_==="github"&&!Le&&an(!1);const ue=Me(x);ue>0&&y(aa[ue-1])},[x,Le,an,Me]),se=i.useCallback(()=>{kt()},[kt]),te=i.useCallback(async _=>{pt(Ce=>{const We=Ce[_];if(We&&We!=="pending"){const{[_]:At,...q}=Ce;return q}return Ce});const ue=()=>{J(Ce=>{if(!(_ in Ce))return Ce;const We={...Ce};return delete We[_],We}),je(Ce=>{if(!(_ in Ce))return Ce;const We={...Ce};return delete We[_],We}),xe(Ce=>{if(!(_ in Ce))return Ce;const We={...Ce};return delete We[_],We})};ue(),pt(Ce=>({...Ce,[_]:"pending"})),$(_),Rt.current=0;try{const{url:Ce,instructions:We,manualCode:At}=await hN(_);We?.trim()&&J(q=>({...q,[_]:We})),At&&je(q=>({...q,[_]:At})),window.open(Di(Ce),"_blank"),G.current=setInterval(async()=>{if(Rt.current++,Rt.current>=iO){G.current&&(clearInterval(G.current),G.current=null),$(null),K(q=>q.map(we=>we.id===_?{...we,loginInProgress:!1}:we)),pt(q=>({...q,[_]:"timeout"})),ue(),n("Login timed out. Please try again.","warning");return}try{const{providers:q,ghCli:we}=await Co(),Oe=rg(q);K(Oe),ne(we);const It=Oe.find(Kt=>Kt.id===_);if(It?.authenticated){G.current&&(clearInterval(G.current),G.current=null),$(null),pt(Kt=>({...Kt,[_]:"success"})),ue(),_==="github"&&an(!1),n("Login successful","success");return}It?.loginInProgress||(G.current&&(clearInterval(G.current),G.current=null),$(null),pt(Kt=>({...Kt,[_]:"failed"})),ue(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(Ce){Ce instanceof Error&&Ce.message.includes("already in progress")||Ce&&typeof Ce=="object"&&"status"in Ce&&Ce.status===409?(n("Login already in progress. Cancel it to retry.","warning"),pt(At=>({...At,[_]:"pending"})),Gt()):(n(Ce instanceof Error?Ce.message:"Login failed","error"),pt(At=>({...At,[_]:"failed"}))),$(null),ue()}},[n,Gt,an]),De=i.useCallback(async _=>{const ue=He[_]?.trim();if(!ue){n("Paste the full redirect URL or authorization code first.","warning");return}Y(_);try{(await pN(_,ue)).submitted?(xe(We=>{if(!(_ in We))return We;const At={...We};return delete At[_],At}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(Ce){n(Ee(Ce)||"Failed to submit authorization code","error")}finally{Y(null)}},[n,He]),ft=i.useCallback(async _=>{G.current&&(clearInterval(G.current),G.current=null),$(_),Rt.current=0,K(ue=>ue.map(Ce=>Ce.id===_?{...Ce,loginInProgress:!1}:Ce)),pt(ue=>({...ue,[_]:"cancelled"}));try{await gN(_),await Gt().catch(()=>{}),n("Login cancelled","success")}catch(ue){n(Ee(ue)||"Failed to cancel login","error")}finally{$(null),J(ue=>{if(!(_ in ue))return ue;const Ce={...ue};return delete Ce[_],Ce}),je(ue=>{if(!(_ in ue))return ue;const Ce={...ue};return delete Ce[_],Ce}),xe(ue=>{if(!(_ in ue))return ue;const Ce={...ue};return delete Ce[_],Ce}),Y(ue=>ue===_?null:ue)}},[n,Gt]),qt=i.useCallback((_,ue)=>{B(We=>({...We,[_]:ue}));const Ce=Nt.current[_];Ce&&(clearTimeout(Ce),delete Nt.current[_]),Fe(We=>{if(!We[_])return We;const At={...We};return delete At[_],At}),qe(We=>{if(!We[_])return We;const At={...We};return delete At[_],At})},[]),zt=i.useCallback(()=>{const _=yt.current;if(!_)return;const ue=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof _.scrollTo=="function"){_.scrollTo({top:0,behavior:ue?"auto":"smooth"});return}}catch{}_.scrollTop=0},[]),Pn=i.useCallback(async(_,ue)=>{const Ce=(ue??fe[_]??"").trim(),We=ZL(_,Ce);if(We){Fe(q=>({...q,[_]:We}));return}const At=Nt.current[_];At&&(clearTimeout(At),delete Nt.current[_]),$(_),Fe(q=>{const we={...q};return delete we[_],we}),qe(q=>{if(!q[_])return q;const we={...q};return delete we[_],we});try{await bN(_,Ce),await Gt(),zt(),B(q=>{const we={...q};return delete we[_],we}),Fe(q=>{if(!q[_])return q;const we={...q};return delete we[_],we}),qe(q=>({...q,[_]:"✓ Key saved"})),Nt.current[_]=setTimeout(()=>{qe(q=>{if(!q[_])return q;const we={...q};return delete we[_],we}),delete Nt.current[_]},3e3),n("API key saved","success")}catch(q){const we=q instanceof TypeError&&q.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":q instanceof Error?q.message:"Failed to save API key";Fe(Oe=>({...Oe,[_]:we})),qe(Oe=>{if(!Oe[_])return Oe;const It={...Oe};return delete It[_],It}),n(we,"error")}finally{$(null)}},[fe,n,Gt,zt]),he=i.useCallback(async _=>{$(_);try{await xN(_),await Gt(),n("API key removed","success")}catch(ue){n(ue instanceof Error?ue.message:"Failed to clear API key","error")}finally{$(null)}},[n,Gt]),mt=i.useCallback(async _=>{$(_);try{await fN(_),await Gt(),n("Logged out","success")}catch(ue){n(ue instanceof Error?ue.message:"Logout failed","error")}finally{$(null)}},[n,Gt]),ht=i.useCallback(_=>{W(_)},[]),wt=i.useCallback(async()=>{try{const _={modelOnboardingComplete:!0};if(oe){const ue=oe.indexOf("/"),Ce=ue!==-1?oe.slice(0,ue):void 0,We=ue!==-1?oe.slice(ue+1):oe,At=ie.find(q=>q.id===We);At?(_.defaultProvider=At.provider,_.defaultModelId=At.id):Ce&&We&&(_.defaultProvider=Ce,_.defaultModelId=We)}await Dn(_),og()}catch{}},[oe,ie,Dn,og]),Xe=i.useCallback(async()=>{const _=[...new Set([...b,"first-task"])];pe(!0);try{await wt(),ci("onboarding:completed",{completedSteps:_,skippedSteps:S}),v(_),j(ue=>ue.filter(Ce=>Ce!=="first-task")),y("complete")}finally{pe(!1)}},[wt,b,S]),Et=i.useCallback(async()=>{if(!s)return;const _=N.trim();if(!_){O("Please enter a task description.");return}O(null),E(!0);let ue=!1;try{const Ce=await ib({description:_,source:{sourceType:"dashboard_ui"}},s);A(Ce),w(!0),ci("onboarding:first-task-created",{taskId:Ce?.id}),n("Task created","success"),ue=!0}catch(Ce){const We=Ce instanceof Error?Ce.message:"Something went wrong creating your task. Please try again.";O(We),n(We,"error")}finally{E(!1)}ue&&wt()},[s,N,n,wt]),Zt=i.useCallback(async()=>{pe(!0);try{await wt()}finally{pe(!1)}ci("onboarding:open-new-task",{}),r?.()},[wt,r]),le=i.useCallback(async()=>{if(Ve){pe(!0);try{await wt()}finally{pe(!1)}g(!1),e(),ci("onboarding:open-github-import",{}),o?.()}},[wt,Ve,e,o]),lt=i.useCallback(async()=>{ci("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),pe(!0);try{await Dn({modelOnboardingComplete:!0})}catch{}g(!1),e()},[x,b,S,e]),nn=i.useCallback(()=>{ci("onboarding:finished",{}),g(!1),e()},[e]),Rn=i.useCallback(()=>{const _=l??U;_&&(wt(),c?.(_),e())},[l,U,wt,c,e]),Hn=i.useCallback(()=>{wt(),e()},[wt,e]),wn=Dt(),rs=D.filter(_=>_.id!=="github"),_s=at.host!=="web"&&!at.activeProfileId,bn=[...rs].sort(mg),Ut=bn.some(_=>!_.type||_.type==="oauth"),xs=bn.some(_=>_.type==="api_key"),xn=rs.filter(_=>_.authenticated),Xn=xn.length>0,$n=!!s,vs=x==="github"&&!Xn,ms=i.useCallback(async()=>{if(be){ct(null),Ae(!0);try{const _=await be.saveProfile({name:me,serverUrl:_e,authToken:dt.trim()?dt:null});try{await be.setActiveProfile(_.id)}catch(ue){ct(Ee(ue)||"Saved profile but failed to activate it");return}xt(""),Qe(""),n("Remote server profile saved","success")}catch(_){ct(Ee(_)||"Failed to save shell connection")}finally{Ae(!1)}}},[be,me,_e,dt,n]);if(!p)return null;const hs=(()=>{if(!oe)return"";const _=oe.indexOf("/"),ue=_===-1?void 0:oe.slice(0,_),Ce=_===-1?oe:oe.slice(_+1),We=ie.find(At=>At.id===Ce&&(!ue||At.provider===ue));return We?.name?We.name:ue?`${Eu(ue)} ${Ce}`:oe})(),Jn=[];if($n?Jn.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Jn.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Xn){const _=Eu(xn[0]?.id??"");Jn.push({label:"AI Provider",status:"connected",detail:`${_} connected — AI agents can work on tasks`})}else rs.length>0&&rs.some(_=>Lt[_.id])?Jn.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Jn.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Ve?Jn.push({label:"GitHub",status:"connected",detail:Pt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!ye||ke?Jn.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Jn.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),hs&&Jn.push({label:"Default Model",status:"connected",detail:hs});const ps=l??U,Ns=ps?.description?.split(`
|
|
692
|
+
`)[0]?.trim()||ps?.title||"",Yn=new Set(Hd),ys=bn.filter(_=>Yn.has(_.id)).sort((_,ue)=>{const Ce=Hd.indexOf(_.id),We=Hd.indexOf(ue.id);return Ce!==We?Ce-We:mg(_,ue)}),ws=bn.filter(_=>_.authenticated&&!Yn.has(_.id)),Ms=bn.filter(_=>!_.authenticated&&!Yn.has(_.id)),X=_=>{const ue=ge[_.id]==="timeout"||ge[_.id]==="failed"||ge[_.id]==="cancelled",Ce=_.loginInProgress&&!ue;if(_.id==="llama-cpp"&&_.type==="cli")return t.jsx(pL,{authenticated:_.authenticated,onToggled:()=>{Gt()}},_.id);if(_.id==="claude-cli"&&_.type==="cli")return t.jsx(uL,{authenticated:_.authenticated,onToggled:()=>{Gt()}},_.id);if(_.id==="cursor-cli"&&_.type==="cli")return t.jsx(hL,{authenticated:_.authenticated,onToggled:()=>{Gt()}},_.id);if(_.type==="api_key"){const We=Mu(_.id),At=tO(_);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${_.id}`,className:`onboarding-provider-card${_.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${_.id}`,"aria-hidden":"true",children:t.jsx(Fn,{provider:_.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Qg,{size:14,className:"onboarding-provider-key-icon"}),_.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:We.description}),t.jsx(bt,{status:Ot(_)}),_.authenticated&&_.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",_.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(sO,{provider:_,apiKeyInfo:At,inputValue:fe[_.id]??"",isSaving:P===_.id,error:ve[_.id],success:ae[_.id],isConnected:_.authenticated,onInputChange:qt,onSave:Pn,onClear:he})})]},_.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${_.id}`,className:`onboarding-provider-card${_.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${_.id}`,"aria-hidden":"true",children:t.jsx(Fn,{provider:_.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:_.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Mu(_.id).description}),t.jsx(bt,{status:Ot(_)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:P===_.id?_.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 ft(_.id),children:"Cancel"})]}):Ce?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 ft(_.id),children:"Cancel"})]}):_.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>mt(_.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>te(_.id),children:"Login"})}),(P===_.id||Ce)&&k[_.id]&&t.jsx(Ud,{instructions:k[_.id],"data-testid":`onboarding-login-instructions-${_.id}`}),(P===_.id||Ce)&&ce[_.id]&&t.jsx(gL,{value:He[_.id]??"",onChange:We=>xe(At=>({...At,[_.id]:We})),onSubmit:()=>void De(_.id),prompt:ce[_.id].prompt,placeholder:ce[_.id].placeholder,helpText:ce[_.id].helpText,disabled:Ne===_.id,submitLabel:Ne===_.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${_.id}`}),ge[_.id]==="timeout"&&P!==_.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),ge[_.id]==="failed"&&P!==_.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},_.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:Se,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(as,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(si,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Am,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Am,{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:lt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(un,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:tn.map((_,ue)=>{const Ce=Qt>ue,We=b.includes(_.key)&&Ce,At=S.includes(_.key)&&!b.includes(_.key)&&Ce,q=We||At;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[ue>0&&t.jsx("div",{className:`model-onboarding-step-connector ${ue<=Qt?"done":""}`}),q?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===_.key?"active":""} ${We?"done":""} ${At?"skipped":""}`,onClick:()=>y(_.key),"aria-label":`Go back to ${_.label}`,title:`Review ${_.label}`,children:[t.jsx("span",{className:"step-number",children:We?t.jsx(Gn,{size:14}):At?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ue+1}),t.jsx("span",{className:"step-label",children:_.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===_.key?"active":""} ${We?"done":""} ${At?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:We?t.jsx(Gn,{size:14}):At?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ue+1}),t.jsx("span",{className:"step-label",children:_.label})]})]},_.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:yt,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."}),_s&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connect remote Fusion server"}),t.jsx("p",{className:"onboarding-helper-text",children:"Your native shell needs an active remote profile before dashboard handoff can complete."}),t.jsx("label",{htmlFor:"onboarding-shell-profile-name",className:"onboarding-apikey-field-label",children:"Profile name"}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:me,onChange:_=>re(_.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-server-url",className:"onboarding-apikey-field-label",children:"Server URL"}),t.jsx("input",{id:"onboarding-shell-server-url",className:"input",placeholder:"https://your-fusion-host",value:_e,onChange:_=>xt(_.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-token",className:"onboarding-apikey-field-label",children:"Auth token (optional)"}),t.jsx("input",{id:"onboarding-shell-token",className:"input",type:"password",value:dt,onChange:_=>Qe(_.target.value)}),Je&&t.jsx("small",{className:"field-error",children:Je}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void be?.openConnectionManager(),children:"Open manager"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void ms(),disabled:!_e.trim()||vt,children:vt?"Saving…":"Save remote server"})]})]}),!F&&D.length>0&&(()=>{const _=D.filter(q=>q.id!=="github"&&q.authenticated).length,ue=D.filter(q=>q.id!=="github").length,Ce=Object.keys(Lt).filter(q=>!D.find(we=>we.id===q)?.authenticated).length;if(ue===0)return null;let We="onboarding-provider-summary",At="";return _>0?(We+=" onboarding-provider-summary--connected",At=`✓ ${_} of ${ue} provider${ue!==1?"s":""} connected`):Ce>0?(We+=" onboarding-provider-summary--skipped",At=`${Ce} provider${Ce!==1?"s":""} skipped`):(We+=" onboarding-provider-summary--none",At="No providers connected yet"),t.jsx("div",{className:We,"data-testid":"provider-summary",children:At})})(),t.jsx(la,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(di,{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."})}),D.length>0&&!D.some(_=>_.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),F?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(jt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):D.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(la,{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"}),ys.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ys.map(_=>X(_))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),ws.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:ws.map(_=>X(_))})]}),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(di,{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."})}),ie.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(Is,{models:ie,value:oe,onChange:ht,placeholder:"Select a default model…",label:"Default model"})}),oe&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",ie.find(_=>_.id===oe)?.name??oe]})})]}),t.jsx(di,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Ms.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Ms.map(_=>X(_))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),Pe.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:Pe.map(_=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(Fn,{provider:_.id,size:"sm"}),t.jsx("span",{children:_.name||_.id})]},_.id))}):null,Be?t.jsx(vL,{onSave:sn,onCancel:()=>{de(!1),Ue(void 0)},saving:Ie,error:st}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>de(!0),children:"Add custom provider"})]})}),Ut&&t.jsx(di,{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."})}),xs&&t.jsx(di,{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(la,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Ve?t.jsx("p",{className:"model-onboarding-description",children:Pt?"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."}),!Ve&&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"})]})}),vs&&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(di,{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."})}),ye?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(si,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Ft,{status:wn})})]}),Le&&(P==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>mt("github"),children:"Disconnect"}))]}),(wn==="not-connected"||wn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[P==="github"||Ke?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 ft("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>te("github"),children:[t.jsx(si,{size:16}),"Connect"]}),(P==="github"||Ke)&&k.github&&t.jsx(Ud,{instructions:k.github,"data-testid":"onboarding-login-instructions-github"})]}),wn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Pt?"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."}),wn==="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:()=>te("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:se,children:"Skip for now"})]})]}),wn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),wn==="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:()=>te("github"),children:"Connect anyway"})})]}),wn==="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(Fn,{provider:"github",size:"lg"})}),Pt?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:()=>y("project-setup"),children:Pt?"Continue with gh CLI auth →":"Continue without GitHub →"}),Pt&&(P==="github"||Ke?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(jt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>te("github"),children:[t.jsx(Fn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Pt&&(P==="github"||Ke)&&k.github&&t.jsx(Ud,{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."}),$n?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(di,{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."}),C&&ps?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:ps.id}),Ns&&t.jsx("p",{className:"onboarding-task-created__description",children:Ns}),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:Rn,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Hn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[$n?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:N,onChange:_=>{R(_.target.value),O(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:Et,disabled:z,"data-testid":"onboarding-first-task-submit",children:z?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),I&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:I}),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(nO,{items:Jn}),$n&&t.jsxs(t.Fragment,{children:[t.jsx(di,{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:Zt,disabled:L,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Mn,{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${Ve?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:le,disabled:L||!Ve,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(si,{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"}),!Ve&&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:lt,disabled:L,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:kt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:it,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:kt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:it,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:it,disabled:!$n,children:"Next →"})]}),x==="first-task"&&!C&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:$t,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Xe,disabled:L,children:L?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:nn,children:[t.jsx(Gn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function $v({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 rO=i.lazy(()=>Sn(()=>import("./SetupWizardModal-CgtvpMX9.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),oO=i.lazy(()=>Sn(()=>import("./SettingsModal-DBcjf9Bu.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function lO(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Sn(()=>import("./SettingsModal-DBcjf9Bu.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function cO({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,y]=i.useState(null),b=c.detailTask?(()=>{const N=n.find(R=>R.id===c.detailTask?.id);return N?"prompt"in c.detailTask?{...c.detailTask,...N,prompt:c.detailTask.prompt,log:c.detailTask.log}:N:c.detailTask})():null,v=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),j=i.useCallback(()=>{c.openGitHubImport()},[c]),C=i.useCallback(N=>{y(null),c.closeModelOnboarding(),c.openDetailTask(N)},[c]),w=i.useCallback(async N=>{const R=await u.handleModalCreate(N);return c.modelOnboardingOpen&&y(R),R},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&x&&y(null)},[c.modelOnboardingOpen,x]),i.useEffect(()=>{lO()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(_a,{children:t.jsx(EP,{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(_a,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(oO,{onClose:v,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(F$,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(_a,{children:t.jsx(H$,{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(_a,{children:t.jsx(Z$,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(w4,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(j4,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(V4,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(K4,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(nD,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(ID,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(kD,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(_a,{children:t.jsx(CD,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:w,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(LD,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:N=>{const R=n.find(z=>z.id===N);R&&c.openDetailTask(R)}}),t.jsx(_a,{children:t.jsx(FD,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(_a,{children:t.jsx(JD,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(dL,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(rO,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(aO,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:j,firstCreatedTask:x,onViewTask:C}),t.jsx($v,{toasts:o,onRemove:l})]})}function dO({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 Au=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function uO(e,n){if(n==="ready")return"done";const s=Au.findIndex(r=>r.id===n),a=Au.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function mO({stage:e}){const[n]=i.useState(()=>ij());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:Au.map(s=>{const a=uO(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(jt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const hO=5e3;function pO(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function fO(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++,Gl(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 gO(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 y=await c1(n);o(y)}catch(y){if(y instanceof Error&&y.name==="AbortError")return;u(y instanceof Error?y.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()},hO),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=fO(e,s,a),g=pO(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const bO={planning:$i,subtask:$a,mission_interview:Rs,milestone_interview:Rs,slice_interview:Rs},xO={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function vO({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=pi(),[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}=Or(),g=i.useMemo(()=>qa(),[]);if(i.useEffect(()=>{if(!l)return;const b=v=>{m.current&&!m.current.contains(v.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,v=new Map;for(const S of e){const j=p.get(S.id),C=[S.status,S.updatedAt,j?.tabId??S.lockedByTab??"",j?.stale?"stale":"fresh"].join("|"),w=h.current.get(S.id);w&&w!==C&&b.add(S.id),v.set(S.id,C)}if(h.current=v,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,y=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${y?" 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(jt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Jd,{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 v=bO[b.type],S=b.status==="generating",j=b.status==="awaiting_input",C=b.status==="error",w=p.get(b.id),N=w?.tabId??b.lockedByTab??null,R=!!(N&&N!==g&&!w?.stale),z=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${z?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:z?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:z?"translateY(-1px)":void 0},onClick:async()=>{R&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[C?t.jsx(Ws,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(v,{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:[C?"Failed":xO[b.type],S&&" — generating...",j&&!R&&" — needs input",j&&R&&" — active in another tab"]})]}),S&&t.jsx(jt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),j&&!R&&t.jsx(Jd,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),j&&R&&t.jsx(pc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:E=>{E.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(un,{size:12})})]},b.id)})})]})]})}function yO(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 wO(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:is};case"paused":return{label:"Paused",color:"var(--triage)",icon:vi};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:as}}}function kO({tasks:e,projectId:n,taskStuckTimeoutMs:s,staleHighFanoutBlockerAgeThresholdMs:a,backgroundSessions:r,backgroundGenerating:o,backgroundNeedsInput:l,onOpenBackgroundSession:c,onDismissBackgroundSession:d,lastFetchTimeMs:u,currentProjectPath:m,onOpenProjectDirectory:h,keyboardOpen:f}){if(f)return null;const{stats:p,loading:g,error:x}=gO(e,n,s,u),[y,b]=i.useState(!1),v=i.useMemo(()=>wO(p.executorState),[p.executorState]),S=i.useMemo(()=>yO(p.lastActivityAt),[p.lastActivityAt]),j=i.useMemo(()=>{const w=Ju(e,{staleHighFanoutAgeThresholdMs:a??Ab});return Array.from(w.values()).map(R=>R.escalation).filter(R=>!!R).sort((R,z)=>z.activeTodoCount!==R.activeTodoCount?z.activeTodoCount-R.activeTodoCount:z.totalActiveCount!==R.totalActiveCount?z.totalActiveCount-R.totalActiveCount:z.blockingAgeMs!==R.blockingAgeMs?z.blockingAgeMs-R.blockingAgeMs:R.blockerId.localeCompare(z.blockerId,"en",{numeric:!0,sensitivity:"base"}))[0]??null},[e,a]),C=v.icon;return x?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(Oo,{size:14}),x]})}):g&&p.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 ${p.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[r&&r.length>0&&c&&d&&t.jsxs(t.Fragment,{children:[t.jsx(vO,{sessions:r,generating:o??0,needsInput:l??0,onOpenSession:c,onDismissSession:d}),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:p.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 ${p.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:p.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:p.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),p.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:p.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 ${p.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 ${p.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:p.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:p.inReviewCount})]}),j&&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--fanout",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--fanout executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Escalated"}),t.jsxs("span",{className:"executor-status-bar__fanout-summary",title:`Escalated blocker ${j.blockerId}: ${j.activeTodoCount} todo waiting (threshold ${Wu}), ${j.totalActiveCount} active total`,children:[j.blockerId," · ",j.activeTodoCount," todo"]})]})]}),m&&h&&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${y?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(w=>!w),"aria-label":y?"Hide project directory":"Show project directory","aria-expanded":y,"data-testid":"executor-project-path-toggle",title:y?"Hide project directory":"Show project directory",children:t.jsx(Es,{size:12,"aria-hidden":"true"})}),y&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:h,title:m,"data-testid":"executor-project-path-link",children:m})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(Ji,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:S})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(C,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const jO={planning:$i,subtask:$a,mission_interview:Rs,milestone_interview:Rs,slice_interview:Rs},NO={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Dv="fusion:session-banner-dismissed";function bo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function SO(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Dv);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:bo(r);s.set(a,o)}return s}catch{return new Map}}function CO(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Dv,JSON.stringify(n))}catch{}}const Vi=SO();function EO({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{CO(Vi),o(g=>g+1)};i.useEffect(()=>{if(Vi.size===0)return;const g=new Map(e.map(y=>[y.id,y]));let x=!1;for(const[y,b]of Vi){const v=g.get(y);if(!v)continue;if(!(v.status==="awaiting_input"||v.status==="error")){Vi.delete(y),x=!0;continue}bo(v.updatedAt)>b&&(Vi.delete(y),x=!0)}x&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const x=Vi.get(g.id);return x===void 0?!0:bo(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=>{Vi.set(g.id,Math.max(bo(g.updatedAt),Date.now())),l()},f=g=>{Vi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const x of c)Vi.set(x.id,Math.max(bo(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(Ws,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(un,{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=jO[g.type],y=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${y?" 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:[y?t.jsx(Ws,{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:y?"Failed":NO[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:y?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(un,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Lv="fusion:cli-binary-banner-dismissed";function _O(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Lv)==="1"}catch{return!1}}function MO(){if(!(typeof window>"u"))try{window.localStorage.setItem(Lv,"1")}catch{}}function AO({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>_O()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let v=!1;return tN().then(S=>{v||s(S)}).catch(()=>{}),()=>{v=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const v=await nN();s({binary:v.binary,expectedVersion:v.expectedVersion,state:v.state,install:v.install}),v.installResult.success||d(v.installResult.permissionsHint||v.installResult.stderr||`Install failed (exit ${v.installResult.exitCode??"n/a"})`)}catch(v){d(v instanceof Error?v.message:String(v))}finally{l(!1)}},[]),m=i.useCallback(()=>{MO(),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."]}),y=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:y}),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(un,{size:16})})]})}function RO({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:"fn update"})," for an installed CLI, or pull this source checkout."," ",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(un,{size:16,"aria-hidden":"true"})})]})}function IO({pendingCount:e,onOpenMailbox:n,onDismiss:s}){const a=e===1?"request":"requests";return t.jsx("section",{className:"approval-notification-banner",role:"region","aria-live":"polite","aria-label":"Approval requests",children:t.jsxs("div",{className:"approval-notification-banner__content",children:[t.jsxs("div",{className:"approval-notification-banner__headline",children:[t.jsx("span",{className:"status-dot","aria-hidden":"true"}),t.jsx(Oo,{"aria-hidden":"true"}),t.jsxs("span",{children:[e," approval ",a," need your attention"]})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(ra,{"aria-hidden":"true"}),t.jsx("span",{children:"Open Mailbox"})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":"Dismiss approval notification banner",children:t.jsx(un,{"aria-hidden":"true"})})]})]})})}function TO({onResume:e}){const n=$L();if(!n)return null;const s=n.completedSteps.length,a=aa.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(gs,{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:()=>{ci("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(is,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function PO({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Ar(),a=Rv(),[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,j]=await Promise.all([Co(),Yi()]);if(b)return;const C=S.providers??[],w=C.find(I=>I.id==="github"),R=!C.some(I=>I.id!=="github"&&I.authenticated),z=!j.defaultProvider&&!j.defaultModelId,E=w?!w.authenticated:!1;h({needsAiProvider:R,needsDefaultModel:z,needsGitHub:E})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{TL(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),x=i.useCallback(()=>{e("authentication")},[e]),y=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:as}),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:Qg}),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:si}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,g,p]);return!s||a||d||r||l||y.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($i,{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:y.map(b=>{const v=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(v,{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(la,{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(un,{size:16,"aria-hidden":!0})})]})}function $O({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 ao(e){return e>99?"99+":String(e)}function DO({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,stashOrphanCount:f=0,onOpenGitManager:p,onOpenWorkflowSteps:g,onOpenSchedules:x,onOpenScripts:y,onToggleTerminal:b,onOpenFiles:v,onOpenTodos:S,todosOpen:j=!1,onOpenGitHubImport:C,onOpenPlanning:w,onResumePlanning:N,activePlanningSessionCount:R=0,onOpenUsage:z,onRunScript:E,projectId:I,onViewAllProjects:O,showSkillsTab:U,experimentalFeatures:A,onOpenNodes:D,pluginDashboardViews:K=[],shellConnectionControl:Z}){const ne=ri(),[F,M]=i.useState(!1),[P,$]=i.useState(!1),[k,J]=i.useState({}),[ce,je]=i.useState(!1),He=i.useMemo(()=>Object.entries(k).sort(([ae],[qe])=>ae.localeCompare(qe)),[k]);i.useEffect(()=>{if(!P)return;let ae=!1;return je(!0),Eo(I).then(qe=>{ae||J(qe)}).catch(()=>{ae||J({})}).finally(()=>{ae||je(!1)}),()=>{ae=!0}},[P,I]);const xe=i.useCallback(()=>M(!1),[]),Ne=i.useCallback(ae=>{xe(),ae?.()},[xe]);if(i.useEffect(()=>{if(!F)return;const ae=qe=>{qe.key==="Escape"&&M(!1)};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[F]),ne!=="mobile"||a||r)return null;const Y=R>0&&N?N:w,ie=!!U,ee=!!A?.todoView,oe=ie,W=ie&&!oe,fe=K.filter(ae=>ae.view.placement==="primary").sort((ae,qe)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(qe.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),B=new Set(fe.map(ae=>`${ae.pluginId}:${ae.view.viewId}`)),ve=K.filter(ae=>!B.has(`${ae.pluginId}:${ae.view.viewId}`)).sort((ae,qe)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(qe.view.order??Number.MAX_SAFE_INTEGER)),Fe=e==="documents"||!!A?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||j&&ee||e==="skills"&&!oe||e==="graph"||e==="stash-recovery"||pr(e)&&!fe.some(ae=>vo(ae.pluginId,ae.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(ma,{}),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(Rs,{}),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(Ki,{}),h&&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.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Da,{}),m>0&&e!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Pending approvals"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:ao(u)})]}),oe&&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(as,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),fe.map(ae=>{const qe=vo(ae.pluginId,ae.view.viewId),Pe=Vl(ae.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===qe||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${ae.pluginId}-${ae.view.viewId}`,role:"tab","aria-selected":e===qe||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph",onClick:()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":qe),children:[t.jsx(Pe,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${Fe?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>M(ae=>!ae),children:[t.jsx(Yd,{}),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:xe}),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"}),Z?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:Z}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>Ne(d),children:[t.jsx(Da,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:ao(u)}),m>0&&t.jsx("span",{className:"mobile-more-item-badge",children:ao(m)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>Ne(l),children:[t.jsx(Ys,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>Ne(c),children:[t.jsx(vr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>Ne(p),children:[t.jsx(Fs,{}),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:()=>Ne(b),children:[t.jsx(Gi,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>$(ae=>!ae),"aria-expanded":P,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(On,{size:14,className:`mobile-more-chevron${P?" mobile-more-chevron--open":""}`})})]}),P&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:ce?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(jt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):He.length>0?t.jsxs(t.Fragment,{children:[He.map(([ae,qe])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${ae}`,onClick:()=>{E&&E(ae,qe),xe(),$(!1)},children:[t.jsx(is,{}),t.jsx("span",{children:ae})]},ae)),y&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{xe(),$(!1),y()},children:[t.jsx(xi,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):y&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{xe(),$(!1),y()},children:[t.jsx(xi,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>Ne(v),children:[t.jsx(Es,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>Ne(Y),children:[t.jsx($i,{}),t.jsx("span",{children:"Planning"}),R>0&&t.jsx("span",{className:"mobile-more-item-badge",children:ao(R)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>Ne(g),children:[t.jsx(Bl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>Ne(x),children:[t.jsx(Ji,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>Ne(C),children:[t.jsx($O,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>Ne(z),children:[t.jsx(Ys,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>Ne(O),children:[t.jsx(uc,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>Ne(()=>n("documents")),children:[t.jsx(ua,{}),t.jsx("span",{children:"Documents"})]}),A?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>Ne(()=>n("evals")),children:[t.jsx(Rs,{}),t.jsx("span",{children:"Evals"})]}),W&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>Ne(()=>n("skills")),children:[t.jsx(as,{}),t.jsx("span",{children:"Skills"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>Ne(()=>n("stash-recovery")),children:[t.jsx(Pa,{}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"mobile-more-item-badge",children:ao(f)}):null]}),A?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>Ne(()=>n("research")),children:[t.jsx(Wi,{}),t.jsx("span",{children:"Research"})]}),A?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>Ne(()=>n("insights")),children:[t.jsx(gs,{}),t.jsx("span",{children:"Insights"})]}),A?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>Ne(()=>n("memory")),children:[t.jsx(No,{}),t.jsx("span",{children:"Memory"})]}),A?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{Ne(()=>n("dev-server"))},children:[t.jsx(vr,{}),t.jsx("span",{children:"Dev Server"})]}),A?.nodesView&&D&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>Ne(D),children:[t.jsx(pk,{}),t.jsx("span",{children:"Nodes"})]}),ee&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>Ne(()=>S?.()),children:[t.jsx($u,{}),t.jsx("span",{children:"Todos"})]}),ve.map(ae=>{const qe=vo(ae.pluginId,ae.view.viewId),Pe=Vl(ae.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${ae.pluginId}-${ae.view.viewId}`,onClick:()=>Ne(()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":qe)),children:[t.jsx(Pe,{}),t.jsx("span",{children:ae.view.label})]},`${ae.pluginId}:${ae.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:()=>Ne(o),children:[t.jsx(xo,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function hg(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Ov(e,n){const s=n.trim();if(!s)return!0;const a=hg(s);return hg(e).includes(a)||e.toLowerCase().includes(s.toLowerCase())}function LO({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below",roomMemberIds:l,roomName:c}){const d=i.useMemo(()=>e.filter(g=>Ov(g.name,n)),[e,n]),u=!!l,m=u&&n.trim().length>0,h=i.useMemo(()=>u?d.filter(g=>l?.has(g.id)):d,[d,l,u]),f=i.useMemo(()=>u?d.filter(g=>!l?.has(g.id)):[],[d,l,u]),p=m?[...h,...f]:h;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:p.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):t.jsxs(t.Fragment,{children:[u&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:c?`Members of #${c}`:"Room members"}),h.map((g,x)=>t.jsxs("button",{type:"button",className:`agent-mention-item${x===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:y=>y.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":x===s,children:[t.jsx(sc,{agent:g,size:20}),u&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":"Room member"}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)),u&&!m&&f.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:"Type to search other agents"}),u&&m&&f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:"Other agents"}),f.map((g,x)=>{const y=h.length+x;return t.jsxs("button",{type:"button",className:`agent-mention-item${y===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:b=>b.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":y===s,children:[t.jsx(sc,{agent:g,size:20}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)})]})]})}):null}function pg(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,y=null;const b=()=>{x=null,a(h)},v=()=>{y=null,r(f)},S=()=>{x!==null&&(cancelAnimationFrame(x),x=null),y!==null&&(cancelAnimationFrame(y),y=null)};return l.current=S,{handlers:{onThinking:C=>{f+=C,y===null&&(y=requestAnimationFrame(v))},onText:C=>{h+=C,x===null&&(x=requestAnimationFrame(b))},onToolStart:C=>{p=[...p,{toolName:C.toolName,args:C.args,isError:!1,status:"running"}],o(p)},onToolEnd:C=>{const w=[...p];for(let N=w.length-1;N>=0;N--){const R=w[N];if(R?.toolName===C.toolName&&R.status==="running"){w[N]={...R,status:"completed",isError:C.isError,result:C.result},p=w,o(w);return}}p=[...w,{toolName:C.toolName,isError:C.isError,result:C.result,status:"completed"}],o(p)},onFallback:C=>{g=C,m?.(C,n),c?.(`Primary model unavailable. Switched to fallback ${C.fallbackModel}.`,"warning")},onDone:C=>{S(),d({messageId:C.messageId,message:C.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:C=>{S(),u(C,s)}},cancelFlushes:S}}const OO=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function FO(e){const n=e.trim().toLowerCase();return n?OO.some(s=>n.includes(s)):!1}function zO(){const e=i.useRef(null),n=i.useRef(null);i.useEffect(()=>{if(typeof document>"u")return;const r=()=>{const o=Date.now();if(document.visibilityState==="hidden"){e.current=o;return}document.visibilityState==="visible"&&(n.current=o)};return r(),document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[]);const s=i.useCallback(()=>typeof document<"u"&&document.visibilityState==="hidden",[]),a=i.useCallback((r=5e3)=>{const o=e.current;if(o===null)return!1;const l=Date.now();if(s())return l-o<=r;const c=n.current;return c===null||c<o?!1:l-c<=r},[s]);return i.useMemo(()=>({isHiddenNow:s,wasRecentlyHidden:a}),[s,a])}const hr="__fn_agent__";function Fv(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Rl(e,n,s){const a=typeof e=="string"?e.trim():"",r=Fv(n,s),o=a||(r.modelProvider&&r.modelId?hr:"");return o?{agentId:o,...r}:null}function Il(e,n,s){const a=Fv(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function fg(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 BO(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 UO(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 lr(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:BO(e.metadata),fallbackInfo:UO(e.metadata),createdAt:e.createdAt}}function HO(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(""),[y,b]=i.useState(""),[v,S]=i.useState([]),[j,C]=i.useState(""),w=i.useRef(null),N=i.useRef(!1),R=i.useRef(null),z=i.useRef(""),E=i.useRef(f);E.current=f;const I=i.useRef(null),O=i.useRef(""),U=i.useRef(null),A=i.useRef(s);A.current=s;const D=i.useRef(0),K=3,Z=i.useRef(!1);i.useEffect(()=>{z.current=j},[j]);const ne=i.useCallback(async()=>{c(!0);try{const W=await ah(e);o(W.sessions)}catch(W){console.error("[useQuickChat] Failed to refresh sessions:",W)}finally{c(!1)}},[e]),F=i.useCallback(async W=>{const L={agentId:W.agentId};return W.modelProvider&&W.modelId&&(L.modelProvider=W.modelProvider,L.modelId=W.modelId),(await I0(L,e)).session},[e]),M=i.useCallback((W,L)=>{if(w.current||!W)return!0;N.current=!1,L&&(x(L.streamingText),b(L.streamingThinking),S(L.toolCalls)),p(!0);const{handlers:pe}=pg({sessionId:W,tempUserMessageId:"",setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(fe,B)=>{const ve=fg(fe.fallbackModel);o(Fe=>Fe.map(ae=>ae.id===B?{...ae,...ve}:ae)),a(Fe=>Fe&&Fe.id===B?{...Fe,...ve}:Fe)},onDone:()=>{x(""),b(""),S([]),p(!1),E.current=!1,w.current=null,Vr(W,{limit:50},e).then(fe=>{u(fe.messages.map(lr))}).catch(()=>{})},onError:fe=>{x(""),b(""),S([]),p(!1),E.current=!1,w.current=null;const B=typeof fe=="string"&&fe.trim()?fe:"Failed to get response";n?.(B,"error"),Vr(W,{limit:50},e).then(ve=>{u(ve.messages.map(lr))}).catch(()=>{})}});return w.current=D0(W,pe,e,{...typeof L?.replayFromEventId=="number"?{lastEventId:L.replayFromEventId}:{}}),!0},[n,e]),P=i.useCallback(async(W,L,pe)=>{const fe=Rl(W,L,pe);if(!fe)return;const B=Il(fe.agentId,fe.modelProvider,fe.modelId);c(!0);try{const{session:ve}=await R0({agentId:fe.agentId,modelProvider:fe.modelProvider,modelId:fe.modelId},e);if(ve)a(ve),O.current=B,ve.isGenerating&&M(ve.id,ve.inFlightGeneration);else{const Fe=await F(fe);a(Fe),O.current=B}D.current=0}catch(ve){console.error("[useQuickChat] Failed to initialize session:",ve),D.current+=1,D.current<=K&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[M,e,n,F]),$=i.useCallback(async()=>{if(s){h(!0);try{const W=await Vr(s.id,{limit:50},e);u(W.messages.map(lr))}catch(W){console.error("[useQuickChat] Failed to load messages:",W)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?$():u([])},[s,$]),i.useEffect(()=>{if(!s?.isGenerating||(w.current||M(s.id,s.inFlightGeneration),!E.current||w.current||!s))return;const W=setInterval(async()=>{if(!E.current||w.current||!s){clearInterval(W);return}try{if(!(await T0(s.id,e)).session.isGenerating){clearInterval(W);const pe=await Vr(s.id,{limit:50},e);u(pe.messages.map(lr)),x(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(W)},[s,M,e]);const k=i.useCallback(async()=>{if(s){h(!0);try{const W=await Vr(s.id,{limit:50},e);u(W.messages.map(lr))}catch(W){console.error("[useQuickChat] Failed to reload messages:",W)}finally{h(!1)}}},[s,e]),J=i.useCallback(()=>{R.current?.(),R.current=null,z.current="",C(""),x(""),b(""),S([]),p(!1)},[]),ce=i.useCallback(async(W,L,pe)=>{const fe=Rl(W,L,pe);if(!fe)return;const B=Il(fe.agentId,fe.modelProvider,fe.modelId);U.current=fe;const ve=B===O.current&&A.current;if(ve||(w.current&&(w.current.close(),w.current=null),J()),ve){await k();return}a(null),u([]),O.current=B,await P(fe.agentId,fe.modelProvider,fe.modelId)},[P,k,J]),je=i.useCallback(async W=>{const L=Rl(W.agentId,W.modelProvider??void 0,W.modelId??void 0);L&&(U.current=L,O.current=Il(L.agentId,L.modelProvider,L.modelId),w.current&&(w.current.close(),w.current=null),J(),a(W),W.isGenerating&&M(W.id,W.inFlightGeneration))},[M,J]),He=i.useCallback(async(W,L)=>{await ce(hr,W,L)},[ce]),xe=i.useCallback(async(W,L,pe)=>{const B=Rl(W??"",L,pe)??U.current;if(!B)return;U.current=B;const ve=Il(B.agentId,B.modelProvider,B.modelId);Z.current=!0,D.current=0,w.current&&(w.current.close(),w.current=null),J(),u([]),a(null),c(!0);try{const Fe=await F(B);a(Fe),O.current=ve;const ae=await ah(e);o(ae.sessions)}catch(Fe){console.error("[useQuickChat] Failed to start a fresh session:",Fe),n?.("Failed to start a new chat","error")}finally{Z.current=!1,c(!1)}},[n,F,e,J]),Ne=i.useCallback(()=>{s&&(N.current=!0,R.current?.(),R.current=null,w.current?.close(),w.current=null,P0(s.id,e).catch(()=>{}),p(!1),x(""),b(""),S([]))},[s,e]),Y=i.useCallback(()=>{z.current="",C("")},[]),ie=i.useRef(()=>Promise.resolve()),ee=zO(),oe=i.useCallback((W,L)=>{if(!s||!W.trim()&&(!L||L.length===0))return Promise.resolve();if(E.current)return L&&L.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(z.current=W,C(W),Promise.resolve());const pe=new Promise((fe,B)=>{I.current={resolve:fe,reject:B},N.current=!1,w.current&&(w.current.close(),w.current=null);const ve=`temp-${Date.now()}`,Fe={id:ve,sessionId:s.id,role:"user",content:W,createdAt:new Date().toISOString()};u(qe=>[...qe,Fe]),x(""),b(""),S([]),p(!0);const{handlers:ae}=pg({sessionId:s.id,tempUserMessageId:ve,setStreamingText:x,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(qe,Pe)=>{const nt=fg(qe.fallbackModel);o(Be=>Be.map(de=>de.id===Pe?{...de,...nt}:de)),a(Be=>Be&&Be.id===Pe?{...Be,...nt}:Be)},onDone:({messageId:qe,message:Pe,accumulated:nt})=>{const Be=Pe?lr(Pe):{id:qe||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:nt.text,thinkingOutput:nt.thinking||void 0,toolCalls:nt.toolCalls.length>0?nt.toolCalls:void 0,fallbackInfo:nt.fallbackInfo,createdAt:new Date().toISOString()};u(Ie=>[...Ie,Be]),x(""),b(""),S([]),p(!1),E.current=!1,w.current=null,I.current?.resolve(),I.current=null;const de=z.current.trim();de&&(z.current="",C(""),ie.current(de))},onError:qe=>{x(""),b(""),S([]),p(!1),E.current=!1,w.current=null,console.error("[useQuickChat] Stream error:",qe);const Pe=typeof qe=="string"&&qe.trim()?qe:"Failed to get response";if(typeof qe=="string"&&FO(qe)&&(ee.isHiddenNow()||ee.wasRecentlyHidden(5e3))?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",qe),I.current?.resolve()):(n?.(Pe,"error"),I.current?.reject(new Error(Pe))),I.current=null,!N.current){const Be=z.current.trim();Be&&(z.current="",C(""),ie.current(Be))}k()}});w.current=$0(s.id,W,ae,L,e)});return pe.catch(()=>{}),pe},[s,e,n,k,ee]);return ie.current=oe,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:y,streamingToolCalls:v,pendingMessage:j,sendMessage:oe,stopStreaming:Ne,clearPendingMessage:Y,switchSession:ce,selectSession:je,startModelChat:He,startFreshSession:xe,refreshSessions:ne,loadMessages:$,reloadMessages:k,skipNextSessionInitRef:Z}),[s,r,l,d,m,f,g,y,v,j,oe,Ne,Y,ce,je,He,xe,ne,$,k])}function qO(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,y=n?.showSystemAgents??!1,b=await Pr({...x,...p,includeEphemeral:p?.includeEphemeral??y},e),v=Array.from(new Map(b.map(S=>[S.id,S])).values());a(v)}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 JS(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 hi(`/api/events${p}`,{events:{"agent:created":g,"agent:updated":g,"agent:deleted":g,"agent:stateChanged":g,"approval:requested":g,"approval:updated":g,"approval:decided":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||!MC(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function VO({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=dC(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(Jg,{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 WO=200;function KO(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),y=i.useRef(null);i.useEffect(()=>()=>{x.current&&clearTimeout(x.current),y.current?.abort()},[]);const b=i.useCallback((w,N)=>{if(N<0||N>w.length){r(!1);return}const R=z=>/[a-zA-Z0-9/_.-]/.test(z);for(let z=N-1;z>=0;z--){if(w[z]==="#")if(z===0){const E=w.slice(z+1,N);d(z),l(E),g(0),r(!0);return}else{const E=w[z-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const I=w.slice(z+1,N);d(z),l(I),g(0),r(!0);return}r(!1);return}if(!R(w[z])){r(!1);return}}r(!1)},[]),v=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async w=>{if(!w.trim()){m([]),f(!1);return}y.current?.abort(),y.current=new AbortController;try{f(!0);const N=await eS(w,s,n);m(N.files),g(0)}catch(N){N.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},WO),()=>{x.current&&clearTimeout(x.current)}},[o,a,S]);const j=i.useCallback((w,N)=>{if(!a||c<0)return N;const R=N.slice(0,c),z=N.slice(c+1),E=z.match(/[\s]|$/),I=E?E.index:z.length,O=z.slice(I);return`${R}#${w.path}${O}`},[a,c]),C=i.useCallback((w,N)=>{if(!a||u.length===0)return!1;switch(w.key){case"ArrowDown":return w.preventDefault(),g(R=>Math.min(R+1,u.length-1)),!0;case"ArrowUp":return w.preventDefault(),g(R=>Math.max(R-1,0)),!0;case"Enter":case"Tab":return u[p]?(w.preventDefault(),!0):!1;case"Escape":return w.preventDefault(),v(),!0;default:return!1}},[a,u,p,v]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:j,dismissMention:v,handleKeyDown:C}}function GO(e){return`${e.name?.trim()||e.id} (${e.role})`}function ro(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 JO(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 Ll(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function YO(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}=${Ll(r,50)}`}).join(", ")}function QO(e){if(e===void 0)return null;if(typeof e=="string")return Ll(e,200);try{return Ll(JSON.stringify(e),200)}catch{return Ll(String(e),200)}}function zv(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,y=YO(f.args),b=QO(f.result),v=g?y:b?`result: ${b}`:y?`args: ${y}`:null,S=n?null:v,j=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:j})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[y&&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:y})]}),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(Im,{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(Im,{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 Bv={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 gg(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 XO(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 Tl={width:320,height:400},ZO=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"]),eF=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function tF(e){return e.type.startsWith("image/")}function nF(e){if(ZO.has(e.type))return!0;const n=e.name.toLowerCase();return eF.some(s=>n.endsWith(s))}const cr={width:280,height:260},Os=768,dr=8;function sF(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const j=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return j&&parseFloat(j)||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 j=`fusion-quick-chat-position-${e||"default"}`;try{const C=localStorage.getItem(j);if(C){const w=JSON.parse(C);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(j=>{if(typeof window>"u")return j;const C=48,w=window.innerWidth<=768?4:8,N=window.innerWidth<=768?44:0,R=window.innerWidth>768?s():0,z=window.innerWidth-C-w,E=window.innerHeight-C-w-N-R;return{x:Math.max(w,Math.min(z,j.x)),y:Math.max(w,Math.min(E,j.y))}},[s]),g=i.useCallback(j=>{if(typeof window>"u")return;const C=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(C,JSON.stringify(j))}catch{}},[e]),x=i.useCallback(()=>{if(!d.current)return;const j=h.current,C=m.current;j&&C!==null&&typeof j.releasePointerCapture=="function"&&j.releasePointerCapture(C),d.current=null,m.current=null,h.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",y),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",v)},[g]),y=i.useCallback(j=>{if(!d.current||m.current!==null&&j.pointerId!==m.current)return;const C=j.clientX-d.current.pointerX,w=j.clientY-d.current.pointerY;if((Math.abs(C)>=5||Math.abs(w)>=5)&&(f.current=!0),!f.current)return;const N=d.current.x-C,R=d.current.y-w,z=p({x:N,y:R});u.current=z,o(z)},[p]),b=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||x()},[x]),v=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||x()},[x]),S=i.useCallback(j=>{if(j.button!==0&&j.pointerType==="mouse")return;const C=j.currentTarget;j.preventDefault(),typeof C.setPointerCapture=="function"&&C.setPointerCapture(j.pointerId);const w=u.current;d.current={x:w.x,y:w.y,pointerX:j.clientX,pointerY:j.clientY},m.current=j.pointerId,h.current=C,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",y,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",v)},[v,y,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",y),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",v),document.body.style.userSelect=""},[v,y,b]),{position:r,isDragging:l,handlePointerDown:S}}function iF(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Os,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const x=Math.max(cr.width,window.innerWidth-p-dr),y=Math.max(cr.height,window.innerHeight-g-dr);return{width:Math.max(cr.width,Math.min(x,f.width)),height:Math.max(cr.height,Math.min(y,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Os)return Tl;try{const f=localStorage.getItem(a);if(!f)return Tl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Tl:{width:p.width,height:p.height}}catch{return Tl}},[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 y=v=>{const S=v.clientX-x.pointerX,j=v.clientY-x.pointerY;let C=x.width,w=x.height,N=x.anchorRight,R=x.anchorBottom;if(p.includes("w")&&(C=x.width-S),p.includes("e")){const A=S;C=x.width+A,N=x.anchorRight-A}if(p.includes("n")&&(w=x.height-j),p.includes("s")){const A=j;w=x.height+A,R=x.anchorBottom-A}const z=n+N,E=s+R,I=o({width:C,height:w},z,E),O=Math.max(dr-n,Math.min(window.innerWidth-n-cr.width-dr,N)),U=Math.max(dr-s,Math.min(window.innerHeight-s-cr.height-dr,R));d(I),m({right:O,bottom:U})},b=v=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(v.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",y),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",y),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 bg=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,roomContext:r,onToggleRender:o}){const l=n.role==="user",c=i.useMemo(()=>{if(!l)return null;const u=n.content,m=/@([\w-]+)/g,h=[];let f=0,p=m.exec(u);for(;p;){const[g,x=""]=p,y=p.index;y>f&&h.push(u.slice(f,y));const b=x.replace(/_/g," ").toLowerCase(),v=a.get(b);if(v){const S=!!(r&&!r.memberIds.has(v.id)),j=S?`Not a member of ${r?.roomName}`:void 0;h.push(t.jsxs("span",{className:`chat-mention-chip${S?" chat-mention-chip--non-member":""}`,title:j,"aria-label":j,children:["@",v.name.replace(/\s+/g,"_")]},`${v.id}-${y}`))}else h.push(g);f=y+g.length,p=m.exec(u)}return f<u.length&&h.push(u.slice(f)),h.length===0?u:h},[l,n.content,a,r]),d=i.useMemo(()=>l?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(ki,{remarkPlugins:[ji],components:Bv,children:n.content})}),[l,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${l?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[l?t.jsx("p",{children:c}):t.jsxs(t.Fragment,{children:[d,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:()=>o(n.id),children:s?t.jsx(Pu,{size:14}):t.jsx(Ir,{size:14})})]}),zv(n.toolCalls,!0)]})});function aF({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d,roomContext:u=null}){const{agents:m}=qO(e),[h,f]=i.useState(!1),p=a!==void 0,g=p?a:h,x=p?q=>{r?.(typeof q=="function"?q(g):q)}:f,{keyboardOpen:y}=Zi({enabled:g}),b=ri(),v=b==="mobile",[S,j]=i.useState("agent"),[C,w]=i.useState(""),[N,R]=i.useState(!1),[z,E]=i.useState("model"),[I,O]=i.useState(""),[U,A]=i.useState(""),[D,K]=i.useState([]),[Z,ne]=i.useState(!1),[F,M]=i.useState(""),[P,$]=i.useState(""),[k,J]=i.useState(""),[ce,je]=i.useState([]),[He,xe]=i.useState(!1),[Ne,Y]=i.useState(!1),[ie,ee]=i.useState(""),[oe,W]=i.useState(0),[L,pe]=i.useState(""),[fe,B]=i.useState(!1),[ve,Fe]=i.useState(0),[ae,qe]=i.useState(-1),[Pe,nt]=i.useState(()=>new Set),[Be,de]=i.useState(!1),[Ie,$e]=i.useState([]),[st,Ue]=i.useState(!1),[me,re]=i.useState(!1),[,_e]=i.useState(!1),[xt,dt]=i.useState({top:0,left:0}),Qe=KO({projectId:e}),vt=i.useCallback(q=>{if(!q||!Qe.mentionActive)return;const we=q.getBoundingClientRect();dt({top:we.top-260,left:we.left+8})},[Qe.mentionActive]),Ae=i.useRef(!1),Je=i.useRef(!1),ct=i.useRef(""),Nt=i.useRef(0),yt=i.useRef(null),Se=i.useRef(null),G=i.useRef(0),{position:ge,isDragging:pt,handlePointerDown:ke}=sF(e,Ae),tt=ge.y+60,{panelSize:Rt,anchorOffset:Re,handleResizeStart:be}=iF(e,ge.x,tt),at=typeof window<"u"&&window.innerWidth>Os,{activeSession:ot,messages:gt,isStreaming:St,streamingText:Lt,streamingThinking:Yt,streamingToolCalls:tn,sessions:mn,sessionsLoading:Qt,messagesLoading:yn,sendMessage:Gt,stopStreaming:on,pendingMessage:sn,clearPendingMessage:ln,switchSession:Wt,selectSession:ye,startModelChat:Le,startFreshSession:Ke,refreshSessions:ut,skipNextSessionInitRef:Ve}=HO(e,n),Pt=i.useRef(null),Ot=i.useRef(null),bt=i.useRef(null),Dt=i.useRef(null),Ft=i.useRef(null),Ht=i.useRef([]),rn=i.useRef(!1),Xt=i.useRef(!1),an=i.useRef(!1),Me=i.useRef(null),it=i.useRef(!1),kt=i.useRef(!1),$t=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!g||typeof window>"u"||typeof document>"u"||window.innerWidth>Os)return;const q=window.scrollY,we=document.documentElement,Oe=document.body,It={htmlOverflow:we.style.overflow,bodyOverflow:Oe.style.overflow};return window.scrollTo(0,0),we.style.overflow="hidden",Oe.style.overflow="hidden",()=>{we.style.overflow=It.htmlOverflow,Oe.style.overflow=It.bodyOverflow,window.scrollTo(0,q)}},[g]),i.useLayoutEffect(()=>{if(!g||typeof window>"u"||!window.visualViewport)return;const q=Pt.current;if(!q)return;const we=window.visualViewport,Oe=()=>{it.current||(q.style.setProperty("--vv-height",`${we.height}px`),q.style.setProperty("--vv-offset-top",`${we.offsetTop||0}px`))};return Oe(),we.addEventListener("resize",Oe),we.addEventListener("scroll",Oe),()=>{we.removeEventListener("resize",Oe),we.removeEventListener("scroll",Oe)}},[g]);const se=F||P,te=i.useMemo(()=>ro(se),[se]),De=i.useMemo(()=>S==="model"&&ot?.modelProvider&&ot?.modelId?`${ot.modelProvider}/${ot.modelId}`:se,[ot?.modelId,ot?.modelProvider,S,se]),ft=i.useMemo(()=>ro(De),[De]),qt=i.useMemo(()=>D.find(q=>`${q.provider}/${q.id}`===De)??null,[De,D]),zt=i.useMemo(()=>JO(qt,ft),[qt,ft]),Pn=i.useMemo(()=>S==="model"?te?`${hr}::${te.modelProvider}/${te.modelId}`:"":C?`${C}::`:"",[S,C,te]),mt=!(S==="agent"?!!C:!!te)||!ot;i.useEffect(()=>{if(m.length===0){w(""),j("model");return}m.some(we=>we.id===C)||w(m[0]?.id??"")},[m,C]),i.useEffect(()=>{!g||Je.current||(Je.current=!0,ne(!0),Ks().then(q=>{const we=q.models??[];if(K(we),F||we.length===0)return;const Oe=q.defaultProvider,It=q.defaultModelId;if(Oe&&It){const fn=`${Oe}/${It}`;if(we.some(jn=>`${jn.provider}/${jn.id}`===fn)){$(fn),M(fn),j("model");return}}$("");const Kt=we[0];Kt&&M(`${Kt.provider}/${Kt.id}`)}).catch(q=>{console.error("[QuickChatFAB] Failed to load models:",q),K([]),$("")}).finally(()=>{ne(!1)}))},[g,m.length,F]),i.useEffect(()=>{!g||!e||(xe(!0),A0(e).then(q=>{je(q)}).catch(()=>{je([])}).finally(()=>{xe(!1)}))},[g,e]),i.useEffect(()=>{g&&ut()},[g,ut]),i.useEffect(()=>{if(!g){ct.current="";return}if(!Pn){ct.current="";return}if(Ve.current){ct.current=Pn;return}const q=Pn===ct.current&&!ot&&!Qt;if(!(Pn===ct.current&&!q)){if(ct.current=Pn,S==="model"&&te){Le(te.modelProvider,te.modelId);return}S==="agent"&&C&&Wt(C)}},[g,S,te,C,Pn,ot,Qt,Le,Wt,Ve]),i.useEffect(()=>{g||(B(!1),pe(""),qe(-1),Y(!1),ee(""),W(0),Ht.current.forEach(q=>{q.previewUrl&&URL.revokeObjectURL(q.previewUrl)}),$e([]))},[g]),i.useEffect(()=>{Ht.current=Ie},[Ie]),i.useEffect(()=>{if(!g){rn.current=!1;return}typeof window>"u"||(rn.current=window.innerWidth<=Os)},[g]),i.useEffect(()=>{if(!g||mt||!rn.current)return;const q=Dt.current;if(!q)return;const we=document.activeElement,Oe=we?Pt.current?.contains(we):!1,It=we===document.body,Kt=we===Me.current;if(!Oe&&!It&&!Kt){rn.current=!1;return}if(Kt){q.focus({preventScroll:!0}),rn.current=!1;return}const fn=requestAnimationFrame(()=>{q.focus(),rn.current=!1});return()=>cancelAnimationFrame(fn)},[g,mt]),i.useEffect(()=>()=>{Ht.current.forEach(q=>{q.previewUrl&&URL.revokeObjectURL(q.previewUrl)})},[]);const ht=i.useCallback(()=>{R(!0),E("model"),O(m[0]?.id??""),A(F||P||"")},[m,P,F]),wt=i.useMemo(()=>m.find(q=>q.id===C)??null,[m,C]),Xe=i.useMemo(()=>{const q=ie.trim().toLowerCase();return(q?ce.filter(Oe=>Oe.name.toLowerCase().includes(q)):ce).slice(0,10)},[ce,ie]),Et=i.useMemo(()=>{const q=m.filter(It=>Ov(It.name,L));if(!u)return q;const we=q.filter(It=>u.memberIds.has(It.id));if(L.trim().length===0)return we;const Oe=q.filter(It=>!u.memberIds.has(It.id));return[...we,...Oe]},[m,L,u]),Zt=i.useMemo(()=>{const q=new Map;for(const we of m)q.set(we.name.toLowerCase(),we);return q},[m]);i.useEffect(()=>{W(0)},[Xe]),i.useEffect(()=>{Fe(0)},[L,fe]),i.useEffect(()=>()=>{yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null),Se.current!==null&&(window.clearTimeout(Se.current),Se.current=null)},[]),i.useEffect(()=>{if(!g)return;const q=Oe=>{const It=Oe.target;Pt.current?.contains(It)||Ot.current?.contains(It)||It.closest(".model-combobox-dropdown--portal")||x(!1)},we=Oe=>{Oe.key==="Escape"&&x(!1)};return document.addEventListener("mousedown",q),document.addEventListener("keydown",we),()=>{document.removeEventListener("mousedown",q),document.removeEventListener("keydown",we)}},[g,x]);const le=i.useCallback(()=>{const q=bt.current;if(!q)return;const Oe=q.scrollTop+q.clientHeight>=q.scrollHeight-50;re(!Oe),kt.current=!Oe},[]),lt=i.useCallback(q=>{if(!q.isConnected)return;let we=0,Oe=0,It=-1;const Kt=6,fn=()=>{if(q.isConnected){if(q.scrollTop=q.scrollHeight,q.scrollHeight===It?Oe+=1:(Oe=0,It=q.scrollHeight),we+=1,we>=Kt||Oe>=2){re(!1),kt.current=!1;return}window.requestAnimationFrame(fn)}};fn()},[]),nn=i.useCallback(()=>{const q=bt.current;q&<(q)},[lt]);i.useLayoutEffect(()=>{const q=ot?.id??null,we=$t.current;if($t.current={isOpen:g,sessionId:q},!g||!q)return;const Oe=!we.isOpen&&g,It=we.isOpen&&we.sessionId!==q;if(!Oe&&!It)return;const Kt=bt.current;Kt&<(Kt)},[g,ot?.id,lt]),i.useEffect(()=>{if(!v||!g||!ot)return;const q=()=>{const Oe=bt.current;Oe&<(Oe)},we=()=>{document.visibilityState==="visible"&&q()};return document.addEventListener("visibilitychange",we),window.addEventListener("pageshow",q),()=>{document.removeEventListener("visibilitychange",we),window.removeEventListener("pageshow",q)}},[v,g,ot,lt]),i.useEffect(()=>{g&&(kt.current||nn())},[gt,Lt,Yt,St,g,nn]);const Rn=i.useMemo(()=>{const q=new Map(m.map(Oe=>[Oe.id,Oe.name?.trim()||Oe.id])),we=new Map(D.map(Oe=>[`${Oe.provider}/${Oe.id}`,Oe.name?.trim()||""]));return mn.map((Oe,It)=>{const Kt=Oe.title?.trim()||`Session ${It+1}`;let fn=null;if(Oe.agentId&&Oe.agentId!==hr)fn=q.get(Oe.agentId)||Oe.agentId;else if(Oe.modelProvider&&Oe.modelId){const An=`${Oe.modelProvider}/${Oe.modelId}`,jn=we.get(An);fn=jn?`${jn} [${An}]`:An}return{id:Oe.id,label:fn?`${Kt} — ${fn}`:Kt}})},[m,D,mn]),Hn=i.useMemo(()=>S==="agent"?wt?`Message ${wt.name||wt.id}`:"Select an agent to start chatting":zt?`Message ${zt}`:"Select a model to start chatting",[S,wt,zt]),wn=i.useCallback(q=>{const we=mn.find(Oe=>Oe.id===q);we&&(we.modelProvider&&we.modelId?(j("model"),M(`${we.modelProvider}/${we.modelId}`)):(j("agent"),w(we.agentId)),ye(we))},[ye,mn]),rs=i.useCallback(async()=>{if(!Qt){if(z==="agent"){if(!I)return;j("agent"),w(I),await Ke(I)}else{const q=ro(U||F||P);if(!q)return;j("model"),M(`${q.modelProvider}/${q.modelId}`),await Ke(hr,q.modelProvider,q.modelId)}await ut(),R(!1),E("model")}},[P,I,z,U,ut,F,Qt,Ke]),_s=sn.length>50?`${sn.slice(0,50)}…`:sn,bn=i.useCallback(q=>{if(!q||q.length===0)return;const we=[];for(let Oe=0;Oe<q.length;Oe+=1){const It=q[Oe];nF(It)&&we.push({file:It,previewUrl:tF(It)?URL.createObjectURL(It):""})}we.length>0&&$e(Oe=>[...Oe,...we])},[]),Ut=i.useCallback(q=>{$e(we=>{const Oe=we[q];return Oe?.previewUrl&&URL.revokeObjectURL(Oe.previewUrl),we.filter((It,Kt)=>Kt!==q)})},[]),xs=i.useCallback(q=>{bn(q.clipboardData?.files)},[bn]),xn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Os)return;const q=Dt.current;!q||q.disabled||q.focus({preventScroll:!0})},[]),Xn=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Os||(an.current=!0)},[]),$n=i.useCallback(async()=>{const q=k.trim(),we=Ht.current;if(!(!q&&we.length===0)&&!mt){if(J(""),B(!1),pe(""),qe(-1),q==="/help"){de(!0),xn(),an.current=!1;return}if(q==="/clear"||q==="/new"){on(),ln(),we.forEach(Oe=>{Oe.previewUrl&&URL.revokeObjectURL(Oe.previewUrl)}),$e(Oe=>Oe.filter(It=>!we.includes(It)));try{if(S==="model"){const Oe=ro(se);if(!Oe)return;await Ke(hr,Oe.modelProvider,Oe.modelId)}else C&&await Ke(C)}catch{n("Failed to clear conversation","error")}finally{xn(),an.current=!1}return}try{de(!1),await Gt(q,we.map(Oe=>Oe.file)),we.forEach(Oe=>{Oe.previewUrl&&URL.revokeObjectURL(Oe.previewUrl)}),$e(Oe=>Oe.filter(It=>!we.includes(It)))}catch{}finally{xn(),an.current=!1}}},[n,S,ln,xn,mt,k,se,C,Gt,Ke,on]),vs=i.useCallback(q=>{q.preventDefault(),G.current+=1,Ue(!0)},[]),ms=i.useCallback(q=>{q.preventDefault(),q.dataTransfer.dropEffect="copy",Ue(!0)},[]),hs=i.useCallback(q=>{q.preventDefault(),G.current=Math.max(0,G.current-1),G.current===0&&Ue(!1)},[]),Jn=i.useCallback(q=>{q.preventDefault(),G.current=0,Ue(!1),bn(q.dataTransfer?.files)},[bn]),ps=i.useCallback((q,we)=>{const Oe=XO(q,we);if(Oe){B(!0),pe(Oe.filter),qe(Oe.start);return}B(!1),pe(""),qe(-1)},[]),Ns=i.useCallback(q=>{J(we=>{const Oe=gg(we);if(!Oe)return we;const It=`/skill:${q.name} `,Kt=we.slice(0,Oe.start)+It+we.slice(Oe.end);return window.requestAnimationFrame(()=>{Dt.current&&Dt.current.focus()}),Kt}),Y(!1),ee(""),W(0)},[]),Yn=i.useCallback(q=>{const we=Dt.current;if(!we||ae<0)return;const Oe=we.selectionStart??Nt.current,It=we.selectionEnd??Oe,Kt=Math.max(Oe,It),fn=Math.min(ae,Kt),jn=`${`@${q.name.replace(/\s+/g,"_")}`} `,En=k.slice(0,fn)+jn+k.slice(Kt),ts=fn+jn.length;J(En),B(!1),pe(""),Fe(0),qe(-1),window.requestAnimationFrame(()=>{Dt.current&&(Dt.current.focus(),Dt.current.setSelectionRange(ts,ts))})},[ae,k]),ys=i.useCallback(q=>{const we=q.target.value,Oe=q.target.selectionStart??we.length;Nt.current=Oe,J(we),Be&&we.trim().length>0&&de(!1),ps(we,Oe);const It=gg(we);It?(Y(!0),ee(It.filter)):(Y(!1),ee("")),Qe.detectMention(we,Oe),_e(Qe.mentionActive),Qe.mentionActive&&vt(q.target)},[Be,ps,Qe,vt]),ws=i.useCallback(()=>{if(an.current){window.requestAnimationFrame(()=>{xn()});return}typeof window<"u"&&window.innerWidth<=Os&&Pt.current&&(it.current=!0,Pt.current.style.removeProperty("--vv-height"),Pt.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{it.current=!1},450)),yt.current!==null&&window.clearTimeout(yt.current),yt.current=window.setTimeout(()=>{B(!1),pe(""),qe(-1),_e(!1),Qe.dismissMention(),yt.current=null},120),Se.current!==null&&window.clearTimeout(Se.current),Se.current=window.setTimeout(()=>{Y(!1),Se.current=null},120)},[Qe,xn]),Ms=i.useCallback(()=>{it.current=!1,yt.current!==null&&(window.clearTimeout(yt.current),yt.current=null),Se.current!==null&&(window.clearTimeout(Se.current),Se.current=null)},[]),X=i.useCallback(q=>{const we=q.currentTarget,Oe=we.selectionStart??we.value.length;Nt.current=Oe,ps(we.value,Oe),Qe.detectMention(we.value,Oe),_e(Qe.mentionActive),Qe.mentionActive&&vt(we)},[ps,Qe,vt]),_=i.useCallback(q=>{q.key!=="Escape"&&X(q)},[X]),ue=i.useCallback(q=>{nt(we=>{const Oe=new Set(we);return Oe.has(q)?Oe.delete(q):Oe.add(q),Oe})},[]),Ce=i.useCallback((q,we=!1)=>we?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:q}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ki,{remarkPlugins:[ji],components:Bv,children:q})}),[]),We=i.useCallback(q=>{if(Nt.current=q.currentTarget.selectionStart??Nt.current,Qe.mentionActive&&Qe.files.length>0){if(Qe.handleKeyDown(q,k),q.key==="Enter"||q.key==="Tab"){const we=Qe.files[Qe.selectedIndex];if(we){const Oe=Qe.selectFile(we,k);J(Oe),Qe.dismissMention(),_e(!1)}}return}if(fe&&q.key==="ArrowDown"){q.preventDefault(),Et.length>0&&Fe(we=>(we+1)%Et.length);return}if(fe&&q.key==="ArrowUp"){q.preventDefault(),Et.length>0&&Fe(we=>we===0?Et.length-1:we-1);return}if(fe&&q.key==="Enter"){q.preventDefault();const we=Et[ve]??Et[0];we&&Yn(we);return}if(fe&&q.key==="Escape"){q.preventDefault(),q.stopPropagation(),B(!1),pe(""),qe(-1);return}if(Ne&&Xe.length>0&&q.key==="ArrowDown"){q.preventDefault(),W(we=>(we+1)%Xe.length);return}if(Ne&&Xe.length>0&&q.key==="ArrowUp"){q.preventDefault(),W(we=>we===0?Xe.length-1:we-1);return}if(Ne&&(q.key==="Enter"||q.key==="Tab")){q.preventDefault();const we=Xe[oe]??Xe[0];we&&Ns(we);return}if(Ne&&q.key==="Escape"){q.preventDefault(),Y(!1),ee("");return}q.key!=="Enter"||q.shiftKey||(q.preventDefault(),$n())},[fe,Et,ve,Yn,$n,Qe,k,Ne,Xe,oe,Ns]),At=i.useCallback(()=>{if(Ae.current){Ae.current=!1;return}if(g){x(!1);return}typeof window<"u"&&window.innerWidth<=Os&&Me.current?.focus({preventScroll:!0}),x(!0)},[g,x]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:Me,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Ot,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":pt?"true":"false",style:{right:ge.x,bottom:ge.y},onPointerDown:ke,onClick:At,children:t.jsx(Ki,{size:24})}),g&&t.jsxs("div",{className:`quick-chat-panel${v&&y?" quick-chat-panel--keyboard-open":""}`,ref:Pt,"data-testid":"quick-chat-panel",style:{...at?{right:ge.x+Re.right,bottom:tt+Re.bottom,width:Rt.width,height:Rt.height}:{}},children:[at&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:be,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:be,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:be,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:be,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:be,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:be,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:be,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:be,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"}),S==="model"&&zt&&(()=>{const q=qt?.provider??ft?.modelProvider??"";return b==="mobile"&&zt.length>12&&q?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:zt,"aria-label":zt,children:t.jsx(Fn,{provider:q,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:zt,children:zt})})()]}),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:ht,disabled:Qt,children:t.jsx(Mn,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>x(!1),children:t.jsx(un,{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:ot?.id??"",onChange:q=>wn(q.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Qt?"Loading sessions…":"Select a session"}),Rn.map(q=>t.jsx("option",{value:q.id,children:q.label},q.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${z==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>E("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${z==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>E("agent"),children:"Agent"})]}),z==="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:I,onChange:q=>O(q.target.value),"data-testid":"quick-chat-new-agent-select",children:m.map(q=>t.jsx("option",{value:q.id,children:GO(q)},q.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(Is,{id:"quick-chat-new-model-select",models:D,value:U,onChange:A,label:"Select model override",placeholder:Z?"Loading models…":"Select a model",disabled:Z||D.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:()=>{R(!1),E("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void rs(),disabled:Qt||(z==="agent"?!I:!ro(U||F||P)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:bt,"data-testid":"quick-chat-messages",onScroll:le,children:Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):St?t.jsxs(t.Fragment,{children:[gt.map(q=>t.jsx(bg,{message:q,forcePlain:q.role!=="user"&&Pe.has(q.id),mentionAgentsByName:Zt,roomContext:u,onToggleRender:ue},q.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Ce("Available commands:\n- `/new` or `/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:[Lt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Ce(Lt,Pe.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Pe.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Pe.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>ue("__streaming__"),children:Pe.has("__streaming__")?t.jsx(Pu,{size:14}):t.jsx(Ir,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Yt?"Thinking…":"Connecting…"}),zv(tn,!0),Yt&&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:Yt})]})]})]}):yn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):gt.length===0&&!Lt&&!Yt&&!St&&!Be?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[gt.map(q=>t.jsx(bg,{message:q,forcePlain:q.role!=="user"&&Pe.has(q.id),mentionAgentsByName:Zt,roomContext:u,onToggleRender:ue},q.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Ce("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),me&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:nn,children:[t.jsx(pn,{size:14}),"Latest"]}),Ie.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Ie.map((q,we)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${we}`,children:[q.previewUrl?t.jsx("img",{src:q.previewUrl,alt:q.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:q.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${we}`,"aria-label":`Remove ${q.file.name}`,onClick:()=>Ut(we),children:"×"})]},`${q.file.name}-${we}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${st?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:vs,onDragOver:ms,onDragLeave:hs,onDrop:Jn,children:[t.jsx("input",{ref:Ft,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:q=>{bn(q.target.files),q.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:()=>Ft.current?.click(),children:t.jsx(Xg,{size:16})}),t.jsx("input",{ref:Dt,type:"text",value:k,onChange:ys,onKeyDown:We,onKeyUp:_,onClick:X,onBlur:ws,onFocus:Ms,onPaste:xs,onTouchStart:q=>{typeof window>"u"||window.innerWidth>Os||document.activeElement!==q.currentTarget&&(q.preventDefault(),q.currentTarget.focus({preventScroll:!0}))},placeholder:Hn,disabled:mt,"data-testid":"quick-chat-input"}),St?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:q=>{typeof window>"u"||window.innerWidth>Os||(q.preventDefault(),q.pointerType&&q.pointerType!=="mouse"&&(Xt.current=!0,on()))},onTouchStart:q=>{typeof window>"u"||window.innerWidth>Os||(q.preventDefault(),Xt.current=!0,on())},onMouseDown:q=>{typeof window>"u"||window.innerWidth>Os||q.preventDefault()},onClick:()=>{if(Xt.current){Xt.current=!1;return}on()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(Ii,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:q=>{typeof window>"u"||window.innerWidth>Os||(q.preventDefault(),q.pointerType&&q.pointerType!=="mouse"&&(Xt.current=!0,Xn(),xn(),$n()))},onTouchStart:q=>{typeof window>"u"||window.innerWidth>Os||(q.preventDefault(),Xt.current=!0,Xn(),xn(),$n())},onMouseDown:q=>{typeof window>"u"||window.innerWidth>Os||q.preventDefault()},onClick:()=>{if(Xt.current){Xt.current=!1;return}$n()},disabled:mt||k.trim().length===0&&Ie.length===0,"data-testid":"quick-chat-send",children:t.jsx(Ia,{size:16})})]}),t.jsx(LO,{agents:m,filter:L,highlightedIndex:ve,visible:fe,onSelect:Yn,position:"above",roomMemberIds:u?.memberIds,roomName:u?.roomName}),t.jsx(VO,{visible:Qe.mentionActive&&!fe,position:xt,files:Qe.files,selectedIndex:Qe.selectedIndex,onSelect:q=>{const we=Qe.selectFile(q,k);J(we),Qe.dismissMention(),_e(!1),Dt.current?.focus()},loading:Qe.loading}),Ne&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:He?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):Xe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:ie?"No skills found":"No skills available"}):Xe.map((q,we)=>t.jsxs("button",{type:"button",role:"option","aria-selected":we===oe,className:`chat-skill-menu-item${we===oe?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Oe=>Oe.preventDefault(),onMouseEnter:()=>W(we),onClick:()=>Ns(q),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:q.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:q.relativePath,children:q.relativePath})]},q.id))}),sn&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${_s}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:ln,children:"×"})]})]})})]})]})}function oo(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function xg(e){return e.status==="generating"||e.status==="awaiting_input"}function lo(e){return e==="complete"||e==="error"}function rF(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Or(),u=i.useCallback(()=>{zu(e).then(p=>{const g=p.filter(y=>{const b=oo(y.updatedAt),v=r.current.get(y.id);return v===void 0?!0:b<=v?!1:(r.current.delete(y.id),!0)}),x=new Map;for(const y of g)x.set(y.id,oo(y.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(y=>[y.id,y]));for(const y of o.values()){if(e&&y.projectId&&y.projectId!==e)continue;const b=y.lastEventTimestamp,v=a.current.get(y.sessionId)??0;if(b<v)continue;const S=r.current.get(y.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!lo(y.status)&&r.current.delete(y.sessionId),lo(y.status)){x.delete(y.sessionId)&&(g=!0),a.current.set(y.sessionId,b);continue}const j=x.get(y.sessionId),C=y.type??j?.type,w=y.title??j?.title;if(!j&&(!C||!w))continue;const N={id:y.sessionId,type:C??"planning",status:y.status,title:w??"AI Session",projectId:y.projectId??j?.projectId??e??null,lockedByTab:y.owningTabId??j?.lockedByTab??null,updatedAt:y.updatedAt??j?.updatedAt??new Date(b).toISOString()},R=x.get(y.sessionId);(!R||R.status!==N.status||R.title!==N.title||R.type!==N.type||R.projectId!==N.projectId||R.lockedByTab!==N.lockedByTab||R.updatedAt!==N.updatedAt)&&(x.set(y.sessionId,N),a.current.set(y.sessionId,b),g=!0)}return g?[...x.values()].sort((y,b)=>oo(b.updatedAt)-oo(y.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=y=>{try{const b=JSON.parse(y.data),v=oo(b.updatedAt)||Date.now();s(S=>{const j=a.current.get(b.id)??0;if(v<j)return S;const C=r.current.get(b.id);if(C!==void 0&&v<=C)return S;if(C!==void 0&&v>C&&!lo(b.status)&&r.current.delete(b.id),a.current.set(b.id,v),lo(b.status))return S.filter(N=>N.id!==b.id);const w=S.findIndex(N=>N.id===b.id);if(w>=0){const N=[...S];return N[w]=b,N}return xg(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:v}),lo(b.status)&&c({sessionId:b.id,status:b.status,timestamp:v})}catch{}},x=y=>{try{const b=JSON.parse(y.data),v=Date.now();r.current.set(b,v),a.current.set(b,Math.max(a.current.get(b)??0,v)),c({sessionId:b,status:"complete",timestamp:v}),s(S=>S.filter(j=>j.id!==b))}catch{}};return hi(`/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,y=qa();let b=!1;if(x==="planning")try{await lb(p,e,y)}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 ub(p,e,y)}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 gb(p,e,y)}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 v=Date.now();r.current.set(p,v),a.current.set(p,Math.max(a.current.get(p)??0,v)),c({sessionId:p,status:"complete",timestamp:v});try{await bb(p)}catch{}s(S=>S.filter(j=>j.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>xg(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 rc="fusion:hide-session-banners",Ru="fusion:session-banner-pref-changed";function oF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(rc)==="1"}catch{return!1}}function lF(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===rc&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Ru,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Ru,s)}}function n8(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(rc,"1"):window.localStorage.removeItem(rc),window.dispatchEvent(new Event(Ru))}catch{}}function cF(){return i.useSyncExternalStore(lF,oF,()=>!1)}function As(e){return{...e,column:Mb(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function vg(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function dF(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 qd(e,n){if(vg(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return dF(e,n);const a=vg(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 uF(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),y=i.useRef(n);u.current=r,f.current=s,y.current!==n&&(y.current=n,x.current++);const b=1e3,v=i.useCallback(async ne=>{const F=++m.current,M=n,P=ne?.searchQueryOverride??f.current,$=ne?.includeArchivedOverride??d.current;try{const k=await Ej(void 0,void 0,M,P,$);if(m.current!==F||n!==M)return;o(k.map(As)),g.current=Date.now()}catch{if(m.current!==F||n!==M)return;if(ne?.clearOnError){o([]);return}o(k=>k)}},[n]);p.current=v;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),j=i.useRef(s);i.useEffect(()=>{if(s===void 0&&j.current===void 0)return;j.current=s;const ne=setTimeout(()=>{v({searchQueryOverride:s})},300);return()=>clearTimeout(ne)},[s]),i.useEffect(()=>{v({clearOnError:!0});const ne=()=>{if(document.visibilityState!=="visible")return;const F=Date.now();F-h.current<b||(h.current=F,v())};return document.addEventListener("visibilitychange",ne),()=>{document.removeEventListener("visibilitychange",ne)}},[v]),i.useEffect(()=>{if(a===!1)return;const ne=x.current,F=n?`?projectId=${encodeURIComponent(n)}`:"",M=()=>x.current!==ne;let P=!0;const $=xe=>{if(M())return;const Ne=As(JSON.parse(xe.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(Y=>{const ie=Y.findIndex(L=>L.id===Ne.id);if(ie===-1)return[...Y,Ne];const ee=Y[ie],oe=qd(ee,Ne);if(oe===ee)return Y;const W=[...Y];return W[ie]=oe,W}),g.current=Date.now()},k=xe=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ne,to:Y}=JSON.parse(xe.data),ie=As(Ne),ee={...ie,column:Mb(Y,ie.column)};o(oe=>{const W=oe.findIndex(pe=>pe.id===ee.id);if(W===-1)return[...oe,ee];const L=[...oe];return L[W]=ee,L}),g.current=Date.now()},J=xe=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ne=As(JSON.parse(xe.data));o(Y=>{const ie=Y.findIndex(L=>L.id===Ne.id);if(ie===-1)return[...Y,Ne];const ee=Y[ie],oe=qd(ee,Ne);if(oe===ee)return Y;const W=[...Y];return W[ie]=oe,W}),g.current=Date.now()},ce=xe=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const Ne=As(JSON.parse(xe.data));o(Y=>Y.filter(ie=>ie.id!==Ne.id))},je=xe=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:Ne}=JSON.parse(xe.data),ie={...As(Ne),column:"done"};o(ee=>{const oe=ee.findIndex(L=>L.id===ie.id);if(oe===-1)return[...ee,ie];const W=[...ee];return W[oe]=ie,W})},He=hi(`/api/events${F}`,{events:{"task:created":$,"task:moved":k,"task:updated":J,"task:deleted":ce,"task:merged":je},onReconnect:()=>{P&&(M()||p.current())}});return()=>{P=!1,He()}},[n,a]);const C=i.useCallback(async ne=>{const F=As(await ib(ne,n));return o(M=>M.some(P=>P.id===F.id)?M:[...M,F]),F},[n]),w=i.useCallback(async(ne,F,M)=>As(await Mj(ne,F,n,M)),[n]),N=i.useCallback(async ne=>As(await ab(ne,n)),[n]),R=i.useCallback(async(ne,F)=>As(await Aj(ne,n,F)),[n]),z=i.useCallback(async ne=>Rj(ne,n),[n]),E=i.useCallback(async ne=>As(await Ij(ne,n)),[n]),I=i.useCallback(async ne=>As(await Tj(ne,n)),[n]),O=i.useCallback(async ne=>{const F=As(await Pj(ne,n));return o(M=>M.some(P=>P.id===F.id)?M:[...M,F]),F},[n]),U=i.useCallback(async(ne,F)=>{const M=u.current.find($=>$.id===ne),P=M?{...M,...F,updatedAt:new Date().toISOString()}:void 0;P&&o($=>$.map(k=>k.id===ne?P:k));try{const $=As(await Hs(ne,F,n));return o(k=>k.map(J=>J.id===ne?$:J)),$}catch($){throw M&&o(k=>k.map(J=>J.id===ne?M:J)),$}},[n]),A=i.useCallback(async ne=>{const F=As(await Dj(ne,n));return o(M=>M.map(P=>P.id===ne?F:P)),F},[n]),D=i.useCallback(async ne=>{const F=As(await Lj(ne,n));return o(M=>M.map(P=>P.id===ne?F:P)),F},[n]),K=i.useCallback(async()=>{const F=(await Oj(n)).map(As);return o(M=>M.map(P=>F.find(k=>k.id===P.id)||P)),F},[n]),Z=i.useCallback(ne=>{if(ne.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const F=ne.map(As);o(M=>{let P=M;for(const $ of F){const k=P.findIndex(je=>je.id===$.id);if(k===-1){P===M&&(P=[...M]),P.push($);continue}const J=P[k],ce=qd(J,$);ce!==J&&(P===M&&(P=[...M]),P[k]=ce)}return P}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:w,pauseTask:N,deleteTask:R,mergeTask:z,retryTask:E,resetTask:I,duplicateTask:O,updateTask:U,archiveTask:A,unarchiveTask:D,archiveAllDone:K,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:Z,lastFetchTimeMs:g.current}}const mF=5e3,hF=1e3;function pF(e){const s=(ZS(e)?e.nodeMappings??e.projectNodeMappings??e.pathMappings??[]:[]).filter(a=>!!a?.nodeId&&!!a?.path).map(a=>({nodeId:a.nodeId,nodeName:a.nodeName,path:a.path,available:a.available!==!1}));return s.length>0?s:e.nodeId&&e.path?[{nodeId:e.nodeId,nodeName:e._sourceNodeName,path:e.path,available:!0}]:[]}function yg(e){return e.map(n=>({...n,nodeMappings:pF(n)}))}function fF(){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 Xm();n(yg(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 y=await Xm(),b=yg(y),v=Math.round(performance.now()-x);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${v}ms (${b.length} projects)`),f||(n(b),o(null))}catch(y){const b=Math.round(performance.now()-x);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${y instanceof Error?y.message:String(y)}`),f||o(y instanceof Error?y.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<hF||(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()},mF),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await o1(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await p1(f,p);return n(x=>x.map(y=>y.id===f?g:y)),g},[]),h=i.useCallback(async f=>{await hb(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 gF="kb-dashboard-current-project";function bF(e){return e??"local"}function xF(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=bF(s);i.useEffect(()=>{let p=!1;async function g(){try{const x=await Yi();if(p)return;u.current=x.dashboardCurrentProjectIdByNode??{};const y=u.current[m];if(y){const b=e.find(v=>v.id===y);b&&(r(b),c.current=!0)}if(!y)try{const b=localStorage.getItem(gF);if(b){const v=JSON.parse(b);v?.id&&e.some(j=>j.id===v.id)&&(r(v),c.current=!0,u.current={...u.current,[m]:v.id},await Dn({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(y=>y.status==="active");r(x||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,Dn({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,Dn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Dn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Uv=i.createContext(null);function vF({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(Uv.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function yF(){const e=i.useContext(Uv);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const Hv="kb-dashboard-theme-mode",qv="kb-dashboard-color-theme",Vv="kb-dashboard-font-scale-pct",Iu=100,wF=85,kF=125,Wv=[...EC],Tu="theme-data",co="theme-data.css";function jF(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${co}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${co}`:e.replace(/\/[^/]+$/,`/${co}`):`/${co}`:`/${co}`}const Qs=typeof window<"u",NF=Qs?i.useLayoutEffect:i.useEffect;function Kv(e){return e==="dark"||e==="light"||e==="system"}function wg(){if(!Qs)return"dark";try{const e=localStorage.getItem(Hv);if(Kv(e))return e}catch{}return"dark"}function kg(){if(!Qs)return"default";try{const e=localStorage.getItem(qv);if(e&&Wv.includes(e))return e}catch{}return"default"}function jg(e){if(Qs)try{localStorage.setItem(Hv,e)}catch{}}function Ng(e){if(Qs)try{localStorage.setItem(qv,e)}catch{}}function Io(e){return typeof e!="number"||!Number.isFinite(e)?Iu:Math.min(kF,Math.max(wF,Math.round(e)))}function Sg(){if(!Qs)return Iu;try{const e=Number(localStorage.getItem(Vv));return Io(e)}catch{return Iu}}function Cg(e){if(Qs)try{localStorage.setItem(Vv,String(Io(e)))}catch{}}function SF(e,n){return e==="system"?n?"dark":"light":e}function CF(e,n,s,a){if(!Qs)return;const r=SF(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Io(s)}%`}function Eg(){if(!Qs)return;const e=jF(),n=document.getElementById(Tu);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=Tu,document.head.appendChild(s)}function _g(){if(!Qs)return;const e=document.getElementById(Tu);e&&e.remove()}function EF(){const[e,n]=i.useState(()=>wg()),[s,a]=i.useState(()=>kg()),[r,o]=i.useState(()=>Sg()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Qs?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(!Qs||!l)return;let S=!1;return Yi().then(j=>{if(!S&&(Kv(j.themeMode)&&!p.current&&(m.current!==j.themeMode&&(m.current=j.themeMode,n(j.themeMode)),wg()!==j.themeMode&&jg(j.themeMode)),j.colorTheme&&Wv.includes(j.colorTheme)&&!g.current&&(h.current!==j.colorTheme&&(h.current=j.colorTheme,a(j.colorTheme)),kg()!==j.colorTheme&&Ng(j.colorTheme)),!x.current)){const C=Io(j.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),Sg()!==C&&Cg(C)}}).catch(j=>{console.warn("[useTheme] Failed to hydrate theme from global settings",j)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Qs)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),j=C=>{u(C.matches)};return S.addEventListener("change",j),()=>S.removeEventListener("change",j)},[]),NF(()=>{CF(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Qs||l||(s!=="default"?Eg():_g())},[s,l]);const y=i.useCallback(S=>{p.current=!0,m.current=S,n(S),jg(S),Dn({themeMode:S}).catch(j=>{console.warn("[useTheme] Failed to persist themeMode to global settings",j)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),Ng(S),S!=="default"?Eg():_g(),Dn({colorTheme:S}).catch(j=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",j)})},[]),v=i.useCallback(S=>{const j=Io(S);x.current=!0,f.current=j,o(j),Cg(j),Dn({dashboardFontScalePct:j}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:y,setColorTheme:b,setDashboardFontScalePct:v,isSystemDark:d}}function _F(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),[y,b]=i.useState(null),[v,S]=i.useState("definition"),[j,C]=i.useState(null),[w,N]=i.useState(!1),[R,z]=i.useState(void 0),[E,I]=i.useState(!1),[O,U]=i.useState(!1),[A,D]=i.useState(!1),[K,Z]=i.useState(null),[ne,F]=i.useState(!1),[M,P]=i.useState(!1),[$,k]=i.useState(void 0),[J,ce]=i.useState(!1),[je,He]=i.useState(!1),[xe,Ne]=i.useState("project"),[Y,ie]=i.useState(!1),[ee,oe]=i.useState(!1),[W,L]=i.useState(!1),[pe,fe]=i.useState(!1),[B,ve]=i.useState(!1),[Fe,ae]=i.useState(!1),[qe,Pe]=i.useState(!1),nt=!!(y||w||s||r||m||M||J||je||Y||ee||W||B||pe||A||ne||E||O||Fe||qe),Be=i.useCallback(()=>a(!0),[]),de=i.useCallback(()=>a(!1),[]),Ie=i.useCallback(()=>o(!0),[]),$e=i.useCallback(bt=>{c(bt),o(!0)},[]),st=i.useCallback(()=>{const bt=n[0];bt&&(u(bt.id),o(!0))},[n]),Ue=i.useCallback(bt=>{u(bt),o(!0)},[]),me=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),re=i.useCallback(bt=>{p(bt),h(!0)},[]),_e=i.useCallback(bt=>{x(bt),h(!0)},[]),xt=i.useCallback(()=>{h(!1),p(null),x(void 0)},[]),dt=i.useCallback((bt,Dt="definition",Ft)=>{b(bt),S(Dt),C(Ft?.origin??null)},[]),Qe=i.useCallback(bt=>{b(bt),S("changes"),C(null)},[]),vt=i.useCallback(bt=>{b(Dt=>Dt&&{...Dt,...bt})},[]),Ae=i.useCallback(()=>{b(null),C(null)},[]),Je=i.useCallback(bt=>{z(bt),N(!0)},[]),ct=i.useCallback(()=>{N(!1),z(void 0)},[]),Nt=i.useCallback(()=>I(!0),[]),yt=i.useCallback(()=>I(!1),[]),Se=i.useCallback(()=>U(!0),[]),G=i.useCallback(()=>U(!1),[]),ge=i.useCallback(bt=>{Z(bt??null),D(!0)},[]),pt=i.useCallback(()=>{D(!1),Z(null)},[]),ke=i.useCallback(()=>F(!0),[]),tt=i.useCallback(()=>F(!1),[]),Rt=i.useCallback(()=>{P(bt=>!bt)},[]),Re=i.useCallback(()=>{P(!1),k(void 0)},[]),be=i.useCallback(()=>ce(!0),[]),at=i.useCallback(()=>ce(!1),[]),ot=i.useCallback(()=>He(!0),[]),gt=i.useCallback(()=>He(!1),[]),St=i.useCallback(bt=>{Ne(bt)},[]),Lt=i.useCallback(()=>ie(!0),[]),Yt=i.useCallback(()=>ie(!1),[]),tn=i.useCallback(()=>oe(!0),[]),mn=i.useCallback(()=>oe(!1),[]),Qt=i.useCallback(()=>L(!0),[]),yn=i.useCallback(()=>L(!1),[]),Gt=i.useCallback(()=>fe(!0),[]),on=i.useCallback(()=>fe(!1),[]),sn=i.useCallback(()=>ve(!0),[]),ln=i.useCallback(()=>ve(!1),[]),Wt=i.useCallback(async(bt,Dt)=>{ve(!1),k(Dt),P(!0)},[]),ye=i.useCallback(()=>ae(!0),[]),Le=i.useCallback(()=>ae(!1),[]),Ke=i.useCallback(()=>Pe(!0),[]),ut=i.useCallback(()=>Pe(!1),[]),Ve=i.useCallback((bt,Dt)=>{Dt(`Created ${bt.id} from planning mode`,"success"),o(!1),c(null)},[]),Pt=i.useCallback((bt,Dt)=>{const Ft=bt.map(Ht=>Ht.id).join(", ");Dt(`Created ${Ft} from planning mode`,"success"),o(!1),c(null)},[]),Ot=i.useCallback((bt,Dt)=>{const Ft=bt.map(Ht=>Ht.id).join(", ");Dt(`Created ${Ft} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:y,detailTaskInitialTab:v,detailTaskOrigin:j,settingsOpen:w,settingsInitialSection:R,schedulesOpen:E,githubImportOpen:O,usageOpen:A,usageAnchorRect:K,systemStatsOpen:ne,terminalOpen:M,terminalInitialCommand:$,filesOpen:J,todosOpen:je,fileBrowserWorkspace:xe,activityLogOpen:Y,gitManagerOpen:ee,workflowStepsOpen:W,agentsOpen:pe,scriptsOpen:B,setupWizardOpen:Fe,modelOnboardingOpen:qe,anyModalOpen:nt,openNewTask:Be,closeNewTask:de,openPlanning:Ie,openPlanningWithInitialPlan:$e,resumePlanning:st,openPlanningWithSession:Ue,closePlanning:me,openSubtaskBreakdown:re,openSubtaskWithSession:_e,closeSubtask:xt,openDetailTask:dt,openDetailWithChangesTab:Qe,updateDetailTask:vt,closeDetailTask:Ae,openSettings:Je,closeSettings:ct,openSchedules:Nt,closeSchedules:yt,openGitHubImport:Se,closeGitHubImport:G,openUsage:ge,closeUsage:pt,openSystemStats:ke,closeSystemStats:tt,toggleTerminal:Rt,closeTerminal:Re,openFiles:be,closeFiles:at,openTodos:ot,closeTodos:gt,setFileWorkspace:St,openActivityLog:Lt,closeActivityLog:Yt,openGitManager:tn,closeGitManager:mn,openWorkflowSteps:Qt,closeWorkflowSteps:yn,openAgents:Gt,closeAgents:on,openScripts:sn,closeScripts:ln,runScript:Wt,openSetupWizard:ye,closeSetupWizard:Le,openModelOnboarding:Ke,closeModelOnboarding:ut,onPlanningTaskCreated:Ve,onPlanningTasksCreated:Pt,onSubtaskTasksCreated:Ot}}function MF(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(7200*1e3),[x,y]=i.useState(!1),[b,v]=i.useState(!1),[S,j]=i.useState(!1),[C,w]=i.useState({}),[N,R]=i.useState(!1),[z,E]=i.useState(!1),[I,O]=i.useState(!1),[U,A]=i.useState(!1),[D,K]=i.useState(!0),Z=i.useCallback(async()=>{const[k,J]=await Promise.allSettled([Bj(e),gc(e)]);if(k.status==="fulfilled"&&(s(k.value.maxConcurrent),r(k.value.rootDir)),J.status==="fulfilled"){const ce=J.value;l(!!ce.autoMerge),d(!!ce.globalPause),m(!!ce.enginePaused),v(!!ce.prAuthAvailable),f(ce.taskStuckTimeoutMs),g(ce.staleHighFanoutBlockerAgeThresholdMs??7200*1e3),y(ce.showQuickChatFAB===!0),w(ce.experimentalFeatures??{});const je=ce.experimentalFeatures??{};R(je.insights===!0),E(je.memoryView===!0),O(je.devServerView===!0||je.devServer===!0),A(je.todoView===!0);const He=ce.autoReloadOnVersionChange!==!1;K(He),Tc(He)}j(!0)},[e]);i.useEffect(()=>{j(!1),w({}),R(!1),E(!1),O(!1),A(!1),Z()},[Z]);const ne=i.useCallback(async()=>{const k=!o;l(k);try{await Xo({autoMerge:k},e)}catch{l(!k)}},[o,e]),F=i.useCallback(async()=>{const k=!c;d(k);try{await Xo({globalPause:k,globalPauseReason:k?"manual":void 0},e)}catch{d(!k)}},[c,e]),M=i.useCallback(async()=>{const k=!u;m(k);try{await Xo({enginePaused:k},e)}catch{m(!k)}},[u,e]),P=i.useCallback(async()=>{const k=!x;y(k);try{await Xo({showQuickChatFAB:k},e)}catch{y(!k)}},[x,e]),$=i.useCallback(async()=>{const k=!D;K(k),Tc(k);try{await Dn({autoReloadOnVersionChange:k})}catch{K(!k),Tc(!k)}},[D]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,staleHighFanoutBlockerAgeThresholdMs:p,showQuickChatFAB:x,prAuthAvailable:b,settingsLoaded:S,experimentalFeatures:C,insightsEnabled:N,memoryEnabled:z,devServerEnabled:I,todosEnabled:U,autoReloadOnVersionChange:D,toggleAutoMerge:ne,toggleGlobalPause:F,toggleEnginePause:M,toggleShowQuickChatFAB:P,toggleAutoReloadOnVersionChange:$,refresh:Z}}function AF(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(!1),h=i.useRef(null);return i.useEffect(()=>{if(!m.current){const b=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(b){const v=b[1];if(/^[A-Z]+-\d+$/.test(v)){const S=new URLSearchParams(window.location.search);S.set("task",v);const j=S.toString(),C=window.history.state??{};window.history.replaceState(C,"",j?`/?${j}`:"/"),m.current=!0}}}const p=new URLSearchParams(window.location.search),g=p.get("project"),x=p.get("task");if(!x||a)return;if(g){const b=s.find(v=>v.id===g);if(!b){l(`Project '${g}' not found`,"error");return}r?.id!==b.id&&o(b)}if(u.current)return;u.current=!0,La(x,g??n).then(b=>{c(b),h.current=x}).catch(()=>{l(`Task ${x} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(h.current){const p=new URLSearchParams(window.location.search);p.delete("task");const g=p.toString(),x=window.history.state??{};window.history.replaceState(x,"",g?`${window.location.pathname}?${g}`:window.location.pathname),h.current=null}d()},[d])}}function RF(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Ks().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 Dn({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 Dn({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 IF({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;Co().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return Yi().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!Ar()?l=!0:!u&&!Ar()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ci("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ci("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Mg="kb-update-banner-dismissed";function TF(){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(Mg)==="true";u(h);let f=!1;return Uj().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(Mg,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const PF=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server","stash-recovery"];function $F(e){return e!==null&&PF.includes(e)}function Vd(e){return e!==null&&($F(e)||pr(e))}const DF=Wo("fusion-plugin-roadmap","roadmaps");function Ag(e){return e==="devserver"?"dev-server":e}function Rg(e){return e!=="roadmaps"?"board":Nb("fusion-plugin-roadmap","roadmaps")?DF:"board"}function LF(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=Bn("kb-dashboard-task-view");return b==="roadmaps"?Rg(b):Vd(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=Bn("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(Rg(b));else if(Vd(b)){const v=!g.current&&b==="devserver";p(v?"devserver":Ag(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{us("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{if(typeof window>"u")return;const b=new URLSearchParams(window.location.search).get("view");b&&Vd(b)&&p(Ag(b))},[]),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)},[]),y=i.useCallback(()=>{const b=["dark","light","system"],v=b.indexOf(d),S=b[(v+1)%b.length];u(S)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:y}}function OF(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 Wd=new Map,FF=6e4;function zF(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";Wd.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=Wd.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 M0(e);if(f)return;Wd.set(h,{views:x,expiresAt:Date.now()+FF}),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 BF({taskView:e,context:n}){return t.jsx(pC,{viewId:e,context:n})}let Ig=!1;function Rr(e,n){return function(){return i.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function UF(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",a=(await Sn(()=>import("./dashboard-view-Ws9_ZnKu.js"),__vite__mapDeps([24,1,25,5,6,26])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Rr(e,n)})}async function HF(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",a=(await Sn(()=>import("./dashboard-view-BWGH_fAq.js"),__vite__mapDeps([27,1,25,28])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Rr(e,n)})}async function qF(){const e="@fusion-plugin-examples/cli-printing-press/dashboard-view",n="CliPrintingPressWizardView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Rr(e,n)})}catch{return{default:Rr(e,n)}}}async function VF(){const e="@fusion-plugin-examples/cli-printing-press/manage-view",n="CliPrintingPressManageView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Rr(e,n)})}catch{return{default:Rr(e,n)}}}function Gv(){Ig||(Ig=!0,sl("fusion-plugin-dependency-graph","graph",i.lazy(UF)),sl("fusion-plugin-roadmap","roadmaps",i.lazy(HF)),sl("fusion-plugin-cli-printing-press","wizard",i.lazy(qF)),sl("fusion-plugin-cli-printing-press","manage",i.lazy(VF)))}function WF(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(R=>{n(R),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),x=i.useCallback(()=>{u()},[u]),y=i.useCallback(()=>{m()},[m]),b=i.useCallback(R=>{h(),n(R),a("project"),d(`Project ${R.name} registered successfully`,"success"),o()},[h,n,a,d,o]),v=i.useCallback(()=>{f()},[f]),S=i.useCallback(async R=>{try{await m1(R.id),d(`Project ${R.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${R.name}`,"error")}},[d,o]),j=i.useCallback(async R=>{try{await h1(R.id),d(`Project ${R.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${R.name}`,"error")}},[d,o]),C=i.useCallback(async R=>{try{await hb(R.id),d(`Project ${R.name} removed`,"success"),r?.id===R.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${R.name}`,"error")}},[r,s,a,d,o]),w=i.useCallback(async R=>{try{await l(R)}catch{d("Failed to update favorites","error")}},[l,d]),N=i.useCallback(async R=>{try{await c(R)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:x,handleAddProject:y,handleSetupComplete:b,handleModelOnboardingComplete:v,handlePauseProject:S,handleResumeProject:j,handleRemoveProject:C,handleToggleFavorite:w,handleToggleModelFavorite:N}}function KF(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}}function GF(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 v=[L0(e),O0(e)];s&&(v.push(F0(e,s,a)),v.push(z0(e,s)));const S=await Promise.allSettled(v);if(b.signal.aborted)return;const j=S[0],C=S[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(u(j.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.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(v){b.signal.aborted||(p(v instanceof Error?v.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(x(),()=>{g.current?.abort()}),[x]);const y=i.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:y}}function JF(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 hi(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 YF="fusion-dashboard-current-node",Jv=i.createContext(null);function QF({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 Yi();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(YF);if(g){const x=JSON.parse(g);x?.id&&x?.type==="remote"&&(l.current=x.id,await Dn({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,Dn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Dn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Dn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(Jv.Provider,{value:u,children:e})}function XF(){const e=i.useContext(Jv);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const ZF=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],ez=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let oc=null,Tg=!1;function tz(e){if(typeof e=="boolean")return e;if(typeof e=="string"){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1}}function nz(e){if(!(typeof e!="string"||e.trim().length===0))try{const n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString().replace(/\/$/,"")}catch{return}}function Yv(e){if(e==="browser"||e==="desktop-shell"||e==="mobile-shell")return e;if(e==="desktop")return"desktop-shell";if(e==="mobile")return"mobile-shell"}function sz(e){return e==="local"||e==="remote"?e:void 0}function Qv(e){const n=sz(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=nz(e.serverUrl),r=tz(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function iz(e){for(const n of ez){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=Yv(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:Qv({kind:r,mode:a.mode??a.shellMode,connectionId:a.connectionId??a.profileId,serverUrl:a.serverUrl??a.serverBaseUrl,canOpenConnectionManager:a.canOpenConnectionManager??a.shellCanOpenConnectionManager})}return null}function az(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=Yv(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:Qv({kind:a,mode:s.get("mode")??s.get("shellMode"),connectionId:s.get("connectionId")??s.get("profileId"),serverUrl:s.get("serverUrl")??s.get("serverBaseUrl"),canOpenConnectionManager:s.get("canOpenConnectionManager")??s.get("shellCanOpenConnectionManager")}):null}function rz(e){try{const n=new URL(e.location.href);let s=!1;for(const r of ZF)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const a=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",a)}catch{}}function oz(e=window){const n=iz(e);if(n)return n;const s=az(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function Xv(e=window){return!Tg&&typeof window<"u"&&(oc=oz(e),rz(e),Tg=!0),oc??{kind:"browser"}}function lz(){return oc||(typeof window>"u"?{kind:"browser"}:Xv(window))}const cz={kind:"browser"},Zv=i.createContext({host:cz,isNativeShell:!1,kind:"browser"});function dz(e){const n=e.kind!=="browser";return{host:e,isNativeShell:n,kind:e.kind,...n?{mode:e.mode,connectionId:e.connectionId,serverUrl:e.serverUrl,canOpenConnectionManager:e.canOpenConnectionManager}:{}}}function uz({children:e}){const n=i.useMemo(()=>dz(lz()),[]);return t.jsx(Zv.Provider,{value:n,children:e})}function mz(){return i.useContext(Zv)}function hz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function pz({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),[y,b]=i.useState(!1),v=s.host==="desktop-shell";i.useEffect(()=>{v&&o(s.desktopMode??"remote")},[v,s.desktopMode]);const S=i.useMemo(()=>v&&r==="local"?!0:d.trim().length>0,[v,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."}),v&&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"})]}),(!v||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null),x(!0);try{const j=await n.startQrScan();u(j.serverUrl),h(j.authToken??"")}catch(j){p(j.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:j=>c(j.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:j=>u(j.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:j=>h(j.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||y,onClick:async()=>{p(null),b(!0);try{if(v&&r==="local"){await n.setDesktopMode("local"),a();return}const j=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(v&&await n.setDesktopMode("remote"),await n.setActiveProfile(j.id),typeof window<"u"&&s.host!=="web"){window.location.href=hz(j.serverUrl,j.authToken??null);return}a()}catch(j){p(j.message)}finally{b(!1)}},children:y?"Saving…":"Continue"})})]})}):null}function fz({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(w=>w.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState(null),[c,d]=i.useState({}),[u,m]=i.useState(null),[h,f]=i.useState(null);if(!e)return null;const p=o==="__new__",g=p?null:s.profiles.find(w=>w.id===o)??r,x=c.name??g?.name??"",y=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",v=()=>{l(null),d({}),f(null)},S=async()=>{f(null);try{const w=new URL(y.trim());if(!/^https?:$/.test(w.protocol))throw new Error("Server URL must use http or https");const N=await n.saveProfile({id:p?void 0:o??g?.id,name:x||"Remote Server",serverUrl:y,authToken:b||null});await n.setActiveProfile(N.id),l(N.id),d({})}catch(w){f(w.message)}},j=async()=>{f(null);try{const w=await n.startQrScan();l("__new__"),d({name:"",serverUrl:w.serverUrl,authToken:w.authToken??""})}catch(w){f(w.message)}},C=async()=>{u&&(await n.deleteProfile(u.id),m(null),v())};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.length===0?t.jsxs("div",{className:"card native-shell-connection-manager__empty-state",children:[t.jsx("p",{className:"settings-muted",children:"No remote servers saved yet."}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add server"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void j(),children:"Scan QR"})]})]}):s.profiles.map(w=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:w.name}),t.jsx("div",{className:"settings-muted",children:w.serverUrl}),w.id===s.activeProfileId&&t.jsx("span",{className:"native-shell-connection-manager__active-pill",children:"Active"})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Edit ${w.name}`,onClick:()=>{l(w.id),d(w)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${w.name}`,onClick:()=>void n.setActiveProfile(w.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${w.name}`,onClick:()=>m(w),children:"Delete"})]})]},w.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:""}),f(null)},children:"Add connection"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void j(),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:x,onChange:w=>d(N=>({...N,name:w.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:y,onChange:w=>d(N=>({...N,serverUrl:w.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:b??"",onChange:w=>d(N=>({...N,authToken:w.target.value}))}),h&&t.jsx("p",{className:"form-error",role:"alert",children:h})]}),u&&t.jsxs("div",{className:"native-shell-connection-manager__delete-confirm",role:"alertdialog","aria-label":"Delete server confirmation",children:[t.jsxs("p",{children:["Delete ",t.jsx("strong",{children:u.name}),"? This removes the saved profile."]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m(null),children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void C(),children:"Delete"})]})]}),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",onClick:v,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void S(),disabled:!y.trim(),children:"Save"})]})]})})}function gz(e){if(e.hostKind==="desktop-shell"&&e.mode==="local")return{title:"Desktop local mode",actionLabel:"Switch server",dotClassName:"status-dot status-dot--online"};const n=e.profileLabel??e.profileId,s=e.serverOrigin,a=n&&s?`${n} · ${s}`:n??s;return e.mode==="remote"?{title:a??"Connection info unavailable",actionLabel:e.hostKind==="desktop-shell"?"Switch server":"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}:{title:a??"Connection info unavailable",actionLabel:"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}}function Pg({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=gz(e),a=i.useCallback(async()=>{const r=await e.openConnectionManager();!r.ok&&r.reason==="failed"&&n?.(r.error??"Failed to open connection manager")},[n,e]);return t.jsxs("button",{type:"button",className:"btn shell-connection-status",onClick:()=>void a(),"data-testid":"shell-connection-status-button",children:[t.jsx("span",{className:s.dotClassName,"aria-hidden":"true"}),t.jsx("span",{className:"shell-connection-status__kind",children:e.hostKind==="desktop-shell"?"Desktop":"Mobile"}),t.jsx("span",{className:"shell-connection-status__summary",title:s.title,children:s.title}),t.jsx("span",{className:"shell-connection-status__action",children:s.actionLabel})]})}function bz(e){if(e)try{return new URL(e).origin}catch{return}}function xz(e,n){const s=e.profiles.find(a=>a.id===e.activeProfileId)??null;return s||(n.kind==="browser"||!n.connectionId?null:e.profiles.find(a=>a.id===n.connectionId)??null)}async function vz(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function yz(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await vz(a),o=r?xz(r,e):null,l=e.kind==="browser"?void 0:e.mode??r?.desktopMode,c=o?.id??(e.kind==="browser"?void 0:e.connectionId),d=o?.name,u=bz(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),m=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",h=e.kind==="mobile-shell"&&typeof a?.openConnectionManager=="function",f=m||h;return{hostKind:e.kind,available:f,...l?{mode:l}:{},...c?{profileId:c}:{},...d?{profileLabel:d}:{},...u?{serverOrigin:u}:{},openConnectionManager:async()=>{try{return m?(await s.openConnectionManager?.(),{ok:!0}):h?(await a.openConnectionManager(),{ok:!0}):{ok:!1,reason:"unsupported"}}catch(p){return{ok:!1,reason:"failed",error:p instanceof Error?p.message:String(p)}}}}}function wz({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&&(bj(l),window.location.reload())},[n]),o=i.useCallback(()=>{xj(),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 kz=200,jz=i.lazy(()=>Sn(()=>import("./AgentsView-D-N6aA0P.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])).then(e=>({default:e.AgentsView}))),Nz=i.lazy(()=>Sn(()=>import("./DocumentsView-BWXOxpuq.js"),__vite__mapDeps([32,1,5,6,33])).then(e=>({default:e.DocumentsView}))),Sz=i.lazy(()=>Sn(()=>import("./InsightsView-BBpRiolN.js"),__vite__mapDeps([34,1,22,5,6,35])).then(e=>({default:e.InsightsView}))),Cz=i.lazy(()=>Sn(()=>import("./ResearchView-XZuRtOxE.js"),__vite__mapDeps([36,1,5,6,37])).then(e=>({default:e.ResearchView}))),Ez=i.lazy(()=>Sn(()=>import("./EvalsView-CJFbtL7i.js"),__vite__mapDeps([38,1,5,6,39])).then(e=>({default:e.EvalsView}))),_z=i.lazy(()=>Sn(()=>import("./NodesView-CGQWSNZM.js"),__vite__mapDeps([40,1,17,30,5,6,41])).then(e=>({default:e.NodesView}))),Mz=i.lazy(()=>Sn(()=>import("./ChatView-DnCdKu8Z.js"),__vite__mapDeps([42,1,5,6,43])).then(e=>({default:e.ChatView}))),Az=i.lazy(()=>Sn(()=>import("./SkillsView-DErYRumF.js"),__vite__mapDeps([44,1,5,6,45])).then(e=>({default:e.SkillsView}))),Rz=i.lazy(()=>Sn(()=>import("./MemoryView-48LuNkKk.js"),__vite__mapDeps([46,1,20,21,5,6,47])).then(e=>({default:e.MemoryView}))),Iz=i.lazy(()=>Sn(()=>import("./DevServerView-BiA1nYtt.js"),__vite__mapDeps([48,1,5,6,49])).then(e=>({default:e.DevServerView})));i.lazy(()=>Sn(()=>import("./TodoView-BD9NRwq0.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));const Tz=i.lazy(()=>Sn(()=>import("./StashRecoveryView-QJrNS4Vg.js"),__vite__mapDeps([50,1,5,6,51])).then(e=>({default:e.StashRecoveryView})));function Pz(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Sn(()=>import("./AgentsView-D-N6aA0P.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])),Sn(()=>import("./DocumentsView-BWXOxpuq.js"),__vite__mapDeps([32,1,5,6,33])),Sn(()=>import("./InsightsView-BBpRiolN.js"),__vite__mapDeps([34,1,22,5,6,35])),Sn(()=>import("./ResearchView-XZuRtOxE.js"),__vite__mapDeps([36,1,5,6,37])),Sn(()=>import("./EvalsView-CJFbtL7i.js"),__vite__mapDeps([38,1,5,6,39])),Sn(()=>import("./NodesView-CGQWSNZM.js"),__vite__mapDeps([40,1,17,30,5,6,41])),Sn(()=>import("./ChatView-DnCdKu8Z.js"),__vite__mapDeps([42,1,5,6,43])),Sn(()=>import("./SkillsView-DErYRumF.js"),__vite__mapDeps([44,1,5,6,45])),Sn(()=>import("./MemoryView-48LuNkKk.js"),__vite__mapDeps([46,1,20,21,5,6,47])),Sn(()=>import("./DevServerView-BiA1nYtt.js"),__vite__mapDeps([48,1,5,6,49])),Sn(()=>import("./TodoView-BD9NRwq0.js"),__vite__mapDeps([11,1,5,6,12])),Sn(()=>import("./StashRecoveryView-QJrNS4Vg.js"),__vite__mapDeps([50,1,5,6,51]))})}Gv();const Kd="kb-setup-warning-dismissed",$z="kb-chat-active-session",$g="kb-dashboard-working-branch-filter",Dg="kb-dashboard-base-branch-filter",Lg="__fusion:no-branch__",ey="fusion:approval-banner-dismissed";function Dz(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function Og(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Lz(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(ey);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n))typeof r=="number"&&Number.isFinite(r)&&s.set(a,r);return s}catch{return new Map}}function Fg(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(ey,JSON.stringify(n))}catch{}}function Oz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function Fz(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function zz(){const{toasts:e,addToast:n,removeToast:s}=yF(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=Av(),c=mz();i.useEffect(()=>{Pz()},[]);const{projects:d,loading:u,error:m,refresh:h}=fF(),{nodes:f}=yc(),{currentNode:p,currentNodeId:g,isRemote:x,setCurrentNode:y,clearCurrentNode:b}=XF(),{currentProject:v,setCurrentProject:S,clearCurrentProject:j,loading:C}=xF(d,{nodeId:g}),{hasAiProvider:w,hasGithub:N,loading:R,hasWarnings:z}=Cv(v?.id),{updateAvailable:E,latestVersion:I,currentVersion:O,dismissed:U,dismiss:A}=TF();i.useEffect(()=>{if(g&&!p&&f.length>0){const Ye=f.find(Tt=>Tt.id===g);if(Ye){y(Ye);return}}g&&f.length>0&&(f.some(Tt=>Tt.id===g)||b())},[g,p,f,y,b]);const[D,K]=i.useState(""),[Z,ne]=i.useState(""),[F,M]=i.useState("");i.useEffect(()=>{ne(Bn($g,v?.id)??""),M(Bn(Dg,v?.id)??"")},[v?.id]);const P=i.useCallback(Ye=>{ne(Ye),us($g,Ye,v?.id)},[v?.id]),$=i.useCallback(Ye=>{M(Ye),us(Dg,Ye,v?.id)},[v?.id]),k=GF(g,{projectId:v?.id,searchQuery:D||void 0});JF(g);const J=x&&k.projects.length>0?k.projects:d,{themeMode:ce,colorTheme:je,dashboardFontScalePct:He,setThemeMode:xe,setColorTheme:Ne,setDashboardFontScalePct:Y}=EF(),{sessions:ie,generating:ee,needsInput:oe,planningSessions:W,dismissSession:L}=rF(v?.id),pe=ie.filter(Ye=>Ye.status==="awaiting_input"||Ye.status==="error"),fe=cF(),B=_F({projectId:v?.id,planningSessions:W}),Fe=ri()==="mobile",{pushNav:ae,replaceCurrent:qe}=OF({enabled:!0}),{viewMode:Pe,setViewMode:nt,taskView:Be,handleChangeTaskView:de}=LF({projectsLoading:u,projectsError:m,currentProjectLoading:C,currentProject:v,projectsLength:d.length,setupWizardOpen:B.setupWizardOpen,openSetupWizard:B.openSetupWizard,themeMode:ce,setThemeMode:xe}),{views:Ie}=zF(v?.id),$e=i.useMemo(()=>{const Ye=Ie.find(Tt=>Tt.pluginId==="fusion-plugin-dependency-graph"&&Tt.view.viewId==="graph");return Ye?`plugin:${Ye.pluginId}:${Ye.view.viewId}`:Nb("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[Ie]),st=i.useCallback(Ye=>{Ye==="missions"&&(an(void 0),it(void 0),$t(void 0));const Tt=Be;de(Ye),Tt!==Ye&&ae({type:"view",revert:()=>de(Tt)})},[de,Be,ae]),Ue=Be==="board"||Be==="list",{tasks:me,createTask:re,moveTask:_e,pauseTask:xt,deleteTask:dt,mergeTask:Qe,retryTask:vt,resetTask:Ae,updateTask:Je,duplicateTask:ct,archiveTask:Nt,unarchiveTask:yt,archiveAllDone:Se,loadArchivedTasks:G,ingestCreatedTasks:ge,lastFetchTimeMs:pt}=uF({...v?{projectId:v.id}:{},searchQuery:D||void 0,sseEnabled:Ue}),ke=x&&k.tasks.length>0?k.tasks:me,[tt,Rt]=i.useState(!1),[Re,be]=i.useState(0),at=i.useRef(performance.now()),ot=i.useRef(!1),gt=i.useRef(!1),St=i.useMemo(()=>u?"projects":C?"project":"tasks",[u,C]);i.useEffect(()=>{if(!u&&!ot.current){ot.current=!0;const Ye=`projects loaded at ${Math.round(performance.now()-at.current)}ms from mount`;console.log(`[App] ${Ye}`)}if(!C&&!gt.current){gt.current=!0;const Ye=`current-project resolved at ${Math.round(performance.now()-at.current)}ms from mount`;console.log(`[App] ${Ye}`)}},[u,C]),i.useEffect(()=>{if(tt||u||C)return;const Ye=performance.now(),Tt=window.setTimeout(()=>{const cn=`dashboard ready at ${Math.round(performance.now()-at.current)}ms from mount (settle delay=${Math.round(performance.now()-Ye)}ms)`;console.log(`[App] ${cn}`),Rt(!0)},kz);return()=>{window.clearTimeout(Tt)}},[tt,u,C]);const{keyboardOpen:Lt}=Zi({enabled:Fe}),Yt=Fe&&Lt&&!B.anyModalOpen;Ni(Yt);const[tn,mn]=i.useState(0),[Qt,yn]=i.useState(0),[Gt,on]=i.useState(!1),[sn,ln]=i.useState(0),[Wt,ye]=i.useState(null),Le=i.useRef(new Map),Ke=i.useRef(new Set),ut=i.useRef(Lz()),Ve=i.useCallback(()=>{xb(v?.id).then(Ye=>{mn(Ye.unreadCount),yn(Ye.pendingApprovalCount??0)}).catch(Ye=>{console.warn("[App] Failed to fetch mailbox unread count:",Ye)})},[v?.id]);i.useEffect(()=>{const Ye=new Map,Tt=new Set;for(const cn of me)Ye.set(cn.id,cn.status),cn.status==="awaiting-approval"&&Tt.add(`task:${cn.id}`);Le.current=Ye,Ke.current=Tt},[me]),i.useEffect(()=>{Ve();const Ye=new URLSearchParams;v?.id&&Ye.set("projectId",v.id);const Tt=Ye.size>0?`?${Ye.toString()}`:"",cn=cs=>{const qn=ut.current.get(cs.dedupeKey);qn!==void 0&&cs.updatedAtMs<=qn||ye(cs)};return hi(`/api/events${Tt}`,{onReconnect:Ve,events:{"message:sent":Ve,"message:received":Ve,"message:read":Ve,"message:deleted":Ve,"approval:requested":cs=>{Ve();try{const qn=JSON.parse(cs.data),Cs=qn.id?`approval:${qn.id}`:qn.taskId?`task:${qn.taskId}`:void 0;if(!Cs||Ke.current.has(Cs))return;Ke.current.add(Cs),cn({dedupeKey:Cs,updatedAtMs:Og(qn.updatedAt??qn.createdAt)})}catch{}},"approval:updated":Ve,"approval:decided":Ve,"task:updated":cs=>{try{const qn=JSON.parse(cs.data);if(!qn?.id)return;const Cs=`task:${qn.id}`,na=Le.current.get(qn.id);if(Le.current.set(qn.id,qn.status),qn.status!=="awaiting-approval"){Ke.current.delete(Cs),ut.current.delete(Cs),Fg(ut.current);return}if(Ke.current.has(Cs))return;Dz(qn.status,na)&&(Ke.current.add(Cs),cn({dedupeKey:Cs,updatedAtMs:Og(qn.updatedAt)}),Ve())}catch{}}}})},[v?.id,Ve]),i.useEffect(()=>{Be==="chat"&&on(!1)},[Be]),i.useEffect(()=>{let Ye=!1;const Tt=async()=>{try{const cs=await T("/stash-recovery/orphans");Ye||ln(cs.count??0)}catch{Ye||ln(0)}};Tt();const cn=window.setInterval(()=>void Tt(),3e4);return()=>{Ye=!0,window.clearInterval(cn)}},[v?.id]),i.useEffect(()=>{const Ye=new URLSearchParams;v?.id&&Ye.set("projectId",v.id);const Tt=Ye.size>0?`?${Ye.toString()}`:"";return hi(`/api/events${Tt}`,{events:{"chat:message:added":cn=>{try{const cs=JSON.parse(cn.data),qn=Bn($z,v?.id);if(!qn||cs.role!=="assistant"||Be==="chat"||cs.sessionId!==qn||cs.projectId&&v?.id&&cs.projectId!==v.id)return;on(!0)}catch{}}}})},[v?.id,Be]);const Pt=i.useMemo(()=>Array.from(new Set(ke.map(Ye=>Ye.branch?.trim()).filter(Ye=>!!(Ye&&Ye.length>0)))).sort((Ye,Tt)=>Ye.localeCompare(Tt)),[ke]),Ot=i.useMemo(()=>Array.from(new Set(ke.map(Ye=>Ye.baseBranch?.trim()).filter(Ye=>!!(Ye&&Ye.length>0)))).sort((Ye,Tt)=>Ye.localeCompare(Tt)),[ke]),bt=i.useMemo(()=>ke.filter(Ye=>{const Tt=Ye.branch?.trim()??"",cn=Ye.baseBranch?.trim()??"";if(Z===Lg){if(Tt.length>0)return!1}else if(Z.length>0&&Tt!==Z)return!1;if(F===Lg){if(cn.length>0)return!1}else if(F.length>0&&cn!==F)return!1;return!0}),[ke,Z,F]),[Dt,Ft]=i.useState(!1),[Ht,rn]=i.useState(!1),[Xt,an]=i.useState(void 0),[Me,it]=i.useState(void 0),[kt,$t]=i.useState(void 0),[se,te]=i.useState(!1),[De,ft]=i.useState(!1),[qt,zt]=i.useState(()=>Bn(Kd,v?.id)==="true");i.useEffect(()=>{zt(Bn(Kd,v?.id)==="true")},[v?.id]),i.useEffect(()=>{const Ye=()=>{ft(!0)};return window.addEventListener(su,Ye),()=>{window.removeEventListener(su,Ye)}},[]);const Pn=i.useCallback(()=>{us(Kd,"true",v?.id),zt(!0)},[v?.id]),{maxConcurrent:he,autoMerge:mt,globalPaused:ht,enginePaused:wt,taskStuckTimeoutMs:Xe,staleHighFanoutBlockerAgeThresholdMs:Et,showQuickChatFAB:Zt,prAuthAvailable:le,settingsLoaded:lt,experimentalFeatures:nn,insightsEnabled:Rn,memoryEnabled:Hn,devServerEnabled:wn,todosEnabled:rs,toggleAutoMerge:_s,toggleGlobalPause:bn,toggleEnginePause:Ut,refresh:xs}=MF(v?.id),xn=nn.skillsView===!0,Xn=nn.nodesView===!0,$n=nn.researchView===!0,vs=nn.evalsView===!0,ms=nn.agentOnboarding===!0,hs=!0,Jn=i.useCallback(()=>{B.closeSettings(),be(Ye=>Ye+1),xs()},[B,xs]);i.useEffect(()=>{if(lt&&!pr(Be)){if(Be==="graph"&&!$e){de("board");return}Be==="skills"&&!xn&&de("board"),Be==="insights"&&!Rn&&de("board"),Be==="memory"&&!Hn&&de("board"),(Be==="devserver"||Be==="dev-server")&&!wn&&de("board"),Be==="research"&&!$n&&de("board"),Be==="evals"&&!vs&&de("board")}},[Be,lt,xn,Rn,de,hs,Hn,wn,$n,vs,$e]),i.useEffect(()=>{Dt&&!Xn&&Ft(!1)},[Dt,Xn]);const{availableModels:ps,favoriteProviders:Ns,favoriteModels:Yn,toggleFavoriteProvider:ys,toggleFavoriteModel:ws}=RF();IF({projectId:v?.id,setupWizardOpen:B.setupWizardOpen,openModelOnboarding:B.openModelOnboarding,openSettings:B.openSettings});const{handleSelectProject:Ms,handleViewAllProjects:X,handleAddProject:_,handleSetupComplete:ue,handleModelOnboardingComplete:Ce,handlePauseProject:We,handleResumeProject:At,handleRemoveProject:q,handleToggleFavorite:we,handleToggleModelFavorite:Oe}=WF({setCurrentProject:S,clearCurrentProject:j,setViewMode:nt,currentProject:v,refreshProjects:h,toggleFavoriteProvider:ys,toggleFavoriteModel:ws,addToast:n,openSettings:B.openSettings,openSetupWizard:B.openSetupWizard,closeSetupWizard:B.closeSetupWizard,closeModelOnboarding:B.closeModelOnboarding}),{handleDetailClose:It}=AF({projectId:v?.id,projects:d,projectsLoading:u,currentProject:v,setCurrentProject:S,addToast:n,openTaskDetail:B.openDetailTask,closeTaskDetail:B.closeDetailTask}),Kt=i.useCallback(async({insightId:Ye,title:Tt,description:cn})=>{await re({title:Tt,description:cn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Ye}}})},[re]),{handleBoardQuickCreate:fn,handleModalCreate:An,handlePlanningTaskCreated:jn,handlePlanningTasksCreated:En,handleSubtaskTasksCreated:ts,handleGitHubImport:Ln}=KF({createTask:re,ingestCreatedTasks:ge,onPlanningTaskCreated:B.onPlanningTaskCreated,onPlanningTasksCreated:B.onPlanningTasksCreated,onSubtaskTasksCreated:B.onSubtaskTasksCreated,addToast:n}),os=i.useCallback((Ye,Tt)=>{Tt==="changes"?B.openDetailWithChangesTab(Ye):B.openDetailTask(Ye,Tt),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),fs=i.useCallback(async Ye=>{try{const Tt=await La(Ye,v?.id);B.openDetailTask(Tt,"logs"),ae({type:"modal",close:B.closeDetailTask})}catch(Tt){n(`Failed to open task logs: ${Tt.message}`,"error")}},[B,v?.id,n,ae]),[ns,Zn]=i.useState([]);i.useEffect(()=>{let Ye=!1;return Uo(v?.id).then(Tt=>{Ye||Zn(Tt)}).catch(()=>{Ye||Zn([])}),()=>{Ye=!0}},[v?.id]);const es=i.useMemo(()=>new Map(ns.map(Ye=>[Ye.id,Ye.name])),[ns]);i.useCallback(()=>{Xn&&Ft(Ye=>!Ye)},[Xn]);const Ss=i.useCallback(()=>{Xn&&(Dt?Ft(!1):(Ft(!0),ae({type:"view",revert:()=>Ft(!1)})))},[Xn,Dt,ae]),ls=i.useCallback((Ye,Tt,cn)=>{B.openDetailTask(Ye,Tt,cn),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),ss=i.useCallback(Ye=>{B.openSettings(Ye),ae({type:"modal",close:Jn})},[B,ae,Jn]),Zs=i.useCallback(()=>{B.openNewTask(),ae({type:"modal",close:B.closeNewTask})},[B,ae]),Si=i.useCallback(()=>{B.openPlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),ga=i.useCallback(Ye=>{B.openPlanningWithInitialPlan(Ye),ae({type:"modal",close:B.closePlanning})},[B,ae]),Va=i.useCallback(()=>{B.resumePlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),Wa=i.useCallback(Ye=>{B.openSubtaskBreakdown(Ye),ae({type:"modal",close:B.closeSubtask})},[B,ae]),Ka=i.useCallback(()=>{B.openGitHubImport(),ae({type:"modal",close:B.closeGitHubImport})},[B,ae]),oi=i.useCallback(()=>{B.terminalOpen?B.toggleTerminal():(B.toggleTerminal(),ae({type:"modal",close:B.closeTerminal}))},[B,ae]),gn=i.useCallback(()=>{B.openFiles(),ae({type:"modal",close:B.closeFiles})},[B,ae]),Fi=i.useCallback(()=>{B.openTodos(),ae({type:"modal",close:B.closeTodos})},[B,ae]),ea=i.useCallback(()=>{B.openActivityLog(),ae({type:"modal",close:B.closeActivityLog})},[B,ae]),ba=i.useCallback(()=>{B.openGitManager(),ae({type:"modal",close:B.closeGitManager})},[B,ae]),Ga=i.useCallback(()=>{B.openSystemStats(),ae({type:"modal",close:B.closeSystemStats})},[B,ae]),xa=i.useCallback(()=>{B.openSchedules(),ae({type:"modal",close:B.closeSchedules})},[B,ae]),va=i.useCallback(()=>{B.openScripts(),ae({type:"modal",close:B.closeScripts})},[B,ae]),ya=i.useCallback(()=>{B.openWorkflowSteps(),ae({type:"modal",close:B.closeWorkflowSteps})},[B,ae]),Ja=i.useCallback(Ye=>{B.openUsage(Ye),ae({type:"modal",close:B.closeUsage})},[B,ae]),wa=i.useCallback(async(Ye,Tt)=>{await B.runScript(Ye,Tt),qe({type:"modal",close:B.closeTerminal})},[B,qe]),Fr=i.useCallback(()=>{B.closeSettings(),B.openModelOnboarding(),qe({type:"modal",close:B.closeModelOnboarding})},[B,qe]),ka=i.useCallback(()=>{B.setFileWorkspace("project"),B.openFiles()},[B]),Us=i.useCallback(async()=>{rn(!0);try{await h()}finally{rn(!1)}},[h]),Ci=i.useCallback(Ye=>{it(Ye),an(void 0),de("missions")},[de]),ei=i.useCallback(Ye=>{Ye.type==="planning"?B.openPlanningWithSession(Ye.id):Ye.type==="subtask"?B.openSubtaskWithSession(Ye.id):Ye.type==="mission_interview"?(it(void 0),an(Ye.id),$t(void 0),de("missions")):(Ye.type==="milestone_interview"||Ye.type==="slice_interview")&&(an(void 0),it(void 0),$t(Ye.id),de("missions"))},[de,B]),ta=i.useCallback(()=>{},[]),ja=i.useCallback(()=>{},[]),[zr,Ei]=i.useState(!1),[Na,Sa]=i.useState(!1),[zi,Ya]=i.useState(null),Br=Fz(r,o,zr);i.useEffect(()=>{!a||l===0||Sa(!0)},[a,l]),i.useEffect(()=>{let Ye=!1;return yz(c.host).then(Tt=>{Ye||Ya(Tt)}),()=>{Ye=!0}},[c.host,r.activeProfileId,r.desktopMode,r.host,r.profiles]),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 Ye=r.profiles.find(cn=>cn.id===r.activeProfileId);if(!Ye||typeof window>"u")return;const Tt=Oz(Ye.serverUrl,Ye.authToken??null);window.location.href!==Tt&&(window.location.href=Tt)},[r]);const Qa=!u&&!C&&d.length===0&&!v&&!!m,Xa=()=>{if(Qa)return t.jsx(dO,{errorMessage:m??"Failed to fetch projects",isRetrying:Ht,onRetry:Us,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(Dt)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(_z,{addToast:n,onClose:()=>Ft(!1)})})})});if(Pe==="overview")return t.jsx($s,{children:t.jsx(qP,{projects:d,loading:u,onSelectProject:Ms,onAddProject:_,onPauseProject:We,onResumeProject:At,onRemoveProject:q,nodes:f})});const Ye=Be==="graph"?$e:pr(Be)?Be:null;return Ye?t.jsx($s,{children:t.jsx(BF,{taskView:Ye,context:{projectId:v?.id,tasks:x&&k.tasks.length>0?k.tasks:me,workflowSteps:ns,openTaskDetail:(Tt,cn)=>ls(Tt,cn),renderTaskCard:Tt=>t.jsx(_o,{task:Tt,projectId:v?.id,onOpenDetail:cn=>ls(cn),addToast:n,workflowStepNameLookup:es,disableDrag:!0}),addToast:n}})}):Be==="skills"?!lt||!xn?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Az,{addToast:n,projectId:v?.id,onClose:()=>de("board")})})}):Be==="chat"?t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Mz,{addToast:n,projectId:v?.id,experimentalFeatures:nn})})}):Be==="mailbox"?t.jsx($s,{children:t.jsx(L$,{projectId:v?.id,addToast:n,onUnreadCountChange:mn})}):Be==="missions"?t.jsx($s,{children:t.jsx(I$,{isInline:!0,isOpen:!0,onClose:()=>{it(void 0),an(void 0),$t(void 0),de("board")},addToast:n,projectId:v?.id,onSelectTask:Tt=>{const cn=me.find(cs=>cs.id===Tt);cn&&ls(cn)},availableTasks:me.map(Tt=>({id:Tt.id,title:Tt.title})),resumeSessionId:Xt,targetMissionId:Me,milestoneSliceResumeSessionId:kt,onMilestoneSliceResumeFetchError:()=>$t(void 0)})}):Be==="agents"&&hs?t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(jz,{addToast:n,projectId:v?.id,onOpenTaskLogs:fs,agentOnboardingEnabled:ms})})}):Be==="documents"?t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Nz,{projectId:v?.id,addToast:n,onOpenDetail:ls})})}):Be==="stash-recovery"?t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Tz,{})})}):Be==="insights"?!lt||!Rn?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Sz,{projectId:v?.id,addToast:n,onClose:()=>de("board"),onCreateTask:Kt})})}):Be==="research"?!lt||!$n?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Cz,{projectId:v?.id,addToast:n,onOpenSettings:Tt=>B.openSettings(Tt),readinessVersion:Re})})}):Be==="evals"?!lt||!vs?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Ez,{projectId:v?.id,onOpenSettings:Tt=>B.openSettings(Tt),onOpenTaskDetail:Tt=>{La(Tt,v?.id).then(cn=>ls(cn)).catch(cn=>n(cn instanceof Error?cn.message:"Failed to open task detail","error"))}})})}):Be==="memory"?!lt||!Hn?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Rz,{addToast:n,projectId:v?.id})})}):Be==="devserver"||Be==="dev-server"?!lt||!wn?null:t.jsx($s,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(Iz,{addToast:n,projectId:v?.id})})}):Be==="board"?t.jsx($s,{children:t.jsx(UE,{tasks:bt,projectId:v?.id,maxConcurrent:he,onMoveTask:_e,onPauseTask:xt,onOpenDetail:ls,addToast:n,onQuickCreate:fn,onNewTask:Zs,onPlanningMode:ga,onSubtaskBreakdown:Wa,autoMerge:mt,onToggleAutoMerge:_s,globalPaused:ht,onUpdateTask:Je,onRetryTask:vt,onArchiveTask:Nt,onUnarchiveTask:yt,onDeleteTask:dt,onArchiveAllDone:Se,onLoadArchivedTasks:G,searchQuery:D,availableModels:ps,onOpenDetailWithTab:os,favoriteProviders:Ns,favoriteModels:Yn,onToggleFavorite:we,onToggleModelFavorite:Oe,taskStuckTimeoutMs:Xe,staleHighFanoutBlockerAgeThresholdMs:Et,onOpenMission:Ci,lastFetchTimeMs:pt})}):t.jsx($s,{children:t.jsx(IP,{tasks:x&&k.tasks.length>0?k.tasks:me,projectId:v?.id,onMoveTask:_e,onRetryTask:vt,onDeleteTask:dt,onMergeTask:Qe,onResetTask:Ae,onDuplicateTask:ct,onOpenDetail:(Tt,cn)=>ls(Tt,void 0,cn),addToast:n,globalPaused:ht,onNewTask:Zs,onQuickCreate:fn,onPlanningMode:ga,onSubtaskBreakdown:Wa,availableModels:ps,favoriteProviders:Ns,favoriteModels:Yn,onToggleFavorite:we,onToggleModelFavorite:Oe,taskStuckTimeoutMs:Xe,searchQuery:D,lastFetchTimeMs:pt,prAuthAvailable:le})})};if(!tt)return t.jsxs(t.Fragment,{children:[t.jsx(mO,{stage:St}),t.jsx($v,{toasts:e,onRemove:s})]});const Za=!B.modelOnboardingOpen&&PL(),Ur=!B.modelOnboardingOpen&&!Za&&Ar()&&!Rv();return t.jsxs(t.Fragment,{children:[t.jsx(xC,{shellHost:c.host,onOpenSettings:ss,onOpenGitHubImport:Ka,onOpenPlanning:Si,onResumePlanning:Va,activePlanningSessionCount:W.length,onOpenUsage:Ja,onOpenActivityLog:ea,onOpenSystemStats:Ga,onOpenMailbox:()=>st("mailbox"),mailboxUnreadCount:tn,mailboxPendingApprovalCount:Qt,chatHasUnreadResponse:Gt,stashOrphanCount:sn,onOpenSchedules:xa,onOpenGitManager:ba,onOpenNodes:Ss,showNodesButton:Xn,onOpenWorkflowSteps:ya,onOpenScripts:va,onRunScript:wa,onToggleTerminal:oi,onOpenFiles:gn,filesOpen:B.filesOpen,onOpenTodos:Fi,todosOpen:B.todosOpen,todosEnabled:rs,globalPaused:ht,enginePaused:wt,onToggleGlobalPause:bn,onToggleEnginePause:Ut,view:Be,onChangeView:Pe==="project"&&v?st:void 0,showSkillsTab:xn,showAgentsTab:hs,searchQuery:D,onSearchChange:K,branchFilter:Z,baseBranchFilter:F,branchOptions:Pt,baseBranchOptions:Ot,onBranchFilterChange:P,onBaseBranchFilterChange:$,projects:J,currentProject:v,onSelectProject:Ms,onViewAllProjects:X,projectId:v?.id,mobileNavEnabled:Fe,availableNodes:f,currentNode:p,onSelectNode:Ye=>{Ye===null?b():y(Ye)},isRemote:x,experimentalFeatures:{insights:Rn,memoryView:Hn,devServer:wn,devServerView:wn,researchView:$n,evalsView:vs},pluginDashboardViews:Ie,shellConnectionControl:!Fe&&zi?t.jsx(Pg,{status:zi,onError:Ye=>n(Ye,"error")}):void 0}),Pe==="project"&&v&&!Dt&&Be!=="missions"&&!B.isPlanningOpen&&!fe&&t.jsx(EO,{sessions:pe,onResumeSession:ei,onDismissSession:ta,onDismissAll:ja}),Pe==="project"&&v&&t.jsx(AO,{onOpenSettings:()=>B.openSettings("general")}),Pe==="project"&&v&&Za&&t.jsx(TO,{onResume:B.openModelOnboarding}),Pe==="project"&&v&&Ur&&t.jsx(PO,{onOpenModelOnboarding:B.openModelOnboarding,onOpenSettings:Ye=>B.openSettings(Ye)}),Pe==="project"&&v&&E&&I&&O&&!U&&t.jsx(RO,{latestVersion:I,currentVersion:O,onDismiss:A}),Pe==="project"&&v&&!R&&z&&!qt&&t.jsx(Ev,{hasAiProvider:w,hasGithub:N,onDismiss:Pn}),Pe==="project"&&v&&Wt&&t.jsx(IO,{pendingCount:Math.max(Qt,1),onOpenMailbox:()=>st("mailbox"),onDismiss:()=>{ut.current.set(Wt.dedupeKey,Math.max(Date.now(),Wt.updatedAtMs)),Fg(ut.current),ye(null)}}),t.jsx("div",{className:`project-content${Pe==="project"&&v&&(!Fe||!Yt)?" project-content--with-footer":""}${Fe&&!Yt?" project-content--with-mobile-nav":""}`,children:Xa()}),Pe==="project"&&v&&!Dt&&t.jsx(kO,{tasks:x&&k.tasks.length>0?k.tasks:me,projectId:v.id,taskStuckTimeoutMs:Xe,staleHighFanoutBlockerAgeThresholdMs:Et,backgroundSessions:ie,backgroundGenerating:ee,backgroundNeedsInput:oe,onOpenBackgroundSession:ei,onDismissBackgroundSession:L,lastFetchTimeMs:pt,currentProjectPath:v.path,onOpenProjectDirectory:ka,keyboardOpen:Yt}),t.jsx(DO,{view:Be,onChangeView:Pe==="project"&&v?st:()=>{},footerVisible:Pe==="project"&&!!v,modalOpen:B.anyModalOpen,keyboardOpen:Yt,onOpenSettings:ss,onOpenActivityLog:ea,onOpenSystemStats:Ga,onOpenMailbox:()=>st("mailbox"),onOpenNodes:Ss,mailboxUnreadCount:tn,mailboxPendingApprovalCount:Qt,chatHasUnreadResponse:Gt,stashOrphanCount:sn,onOpenGitManager:ba,onOpenWorkflowSteps:ya,onOpenSchedules:xa,onOpenScripts:va,onToggleTerminal:oi,onOpenFiles:gn,onOpenTodos:Fi,todosOpen:B.todosOpen,onOpenGitHubImport:Ka,onOpenPlanning:Si,onResumePlanning:Va,activePlanningSessionCount:W.length,onOpenUsage:()=>Ja(null),onViewAllProjects:X,onRunScript:wa,projectId:v?.id,showSkillsTab:xn,experimentalFeatures:{insights:Rn,memoryView:Hn,devServer:wn,devServerView:wn,todoView:rs,researchView:$n,evalsView:vs,nodesView:Xn},pluginDashboardViews:Ie,shellConnectionControl:Fe&&zi?t.jsx(Pg,{status:zi,onError:Ye=>n(Ye,"error")}):void 0}),Pe==="project"&&v&&Be!=="chat"&&Be!=="mailbox"&&Be!=="insights"&&Be!=="evals"&&Be!=="devserver"&&Be!=="dev-server"&&Be!=="graph"&&!pr(Be)&&t.jsx(aF,{projectId:v.id,addToast:n,showFAB:Zt,open:se,onOpenChange:te,favoriteProviders:Ns,favoriteModels:Yn,onToggleFavorite:we,onToggleModelFavorite:Oe}),t.jsx(cO,{projectId:v?.id,tasks:me,projects:d,currentProject:v,addToast:n,toasts:e,removeToast:s,modalManager:B,projectActions:{handleAddProject:_,handleSetupComplete:ue,handleModelOnboardingComplete:Ce},taskHandlers:{handleModalCreate:An,handlePlanningTaskCreated:jn,handlePlanningTasksCreated:En,handleSubtaskTasksCreated:ts,handleGitHubImport:Ln},taskOperations:{moveTask:_e,deleteTask:dt,mergeTask:Qe,retryTask:vt,resetTask:Ae,duplicateTask:ct},deepLink:{handleDetailClose:It},settings:{prAuthAvailable:le,themeMode:ce,colorTheme:je,dashboardFontScalePct:He,setThemeMode:xe,setColorTheme:Ne,setDashboardFontScalePct:Y},onSettingsClose:Jn,onReopenOnboarding:Fr}),t.jsx(wz,{open:De}),a&&t.jsxs(t.Fragment,{children:[t.jsx(pz,{open:Br,shellApi:a,shellState:r,onComplete:()=>Ei(!0)}),t.jsx(fz,{open:Na,shellApi:a,shellState:r,onClose:()=>Sa(!1)})]})]})}function Bz(){return t.jsx(vF,{children:t.jsx(uz,{children:t.jsx(kL,{children:t.jsx(QF,{children:t.jsx(IC,{children:t.jsx(zz,{})})})})})})}function ty(e){e.postMessage({type:"SKIP_WAITING"})}function zg(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&ty(e)})}function Uz(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,Lu("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&ty(s.waiting),s.installing&&zg(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&zg(a)})}).catch(s=>{console.log("SW registration failed:",s)})}Sj();dj();Xv();Gv();cy.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(uj,{children:t.jsx(Bz,{})})}));Uz();export{WS as $,Ys as A,zn as B,Gn as C,MC as D,v6 as E,ua as F,dc as G,Zd as H,Mn as I,Fl as J,t8 as K,jt as L,Lo as M,pk as N,cL as O,Fn as P,Bd as Q,bs as R,Wi as S,Oo as T,is as U,vi as V,_n as W,un as X,aL as Y,as as Z,Sn as _,pn as a,I6 as a$,QD as a0,XD as a1,KS as a2,g6 as a3,GS as a4,M3 as a5,A3 as a6,XN as a7,Pu as a8,Ir as a9,B5 as aA,z5 as aB,F5 as aC,L5 as aD,Ej as aE,Co as aF,T5 as aG,$5 as aH,P5 as aI,W5 as aJ,q5 as aK,V5 as aL,K5 as aM,P6 as aN,e8 as aO,So as aP,Gd as aQ,Ok as aR,Ii as aS,Mk as aT,Xy as aU,zP as aV,qs as aW,eb as aX,Ek as aY,A6 as aZ,R6 as a_,Ua as aa,ki as ab,ji as ac,Pi as ad,S5 as ae,A5 as af,M5 as ag,sb as ah,R5 as ai,C5 as aj,I5 as ak,E5 as al,_5 as am,gs as an,To as ao,xo as ap,Ws as aq,Jk as ar,$i as as,Kg as at,Ji as au,xy as av,D5 as aw,O5 as ax,H5 as ay,U5 as az,On as b,Fu as b$,T6 as b0,yc as b1,fF as b2,ah as b3,Vr as b4,pg as b5,D0 as b6,jr as b7,I0 as b8,b5 as b9,p5 as bA,g5 as bB,c3 as bC,l3 as bD,o3 as bE,d3 as bF,v3 as bG,y3 as bH,g3 as bI,h3 as bJ,p3 as bK,f3 as bL,m3 as bM,u3 as bN,r3 as bO,b3 as bP,O4 as bQ,Y3 as bR,J3 as bS,n6 as bT,G3 as bU,Q3 as bV,X3 as bW,Z3 as bX,e6 as bY,kS as bZ,t6 as b_,x5 as ba,P0 as bb,zO as bc,$0 as bd,FO as be,k5 as bf,j5 as bg,v5 as bh,y5 as bi,w5 as bj,N5 as bk,KO as bl,Zi as bm,Ov as bn,A0 as bo,js as bp,da as bq,lc as br,LO as bs,Ia as bt,Xg as bu,VO as bv,Jg as bw,Im as bx,Ki as by,f5 as bz,et as c,gN as c$,vS as c0,yS as c1,wS as c2,xS as c3,K3 as c4,fc as c5,Dk as c6,vr as c7,F6 as c8,z6 as c9,$3 as cA,z3 as cB,D3 as cC,L3 as cD,Cy as cE,dN as cF,U3 as cG,uN as cH,H3 as cI,di as cJ,Li as cK,cF as cL,N4 as cM,w3 as cN,D6 as cO,Kz as cP,Gz as cQ,rg as cR,C6 as cS,Jz as cT,Qz as cU,a3 as cV,i3 as cW,NN as cX,hN as cY,Di as cZ,pN as c_,B6 as ca,U6 as cb,H6 as cc,q6 as cd,V6 as ce,O6 as cf,ib as cg,Vw as ch,T as ci,Gl as cj,_o as ck,yr as cl,o1 as cm,bj as cn,xj as co,tN as cp,nN as cq,r5 as cr,I3 as cs,R3 as ct,o5 as cu,T3 as cv,B3 as cw,O3 as cx,P3 as cy,F3 as cz,S6 as d,d6 as d$,fN as d0,bN as d1,xN as d2,N3 as d3,E6 as d4,_6 as d5,M6 as d6,Qi as d7,J5 as d8,Y5 as d9,x3 as dA,W6 as dB,G6 as dC,Q6 as dD,J6 as dE,K6 as dF,Y6 as dG,X6 as dH,au as dI,Om as dJ,h6 as dK,f6 as dL,S0 as dM,ew as dN,Da as dO,Fs as dP,Pw as dQ,Z6 as dR,x6 as dS,Do as dT,ET as dU,ra as dV,p6 as dW,w6 as dX,y6 as dY,Gg as dZ,u6 as d_,L6 as da,Xz as db,Jd as dc,Es as dd,D4 as de,uL as df,hL as dg,pL as dh,la as di,Ud as dj,gL as dk,e3 as dl,Yz as dm,t3 as dn,Zz as dp,n3 as dq,s3 as dr,Oa as ds,n8 as dt,SC as du,xc as dv,Q5 as dw,Vp as dx,X5 as dy,Z5 as dz,j6 as e,i6 as e0,a6 as e1,YD as e2,Ea as e3,b6 as e4,l6 as e5,o6 as e6,ZN as e7,c6 as e8,m6 as e9,_3 as eA,C3 as eB,e5 as ea,w0 as eb,r6 as ec,s6 as ed,mi as ee,W3 as ef,q3 as eg,V3 as eh,t5 as ei,l5 as ej,eu as ek,u5 as el,m5 as em,d5 as en,i5 as eo,s5 as ep,a5 as eq,n5 as er,c5 as es,$6 as et,G5 as eu,S3 as ev,k3 as ew,j3 as ex,kk as ey,E3 as ez,La as f,N6 as g,Ks as h,Pr as i,Dn as j,sc as k,h5 as l,Is as m,VS as n,k6 as o,ri as p,qO as q,ZD as r,hi as s,Bn as t,Ni as u,pi as v,us as w,gc as x,Xo as y,Ee as z};
|