@runfusion/fusion 0.40.1 → 0.41.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/client/.vite/manifest.json +68 -68
- package/dist/client/assets/{AgentDetailView-BrETpTDj.js → AgentDetailView-krC0B2O0.js} +1 -1
- package/dist/client/assets/{AgentPermissionPolicyEditor-BP6d1LFG.js → AgentPermissionPolicyEditor-VDXL4XQc.js} +1 -1
- package/dist/client/assets/{AgentsView-COx3draV.js → AgentsView-ChXccELt.js} +3 -3
- package/dist/client/assets/{ChatView-CrVSqQK_.js → ChatView-Dz_xBKit.js} +1 -1
- package/dist/client/assets/{DevServerView-DXQ1LX4H.js → DevServerView-DGOahw1o.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-B_8ICSPl.js → DirectoryPicker-DgqHlxyh.js} +1 -1
- package/dist/client/assets/{DocumentsView-DmNB9rJZ.js → DocumentsView-CbbZwzbH.js} +1 -1
- package/dist/client/assets/{EvalsView-72w3_AO6.js → EvalsView-BL_ue7fJ.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-Be4oaohM.js → ExperimentalAgentOnboardingModal-8H4XAu4O.js} +1 -1
- package/dist/client/assets/{GoalsView-DkEXO_mx.js → GoalsView-CO4FVL3E.js} +1 -1
- package/dist/client/assets/{InsightsView-_-wd4BOJ.js → InsightsView-C5vLvWVE.js} +1 -1
- package/dist/client/assets/{MemoryView-BOCIc8HT.js → MemoryView-BL3W3yOv.js} +1 -1
- package/dist/client/assets/{NodesView-DTQP1j4H.js → NodesView-DfBNNm9c.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-BqaI9GKX.js → PiExtensionsManager-HvSiVeDN.js} +1 -1
- package/dist/client/assets/{PluginManager-DYaVwsXd.js → PluginManager-DIjrlhnU.js} +1 -1
- package/dist/client/assets/{PullRequestView-Dk9a7jRZ.js → PullRequestView-C2jQX8xZ.js} +1 -1
- package/dist/client/assets/{ReliabilityView-B-i5SOoD.js → ReliabilityView-DbqEwoRs.js} +1 -1
- package/dist/client/assets/{ResearchView-C2Gx8jC9.js → ResearchView-C1QghmLI.js} +1 -1
- package/dist/client/assets/{SecretsView-Db2HAGi2.js → SecretsView-Y2MQ-9n5.js} +1 -1
- package/dist/client/assets/{SessionTerminal-DwlNZLlr.js → SessionTerminal-DaTXNT3A.js} +1 -1
- package/dist/client/assets/{SettingsModal-Dje7N0hv.js → SettingsModal-BAzm2kYd.js} +3 -3
- package/dist/client/assets/{SettingsModal-B-d30TVy.js → SettingsModal-DabcZZ6S.js} +1 -1
- package/dist/client/assets/{SetupWizardModal-Cw3RdN83.js → SetupWizardModal-Db-Rxinm.js} +1 -1
- package/dist/client/assets/{SkillsView-BGyynaI4.js → SkillsView-CIEY1-DE.js} +1 -1
- package/dist/client/assets/{StashRecoveryView-CFaU-hym.js → StashRecoveryView-B6iDu5tI.js} +1 -1
- package/dist/client/assets/{TodoView-Djjwcb49.js → TodoView-B8IK_BPM.js} +1 -1
- package/dist/client/assets/{WorkflowNodeEditor-vnXnKvAr.js → WorkflowNodeEditor-DaPyvD_R.js} +1 -1
- package/dist/client/assets/{dashboard-view-DOEa6gWS.js → dashboard-view-Dn4CztR6.js} +1 -1
- package/dist/client/assets/{folder-open-BtEAEp7E.js → folder-open-C9XAaduE.js} +1 -1
- package/dist/client/assets/{index-CW4OzecJ.js → index-CgfrecpF.js} +5 -5
- package/dist/client/assets/{upload-Y9NiLQ9o.js → upload-BRAEugYV.js} +1 -1
- package/dist/client/assets/{users-B13HD4Tp.js → users-BlflbMZ3.js} +1 -1
- package/dist/client/index.html +1 -1
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
- 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/package.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 +3 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SessionTerminal-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/SessionTerminal-DaTXNT3A.js","assets/vendor-react-D37HfzIf.js","assets/vendor-xterm-tcedd2Jt.js","assets/vendor-xterm-LZoznX6r.css","assets/vendor-i18n-CV0mwX_-.js","assets/vendor-reactflow-CRZcPCXF.js","assets/vendor-reactflow-C5ap-Sga.css","assets/vendor-codemirror-jBKmHyH0.js","assets/SessionTerminal-BiigPP2l.css","assets/AgentDetailView-krC0B2O0.js","assets/ExperimentalAgentOnboardingModal-8H4XAu4O.js","assets/ExperimentalAgentOnboardingModal-BNpveCEk.css","assets/AgentPermissionPolicyEditor-VDXL4XQc.js","assets/AgentPermissionPolicyEditor-CGxjOr6G.css","assets/AgentDetailView-CY-O6VkV.css","assets/addon-fit-B4jkcKk4.js","assets/addon-web-links-CRNLzj7m.js","assets/addon-webgl-CeCSULF1.js","assets/TodoView-B8IK_BPM.js","assets/TodoView-7xIh-Fmi.css","assets/SetupWizardModal-Db-Rxinm.js","assets/DirectoryPicker-DgqHlxyh.js","assets/folder-open-C9XAaduE.js","assets/DirectoryPicker-DTKtd8L2.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CIqFbkrD.css","assets/SettingsModal-BAzm2kYd.js","assets/SecretsView-Y2MQ-9n5.js","assets/SecretsView-D5bHZ-wM.css","assets/users-BlflbMZ3.js","assets/SettingsModal-DabcZZ6S.js","assets/SettingsModal-bJvc9aHl.css","assets/SettingsModal-nF_GaeeK.css","assets/WorkflowNodeEditor-DaPyvD_R.js","assets/upload-BRAEugYV.js","assets/WorkflowNodeEditor-Po5uv_dN.css","assets/dashboard-view-Dn4CztR6.js","assets/zoom-out-CSTHbJgD.js","assets/createLucideIcon-BYvOGRiO.js","assets/dashboard-view-CuUPQZzi.css","assets/dashboard-view-DlKsVySD.js","assets/x-CqNX_9E2.js","assets/dashboard-view-DdGlfuu-.css","assets/dashboard-view-O5j3PSGY.js","assets/dashboard-view-BgiLoG1G.css","assets/AgentsView-ChXccELt.js","assets/AgentsView-DfznJDek.css","assets/DocumentsView-CbbZwzbH.js","assets/DocumentsView-WfVoTZt8.css","assets/InsightsView-C5vLvWVE.js","assets/InsightsView-C9-mqVvf.css","assets/ResearchView-C1QghmLI.js","assets/ResearchView-DTh8FLUm.css","assets/EvalsView-BL_ue7fJ.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-DfBNNm9c.js","assets/NodesView-7VInxyf_.css","assets/ChatView-Dz_xBKit.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-CIEY1-DE.js","assets/SkillsView-3bhGyWs1.css","assets/MemoryView-BL3W3yOv.js","assets/MemoryView-zaXewZzi.css","assets/ReliabilityView-DbqEwoRs.js","assets/ReliabilityView-eoKBhBc4.css","assets/DevServerView-DGOahw1o.js","assets/DevServerView-VTQY28P7.css","assets/GoalsView-CO4FVL3E.js","assets/GoalsView-DI66UsjT.css","assets/StashRecoveryView-B6iDu5tI.js","assets/StashRecoveryView-B_8WIQEo.css","assets/PullRequestView-C2jQX8xZ.js","assets/PullRequestView-WQIS0zUC.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{r as a,j as t,R as gr,b as ur,g as gk,c as zS}from"./vendor-react-D37HfzIf.js";import{u as st,T as Ga,i as uu,B as BS,a as US,b as HS,I as VS}from"./vendor-i18n-CV0mwX_-.js";import{H as Uo,P as Ho,R as qS,i as WS}from"./vendor-reactflow-CRZcPCXF.js";import"./vendor-xterm-tcedd2Jt.js";import{j as Xf,c as GS,a as KS,m as JS,C as yl,E as Pr,b as Hu,l as Qf,o as YS,s as XS,d as QS}from"./vendor-codemirror-jBKmHyH0.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
|
|
3
3
|
* @license lucide-react v1.7.0 - ISC
|
|
4
4
|
*
|
|
@@ -714,7 +714,7 @@ import{r as a,j as t,R as gr,b as ur,g as gk,c as zS}from"./vendor-react-D37HfzI
|
|
|
714
714
|
*
|
|
715
715
|
* This source code is licensed under the ISC license.
|
|
716
716
|
* See the LICENSE file in the root directory of this source tree.
|
|
717
|
-
*/const p_=[["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"}]],Ws=mt("zap",p_),og=200,Io=[];function di(e,n,s){Io.push({ts:new Date().toISOString(),source:e,event:n,detail:s}),Io.length>og&&Io.splice(0,Io.length-og)}function f_(){return[...Io]}function g_(){Io.length=0}typeof window<"u"&&(window.__fusionDebug??={},window.__fusionDebug.dashboardTraces={get:f_,clear:g_});const Sh="fusion:version-reload",Ch="fusion:version-update",_p="fusion:version-reloaded-remote";let bu=!0;function qu(e){bu=e}function b_(){try{if(sessionStorage.getItem(Ch))return sessionStorage.removeItem(Ch),!0}catch{}return!1}function Ep(e){const n=!!sessionStorage.getItem(Sh);if(di("versionCheck","reload-attempt",{reason:e,alreadySet:n}),n){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(Sh,"1"),!bu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function v_(){try{return sessionStorage.getItem(_p)}catch{return null}}function x_(e){try{sessionStorage.setItem(_p,e)}catch{}}function y_(){try{sessionStorage.removeItem(_p)}catch{}}function k_(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 w_(e){return k_(e)?(Ep(`chunk load error: ${e?.message??e}`),!0):!1}async function j_(){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 N_(){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&&(bu=!1)}catch{}}const S_=6e4,C_=5*6e4;let lg=0,Wu=!1,$c=null,cg=0,dg=null;async function zc(e="initial"){if(!(Wu||document.visibilityState!=="visible")&&!(Date.now()-lg<S_)){lg=Date.now(),Wu=!0;try{const n=await j_();if(n===null){di("versionCheck","remote-unavailable",{trigger:e,visibilityState:document.visibilityState}),$c=null;return}if(n==="f0d6d70a3-d53bffbb"){$c=null,y_();return}if(di("versionCheck","mismatch",{local:"f0d6d70a3-d53bffbb",remote:n,trigger:e,visibilityState:document.visibilityState}),console.info("[versionCheck] mismatch",{local:"f0d6d70a3-d53bffbb",remote:n,trigger:e}),$c!==n){$c=n,cg=Date.now(),di("versionCheck","mismatch-pending",{local:"f0d6d70a3-d53bffbb",remote:n,trigger:e,visibilityState:document.visibilityState});return}if(di("versionCheck","mismatch-confirmed",{remote:n,trigger:e,elapsedMs:Date.now()-cg}),v_()===n){di("versionCheck","reload-suppressed",{remote:n,trigger:e,reason:"already-reloaded-remote-version"}),console.info("[versionCheck] reload already attempted for remote version",n);return}try{sessionStorage.setItem(Ch,"1")}catch{}bu&&x_(n),Ep(`build version changed: f0d6d70a3-d53bffbb -> ${n}`)}finally{Wu=!1}}}function __(){N_(),window.setTimeout(()=>sessionStorage.removeItem(Sh),5e3),document.addEventListener("visibilitychange",()=>{zc("visibilitychange")}),window.addEventListener("focus",()=>{zc("focus")}),window.setTimeout(()=>void zc("initial"),2e3),dg===null&&(dg=window.setInterval(()=>{zc("poll")},C_))}class yc extends a.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!w_(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",i=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(oa,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:i}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Ys({children:e,onError:n}){return t.jsx(yc,{level:"page",onError:n,children:e})}function ir({children:e,onError:n}){return t.jsx(yc,{level:"modal",onError:n,children:e})}function E_({children:e,onError:n}){return t.jsx(yc,{level:"root",onError:n,children:e})}function Gu(){return typeof window>"u"?null:window.fusionShell??null}function M_(e){return e?.host==="desktop-shell"}function A_(e){const n=e.desktopModeState;return n?n.isFirstRun||n.desktopMode===null:!e.desktopMode}async function ug(e,n=3e4){const s=Date.now()+n;for(;Date.now()<s;){const r=(await e.getState()).localRuntime;if(r?.state==="running"&&(r.baseUrl||r.port))return{baseUrl:r.baseUrl??`http://127.0.0.1:${r.port}`};if(r?.state==="error")throw new Error(r.error??"Local runtime failed to start");await new Promise(o=>setTimeout(o,250))}throw new Error("Local runtime did not become ready in time")}function mg(e){const n=new URL(window.location.href);n.searchParams.set("serverBaseUrl",e),n.searchParams.set("shellKind","desktop-shell"),n.searchParams.set("shellMode","local"),window.location.replace(n.toString())}function T_({children:e}){const{t:n}=st("app"),[s,i]=a.useState({kind:"loading"});if(a.useEffect(()=>{const r=Gu();if(!r){i({kind:"bypass"});return}let o=!1;return(async()=>{try{const l=await r.getState();if(o)return;if(!M_(l)){i({kind:"bypass"});return}if(A_(l)){i({kind:"chooser",state:l});return}if(l.desktopMode==="local"){const d=new URLSearchParams(window.location.search);if(d.has("serverBaseUrl")){i({kind:"ready",serverBaseUrl:d.get("serverBaseUrl")??void 0});return}i({kind:"starting-local",message:n("desktop.startingLocalRuntime","Starting local Fusion runtime…")});const{baseUrl:c}=await ug(r);if(o)return;mg(c);return}i({kind:"ready"})}catch(l){if(o)return;i({kind:"local-error",message:l instanceof Error?l.message:String(l)})}})(),()=>{o=!0}},[]),a.useEffect(()=>{const r=Gu();if(!(!r?.onResetDesktopModeRequest||!r.resetDesktopMode))return r.onResetDesktopModeRequest(()=>{(async()=>{try{await r.resetDesktopMode?.()}catch{}const o=new URL(window.location.href);o.searchParams.delete("serverBaseUrl"),o.searchParams.delete("shellMode"),window.location.replace(o.toString())})()})},[]),s.kind==="loading"||s.kind==="starting-local"){const r=s.kind==="loading"?n("desktop.loading","Loading Fusion…"):s.message;return t.jsx("div",{className:"desktop-launch-gate",role:"status","aria-live":"polite",children:t.jsx("div",{className:"desktop-launch-gate__panel",children:t.jsx("p",{children:r})})})}return s.kind==="local-error"?t.jsx("div",{className:"desktop-launch-gate",role:"alert",children:t.jsxs("div",{className:"desktop-launch-gate__panel",children:[t.jsx("h2",{children:n("desktop.couldNotStart","Couldn't start local Fusion")}),t.jsx("p",{children:s.message}),t.jsx("button",{type:"button",className:"btn",onClick:()=>{window.location.reload()},children:n("desktop.retry","Retry")})]})}):s.kind==="chooser"?t.jsx(R_,{onPick:async r=>{const o=Gu();if(o){i({kind:"starting-local",message:r==="local"?n("desktop.startingLocalRuntime","Starting local Fusion runtime…"):n("desktop.settingUpRemote","Setting up remote connection…")});try{if(await o.setDesktopMode(r),r==="local"){const{baseUrl:l}=await ug(o);mg(l);return}await o.openConnectionManager(),window.location.reload()}catch(l){i({kind:"local-error",message:l instanceof Error?l.message:String(l)})}}}}):t.jsx(t.Fragment,{children:e})}function R_({onPick:e}){const{t:n}=st("app"),[s,i]=a.useState(null);return t.jsx("div",{className:"desktop-launch-gate",role:"dialog","aria-labelledby":"desktop-launch-gate-title",children:t.jsxs("div",{className:"desktop-launch-gate__panel",children:[t.jsx("h1",{id:"desktop-launch-gate-title",children:n("desktop.chooseMode","How do you want to run Fusion?")}),t.jsx("p",{children:n("desktop.chooseModeDescription","Run Fusion locally in this app, or connect to a Fusion server you're already running somewhere else.")}),t.jsxs("div",{className:"desktop-launch-gate__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",disabled:s!==null,onClick:()=>{i("local"),e("local")},children:s==="local"?n("desktop.starting","Starting…"):n("desktop.runLocalButton","Run Fusion Locally")}),t.jsx("button",{type:"button",className:"btn",disabled:s!==null,onClick:()=>{i("remote"),e("remote")},children:s==="remote"?n("desktop.opening","Opening…"):n("desktop.connectRemoteButton","Connect to Remote Fusion")})]})]})})}const P_="modulepreload",I_=function(e){return"/"+e},hg={},ln=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(m){return Promise.all(m.map(p=>Promise.resolve(p).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),c=d?.nonce||d?.getAttribute("nonce");r=l(s.map(m=>{if(m=I_(m),m in hg)return;hg[m]=!0;const p=m.endsWith(".css"),h=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${h}`))return;const u=document.createElement("link");if(u.rel=p?"stylesheet":P_,p||(u.as="script"),u.crossOrigin="",u.href=m,c&&u.setAttribute("nonce",c),document.head.appendChild(u),p)return new Promise((f,b)=>{u.addEventListener("load",f),u.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${m}`)))})}))}function o(l){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=l,window.dispatchEvent(d),!d.defaultPrevented)throw l}return r.then(l=>{for(const d of l||[])d.status==="rejected"&&o(d.reason);return n().catch(o)})},D_=20;function L_(e){const n=e.todoCount>e.threshold&&e.idleNonEphemeralAgentCount===0;return{atRisk:n,todoCount:e.todoCount,inProgressCount:e.inProgressCount,inReviewCount:e.inReviewCount,idleNonEphemeralAgentCount:e.idleNonEphemeralAgentCount,threshold:e.threshold,reason:n?"todo-exceeds-threshold-and-no-idle-agents":"ok"}}const F_={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,language:void 0,defaultProvider:void 0,defaultModelId:void 0,testMode:void 0,mergeRequestContractShadowEnabled:!1,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyAccessToken:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","message:agent-to-user","message:agent-to-agent","message:room","gridlock","board-stall-unrecovered","fallback-used","memory-dreams-processed","token-budget"],ntfyDashboardHost:void 0,taskTokenBudget:void 0,failureNotificationDelayMs:3e4,failureNotificationMode:"sticky-only",webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,cliOnboardingCompletedAt:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,openrouterAppAttribution:void 0,openrouterModelFilters:void 0,openrouterProviderPreferences:void 0,opencodeGoModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!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,persistAgentThinkingLogPermanent:!1,persistAgentThinkingLogEphemeral:!1,persistAgentThinkingLog:!1,agentMemoryInclusionMode:"full",secretsAccessPolicy:void 0,secretsSyncPassphraseConfigured:!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}},worktrunk:{enabled:!1,binaryPath:void 0,installedBinaryPath:void 0,onFailure:"fail"},owningNodeHandoffPolicy:"reassign-to-local",experimentalFeatures:{},cliAgents:{}},O_={globalPause:!1,globalPauseReason:void 0,defaultWorkflowId:void 0,enabledBuiltinWorkflowIds:void 0,approvedWorkflowCliCommands:void 0,approvedCliAutonomyAdapters:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,autoClaimCandidatesInPrompt:5,tombstoneStickyWindowDays:7,heartbeatScopeDiscipline:"strict",heartbeatPromptTemplate:"default",groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,testMode:void 0,mergeRequestContractShadowEnabled:!1,mergeStrategy:"direct",directMergeCommitStrategy:"always-squash",mergeIntegrationWorktree:"reuse-task-worktree",mergeAdvanceAutoSync:"stash-and-ff",integrationBranch:void 0,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",owningNodeHandoffPolicy:"reassign-to-local",defaultNodeId:void 0,secretsEnv:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,executorAllowSiblingBranchRename:!1,worktreeNaming:"random",worktrunk:{enabled:!1,binaryPath:void 0,installedBinaryPath:void 0,onFailure:"fail"},worktreesDir:void 0,taskPrefix:"FN",taskAttributionTrailerNames:["Fusion-Task-Id"],commitMsgHookEnabled:!0,includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",defaultProviderOverride:void 0,defaultModelIdOverride:void 0,modelPresets:[],autoSelectModelPreset:!1,completionDocumentationMode:"off",defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,mergerAutostashMaxAgeHours:24,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,prerebaseAutoEnabled:!0,prerebaseHotFiles:["AGENTS.md","packages/core/src/store.ts","packages/core/src/db.ts","packages/engine/src/executor.ts","packages/engine/src/scheduler.ts","packages/engine/src/merger.ts","packages/dashboard/app/styles.css"],prerebaseDivergenceThreshold:50,mergeConflictStrategy:"smart-prefer-main",merger:{mode:"ai",maxReviewPasses:3,allowDirtyLocalCheckoutSync:!1},mergeDiffVolumeMinLines:void 0,mergeDiffVolumeThreshold:void 0,mergeDiffVolumeAllowlist:void 0,mergeStrategyOverlapBehavior:"flip-to-prefer-branch",postMergeAuditMode:"warn",mergeAuditAutoRecovery:"ai-assisted",autoRecovery:{mode:"deterministic-only",maxRetries:3},reliabilityStatsResetAt:void 0,buildTimeoutMs:3e5,ephemeralAgentsEnabled:!0,agentProvisioning:{},sandboxProvisioning:{},defaultAgentPermissionPolicy:void 0,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:6e5,dispatchOscillationThreshold:5,dispatchOscillationWindowMs:6e4,dispatchOscillationSettleMs:5e3,runtimeStopDrainMs:2e3,engineActiveSinceMs:void 0,engineActivationGraceMs:5*6e4,inReviewStallDeadlockThreshold:3,stalePausedReviewThresholdMs:1440*6e4,inReviewStalledThresholdMs:1440*6e4,stalePausedTodoThresholdMs:1440*6e4,pausedScopeDecayMs:30*6e4,metaTaskStallAutoCloseMs:120*6e4,metaTaskActiveExecutionGraceMs:30*6e4,boardStallSweepWindowMs:120*6e4,boardStallBlockedGrowthThreshold:3,capacityRiskBannerEnabled:!1,capacityRiskTodoThreshold:20,backlogPressureAlertEnabled:!0,backlogPressureRatioThreshold:10,backlogPressureMinTodoCount:5,backlogPressureAlertCooldownMs:1440*6e4,dependencyBlockedTodoReportEnabled:!0,dependencyBlockedTodoFreshAgeMs:30*6e4,dependencyBlockedTodoStaleAgeMs:240*6e4,dependencyBlockedTodoMinCount:1,dependencyBlockedTodoReportCooldownMs:360*6e4,staleHighFanoutBlockerAgeThresholdMs:7200*1e3,staleInProgressWarningMs:240*6e4,staleInProgressCriticalMs:1440*6e4,staleInReviewWarningMs:1440*6e4,staleInReviewCriticalMs:4320*6e4,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxBranchConflictRecoveries:5,maxTotalRetriesBeforeFail:25,preserveProgressOnStuckRequeue:!0,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,doneAutoArchiveDays:0,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,githubCloseSourceIssueOnDone:!1,githubTrackingEnabledByDefault:!1,githubTrackingDefaultRepo:void 0,githubTrackingDedupEnabled:!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,taskTokenBudget:void 0,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionIntervalMs:36e5,reflectionAfterTask:!0,showQuickChatFAB:!1,chatAutoCleanupDays:0,mailAutoCleanupDays:0,operationalLogRetentionDays:30,agentLogFileRetentionDays:0,chatRoomRecentVerbatimMessages:25,chatRoomCompactionFetchLimit:200,chatRoomSummaryMaxChars:3e3,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}},sandbox:{backend:"native",policy:{allowNetwork:!0,allowedPaths:[]},failureMode:"fail-hard"},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},$_=Object.freeze(Object.keys(F_)),z_=Object.freeze(Object.keys(O_));function J7(e){return $_.includes(e)}function Y7(e){return z_.includes(e)}function X7(e,n){const s=n.ephemeral?e?.persistAgentThinkingLogEphemeral:e?.persistAgentThinkingLogPermanent;return typeof s=="boolean"?s:typeof e?.persistAgentThinkingLog=="boolean"?e.persistAgentThinkingLog:!1}function Re(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const B_={provider:"mock",modelId:"scripted"};function U_(e){return e?.testMode===!0||e?.defaultProvider?.trim().toLowerCase()==="mock"}function eo(e,n){return U_(n)?B_:e}function H_(e){return!!(e?.provider&&e?.modelId)}function to(...e){for(const n of e)if(H_(n))return{provider:n.provider,modelId:n.modelId};return{}}function Mp(e){return eo(to({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId}),e)}function V_(e){return eo(to({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Mp(e)),e)}function q_(e){return eo(to({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Mp(e)),e)}function W_(e){return eo(to({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Mp(e)),e)}function Ap(e,n){return eo(to({provider:e.modelProvider,modelId:e.modelId},V_(n)),n)}function Tp(e,n){return eo(to({provider:e.validatorModelProvider,modelId:e.validatorModelId},W_(n)),n)}function Rp(e,n){return eo(to({provider:e.planningModelProvider,modelId:e.planningModelId},q_(n)),n)}const Q7=["off","minimal","low","medium","high"],$d=["triage","todo","in-progress","in-review","done","archived"],zd="triage";function vu(e){return typeof e=="string"&&$d.includes(e)}function G_(e,n=zd){return vu(e)?e:n}const xr=["low","normal","high","urgent"],yi="normal",Pp=5,Pk=7200*1e3,K_=["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"],Ik=["en","zh-CN","zh-TW","fr","es","ko"],J_="en";function pg(e){return typeof e=="string"&&Ik.includes(e)}let fg=!1;function Z7(e){return e==="reuse-task-worktree"||e==="cwd-integration-branch"?e:e==="cwd-main"?(fg||(fg=!0,console.warn("[merger] settings.mergeIntegrationWorktree=cwd-main is legacy; normalized to cwd-integration-branch")),"cwd-integration-branch"):"reuse-task-worktree"}function eq(e){return e==="off"||e==="ff-only"||e==="stash-and-ff"?e:"stash-and-ff"}const xu=/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,To={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},gg={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"},_h={triage:["todo","archived"],todo:["in-progress","triage","archived"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function Y_(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)}const tq=["git_write","file_write_delete","command_execution","network_api","task_agent_mutation"],nq={git_write:["git commit","git push","git merge","git branch -d","git worktree add","write","edit"],file_write_delete:["write","edit","fn_task_attach"],command_execution:["bash (non-git)","read","find","grep","ls"],network_api:["fn_research_run (web/research)","fn_web_fetch","worktrunk_install"],task_agent_mutation:["fn_task_create","fn_delegate_task","fn_task_import_github","fn_task_import_github_issue","fn_spawn_agent","fn_update_agent_config","fn_update_identity"]},sq=["fn_send_message","fn_post_room_message","fn_read_messages","fn_task_log","fn_task_done","fn_heartbeat_done","fn_task_document_write","fn_task_document_read","fn_memory_search","fn_memory_get","fn_memory_append","fn_read_evaluations","fn_reflect_on_performance"],iq=["always","trusted-only","never"];function cl(e){return e.replace(/\\/g,"/")}function Ip(e){return e.replace(/[\\/]+$/g,"")}function Dp(e){const n=cl(Ip(e));return n?n.split("/").filter(Boolean):[]}function Lp(e){const n=cl(Ip(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Dk(e,n){const s=Dp(e);return s.length===0?cl(e):s.slice(-2).join("/")}function X_(e){const n=cl(Ip(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function Eh(e,n){return!e||e==="."?n:[...Dp(e),n].join("/")}function Q_(e){const n=Dp(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function aq(e){const n=cl(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 d=0;d<o.length;d+=1)l.push({label:o[d],path:`${r}${o.slice(0,d+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const i=n.split("/").filter(Boolean);return i.map((r,o)=>({label:r,path:i.slice(0,o+1).join("/")}))}const Z_={active:{label:"Active",color:"var(--color-success)",icon:Ds},paused:{label:"Paused",color:"var(--color-warning)",icon:ia},errored:{label:"Error",color:"var(--color-error)",icon:oi},initializing:{label:"Initializing",color:"var(--color-info)",icon:Et}},Lk={label:"Unknown",color:"var(--color-error)",icon:oi};function eE(e){return e?e.split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):Lk.label}function Fk(e){const n=Z_[e];return n||{...Lk,label:eE(e)}}function Ok(e){return e==="initializing"}const bg="fusion_project_bookmarks";function tE(){const[e,n]=a.useState(()=>{try{const r=localStorage.getItem(bg);if(r){const o=JSON.parse(r);if(Array.isArray(o))return new Set(o.filter(l=>typeof l=="string"))}}catch{}return new Set});a.useEffect(()=>{try{localStorage.setItem(bg,JSON.stringify([...e]))}catch{}},[e]);const s=a.useCallback(r=>{n(o=>{const l=new Set(o);return l.has(r)?l.delete(r):l.add(r),l})},[]),i=a.useCallback(r=>e.has(r),[e]);return{bookmarkedIds:e,toggleBookmark:s,isBookmarked:i}}function vg({text:e,query:n}){if(!n.trim())return t.jsx(t.Fragment,{children:e});const s=e.toLowerCase(),i=n.toLowerCase(),r=s.indexOf(i);if(r===-1)return t.jsx(t.Fragment,{children:e});const o=e.slice(0,r),l=e.slice(r,r+n.length),d=e.slice(r+n.length);return t.jsxs(t.Fragment,{children:[o,t.jsx("mark",{className:"project-selector__highlight",children:l}),d]})}function nE({projects:e,currentProject:n,onSelect:s,onViewAll:i,recentProjectIds:r=[],allowSingleProject:o=!1,viewAllLabel:l}){const{t:d}=st("app"),[c,m]=a.useState(!1),[p,h]=a.useState(""),[u,f]=a.useState(-1),b=a.useRef(null),y=a.useRef(null),v=a.useRef(null),x=a.useRef(new Map),{bookmarkedIds:k,toggleBookmark:w,isBookmarked:g}=tE();a.useEffect(()=>{if(!c)return;const R=L=>{b.current&&!b.current.contains(L.target)&&y.current&&!y.current.contains(L.target)&&(m(!1),h(""))};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[c]),a.useEffect(()=>{if(!c)return;const R=L=>{L.key==="Escape"&&(m(!1),h(""),y.current?.focus())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[c]),a.useEffect(()=>{c&&setTimeout(()=>v.current?.focus(),0)},[c]);const j=a.useMemo(()=>r.map(R=>e.find(L=>L.id===R)).filter(R=>R!==void 0&&R.id!==n?.id).slice(0,3),[r,e,n]),S=a.useMemo(()=>{if(!p.trim())return e;const R=p.toLowerCase();return e.filter(L=>L.name.toLowerCase().includes(R)||L.path.toLowerCase().includes(R))},[e,p]),C=a.useMemo(()=>{if(!p.trim())return null;const R=p.toLowerCase(),O=S.filter(J=>J.id!==n?.id).filter(J=>J.name.toLowerCase()===R);return O.length===1?O[0]:null},[S,p,n]),E=a.useMemo(()=>{const R=new Set(j.map(B=>B.id)),L=n?.id,O=!!p.trim(),J=O?[]:S.filter(B=>B.id!==L&&k.has(B.id)&&!R.has(B.id)),A=new Set([...J.map(B=>B.id),...O?[]:R]),de=S.filter(B=>B.id!==L&&!A.has(B.id));return{bookmarked:J,recent:O?[]:j,others:de}},[S,j,n,p,k]),F=a.useMemo(()=>{const R=E.bookmarked.length,L=E.recent.length,O=E.others.length;return R+L+O+1},[E]),M=a.useCallback(R=>{switch(R.key){case"ArrowDown":R.preventDefault(),f(L=>L<F-1?L+1:0);break;case"ArrowUp":R.preventDefault(),f(L=>L>0?L-1:F-1);break;case"Enter":if(R.preventDefault(),u>=0){const L=E.bookmarked.length,O=E.recent.length,J=E.others.length;u<L?s?.(E.bookmarked[u]):u<L+O?s?.(E.recent[u-L]):u<L+O+J?s?.(E.others[u-L-O]):i(),m(!1),h("")}else C&&(s?.(C),m(!1),h(""));break;case"Home":R.preventDefault(),f(0);break;case"End":R.preventDefault(),f(F-1);break}},[u,F,E,s,i,C]);a.useEffect(()=>{if(c&&p.trim())if(C){const R=E.bookmarked.length,L=E.recent.length,O=E.others.findIndex(J=>J.id===C.id);O>=0&&f(R+L+O)}else E.others.length>0?f(E.bookmarked.length+E.recent.length):f(-1);else c&&!p.trim()&&f(-1)},[c,p,C,E]),a.useEffect(()=>{if(u<0)return;const R=x.current.get(u);R&&R.scrollIntoView({block:"nearest"})},[u]);const D=a.useCallback(R=>{s?.(R),m(!1),h("")},[s]),_=a.useCallback(()=>{i(),m(!1),h("")},[i]),V=a.useCallback(()=>{m(R=>(R||h(""),!R))},[]),N=R=>{const L=Fk(R),O=L.icon;return t.jsx(O,{size:14,style:{color:L.color},className:Ok(R)?"animate-spin":""})},$=R=>{const L=g(R);return t.jsx("span",{role:"button",tabIndex:0,className:`project-selector__bookmark ${L?"bookmarked":""}`,onClick:O=>{O.stopPropagation(),w(R)},onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.stopPropagation(),O.preventDefault(),w(R))},"aria-label":L?d("projectSelector.removeBookmark","Remove bookmark"):d("projectSelector.addBookmark","Bookmark project"),"data-testid":`bookmark-toggle-${R}`,children:t.jsx(Od,{size:14,fill:L?"currentColor":"none"})})};return!o&&e.length<=1?null:t.jsxs("div",{className:"project-selector",ref:b,children:[t.jsxs("button",{ref:y,className:`project-selector__trigger ${c?"open":""}`,onClick:V,"aria-expanded":c,"aria-haspopup":"listbox","aria-label":d("projectSelector.ariaLabel","Select project"),title:n?.name?d("projectSelector.switchProjectTitle","Switch project (current: {{name}})",{name:n.name}):d("projectSelector.projectsTitle","Projects"),"data-testid":"project-selector-trigger",children:[t.jsx(Zs,{size:16,className:"project-selector__trigger-icon"}),t.jsx("span",{className:"project-selector__trigger-text",children:n?.name||d("projectSelector.projects","Projects")}),t.jsx(Ln,{size:14,className:`project-selector__trigger-chevron ${c?"rotate":""}`})]}),c&&t.jsxs("div",{className:"project-selector__dropdown",role:"listbox","aria-label":"Projects",onKeyDown:M,"data-testid":"project-selector-dropdown",children:[t.jsxs("div",{className:"project-selector__search",children:[t.jsx(na,{size:14,className:"project-selector__search-icon"}),t.jsx("input",{ref:v,type:"text",placeholder:d("projectSelector.searchPlaceholder","Search projects..."),value:p,onChange:R=>h(R.target.value),className:"project-selector__search-input","data-testid":"project-selector-search-input","aria-label":d("projectSelector.searchAriaLabel","Type to search projects")}),p&&t.jsx("button",{className:"project-selector__search-clear",onClick:()=>h(""),"aria-label":d("projectSelector.clearSearch","Clear search"),children:t.jsx(Fn,{size:12})})]}),C&&t.jsx("div",{className:"project-selector__exact-match","data-testid":"project-selector-exact-match",children:d("projectSelector.exactMatch","Exact match — press Enter to select")}),E.bookmarked.length>0&&t.jsxs("div",{className:"project-selector__section",children:[t.jsxs("div",{className:"project-selector__section-header",children:[t.jsx(Od,{size:12,fill:"currentColor"}),t.jsx("span",{children:d("projectSelector.bookmarked","Bookmarked")})]}),E.bookmarked.map((R,L)=>t.jsxs("button",{ref:O=>{O?x.current.set(L,O):x.current.delete(L)},className:`project-selector__item ${u===L?"highlighted":""}`,onClick:()=>D(R),role:"option","aria-selected":n?.id===R.id,children:[N(R.status),t.jsx("span",{className:"project-selector__item-name",children:R.name}),$(R.id),n?.id===R.id&&t.jsx(Qs,{size:14,className:"project-selector__item-check"})]},R.id))]}),E.recent.length>0&&t.jsxs("div",{className:"project-selector__section",children:[t.jsxs("div",{className:"project-selector__section-header",children:[t.jsx(ha,{size:12}),t.jsx("span",{children:d("projectSelector.recent","Recent")})]}),E.recent.map((R,L)=>{const O=E.bookmarked.length+L;return t.jsxs("button",{ref:J=>{J?x.current.set(O,J):x.current.delete(O)},className:`project-selector__item ${u===O?"highlighted":""}`,onClick:()=>D(R),role:"option","aria-selected":n?.id===R.id,children:[N(R.status),t.jsx("span",{className:"project-selector__item-name",children:R.name}),$(R.id),n?.id===R.id&&t.jsx(Qs,{size:14,className:"project-selector__item-check"})]},R.id)})]}),t.jsxs("div",{className:"project-selector__section",children:[(E.bookmarked.length>0||E.recent.length>0)&&t.jsxs("div",{className:"project-selector__section-header",children:[t.jsx(Zs,{size:12}),t.jsx("span",{children:d("projectSelector.allProjects","All Projects")})]}),E.others.length===0&&p?t.jsxs("div",{className:"project-selector__no-results","data-testid":"project-selector-no-results",children:[t.jsx(na,{size:14,className:"project-selector__no-results-icon"}),t.jsx("span",{children:d("projectSelector.noResults",'No projects match "{{query}}"',{query:p})})]}):E.others.map((R,L)=>{const O=E.bookmarked.length+E.recent.length+L,J=C?.id===R.id;return t.jsxs("button",{ref:A=>{A?x.current.set(O,A):x.current.delete(O)},className:`project-selector__item ${u===O?"highlighted":""} ${J?"exact-match":""}`,onClick:()=>D(R),role:"option","aria-selected":n?.id===R.id,"data-testid":`project-selector-item-${R.id}`,children:[N(R.status),t.jsxs("div",{className:"project-selector__item-info",children:[t.jsx("span",{className:"project-selector__item-name",children:t.jsx(vg,{text:R.name,query:p})}),R.path&&t.jsx("span",{className:"project-selector__item-path",children:t.jsx(vg,{text:Dk(R.path),query:p})})]}),J&&t.jsx("span",{className:"project-selector__exact-badge",children:d("projectSelector.exact","Exact")}),$(R.id),n?.id===R.id&&t.jsx(Qs,{size:14,className:"project-selector__item-check"})]},R.id)})]}),t.jsx("div",{className:"project-selector__footer",children:t.jsxs("button",{ref:R=>{const L=F-1;R?x.current.set(L,R):x.current.delete(L)},className:`project-selector__view-all ${u===F-1?"highlighted":""}`,onClick:_,"data-testid":"manage-projects-action",children:[t.jsx(qo,{size:14}),t.jsx("span",{children:l??d("projectSelector.viewAll","View All Projects")})]})})]})]})}const Fp="fn.authToken",xg="token",sE="fn_token";let Do,yg=!1,Bd=!1;const Mh="fn:auth-token-recovery-required",Ah="fusion:oauth-relogin-success";function iE(){try{const e=window.localStorage.getItem(Fp);return e&&e.length>0?e:void 0}catch{return}}function $k(e){try{window.localStorage.setItem(Fp,e)}catch{}}function aE(){if(!(yg||typeof window>"u")){yg=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(xg);if(!n)return;$k(n),e.searchParams.delete(xg);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Jo(){if(Do!==void 0)return Do;const e=aE();if(e)return Do=e,e;const n=iE();if(n)return Do=n,n}function rE(e){Do=e,Bd=!1,$k(e)}function oE(){Do=void 0,Bd=!1;try{window.localStorage.removeItem(Fp)}catch{}}function kg(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function lE(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function cE(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!lE(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=kg(e.protocol)===kg(n.protocol);return s&&i&&r}function dE(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 pa(e){const n=Jo();if(!n||typeof window>"u")return e;const s=dE(e);return!s||!cE(s.parsed)?e:(s.parsed.searchParams.set(sE,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Ki(e){const n=Jo();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function uE(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function mE(){typeof window>"u"||Bd||(Bd=!0,window.dispatchEvent(new CustomEvent(Mh)))}async function hE(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();uE(i)&&mE()}catch{}}function pE(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Jo();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=Jo(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const c=new URL(o,window.location.origin);return c.origin!==window.location.origin?!1:c.pathname.startsWith("/api/")||c.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,i);const d=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!d.has("Authorization")&&d.set("Authorization",`Bearer ${r}`),e(s,{...i,headers:d}).then(c=>(hE(c),c))}}const go=new Map;function fE(){let e,n;return{external:new Promise((i,r)=>{e=i,n=r}),resolve:e,reject:n,done:!1}}function wg(e,n){n.then(s=>{e.done||(e.done=!0,e.resolve(s))},s=>{e.done||(e.done=!0,e.reject(s))})}function Oi(e,n,s){const i=go.get(e);if(i&&!i.done)return s?.forceFresh&&wg(i,n()),i.external;const r=fE();return wg(r,n()),r.external.then(()=>{go.get(e)===r&&go.delete(e)},()=>{go.get(e)===r&&go.delete(e)}),go.set(e,r),r.external}class Ka extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function zk(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function ci(e){return`/api${e}`}async function I(e,n={}){const s=ci(e),i=Jo(),r=(()=>{if(i){const u=new Headers(n.headers??{});return u.has("Content-Type")||u.set("Content-Type","application/json"),Ki(u)}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")??"",d=await o.text(),c=l.includes("application/json");if(l.includes("text/html")||zk(d))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!c){const h=d.length>160?`${d.slice(0,160)}...`:d;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let p;try{p=d?JSON.parse(d):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=p;throw new Ka(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return p}function gE(){return I("/health")}function Bk(){return I("/health/refresh",{method:"POST"})}function rq(){return I("/updates/check")}function Uk(e,n,s,i,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),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return I(`/tasks${l}`)}async function pr(e,n){const i=ci(K(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:Ki({"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")}class bE extends Error{matches;constructor(n){super("duplicate_candidates"),this.name="DuplicateCandidatesError",this.matches=n}}async function vE(e,n){return(await I(K("/tasks/duplicate-check",n),{method:"POST",body:JSON.stringify(e)})).matches??[]}async function Hk(e,n,s){const{title:i,description:r,column:o,dependencies:l,breakIntoSubtasks:d,enabledWorkflowSteps:c,workflowId:m,assignedAgentId:p,modelPresetId:h,modelProvider:u,modelId:f,validatorModelProvider:b,validatorModelId:y,planningModelProvider:v,planningModelId:x,thinkingLevel:k,summarize:w,reviewLevel:g,executionMode:j,autoMerge:S,priority:C,source:E,nodeId:F,branch:M,baseBranch:D,branchSelection:_,githubTracking:V,acknowledgedDuplicates:N,bypassDuplicateCheck:$}=e;try{return await jc(K("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:i,description:r,column:o,dependencies:l,breakIntoSubtasks:d,enabledWorkflowSteps:c,workflowId:m,assignedAgentId:p,modelPresetId:h,modelProvider:u,modelId:f,validatorModelProvider:b,validatorModelId:y,planningModelProvider:v,planningModelId:x,thinkingLevel:k,summarize:w,reviewLevel:g,executionMode:j,autoMerge:S,priority:C,source:E,nodeId:F,branch:M,baseBranch:D,branchSelection:_,githubTracking:V,acknowledgedDuplicates:N,bypassDuplicateCheck:$})})}catch(R){if(R instanceof Ka&&R.status===409&&R.message==="duplicate_candidates"){const L=Array.isArray(R.details?.matches)?R.details?.matches:[];throw new bE(L)}throw R}}function si(e,n,s){return I(K(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function xE(e,n,s,i,r,o,l,d,c){return I(K("/tasks/batch-update-models",c),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:d})})}function yE(e,n,s,i){return I(K(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof i=="object"&&i?.preserveProgress?{preserveProgress:!0}:{}})})}function kE(e,n,s){return I(K(`/tasks/${e}/custom-fields`,s),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({customFields:n})})}function Op(e){return I(K("/tasks/board-workflows",e))}function wE(e,n){return I(K(`/tasks/${e}/promote`,n),{method:"POST"})}function jE(e,n,s){const i=new URLSearchParams;s?.removeDependencyReferences&&i.set("removeDependencyReferences","true"),s?.removeLineageReferences&&i.set("removeLineageReferences","true"),s?.githubIssueAction&&i.set("githubIssueAction",s.githubIssueAction),s?.allowResurrection&&i.set("allowResurrection","true");const r=i.size>0?`?${i.toString()}`:"";return I(K(`/tasks/${e}${r}`,n),{method:"DELETE"})}function NE(e,n){return I(K(`/tasks/${e}/merge`,n),{method:"POST"})}function Vk(e,n){return I(K(`/branch-groups/${e}`,n))}function qk(e,n){return I(K(`/branch-groups/${e}/promote`,n),{method:"POST",body:JSON.stringify({})})}function Wk(e,n){return I(K(`/branch-groups/${e}/abandon`,n),{method:"POST",body:JSON.stringify({})})}function SE(e,n){return I(K(`/tasks/${e}/retry`,n),{method:"POST"})}function CE(e,n){return I(K(`/tasks/${e}/recover-branch-binding`,n),{method:"POST"})}function _E(e,n){return I(K(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function EE(e,n){return I(K(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Gk(e,n){return I(K(`/tasks/${e}/pause`,n),{method:"POST"})}function Kk(e,n){return I(K(`/tasks/${e}/unpause`,n),{method:"POST"})}function ME(e,n,s){const i=new URLSearchParams;s?.removeLineageReferences&&i.set("removeLineageReferences","true");const r=i.size>0?`?${i.toString()}`:"";return I(K(`/tasks/${e}/archive${r}`,n),{method:"POST"})}function AE(e,n){return I(K(`/tasks/${e}/unarchive`,n),{method:"POST"})}function TE(e){return I(K("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function RE(e,n){return I(K(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function PE(e,n){return I(K(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Jk(e){const n=K("/config",e);return Oi(n,()=>I(n))}function yu(e,n){const s=K("/settings",e);return Oi(s,()=>I(s),n)}function Bc(e,n){return I(K("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function IE(e){return I(K("/update-check",e))}function oq(e){return I(K("/remote/settings",e))}function lq(e,n){return I(K("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function cq(e){return I(K("/remote/status",e))}function dq(e){return I(K("/remote/install-cloudflared",e),{method:"POST"})}function uq(e){return I(K("/remote/tunnel/start",e),{method:"POST"})}function mq(e){return I(K("/remote/tunnel/stop",e),{method:"POST"})}function hq(e){return I(K("/remote/tunnel/kill-external",e),{method:"POST"})}function pq(e){return I(K("/remote/token/persistent/regenerate",e),{method:"POST"})}function fq(e,n){return I(K("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Yk(e,n,s){const i=new URLSearchParams;e&&i.set("format",e),i.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&i.set("ttlMs",String(s));const r=i.toString();return r?`?${r}`:""}function gq(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=Yk(null,s,i);return I(K(`/remote/url${r}`,n))}function bq(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=Yk(e,i,r);return I(K(`/remote/qr${o}`,s))}function vq(e){return I(K("/memory",e))}function xq(e,n){return I(K("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function yq(e){return I(K("/memory/files",e))}function kq(e,n){const s=`path=${encodeURIComponent(e)}`;return I(K(`/memory/file?${s}`,n))}function wq(e,n,s){return I(K("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function jq(e,n){let s,i=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return I(K("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function Nq(e){return I(K("/memory/dream",e),{method:"POST"})}function Sq(e){return I(K("/memory/insights",e))}function Cq(e,n){return I(K("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function _q(e){return I(K("/memory/extract",e),{method:"POST"})}function Eq(e){return I(K("/memory/audit",e))}function Mq(e){return I(K("/memory/stats",e))}function Aq(e){return I(K("/memory/backend",e))}function Tq(e){return I(K("/memory/install-qmd",e),{method:"POST"})}function Rq(e,n){return I(K("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Ja(e){return Oi("/settings/global",()=>I("/settings/global"),e)}function Ms(e){return I("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function Pq(e){return I(K("/settings/scopes",e))}function Iq(e){return I(K("/settings/pi-extensions",e))}function Dq(e,n){return I(K("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function Lq(e,n,s){return I(K("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function Fq(){return I("/pi-settings")}async function Oq(e){return I("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function $q(e){return I("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function zq(e){return I(K("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function ku(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ci(K(`/tasks/${e}/attachments`,s)),{method:"POST",headers:Ki(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function DE(e,n,s){return I(K(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function jg(e,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",o=K(`/tasks/${e}/logs${r}`,n),l=await fetch(ci(o),{headers:Ki()});if(!l.ok){const p=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(p.error||`HTTP ${l.status}`)}const d=await l.json(),c=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):d.length,m=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:d,total:c,hasMore:m}}function LE(e,n,s,i){return I(K(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function FE(e,n,s){return I(K(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function OE(e,n){return I(K(`/tasks/${e}/documents`,n))}function $E(e,n,s){return I(K(`/tasks/${e}/documents/${n}/revisions`,s))}async function Bq(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return I(K(r,n))}function Uq(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return I(K(r,e))}function Ng(e,n,s,i,r){return I(K(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function zE(e,n,s){return I(K(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function BE(e,n,s){return I(K(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function UE(e,n,s){return I(K(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function HE(e,n){return I(K(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function VE(e,n,s){return I(K(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function fa(){return I("/models")}function qE(){return I("/usage")}function WE(){return I("/providers/claude-cli/status")}function GE(){return I("/system/fn-binary/status")}function KE(){return I("/system/fn-binary/install",{method:"POST"})}function JE(){return I("/providers/droid-cli/status")}function YE(){return I("/providers/cursor-cli/status")}function XE(){return I("/providers/llama-cpp/status")}async function Hq(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/hermes/status${n}`)}async function Vq(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await I(`/providers/hermes/profiles${n}`)).profiles??[]}async function qq(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/openclaw/status${n}`)}async function Wq(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),I(`/providers/paperclip/status?${n.toString()}`)}async function Gq(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function Kq(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function Jq(e){return I("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function Yq(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function Xq(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await I(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function Qq(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await I(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function Zq(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function QE(e){return I("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function ZE(e){return I("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function eM(e){return I("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function tM(e){return I("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function nM(){const n=(await I("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":s.apiType==="google-generative-ai"?"google-generative-ai":s.apiType==="openai-responses"?"openai-responses":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(i=>({id:i.id,name:i.name}))}));return Object.assign(n,{providers:n})}function sM(e){return I("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function eW(e,n){const s=n,i={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":s.api==="google-generative-ai"?"google-generative-ai":s.api==="openai-responses"?"openai-responses":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(i)})}function tW(e){return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function iM(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":e.api==="google-generative-ai"?"google-generative-ai":e.api==="openai-responses"?"openai-responses":"openai-compatible";return sM({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}))})}async function aM(e){return I("/custom-providers/probe-models",{method:"POST",body:JSON.stringify({baseUrl:e.baseUrl,apiKey:e.apiKey,apiType:e.apiType})})}function Yo(e){return Oi("/auth/status",()=>I("/auth/status"),e)}function rM(e){return I("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function oM(e,n){return I("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function lM(e){return I("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function cM(e){return I("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function dM(e,n){return I("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function uM(e){return I("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function mM(e,n,s,i){return I("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function hM(e,n,s,i){return I(K("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function pM(e,n,s){return I("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function fM(e,n,s,i){return I(K("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function gM(e){return I(K("/git/remotes",e))}function bM(e){return I(K("/git/remotes/detailed",e))}function vM(e,n,s){return I(K("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function xM(e,n){return I(K(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yM(e,n,s){return I(K(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function kM(e,n,s){return I(K(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Sg(e,n){return I(K(`/tasks/${e}/pr/generate-metadata`,n),{method:"POST"})}function wM(e,n,s){const i=s?`?base=${encodeURIComponent(s)}`:"";return I(K(`/tasks/${e}/pr/preflight${i}`,n))}function jM(e,n,s){return I(K(`/tasks/${e}/pr/resolve-conflicts`,s),{method:"POST",...n?{body:JSON.stringify({base:n})}:{}})}function NM(e,n,s){return I(K(`/tasks/${e}/pr/push-branch`,s),{method:"POST",...n?{body:JSON.stringify({base:n})}:{}})}function SM(e,n){return I(K(`/tasks/${e}/pr/options`,n))}function CM(e,n,s){return I(K(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Th(e,n){return I(K(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}function _M(e,n,s){return I(K(`/tasks/${e}/pr/${n}/unlink`,s),{method:"POST",body:JSON.stringify({})})}function EM(e,n){return I(K(`/tasks/${e}/pr/reclaim-conflict`,n),{method:"POST"})}function MM(e,n,s,i){const r=i?`?pr=${encodeURIComponent(String(i))}`:"";return I(K(`/tasks/${e}/pr/merge${r}`,s),{method:"POST",body:JSON.stringify(n?{method:n}:{})})}function AM(e,n,s,i,r){const o=r?`?pr=${encodeURIComponent(String(r))}`:"";return I(K(`/tasks/${e}/pr/auto-merge${o}`,i),{method:"POST",body:JSON.stringify({enabled:n,strategy:s})})}function TM(e,n,s){const i=s?`?pr=${encodeURIComponent(String(s))}`:"";return I(K(`/tasks/${e}/pr/checks${i}`,n))}function Cg(e,n,s){const i=s?`?pr=${encodeURIComponent(String(s))}`:"";return I(K(`/tasks/${e}/pr/reviews${i}`,n))}function Uc(e,n,s,i){return I(K("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function _g(e,n){return I(K(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function RM(e){return I(K("/terminal/sessions",e))}function Ui(e,n){const s=K("/git/status",e);if(!n?.extended)return I(s);const i=s.includes("?")?"&":"?";return I(`${s}${i}extended=1`)}function PM(e,n){const s=e?`?limit=${e}`:"";return I(K(`/git/commits${s}`,n))}function Ud(e,n){return I(K(`/git/commits/${e}/diff`,n))}function IM(e){return I(K("/git/commits/ahead",e))}function DM(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return I(K(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Ro(e){return I(K("/git/branches",e))}function LM(e,n,s){const i=`?limit=${n}`;return I(K(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function FM(e){return I(K("/git/worktrees",e))}function OM(e,n,s){return I(K("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function $M(e,n){return I(K(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Eg(e,n,s){const i=n?"?force=true":"";return I(K(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function zM(e,n){return I(K("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Mg(e,n){const s=typeof e=="string"?void 0:e;return I(K("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function Ag(e){return I(K("/git/push",e),{method:"POST"})}function Hc(e){return I(K("/git/stashes",e))}function BM(e,n){return I(K("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function UM(e,n,s){return I(K(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function HM(e,n){return I(K(`/git/stashes/${e}`,n),{method:"DELETE"})}function VM(e,n){return I(K(`/git/stashes/${e}/diff`,n))}function qM(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),I(K(`/git/diff/file?${i.toString()}`,s))}function bo(e){return I(K("/git/changes",e))}function Tg(e,n){return I(K("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function WM(e,n){return I(K("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Rg(e,n){return I(K("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function GM(e,n){return I(K("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function KM(e){return I(K("/workspaces",e))}function JM(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),I(`/files?${i.toString()}`)}function YM(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function XM(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function QM(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),I(`/files/search?${i.toString()}`)}function ZM(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/mkdir?${i.toString()}`,{method:"POST",body:JSON.stringify({path:n})})}function eA(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${i.toString()}`,{method:"POST",body:JSON.stringify({content:""})})}function tA(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function nA(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function sA(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function iA(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Xk(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function aA(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function rA(e,n,s){return I(K("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function oA(e,n,s,i,r){return I(K("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:i?.planningDepth,customQuestionCount:i?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function Pg(e,n,s,i){return I(K("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function lA(e,n,s){return I(K(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function cA(e,n,s){return I(K(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dA(e,n,s){return I(K(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Qk(e,n,s){return I(K("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function nW(e,n,s,i){return I(K("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:i?.planningModelProvider,planningModelId:i?.planningModelId})})}function sW(e,n,s){return I(K("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function iW(e,n){return I(K("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function uA(e,n,s,i){return I(K("/planning/create-task",s),{method:"POST",body:JSON.stringify({...n?{sessionId:e,summary:n}:{sessionId:e},...i?.branch!==void 0?{branch:i.branch}:{},...i?.baseBranch!==void 0?{baseBranch:i.baseBranch}:{},...i?.branchSelection?{branchSelection:i.branchSelection}:{}})})}function mA(e,n,s){return I(K("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function hA(e,n,s,i){return I(K("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n,...i?.branchSelection?{branchSelection:i.branchSelection}:{},...i?.branchAssignment?{branchAssignment:i.branchAssignment}:{}})})}const Rh=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Rh))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function pA(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function dl(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,d=null,c=null,m=!1;const p=f=>{const b=f.lastEventId;if(!b)return!0;const y=Number.parseInt(b,10);return Number.isFinite(y)?c!==null&&y<=c?!1:(c=y,!0):!0},h=()=>{if(o)return;const f=pA(e,c),b=new EventSource(pa(f));r=b,b.onopen=()=>{l=0,m=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},b.onmessage=y=>{const v=y;p(v)&&n.onMessage?.(v)};for(const[y,v]of Object.entries(n.events??{}))b.addEventListener(y,x=>{const k=x;p(k)&&v(k)});b.onerror=()=>{if(o||r!==b)return;if(b.readyState===EventSource.CONNECTING){m||(m=!0,s.onConnectionStateChange?.("reconnecting"));return}if(b.close(),l>=i){s.onFatalError?.("Connection lost");return}m=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);d=setTimeout(()=>{d=null,h()},v)}};h();const u={close:()=>{o=!0,d&&(clearTimeout(d),d=null),r?.close(),Rh.delete(u)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Rh.add(u),u}function Ig(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,d=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${d} · ${i} (${l})`}}function Xo(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function fA(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 gA(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>fA(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function bA(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,i=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((m,p)=>({id:p+1,text:m,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(m=>m.id>r).slice(0,s),totalLines:o};const d=Math.max(o-i,0),c=Math.max(d-s,0);return{lines:l.slice(c,d),totalLines:o}}function Dg(e){return Array.isArray(e)?e.map(Ig):(e.candidates??[]).map(Ig)}async function vA(e){try{const n=await I(K("/dev-server/candidates",e));return Dg(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await I(K("/dev-server/detect",e));return Dg(s)}throw n}}function $p(e){return I(K("/dev-server/status",e)).then(Xo)}async function aW(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await I(K(`/dev-server/logs/history${i}`,n));return gA(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await $p(n);return bA(o.logs,e)}throw r}}function xA(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return I(K("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(Xo)}function yA(e){return I(K("/dev-server/stop",e),{method:"POST"}).then(Xo)}function kA(e){return I(K("/dev-server/restart",e),{method:"POST"}).then(Xo)}async function wA(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await I(K("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Xo(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await I(K("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Xo(r)}throw i}}function rW(e){return ci(K("/dev-server/logs/stream",e))}async function oW(e){try{return(await I(K("/devserver",e))).sessions??[]}catch{try{const n=await $p(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function lW(e,n){try{return await I(K(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await $p(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function cW(e,n){try{return await I(K(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await xA({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function dW(e,n){try{return await I(K(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await yA(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function uW(e,n){try{return await I(K(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await kA(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function mW(e,n,s){try{const i=await I(K(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await wA({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function hW(e){try{return(await I(K("/devserver/detect",e))).candidates??[]}catch{try{return(await vA(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function pW(e,n){return ci(K(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function kc(e,n,s=25e3){const i=setInterval(()=>{vR(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function jA(e,n){return ci(K(`/planning/${encodeURIComponent(e)}/stream`,n))}function NA(e,n){return ci(K(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function fW(e,n,s,i){const r=NA(e,n),o=dl(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 d=JSON.parse(l.data);s.onError?.(d.message||d)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function SA(e,n,s,i){const r=jA(e,n);let o=null,l=null;const d=()=>{o?.stop(),o=null},c=dl(r,{onOpen:()=>{d(),o=kc(e,n)},onMessage:m=>{m.data.startsWith(":")},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},question:m=>{try{s.onQuestion?.(JSON.parse(m.data))}catch(p){console.error("[planning] Failed to parse question event:",p)}},summary:m=>{try{s.onSummary?.(JSON.parse(m.data))}catch(p){console.error("[planning] Failed to parse summary event:",p)}},error:m=>{try{const p=JSON.parse(m.data);s.onError?.(p.message||p)}catch{s.onError?.(m.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{d(),s.onError?.(m)}});return l={close:()=>{d(),c.close()},isConnected:c.isConnected},l}function wc(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const i=s.toString();return i?`${e}?${i}`:e}function CA(e){return I(wc("/routines",e))}function _A(e,n){return I(wc("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Lg(e,n,s){return I(wc(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function EA(e,n){await I(wc(`/routines/${e}`,n),{method:"DELETE"})}function MA(e,n){return I(wc(`/routines/${e}/trigger`,n),{method:"POST"})}function Fg(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity${s}`)}function AA(e){const n=K("/activity",e);return I(n,{method:"DELETE"})}function zp(e){const n=K("/workflow-steps",e);return Oi(n,()=>I(n))}function TA(e,n){return I(K(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Bp(e,n){const s=n?.includeDisabledBuiltins?"?includeDisabledBuiltins=true":"",i=K(`/workflows${s}`,e);return Oi(i,()=>I(i))}function gW(e){const n=K("/traits",e);return Oi(n,()=>I(n).then(s=>s.traits))}function bW(e){const n=K("/step-parsers",e);return Oi(n,()=>I(n).then(s=>s.parsers.map(i=>i.id)))}function Zk(e,n){return I(K(`/workflows/${encodeURIComponent(e)}`,n))}function vW(e,n){return I(K("/workflows",n),{method:"POST",body:JSON.stringify(e)})}function xW(e,n,s){return I(K(`/workflows/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yW(e,n){return I(K(`/workflows/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kW(e,n){return I(K(`/workflows/${encodeURIComponent(e)}/setting-values`,n))}function wW(e,n,s){return I(K(`/workflows/${encodeURIComponent(e)}/setting-values`,s),{method:"PATCH",body:JSON.stringify({values:n})})}function jW(e,n){return I(K(`/workflows/${encodeURIComponent(e)}/compile`,n),{method:"POST"})}async function NW(e,n){const s=await I(K(`/workflows/${encodeURIComponent(e)}/export`,n)),i=(s.name||"workflow").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"workflow",r=new Blob([JSON.stringify(s,null,2)],{type:"application/json"}),o=URL.createObjectURL(r),l=document.createElement("a");return l.href=o,l.download=`${i}.workflow.json`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o),s}function SW(e,n){return I(K("/workflows/import",n),{method:"POST",body:JSON.stringify(e)})}function CW(e){return I(K("/workflows/migrate-legacy-steps",e),{method:"POST"})}function _W(e,n,s){return I(K("/workflows/design",n),{method:"POST",body:JSON.stringify(e),signal:s})}function RA(e,n){return I(K(`/tasks/${encodeURIComponent(e)}/workflow`,n))}function PA(e,n,s){return I(K(`/tasks/${encodeURIComponent(e)}/workflow`,s),{method:"PUT",body:JSON.stringify({workflowId:n})})}function IA(e,n){return I(K(`/tasks/${encodeURIComponent(e)}/workflow/approve-cli`,n),{method:"POST"})}function DA(e,n,s){return I(K(`/tasks/${encodeURIComponent(e)}/workflow/input`,s),{method:"POST",body:JSON.stringify({text:n})})}function LA(e){return I(K("/project/default-workflow",e))}function FA(e,n){return I(K("/project/default-workflow",n),{method:"PUT",body:JSON.stringify({workflowId:e})})}function EW(){return I("/workflow-step-templates")}function MW(){return I("/plugin-workflow-step-templates")}function Hd(e){return I(K("/scripts",e))}function OA(e,n,s){return I(K("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function $A(e,n){return I(K(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function ew(e,n,s){return(await I(K("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Vc={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 tw(e){if(!(e instanceof Error))return Vc.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Vc.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Vc.INVALID_TYPE:n.startsWith("text must")||n.startsWith("title must")||n.includes("text is required")||n.includes("type is required")||n.includes("title is required")?e.message:Vc.NETWORK}async function AW(e,n){return(await I(K("/ai/draft-goal-description",n),{method:"POST",body:JSON.stringify({title:e})})).description}function zA(e,n){return I(K("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function BA(e,n,s){return I(K(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function UA(e,n){return ci(K(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function HA(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},d=dl(UA(e,n),{onOpen:()=>{l(),r=kc(e,n)},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},subtasks:c=>{try{s.onSubtasks?.(JSON.parse(c.data))}catch(m){console.error("[subtasks] Failed to parse subtasks event:",m)}},error:c=>{try{const m=JSON.parse(c.data),p=typeof m=="string"&&m.length>0?m:null;s.onError?.(p||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{l(),s.onError?.(c)}});return o={close:()=>{l(),d.close()},isConnected:d.isConnected},o}function VA(e,n,s,i,r){return I(K("/subtasks/create-tasks",i),{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 nw(e,n,s){return I(K("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function K(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function qA(e,n,s){if(!n||n===s)return e;const i="/api",r=e.startsWith(i)?e.slice(i.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function jc(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=qA(e,s,i);return I(o,r)}function br(e,n,s){const i=new URLSearchParams;e?.state&&i.set("state",e.state),e?.role&&i.set("role",e.role),e?.includeEphemeral===!0&&i.set("includeEphemeral","true"),n&&i.set("projectId",n);const o=`/agents${i.size>0?`?${i.toString()}`:""}`;return Oi(o,()=>I(o),s)}function Ph(e,n){return I(K(`/agents/${encodeURIComponent(e)}`,n))}function WA(e,n){return I(K("/agents",n),{method:"POST",body:JSON.stringify(e)})}function GA(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function TW(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ci(K(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:Ki(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function RW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function PW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function IW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function DW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function LW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function FW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function OW(e,n,s){const i=`path=${encodeURIComponent(n)}`;return I(K(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function $W(e,n,s,i){return I(K(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function KA(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function JA(e,n){return I(K(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function zW(e,n,s){const i=new URLSearchParams;n!==void 0&&i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/runs${r}`)}function BW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function UW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function HW(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/prompt-sizes${r}`)}function VW(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return I(K(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function qW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Og(e,n){const s=K("/agents/stats",e);return Oi(s,()=>I(s),n)}function WW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function GW(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return I(`/agents/org-tree${i?`?${i}`:""}`)}function KW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function $g(e,n,s){return I(K(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function sw(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 YA(e,n){const s=await I(K(`/tasks/${encodeURIComponent(e)}/review`,n));return sw(s)}async function XA(e,n){const s=await I(K(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return sw(s)}function QA(e,n,s){return I(K(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function JW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/tasks`,n))}function YW(){return I("/agents/companies")}function XW(e,n){return I(K("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function QW(e,n){return I(K("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function ZW(e,n){return I(K(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function eG(e){return I(K("/backups",e))}function tG(e){return I(K("/backups",e),{method:"POST"})}function nG(e,n){const s=K("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return I(i)}function sG(e,n,s){return I(K("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}async function ZA(e,n,s,i){const r=i?`/api/ai/summarize-title?projectId=${encodeURIComponent(i)}`:"/api/ai/summarize-title",o=await fetch(r,{method:"POST",headers:Ki({"Content-Type":"application/json"}),body:JSON.stringify({description:e,provider:n,modelId:s})}),l=o.headers.get("content-type")??"",d=await o.text();if(!l.includes("application/json"))throw new Error(`API returned non-JSON response: ${d.slice(0,100)}`);const m=JSON.parse(d);if(!o.ok){const p=m.error||"Request failed";throw o.status===400?new Error(`Invalid request: ${p}`):o.status===429?new Error(`Rate limit exceeded: ${p}`):o.status===503?new Error(`AI service temporarily unavailable: ${p}`):new Error(p)}if(!m.title)throw new Error("API returned empty title");return m.title}function iG(){return I("/projects")}function eT(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function zg(){return Oi("/projects/across-nodes",()=>I("/projects/across-nodes"))}function Vd(){return Oi("/nodes",()=>I("/nodes"))}function aG(){return I("/docker/nodes")}function rG(e){return I(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function oG(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const i=s.size>0?`?${s.toString()}`:"";return I(`/docker/nodes/${encodeURIComponent(e)}/logs${i}`)}function lG(e){return I("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function tT(e){return I("/nodes",{method:"POST",body:JSON.stringify(e)})}function nT(e){return I("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function sT(e,n){return I(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function iT(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config`)}function aT(e,n){return I(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function rT(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function Bg(e){return I(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function oT(e){const n=await I(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}async function cG(){return I("/mesh/state")}function dG(e,n,s,i){const r=s&&s!==i?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=Jo();l&&o.set("fn_token",l);const d=o.toString(),c=`/browse-directory${d?`?${d}`:""}`;return I(c)}function uG(e){return I("/create-directory",{method:"POST",body:JSON.stringify({path:e})})}function lT(e){return I("/projects",{method:"POST",body:JSON.stringify(e)})}function iw(e){return I(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function cT(e,n,s){return I(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function Ug(e){return I(`/projects/${encodeURIComponent(e)}/health`)}function dT(e){const n=K("/executor/stats",e);return Oi(n,()=>I(n))}function uT(e){return I(K("/system-stats",e))}function mT(e){return I(K("/kill-vitest",e),{method:"POST"})}function Hg(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity-feed${s}`)}function hT(e){return I(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function pT(e){return I(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function mG(){return I("/global-concurrency")}function hG(e){return I("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function fT(e,n){return I(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function aw(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function gT(e){return I(K("/missions",e))}function bT(e,n){return I(K("/missions",n),{method:"POST",body:JSON.stringify(e)})}function rw(e,n){return I(K(`/missions/${encodeURIComponent(e)}`,n))}function vT(e,n,s){return I(K(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function xT(e,n){return I(K(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yT(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return I(K(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function kT(e){return I(K("/missions/health",e))}function wT(e,n,s){return I(K(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function jT(e,n,s){return I(K(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function NT(e,n){return I(K(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ST(e,n,s){return I(K(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function CT(e,n,s){return I(K(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function _T(e,n){return I(K(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ET(e,n){return I(K(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function MT(e,n,s){return I(K(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function AT(e,n,s){return I(K(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function TT(e,n){return I(K(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function RT(e,n,s){return I(K(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function PT(e,n){return I(K(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function IT(e,n,s,i,r){return I(K(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function DT(e,n,s){return I(K(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify(s??{})})}function LT(e,n){return I(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function FT(e,n,s){return I(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function OT(e,n,s){return I(K(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $T(e,n,s){return I(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function zT(e,n,s){return I(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Vg(e,n){return I(K(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Ku(e,n){return I(K(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function qg(e,n){return I(K(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function BT(e,n){return I(K(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Wg(e,n){return I(K(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function UT(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return I(K(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function HT(e,n){return I(K(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function VT(e,n){return I(K(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function qT(e,n){return I(K(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function WT(e,n){return I(K(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function GT(e,n,s){return I(K(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function KT(e,n,s){return I(K("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function JT(e,n,s,i){return I(K("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function YT(e,n,s){return I(K(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function XT(e,n,s){return I(K("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}async function QT(e){const n=e?`?${new URLSearchParams({projectId:e}).toString()}`:"";return(await I(`/missions/interview/drafts${n}`)).drafts??[]}function ZT(e,n,s){return I(K(`/missions/interview/drafts/${encodeURIComponent(e)}/discard`,n),{method:"POST",body:JSON.stringify({tabId:s})})}function eR(e,n,s,i){return I(K("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function tR(e,n,s,i){const r=ci(K(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const d=()=>{o?.stop(),o=null},c=dl(r,{onOpen:()=>{d(),o=kc(e,n)},onMessage:m=>{m.data.startsWith(":")},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},question:m=>{try{s.onQuestion?.(JSON.parse(m.data))}catch(p){console.error("[mission-interview] Failed to parse question event:",p)}},summary:m=>{try{s.onSummary?.(JSON.parse(m.data))}catch(p){console.error("[mission-interview] Failed to parse summary event:",p)}},error:m=>{try{const p=JSON.parse(m.data);s.onError?.(p.message||p)}catch{s.onError?.(m.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{d(),s.onError?.(m)}});return l={close:()=>{d(),c.close()},isConnected:c.isConnected},l}function Nc(e,n,s){return K(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Sc(e,n,s){return K(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function nR(e,n){return I(Nc(e,"/start",n),{method:"POST"})}function sR(e,n,s,i){return I(Nc(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function iR(e,n,s,i){const r=ci(Nc(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const d=()=>{o?.stop(),o=null},c=dl(r,{onOpen:()=>{d(),o=kc(e,n)},onMessage:m=>{m.data.startsWith(":")},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},question:m=>{try{s.onQuestion?.(JSON.parse(m.data))}catch(p){console.error("[milestone-interview] Failed to parse question event:",p)}},summary:m=>{try{s.onSummary?.(JSON.parse(m.data))}catch(p){console.error("[milestone-interview] Failed to parse summary event:",p)}},error:m=>{try{const p=JSON.parse(m.data);s.onError?.(p.message||p)}catch{s.onError?.(m.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{d(),s.onError?.(m)}});return l={close:()=>{d(),c.close()},isConnected:c.isConnected},l}function aR(e,n,s){return I(Nc(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function rR(e,n){return I(Nc(e,"/skip",n),{method:"POST"})}function oR(e,n){return I(Sc(e,"/start",n),{method:"POST"})}function lR(e,n,s,i){return I(Sc(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function cR(e,n,s,i){const r=ci(Sc(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const d=()=>{o?.stop(),o=null},c=dl(r,{onOpen:()=>{d(),o=kc(e,n)},onMessage:m=>{m.data.startsWith(":")},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},question:m=>{try{s.onQuestion?.(JSON.parse(m.data))}catch(p){console.error("[slice-interview] Failed to parse question event:",p)}},summary:m=>{try{s.onSummary?.(JSON.parse(m.data))}catch(p){console.error("[slice-interview] Failed to parse summary event:",p)}},error:m=>{try{const p=JSON.parse(m.data);s.onError?.(p.message||p)}catch{s.onError?.(m.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{d(),s.onError?.(m)}});return l={close:()=>{d(),c.close()},isConnected:c.isConnected},l}function dR(e,n,s){return I(Sc(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function uR(e,n){return I(Sc(e,"/skip",n),{method:"POST"})}async function mR(e,n){try{return await I(K(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function pG(e){return I(K("/todos",e))}function fG(e,n){const s={title:e};return I(K("/todos",n),{method:"POST",body:JSON.stringify(s)})}function gG(e,n,s){const i={title:n};return I(K(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function bG(e,n){return I(K(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function vG(e,n,s){const i={text:n};return I(K(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function xG(e,n,s){const i=n;return I(K(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function yG(e,n){return I(K(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kG(e,n,s){return I(K(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Qo(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Up(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const i=s.toString(),r=await fetch(ci(`/ai-sessions${i?`?${i}`:""}`),{headers:Ki()});return r.ok?(await r.json()).sessions??[]:[]}async function hR(e){return I(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function pR(e){return I(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Aa(e){const n=await fetch(ci(`/ai-sessions/${encodeURIComponent(e)}`),{headers:Ki()});return n.ok?n.json():null}async function fR(e,n){const s=await I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function gR(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function bR(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function ow(e){const n=ci(`/ai-sessions/${encodeURIComponent(e)}`),s=await fetch(n,{method:"DELETE",headers:Ki()});if(s.ok||s.status===404)return;const i=s.headers.get("content-type")??"",r=await s.text(),o=i.includes("application/json");if(i.includes("text/html")||zk(r))throw new Error(`API returned HTML instead of JSON for ${n}. The endpoint may not be properly configured. (${s.status} ${s.statusText})`);if(!o){const m=r.length>160?`${r.slice(0,160)}...`:r;throw new Error(`API returned ${i||"an unknown content type"} instead of JSON for ${n}. (${s.status} ${s.statusText})${m?` Response: ${m}`:""}`)}let d;try{d=r?JSON.parse(r):null}catch{throw new Error(`API returned invalid JSON for ${n}. (${s.status} ${s.statusText})`)}const c=d;throw new Ka(c?.error||`Request failed for ${n}: ${s.status} ${s.statusText}`,s.status,c?.details)}function vR(e,n){return I(K(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function xR(e,n,s){return I(K(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function yR(e,n){return I(K(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function kR(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return I(`/messages/inbox${i}`)}function wR(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return I(`/messages/outbox${i}`)}function lw(e){return I(K("/messages/unread-count",e))}function jR(e,n){return I(K("/messages",n),{method:"POST",body:JSON.stringify(e)})}function NR(e,n){return I(K(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function SR(e){return I(K("/messages/read-all",e),{method:"POST"})}function CR(e,n){return I(K(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _R(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return I(K(i,s))}function ER(e,n){return I(K(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function MR(e){return I(K("/agents/mailbox/all",e))}function qc(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 i=s.size>0?`?${s.toString()}`:"";return I(`/approvals${i}`)}function Gg(e,n){return I(K(`/approvals/${encodeURIComponent(e)}`,n))}function AR(e,n,s){return I(K(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function wG(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function jG(e,n){return I(K(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function NG(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/performance${r}`)}function SG(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function CG(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function _G(e,n){return I(K(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function EG(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function MG(e,n){return I(K(`/agents/${encodeURIComponent(e)}/budget`,n))}function AG(e,n){return I(K(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function TG(e){return I(K("/plugins",e))}async function RG(e,n,s){const i=new URLSearchParams;e?.trim()&&i.set("q",e.trim()),n?.trim()&&i.set("category",n.trim());const r=i.size>0?`?${i.toString()}`:"";return(await I(K(`/plugins/registry${r}`,s))).plugins}async function PG(e,n){return I(K("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function IG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function DG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function LG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function FG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function OG(e,n,s){return I(K(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function $G(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function zG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function BG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function UG(e,n,s){return I(K(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function HG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function TR(e){const n=K("/plugins/ui-slots",e);return Oi(n,()=>I(n))}async function RR(e){return I(K("/plugins/dashboard-views",e))}async function VG(e){return I(K("/plugins/runtimes",e))}async function PR(e){return(await I(K("/skills/discovered",e))).skills}async function qG(e,n,s){return I(K("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function WG(e,n,s){return I(K("/skills/install",s),{method:"POST",body:JSON.stringify({source:e,skill:n})})}async function GG(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return I(K(`/skills/catalog${r}`,s))}async function KG(e,n){return(await I(K(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Kg(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return I(`/chat/sessions${i?`?${i}`:""}`)}async function IR(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await I(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function DR(e,n){return I(K("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function kl(e,n){return I(K(`/chat/sessions/${encodeURIComponent(e)}`,n))}function JG(e,n,s){return I(K(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function YG(e,n){return I(K(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function wl(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before),n?.order&&i.set("order",n.order);const r=i.toString();return I(K(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function LR(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 i=s.toString();return I(`/chat/rooms${i?`?${i}`:""}`)}function FR(e,n){const s={...e,...n?{projectId:n}:{}};return I(K("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function OR(e,n){return I(K(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $R(e,n){return I(K(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function Ju(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before),n?.order&&i.set("order",n.order);const r=i.toString();return I(K(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}async function zR(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ci(K(`/chat/rooms/${encodeURIComponent(e)}/attachments`,s)),{method:"POST",headers:Ki(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}function BR(e,n){return ci(K(`/chat/rooms/${encodeURIComponent(e)}/attachments/`,n))}function UR(e,n,s){return I(K(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function HR(e,n){return I(K(`/chat/rooms/${encodeURIComponent(e)}/messages`,n),{method:"DELETE"})}function VR(e,n){return I(K(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function qR(e){if(!e||typeof e!="object")return null;const n=e,s=typeof n.summary=="string"?n.summary.trim():"";if(!s)return null;const i=(()=>{const r=n.reference;if(!r||typeof r!="object")return;const o=r,l=typeof o.kind=="string"?o.kind.trim():"",d=typeof o.id=="string"?o.id.trim():"";if(!(!l||!d))return{kind:l,id:d,...typeof o.label=="string"&&o.label.trim()?{label:o.label.trim()}:{}}})();return{summary:s,...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...i?{reference:i}:{}}}function cw(e){try{const n=JSON.parse(e),s=qR(n);return s||(n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:e||"Stream error")}catch{return e||"Stream error"}}function WR(e,n,s,i,r,o){const l=ci(K(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),d=new AbortController;let c=!1,m=!1,p=!1;const h=Math.max(1e3,6e4);let u=null;const f=()=>{u&&(clearTimeout(u),u=null)},b=()=>{p||(p=!0,f())},y=(v,x)=>{if(v)switch(b(),v){case"thinking":try{s.onThinking?.(JSON.parse(x))}catch{s.onThinking?.(x)}break;case"text":try{s.onText?.(JSON.parse(x))}catch{s.onText?.(x)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(x))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(x))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(x))}catch{}break;case"done":m=!0;try{const k=JSON.parse(x);s.onDone?.({messageId:typeof k.messageId=="string"?k.messageId:"",...k.message&&typeof k.message=="object"?{message:k.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":m=!0,s.onError?.(cw(x));break}};return(async()=>{try{const v=Array.isArray(i)&&i.length>0,x=v?(()=>{const M=new FormData;return M.append("content",n),i.forEach(D=>M.append("attachments",D)),M})():JSON.stringify({content:n}),k=await fetch(l,{method:"POST",headers:v?Ki():Ki({"Content-Type":"application/json"}),body:x,signal:d.signal});if(!k.ok){const M=await k.text();let D=`Request failed: ${k.status}`;try{D=JSON.parse(M).error||D}catch{}s.onError?.(D);return}if(!k.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),u=setTimeout(()=>{m||c||p||(m=!0,s.onError?.("Timed out waiting for first response event"),d.abort())},h);const w=k.body.getReader(),g=new TextDecoder;let j="",S="",C=[];const E=(M,D=!1)=>{j+=M;const _=j.split(`
|
|
717
|
+
*/const p_=[["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"}]],Ws=mt("zap",p_),og=200,Io=[];function di(e,n,s){Io.push({ts:new Date().toISOString(),source:e,event:n,detail:s}),Io.length>og&&Io.splice(0,Io.length-og)}function f_(){return[...Io]}function g_(){Io.length=0}typeof window<"u"&&(window.__fusionDebug??={},window.__fusionDebug.dashboardTraces={get:f_,clear:g_});const Sh="fusion:version-reload",Ch="fusion:version-update",_p="fusion:version-reloaded-remote";let bu=!0;function qu(e){bu=e}function b_(){try{if(sessionStorage.getItem(Ch))return sessionStorage.removeItem(Ch),!0}catch{}return!1}function Ep(e){const n=!!sessionStorage.getItem(Sh);if(di("versionCheck","reload-attempt",{reason:e,alreadySet:n}),n){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(Sh,"1"),!bu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function v_(){try{return sessionStorage.getItem(_p)}catch{return null}}function x_(e){try{sessionStorage.setItem(_p,e)}catch{}}function y_(){try{sessionStorage.removeItem(_p)}catch{}}function k_(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 w_(e){return k_(e)?(Ep(`chunk load error: ${e?.message??e}`),!0):!1}async function j_(){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 N_(){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&&(bu=!1)}catch{}}const S_=6e4,C_=5*6e4;let lg=0,Wu=!1,$c=null,cg=0,dg=null;async function zc(e="initial"){if(!(Wu||document.visibilityState!=="visible")&&!(Date.now()-lg<S_)){lg=Date.now(),Wu=!0;try{const n=await j_();if(n===null){di("versionCheck","remote-unavailable",{trigger:e,visibilityState:document.visibilityState}),$c=null;return}if(n==="4151a19e8-da2d2882"){$c=null,y_();return}if(di("versionCheck","mismatch",{local:"4151a19e8-da2d2882",remote:n,trigger:e,visibilityState:document.visibilityState}),console.info("[versionCheck] mismatch",{local:"4151a19e8-da2d2882",remote:n,trigger:e}),$c!==n){$c=n,cg=Date.now(),di("versionCheck","mismatch-pending",{local:"4151a19e8-da2d2882",remote:n,trigger:e,visibilityState:document.visibilityState});return}if(di("versionCheck","mismatch-confirmed",{remote:n,trigger:e,elapsedMs:Date.now()-cg}),v_()===n){di("versionCheck","reload-suppressed",{remote:n,trigger:e,reason:"already-reloaded-remote-version"}),console.info("[versionCheck] reload already attempted for remote version",n);return}try{sessionStorage.setItem(Ch,"1")}catch{}bu&&x_(n),Ep(`build version changed: 4151a19e8-da2d2882 -> ${n}`)}finally{Wu=!1}}}function __(){N_(),window.setTimeout(()=>sessionStorage.removeItem(Sh),5e3),document.addEventListener("visibilitychange",()=>{zc("visibilitychange")}),window.addEventListener("focus",()=>{zc("focus")}),window.setTimeout(()=>void zc("initial"),2e3),dg===null&&(dg=window.setInterval(()=>{zc("poll")},C_))}class yc extends a.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!w_(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",i=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(oa,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:i}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Ys({children:e,onError:n}){return t.jsx(yc,{level:"page",onError:n,children:e})}function ir({children:e,onError:n}){return t.jsx(yc,{level:"modal",onError:n,children:e})}function E_({children:e,onError:n}){return t.jsx(yc,{level:"root",onError:n,children:e})}function Gu(){return typeof window>"u"?null:window.fusionShell??null}function M_(e){return e?.host==="desktop-shell"}function A_(e){const n=e.desktopModeState;return n?n.isFirstRun||n.desktopMode===null:!e.desktopMode}async function ug(e,n=3e4){const s=Date.now()+n;for(;Date.now()<s;){const r=(await e.getState()).localRuntime;if(r?.state==="running"&&(r.baseUrl||r.port))return{baseUrl:r.baseUrl??`http://127.0.0.1:${r.port}`};if(r?.state==="error")throw new Error(r.error??"Local runtime failed to start");await new Promise(o=>setTimeout(o,250))}throw new Error("Local runtime did not become ready in time")}function mg(e){const n=new URL(window.location.href);n.searchParams.set("serverBaseUrl",e),n.searchParams.set("shellKind","desktop-shell"),n.searchParams.set("shellMode","local"),window.location.replace(n.toString())}function T_({children:e}){const{t:n}=st("app"),[s,i]=a.useState({kind:"loading"});if(a.useEffect(()=>{const r=Gu();if(!r){i({kind:"bypass"});return}let o=!1;return(async()=>{try{const l=await r.getState();if(o)return;if(!M_(l)){i({kind:"bypass"});return}if(A_(l)){i({kind:"chooser",state:l});return}if(l.desktopMode==="local"){const d=new URLSearchParams(window.location.search);if(d.has("serverBaseUrl")){i({kind:"ready",serverBaseUrl:d.get("serverBaseUrl")??void 0});return}i({kind:"starting-local",message:n("desktop.startingLocalRuntime","Starting local Fusion runtime…")});const{baseUrl:c}=await ug(r);if(o)return;mg(c);return}i({kind:"ready"})}catch(l){if(o)return;i({kind:"local-error",message:l instanceof Error?l.message:String(l)})}})(),()=>{o=!0}},[]),a.useEffect(()=>{const r=Gu();if(!(!r?.onResetDesktopModeRequest||!r.resetDesktopMode))return r.onResetDesktopModeRequest(()=>{(async()=>{try{await r.resetDesktopMode?.()}catch{}const o=new URL(window.location.href);o.searchParams.delete("serverBaseUrl"),o.searchParams.delete("shellMode"),window.location.replace(o.toString())})()})},[]),s.kind==="loading"||s.kind==="starting-local"){const r=s.kind==="loading"?n("desktop.loading","Loading Fusion…"):s.message;return t.jsx("div",{className:"desktop-launch-gate",role:"status","aria-live":"polite",children:t.jsx("div",{className:"desktop-launch-gate__panel",children:t.jsx("p",{children:r})})})}return s.kind==="local-error"?t.jsx("div",{className:"desktop-launch-gate",role:"alert",children:t.jsxs("div",{className:"desktop-launch-gate__panel",children:[t.jsx("h2",{children:n("desktop.couldNotStart","Couldn't start local Fusion")}),t.jsx("p",{children:s.message}),t.jsx("button",{type:"button",className:"btn",onClick:()=>{window.location.reload()},children:n("desktop.retry","Retry")})]})}):s.kind==="chooser"?t.jsx(R_,{onPick:async r=>{const o=Gu();if(o){i({kind:"starting-local",message:r==="local"?n("desktop.startingLocalRuntime","Starting local Fusion runtime…"):n("desktop.settingUpRemote","Setting up remote connection…")});try{if(await o.setDesktopMode(r),r==="local"){const{baseUrl:l}=await ug(o);mg(l);return}await o.openConnectionManager(),window.location.reload()}catch(l){i({kind:"local-error",message:l instanceof Error?l.message:String(l)})}}}}):t.jsx(t.Fragment,{children:e})}function R_({onPick:e}){const{t:n}=st("app"),[s,i]=a.useState(null);return t.jsx("div",{className:"desktop-launch-gate",role:"dialog","aria-labelledby":"desktop-launch-gate-title",children:t.jsxs("div",{className:"desktop-launch-gate__panel",children:[t.jsx("h1",{id:"desktop-launch-gate-title",children:n("desktop.chooseMode","How do you want to run Fusion?")}),t.jsx("p",{children:n("desktop.chooseModeDescription","Run Fusion locally in this app, or connect to a Fusion server you're already running somewhere else.")}),t.jsxs("div",{className:"desktop-launch-gate__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",disabled:s!==null,onClick:()=>{i("local"),e("local")},children:s==="local"?n("desktop.starting","Starting…"):n("desktop.runLocalButton","Run Fusion Locally")}),t.jsx("button",{type:"button",className:"btn",disabled:s!==null,onClick:()=>{i("remote"),e("remote")},children:s==="remote"?n("desktop.opening","Opening…"):n("desktop.connectRemoteButton","Connect to Remote Fusion")})]})]})})}const P_="modulepreload",I_=function(e){return"/"+e},hg={},ln=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(m){return Promise.all(m.map(p=>Promise.resolve(p).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const d=document.querySelector("meta[property=csp-nonce]"),c=d?.nonce||d?.getAttribute("nonce");r=l(s.map(m=>{if(m=I_(m),m in hg)return;hg[m]=!0;const p=m.endsWith(".css"),h=p?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${m}"]${h}`))return;const u=document.createElement("link");if(u.rel=p?"stylesheet":P_,p||(u.as="script"),u.crossOrigin="",u.href=m,c&&u.setAttribute("nonce",c),document.head.appendChild(u),p)return new Promise((f,b)=>{u.addEventListener("load",f),u.addEventListener("error",()=>b(new Error(`Unable to preload CSS for ${m}`)))})}))}function o(l){const d=new Event("vite:preloadError",{cancelable:!0});if(d.payload=l,window.dispatchEvent(d),!d.defaultPrevented)throw l}return r.then(l=>{for(const d of l||[])d.status==="rejected"&&o(d.reason);return n().catch(o)})},D_=20;function L_(e){const n=e.todoCount>e.threshold&&e.idleNonEphemeralAgentCount===0;return{atRisk:n,todoCount:e.todoCount,inProgressCount:e.inProgressCount,inReviewCount:e.inReviewCount,idleNonEphemeralAgentCount:e.idleNonEphemeralAgentCount,threshold:e.threshold,reason:n?"todo-exceeds-threshold-and-no-idle-agents":"ok"}}const F_={themeMode:"dark",colorTheme:"default",dashboardFontScalePct:100,language:void 0,defaultProvider:void 0,defaultModelId:void 0,testMode:void 0,mergeRequestContractShadowEnabled:!1,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyAccessToken:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","message:agent-to-user","message:agent-to-agent","message:room","gridlock","board-stall-unrecovered","fallback-used","memory-dreams-processed","token-budget"],ntfyDashboardHost:void 0,taskTokenBudget:void 0,failureNotificationDelayMs:3e4,failureNotificationMode:"sticky-only",webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],customProviders:[],defaultProjectId:void 0,setupComplete:void 0,cliOnboardingCompletedAt:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,openrouterAppAttribution:void 0,openrouterModelFilters:void 0,openrouterProviderPreferences:void 0,opencodeGoModelSync:!0,updateCheckEnabled:!0,fnBinaryCheckEnabled:!0,updateCheckFrequency:"daily",autoReloadOnVersionChange:!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,persistAgentThinkingLogPermanent:!1,persistAgentThinkingLogEphemeral:!1,persistAgentThinkingLog:!1,agentMemoryInclusionMode:"full",secretsAccessPolicy:void 0,secretsSyncPassphraseConfigured:!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}},worktrunk:{enabled:!1,binaryPath:void 0,installedBinaryPath:void 0,onFailure:"fail"},owningNodeHandoffPolicy:"reassign-to-local",experimentalFeatures:{},cliAgents:{}},O_={globalPause:!1,globalPauseReason:void 0,defaultWorkflowId:void 0,enabledBuiltinWorkflowIds:void 0,approvedWorkflowCliCommands:void 0,approvedCliAutonomyAdapters:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,autoClaimCandidatesInPrompt:5,tombstoneStickyWindowDays:7,heartbeatScopeDiscipline:"strict",heartbeatPromptTemplate:"default",groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,testMode:void 0,mergeRequestContractShadowEnabled:!1,mergeStrategy:"direct",directMergeCommitStrategy:"always-squash",mergeIntegrationWorktree:"reuse-task-worktree",mergeAdvanceAutoSync:"stash-and-ff",integrationBranch:void 0,pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",owningNodeHandoffPolicy:"reassign-to-local",defaultNodeId:void 0,secretsEnv:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,executorAllowSiblingBranchRename:!1,worktreeNaming:"random",worktrunk:{enabled:!1,binaryPath:void 0,installedBinaryPath:void 0,onFailure:"fail"},worktreesDir:void 0,taskPrefix:"FN",taskAttributionTrailerNames:["Fusion-Task-Id"],commitMsgHookEnabled:!0,includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",defaultProviderOverride:void 0,defaultModelIdOverride:void 0,modelPresets:[],autoSelectModelPreset:!1,completionDocumentationMode:"off",defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,mergerAutostashMaxAgeHours:24,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,prerebaseAutoEnabled:!0,prerebaseHotFiles:["AGENTS.md","packages/core/src/store.ts","packages/core/src/db.ts","packages/engine/src/executor.ts","packages/engine/src/scheduler.ts","packages/engine/src/merger.ts","packages/dashboard/app/styles.css"],prerebaseDivergenceThreshold:50,mergeConflictStrategy:"smart-prefer-main",merger:{mode:"ai",maxReviewPasses:3,allowDirtyLocalCheckoutSync:!1},mergeDiffVolumeMinLines:void 0,mergeDiffVolumeThreshold:void 0,mergeDiffVolumeAllowlist:void 0,mergeStrategyOverlapBehavior:"flip-to-prefer-branch",postMergeAuditMode:"warn",mergeAuditAutoRecovery:"ai-assisted",autoRecovery:{mode:"deterministic-only",maxRetries:3},reliabilityStatsResetAt:void 0,buildTimeoutMs:3e5,ephemeralAgentsEnabled:!0,agentProvisioning:{},sandboxProvisioning:{},defaultAgentPermissionPolicy:void 0,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:6e5,dispatchOscillationThreshold:5,dispatchOscillationWindowMs:6e4,dispatchOscillationSettleMs:5e3,runtimeStopDrainMs:2e3,engineActiveSinceMs:void 0,engineActivationGraceMs:5*6e4,inReviewStallDeadlockThreshold:3,stalePausedReviewThresholdMs:1440*6e4,inReviewStalledThresholdMs:1440*6e4,stalePausedTodoThresholdMs:1440*6e4,pausedScopeDecayMs:30*6e4,metaTaskStallAutoCloseMs:120*6e4,metaTaskActiveExecutionGraceMs:30*6e4,boardStallSweepWindowMs:120*6e4,boardStallBlockedGrowthThreshold:3,capacityRiskBannerEnabled:!1,capacityRiskTodoThreshold:20,backlogPressureAlertEnabled:!0,backlogPressureRatioThreshold:10,backlogPressureMinTodoCount:5,backlogPressureAlertCooldownMs:1440*6e4,dependencyBlockedTodoReportEnabled:!0,dependencyBlockedTodoFreshAgeMs:30*6e4,dependencyBlockedTodoStaleAgeMs:240*6e4,dependencyBlockedTodoMinCount:1,dependencyBlockedTodoReportCooldownMs:360*6e4,staleHighFanoutBlockerAgeThresholdMs:7200*1e3,staleInProgressWarningMs:240*6e4,staleInProgressCriticalMs:1440*6e4,staleInReviewWarningMs:1440*6e4,staleInReviewCriticalMs:4320*6e4,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxBranchConflictRecoveries:5,maxTotalRetriesBeforeFail:25,preserveProgressOnStuckRequeue:!0,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:3e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,doneAutoArchiveDays:0,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,githubCloseSourceIssueOnDone:!1,githubTrackingEnabledByDefault:!1,githubTrackingDefaultRepo:void 0,githubTrackingDedupEnabled:!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,taskTokenBudget:void 0,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,reflectionIntervalMs:36e5,reflectionAfterTask:!0,showQuickChatFAB:!1,chatAutoCleanupDays:0,mailAutoCleanupDays:0,operationalLogRetentionDays:30,agentLogFileRetentionDays:0,chatRoomRecentVerbatimMessages:25,chatRoomCompactionFetchLimit:200,chatRoomSummaryMaxChars:3e3,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}},sandbox:{backend:"native",policy:{allowNetwork:!0,allowedPaths:[]},failureMode:"fail-hard"},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},$_=Object.freeze(Object.keys(F_)),z_=Object.freeze(Object.keys(O_));function J7(e){return $_.includes(e)}function Y7(e){return z_.includes(e)}function X7(e,n){const s=n.ephemeral?e?.persistAgentThinkingLogEphemeral:e?.persistAgentThinkingLogPermanent;return typeof s=="boolean"?s:typeof e?.persistAgentThinkingLog=="boolean"?e.persistAgentThinkingLog:!1}function Re(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const B_={provider:"mock",modelId:"scripted"};function U_(e){return e?.testMode===!0||e?.defaultProvider?.trim().toLowerCase()==="mock"}function eo(e,n){return U_(n)?B_:e}function H_(e){return!!(e?.provider&&e?.modelId)}function to(...e){for(const n of e)if(H_(n))return{provider:n.provider,modelId:n.modelId};return{}}function Mp(e){return eo(to({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId}),e)}function V_(e){return eo(to({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Mp(e)),e)}function q_(e){return eo(to({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Mp(e)),e)}function W_(e){return eo(to({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Mp(e)),e)}function Ap(e,n){return eo(to({provider:e.modelProvider,modelId:e.modelId},V_(n)),n)}function Tp(e,n){return eo(to({provider:e.validatorModelProvider,modelId:e.validatorModelId},W_(n)),n)}function Rp(e,n){return eo(to({provider:e.planningModelProvider,modelId:e.planningModelId},q_(n)),n)}const Q7=["off","minimal","low","medium","high"],$d=["triage","todo","in-progress","in-review","done","archived"],zd="triage";function vu(e){return typeof e=="string"&&$d.includes(e)}function G_(e,n=zd){return vu(e)?e:n}const xr=["low","normal","high","urgent"],yi="normal",Pp=5,Pk=7200*1e3,K_=["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"],Ik=["en","zh-CN","zh-TW","fr","es","ko"],J_="en";function pg(e){return typeof e=="string"&&Ik.includes(e)}let fg=!1;function Z7(e){return e==="reuse-task-worktree"||e==="cwd-integration-branch"?e:e==="cwd-main"?(fg||(fg=!0,console.warn("[merger] settings.mergeIntegrationWorktree=cwd-main is legacy; normalized to cwd-integration-branch")),"cwd-integration-branch"):"reuse-task-worktree"}function eq(e){return e==="off"||e==="ff-only"||e==="stash-and-ff"?e:"stash-and-ff"}const xu=/^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/,To={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},gg={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"},_h={triage:["todo","archived"],todo:["in-progress","triage","archived"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo","triage"],done:["todo","triage","archived"],archived:["done"]};function Y_(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)}const tq=["git_write","file_write_delete","command_execution","network_api","task_agent_mutation"],nq={git_write:["git commit","git push","git merge","git branch -d","git worktree add","write","edit"],file_write_delete:["write","edit","fn_task_attach"],command_execution:["bash (non-git)","read","find","grep","ls"],network_api:["fn_research_run (web/research)","fn_web_fetch","worktrunk_install"],task_agent_mutation:["fn_task_create","fn_delegate_task","fn_task_import_github","fn_task_import_github_issue","fn_spawn_agent","fn_update_agent_config","fn_update_identity"]},sq=["fn_send_message","fn_post_room_message","fn_read_messages","fn_task_log","fn_task_done","fn_heartbeat_done","fn_task_document_write","fn_task_document_read","fn_memory_search","fn_memory_get","fn_memory_append","fn_read_evaluations","fn_reflect_on_performance"],iq=["always","trusted-only","never"];function cl(e){return e.replace(/\\/g,"/")}function Ip(e){return e.replace(/[\\/]+$/g,"")}function Dp(e){const n=cl(Ip(e));return n?n.split("/").filter(Boolean):[]}function Lp(e){const n=cl(Ip(e));if(!n)return e;const s=n.split("/").filter(Boolean);return s[s.length-1]||n}function Dk(e,n){const s=Dp(e);return s.length===0?cl(e):s.slice(-2).join("/")}function X_(e){const n=cl(Ip(e)),s=n.lastIndexOf("/");return s<0?"":n.slice(0,s+1)}function Eh(e,n){return!e||e==="."?n:[...Dp(e),n].join("/")}function Q_(e){const n=Dp(e);return n.length===0?".":(n.pop(),n.length===0?".":n.join("/"))}function aq(e){const n=cl(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 d=0;d<o.length;d+=1)l.push({label:o[d],path:`${r}${o.slice(0,d+1).join("/")}`});return l}if(n.startsWith("/")){const r=n.split("/").filter(Boolean),o=[{label:"/",path:"/"}];for(let l=0;l<r.length;l+=1)o.push({label:r[l],path:`/${r.slice(0,l+1).join("/")}`});return o}const i=n.split("/").filter(Boolean);return i.map((r,o)=>({label:r,path:i.slice(0,o+1).join("/")}))}const Z_={active:{label:"Active",color:"var(--color-success)",icon:Ds},paused:{label:"Paused",color:"var(--color-warning)",icon:ia},errored:{label:"Error",color:"var(--color-error)",icon:oi},initializing:{label:"Initializing",color:"var(--color-info)",icon:Et}},Lk={label:"Unknown",color:"var(--color-error)",icon:oi};function eE(e){return e?e.split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" "):Lk.label}function Fk(e){const n=Z_[e];return n||{...Lk,label:eE(e)}}function Ok(e){return e==="initializing"}const bg="fusion_project_bookmarks";function tE(){const[e,n]=a.useState(()=>{try{const r=localStorage.getItem(bg);if(r){const o=JSON.parse(r);if(Array.isArray(o))return new Set(o.filter(l=>typeof l=="string"))}}catch{}return new Set});a.useEffect(()=>{try{localStorage.setItem(bg,JSON.stringify([...e]))}catch{}},[e]);const s=a.useCallback(r=>{n(o=>{const l=new Set(o);return l.has(r)?l.delete(r):l.add(r),l})},[]),i=a.useCallback(r=>e.has(r),[e]);return{bookmarkedIds:e,toggleBookmark:s,isBookmarked:i}}function vg({text:e,query:n}){if(!n.trim())return t.jsx(t.Fragment,{children:e});const s=e.toLowerCase(),i=n.toLowerCase(),r=s.indexOf(i);if(r===-1)return t.jsx(t.Fragment,{children:e});const o=e.slice(0,r),l=e.slice(r,r+n.length),d=e.slice(r+n.length);return t.jsxs(t.Fragment,{children:[o,t.jsx("mark",{className:"project-selector__highlight",children:l}),d]})}function nE({projects:e,currentProject:n,onSelect:s,onViewAll:i,recentProjectIds:r=[],allowSingleProject:o=!1,viewAllLabel:l}){const{t:d}=st("app"),[c,m]=a.useState(!1),[p,h]=a.useState(""),[u,f]=a.useState(-1),b=a.useRef(null),y=a.useRef(null),v=a.useRef(null),x=a.useRef(new Map),{bookmarkedIds:k,toggleBookmark:w,isBookmarked:g}=tE();a.useEffect(()=>{if(!c)return;const R=L=>{b.current&&!b.current.contains(L.target)&&y.current&&!y.current.contains(L.target)&&(m(!1),h(""))};return document.addEventListener("mousedown",R),()=>document.removeEventListener("mousedown",R)},[c]),a.useEffect(()=>{if(!c)return;const R=L=>{L.key==="Escape"&&(m(!1),h(""),y.current?.focus())};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[c]),a.useEffect(()=>{c&&setTimeout(()=>v.current?.focus(),0)},[c]);const j=a.useMemo(()=>r.map(R=>e.find(L=>L.id===R)).filter(R=>R!==void 0&&R.id!==n?.id).slice(0,3),[r,e,n]),S=a.useMemo(()=>{if(!p.trim())return e;const R=p.toLowerCase();return e.filter(L=>L.name.toLowerCase().includes(R)||L.path.toLowerCase().includes(R))},[e,p]),C=a.useMemo(()=>{if(!p.trim())return null;const R=p.toLowerCase(),O=S.filter(J=>J.id!==n?.id).filter(J=>J.name.toLowerCase()===R);return O.length===1?O[0]:null},[S,p,n]),E=a.useMemo(()=>{const R=new Set(j.map(B=>B.id)),L=n?.id,O=!!p.trim(),J=O?[]:S.filter(B=>B.id!==L&&k.has(B.id)&&!R.has(B.id)),A=new Set([...J.map(B=>B.id),...O?[]:R]),de=S.filter(B=>B.id!==L&&!A.has(B.id));return{bookmarked:J,recent:O?[]:j,others:de}},[S,j,n,p,k]),F=a.useMemo(()=>{const R=E.bookmarked.length,L=E.recent.length,O=E.others.length;return R+L+O+1},[E]),M=a.useCallback(R=>{switch(R.key){case"ArrowDown":R.preventDefault(),f(L=>L<F-1?L+1:0);break;case"ArrowUp":R.preventDefault(),f(L=>L>0?L-1:F-1);break;case"Enter":if(R.preventDefault(),u>=0){const L=E.bookmarked.length,O=E.recent.length,J=E.others.length;u<L?s?.(E.bookmarked[u]):u<L+O?s?.(E.recent[u-L]):u<L+O+J?s?.(E.others[u-L-O]):i(),m(!1),h("")}else C&&(s?.(C),m(!1),h(""));break;case"Home":R.preventDefault(),f(0);break;case"End":R.preventDefault(),f(F-1);break}},[u,F,E,s,i,C]);a.useEffect(()=>{if(c&&p.trim())if(C){const R=E.bookmarked.length,L=E.recent.length,O=E.others.findIndex(J=>J.id===C.id);O>=0&&f(R+L+O)}else E.others.length>0?f(E.bookmarked.length+E.recent.length):f(-1);else c&&!p.trim()&&f(-1)},[c,p,C,E]),a.useEffect(()=>{if(u<0)return;const R=x.current.get(u);R&&R.scrollIntoView({block:"nearest"})},[u]);const D=a.useCallback(R=>{s?.(R),m(!1),h("")},[s]),_=a.useCallback(()=>{i(),m(!1),h("")},[i]),V=a.useCallback(()=>{m(R=>(R||h(""),!R))},[]),N=R=>{const L=Fk(R),O=L.icon;return t.jsx(O,{size:14,style:{color:L.color},className:Ok(R)?"animate-spin":""})},$=R=>{const L=g(R);return t.jsx("span",{role:"button",tabIndex:0,className:`project-selector__bookmark ${L?"bookmarked":""}`,onClick:O=>{O.stopPropagation(),w(R)},onKeyDown:O=>{(O.key==="Enter"||O.key===" ")&&(O.stopPropagation(),O.preventDefault(),w(R))},"aria-label":L?d("projectSelector.removeBookmark","Remove bookmark"):d("projectSelector.addBookmark","Bookmark project"),"data-testid":`bookmark-toggle-${R}`,children:t.jsx(Od,{size:14,fill:L?"currentColor":"none"})})};return!o&&e.length<=1?null:t.jsxs("div",{className:"project-selector",ref:b,children:[t.jsxs("button",{ref:y,className:`project-selector__trigger ${c?"open":""}`,onClick:V,"aria-expanded":c,"aria-haspopup":"listbox","aria-label":d("projectSelector.ariaLabel","Select project"),title:n?.name?d("projectSelector.switchProjectTitle","Switch project (current: {{name}})",{name:n.name}):d("projectSelector.projectsTitle","Projects"),"data-testid":"project-selector-trigger",children:[t.jsx(Zs,{size:16,className:"project-selector__trigger-icon"}),t.jsx("span",{className:"project-selector__trigger-text",children:n?.name||d("projectSelector.projects","Projects")}),t.jsx(Ln,{size:14,className:`project-selector__trigger-chevron ${c?"rotate":""}`})]}),c&&t.jsxs("div",{className:"project-selector__dropdown",role:"listbox","aria-label":"Projects",onKeyDown:M,"data-testid":"project-selector-dropdown",children:[t.jsxs("div",{className:"project-selector__search",children:[t.jsx(na,{size:14,className:"project-selector__search-icon"}),t.jsx("input",{ref:v,type:"text",placeholder:d("projectSelector.searchPlaceholder","Search projects..."),value:p,onChange:R=>h(R.target.value),className:"project-selector__search-input","data-testid":"project-selector-search-input","aria-label":d("projectSelector.searchAriaLabel","Type to search projects")}),p&&t.jsx("button",{className:"project-selector__search-clear",onClick:()=>h(""),"aria-label":d("projectSelector.clearSearch","Clear search"),children:t.jsx(Fn,{size:12})})]}),C&&t.jsx("div",{className:"project-selector__exact-match","data-testid":"project-selector-exact-match",children:d("projectSelector.exactMatch","Exact match — press Enter to select")}),E.bookmarked.length>0&&t.jsxs("div",{className:"project-selector__section",children:[t.jsxs("div",{className:"project-selector__section-header",children:[t.jsx(Od,{size:12,fill:"currentColor"}),t.jsx("span",{children:d("projectSelector.bookmarked","Bookmarked")})]}),E.bookmarked.map((R,L)=>t.jsxs("button",{ref:O=>{O?x.current.set(L,O):x.current.delete(L)},className:`project-selector__item ${u===L?"highlighted":""}`,onClick:()=>D(R),role:"option","aria-selected":n?.id===R.id,children:[N(R.status),t.jsx("span",{className:"project-selector__item-name",children:R.name}),$(R.id),n?.id===R.id&&t.jsx(Qs,{size:14,className:"project-selector__item-check"})]},R.id))]}),E.recent.length>0&&t.jsxs("div",{className:"project-selector__section",children:[t.jsxs("div",{className:"project-selector__section-header",children:[t.jsx(ha,{size:12}),t.jsx("span",{children:d("projectSelector.recent","Recent")})]}),E.recent.map((R,L)=>{const O=E.bookmarked.length+L;return t.jsxs("button",{ref:J=>{J?x.current.set(O,J):x.current.delete(O)},className:`project-selector__item ${u===O?"highlighted":""}`,onClick:()=>D(R),role:"option","aria-selected":n?.id===R.id,children:[N(R.status),t.jsx("span",{className:"project-selector__item-name",children:R.name}),$(R.id),n?.id===R.id&&t.jsx(Qs,{size:14,className:"project-selector__item-check"})]},R.id)})]}),t.jsxs("div",{className:"project-selector__section",children:[(E.bookmarked.length>0||E.recent.length>0)&&t.jsxs("div",{className:"project-selector__section-header",children:[t.jsx(Zs,{size:12}),t.jsx("span",{children:d("projectSelector.allProjects","All Projects")})]}),E.others.length===0&&p?t.jsxs("div",{className:"project-selector__no-results","data-testid":"project-selector-no-results",children:[t.jsx(na,{size:14,className:"project-selector__no-results-icon"}),t.jsx("span",{children:d("projectSelector.noResults",'No projects match "{{query}}"',{query:p})})]}):E.others.map((R,L)=>{const O=E.bookmarked.length+E.recent.length+L,J=C?.id===R.id;return t.jsxs("button",{ref:A=>{A?x.current.set(O,A):x.current.delete(O)},className:`project-selector__item ${u===O?"highlighted":""} ${J?"exact-match":""}`,onClick:()=>D(R),role:"option","aria-selected":n?.id===R.id,"data-testid":`project-selector-item-${R.id}`,children:[N(R.status),t.jsxs("div",{className:"project-selector__item-info",children:[t.jsx("span",{className:"project-selector__item-name",children:t.jsx(vg,{text:R.name,query:p})}),R.path&&t.jsx("span",{className:"project-selector__item-path",children:t.jsx(vg,{text:Dk(R.path),query:p})})]}),J&&t.jsx("span",{className:"project-selector__exact-badge",children:d("projectSelector.exact","Exact")}),$(R.id),n?.id===R.id&&t.jsx(Qs,{size:14,className:"project-selector__item-check"})]},R.id)})]}),t.jsx("div",{className:"project-selector__footer",children:t.jsxs("button",{ref:R=>{const L=F-1;R?x.current.set(L,R):x.current.delete(L)},className:`project-selector__view-all ${u===F-1?"highlighted":""}`,onClick:_,"data-testid":"manage-projects-action",children:[t.jsx(qo,{size:14}),t.jsx("span",{children:l??d("projectSelector.viewAll","View All Projects")})]})})]})]})}const Fp="fn.authToken",xg="token",sE="fn_token";let Do,yg=!1,Bd=!1;const Mh="fn:auth-token-recovery-required",Ah="fusion:oauth-relogin-success";function iE(){try{const e=window.localStorage.getItem(Fp);return e&&e.length>0?e:void 0}catch{return}}function $k(e){try{window.localStorage.setItem(Fp,e)}catch{}}function aE(){if(!(yg||typeof window>"u")){yg=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(xg);if(!n)return;$k(n),e.searchParams.delete(xg);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Jo(){if(Do!==void 0)return Do;const e=aE();if(e)return Do=e,e;const n=iE();if(n)return Do=n,n}function rE(e){Do=e,Bd=!1,$k(e)}function oE(){Do=void 0,Bd=!1;try{window.localStorage.removeItem(Fp)}catch{}}function kg(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function lE(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function cE(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!lE(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=kg(e.protocol)===kg(n.protocol);return s&&i&&r}function dE(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 pa(e){const n=Jo();if(!n||typeof window>"u")return e;const s=dE(e);return!s||!cE(s.parsed)?e:(s.parsed.searchParams.set(sE,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function Ki(e){const n=Jo();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function uE(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function mE(){typeof window>"u"||Bd||(Bd=!0,window.dispatchEvent(new CustomEvent(Mh)))}async function hE(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();uE(i)&&mE()}catch{}}function pE(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Jo();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=Jo(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const c=new URL(o,window.location.origin);return c.origin!==window.location.origin?!1:c.pathname.startsWith("/api/")||c.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,i);const d=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!d.has("Authorization")&&d.set("Authorization",`Bearer ${r}`),e(s,{...i,headers:d}).then(c=>(hE(c),c))}}const go=new Map;function fE(){let e,n;return{external:new Promise((i,r)=>{e=i,n=r}),resolve:e,reject:n,done:!1}}function wg(e,n){n.then(s=>{e.done||(e.done=!0,e.resolve(s))},s=>{e.done||(e.done=!0,e.reject(s))})}function Oi(e,n,s){const i=go.get(e);if(i&&!i.done)return s?.forceFresh&&wg(i,n()),i.external;const r=fE();return wg(r,n()),r.external.then(()=>{go.get(e)===r&&go.delete(e)},()=>{go.get(e)===r&&go.delete(e)}),go.set(e,r),r.external}class Ka extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function zk(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function ci(e){return`/api${e}`}async function I(e,n={}){const s=ci(e),i=Jo(),r=(()=>{if(i){const u=new Headers(n.headers??{});return u.has("Content-Type")||u.set("Content-Type","application/json"),Ki(u)}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")??"",d=await o.text(),c=l.includes("application/json");if(l.includes("text/html")||zk(d))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!c){const h=d.length>160?`${d.slice(0,160)}...`:d;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let p;try{p=d?JSON.parse(d):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=p;throw new Ka(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return p}function gE(){return I("/health")}function Bk(){return I("/health/refresh",{method:"POST"})}function rq(){return I("/updates/check")}function Uk(e,n,s,i,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),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return I(`/tasks${l}`)}async function pr(e,n){const i=ci(K(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:Ki({"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")}class bE extends Error{matches;constructor(n){super("duplicate_candidates"),this.name="DuplicateCandidatesError",this.matches=n}}async function vE(e,n){return(await I(K("/tasks/duplicate-check",n),{method:"POST",body:JSON.stringify(e)})).matches??[]}async function Hk(e,n,s){const{title:i,description:r,column:o,dependencies:l,breakIntoSubtasks:d,enabledWorkflowSteps:c,workflowId:m,assignedAgentId:p,modelPresetId:h,modelProvider:u,modelId:f,validatorModelProvider:b,validatorModelId:y,planningModelProvider:v,planningModelId:x,thinkingLevel:k,summarize:w,reviewLevel:g,executionMode:j,autoMerge:S,priority:C,source:E,nodeId:F,branch:M,baseBranch:D,branchSelection:_,githubTracking:V,acknowledgedDuplicates:N,bypassDuplicateCheck:$}=e;try{return await jc(K("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:i,description:r,column:o,dependencies:l,breakIntoSubtasks:d,enabledWorkflowSteps:c,workflowId:m,assignedAgentId:p,modelPresetId:h,modelProvider:u,modelId:f,validatorModelProvider:b,validatorModelId:y,planningModelProvider:v,planningModelId:x,thinkingLevel:k,summarize:w,reviewLevel:g,executionMode:j,autoMerge:S,priority:C,source:E,nodeId:F,branch:M,baseBranch:D,branchSelection:_,githubTracking:V,acknowledgedDuplicates:N,bypassDuplicateCheck:$})})}catch(R){if(R instanceof Ka&&R.status===409&&R.message==="duplicate_candidates"){const L=Array.isArray(R.details?.matches)?R.details?.matches:[];throw new bE(L)}throw R}}function si(e,n,s){return I(K(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function xE(e,n,s,i,r,o,l,d,c){return I(K("/tasks/batch-update-models",c),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:d})})}function yE(e,n,s,i){return I(K(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof i=="object"&&i?.preserveProgress?{preserveProgress:!0}:{}})})}function kE(e,n,s){return I(K(`/tasks/${e}/custom-fields`,s),{method:"PATCH",headers:{"Content-Type":"application/json"},body:JSON.stringify({customFields:n})})}function Op(e){return I(K("/tasks/board-workflows",e))}function wE(e,n){return I(K(`/tasks/${e}/promote`,n),{method:"POST"})}function jE(e,n,s){const i=new URLSearchParams;s?.removeDependencyReferences&&i.set("removeDependencyReferences","true"),s?.removeLineageReferences&&i.set("removeLineageReferences","true"),s?.githubIssueAction&&i.set("githubIssueAction",s.githubIssueAction),s?.allowResurrection&&i.set("allowResurrection","true");const r=i.size>0?`?${i.toString()}`:"";return I(K(`/tasks/${e}${r}`,n),{method:"DELETE"})}function NE(e,n){return I(K(`/tasks/${e}/merge`,n),{method:"POST"})}function Vk(e,n){return I(K(`/branch-groups/${e}`,n))}function qk(e,n){return I(K(`/branch-groups/${e}/promote`,n),{method:"POST",body:JSON.stringify({})})}function Wk(e,n){return I(K(`/branch-groups/${e}/abandon`,n),{method:"POST",body:JSON.stringify({})})}function SE(e,n){return I(K(`/tasks/${e}/retry`,n),{method:"POST"})}function CE(e,n){return I(K(`/tasks/${e}/recover-branch-binding`,n),{method:"POST"})}function _E(e,n){return I(K(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function EE(e,n){return I(K(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Gk(e,n){return I(K(`/tasks/${e}/pause`,n),{method:"POST"})}function Kk(e,n){return I(K(`/tasks/${e}/unpause`,n),{method:"POST"})}function ME(e,n,s){const i=new URLSearchParams;s?.removeLineageReferences&&i.set("removeLineageReferences","true");const r=i.size>0?`?${i.toString()}`:"";return I(K(`/tasks/${e}/archive${r}`,n),{method:"POST"})}function AE(e,n){return I(K(`/tasks/${e}/unarchive`,n),{method:"POST"})}function TE(e){return I(K("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function RE(e,n){return I(K(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function PE(e,n){return I(K(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Jk(e){const n=K("/config",e);return Oi(n,()=>I(n))}function yu(e,n){const s=K("/settings",e);return Oi(s,()=>I(s),n)}function Bc(e,n){return I(K("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function IE(e){return I(K("/update-check",e))}function oq(e){return I(K("/remote/settings",e))}function lq(e,n){return I(K("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function cq(e){return I(K("/remote/status",e))}function dq(e){return I(K("/remote/install-cloudflared",e),{method:"POST"})}function uq(e){return I(K("/remote/tunnel/start",e),{method:"POST"})}function mq(e){return I(K("/remote/tunnel/stop",e),{method:"POST"})}function hq(e){return I(K("/remote/tunnel/kill-external",e),{method:"POST"})}function pq(e){return I(K("/remote/token/persistent/regenerate",e),{method:"POST"})}function fq(e,n){return I(K("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function Yk(e,n,s){const i=new URLSearchParams;e&&i.set("format",e),i.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&i.set("ttlMs",String(s));const r=i.toString();return r?`?${r}`:""}function gq(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=Yk(null,s,i);return I(K(`/remote/url${r}`,n))}function bq(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=Yk(e,i,r);return I(K(`/remote/qr${o}`,s))}function vq(e){return I(K("/memory",e))}function xq(e,n){return I(K("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function yq(e){return I(K("/memory/files",e))}function kq(e,n){const s=`path=${encodeURIComponent(e)}`;return I(K(`/memory/file?${s}`,n))}function wq(e,n,s){return I(K("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function jq(e,n){let s,i=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:i=r}return I(K("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function Nq(e){return I(K("/memory/dream",e),{method:"POST"})}function Sq(e){return I(K("/memory/insights",e))}function Cq(e,n){return I(K("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function _q(e){return I(K("/memory/extract",e),{method:"POST"})}function Eq(e){return I(K("/memory/audit",e))}function Mq(e){return I(K("/memory/stats",e))}function Aq(e){return I(K("/memory/backend",e))}function Tq(e){return I(K("/memory/install-qmd",e),{method:"POST"})}function Rq(e,n){return I(K("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Ja(e){return Oi("/settings/global",()=>I("/settings/global"),e)}function Ms(e){return I("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function Pq(e){return I(K("/settings/scopes",e))}function Iq(e){return I(K("/settings/pi-extensions",e))}function Dq(e,n){return I(K("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function Lq(e,n,s){return I(K("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function Fq(){return I("/pi-settings")}async function Oq(e){return I("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function $q(e){return I("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function zq(e){return I(K("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function ku(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ci(K(`/tasks/${e}/attachments`,s)),{method:"POST",headers:Ki(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function DE(e,n,s){return I(K(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function jg(e,n,s){const i=new URLSearchParams;s?.limit!==void 0&&i.set("limit",String(s.limit)),s?.offset!==void 0&&i.set("offset",String(s.offset));const r=i.toString()?`?${i.toString()}`:"",o=K(`/tasks/${e}/logs${r}`,n),l=await fetch(ci(o),{headers:Ki()});if(!l.ok){const p=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(p.error||`HTTP ${l.status}`)}const d=await l.json(),c=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):d.length,m=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:d,total:c,hasMore:m}}function LE(e,n,s,i){return I(K(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function FE(e,n,s){return I(K(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function OE(e,n){return I(K(`/tasks/${e}/documents`,n))}function $E(e,n,s){return I(K(`/tasks/${e}/documents/${n}/revisions`,s))}async function Bq(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const i=s.toString(),r=`/documents${i?`?${i}`:""}`;return I(K(r,n))}function Uq(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return I(K(r,e))}function Ng(e,n,s,i,r){return I(K(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function zE(e,n,s){return I(K(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function BE(e,n,s){return I(K(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function UE(e,n,s){return I(K(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function HE(e,n){return I(K(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function VE(e,n,s){return I(K(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function fa(){return I("/models")}function qE(){return I("/usage")}function WE(){return I("/providers/claude-cli/status")}function GE(){return I("/system/fn-binary/status")}function KE(){return I("/system/fn-binary/install",{method:"POST"})}function JE(){return I("/providers/droid-cli/status")}function YE(){return I("/providers/cursor-cli/status")}function XE(){return I("/providers/llama-cpp/status")}async function Hq(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/hermes/status${n}`)}async function Vq(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await I(`/providers/hermes/profiles${n}`)).profiles??[]}async function qq(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/openclaw/status${n}`)}async function Wq(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),I(`/providers/paperclip/status?${n.toString()}`)}async function Gq(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function Kq(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function Jq(e){return I("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function Yq(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function Xq(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await I(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function Qq(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await I(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function Zq(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function QE(e){return I("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function ZE(e){return I("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function eM(e){return I("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function tM(e){return I("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function nM(){const n=(await I("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":s.apiType==="google-generative-ai"?"google-generative-ai":s.apiType==="openai-responses"?"openai-responses":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(i=>({id:i.id,name:i.name}))}));return Object.assign(n,{providers:n})}function sM(e){return I("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function eW(e,n){const s=n,i={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":s.api==="google-generative-ai"?"google-generative-ai":s.api==="openai-responses"?"openai-responses":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(i)})}function tW(e){return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function iM(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":e.api==="google-generative-ai"?"google-generative-ai":e.api==="openai-responses"?"openai-responses":"openai-compatible";return sM({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}))})}async function aM(e){return I("/custom-providers/probe-models",{method:"POST",body:JSON.stringify({baseUrl:e.baseUrl,apiKey:e.apiKey,apiType:e.apiType})})}function Yo(e){return Oi("/auth/status",()=>I("/auth/status"),e)}function rM(e){return I("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function oM(e,n){return I("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function lM(e){return I("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function cM(e){return I("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function dM(e,n){return I("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function uM(e){return I("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function mM(e,n,s,i){return I("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function hM(e,n,s,i){return I(K("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function pM(e,n,s){return I("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function fM(e,n,s,i){return I(K("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function gM(e){return I(K("/git/remotes",e))}function bM(e){return I(K("/git/remotes/detailed",e))}function vM(e,n,s){return I(K("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function xM(e,n){return I(K(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yM(e,n,s){return I(K(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function kM(e,n,s){return I(K(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function Sg(e,n){return I(K(`/tasks/${e}/pr/generate-metadata`,n),{method:"POST"})}function wM(e,n,s){const i=s?`?base=${encodeURIComponent(s)}`:"";return I(K(`/tasks/${e}/pr/preflight${i}`,n))}function jM(e,n,s){return I(K(`/tasks/${e}/pr/resolve-conflicts`,s),{method:"POST",...n?{body:JSON.stringify({base:n})}:{}})}function NM(e,n,s){return I(K(`/tasks/${e}/pr/push-branch`,s),{method:"POST",...n?{body:JSON.stringify({base:n})}:{}})}function SM(e,n){return I(K(`/tasks/${e}/pr/options`,n))}function CM(e,n,s){return I(K(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function Th(e,n){return I(K(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}function _M(e,n,s){return I(K(`/tasks/${e}/pr/${n}/unlink`,s),{method:"POST",body:JSON.stringify({})})}function EM(e,n){return I(K(`/tasks/${e}/pr/reclaim-conflict`,n),{method:"POST"})}function MM(e,n,s,i){const r=i?`?pr=${encodeURIComponent(String(i))}`:"";return I(K(`/tasks/${e}/pr/merge${r}`,s),{method:"POST",body:JSON.stringify(n?{method:n}:{})})}function AM(e,n,s,i,r){const o=r?`?pr=${encodeURIComponent(String(r))}`:"";return I(K(`/tasks/${e}/pr/auto-merge${o}`,i),{method:"POST",body:JSON.stringify({enabled:n,strategy:s})})}function TM(e,n,s){const i=s?`?pr=${encodeURIComponent(String(s))}`:"";return I(K(`/tasks/${e}/pr/checks${i}`,n))}function Cg(e,n,s){const i=s?`?pr=${encodeURIComponent(String(s))}`:"";return I(K(`/tasks/${e}/pr/reviews${i}`,n))}function Uc(e,n,s,i){return I(K("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function _g(e,n){return I(K(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function RM(e){return I(K("/terminal/sessions",e))}function Ui(e,n){const s=K("/git/status",e);if(!n?.extended)return I(s);const i=s.includes("?")?"&":"?";return I(`${s}${i}extended=1`)}function PM(e,n){const s=e?`?limit=${e}`:"";return I(K(`/git/commits${s}`,n))}function Ud(e,n){return I(K(`/git/commits/${e}/diff`,n))}function IM(e){return I(K("/git/commits/ahead",e))}function DM(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return I(K(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Ro(e){return I(K("/git/branches",e))}function LM(e,n,s){const i=`?limit=${n}`;return I(K(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function FM(e){return I(K("/git/worktrees",e))}function OM(e,n,s){return I(K("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function $M(e,n){return I(K(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Eg(e,n,s){const i=n?"?force=true":"";return I(K(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function zM(e,n){return I(K("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function Mg(e,n){const s=typeof e=="string"?void 0:e;return I(K("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function Ag(e){return I(K("/git/push",e),{method:"POST"})}function Hc(e){return I(K("/git/stashes",e))}function BM(e,n){return I(K("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function UM(e,n,s){return I(K(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function HM(e,n){return I(K(`/git/stashes/${e}`,n),{method:"DELETE"})}function VM(e,n){return I(K(`/git/stashes/${e}/diff`,n))}function qM(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),I(K(`/git/diff/file?${i.toString()}`,s))}function bo(e){return I(K("/git/changes",e))}function Tg(e,n){return I(K("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function WM(e,n){return I(K("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Rg(e,n){return I(K("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function GM(e,n){return I(K("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function KM(e){return I(K("/workspaces",e))}function JM(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),I(`/files?${i.toString()}`)}function YM(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function XM(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function QM(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),I(`/files/search?${i.toString()}`)}function ZM(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/mkdir?${i.toString()}`,{method:"POST",body:JSON.stringify({path:n})})}function eA(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${i.toString()}`,{method:"POST",body:JSON.stringify({content:""})})}function tA(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function nA(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function sA(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),I(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function iA(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),I(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function Xk(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function aA(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function rA(e,n,s){return I(K("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function oA(e,n,s,i,r){return I(K("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:i?.planningDepth,customQuestionCount:i?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function Pg(e,n,s,i){return I(K("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function lA(e,n,s){return I(K(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function cA(e,n,s){return I(K(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dA(e,n,s){return I(K(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Qk(e,n,s){return I(K("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function nW(e,n,s,i){return I(K("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:i?.planningModelProvider,planningModelId:i?.planningModelId})})}function sW(e,n,s){return I(K("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function iW(e,n){return I(K("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function uA(e,n,s,i){return I(K("/planning/create-task",s),{method:"POST",body:JSON.stringify({...n?{sessionId:e,summary:n}:{sessionId:e},...i?.branch!==void 0?{branch:i.branch}:{},...i?.baseBranch!==void 0?{baseBranch:i.baseBranch}:{},...i?.branchSelection?{branchSelection:i.branchSelection}:{}})})}function mA(e,n,s){return I(K("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function hA(e,n,s,i){return I(K("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n,...i?.branchSelection?{branchSelection:i.branchSelection}:{},...i?.branchAssignment?{branchAssignment:i.branchAssignment}:{}})})}const Rh=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Rh))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function pA(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function dl(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,d=null,c=null,m=!1;const p=f=>{const b=f.lastEventId;if(!b)return!0;const y=Number.parseInt(b,10);return Number.isFinite(y)?c!==null&&y<=c?!1:(c=y,!0):!0},h=()=>{if(o)return;const f=pA(e,c),b=new EventSource(pa(f));r=b,b.onopen=()=>{l=0,m=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},b.onmessage=y=>{const v=y;p(v)&&n.onMessage?.(v)};for(const[y,v]of Object.entries(n.events??{}))b.addEventListener(y,x=>{const k=x;p(k)&&v(k)});b.onerror=()=>{if(o||r!==b)return;if(b.readyState===EventSource.CONNECTING){m||(m=!0,s.onConnectionStateChange?.("reconnecting"));return}if(b.close(),l>=i){s.onFatalError?.("Connection lost");return}m=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);d=setTimeout(()=>{d=null,h()},v)}};h();const u={close:()=>{o=!0,d&&(clearTimeout(d),d=null),r?.close(),Rh.delete(u)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Rh.add(u),u}function Ig(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,d=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${d} · ${i} (${l})`}}function Xo(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",i=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:i,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:i,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function fA(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 gA(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>fA(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function bA(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,i=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((m,p)=>({id:p+1,text:m,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(m=>m.id>r).slice(0,s),totalLines:o};const d=Math.max(o-i,0),c=Math.max(d-s,0);return{lines:l.slice(c,d),totalLines:o}}function Dg(e){return Array.isArray(e)?e.map(Ig):(e.candidates??[]).map(Ig)}async function vA(e){try{const n=await I(K("/dev-server/candidates",e));return Dg(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await I(K("/dev-server/detect",e));return Dg(s)}throw n}}function $p(e){return I(K("/dev-server/status",e)).then(Xo)}async function aW(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const i=s.size>0?`?${s.toString()}`:"";try{const r=await I(K(`/dev-server/logs/history${i}`,n));return gA(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await $p(n);return bA(o.logs,e)}throw r}}function xA(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return I(K("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(Xo)}function yA(e){return I(K("/dev-server/stop",e),{method:"POST"}).then(Xo)}function kA(e){return I(K("/dev-server/restart",e),{method:"POST"}).then(Xo)}async function wA(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await I(K("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Xo(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await I(K("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Xo(r)}throw i}}function rW(e){return ci(K("/dev-server/logs/stream",e))}async function oW(e){try{return(await I(K("/devserver",e))).sessions??[]}catch{try{const n=await $p(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function lW(e,n){try{return await I(K(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await $p(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function cW(e,n){try{return await I(K(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await xA({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function dW(e,n){try{return await I(K(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await yA(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function uW(e,n){try{return await I(K(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await kA(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(i=>({timestamp:new Date().toISOString(),stream:i.startsWith("[stderr]")?"stderr":"stdout",text:i.replace(/^\[stderr\]\s*/,"")}))}}}async function mW(e,n,s){try{const i=await I(K(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:i.url??null,source:i.source??null}}catch{const i=await wA({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function hW(e){try{return(await I(K("/devserver/detect",e))).candidates??[]}catch{try{return(await vA(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function pW(e,n){return ci(K(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function kc(e,n,s=25e3){const i=setInterval(()=>{vR(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function jA(e,n){return ci(K(`/planning/${encodeURIComponent(e)}/stream`,n))}function NA(e,n){return ci(K(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function fW(e,n,s,i){const r=NA(e,n),o=dl(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 d=JSON.parse(l.data);s.onError?.(d.message||d)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function SA(e,n,s,i){const r=jA(e,n);let o=null,l=null;const d=()=>{o?.stop(),o=null},c=dl(r,{onOpen:()=>{d(),o=kc(e,n)},onMessage:m=>{m.data.startsWith(":")},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},question:m=>{try{s.onQuestion?.(JSON.parse(m.data))}catch(p){console.error("[planning] Failed to parse question event:",p)}},summary:m=>{try{s.onSummary?.(JSON.parse(m.data))}catch(p){console.error("[planning] Failed to parse summary event:",p)}},error:m=>{try{const p=JSON.parse(m.data);s.onError?.(p.message||p)}catch{s.onError?.(m.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{d(),s.onError?.(m)}});return l={close:()=>{d(),c.close()},isConnected:c.isConnected},l}function wc(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const i=s.toString();return i?`${e}?${i}`:e}function CA(e){return I(wc("/routines",e))}function _A(e,n){return I(wc("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Lg(e,n,s){return I(wc(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function EA(e,n){await I(wc(`/routines/${e}`,n),{method:"DELETE"})}function MA(e,n){return I(wc(`/routines/${e}/trigger`,n),{method:"POST"})}function Fg(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity${s}`)}function AA(e){const n=K("/activity",e);return I(n,{method:"DELETE"})}function zp(e){const n=K("/workflow-steps",e);return Oi(n,()=>I(n))}function TA(e,n){return I(K(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function Bp(e,n){const s=n?.includeDisabledBuiltins?"?includeDisabledBuiltins=true":"",i=K(`/workflows${s}`,e);return Oi(i,()=>I(i))}function gW(e){const n=K("/traits",e);return Oi(n,()=>I(n).then(s=>s.traits))}function bW(e){const n=K("/step-parsers",e);return Oi(n,()=>I(n).then(s=>s.parsers.map(i=>i.id)))}function Zk(e,n){return I(K(`/workflows/${encodeURIComponent(e)}`,n))}function vW(e,n){return I(K("/workflows",n),{method:"POST",body:JSON.stringify(e)})}function xW(e,n,s){return I(K(`/workflows/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yW(e,n){return I(K(`/workflows/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kW(e,n){return I(K(`/workflows/${encodeURIComponent(e)}/setting-values`,n))}function wW(e,n,s){return I(K(`/workflows/${encodeURIComponent(e)}/setting-values`,s),{method:"PATCH",body:JSON.stringify({values:n})})}function jW(e,n){return I(K(`/workflows/${encodeURIComponent(e)}/compile`,n),{method:"POST"})}async function NW(e,n){const s=await I(K(`/workflows/${encodeURIComponent(e)}/export`,n)),i=(s.name||"workflow").replace(/[^\w.-]+/g,"-").replace(/^-+|-+$/g,"")||"workflow",r=new Blob([JSON.stringify(s,null,2)],{type:"application/json"}),o=URL.createObjectURL(r),l=document.createElement("a");return l.href=o,l.download=`${i}.workflow.json`,document.body.appendChild(l),l.click(),document.body.removeChild(l),URL.revokeObjectURL(o),s}function SW(e,n){return I(K("/workflows/import",n),{method:"POST",body:JSON.stringify(e)})}function CW(e){return I(K("/workflows/migrate-legacy-steps",e),{method:"POST"})}function _W(e,n,s){return I(K("/workflows/design",n),{method:"POST",body:JSON.stringify(e),signal:s})}function RA(e,n){return I(K(`/tasks/${encodeURIComponent(e)}/workflow`,n))}function PA(e,n,s){return I(K(`/tasks/${encodeURIComponent(e)}/workflow`,s),{method:"PUT",body:JSON.stringify({workflowId:n})})}function IA(e,n){return I(K(`/tasks/${encodeURIComponent(e)}/workflow/approve-cli`,n),{method:"POST"})}function DA(e,n,s){return I(K(`/tasks/${encodeURIComponent(e)}/workflow/input`,s),{method:"POST",body:JSON.stringify({text:n})})}function LA(e){return I(K("/project/default-workflow",e))}function FA(e,n){return I(K("/project/default-workflow",n),{method:"PUT",body:JSON.stringify({workflowId:e})})}function EW(){return I("/workflow-step-templates")}function MW(){return I("/plugin-workflow-step-templates")}function Hd(e){return I(K("/scripts",e))}function OA(e,n,s){return I(K("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function $A(e,n){return I(K(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function ew(e,n,s){return(await I(K("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Vc={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 tw(e){if(!(e instanceof Error))return Vc.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Vc.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Vc.INVALID_TYPE:n.startsWith("text must")||n.startsWith("title must")||n.includes("text is required")||n.includes("type is required")||n.includes("title is required")?e.message:Vc.NETWORK}async function AW(e,n){return(await I(K("/ai/draft-goal-description",n),{method:"POST",body:JSON.stringify({title:e})})).description}function zA(e,n){return I(K("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function BA(e,n,s){return I(K(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function UA(e,n){return ci(K(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function HA(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},d=dl(UA(e,n),{onOpen:()=>{l(),r=kc(e,n)},events:{thinking:c=>{try{s.onThinking?.(JSON.parse(c.data))}catch{s.onThinking?.(c.data)}},subtasks:c=>{try{s.onSubtasks?.(JSON.parse(c.data))}catch(m){console.error("[subtasks] Failed to parse subtasks event:",m)}},error:c=>{try{const m=JSON.parse(c.data),p=typeof m=="string"&&m.length>0?m:null;s.onError?.(p||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:c=>{l(),s.onError?.(c)}});return o={close:()=>{l(),d.close()},isConnected:d.isConnected},o}function VA(e,n,s,i,r){return I(K("/subtasks/create-tasks",i),{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 nw(e,n,s){return I(K("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function K(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function qA(e,n,s){if(!n||n===s)return e;const i="/api",r=e.startsWith(i)?e.slice(i.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function jc(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=qA(e,s,i);return I(o,r)}function br(e,n,s){const i=new URLSearchParams;e?.state&&i.set("state",e.state),e?.role&&i.set("role",e.role),e?.includeEphemeral===!0&&i.set("includeEphemeral","true"),n&&i.set("projectId",n);const o=`/agents${i.size>0?`?${i.toString()}`:""}`;return Oi(o,()=>I(o),s)}function Ph(e,n){return I(K(`/agents/${encodeURIComponent(e)}`,n))}function WA(e,n){return I(K("/agents",n),{method:"POST",body:JSON.stringify(e)})}function GA(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function TW(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ci(K(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:Ki(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function RW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function PW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function IW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function DW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function LW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function FW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function OW(e,n,s){const i=`path=${encodeURIComponent(n)}`;return I(K(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function $W(e,n,s,i){return I(K(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function KA(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function JA(e,n){return I(K(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function zW(e,n,s){const i=new URLSearchParams;n!==void 0&&i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/runs${r}`)}function BW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function UW(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function HW(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/prompt-sizes${r}`)}function VW(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return I(K(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function qW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Og(e,n){const s=K("/agents/stats",e);return Oi(s,()=>I(s),n)}function WW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function GW(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return I(`/agents/org-tree${i?`?${i}`:""}`)}function KW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function $g(e,n,s){return I(K(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function sw(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 YA(e,n){const s=await I(K(`/tasks/${encodeURIComponent(e)}/review`,n));return sw(s)}async function XA(e,n){const s=await I(K(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return sw(s)}function QA(e,n,s){return I(K(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function JW(e,n){return I(K(`/agents/${encodeURIComponent(e)}/tasks`,n))}function YW(){return I("/agents/companies")}function XW(e,n){return I(K("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function QW(e,n){return I(K("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function ZW(e,n){return I(K(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function eG(e){return I(K("/backups",e))}function tG(e){return I(K("/backups",e),{method:"POST"})}function nG(e,n){const s=K("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return I(i)}function sG(e,n,s){return I(K("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}async function ZA(e,n,s,i){const r=i?`/api/ai/summarize-title?projectId=${encodeURIComponent(i)}`:"/api/ai/summarize-title",o=await fetch(r,{method:"POST",headers:Ki({"Content-Type":"application/json"}),body:JSON.stringify({description:e,provider:n,modelId:s})}),l=o.headers.get("content-type")??"",d=await o.text();if(!l.includes("application/json"))throw new Error(`API returned non-JSON response: ${d.slice(0,100)}`);const m=JSON.parse(d);if(!o.ok){const p=m.error||"Request failed";throw o.status===400?new Error(`Invalid request: ${p}`):o.status===429?new Error(`Rate limit exceeded: ${p}`):o.status===503?new Error(`AI service temporarily unavailable: ${p}`):new Error(p)}if(!m.title)throw new Error("API returned empty title");return m.title}function iG(){return I("/projects")}function eT(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function zg(){return Oi("/projects/across-nodes",()=>I("/projects/across-nodes"))}function Vd(){return Oi("/nodes",()=>I("/nodes"))}function aG(){return I("/docker/nodes")}function rG(e){return I(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function oG(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const i=s.size>0?`?${s.toString()}`:"";return I(`/docker/nodes/${encodeURIComponent(e)}/logs${i}`)}function lG(e){return I("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function tT(e){return I("/nodes",{method:"POST",body:JSON.stringify(e)})}function nT(e){return I("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function sT(e,n){return I(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function iT(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config`)}function aT(e,n){return I(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function rT(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function Bg(e){return I(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function oT(e){const n=await I(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}async function cG(){return I("/mesh/state")}function dG(e,n,s,i){const r=s&&s!==i?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=Jo();l&&o.set("fn_token",l);const d=o.toString(),c=`/browse-directory${d?`?${d}`:""}`;return I(c)}function uG(e){return I("/create-directory",{method:"POST",body:JSON.stringify({path:e})})}function lT(e){return I("/projects",{method:"POST",body:JSON.stringify(e)})}function iw(e){return I(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function cT(e,n,s){return I(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function Ug(e){return I(`/projects/${encodeURIComponent(e)}/health`)}function dT(e){const n=K("/executor/stats",e);return Oi(n,()=>I(n))}function uT(e){return I(K("/system-stats",e))}function mT(e){return I(K("/kill-vitest",e),{method:"POST"})}function Hg(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity-feed${s}`)}function hT(e){return I(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function pT(e){return I(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function mG(){return I("/global-concurrency")}function hG(e){return I("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function fT(e,n){return I(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function aw(e,n,s){const i=new URLSearchParams;n&&i.set("worktree",n),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function gT(e){return I(K("/missions",e))}function bT(e,n){return I(K("/missions",n),{method:"POST",body:JSON.stringify(e)})}function rw(e,n){return I(K(`/missions/${encodeURIComponent(e)}`,n))}function vT(e,n,s){return I(K(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function xT(e,n){return I(K(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yT(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return I(K(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function kT(e){return I(K("/missions/health",e))}function wT(e,n,s){return I(K(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function jT(e,n,s){return I(K(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function NT(e,n){return I(K(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ST(e,n,s){return I(K(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function CT(e,n,s){return I(K(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function _T(e,n){return I(K(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ET(e,n){return I(K(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function MT(e,n,s){return I(K(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function AT(e,n,s){return I(K(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function TT(e,n){return I(K(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function RT(e,n,s){return I(K(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function PT(e,n){return I(K(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function IT(e,n,s,i,r){return I(K(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function DT(e,n,s){return I(K(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify(s??{})})}function LT(e,n){return I(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function FT(e,n,s){return I(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function OT(e,n,s){return I(K(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $T(e,n,s){return I(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function zT(e,n,s){return I(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Vg(e,n){return I(K(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Ku(e,n){return I(K(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function qg(e,n){return I(K(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function BT(e,n){return I(K(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Wg(e,n){return I(K(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function UT(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset));const r=i.size>0?`?${i.toString()}`:"";return I(K(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function HT(e,n){return I(K(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function VT(e,n){return I(K(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function qT(e,n){return I(K(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function WT(e,n){return I(K(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function GT(e,n,s){return I(K(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function KT(e,n,s){return I(K("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function JT(e,n,s,i){return I(K("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function YT(e,n,s){return I(K(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function XT(e,n,s){return I(K("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}async function QT(e){const n=e?`?${new URLSearchParams({projectId:e}).toString()}`:"";return(await I(`/missions/interview/drafts${n}`)).drafts??[]}function ZT(e,n,s){return I(K(`/missions/interview/drafts/${encodeURIComponent(e)}/discard`,n),{method:"POST",body:JSON.stringify({tabId:s})})}function eR(e,n,s,i){return I(K("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function tR(e,n,s,i){const r=ci(K(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const d=()=>{o?.stop(),o=null},c=dl(r,{onOpen:()=>{d(),o=kc(e,n)},onMessage:m=>{m.data.startsWith(":")},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},question:m=>{try{s.onQuestion?.(JSON.parse(m.data))}catch(p){console.error("[mission-interview] Failed to parse question event:",p)}},summary:m=>{try{s.onSummary?.(JSON.parse(m.data))}catch(p){console.error("[mission-interview] Failed to parse summary event:",p)}},error:m=>{try{const p=JSON.parse(m.data);s.onError?.(p.message||p)}catch{s.onError?.(m.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{d(),s.onError?.(m)}});return l={close:()=>{d(),c.close()},isConnected:c.isConnected},l}function Nc(e,n,s){return K(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Sc(e,n,s){return K(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function nR(e,n){return I(Nc(e,"/start",n),{method:"POST"})}function sR(e,n,s,i){return I(Nc(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function iR(e,n,s,i){const r=ci(Nc(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const d=()=>{o?.stop(),o=null},c=dl(r,{onOpen:()=>{d(),o=kc(e,n)},onMessage:m=>{m.data.startsWith(":")},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},question:m=>{try{s.onQuestion?.(JSON.parse(m.data))}catch(p){console.error("[milestone-interview] Failed to parse question event:",p)}},summary:m=>{try{s.onSummary?.(JSON.parse(m.data))}catch(p){console.error("[milestone-interview] Failed to parse summary event:",p)}},error:m=>{try{const p=JSON.parse(m.data);s.onError?.(p.message||p)}catch{s.onError?.(m.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{d(),s.onError?.(m)}});return l={close:()=>{d(),c.close()},isConnected:c.isConnected},l}function aR(e,n,s){return I(Nc(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function rR(e,n){return I(Nc(e,"/skip",n),{method:"POST"})}function oR(e,n){return I(Sc(e,"/start",n),{method:"POST"})}function lR(e,n,s,i){return I(Sc(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function cR(e,n,s,i){const r=ci(Sc(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const d=()=>{o?.stop(),o=null},c=dl(r,{onOpen:()=>{d(),o=kc(e,n)},onMessage:m=>{m.data.startsWith(":")},events:{thinking:m=>{try{s.onThinking?.(JSON.parse(m.data))}catch{s.onThinking?.(m.data)}},question:m=>{try{s.onQuestion?.(JSON.parse(m.data))}catch(p){console.error("[slice-interview] Failed to parse question event:",p)}},summary:m=>{try{s.onSummary?.(JSON.parse(m.data))}catch(p){console.error("[slice-interview] Failed to parse summary event:",p)}},error:m=>{try{const p=JSON.parse(m.data);s.onError?.(p.message||p)}catch{s.onError?.(m.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:m=>{d(),s.onError?.(m)}});return l={close:()=>{d(),c.close()},isConnected:c.isConnected},l}function dR(e,n,s){return I(Sc(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function uR(e,n){return I(Sc(e,"/skip",n),{method:"POST"})}async function mR(e,n){try{return await I(K(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function pG(e){return I(K("/todos",e))}function fG(e,n){const s={title:e};return I(K("/todos",n),{method:"POST",body:JSON.stringify(s)})}function gG(e,n,s){const i={title:n};return I(K(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function bG(e,n){return I(K(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function vG(e,n,s){const i={text:n};return I(K(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function xG(e,n,s){const i=n;return I(K(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function yG(e,n){return I(K(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kG(e,n,s){return I(K(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Qo(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Up(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const i=s.toString(),r=await fetch(ci(`/ai-sessions${i?`?${i}`:""}`),{headers:Ki()});return r.ok?(await r.json()).sessions??[]:[]}async function hR(e){return I(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function pR(e){return I(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Aa(e){const n=await fetch(ci(`/ai-sessions/${encodeURIComponent(e)}`),{headers:Ki()});return n.ok?n.json():null}async function fR(e,n){const s=await I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function gR(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function bR(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function ow(e){const n=ci(`/ai-sessions/${encodeURIComponent(e)}`),s=await fetch(n,{method:"DELETE",headers:Ki()});if(s.ok||s.status===404)return;const i=s.headers.get("content-type")??"",r=await s.text(),o=i.includes("application/json");if(i.includes("text/html")||zk(r))throw new Error(`API returned HTML instead of JSON for ${n}. The endpoint may not be properly configured. (${s.status} ${s.statusText})`);if(!o){const m=r.length>160?`${r.slice(0,160)}...`:r;throw new Error(`API returned ${i||"an unknown content type"} instead of JSON for ${n}. (${s.status} ${s.statusText})${m?` Response: ${m}`:""}`)}let d;try{d=r?JSON.parse(r):null}catch{throw new Error(`API returned invalid JSON for ${n}. (${s.status} ${s.statusText})`)}const c=d;throw new Ka(c?.error||`Request failed for ${n}: ${s.status} ${s.statusText}`,s.status,c?.details)}function vR(e,n){return I(K(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function xR(e,n,s){return I(K(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function yR(e,n){return I(K(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function kR(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return I(`/messages/inbox${i}`)}function wR(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return I(`/messages/outbox${i}`)}function lw(e){return I(K("/messages/unread-count",e))}function jR(e,n){return I(K("/messages",n),{method:"POST",body:JSON.stringify(e)})}function NR(e,n){return I(K(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function SR(e){return I(K("/messages/read-all",e),{method:"POST"})}function CR(e,n){return I(K(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function _R(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return I(K(i,s))}function ER(e,n){return I(K(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function MR(e){return I(K("/agents/mailbox/all",e))}function qc(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 i=s.size>0?`?${s.toString()}`:"";return I(`/approvals${i}`)}function Gg(e,n){return I(K(`/approvals/${encodeURIComponent(e)}`,n))}function AR(e,n,s){return I(K(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function wG(e,n,s){const i=new URLSearchParams;i.set("limit",String(n)),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function jG(e,n){return I(K(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function NG(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/performance${r}`)}function SG(e,n,s){const i=new URLSearchParams;i.set("limit",String(n.limit)),n?.category&&i.set("category",n.category),s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function CG(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function _G(e,n){return I(K(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function EG(e,n,s){return I(K(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function MG(e,n){return I(K(`/agents/${encodeURIComponent(e)}/budget`,n))}function AG(e,n){return I(K(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function TG(e){return I(K("/plugins",e))}async function RG(e,n,s){const i=new URLSearchParams;e?.trim()&&i.set("q",e.trim()),n?.trim()&&i.set("category",n.trim());const r=i.size>0?`?${i.toString()}`:"";return(await I(K(`/plugins/registry${r}`,s))).plugins}async function PG(e,n){return I(K("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function IG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function DG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function LG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function FG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function OG(e,n,s){return I(K(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function $G(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function zG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function BG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function UG(e,n,s){return I(K(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function HG(e,n){return I(K(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function TR(e){const n=K("/plugins/ui-slots",e);return Oi(n,()=>I(n))}async function RR(e){return I(K("/plugins/dashboard-views",e))}async function VG(e){return I(K("/plugins/runtimes",e))}async function PR(e){return(await I(K("/skills/discovered",e))).skills}async function qG(e,n,s){return I(K("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function WG(e,n,s){return I(K("/skills/install",s),{method:"POST",body:JSON.stringify({source:e,skill:n})})}async function GG(e,n,s){const i=new URLSearchParams;e&&i.set("q",e),i.set("limit",String(n));const r=i.size>0?`?${i.toString()}`:"";return I(K(`/skills/catalog${r}`,s))}async function KG(e,n){return(await I(K(`/skills/${encodeURIComponent(e)}/content`,n))).content}function Kg(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return I(`/chat/sessions${i?`?${i}`:""}`)}async function IR(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const i=e.modelProvider?.trim(),r=e.modelId?.trim();if(i&&!r||!i&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),i&&r&&(o.set("modelProvider",i),o.set("modelId",r)),{session:(await I(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function DR(e,n){return I(K("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function kl(e,n){return I(K(`/chat/sessions/${encodeURIComponent(e)}`,n))}function JG(e,n,s){return I(K(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function YG(e,n){return I(K(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function wl(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before),n?.order&&i.set("order",n.order);const r=i.toString();return I(K(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function LR(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 i=s.toString();return I(`/chat/rooms${i?`?${i}`:""}`)}function FR(e,n){const s={...e,...n?{projectId:n}:{}};return I(K("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function OR(e,n){return I(K(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $R(e,n){return I(K(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function Ju(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before),n?.order&&i.set("order",n.order);const r=i.toString();return I(K(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}async function zR(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(ci(K(`/chat/rooms/${encodeURIComponent(e)}/attachments`,s)),{method:"POST",headers:Ki(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}function BR(e,n){return ci(K(`/chat/rooms/${encodeURIComponent(e)}/attachments/`,n))}function UR(e,n,s){return I(K(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function HR(e,n){return I(K(`/chat/rooms/${encodeURIComponent(e)}/messages`,n),{method:"DELETE"})}function VR(e,n){return I(K(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function qR(e){if(!e||typeof e!="object")return null;const n=e,s=typeof n.summary=="string"?n.summary.trim():"";if(!s)return null;const i=(()=>{const r=n.reference;if(!r||typeof r!="object")return;const o=r,l=typeof o.kind=="string"?o.kind.trim():"",d=typeof o.id=="string"?o.id.trim():"";if(!(!l||!d))return{kind:l,id:d,...typeof o.label=="string"&&o.label.trim()?{label:o.label.trim()}:{}}})();return{summary:s,...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...i?{reference:i}:{}}}function cw(e){try{const n=JSON.parse(e),s=qR(n);return s||(n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:e||"Stream error")}catch{return e||"Stream error"}}function WR(e,n,s,i,r,o){const l=ci(K(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),d=new AbortController;let c=!1,m=!1,p=!1;const h=Math.max(1e3,6e4);let u=null;const f=()=>{u&&(clearTimeout(u),u=null)},b=()=>{p||(p=!0,f())},y=(v,x)=>{if(v)switch(b(),v){case"thinking":try{s.onThinking?.(JSON.parse(x))}catch{s.onThinking?.(x)}break;case"text":try{s.onText?.(JSON.parse(x))}catch{s.onText?.(x)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(x))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(x))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(x))}catch{}break;case"done":m=!0;try{const k=JSON.parse(x);s.onDone?.({messageId:typeof k.messageId=="string"?k.messageId:"",...k.message&&typeof k.message=="object"?{message:k.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":m=!0,s.onError?.(cw(x));break}};return(async()=>{try{const v=Array.isArray(i)&&i.length>0,x=v?(()=>{const M=new FormData;return M.append("content",n),i.forEach(D=>M.append("attachments",D)),M})():JSON.stringify({content:n}),k=await fetch(l,{method:"POST",headers:v?Ki():Ki({"Content-Type":"application/json"}),body:x,signal:d.signal});if(!k.ok){const M=await k.text();let D=`Request failed: ${k.status}`;try{D=JSON.parse(M).error||D}catch{}s.onError?.(D);return}if(!k.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),u=setTimeout(()=>{m||c||p||(m=!0,s.onError?.("Timed out waiting for first response event"),d.abort())},h);const w=k.body.getReader(),g=new TextDecoder;let j="",S="",C=[];const E=(M,D=!1)=>{j+=M;const _=j.split(`
|
|
718
718
|
`);j=_.pop()||"",D&&j.length>0&&(_.push(j),j="");for(const V of _){const N=V.endsWith("\r")?V.slice(0,-1):V;if(N.startsWith("event:"))S=N.slice(6).trim();else if(N.startsWith("data:")){const $=N.slice(5);C.push($.startsWith(" ")?$.slice(1):$)}else if(N===""){const $=C.join(`
|
|
719
719
|
`);y(S,$),S="",C=[]}}if(D&&S&&C.length>0){const V=C.join(`
|
|
720
720
|
`);y(S,V),S="",C=[]}};for(;;){const{done:M,value:D}=await w.read();if(M){E(g.decode(),!0);break}E(g.decode(D,{stream:!0}))}const F=j.length>0||S.length>0||C.length>0;!m&&!c&&!F&&s.onError?.("Connection closed unexpectedly"),f()}catch(v){if(v instanceof DOMException&&v.name==="AbortError"){!c&&!m&&s.onError?.("Connection aborted"),f();return}if(c){f();return}f(),s.onError?.(v instanceof Error?v.message:"Connection error")}})(),{close:()=>{c=!0,f(),d.abort()},isConnected:()=>!c}}function GR(e,n,s,i){const r=ci(K(`/chat/sessions/${encodeURIComponent(e)}/stream`,s)),o=new AbortController;let l=!1,d=!1;const c=(m,p)=>{if(m)switch(m){case"thinking":try{n.onThinking?.(JSON.parse(p))}catch{n.onThinking?.(p)}break;case"text":try{n.onText?.(JSON.parse(p))}catch{n.onText?.(p)}break;case"tool_start":try{n.onToolStart?.(JSON.parse(p))}catch{}break;case"tool_end":try{n.onToolEnd?.(JSON.parse(p))}catch{}break;case"fallback":try{n.onFallback?.(JSON.parse(p))}catch{}break;case"done":d=!0;try{const h=JSON.parse(p);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":d=!0,n.onError?.(cw(p));break}};return(async()=>{try{const m=new Headers(Ki());typeof i?.lastEventId=="number"&&m.set("Last-Event-ID",String(i.lastEventId));const p=await fetch(r,{method:"GET",headers:m,signal:o.signal});if(!p.ok){const k=await p.text();let w=`Request failed: ${p.status}`;try{w=JSON.parse(k).error||w}catch{}n.onError?.(w);return}if(!p.body){n.onError?.("No response body");return}n.onConnectionStateChange?.("connected");const h=p.body.getReader(),u=new TextDecoder;let f="",b="",y=[];const v=(k,w=!1)=>{f+=k;const g=f.split(`
|
|
@@ -766,7 +766,7 @@ Delete anyway by unlinking these references first?`,{taskId:e.id,children:Dn.lin
|
|
|
766
766
|
`).map((s,i)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
|
|
767
767
|
`},i):t.jsx(gr.Fragment,{children:`${s}
|
|
768
768
|
`},i)})}function zz(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Bz({isOpen:e,taskId:n,files:s,stats:i,mergeDetails:r,column:o,onClose:l,onRefresh:d}){const{t:c}=st("app"),[m,p]=a.useState(null),[h,u]=a.useState(!0),f=a.useRef(null);La(f,e,"fusion:changes-diff-modal-size");const b=yr(l);a.useEffect(()=>{s.length>0&&m===null&&p(0)},[s,m]);const y=a.useCallback(()=>{p(w=>w!==null&&w>0?w-1:w)},[]),v=a.useCallback(()=>{p(w=>w!==null&&w<s.length-1?w+1:w)},[]);if(a.useEffect(()=>{if(!e)return;const w=g=>{if(g.key==="Escape"){l();return}g.key==="ArrowUp"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),y()),g.key==="ArrowDown"&&(g.metaKey||g.ctrlKey)&&(g.preventDefault(),v())};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[e,l,y,v]),!e)return null;const x=m!==null?s[m]:null,k=o==="done";return t.jsx("div",{className:"modal-overlay open",...b,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(da,{size:18}),t.jsxs("span",{children:[c("changes.title","Changes")," — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",i.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:y,disabled:m===null||m<=0,title:c("changes.previousFile","Previous file (Ctrl+↑)"),"aria-label":c("changes.previousFileAria","Previous file"),children:t.jsx(mu,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:m!==null?`${m+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:v,disabled:m===null||m>=s.length-1,title:c("changes.nextFile","Next file (Ctrl+↓)"),"aria-label":c("changes.nextFileAria","Next file"),children:t.jsx(ls,{})})]}),t.jsx("button",{className:`btn btn-sm ${h?"btn-primary":""}`,onClick:()=>u(w=>!w),title:h?c("changes.disableWrap","Disable word wrap"):c("changes.enableWrap","Enable word wrap"),"aria-label":c("changes.toggleWrap","Toggle word wrap"),children:t.jsx(Cp,{size:14})}),d&&t.jsxs("button",{className:"btn btn-sm",onClick:d,children:[t.jsx(xs,{size:14}),c("actions.refresh","Refresh")]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":c("actions.close","Close"),children:t.jsx(Fn,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[k&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(vc,{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.jsx("div",{className:"commit-diff-timestamp",children:c("changes.merged","Merged {{date}}",{date:new Date(r.mergedAt).toLocaleString()})})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((w,g)=>t.jsxs("button",{className:`changes-diff-file-item ${m===g?"selected":""}`,onClick:()=>p(g),title:w.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${w.status}`,children:zz(w.status)}),t.jsx("span",{className:"changes-diff-file-path",title:w.path,children:t.jsx("bdo",{dir:"ltr",children:w.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",w.additions," -",w.deletions]})]},w.path))})]}),t.jsx("div",{className:"changes-diff-content",children:x?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:x.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",x.additions," -",x.deletions]})]}),x.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${h?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:tN(x.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:c("changes.noDiff","No diff available for this file.")})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(da,{size:48,opacity:.3}),t.jsx("p",{children:c("changes.selectFile","Select a file to view its diff")})]})})]})]})})}function nN(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Dm(e,n,s,i="execution",r){const o=(l,d,c)=>r?r(l,d,c):d;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(vc,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsx("div",{className:"commit-diff-timestamp",children:o("taskChanges.merged","Merged {{date}}",{date:new Date(s.mergedAt).toLocaleString()})})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(da,{size:24}),t.jsx("p",{children:o("taskChanges.fileCount","{{count}} file{{plural}} changed.",{count:e.length,plural:e.length===1?"":"s"})}),t.jsx("span",{className:"task-changes-state-hint",children:n?i==="landed"?o("taskChanges.landedFilesHint","These are files captured from the merged commit metadata. The lineage-backed diff is unavailable for this task."):o("taskChanges.executionFilesHint","These are files captured from the worktree during execution. They may differ from the files that actually landed on main. The lineage-backed diff is unavailable for this task."):o("taskChanges.emptyWorktreeHint","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(l=>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:o("taskChanges.statusUnknown","status unknown"),children:nN("unknown")}),t.jsx("span",{className:"changes-file-path",title:l,children:t.jsx("bdo",{dir:"ltr",children:l})})]})},l))})]})}function Uz({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const{t:l}=st("app"),[d,c]=a.useState([]),[m,p]=a.useState({filesChanged:0,additions:0,deletions:0}),[h,u]=a.useState(!0),[f,b]=a.useState(null),[y,v]=a.useState(new Set),[x,k]=a.useState(null),[w,g]=a.useState(!0),[j,S]=a.useState(!1),C=i==="done",E=C&&!!r?.commitSha,F=i==="in-progress"||i==="in-review"||C,M=a.useCallback(async()=>{if(!F&&!C){u(!1);return}try{if(u(!0),b(null),!F){c([]),p({filesChanged:0,additions:0,deletions:0});return}const R=await aw(e,void 0,s),L=R.files.map(O=>({path:O.path,status:O.status,additions:O.additions,deletions:O.deletions,patch:O.patch}));c(L),p(R.stats),L.length>0&&(v(new Set([L[0].path])),k(0))}catch(R){C&&!r?.commitSha?(c([]),p({filesChanged:0,additions:0,deletions:0}),b(null)):b(Re(R)||l("taskChanges.loadError","Failed to load task changes"))}finally{u(!1)}},[e,s,F,C,r?.commitSha]);a.useEffect(()=>{M()},[M]);const D=R=>{v(L=>{const O=new Set(L);if(O.has(R))O.delete(R);else{O.add(R);const J=d.findIndex(A=>A.path===R);J!==-1&&k(J)}return O})},_=R=>{if(R<0||R>=d.length)return;const L=d[R].path;v(new Set([L])),k(R)},V=x!==null&&x>0,N=x!==null&&x<d.length-1,$=()=>t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(da,{size:16}),l("taskChanges.filesChangedHeading","Files Changed ({{count}})",{count:m.filesChanged})]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",m.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",m.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[d.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>V&&_(x-1),disabled:!V,title:l("taskChanges.previousFile","Previous file"),"aria-label":l("taskChanges.previousFile","Previous file"),children:t.jsx(mu,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:x!==null?`${x+1}/${d.length}`:`—/${d.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>N&&_(x+1),disabled:!N,title:l("taskChanges.nextFile","Next file"),"aria-label":l("taskChanges.nextFile","Next file"),children:t.jsx(ls,{})})]}),t.jsx("button",{className:`btn btn-sm ${w?"btn-primary":""}`,onClick:()=>g(R=>!R),title:l(`taskChanges.${w?"disableWordWrap":"enableWordWrap"}`,w?"Disable word wrap":"Enable word wrap"),"aria-label":l("taskChanges.toggleWordWrap","Toggle word wrap"),children:t.jsx(Cp,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:M,disabled:h,children:l("common.refresh","Refresh")}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>S(!0),title:l("taskChanges.expandDiff","Expand to full-screen diff view"),"aria-label":l("taskChanges.expandDiffView","Expand diff view"),children:t.jsx(gu,{})})]})]})]});if(h)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:l("taskChanges.loading","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(oi,{size:16}),t.jsx("span",{children:l("taskChanges.error","Error loading changes: {{error}}",{error:f})})]})});if(!C&&!n&&d.length===0)return o&&o.length>0?Dm(o,!1,void 0,"execution",l):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(da,{size:24}),t.jsx("p",{children:l("taskChanges.noWorktree","No worktree available for this task.")}),t.jsx("span",{className:"task-changes-state-hint",children:l("taskChanges.noWorktreeHint","Changes will be shown once the task is in progress.")})]})});if(d.length===0){if(C&&!E){const R=r?.landedFiles&&r.landedFiles.length>0?r.landedFiles:o;if(R&&R.length>0)return Dm(R,!0,r,r?.landedFiles?.length?"landed":"execution",l);const L=r?.filesChanged,O=r?.insertions,J=r?.deletions,A=L!=null||O!=null||J!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(da,{size:24}),t.jsx("p",{children:l("taskChanges.unavailable","Detailed file changes unavailable.")}),t.jsx("span",{className:"task-changes-state-hint",children:A?l("taskChanges.summaryHint","Final commit summary: {{files}} file{{plural}} changed, +{{additions}} additions, -{{deletions}} deletions. Counts only the recorded merge/squash commit, not the full task lineage.",{files:L??0,plural:(L??0)===1?"":"s",additions:O??0,deletions:J??0}):l("taskChanges.noMergeCommit","No merge commit was recorded for this task.")})]})})}return!C&&o&&o.length>0?Dm(o,C,r,"execution",l):t.jsxs("div",{className:"detail-section task-changes-tab",children:[$(),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(da,{size:24}),t.jsx("p",{children:l("taskChanges.noFilesModified","No files modified.")}),t.jsx("span",{className:"task-changes-state-hint",children:C?l("taskChanges.noMergeFileChanges","No file changes were recorded in the merge commit."):l("taskChanges.noExecutionModifications","The agent did not modify any files during execution.")})]})]})}return t.jsxs("div",{className:"detail-section task-changes-tab",children:[C&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(vc,{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.jsx("div",{className:"commit-diff-timestamp",children:l("taskChanges.mergedAt","Merged {{date}}",{date:new Date(r.mergedAt).toLocaleString()})}),r.noOpVerifiedShortCircuit&&t.jsx("div",{className:"text-muted",children:l("taskChanges.noOpShortCircuit","Verified short-circuit — work was already on main (rebase walked foreign commits).")}),r.landedFilesCaptureFallback==="attribution-failed"&&t.jsx("div",{className:"text-muted",children:l("taskChanges.attributionFailed","Landed-files set may include foreign commits (attribution unavailable).")})]}),$(),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:d.map(R=>{const L=y.has(R.path);return t.jsxs("div",{className:`changes-file-item ${L?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>D(R.path),children:[t.jsx("span",{className:"changes-file-toggle",children:L?t.jsx(Ln,{size:14}):t.jsx(ls,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${R.status}`,title:R.status,children:nN(R.status)}),t.jsx("span",{className:"changes-file-path",title:R.path,children:t.jsx("bdo",{dir:"ltr",children:R.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${R.additions} -${R.deletions}`,children:["+",R.additions," -",R.deletions]})]}),L&&R.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:tN(R.patch)})})})]},R.path)})}),t.jsx(Bz,{isOpen:j,taskId:e,files:d,stats:m,mergeDetails:r,column:i,onClose:()=>S(!1),onRefresh:M})]})}function Jv(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function Hz(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function yK(e,n){const s=Hz(e),i=new Set(n.map(d=>d.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const d=`-${l}`;o=`${s.slice(0,r-d.length)}${d}`,l++}return o}function Yv(e){const n=e?.trim()??"";return xu.test(n)?n:""}function sN(e,n){const s=Yv(e?.githubTrackingDefaultRepo);return s||Yv(n?.githubTrackingDefaultRepo)}function Vz(e,n){return e==="online"?n("taskForm.nodeStatusOnline","Online"):e==="connecting"?n("taskForm.nodeStatusConnecting","Connecting"):e==="error"?n("taskForm.nodeStatusError","Error"):n("taskForm.nodeStatusOffline","Offline")}const Xv=["image/png","image/jpeg","image/gif","image/webp"],qz=["main","master","trunk","develop"],Qv="__fusion-custom__",Zv="";function Wz(e){const n=new Set,s=[];for(const i of qz)e.includes(i)&&!n.has(i)&&(s.push(i),n.add(i));for(const i of[...e].sort((r,o)=>r.localeCompare(o)))n.has(i)||(n.add(i),s.push(i));return s}function iN({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,branch:d,onBranchChange:c,branchMode:m,onBranchModeChange:p,baseBranch:h,onBaseBranchChange:u,nodeId:f,onNodeIdChange:b,nodeOptions:y,nodeOverrideDisabled:v=!1,nodeOverrideDisabledReason:x,priority:k,onPriorityChange:w,executorModel:g,onExecutorModelChange:j,validatorModel:S,onValidatorModelChange:C,planningModel:E,onPlanningModelChange:F,thinkingLevel:M,onThinkingLevelChange:D,presetMode:_,onPresetModeChange:V,selectedPresetId:N,onSelectedPresetIdChange:$,selectedWorkflowId:R,onWorkflowIdChange:L,pendingImages:O,onImagesChange:J,tasks:A,projectId:de,disabled:B=!1,addToast:P,isActive:Z=!0,onAutoSaveDescription:T,onPlanningMode:ie,onSubtaskBreakdown:le,onClose:be,renderBelowPrimary:Le,renderBelowModelConfiguration:xe,hideDependencies:q,autoExpandMoreOptionsOnSelection:ce=!0,reviewLevel:De,onReviewLevelChange:He,autoMerge:qe,onAutoMergeChange:pe,executionMode:te,onExecutionModeChange:me,githubTrackingEnabled:se,onGithubTrackingEnabledChange:z,githubRepoOverride:Y,onGithubRepoOverrideChange:he}){const{t:X}=st("app"),ye=(q?!1:o.length>0)||O.length>0||_!=="default"||(k??yi)!==yi||g!==""||S!==""||(E||"")!==""||(M||"")!==""||De!==void 0||qe!==void 0||te==="fast"||(d||"")!==""||(h||"")!==""||(f||"")!==""||se===!0||(Y||"")!=="",[ot,ue]=a.useState(!1),[je,$e]=a.useState(ce?ye:!1),[Ce,We]=a.useState(""),[ke,Ee]=a.useState([]),[Ze,Ke]=a.useState([]),[dt,Fe]=a.useState([]),[nt,Nt]=a.useState(!1),[Ft,ze]=a.useState(null),[it,Mt]=a.useState(null),[Ht,Me]=a.useState([]),[Ae,ee]=a.useState(!1),[Ie,Pe]=a.useState("idle"),[oe,re]=a.useState([]),[_e,fe]=a.useState(!1),[Xe,kt]=a.useState(!1),[Rt,Vt]=a.useState(!1),[Pt,bt]=a.useState(!1),pt=a.useRef(null),ft=a.useRef(null),_t=a.useRef(null),Yt=a.useRef(null),on=a.useRef(null),An=a.useRef(null),vn=a.useRef(null),Qt=a.useRef(!1),sn=a.useRef(ye),mn=a.useRef(n.trim()),Kt=a.useRef(n.trim());a.useEffect(()=>{Z&&(Nt(!0),fa().then(G=>{Ee(G.models),Ke(G.favoriteProviders),Fe(G.favoriteModels)}).catch(()=>{}).finally(()=>Nt(!1)),yu(de).then(G=>ze(G)).catch(()=>ze(null)),L&&(ee(!0),Bp(de).then(G=>Me(G.filter(Oe=>Oe.kind!=="fragment"))).catch(()=>Me([])).finally(()=>ee(!1))),Ja().then(G=>Mt(G)).catch(()=>Mt(null)))},[Z,de,L]);const fn=Ft?.modelPresets||[],$n=fn.find(G=>G.id===N),On=sN(Ft,it),xn=(Y||"").trim(),Vn=xn.length>0&&!xu.test(xn),Rn=(q?!1:o.length>0)||O.length>0||_!=="default"||(k??yi)!==yi||g!==""||S!==""||(E||"")!==""||(M||"")!==""||De!==void 0||qe!==void 0||te==="fast"||(d||"")!==""||(h||"")!==""||(f||"")!==""||se===!0||(Y||"")!=="";a.useEffect(()=>{if(e!=="create"||!Z||!Ft?.autoSelectModelPreset)return;const G=(Ft.defaultPresetBySize,void 0);if(G){const Oe=Jv(G);$(G.id),V("preset"),j(Oe.executorValue),C(Oe.validatorValue)}},[Z,Ft,fn,e]);const Pn=a.useRef(!1);a.useEffect(()=>{e!=="create"||!Z||z&&(Pn.current||Ft&&(z(Ft.githubTrackingEnabledByDefault??!1),Pn.current=!0))},[e,Z,Ft,z]),a.useEffect(()=>{!Z||!u||Ro(de).then(G=>{const Oe=G.map(yt=>yt.name).filter(yt=>typeof yt=="string"&&yt.length>0);re(Wz(Oe))}).catch(()=>re([]))},[Z,u,de]),a.useEffect(()=>{Z||(Pn.current=!1)},[Z]),a.useEffect(()=>{if(!ce){sn.current=Rn;return}Rn&&!sn.current&&$e(!0),sn.current=Rn},[Rn,ce]),a.useEffect(()=>{je||(ue(!1),We(""))},[je]),a.useEffect(()=>{e!=="edit"||!Z||Yt.current&&(Yt.current.focus(),Yt.current.select())},[e,Z]),a.useEffect(()=>{if(!ot)return;const G=Oe=>{ft.current&&!ft.current.contains(Oe.target)&&ue(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[ot]),a.useEffect(()=>{(e!=="edit"||B)&&bt(!1)},[e,B]),a.useEffect(()=>{if(e!=="edit"){Pe("idle");return}const G=n.trim();mn.current=G,Kt.current=G,Pe("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!T||!Z)return;const G=n.trim(),Oe=mn.current;if(G===Oe||G===Kt.current){An.current&&(clearTimeout(An.current),An.current=null),Qt.current||Pe("idle");return}return An.current&&clearTimeout(An.current),An.current=setTimeout(async()=>{if(!Qt.current){Qt.current=!0,Pe("saving");try{await T(G),Kt.current=G,Pe("saved"),vn.current&&clearTimeout(vn.current),vn.current=setTimeout(()=>{Pe("idle"),vn.current=null},2e3)}catch{Pe("idle")}finally{Qt.current=!1,An.current=null}}},1500),()=>{An.current&&(clearTimeout(An.current),An.current=null)}},[e,n,T,Z]),a.useEffect(()=>()=>{An.current&&clearTimeout(An.current),vn.current&&clearTimeout(vn.current)},[]),a.useEffect(()=>{if(!Xe)return;const G=Oe=>{pt.current&&!pt.current.contains(Oe.target)&&kt(!1)};return document.addEventListener("mousedown",G),()=>document.removeEventListener("mousedown",G)},[Xe]);const zn=a.useCallback(G=>{const Oe=G.clipboardData?.items;if(Oe)for(let yt=0;yt<Oe.length;yt++){const Gt=Oe[yt];if(Gt.type.startsWith("image/")){const Sn=Gt.getAsFile();if(Sn&&Xv.includes(Sn.type)){G.preventDefault(),J([...O,{file:Sn,previewUrl:URL.createObjectURL(Sn)}]);return}}}},[O,J]),Nn=a.useCallback(G=>{G.preventDefault();const Oe=G.dataTransfer.files;for(let yt=0;yt<Oe.length;yt++){const Gt=Oe[yt];if(Xv.includes(Gt.type)){J([...O,{file:Gt,previewUrl:URL.createObjectURL(Gt)}]);return}}},[O,J]),dn=a.useCallback(G=>{const Oe=O[G];Oe&&URL.revokeObjectURL(Oe.previewUrl),J(O.filter((yt,Gt)=>Gt!==G))},[O,J]),Tt=a.useCallback(G=>{l(o.includes(G)?o.filter(Oe=>Oe!==G):[...o,G])},[o,l]),Yn=(G,Oe)=>G.length>Oe?G.slice(0,Oe)+"…":G,cn=a.useCallback(G=>{s(G.target.value);const Oe=G.target;Oe.style.height="auto",Oe.style.height=Oe.scrollHeight+"px"},[s]),Bn=a.useCallback(()=>{bt(G=>!G)},[]),kn=a.useCallback(G=>{!Pt||G.key!=="Escape"||(G.preventDefault(),G.stopPropagation(),bt(!1))},[Pt]),pn=a.useCallback(async G=>{const Oe=n.trim();if(!(!Oe||Rt)){Vt(!0);try{const yt=await ew(Oe,G,de);s(yt),kt(!1),P(X("taskForm.descriptionRefinedToast","Description refined with AI"),"success"),_t.current&&(_t.current.style.height="auto",_t.current.style.height=_t.current.scrollHeight+"px")}catch(yt){const Gt=tw(yt);P(Gt,"error")}finally{Vt(!1)}}},[n,Rt,P,s,de]),un=a.useCallback(async G=>{const Oe=Ze,Gt=Oe.includes(G)?Oe.filter(Sn=>Sn!==G):[G,...Oe];Ke(Gt);try{await Ms({favoriteProviders:Gt,favoriteModels:dt})}catch{Ke(Oe)}},[Ze,dt]),At=a.useCallback(async G=>{const Oe=dt,Gt=Oe.includes(G)?Oe.filter(Sn=>Sn!==G):[G,...Oe];Fe(Gt);try{await Ms({favoriteProviders:Ze,favoriteModels:Gt})}catch{Fe(Oe)}},[dt,Ze]),an=Ft?.defaultWorkflowId??null,Wn=A.filter(G=>!o.includes(G.id)).sort((G,Oe)=>{const yt=Oe.createdAt.localeCompare(G.createdAt);if(yt!==0)return yt;const Gt=parseInt(G.id.slice(G.id.lastIndexOf("-")+1),10)||0;return(parseInt(Oe.id.slice(Oe.id.lastIndexOf("-")+1),10)||0)-Gt}),Xn=Ce?Wn.filter(G=>G.id.toLowerCase().includes(Ce.toLowerCase())||G.title&&G.title.toLowerCase().includes(Ce.toLowerCase())||G.description&&G.description.toLowerCase().includes(Ce.toLowerCase())):Wn;return t.jsxs("div",{className:"task-form",onDrop:Nn,onDragOver:G=>G.preventDefault(),onPaste:zn,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:X("taskForm.titleLabel","Title")}),t.jsx("input",{ref:Yt,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:X("taskForm.titlePlaceholder","Task title"),value:i||"",onChange:G=>r(G.target.value),disabled:B})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:X("taskForm.descriptionLabel","Description")}),t.jsx("span",{className:`description-auto-save-status${Ie==="idle"?"":" is-visible"}`,"aria-live":"polite",children:Ie==="saving"?X("taskForm.autoSaveSaving","Saving..."):Ie==="saved"?X("taskForm.autoSaveSaved","Saved"):""})]}),t.jsxs("div",{className:`description-with-refine${Pt?" description--fullscreen":""}`,ref:pt,onKeyDown:kn,children:[Pt&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:X("taskForm.editingDescription","Editing Description")}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Bn,"aria-label":X("taskForm.collapseDescription","Collapse description"),title:X("taskForm.collapseDescription","Collapse description"),children:t.jsx(xc,{size:14})})]}),t.jsx("textarea",{ref:_t,autoFocus:e==="create",id:"task-form-description",value:n,onChange:cn,placeholder:X("taskForm.descriptionPlaceholder","What needs to be done?"),rows:e==="edit"?8:5,disabled:B||Rt}),(()=>{const G=!!n.trim()&&!B;return t.jsxs(t.Fragment,{children:[!Pt&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${G?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Bn,"aria-label":X("taskForm.expandDescription","Expand description"),title:X("taskForm.expandDescription","Expand description"),children:t.jsx(gu,{size:14})}),G&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Rt?"refine-button--loading":""}`,onClick:()=>kt(Oe=>!Oe),disabled:Rt,"data-testid":"refine-button",title:X("taskForm.refineTitle","Refine description with AI"),children:[t.jsx($s,{size:12,style:{verticalAlign:"middle"}}),Rt?X("taskForm.refineInProgress","Refining..."):X("taskForm.refineButton","Refine")]})]})})(),Xe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:G=>G.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>pn("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:X("taskForm.refineClarifyTitle","Clarify")}),t.jsx("div",{className:"refine-menu-item-desc",children:X("taskForm.refineClarifyDesc","Make the description clearer and more specific")})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>pn("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:X("taskForm.refineAddDetailsTitle","Add details")}),t.jsx("div",{className:"refine-menu-item-desc",children:X("taskForm.refineAddDetailsDesc","Add implementation details and context")})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>pn("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:X("taskForm.refineExpandTitle","Expand")}),t.jsx("div",{className:"refine-menu-item-desc",children:X("taskForm.refineExpandDesc","Expand into a more comprehensive description")})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>pn("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:X("taskForm.refineSimplifyTitle","Simplify")}),t.jsx("div",{className:"refine-menu-item-desc",children:X("taskForm.refineSimplifyDesc","Simplify and make more concise")})]})]})]})]}),e==="create"&&(ie||le)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[ie&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const G=n.trim();if(!G){P(X("taskForm.enterDescriptionFirst","Enter a description first"),"error");return}be?.(),ie(G)},disabled:B||!n.trim(),"data-testid":"task-form-plan-button",children:X("taskForm.planButton","Plan")}),le&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const G=n.trim();if(!G){P(X("taskForm.enterDescriptionFirst","Enter a description first"),"error");return}be?.(),le(G)},disabled:B||!n.trim(),"data-testid":"task-form-subtask-button",children:X("taskForm.subtaskButton","Subtask")})]})]}),Le,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>$e(G=>!G),"aria-expanded":je,"aria-controls":"task-form-more-options",disabled:B,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:X("taskForm.moreOptions","More options")}),je?t.jsx(ra,{size:14}):t.jsx(Ln,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${je?"":" collapsed"}`,"aria-hidden":!je,hidden:!je,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:X("taskForm.attachmentsLabel","Attachments")}),O.length>0&&t.jsx("div",{className:"inline-create-previews",children:O.map((G,Oe)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:G.previewUrl,alt:G.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>dn(Oe),disabled:B,title:X("taskForm.removeImage","Remove image"),children:"×"})]},G.previewUrl))}),t.jsx("input",{ref:on,type:"file",accept:"image/*",onChange:G=>{const Oe=G.target.files?.[0];Oe&&(J([...O,{file:Oe,previewUrl:URL.createObjectURL(Oe)}]),G.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>on.current?.click(),disabled:B,children:X("taskForm.attachScreenshot","Attach Screenshot")}),t.jsx("small",{children:X("taskForm.attachHint","You can also paste images or drag & drop")})]}),b&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:X("taskForm.nodeOverrideLabel","Execution Node Override")}),t.jsxs("select",{id:"task-node-select",className:"select",value:f??"",onChange:G=>b(G.target.value||void 0),disabled:B||v,children:[t.jsx("option",{value:"",children:X("taskForm.nodeDefaultOption","Use project default / local")}),(y??[]).map(G=>t.jsxs("option",{value:G.id,children:[G.name," (",Vz(G.status,X),")"]},G.id))]}),(()=>{const G=(y??[]).find(Oe=>Oe.id===f);return G?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Wr,{status:G.status,showLabel:!0})}):null})(),t.jsx("small",{children:x??X("taskForm.nodeOverrideHint","Task override takes priority over project default node routing.")})]}),!q&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:X("taskForm.dependenciesLabel","Dependencies")}),t.jsxs("div",{className:"dep-trigger-wrap",ref:ft,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ue(G=>!G),disabled:B,children:o.length>0?X("taskForm.dependenciesSelected","{{count}} selected",{count:o.length}):X("taskForm.addDependencies","Add dependencies")}),ot&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:X("taskForm.searchTasksPlaceholder","Search tasks…"),autoFocus:!0,value:Ce,onChange:G=>We(G.target.value),onClick:G=>G.stopPropagation()}),Xn.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:X("taskForm.noAvailableTasks","No available tasks")}):Xn.map(G=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(G.id)?" selected":""}`,onClick:()=>Tt(G.id),onMouseDown:Oe=>Oe.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:G.id}),t.jsx("span",{className:"dep-dropdown-title",children:Yn(G.title||G.description||G.id,30)})]},G.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(G=>t.jsxs("span",{className:"dep-chip",children:[G,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>Tt(G),disabled:B,children:"×"})]},G))})]})}),(c||u||p)&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:X("taskForm.branchSettingsLabel","Branch Settings")}),p?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-branch-mode",className:"model-select-label",children:X("taskForm.branchStrategyLabel","Branch strategy")}),t.jsxs("select",{id:"task-branch-mode",className:"input",value:m??"project-default",onChange:G=>p(G.target.value),disabled:B,children:[t.jsx("option",{value:"project-default",children:X("taskForm.branchModeProjectDefault","Use project/default branch")}),t.jsx("option",{value:"auto-new",children:X("taskForm.branchModeAutoNew","Create auto-named branch per task")}),t.jsx("option",{value:"existing",children:X("taskForm.branchModeExisting","Use existing branch")}),t.jsx("option",{value:"custom-new",children:X("taskForm.branchModeCustomNew","Create custom new branch")}),t.jsx("option",{value:"shared-group",children:X("taskForm.branchModeSharedGroup","Merge into a shared feature branch")})]})]}):null,c&&(!p||m==="existing"||m==="custom-new"||m==="shared-group")&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-working-branch",className:"model-select-label",children:m==="shared-group"?X("taskForm.sharedFeatureBranchLabel","Shared feature branch"):p?X("taskForm.branchNameLabel","Branch name"):X("taskForm.workingBranchLabel","Working branch")}),t.jsx("input",{id:"task-working-branch",className:"input",value:d||"",onChange:G=>c(G.target.value),placeholder:m==="shared-group"?X("taskForm.sharedBranchPlaceholder","e.g. clionboarding"):X("taskForm.branchPlaceholder","e.g. feature/my-task"),disabled:B})]}),u&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-base-branch",className:"model-select-label",children:X("taskForm.baseBranchLabel","Merge target / base branch")}),(()=>{const G=h||"",Oe=G.length>0&&oe.includes(G);return _e||G.length>0&&!Oe||oe.length===0?t.jsxs("div",{className:"form-inline-group",children:[t.jsx("input",{id:"task-base-branch",className:"input",value:G,onChange:Gt=>u(Gt.target.value),placeholder:X("taskForm.baseBranchPlaceholder","e.g. main"),disabled:B,"data-testid":"task-base-branch-custom-input"}),t.jsx("button",{type:"button",className:"btn-link",onClick:()=>{fe(!1),u("")},disabled:B,"data-testid":"task-base-branch-use-dropdown",children:X("taskForm.useDropdown","Use dropdown")})]}):t.jsxs("select",{id:"task-base-branch",className:"select",value:G,onChange:Gt=>{const Sn=Gt.target.value;if(Sn===Qv){fe(!0);return}u(Sn===Zv?"":Sn)},disabled:B,"data-testid":"task-base-branch-select",children:[t.jsx("option",{value:Zv,children:X("taskForm.baseBranchDefault","(default / project branch)")}),oe.map(Gt=>t.jsx("option",{value:Gt,children:Gt},Gt)),t.jsx("option",{value:Qv,children:X("taskForm.baseBranchCustom","Custom…")})]})})()]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:X("taskForm.modelConfigLabel","Model Configuration")}),w&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:X("taskForm.priorityLabel","Priority")}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:k??yi,onChange:G=>w(G.target.value),disabled:B,children:xr.map(G=>t.jsx("option",{value:G,children:X(`taskForm.priority_${G}`,G[0].toUpperCase()+G.slice(1))},G))})]}),me&&te!==void 0&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-execution-mode",className:"model-select-label",children:X("taskForm.executionModeLabel","Execution mode")}),t.jsxs("select",{id:"task-execution-mode","data-testid":"task-form-execution-mode-select",value:te,onChange:G=>me(G.target.value),disabled:B,children:[t.jsx("option",{value:"standard",children:X("taskForm.executionModeStandard","Standard")}),t.jsx("option",{value:"fast",children:X("taskForm.executionModeFast","Fast")})]})]}),nt?t.jsx("div",{className:"model-selector-loading",children:X("taskForm.loadingModels","Loading models…")}):ke.length===0?t.jsx("small",{children:X("taskForm.noModelsAvailable","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:X("taskForm.presetLabel","Preset")}),t.jsxs("select",{id:"model-preset",value:_==="preset"?N:_,onChange:G=>{const Oe=G.target.value;if(Oe==="default"){V("default"),$(""),j(""),C("");return}if(Oe==="custom"){V("custom"),$("");return}const yt=fn.find(Sn=>Sn.id===Oe),Gt=Jv(yt);V("preset"),$(Oe),j(Gt.executorValue),C(Gt.validatorValue)},disabled:B,children:[t.jsx("option",{value:"default",children:X("taskForm.presetUseDefault","Use default")}),fn.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,fn.map(G=>t.jsx("option",{value:G.id,children:G.name},G.id)),t.jsx("option",{value:"custom",children:X("taskForm.presetCustom","Custom")})]})]}),_==="preset"&&$n?t.jsx("small",{children:X("taskForm.usingPreset","Using preset: {{name}}",{name:$n.name})}):null,_==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>V("custom"),disabled:B,children:X("taskForm.overridePreset","Override")}):null,t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:X("taskForm.executorLabel","Executor")}),t.jsx(wi,{id:"executor-model",label:X("taskForm.executorModelLabel","Executor Model"),value:g,onChange:G=>{V("custom"),$(""),j(G)},models:ke,disabled:B||_==="preset",favoriteProviders:Ze,onToggleFavorite:un,favoriteModels:dt,onToggleModelFavorite:At})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:X("taskForm.reviewerLabel","Reviewer")}),t.jsx(wi,{id:"validator-model",label:X("taskForm.reviewerModelLabel","Reviewer Model"),value:S,onChange:G=>{V("custom"),$(""),C(G)},models:ke,disabled:B||_==="preset",favoriteProviders:Ze,onToggleFavorite:un,favoriteModels:dt,onToggleModelFavorite:At})]}),F&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:X("taskForm.planningLabel","Planning")}),t.jsx(wi,{id:"planning-model",label:X("taskForm.planningModelLabel","Planning Model"),value:E||"",onChange:G=>{V("custom"),$(""),F(G)},models:ke,disabled:B||_==="preset",favoriteProviders:Ze,onToggleFavorite:un,favoriteModels:dt,onToggleModelFavorite:At})]}),D&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:X("taskForm.thinkingLabel","Thinking")}),t.jsxs("select",{id:"thinking-level",value:M||"",onChange:G=>D(G.target.value),disabled:B||_==="preset",children:[t.jsx("option",{value:"",children:X("taskForm.thinkingDefault","Default ({{level}})",{level:Ft?.defaultThinkingLevel??"off"})}),t.jsx("option",{value:"off",children:X("taskForm.thinkingOff","Off")}),t.jsx("option",{value:"minimal",children:X("taskForm.thinkingMinimal","Minimal")}),t.jsx("option",{value:"low",children:X("taskForm.thinkingLow","Low")}),t.jsx("option",{value:"medium",children:X("taskForm.thinkingMedium","Medium")}),t.jsx("option",{value:"high",children:X("taskForm.thinkingHigh","High")})]})]}),He&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:X("taskForm.reviewLabel","Review")}),t.jsxs("select",{id:"review-level",value:De??"",onChange:G=>He(G.target.value===""?void 0:parseInt(G.target.value,10)),disabled:B,children:[t.jsx("option",{value:"",children:X("taskForm.reviewDefault","Default (Auto — triage decides)")}),t.jsx("option",{value:"0",children:X("taskForm.reviewLevel0","0 — None")}),t.jsx("option",{value:"1",children:X("taskForm.reviewLevel1","1 — Plan Only")}),t.jsx("option",{value:"2",children:X("taskForm.reviewLevel2","2 — Plan and Code")}),t.jsx("option",{value:"3",children:X("taskForm.reviewLevel3","3 — Full")})]})]}),pe&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-automerge-select",className:"model-select-label",children:X("taskForm.autoMergeLabel","Auto-merge")}),t.jsxs("select",{id:"task-automerge-select","data-testid":"task-automerge-select",value:qe===void 0?"":qe?"on":"off",onChange:G=>G.target.value==="on"?pe(!0):G.target.value==="off"?pe(!1):pe(void 0),disabled:B,children:[t.jsx("option",{value:"",children:X("taskForm.autoMergeDefault","Default (Follow project setting)")}),t.jsx("option",{value:"on",children:X("taskForm.autoMergeEnabled","Enabled")}),t.jsx("option",{value:"off",children:X("taskForm.autoMergeDisabled","Disabled")})]}),t.jsx("small",{children:X("taskForm.autoMergeHint","Default follows the project auto-merge setting.")})]})]})]}),xe,L&&t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{htmlFor:"task-workflow-select",children:X("taskForm.workflowLabel","Workflow")}),Ae?t.jsx("div",{className:"workflow-select-loading","data-testid":"task-workflow-loading",children:X("taskForm.workflowsLoading","Loading workflows…")}):Ht.length===0?t.jsx("div",{className:"workflow-select-cta","data-testid":"task-workflow-cta",children:X("taskForm.workflowsCta","Set up workflows in the editor")}):t.jsxs("select",{id:"task-workflow-select","data-testid":"task-workflow-select",value:R===null?"__none__":R===void 0?an??"__none__":R,disabled:B,onChange:G=>{const Oe=G.target.value;L(Oe==="__none__"?null:Oe)},children:[t.jsx("option",{value:"__none__",children:X("taskForm.workflowNone","No workflow")}),an&&Ht.some(G=>G.id===an)&&t.jsx("option",{value:an,children:`${Ht.find(G=>G.id===an)?.name??an} ${X("taskForm.workflowDefaultBadge","(default)")}`}),Ht.filter(G=>G.id!==an).map(G=>t.jsx("option",{value:G.id,children:G.name},G.id))]}),t.jsx("small",{className:"workflow-select-help","data-testid":"task-workflow-help",children:X("taskForm.workflowHelp","The selected workflow's steps run automatically around this task's execution.")})]}),(z||he)&&t.jsxs("div",{className:"form-group","data-testid":"task-form-github-tracking",children:[t.jsx("label",{children:X("taskForm.githubTrackingLabel","GitHub Tracking")}),z&&t.jsxs("label",{className:"checkbox-label",htmlFor:"task-github-tracking-enabled",children:[t.jsx("input",{id:"task-github-tracking-enabled",type:"checkbox",checked:se===!0,onChange:G=>{Pn.current=!0,z(G.target.checked)},disabled:B}),X("taskForm.githubTrackingEnable","Enable GitHub issue tracking for this task")]}),he&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-github-repo-override",className:"model-select-label",children:X("taskForm.githubRepoLabel","Repository (owner/repo)")}),t.jsx("input",{id:"task-github-repo-override",className:"input",value:Y||"",onChange:G=>he(G.target.value),placeholder:On||"owner/repo",disabled:B}),Vn?t.jsx("div",{className:"form-error",children:X("taskForm.githubRepoFormatError","Repository must be in owner/repo format.")}):null]})]})]})]})}function aN({value:e,onChange:n,projectId:s,addToast:i,disabled:r,label:o="Workflow",onManage:l,hasActiveSession:d}){const{t:c}=st("app"),m=a.useId(),{confirm:p}=Yi(),[h,u]=a.useState([]),[f,b]=a.useState(!1),[y,v]=a.useState(!1);a.useEffect(()=>{let k=!1;return u([]),b(!0),Bp(s).then(async w=>{if(e&&!w.some(g=>g.id===e))try{const g=await Zk(e,s);w=[...w,g]}catch{}k||u(w)}).catch(w=>{k||u([]),i?.(Re(w)||"Failed to load workflows","error")}).finally(()=>{k||b(!1)}),()=>{k=!0}},[s,i,e]);const x=a.useCallback(async k=>{const w=k===""?null:k;if(!(d&&!await p({title:c("workflowSelector.switchActiveTitle","Switch workflow?"),message:c("workflowSelector.switchActiveMessage","This task has an active session. Switching workflows aborts it and re-homes the card into the new workflow's entry column. Continue?"),confirmLabel:c("workflowSelector.switchConfirm","Switch and abort"),cancelLabel:c("workflowSelector.switchCancel","Cancel"),danger:!0}))){v(!0);try{await n(w)}catch(g){i?.(Re(g)||"Failed to apply workflow","error")}finally{v(!1)}}},[n,i,d,p,c]);return t.jsxs("div",{className:"workflow-selector","data-testid":"workflow-selector",children:[t.jsxs("div",{className:"workflow-selector-label",children:[t.jsx("div",{className:"workflow-selector-label-text",children:t.jsxs("label",{htmlFor:m,className:"workflow-selector-title",children:[t.jsx(lc,{size:14,"aria-hidden":!0})," ",o]})}),t.jsxs("select",{id:m,value:e??"",disabled:r||f||y,onChange:k=>void x(k.target.value),children:[t.jsx("option",{value:"",children:"None"}),h.map(k=>t.jsx("option",{value:k.id,children:k.name},k.id))]})]}),l&&t.jsx("button",{type:"button",className:"workflow-selector-manage",onClick:l,children:"Manage…"})]})}function kK({projectId:e,addToast:n,onManage:s}){const[i,r]=a.useState(null);a.useEffect(()=>{let l=!1;return r(null),LA(e).then(d=>{l||r(d.workflowId)}).catch(()=>{l||r(null)}),()=>{l=!0}},[e]);const o=a.useCallback(async l=>{const d=await FA(l,e);r(d.workflowId),n?.(l?"Default workflow set":"Default workflow cleared","success")},[e,n]);return t.jsx(aN,{value:i,onChange:o,projectId:e,addToast:n,label:"Default workflow for new tasks",onManage:s})}const wK=240,jK=64,rN=560,oN=220,lN=30,cN=56,dN=260,tl="::";function Qd(e,n){return`${e}${tl}${n}`}function ip(e,n){const s=`${e}${tl}`;return n.startsWith(s)?n.slice(s.length):n}const Tu=220,Gz=5e3,Kz=-40,wf=0,jf=0,Jz=1,Zd=2,Yz=e=>`__col__:${e}`,Nf=e=>e.startsWith("__col__:"),NK=e=>e.slice(8);function uN(e){return wf+e*Tu}function Xz(e,n){if(n.length===0)return;const s=Math.floor((e-wf)/Tu),i=Math.max(0,Math.min(n.length-1,s));return n[i]?.id}function Qz(e,n){if(n.length===0)return;const s=Math.floor((e-wf)/Tu);if(!(s<0||s>=n.length))return n[s]?.id}function nl(e){return e.version==="v2"}function mc(e){return e.config?.seam==="merge"||e.kind==="pr-merge"?"merge":e.kind==="pr-create"||e.kind==="pr-respond"?"prompt":e.kind}function Bo(e){const n=e.config?.name;return typeof n=="string"&&n.trim()?n:e.config?.seam==="merge"?"Merge boundary":e.id}function Zz(e){return e.map((n,s)=>({id:Yz(n.id),type:"group",position:{x:Kz,y:uN(s)},data:{kind:"start",label:n.name,column:n.id},draggable:!1,selectable:!1,deletable:!1,zIndex:jf,style:{width:Gz,height:Tu},className:"wf-column-band"}))}function eB(e){if(e.kind!=="foreach")return;const n=e.config;if(!(!n||!n.template))return n}function tB(e){if(e.kind!=="loop")return;const n=e.config;if(!(!n||!n.template))return n}function Sf(e){return eB(e)??tB(e)}function mN(e,n){if(n)return"wf-edge-rework";if(e==="failure")return"wf-edge-failure"}function eu(e,n,s=""){const i=e.condition??"success",r=e.kind==="rework";return{id:`e-${s}${e.from}-${e.to}-${n}`,source:s?`${s}${e.from}`:e.from,target:s?`${s}${e.to}`:e.to,label:r?`${ap(i)} (rework)`:ap(i),data:{condition:i,kind:r?"rework":void 0},type:r?"step":void 0,animated:r,className:mN(i,r),interactionWidth:hN,markerEnd:void 0,zIndex:Jz}}const hN=24;function ap(e){return e.startsWith("outcome:")?e.slice(8):e}function nB(e){const n=nl(e.ir)?e.ir.columns:[],s=Zz(n),i=[],r=[],o=e.ir.nodes.map((d,c)=>{const m=e.layout?.[d.id],p=mc(d),h=nl(e.ir)?d.column:void 0,u=h?n.findIndex(y=>y.id===h):-1,f=u>=0?uN(u)+70:120,b=Sf(d);if(b){const y=b.template;y.nodes.forEach((k,w)=>{const g=Qd(d.id,k.id),j=e.layout?.[g]??{x:lN+w*dN,y:cN},S=mc(k);i.push({id:g,type:S,position:j,parentId:d.id,extent:"parent",data:{kind:S,label:Bo(k),config:{...k.config??{}}},deletable:!0,zIndex:Zd})}),y.edges.forEach((k,w)=>{r.push(eu(k,w,`${d.id}${tl}`))});const{template:v,...x}=d.config??{};return{id:d.id,type:p,position:m??{x:80+c*180,y:f},data:{kind:p,label:Bo(d),config:{...x},column:h,templateEmpty:y.nodes.length===0},style:{width:rN,height:oN},deletable:!0,zIndex:jf}}return{id:d.id,type:p,position:m??{x:80+c*180,y:f},data:{kind:p,label:Bo(d),config:{...d.config??{}},column:h},deletable:d.kind!=="start"&&d.kind!=="end",zIndex:Zd}}),l=e.ir.edges.map((d,c)=>eu(d,c));return{nodes:[...s,...o,...i],edges:[...l,...r]}}function sB(e){const n=e.data,s={...n.config??{}},i=n.kind==="merge"?"Merge boundary":e.id;return n.kind!=="start"&&n.kind!=="end"&&n.label&&n.label!==i?s.name=n.label:delete s.name,s}function SK(e,n,s,i,r,o){const l=n.filter(k=>!Nf(k.id)),d=l.filter(k=>!k.parentId),c=new Map;for(const k of l)if(k.parentId){const w=c.get(k.parentId)??[];w.push(k),c.set(k.parentId,w)}new Set(d.filter(k=>k.data.kind==="foreach"||k.data.kind==="loop").map(k=>k.id));const m=Array.isArray(r)&&r.length>0,p=Array.isArray(o)&&o.length>0,h=Array.isArray(i)&&i.length>0||m||p,u={};function f(k,w){const g=k.data,j=sB(k);if(g.kind==="merge")return{id:w,kind:"prompt",config:{...j??{},seam:"merge"}};if(g.kind==="foreach"||g.kind==="loop"){const S=c.get(k.id)??[],C=S.map(D=>{const _=ip(k.id,D.id);return u[D.id]={x:Math.round(D.position.x),y:Math.round(D.position.y)},f(D,_)}),E=new Set(S.map(D=>D.id)),F=s.filter(D=>E.has(D.source)&&E.has(D.target)).map(D=>ex(D,k.id)),M=j??{};return{id:w,kind:g.kind,config:{...M,template:{nodes:C,edges:F}}}}return{id:w,kind:g.kind,config:j&&Object.keys(j).length?j:void 0}}const b=Array.isArray(i)&&i.length>0,y=d.map(k=>{const w=b?k.data.column??Xz(k.position.y,i):void 0,g=f(k,k.id);return u[k.id]={x:Math.round(k.position.x),y:Math.round(k.position.y)},w?{...g,column:w}:g}),v=new Map;for(const[k,w]of c)for(const g of w)v.set(g.id,k);const x=s.filter(k=>{const w=v.get(k.source),g=v.get(k.target);return!(w&&g&&w===g)}).map(k=>ex(k));if(h){const k={version:"v2",name:e,columns:b?i.map(w=>({id:w.id,name:w.name,traits:w.traits,...w.agent?{agent:w.agent}:{}})):[],nodes:y,edges:x};return m&&(k.fields=r.map(w=>({...w}))),p&&(k.settings=o.map(w=>({...w,options:w.options?w.options.map(g=>({...g})):void 0,render:w.render?{...w.render}:void 0}))),{ir:k,layout:u}}return{ir:{version:"v1",name:e,nodes:y,edges:x},layout:u}}function ex(e,n){const s=e.data?.condition??"success",i=e.data?.kind==="rework",r=n?ip(n,e.source):e.source,o=n?ip(n,e.target):e.target;return{from:r,to:o,condition:s,...i?{kind:"rework"}:{}}}const iB=new Set(["start","end"]);function aB(e){return Nf(e.id)||iB.has(e.data.kind)}function CK(e,n,s){const i=new Set(s),r=new Map(e.map(m=>[m.id,m])),o=new Set;for(const m of i){const p=r.get(m);if(!(!p||aB(p))&&(o.add(m),p.data.kind==="foreach"||p.data.kind==="loop"))for(const h of e)h.parentId===m&&o.add(h.id)}const l=new Set;for(const m of n)i.has(m.id)&&l.add(m.id);const d=e.filter(m=>!o.has(m.id)),c=n.filter(m=>!l.has(m.id)&&!o.has(m.source)&&!o.has(m.target));return{nodes:d,edges:c}}const rB=new Set(["prompt","script","gate","code","foreach","loop"]);function oB(e){return e==="step-review"?"verdicts":e&&rB.has(e)?"conditions":"readonly"}function lB(e,n,s){if(n===s)return!0;const i=new Map;for(const l of e){if(l.data?.kind==="rework")continue;const d=i.get(l.source)??[];d.push(l.target),i.set(l.source,d)}const r=new Set,o=[s];for(;o.length;){const l=o.pop();if(l===n)return!0;if(!r.has(l)){r.add(l);for(const d of i.get(l)??[])o.push(d)}}return!1}let tx=0;function pN(){return tx+=1,`e-${Date.now().toString(36)}-${tx}`}let nx=0;function Cf(){return nx+=1,`n-${Date.now().toString(36)}-${nx}`}function _K(e,n,s){const i=e.source??void 0,r=e.target??void 0;if(!i||!r)return{error:"missing-endpoint"};const o=s.find(h=>h.id===i),l=s.find(h=>h.id===r),d=new Set(n.filter(h=>h.source===i&&h.target===r).map(h=>h.data?.condition??"success")),c=oB(o?.data.kind)==="conditions";let m="success";if(d.has("success"))if(c&&!d.has("failure"))m="failure";else return{error:"duplicate"};else if(d.has(m))return{error:"duplicate"};return!(!!o?.parentId&&o.parentId===l?.parentId)&&lB(n,i,r)?{error:"cycle"}:{edge:{id:pN(),source:i,target:r,label:ap(m),data:{condition:m,kind:void 0},className:mN(m,!1),interactionWidth:hN}}}function cB(e,n){const s={},i=[],r=[];for(const o of e){const l=n.get(o.trait);if(!l){r.push(o.trait);continue}for(const[d,c]of Object.entries(l.flags))c&&(s[d]=!0);l.flags.countsTowardWip&&i.push(l.id)}return{flags:s,capacityTraitIds:i,unknown:r}}function EK(e,n){const s=new Map(n.map(o=>[o.id,o])),i=[];let r=0;for(const o of e){const{flags:l,capacityTraitIds:d,unknown:c}=cB(o.traits,s);for(const m of c)i.push({code:"unknown-trait",severity:"error",columnId:o.id,traitIds:[m],message:`Column '${o.id}' references unknown trait '${m}'`});l.complete&&l.countsTowardWip&&i.push({code:"complete-with-wip",severity:"error",columnId:o.id,traitIds:d,message:`Column '${o.name||o.id}' is both a completion column and counts toward WIP`}),d.length>1&&i.push({code:"two-capacity-traits",severity:"error",columnId:o.id,traitIds:d,message:`Column '${o.name||o.id}' has more than one capacity (WIP) trait`}),l.complete&&l.intake&&i.push({code:"complete-with-intake",severity:"error",columnId:o.id,traitIds:[],message:`Column '${o.name||o.id}' is both a completion column and an intake column`}),l.archived&&l.countsTowardWip&&i.push({code:"archived-with-wip",severity:"error",columnId:o.id,traitIds:[],message:`Column '${o.name||o.id}' is archived but counts toward WIP`}),l.intake&&(r+=1)}return r>1&&i.push({code:"multiple-intake-columns",severity:"error",columnId:null,traitIds:[],message:`Workflow has ${r} intake columns; exactly one is allowed`}),i}function MK(e,n){if(n.length===0)return[];const s=[];for(const i of e){if(Nf(i.id)||i.type==="group"||i.parentId||i.data.kind==="start"||i.data.kind==="end")continue;const r=i.data.column;if(r&&n.some(l=>l.id===r))continue;if(r&&!n.some(l=>l.id===r)){s.push(i.id);continue}Qz(i.position.y,n)||s.push(i.id)}return s}function AK(e){return nl(e.ir)?e.ir.columns.map(n=>({...n,traits:[...n.traits]})):[]}function TK(e){const n=e.ir;return!nl(e.ir)||!Array.isArray(n.fields)?[]:n.fields.map(s=>({...s,options:s.options?s.options.map(i=>({...i})):void 0,render:s.render?{...s.render}:void 0}))}function RK(e){const n=e.ir;return!nl(e.ir)||!Array.isArray(n.settings)?[]:n.settings.map(s=>({...s,options:s.options?s.options.map(i=>({...i})):void 0,render:s.render?{...s.render}:void 0}))}function PK(e){return{version:"v1",name:e,nodes:[{id:"start",kind:"start"},{id:"end",kind:"end"}],edges:[{from:"start",to:"end",condition:"success"}]}}function IK(){return{start:{x:80,y:140},end:{x:460,y:140}}}const sx=new Set(["execute","review","merge"]);function dB(e){if(e.data?.kind==="merge")return"merge";const n=e.data?.config?.seam;return typeof n=="string"?n:void 0}function uB(e){const n=e.config?.seam;return typeof n=="string"?n:void 0}function DK(e,n){const s=new Set;for(const o of n){const l=dB(o);l&&sx.has(l)&&s.add(l)}const i=[],r=new Set;for(const o of e.nodes){const l=uB(o);l&&sx.has(l)&&s.has(l)&&!r.has(l)&&(r.add(l),i.push(l))}return i}function mB(e,n,s){const i=mc(e);return{id:n,type:i,position:s,data:{kind:i,label:Bo(e),config:{...e.config??{}}},deletable:e.kind!=="start"&&e.kind!=="end",zIndex:Zd}}function LK(e,n,s,i,r){const o=s.nodes.filter(v=>v.kind!=="start"&&v.kind!=="end"),l=new Set(s.nodes.filter(v=>v.kind==="start"||v.kind==="end").map(v=>v.id)),d=new Map;for(const v of o)d.set(v.id,Cf());const c=o.map(v=>r?.[v.id]).filter(v=>!!v),m=c.length?Math.min(...c.map(v=>v.x)):0,p=c.length?Math.min(...c.map(v=>v.y)):0,h=[],u=[],f=[],b=o.map((v,x)=>{const k=d.get(v.id);h.push(k);const w=r?.[v.id],g=w?{x:i.x+(w.x-m),y:i.y+(w.y-p)}:{x:i.x+x*180,y:i.y},j=Sf(v);if(j){const S=j.template,C=mc(v);S.nodes.forEach((M,D)=>{const _=mc(M),V=r?.[Qd(v.id,M.id)]??{x:lN+D*dN,y:cN};u.push({id:Qd(k,M.id),type:_,position:V,parentId:k,extent:"parent",data:{kind:_,label:Bo(M),config:{...M.config??{}}},deletable:!0,zIndex:Zd})}),S.edges.forEach((M,D)=>{f.push(eu(M,D,`${k}${tl}`))});const{template:E,...F}=v.config??{};return{id:k,type:C,position:g,data:{kind:C,label:Bo(v),config:{...F},templateEmpty:S.nodes.length===0},style:{width:rN,height:oN},deletable:!0,zIndex:jf}}return mB(v,k,g)}),y=s.edges.filter(v=>!l.has(v.from)&&!l.has(v.to)).filter(v=>d.has(v.from)&&d.has(v.to)).map((v,x)=>({...eu(v,x),id:pN(),source:d.get(v.from),target:d.get(v.to)}));return{nodes:[...e,...b,...u],edges:[...n,...y,...f],insertedNodeIds:h}}function hB(e,n){for(const r of e.nodes)n.set(r.id,Cf());const s=e.nodes.map(r=>fN(r,n.get(r.id))),i=e.edges.map(r=>({...r,from:n.get(r.from)??r.from,to:n.get(r.to)??r.to}));return{nodes:s,edges:i}}function fN(e,n,s){const i=e.config?{...e.config}:void 0,r=Sf(e);if(r&&i){const l=new Map;i.template=hB(r.template,l),s?.set(e.id,l)}const o={id:n,kind:e.kind};return e.column!==void 0&&(o.column=e.column),i&&(o.config=i),o}function FK(e,n){const s=new Map;for(const c of e.nodes)s.set(c.id,Cf());const i=new Map,r=e.nodes.map(c=>fN(c,s.get(c.id),i)),o=e.edges.map(c=>({...c,from:s.get(c.from)??c.from,to:s.get(c.to)??c.to})),l={};for(const[c,m]of Object.entries(n)){const p=c.indexOf(tl);if(p>=0){const u=c.slice(0,p),f=c.slice(p+tl.length),b=s.get(u),v=i.get(u)?.get(f);if(b&&v){l[Qd(b,v)]={...m};continue}}const h=s.get(c);l[h??c]={...m}}let d;return nl(e)?d={...e,nodes:r,edges:o,columns:e.columns.map(m=>({...m,traits:m.traits.map(p=>({...p}))}))}:d={...e,nodes:r,edges:o},{ir:d,layout:l}}const pB=(e,n,s)=>s?n.replace(/\{\{(\w+)\}\}/g,(i,r)=>r in s?String(s[r]):`{{${r}}}`):n,nd=40;function Os(e){return typeof e=="string"?e:""}function sd(e,n){const s=e.trim();return s.length<=n?s:`${s.slice(0,n-1)}…`}function Lm(e){return(e.split(/\r?\n/,1)[0]??"").trim()}function fB(e,n){const s=Os(e.modelProvider),i=Os(e.modelId),r=n.models?.find(o=>o.provider===s&&o.id===i);return r?.name?r.name:s&&i?`${s}/${i}`:i||""}function gB(e){const n=e.mode;return n&&typeof n=="object"&&"quorum"in n?`quorum(${n.quorum})`:typeof n=="string"?n:"all"}function bB(e,n={},s=pB){const i=e.kind,r=e.config??{};switch(i){case"prompt":{const o=Os(r.seam);if(o)switch(o){case"execute":return s("workflowNodes.summarySeamExecute","Execute (engine)");case"review":return s("workflowNodes.summarySeamReview","Review (engine)");case"merge":return s("workflowNodes.summarySeamMerge","Merge boundary");case"planning":return s("workflowNodes.summarySeamPlanning","Plan (engine)");case"step-execute":return s("workflowNodes.summarySeamStepExecute","Step execute (engine)");default:return s("workflowNodes.summarySeamUnknown","Seam: {{seam}}",{seam:o})}const l=Os(r.executor)||"model";if(l==="agent"){const c=Os(r.agentId);return c?n.agents?.find(p=>p.id===c)?.name||c:s("workflowNodes.summaryNotConfigured","Not configured")}if(l==="skill"){const c=Os(r.skillName);return c?n.skills?.find(p=>p.name===c||p.id===c)?.name||c:s("workflowNodes.summaryNotConfigured","Not configured")}if(l==="cli"){if((Os(r.cliMode)||"command")==="script")return Os(r.scriptName)||s("workflowNodes.summaryNotConfigured","Not configured");const m=Os(r.cliCommand);return m?sd(m,nd):s("workflowNodes.summaryNotConfigured","Not configured")}const d=fB(r,n);return d||(r.awaitInput===!0?s("workflowNodes.summaryAwaitInput","Waits for user input"):s("workflowNodes.summaryNotConfigured","Not configured"))}case"script":return Os(r.scriptName)||s("workflowNodes.summaryNotConfigured","Not configured");case"gate":{const o=Os(r.prompt);return o?sd(Lm(o),nd):(Os(r.gateMode)||"gate")==="advisory"?s("workflowNodes.summaryGateAdvisory","Advisory"):s("workflowNodes.summaryGateBlocks","Gate (blocks)")}case"hold":{const o=Os(r.release)||"manual";return s("workflowNodes.summaryHoldRelease","Release: {{release}}",{release:o})}case"join":return gB(r);case"foreach":{const o=Os(r.mode)||"sequential",l=Os(r.isolation)||(o==="parallel"?"worktree":"shared");return`${o} · ${l}`}case"loop":{const o=r.exitWhen,l=o&&typeof o=="object"?(()=>{const c=o,m=Os(c.type);return m==="output-matches"?s("workflowNodes.summaryLoopUntilMatches","until matches /{{pattern}}/",{pattern:Os(c.pattern)}):m==="output-contains"?s("workflowNodes.summaryLoopUntilContains",'until contains "{{value}}"',{value:Os(c.value)}):""})():"",d=typeof r.maxIterations=="number"&&Number.isFinite(r.maxIterations)?s("workflowNodes.summaryLoopIterations","{{count}}x",{count:r.maxIterations}):s("workflowNodes.summaryLoopIterations","{{count}}x",{count:3});return l?`${l} · ${d}`:d}case"step-review":{const o=Os(r.type)||"code";return s("workflowNodes.summaryReviewType","{{type}} review",{type:o})}case"parse-steps":{const o=Os(r.parser)||"step-headings",l=Os(r.artifact);return l?`${o} · ${l}`:o}case"code":{const o=Lm(Os(r.source));return o?sd(o,nd):s("workflowNodes.summaryCodeDefault","TypeScript")}case"notify":{const o=Os(r.event)||"workflow-notify",l=sd(Lm(Os(r.message)),nd);return l?`${o} · ${l}`:o}case"start":case"end":case"split":case"merge":default:return""}}const vB=a.createContext({});function xB(){return a.useContext(vB)}const yB={start:Ds,end:Sk,prompt:Ra,script:ua,gate:W1,merge:rc,hold:LC,split:X1,join:h1,foreach:Fd,loop:Fd,"step-review":UC,"parse-steps":Ek,code:GC,notify:bC};function _f({message:e}){return t.jsxs("span",{className:"wf-node-error-badge",role:"alert","data-testid":"wf-node-error-badge",title:e,children:[t.jsx(oa,{size:11,"aria-hidden":!0})," ",e]})}function Hi({data:e,kind:n}){const{t:s}=st("app"),i=xB(),r=yB[n],o=n!=="start",l=n!=="end",d=n==="hold"?e.config?.release:void 0,c=n==="join"?(()=>{const f=e.config?.mode;return f&&typeof f=="object"&&"quorum"in f?`quorum(${f.quorum})`:typeof f=="string"?f:"all"})():void 0,m=n==="prompt"?e.config?.seam:void 0,p=n==="step-review"?e.config?.type:void 0,h=n==="parse-steps"?e.config?.parser:void 0,u=bB(e,i,s);return t.jsxs("div",{className:`wf-node wf-node-${n}${m==="step-execute"?" wf-node-step-execute":""}${e.errorBadge?" wf-node--error":""}`,"data-testid":`wf-node-${n}`,children:[o&&t.jsx(Uo,{type:"target",position:Ho.Left}),t.jsxs("div",{className:"wf-node-header",children:[t.jsx("span",{className:"wf-node-icon",children:t.jsx(r,{size:14,"aria-hidden":!0})}),t.jsx("span",{className:"wf-node-label",children:e.label||n}),n==="gate"&&t.jsx("span",{className:"wf-node-badge",children:"gate"}),d&&t.jsx("span",{className:"wf-node-badge",children:d}),c&&t.jsx("span",{className:"wf-node-badge",children:c}),m==="step-execute"&&t.jsx("span",{className:"wf-node-badge",children:"step"}),p&&t.jsx("span",{className:"wf-node-badge",children:p}),h&&t.jsx("span",{className:"wf-node-badge",children:h}),e.errorBadge&&t.jsx(_f,{message:e.errorBadge})]}),u&&t.jsx("div",{className:"wf-node-summary","data-testid":"wf-node-summary",title:u,children:u}),l&&t.jsx(Uo,{type:"source",position:Ho.Right})]})}function kB({data:e}){const n=e.config?.mode??"sequential",s=e.config?.isolation??(n==="parallel"?"worktree":"shared"),i=e.templateEmpty===!0;return t.jsxs("div",{className:`wf-foreach-group${e.errorBadge?" wf-node--error":""}`,"data-testid":"wf-node-foreach",children:[t.jsx(Uo,{type:"target",position:Ho.Left}),t.jsxs("div",{className:"wf-foreach-header",children:[t.jsx("span",{className:"wf-node-icon",children:t.jsx(Fd,{size:14,"aria-hidden":!0})}),t.jsx("span",{className:"wf-node-label",children:e.label||"foreach"}),t.jsx("span",{className:"wf-node-badge",children:n}),t.jsx("span",{className:"wf-node-badge",children:s})]}),i&&t.jsx("div",{className:"wf-foreach-empty","data-testid":"wf-foreach-empty",children:e.emptyHint||"Drag a step-execute node here"}),e.errorBadge&&t.jsx(_f,{message:e.errorBadge}),t.jsx(Uo,{type:"source",position:Ho.Right})]})}function wB({data:e}){const n=e.config?.maxIterations,s=e.config?.timeoutMs,i=e.templateEmpty===!0;return t.jsxs("div",{className:`wf-foreach-group wf-loop-group${e.errorBadge?" wf-node--error":""}`,"data-testid":"wf-node-loop",children:[t.jsx(Uo,{type:"target",position:Ho.Left}),t.jsxs("div",{className:"wf-foreach-header",children:[t.jsx("span",{className:"wf-node-icon",children:t.jsx(Fd,{size:14,"aria-hidden":!0})}),t.jsx("span",{className:"wf-node-label",children:e.label||"loop"}),t.jsxs("span",{className:"wf-node-badge",children:[n??3,"x"]}),s!=null&&t.jsxs("span",{className:"wf-node-badge",children:[s,"ms"]})]}),i&&t.jsx("div",{className:"wf-foreach-empty","data-testid":"wf-loop-empty",children:e.emptyHint||"Drag loop steps here"}),e.errorBadge&&t.jsx(_f,{message:e.errorBadge}),t.jsx(Uo,{type:"source",position:Ho.Right})]})}const jB={start:({data:e})=>t.jsx(Hi,{data:e,kind:"start"}),end:({data:e})=>t.jsx(Hi,{data:e,kind:"end"}),prompt:({data:e})=>t.jsx(Hi,{data:e,kind:"prompt"}),script:({data:e})=>t.jsx(Hi,{data:e,kind:"script"}),gate:({data:e})=>t.jsx(Hi,{data:e,kind:"gate"}),merge:({data:e})=>t.jsx(Hi,{data:e,kind:"merge"}),hold:({data:e})=>t.jsx(Hi,{data:e,kind:"hold"}),split:({data:e})=>t.jsx(Hi,{data:e,kind:"split"}),join:({data:e})=>t.jsx(Hi,{data:e,kind:"join"}),foreach:({data:e})=>t.jsx(kB,{data:e}),loop:({data:e})=>t.jsx(wB,{data:e}),"step-review":({data:e})=>t.jsx(Hi,{data:e,kind:"step-review"}),"parse-steps":({data:e})=>t.jsx(Hi,{data:e,kind:"parse-steps"}),code:({data:e})=>t.jsx(Hi,{data:e,kind:"code"}),notify:({data:e})=>t.jsx(Hi,{data:e,kind:"notify"})},Fm={p:({children:e,...n})=>t.jsx("p",{...n,children:hi(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:hi(e)}),code:({children:e,...n})=>t.jsx("code",{...n,children:hi(e)}),pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:hi(e)}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function NB(e){if(!e)return"Reply in the comments and unpause the task to continue.";const n=/^workflow-input:[^:]+:\s*(.*)$/s.exec(e);return n?n[1].trim()||"Reply in the comments and unpause the task to continue.":e}function SB(e){if(!e)return"";const n=/^workflow-cli-approval:[^:]+:\s*(.*)$/s.exec(e);return n?n[1].trim():e}function CB(e,n){switch(e){case"passed":return n("workflow.statusPassed","Passed");case"failed":return n("workflow.statusFailed","Failed");case"advisory_failure":return n("workflow.statusAdvisory","Advisory failure");case"skipped":return n("workflow.statusSkipped","Skipped");case"pending":return n("workflow.statusRunning","Running…");default:return e}}function _B(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),d=o%60;return`${l}m ${d}s`}function EB(e){return e?new Date(e).toLocaleString():null}function MB(e){const n=e.split(`
|
|
769
|
-
`);return n.length<=1?e:`${n.length} lines`}function id(e,n,s,i){const r=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${r}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?i("workflow.postMerge","Post-merge"):i("workflow.preMerge","Pre-merge")})}function AB(e,n,s){return e?n.find(r=>r.id===e)?.name||s("workflow.customWorkflowFallback","Custom workflow"):s("workflow.defaultWorkflow","Default")}function TB(e,n){return e.some(s=>s.status==="failed")?{label:n("workflow.statusFailed","Failed"),badgeClass:"workflow-result-badge--failed",testId:"failed"}:e.some(s=>s.status==="advisory_failure")?{label:n("workflow.statusAdvisory","Advisory"),badgeClass:"workflow-result-badge--advisory_failure",testId:"advisory"}:e.some(s=>s.status==="pending")?{label:n("workflow.aggregateInProgress","In progress"),badgeClass:"workflow-result-badge--pending",testId:"pending"}:e.length===0?{label:n("workflow.aggregateNoResults","No results"),badgeClass:"workflow-result-badge--skipped",testId:"no-results"}:{label:n("workflow.aggregateAllPassed","All passed"),badgeClass:"workflow-result-badge--passed",testId:"passed"}}function RB(e,n,s,i,r){if(n==="awaiting-user-input")return{label:r("workflow.executionAwaitingInput","Awaiting input"),badgeClass:"workflow-result-badge--pending",testId:"awaiting-input"};if(n==="awaiting-cli-approval")return{label:r("workflow.executionAwaitingCliApproval","Awaiting CLI approval"),badgeClass:"workflow-result-badge--pending",testId:"awaiting-cli-approval"};if(n==="paused"||s)return{label:r("workflow.executionPaused","Paused"),badgeClass:"workflow-result-badge--pending",testId:"paused"};const o=i.find(d=>d.status==="pending");if(o){const d=(o.phase||"pre-merge")==="post-merge";return{label:d?r("workflow.executionPostMerge","Post-merge steps running"):r("workflow.executionPreMerge","Pre-merge steps running"),badgeClass:"workflow-result-badge--pending",testId:d?"post-merge":"pre-merge"}}return i.length>0&&i.every(d=>["passed","failed","advisory_failure","skipped"].includes(d.status))||n==="done"||e?.column==="done"||e?.column==="in-review"?{label:r("workflow.executionCompleted","Completed"),badgeClass:"workflow-result-badge--passed",testId:"completed"}:{label:r("workflow.executionNotStarted","Not started"),badgeClass:"workflow-result-badge--pending",testId:"not-started"}}function Om(e){return!e?.provider||!e.modelId?"Default":`${e.provider}/${e.modelId}`}function PB({entries:e,startedAt:n,stepId:s,t:i}){const r=a.useRef(null),o=new Date(n).getTime(),l=e.filter(d=>new Date(d.timestamp).getTime()>=o);return a.useEffect(()=>{const d=r.current;d&&(d.scrollTop=d.scrollHeight)},[l.length]),l.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:i("workflow.waitingForOutput","Waiting for agent output…")})}):t.jsx("div",{ref:r,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:l.map((d,c)=>d.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",Hs(d.text),d.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Hs(d.detail)]})]},c):d.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",Hs(d.text),d.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Hs(d.detail)]})]},c):d.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",Hs(d.text),d.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Hs(d.detail)]})]},c):d.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:Hs(d.text)},c):t.jsx("span",{className:"workflow-live-log-text",children:Hs(d.text)},c))})}function IB({taskId:e,task:n,results:s,loading:i,enabledWorkflowSteps:r,canEdit:o,projectId:l,isTaskInProgress:d,onWorkflowStepsChange:c,taskStatus:m,taskPausedReason:p,settings:h,onEditWorkflow:u,onWorkflowReconciled:f}){const{t:b}=st("app"),[y,v]=a.useState({}),[x,k]=a.useState({}),[w,g]=a.useState(""),[j,S]=a.useState(!1),[C,E]=a.useState(!1),[F,M]=a.useState(null),[D,_]=a.useState([]),[V,N]=a.useState([]),[$,R]=a.useState(!1),[L,O]=a.useState(null),[J,A]=a.useState(null),[de,B]=a.useState(!1),[P,Z]=a.useState({}),[T,ie]=a.useState(!1),[le,be]=a.useState(!1);a.useEffect(()=>{g(""),S(!1),E(!1),A(null)},[e,m,p]),a.useEffect(()=>{let Me=!1;return RA(e,l).then(Ae=>{Me||O(Ae.workflowId)}).catch(()=>{}),()=>{Me=!0}},[e,l]);const Le=a.useCallback(async Me=>{const Ae=await PA(e,Me,l);O(Ae.workflowId),c?.(Ae.enabledWorkflowSteps),Ae.reconciliation&&!Ae.reconciliation.preserved&&f?.()},[e,l,c,f]);a.useEffect(()=>{let Me=!1;return Bp(l).then(Ae=>{Me||N(Ae)}).catch(()=>{Me||N([])}),()=>{Me=!0}},[l]),a.useEffect(()=>{if(!de||!L||P[L])return;let Me=!1;return ie(!0),Zk(L,l).then(Ae=>{Me||Z(ee=>({...ee,[L]:Ae}))}).catch(()=>{}).finally(()=>{Me||ie(!1)}),()=>{Me=!0}},[de,L,l,P]);const xe=s.some(Me=>Me.status==="pending"),{entries:q}=Wj(e,!!d&&xe,l);a.useEffect(()=>{let Me=!1;return zp(l).then(Ae=>{Me||_(Ae.filter(ee=>ee.enabled))}).catch(()=>{Me||_([])}),()=>{Me=!0}},[l]);const ce=r??[],De=a.useMemo(()=>D.map(Me=>({id:Me.id,name:Me.name,description:Me.description,phase:Me.phase||"pre-merge"})),[D]),He=a.useMemo(()=>new Map(De.map(Me=>[Me.id,Me])),[De]),qe=Me=>{v(Ae=>({...Ae,[Me]:!Ae[Me]}))},pe=Me=>{k(Ae=>{const ee=Ae[Me]??"markdown";return{...Ae,[Me]:ee==="markdown"?"plain":"markdown"}})},te=Me=>{M(Me)},me=()=>{M(null)};a.useEffect(()=>{if(!F)return;const Me=Ae=>{Ae.key==="Escape"&&me()};return document.addEventListener("keydown",Me),()=>{document.removeEventListener("keydown",Me)}},[F]);const se=a.useCallback((Me,Ae)=>{if(c){if(Ae){if(ce.includes(Me)){c(ce);return}c([...ce,Me]);return}c(ce.filter(ee=>ee!==Me))}},[c,ce]),z=a.useCallback(Me=>{if(!c||Me<=0)return;const Ae=[...ce];[Ae[Me-1],Ae[Me]]=[Ae[Me],Ae[Me-1]],c(Ae)},[c,ce]),Y=a.useCallback(Me=>{if(!c||Me>=ce.length-1)return;const Ae=[...ce];[Ae[Me],Ae[Me+1]]=[Ae[Me+1],Ae[Me]],c(Ae)},[c,ce]),he=a.useCallback(Me=>{c&&c(ce.filter(Ae=>Ae!==Me))},[c,ce]),X=s.length>0,ye=ce.length>0;a.useEffect(()=>{o||R(!1)},[o]);const ot=a.useMemo(()=>ce.map(Me=>{const Ae=He.get(Me);return{id:Me,name:Ae?.name||Me,description:Ae?.description||b("workflow.stepDefinitionNotFound","Step definition not found."),phase:Ae?.phase||"pre-merge"}}),[ce,He,b]),ue=a.useMemo(()=>AB(L,V,b),[L,V,b]),je=a.useMemo(()=>RB(n,m,p,s,b),[n,m,p,s,b]),$e=a.useMemo(()=>TB(s,b),[s,b]),Ce=a.useMemo(()=>s.filter(Me=>["passed","skipped","failed","advisory_failure"].includes(Me.status)).length,[s]),We=L?P[L]:void 0,ke=a.useMemo(()=>We?nB(We):null,[We]),Ee=a.useMemo(()=>n?Ap(n,h):void 0,[n,h]),Ze=a.useMemo(()=>n?Tp(n,h):void 0,[n,h]),Ke=a.useMemo(()=>n?Rp(n,h):void 0,[n,h]),dt=()=>!o||!$||i?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:b("workflow.selectStepsDescription","Select steps to run after task implementation completes")}),t.jsx("div",{className:"workflow-steps-list",children:De.map(Me=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${Me.id}`,children:[t.jsx("input",{type:"checkbox",checked:ce.includes(Me.id),onChange:Ae=>se(Me.id,Ae.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[Me.name,id(Me.phase,Me.id,"workflow-step-phase",b)]}),t.jsx("div",{className:"workflow-step-description",children:Me.description})]})]},Me.id))})]}),ce.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:b("workflow.executionOrder","Execution order:")}),ce.map((Me,Ae)=>{const ee=He.get(Me);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${Me}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Ae+1}),t.jsx("span",{className:"workflow-step-order-name",children:ee?.name||Me}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>z(Ae),disabled:Ae===0,"data-testid":`workflow-step-move-up-${Me}`,title:b("workflow.moveUp","Move up"),children:t.jsx(ra,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Y(Ae),disabled:Ae===ce.length-1,"data-testid":`workflow-step-move-down-${Me}`,title:b("workflow.moveDown","Move down"),children:t.jsx(Ln,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>he(Me),"data-testid":`workflow-step-remove-${Me}`,title:b("workflow.remove","Remove"),children:t.jsx(Fn,{})})]})]},Me)})]})]}),Fe=()=>{if(i)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:b("workflow.loadingResults","Loading workflow results…")})]});if(!X)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:b("workflow.noStepsConfigured","No workflow steps configured for this task.")}),t.jsx("p",{className:"workflow-results-empty-hint",children:b("workflow.stepsExplanation","Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds.")})]});const Me=s.filter(re=>re.status==="passed").length,Ae=s.filter(re=>re.status==="failed").length,ee=s.filter(re=>re.status==="advisory_failure"),Ie=s.filter(re=>re.status==="skipped").length,Pe=s.filter(re=>re.status==="pending").length,oe=[b("workflow.summaryStepCount",{count:s.length,defaultValue_one:"{{count}} step",defaultValue_other:"{{count}} steps"})];return Me>0&&oe.push(b("workflow.summaryPassed","{{count}} passed",{count:Me})),Ae>0&&oe.push(b("workflow.summaryFailed","{{count}} failed",{count:Ae})),ee.length>0&&oe.push(b("workflow.summaryAdvisory","{{count}} advisory",{count:ee.length})),Ie>0&&oe.push(b("workflow.summarySkipped","{{count}} skipped",{count:Ie})),Pe>0&&oe.push(b("workflow.summaryRunning","{{count}} running",{count:Pe})),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:oe.join(b("workflow.summarySeparator"," · "))}),ee.length>0&&t.jsxs("div",{className:"workflow-polish-notes","data-testid":"workflow-polish-notes",children:[t.jsx("h4",{children:b("workflow.polishNotes","Polish notes")}),t.jsx("p",{children:b("workflow.advisoryExplanation","Advisory workflow steps flagged non-blocking improvements:")}),t.jsx("ul",{children:ee.map((re,_e)=>t.jsxs("li",{children:[t.jsxs("strong",{children:[re.workflowStepName,":"]})," ",re.output||b("workflow.needsReview","Needs follow-up review.")]},`advisory-${re.workflowStepId}-${_e}`))})]}),s.map((re,_e)=>{const fe=re.phase||"pre-merge",Xe=y[re.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${re.status}`,"data-testid":`workflow-result-item-${re.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[re.workflowStepName,id(fe,re.workflowStepId,"workflow-result-phase",b)]}),t.jsxs("div",{className:"workflow-result-badges",children:[re.verdict&&t.jsx("span",{className:`workflow-verdict-badge workflow-verdict-badge--${re.verdict}`,"data-testid":`workflow-verdict-badge-${re.workflowStepId}`,children:re.verdict}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${re.status}`,"data-testid":`workflow-result-badge-${re.workflowStepId}`,children:CB(re.status,b)})]})]}),re.notes&&re.status!=="pending"&&t.jsxs("div",{className:"workflow-result-notes","data-testid":`workflow-result-notes-${re.workflowStepId}`,children:[t.jsxs("span",{className:"workflow-result-notes-label",children:[b("workflow.notes","Notes:")," "]}),t.jsx(Di,{remarkPlugins:[Li],components:Fm,children:re.notes})]}),t.jsxs("div",{className:"workflow-result-meta",children:[re.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:[b("workflow.started","Started:")," ",EB(re.startedAt)]}),re.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:_B(re.startedAt,re.completedAt)})]}),re.status==="pending"&&re.startedAt?t.jsx(PB,{entries:q,startedAt:re.startedAt,stepId:re.workflowStepId,t:b}):re.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsxs("span",{className:"workflow-result-output-label",children:[b("workflow.output","Output:")," "]}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>qe(re.workflowStepId),"data-testid":`workflow-result-toggle-${re.workflowStepId}`,children:Xe?b("workflow.hideOutput","Hide output"):b("workflow.showOutput","Show output")}),!Xe&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${re.workflowStepId}`,children:MB(re.output)}),Xe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>pe(re.workflowStepId),"data-testid":`workflow-result-mode-toggle-${re.workflowStepId}`,title:(x[re.workflowStepId]??"markdown")==="markdown"?b("workflow.switchToPlain","Switch to plain text"):b("workflow.switchToMarkdown","Switch to markdown"),children:(x[re.workflowStepId]??"markdown")==="markdown"?b("workflow.markdown","Markdown"):b("workflow.plain","Plain")}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>te(re.workflowStepId),"data-testid":`workflow-result-expand-${re.workflowStepId}`,title:b("workflow.expandOutput","Expand output"),children:t.jsx(gu,{size:12})})]})]}),Xe&&t.jsx("div",{className:`workflow-result-output${(x[re.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${re.workflowStepId}`,children:(x[re.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Di,{remarkPlugins:[Li],components:Fm,children:re.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Hs(re.output??"")})})]}):null]},`${re.workflowStepId}-${_e}`)})]})},nt=o?t.jsx("button",{type:"button",className:"btn btn-sm workflow-results-edit-toggle",onClick:()=>R(Me=>!Me),"data-testid":"workflow-steps-edit-toggle","aria-label":$?b("workflow.doneEditingAriaLabel","Done editing workflow steps"):b("workflow.editAriaLabel","Edit workflow steps"),title:$?b("workflow.done","Done"):b("workflow.edit","Edit"),children:$?t.jsxs(t.Fragment,{children:[t.jsx(Qs,{size:14}),b("workflow.done","Done")]}):t.jsxs(t.Fragment,{children:[t.jsx(Si,{size:14}),b("workflow.edit","Edit")]})}):null,Nt=!i&&!X&&ye,Ft=o&&X,ze=m==="awaiting-user-input",it=m==="awaiting-cli-approval",Mt=async()=>{if(!(!w.trim()||j)){S(!0),A(null);try{await DA(e,w,l),g(""),E(!0)}catch(Me){A(Re(Me)||"Failed to resume task")}finally{S(!1)}}},Ht=async()=>{if(!j){S(!0),A(null);try{await IA(e,l),E(!0)}catch(Me){A(Re(Me)||"Failed to approve command")}finally{S(!1)}}};return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[ze&&t.jsxs("div",{className:"workflow-input-banner",role:"alert",children:[t.jsx("strong",{children:"Waiting for your input"}),t.jsx("span",{children:NB(p)}),C?t.jsx("span",{className:"workflow-input-resuming",children:"Resuming…"}):t.jsxs("div",{className:"workflow-input-actions",children:[t.jsx("textarea",{className:"workflow-input-textarea",rows:3,placeholder:"Type your reply…",value:w,onChange:Me=>g(Me.target.value),disabled:j}),t.jsx("button",{type:"button",className:"workflow-input-submit",onClick:Mt,disabled:j||!w.trim(),children:j?"Submitting…":"Submit & resume"}),J&&t.jsx("span",{className:"workflow-input-error",role:"alert",children:J})]})]}),it&&t.jsxs("div",{className:"workflow-input-banner workflow-input-banner--approval",role:"alert",children:[t.jsx("strong",{children:"Approve CLI command?"}),t.jsx("span",{className:"workflow-input-approval-warning",children:"This command will run in the task worktree. Approving trusts this exact command for future runs."}),t.jsx("pre",{className:"workflow-input-approval-command",children:t.jsx("code",{children:SB(p)})}),C?t.jsx("span",{className:"workflow-input-resuming",children:"Resuming…"}):t.jsxs("div",{className:"workflow-input-actions",children:[t.jsx("button",{type:"button",className:"workflow-input-submit",onClick:Ht,disabled:j,children:j?"Approving…":"Approve & run"}),t.jsx("span",{className:"workflow-input-keep-paused",children:"To reject, keep the task paused and do not approve."}),J&&t.jsx("span",{className:"workflow-input-error",role:"alert",children:J})]})]}),t.jsxs("section",{className:"card workflow-state-summary","data-testid":"workflow-state-summary",children:[t.jsx("div",{className:"workflow-state-summary__header",children:t.jsx("h4",{children:b("workflow.overview","Workflow overview")})}),t.jsxs("div",{className:"workflow-state-summary__grid",children:[t.jsxs("div",{className:"workflow-state-summary__item","data-testid":"workflow-state-summary-name",children:[t.jsx("span",{className:"workflow-state-summary__label",children:b("workflow.workflowName","Workflow")}),t.jsx("span",{className:"workflow-state-summary__value",children:ue})]}),t.jsxs("div",{className:"workflow-state-summary__item","data-testid":"workflow-state-summary-phase",children:[t.jsx("span",{className:"workflow-state-summary__label",children:b("workflow.executionPhase","Execution phase")}),t.jsx("span",{className:`workflow-result-badge ${je.badgeClass}`,"data-testid":`workflow-phase-badge-${je.testId}`,children:je.label})]}),t.jsxs("div",{className:"workflow-state-summary__item","data-testid":"workflow-state-summary-aggregate",children:[t.jsx("span",{className:"workflow-state-summary__label",children:b("workflow.aggregateResult","Aggregate result")}),t.jsx("span",{className:`workflow-result-badge ${$e.badgeClass}`,"data-testid":`workflow-aggregate-badge-${$e.testId}`,children:$e.label})]}),t.jsxs("div",{className:"workflow-state-summary__item","data-testid":"workflow-state-summary-count",children:[t.jsx("span",{className:"workflow-state-summary__label",children:b("workflow.stepProgress","Step count")}),t.jsx("span",{className:"workflow-state-summary__value",children:b("workflow.stepProgressValue","{{completed}} of {{total}} steps completed",{completed:Ce,total:s.length})})]})]})]}),t.jsxs("section",{className:"card workflow-disclosure","data-testid":"workflow-graph-section",children:[t.jsx("button",{type:"button",className:"workflow-disclosure__toggle",onClick:()=>B(Me=>!Me),"data-testid":"workflow-graph-toggle",children:t.jsxs("span",{className:"workflow-disclosure__title",children:[de?t.jsx(Ln,{"aria-hidden":!0}):t.jsx(ls,{"aria-hidden":!0}),b("workflow.graph","Workflow graph")]})}),de&&t.jsx("div",{className:"workflow-disclosure__content",children:L?T&&!We?t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-graph-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:b("workflow.loadingGraph","Loading workflow graph…")})]}):ke?t.jsx("div",{className:"workflow-graph-preview","data-testid":"workflow-graph-preview",children:t.jsx(qS,{children:t.jsx(WS,{nodes:ke.nodes,edges:ke.edges,nodeTypes:jB,fitView:!0,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,zoomOnScroll:!1,panOnDrag:!1,preventScrolling:!1,attributionPosition:"bottom-left"})})}):t.jsx("p",{className:"workflow-disclosure__empty","data-testid":"workflow-graph-unavailable",children:b("workflow.graphUnavailable","Workflow graph unavailable")}):t.jsx("p",{className:"workflow-disclosure__empty","data-testid":"workflow-graph-empty",children:b("workflow.noWorkflowAssigned","No workflow assigned")})})]}),t.jsxs("section",{className:"card workflow-management","data-testid":"workflow-management-section",children:[t.jsxs("div",{className:"workflow-management__header",children:[t.jsx("h4",{children:b("workflow.workflowName","Workflow")}),o&&L&&u&&t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:u,"data-testid":"workflow-edit-button",children:[t.jsx(Si,{"aria-hidden":!0}),b("workflow.editWorkflow","Edit workflow")]})]}),t.jsx(aN,{value:L,onChange:Le,projectId:l,label:"Custom workflow",disabled:!o})]}),t.jsxs("section",{className:"card workflow-disclosure","data-testid":"workflow-model-settings-section",children:[t.jsx("button",{type:"button",className:"workflow-disclosure__toggle",onClick:()=>be(Me=>!Me),"data-testid":"workflow-model-settings-toggle",children:t.jsxs("span",{className:"workflow-disclosure__title",children:[le?t.jsx(Ln,{"aria-hidden":!0}):t.jsx(ls,{"aria-hidden":!0}),b("workflow.modelSettings","Model settings")]})}),le&&t.jsx("div",{className:"workflow-disclosure__content workflow-state-summary__grid","data-testid":"workflow-model-settings-content",children:[{key:"executor",label:b("models.targetLabels.executor","Executor"),value:Om(Ee),provider:Ee?.provider},{key:"reviewer",label:b("models.targetLabels.validator","Reviewer"),value:Om(Ze),provider:Ze?.provider},{key:"planning",label:b("models.targetLabels.planning","Planning"),value:Om(Ke),provider:Ke?.provider},{key:"thinking",label:b("workflow.thinkingLevel","Thinking level"),value:n?.thinkingLevel||"Default"}].map(Me=>t.jsxs("div",{className:"workflow-state-summary__item","data-testid":`workflow-model-setting-${Me.key}`,children:[t.jsx("span",{className:"workflow-state-summary__label",children:Me.label}),t.jsxs("span",{className:"workflow-state-summary__value workflow-model-value",children:[Me.provider?t.jsx(hs,{provider:Me.provider,size:"sm"}):null,Me.value]})]},Me.key))})]}),Nt?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:b("workflow.configuredSteps","Configured Workflow Steps")}),t.jsx("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:b("workflow.stepCount",{count:ot.length,defaultValue_one:"{{count}} step",defaultValue_other:"{{count}} steps"})})]}),nt]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:ot.map(Me=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${Me.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[t.jsx("span",{className:"workflow-configured-name-text",children:Me.name}),id(Me.phase,Me.id,"workflow-configured-phase",b)]}),t.jsx("p",{className:"workflow-configured-description",children:Me.description})]},Me.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:b("workflow.stepsExplanation","Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds.")}),dt()]}):t.jsxs(t.Fragment,{children:[Ft&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:b("workflow.steps","Workflow Steps")}),nt]}),Fe(),dt()]}),F&&(()=>{const Me=s.find(Ie=>Ie.workflowStepId===F);if(!Me)return null;const Ae=x[Me.workflowStepId]??"markdown",ee=Me.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:Ie=>{Ie.target===Ie.currentTarget&&me()},"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:Me.workflowStepName}),id(ee,Me.workflowStepId,"workflow-output-modal-phase",b)]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>pe(Me.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:Ae==="markdown"?b("workflow.switchToPlain","Switch to plain text"):b("workflow.switchToMarkdown","Switch to markdown"),children:Ae==="markdown"?b("workflow.markdown","Markdown"):b("workflow.plain","Plain")}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:me,"data-testid":"workflow-output-modal-close","aria-label":b("actions.close","Close"),children:t.jsx(Fn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${Ae==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:Ae==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Di,{remarkPlugins:[Li],components:Fm,children:Me.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Hs(Me.output??"")})})})]})})})()]})}function DB(e,n){return e==="block"?n("routing.policyLabel.block","Block execution"):e==="fallback-local"?n("routing.policyLabel.fallback","Fall back to local"):n("routing.policyLabel.notConfigured","Not configured")}const LB=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function FB(e){return e!==void 0&&e!=="online"}function OB({task:e,settings:n,addToast:s,onTaskUpdated:i}){const{t:r}=st("app"),[o,l]=a.useState([]),[d,c]=a.useState(!1),[m,p]=a.useState(null),[h,u]=a.useState(e.nodeId??""),[f,b]=a.useState(!1),y=a.useRef(e.id);a.useEffect(()=>{y.current=e.id,u(e.nodeId??""),b(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),p(null),Vd().then(D=>{l(D)}).catch(D=>{p(Re(D)||r("routing.errorLoadingNodes","Failed to load nodes"))}).finally(()=>{c(!1)})},[]);const v=a.useMemo(()=>new Map(o.map(D=>[D.id,D])),[o]),x=a.useMemo(()=>[...o].sort((D,_)=>D.name.localeCompare(_.name)),[o]),k=n,w=e.nodeId??k?.defaultNodeId??null,g=e.nodeId?r("routing.source.override","Per-task override"):k?.defaultNodeId?r("routing.source.projectDefault","Project default"):r("routing.source.noRouting","No routing"),j=w?v.get(w):void 0,S=j?`${j.name} (${j.type})`:w?`${w} (${r("routing.nodeUnavailable","node unavailable or unknown")})`:r("routing.localNoConfiguration","Local (no routing configured)"),C=e.column==="in-progress"||LB.has(e.status),E=C||f||d,F=a.useCallback(async D=>{if(D===h)return;const _=e.id,V=h;u(D),b(!0);try{const N=await si(_,{nodeId:D||null});if(y.current!==_)return;u(N.nodeId??""),i?.(N),s(D?r("routing.overrideUpdated","Node override updated"):r("routing.overrideCleared","Node override cleared"),"success")}catch(N){if(y.current!==_)return;u(V),s(Re(N)||r("routing.errorUpdatingOverride","Failed to update node override"),"error")}finally{y.current===_&&b(!1)}},[s,i,h,e.id]),M=a.useCallback(()=>{F("")},[F]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:r("routing.title","Task Routing")}),t.jsx("p",{className:"routing-tab__intro",children:r("routing.intro","View the effective execution node and control per-task node override.")}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:r("routing.summarySection","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:r("routing.effectiveNode","Effective node")}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(Wr,{status:j.status,compact:!0}):null,S,FB(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:r("routing.unhealthy","Unhealthy")}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:r("routing.source","Routing source")}),t.jsx("span",{className:"routing-summary-value",children:g})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:r("routing.unavailablePolicy","Unavailable-node policy")}),t.jsx("span",{className:"routing-summary-value",children:DB(k?.unavailableNodePolicy,r)})]})]}),C&&w?t.jsx("div",{className:"routing-tab__info-banner",children:r("routing.lockedWhileActive","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:r("routing.overrideSection","Node Override")}),C?t.jsx("div",{className:"routing-tab__warning-banner",children:r("routing.cannotChangeWhileActive","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:r("routing.selectLabel","Select execution node")}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:h,disabled:E,onChange:D=>{F(D.target.value)},children:[t.jsx("option",{value:"",children:r("routing.useProjectDefault","Use project default")}),x.map(D=>t.jsxs("option",{value:D.id,title:`Status: ${D.status}`,children:[D.name," (",D.type,") — ",D.status]},D.id))]}),m?t.jsx("div",{className:"routing-tab__error",children:m}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:[r("routing.overrideSetTo","Override set to"),": ",v.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:C||f,onClick:M,children:r("routing.clearOverride","Clear override")})]}):null]})]})}const $B=/^[a-zA-Z0-9_-]{1,64}$/,zB=200;function ix(e){return e?new Date(e).toLocaleString():""}function BB(e,n=zB){return e.length<=n?e:e.substring(0,n)+"…"}function UB({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const{t:o}=st("app"),[l,d]=a.useState([]),[c,m]=a.useState(!0),[p,h]=a.useState(null),[u,f]=a.useState(""),[b,y]=a.useState(null),[v,x]=a.useState(""),[k,w]=a.useState(null),[g,j]=a.useState([]),[S,C]=a.useState(!1),[E,F]=a.useState(!1),[M,D]=a.useState(""),[_,V]=a.useState(""),[N,$]=a.useState(!1),[R,L]=a.useState(null),[O,J]=a.useState(null),[A,de]=a.useState(!1),B=a.useCallback(async()=>{try{const q=await OE(e,i);d(q)}catch(q){n(Re(q)||o("taskDocuments.failedToLoad","Failed to load documents"),"error")}finally{m(!1)}},[e,i,n]);a.useEffect(()=>{B()},[B]);async function P(q){p===q.key?(h(null),f(""),y(null),x(""),w(null),j([]),de(!1)):(h(q.key),f(q.content),y(null),x(""),w(null),j([]),de(!1))}async function Z(q){if(k===q)w(null),j([]);else{w(q),C(!0);try{const ce=await $E(e,q,i);j(ce)}catch(ce){n(Re(ce)||o("taskDocuments.failedToLoadRevisions","Failed to load revisions"),"error")}finally{C(!1)}}}function T(){p&&(y(p),x(u))}function ie(){y(null),x("")}async function le(){if(!(!b||!v.trim())){$(!0);try{await Ng(e,b,v,{},i),y(null),x(""),await B();const q=l.find(ce=>ce.key===b);q&&f(q.content),n(o("taskDocuments.saved","Document saved"),"success")}catch(q){n(Re(q)||o("taskDocuments.failedToSave","Failed to save document"),"error")}finally{$(!1)}}}async function be(){const q=M.trim(),ce=_.trim();if(!q){n(o("taskDocuments.keyRequired","Document key is required"),"error");return}if(!$B.test(q)){n(o("taskDocuments.invalidKeyFormat","Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores."),"error");return}if(!ce){n(o("taskDocuments.contentRequired","Content is required"),"error");return}$(!0);try{await Ng(e,q,ce,{},i),F(!1),D(""),V(""),await B(),n(o("taskDocuments.created","Document created"),"success")}catch(De){n(Re(De)||o("taskDocuments.failedToCreate","Failed to create document"),"error")}finally{$(!1)}}async function Le(q){L(q);try{await zE(e,q,i),J(null),L(null),p===q&&(h(null),f("")),k===q&&(w(null),j([])),await B(),n(o("taskDocuments.deleted","Document deleted"),"success")}catch(ce){n(Re(ce)||o("taskDocuments.failedToDelete","Failed to delete document"),"error")}finally{L(null)}}function xe(q){f(q.content),y(null),x("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:o("taskDocuments.heading","Documents")}),t.jsx("div",{className:"detail-log-empty",children:o("taskDocuments.loading","Loading documents…")})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:o("taskDocuments.heading","Documents")}),E&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:o("taskDocuments.newDocumentTitle","New Document")}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:o("taskDocuments.keyLabel","Key")}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:M,onChange:q=>D(q.target.value),placeholder:o("taskDocuments.keyPlaceholder","e.g., plan, notes, research"),disabled:N}),t.jsx("span",{className:"form-hint",children:o("taskDocuments.keyHint","Alphanumeric, hyphens, underscores (1-64 chars)")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:o("taskDocuments.contentLabel","Content")}),t.jsx("textarea",{id:"doc-content",value:_,onChange:q=>V(q.target.value),rows:6,placeholder:o("taskDocuments.contentPlaceholder","Enter document content…"),disabled:N})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{F(!1),D(""),V("")},disabled:N,children:o("taskDocuments.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void be(),disabled:N||!M.trim()||!_.trim(),children:N?o("taskDocuments.creating","Creating…"):o("taskDocuments.create","Create")})]})]}),l.length===0&&!E?t.jsx("div",{className:"detail-log-empty",children:o("taskDocuments.noDocuments","No documents yet.")}):t.jsx("div",{className:"task-documents-list",children:l.map(q=>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(Hr,{size:14}),t.jsx("span",{className:"task-document-key",children:q.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",q.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:q.author}),t.jsx("span",{className:"task-document-timestamp",children:ix(q.updatedAt||q.createdAt)})]})]}),p===q.key&&b!==q.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:()=>de(ce=>!ce),"aria-label":A?o("taskDocuments.switchToPlainText","Switch to plain text"):o("taskDocuments.switchToMarkdown","Switch to markdown"),"aria-pressed":A,title:A?o("taskDocuments.switchToPlainText","Switch to plain text"):o("taskDocuments.switchToMarkdown","Switch to markdown"),children:A?o("taskDocuments.modeMarkdown","Markdown"):o("taskDocuments.modePlain","Plain")})}),t.jsx("div",{className:"task-document-content",children:A?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(Di,{remarkPlugins:[Li],children:u})})}):t.jsx("pre",{className:"task-document-content-text",children:u})}),k===q.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:o("taskDocuments.revisionHistory","Revision History")}),S?t.jsx("div",{className:"detail-log-empty",children:o("taskDocuments.loadingRevisions","Loading…")}):g.length<=1?t.jsx("div",{className:"detail-log-empty",children:o("taskDocuments.noPreviousRevisions","No previous revisions.")}):t.jsx("div",{className:"task-document-revision-list",children:g.filter(ce=>ce.revision<q.revision).sort((ce,De)=>De.revision-ce.revision).map(ce=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>xe(ce),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ce.revision]}),t.jsx("span",{className:"revision-author",children:ce.author}),t.jsx("span",{className:"revision-timestamp",children:ix(ce.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:BB(ce.content,100)})]},ce.id))})]})]}),b===q.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:v,onChange:ce=>x(ce.target.value),rows:10,disabled:N}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ie,disabled:N,children:o("taskDocuments.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void le(),disabled:N||!v.trim(),children:N?o("taskDocuments.saving","Saving…"):o("taskDocuments.save","Save")})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void P(q),children:p===q.key?t.jsxs(t.Fragment,{children:[t.jsx(ra,{size:14})," ",o("taskDocuments.collapse","Collapse")]}):t.jsxs(t.Fragment,{children:[t.jsx(Ln,{size:14})," ",o("taskDocuments.expand","Expand")]})}),p===q.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void Z(q.key),children:[t.jsx(Ur,{size:14})," ",o("taskDocuments.history","History")]}),r&&b!==q.key&&t.jsx("button",{className:"btn btn-sm",onClick:T,children:o("taskDocuments.edit","Edit")}),r&&(O===q.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:o("taskDocuments.deleteConfirm","Delete?")}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void Le(q.key),disabled:R===q.key,children:R===q.key?"…":o("taskDocuments.yes","Yes")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>J(null),disabled:R===q.key,children:o("taskDocuments.no","No")})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>J(q.key),children:t.jsx(as,{size:14})}))]})]})]},q.key))}),r&&!E&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>F(!0),children:[t.jsx(ys,{size:14})," ",o("taskDocuments.newDocumentButton","New Document")]})]})}function rr(e){return e.toLocaleString()}function HB(e){return`${(e*100).toFixed(1)}%`}function $m(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function wo(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),i=Math.round(n%60);return`${s}m ${i}s`}function VB(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 d;if(o.completedAt){const c=new Date(o.completedAt).getTime();if(Number.isNaN(c)||c<l)return null;d=c}else d=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:d-l}}).filter(o=>o!==null),i=_w(e,n)??0,r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:i,longestStep:r}}function qB({tokenUsage:e,loading:n,task:s}){const{t:i}=st("app"),r=Date.now(),o=Sw(s?.log??[]),l=o.filter(k=>typeof k.durationMs=="number"),d=l.reduce((k,w)=>k+(w.durationMs??0),0),c=Cw(s?.log)??0,m=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(d,c),p=l.reduce((k,w)=>!k||(w.durationMs??0)>(k.durationMs??0)?w:k,void 0),h=VB(s?.workflowStepResults??[]),u=s?Mw(s,r):null,f=Ew(s?.executionStartedAt,s?.executionCompletedAt,r),b=uI(s?.firstExecutionAt,s?.executionCompletedAt,r),y=u??f??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:m+h.totalDurationMs),v=b!=null&&b!==y,x=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":i("taskDetail.executionStatsAria","Task execution statistics"),children:[t.jsx("h4",{children:i("taskDetail.executionAndTokenStats","Execution & Token Stats")}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:i("taskDetail.executionTiming","Execution Timing")}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":i("taskDetail.executionTimingMetricsAria","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:i("taskDetail.timingEvents","Timing events")}),t.jsx("span",{className:"task-token-stats-panel__value",children:o.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.timedDuration","Timed duration")}),t.jsx("span",{className:"task-token-stats-panel__value",children:wo(m)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.workflowTimedSteps","Workflow timed steps")}),t.jsx("span",{className:"task-token-stats-panel__value",children:h.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.workflowRuntime","Workflow runtime")}),t.jsx("span",{className:"task-token-stats-panel__value",children:wo(h.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.totalExecutionTime","Total execution time")}),t.jsx("span",{className:"task-token-stats-panel__value",children:wo(y)})]}),v?t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.wallClockSinceFirst","Wall-clock since first execution")}),t.jsx("span",{className:"task-token-stats-panel__value",children:wo(b)})]}):null]}),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:i("taskDetail.longestTimingEvent","Longest timing event")}),t.jsx("dd",{children:p?.durationMs?`${p.summary} (${wo(p.durationMs)})`:i("taskDetail.noTimedEvents","No timed events recorded yet.")})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:i("taskDetail.longestWorkflowStep","Longest workflow step")}),t.jsx("dd",{children:h.longestStep?`${h.longestStep.name} (${wo(h.longestStep.durationMs)})`:i("taskDetail.noWorkflowStepTimings","No completed workflow step timings yet.")})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:i("taskDetail.executionDetails","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:i("taskDetail.executionMode","Execution mode")}),t.jsx("dd",{children:s?.executionMode==="fast"?i("taskDetail.executionModeFast","Fast"):i("taskDetail.executionModeStandard","Standard")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.runtimeStatus","Runtime status")}),t.jsx("dd",{children:s?.status??i("taskDetail.notSet","Not set")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.paused","Paused")}),t.jsx("dd",{children:s?.paused?i("taskDetail.yes","Yes"):i("taskDetail.no","No")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.stepProgress","Step progress")}),t.jsx("dd",{children:x>0?`${Math.min((s?.currentStep??0)+1,x)} / ${x}`:i("taskDetail.noSteps","No steps")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.retriesLabel","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:i("taskDetail.recoveryState","Recovery state")}),t.jsx("dd",{children:s?.nextRecoveryAt?i("taskDetail.nextRecoveryAt","Next recovery at {{time}}",{time:$m(s.nextRecoveryAt)}):i("taskDetail.noScheduledRecovery","No scheduled recovery")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.selfHealCounters","Self-heal counters")}),t.jsx("dd",{children:i("taskDetail.selfHealValues","stuck kills: {{stuckKills}}, post-review fixes: {{postReviewFixes}}",{stuckKills:s?.stuckKillCount??0,postReviewFixes:s?.postReviewFixCount??0})})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.runtimeLinks","Runtime links")}),t.jsx("dd",{children:[s?.assignedAgentId?i("taskDetail.agentLink","agent {{id}}",{id:s.assignedAgentId}):null,s?.checkedOutBy?i("taskDetail.checkoutLink","checkout {{id}}",{id:s.checkedOutBy}):null,s?.blockedBy?i("taskDetail.blockedByLink","blocked by {{id}}",{id:s.blockedBy}):null,s?.sessionFile?i("taskDetail.hasSession","has session"):null].filter(Boolean).join(", ")||i("taskDetail.noRuntimeLinks","No runtime links")})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:i("taskDetail.tokenUsage","Token Usage")}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:i("taskDetail.loadingTokenStats","Loading token statistics…")}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":i("taskDetail.tokenTotalsAria","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:i("taskDetail.inputTokens","Input")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.outputTokens","Output")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.cacheRead","Cache read")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.cacheWrite","Cache write")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.cacheWriteTokens??0)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.totalTokens","Total")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.totalTokens)})]})]}),t.jsxs("div",{className:"task-token-stats-panel__cache-ratio",children:[t.jsx("span",{className:"task-token-stats-panel__cache-ratio-label",children:i("taskDetail.cacheHitRatio","Cache hit ratio:")})," ",t.jsx("span",{className:"task-token-stats-panel__cache-ratio-value",children:e.inputTokens+e.cachedTokens>0?HB(e.cachedTokens/(e.inputTokens+e.cachedTokens)):"—"})]}),t.jsx("div",{className:"task-token-stats-panel__cache-breakdown",children:i("taskDetail.cacheBreakdown","(read {{read}} / write {{write}} / input {{input}})",{read:rr(e.cachedTokens),write:rr(e.cacheWriteTokens??0),input:rr(e.inputTokens)})}),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:i("taskDetail.firstUsed","First used")}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:$m(e.firstUsedAt)})})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:i("taskDetail.lastUsed","Last used")}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.lastUsedAt,children:$m(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:i("taskDetail.noTokenUsage","No token usage recorded for this task yet.")})]})]})}function WB({groupId:e,projectId:n}){const{t:s}=st("app"),[i,r]=a.useState(null),[o,l]=a.useState(!0),[d,c]=a.useState(null),[m,p]=a.useState(!1),[h,u]=a.useState(!1),[f,b]=a.useState(!1),y=a.useCallback(async()=>{try{const j=await Vk(e,n);r(j.group),c(null)}catch(j){const S=j instanceof Error?j.message:s("branchGroup.loadError","Failed to load branch group");c(S)}finally{l(!1)}},[e,n,s]);a.useEffect(()=>{l(!0),y()},[y]),a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const j=window.matchMedia("(max-width: 768px)"),S=E=>{b(E)};S(j.matches);const C=E=>{S(E.matches)};return typeof j.addEventListener=="function"?(j.addEventListener("change",C),()=>j.removeEventListener("change",C)):(j.addListener(C),()=>j.removeListener(C))},[]),a.useEffect(()=>{const j=n?`?projectId=${encodeURIComponent(n)}`:"";return li(`/api/events${j}`,{events:{"task:updated":()=>{y()}},onReconnect:()=>{y()}})},[y,n]);const v=a.useMemo(()=>i?s("branchGroup.completionText","{{landed}} of {{total}} members finished",{landed:i.completion.landed,total:i.completion.total}):"",[i,s]),x=a.useCallback(async()=>{p(!0);try{await qk(e,n),await y()}finally{p(!1)}},[e,y,n]),k=a.useCallback(async()=>{u(!0);try{await Wk(e,n),await y()}finally{u(!1)}},[e,y,n]);if(o)return t.jsxs("div",{className:"card branch-group-card",children:[t.jsx(Et,{className:"spin",size:14})," ",s("branchGroup.loading","Loading branch group…")]});if(d||!i)return t.jsx("div",{className:"card branch-group-card branch-group-card-error",children:d??s("branchGroup.unavailable","Branch group unavailable")});const w=i.completion.total>0?i.completion.landed/i.completion.total*100:0,g=i.completion.complete;return t.jsxs("section",{className:"card branch-group-card",children:[t.jsxs("header",{className:"branch-group-card-header",children:[t.jsxs("div",{className:"branch-group-card-title",children:[t.jsx(ui,{size:14}),t.jsx("strong",{children:i.branchName})]}),t.jsxs("div",{className:"branch-group-card-header-meta",children:[t.jsx("span",{className:"badge branch-group-card-badge",children:s("branchGroup.groupLabel","Group {{id}}",{id:i.id})}),t.jsx("button",{type:"button",className:"btn btn-icon",onClick:()=>b(j=>!j),"aria-expanded":!f,"aria-label":f?s("branchGroup.expandLabel","Expand branch group"):s("branchGroup.collapseLabel","Collapse branch group"),children:f?t.jsx(ls,{size:14}):t.jsx(Ln,{size:14})})]})]}),t.jsx("div",{className:"branch-group-card-progress-text",children:v}),t.jsx("div",{className:"branch-group-card-progress",role:"progressbar","aria-valuenow":i.completion.landed,"aria-valuemin":0,"aria-valuemax":i.completion.total,children:t.jsx("span",{className:"branch-group-card-progress-fill",style:{width:`${w}%`}})}),!f&&t.jsx("ul",{className:"branch-group-card-members",children:i.members.map(j=>t.jsxs("li",{className:"branch-group-card-member",children:[t.jsx("span",{className:`status-dot ${j.landed?"status-dot--online":"status-dot--pending"}`}),t.jsxs("span",{className:"branch-group-card-member-title",children:[j.taskId," · ",j.title]}),t.jsx("span",{className:"branch-group-card-member-status",children:j.landed?t.jsx(gc,{size:14}):t.jsx(yk,{size:14})})]},j.taskId))}),!f&&(i.prState==="merged"||i.prState==="closed")&&t.jsxs("div",{className:"branch-group-card-actions",children:[t.jsx("span",{className:"badge",children:i.prState==="merged"?"Group PR merged":"Group PR closed"}),i.prUrl&&t.jsxs("a",{className:"btn",href:i.prUrl,target:"_blank",rel:"noreferrer",children:[t.jsx(ai,{size:14})," PR #",i.prNumber??"—",t.jsx(Vo,{size:12})]})]}),!f&&(g||i.prState==="open")&&i.prState!=="merged"&&i.prState!=="closed"&&t.jsxs("div",{className:"branch-group-card-actions",children:[i.prUrl&&t.jsxs("a",{className:"btn",href:i.prUrl,target:"_blank",rel:"noreferrer",children:[t.jsx(ai,{size:14})," PR #",i.prNumber??"—",t.jsx(Vo,{size:12})]}),g&&(i.autoMerge?t.jsx("span",{className:"badge",children:s("branchGroup.autoMergeEnabled","Auto-merge enabled")}):i.prState==="none"?t.jsxs("button",{type:"button",className:"btn",onClick:()=>void x(),disabled:m,children:[m?t.jsx(Et,{size:14,className:"spin"}):t.jsx(ai,{size:14}),s("branchGroup.openPr","Open PR")]}):t.jsxs("button",{type:"button",className:"btn",onClick:()=>void x(),disabled:m,children:[m?t.jsx(Et,{size:14,className:"spin"}):t.jsx(ai,{size:14}),s("branchGroup.mergeIntoMain","Merge group into main")]})),i.prState==="open"&&t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void k(),disabled:h,children:[h?t.jsx(Et,{size:14,className:"spin"}):null,s("branchGroup.abandonGroup","Abandon group")]})]})]})}const gN=/^In-review stall surfaced \[([^\]]+)\]/;function GB(e,n){if(!e.log?.length)return;const s=[...e.log].reverse();for(const[i,r]of s.entries()){const o=r.action.match(gN);if(!(!o||o[1]!==n))return{entry:r,reversedIndex:i,code:n}}}const Ef=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),ax=/^Stale paused review surfaced \[([^\]]+)\]/,rx={p:({children:e,...n})=>t.jsx("p",{...n,children:hi(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:hi(e)}),code:({children:e,...n})=>{const s=typeof e=="string"?e:gr.Children.toArray(e).join(""),i=Hs(s);return i.length===1&&typeof i[0]=="string"?t.jsx("code",{...n,children:e}):t.jsx("code",{...n,children:i})}};function KB(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const i=s.text.match(/^Executor using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function JB(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const i=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function ox(e){return(e.title??"").trim().length>0?!0:!!(e.description??"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)}function bN(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 i=typeof n?.modelProvider=="string"?n.modelProvider.trim():"",r=typeof n?.modelId=="string"?n.modelId.trim():"";return{provider:i||void 0,modelId:r||void 0}}function YB(e,n,s,i){const r=KB(n);if(r)return r;if(Ef.has(e.status??"")||e.column==="in-progress"){const o=bN(s);if(o.provider&&o.modelId)return o}return Ap(e,i)}function XB(e,n,s,i){const r=JB(n);if(r)return r;if(Ef.has(e.status??"")||e.column==="in-progress"){const o=bN(s);if(o.provider&&o.modelId)return o}return Tp(e,i)}function QB(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const i=s.text.match(/^Triage using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function ZB(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=QB(n);return i||Rp(e,s)}function e6(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--in-progress)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function jo(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function t6(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Tl(e){const n=Math.max(1,Math.floor(e/6e4)),s=Math.floor(n/1440),i=Math.floor(n%1440/60),r=n%60;return s>0?`${s}d ${i}h`:i>0?`${i}h ${r}m`:`${r}m`}const n6=a.lazy(()=>ln(()=>import("./SessionTerminal-DwlNZLlr.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(e=>({default:e.SessionTerminal})));function s6(e,n={}){return e?e.agentState==="starting"||e.agentState==="ready"||e.agentState==="busy"||e.agentState==="waitingOnInput"?{kind:"live",readOnly:!!n.oneShot,mode:"live",showConfirmAdvance:!!n.genericIdle}:e.agentState==="done"?{kind:"replay",mode:"idle"}:{kind:"replay",mode:"ended"}:{kind:"hidden"}}function zm(e,n){return e.length>n?e.slice(0,n)+"…":e}function lx(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function Bm(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Um(e){return e.trim()}function i6(e){const n=e.trim();return n.length>0?n:void 0}function Ua(e){return typeof e=="string"&&xr.includes(e)?e:yi}function Ha(e){return e==="fast"?"fast":"standard"}function a6(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function r6(e){const n=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/(issues|pull)\/(\d+)(?:$|[/?#])/);if(!n)return null;const[,s,i,,r]=n;return{label:`${s}/${i}#${r}`,href:e}}function o6(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 l6=a.lazy(()=>ln(()=>import("./AgentDetailView-BrETpTDj.js"),__vite__mapDeps([9,1,4,10,11,12,13,5,6,2,3,7,14])).then(e=>({default:e.AgentDetailView})));function c6(e,n={}){const s=n.t;switch(e.sourceType){case"dashboard_ui":return{label:s?s("taskDetail.provenance.dashboard","Dashboard"):"Dashboard"};case"quick_chat":return{label:s?s("taskDetail.provenance.quickChat","Quick Chat"):"Quick Chat"};case"chat_session":return{label:s?s("taskDetail.provenance.chatSession","Chat Session"):"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??(s?s("taskDetail.provenance.agent","agent"):"agent"),sourceAgentId:e.sourceAgentId};case"automation":return{label:s?s("taskDetail.provenance.automation","Automation"):"Automation"};case"cron":return{label:s?s("taskDetail.provenance.scheduledTask","Scheduled Task"):"Scheduled Task"};case"workflow_step":return{label:s?s("taskDetail.provenance.workflowStep","Workflow Step"):"Workflow Step"};case"github_import":{const i=a6(e.sourceMetadata),r=i?r6(i):null;return{label:s?s("taskDetail.provenance.githubImport","GitHub Import"):"GitHub Import",contextInfo:i?r?.label??(s?s("taskDetail.provenance.openIssue","Open issue"):"Open issue"):void 0,contextHref:i,contextInfoFull:i}}case"research":{const i=o6(e.sourceMetadata);return{label:s?s("taskDetail.provenance.research","Research"):"Research",contextInfo:i,contextInfoFull:i}}case"task_refine":return{label:s?s("taskDetail.provenance.refinement","Refinement"):"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:s?s("taskDetail.provenance.duplicate","Duplicate"):"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:s?s("taskDetail.provenance.cli","CLI"):"CLI"};case"api":return{label:s?s("taskDetail.provenance.api","API"):"API"};case"recovery":return{label:s?s("taskDetail.provenance.recovery","Recovery"):"Recovery"};case"unknown":default:return null}}const Hm=200,d6=new Set(["triage","todo"]),u6=new Set(["triage","todo","in-progress","in-review"]);function vN({task:e,projectId:n,tasks:s=[],onOpenDetail:i,onMoveTask:r,onDeleteTask:o,onArchiveTask:l,onMergeTask:d,onRetryTask:c,onResetTask:m,onDuplicateTask:p,onTaskUpdated:h,addToast:u,prAuthAvailable:f,onOpenWorkflowEditor:b,initialTab:y="definition",mobileHeaderMode:v="close",embedded:x=!1,onRequestClose:k,workflowFieldDefs:w}){const{t:g}=st("app"),j=Xp(),[S,C]=a.useState(y==="retries"?"definition":y),[E,F]=a.useState(null),[M,D]=a.useState(()=>"prompt"in e?e:null),[_,V]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){D(e),V(!1);return}let H=!1;return V(!0),D(null),pr(e.id,n).then(we=>{H||(D(we),V(!1))}).catch(()=>{H||V(!1)}),()=>{H=!0}},[e.id,n]);const N=M?{...M,...e,prompt:M.prompt,log:M.log,githubTracking:e.githubTracking??M.githubTracking}:{...e,prompt:""},$=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,R=typeof N.sourceMetadata?.nearDuplicateOf=="string"?N.sourceMetadata.nearDuplicateOf:null,L=!!R&&N.sourceMetadata?.nearDuplicateDismissed!==!0&&e.column!=="archived"&&e.column!=="done",[O,J]=a.useState(null),[A,de]=a.useState(null),B=c6(N,{sourceAgentName:O?.name,t:g});a.useEffect(()=>{C(y==="retries"?"definition":y),y==="retries"&&rs(!0)},[y]),a.useEffect(()=>{S==="pr"&&e.column!=="in-review"&&C("definition")},[S,e.column]),a.useEffect(()=>{be(e.column==="triage")},[e.column,e.id]);const[P,Z]=a.useState("activity"),[T,ie]=a.useState(null),[le,be]=a.useState(()=>e.column==="triage"),[Le,xe]=a.useState(e.attachments||[]),[q,ce]=a.useState(!1),[De,He]=a.useState(e.dependencies||[]),[qe,pe]=a.useState(!1),[te,me]=a.useState(""),[se,z]=a.useState(null),[Y,he]=a.useState([]),[X,ye]=a.useState(!1),[ot,ue]=a.useState(!1),[je,$e]=a.useState(!1),[Ce,We]=a.useState(!1),[ke,Ee]=a.useState(!1),[Ze,Ke]=a.useState(N.prompt||""),[dt,Fe]=a.useState(""),[nt,Nt]=a.useState(!1),[Ft,ze]=a.useState(!1),[it,Mt]=a.useState(w!==void 0?w??null:null),[Ht,Me]=a.useState(e.customFields??{}),[Ae,ee]=a.useState(null);a.useEffect(()=>{Me(e.customFields??{})},[e.id,e.customFields]),a.useEffect(()=>{if(w!==void 0){Mt(w??null);return}let H=!1;return Op(n).then(we=>{if(H)return;const lt=we.taskWorkflowIds[e.id]??we.defaultWorkflowId,wt=we.workflows.find(jn=>jn.id===lt);Mt(wt?.fields??null)}).catch(()=>{H||Mt(null)}),()=>{H=!0}},[e.id,n,w]);const Ie=a.useCallback(async H=>{ee(null);try{const we=await kE(e.id,H,n);Me(we.customFields??{}),h?.(we)}catch(we){if(we instanceof Ka&&we.details&&typeof we.details.fieldId=="string"){ee({code:we.details.code??"type-mismatch",fieldId:we.details.fieldId,detail:typeof we.details.detail=="string"?we.details.detail:we.message});return}u(Re(we)||g("taskFields.saveFailed","Failed to save field"),"error")}},[e.id,n,h,u,g]);a.useEffect(()=>{if(S!=="logs"||P!=="activity"){ie(null);return}if(!T)return;const H=Te.current?.querySelector('[data-stall-highlight="true"]');H&&typeof H.scrollIntoView=="function"&&H.scrollIntoView({block:"nearest",behavior:"smooth"})},[S,P,T]);const[Pe,oe]=a.useState(""),[re,_e]=a.useState(!1),[fe,Xe]=a.useState(!1),[kt,Rt]=a.useState(e.title||""),[Vt,Pt]=a.useState(e.description||""),[bt,pt]=a.useState(e.dependencies||[]),[ft,_t]=a.useState(e.branch??""),[Yt,on]=a.useState(e.baseBranch??""),[An,vn]=a.useState(""),[Qt,sn]=a.useState(""),[mn,Kt]=a.useState(""),[fn,$n]=a.useState(""),[On,xn]=a.useState("default"),[Vn,Rn]=a.useState(void 0),[Pn,zn]=a.useState(yi),[Nn,dn]=a.useState(e.nodeId),[Tt,Yn]=a.useState(Ha(e.executionMode)),[cn,Bn]=a.useState(""),[kn,pn]=a.useState(e.enabledWorkflowSteps||[]),[un,At]=a.useState(e.sourceIssue?.provider??""),[an,Wn]=a.useState(e.sourceIssue?.repository??""),[Xn,G]=a.useState(e.sourceIssue?.externalIssueId??""),[Oe,yt]=a.useState(e.sourceIssue?.url??""),[Gt,Sn]=a.useState([]),[Un,bn]=a.useState(!1),[gn,ps]=a.useState(!1),[Ne,ae]=a.useState(Ua(e.priority)),[Se,ut]=a.useState(!1),[It,ht]=a.useState(Ha(e.executionMode)),[et,Ut]=a.useState(!1),[$t,rn]=a.useState(e.noCommitsExpected===!0),[Cn,ve]=a.useState(!1),at=a.useRef(!1),Ge=a.useRef(e.id),[tt,gt]=a.useState(!1),[St,Xt]=a.useState(!1),[ss,Ts]=a.useState(!1),[Ls,rs]=a.useState(y==="retries"),[ei,Mi]=a.useState(!1),[ti,mi]=a.useState(e.githubTracking?.repoOverride??""),[zs,Qn]=a.useState(null),[Zt,Q]=a.useState(null),[Qe,vt]=a.useState(!1),[xt,zt]=a.useState(!1),[Wt,hn]=a.useState(!1),[In,gs]=a.useState(null),ks=a.useRef(null),Te=a.useRef(null),U=a.useRef(null),ge=a.useRef(null),{getSlotsForId:rt}=uw(n),Dt=rt("task-detail-tab").map((H,we)=>({entry:H,tabId:`plugin-${H.pluginId}-${we}`})),en=typeof S=="string"&&S.startsWith("plugin-")?Dt.find(H=>H.tabId===S)??null:null,tn=E?.adapterId!=null&&(E?.autonomyPosture?.purpose==="planning"||E?.autonomyPosture?.purpose==="validator"||E?.autonomyPosture?.readOnly===!0),Dn=E?.autonomyPosture?.genericIdle===!0,_n=a.useMemo(()=>s6(E,{oneShot:tn,genericIdle:Dn}),[E,tn,Dn]),is=_n.kind!=="hidden",Ss=a.useMemo(()=>{if(!E)return;const H=E.autonomyPosture??{},we=Array.isArray(H.elevatedFlags)?H.elevatedFlags:void 0;return{adapterName:H.adapterName??E.adapterId,mode:H.mode??(H.autoApprove?"auto-approve":void 0),elevated:H.elevated===!0,elevatedFlags:we,resolved:Array.isArray(H.resolved)?H.resolved:void 0}},[E]),Rs=a.useCallback(async H=>{if(E)try{await I(`/cli-sessions/${encodeURIComponent(E.id)}/confirm-advance`,{method:"POST",body:JSON.stringify({decision:H,...n?{projectId:n}:{}})})}catch{}},[E,n]);a.useEffect(()=>{S==="terminal"&&!is&&C("definition")},[S,is]),a.useEffect(()=>(at.current=!0,()=>{at.current=!1}),[]),a.useEffect(()=>{Ge.current=e.id},[e.id]);const[ne,Ue]=a.useState(void 0),[Je,qt]=a.useState(null),[En,yn]=a.useState([]),[os,fs]=a.useState(!1),[ws,js]=a.useState(e.enabledWorkflowSteps||[]),Vs=e.column==="in-progress"||Ef.has(e.status);a.useEffect(()=>{Rt(e.title||""),Pt(e.description||""),_t(e.branch??""),on(e.baseBranch??""),At(e.sourceIssue?.provider??""),Wn(e.sourceIssue?.repository??""),G(e.sourceIssue?.externalIssueId??""),yt(e.sourceIssue?.url??""),Yn(Ha(e.executionMode)),Ts(!1),Mi(!1),mi(N.githubTracking?.repoOverride??""),Qn(null),Q(null),Xe(!1),gs(null),zt(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,N.githubTracking]),a.useEffect(()=>{js(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{ae(Ua(e.priority))},[e.id,e.priority]),a.useEffect(()=>{ht(Ha(e.executionMode))},[e.id,e.executionMode]),a.useEffect(()=>{rn(e.noCommitsExpected===!0)},[e.id,e.noCommitsExpected]),a.useEffect(()=>{zs!==null&&N.githubTracking?.enabled===!0===zs&&Qn(null)},[zs,N.githubTracking?.enabled]),a.useEffect(()=>{let H=!1;return yu(n).then(we=>{H||Ue(we)}).catch(()=>{}),Ja().then(we=>{H||qt(we)}).catch(()=>{H||qt(null)}),()=>{H=!0}},[n]),a.useEffect(()=>{if(S!=="workflow")return;let H=!1;return fs(!0),TA(e.id,n).then(we=>{H||yn(we)}).catch(we=>{H||u(g("taskDetail.workflow.loadFailed","Failed to load workflow results: {{error}}",{error:Re(we)}),"error")}).finally(()=>{H||fs(!1)}),()=>{H=!0}},[S,e.id,n,u]),a.useEffect(()=>{if(S!=="workflow")return;const H=n?`?projectId=${encodeURIComponent(n)}`:"",we=lt=>{try{const wt=JSON.parse(lt.data);wt.id===e.id&&Array.isArray(wt.workflowStepResults)&&yn(wt.workflowStepResults)}catch{}};return li(`/api/events${H}`,{events:{"task:updated":we}})},[S,e.id,n]),a.useEffect(()=>{let H=!1;const we=new URLSearchParams({taskId:e.id});return n&&we.set("projectId",n),I(`/cli-sessions?${we.toString()}`).then(lt=>{if(H)return;const wt=lt.sessions??[];F(wt.length>0?wt[wt.length-1]:null)}).catch(()=>{H||F(null)}),()=>{H=!0}},[e.id,n]),a.useEffect(()=>{const H=n?`?projectId=${encodeURIComponent(n)}`:"",we=lt=>{try{const wt=JSON.parse(lt.data);if(wt.taskId!==e.id)return;F(jn=>{if((!jn||jn.id!==wt.sessionId)&&!jn)return jn;const Js={...jn};return wt.state==="starting"||wt.state==="ready"||wt.state==="busy"||wt.state==="waitingOnInput"||wt.state==="done"||wt.state==="dead"||wt.state==="needsAttention"?Js.agentState=wt.state:(wt.state==="idle"||wt.state==="resuming")&&(Js.agentState="busy"),wt.terminationReason!==void 0&&(Js.terminationReason=wt.terminationReason??null),Js})}catch{}};return li(`/api/events${H}`,{events:{"cli:session:state":we}})},[e.id,n]),a.useEffect(()=>{qe||me("")},[qe]),a.useEffect(()=>{if(!e.assignedAgentId){z(null);return}const H=Y.find(lt=>lt.id===e.assignedAgentId);if(H){z(H);return}let we=!1;return Ph(e.assignedAgentId,n).then(lt=>{we||z(lt)}).catch(()=>{we||z(null)}),()=>{we=!0}},[e.assignedAgentId,n,Y]),a.useEffect(()=>{if(!e.sourceAgentId){J(null);return}const H=Y.find(lt=>lt.id===e.sourceAgentId);if(H){J(H);return}let we=!1;return Promise.resolve(Ph(e.sourceAgentId,n)).then(lt=>{we||J(lt??null)}).catch(()=>{we||J(null)}),()=>{we=!0}},[e.sourceAgentId,n,Y]),a.useEffect(()=>{ye(!1)},[e.id]),a.useEffect(()=>{if(!(tt||St))return;const we=lt=>{const wt=lt.target,jn=ks.current?.contains(wt),Js=ge.current?.contains(wt);!jn&&tt&>(!1),!Js&&St&&Xt(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[tt,St]),a.useEffect(()=>{if(!(tt||St))return;const we=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),tt&>(!1),St&&Xt(!1))};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[tt,St]),a.useEffect(()=>{Ee(!1),Ke(N.prompt||""),Fe("")},[e.id,N.prompt]);const qs=d6.has(e.column)&&!Un,Ai=u6.has(e.column)&&!Un,pi=zs??N.githubTracking?.enabled===!0,Fs=N.githubTracking?.issue,ji=_&&typeof e.githubTracking>"u",Oa=ox(e),wr=Ai&&!Fs&&!ji&&(!pi||Qe&&N.githubTracking?.enabled!==!0),fl=Ai||pi||!!Fs,fi=e.retrySummary,gl=[{key:"stuckKill",label:g("taskDetail.retries.stuckKill","Stuck kills"),title:g("taskDetail.retries.stuckKillTitle","Stuck-task detector forced agent kill retries"),value:fi?.stuckKill??0},{key:"recovery",label:g("taskDetail.retries.recovery","Recovery retries"),title:g("taskDetail.retries.recoveryTitle","Transient executor recovery retries"),value:fi?.recovery??0},{key:"taskDone",label:g("taskDetail.retries.taskDone","task_done retries"),title:g("taskDetail.retries.taskDoneTitle","Agent exited without task_done and task was retried"),value:fi?.taskDone??0},{key:"workflowStep",label:g("taskDetail.retries.workflowStep","Workflow retries"),title:g("taskDetail.retries.workflowStepTitle","Workflow step failure retries"),value:fi?.workflowStep??0},{key:"verification",label:g("taskDetail.retries.verification","Verification bounces"),title:g("taskDetail.retries.verificationTitle","Verification failure bounce retries"),value:fi?.verification??0},{key:"postReviewFix",label:g("taskDetail.retries.postReviewFix","Post-review fixes"),title:g("taskDetail.retries.postReviewFixTitle","Post-review remediation retries"),value:fi?.postReviewFix??0},{key:"mergeConflict",label:g("taskDetail.retries.mergeConflict","Merge conflict bounces"),title:g("taskDetail.retries.mergeConflictTitle","Merge conflict bounce retries"),value:fi?.mergeConflict??0},{key:"branchConflict",label:g("taskDetail.retries.branchConflict","Branch conflict recovery"),title:g("taskDetail.retries.branchConflictTitle","FN-4068 branch-conflict recovery retries"),value:fi?.branchConflict??0},{key:"reviewerContext",label:g("taskDetail.retries.reviewerContext","Reviewer context retries"),title:g("taskDetail.retries.reviewerContextTitle","FN-4082 compact reviewer retry"),value:fi?.reviewerContext??0},{key:"reviewerFallback",label:g("taskDetail.retries.reviewerFallback","Reviewer fallback retries"),title:g("taskDetail.retries.reviewerFallbackTitle","FN-4092 fallback-model retry"),value:fi?.reviewerFallback??0}].filter(H=>H.value>0),la=ji?g("taskDetail.githubTracking.statusLoading","Loading"):Fs?g("taskDetail.githubTracking.statusLinked","Linked"):pi?g("taskDetail.githubTracking.statusEnabled","Enabled"):g("taskDetail.githubTracking.statusDisabled","Disabled"),ba=!Fs&&(Qe||ji),va=sN(ne??null,Je),Xi=ti.trim(),jr=(e.description??"").trim().length>0,bl=!fe&&qs&&jr,Nr=a.useCallback(async()=>{if(gn||Un||!jr)return;const H=e.id;ps(!0);try{const we=await ZA(e.description||"",void 0,void 0,n);if(Ge.current!==H)return;const lt=await si(e.id,{title:we},n);if(Ge.current!==H)return;D(wt=>wt?{...wt,...lt}:lt),h?.(lt),u(g("taskDetail.title.summarizeSuccess","Title updated from description"),"success")}catch(we){Ge.current===H&&u(g("taskDetail.title.summarizeFailed","Failed to summarize title: {{error}}",{error:Re(we)}),"error")}finally{at.current&&Ge.current===H&&ps(!1)}},[u,jr,Un,gn,h,n,g,e.description,e.id]),Sr=a.useCallback(async()=>{if(!Ai||Qe)return;const H=e.id,we=!pi;Qn(we),vt(!0);try{const lt=await si(e.id,{githubTracking:{enabled:we}},n);if(Ge.current!==H)return;D(wt=>wt?{...wt,...lt,githubTracking:lt.githubTracking}:lt),h?.(lt)}catch(lt){if(Ge.current!==H)return;Qn(N.githubTracking?.enabled===!0),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(lt)}),"error")}finally{at.current&&Ge.current===H&&vt(!1)}},[u,Ai,pi,Qe,h,n,N.githubTracking?.enabled,e.id]),io=a.useCallback(async()=>{if(!Ai||Qe)return;const H=e.id;if(Xi.length>0&&!xu.test(Xi)){Q(g("taskDetail.githubTracking.repoOverrideFormat","Repository override must be in owner/repo format"));return}Q(null),vt(!0);try{const we=await si(e.id,{githubTracking:{repoOverride:Xi.length>0?Xi:null}},n);if(Ge.current!==H)return;D(lt=>lt?{...lt,...we,githubTracking:we.githubTracking}:we),h?.(we)}catch(we){if(Ge.current!==H)return;u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(we)}),"error")}finally{at.current&&Ge.current===H&&vt(!1)}},[u,Ai,Xi,Qe,h,n,e.id]),vl=a.useCallback(async()=>{if(!pi||Fs||Qe)return;if(!ox(e)){u(g("taskDetail.githubTracking.addTitleBeforeCreating","Add a title before creating a tracking issue"),"info");return}const H=e.id;vt(!0);try{const we=await si(e.id,{githubTracking:{enabled:!0}},n);if(Ge.current!==H)return;D(lt=>lt?{...lt,...we,githubTracking:we.githubTracking}:we),h?.(we),u(g("taskDetail.githubTracking.issueCreationRequested","Requested GitHub tracking issue creation"),"info")}catch(we){if(Ge.current!==H)return;u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(we)}),"error")}finally{at.current&&Ge.current===H&&vt(!1)}},[u,Fs,pi,Qe,h,n,e]),Qa=a.useCallback(()=>{if(!qs)return;Xe(!0),Rt(e.title||""),Pt(e.description||""),pt(e.dependencies||[]),_t(e.branch??""),on(e.baseBranch??"");const H=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",we=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";vn(H),sn(we),Kt(lt),$n(e.thinkingLevel??""),dn(e.nodeId),xn(H||we||lt?"custom":"default"),Bn(""),pn(e.enabledWorkflowSteps||[]),Yn(Ha(e.executionMode)),At(e.sourceIssue?.provider??""),Wn(e.sourceIssue?.repository??""),G(e.sourceIssue?.externalIssueId??""),yt(e.sourceIssue?.url??""),Sn([]),Rn(e.reviewLevel),zn(Ua(e.priority))},[qs,e]),$a=a.useCallback(()=>{Xe(!1),Rt(e.title||""),Pt(e.description||""),pt(e.dependencies||[]),_t(e.branch??""),on(e.baseBranch??""),dn(e.nodeId),At(e.sourceIssue?.provider??""),Wn(e.sourceIssue?.repository??""),G(e.sourceIssue?.externalIssueId??""),yt(e.sourceIssue?.url??""),zn(Ua(e.priority)),Yn(Ha(e.executionMode)),Gt.forEach(H=>URL.revokeObjectURL(H.previewUrl)),Sn([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Gt]),[za,gi]=a.useState("idle"),zi=a.useRef(null),xa=a.useRef(0),Cr=a.useCallback(H=>{const we={},lt=kt.trim(),wt=Vt.trim();lt&<!==(e.title??"")&&(we.title=lt),H&&wt&&wt!==(e.description??"")&&(we.description=wt),lx(bt,e.dependencies??[])||(we.dependencies=bt),lx(kn,e.enabledWorkflowSteps??[])||(we.enabledWorkflowSteps=kn);const jn=ft.trim()||null,Js=e.branch??null;jn!==Js&&(we.branch=jn);const Dc=Yt.trim()||null,Rr=e.baseBranch??null;Dc!==Rr&&(we.baseBranch=Dc);const Ou=Bm(An),Lc=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";An!==Lc&&(we.modelProvider=Ou?.provider??null,we.modelId=Ou?.modelId??null);const ho=Bm(Qt),Yf=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Qt!==Yf&&(we.validatorModelProvider=ho?.provider??null,we.validatorModelId=ho?.modelId??null);const Fc=Bm(mn),FS=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";mn!==FS&&(we.planningModelProvider=Fc?.provider??null,we.planningModelId=Fc?.modelId??null);const OS=e.thinkingLevel??"";fn!==OS&&(we.thinkingLevel=fn!==""?fn:null),(e.nodeId??void 0)!==Nn&&(we.nodeId=Nn??null),Vn!==e.reviewLevel&&(we.reviewLevel=Vn),Pn!==Ua(e.priority)&&(we.priority=Pn),Tt!==Ha(e.executionMode)&&(we.executionMode=Tt==="fast"?"fast":null);const $u=Um(un),zu=Um(an),Oc=Um(Xn),Bu=i6(Oe);if($u.length===0&&zu.length===0&&Oc.length===0&&!Bu)e.sourceIssue&&(we.sourceIssue=null);else{if(!$u||!zu||!Oc)return{updates:null,error:g("taskDetail.edit.sourceIssueRequiredFields","Source issue provider, repository, and issue identifier are required")};const $S=Number.parseInt(Oc,10),Uu=e.sourceIssue?.issueNumber??$S;if(!Number.isFinite(Uu)||Uu<=0)return{updates:null,error:g("taskDetail.edit.sourceIssueIdentifierNumeric","Source issue identifier must be numeric for new metadata")};const po={provider:$u,repository:zu,externalIssueId:Oc,issueNumber:Uu,...Bu?{url:Bu}:{}},fo=e.sourceIssue;(!fo||fo.provider!==po.provider||fo.repository!==po.repository||fo.externalIssueId!==po.externalIssueId||fo.issueNumber!==po.issueNumber||(fo.url??void 0)!==po.url)&&(we.sourceIssue=po)}return{updates:we,error:null}},[Yt,ft,bt,Vt,Tt,An,Nn,mn,Pn,Vn,kn,Xn,un,an,Oe,fn,kt,Qt,e]),Ti=a.useCallback(async H=>{const{updates:we,error:lt}=Cr(H);if(!we)return gi("error"),lt&&u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:lt}),"error"),!1;if(Object.keys(we).length===0)return!0;const wt=++xa.current;bn(!0),gi("saving");try{const jn=await si(e.id,we,n);return wt!==xa.current?void 0:(h?.(jn),gi("saved"),!0)}catch(jn){return wt===xa.current&&(gi("error"),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(jn)}),"error")),!1}finally{at.current&&wt===xa.current&&bn(!1)}},[u,Cr,h,n,e.id]),ao=a.useCallback(async H=>{await Ti(!0)},[Ti]),Bi=a.useCallback(async()=>{await Ti(!0)&&(u(g("taskDetail.updateSuccess","Updated {{id}}",{id:e.id}),"success"),at.current&&Xe(!1))},[u,Ti,e.id]);a.useEffect(()=>{if(fe)return zi.current&&clearTimeout(zi.current),zi.current=setTimeout(()=>{Ti(!1)},700),()=>{zi.current&&(clearTimeout(zi.current),zi.current=null)}},[fe,kt,bt,ft,Yt,An,Qt,mn,fn,Nn,Vn,Pn,Tt,kn,un,an,Xn,Oe,Ti]);const ro=a.useCallback(async H=>{const we=Ua(H),lt=Ua(e.priority);if(we===lt){ae(lt);return}const wt=Ne;ae(we),ut(!0);try{const jn=await si(e.id,{priority:we},n);ae(Ua(jn.priority)),h?.(jn),u(g("taskDetail.priority.updated","Priority updated to {{priority}}",{priority:Ua(jn.priority)}),"success")}catch(jn){ae(wt),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(jn)}),"error")}finally{at.current&&ut(!1)}},[e.id,e.priority,n,Ne,h,u]),Za=a.useCallback(async()=>{const we=Ha(e.executionMode)==="fast"?"standard":"fast",lt=It;ht(we),Ut(!0);try{const wt=await si(e.id,{executionMode:we==="fast"?"fast":null},n),jn=Ha(wt.executionMode);ht(jn),h?.(wt),u(g("taskDetail.executionMode.updated","Execution mode updated to {{mode}}",{mode:jn}),"success")}catch(wt){ht(lt),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(wt)}),"error")}finally{at.current&&Ut(!1)}},[e.id,e.executionMode,n,It,h,u]),_r=a.useCallback(async()=>{const H=!$t,we=$t;rn(H),ve(!0);try{const lt=await si(e.id,{noCommitsExpected:H},n),wt=lt.noCommitsExpected===!0;rn(wt),h?.(lt),u(wt?g("taskDetail.noCommits.enabled","No-commits expectation enabled"):g("taskDetail.noCommits.disabled","No-commits expectation disabled"),"success")}catch(lt){rn(we),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(lt)}),"error")}finally{at.current&&ve(!1)}},[e.id,n,$t,h,u]),Ba=a.useCallback(H=>{fe&&(H.key==="Escape"?(H.preventDefault(),$a()):H.key==="Enter"&&(H.ctrlKey||H.metaKey)&&(H.preventDefault(),Bi()))},[fe,$a,Bi]);a.useEffect(()=>{if(fe)return document.addEventListener("keydown",Ba),()=>document.removeEventListener("keydown",Ba)},[fe,Ba]);const ya=a.useRef(null),{nodes:oo}=Nu(),{confirm:Cs,confirmWithChoice:ka,confirmWithCheckbox:wa}=Yi(),Er=a.useCallback(async()=>{if(!(!qs||!Fs||Qe||!await Cs({title:g("taskDetail.githubTracking.unlinkTitle","Unlink GitHub issue?"),message:g("taskDetail.githubTracking.unlinkMessage","This stops Fusion from syncing with the linked GitHub issue. The issue itself will not be modified."),confirmLabel:g("taskDetail.githubTracking.unlinkConfirm","Unlink"),danger:!0}))){vt(!0);try{const we=await si(e.id,{githubTracking:{issue:null}},n);h?.(we),u(g("taskDetail.githubTracking.issueUnlinked","GitHub issue unlinked"),"success")}catch(we){u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(we)}),"error")}finally{at.current&&vt(!1)}}},[u,qs,Cs,Fs,Qe,h,n,e.id]),{entries:ja,loading:lo,loadMore:co,hasMore:Mr,total:Ar,loadingMore:er}=Wj(e.id,S==="logs"&&P==="agent-log",n),Kn=a.useCallback(()=>{k?.()},[k]);a.useEffect(()=>{if(x)return;const H=we=>{we.key==="Escape"&&!fe&&Kn()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[x,Kn,fe]);const tr=a.useCallback(async H=>{try{const we=e.steps.some(jn=>jn.status!=="pending"),lt=(H==="todo"||H==="triage")&&we;let wt;if(lt){if(await Cs({title:g("taskDetail.move.preserveProgressTitle","Preserve Progress?"),message:g("taskDetail.move.preserveProgressMessage","This task has completed steps. Keep progress before moving?"),confirmLabel:g("taskDetail.move.keepProgress","Keep Progress"),cancelLabel:g("taskDetail.move.resetProgress","Reset Progress")}))wt={preserveProgress:!0};else if(!await Cs({title:g("taskDetail.move.resetProgressTitle","Reset Progress?"),message:g("taskDetail.move.resetProgressMessage","Reset all step progress before moving this task?"),confirmLabel:g("taskDetail.move.resetProgress","Reset Progress"),cancelLabel:g("taskDetail.move.cancelMove","Cancel Move"),danger:!0}))return}await r(e.id,H,wt),Kn(),u(g("taskDetail.move.movedTo","Moved to {{column}}",{column:j(H)}),"success")}catch(we){u(Re(we),"error")}},[e.id,e.steps,r,Kn,u,Cs]),nr=a.useCallback(async()=>{let H=!1;if(e.column==="done"&&l){const wt=await ka({title:g("taskDetail.delete.title","Delete Task"),message:g("taskDetail.delete.message","Delete {{id}}?",{id:e.id}),confirmLabel:g("taskDetail.delete.confirm","Delete"),cancelLabel:g("common.cancel","Cancel"),tertiaryLabel:g("taskDetail.delete.archiveInstead","Archive Instead"),danger:!0});if(wt==="tertiary"){try{await l(e.id),u(g("taskDetail.nearDuplicate.archived","Archived {{id}}",{id:e.id}),"success"),Kn()}catch(jn){const Js=Ta(jn);if(!Js||Js.lineageChildIds.length===0){u(Re(jn),"error");return}if(!await Cs({title:g("taskDetail.delete.forceDeleteTitle","Force Delete Task"),message:`${e.id} has lineage children (${Js.lineageChildIds.join(", ")}) that reference it as a source parent.
|
|
769
|
+
`);return n.length<=1?e:`${n.length} lines`}function id(e,n,s,i){const r=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${r}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?i("workflow.postMerge","Post-merge"):i("workflow.preMerge","Pre-merge")})}function AB(e,n,s){return e?n.find(r=>r.id===e)?.name||s("workflow.customWorkflowFallback","Custom workflow"):s("workflow.defaultWorkflow","Default")}function TB(e,n){return e.some(s=>s.status==="failed")?{label:n("workflow.statusFailed","Failed"),badgeClass:"workflow-result-badge--failed",testId:"failed"}:e.some(s=>s.status==="advisory_failure")?{label:n("workflow.statusAdvisory","Advisory"),badgeClass:"workflow-result-badge--advisory_failure",testId:"advisory"}:e.some(s=>s.status==="pending")?{label:n("workflow.aggregateInProgress","In progress"),badgeClass:"workflow-result-badge--pending",testId:"pending"}:e.length===0?{label:n("workflow.aggregateNoResults","No results"),badgeClass:"workflow-result-badge--skipped",testId:"no-results"}:{label:n("workflow.aggregateAllPassed","All passed"),badgeClass:"workflow-result-badge--passed",testId:"passed"}}function RB(e,n,s,i,r){if(n==="awaiting-user-input")return{label:r("workflow.executionAwaitingInput","Awaiting input"),badgeClass:"workflow-result-badge--pending",testId:"awaiting-input"};if(n==="awaiting-cli-approval")return{label:r("workflow.executionAwaitingCliApproval","Awaiting CLI approval"),badgeClass:"workflow-result-badge--pending",testId:"awaiting-cli-approval"};if(n==="paused"||s)return{label:r("workflow.executionPaused","Paused"),badgeClass:"workflow-result-badge--pending",testId:"paused"};const o=i.find(d=>d.status==="pending");if(o){const d=(o.phase||"pre-merge")==="post-merge";return{label:d?r("workflow.executionPostMerge","Post-merge steps running"):r("workflow.executionPreMerge","Pre-merge steps running"),badgeClass:"workflow-result-badge--pending",testId:d?"post-merge":"pre-merge"}}return i.length>0&&i.every(d=>["passed","failed","advisory_failure","skipped"].includes(d.status))||n==="done"||e?.column==="done"||e?.column==="in-review"?{label:r("workflow.executionCompleted","Completed"),badgeClass:"workflow-result-badge--passed",testId:"completed"}:{label:r("workflow.executionNotStarted","Not started"),badgeClass:"workflow-result-badge--pending",testId:"not-started"}}function Om(e){return!e?.provider||!e.modelId?"Default":`${e.provider}/${e.modelId}`}function PB({entries:e,startedAt:n,stepId:s,t:i}){const r=a.useRef(null),o=new Date(n).getTime(),l=e.filter(d=>new Date(d.timestamp).getTime()>=o);return a.useEffect(()=>{const d=r.current;d&&(d.scrollTop=d.scrollHeight)},[l.length]),l.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:i("workflow.waitingForOutput","Waiting for agent output…")})}):t.jsx("div",{ref:r,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:l.map((d,c)=>d.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",Hs(d.text),d.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Hs(d.detail)]})]},c):d.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",Hs(d.text),d.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Hs(d.detail)]})]},c):d.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",Hs(d.text),d.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Hs(d.detail)]})]},c):d.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:Hs(d.text)},c):t.jsx("span",{className:"workflow-live-log-text",children:Hs(d.text)},c))})}function IB({taskId:e,task:n,results:s,loading:i,enabledWorkflowSteps:r,canEdit:o,projectId:l,isTaskInProgress:d,onWorkflowStepsChange:c,taskStatus:m,taskPausedReason:p,settings:h,onEditWorkflow:u,onWorkflowReconciled:f}){const{t:b}=st("app"),[y,v]=a.useState({}),[x,k]=a.useState({}),[w,g]=a.useState(""),[j,S]=a.useState(!1),[C,E]=a.useState(!1),[F,M]=a.useState(null),[D,_]=a.useState([]),[V,N]=a.useState([]),[$,R]=a.useState(!1),[L,O]=a.useState(null),[J,A]=a.useState(null),[de,B]=a.useState(!1),[P,Z]=a.useState({}),[T,ie]=a.useState(!1),[le,be]=a.useState(!1);a.useEffect(()=>{g(""),S(!1),E(!1),A(null)},[e,m,p]),a.useEffect(()=>{let Me=!1;return RA(e,l).then(Ae=>{Me||O(Ae.workflowId)}).catch(()=>{}),()=>{Me=!0}},[e,l]);const Le=a.useCallback(async Me=>{const Ae=await PA(e,Me,l);O(Ae.workflowId),c?.(Ae.enabledWorkflowSteps),Ae.reconciliation&&!Ae.reconciliation.preserved&&f?.()},[e,l,c,f]);a.useEffect(()=>{let Me=!1;return Bp(l).then(Ae=>{Me||N(Ae)}).catch(()=>{Me||N([])}),()=>{Me=!0}},[l]),a.useEffect(()=>{if(!de||!L||P[L])return;let Me=!1;return ie(!0),Zk(L,l).then(Ae=>{Me||Z(ee=>({...ee,[L]:Ae}))}).catch(()=>{}).finally(()=>{Me||ie(!1)}),()=>{Me=!0}},[de,L,l,P]);const xe=s.some(Me=>Me.status==="pending"),{entries:q}=Wj(e,!!d&&xe,l);a.useEffect(()=>{let Me=!1;return zp(l).then(Ae=>{Me||_(Ae.filter(ee=>ee.enabled))}).catch(()=>{Me||_([])}),()=>{Me=!0}},[l]);const ce=r??[],De=a.useMemo(()=>D.map(Me=>({id:Me.id,name:Me.name,description:Me.description,phase:Me.phase||"pre-merge"})),[D]),He=a.useMemo(()=>new Map(De.map(Me=>[Me.id,Me])),[De]),qe=Me=>{v(Ae=>({...Ae,[Me]:!Ae[Me]}))},pe=Me=>{k(Ae=>{const ee=Ae[Me]??"markdown";return{...Ae,[Me]:ee==="markdown"?"plain":"markdown"}})},te=Me=>{M(Me)},me=()=>{M(null)};a.useEffect(()=>{if(!F)return;const Me=Ae=>{Ae.key==="Escape"&&me()};return document.addEventListener("keydown",Me),()=>{document.removeEventListener("keydown",Me)}},[F]);const se=a.useCallback((Me,Ae)=>{if(c){if(Ae){if(ce.includes(Me)){c(ce);return}c([...ce,Me]);return}c(ce.filter(ee=>ee!==Me))}},[c,ce]),z=a.useCallback(Me=>{if(!c||Me<=0)return;const Ae=[...ce];[Ae[Me-1],Ae[Me]]=[Ae[Me],Ae[Me-1]],c(Ae)},[c,ce]),Y=a.useCallback(Me=>{if(!c||Me>=ce.length-1)return;const Ae=[...ce];[Ae[Me],Ae[Me+1]]=[Ae[Me+1],Ae[Me]],c(Ae)},[c,ce]),he=a.useCallback(Me=>{c&&c(ce.filter(Ae=>Ae!==Me))},[c,ce]),X=s.length>0,ye=ce.length>0;a.useEffect(()=>{o||R(!1)},[o]);const ot=a.useMemo(()=>ce.map(Me=>{const Ae=He.get(Me);return{id:Me,name:Ae?.name||Me,description:Ae?.description||b("workflow.stepDefinitionNotFound","Step definition not found."),phase:Ae?.phase||"pre-merge"}}),[ce,He,b]),ue=a.useMemo(()=>AB(L,V,b),[L,V,b]),je=a.useMemo(()=>RB(n,m,p,s,b),[n,m,p,s,b]),$e=a.useMemo(()=>TB(s,b),[s,b]),Ce=a.useMemo(()=>s.filter(Me=>["passed","skipped","failed","advisory_failure"].includes(Me.status)).length,[s]),We=L?P[L]:void 0,ke=a.useMemo(()=>We?nB(We):null,[We]),Ee=a.useMemo(()=>n?Ap(n,h):void 0,[n,h]),Ze=a.useMemo(()=>n?Tp(n,h):void 0,[n,h]),Ke=a.useMemo(()=>n?Rp(n,h):void 0,[n,h]),dt=()=>!o||!$||i?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:b("workflow.selectStepsDescription","Select steps to run after task implementation completes")}),t.jsx("div",{className:"workflow-steps-list",children:De.map(Me=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${Me.id}`,children:[t.jsx("input",{type:"checkbox",checked:ce.includes(Me.id),onChange:Ae=>se(Me.id,Ae.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[Me.name,id(Me.phase,Me.id,"workflow-step-phase",b)]}),t.jsx("div",{className:"workflow-step-description",children:Me.description})]})]},Me.id))})]}),ce.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:b("workflow.executionOrder","Execution order:")}),ce.map((Me,Ae)=>{const ee=He.get(Me);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${Me}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Ae+1}),t.jsx("span",{className:"workflow-step-order-name",children:ee?.name||Me}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>z(Ae),disabled:Ae===0,"data-testid":`workflow-step-move-up-${Me}`,title:b("workflow.moveUp","Move up"),children:t.jsx(ra,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Y(Ae),disabled:Ae===ce.length-1,"data-testid":`workflow-step-move-down-${Me}`,title:b("workflow.moveDown","Move down"),children:t.jsx(Ln,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>he(Me),"data-testid":`workflow-step-remove-${Me}`,title:b("workflow.remove","Remove"),children:t.jsx(Fn,{})})]})]},Me)})]})]}),Fe=()=>{if(i)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:b("workflow.loadingResults","Loading workflow results…")})]});if(!X)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:b("workflow.noStepsConfigured","No workflow steps configured for this task.")}),t.jsx("p",{className:"workflow-results-empty-hint",children:b("workflow.stepsExplanation","Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds.")})]});const Me=s.filter(re=>re.status==="passed").length,Ae=s.filter(re=>re.status==="failed").length,ee=s.filter(re=>re.status==="advisory_failure"),Ie=s.filter(re=>re.status==="skipped").length,Pe=s.filter(re=>re.status==="pending").length,oe=[b("workflow.summaryStepCount",{count:s.length,defaultValue_one:"{{count}} step",defaultValue_other:"{{count}} steps"})];return Me>0&&oe.push(b("workflow.summaryPassed","{{count}} passed",{count:Me})),Ae>0&&oe.push(b("workflow.summaryFailed","{{count}} failed",{count:Ae})),ee.length>0&&oe.push(b("workflow.summaryAdvisory","{{count}} advisory",{count:ee.length})),Ie>0&&oe.push(b("workflow.summarySkipped","{{count}} skipped",{count:Ie})),Pe>0&&oe.push(b("workflow.summaryRunning","{{count}} running",{count:Pe})),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:oe.join(b("workflow.summarySeparator"," · "))}),ee.length>0&&t.jsxs("div",{className:"workflow-polish-notes","data-testid":"workflow-polish-notes",children:[t.jsx("h4",{children:b("workflow.polishNotes","Polish notes")}),t.jsx("p",{children:b("workflow.advisoryExplanation","Advisory workflow steps flagged non-blocking improvements:")}),t.jsx("ul",{children:ee.map((re,_e)=>t.jsxs("li",{children:[t.jsxs("strong",{children:[re.workflowStepName,":"]})," ",re.output||b("workflow.needsReview","Needs follow-up review.")]},`advisory-${re.workflowStepId}-${_e}`))})]}),s.map((re,_e)=>{const fe=re.phase||"pre-merge",Xe=y[re.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${re.status}`,"data-testid":`workflow-result-item-${re.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[re.workflowStepName,id(fe,re.workflowStepId,"workflow-result-phase",b)]}),t.jsxs("div",{className:"workflow-result-badges",children:[re.verdict&&t.jsx("span",{className:`workflow-verdict-badge workflow-verdict-badge--${re.verdict}`,"data-testid":`workflow-verdict-badge-${re.workflowStepId}`,children:re.verdict}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${re.status}`,"data-testid":`workflow-result-badge-${re.workflowStepId}`,children:CB(re.status,b)})]})]}),re.notes&&re.status!=="pending"&&t.jsxs("div",{className:"workflow-result-notes","data-testid":`workflow-result-notes-${re.workflowStepId}`,children:[t.jsxs("span",{className:"workflow-result-notes-label",children:[b("workflow.notes","Notes:")," "]}),t.jsx(Di,{remarkPlugins:[Li],components:Fm,children:re.notes})]}),t.jsxs("div",{className:"workflow-result-meta",children:[re.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:[b("workflow.started","Started:")," ",EB(re.startedAt)]}),re.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:_B(re.startedAt,re.completedAt)})]}),re.status==="pending"&&re.startedAt?t.jsx(PB,{entries:q,startedAt:re.startedAt,stepId:re.workflowStepId,t:b}):re.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsxs("span",{className:"workflow-result-output-label",children:[b("workflow.output","Output:")," "]}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>qe(re.workflowStepId),"data-testid":`workflow-result-toggle-${re.workflowStepId}`,children:Xe?b("workflow.hideOutput","Hide output"):b("workflow.showOutput","Show output")}),!Xe&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${re.workflowStepId}`,children:MB(re.output)}),Xe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>pe(re.workflowStepId),"data-testid":`workflow-result-mode-toggle-${re.workflowStepId}`,title:(x[re.workflowStepId]??"markdown")==="markdown"?b("workflow.switchToPlain","Switch to plain text"):b("workflow.switchToMarkdown","Switch to markdown"),children:(x[re.workflowStepId]??"markdown")==="markdown"?b("workflow.markdown","Markdown"):b("workflow.plain","Plain")}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>te(re.workflowStepId),"data-testid":`workflow-result-expand-${re.workflowStepId}`,title:b("workflow.expandOutput","Expand output"),children:t.jsx(gu,{size:12})})]})]}),Xe&&t.jsx("div",{className:`workflow-result-output${(x[re.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${re.workflowStepId}`,children:(x[re.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Di,{remarkPlugins:[Li],components:Fm,children:re.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Hs(re.output??"")})})]}):null]},`${re.workflowStepId}-${_e}`)})]})},nt=o?t.jsx("button",{type:"button",className:"btn btn-sm workflow-results-edit-toggle",onClick:()=>R(Me=>!Me),"data-testid":"workflow-steps-edit-toggle","aria-label":$?b("workflow.doneEditingAriaLabel","Done editing workflow steps"):b("workflow.editAriaLabel","Edit workflow steps"),title:$?b("workflow.done","Done"):b("workflow.edit","Edit"),children:$?t.jsxs(t.Fragment,{children:[t.jsx(Qs,{size:14}),b("workflow.done","Done")]}):t.jsxs(t.Fragment,{children:[t.jsx(Si,{size:14}),b("workflow.edit","Edit")]})}):null,Nt=!i&&!X&&ye,Ft=o&&X,ze=m==="awaiting-user-input",it=m==="awaiting-cli-approval",Mt=async()=>{if(!(!w.trim()||j)){S(!0),A(null);try{await DA(e,w,l),g(""),E(!0)}catch(Me){A(Re(Me)||"Failed to resume task")}finally{S(!1)}}},Ht=async()=>{if(!j){S(!0),A(null);try{await IA(e,l),E(!0)}catch(Me){A(Re(Me)||"Failed to approve command")}finally{S(!1)}}};return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[ze&&t.jsxs("div",{className:"workflow-input-banner",role:"alert",children:[t.jsx("strong",{children:"Waiting for your input"}),t.jsx("span",{children:NB(p)}),C?t.jsx("span",{className:"workflow-input-resuming",children:"Resuming…"}):t.jsxs("div",{className:"workflow-input-actions",children:[t.jsx("textarea",{className:"workflow-input-textarea",rows:3,placeholder:"Type your reply…",value:w,onChange:Me=>g(Me.target.value),disabled:j}),t.jsx("button",{type:"button",className:"workflow-input-submit",onClick:Mt,disabled:j||!w.trim(),children:j?"Submitting…":"Submit & resume"}),J&&t.jsx("span",{className:"workflow-input-error",role:"alert",children:J})]})]}),it&&t.jsxs("div",{className:"workflow-input-banner workflow-input-banner--approval",role:"alert",children:[t.jsx("strong",{children:"Approve CLI command?"}),t.jsx("span",{className:"workflow-input-approval-warning",children:"This command will run in the task worktree. Approving trusts this exact command for future runs."}),t.jsx("pre",{className:"workflow-input-approval-command",children:t.jsx("code",{children:SB(p)})}),C?t.jsx("span",{className:"workflow-input-resuming",children:"Resuming…"}):t.jsxs("div",{className:"workflow-input-actions",children:[t.jsx("button",{type:"button",className:"workflow-input-submit",onClick:Ht,disabled:j,children:j?"Approving…":"Approve & run"}),t.jsx("span",{className:"workflow-input-keep-paused",children:"To reject, keep the task paused and do not approve."}),J&&t.jsx("span",{className:"workflow-input-error",role:"alert",children:J})]})]}),t.jsxs("section",{className:"card workflow-state-summary","data-testid":"workflow-state-summary",children:[t.jsx("div",{className:"workflow-state-summary__header",children:t.jsx("h4",{children:b("workflow.overview","Workflow overview")})}),t.jsxs("div",{className:"workflow-state-summary__grid",children:[t.jsxs("div",{className:"workflow-state-summary__item","data-testid":"workflow-state-summary-name",children:[t.jsx("span",{className:"workflow-state-summary__label",children:b("workflow.workflowName","Workflow")}),t.jsx("span",{className:"workflow-state-summary__value",children:ue})]}),t.jsxs("div",{className:"workflow-state-summary__item","data-testid":"workflow-state-summary-phase",children:[t.jsx("span",{className:"workflow-state-summary__label",children:b("workflow.executionPhase","Execution phase")}),t.jsx("span",{className:`workflow-result-badge ${je.badgeClass}`,"data-testid":`workflow-phase-badge-${je.testId}`,children:je.label})]}),t.jsxs("div",{className:"workflow-state-summary__item","data-testid":"workflow-state-summary-aggregate",children:[t.jsx("span",{className:"workflow-state-summary__label",children:b("workflow.aggregateResult","Aggregate result")}),t.jsx("span",{className:`workflow-result-badge ${$e.badgeClass}`,"data-testid":`workflow-aggregate-badge-${$e.testId}`,children:$e.label})]}),t.jsxs("div",{className:"workflow-state-summary__item","data-testid":"workflow-state-summary-count",children:[t.jsx("span",{className:"workflow-state-summary__label",children:b("workflow.stepProgress","Step count")}),t.jsx("span",{className:"workflow-state-summary__value",children:b("workflow.stepProgressValue","{{completed}} of {{total}} steps completed",{completed:Ce,total:s.length})})]})]})]}),t.jsxs("section",{className:"card workflow-disclosure","data-testid":"workflow-graph-section",children:[t.jsx("button",{type:"button",className:"workflow-disclosure__toggle",onClick:()=>B(Me=>!Me),"data-testid":"workflow-graph-toggle",children:t.jsxs("span",{className:"workflow-disclosure__title",children:[de?t.jsx(Ln,{"aria-hidden":!0}):t.jsx(ls,{"aria-hidden":!0}),b("workflow.graph","Workflow graph")]})}),de&&t.jsx("div",{className:"workflow-disclosure__content",children:L?T&&!We?t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-graph-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:b("workflow.loadingGraph","Loading workflow graph…")})]}):ke?t.jsx("div",{className:"workflow-graph-preview","data-testid":"workflow-graph-preview",children:t.jsx(qS,{children:t.jsx(WS,{nodes:ke.nodes,edges:ke.edges,nodeTypes:jB,fitView:!0,nodesDraggable:!1,nodesConnectable:!1,elementsSelectable:!1,zoomOnScroll:!1,panOnDrag:!1,preventScrolling:!1,attributionPosition:"bottom-left"})})}):t.jsx("p",{className:"workflow-disclosure__empty","data-testid":"workflow-graph-unavailable",children:b("workflow.graphUnavailable","Workflow graph unavailable")}):t.jsx("p",{className:"workflow-disclosure__empty","data-testid":"workflow-graph-empty",children:b("workflow.noWorkflowAssigned","No workflow assigned")})})]}),t.jsxs("section",{className:"card workflow-management","data-testid":"workflow-management-section",children:[t.jsxs("div",{className:"workflow-management__header",children:[t.jsx("h4",{children:b("workflow.workflowName","Workflow")}),o&&L&&u&&t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:u,"data-testid":"workflow-edit-button",children:[t.jsx(Si,{"aria-hidden":!0}),b("workflow.editWorkflow","Edit workflow")]})]}),t.jsx(aN,{value:L,onChange:Le,projectId:l,label:"Custom workflow",disabled:!o})]}),t.jsxs("section",{className:"card workflow-disclosure","data-testid":"workflow-model-settings-section",children:[t.jsx("button",{type:"button",className:"workflow-disclosure__toggle",onClick:()=>be(Me=>!Me),"data-testid":"workflow-model-settings-toggle",children:t.jsxs("span",{className:"workflow-disclosure__title",children:[le?t.jsx(Ln,{"aria-hidden":!0}):t.jsx(ls,{"aria-hidden":!0}),b("workflow.modelSettings","Model settings")]})}),le&&t.jsx("div",{className:"workflow-disclosure__content workflow-state-summary__grid","data-testid":"workflow-model-settings-content",children:[{key:"executor",label:b("models.targetLabels.executor","Executor"),value:Om(Ee),provider:Ee?.provider},{key:"reviewer",label:b("models.targetLabels.validator","Reviewer"),value:Om(Ze),provider:Ze?.provider},{key:"planning",label:b("models.targetLabels.planning","Planning"),value:Om(Ke),provider:Ke?.provider},{key:"thinking",label:b("workflow.thinkingLevel","Thinking level"),value:n?.thinkingLevel||"Default"}].map(Me=>t.jsxs("div",{className:"workflow-state-summary__item","data-testid":`workflow-model-setting-${Me.key}`,children:[t.jsx("span",{className:"workflow-state-summary__label",children:Me.label}),t.jsxs("span",{className:"workflow-state-summary__value workflow-model-value",children:[Me.provider?t.jsx(hs,{provider:Me.provider,size:"sm"}):null,Me.value]})]},Me.key))})]}),Nt?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:b("workflow.configuredSteps","Configured Workflow Steps")}),t.jsx("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:b("workflow.stepCount",{count:ot.length,defaultValue_one:"{{count}} step",defaultValue_other:"{{count}} steps"})})]}),nt]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:ot.map(Me=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${Me.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[t.jsx("span",{className:"workflow-configured-name-text",children:Me.name}),id(Me.phase,Me.id,"workflow-configured-phase",b)]}),t.jsx("p",{className:"workflow-configured-description",children:Me.description})]},Me.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:b("workflow.stepsExplanation","Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds.")}),dt()]}):t.jsxs(t.Fragment,{children:[Ft&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:b("workflow.steps","Workflow Steps")}),nt]}),Fe(),dt()]}),F&&(()=>{const Me=s.find(Ie=>Ie.workflowStepId===F);if(!Me)return null;const Ae=x[Me.workflowStepId]??"markdown",ee=Me.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:Ie=>{Ie.target===Ie.currentTarget&&me()},"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:Me.workflowStepName}),id(ee,Me.workflowStepId,"workflow-output-modal-phase",b)]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>pe(Me.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:Ae==="markdown"?b("workflow.switchToPlain","Switch to plain text"):b("workflow.switchToMarkdown","Switch to markdown"),children:Ae==="markdown"?b("workflow.markdown","Markdown"):b("workflow.plain","Plain")}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:me,"data-testid":"workflow-output-modal-close","aria-label":b("actions.close","Close"),children:t.jsx(Fn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${Ae==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:Ae==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(Di,{remarkPlugins:[Li],components:Fm,children:Me.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Hs(Me.output??"")})})})]})})})()]})}function DB(e,n){return e==="block"?n("routing.policyLabel.block","Block execution"):e==="fallback-local"?n("routing.policyLabel.fallback","Fall back to local"):n("routing.policyLabel.notConfigured","Not configured")}const LB=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function FB(e){return e!==void 0&&e!=="online"}function OB({task:e,settings:n,addToast:s,onTaskUpdated:i}){const{t:r}=st("app"),[o,l]=a.useState([]),[d,c]=a.useState(!1),[m,p]=a.useState(null),[h,u]=a.useState(e.nodeId??""),[f,b]=a.useState(!1),y=a.useRef(e.id);a.useEffect(()=>{y.current=e.id,u(e.nodeId??""),b(!1)},[e.id,e.nodeId]),a.useEffect(()=>{c(!0),p(null),Vd().then(D=>{l(D)}).catch(D=>{p(Re(D)||r("routing.errorLoadingNodes","Failed to load nodes"))}).finally(()=>{c(!1)})},[]);const v=a.useMemo(()=>new Map(o.map(D=>[D.id,D])),[o]),x=a.useMemo(()=>[...o].sort((D,_)=>D.name.localeCompare(_.name)),[o]),k=n,w=e.nodeId??k?.defaultNodeId??null,g=e.nodeId?r("routing.source.override","Per-task override"):k?.defaultNodeId?r("routing.source.projectDefault","Project default"):r("routing.source.noRouting","No routing"),j=w?v.get(w):void 0,S=j?`${j.name} (${j.type})`:w?`${w} (${r("routing.nodeUnavailable","node unavailable or unknown")})`:r("routing.localNoConfiguration","Local (no routing configured)"),C=e.column==="in-progress"||LB.has(e.status),E=C||f||d,F=a.useCallback(async D=>{if(D===h)return;const _=e.id,V=h;u(D),b(!0);try{const N=await si(_,{nodeId:D||null});if(y.current!==_)return;u(N.nodeId??""),i?.(N),s(D?r("routing.overrideUpdated","Node override updated"):r("routing.overrideCleared","Node override cleared"),"success")}catch(N){if(y.current!==_)return;u(V),s(Re(N)||r("routing.errorUpdatingOverride","Failed to update node override"),"error")}finally{y.current===_&&b(!1)}},[s,i,h,e.id]),M=a.useCallback(()=>{F("")},[F]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:r("routing.title","Task Routing")}),t.jsx("p",{className:"routing-tab__intro",children:r("routing.intro","View the effective execution node and control per-task node override.")}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:r("routing.summarySection","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:r("routing.effectiveNode","Effective node")}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(Wr,{status:j.status,compact:!0}):null,S,FB(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:r("routing.unhealthy","Unhealthy")}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:r("routing.source","Routing source")}),t.jsx("span",{className:"routing-summary-value",children:g})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:r("routing.unavailablePolicy","Unavailable-node policy")}),t.jsx("span",{className:"routing-summary-value",children:DB(k?.unavailableNodePolicy,r)})]})]}),C&&w?t.jsx("div",{className:"routing-tab__info-banner",children:r("routing.lockedWhileActive","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:r("routing.overrideSection","Node Override")}),C?t.jsx("div",{className:"routing-tab__warning-banner",children:r("routing.cannotChangeWhileActive","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:r("routing.selectLabel","Select execution node")}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:h,disabled:E,onChange:D=>{F(D.target.value)},children:[t.jsx("option",{value:"",children:r("routing.useProjectDefault","Use project default")}),x.map(D=>t.jsxs("option",{value:D.id,title:`Status: ${D.status}`,children:[D.name," (",D.type,") — ",D.status]},D.id))]}),m?t.jsx("div",{className:"routing-tab__error",children:m}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:[r("routing.overrideSetTo","Override set to"),": ",v.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:C||f,onClick:M,children:r("routing.clearOverride","Clear override")})]}):null]})]})}const $B=/^[a-zA-Z0-9_-]{1,64}$/,zB=200;function ix(e){return e?new Date(e).toLocaleString():""}function BB(e,n=zB){return e.length<=n?e:e.substring(0,n)+"…"}function UB({taskId:e,addToast:n,onTaskUpdated:s,projectId:i,canEdit:r=!1}){const{t:o}=st("app"),[l,d]=a.useState([]),[c,m]=a.useState(!0),[p,h]=a.useState(null),[u,f]=a.useState(""),[b,y]=a.useState(null),[v,x]=a.useState(""),[k,w]=a.useState(null),[g,j]=a.useState([]),[S,C]=a.useState(!1),[E,F]=a.useState(!1),[M,D]=a.useState(""),[_,V]=a.useState(""),[N,$]=a.useState(!1),[R,L]=a.useState(null),[O,J]=a.useState(null),[A,de]=a.useState(!1),B=a.useCallback(async()=>{try{const q=await OE(e,i);d(q)}catch(q){n(Re(q)||o("taskDocuments.failedToLoad","Failed to load documents"),"error")}finally{m(!1)}},[e,i,n]);a.useEffect(()=>{B()},[B]);async function P(q){p===q.key?(h(null),f(""),y(null),x(""),w(null),j([]),de(!1)):(h(q.key),f(q.content),y(null),x(""),w(null),j([]),de(!1))}async function Z(q){if(k===q)w(null),j([]);else{w(q),C(!0);try{const ce=await $E(e,q,i);j(ce)}catch(ce){n(Re(ce)||o("taskDocuments.failedToLoadRevisions","Failed to load revisions"),"error")}finally{C(!1)}}}function T(){p&&(y(p),x(u))}function ie(){y(null),x("")}async function le(){if(!(!b||!v.trim())){$(!0);try{await Ng(e,b,v,{},i),y(null),x(""),await B();const q=l.find(ce=>ce.key===b);q&&f(q.content),n(o("taskDocuments.saved","Document saved"),"success")}catch(q){n(Re(q)||o("taskDocuments.failedToSave","Failed to save document"),"error")}finally{$(!1)}}}async function be(){const q=M.trim(),ce=_.trim();if(!q){n(o("taskDocuments.keyRequired","Document key is required"),"error");return}if(!$B.test(q)){n(o("taskDocuments.invalidKeyFormat","Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores."),"error");return}if(!ce){n(o("taskDocuments.contentRequired","Content is required"),"error");return}$(!0);try{await Ng(e,q,ce,{},i),F(!1),D(""),V(""),await B(),n(o("taskDocuments.created","Document created"),"success")}catch(De){n(Re(De)||o("taskDocuments.failedToCreate","Failed to create document"),"error")}finally{$(!1)}}async function Le(q){L(q);try{await zE(e,q,i),J(null),L(null),p===q&&(h(null),f("")),k===q&&(w(null),j([])),await B(),n(o("taskDocuments.deleted","Document deleted"),"success")}catch(ce){n(Re(ce)||o("taskDocuments.failedToDelete","Failed to delete document"),"error")}finally{L(null)}}function xe(q){f(q.content),y(null),x("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:o("taskDocuments.heading","Documents")}),t.jsx("div",{className:"detail-log-empty",children:o("taskDocuments.loading","Loading documents…")})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:o("taskDocuments.heading","Documents")}),E&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:o("taskDocuments.newDocumentTitle","New Document")}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:o("taskDocuments.keyLabel","Key")}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:M,onChange:q=>D(q.target.value),placeholder:o("taskDocuments.keyPlaceholder","e.g., plan, notes, research"),disabled:N}),t.jsx("span",{className:"form-hint",children:o("taskDocuments.keyHint","Alphanumeric, hyphens, underscores (1-64 chars)")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:o("taskDocuments.contentLabel","Content")}),t.jsx("textarea",{id:"doc-content",value:_,onChange:q=>V(q.target.value),rows:6,placeholder:o("taskDocuments.contentPlaceholder","Enter document content…"),disabled:N})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{F(!1),D(""),V("")},disabled:N,children:o("taskDocuments.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void be(),disabled:N||!M.trim()||!_.trim(),children:N?o("taskDocuments.creating","Creating…"):o("taskDocuments.create","Create")})]})]}),l.length===0&&!E?t.jsx("div",{className:"detail-log-empty",children:o("taskDocuments.noDocuments","No documents yet.")}):t.jsx("div",{className:"task-documents-list",children:l.map(q=>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(Hr,{size:14}),t.jsx("span",{className:"task-document-key",children:q.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",q.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:q.author}),t.jsx("span",{className:"task-document-timestamp",children:ix(q.updatedAt||q.createdAt)})]})]}),p===q.key&&b!==q.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:()=>de(ce=>!ce),"aria-label":A?o("taskDocuments.switchToPlainText","Switch to plain text"):o("taskDocuments.switchToMarkdown","Switch to markdown"),"aria-pressed":A,title:A?o("taskDocuments.switchToPlainText","Switch to plain text"):o("taskDocuments.switchToMarkdown","Switch to markdown"),children:A?o("taskDocuments.modeMarkdown","Markdown"):o("taskDocuments.modePlain","Plain")})}),t.jsx("div",{className:"task-document-content",children:A?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(Di,{remarkPlugins:[Li],children:u})})}):t.jsx("pre",{className:"task-document-content-text",children:u})}),k===q.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:o("taskDocuments.revisionHistory","Revision History")}),S?t.jsx("div",{className:"detail-log-empty",children:o("taskDocuments.loadingRevisions","Loading…")}):g.length<=1?t.jsx("div",{className:"detail-log-empty",children:o("taskDocuments.noPreviousRevisions","No previous revisions.")}):t.jsx("div",{className:"task-document-revision-list",children:g.filter(ce=>ce.revision<q.revision).sort((ce,De)=>De.revision-ce.revision).map(ce=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>xe(ce),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",ce.revision]}),t.jsx("span",{className:"revision-author",children:ce.author}),t.jsx("span",{className:"revision-timestamp",children:ix(ce.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:BB(ce.content,100)})]},ce.id))})]})]}),b===q.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:v,onChange:ce=>x(ce.target.value),rows:10,disabled:N}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:ie,disabled:N,children:o("taskDocuments.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void le(),disabled:N||!v.trim(),children:N?o("taskDocuments.saving","Saving…"):o("taskDocuments.save","Save")})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void P(q),children:p===q.key?t.jsxs(t.Fragment,{children:[t.jsx(ra,{size:14})," ",o("taskDocuments.collapse","Collapse")]}):t.jsxs(t.Fragment,{children:[t.jsx(Ln,{size:14})," ",o("taskDocuments.expand","Expand")]})}),p===q.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void Z(q.key),children:[t.jsx(Ur,{size:14})," ",o("taskDocuments.history","History")]}),r&&b!==q.key&&t.jsx("button",{className:"btn btn-sm",onClick:T,children:o("taskDocuments.edit","Edit")}),r&&(O===q.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:o("taskDocuments.deleteConfirm","Delete?")}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void Le(q.key),disabled:R===q.key,children:R===q.key?"…":o("taskDocuments.yes","Yes")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>J(null),disabled:R===q.key,children:o("taskDocuments.no","No")})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>J(q.key),children:t.jsx(as,{size:14})}))]})]})]},q.key))}),r&&!E&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>F(!0),children:[t.jsx(ys,{size:14})," ",o("taskDocuments.newDocumentButton","New Document")]})]})}function rr(e){return e.toLocaleString()}function HB(e){return`${(e*100).toFixed(1)}%`}function $m(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function wo(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),i=Math.round(n%60);return`${s}m ${i}s`}function VB(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 d;if(o.completedAt){const c=new Date(o.completedAt).getTime();if(Number.isNaN(c)||c<l)return null;d=c}else d=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:d-l}}).filter(o=>o!==null),i=_w(e,n)??0,r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:i,longestStep:r}}function qB({tokenUsage:e,loading:n,task:s}){const{t:i}=st("app"),r=Date.now(),o=Sw(s?.log??[]),l=o.filter(k=>typeof k.durationMs=="number"),d=l.reduce((k,w)=>k+(w.durationMs??0),0),c=Cw(s?.log)??0,m=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(d,c),p=l.reduce((k,w)=>!k||(w.durationMs??0)>(k.durationMs??0)?w:k,void 0),h=VB(s?.workflowStepResults??[]),u=s?Mw(s,r):null,f=Ew(s?.executionStartedAt,s?.executionCompletedAt,r),b=uI(s?.firstExecutionAt,s?.executionCompletedAt,r),y=u??f??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:m+h.totalDurationMs),v=b!=null&&b!==y,x=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":i("taskDetail.executionStatsAria","Task execution statistics"),children:[t.jsx("h4",{children:i("taskDetail.executionAndTokenStats","Execution & Token Stats")}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:i("taskDetail.executionTiming","Execution Timing")}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":i("taskDetail.executionTimingMetricsAria","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:i("taskDetail.timingEvents","Timing events")}),t.jsx("span",{className:"task-token-stats-panel__value",children:o.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.timedDuration","Timed duration")}),t.jsx("span",{className:"task-token-stats-panel__value",children:wo(m)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.workflowTimedSteps","Workflow timed steps")}),t.jsx("span",{className:"task-token-stats-panel__value",children:h.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.workflowRuntime","Workflow runtime")}),t.jsx("span",{className:"task-token-stats-panel__value",children:wo(h.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.totalExecutionTime","Total execution time")}),t.jsx("span",{className:"task-token-stats-panel__value",children:wo(y)})]}),v?t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.wallClockSinceFirst","Wall-clock since first execution")}),t.jsx("span",{className:"task-token-stats-panel__value",children:wo(b)})]}):null]}),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:i("taskDetail.longestTimingEvent","Longest timing event")}),t.jsx("dd",{children:p?.durationMs?`${p.summary} (${wo(p.durationMs)})`:i("taskDetail.noTimedEvents","No timed events recorded yet.")})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:i("taskDetail.longestWorkflowStep","Longest workflow step")}),t.jsx("dd",{children:h.longestStep?`${h.longestStep.name} (${wo(h.longestStep.durationMs)})`:i("taskDetail.noWorkflowStepTimings","No completed workflow step timings yet.")})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:i("taskDetail.executionDetails","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:i("taskDetail.executionMode","Execution mode")}),t.jsx("dd",{children:s?.executionMode==="fast"?i("taskDetail.executionModeFast","Fast"):i("taskDetail.executionModeStandard","Standard")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.runtimeStatus","Runtime status")}),t.jsx("dd",{children:s?.status??i("taskDetail.notSet","Not set")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.paused","Paused")}),t.jsx("dd",{children:s?.paused?i("taskDetail.yes","Yes"):i("taskDetail.no","No")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.stepProgress","Step progress")}),t.jsx("dd",{children:x>0?`${Math.min((s?.currentStep??0)+1,x)} / ${x}`:i("taskDetail.noSteps","No steps")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.retriesLabel","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:i("taskDetail.recoveryState","Recovery state")}),t.jsx("dd",{children:s?.nextRecoveryAt?i("taskDetail.nextRecoveryAt","Next recovery at {{time}}",{time:$m(s.nextRecoveryAt)}):i("taskDetail.noScheduledRecovery","No scheduled recovery")})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.selfHealCounters","Self-heal counters")}),t.jsx("dd",{children:i("taskDetail.selfHealValues","stuck kills: {{stuckKills}}, post-review fixes: {{postReviewFixes}}",{stuckKills:s?.stuckKillCount??0,postReviewFixes:s?.postReviewFixCount??0})})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:i("taskDetail.runtimeLinks","Runtime links")}),t.jsx("dd",{children:[s?.assignedAgentId?i("taskDetail.agentLink","agent {{id}}",{id:s.assignedAgentId}):null,s?.checkedOutBy?i("taskDetail.checkoutLink","checkout {{id}}",{id:s.checkedOutBy}):null,s?.blockedBy?i("taskDetail.blockedByLink","blocked by {{id}}",{id:s.blockedBy}):null,s?.sessionFile?i("taskDetail.hasSession","has session"):null].filter(Boolean).join(", ")||i("taskDetail.noRuntimeLinks","No runtime links")})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:i("taskDetail.tokenUsage","Token Usage")}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:i("taskDetail.loadingTokenStats","Loading token statistics…")}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":i("taskDetail.tokenTotalsAria","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:i("taskDetail.inputTokens","Input")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.outputTokens","Output")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.cacheRead","Cache read")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.cacheWrite","Cache write")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.cacheWriteTokens??0)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:i("taskDetail.totalTokens","Total")}),t.jsx("span",{className:"task-token-stats-panel__value",children:rr(e.totalTokens)})]})]}),t.jsxs("div",{className:"task-token-stats-panel__cache-ratio",children:[t.jsx("span",{className:"task-token-stats-panel__cache-ratio-label",children:i("taskDetail.cacheHitRatio","Cache hit ratio:")})," ",t.jsx("span",{className:"task-token-stats-panel__cache-ratio-value",children:e.inputTokens+e.cachedTokens>0?HB(e.cachedTokens/(e.inputTokens+e.cachedTokens)):"—"})]}),t.jsx("div",{className:"task-token-stats-panel__cache-breakdown",children:i("taskDetail.cacheBreakdown","(read {{read}} / write {{write}} / input {{input}})",{read:rr(e.cachedTokens),write:rr(e.cacheWriteTokens??0),input:rr(e.inputTokens)})}),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:i("taskDetail.firstUsed","First used")}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:$m(e.firstUsedAt)})})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:i("taskDetail.lastUsed","Last used")}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.lastUsedAt,children:$m(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:i("taskDetail.noTokenUsage","No token usage recorded for this task yet.")})]})]})}function WB({groupId:e,projectId:n}){const{t:s}=st("app"),[i,r]=a.useState(null),[o,l]=a.useState(!0),[d,c]=a.useState(null),[m,p]=a.useState(!1),[h,u]=a.useState(!1),[f,b]=a.useState(!1),y=a.useCallback(async()=>{try{const j=await Vk(e,n);r(j.group),c(null)}catch(j){const S=j instanceof Error?j.message:s("branchGroup.loadError","Failed to load branch group");c(S)}finally{l(!1)}},[e,n,s]);a.useEffect(()=>{l(!0),y()},[y]),a.useEffect(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return;const j=window.matchMedia("(max-width: 768px)"),S=E=>{b(E)};S(j.matches);const C=E=>{S(E.matches)};return typeof j.addEventListener=="function"?(j.addEventListener("change",C),()=>j.removeEventListener("change",C)):(j.addListener(C),()=>j.removeListener(C))},[]),a.useEffect(()=>{const j=n?`?projectId=${encodeURIComponent(n)}`:"";return li(`/api/events${j}`,{events:{"task:updated":()=>{y()}},onReconnect:()=>{y()}})},[y,n]);const v=a.useMemo(()=>i?s("branchGroup.completionText","{{landed}} of {{total}} members finished",{landed:i.completion.landed,total:i.completion.total}):"",[i,s]),x=a.useCallback(async()=>{p(!0);try{await qk(e,n),await y()}finally{p(!1)}},[e,y,n]),k=a.useCallback(async()=>{u(!0);try{await Wk(e,n),await y()}finally{u(!1)}},[e,y,n]);if(o)return t.jsxs("div",{className:"card branch-group-card",children:[t.jsx(Et,{className:"spin",size:14})," ",s("branchGroup.loading","Loading branch group…")]});if(d||!i)return t.jsx("div",{className:"card branch-group-card branch-group-card-error",children:d??s("branchGroup.unavailable","Branch group unavailable")});const w=i.completion.total>0?i.completion.landed/i.completion.total*100:0,g=i.completion.complete;return t.jsxs("section",{className:"card branch-group-card",children:[t.jsxs("header",{className:"branch-group-card-header",children:[t.jsxs("div",{className:"branch-group-card-title",children:[t.jsx(ui,{size:14}),t.jsx("strong",{children:i.branchName})]}),t.jsxs("div",{className:"branch-group-card-header-meta",children:[t.jsx("span",{className:"badge branch-group-card-badge",children:s("branchGroup.groupLabel","Group {{id}}",{id:i.id})}),t.jsx("button",{type:"button",className:"btn btn-icon",onClick:()=>b(j=>!j),"aria-expanded":!f,"aria-label":f?s("branchGroup.expandLabel","Expand branch group"):s("branchGroup.collapseLabel","Collapse branch group"),children:f?t.jsx(ls,{size:14}):t.jsx(Ln,{size:14})})]})]}),t.jsx("div",{className:"branch-group-card-progress-text",children:v}),t.jsx("div",{className:"branch-group-card-progress",role:"progressbar","aria-valuenow":i.completion.landed,"aria-valuemin":0,"aria-valuemax":i.completion.total,children:t.jsx("span",{className:"branch-group-card-progress-fill",style:{width:`${w}%`}})}),!f&&t.jsx("ul",{className:"branch-group-card-members",children:i.members.map(j=>t.jsxs("li",{className:"branch-group-card-member",children:[t.jsx("span",{className:`status-dot ${j.landed?"status-dot--online":"status-dot--pending"}`}),t.jsxs("span",{className:"branch-group-card-member-title",children:[j.taskId," · ",j.title]}),t.jsx("span",{className:"branch-group-card-member-status",children:j.landed?t.jsx(gc,{size:14}):t.jsx(yk,{size:14})})]},j.taskId))}),!f&&(i.prState==="merged"||i.prState==="closed")&&t.jsxs("div",{className:"branch-group-card-actions",children:[t.jsx("span",{className:"badge",children:i.prState==="merged"?"Group PR merged":"Group PR closed"}),i.prUrl&&t.jsxs("a",{className:"btn",href:i.prUrl,target:"_blank",rel:"noreferrer",children:[t.jsx(ai,{size:14})," PR #",i.prNumber??"—",t.jsx(Vo,{size:12})]})]}),!f&&(g||i.prState==="open")&&i.prState!=="merged"&&i.prState!=="closed"&&t.jsxs("div",{className:"branch-group-card-actions",children:[i.prUrl&&t.jsxs("a",{className:"btn",href:i.prUrl,target:"_blank",rel:"noreferrer",children:[t.jsx(ai,{size:14})," PR #",i.prNumber??"—",t.jsx(Vo,{size:12})]}),g&&(i.autoMerge?t.jsx("span",{className:"badge",children:s("branchGroup.autoMergeEnabled","Auto-merge enabled")}):i.prState==="none"?t.jsxs("button",{type:"button",className:"btn",onClick:()=>void x(),disabled:m,children:[m?t.jsx(Et,{size:14,className:"spin"}):t.jsx(ai,{size:14}),s("branchGroup.openPr","Open PR")]}):t.jsxs("button",{type:"button",className:"btn",onClick:()=>void x(),disabled:m,children:[m?t.jsx(Et,{size:14,className:"spin"}):t.jsx(ai,{size:14}),s("branchGroup.mergeIntoMain","Merge group into main")]})),i.prState==="open"&&t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void k(),disabled:h,children:[h?t.jsx(Et,{size:14,className:"spin"}):null,s("branchGroup.abandonGroup","Abandon group")]})]})]})}const gN=/^In-review stall surfaced \[([^\]]+)\]/;function GB(e,n){if(!e.log?.length)return;const s=[...e.log].reverse();for(const[i,r]of s.entries()){const o=r.action.match(gN);if(!(!o||o[1]!==n))return{entry:r,reversedIndex:i,code:n}}}const Ef=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),ax=/^Stale paused review surfaced \[([^\]]+)\]/,rx={p:({children:e,...n})=>t.jsx("p",{...n,children:hi(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:hi(e)}),code:({children:e,...n})=>{const s=typeof e=="string"?e:gr.Children.toArray(e).join(""),i=Hs(s);return i.length===1&&typeof i[0]=="string"?t.jsx("code",{...n,children:e}):t.jsx("code",{...n,children:i})}};function KB(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const i=s.text.match(/^Executor using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function JB(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const i=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function ox(e){return(e.title??"").trim().length>0?!0:!!(e.description??"").split(/\r?\n/).map(s=>s.trim()).find(s=>s.length>0)}function bN(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 i=typeof n?.modelProvider=="string"?n.modelProvider.trim():"",r=typeof n?.modelId=="string"?n.modelId.trim():"";return{provider:i||void 0,modelId:r||void 0}}function YB(e,n,s,i){const r=KB(n);if(r)return r;if(Ef.has(e.status??"")||e.column==="in-progress"){const o=bN(s);if(o.provider&&o.modelId)return o}return Ap(e,i)}function XB(e,n,s,i){const r=JB(n);if(r)return r;if(Ef.has(e.status??"")||e.column==="in-progress"){const o=bN(s);if(o.provider&&o.modelId)return o}return Tp(e,i)}function QB(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const i=s.text.match(/^Triage using model: (.+?)\/(.+)$/);i&&(n={provider:i[1],modelId:i[2]})}return n}function ZB(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const i=QB(n);return i||Rp(e,s)}function e6(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--in-progress)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function jo(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function t6(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function Tl(e){const n=Math.max(1,Math.floor(e/6e4)),s=Math.floor(n/1440),i=Math.floor(n%1440/60),r=n%60;return s>0?`${s}d ${i}h`:i>0?`${i}h ${r}m`:`${r}m`}const n6=a.lazy(()=>ln(()=>import("./SessionTerminal-DaTXNT3A.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8])).then(e=>({default:e.SessionTerminal})));function s6(e,n={}){return e?e.agentState==="starting"||e.agentState==="ready"||e.agentState==="busy"||e.agentState==="waitingOnInput"?{kind:"live",readOnly:!!n.oneShot,mode:"live",showConfirmAdvance:!!n.genericIdle}:e.agentState==="done"?{kind:"replay",mode:"idle"}:{kind:"replay",mode:"ended"}:{kind:"hidden"}}function zm(e,n){return e.length>n?e.slice(0,n)+"…":e}function lx(e=[],n=[]){return e.length===n.length&&e.every((s,i)=>s===n[i])}function Bm(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Um(e){return e.trim()}function i6(e){const n=e.trim();return n.length>0?n:void 0}function Ua(e){return typeof e=="string"&&xr.includes(e)?e:yi}function Ha(e){return e==="fast"?"fast":"standard"}function a6(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function r6(e){const n=e.match(/^https:\/\/github\.com\/([^/]+)\/([^/]+)\/(issues|pull)\/(\d+)(?:$|[/?#])/);if(!n)return null;const[,s,i,,r]=n;return{label:`${s}/${i}#${r}`,href:e}}function o6(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 l6=a.lazy(()=>ln(()=>import("./AgentDetailView-krC0B2O0.js"),__vite__mapDeps([9,1,4,10,11,12,13,5,6,2,3,7,14])).then(e=>({default:e.AgentDetailView})));function c6(e,n={}){const s=n.t;switch(e.sourceType){case"dashboard_ui":return{label:s?s("taskDetail.provenance.dashboard","Dashboard"):"Dashboard"};case"quick_chat":return{label:s?s("taskDetail.provenance.quickChat","Quick Chat"):"Quick Chat"};case"chat_session":return{label:s?s("taskDetail.provenance.chatSession","Chat Session"):"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??(s?s("taskDetail.provenance.agent","agent"):"agent"),sourceAgentId:e.sourceAgentId};case"automation":return{label:s?s("taskDetail.provenance.automation","Automation"):"Automation"};case"cron":return{label:s?s("taskDetail.provenance.scheduledTask","Scheduled Task"):"Scheduled Task"};case"workflow_step":return{label:s?s("taskDetail.provenance.workflowStep","Workflow Step"):"Workflow Step"};case"github_import":{const i=a6(e.sourceMetadata),r=i?r6(i):null;return{label:s?s("taskDetail.provenance.githubImport","GitHub Import"):"GitHub Import",contextInfo:i?r?.label??(s?s("taskDetail.provenance.openIssue","Open issue"):"Open issue"):void 0,contextHref:i,contextInfoFull:i}}case"research":{const i=o6(e.sourceMetadata);return{label:s?s("taskDetail.provenance.research","Research"):"Research",contextInfo:i,contextInfoFull:i}}case"task_refine":return{label:s?s("taskDetail.provenance.refinement","Refinement"):"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:s?s("taskDetail.provenance.duplicate","Duplicate"):"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:s?s("taskDetail.provenance.cli","CLI"):"CLI"};case"api":return{label:s?s("taskDetail.provenance.api","API"):"API"};case"recovery":return{label:s?s("taskDetail.provenance.recovery","Recovery"):"Recovery"};case"unknown":default:return null}}const Hm=200,d6=new Set(["triage","todo"]),u6=new Set(["triage","todo","in-progress","in-review"]);function vN({task:e,projectId:n,tasks:s=[],onOpenDetail:i,onMoveTask:r,onDeleteTask:o,onArchiveTask:l,onMergeTask:d,onRetryTask:c,onResetTask:m,onDuplicateTask:p,onTaskUpdated:h,addToast:u,prAuthAvailable:f,onOpenWorkflowEditor:b,initialTab:y="definition",mobileHeaderMode:v="close",embedded:x=!1,onRequestClose:k,workflowFieldDefs:w}){const{t:g}=st("app"),j=Xp(),[S,C]=a.useState(y==="retries"?"definition":y),[E,F]=a.useState(null),[M,D]=a.useState(()=>"prompt"in e?e:null),[_,V]=a.useState(()=>!("prompt"in e));a.useEffect(()=>{if("prompt"in e){D(e),V(!1);return}let H=!1;return V(!0),D(null),pr(e.id,n).then(we=>{H||(D(we),V(!1))}).catch(()=>{H||V(!1)}),()=>{H=!0}},[e.id,n]);const N=M?{...M,...e,prompt:M.prompt,log:M.log,githubTracking:e.githubTracking??M.githubTracking}:{...e,prompt:""},$=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,R=typeof N.sourceMetadata?.nearDuplicateOf=="string"?N.sourceMetadata.nearDuplicateOf:null,L=!!R&&N.sourceMetadata?.nearDuplicateDismissed!==!0&&e.column!=="archived"&&e.column!=="done",[O,J]=a.useState(null),[A,de]=a.useState(null),B=c6(N,{sourceAgentName:O?.name,t:g});a.useEffect(()=>{C(y==="retries"?"definition":y),y==="retries"&&rs(!0)},[y]),a.useEffect(()=>{S==="pr"&&e.column!=="in-review"&&C("definition")},[S,e.column]),a.useEffect(()=>{be(e.column==="triage")},[e.column,e.id]);const[P,Z]=a.useState("activity"),[T,ie]=a.useState(null),[le,be]=a.useState(()=>e.column==="triage"),[Le,xe]=a.useState(e.attachments||[]),[q,ce]=a.useState(!1),[De,He]=a.useState(e.dependencies||[]),[qe,pe]=a.useState(!1),[te,me]=a.useState(""),[se,z]=a.useState(null),[Y,he]=a.useState([]),[X,ye]=a.useState(!1),[ot,ue]=a.useState(!1),[je,$e]=a.useState(!1),[Ce,We]=a.useState(!1),[ke,Ee]=a.useState(!1),[Ze,Ke]=a.useState(N.prompt||""),[dt,Fe]=a.useState(""),[nt,Nt]=a.useState(!1),[Ft,ze]=a.useState(!1),[it,Mt]=a.useState(w!==void 0?w??null:null),[Ht,Me]=a.useState(e.customFields??{}),[Ae,ee]=a.useState(null);a.useEffect(()=>{Me(e.customFields??{})},[e.id,e.customFields]),a.useEffect(()=>{if(w!==void 0){Mt(w??null);return}let H=!1;return Op(n).then(we=>{if(H)return;const lt=we.taskWorkflowIds[e.id]??we.defaultWorkflowId,wt=we.workflows.find(jn=>jn.id===lt);Mt(wt?.fields??null)}).catch(()=>{H||Mt(null)}),()=>{H=!0}},[e.id,n,w]);const Ie=a.useCallback(async H=>{ee(null);try{const we=await kE(e.id,H,n);Me(we.customFields??{}),h?.(we)}catch(we){if(we instanceof Ka&&we.details&&typeof we.details.fieldId=="string"){ee({code:we.details.code??"type-mismatch",fieldId:we.details.fieldId,detail:typeof we.details.detail=="string"?we.details.detail:we.message});return}u(Re(we)||g("taskFields.saveFailed","Failed to save field"),"error")}},[e.id,n,h,u,g]);a.useEffect(()=>{if(S!=="logs"||P!=="activity"){ie(null);return}if(!T)return;const H=Te.current?.querySelector('[data-stall-highlight="true"]');H&&typeof H.scrollIntoView=="function"&&H.scrollIntoView({block:"nearest",behavior:"smooth"})},[S,P,T]);const[Pe,oe]=a.useState(""),[re,_e]=a.useState(!1),[fe,Xe]=a.useState(!1),[kt,Rt]=a.useState(e.title||""),[Vt,Pt]=a.useState(e.description||""),[bt,pt]=a.useState(e.dependencies||[]),[ft,_t]=a.useState(e.branch??""),[Yt,on]=a.useState(e.baseBranch??""),[An,vn]=a.useState(""),[Qt,sn]=a.useState(""),[mn,Kt]=a.useState(""),[fn,$n]=a.useState(""),[On,xn]=a.useState("default"),[Vn,Rn]=a.useState(void 0),[Pn,zn]=a.useState(yi),[Nn,dn]=a.useState(e.nodeId),[Tt,Yn]=a.useState(Ha(e.executionMode)),[cn,Bn]=a.useState(""),[kn,pn]=a.useState(e.enabledWorkflowSteps||[]),[un,At]=a.useState(e.sourceIssue?.provider??""),[an,Wn]=a.useState(e.sourceIssue?.repository??""),[Xn,G]=a.useState(e.sourceIssue?.externalIssueId??""),[Oe,yt]=a.useState(e.sourceIssue?.url??""),[Gt,Sn]=a.useState([]),[Un,bn]=a.useState(!1),[gn,ps]=a.useState(!1),[Ne,ae]=a.useState(Ua(e.priority)),[Se,ut]=a.useState(!1),[It,ht]=a.useState(Ha(e.executionMode)),[et,Ut]=a.useState(!1),[$t,rn]=a.useState(e.noCommitsExpected===!0),[Cn,ve]=a.useState(!1),at=a.useRef(!1),Ge=a.useRef(e.id),[tt,gt]=a.useState(!1),[St,Xt]=a.useState(!1),[ss,Ts]=a.useState(!1),[Ls,rs]=a.useState(y==="retries"),[ei,Mi]=a.useState(!1),[ti,mi]=a.useState(e.githubTracking?.repoOverride??""),[zs,Qn]=a.useState(null),[Zt,Q]=a.useState(null),[Qe,vt]=a.useState(!1),[xt,zt]=a.useState(!1),[Wt,hn]=a.useState(!1),[In,gs]=a.useState(null),ks=a.useRef(null),Te=a.useRef(null),U=a.useRef(null),ge=a.useRef(null),{getSlotsForId:rt}=uw(n),Dt=rt("task-detail-tab").map((H,we)=>({entry:H,tabId:`plugin-${H.pluginId}-${we}`})),en=typeof S=="string"&&S.startsWith("plugin-")?Dt.find(H=>H.tabId===S)??null:null,tn=E?.adapterId!=null&&(E?.autonomyPosture?.purpose==="planning"||E?.autonomyPosture?.purpose==="validator"||E?.autonomyPosture?.readOnly===!0),Dn=E?.autonomyPosture?.genericIdle===!0,_n=a.useMemo(()=>s6(E,{oneShot:tn,genericIdle:Dn}),[E,tn,Dn]),is=_n.kind!=="hidden",Ss=a.useMemo(()=>{if(!E)return;const H=E.autonomyPosture??{},we=Array.isArray(H.elevatedFlags)?H.elevatedFlags:void 0;return{adapterName:H.adapterName??E.adapterId,mode:H.mode??(H.autoApprove?"auto-approve":void 0),elevated:H.elevated===!0,elevatedFlags:we,resolved:Array.isArray(H.resolved)?H.resolved:void 0}},[E]),Rs=a.useCallback(async H=>{if(E)try{await I(`/cli-sessions/${encodeURIComponent(E.id)}/confirm-advance`,{method:"POST",body:JSON.stringify({decision:H,...n?{projectId:n}:{}})})}catch{}},[E,n]);a.useEffect(()=>{S==="terminal"&&!is&&C("definition")},[S,is]),a.useEffect(()=>(at.current=!0,()=>{at.current=!1}),[]),a.useEffect(()=>{Ge.current=e.id},[e.id]);const[ne,Ue]=a.useState(void 0),[Je,qt]=a.useState(null),[En,yn]=a.useState([]),[os,fs]=a.useState(!1),[ws,js]=a.useState(e.enabledWorkflowSteps||[]),Vs=e.column==="in-progress"||Ef.has(e.status);a.useEffect(()=>{Rt(e.title||""),Pt(e.description||""),_t(e.branch??""),on(e.baseBranch??""),At(e.sourceIssue?.provider??""),Wn(e.sourceIssue?.repository??""),G(e.sourceIssue?.externalIssueId??""),yt(e.sourceIssue?.url??""),Yn(Ha(e.executionMode)),Ts(!1),Mi(!1),mi(N.githubTracking?.repoOverride??""),Qn(null),Q(null),Xe(!1),gs(null),zt(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,N.githubTracking]),a.useEffect(()=>{js(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),a.useEffect(()=>{ae(Ua(e.priority))},[e.id,e.priority]),a.useEffect(()=>{ht(Ha(e.executionMode))},[e.id,e.executionMode]),a.useEffect(()=>{rn(e.noCommitsExpected===!0)},[e.id,e.noCommitsExpected]),a.useEffect(()=>{zs!==null&&N.githubTracking?.enabled===!0===zs&&Qn(null)},[zs,N.githubTracking?.enabled]),a.useEffect(()=>{let H=!1;return yu(n).then(we=>{H||Ue(we)}).catch(()=>{}),Ja().then(we=>{H||qt(we)}).catch(()=>{H||qt(null)}),()=>{H=!0}},[n]),a.useEffect(()=>{if(S!=="workflow")return;let H=!1;return fs(!0),TA(e.id,n).then(we=>{H||yn(we)}).catch(we=>{H||u(g("taskDetail.workflow.loadFailed","Failed to load workflow results: {{error}}",{error:Re(we)}),"error")}).finally(()=>{H||fs(!1)}),()=>{H=!0}},[S,e.id,n,u]),a.useEffect(()=>{if(S!=="workflow")return;const H=n?`?projectId=${encodeURIComponent(n)}`:"",we=lt=>{try{const wt=JSON.parse(lt.data);wt.id===e.id&&Array.isArray(wt.workflowStepResults)&&yn(wt.workflowStepResults)}catch{}};return li(`/api/events${H}`,{events:{"task:updated":we}})},[S,e.id,n]),a.useEffect(()=>{let H=!1;const we=new URLSearchParams({taskId:e.id});return n&&we.set("projectId",n),I(`/cli-sessions?${we.toString()}`).then(lt=>{if(H)return;const wt=lt.sessions??[];F(wt.length>0?wt[wt.length-1]:null)}).catch(()=>{H||F(null)}),()=>{H=!0}},[e.id,n]),a.useEffect(()=>{const H=n?`?projectId=${encodeURIComponent(n)}`:"",we=lt=>{try{const wt=JSON.parse(lt.data);if(wt.taskId!==e.id)return;F(jn=>{if((!jn||jn.id!==wt.sessionId)&&!jn)return jn;const Js={...jn};return wt.state==="starting"||wt.state==="ready"||wt.state==="busy"||wt.state==="waitingOnInput"||wt.state==="done"||wt.state==="dead"||wt.state==="needsAttention"?Js.agentState=wt.state:(wt.state==="idle"||wt.state==="resuming")&&(Js.agentState="busy"),wt.terminationReason!==void 0&&(Js.terminationReason=wt.terminationReason??null),Js})}catch{}};return li(`/api/events${H}`,{events:{"cli:session:state":we}})},[e.id,n]),a.useEffect(()=>{qe||me("")},[qe]),a.useEffect(()=>{if(!e.assignedAgentId){z(null);return}const H=Y.find(lt=>lt.id===e.assignedAgentId);if(H){z(H);return}let we=!1;return Ph(e.assignedAgentId,n).then(lt=>{we||z(lt)}).catch(()=>{we||z(null)}),()=>{we=!0}},[e.assignedAgentId,n,Y]),a.useEffect(()=>{if(!e.sourceAgentId){J(null);return}const H=Y.find(lt=>lt.id===e.sourceAgentId);if(H){J(H);return}let we=!1;return Promise.resolve(Ph(e.sourceAgentId,n)).then(lt=>{we||J(lt??null)}).catch(()=>{we||J(null)}),()=>{we=!0}},[e.sourceAgentId,n,Y]),a.useEffect(()=>{ye(!1)},[e.id]),a.useEffect(()=>{if(!(tt||St))return;const we=lt=>{const wt=lt.target,jn=ks.current?.contains(wt),Js=ge.current?.contains(wt);!jn&&tt&>(!1),!Js&&St&&Xt(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[tt,St]),a.useEffect(()=>{if(!(tt||St))return;const we=lt=>{lt.key==="Escape"&&(lt.stopPropagation(),tt&>(!1),St&&Xt(!1))};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[tt,St]),a.useEffect(()=>{Ee(!1),Ke(N.prompt||""),Fe("")},[e.id,N.prompt]);const qs=d6.has(e.column)&&!Un,Ai=u6.has(e.column)&&!Un,pi=zs??N.githubTracking?.enabled===!0,Fs=N.githubTracking?.issue,ji=_&&typeof e.githubTracking>"u",Oa=ox(e),wr=Ai&&!Fs&&!ji&&(!pi||Qe&&N.githubTracking?.enabled!==!0),fl=Ai||pi||!!Fs,fi=e.retrySummary,gl=[{key:"stuckKill",label:g("taskDetail.retries.stuckKill","Stuck kills"),title:g("taskDetail.retries.stuckKillTitle","Stuck-task detector forced agent kill retries"),value:fi?.stuckKill??0},{key:"recovery",label:g("taskDetail.retries.recovery","Recovery retries"),title:g("taskDetail.retries.recoveryTitle","Transient executor recovery retries"),value:fi?.recovery??0},{key:"taskDone",label:g("taskDetail.retries.taskDone","task_done retries"),title:g("taskDetail.retries.taskDoneTitle","Agent exited without task_done and task was retried"),value:fi?.taskDone??0},{key:"workflowStep",label:g("taskDetail.retries.workflowStep","Workflow retries"),title:g("taskDetail.retries.workflowStepTitle","Workflow step failure retries"),value:fi?.workflowStep??0},{key:"verification",label:g("taskDetail.retries.verification","Verification bounces"),title:g("taskDetail.retries.verificationTitle","Verification failure bounce retries"),value:fi?.verification??0},{key:"postReviewFix",label:g("taskDetail.retries.postReviewFix","Post-review fixes"),title:g("taskDetail.retries.postReviewFixTitle","Post-review remediation retries"),value:fi?.postReviewFix??0},{key:"mergeConflict",label:g("taskDetail.retries.mergeConflict","Merge conflict bounces"),title:g("taskDetail.retries.mergeConflictTitle","Merge conflict bounce retries"),value:fi?.mergeConflict??0},{key:"branchConflict",label:g("taskDetail.retries.branchConflict","Branch conflict recovery"),title:g("taskDetail.retries.branchConflictTitle","FN-4068 branch-conflict recovery retries"),value:fi?.branchConflict??0},{key:"reviewerContext",label:g("taskDetail.retries.reviewerContext","Reviewer context retries"),title:g("taskDetail.retries.reviewerContextTitle","FN-4082 compact reviewer retry"),value:fi?.reviewerContext??0},{key:"reviewerFallback",label:g("taskDetail.retries.reviewerFallback","Reviewer fallback retries"),title:g("taskDetail.retries.reviewerFallbackTitle","FN-4092 fallback-model retry"),value:fi?.reviewerFallback??0}].filter(H=>H.value>0),la=ji?g("taskDetail.githubTracking.statusLoading","Loading"):Fs?g("taskDetail.githubTracking.statusLinked","Linked"):pi?g("taskDetail.githubTracking.statusEnabled","Enabled"):g("taskDetail.githubTracking.statusDisabled","Disabled"),ba=!Fs&&(Qe||ji),va=sN(ne??null,Je),Xi=ti.trim(),jr=(e.description??"").trim().length>0,bl=!fe&&qs&&jr,Nr=a.useCallback(async()=>{if(gn||Un||!jr)return;const H=e.id;ps(!0);try{const we=await ZA(e.description||"",void 0,void 0,n);if(Ge.current!==H)return;const lt=await si(e.id,{title:we},n);if(Ge.current!==H)return;D(wt=>wt?{...wt,...lt}:lt),h?.(lt),u(g("taskDetail.title.summarizeSuccess","Title updated from description"),"success")}catch(we){Ge.current===H&&u(g("taskDetail.title.summarizeFailed","Failed to summarize title: {{error}}",{error:Re(we)}),"error")}finally{at.current&&Ge.current===H&&ps(!1)}},[u,jr,Un,gn,h,n,g,e.description,e.id]),Sr=a.useCallback(async()=>{if(!Ai||Qe)return;const H=e.id,we=!pi;Qn(we),vt(!0);try{const lt=await si(e.id,{githubTracking:{enabled:we}},n);if(Ge.current!==H)return;D(wt=>wt?{...wt,...lt,githubTracking:lt.githubTracking}:lt),h?.(lt)}catch(lt){if(Ge.current!==H)return;Qn(N.githubTracking?.enabled===!0),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(lt)}),"error")}finally{at.current&&Ge.current===H&&vt(!1)}},[u,Ai,pi,Qe,h,n,N.githubTracking?.enabled,e.id]),io=a.useCallback(async()=>{if(!Ai||Qe)return;const H=e.id;if(Xi.length>0&&!xu.test(Xi)){Q(g("taskDetail.githubTracking.repoOverrideFormat","Repository override must be in owner/repo format"));return}Q(null),vt(!0);try{const we=await si(e.id,{githubTracking:{repoOverride:Xi.length>0?Xi:null}},n);if(Ge.current!==H)return;D(lt=>lt?{...lt,...we,githubTracking:we.githubTracking}:we),h?.(we)}catch(we){if(Ge.current!==H)return;u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(we)}),"error")}finally{at.current&&Ge.current===H&&vt(!1)}},[u,Ai,Xi,Qe,h,n,e.id]),vl=a.useCallback(async()=>{if(!pi||Fs||Qe)return;if(!ox(e)){u(g("taskDetail.githubTracking.addTitleBeforeCreating","Add a title before creating a tracking issue"),"info");return}const H=e.id;vt(!0);try{const we=await si(e.id,{githubTracking:{enabled:!0}},n);if(Ge.current!==H)return;D(lt=>lt?{...lt,...we,githubTracking:we.githubTracking}:we),h?.(we),u(g("taskDetail.githubTracking.issueCreationRequested","Requested GitHub tracking issue creation"),"info")}catch(we){if(Ge.current!==H)return;u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(we)}),"error")}finally{at.current&&Ge.current===H&&vt(!1)}},[u,Fs,pi,Qe,h,n,e]),Qa=a.useCallback(()=>{if(!qs)return;Xe(!0),Rt(e.title||""),Pt(e.description||""),pt(e.dependencies||[]),_t(e.branch??""),on(e.baseBranch??"");const H=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",we=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",lt=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";vn(H),sn(we),Kt(lt),$n(e.thinkingLevel??""),dn(e.nodeId),xn(H||we||lt?"custom":"default"),Bn(""),pn(e.enabledWorkflowSteps||[]),Yn(Ha(e.executionMode)),At(e.sourceIssue?.provider??""),Wn(e.sourceIssue?.repository??""),G(e.sourceIssue?.externalIssueId??""),yt(e.sourceIssue?.url??""),Sn([]),Rn(e.reviewLevel),zn(Ua(e.priority))},[qs,e]),$a=a.useCallback(()=>{Xe(!1),Rt(e.title||""),Pt(e.description||""),pt(e.dependencies||[]),_t(e.branch??""),on(e.baseBranch??""),dn(e.nodeId),At(e.sourceIssue?.provider??""),Wn(e.sourceIssue?.repository??""),G(e.sourceIssue?.externalIssueId??""),yt(e.sourceIssue?.url??""),zn(Ua(e.priority)),Yn(Ha(e.executionMode)),Gt.forEach(H=>URL.revokeObjectURL(H.previewUrl)),Sn([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Gt]),[za,gi]=a.useState("idle"),zi=a.useRef(null),xa=a.useRef(0),Cr=a.useCallback(H=>{const we={},lt=kt.trim(),wt=Vt.trim();lt&<!==(e.title??"")&&(we.title=lt),H&&wt&&wt!==(e.description??"")&&(we.description=wt),lx(bt,e.dependencies??[])||(we.dependencies=bt),lx(kn,e.enabledWorkflowSteps??[])||(we.enabledWorkflowSteps=kn);const jn=ft.trim()||null,Js=e.branch??null;jn!==Js&&(we.branch=jn);const Dc=Yt.trim()||null,Rr=e.baseBranch??null;Dc!==Rr&&(we.baseBranch=Dc);const Ou=Bm(An),Lc=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";An!==Lc&&(we.modelProvider=Ou?.provider??null,we.modelId=Ou?.modelId??null);const ho=Bm(Qt),Yf=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Qt!==Yf&&(we.validatorModelProvider=ho?.provider??null,we.validatorModelId=ho?.modelId??null);const Fc=Bm(mn),FS=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";mn!==FS&&(we.planningModelProvider=Fc?.provider??null,we.planningModelId=Fc?.modelId??null);const OS=e.thinkingLevel??"";fn!==OS&&(we.thinkingLevel=fn!==""?fn:null),(e.nodeId??void 0)!==Nn&&(we.nodeId=Nn??null),Vn!==e.reviewLevel&&(we.reviewLevel=Vn),Pn!==Ua(e.priority)&&(we.priority=Pn),Tt!==Ha(e.executionMode)&&(we.executionMode=Tt==="fast"?"fast":null);const $u=Um(un),zu=Um(an),Oc=Um(Xn),Bu=i6(Oe);if($u.length===0&&zu.length===0&&Oc.length===0&&!Bu)e.sourceIssue&&(we.sourceIssue=null);else{if(!$u||!zu||!Oc)return{updates:null,error:g("taskDetail.edit.sourceIssueRequiredFields","Source issue provider, repository, and issue identifier are required")};const $S=Number.parseInt(Oc,10),Uu=e.sourceIssue?.issueNumber??$S;if(!Number.isFinite(Uu)||Uu<=0)return{updates:null,error:g("taskDetail.edit.sourceIssueIdentifierNumeric","Source issue identifier must be numeric for new metadata")};const po={provider:$u,repository:zu,externalIssueId:Oc,issueNumber:Uu,...Bu?{url:Bu}:{}},fo=e.sourceIssue;(!fo||fo.provider!==po.provider||fo.repository!==po.repository||fo.externalIssueId!==po.externalIssueId||fo.issueNumber!==po.issueNumber||(fo.url??void 0)!==po.url)&&(we.sourceIssue=po)}return{updates:we,error:null}},[Yt,ft,bt,Vt,Tt,An,Nn,mn,Pn,Vn,kn,Xn,un,an,Oe,fn,kt,Qt,e]),Ti=a.useCallback(async H=>{const{updates:we,error:lt}=Cr(H);if(!we)return gi("error"),lt&&u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:lt}),"error"),!1;if(Object.keys(we).length===0)return!0;const wt=++xa.current;bn(!0),gi("saving");try{const jn=await si(e.id,we,n);return wt!==xa.current?void 0:(h?.(jn),gi("saved"),!0)}catch(jn){return wt===xa.current&&(gi("error"),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(jn)}),"error")),!1}finally{at.current&&wt===xa.current&&bn(!1)}},[u,Cr,h,n,e.id]),ao=a.useCallback(async H=>{await Ti(!0)},[Ti]),Bi=a.useCallback(async()=>{await Ti(!0)&&(u(g("taskDetail.updateSuccess","Updated {{id}}",{id:e.id}),"success"),at.current&&Xe(!1))},[u,Ti,e.id]);a.useEffect(()=>{if(fe)return zi.current&&clearTimeout(zi.current),zi.current=setTimeout(()=>{Ti(!1)},700),()=>{zi.current&&(clearTimeout(zi.current),zi.current=null)}},[fe,kt,bt,ft,Yt,An,Qt,mn,fn,Nn,Vn,Pn,Tt,kn,un,an,Xn,Oe,Ti]);const ro=a.useCallback(async H=>{const we=Ua(H),lt=Ua(e.priority);if(we===lt){ae(lt);return}const wt=Ne;ae(we),ut(!0);try{const jn=await si(e.id,{priority:we},n);ae(Ua(jn.priority)),h?.(jn),u(g("taskDetail.priority.updated","Priority updated to {{priority}}",{priority:Ua(jn.priority)}),"success")}catch(jn){ae(wt),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(jn)}),"error")}finally{at.current&&ut(!1)}},[e.id,e.priority,n,Ne,h,u]),Za=a.useCallback(async()=>{const we=Ha(e.executionMode)==="fast"?"standard":"fast",lt=It;ht(we),Ut(!0);try{const wt=await si(e.id,{executionMode:we==="fast"?"fast":null},n),jn=Ha(wt.executionMode);ht(jn),h?.(wt),u(g("taskDetail.executionMode.updated","Execution mode updated to {{mode}}",{mode:jn}),"success")}catch(wt){ht(lt),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(wt)}),"error")}finally{at.current&&Ut(!1)}},[e.id,e.executionMode,n,It,h,u]),_r=a.useCallback(async()=>{const H=!$t,we=$t;rn(H),ve(!0);try{const lt=await si(e.id,{noCommitsExpected:H},n),wt=lt.noCommitsExpected===!0;rn(wt),h?.(lt),u(wt?g("taskDetail.noCommits.enabled","No-commits expectation enabled"):g("taskDetail.noCommits.disabled","No-commits expectation disabled"),"success")}catch(lt){rn(we),u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(lt)}),"error")}finally{at.current&&ve(!1)}},[e.id,n,$t,h,u]),Ba=a.useCallback(H=>{fe&&(H.key==="Escape"?(H.preventDefault(),$a()):H.key==="Enter"&&(H.ctrlKey||H.metaKey)&&(H.preventDefault(),Bi()))},[fe,$a,Bi]);a.useEffect(()=>{if(fe)return document.addEventListener("keydown",Ba),()=>document.removeEventListener("keydown",Ba)},[fe,Ba]);const ya=a.useRef(null),{nodes:oo}=Nu(),{confirm:Cs,confirmWithChoice:ka,confirmWithCheckbox:wa}=Yi(),Er=a.useCallback(async()=>{if(!(!qs||!Fs||Qe||!await Cs({title:g("taskDetail.githubTracking.unlinkTitle","Unlink GitHub issue?"),message:g("taskDetail.githubTracking.unlinkMessage","This stops Fusion from syncing with the linked GitHub issue. The issue itself will not be modified."),confirmLabel:g("taskDetail.githubTracking.unlinkConfirm","Unlink"),danger:!0}))){vt(!0);try{const we=await si(e.id,{githubTracking:{issue:null}},n);h?.(we),u(g("taskDetail.githubTracking.issueUnlinked","GitHub issue unlinked"),"success")}catch(we){u(g("taskDetail.updateFailed","Failed to update {{id}}: {{error}}",{id:e.id,error:Re(we)}),"error")}finally{at.current&&vt(!1)}}},[u,qs,Cs,Fs,Qe,h,n,e.id]),{entries:ja,loading:lo,loadMore:co,hasMore:Mr,total:Ar,loadingMore:er}=Wj(e.id,S==="logs"&&P==="agent-log",n),Kn=a.useCallback(()=>{k?.()},[k]);a.useEffect(()=>{if(x)return;const H=we=>{we.key==="Escape"&&!fe&&Kn()};return document.addEventListener("keydown",H),()=>document.removeEventListener("keydown",H)},[x,Kn,fe]);const tr=a.useCallback(async H=>{try{const we=e.steps.some(jn=>jn.status!=="pending"),lt=(H==="todo"||H==="triage")&&we;let wt;if(lt){if(await Cs({title:g("taskDetail.move.preserveProgressTitle","Preserve Progress?"),message:g("taskDetail.move.preserveProgressMessage","This task has completed steps. Keep progress before moving?"),confirmLabel:g("taskDetail.move.keepProgress","Keep Progress"),cancelLabel:g("taskDetail.move.resetProgress","Reset Progress")}))wt={preserveProgress:!0};else if(!await Cs({title:g("taskDetail.move.resetProgressTitle","Reset Progress?"),message:g("taskDetail.move.resetProgressMessage","Reset all step progress before moving this task?"),confirmLabel:g("taskDetail.move.resetProgress","Reset Progress"),cancelLabel:g("taskDetail.move.cancelMove","Cancel Move"),danger:!0}))return}await r(e.id,H,wt),Kn(),u(g("taskDetail.move.movedTo","Moved to {{column}}",{column:j(H)}),"success")}catch(we){u(Re(we),"error")}},[e.id,e.steps,r,Kn,u,Cs]),nr=a.useCallback(async()=>{let H=!1;if(e.column==="done"&&l){const wt=await ka({title:g("taskDetail.delete.title","Delete Task"),message:g("taskDetail.delete.message","Delete {{id}}?",{id:e.id}),confirmLabel:g("taskDetail.delete.confirm","Delete"),cancelLabel:g("common.cancel","Cancel"),tertiaryLabel:g("taskDetail.delete.archiveInstead","Archive Instead"),danger:!0});if(wt==="tertiary"){try{await l(e.id),u(g("taskDetail.nearDuplicate.archived","Archived {{id}}",{id:e.id}),"success"),Kn()}catch(jn){const Js=Ta(jn);if(!Js||Js.lineageChildIds.length===0){u(Re(jn),"error");return}if(!await Cs({title:g("taskDetail.delete.forceDeleteTitle","Force Delete Task"),message:`${e.id} has lineage children (${Js.lineageChildIds.join(", ")}) that reference it as a source parent.
|
|
770
770
|
|
|
771
771
|
`+g("taskDetail.delete.archiveUnlinkPrompt","Archive anyway by unlinking these references first?"),danger:!0}))return;try{await l(e.id,{removeLineageReferences:!0}),u(g("taskDetail.delete.archivedAfterUnlink","Archived {{id}} after unlinking lineage references",{id:e.id}),"success"),Kn()}catch(Rr){u(Re(Rr),"error")}}return}if(wt!=="primary")return}else{const{choice:wt,checkboxValue:jn}=await wa({title:g("taskDetail.delete.title","Delete Task"),message:g("taskDetail.delete.message","Delete {{id}}?",{id:e.id}),danger:!0,checkbox:{label:g("taskDetail.delete.allowRecreation","Allow re-creation later (operator unlock)"),description:g("taskDetail.delete.allowRecreationDesc","Lets agents recreate this task ID without --force-resurrect. Leave unchecked to keep this task tombstoned."),defaultChecked:!1}});if(wt!=="primary")return;H=jn===!0}const we=e.githubTracking?.enabled===!0?e.githubTracking.issue:void 0;let lt;if(we?.owner&&we.repo&&we.number){const wt=`${we.owner}/${we.repo}#${we.number}`;await Cs({title:g("taskDetail.delete.linkedIssueTitle","Linked GitHub Issue"),message:g("taskDetail.delete.linkedIssueMessage",`Choose what to do with {{issueRef}} when deleting {{id}}.
|
|
772
772
|
|
|
@@ -788,6 +788,6 @@ Archive anyway by unlinking these references first?`,{taskId:Ut.id,children:rn.l
|
|
|
788
788
|
\x1B[33m[Process exited with code ${_e}]\x1B[0m\r
|
|
789
789
|
`))});return()=>{Ie(),Pe(),oe(),re()}},[m,q?.sessionId,q?.id,q,Y,ye,je,ot,ue,te]),a.useEffect(()=>{if(Y!=="connected"||!s||!q||R.current===s||J.current?.command===s||A.current)return;if(R.current=s,R.current===s&&L.current===s){setTimeout(()=>{P.current(s+`
|
|
790
790
|
`)},500);return}A.current=!0,He().then(Ie=>{J.current={command:s,sessionId:Ie.sessionId},M(Pe=>Pe+1)}).catch(Ie=>{const Pe=Re(Ie);l(r("terminal.createScriptTabError","Failed to create terminal tab for script: {{message}}",{message:Pe})),R.current===s&&(R.current=!1)}).finally(()=>{A.current=!1})},[Y,s,q,He,f,r]),a.useEffect(()=>{const Ae=J.current;if(Y!=="connected"||!q||!Ae||Ae.sessionId!==q.sessionId)return;J.current=null;const ee=setTimeout(()=>{P.current(Ae.command+`
|
|
791
|
-
`)},500);return()=>clearTimeout(ee)},[Y,q?.sessionId,F]),a.useEffect(()=>{if(!m||!N.current)return;N.current.options.fontSize=w,le.current!==null&&(cancelAnimationFrame(le.current),le.current=null);const Ae=requestAnimationFrame(()=>{le.current=null,We()});return le.current=Ae,()=>{le.current===Ae&&(cancelAnimationFrame(Ae),le.current=null)}},[w,m,We]),a.useEffect(()=>{if(!e)return;const Ae=ee=>{if(!(!ee.ctrlKey&&!ee.metaKey)){if(ee.code==="Equal"||ee.code==="NumpadAdd"){ee.preventDefault(),g(Ie=>Jl(Ie+1));return}if(ee.code==="Minus"||ee.code==="NumpadSubtract"){ee.preventDefault(),g(Ie=>Jl(Ie-1));return}if(ee.code==="Digit0"||ee.code==="Numpad0"){ee.preventDefault(),g(Kl);return}}};return window.addEventListener("keydown",Ae),()=>window.removeEventListener("keydown",Ae)},[e,We]),a.useEffect(()=>{if(!e)return;const Ae=ee=>{ee.key==="Escape"&&n()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[e,n]),a.useEffect(()=>{Y==="connected"&&N.current&&setTimeout(()=>{if(!N.current||!D.current)return;const Ae=D.current.querySelector(".xterm-helper-textarea");Ae&&Ae.focus();try{D.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[Y]);const ke=a.useCallback(()=>{if(!D.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;N.current?.focus();const ee=D.current.querySelector(".xterm-helper-textarea");if(!ee)return;ee.autocapitalize="off",ee.autocomplete="off",ee.autocorrect="off",ee.spellcheck=!1,ee.setAttribute("inputmode","text");try{ee.focus({preventScroll:!0})}catch{ee.focus()}const Ie=ee.value.length;ee.setSelectionRange(Ie,Ie)},[]);a.useEffect(()=>Ce(()=>{N.current?.clear(),c(null),R.current=!1,N.current&&(N.current.dispose(),N.current=null),$.current=null,de.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),p(!1),u(null),z().catch(ee=>{console.error("Failed to replace invalid terminal session:",ee)})}),[Ce,z]);const Ee=a.useCallback(Ae=>{Ae.target===Ae.currentTarget&&(V.current=!0)},[]),Ze=a.useCallback(Ae=>{V.current&&Ae.target===Ae.currentTarget&&n(),V.current=!1},[n]),Ke=a.useCallback(()=>{N.current?.clear()},[]),dt=a.useCallback(async()=>{N.current?.clear(),c(null),R.current=!1;try{await me()}catch(Ae){l(Re(Ae)||"Failed to restart terminal session")}},[me]),Fe=a.useCallback(()=>{N.current&&(N.current.dispose(),N.current=null),$.current=null,de.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),u(null),p(!1)},[]),nt=a.useCallback(()=>{window.location.reload()},[]),Nt=a.useCallback(()=>{g(Ae=>Jl(Ae+1))},[]),Ft=a.useCallback(()=>{g(Ae=>Jl(Ae-1))},[]),ze=a.useCallback(Ae=>{E(ee=>ee===Ae?null:Ae)},[]),it=a.useCallback(Ae=>{if(C==="ctrl"){he(u5(Ae)),E(null);return}if(C==="alt"){he(m5(Ae)),E(null);return}he(Ae)},[he,C]),Mt=a.useCallback(Ae=>{he(Ae),E(null)},[he]);if(!e)return null;const Ht=()=>{switch(Y){case"connected":return t.jsx("span",{className:"terminal-status connected",title:r("terminal.statusConnected","Connected")});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:r("terminal.statusConnecting","Connecting...")});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:r("terminal.statusDisconnected","Disconnected")});default:return null}},Me=!ce||!q&&!De;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ee,onMouseUp:Ze,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:y>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:_,className:"modal terminal-modal","data-testid":"terminal-modal",style:y>0?{"--keyboard-overlap":`${y}px`,"--vv-height":x?`${x}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[xe.map(Ae=>t.jsxs("div",{className:`terminal-tab ${Ae.isActive?"terminal-tab--active":""}`,onClick:()=>pe(Ae.id),title:Ae.title,role:"tab","aria-selected":Ae.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ae.title}),xe.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:ee=>{ee.stopPropagation(),qe(Ae.id)},title:r("terminal.closeTab","Close tab"),children:"×"})]},Ae.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:He,title:r("terminal.newTerminal","New terminal"),children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ua,{size:16}),Ht()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[Y==="disconnected"&&q&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:$e,title:r("terminal.reconnect","Reconnect"),"data-testid":"terminal-reconnect-btn",children:[t.jsx(xs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:r("terminal.reconnect","Reconnect")})]}),d!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:dt,title:r("terminal.newSession","New Session"),"data-testid":"terminal-restart-btn",children:[t.jsx(xs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:r("terminal.newSession","New Session")})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Ke,"data-testid":"terminal-clear-btn",title:r("terminal.clearTerminal","Clear terminal"),children:[t.jsx(as,{size:14}),t.jsx("span",{className:"terminal-action-label",children:r("terminal.clear","Clear")})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>S(Ae=>!Ae),"data-testid":"terminal-shortcut-toggle",title:r("terminal.shortcuts","Shortcuts"),"aria-pressed":j,children:[t.jsx(K0,{size:14}),t.jsx("span",{className:"terminal-action-label",children:r("terminal.shortcuts","Shortcuts")})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:r("terminal.closeTerminal","Close terminal"),children:t.jsx(Fn,{size:20})})]})]}),o&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:o}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[Me&&!De&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:r("terminal.startingTerminal","Starting terminal...")})]}),De&&!q&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsx("span",{children:r("terminal.failedToStartTerminal","Failed to start terminal: {{error}}",{error:De})}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:se,"data-testid":"terminal-retry-btn",children:[t.jsx(xs,{size:14}),r("actions.retry","Retry")]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:nt,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(xs,{size:14}),r("terminal.refreshPage","Refresh page")]})]})]})}),h&&q&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsx("span",{children:r("terminal.initializeError","Terminal UI failed to initialize: {{error}}",{error:h})}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Fe,"data-testid":"terminal-reinit-btn",children:[t.jsx(xs,{size:14}),r("terminal.reinitialize","Reinitialize")]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:nt,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(xs,{size:14}),r("terminal.refreshPage","Refresh page")]})]})]})}),t.jsx("div",{ref:D,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:ke,onTouchStart:ke},q?.sessionId)]}),j&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${C==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>ze("ctrl"),"aria-pressed":C==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${C==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>ze("alt"),"aria-pressed":C==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Mt("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Mt(" "),children:"Tab"})]}),h5.map(Ae=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>it(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 ${Y}`,children:[Y==="connected"&&r("terminal.statusConnected","Connected"),Y==="connecting"&&r("terminal.statusConnecting","Connecting..."),Y==="reconnecting"&&r("terminal.statusReconnecting","Reconnecting..."),Y==="disconnected"&&r("terminal.statusDisconnected","Disconnected")]}),d!==null&&t.jsx("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:r("terminal.exitLabel","Exit: {{code}}",{code:d})}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:Ft,"data-testid":"terminal-font-size-decrease","aria-label":r("terminal.decreaseFontSize","Decrease terminal font size"),children:t.jsx(x1,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[w,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:Nt,"data-testid":"terminal-font-size-increase","aria-label":r("terminal.increaseFontSize","Increase terminal font size"),children:t.jsx(ys,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:r("terminal.helpText","Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close")})]})]})})}const Il={name:"",command:""};function Qx(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function w5(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function j5({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const{t:o}=st("app");ga(e);const[l,d]=a.useState({}),[c,m]=a.useState(!0),[p,h]=a.useState(!1),[u,f]=a.useState(null),[b,y]=a.useState(Il),[v,x]=a.useState(!1),[k,w]=a.useState(null),[g,j]=a.useState(null),S=yr(n),C=a.useCallback(async()=>{try{m(!0);const L=await Hd(i);d(L)}catch(L){s(Re(L)||o("scriptsModal.failedToLoadScripts","Failed to load scripts"),"error")}finally{m(!1)}},[s,i]);a.useEffect(()=>{e&&C()},[e,C]);const E=a.useCallback(()=>{h(!0),f(null),y(Il),j(null)},[]),F=a.useCallback((L,O)=>{f(L),h(!1),y({name:L,command:O}),j(null)},[]),M=a.useCallback(()=>{f(null),h(!1),y(Il),j(null)},[]),D=a.useCallback(L=>{y(O=>({...O,name:L})),L&&!Qx(L)?j(o("scriptsModal.nameErrorMsg","Name must contain only letters, numbers, hyphens, and underscores (no spaces)")):j(null)},[o]),_=a.useCallback(async()=>{const L=b.name.trim(),O=b.command.trim();if(!L){s(o("scriptsModal.scriptNameRequired","Script name is required"),"error");return}if(!Qx(L)){s(o("scriptsModal.nameErrorMsg","Script name must contain only letters, numbers, hyphens, and underscores (no spaces)"),"error");return}if(!O){s(o("scriptsModal.scriptCommandRequired","Script command is required"),"error");return}x(!0);try{await OA(L,O,i),s(u?o("scriptsModal.scriptUpdated","Script updated"):o("scriptsModal.scriptCreated","Script created"),"success"),f(null),h(!1),y(Il),j(null),await C()}catch(J){const A=Re(J);A?.includes("already exists")?s(o("scriptsModal.scriptAlreadyExists","A script with this name already exists"),"error"):s(A||o("scriptsModal.failedToSave","Failed to save script"),"error")}finally{x(!1)}},[b,u,s,C,i,o]),V=a.useCallback(async L=>{try{await $A(L,i),s(o("scriptsModal.scriptDeleted","Script deleted"),"success"),w(null),u===L&&(f(null),y(Il)),await C()}catch(O){s(Re(O)||o("scriptsModal.failedToDelete","Failed to delete script"),"error")}},[u,s,C,i,o]),N=a.useCallback((L,O)=>{r&&r(L,O)},[r]);if(!e)return null;const $=p||u!==null,R=Object.entries(l).map(([L,O])=>({name:L,command:O}));return t.jsx("div",{className:"modal-overlay open",...S,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(ua,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),o("scriptsModal.title","Scripts")]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":o("actions.close","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(Et,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),o("scriptsModal.loadingScripts","Loading scripts...")]}):$?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:o("scriptsModal.scriptName","Script Name")}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:b.name,onChange:L=>D(L.target.value),placeholder:o("scriptsModal.scriptNamePlaceholder","e.g., build, test, lint"),disabled:v||u!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:g?"var(--color-error)":void 0}}),g&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:g}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:o("scriptsModal.nameHint","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:o("scriptsModal.command","Command")}),t.jsx("textarea",{id:"script-command",className:"input",value:b.command,onChange:L=>y(O=>({...O,command:L.target.value})),placeholder:o("scriptsModal.commandPlaceholder","e.g., npm run build"),rows:3,disabled:v,"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:M,disabled:v,"data-testid":"script-cancel-btn",children:o("actions.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary",onClick:_,disabled:v||!!g,"data-testid":"script-save-btn",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:14,className:"spin",style:{marginRight:"6px"}}),o("scriptsModal.saving","Saving...")]}):u?o("actions.update","Update"):o("actions.create","Create")})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:R.length===0?o("scriptsModal.noScriptsDefined","No scripts defined"):o("scriptsModal.scriptCount","{{count}} script",{count:R.length,defaultValue_other:"{{count}} scripts"})}),t.jsxs("button",{className:"btn btn-primary",onClick:E,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(ys,{size:14}),o("scriptsModal.addScript","Add Script")]})]}),R.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(ua,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:o("scriptsModal.noScriptsYet","No scripts defined yet.")}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:o("scriptsModal.addScriptsHint","Add scripts to quickly run common commands from the dashboard.")})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:R.map(L=>t.jsx("div",{className:"script-card","data-testid":`script-${L.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:L.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:L.command,children:w5(L.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:()=>N(L.name,L.command),title:o("scriptsModal.runScript","Run script"),"aria-label":o("scriptsModal.runScriptNamed","Run {{name}}",{name:L.name}),"data-testid":`run-script-${L.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Ds,{size:12}),o("actions.run","Run")]}),t.jsx("button",{className:"btn-icon",onClick:()=>F(L.name,L.command),title:o("actions.edit","Edit"),"aria-label":o("scriptsModal.editScriptNamed","Edit {{name}}",{name:L.name}),"data-testid":`edit-script-${L.name}`,children:t.jsx(ys,{size:14,style:{transform:"rotate(45deg)"}})}),k===L.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>V(L.name),title:o("scriptsModal.confirmDelete","Confirm delete"),"aria-label":o("scriptsModal.confirmDeleteNamed","Confirm delete {{name}}",{name:L.name}),"data-testid":`confirm-delete-script-${L.name}`,style:{color:"var(--color-error)"},children:t.jsx(as,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>w(null),title:o("scriptsModal.cancelDelete","Cancel delete"),"aria-label":o("scriptsModal.cancelDelete","Cancel delete"),"data-testid":`cancel-delete-script-${L.name}`,children:t.jsx(Fn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>w(L.name),title:o("actions.delete","Delete"),"aria-label":o("scriptsModal.deleteScriptNamed","Delete {{name}}",{name:L.name}),"data-testid":`delete-script-${L.name}`,children:t.jsx(as,{size:14})})]})]})},L.name))})]})})]})})}function N5(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[d,c]=a.useState(!1),[m,p]=a.useState(null),[h,u]=a.useState(0),f=a.useCallback(()=>{u(y=>y+1)},[]),b=a.useCallback(y=>{l(y),p(null)},[]);return a.useEffect(()=>{l("."),p(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let y=!1;async function v(){c(!0),p(null);try{const x=await JM(e,o==="."?void 0:o,s);y||r(x.entries)}catch(x){y||(p(Re(x)||"Failed to load files"),r([]))}finally{y||c(!1)}}return v(),()=>{y=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:b,loading:d,error:m,refresh:f}}function S5(e,n,s,i){const{t:r}=st("app"),[o,l]=a.useState(""),[d,c]=a.useState(""),[m,p]=a.useState(null),[h,u]=a.useState(!1),[f,b]=a.useState(!1),[y,v]=a.useState(null),x=a.useCallback(g=>{l(g),v(null)},[]);a.useEffect(()=>{if(!e||!n){l(""),c(""),p(null),v(null);return}let g=!1;async function j(){u(!0),v(null);try{const S=await YM(e,n,i);g||(l(S.content),c(S.content),p(S.mtime))}catch(S){g||(v(Re(S)||r("editor.failedLoadFile","Failed to load file")),l(""),c(""),p(null))}finally{g||u(!1)}}return j(),()=>{g=!0}},[e,n,s,i]);const k=o!==d,w=a.useCallback(async()=>{if(!(!e||!n||!k)){b(!0),v(null);try{const g=await XM(e,n,o,i);c(o),p(g.mtime)}catch(g){throw v(Re(g)||r("editor.failedSaveFile","Failed to save file")),g}finally{b(!1)}}},[e,n,o,k,i]);return{content:o,setContent:x,originalContent:d,loading:h,saving:f,error:y,save:w,hasChanges:k,mtime:m}}const C5=1e4;function _5(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function E5(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function M5(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[d,c]=a.useState(null);return a.useEffect(()=>{let m=!1;async function p(){try{const u=await KM(e);if(m)return;s(_5(u.project)),r(u.tasks.map(E5)),c(null)}catch(u){m||c(Re(u)||"Failed to load workspaces")}finally{m||l(!1)}}p();const h=window.setInterval(()=>{p()},C5);return()=>{m=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:d}}function A5(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function T5(e){return e?new Date(e).toLocaleDateString():""}function Zx(e,n){return Eh(e,n)}const Dl={visible:!1,x:0,y:0,entry:null,entryFullPath:""},nh={type:null,entry:null,entryFullPath:""},R5=200,P5=500,ey=10;function I5({x:e,y:n,entry:s,onAction:i,onClose:r}){const{t:o}=st("app"),l=a.useRef(null),[d,c]=a.useState({x:e,y:n});a.useEffect(()=>{const h=l.current;if(!h)return;const u=h.getBoundingClientRect(),f=window.visualViewport,b=f?.width&&f.width>0?f.width:window.innerWidth,y=f?.height&&f.height>0?f.height:window.innerHeight,v=f?.offsetLeft??0,x=f?.offsetTop??0,k=8;let w=e-v,g=n-x;w+u.width>b-k&&(w=b-k-u.width),g+u.height>y-k&&(g=y-k-u.height),w<k&&(w=k),g<k&&(g=k),c({x:w+v,y:g+x})},[e,n]),a.useEffect(()=>{const h=u=>{u.key==="Escape"&&r()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[r]);const m=s.type==="directory",p=[{id:"copy",label:o("fileBrowser.contextCopy","Copy"),icon:Pa,disabled:!1},{id:"move",label:o("fileBrowser.contextMove","Move"),icon:w1,disabled:!1},{id:"rename",label:o("fileBrowser.contextRename","Rename"),icon:Si,disabled:!1},...m?[{id:"download-zip",label:o("fileBrowser.contextDownloadZip","Download as ZIP"),icon:Qr,disabled:!1}]:[{id:"download",label:o("fileBrowser.contextDownload","Download"),icon:ZC,disabled:!1}],{id:"divider",label:"",icon:Pa,disabled:!0},{id:"delete",label:o("fileBrowser.contextDelete","Delete"),icon:as,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:l,className:"file-browser-context-menu",role:"menu","aria-label":o("fileBrowser.contextMenuLabel","File operations"),style:{left:d.x,top:d.y},onClick:h=>h.stopPropagation(),children:p.map(h=>h.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 ${h.disabled?"file-browser-context-menu__disabled":""} ${h.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:h.disabled,onClick:()=>i(h.id),children:[t.jsx(h.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:h.label})]},h.id))})})}function D5({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const{t:d}=st("app"),c=a.useRef(null),m=e==="rename"&&n?n.name:"",[p,h]=a.useState(m);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&n&&c.current){const y=n.name.lastIndexOf(".");y>0?c.current.setSelectionRange(0,y):c.current.select()}},[e,n]);const u=y=>{y.key==="Enter"&&p.trim()&&i(p.trim()),y.key==="Escape"&&r()};if(e==="delete"&&n)return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:y=>y.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:d("fileBrowser.deleteTitle","Delete {{type}}",{type:n.type==="directory"?d("fileBrowser.typeFolder","Folder"):d("fileBrowser.typeFile","File")})}),t.jsxs("div",{className:"file-browser-dialog-message",children:[d("fileBrowser.deleteConfirm","Are you sure you want to delete {{name}}?",{name:n.name}),n.type==="directory"&&` ${d("fileBrowser.deleteRecursive","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:d("common.cancel","Cancel")}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?d("fileBrowser.deleting","Deleting..."):d("fileBrowser.delete","Delete")})]})]})});const b={copy:{title:d("fileBrowser.copyTitle","Copy"),placeholder:d("fileBrowser.copyPlaceholder","Destination path"),confirm:d("fileBrowser.copy","Copy")},move:{title:d("fileBrowser.moveTitle","Move"),placeholder:d("fileBrowser.movePlaceholder","Destination path"),confirm:d("fileBrowser.move","Move")},rename:{title:d("fileBrowser.renameTitle","Rename"),placeholder:d("fileBrowser.renamePlaceholder","New name"),confirm:d("fileBrowser.rename","Rename")},"create-file":{title:d("fileBrowser.newFile","New File"),placeholder:d("fileBrowser.fileNamePlaceholder","File name"),confirm:d("fileBrowser.create","Create")},"create-folder":{title:d("fileBrowser.newFolder","New Folder"),placeholder:d("fileBrowser.folderNamePlaceholder","Folder name"),confirm:d("fileBrowser.create","Create")}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:y=>y.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:b.title}),n&&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:p,onChange:y=>h(y.target.value),placeholder:b.placeholder,onKeyDown:u,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:d("common.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(p.trim()),disabled:o||!p.trim(),children:o?`${b.confirm}${d("fileBrowser.operationSuffix","ing...")}`:b.confirm})]})]})})}function L5({entries:e,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:o,onRetry:l,workspace:d,onRefresh:c,projectId:m}){const{t:p}=st("app"),[h,u]=a.useState(Dl),[f,b]=a.useState(nh),[y,v]=a.useState(!1),[x,k]=a.useState(null),[w,g]=a.useState(!1),[j,S]=a.useState(null),C=a.useRef(null),E=a.useRef(null),F=a.useRef(null),M=a.useRef(!1),D=a.useCallback(()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null),E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),_=a.useCallback(()=>{D(),F.current=null,g(!1),S(null)},[D]);a.useEffect(()=>()=>{D()},[D]);const V=a.useCallback((P,Z,T,ie)=>{u({visible:!0,x:P,y:Z,entry:T,entryFullPath:ie})},[]),N=a.useCallback((P,Z,T)=>{if(P.touches.length!==1)return;const ie=P.touches[0];ie&&(_(),F.current={x:ie.clientX,y:ie.clientY},E.current=window.setTimeout(()=>{g(!0),S(T)},R5),C.current=window.setTimeout(()=>{const le=F.current;le&&(M.current=!0,g(!1),S(null),D(),V(le.x,le.y,Z,T))},P5))},[_,D,V]),$=a.useCallback(P=>{const Z=F.current,T=P.touches[0];!Z||!T||(Math.abs(T.clientX-Z.x)>ey||Math.abs(T.clientY-Z.y)>ey)&&_()},[_]),R=a.useCallback(()=>{_()},[_]);a.useEffect(()=>{if(!h.visible)return;const P=document.querySelector(".file-browser-list"),Z=()=>{M.current=!1,_(),u(Dl)};return P?.addEventListener("scroll",Z),()=>P?.removeEventListener("scroll",Z)},[_,h.visible]),a.useEffect(()=>{if(!h.visible)return;const P=Z=>{Z.key==="Escape"&&(M.current=!1,u(Dl))};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[h.visible]);const L=a.useCallback((P,Z)=>{P.preventDefault(),P.stopPropagation(),_(),M.current=!1,V(P.clientX,P.clientY,Z,Zx(n,Z.name))},[_,n,V]),O=a.useCallback(P=>{d&&(b({type:P,entry:null,entryFullPath:n}),k(null))},[n,d]),J=a.useCallback(P=>{if(!h.entry)return;M.current=!1;const Z=h.entry,T=h.entryFullPath;if(u(Dl),P==="download"){if(!d)return;const ie=Xk(d,T,m);window.open(pa(ie),"_blank");return}if(P==="download-zip"){if(!d)return;const ie=aA(d,T,m);window.open(pa(ie),"_blank");return}b({type:P,entry:Z,entryFullPath:T}),k(null)},[h,d,m]),A=a.useCallback(async P=>{if(!(!f.type||!d)){v(!0),k(null);try{switch(f.type){case"copy":if(!f.entry)return;await tA(d,f.entryFullPath,P,m);break;case"move":if(!f.entry)return;await nA(d,f.entryFullPath,P,m);break;case"rename":if(!f.entry)return;await iA(d,f.entryFullPath,P,m);break;case"delete":if(!f.entry)return;await sA(d,f.entryFullPath,m);break;case"create-file":{const Z=Eh(f.entryFullPath,P);await eA(d,Z,m),s(Z);break}case"create-folder":await ZM(d,Eh(f.entryFullPath,P),m);break}b(nh),c?.()}catch(Z){k(Re(Z)||p("fileBrowser.operationFailed","Operation failed"))}finally{v(!1)}}},[f,d,c,s,m,p]),de=a.useCallback(()=>{b(nh),k(null)},[]),B=a.useCallback((P,Z)=>{if(M.current){M.current=!1;return}h.visible||(P.type==="directory"?i(Z):s(Z))},[h.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(Et,{className:"spin",size:24}),t.jsx("span",{children:p("fileBrowser.loadingFiles","Loading files...")})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsx("p",{children:p("fileBrowser.error","Error: {{message}}",{message:o})}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:p("common.retry","Retry")})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{i(Q_(n))},children:[t.jsx(ls,{size:16,style:{transform:"rotate(-90deg)"}}),p("fileBrowser.upOneLevel","Up one level")]}),t.jsx("span",{className:"file-browser-path",children:n==="."?p("fileBrowser.root","Root"):cl(n)}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>O("create-file"),disabled:!d,children:[t.jsx(m0,{size:14}),p("fileBrowser.newFile","New File")]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>O("create-folder"),disabled:!d,children:[t.jsx(C0,{size:14}),p("fileBrowser.newFolder","New Folder")]})]})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:p("fileBrowser.emptyDirectory","(empty directory)")}):e.map(P=>{const Z=Zx(n,P.name),T=w&&j===Z;return t.jsxs("div",{className:`file-node file-node--${P.type} ${T?"file-node--long-pressing":""}`,onClick:()=>B(P,Z),onContextMenu:ie=>L(ie,P),onTouchStart:ie=>N(ie,P,Z),onTouchMove:$,onTouchEnd:R,onTouchCancel:R,children:[t.jsx("div",{className:"file-node-icon",children:P.type==="directory"?t.jsx(Zs,{size:16}):t.jsx(Nk,{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:A5(P.size)}),P.mtime&&t.jsx("div",{className:"file-node-time",children:T5(P.mtime)})]},P.name)})}),h.visible&&h.entry&&t.jsx(I5,{x:h.x,y:h.y,entry:h.entry,onAction:J,onClose:()=>{M.current=!1,u(Dl)}}),f.type&&t.jsx(D5,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:A,onCancel:de,loading:y,error:x})]})}function F5(e){if(!e)return null;const n=e.toLowerCase();return n.endsWith(".js")||n.endsWith(".mjs")||n.endsWith(".cjs")||n.endsWith(".jsx")?Xf({jsx:!0}):n.endsWith(".ts")||n.endsWith(".tsx")?Xf({jsx:!0,typescript:!0}):n.endsWith(".css")?GS():n.endsWith(".json")?KS():n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")?JS():null}function O5(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function ty(){return document.documentElement.dataset.theme!=="light"}function ny(e){return e?[YS]:[XS(QS)]}function $5({content:e,onChange:n,readOnly:s,filePath:i,showLineNumbers:r=!1,onToggleLineNumbers:o,canToggleLineNumbers:l=!0,toolbarExpanded:d,toolbarActionsId:c}){const{t:m}=st("app"),[p,h]=a.useState(!1),[u,f]=a.useState(!0),[b,y]=a.useState(!1),v=d!==void 0,x=v?d:b,k=a.useRef(null),w=a.useRef(null),g=a.useRef(!1),j=a.useRef(n);j.current=n;const S=a.useRef(new yl),C=a.useRef(new yl),E=a.useRef(new yl),F=a.useRef(new yl),M=a.useRef(new yl),D=O5(i),_=a.useId(),V=c??_,[N,$]=a.useState(()=>ty()),R=D&&(s?!0:p),L=r&&!s&&!R,O=!!o&&l&&!s&&!R,J=D||!s||O,A=a.useMemo(()=>F5(i),[i]),de=a.useCallback(()=>h(!1),[]),B=a.useCallback(()=>h(!0),[]),P=a.useCallback(()=>f(T=>!T),[]),Z=a.useCallback(()=>{v||y(T=>!T)},[v]);return a.useEffect(()=>{if(!k.current||R)return;const T=Pr.theme({"&":{height:"100%",fontFamily:"var(--font-mono)",backgroundColor:"var(--bg)",color:"var(--text)"},".cm-gutters":{backgroundColor:"var(--surface)",color:"var(--text-muted)",borderRight:"calc(var(--space-xs) * 0.25) solid var(--border)"},"&.cm-focused":{outline:"none"}}),ie=Hu.create({doc:e,extensions:[S.current.of(L?Qf():[]),C.current.of(u?Pr.lineWrapping:[]),E.current.of(s?[Hu.readOnly.of(!0),Pr.editable.of(!1)]:[]),F.current.of(A??[]),M.current.of(ny(N)),T,Pr.updateListener.of(be=>{!be.docChanged||g.current||j.current(be.state.doc.toString())})]}),le=new Pr({state:ie,parent:k.current});return w.current=le,()=>{w.current=null,le.destroy()}},[R]),a.useEffect(()=>{const T=new MutationObserver(()=>{$(ty())});return T.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>T.disconnect()},[]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:S.current.reconfigure(L?Qf():[])})},[L]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:C.current.reconfigure(u?Pr.lineWrapping:[])})},[u]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:E.current.reconfigure(s?[Hu.readOnly.of(!0),Pr.editable.of(!1)]:[])})},[s]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:F.current.reconfigure(A??[])})},[A]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:M.current.reconfigure(ny(N))})},[N]),a.useEffect(()=>{const T=w.current;!T||T.state.doc.toString()===e||(g.current=!0,T.dispatch({changes:{from:0,to:T.state.doc.length,insert:e}}),g.current=!1)},[e]),t.jsxs("div",{className:"file-editor-container",children:[J&&(x||!v)?t.jsxs("div",{className:`file-editor-toolbar ${x?"file-editor-toolbar--expanded":""}`,children:[!v&&t.jsx("button",{className:"btn btn-sm btn-icon file-editor-toolbar-button",onClick:Z,"aria-label":m("fileEditor.toggleOptions","Toggle editor options"),title:m("fileEditor.toggleOptions","Toggle editor options"),"aria-expanded":x,"aria-controls":V,children:x?t.jsx(ra,{size:14}):t.jsx(Ln,{size:14})}),t.jsxs("div",{className:"file-editor-toolbar-actions",id:V,hidden:!x,children:[D?t.jsxs(t.Fragment,{children:[!s&&t.jsxs("button",{className:`btn btn-sm file-editor-toolbar-button ${R?"":"btn-primary"}`,onClick:de,disabled:!R,"aria-label":m("fileEditor.editMode","Edit mode"),children:[t.jsx(jk,{size:14}),m("fileEditor.edit","Edit")]}),t.jsxs("button",{className:`btn btn-sm file-editor-toolbar-button ${R?"btn-primary":""}`,onClick:B,disabled:R,"aria-label":m("fileEditor.previewMode","Preview mode"),children:[t.jsx(bc,{size:14}),m("fileEditor.preview","Preview")]})]}):null,O&&t.jsxs("button",{className:`btn btn-sm file-editor-toolbar-button ${r?"btn-primary":""}`,onClick:o,"aria-label":m("fileEditor.toggleLineNumbers","Toggle line numbers"),"aria-pressed":r,title:m("fileEditor.toggleLineNumbers","Toggle line numbers"),children:[t.jsx(t1,{size:14}),t.jsx("span",{children:m("fileEditor.lineNumber","Line #")})]}),!s&&t.jsxs("button",{className:`btn btn-sm file-editor-toolbar-button ${u?"btn-primary":""}`,onClick:P,"aria-label":m("fileEditor.toggleWordWrap","Toggle word wrap"),title:m("fileEditor.toggleWordWrap","Toggle word wrap"),children:[t.jsx(Cp,{size:14}),t.jsx("span",{children:m("fileEditor.wrap","Wrap")})]})]})]}):null,R?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(Di,{remarkPlugins:[Li],children:e})}):t.jsx("div",{className:"file-editor-codemirror",ref:k,"aria-label":i?m("fileEditor.editorFor",`Editor for ${i}`):m("fileEditor.fileEditor","File editor")})]})}function z5(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function B5({currentWorkspace:e,projectName:n,workspaces:s,onSelect:i}){const{t:r}=st("app"),[o,l]=a.useState(!1),d=typeof e=="string"?e:"project",c=a.useMemo(()=>d==="project"?n||r("workspace.projectRoot","Project Root"):s.find(p=>p.id===d)?.label??d,[d,n,s,r]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>l(m=>!m),"aria-haspopup":"listbox","aria-expanded":o,children:[d==="project"?t.jsx(ng,{size:14}):t.jsx(wh,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:c}),t.jsx(Ln,{size:14,className:`workspace-selector-trigger-icon${o?" open":""}`})]}),o&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":r("workspace.selectWorkspace","Select workspace"),children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${d==="project"?" active":""}`,onClick:()=>{i("project"),l(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(ng,{size:14}),t.jsx("span",{children:r("workspace.projectRoot","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:r("workspace.taskWorktrees","Task Worktrees")}),s.map(m=>t.jsxs("button",{type:"button",className:`workspace-selector-option${d===m.id?" active":""}`,onClick:()=>{i(m.id),l(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(wh,{size:14}),t.jsx("span",{children:m.id})]}),m.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:m.title,children:z5(m.title)})]},m.id))]})]})]})}const U5=768,H5=280,bd=180,vd=500,sy="fusion:file-browser-sidebar-width",iy="kb-files-line-numbers",RN=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),V5=new Set([...RN,".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 Ll(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return V5.has(n)}function q5(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return RN.has(n)}function W5(e){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,""),s=n.lastIndexOf("/");return s>0?n.slice(0,s):"."}function G5({initialWorkspace:e="project",initialFile:n=null,onClose:s,onWorkspaceChange:i,projectId:r}){const{t:o}=st("app"),{projectName:l,workspaces:d}=M5(r),c=a.useRef(null);La(c,!0,"fusion:files-modal-size");const m=yr(s),[p,h]=a.useState(e),[u,f]=a.useState(null),[b,y]=a.useState(!1),[v,x]=a.useState("list"),[k,w]=a.useState(H5),[g,j]=a.useState(!1),[S,C]=a.useState(!1),E=a.useId(),{entries:F,currentPath:M,setPath:D,loading:_,error:V,refresh:N}=N5(p,!0,r),{content:$,setContent:R,originalContent:L,loading:O,saving:J,error:A,save:de,hasChanges:B,mtime:P}=S5(p,u,!0,r);a.useEffect(()=>{h(e)},[e]),a.useEffect(()=>{const pe=()=>{y(window.innerWidth<=U5)};return pe(),window.addEventListener("resize",pe),()=>window.removeEventListener("resize",pe)},[]),a.useEffect(()=>{u||x("list"),C(!1)},[u]),a.useEffect(()=>{if(!n){f(null);return}f(n),D(W5(n)),b&&x("editor")},[n,b,D]),a.useEffect(()=>{try{const pe=localStorage.getItem(sy);if(!pe)return;const te=Number.parseInt(pe,10);if(!Number.isNaN(te)){const me=Math.max(bd,Math.min(vd,te));w(me)}}catch{}},[]),a.useEffect(()=>{const pe=cs(iy,r);j(pe==="true")},[r]),a.useEffect(()=>{const pe=te=>{te.key==="Escape"&&s(),(te.metaKey||te.ctrlKey)&&te.key==="s"&&(te.preventDefault(),B&&!J&&de())};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[s,B,J,de]);const Z=a.useCallback(pe=>{f(pe),b&&x("editor")},[b]),T=a.useCallback(()=>{x("list")},[]),ie=a.useCallback(()=>{R(L)},[L,R]),le=a.useCallback(pe=>{h(pe),f(null),x("list"),i?.(pe)},[i]),be=a.useCallback(pe=>{try{localStorage.setItem(sy,String(pe))}catch{}},[]),Le=a.useCallback(pe=>{if(b)return;pe.preventDefault(),pe.stopPropagation();const te=pe.currentTarget;typeof te.setPointerCapture=="function"&&te.setPointerCapture(pe.pointerId);const me=pe.clientX,se=k;let z=se;document.body.style.userSelect="none";const Y=X=>{const ye=X.clientX-me,ot=Math.max(bd,Math.min(vd,se+ye));z=ot,w(ot)},he=X=>{typeof te.releasePointerCapture=="function"&&te.releasePointerCapture(X.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Y),document.removeEventListener("pointerup",he),be(z)};document.addEventListener("pointermove",Y),document.addEventListener("pointerup",he)},[b,be,k]),xe=a.useCallback(pe=>{if(b)return;const te=20;if(pe.key!=="ArrowLeft"&&pe.key!=="ArrowRight")return;pe.preventDefault();const me=pe.key==="ArrowLeft"?-te:te,se=Math.max(bd,Math.min(vd,k+me));w(se),be(se)},[b,be,k]),q=a.useCallback(()=>{j(pe=>{const te=!pe;return _s(iy,String(te),r),te})},[r]),ce=a.useMemo(()=>p==="project"?o("fileBrowser.workspaceProject","Project"):d.find(pe=>pe.id===p)?.id??p,[p,d,o]),De=o("fileBrowser.modalTitle","Files — {{workspace}}",{workspace:ce}),He=a.useMemo(()=>!u||!q5(u)?null:Xk(p,u,r),[u,p,r]),qe=pe=>{const te=new Blob([pe]).size;return te<1024?`${te} B`:`${(te/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...m,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:c,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(Zs,{size:18}),t.jsx("span",{children:De}),u&&t.jsx("span",{className:"file-browser-header-path",children:u})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(B5,{currentWorkspace:p,projectName:l,workspaces:d,onSelect:le}),t.jsx("button",{className:"modal-close",onClick:s,"aria-label":o("actions.close","Close"),children:t.jsx(Fn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${b?"mobile":""} ${v==="list"?"active":""}`,style:b?void 0:{width:`${k}px`},children:t.jsx(L5,{entries:F,currentPath:M,onSelectFile:Z,onNavigate:D,loading:_,error:V,onRetry:N,workspace:p,onRefresh:N,projectId:r})}),!b&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":bd,"aria-valuemax":vd,"aria-valuenow":k,"aria-label":o("fileBrowser.resizeSidebar","Resize sidebar"),tabIndex:0,onPointerDown:Le,onKeyDown:xe}),t.jsx("div",{className:`file-browser-content ${b?"mobile":""} ${v==="editor"?"active":""}`,children:u?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[b&&v==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:T,"aria-label":o("fileBrowser.back","Back to file list"),children:[t.jsx(Zr,{size:16}),t.jsx("span",{children:o("actions.back","Back")})]}),!Ll(u)&&t.jsx("button",{className:"btn btn-sm btn-icon file-editor-toolbar-button",onClick:()=>C(pe=>!pe),"aria-label":o("fileBrowser.toggleEditorOptions","Toggle editor options"),title:o("fileBrowser.toggleEditorOptions","Toggle editor options"),"aria-expanded":S,"aria-controls":E,children:S?t.jsx(ra,{size:14}):t.jsx(Ln,{size:14})}),u,Ll(u)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(x0,{size:12}),o("fileBrowser.binaryReadOnly","Binary file — read only")]}),P&&t.jsx("span",{className:"file-browser-mtime",children:o("fileBrowser.modified","Modified: {{date}}",{date:new Date(P).toLocaleString()})}),O&&t.jsx("span",{className:"file-browser-loading",children:o("fileBrowser.loading","Loading…")})]}),t.jsx("div",{className:"file-browser-actions",children:!He&&B&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:ie,disabled:J,children:[t.jsx(L1,{size:14}),o("actions.discard","Discard")]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void de(),disabled:J,children:[t.jsx(Tk,{size:14}),J?o("fileBrowser.saving","Saving…"):o("actions.save","Save")]})]})})]}),A&&!He&&t.jsx("div",{className:"file-browser-error-banner",children:A}),He?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:He,alt:u??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx($5,{content:$,onChange:R,filePath:u,readOnly:Ll(u),showLineNumbers:g&&!Ll(u),onToggleLineNumbers:q,canToggleLineNumbers:!Ll(u),toolbarExpanded:S,toolbarActionsId:E})}),!He&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:qe($)}),B&&t.jsx("span",{className:"file-browser-unsaved",children:o("fileBrowser.unsavedChanges","Unsaved changes")})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Zs,{size:48,opacity:.3}),t.jsx("p",{children:o("fileBrowser.selectFileToEdit","Select a file to edit")})]})})]})]})})}const K5=a.lazy(()=>ln(()=>import("./TodoView-Djjwcb49.js"),__vite__mapDeps([18,1,4,5,6,2,3,7,19])).then(e=>({default:e.TodoView})));function J5({onClose:e,projectId:n,addToast:s,onPlanningMode:i}){const{t:r}=st("app"),o=yr(e),d=Ji()==="mobile",{keyboardOverlap:c,viewportHeight:m,viewportOffsetTop:p,keyboardOpen:h}=Xa({enabled:d});ga(d);const u=h?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${p}px`,...m!==null?{"--vv-height":`${m}px`}:{}}:{};return a.useEffect(()=>{const f=b=>{b.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...o,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:u,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(Ek,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:r("todo.todos","Todos")}),t.jsx("p",{children:r("todo.manageDescription","Manage reusable todo lists for your project.")})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":r("common.close","Close"),children:t.jsx(Fn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(K5,{projectId:n,addToast:s,onPlanningMode:i,onClose:e,mobileKeyboardActive:d&&h})})})]})})}function Y5(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[i,r]=a.useState({providers:[],loading:!0,error:null,lastUpdated:null,hasFetched:!1}),o=a.useRef(null),l=a.useRef(null),d=a.useRef(i),c=ul();a.useEffect(()=>{d.current=i},[i]);const m=a.useCallback(u=>d.current.hasFetched&&_c(u,c.wasRecentlyHidden()),[c]),p=a.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(f=>({...f,loading:!0,error:null}));try{const{providers:f}=await qE();r({providers:f,loading:!1,error:null,lastUpdated:new Date,hasFetched:!0})}catch(f){if(f instanceof Error&&f.name==="AbortError")return;const b=Re(f)||"Failed to fetch usage data";if(m(b)){r(y=>({...y,loading:!1}));return}r(y=>({...y,loading:!1,error:b,hasFetched:!0}))}},[m]);a.useEffect(()=>{p()},[p]),a.useEffect(()=>{if(s)return o.current=setInterval(()=>{p(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,p]),a.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const h=a.useCallback(()=>p(!0),[p]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,hasFetched:i.hasFetched,refresh:h}}function X5(e){const n=new Date(e),s=new Date,i=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return i;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),d=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return d>=1&&d<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${i}`}function Q5(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const PN="kb-usage-hidden-windows",IN="kb-usage-modal-size",DN="kb-usage-provider-order";function ay(e){const n=cs(IN,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 ry(e){const n=cs(PN,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((i,[r,o])=>{if(Array.isArray(o)){const l=o.filter(d=>typeof d=="string");l.length>0&&(i[r]=l)}return i},{})}catch{return{}}}function Z5(e,n){_s(PN,JSON.stringify(e),n)}function oy(e){const n=cs(DN,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(i=>typeof i=="string"):[]}catch{return[]}}function ly(e,n){_s(DN,JSON.stringify(e),n)}const eU="::";function LN(e,n){return`${n}${eU}${e}`}function Pf(e,n,s){return e===LN(n,s)||e===n}function If(e,n,s,i){return(i[e]??[]).some(r=>Pf(r,n,s))}function tU(e,n,s){return(n??[]).reduce((i,r,o)=>i+(If(e,r.label,o,s)?1:0),0)}function nU(e,n,s){const i=n??[],r=tU(e,i,s),o=s[e]??[];if(o.length===0)return r;const l=o.reduce((d,c)=>{const m=i.some((p,h)=>Pf(c,p.label,h));return d+(m?0:1)},0);return r+l}function sU({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const{t:r}=st("app"),o=Q5(e.percentUsed),l=n==="remaining",d=Math.round(l?e.percentLeft:e.percentUsed),c=l?r("usage.percentRemaining","{{percent}}% remaining",{percent:Math.round(e.percentLeft)}):r("usage.percentUsed","{{percent}}% used",{percent:Math.round(e.percentUsed)}),m=l?r("usage.percentUsed","{{percent}}% used",{percent:Math.round(e.percentUsed)}):r("usage.percentLeft","{{percent}}% left",{percent:Math.round(e.percentLeft)});let p=e.resetText;if(!p&&e.resetAt){const x=new Date(e.resetAt).getTime()-Date.now();if(x>0){const k=Math.floor(x/36e5),w=Math.floor(k/24),g=k%24;if(w>0&&g>0)p=r("usage.resetsInDaysHours","resets in {{days}}d {{hours}}h",{days:w,hours:g});else if(w>0)p=r("usage.resetsInDays","resets in {{days}}d",{days:w});else if(k>0)p=r("usage.resetsInHours","resets in {{hours}}h",{hours:k});else{const j=Math.floor(x/6e4);p=r("usage.resetsInMinutes","resets in {{mins}}m",{mins:j})}}}const h=e.pace,u=h!==void 0;let f=0;u&&(f=l?100-h.percentElapsed:h.percentElapsed);const b=h?.status==="ahead",y=h?.status==="behind",v=h?.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",{type:"button",className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":r("usage.hideWindow","Hide {{label}}",{label:e.label}),"data-testid":"usage-window-hide-btn",children:t.jsx(bc,{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 ${o}`,style:{width:`${d}%`},role:"progressbar","aria-valuenow":d,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),u&&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:m}),t.jsxs("span",{className:"usage-window-reset-group",children:[p&&t.jsx("span",{className:"usage-window-reset",children:p}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:X5(e.resetAt)})]})]}),u&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[b&&t.jsxs(t.Fragment,{children:[t.jsx(oa,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:h.message})]}),y&&t.jsxs(t.Fragment,{children:[t.jsx(r_,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:h.message})]}),v&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:h.message})]})]})]})}function iU(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 aU({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:d,onDragStart:c,onDragOver:m,onDragLeave:p,onDrop:h,onDragEnd:u,isTouchReorderMode:f,canMoveUp:b,canMoveDown:y,onMoveUp:v,onMoveDown:x}){const{t:k}=st("app"),w=e.windows??[],g=nU(e.name,w,s),j=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:k("usage.statusError","Error")});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:k("usage.statusNotConfigured","Not configured")})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&d==="before"?" usage-provider--drag-over-before":""}${l&&d==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!f,onDragStart:f?void 0:c,onDragOver:f?void 0:m,onDragLeave:f?void 0:p,onDrop:f?void 0:h,onDragEnd:f?void 0:u,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(hs,{provider:iU(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),g>0&&t.jsx("button",{type:"button",className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:k("usage.showHidden","Show hidden ({{count}})",{count:g})})]}),t.jsxs("div",{className:"usage-provider-actions",children:[f&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":k("usage.reorderProvider","Reorder {{provider}}",{provider:e.name}),children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:v,disabled:!b,"aria-label":k("usage.moveProviderUp","Move {{provider}} up",{provider:e.name}),children:t.jsx(ra,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:x,disabled:!y,"aria-label":k("usage.moveProviderDown","Move {{provider}} down",{provider:e.name}),children:t.jsx(Ln,{size:14})})]}),j(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(pu,{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})}),w.length>0?t.jsx("div",{className:"usage-provider-windows",children:w.map((S,C)=>{const E=If(e.name,S.label,C,s);return t.jsx(sU,{window:S,viewMode:n,isHidden:E,onToggleHidden:()=>i(e.name,S.label,C)},`${e.name}-${S.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:k("usage.noDataAvailable","No usage data available")}):null]})}function rU(){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 oU({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{t:r}=st("app"),{providers:o,loading:l,error:d,lastUpdated:c,hasFetched:m,refresh:p}=Y5({autoRefresh:e}),[h,u]=a.useState(!1),[f,b]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[y,v]=a.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[x,k]=a.useState("used"),[w,g]=a.useState(()=>ry(s)),[j,S]=a.useState(()=>oy(s)),[C,E]=a.useState(null),[F,M]=a.useState(null),[D,_]=a.useState(null),V=a.useRef(null),N=a.useRef(null),$=a.useRef(e),[R,L]=a.useState(()=>ay(s));a.useEffect(()=>{L(ay(s))},[s]),a.useEffect(()=>{if(!e||!f)return;const se=N.current;if(!se||typeof ResizeObserver>"u")return;let z=null;const Y=new ResizeObserver(he=>{const X=he[0];if(!X)return;const{width:ye,height:ot}=X.contentRect;ye<=0||ot<=0||(z&&clearTimeout(z),z=setTimeout(()=>{_s(IN,JSON.stringify({width:Math.round(ye),height:Math.round(ot)}),s)},250))});return Y.observe(se),()=>{z&&clearTimeout(z),Y.disconnect()}},[e,f,s]),a.useEffect(()=>{if(typeof window>"u")return;const se=window.matchMedia?.("(pointer: coarse)"),z=()=>{b(window.innerWidth>=769),v(se?.matches??!1)};return z(),window.addEventListener("resize",z),se?.addEventListener?.("change",z),()=>{window.removeEventListener("resize",z),se?.removeEventListener?.("change",z)}},[]),a.useEffect(()=>{!$.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&p(),$.current=e},[e,c,p]),a.useEffect(()=>{const se=cs("kb-usage-view-mode",s);if(se==="used"||se==="remaining"){k(se);return}k("used")},[s]);const O=a.useCallback(se=>{k(se),_s("kb-usage-view-mode",se,s)},[s]);a.useEffect(()=>{g(ry(s)),S(oy(s))},[s]),a.useEffect(()=>{Z5(w,s)},[w,s]);const J=a.useCallback((se,z,Y)=>{g(he=>{const X=LN(z,Y),ye=he[se]??[];if(If(se,z,Y,he)){const ot=ye.filter(ue=>!Pf(ue,z,Y));if(ot.length===0){const{[se]:ue,...je}=he;return je}return{...he,[se]:ot}}return{...he,[se]:[...ye,X]}})},[]),A=a.useCallback(se=>{g(z=>{if(!z[se])return z;const{[se]:Y,...he}=z;return he})},[]),de=a.useCallback(se=>{if(j.length===0)return se;const z=new Map(se.map(he=>[he.name,he])),Y=[];for(const he of j){const X=z.get(he);X&&(Y.push(X),z.delete(he))}return[...Y,...z.values()]},[j]),B=a.useCallback((se,z)=>{se.dataTransfer.effectAllowed="move",se.dataTransfer.setData("text/plain",z),E(z)},[]),P=a.useCallback((se,z)=>{if(!C||C===z)return;se.preventDefault(),se.dataTransfer.dropEffect="move";const{top:Y,height:he}=se.currentTarget.getBoundingClientRect(),X=Y+he/2,ye=se.clientY<X?"before":"after";M(z),_(ye)},[C]),Z=a.useCallback((se,z)=>{se.preventDefault();const Y=C??se.dataTransfer.getData("text/plain");if(!Y||Y===z){M(null),_(null);return}const X=de(o).map(ue=>ue.name).filter(ue=>ue!==Y),ye=X.indexOf(z);if(ye<0){M(null),_(null);return}const ot=D==="after"?ye+1:ye;X.splice(ot,0,Y),ly(X,s),S(X),M(null),_(null)},[C,D,s,o,de]),T=a.useCallback(()=>{E(null),M(null),_(null)},[]),ie=a.useCallback((se,z)=>{const Y=de(o).map(ue=>ue.name),he=Y.indexOf(se),X=he+z;if(he<0||X<0||X>=Y.length)return;const ye=[...Y],[ot]=ye.splice(he,1);ye.splice(X,0,ot),ly(ye,s),S(ye)},[s,o,de]),le=a.useCallback(async()=>{u(!0),await p(),u(!1)},[p]);a.useEffect(()=>{if(!e)return;const se=z=>{z.key==="Escape"&&n()};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[e,n]);const be=a.useCallback(se=>{se.target===se.currentTarget&&n()},[n]);if(!e)return null;const Le=!!(i&&f),xe=8,q=12,De=R?.width??420,He=Le?Math.min((i?.bottom??0)+xe,window.innerHeight-q):void 0,qe=Le?Math.max(8,(i?.right??0)-De):void 0,pe=f&&R?{width:R.width,height:R.height}:{},te=de(o),me=t.jsxs("div",{ref:N,className:`usage-modal${Le?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:Le?{position:"fixed",top:He,left:qe,...pe}:pe,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ci,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:r("usage.title","Usage")})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":r("usage.viewModeLabel","Usage view mode"),children:[t.jsx("button",{className:`usage-view-toggle-btn ${x==="used"?"active":""}`,onClick:()=>O("used"),"aria-pressed":x==="used","data-testid":"usage-view-toggle-used",children:r("usage.viewModeUsed","Used")}),t.jsx("button",{className:`usage-view-toggle-btn ${x==="remaining"?"active":""}`,onClick:()=>O("remaining"),"aria-pressed":x==="remaining","data-testid":"usage-view-toggle-remaining",children:r("usage.viewModeRemaining","Remaining")})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":r("actions.closeModal","Close usage modal"),"data-testid":"usage-modal-close",children:t.jsx(Fn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:V,children:!m&&!d&&o.length===0?t.jsx(rU,{}):d&&o.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:r("usage.failedToLoad","Failed to load usage data")}),t.jsx("p",{className:"usage-error-message",children:d}),t.jsx("button",{className:"btn btn-sm",onClick:le,children:r("actions.retry","Retry")})]}):o.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:r("usage.noProvidersConfigured","No AI providers configured")}),t.jsx("p",{className:"usage-empty-hint",children:r("usage.configureAuthHint","Configure authentication in Settings to see usage data.")})]}):t.jsx("div",{className:"usage-providers",children:te.map((se,z)=>t.jsx(aU,{provider:se,viewMode:x,hiddenWindows:w,onToggleWindow:J,onShowAllHidden:A,isDragging:C===se.name,isDragOver:F===se.name,dragOverPosition:F===se.name?D:null,onDragStart:Y=>B(Y,se.name),onDragOver:Y=>P(Y,se.name),onDragLeave:()=>{F===se.name&&(M(null),_(null))},onDrop:Y=>Z(Y,se.name),onDragEnd:T,isTouchReorderMode:y,canMoveUp:z>0,canMoveDown:z<te.length-1,onMoveUp:()=>ie(se.name,-1),onMoveDown:()=>ie(se.name,1)},se.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.jsx("span",{children:r("usage.lastUpdated","Last updated: {{time}}",{time:c.toLocaleTimeString()})})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:le,disabled:l||h,"data-testid":"usage-refresh-btn",children:[t.jsx(xs,{size:14,className:h?"spin":"",style:{marginRight:6}}),r("actions.refresh","Refresh")]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:r("actions.close","Close")})]})]})]});return Le?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),me]}):t.jsx("div",{className:"modal-overlay open",onClick:be,"data-testid":"usage-modal-overlay",children:me})}function FN(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),i=n%60;if(s<60)return i>0?`${s}m ${i}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function au(e){const n=Date.now(),s=new Date(e).getTime(),i=n-s;if(i<0){const r=Math.abs(i);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:`${Math.floor(i/864e5)}d ago`}const lU={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},ON={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},cU={cron:xk,webhook:Rk,api:kk,manual:Ws},dU={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},uU={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function mU({result:e}){const{t:n}=st("app"),s=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(Es,{size:12}):t.jsx(vr,{size:12}),t.jsx("span",{children:e.success?n("routine.resultSuccess","Success"):n("routine.resultFailed","Failed")}),s>0&&t.jsx("span",{className:"schedule-run-duration",children:FN(s)})]})}function hU({result:e,index:n}){const[s,i]=a.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>i(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${au(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Es,{size:12}):t.jsx(vr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:au(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:ON[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:FN(r)}),s?t.jsx(ra,{size:12}):t.jsx(Ln,{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 pU({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const{t:d}=st("app"),[c,m]=a.useState(!1),{confirm:p}=Yi(),h=a.useCallback(async()=>{await p({title:d("routine.deleteTitle","Delete Routine"),message:d("routine.deleteMessage",'Delete routine "{{name}}"? This cannot be undone.',{name:e.name}),danger:!0})&&s(e)},[e,s,p,d]),u=lU[e.trigger.type],f=cU[e.trigger.type],b=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:u,color:u},children:[t.jsx(f,{size:10}),ON[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(Np,{size:10}):t.jsx(Zs,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>i(e),disabled:o,title:o?d("routine.running","Running…"):d("routine.runNow","Run now"),"aria-label":o?d("routine.running","Running…"):d("routine.runNameNow","Run {{name}} now",{name:e.name}),children:o?t.jsx(Et,{className:"spinner"}):t.jsx(Ds,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?d("routine.disable","Disable"):d("routine.enable","Enable"),"aria-label":e.enabled?d("routine.disableName","Disable {{name}}",{name:e.name}):d("routine.enableName","Enable {{name}}",{name:e.name}),"aria-pressed":e.enabled,children:e.enabled?t.jsx(ia,{}):t.jsx(Ds,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:d("routine.edit","Edit"),"aria-label":d("routine.editName","Edit {{name}}",{name:e.name}),children:t.jsx(Si,{})}),t.jsx("button",{className:"btn-icon",onClick:h,title:d("routine.delete","Delete"),"aria-label":d("routine.deleteName","Delete {{name}}",{name:e.name}),children:t.jsx(as,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Vr,{size:12}),t.jsx("span",{className:"routine-policy-badge",children:d("routine.stepCount","{{count}} step",{count:e.steps.length,defaultValue_one:"{{count}} step",defaultValue_other:"{{count}} steps"})})]}):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"&&b&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ha,{size:12}),t.jsx("code",{className:"routine-cron",children:b})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:dU[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:uU[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:au(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:au(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(mU,{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:()=>m(y=>!y),"aria-expanded":c,children:[c?t.jsx(ra,{size:12}):t.jsx(Ln,{size:12}),t.jsx("span",{children:d("routine.runHistory","Run History ({{count}})",{count:e.runHistory.length})})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((y,v)=>t.jsx(hU,{result:y,index:v},`${y.startedAt}-${v}`)),e.runHistory.length>10&&t.jsx("div",{className:"schedule-history-more",children:d("routine.andMore","…and {{count}} more",{count:e.runHistory.length-10})})]})]})]})}function fU({type:e,size:n=12}){const{t:s}=st("app");return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:s("stepType.commandStepTitle","Command step"),children:[t.jsx(ua,{size:n}),t.jsx("span",{children:s("stepType.command","Command")})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:s("stepType.createTaskStepTitle","Create Task step"),children:[t.jsx(s1,{size:n}),t.jsx("span",{children:s("stepType.createTask","Create Task")})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:s("stepType.aiPromptStepTitle","AI Prompt step"),children:[t.jsx($s,{size:n}),t.jsx("span",{children:s("stepType.aiPrompt","AI Prompt")})]})}function sh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function gU(e){return e==="command"?{id:sh(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:sh(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:sh(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function bU({step:e,onSave:n,onCancel:s}){const{t:i}=st("app"),[r,o]=a.useState(e.name),[l,d]=a.useState(e.type),[c,m]=a.useState(e.command??""),[p,h]=a.useState(e.prompt??""),[u,f]=a.useState(e.modelProvider??""),[b,y]=a.useState(e.modelId??""),[v,x]=a.useState(e.taskTitle??""),[k,w]=a.useState(e.taskDescription??""),[g,j]=a.useState(e.taskColumn??"triage"),[S,C]=a.useState(e.timeoutMs),[E,F]=a.useState(e.continueOnFailure??!1),[M,D]=a.useState({}),[_,V]=a.useState([]),[N,$]=a.useState(!1),[R,L]=a.useState(null);a.useEffect(()=>{let B=!1;return $(!0),L(null),fa().then(P=>{B||V(P.models)}).catch(P=>{B||L(P instanceof Error?P.message:"Failed to load models")}).finally(()=>{B||$(!1)}),()=>{B=!0}},[]);const O=a.useCallback(()=>{const B={};return r.trim()||(B.name=i("schedule.stepNameRequired","Step name is required")),l==="command"&&!c.trim()&&(B.command=i("schedule.commandRequired","Command is required")),l==="ai-prompt"&&!p.trim()&&(B.prompt=i("schedule.promptRequired","Prompt is required")),l==="create-task"&&!k.trim()&&(B.taskDescription=i("schedule.taskDescriptionRequired","Task description is required")),(l==="ai-prompt"||l==="create-task")&&(u||b)&&(!u||!b)&&(B.modelProvider=i("schedule.modelProviderRequired","Both model provider and model ID must be set together")),S!==void 0&&S<1e3&&(B.timeoutMs=i("schedule.timeoutMinimum","Timeout must be at least 1 second (1000ms)")),D(B),Object.keys(B).length===0},[r,l,c,p,k,u,b,S,i]),J=u&&b?`${u}/${b}`:"",A=a.useCallback(B=>{if(!B)f(""),y("");else{const P=B.indexOf("/");P!==-1&&(f(B.slice(0,P)),y(B.slice(P+1)))}},[]),de=a.useCallback(()=>{if(!O())return;const B={...e,name:r.trim(),type:l,command:l==="command"?c.trim():void 0,prompt:l==="ai-prompt"?p.trim():void 0,taskTitle:l==="create-task"&&v.trim()?v.trim():void 0,taskDescription:l==="create-task"&&k.trim()?k.trim():void 0,taskColumn:l==="create-task"?g:void 0,modelProvider:(l==="ai-prompt"||l==="create-task")&&u.trim()?u.trim():void 0,modelId:(l==="ai-prompt"||l==="create-task")&&b.trim()?b.trim():void 0,timeoutMs:S||void 0,continueOnFailure:E};l!=="ai-prompt"&&delete B.prompt,l!=="create-task"&&(delete B.taskTitle,delete B.taskDescription,delete B.taskColumn),n(B)},[O,n,e,r,l,c,p,v,k,g,u,b,S,E]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:i("schedule.stepName","Step Name")}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:i("schedule.stepNamePlaceholder","e.g. Run tests"),value:r,onChange:B=>o(B.target.value),"aria-invalid":!!M.name}),M.name&&t.jsx("small",{className:"field-error",children:M.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:i("schedule.stepType","Step Type")}),t.jsxs("select",{id:`step-type-${e.id}`,value:l,onChange:B=>d(B.target.value),children:[t.jsx("option",{value:"command",children:i("schedule.commandType","Command")}),t.jsx("option",{value:"ai-prompt",children:i("schedule.aiPromptType","AI Prompt")}),t.jsx("option",{value:"create-task",children:i("schedule.createTaskType","Create Task")})]})]}),l==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:i("schedule.command","Command")}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:i("schedule.commandPlaceholder","e.g. npm test"),value:c,onChange:B=>m(B.target.value),rows:2,"aria-invalid":!!M.command}),M.command&&t.jsx("small",{className:"field-error",children:M.command})]}),l==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:i("schedule.prompt","Prompt")}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:i("schedule.promptPlaceholder","e.g. Summarize the test results and highlight any failures"),value:p,onChange:B=>h(B.target.value),rows:3,"aria-invalid":!!M.prompt}),M.prompt&&t.jsx("small",{className:"field-error",children:M.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:i("schedule.modelOptional","Model (optional)")}),t.jsx(wi,{id:`step-model-${e.id}`,label:i("schedule.model","Model"),models:_,value:J,onChange:A,placeholder:i("schedule.useDefault","Use default"),disabled:N}),R&&t.jsx("small",{className:"field-error",children:R}),t.jsx("small",{children:i("schedule.modelHelp","AI model for this step. Uses default if not selected.")})]})]}),l==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:i("schedule.taskTitleOptional","Task Title (optional)")}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:i("schedule.taskTitlePlaceholder","e.g. Review weekly dependencies"),value:v,onChange:B=>x(B.target.value)}),t.jsx("small",{children:i("schedule.taskTitleHelp","Leave blank to auto-summarize from description")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:i("schedule.taskDescription","Task Description *")}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:i("schedule.taskDescriptionPlaceholder","e.g. Check all npm dependencies for security vulnerabilities and update outdated packages"),value:k,onChange:B=>w(B.target.value),rows:4,"aria-invalid":!!M.taskDescription}),M.taskDescription&&t.jsx("small",{className:"field-error",children:M.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:i("schedule.targetColumn","Target Column")}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:g,onChange:B=>j(B.target.value),children:[t.jsx("option",{value:"triage",children:i("schedule.triageColumn","Triage")}),t.jsx("option",{value:"todo",children:i("schedule.todoColumn","To Do")})]}),t.jsx("small",{children:i("schedule.targetColumnHelp","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:i("schedule.executorModelOptional","Executor Model (optional)")}),t.jsx(wi,{id:`step-task-model-${e.id}`,label:i("schedule.model","Model"),models:_,value:J,onChange:A,placeholder:i("schedule.useDefault","Use default"),disabled:N}),R&&t.jsx("small",{className:"field-error",children:R}),M.modelProvider&&t.jsx("small",{className:"field-error",children:M.modelProvider}),t.jsx("small",{children:i("schedule.executorModelHelp","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:i("schedule.timeoutOptional","Timeout (ms, optional)")}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:i("schedule.timeoutPlaceholder","Override schedule timeout"),value:S??"",onChange:B=>C(B.target.value?Number(B.target.value):void 0),"aria-invalid":!!M.timeoutMs}),M.timeoutMs&&t.jsx("small",{className:"field-error",children:M.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:E,onChange:B=>F(B.target.checked)}),i("schedule.continueOnFailure","Continue on failure")]}),t.jsx("small",{children:i("schedule.continueOnFailureHelp","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:i("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:de,children:i("schedule.saveStep","Save Step")})]})]})}function vU({steps:e,onChange:n,onEditingChange:s}){const{t:i}=st("app"),[r,o]=a.useState(null);a.useEffect(()=>{s?.(r!==null)},[r,s]);const l=a.useCallback(p=>{const h=gU(p);n([...e,h]),o(h.id)},[e,n]),d=a.useCallback(p=>{n(e.filter(h=>h.id!==p)),r===p&&o(null)},[e,n,r]),c=a.useCallback((p,h)=>{const u=e.findIndex(y=>y.id===p);if(u<0)return;const f=h==="up"?u-1:u+1;if(f<0||f>=e.length)return;const b=[...e];[b[u],b[f]]=[b[f],b[u]],n(b)},[e,n]),m=a.useCallback(p=>{n(e.map(h=>h.id===p.id?p:h)),o(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:[i("schedule.steps","Steps")," (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:i("schedule.noStepsEmpty","No steps added yet. Add a command or AI prompt step to get started.")})}),t.jsx("div",{className:"steps-list",children:e.map((p,h)=>t.jsx("div",{className:"step-card",children:r===p.id?t.jsx(bU,{step:p,onSave:m,onCancel:()=>o(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(pu,{size:14})}),t.jsx("span",{className:"step-card-index",children:h+1}),t.jsx(fU,{type:p.type}),t.jsx("span",{className:"step-card-name",children:p.name}),p.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:i("schedule.continuesOnFailure","Continues on failure"),children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(p.id,"up"),disabled:h===0,title:i("schedule.moveUp","Move up"),"aria-label":i("schedule.moveStepUp","Move {{name}} up",{name:p.name}),children:t.jsx(ra,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(p.id,"down"),disabled:h===e.length-1,title:i("schedule.moveDown","Move down"),"aria-label":i("schedule.moveStepDown","Move {{name}} down",{name:p.name}),children:t.jsx(Ln,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>o(p.id),title:i("actions.edit","Edit"),"aria-label":i("schedule.editStep","Edit {{name}}",{name:p.name}),children:t.jsx(Si,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>d(p.id),title:i("actions.delete","Delete"),"aria-label":i("schedule.deleteStep","Delete {{name}}",{name:p.name}),children:t.jsx(as,{})})]})]})},p.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("command"),children:[t.jsx(ys,{size:14}),i("schedule.addCommandStep","Add Command Step")]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("ai-prompt"),children:[t.jsx(ys,{size:14}),i("schedule.addAiPromptStep","Add AI Prompt Step")]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("create-task"),children:[t.jsx(ys,{size:14}),i("schedule.addCreateTaskStep","Add Create Task Step")]})]})]})}const $N={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"};function xU(e){const n=e.trim();for(const[s,i]of Object.entries($N))if(i===n)return s;return"custom"}function yU(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function kU(e,n,s,i,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:i||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function wU(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:""}}}function cy(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function dy({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const{t:l}=st("app"),d=!!e,c={hourly:l("schedule.cronPresetHourly","Every hour"),daily:l("schedule.cronPresetDaily","Every day (midnight)"),weekly:l("schedule.cronPresetWeekly","Every week (Monday)"),monthly:l("schedule.cronPresetMonthly","Every month (1st)"),custom:l("schedule.cronPresetCustom","Custom cron expression")},m=[{value:"parallel",label:l("schedule.executionPolicyParallel","Allow concurrent runs")},{value:"queue",label:l("schedule.executionPolicyQueue","Queue after current (one at a time)")},{value:"reject",label:l("schedule.executionPolicyReject","Reject new runs while running")}],p=[{value:"skip",label:l("schedule.catchUpPolicySkip","Skip missed runs")},{value:"run_one",label:l("schedule.catchUpPolicyRunOne","Run the most recent missed run")},{value:"run",label:l("schedule.catchUpPolicyRunAll","Run all missed runs")}],h=e?wU(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,f]=a.useState(e?.name??""),[b,y]=a.useState(e?.description??""),[v,x]=a.useState(h.triggerType),[k,w]=a.useState(h.cronExpression),[g,j]=a.useState(()=>h.triggerType!=="cron"?"custom":xU(h.cronExpression)),[S,C]=a.useState(h.webhookPath),[E,F]=a.useState(h.webhookSecret),[M,D]=a.useState(h.endpoint),[_,V]=a.useState(e?.executionPolicy??"queue"),[N,$]=a.useState(e?.catchUpPolicy??"run_one"),[R,L]=a.useState(e?.enabled??!0),O=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,J=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[A,de]=a.useState(e?.steps&&e.steps.length>0&&!O&&!J?"advanced":"simple"),[B,P]=a.useState(()=>O?"ai-prompt":J?"create-task":"command"),[Z,T]=a.useState(e?.command??""),[ie,le]=a.useState(e?.steps??[]),[be,Le]=a.useState(!1),[xe,q]=a.useState(e?.timeoutMs??3e5),[ce,De]=a.useState(O?e.steps?.[0]?.prompt??"":""),[He,qe]=a.useState(J?e.steps?.[0]?.taskTitle??"":""),[pe,te]=a.useState(J?e.steps?.[0]?.taskDescription??"":""),[me,se]=a.useState(J?e.steps?.[0]?.taskColumn??"triage":"triage"),[z,Y]=a.useState(O||J?e.steps?.[0]?.modelProvider??"":""),[he,X]=a.useState(O||J?e.steps?.[0]?.modelId??"":""),[ye,ot]=a.useState([]),[ue,je]=a.useState(!1),[$e,Ce]=a.useState(null),[We,ke]=a.useState(i??"global"),[Ee,Ze]=a.useState({}),[Ke,dt]=a.useState(!1),Fe=a.useRef(!0);a.useEffect(()=>()=>{Fe.current=!1},[]),a.useEffect(()=>{i&&ke(i)},[i]),a.useEffect(()=>{let _e=!1;return je(!0),Ce(null),fa().then(fe=>{_e||ot(fe.models)}).catch(fe=>{_e||Ce(fe instanceof Error?fe.message:l("schedule.errorLoadModels","Failed to load models"))}).finally(()=>{_e||je(!1)}),()=>{_e=!0}},[]);const nt=z&&he?`${z}/${he}`:"",Nt=a.useCallback(_e=>{if(!_e){Y(""),X("");return}const fe=_e.indexOf("/");fe!==-1&&(Y(_e.slice(0,fe)),X(_e.slice(fe+1)))},[]),Ft=a.useCallback(()=>{const _e={};if(u.trim()||(_e.name=l("schedule.errorNameRequired","Name is required")),We==="project"&&!r&&(_e.scope=l("schedule.errorScopeNoProject","Project-specific entries require an active project.")),v==="cron"&&g==="custom"&&(k.trim()?yU(k)||(_e.cronExpression=l("schedule.errorCronInvalid","Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')")):_e.cronExpression=l("schedule.errorCronRequired","Cron expression is required")),v==="webhook"&&!S.trim()&&(_e.webhookPath=l("schedule.errorWebhookPathRequired","Webhook path is required")),v==="api"&&!M.trim()&&(_e.endpoint=l("schedule.errorApiEndpointRequired","API endpoint is required")),A==="simple")B==="command"&&!Z.trim()&&(_e.command=l("schedule.errorCommandRequired","Command is required")),B==="ai-prompt"&&!ce.trim()&&(_e.prompt=l("schedule.errorPromptRequired","Prompt is required")),B==="create-task"&&!pe.trim()&&(_e.taskDescription=l("schedule.errorTaskDescriptionRequired","Task description is required")),(z.trim()&&!he.trim()||!z.trim()&&he.trim())&&(_e.model=l("schedule.errorModelIncomplete","Both model provider and model ID must be set, or both must be empty"));else{ie.length===0&&(_e.steps=l("schedule.errorStepsRequired","At least one step is required")),be&&(_e.stepsEditing=l("schedule.errorStepsEditing","Please save or cancel all step edits before saving the routine"));const fe=[];ie.forEach((Xe,kt)=>{Xe.name?.trim()||fe.push(l("schedule.errorStepNameRequired","Step {{n}}: Name is required",{n:kt+1})),Xe.type==="command"&&!Xe.command?.trim()&&fe.push(l("schedule.errorStepCommandRequired","Step {{n}}: Command is required",{n:kt+1})),Xe.type==="ai-prompt"&&!Xe.prompt?.trim()&&fe.push(l("schedule.errorStepPromptRequired","Step {{n}}: Prompt is required",{n:kt+1})),Xe.type==="create-task"&&!Xe.taskDescription?.trim()&&fe.push(l("schedule.errorStepTaskDescRequired","Step {{n}}: Task description is required",{n:kt+1}))}),fe.length>0&&(_e.steps=fe.join("; "))}return xe<1e3&&(_e.timeoutMs=l("schedule.errorTimeoutMin","Timeout must be at least 1 second (1000ms)")),Ze(_e),Object.keys(_e).length===0},[u,v,k,g,S,M,We,r,A,B,Z,ce,pe,z,he,ie,be,xe]),ze=a.useCallback(async _e=>{if(_e.preventDefault(),!!Ft()){dt(!0);try{let fe=e?.scope??We??(r?"project":"global");fe==="project"&&!r&&(fe="global");const Xe=kU(v,k,S,E,M);let kt,Rt;A==="simple"?B==="command"?kt=Z.trim()||void 0:B==="ai-prompt"?Rt=[{id:cy(),type:"ai-prompt",name:u.trim(),prompt:ce.trim(),modelProvider:z.trim()||void 0,modelId:he.trim()||void 0}]:Rt=[{id:cy(),type:"create-task",name:u.trim(),taskTitle:He.trim()||void 0,taskDescription:pe.trim(),taskColumn:me,modelProvider:z.trim()||void 0,modelId:he.trim()||void 0}]:Rt=ie;const Vt={name:u.trim(),agentId:e?.agentId??"",description:b.trim()||void 0,trigger:Xe,command:kt,steps:Rt,timeoutMs:xe,executionPolicy:_,catchUpPolicy:N,enabled:R,scope:fe};await n(Vt)}finally{Fe.current&&dt(!1)}}},[Ft,n,u,b,v,k,S,E,M,A,B,Z,ce,z,he,He,pe,me,ie,xe,_,N,R,We,r,e?.scope,e?.agentId]),it="routine-name-error",Mt="routine-cron-error",Ht="routine-webhook-error",Me="routine-endpoint-error",Ae="routine-command-error",ee="routine-prompt-error",Ie="routine-task-description-error",Pe="routine-model-error",oe="routine-timeout-error",re=a.useCallback(_e=>{j(_e),_e!=="custom"&&w($N[_e])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ze,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:d?l("schedule.editRoutineHeading","Edit Routine"):l("schedule.newRoutineHeading","New Routine")}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:l("schedule.nameLabel","Name")}),t.jsx("input",{id:"routine-name",type:"text",placeholder:l("schedule.namePlaceholder","e.g. Daily standup reminder"),value:u,onChange:_e=>f(_e.target.value),"aria-invalid":!!Ee.name,"aria-describedby":Ee.name?it:void 0}),Ee.name&&t.jsx("small",{id:it,className:"field-error",children:Ee.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:l("schedule.descriptionLabel","Description (optional)")}),t.jsx("textarea",{id:"routine-description",placeholder:l("schedule.descriptionPlaceholder","What does this routine do?"),value:b,onChange:_e=>y(_e.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("schedule.scopeLabel","Scope")}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":l("schedule.scopeAriaLabel","Routine scope"),children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${We==="global"?" active":""}`,onClick:()=>{ke("global"),o?.("global")},role:"radio","aria-checked":We==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?l("schedule.scopeLockedTitle","Scope is locked to {{scope}} for existing routines",{scope:e.scope}):l("schedule.globalScopeTitle","Global scope"),children:[t.jsx(Np,{size:12}),l("schedule.globalScope","Global")]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${We==="project"?" active":""}`,onClick:()=>{ke("project"),o?.("project")},role:"radio","aria-checked":We==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?l("schedule.scopeLockedTitle","Scope is locked to {{scope}} for existing routines",{scope:e.scope}):r?l("schedule.projectScopeTitle","Project scope"):l("schedule.selectProjectTitle","Select a project to enable project scope"),children:[t.jsx(Zs,{size:12}),l("schedule.projectScope","Project")]})]}),t.jsx("small",{children:!r&&!e?.scope?l("schedule.scopeHintNoProject","No active project. Routines will be created at global scope."):We==="project"&&r?l("schedule.scopeHintProject","This routine will be scoped to the current project."):l("schedule.scopeHintGlobal","This routine will be created at global scope.")}),Ee.scope&&t.jsx("small",{className:"field-error",children:Ee.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("schedule.triggerTypeLabel","Trigger Type")}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":l("schedule.triggerTypeAriaLabel","Trigger type"),children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${v==="cron"?" active":""}`,onClick:()=>x("cron"),role:"radio","aria-checked":v==="cron",children:[t.jsx(xk,{size:14}),l("schedule.triggerCron","Cron")]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${v==="webhook"?" active":""}`,onClick:()=>x("webhook"),role:"radio","aria-checked":v==="webhook",children:[t.jsx(Rk,{size:14}),l("schedule.triggerWebhook","Webhook")]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${v==="api"?" active":""}`,onClick:()=>x("api"),role:"radio","aria-checked":v==="api",children:[t.jsx(kk,{size:14}),l("schedule.triggerApi","API")]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${v==="manual"?" active":""}`,onClick:()=>x("manual"),role:"radio","aria-checked":v==="manual",children:[t.jsx(Ws,{size:14}),l("schedule.triggerManual","Manual")]})]})]}),v==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:l("schedule.frequencyLabel","Frequency")}),t.jsx("select",{id:"routine-frequency",value:g,onChange:_e=>re(_e.target.value),children:Object.entries(c).map(([_e,fe])=>t.jsx("option",{value:_e,children:fe},_e))}),t.jsx("label",{htmlFor:"routine-cron",children:l("schedule.cronExpressionLabel","Cron Expression")}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:k,onChange:_e=>w(_e.target.value),disabled:g!=="custom","aria-invalid":!!Ee.cronExpression,"aria-describedby":Ee.cronExpression?Mt:void 0}),Ee.cronExpression?t.jsx("small",{id:Mt,className:"field-error",children:Ee.cronExpression}):t.jsx("small",{children:g==="custom"?t.jsxs(t.Fragment,{children:[l("schedule.cronCustomHint","min hour day month weekday")," — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):l("schedule.cronAutoFilledHint","Auto-filled from preset: {{expression}}",{expression:k})})]}),v==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:l("schedule.webhookPathLabel","Webhook Path")}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:l("schedule.webhookPathPlaceholder","/trigger/my-routine"),value:S,onChange:_e=>C(_e.target.value),"aria-invalid":!!Ee.webhookPath,"aria-describedby":Ee.webhookPath?Ht:void 0}),Ee.webhookPath?t.jsx("small",{id:Ht,className:"field-error",children:Ee.webhookPath}):t.jsx("small",{children:l("schedule.webhookPathHint","URL path for the webhook endpoint")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:l("schedule.webhookSecretLabel","Webhook Secret (optional)")}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:l("schedule.webhookSecretPlaceholder","Optional — leave empty for unauthenticated webhooks"),value:E,onChange:_e=>F(_e.target.value)}),t.jsx("small",{children:l("schedule.webhookSecretHint","HMAC secret for signature verification. Leave empty for unauthenticated webhooks.")})]})]}),v==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:l("schedule.apiEndpointLabel","API Endpoint")}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:l("schedule.apiEndpointPlaceholder","/api/routine/my-routine"),value:M,onChange:_e=>D(_e.target.value),"aria-invalid":!!Ee.endpoint,"aria-describedby":Ee.endpoint?Me:void 0}),Ee.endpoint?t.jsx("small",{id:Me,className:"field-error",children:Ee.endpoint}):t.jsx("small",{children:l("schedule.apiEndpointHint","API endpoint path that triggers this routine")})]}),v==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:l("schedule.manualTriggerInfo","This routine will be triggered manually via the dashboard or API.")})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("schedule.actionModeLabel","Action Mode")}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":l("schedule.actionModeAriaLabel","Action mode"),children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${A==="simple"?" active":""}`,onClick:()=>de("simple"),role:"radio","aria-checked":A==="simple",children:l("schedule.actionModeSimple","Simple")}),t.jsx("button",{type:"button",className:`schedule-mode-btn${A==="advanced"?" active":""}`,onClick:()=>de("advanced"),role:"radio","aria-checked":A==="advanced",children:l("schedule.actionModeAdvanced","Multi-Step")})]}),t.jsx("small",{children:A==="simple"?l("schedule.actionModeSimpleHint","Run one command, prompt, or task creation action"):l("schedule.actionModeAdvancedHint","Run multiple actions sequentially")})]}),A==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("schedule.actionTypeLabel","Action Type")}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":l("schedule.actionTypeAriaLabel","Action type"),children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${B==="command"?" active":""}`,onClick:()=>P("command"),role:"radio","aria-checked":B==="command",children:l("schedule.actionTypeCommand","Command")}),t.jsx("button",{type:"button",className:`schedule-mode-btn${B==="ai-prompt"?" active":""}`,onClick:()=>P("ai-prompt"),role:"radio","aria-checked":B==="ai-prompt",children:l("schedule.actionTypeAiPrompt","AI Prompt")}),t.jsx("button",{type:"button",className:`schedule-mode-btn${B==="create-task"?" active":""}`,onClick:()=>P("create-task"),role:"radio","aria-checked":B==="create-task",children:l("schedule.actionTypeCreateTask","Create Task")})]})]}),B==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:l("schedule.commandLabel","Command")}),t.jsx("input",{id:"routine-command",type:"text",placeholder:l("schedule.commandPlaceholder","e.g. npx runfusion.ai backup --create"),value:Z,onChange:_e=>T(_e.target.value),"aria-invalid":!!Ee.command,"aria-describedby":Ee.command?Ae:void 0}),Ee.command?t.jsx("small",{id:Ae,className:"field-error",children:Ee.command}):t.jsx("small",{children:l("schedule.commandHint","Shell command to execute.")})]}):B==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:l("schedule.promptLabel","Prompt")}),t.jsx("textarea",{id:"routine-prompt",placeholder:l("schedule.promptPlaceholder","e.g. Summarize recent activity and create action items"),value:ce,onChange:_e=>De(_e.target.value),rows:3,"aria-invalid":!!Ee.prompt,"aria-describedby":Ee.prompt?ee:void 0}),Ee.prompt?t.jsx("small",{id:ee,className:"field-error",children:Ee.prompt}):t.jsx("small",{children:l("schedule.promptHint","AI prompt to execute.")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:l("schedule.modelLabel","Model (optional)")}),t.jsx(wi,{id:"routine-model",label:l("schedule.modelDropdownLabel","Model"),models:ye,value:nt,onChange:Nt,placeholder:l("schedule.modelPlaceholder","Use default"),disabled:ue}),$e&&t.jsx("small",{className:"field-error",children:$e}),Ee.model&&t.jsx("small",{id:Pe,className:"field-error",children:Ee.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:l("schedule.taskTitleLabel","Task Title (optional)")}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:l("schedule.taskTitlePlaceholder","e.g. Review weekly dependencies"),value:He,onChange:_e=>qe(_e.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:l("schedule.taskDescriptionLabel","Task Description")}),t.jsx("textarea",{id:"routine-task-description",placeholder:l("schedule.taskDescriptionPlaceholder","e.g. Check npm dependencies for security vulnerabilities"),value:pe,onChange:_e=>te(_e.target.value),rows:4,"aria-invalid":!!Ee.taskDescription,"aria-describedby":Ee.taskDescription?Ie:void 0}),Ee.taskDescription?t.jsx("small",{id:Ie,className:"field-error",children:Ee.taskDescription}):t.jsx("small",{children:l("schedule.taskDescriptionHint","Describes the task that will be created.")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:l("schedule.taskColumnLabel","Target Column")}),t.jsxs("select",{id:"routine-task-column",value:me,onChange:_e=>se(_e.target.value),children:[t.jsx("option",{value:"triage",children:l("schedule.taskColumnTriage","Triage")}),t.jsx("option",{value:"todo",children:l("schedule.taskColumnTodo","To Do")})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:l("schedule.executorModelLabel","Executor Model (optional)")}),t.jsx(wi,{id:"routine-task-model",label:l("schedule.executorModelDropdownLabel","Executor Model"),models:ye,value:nt,onChange:Nt,placeholder:l("schedule.modelPlaceholder","Use default"),disabled:ue}),$e&&t.jsx("small",{className:"field-error",children:$e}),Ee.model&&t.jsx("small",{id:Pe,className:"field-error",children:Ee.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(vU,{steps:ie,onChange:le,onEditingChange:Le}),Ee.steps&&t.jsx("small",{className:"field-error",children:Ee.steps}),Ee.stepsEditing&&t.jsx("small",{className:"field-error",children:Ee.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:l("schedule.timeoutLabel","Timeout (ms)")}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:xe,onChange:_e=>q(Number(_e.target.value)),"aria-invalid":!!Ee.timeoutMs,"aria-describedby":Ee.timeoutMs?oe:void 0}),Ee.timeoutMs?t.jsx("small",{id:oe,className:"field-error",children:Ee.timeoutMs}):t.jsx("small",{children:l("schedule.timeoutHint","Maximum execution time in milliseconds.")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:l("schedule.executionPolicyLabel","Execution Policy")}),t.jsx("select",{id:"routine-execution-policy",value:_,onChange:_e=>V(_e.target.value),children:m.map(_e=>t.jsx("option",{value:_e.value,children:_e.label},_e.value))}),t.jsx("small",{children:l("schedule.executionPolicyHint","How to handle concurrent executions of this routine")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:l("schedule.catchUpPolicyLabel","Catch-up Policy")}),t.jsx("select",{id:"routine-catchup-policy",value:N,onChange:_e=>$(_e.target.value),children:p.map(_e=>t.jsx("option",{value:_e.value,children:_e.label},_e.value))}),t.jsx("small",{children:l("schedule.catchUpPolicyHint","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:R,onChange:_e=>L(_e.target.checked)}),l("schedule.enabledLabel","Enabled")]}),t.jsx("small",{children:l("schedule.enabledHint","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:Ke,children:l("common.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ke,children:Ke?l("common.saving","Saving…"):d?l("schedule.saveChanges","Save Changes"):l("schedule.createRoutine","Create Routine")})]})]})}const jU=3e4;function NU({onClose:e,addToast:n,projectId:s}){const{t:i}=st("app"),[r,o]=a.useState(()=>s?"project":"global"),[l,d]=a.useState([]),[c,m]=a.useState("list"),[p,h]=a.useState(),[u,f]=a.useState(null),[b,y]=a.useState({}),v=a.useRef(null);La(v,!0,"fusion:automation-modal-size");const x=a.useMemo(()=>({scope:r,projectId:r==="project"?s:void 0}),[r,s]),k=a.useCallback(async()=>{try{const $=await CA(x);d($),y(R=>{const L={...R};for(const O of $){const J=L[O.id];if(!J||!O.lastRunResult)continue;const A=O.lastRunResult;A.success===J.success&&(A.output||"")===J.output&&(A.error||"")===(J.error||"")&&delete L[O.id]}return L})}catch($){n(Re($)||i("schedule.loadRoutinesError","Failed to load routines"),"error")}},[n,x]);a.useEffect(()=>{k()},[k]),a.useEffect(()=>{const $=setInterval(()=>{k()},jU);return()=>clearInterval($)},[k]),a.useEffect(()=>{const $=R=>{R.key==="Escape"&&(c!=="list"?(m("list"),h(void 0)):e())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,c]);const w=yr(e),g=a.useCallback(async $=>{try{await _A($,x),n(i("schedule.routineCreated","Routine created"),"success"),m("list"),await k()}catch(R){n(Re(R)||i("schedule.createError","Failed to create routine"),"error")}},[n,k,x,i]),j=a.useCallback($=>{h($),m("edit")},[]),S=a.useCallback(async $=>{if(p)try{await Lg(p.id,$,x),n(i("schedule.routineUpdated","Routine updated"),"success"),m("list"),h(void 0),await k()}catch(R){n(Re(R)||i("schedule.updateError","Failed to update routine"),"error")}},[p,n,k,x,i]),C=a.useCallback(async $=>{try{await EA($.id,x),n(i("schedule.routineDeleted",'Deleted "{{name}}"',{name:$.name}),"success"),await k()}catch(R){n(Re(R)||i("schedule.deleteError","Failed to delete routine"),"error")}},[n,k,x,i]),E=a.useCallback(async $=>{f($.id);try{const{result:R}=await MA($.id,x);y(L=>({...L,[$.id]:{output:R.output||"",error:R.error,success:R.success}})),R.success?n(i("schedule.routineSuccess",'"{{name}}" completed successfully',{name:$.name}),"success"):n(i("schedule.routineFailed",'"{{name}}" failed: {{error}}',{name:$.name,error:R.error||i("schedule.unknownError","Unknown error")}),"error"),await k()}catch(R){n(Re(R)||i("schedule.runError","Failed to run routine"),"error")}finally{f(null)}},[n,k,x,i]),F=a.useCallback(async $=>{try{await Lg($.id,{enabled:!$.enabled},x),n(i(`schedule.routine${$.enabled?"Disabled":"Enabled"}`,`"{{name}}" ${$.enabled?"disabled":"enabled"}`,{name:$.name}),"success"),await k()}catch(R){n(Re(R)||i("schedule.toggleError","Failed to toggle routine"),"error")}},[n,k,x,i]),M=a.useCallback(()=>{m("list"),h(void 0)},[]);a.useEffect(()=>{c!=="list"&&y({})},[c]);const D=a.useCallback($=>{o($),m("list"),h(void 0),y({})},[]),_=()=>c==="create"?t.jsx(dy,{onSubmit:g,onCancel:M,scope:r,projectId:s}):c==="edit"&&p?t.jsx(dy,{routine:p,onSubmit:S,onCancel:M,scope:r,projectId:s}):l.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Ws,{size:48,strokeWidth:1}),t.jsx("h4",{children:i("schedule.noAutomations","No automations yet")}),t.jsx("p",{children:i("schedule.emptyStateDescription","Create an automation with a schedule, webhook, API, or manual trigger.")}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m("create"),children:[t.jsx(ys,{size:14}),i("schedule.createFirst","Create your first automation")]})]}):t.jsx("div",{className:"routine-list",children:l.map($=>t.jsx(pU,{routine:$,onEdit:j,onDelete:C,onRun:E,onToggle:F,running:u===$.id,lastRunOutput:b[$.id]??null},$.id))}),V=()=>_(),N=c==="list"&&l.length>0;return t.jsx("div",{className:"modal-overlay open",...w,children:t.jsxs("div",{ref:v,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(Ws,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:i("schedule.title","Automations")})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":i("common.close","Close"),children:t.jsx(Fn,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":i("schedule.scopeGroup","Scheduling scope"),children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${r==="global"?" active":""}`,onClick:()=>D("global"),"aria-pressed":r==="global",title:i("schedule.globalScope","Global (user-level) automations"),children:[t.jsx(Np,{size:14}),i("schedule.global","Global")]}),t.jsxs("button",{type:"button",className:`scope-btn${r==="project"?" active":""}`,onClick:()=>D("project"),"aria-pressed":r==="project",title:i("schedule.projectScope","Project-scoped automations"),children:[t.jsx(Zs,{size:14}),i("schedule.project","Project")]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Ws,{size:14}),i("schedule.automationCount","{{count}} automation{{plural}}",{count:l.length,plural:l.length===1?"":"s"})]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:N&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m("create"),"aria-label":i("schedule.createNew","Create new automation"),children:[t.jsx(ys,{size:14}),i("schedule.newAutomation","New Automation")]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:V()})]})})}const SU=3e4,mp=new Map,ih=new Map;function uy(e){return e??"default"}function my(e){const n=mp.get(e);return n?Date.now()>=n.expiresAt?(mp.delete(e),null):n:null}function CU(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),i=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:i}}async function _U(e){const n=ih.get(e);if(n)return n;const s=Yo().then(({providers:i,ghCli:r})=>{const l={...CU(i,r),ghCli:r,expiresAt:Date.now()+SU};return mp.set(e,l),l}).finally(()=>{ih.delete(e)});return ih.set(e,s),s}function zN(e){const n=uy(e),s=my(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,d]=a.useState(s?.ghCli),[c,m]=a.useState(s==null),p=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const u=uy(e),f=my(u);if(f)return r(f.hasAiProvider),l(f.hasGithub),d(f.ghCli),m(!1),p.current=!0,()=>{h=!0};p.current=!1;async function b(){!p.current&&m(!0);try{const v=await _U(u);if(h)return;r(v.hasAiProvider),l(v.hasGithub),d(v.ghCli)}catch{}finally{h||(p.current=!0,m(!1))}}return b(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:c,hasWarnings:!i||!o}),[i,o,c])}function BN({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:i}){const{t:r}=st("app");if(e&&n)return null;const o=i?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":r("setup.dismissWarning","Dismiss setup warning"),onClick:i,children:t.jsx(Fn,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:r("setup.compactWarning","⚠ Setup incomplete — AI and/or GitHub features will be limited.")}),o]});const l=[];return e||l.push({key:"ai",title:r("setup.noAiProvider","No AI provider connected"),description:r("setup.noAiProviderDesc","AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup.")}),n||l.push({key:"github",title:r("setup.noGithub","GitHub not connected"),description:r("setup.noGithubDesc","You won't be able to import issues from GitHub, but you can still create tasks manually.")}),t.jsxs("div",{className:`setup-warning-banner${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[o,l.map(d=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:d.title}),t.jsx("p",{className:"setup-warning-banner__description",children:d.description})]},d.key))]})}function EU({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o}){const{t:l}=st("app"),{confirm:d}=Yi(),c=Ji();ga(e);const{keyboardOverlap:m,viewportHeight:p,viewportOffsetTop:h,keyboardOpen:u}=Xa({enabled:c==="mobile"}),f=u?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${h}px`,...p!==null?{"--vv-height":`${p}px`}:{}}:{},[b,y]=a.useState(""),[v,x]=a.useState([]),[k,w]=a.useState("project-default"),[g,j]=a.useState(""),[S,C]=a.useState(""),[E,F]=a.useState([]),[M,D]=a.useState(!1),[_,V]=a.useState(""),[N,$]=a.useState(""),[R,L]=a.useState(""),[O,J]=a.useState(""),[A,de]=a.useState(""),[B,P]=a.useState("default"),[Z,T]=a.useState(!1),[ie,le]=a.useState(void 0),[be,Le]=a.useState(void 0),[xe,q]=a.useState(void 0),[ce,De]=a.useState(yi),[He,qe]=a.useState(void 0),[pe,te]=a.useState(!1),[me,se]=a.useState(""),[z,Y]=a.useState(null),{agents:he,loading:X}=vw(s),[ye,ot]=a.useState(!1),ue=a.useRef(null),[je,$e]=a.useState(!1),[Ce,We]=a.useState(""),ke=a.useRef(null),{hasAiProvider:Ee,hasGithub:Ze,loading:Ke}=zN(s),{nodes:dt}=Nu(),Fe=a.useCallback(()=>{ot(!0)},[]);a.useEffect(()=>{if(!ye)return;const re=_e=>{ue.current&&!ue.current.contains(_e.target)&&ot(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[ye]),a.useEffect(()=>{if(!je)return;const re=_e=>{ke.current&&!ke.current.contains(_e.target)&&($e(!1),We(""))};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[je]);const nt=i.filter(re=>!v.includes(re.id)).sort((re,_e)=>{const fe=_e.createdAt.localeCompare(re.createdAt);if(fe!==0)return fe;const Xe=parseInt(re.id.slice(re.id.lastIndexOf("-")+1),10)||0;return(parseInt(_e.id.slice(_e.id.lastIndexOf("-")+1),10)||0)-Xe}),Nt=Ce?nt.filter(re=>re.id.toLowerCase().includes(Ce.toLowerCase())||re.title&&re.title.toLowerCase().includes(Ce.toLowerCase())||re.description&&re.description.toLowerCase().includes(Ce.toLowerCase())):nt,Ft=(re,_e)=>re.length>_e?re.slice(0,_e)+"…":re,ze=me.trim(),it=ze.length>0&&!xu.test(ze),Mt=k==="existing"||k==="custom-new"||k==="shared-group",Ht=Mt&&!g.trim();a.useEffect(()=>{const re=b.trim()!==""||v.length>0||E.length>0||ie!==void 0||_!==""||N!==""||R!==""||O!==""||z!==null||be!==void 0||xe!==void 0||ce!==yi||He!==void 0||k!=="project-default"||g!==""||S!==""||pe||ze!=="";T(re)},[b,v,E,ie,_,N,R,O,z,be,xe,ce,He,k,g,S,pe,ze]);const Me=a.useCallback(async()=>{Z&&!await d({title:l("newTaskModal.discardChanges","Discard Changes"),message:l("newTaskModal.unsavedChanges","You have unsaved changes. Discard them?"),danger:!0})||(E.forEach(re=>URL.revokeObjectURL(re.previewUrl)),F([]),y(""),x([]),V(""),$(""),L(""),J(""),de(""),P("default"),le(void 0),Y(null),ot(!1),Le(void 0),q(void 0),De(yi),qe(void 0),w("project-default"),j(""),C(""),T(!1),te(!1),se(""),n())},[Z,n,E,d,l]),Ae=a.useCallback(async()=>{const re=b.trim();if(!(!re||M||it||Ht)){D(!0);try{const _e=_.indexOf("/"),fe=N.indexOf("/"),Xe=R.indexOf("/"),kt={title:void 0,description:re,column:"triage",dependencies:v.length?v:void 0,...ie!==void 0?{workflowId:ie}:{},...z?{assignedAgentId:z}:{},modelPresetId:B==="preset"&&A||void 0,modelProvider:_&&_e!==-1?_.slice(0,_e):void 0,modelId:_&&_e!==-1?_.slice(_e+1):void 0,validatorModelProvider:N&&fe!==-1?N.slice(0,fe):void 0,validatorModelId:N&&fe!==-1?N.slice(fe+1):void 0,planningModelProvider:R&&Xe!==-1?R.slice(0,Xe):void 0,planningModelId:R&&Xe!==-1?R.slice(Xe+1):void 0,thinkingLevel:O!==""?O:void 0,reviewLevel:be,...xe!==void 0?{autoMerge:xe}:{},priority:ce,nodeId:He,branchSelection:{mode:k,...Mt&&g.trim()?{branchName:g.trim()}:{},...S.trim()?{baseBranch:S.trim()}:{}},...pe||ze!==""?{githubTracking:{enabled:pe,...ze!==""?{repoOverride:ze}:{}}}:{}},Rt=await r(kt);if(E.length>0){const Vt=[];for(const Pt of E)try{await ku(Rt.id,Pt.file,s)}catch{Vt.push(Pt.file.name)}Vt.length>0&&o(l("newTaskModal.failedToUpload","Failed to upload: {{files}}",{files:Vt.join(", ")}),"error")}E.forEach(Vt=>URL.revokeObjectURL(Vt.previewUrl)),F([]),y(""),x([]),V(""),$(""),L(""),J(""),de(""),P("default"),le(void 0),Y(null),ot(!1),Le(void 0),q(void 0),De(yi),qe(void 0),w("project-default"),j(""),C(""),o(l("newTaskModal.taskCreated","Created {{taskId}}",{taskId:Rt.id}),"success"),n()}catch(_e){o(Re(_e)||l("newTaskModal.failedToCreate","Failed to create task"),"error")}finally{D(!1)}}},[b,v,E,_,N,R,O,M,it,Ht,r,o,n,s,B,A,ie,z,be,xe,ce,He,k,Mt,g,S,pe,ze,l]),ee=a.useCallback(re=>{re.key==="Escape"&&(re.preventDefault(),Me())},[Me]),Pe=(z?he.find(re=>re.id===z):void 0)?.name??z,oe=t.jsxs("div",{className:"new-task-quick-fields",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("newTaskModal.dependencies","Dependencies")}),t.jsxs("div",{className:"dep-trigger-wrap",ref:ke,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>$e(re=>!re),disabled:M,"data-testid":"dep-trigger",children:v.length>0?l("newTaskModal.selectedCount","{{count}} selected",{count:v.length}):l("newTaskModal.addDependencies","Add dependencies")}),je&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:l("newTaskModal.searchTasks","Search tasks…"),autoFocus:!0,value:Ce,onChange:re=>We(re.target.value),onClick:re=>re.stopPropagation()}),Nt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:l("newTaskModal.noAvailableTasks","No available tasks")}):Nt.map(re=>t.jsxs("div",{className:`dep-dropdown-item${v.includes(re.id)?" selected":""}`,onClick:()=>{x(v.includes(re.id)?v.filter(_e=>_e!==re.id):[...v,re.id]),$e(!1),We("")},onMouseDown:_e=>_e.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:re.id}),t.jsx("span",{className:"dep-dropdown-title",children:Ft(re.title||re.description||re.id,30)})]},re.id))]})]}),v.length>0&&t.jsx("div",{className:"selected-deps",children:v.map(re=>t.jsxs("span",{className:"dep-chip",children:[re,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>x(v.filter(_e=>_e!==re)),disabled:M,children:"×"})]},re))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("newTaskModal.assignAgent","Assign Agent")}),t.jsxs("div",{className:"agent-trigger-wrap",ref:ue,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ye?ot(!1):Fe()},disabled:M,"data-testid":"new-task-agent-button",children:[t.jsx(Is,{size:12,style:{verticalAlign:"middle"}}),Pe?` ${Pe}`:` ${l("newTaskModal.assignAgentButton","Assign agent")}`]}),ye&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:re=>re.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:l("newTaskModal.selectAgent","Select agent")}),X&&t.jsx("div",{className:"dep-dropdown-empty",children:l("newTaskModal.loadingAgents","Loading agents...")}),!X&&he.map(re=>t.jsxs("div",{className:`dep-dropdown-item${z===re.id?" selected":""}`,onMouseDown:_e=>_e.preventDefault(),onClick:()=>{Y(re.id===z?null:re.id),ot(!1)},"data-testid":`agent-option-${re.id}`,children:[t.jsx(Is,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:re.role}),t.jsx("span",{className:"dep-dropdown-title",children:re.name})]},re.id)),!X&&he.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:l("newTaskModal.noAgentsAvailable","No agents available")}),z&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:re=>re.preventDefault(),onClick:()=>{Y(null),ot(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:l("newTaskModal.clearSelection","Clear selection")})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Me,onKeyDown:ee,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:re=>re.stopPropagation(),style:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:l("newTaskModal.title","New Task")}),t.jsx("button",{className:"modal-close",onClick:Me,disabled:M,"aria-label":l("actions.close","Close"),children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Ke&&t.jsx(BN,{hasAiProvider:Ee,hasGithub:Ze}),t.jsx(iN,{mode:"create",description:b,onDescriptionChange:y,dependencies:v,onDependenciesChange:x,executorModel:_,onExecutorModelChange:V,validatorModel:N,onValidatorModelChange:$,presetMode:B,onPresetModeChange:P,selectedPresetId:A,onSelectedPresetIdChange:de,selectedWorkflowId:ie,onWorkflowIdChange:le,pendingImages:E,onImagesChange:F,tasks:i,projectId:s,disabled:M,addToast:o,isActive:e,onClose:Me,planningModel:R,onPlanningModelChange:L,thinkingLevel:O,onThinkingLevelChange:J,reviewLevel:be,onReviewLevelChange:Le,autoMerge:xe,onAutoMergeChange:q,priority:ce,onPriorityChange:De,branch:g,onBranchChange:j,branchMode:k,onBranchModeChange:w,baseBranch:S,onBaseBranchChange:C,nodeId:He,onNodeIdChange:qe,nodeOptions:dt,githubTrackingEnabled:pe,onGithubTrackingEnabledChange:te,githubRepoOverride:me,onGithubRepoOverrideChange:se,renderBelowPrimary:oe,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),Ht&&t.jsx("div",{className:"form-error new-task-branch-error",children:l("newTaskModal.branchRequired","Branch name is required for this branch strategy.")}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Me,disabled:M,children:l("actions.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ae,disabled:!b.trim()||M||it||Ht,children:M?l("newTaskModal.creating","Creating..."):l("newTaskModal.createTask","Create Task")})]})]})}):null}function ca(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 hy(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function MU(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function AU(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function TU(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function RU(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 xd(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function PU(e,n){if(!e)return n;const s=new Date(e);return Number.isNaN(s.getTime())?n:s.toLocaleString()}function IU({isOpen:e,onClose:n,projectId:s}){const{t:i}=st("app"),[r,o]=a.useState(null),[l,d]=a.useState(!1),[c,m]=a.useState(null),[p,h]=a.useState(!0),[u,f]=a.useState(90),[b,y]=a.useState(!1),[v,x]=a.useState(!1),[k,w]=a.useState(null),[g,j]=a.useState(null),[S,C]=a.useState(null),E=a.useCallback(async q=>{d(!0);try{const ce=await uT(s);o(ce),m(null),C(Date.now()),q?.preserveKillResult||w(null)}catch(ce){m(ce instanceof Error?ce.message:i("systemStats.errorLoadStats","Failed to load system stats"))}finally{d(!1)}},[s]);a.useEffect(()=>{if(!e)return;E();const q=window.setInterval(()=>{E()},5e3);return()=>{window.clearInterval(q)}},[e,E]),a.useEffect(()=>{if(!e)return;(async()=>{try{const ce=await Ja();h(ce.vitestAutoKillEnabled??!0),f(ce.vitestKillThresholdPct??90),j(null)}catch(ce){j(ce instanceof Error?ce.message:i("systemStats.errorLoadVitestSettings","Failed to load vitest settings"))}})()},[e]),a.useEffect(()=>{if(!e)return;const q=ce=>{ce.key==="Escape"&&n()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[e,n]);const F=a.useMemo(()=>{if(!r)return[];const q=r.systemStats,ce=xd(MU(q.heapUsed,q.heapLimit)),De=xd(AU(q.rss,q.systemTotalMem));return[{label:i("systemStats.rowRss","RSS"),value:ca(q.rss),detail:hy(q.rss,q.systemTotalMem),className:De},{label:i("systemStats.rowHeapUsed","Heap Used"),value:ca(q.heapUsed),detail:i("systemStats.rowHeapUsedDetail","of {{total}}",{total:ca(q.heapTotal)}),className:ce},{label:i("systemStats.rowHeapLimit","Heap Limit"),value:ca(q.heapLimit),detail:i("systemStats.rowHeapLimitDetail","V8 limit")},{label:i("systemStats.rowExternal","External"),value:ca(q.external)},{label:i("systemStats.rowArrayBuffers","Array Buffers"),value:ca(q.arrayBuffers)}]},[r]),M=a.useCallback(async q=>{h(q);try{await Ms({vitestAutoKillEnabled:q}),j(null)}catch(ce){j(ce instanceof Error?ce.message:i("systemStats.errorSaveVitestSettings","Failed to save vitest settings"))}},[]),D=a.useCallback(async q=>{const ce=Math.min(99,Math.max(50,Number.isFinite(q)?Math.round(q):90));f(ce);try{await Ms({vitestKillThresholdPct:ce}),j(null)}catch(De){j(De instanceof Error?De.message:i("systemStats.errorSaveVitestSettings","Failed to save vitest settings"))}},[]),_=a.useCallback(async()=>{if(!b){if(!v){x(!0);return}y(!0);try{const q=await mT(s);w(q),x(!1),await E({preserveKillResult:!0})}catch(q){m(q instanceof Error?q.message:i("systemStats.errorKillVitest","Failed to kill vitest processes"))}finally{y(!1)}}},[v,b,E,s]);if(!e)return null;const V=r?.systemStats,N=l&&!!r,$=S?i("systemStats.updatedAt","Updated {{time}}",{time:new Date(S).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):i("systemStats.waitingFirstUpdate","Waiting for first update"),R=r?.taskStats,L=V?V.systemTotalMem-V.systemFreeMem:0,O=V?TU(L,V.systemTotalMem):"normal",J=V?xd(O):"",A=V&&Number.isFinite(V.systemTotalMem)&&V.systemTotalMem>0?Math.max(0,Math.min(100,L/V.systemTotalMem*100)):0,de=V?i("systemStats.systemMemProgressLabel","System memory used: {{percent}}% ({{used}} of {{total}})",{percent:A.toFixed(1),used:ca(L),total:ca(V.systemTotalMem)}):i("systemStats.systemMemUnavailable","System memory usage unavailable"),B=r?.vitestProcessCount,P=RU(V?.cpuPercent??null,V?.cpuCount??0),Z=xd(P),T=V?.cpuPercent??null,ie=T===null?0:Math.max(0,Math.min(100,T)),le=T===null?i("systemStats.cpuSampling","Sampling…"):`${T.toFixed(1)}%`,be=T===null?i("systemStats.cpuProgressUnavailable","App CPU usage unavailable: waiting for another sample"):i("systemStats.cpuProgressLabel","App CPU usage: {{percent}}%",{percent:T.toFixed(1)}),Le=k?k.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",xe=PU(r?.vitestLastAutoKillAt,i("systemStats.notYet","Not yet"));return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:q=>{q.target===q.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(Ko,{}),t.jsx("span",{children:i("systemStats.title","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:i("systemStats.autoRefresh","Auto-refresh · 5s")}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:$})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void E(),title:i("systemStats.refreshTitle","Refresh"),"aria-label":i("systemStats.refreshAriaLabel","Refresh system stats"),children:t.jsx(xs,{size:16,className:N?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":i("systemStats.closeAriaLabel","Close"),children:t.jsx(Fn,{})})]})]}),l&&!r&&t.jsx("div",{className:"system-stats-modal__state",children:i("systemStats.loading","Loading system stats…")}),c&&!r&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),r&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionProcessAriaLabel","Process stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionProcess","Process")}),t.jsx("dl",{className:"system-stats-modal__grid",children:F.map(q=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:q.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${q.className}`.trim(),children:q.value}),q.detail?t.jsx("span",{className:"system-stats-modal__detail",children:q.detail}):null]})]},q.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionCpuAriaLabel","CPU and load stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionCpu","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:i("systemStats.rowAppCpu","App CPU")}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${Z}`.trim(),children:le}),t.jsx("span",{className:"system-stats-modal__detail",children:T===null?i("systemStats.cpuFirstSamplePending","First sample pending"):i("systemStats.cpuProcessUsage","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--${P}`,role:"progressbar","aria-valuenow":Math.round(ie),"aria-valuemin":0,"aria-valuemax":100,"aria-label":be,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${P}`,style:{width:`${ie}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowLoadAvg","Load Avg")}),t.jsx("dd",{children:V?.loadAvg.map(q=>q.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowCores","Cores")}),t.jsx("dd",{children:V?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowPlatform","Platform")}),t.jsx("dd",{children:V?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowNode","Node")}),t.jsx("dd",{children:V?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowPid","PID")}),t.jsx("dd",{children:V?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionSystemMemAriaLabel","System memory stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionSystem","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:i("systemStats.rowMemoryUsed","Memory Used")}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${J}`.trim(),children:V?ca(L):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:V?`${hy(L,V.systemTotalMem)} of ${ca(V.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--${O}`,role:"progressbar","aria-valuenow":Math.round(A),"aria-valuemin":0,"aria-valuemax":100,"aria-label":de,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${O}`,style:{width:`${A}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowMemoryFree","Memory Free")}),t.jsx("dd",{children:V?ca(V.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionTasksAriaLabel","Task stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionTasks","Tasks")}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowTotal","Total")}),t.jsx("dd",{children:R?.total??0})]}),Object.entries(R?.byColumn??{}).map(([q,ce])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:q}),t.jsx("dd",{children:ce})]},q))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionAgentsAriaLabel","Agent stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionAgents","Agents")}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.agentIdle","idle")}),t.jsx("dd",{children:R?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.agentActive","active")}),t.jsx("dd",{children:R?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.agentRunning","running")}),t.jsx("dd",{children:R?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.agentError","error")}),t.jsx("dd",{children:R?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionVitestAriaLabel","Vitest controls"),children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(V1,{}),t.jsx("span",{children:i("systemStats.sectionVitest","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:i("systemStats.vitestProcesses","Vitest Processes")}),t.jsx("dd",{children:B??"—"})]})}),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 _(),disabled:b||B===0,children:[t.jsx(K1,{}),t.jsx("span",{children:v?i("systemStats.confirmKill","Confirm Kill?"):i("systemStats.killVitest","Kill Vitest Processes")})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:p,onChange:q=>{M(q.target.checked)}}),t.jsx("span",{children:i("systemStats.autoKillLabel","Auto-kill vitest on memory pressure")})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:i("systemStats.killThresholdLabel","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:u,"aria-label":i("systemStats.killThresholdSliderAriaLabel","Kill threshold slider (%)"),onChange:q=>{const ce=Number.parseInt(q.target.value,10);D(Number.isNaN(ce)?90:ce)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:u,"aria-label":i("systemStats.killThresholdInputAriaLabel","Kill threshold (%)"),onChange:q=>{const ce=Number.parseInt(q.target.value,10);D(Number.isNaN(ce)?90:ce)},onBlur:()=>{D(u)}})]})]}),k&&t.jsx("p",{className:Le,children:i("systemStats.killedProcesses","Killed {{count}} processes",{count:k.killed})}),t.jsx("p",{className:"system-stats-modal__last-kill",children:i("systemStats.lastAutoKill","Last auto-kill: {{time}}",{time:xe})}),g&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:g})]})]})]}),c&&r&&t.jsx("div",{className:"system-stats-modal__footer-error",children:i("systemStats.footerRefreshFailed","Latest refresh failed: {{error}}",{error:c})})]})})}const DU=5e3;function LU(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,d]=a.useState([]),[c,m]=a.useState(!1),[p,h]=a.useState(null),[u,f]=a.useState(!1),b=a.useRef(null),y=a.useRef(void 0),v=a.useCallback(async()=>{try{m(!0),h(null);let w;o?w=await Hg({limit:i,projectId:n,type:s}):w=(await Fg({limit:i,type:s,projectId:n})).map(j=>({...j,projectId:n??"",projectName:""})),d(w),f(w.length===i),w.length>0&&(y.current=w[w.length-1].timestamp)}catch(w){h(w instanceof Error?w.message:"Failed to load activity log")}finally{m(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(y.current)try{m(!0);let w;o?w=await Hg({limit:i,projectId:n,type:s,since:y.current}):w=(await Fg({limit:i,type:s,since:y.current,projectId:n})).map(j=>({...j,projectId:n??"",projectName:""})),d(g=>[...g,...w]),f(w.length===i),w.length>0&&(y.current=w[w.length-1].timestamp)}catch(w){h(w instanceof Error?w.message:"Failed to load more entries")}finally{m(!1)}},[i,n,s,o]),k=a.useCallback(()=>{d([]),f(!1),y.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return b.current=setInterval(()=>{v()},DU),()=>{b.current&&(clearInterval(b.current),b.current=null)}},[r,v]),{entries:l,loading:c,error:p,refresh:v,clear:k,hasMore:u,loadMore:x}}function FU(e){return{"task:created":e("activityLog.eventType.taskCreated","Task Created"),"task:moved":e("activityLog.eventType.taskMoved","Task Moved"),"task:updated":e("activityLog.eventType.taskUpdated","Task Updated"),"task:deleted":e("activityLog.eventType.taskDeleted","Task Deleted"),"task:merged":e("activityLog.eventType.taskMerged","Task Merged"),"task:failed":e("activityLog.eventType.taskFailed","Task Failed"),"task:duplicate-warning-overridden":e("activityLog.eventType.duplicateWarningOverridden","Duplicate Warning Overridden"),"task:auto-archived-ghost-bug":e("activityLog.eventType.autoArchivedGhostBug","Task Auto-Archived (Ghost Bug)"),"task:auto-archived-duplicate":e("activityLog.eventType.autoArchivedDuplicate","Task Auto-Archived (Duplicate)"),"task:merge-worktree-reacquired":e("activityLog.eventType.mergeWorktreeReacquired","Merge Worktree Reacquired"),"task:auto-archived-deterministic-duplicate":e("activityLog.eventType.autoArchivedDeterministicDuplicate","Task Auto-Archived (Deterministic Duplicate)"),"task:auto-archived-near-duplicate":e("activityLog.eventType.autoArchivedNearDuplicate","Task Auto-Archived (Near-Duplicate)"),"task:near-duplicate-flagged":e("activityLog.eventType.nearDuplicateFlagged","Near-Duplicate Flagged"),"settings:updated":e("activityLog.eventType.settingsUpdated","Settings Updated"),"project:isolation-transition":e("activityLog.eventType.projectIsolationTransition","Project Isolation Transition")}}const OU={"task:created":t.jsx(ys,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(fc,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(xs,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Fn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Es,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(vr,{size:14,className:"activity-icon failed"}),"task:duplicate-warning-overridden":t.jsx(oi,{size:14,className:"activity-icon updated"}),"task:auto-archived-ghost-bug":t.jsx(oi,{size:14,className:"activity-icon failed"}),"task:auto-archived-duplicate":t.jsx(as,{size:14,className:"activity-icon deleted"}),"task:auto-archived-deterministic-duplicate":t.jsx(as,{size:14,className:"activity-icon deleted"}),"task:auto-archived-near-duplicate":t.jsx(as,{size:14,className:"activity-icon deleted"}),"task:near-duplicate-flagged":t.jsx(oi,{size:14,className:"activity-icon updated"}),"task:merge-worktree-reacquired":t.jsx(xs,{size:14,className:"activity-icon updated"}),"settings:updated":t.jsx(Ql,{size:14,className:"activity-icon settings"}),"project:isolation-transition":t.jsx(Zs,{size:14,className:"activity-icon settings"})};function $U(e,n){const s=new Date(e),r=new Date().getTime()-s.getTime(),o=Math.floor(r/6e4),l=Math.floor(r/36e5),d=Math.floor(r/864e5);return o<1?n("activityLog.time.justNow","Just now"):o<60?n("activityLog.time.minutesAgo","{{count}}m ago",{count:o}):l<24?n("activityLog.time.hoursAgo","{{count}}h ago",{count:l}):d<7?n("activityLog.time.daysAgo","{{count}}d ago",{count:d}):s.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function zU({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:d}){const{t:c}=st("app"),m=FU(c),[p,h]=a.useState("all"),[u,f]=a.useState(r||"all"),[b,y]=a.useState(!1);a.useEffect(()=>{f(r||"all")},[r]);const v=p==="all"?void 0:p,x=u==="all"?void 0:u,k=!d&&o.length>0,{entries:w,loading:g,error:j,refresh:S,hasMore:C}=LU({projectId:x,type:v,limit:100,autoRefresh:e,useCentralFeed:k}),E=w.map(V=>({id:V.id,timestamp:V.timestamp,type:V.type,taskId:V.taskId,taskTitle:V.taskTitle,details:V.details,metadata:V.metadata,projectId:V.projectId,projectName:V.projectName})),F=async()=>{try{await AA(),S(),y(!1)}catch{y(!1)}},M=V=>{i&&i(V)},D=V=>{f(V),l?.(V==="all"?void 0:V)};a.useEffect(()=>{if(!e)return;const V=N=>{N.key==="Escape"&&(b?y(!1):n())};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[e,n,b]);const _=p!=="all"||u!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:V=>{V.target===V.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(Ur,{size:18}),t.jsx("span",{children:c("activityLog.title","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(Zs,{size:14}),t.jsxs("select",{value:u,onChange:V=>D(V.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:c("activityLog.allProjects","All Projects")}),o.map(V=>t.jsx("option",{value:V.id,children:V.name},V.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Ld,{size:14}),t.jsxs("select",{value:p,onChange:V=>h(V.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:c("activityLog.allEvents","All Events")}),Object.entries(m).map(([V,N])=>t.jsx("option",{value:V,children:N},V))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>S(),title:c("activityLog.refresh","Refresh"),"data-testid":"activity-refresh",children:g?t.jsx(Et,{size:14,className:"spin"}):t.jsx(xs,{size:14})}),E.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>y(!0),title:c("activityLog.clearLog","Clear Log"),"data-testid":"activity-clear",children:t.jsx(as,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":c("actions.close","Close"),title:c("actions.close","Close"),"data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:c("activityLog.activeFilters","Active filters:")}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(V=>V.id===u)?.name||u]}),p!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",m[p]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{h("all"),f("all"),l?.(void 0)},children:c("activityLog.clearFilters","Clear all")})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[j&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(oi,{size:16}),t.jsx("span",{children:j})]}),E.length===0&&!g&&!j&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Ur,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?c("activityLog.noMatchingActivity","No activity matches the current filters"):c("activityLog.noActivityRecorded","No activity recorded yet")}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{h("all"),f("all"),l?.(void 0)},children:c("activityLog.clearFiltersBtnLabel","Clear Filters")})]}),t.jsx("div",{className:"activity-log-list",children:E.map(V=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:OU[V.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:m[V.type]}),t.jsx("span",{className:"activity-log-entry-time",children:$U(V.timestamp,c)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[V.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>M(V.taskId),"data-testid":"activity-task-link",children:V.taskId}),V.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:V.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:Hs(V.details??"")})]}),V.metadata&&Object.keys(V.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof V.metadata.from=="string"&&typeof V.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[V.metadata.from," → ",V.metadata.to]}),typeof V.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${V.metadata.merged?"success":"error"}`,children:V.metadata.merged?c("activityLog.merged","Merged"):c("activityLog.notMerged","Not merged")})]})]})]},V.id))}),C&&!g&&t.jsx("button",{className:"activity-log-load-more",onClick:S,"data-testid":"activity-load-more",children:c("activityLog.loadMore","Load More")}),g&&E.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(Et,{size:20,className:"spin"})})]}),b&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:c("activityLog.confirmClear","Clear Activity Log?")}),t.jsx("p",{children:c("activityLog.confirmClearMessage","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:()=>y(!1),children:c("actions.cancel","Cancel")}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:F,children:c("activityLog.confirmClearButton","Clear Log")})]})]})})]})}):null}const Fl=[{id:"status",label:"Status",icon:Ak},{id:"changes",label:"Changes",icon:kh},{id:"commits",label:"Commits",icon:vc},{id:"branches",label:"Branches",icon:ui},{id:"worktrees",label:"Worktrees",icon:O0},{id:"stashes",label:"Stashes",icon:Qr},{id:"remotes",label:"Remotes",icon:rc}];function py({status:e}){switch(e){case"added":case"untracked":return t.jsx(p0,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(jk,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(c0,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Hr,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(g0,{size:14,className:"gm-file-icon"})}}function fy({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 BU(e){const{t:n}=st("app");return a.useCallback(async(s,i)=>{try{await navigator.clipboard.writeText(s),e(i?n("git.copiedLabel","Copied {{label}}",{label:i}):n("git.copiedToClipboard","Copied to clipboard"),"success")}catch{e(n("git.failedToCopy","Failed to copy"),"error")}},[e,n])}function sl(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function UU({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const{t:o}=st("app"),l=Yi(),d=Ji();ga(e);const{keyboardOverlap:c,viewportHeight:m,viewportOffsetTop:p,keyboardOpen:h}=Xa({enabled:d==="mobile"}),u=h?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${p}px`,...m!==null?{"--vv-height":`${m}px`}:{}}:{},f=a.useCallback(()=>{if(d==="mobile"){const G=document.activeElement;G instanceof HTMLElement&&G.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,d]),[b,y]=a.useState("status"),[v,x]=a.useState(!1),[k,w]=a.useState(null),g=a.useRef(null);La(g,e,"fusion:git-modal-size");const j=yr(f),S=BU(i),[C,E]=a.useState(null),[F,M]=a.useState(null),[D,_]=a.useState([]),[V,N]=a.useState(new Set),[$,R]=a.useState(""),[L,O]=a.useState(!1),[J,A]=a.useState(null),[de,B]=a.useState(!1),[P,Z]=a.useState(null),[T,ie]=a.useState(null),le=a.useRef(0),[be,Le]=a.useState([]),[xe,q]=a.useState(null),[ce,De]=a.useState(null),[He,qe]=a.useState(!1),[pe,te]=a.useState(20),[me,se]=a.useState(""),[z,Y]=a.useState([]),[he,X]=a.useState(""),[ye,ot]=a.useState(""),[ue,je]=a.useState(""),[$e,Ce]=a.useState(null),[We,ke]=a.useState([]),[Ee,Ze]=a.useState(!1),[Ke,dt]=a.useState(null),[Fe,nt]=a.useState(null),[Nt,Ft]=a.useState(!1),[ze,it]=a.useState([]),[Mt,Ht]=a.useState([]),[Me,Ae]=a.useState(""),[ee,Ie]=a.useState(null),[Pe,oe]=a.useState(null),[re,_e]=a.useState(null),[fe,Xe]=a.useState(!1),[kt,Rt]=a.useState(null),Vt=a.useRef(0),[Pt,bt]=a.useState(null),[pt,ft]=a.useState(null),_t=a.useCallback(async()=>{if(e){x(!0),w(null);try{switch(b){case"status":{const G=await Ui(r,{extended:!0});E(G);break}case"changes":{const[G,Oe]=await Promise.all([Ui(r,{extended:!0}),bo(r)]);E(G),_(Oe),N(new Set),ie(null),A(null),Z(null);break}case"commits":{const G=await PM(pe,r);Le(G);break}case"branches":{const[G,Oe]=await Promise.all([Ro(r),Ui(r,{extended:!0})]);Y(G),E(Oe);break}case"worktrees":{const G=await FM(r);it(G);break}case"stashes":{const G=await Hc(r);Ht(G),oe(null),_e(null),Rt(null),Vt.current+=1;break}case"remotes":{const G=await Ui(r,{extended:!0});E(G);break}}}catch(G){w(Re(G)||o("git.failedToFetchData","Failed to fetch git data")),i(Re(G)||o("git.failedToFetchData","Failed to fetch git data"),"error")}finally{x(!1)}}},[b,e,pe,i,r]);a.useEffect(()=>{e&&_t()},[_t,e]),a.useEffect(()=>{if(!e)return;const G=Oe=>{if(Oe.key==="Escape"){f();return}if((Oe.key==="ArrowUp"||Oe.key==="ArrowDown")&&Oe.altKey){Oe.preventDefault();const yt=Fl.findIndex(Gt=>Gt.id===b);Oe.key==="ArrowUp"&&yt>0?y(Fl[yt-1].id):Oe.key==="ArrowDown"&&yt<Fl.length-1&&y(Fl[yt+1].id)}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[e,f,b]);const Yt=a.useCallback(async G=>{try{await Tg(G,r),i(o("git.stagedFiles","Staged {{count}} file(s)",{count:G.length}),"success");const Oe=await bo(r);_(Oe),N(new Set),ie(null),A(null),Z(null)}catch(Oe){i(Re(Oe)||o("git.failedToStageFiles","Failed to stage files"),"error")}},[i,r]),on=a.useCallback(async G=>{try{await WM(G,r),i(o("git.unstagedFiles","Unstaged {{count}} file(s)",{count:G.length}),"success");const Oe=await bo(r);_(Oe),N(new Set),ie(null),A(null),Z(null)}catch(Oe){i(Re(Oe)||o("git.failedToUnstageFiles","Failed to unstage files"),"error")}},[i,r]),An=a.useCallback(async G=>{if(await l.confirm({title:o("git.discardChangesTitle","Discard Changes"),message:o("git.discardChangesMessage","Discard changes to {{count}} file(s)? This cannot be undone.",{count:G.length}),danger:!0}))try{await GM(G,r),i(o("git.discardedFiles","Discarded changes to {{count}} file(s)",{count:G.length}),"success");const[yt,Gt]=await Promise.all([bo(r),Ui(r,{extended:!0})]);_(yt),E(Gt),N(new Set),ie(null),A(null),Z(null)}catch(yt){i(Re(yt)||o("git.failedToDiscardChanges","Failed to discard changes"),"error")}},[i,r,l]),vn=a.useCallback(async G=>{if(G.preventDefault(),!!$.trim()){O(!0);try{const Oe=await Rg($.trim(),r);i(o("git.committedHash","Committed: {{hash}}",{hash:Oe.hash}),"success"),R("");const[yt,Gt]=await Promise.all([bo(r),Ui(r,{extended:!0})]);_(yt),E(Gt),ie(null),A(null),Z(null)}catch(Oe){i(Re(Oe)||o("git.failedToCommit","Failed to commit"),"error")}finally{O(!1)}}},[$,i,r,o]),Qt=a.useCallback(async()=>{if($.trim()){O(!0);try{const G=D.filter(Sn=>!Sn.staged).map(Sn=>Sn.file);G.length>0&&await Tg(G,r);const Oe=await Rg($.trim(),r);i(o("git.committedHash","Committed: {{hash}}",{hash:Oe.hash}),"success"),R("");const[yt,Gt]=await Promise.all([bo(r),Ui(r,{extended:!0})]);_(yt),E(Gt),ie(null),A(null),Z(null)}catch(G){i(Re(G)||o("git.failedToCommit","Failed to commit"),"error")}finally{O(!1)}}},[$,D,i,r,o]),sn=a.useCallback(async(G,Oe)=>{ie({file:G,staged:Oe}),B(!0),Z(null);const yt=le.current+1;le.current=yt;try{const Gt=await qM(G,Oe,r);if(le.current!==yt)return;A(Gt)}catch(Gt){if(le.current!==yt)return;const Sn=Re(Gt)||o("git.failedToLoadFileDiff","Failed to load file diff");A(null),Z(Sn),i(Sn,"error")}finally{le.current===yt&&B(!1)}},[i,r,o]),mn=a.useCallback(G=>{N(Oe=>{const yt=new Set(Oe);return yt.has(G)?yt.delete(G):yt.add(G),yt})},[]),Kt=a.useCallback(async G=>{if(xe===G){q(null),De(null);return}q(G),qe(!0);try{const Oe=await Ud(G,r);De(Oe)}catch(Oe){i(Re(Oe)||o("git.failedToLoadDiff","Failed to load diff"),"error"),De(null)}finally{qe(!1)}},[xe,i,r]),fn=a.useCallback(()=>{te(G=>Math.min(G+20,100))},[]),$n=a.useMemo(()=>{if(!me.trim())return be;const G=me.toLowerCase();return be.filter(Oe=>Oe.message.toLowerCase().includes(G)||Oe.author.toLowerCase().includes(G)||Oe.shortHash.toLowerCase().includes(G))},[be,me]),On=a.useCallback(async G=>{if(G.preventDefault(),!!he.trim()){x(!0);try{await OM(he.trim(),ye.trim()||void 0,r),i(o("git.createdBranch","Created branch {{name}}",{name:he}),"success"),X(""),ot("");const Oe=await Ro(r);Y(Oe)}catch(Oe){i(Re(Oe)||o("git.failedToCreateBranch","Failed to create branch"),"error")}finally{x(!1)}}},[he,ye,i,r]),xn=a.useCallback(async G=>{x(!0);try{await $M(G,r),i(o("git.switchedToBranch","Switched to {{name}}",{name:G}),"success");const[Oe,yt]=await Promise.all([Ui(r,{extended:!0}),Ro(r)]);E(Oe),Y(yt)}catch(Oe){i(Re(Oe)||o("git.failedToCheckoutBranch","Failed to checkout branch"),"error")}finally{x(!1)}},[i,r]),Vn=a.useCallback(async G=>{if(await l.confirm({title:o("git.deleteBranchTitle","Delete Branch"),message:o("git.deleteBranchMessage",'Delete branch "{{name}}"?',{name:G}),danger:!0})){x(!0);try{await Eg(G,void 0,r),i(o("git.deletedBranch","Deleted branch {{name}}",{name:G}),"success");const yt=await Ro(r);Y(yt)}catch(yt){if(Re(yt).includes("not fully merged")){if(await l.confirm({title:o("git.forceDeleteBranchTitle","Force Delete Branch"),message:o("git.forceDeleteBranchMessage","Branch has unmerged commits. Force delete?"),danger:!0}))try{await Eg(G,!0,r),i(o("git.forceDeletedBranch","Force deleted branch {{name}}",{name:G}),"success");const Sn=await Ro(r);Y(Sn)}catch(Sn){i(Re(Sn)||o("git.failedToDeleteBranch","Failed to delete branch"),"error")}}else i(Re(yt)||o("git.failedToDeleteBranch","Failed to delete branch"),"error")}finally{x(!1)}}},[i,r,l]),Rn=a.useMemo(()=>{if(!ue.trim())return z;const G=ue.toLowerCase();return z.filter(Oe=>Oe.name.toLowerCase().includes(G))},[z,ue]),Pn=a.useCallback(async G=>{if($e===G){Ce(null),ke([]),dt(null),nt(null);return}Ce(G),ke([]),dt(null),nt(null),Ze(!0);try{const Oe=await LM(G,10,r);ke(Oe)}catch{ke([])}finally{Ze(!1)}},[$e,r]),zn=a.useCallback(async G=>{if(Ke===G){dt(null),nt(null);return}dt(G),nt(null),Ft(!0);try{const Oe=await Ud(G,r);nt(Oe)}catch{nt(null)}finally{Ft(!1)}},[Ke,r]),Nn=a.useCallback(()=>{Ce(null),ke([]),dt(null),nt(null)},[]),dn=a.useCallback(()=>{Vt.current+=1,oe(null),_e(null),Rt(null),Xe(!1)},[]),Tt=a.useCallback(async G=>{G.preventDefault(),Ie("create"),dn();try{await BM(Me.trim()||void 0,r),i(o("git.changesStashed","Changes stashed"),"success"),Ae("");const Oe=await Hc(r);Ht(Oe)}catch(Oe){i(Re(Oe)||o("git.failedToStashChanges","Failed to stash changes"),"error")}finally{Ie(null)}},[Me,i,r,dn]),Yn=a.useCallback(async(G,Oe=!1)=>{Ie(`apply-${G}`),dn();try{await UM(G,Oe,r),i(Oe?o("git.stashPopped","Stash popped"):o("git.stashApplied","Stash applied"),"success");const yt=await Hc(r);Ht(yt)}catch(yt){i(Re(yt)||o("git.failedToApplyStash","Failed to apply stash"),"error")}finally{Ie(null)}},[i,r,dn]),cn=a.useCallback(async G=>{if(await l.confirm({title:o("git.dropStashTitle","Drop Stash"),message:o("git.dropStashMessage","Drop stash@{{{index}}}? This cannot be undone.",{index:G}),danger:!0})){Ie(`drop-${G}`),dn();try{await HM(G,r),i(o("git.stashDropped","Stash dropped"),"success");const yt=await Hc(r);Ht(yt)}catch(yt){i(Re(yt)||o("git.failedToDropStash","Failed to drop stash"),"error")}finally{Ie(null)}}},[i,r,l,dn]),Bn=a.useCallback(async G=>{if(Pe===G){dn();return}const Oe=Vt.current+1;Vt.current=Oe,oe(G),_e(null),Rt(null),Xe(!0);try{const yt=await VM(G,r);if(Vt.current!==Oe)return;_e(yt)}catch(yt){if(Vt.current!==Oe)return;_e(null),Rt(Re(yt)||o("git.failedToLoadStashDiff","Failed to load stash diff"))}finally{Vt.current===Oe&&Xe(!1)}},[Pe,r,dn]),kn=a.useCallback(async()=>{bt("fetch");try{const G=await zM(void 0,r);ft(G),i(G.message||o("git.fetchCompleted","Fetch completed"),G.fetched?"success":"info");const Oe=await Ui(r,{extended:!0});E(Oe)}catch(G){i(Re(G)||o("git.fetchFailed","Fetch failed"),"error")}finally{bt(null)}},[i,r]),pn=a.useCallback(async G=>{bt("pull");try{const Oe=await Mg(G,r);if(ft(Oe),Oe.conflict)i(o("git.mergeConflictDetected","Merge conflict detected. Resolve manually."),"error");else{const Gt=G?.rebase?o("git.pullRebaseCompleted","Pull --rebase completed"):o("git.pullCompleted","Pull completed");i(Oe.message||Gt,"success")}const yt=await Ui(r,{extended:!0});E(yt)}catch(Oe){i(Re(Oe)||o("git.pullFailed","Pull failed"),"error")}finally{bt(null)}},[i,r]),un=a.useCallback(async()=>{bt("push");try{const G=await Ag(r);ft(G),i(G.message||o("git.pushCompleted","Push completed"),"success");const Oe=await Ui(r,{extended:!0});E(Oe)}catch(G){i(Re(G)||o("git.pushFailed","Push failed"),"error")}finally{bt(null)}},[i,r]),At=a.useCallback(async()=>{bt("sync");try{const G=await Mg({rebase:!0},r);if(ft(G),G.conflict){i(o("git.mergeConflictDetected","Merge conflict detected. Resolve manually."),"error");return}const Oe=await Ag(r);ft(Oe),i(o("git.syncedWithOrigin","Synced with origin (pull --rebase + push)"),"success");const yt=await Ui(r,{extended:!0});E(yt)}catch(G){i(Re(G)||o("git.syncWithOriginFailed","Sync with origin failed"),"error")}finally{bt(null)}},[i,r]);a.useEffect(()=>{Jk(r).then(G=>M(G.rootDir)).catch(()=>M(null))},[r]);const an=a.useCallback(async()=>{if(!C?.integrationBranch||C.isOnIntegrationBranch===!1)return;const G=F;if(!G){i(o("git.projectRootNotAvailable","Project root path not available"),"error");return}bt("sync-integration");try{const Oe=r?`?projectId=${encodeURIComponent(r)}`:"";await I(`/git/pull${Oe}`,{method:"POST",body:JSON.stringify({worktreePath:G,integrationBranch:C.integrationBranch,taskId:void 0,skipOriginFetch:!0})}),i(o("git.syncedWorktreeToIntegrationTip","Synced worktree to local integration tip"),"success");const yt=await Ui(r,{extended:!0});E(yt)}catch(Oe){i(Re(Oe)||o("git.syncFailed","Sync failed"),"error")}finally{bt(null)}},[i,r,F,C?.integrationBranch,C?.isOnIntegrationBranch,o]),Wn=a.useMemo(()=>D.filter(G=>G.staged),[D]),Xn=a.useMemo(()=>D.filter(G=>!G.staged),[D]);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:g,style:u,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(wh,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),o("git.modalTitle","Git Manager")]}),t.jsxs("div",{className:"gm-header-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:_t,disabled:v,title:o("git.refresh","Refresh"),children:t.jsx(xs,{size:14,className:v?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":o("git.close","Close"),children:t.jsx(Fn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":o("git.sidebarAriaLabel","Git Manager Sections"),children:Fl.map(G=>{const Oe=G.icon,yt={status:o("git.sectionStatus","Status"),changes:o("git.sectionChanges","Changes"),commits:o("git.sectionCommits","Commits"),branches:o("git.sectionBranches","Branches"),worktrees:o("git.sectionWorktrees","Worktrees"),stashes:o("git.sectionStashes","Stashes"),remotes:o("git.sectionRemotes","Remotes")}[G.id]??G.label;return t.jsxs("button",{role:"tab","aria-selected":b===G.id,className:`gm-nav-item${b===G.id?" active":""}`,onClick:()=>y(G.id),children:[t.jsx(Oe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:yt})]},G.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[v&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(Et,{size:24,className:"spin"}),t.jsx("span",{children:o("git.loading","Loading...")})]}),k&&!v&&t.jsxs("div",{className:"gm-error",children:[t.jsx(oi,{size:18}),t.jsx("span",{children:k}),t.jsx("button",{className:"btn btn-sm",onClick:_t,children:o("git.retry","Retry")})]}),b==="status"&&!v&&C&&t.jsx(HU,{status:C,copyToClipboard:S,onSyncWorkingTree:an,syncing:Pt==="sync-integration"}),b==="changes"&&!v&&t.jsx(VU,{status:C,stagedFiles:Wn,unstagedFiles:Xn,selectedFiles:V,toggleFileSelection:mn,onStageFiles:Yt,onUnstageFiles:on,onDiscardChanges:An,onSelectDiffFile:sn,selectedDiffTarget:T,changeDiff:J,loadingChangeDiff:de,changeDiffError:P,commitMessage:$,setCommitMessage:R,onCommit:vn,onStageAllAndCommit:Qt,committing:L}),b==="commits"&&!v&&t.jsx(qU,{commits:$n,commitSearch:me,setCommitSearch:se,selectedCommit:xe,commitDiff:ce,loadingDiff:He,onCommitClick:Kt,onLoadMore:fn,canLoadMore:be.length>=pe&&pe<100,copyToClipboard:S}),b==="branches"&&!v&&t.jsx(WU,{branches:Rn,branchSearch:ue,setBranchSearch:je,newBranchName:he,setNewBranchName:X,branchBase:ye,setBranchBase:ot,onCreateBranch:On,onCheckoutBranch:xn,onDeleteBranch:Vn,loading:v,allBranches:z,selectedBranch:$e,branchCommits:We,loadingBranchCommits:Ee,expandedBranchCommit:Ke,branchCommitDiff:Fe,loadingBranchCommitDiff:Nt,onSelectBranch:Pn,onBranchCommitClick:zn,onCloseBranchDetails:Nn}),b==="worktrees"&&!v&&t.jsx(GU,{worktrees:ze}),b==="stashes"&&!v&&t.jsx(KU,{stashes:Mt,stashMessage:Me,setStashMessage:Ae,onCreateStash:Tt,onApplyStash:Yn,onDropStash:cn,onToggleStashDiff:Bn,stashLoading:ee,expandedStashIndex:Pe,stashDiff:re,loadingStashDiff:fe,stashDiffError:kt}),b==="remotes"&&!v&&t.jsx(JU,{status:C,remoteLoading:Pt,lastRemoteResult:pt,onFetch:kn,onPull:pn,onPush:un,onSync:At,onSyncIntegrationTip:an,syncIntegrationDisabled:!C?.integrationBranch||C?.isOnIntegrationBranch===!1||Pt!==null,addToast:i,projectId:r,copyToClipboard:S})]})]})]})}):null}function HU({status:e,copyToClipboard:n,onSyncWorkingTree:s,syncing:i}){const{t:r}=st("app"),[o,l]=a.useState(!1),[d,c]=a.useState(new Set),m=(e.recentMergeAdvances??[]).filter(b=>!d.has(b.toSha)),p=m.filter(b=>b.resolution==="pending"),h=p.length>0,u=e.aheadOfIntegration===0&&e.behindIntegration===0,f=h&&!u;return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:r("git.repositoryStatus","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:r("git.statusLabelBranch","Branch")}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:e.branch}),e.integrationBranch&&e.isOnIntegrationBranch===!1&&t.jsxs("span",{className:"gm-status-sub",title:r("git.notOnIntegrationBranchTitle","Currently on a non-integration branch"),children:[" ",r("git.notOnIntegrationBranch","(not on {{branch}})",{branch:e.integrationBranch})]})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelCommit","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,r("git.copyCommitHashLabel","commit hash")),title:e.headSha?r("git.copyShortHashTitleWithFull","Copy short commit hash (use the full SHA below for git operations)"):r("git.copyShortHashTitle","Copy short commit hash"),children:t.jsx(Pa,{size:12})}),e.headSha&&t.jsxs("button",{className:"gm-icon-btn",onClick:()=>n(e.headSha,r("git.copyFullCommitHashLabel","full commit hash")),title:r("git.copyFullShaTitle","Copy full 40-char SHA"),children:[t.jsx(Pa,{size:12}),t.jsx("span",{style:{fontSize:10,marginLeft:2},children:r("git.fullShaAbbrev","full")})]})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelWorkingTree","Working Tree")}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(oi,{size:12}),r("git.workingTreeModified","Modified")]}):t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:12}),r("git.workingTreeClean","Clean")]})}),e.dirtyDetails&&e.dirtyDetails.staged+e.dirtyDetails.modified+e.dirtyDetails.untracked+e.dirtyDetails.conflicted>0&&t.jsxs("span",{className:"gm-status-sub",children:[e.dirtyDetails.staged>0&&t.jsx("span",{title:r("git.staged","Staged"),children:r("git.stagedCount","{{count}} staged",{count:e.dirtyDetails.staged})}),e.dirtyDetails.staged>0&&e.dirtyDetails.modified+e.dirtyDetails.untracked+e.dirtyDetails.conflicted>0&&" · ",e.dirtyDetails.modified>0&&t.jsx("span",{title:r("git.modified","Modified"),children:r("git.modifiedCount","{{count}} modified",{count:e.dirtyDetails.modified})}),e.dirtyDetails.modified>0&&e.dirtyDetails.untracked+e.dirtyDetails.conflicted>0&&" · ",e.dirtyDetails.untracked>0&&t.jsx("span",{title:r("git.untracked","Untracked"),children:r("git.untrackedCount","{{count}} untracked",{count:e.dirtyDetails.untracked})}),e.dirtyDetails.untracked>0&&e.dirtyDetails.conflicted>0&&" · ",e.dirtyDetails.conflicted>0&&t.jsx("span",{title:r("git.unresolvedMergeConflicts","Unresolved merge conflicts"),className:"gm-status-conflict",children:r("git.conflictedCount","{{count}} conflicted",{count:e.dirtyDetails.conflicted})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelVsOrigin","vs origin")}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:r("git.aheadOfUpstream","{{count}} commit(s) ahead of upstream",{count:e.ahead}),children:[t.jsx(Ma,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:r("git.behindUpstream","{{count}} commit(s) behind upstream",{count:e.behind}),children:[t.jsx(hr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Es,{size:12}),r("git.upToDate","Up to date")]})]})]})]}),e.integrationBranch&&t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card","data-testid":"integration-branch-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelIntegrationBranch","Integration branch")}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:e.integrationBranch}),e.integrationBranchSource&&t.jsxs("span",{className:"gm-status-sub",title:r("git.resolvedFrom","Resolved from {{source}}",{source:e.integrationBranchSource}),children:[" ","(",e.integrationBranchSource,")"]})]}),e.integrationTipSha&&t.jsxs("span",{className:"gm-status-sub",children:[r("git.tip","tip")," ",t.jsx("code",{className:"gm-hash",children:e.integrationTipSha.slice(0,8)}),e.integrationTipSource==="remote-only"&&t.jsxs(t.Fragment,{children:[" ",t.jsx("span",{title:r("git.remoteOnlyIntegrationTipTitle","No local refs/heads/<branch>; using refs/remotes/origin/<branch> as the integration tip."),children:r("git.remoteOnlyTrackLocally","(remote-only — run git switch {{branch}} to track locally)",{branch:e.integrationBranch})})]})]}),e.integrationTipSource==="missing"&&t.jsx("span",{className:"gm-status-sub gm-status-conflict",title:r("git.noRefFoundTitle","Neither refs/heads nor refs/remotes/origin has this branch"),children:r("git.noRefFound","no ref found for {{branch}}",{branch:e.integrationBranch})})]}),e.integrationTipSha!==void 0&&(e.aheadOfIntegration!==void 0||e.behindIntegration!==void 0)&&t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.headVsIntegration","HEAD vs {{branch}}",{branch:e.integrationBranch})}),t.jsx("span",{className:"gm-status-value",children:(e.aheadOfIntegration??0)===0&&(e.behindIntegration??0)===0?t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Es,{size:12}),r("git.aligned","Aligned")]}):t.jsxs(t.Fragment,{children:[(e.aheadOfIntegration??0)>0&&t.jsxs("span",{className:"gm-ahead",title:r("git.headAheadOfIntegration","HEAD has {{count}} commit(s) not on {{branch}}",{count:e.aheadOfIntegration,branch:e.integrationBranch}),children:[t.jsx(Ma,{size:12}),e.aheadOfIntegration]}),(e.behindIntegration??0)>0&&t.jsxs("span",{className:"gm-behind",title:r("git.integrationAheadOfHead","{{branch}} has {{count}} commit(s) HEAD doesn't",{branch:e.integrationBranch,count:e.behindIntegration}),children:[t.jsx(hr,{size:12}),e.behindIntegration]})]})})]}),e.originIntegrationTipSha!==void 0&&t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.localVsOrigin","Local {{branch}} vs origin",{branch:e.integrationBranch})}),t.jsx("span",{className:"gm-status-value",children:e.originIntegrationTipSha===null?t.jsx("span",{className:"gm-status-sub",children:r("git.noOriginTracking","no origin tracking")}):e.integrationTipSource==="remote-only"?t.jsx("span",{className:"gm-status-sub",title:r("git.noLocalRefTitle","No local refs/heads/<branch> exists; nothing to compare against origin."),children:r("git.noLocalTracking","no local tracking")}):(e.aheadOfOriginIntegration??0)===0&&(e.behindOriginIntegration??0)===0?t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Es,{size:12}),r("git.synced","Synced")]}):t.jsxs(t.Fragment,{children:[(e.aheadOfOriginIntegration??0)>0&&t.jsxs("span",{className:"gm-ahead",title:r("git.localAheadOfOriginIntegration","Local {{branch}} is {{count}} commit(s) ahead of origin/{{branch}}",{branch:e.integrationBranch,count:e.aheadOfOriginIntegration}),children:[t.jsx(Ma,{size:12}),e.aheadOfOriginIntegration]}),(e.behindOriginIntegration??0)>0&&t.jsxs("span",{className:"gm-behind",title:r("git.localBehindOriginIntegration","Local {{branch}} is {{count}} commit(s) behind origin/{{branch}}",{branch:e.integrationBranch,count:e.behindOriginIntegration}),children:[t.jsx(hr,{size:12}),e.behindOriginIntegration]})]})})]}),e.integrationTipSource==="remote-only"&&e.aheadOfIntegrationRemote!==void 0&&t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.headVsOriginIntegration","HEAD vs origin/{{branch}}",{branch:e.integrationBranch})}),t.jsx("span",{className:"gm-status-value",children:(e.aheadOfIntegrationRemote??0)===0&&(e.behindIntegrationRemote??0)===0?t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Es,{size:12}),r("git.aligned","Aligned")]}):t.jsxs(t.Fragment,{children:[(e.aheadOfIntegrationRemote??0)>0&&t.jsxs("span",{className:"gm-ahead",title:r("git.headAheadOfOriginIntegration","HEAD has {{count}} commit(s) not on origin/{{branch}}",{count:e.aheadOfIntegrationRemote,branch:e.integrationBranch}),children:[t.jsx(Ma,{size:12}),e.aheadOfIntegrationRemote]}),(e.behindIntegrationRemote??0)>0&&t.jsxs("span",{className:"gm-behind",title:r("git.originIntegrationAheadOfHead","origin/{{branch}} has {{count}} commit(s) HEAD doesn't",{branch:e.integrationBranch,count:e.behindIntegrationRemote}),children:[t.jsx(hr,{size:12}),e.behindIntegrationRemote]})]})})]}),(e.stashCount??0)>0&&t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelStashes","Stashes")}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Qr,{size:14}),t.jsx("span",{children:e.stashCount})]})]})]}),e.indexStaleVsHead===!0&&t.jsxs("div",{className:"gm-status-warning","data-testid":"index-stale-warning",role:"alert",children:[t.jsx(oi,{size:14}),t.jsx("div",{children:t.jsx(Ga,{i18nKey:"app:git.staleIndexWarning",defaults:'<strong>Stale index detected.</strong> HEAD has advanced (typically because Fusion\'s merger updated the integration-branch ref) but the index still reflects the previous tip — `git status` will report the new commits inverted as "staged changes." Enable <mergeCode>mergeAdvanceAutoSync</mergeCode> in Settings to have the merger reconcile automatically, or run <resetCode>git reset --hard HEAD</resetCode> to snap forward manually.',components:{strong:t.jsx("strong",{}),mergeCode:t.jsx("code",{}),resetCode:t.jsx("code",{})}})})]}),m.length>0&&t.jsxs("div",{className:"gm-status-advances","data-testid":"recent-merge-advances",children:[t.jsxs("div",{className:"gm-status-advances-header",children:[t.jsxs("span",{children:[r("git.recentIntegrationAdvances","Recent integration-branch advances"),t.jsxs("span",{className:"gm-status-sub",children:[" ","(",r("git.advancesNeedAction","{{count}} need action",{count:p.length}),")"]}),t.jsx("button",{type:"button",className:"gm-icon-btn",style:{marginLeft:6},"aria-expanded":o,"aria-label":o?r("git.hideExplanation","Hide explanation"):r("git.whatDoesThisMean","What does this mean?"),onClick:()=>l(b=>!b),title:r("git.whatDoesThisMean","What does this mean?"),children:t.jsx(q0,{size:13})})]}),f&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:i,"data-testid":"sync-working-tree-btn",title:r("git.syncWorkingTreeTitle","Pull the integration branch into your working tree (auto-stashes uncommitted edits and restores them)"),children:i?r("git.syncing","Syncing…"):r("git.syncWorkingTree","Sync working tree")})]}),o&&t.jsxs("div",{className:"gm-status-advances-help","data-testid":"recent-merge-advances-help",children:[t.jsx("p",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpIntro",defaults:"Each entry is a Fusion task whose squash commit advanced the integration branch ref (<branchCode>{{integrationBranch}}</branchCode>). The <em>auto-sync outcome</em> says whether your working tree was also fast-forwarded to that new tip.",values:{integrationBranch:e.integrationBranch??"main"},components:{branchCode:t.jsx("code",{}),em:t.jsx("em",{})}})}),t.jsxs("ul",{className:"gm-status-advances-help-list",children:[t.jsx("li",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpItem1",defaults:"<c1>clean-sync</c1> / <c2>synced-with-edits-restored</c2> — working tree is in sync; nothing to do.",components:{c1:t.jsx("code",{}),c2:t.jsx("code",{})}})}),t.jsx("li",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpItem2",defaults:"<c1>reachable</c1> / <c2>subsumed</c2> / <c3>orphaned</c3> / <c4>superseded</c4> — already handled (including history rewrites where equivalent content already landed, original SHAs disappeared, or HEAD is already aligned to the rewritten integration tip).",components:{c1:t.jsx("code",{}),c2:t.jsx("code",{}),c3:t.jsx("code",{}),c4:t.jsx("code",{})}})}),t.jsx("li",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpItem3",defaults:"<c1>pending</c1> + <c2>off / not run</c2> — auto-sync is disabled in Settings; the branch ref moved but your worktree didn't follow.",components:{c1:t.jsx("code",{}),c2:t.jsx("code",{})}})}),t.jsx("li",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpItem4",defaults:"<c1>pending</c1> + <c2>stash-failed</c2> / <c3>would-conflict</c3> / similar — auto-sync tried but couldn't reconcile (usually local edits collide with the new commit).",components:{c1:t.jsx("code",{}),c2:t.jsx("code",{}),c3:t.jsx("code",{})}})})]}),t.jsx("p",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpFix",defaults:"<strong>Fix:</strong> Fusion only shows <em>Sync working tree</em> when at least one advance is genuinely <code>pending</code> and HEAD is not aligned with the integration tip. If entries are already handled (subsumed/orphaned/reachable/superseded), no sync action is offered.",components:{strong:t.jsx("strong",{}),em:t.jsx("em",{}),code:t.jsx("code",{})}})})]}),t.jsx("ul",{children:m.map(b=>t.jsxs("li",{className:b.needsAction?"gm-advance-needs-action":"gm-advance-handled",children:[t.jsx("code",{className:"gm-hash",children:b.toSha.slice(0,8)})," ",t.jsx("strong",{children:b.taskId}),b.autoSyncOutcome?t.jsxs("span",{className:"gm-status-sub",children:[" ",r("git.autoSyncOutcome","auto-sync: {{outcome}}",{outcome:b.autoSyncOutcome})]}):t.jsxs("span",{className:"gm-status-sub",children:[" ",r("git.autoSyncOffNotRun","auto-sync: off / not run")]}),t.jsxs("span",{className:"gm-status-sub",children:[" ","· ",new Date(b.advancedAt).toLocaleTimeString()," · ",b.resolution]}),(b.resolution==="orphaned"||b.resolution==="subsumed"||b.resolution==="superseded")&&t.jsx("button",{type:"button",className:"btn btn-xs",onClick:()=>{c(y=>{const v=new Set(y);return v.add(b.toSha),v})},"data-testid":`dismiss-advance-${b.toSha}`,children:r("git.dismiss","Dismiss")})]},`${b.taskId}-${b.toSha}`))})]})]})}function VU({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:d,onSelectDiffFile:c,selectedDiffTarget:m,changeDiff:p,loadingChangeDiff:h,changeDiffError:u,commitMessage:f,setCommitMessage:b,onCommit:y,onStageAllAndCommit:v,committing:x}){const{t:k}=st("app"),w=s.filter(j=>i.has(`unstaged:${j.file}`)),g=n.filter(j=>i.has(`staged:${j.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(ui,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:k("git.workingTreeModified","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.jsx("h5",{children:k("git.unstagedChanges","Unstaged Changes ({{count}})",{count:s.length})}),t.jsxs("div",{className:"gm-file-section-actions",children:[w.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(w.map(j=>j.file)),title:k("git.stageSelected","Stage selected"),children:[t.jsx(ys,{size:12})," ",k("git.stageCount","Stage ({{count}})",{count:w.length})]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>d(w.map(j=>j.file)),title:k("git.discardSelected","Discard selected"),children:t.jsx(vr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.file)),title:k("git.stageAll","Stage all"),children:k("git.stageAll","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:k("git.noUnstagedChanges","No unstaged changes")}):s.map(j=>{const S=m?.file===j.file&&m.staged===!1;return t.jsxs("div",{className:`gm-file-item${S?" active":""}`,onClick:()=>c(j.file,!1),role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),c(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:C=>C.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(py,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(fy,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:C=>{C.stopPropagation(),o([j.file])},title:k("git.stageFile","Stage file"),children:t.jsx(ys,{size:12})})]},`unstaged:${j.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsx("h5",{children:k("git.stagedChanges","Staged Changes ({{count}})",{count:n.length})}),t.jsxs("div",{className:"gm-file-section-actions",children:[g.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(g.map(j=>j.file)),title:k("git.unstageSelected","Unstage selected"),children:k("git.unstageCount","Unstage ({{count}})",{count:g.length})}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.file)),title:k("git.unstageAll","Unstage all"),children:k("git.unstageAll","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:k("git.noStagedChanges","No staged changes")}):n.map(j=>{const S=m?.file===j.file&&m.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${S?" active":""}`,onClick:()=>c(j.file,!0),role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),c(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:C=>C.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(py,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(fy,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:C=>{C.stopPropagation(),l([j.file])},title:k("git.unstageFile","Unstage file"),children:t.jsx(Fn,{size:12})})]},`staged:${j.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:m||h||p||u?t.jsxs("div",{className:"gm-diff-section",children:[m&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(kh,{size:14}),t.jsxs("span",{children:[m.staged?k("git.staged","Staged"):k("git.unstaged","Unstaged")," ",k("git.diffColon","diff:")," "]}),t.jsx("code",{children:m.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),k("git.loadingDiff","Loading diff...")]}),u&&!h&&t.jsx("div",{className:"gm-diff-error",children:u}),p&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[p.stat&&t.jsx("pre",{className:"gm-diff-stat",children:p.stat}),t.jsx("pre",{className:"gm-diff-patch",children:p.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(kh,{size:20}),t.jsx("span",{children:k("git.selectFileToViewDiff","Select a file to view its diff")})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:y,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:k("git.commitMessagePlaceholder","Commit message..."),value:f,onChange:j=>b(j.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!f.trim()||n.length===0,title:n.length===0?k("git.noStagedChangesToCommit","No staged changes to commit"):k("git.commitStagedChanges","Commit staged changes"),children:[x?t.jsx(Et,{size:14,className:"spin"}):t.jsx(zr,{size:14}),k("git.commit","Commit")]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:x||!f.trim(),title:k("git.stageAllAndCommitTitle","Stage all and commit"),children:k("git.stageAllAndCommit","Stage All & Commit")})]})]})]})}function qU({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:i,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:d,canLoadMore:c,copyToClipboard:m}){const{t:p}=st("app");return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:p("git.sectionCommits","Commits")}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(na,{size:14}),t.jsx("input",{type:"text",placeholder:p("git.searchCommits","Search commits..."),value:n,onChange:h=>s(h.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?p("git.noMatchingCommits","No matching commits"):p("git.noCommitsFound","No commits found")}):e.map((h,u)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),u<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(h.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:h.shortHash}),t.jsx("span",{className:"gm-commit-message",title:h.message,children:h.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:h.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:sl(h.date)}),h.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:p("git.mergeBadge","merge")})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>m(h.hash,p("git.copyCommitHashLabel","commit hash")),title:p("git.copyFullHash","Copy full hash"),children:t.jsx(Pa,{size:12})})}),i===h.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),p("git.loadingDiff","Loading diff...")]}):r?t.jsxs(t.Fragment,{children:[h.body&&t.jsx("div",{className:"gm-commit-message-full",children:h.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:p("git.failedToLoadDiff","Failed to load diff")})})]})]},h.hash))}),c&&t.jsx("button",{className:"gm-load-more",onClick:d,children:p("git.loadMoreCommits","Load more commits")})]})}function WU({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:d,onCheckoutBranch:c,onDeleteBranch:m,loading:p,allBranches:h,selectedBranch:u,branchCommits:f,loadingBranchCommits:b,expandedBranchCommit:y,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:k,onBranchCommitClick:w,onCloseBranchDetails:g}){const{t:j}=st("app");return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:j("git.sectionBranches","Branches")}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(na,{size:14}),t.jsx("input",{type:"text",placeholder:j("git.filterBranches","Filter branches..."),value:n,onChange:S=>s(S.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:d,children:[t.jsx("input",{type:"text",placeholder:j("git.newBranchName","New branch name"),value:i,onChange:S=>r(S.target.value),disabled:p}),t.jsxs("select",{value:o,onChange:S=>l(S.target.value),disabled:p,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:j("git.baseHead","Base: HEAD")}),h.map(S=>t.jsx("option",{value:S.name,children:S.name},S.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:p||!i.trim(),children:[t.jsx(ys,{size:14}),j("git.create","Create")]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?j("git.noMatchingBranches","No matching branches"):j("git.noBranchesFound","No branches found")}):e.map(S=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${S.isCurrent?" current":""}${u===S.name?" selected":""}`,onClick:()=>k(S.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[S.isCurrent&&t.jsx(Qs,{size:14,className:"gm-current-icon"}),S.name]}),S.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",S.remote]}),S.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:sl(S.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!S.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:C=>{C.stopPropagation(),c(S.name)},disabled:p,title:j("git.checkout","Checkout"),children:t.jsx(ui,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:C=>{C.stopPropagation(),m(S.name)},disabled:p,title:j("git.deleteBranch","Delete"),children:t.jsx(as,{size:14})})]})})]}),u===S.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(vc,{size:14}),j("git.commitsOnBranch","Commits on {{name}}",{name:S.name})]}),t.jsx("button",{className:"gm-icon-btn",onClick:g,title:j("git.close","Close"),"data-testid":"close-branch-details",children:t.jsx(Fn,{size:14})})]}),b?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(Et,{size:16,className:"spin"}),j("git.loadingCommits","Loading commits...")]}):f.length===0?t.jsx("div",{className:"gm-empty",children:j("git.noCommitsFound","No commits found")}):t.jsx("div",{className:"gm-branch-commits-list",children:f.map(C=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>w(C.hash),"data-testid":`branch-commit-${C.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:C.shortHash}),t.jsx("span",{className:"gm-commit-message",title:C.message,children:C.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:C.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:sl(C.date)}),C.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:j("git.mergeBadge","merge")})]})]}),y===C.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),j("git.loadingDiff","Loading diff...")]}):v?t.jsxs(t.Fragment,{children:[(C.body||C.message)&&t.jsx("div",{className:"gm-commit-message-full",children:C.body||C.message}),v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:j("git.failedToLoadDiff","Failed to load diff")})})]},C.hash))})]})]},S.name))})]})}function GU({worktrees:e}){const{t:n}=st("app");return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:n("git.sectionWorktrees","Worktrees")}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsx("span",{children:n("git.worktreesTotal","{{count}} total",{count:e.length})}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsx("span",{children:n("git.worktreesInUse","{{count}} in use",{count:e.filter(s=>s.taskId).length})})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(s=>t.jsx("div",{className:`gm-worktree-item${s.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[s.isMain&&t.jsx("span",{className:"gm-badge main",children:n("git.worktreeBadgeMain","main")}),s.isBare&&t.jsx("span",{className:"gm-badge bare",children:n("git.worktreeBadgeBare","bare")}),t.jsx("span",{className:"gm-worktree-path",title:s.path,children:Lp(s.path)||s.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[s.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(ui,{size:12}),s.branch]}),s.taskId&&t.jsx("span",{className:"gm-worktree-task",children:s.taskId})]})]})},s.path))})]})}function KU({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:d,expandedStashIndex:c,stashDiff:m,loadingStashDiff:p,stashDiffError:h}){const{t:u}=st("app");return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:u("git.sectionStashes","Stashes")})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:u("git.stashMessagePlaceholder","Stash message (optional)"),value:n,onChange:f=>s(f.target.value),disabled:d!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:d!==null,children:[d==="create"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(Qr,{size:14}),u("git.stash","Stash")]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:u("git.noStashes","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(ui,{size:12}),f.branch]}),t.jsx("span",{children:sl(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:d!==null,children:c===f.index?u("git.hide","Hide"):u("git.view","View")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:d!==null,title:u("git.applyStashKeep","Apply stash (keep)"),children:d===`apply-${f.index}`?t.jsx(Et,{size:14,className:"spin"}):u("git.apply","Apply")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:d!==null,title:u("git.popStashTitle","Pop stash (apply and drop)"),children:u("git.pop","Pop")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:d!==null,title:u("git.dropStash","Drop stash"),children:d===`drop-${f.index}`?t.jsx(Et,{size:14,className:"spin"}):t.jsx(as,{size:14})})]})]}),c===f.index&&t.jsx("div",{className:"gm-stash-diff",children:p?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:14,className:"spin"}),u("git.loadingStashDiff","Loading stash diff…")]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):m?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})]}):null})]},f.index))})]})}function JU({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,onSync:l,onSyncIntegrationTip:d,syncIntegrationDisabled:c,addToast:m,projectId:p,copyToClipboard:h}){const{t:u}=st("app"),f=Fe=>{try{return new URL(Fe).hostname}catch{return Fe.replace(/^git@/,"").split(":")[0]||Fe}},[b,y]=a.useState([]),[v,x]=a.useState(!1),[k,w]=a.useState(null),[g,j]=a.useState(""),[S,C]=a.useState(""),[E,F]=a.useState(null),[M,D]=a.useState(""),[_,V]=a.useState(""),[N,$]=a.useState(!1),[R,L]=a.useState(!1),O=a.useRef(null),[J,A]=a.useState([]),[de,B]=a.useState(!1),[P,Z]=a.useState(null),[T,ie]=a.useState([]),[le,be]=a.useState(!1),[Le,xe]=a.useState(null),q=a.useRef(0),ce=b.find(Fe=>Fe.name===P);a.useEffect(()=>{(n!==null||v)&&L(!1)},[n,v]),a.useEffect(()=>{if(!R)return;const Fe=Nt=>{O.current?.contains(Nt.target)||L(!1)},nt=Nt=>{Nt.key==="Escape"&&L(!1)};return document.addEventListener("mousedown",Fe),document.addEventListener("keydown",nt),()=>{document.removeEventListener("mousedown",Fe),document.removeEventListener("keydown",nt)}},[R]);const[De,He]=a.useState(null),[qe,pe]=a.useState(null),[te,me]=a.useState(!1),[se,z]=a.useState(null),[Y,he]=a.useState(null),[X,ye]=a.useState(!1);a.useEffect(()=>{ot()},[]),a.useEffect(()=>{e&&e.ahead>0?ue():e&&e.ahead===0&&A([])},[e?.ahead]),a.useEffect(()=>{b.length>0&&!P&&Z(b[0].name)},[b]),a.useEffect(()=>{P?je(P):(ie([]),xe(null))},[P]),a.useEffect(()=>{!P||!s||je(P)},[P,s]),a.useEffect(()=>{P&&!b.find(Fe=>Fe.name===P)&&Z(b.length>0?b[0].name:null)},[b,P]);const ot=async()=>{x(!0);try{const Fe=await bM(p);y(Fe)}catch(Fe){m(Re(Fe)||u("git.failedToLoadRemotes","Failed to load remotes"),"error")}finally{x(!1)}},ue=async()=>{B(!0);try{const Fe=await IM(p);A(Fe)}catch{A([])}finally{B(!1)}},je=async Fe=>{const nt=q.current+1;q.current=nt,be(!0),xe(null);try{const Nt=await DM(Fe,void 0,10,p);if(q.current!==nt)return;ie(Nt)}catch(Nt){if(q.current!==nt)return;xe(Re(Nt)||u("git.failedToLoadRemoteCommits","Failed to load remote commits")),ie([])}finally{q.current===nt&&be(!1)}},$e=Yi(),Ce=async Fe=>{if(Fe.preventDefault(),!(!g.trim()||!S.trim())){w("add");try{await vM(g.trim(),S.trim(),p),m(u("git.remoteAdded","Remote '{{name}}' added successfully",{name:g}),"success"),j(""),C(""),$(!1),await ot()}catch(nt){m(Re(nt)||u("git.failedToAddRemote","Failed to add remote"),"error")}finally{w(null)}}},We=async Fe=>{if(await $e.confirm({title:u("git.removeRemoteTitle","Remove Remote"),message:u("git.removeRemoteMessage","Are you sure you want to remove remote '{{name}}'?",{name:Fe}),danger:!0})){w(`remove-${Fe}`);try{await xM(Fe,p),m(u("git.remoteRemoved","Remote '{{name}}' removed",{name:Fe}),"success"),await ot()}catch(Nt){m(Re(Nt)||u("git.failedToRemoveRemote","Failed to remove remote"),"error")}finally{w(null)}}},ke=async Fe=>{if(_.trim()){w(`rename-${Fe}`);try{await yM(Fe,_.trim(),p),m(u("git.remoteRenamed","Remote renamed to '{{name}}'",{name:_.trim()}),"success"),F(null),V(""),await ot()}catch(nt){m(Re(nt)||u("git.failedToRenameRemote","Failed to rename remote"),"error")}finally{w(null)}}},Ee=async Fe=>{if(M.trim()){w(`url-${Fe}`);try{await kM(Fe,M.trim(),p),m(u("git.remoteUrlUpdated","Remote URL updated"),"success"),F(null),D(""),await ot()}catch(nt){m(Re(nt)||u("git.failedToUpdateRemoteUrl","Failed to update remote URL"),"error")}finally{w(null)}}},Ze=a.useCallback(async(Fe,nt)=>{if(nt==="ahead"){if(De===Fe){He(null),pe(null);return}He(Fe),pe(null),me(!0);try{const Nt=await Ud(Fe);pe(Nt)}catch{pe(null)}finally{me(!1)}}else{if(se===Fe){z(null),he(null);return}z(Fe),he(null),ye(!0);try{const Nt=await Ud(Fe);he(Nt)}catch{he(null)}finally{ye(!1)}}},[De,se]),Ke=Fe=>{F(`url-${Fe.name}`),D(Fe.pushUrl||Fe.fetchUrl)},dt=Fe=>{F(`name-${Fe.name}`),V(Fe.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:u("git.sectionRemotes","Remotes")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>$(!N),disabled:k!==null,title:N?u("git.cancel","Cancel"):u("git.addRemote","Add Remote"),children:N?t.jsx(Fn,{size:14}):t.jsx(ys,{size:14})})]}),N&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ce,children:[t.jsx("input",{type:"text",placeholder:u("git.remoteName","Remote name"),value:g,onChange:Fe=>j(Fe.target.value),disabled:k==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:u("git.repositoryUrl","Repository URL"),value:S,onChange:Fe=>C(Fe.target.value),disabled:k==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!g.trim()||!S.trim()||k==="add",children:[k==="add"?t.jsx(Et,{size:12,className:"spin"}):t.jsx(ys,{size:12}),u("git.add","Add")]})]}),v?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Et,{size:16,className:"spin"}),u("git.loading","Loading...")]}):b.length===0?t.jsx("div",{className:"gm-empty",children:u("git.noRemotes","No remotes")}):b.map(Fe=>t.jsxs("div",{className:`gm-remote-selector-item${P===Fe.name?" selected":""}`,onClick:()=>Z(Fe.name),role:"button",tabIndex:0,onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&(nt.preventDefault(),Z(Fe.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:Fe.name}),Fe.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:u("git.defaultBadge","default")})]}),t.jsx("span",{className:"gm-remote-selector-host",title:Fe.fetchUrl,children:f(Fe.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:nt=>{nt.stopPropagation(),We(Fe.name)},disabled:k!==null,title:u("git.removeRemote","Remove remote"),children:t.jsx(as,{size:14})})]},Fe.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[P&&ce?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:P}),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(Ma,{size:14}),u("git.commitsToPush","{{count}} to push",{count:e.ahead})]}),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(hr,{size:14}),u("git.commitsToPull","{{count}} to pull",{count:e.behind})]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||v,children:[n==="fetch"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(xs,{size:14}),u("git.fetch","Fetch")]}),t.jsxs("div",{className:"gm-pull-split",ref:O,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{L(!1),r({rebase:!1})},disabled:n!==null||v,children:[n==="pull"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(ai,{size:14}),u("git.pull","Pull")]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>L(Fe=>!Fe),disabled:n!==null||v,"aria-label":u("git.pullOptions","Pull options"),"aria-haspopup":"menu","aria-expanded":R,children:t.jsx(Ln,{size:14})}),R?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":u("git.pullOptionsMenu","Pull options menu"),children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{L(!1),r({rebase:!1})},children:u("git.pull","Pull")}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{L(!1),r({rebase:!0})},children:u("git.pullRebase","Pull --rebase")})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||v,children:[n==="push"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(Ma,{size:14}),u("git.push","Push")]}),t.jsxs("button",{className:"btn btn-primary",onClick:l,disabled:n!==null||v,title:u("git.syncOriginTitle","Pull --rebase from origin, then push current branch"),"data-testid":"remotes-sync-origin-btn",children:[n==="sync"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(rc,{size:14}),u("git.sync","Sync")]}),e?.integrationBranch&&t.jsxs("button",{className:"btn gm-sync-integration-btn",onClick:d,disabled:c,title:e.isOnIntegrationBranch===!1?u("git.notOnIntegrationBranchBtn","Not on integration branch ({{branch}})",{branch:e.integrationBranch}):u("git.syncLocalTipTitle","Sync working tree to local integration tip (same as banner Pull)"),"data-testid":"remotes-sync-integration-tip-btn",children:[n==="sync-integration"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(rc,{size:14}),u("git.syncLocalTip","Sync local tip")]})]})]}),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:u("git.fetchLabel","Fetch:")}),E===`url-${P}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:M,onChange:Fe=>D(Fe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ee(P),disabled:k===`url-${P}`,children:k===`url-${P}`?t.jsx(Et,{size:12,className:"spin"}):t.jsx(Qs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{F(null),D("")},title:u("git.cancel","Cancel"),children:t.jsx(Fn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:ce.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:ce.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>h(ce.fetchUrl,u("git.fetchUrlLabel","fetch URL")),title:u("git.copyFetchUrl","Copy fetch URL"),children:t.jsx(Pa,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ke(ce),disabled:k!==null,title:u("git.editRemoteUrl","Edit remote URL"),children:t.jsx(Si,{size:14})})]})]})]}),ce.pushUrl&&ce.pushUrl!==ce.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:u("git.pushLabel","Push:")}),t.jsx("span",{className:"gm-url-value",title:ce.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:ce.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>h(ce.pushUrl,u("git.pushUrlLabel","push URL")),title:u("git.copyPushUrl","Copy push URL"),children:t.jsx(Pa,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:E===`name-${P}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:_,onChange:Fe=>V(Fe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>ke(P),disabled:k===`rename-${P}`,children:k===`rename-${P}`?t.jsx(Et,{size:12,className:"spin"}):t.jsx(Qs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{F(null),V("")},title:u("git.cancel","Cancel"),children:t.jsx(Fn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>dt(ce),disabled:k!==null,title:u("git.editRemoteName","Edit remote name"),children:t.jsx(Si,{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(Ma,{size:14}),u("git.commitsToPushHeader","Commits to Push ({{count}})",{count:e.ahead})]})}),de?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Et,{size:14,className:"spin"}),u("git.loading","Loading...")]}):J.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:J.map(Fe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ze(Fe.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&(nt.preventDefault(),Ze(Fe.hash,"ahead"))},title:u("git.clickToViewDiff","Click to view diff"),children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Fe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Fe.message,children:Fe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Fe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:sl(Fe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:De===Fe.hash?t.jsx(Ln,{size:14}):t.jsx(ls,{size:14})})]}),De===Fe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:te?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),u("git.loadingDiff","Loading diff...")]}):qe?t.jsxs(t.Fragment,{children:[(Fe.body||Fe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:Fe.body||Fe.message}),qe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:qe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:qe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:u("git.failedToLoadDiff","Failed to load diff")})})]},Fe.hash))}):t.jsx("div",{className:"gm-empty",children:u("git.noAheadCommitsFound","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(Ak,{size:14}),u("git.recentCommitsOnRemote","Recent commits on {{remote}}",{remote:P})]})}),le?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Et,{size:14,className:"spin"}),u("git.loadingCommits","Loading commits...")]}):Le?t.jsxs("div",{className:"gm-error",children:[t.jsx(oi,{size:14}),Le]}):T.length===0?t.jsx("div",{className:"gm-empty",children:u("git.noCommitsOnRemote","No commits found on {{remote}}. Try fetching first.",{remote:P})}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:T.map(Fe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ze(Fe.hash,"remote"),role:"button",tabIndex:0,onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&(nt.preventDefault(),Ze(Fe.hash,"remote"))},title:u("git.clickToViewDiff","Click to view diff"),children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Fe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Fe.message,children:Fe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Fe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:sl(Fe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:se===Fe.hash?t.jsx(Ln,{size:14}):t.jsx(ls,{size:14})})]}),se===Fe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:X?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),u("git.loadingDiff","Loading diff...")]}):Y?t.jsxs(t.Fragment,{children:[(Fe.body||Fe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:Fe.body||Fe.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:u("git.failedToLoadDiff","Failed to load diff")})})]},Fe.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:u("git.selectRemoteToViewDetails","Select a remote to view details")}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const YU=36e5,XU=3e5,ah=[{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 QU(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 ZU(e){return typeof e!="number"||!Number.isFinite(e)?YU:Math.max(XU,Math.round(e))}function $K(e){if(ah.some(s=>s.value===e))return[...ah];const n={value:e,label:`${QU(e)} (custom)`};return[...ah,n].sort((s,i)=>s.value-i.value)}const e8=4,t8=5*6e4;function n8(e){const n=ZU(e?.heartbeatIntervalMs);return Math.max(n*e8,t8)}function gy(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),i=n%60;return s>0&&i>0?`${s}h ${i}m`:s>0?`${s}h`:`${i}m`}function s8(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 i8(e){const s=e.metadata?.heartbeatTimerRepair;if(!s||typeof s!="object")return{};const i=s;return{repairedAt:typeof i.repairedAt=="string"?i.repairedAt:void 0,staleAtRepair:typeof i.staleAtRepair=="boolean"?i.staleAtRepair:void 0,staleRepairReason:typeof i.staleRepairReason=="string"?i.staleRepairReason:void 0}}function a8(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=s8(e),d=l||o?.enabled!==!1;if(n==="error")return{label:i??"Error",icon:t.jsx(Ci,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(ia,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ci,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!d)return{label:"Heartbeat Disabled",icon:t.jsx(ia,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Is,{size:14}),color:"var(--text-muted)",stateDerived:!1};const c=i8(e);if(c.staleAtRepair&&c.repairedAt){const u=Date.parse(c.repairedAt),f=Date.parse(s);if(Number.isFinite(u)&&Number.isFinite(f)&&f<u)return{label:"Unresponsive",icon:t.jsx(Ci,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:c.staleRepairReason??"Heartbeat scheduler repaired a missing timer; waiting for recovery heartbeat"}}const m=new Date(s).getTime(),p=Date.now()-m,h=n8(o);if(p>h){const u=`No heartbeat for ${gy(p)} (threshold: ${gy(h)})`;return{label:"Unresponsive",icon:t.jsx(Ci,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:u}}return{label:"Healthy",icon:t.jsx(B0,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function ru({agent:e,size:n=36,className:s}){const[i,r]=a.useState(!1);a.useEffect(()=>{r(!1)},[e.imageUrl]);const o=a.useMemo(()=>{if(!e.imageUrl)return;const l=encodeURIComponent(e.updatedAt??""),d=e.imageUrl.includes("?")?"&":"?";return`${e.imageUrl}${d}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&&!i?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(Is,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const r8="https://github.com/Runfusion/Fusion/issues/new";function o8(e,n){const s=`[Agent Error] ${n.surface}${n.agentName?` - ${n.agentName}`:""}`,i=["## 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:i.join(`
|
|
791
|
+
`)},500);return()=>clearTimeout(ee)},[Y,q?.sessionId,F]),a.useEffect(()=>{if(!m||!N.current)return;N.current.options.fontSize=w,le.current!==null&&(cancelAnimationFrame(le.current),le.current=null);const Ae=requestAnimationFrame(()=>{le.current=null,We()});return le.current=Ae,()=>{le.current===Ae&&(cancelAnimationFrame(Ae),le.current=null)}},[w,m,We]),a.useEffect(()=>{if(!e)return;const Ae=ee=>{if(!(!ee.ctrlKey&&!ee.metaKey)){if(ee.code==="Equal"||ee.code==="NumpadAdd"){ee.preventDefault(),g(Ie=>Jl(Ie+1));return}if(ee.code==="Minus"||ee.code==="NumpadSubtract"){ee.preventDefault(),g(Ie=>Jl(Ie-1));return}if(ee.code==="Digit0"||ee.code==="Numpad0"){ee.preventDefault(),g(Kl);return}}};return window.addEventListener("keydown",Ae),()=>window.removeEventListener("keydown",Ae)},[e,We]),a.useEffect(()=>{if(!e)return;const Ae=ee=>{ee.key==="Escape"&&n()};return document.addEventListener("keydown",Ae),()=>document.removeEventListener("keydown",Ae)},[e,n]),a.useEffect(()=>{Y==="connected"&&N.current&&setTimeout(()=>{if(!N.current||!D.current)return;const Ae=D.current.querySelector(".xterm-helper-textarea");Ae&&Ae.focus();try{D.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[Y]);const ke=a.useCallback(()=>{if(!D.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;N.current?.focus();const ee=D.current.querySelector(".xterm-helper-textarea");if(!ee)return;ee.autocapitalize="off",ee.autocomplete="off",ee.autocorrect="off",ee.spellcheck=!1,ee.setAttribute("inputmode","text");try{ee.focus({preventScroll:!0})}catch{ee.focus()}const Ie=ee.value.length;ee.setSelectionRange(Ie,Ie)},[]);a.useEffect(()=>Ce(()=>{N.current?.clear(),c(null),R.current=!1,N.current&&(N.current.dispose(),N.current=null),$.current=null,de.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),p(!1),u(null),z().catch(ee=>{console.error("Failed to replace invalid terminal session:",ee)})}),[Ce,z]);const Ee=a.useCallback(Ae=>{Ae.target===Ae.currentTarget&&(V.current=!0)},[]),Ze=a.useCallback(Ae=>{V.current&&Ae.target===Ae.currentTarget&&n(),V.current=!1},[n]),Ke=a.useCallback(()=>{N.current?.clear()},[]),dt=a.useCallback(async()=>{N.current?.clear(),c(null),R.current=!1;try{await me()}catch(Ae){l(Re(Ae)||"Failed to restart terminal session")}},[me]),Fe=a.useCallback(()=>{N.current&&(N.current.dispose(),N.current=null),$.current=null,de.current=!1,Z.current&&(window.removeEventListener("resize",Z.current),Z.current=null),u(null),p(!1)},[]),nt=a.useCallback(()=>{window.location.reload()},[]),Nt=a.useCallback(()=>{g(Ae=>Jl(Ae+1))},[]),Ft=a.useCallback(()=>{g(Ae=>Jl(Ae-1))},[]),ze=a.useCallback(Ae=>{E(ee=>ee===Ae?null:Ae)},[]),it=a.useCallback(Ae=>{if(C==="ctrl"){he(u5(Ae)),E(null);return}if(C==="alt"){he(m5(Ae)),E(null);return}he(Ae)},[he,C]),Mt=a.useCallback(Ae=>{he(Ae),E(null)},[he]);if(!e)return null;const Ht=()=>{switch(Y){case"connected":return t.jsx("span",{className:"terminal-status connected",title:r("terminal.statusConnected","Connected")});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:r("terminal.statusConnecting","Connecting...")});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:r("terminal.statusDisconnected","Disconnected")});default:return null}},Me=!ce||!q&&!De;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ee,onMouseUp:Ze,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:y>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:_,className:"modal terminal-modal","data-testid":"terminal-modal",style:y>0?{"--keyboard-overlap":`${y}px`,"--vv-height":x?`${x}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[xe.map(Ae=>t.jsxs("div",{className:`terminal-tab ${Ae.isActive?"terminal-tab--active":""}`,onClick:()=>pe(Ae.id),title:Ae.title,role:"tab","aria-selected":Ae.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ae.title}),xe.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:ee=>{ee.stopPropagation(),qe(Ae.id)},title:r("terminal.closeTab","Close tab"),children:"×"})]},Ae.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:He,title:r("terminal.newTerminal","New terminal"),children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ua,{size:16}),Ht()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[Y==="disconnected"&&q&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:$e,title:r("terminal.reconnect","Reconnect"),"data-testid":"terminal-reconnect-btn",children:[t.jsx(xs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:r("terminal.reconnect","Reconnect")})]}),d!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:dt,title:r("terminal.newSession","New Session"),"data-testid":"terminal-restart-btn",children:[t.jsx(xs,{size:14}),t.jsx("span",{className:"terminal-action-label",children:r("terminal.newSession","New Session")})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Ke,"data-testid":"terminal-clear-btn",title:r("terminal.clearTerminal","Clear terminal"),children:[t.jsx(as,{size:14}),t.jsx("span",{className:"terminal-action-label",children:r("terminal.clear","Clear")})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>S(Ae=>!Ae),"data-testid":"terminal-shortcut-toggle",title:r("terminal.shortcuts","Shortcuts"),"aria-pressed":j,children:[t.jsx(K0,{size:14}),t.jsx("span",{className:"terminal-action-label",children:r("terminal.shortcuts","Shortcuts")})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:r("terminal.closeTerminal","Close terminal"),children:t.jsx(Fn,{size:20})})]})]}),o&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:o}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[Me&&!De&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:r("terminal.startingTerminal","Starting terminal...")})]}),De&&!q&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsx("span",{children:r("terminal.failedToStartTerminal","Failed to start terminal: {{error}}",{error:De})}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:se,"data-testid":"terminal-retry-btn",children:[t.jsx(xs,{size:14}),r("actions.retry","Retry")]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:nt,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(xs,{size:14}),r("terminal.refreshPage","Refresh page")]})]})]})}),h&&q&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsx("span",{children:r("terminal.initializeError","Terminal UI failed to initialize: {{error}}",{error:h})}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Fe,"data-testid":"terminal-reinit-btn",children:[t.jsx(xs,{size:14}),r("terminal.reinitialize","Reinitialize")]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:nt,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(xs,{size:14}),r("terminal.refreshPage","Refresh page")]})]})]})}),t.jsx("div",{ref:D,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:ke,onTouchStart:ke},q?.sessionId)]}),j&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${C==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>ze("ctrl"),"aria-pressed":C==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${C==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>ze("alt"),"aria-pressed":C==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Mt("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>Mt(" "),children:"Tab"})]}),h5.map(Ae=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>it(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 ${Y}`,children:[Y==="connected"&&r("terminal.statusConnected","Connected"),Y==="connecting"&&r("terminal.statusConnecting","Connecting..."),Y==="reconnecting"&&r("terminal.statusReconnecting","Reconnecting..."),Y==="disconnected"&&r("terminal.statusDisconnected","Disconnected")]}),d!==null&&t.jsx("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:r("terminal.exitLabel","Exit: {{code}}",{code:d})}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:Ft,"data-testid":"terminal-font-size-decrease","aria-label":r("terminal.decreaseFontSize","Decrease terminal font size"),children:t.jsx(x1,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[w,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:Nt,"data-testid":"terminal-font-size-increase","aria-label":r("terminal.increaseFontSize","Increase terminal font size"),children:t.jsx(ys,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:r("terminal.helpText","Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close")})]})]})})}const Il={name:"",command:""};function Qx(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function w5(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function j5({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const{t:o}=st("app");ga(e);const[l,d]=a.useState({}),[c,m]=a.useState(!0),[p,h]=a.useState(!1),[u,f]=a.useState(null),[b,y]=a.useState(Il),[v,x]=a.useState(!1),[k,w]=a.useState(null),[g,j]=a.useState(null),S=yr(n),C=a.useCallback(async()=>{try{m(!0);const L=await Hd(i);d(L)}catch(L){s(Re(L)||o("scriptsModal.failedToLoadScripts","Failed to load scripts"),"error")}finally{m(!1)}},[s,i]);a.useEffect(()=>{e&&C()},[e,C]);const E=a.useCallback(()=>{h(!0),f(null),y(Il),j(null)},[]),F=a.useCallback((L,O)=>{f(L),h(!1),y({name:L,command:O}),j(null)},[]),M=a.useCallback(()=>{f(null),h(!1),y(Il),j(null)},[]),D=a.useCallback(L=>{y(O=>({...O,name:L})),L&&!Qx(L)?j(o("scriptsModal.nameErrorMsg","Name must contain only letters, numbers, hyphens, and underscores (no spaces)")):j(null)},[o]),_=a.useCallback(async()=>{const L=b.name.trim(),O=b.command.trim();if(!L){s(o("scriptsModal.scriptNameRequired","Script name is required"),"error");return}if(!Qx(L)){s(o("scriptsModal.nameErrorMsg","Script name must contain only letters, numbers, hyphens, and underscores (no spaces)"),"error");return}if(!O){s(o("scriptsModal.scriptCommandRequired","Script command is required"),"error");return}x(!0);try{await OA(L,O,i),s(u?o("scriptsModal.scriptUpdated","Script updated"):o("scriptsModal.scriptCreated","Script created"),"success"),f(null),h(!1),y(Il),j(null),await C()}catch(J){const A=Re(J);A?.includes("already exists")?s(o("scriptsModal.scriptAlreadyExists","A script with this name already exists"),"error"):s(A||o("scriptsModal.failedToSave","Failed to save script"),"error")}finally{x(!1)}},[b,u,s,C,i,o]),V=a.useCallback(async L=>{try{await $A(L,i),s(o("scriptsModal.scriptDeleted","Script deleted"),"success"),w(null),u===L&&(f(null),y(Il)),await C()}catch(O){s(Re(O)||o("scriptsModal.failedToDelete","Failed to delete script"),"error")}},[u,s,C,i,o]),N=a.useCallback((L,O)=>{r&&r(L,O)},[r]);if(!e)return null;const $=p||u!==null,R=Object.entries(l).map(([L,O])=>({name:L,command:O}));return t.jsx("div",{className:"modal-overlay open",...S,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(ua,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),o("scriptsModal.title","Scripts")]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":o("actions.close","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(Et,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),o("scriptsModal.loadingScripts","Loading scripts...")]}):$?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:o("scriptsModal.scriptName","Script Name")}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:b.name,onChange:L=>D(L.target.value),placeholder:o("scriptsModal.scriptNamePlaceholder","e.g., build, test, lint"),disabled:v||u!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:g?"var(--color-error)":void 0}}),g&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:g}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:o("scriptsModal.nameHint","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:o("scriptsModal.command","Command")}),t.jsx("textarea",{id:"script-command",className:"input",value:b.command,onChange:L=>y(O=>({...O,command:L.target.value})),placeholder:o("scriptsModal.commandPlaceholder","e.g., npm run build"),rows:3,disabled:v,"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:M,disabled:v,"data-testid":"script-cancel-btn",children:o("actions.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary",onClick:_,disabled:v||!!g,"data-testid":"script-save-btn",children:v?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:14,className:"spin",style:{marginRight:"6px"}}),o("scriptsModal.saving","Saving...")]}):u?o("actions.update","Update"):o("actions.create","Create")})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:R.length===0?o("scriptsModal.noScriptsDefined","No scripts defined"):o("scriptsModal.scriptCount","{{count}} script",{count:R.length,defaultValue_other:"{{count}} scripts"})}),t.jsxs("button",{className:"btn btn-primary",onClick:E,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(ys,{size:14}),o("scriptsModal.addScript","Add Script")]})]}),R.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(ua,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:o("scriptsModal.noScriptsYet","No scripts defined yet.")}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:o("scriptsModal.addScriptsHint","Add scripts to quickly run common commands from the dashboard.")})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:R.map(L=>t.jsx("div",{className:"script-card","data-testid":`script-${L.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:L.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:L.command,children:w5(L.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:()=>N(L.name,L.command),title:o("scriptsModal.runScript","Run script"),"aria-label":o("scriptsModal.runScriptNamed","Run {{name}}",{name:L.name}),"data-testid":`run-script-${L.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(Ds,{size:12}),o("actions.run","Run")]}),t.jsx("button",{className:"btn-icon",onClick:()=>F(L.name,L.command),title:o("actions.edit","Edit"),"aria-label":o("scriptsModal.editScriptNamed","Edit {{name}}",{name:L.name}),"data-testid":`edit-script-${L.name}`,children:t.jsx(ys,{size:14,style:{transform:"rotate(45deg)"}})}),k===L.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>V(L.name),title:o("scriptsModal.confirmDelete","Confirm delete"),"aria-label":o("scriptsModal.confirmDeleteNamed","Confirm delete {{name}}",{name:L.name}),"data-testid":`confirm-delete-script-${L.name}`,style:{color:"var(--color-error)"},children:t.jsx(as,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>w(null),title:o("scriptsModal.cancelDelete","Cancel delete"),"aria-label":o("scriptsModal.cancelDelete","Cancel delete"),"data-testid":`cancel-delete-script-${L.name}`,children:t.jsx(Fn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>w(L.name),title:o("actions.delete","Delete"),"aria-label":o("scriptsModal.deleteScriptNamed","Delete {{name}}",{name:L.name}),"data-testid":`delete-script-${L.name}`,children:t.jsx(as,{size:14})})]})]})},L.name))})]})})]})})}function N5(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[d,c]=a.useState(!1),[m,p]=a.useState(null),[h,u]=a.useState(0),f=a.useCallback(()=>{u(y=>y+1)},[]),b=a.useCallback(y=>{l(y),p(null)},[]);return a.useEffect(()=>{l("."),p(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let y=!1;async function v(){c(!0),p(null);try{const x=await JM(e,o==="."?void 0:o,s);y||r(x.entries)}catch(x){y||(p(Re(x)||"Failed to load files"),r([]))}finally{y||c(!1)}}return v(),()=>{y=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:b,loading:d,error:m,refresh:f}}function S5(e,n,s,i){const{t:r}=st("app"),[o,l]=a.useState(""),[d,c]=a.useState(""),[m,p]=a.useState(null),[h,u]=a.useState(!1),[f,b]=a.useState(!1),[y,v]=a.useState(null),x=a.useCallback(g=>{l(g),v(null)},[]);a.useEffect(()=>{if(!e||!n){l(""),c(""),p(null),v(null);return}let g=!1;async function j(){u(!0),v(null);try{const S=await YM(e,n,i);g||(l(S.content),c(S.content),p(S.mtime))}catch(S){g||(v(Re(S)||r("editor.failedLoadFile","Failed to load file")),l(""),c(""),p(null))}finally{g||u(!1)}}return j(),()=>{g=!0}},[e,n,s,i]);const k=o!==d,w=a.useCallback(async()=>{if(!(!e||!n||!k)){b(!0),v(null);try{const g=await XM(e,n,o,i);c(o),p(g.mtime)}catch(g){throw v(Re(g)||r("editor.failedSaveFile","Failed to save file")),g}finally{b(!1)}}},[e,n,o,k,i]);return{content:o,setContent:x,originalContent:d,loading:h,saving:f,error:y,save:w,hasChanges:k,mtime:m}}const C5=1e4;function _5(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function E5(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function M5(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[d,c]=a.useState(null);return a.useEffect(()=>{let m=!1;async function p(){try{const u=await KM(e);if(m)return;s(_5(u.project)),r(u.tasks.map(E5)),c(null)}catch(u){m||c(Re(u)||"Failed to load workspaces")}finally{m||l(!1)}}p();const h=window.setInterval(()=>{p()},C5);return()=>{m=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:d}}function A5(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function T5(e){return e?new Date(e).toLocaleDateString():""}function Zx(e,n){return Eh(e,n)}const Dl={visible:!1,x:0,y:0,entry:null,entryFullPath:""},nh={type:null,entry:null,entryFullPath:""},R5=200,P5=500,ey=10;function I5({x:e,y:n,entry:s,onAction:i,onClose:r}){const{t:o}=st("app"),l=a.useRef(null),[d,c]=a.useState({x:e,y:n});a.useEffect(()=>{const h=l.current;if(!h)return;const u=h.getBoundingClientRect(),f=window.visualViewport,b=f?.width&&f.width>0?f.width:window.innerWidth,y=f?.height&&f.height>0?f.height:window.innerHeight,v=f?.offsetLeft??0,x=f?.offsetTop??0,k=8;let w=e-v,g=n-x;w+u.width>b-k&&(w=b-k-u.width),g+u.height>y-k&&(g=y-k-u.height),w<k&&(w=k),g<k&&(g=k),c({x:w+v,y:g+x})},[e,n]),a.useEffect(()=>{const h=u=>{u.key==="Escape"&&r()};return document.addEventListener("keydown",h),()=>document.removeEventListener("keydown",h)},[r]);const m=s.type==="directory",p=[{id:"copy",label:o("fileBrowser.contextCopy","Copy"),icon:Pa,disabled:!1},{id:"move",label:o("fileBrowser.contextMove","Move"),icon:w1,disabled:!1},{id:"rename",label:o("fileBrowser.contextRename","Rename"),icon:Si,disabled:!1},...m?[{id:"download-zip",label:o("fileBrowser.contextDownloadZip","Download as ZIP"),icon:Qr,disabled:!1}]:[{id:"download",label:o("fileBrowser.contextDownload","Download"),icon:ZC,disabled:!1}],{id:"divider",label:"",icon:Pa,disabled:!0},{id:"delete",label:o("fileBrowser.contextDelete","Delete"),icon:as,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:l,className:"file-browser-context-menu",role:"menu","aria-label":o("fileBrowser.contextMenuLabel","File operations"),style:{left:d.x,top:d.y},onClick:h=>h.stopPropagation(),children:p.map(h=>h.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 ${h.disabled?"file-browser-context-menu__disabled":""} ${h.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:h.disabled,onClick:()=>i(h.id),children:[t.jsx(h.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:h.label})]},h.id))})})}function D5({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const{t:d}=st("app"),c=a.useRef(null),m=e==="rename"&&n?n.name:"",[p,h]=a.useState(m);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&n&&c.current){const y=n.name.lastIndexOf(".");y>0?c.current.setSelectionRange(0,y):c.current.select()}},[e,n]);const u=y=>{y.key==="Enter"&&p.trim()&&i(p.trim()),y.key==="Escape"&&r()};if(e==="delete"&&n)return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:y=>y.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:d("fileBrowser.deleteTitle","Delete {{type}}",{type:n.type==="directory"?d("fileBrowser.typeFolder","Folder"):d("fileBrowser.typeFile","File")})}),t.jsxs("div",{className:"file-browser-dialog-message",children:[d("fileBrowser.deleteConfirm","Are you sure you want to delete {{name}}?",{name:n.name}),n.type==="directory"&&` ${d("fileBrowser.deleteRecursive","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:d("common.cancel","Cancel")}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?d("fileBrowser.deleting","Deleting..."):d("fileBrowser.delete","Delete")})]})]})});const b={copy:{title:d("fileBrowser.copyTitle","Copy"),placeholder:d("fileBrowser.copyPlaceholder","Destination path"),confirm:d("fileBrowser.copy","Copy")},move:{title:d("fileBrowser.moveTitle","Move"),placeholder:d("fileBrowser.movePlaceholder","Destination path"),confirm:d("fileBrowser.move","Move")},rename:{title:d("fileBrowser.renameTitle","Rename"),placeholder:d("fileBrowser.renamePlaceholder","New name"),confirm:d("fileBrowser.rename","Rename")},"create-file":{title:d("fileBrowser.newFile","New File"),placeholder:d("fileBrowser.fileNamePlaceholder","File name"),confirm:d("fileBrowser.create","Create")},"create-folder":{title:d("fileBrowser.newFolder","New Folder"),placeholder:d("fileBrowser.folderNamePlaceholder","Folder name"),confirm:d("fileBrowser.create","Create")}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:y=>y.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:b.title}),n&&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:p,onChange:y=>h(y.target.value),placeholder:b.placeholder,onKeyDown:u,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:d("common.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(p.trim()),disabled:o||!p.trim(),children:o?`${b.confirm}${d("fileBrowser.operationSuffix","ing...")}`:b.confirm})]})]})})}function L5({entries:e,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:o,onRetry:l,workspace:d,onRefresh:c,projectId:m}){const{t:p}=st("app"),[h,u]=a.useState(Dl),[f,b]=a.useState(nh),[y,v]=a.useState(!1),[x,k]=a.useState(null),[w,g]=a.useState(!1),[j,S]=a.useState(null),C=a.useRef(null),E=a.useRef(null),F=a.useRef(null),M=a.useRef(!1),D=a.useCallback(()=>{C.current!==null&&(window.clearTimeout(C.current),C.current=null),E.current!==null&&(window.clearTimeout(E.current),E.current=null)},[]),_=a.useCallback(()=>{D(),F.current=null,g(!1),S(null)},[D]);a.useEffect(()=>()=>{D()},[D]);const V=a.useCallback((P,Z,T,ie)=>{u({visible:!0,x:P,y:Z,entry:T,entryFullPath:ie})},[]),N=a.useCallback((P,Z,T)=>{if(P.touches.length!==1)return;const ie=P.touches[0];ie&&(_(),F.current={x:ie.clientX,y:ie.clientY},E.current=window.setTimeout(()=>{g(!0),S(T)},R5),C.current=window.setTimeout(()=>{const le=F.current;le&&(M.current=!0,g(!1),S(null),D(),V(le.x,le.y,Z,T))},P5))},[_,D,V]),$=a.useCallback(P=>{const Z=F.current,T=P.touches[0];!Z||!T||(Math.abs(T.clientX-Z.x)>ey||Math.abs(T.clientY-Z.y)>ey)&&_()},[_]),R=a.useCallback(()=>{_()},[_]);a.useEffect(()=>{if(!h.visible)return;const P=document.querySelector(".file-browser-list"),Z=()=>{M.current=!1,_(),u(Dl)};return P?.addEventListener("scroll",Z),()=>P?.removeEventListener("scroll",Z)},[_,h.visible]),a.useEffect(()=>{if(!h.visible)return;const P=Z=>{Z.key==="Escape"&&(M.current=!1,u(Dl))};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[h.visible]);const L=a.useCallback((P,Z)=>{P.preventDefault(),P.stopPropagation(),_(),M.current=!1,V(P.clientX,P.clientY,Z,Zx(n,Z.name))},[_,n,V]),O=a.useCallback(P=>{d&&(b({type:P,entry:null,entryFullPath:n}),k(null))},[n,d]),J=a.useCallback(P=>{if(!h.entry)return;M.current=!1;const Z=h.entry,T=h.entryFullPath;if(u(Dl),P==="download"){if(!d)return;const ie=Xk(d,T,m);window.open(pa(ie),"_blank");return}if(P==="download-zip"){if(!d)return;const ie=aA(d,T,m);window.open(pa(ie),"_blank");return}b({type:P,entry:Z,entryFullPath:T}),k(null)},[h,d,m]),A=a.useCallback(async P=>{if(!(!f.type||!d)){v(!0),k(null);try{switch(f.type){case"copy":if(!f.entry)return;await tA(d,f.entryFullPath,P,m);break;case"move":if(!f.entry)return;await nA(d,f.entryFullPath,P,m);break;case"rename":if(!f.entry)return;await iA(d,f.entryFullPath,P,m);break;case"delete":if(!f.entry)return;await sA(d,f.entryFullPath,m);break;case"create-file":{const Z=Eh(f.entryFullPath,P);await eA(d,Z,m),s(Z);break}case"create-folder":await ZM(d,Eh(f.entryFullPath,P),m);break}b(nh),c?.()}catch(Z){k(Re(Z)||p("fileBrowser.operationFailed","Operation failed"))}finally{v(!1)}}},[f,d,c,s,m,p]),de=a.useCallback(()=>{b(nh),k(null)},[]),B=a.useCallback((P,Z)=>{if(M.current){M.current=!1;return}h.visible||(P.type==="directory"?i(Z):s(Z))},[h.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(Et,{className:"spin",size:24}),t.jsx("span",{children:p("fileBrowser.loadingFiles","Loading files...")})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsx("p",{children:p("fileBrowser.error","Error: {{message}}",{message:o})}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:p("common.retry","Retry")})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{i(Q_(n))},children:[t.jsx(ls,{size:16,style:{transform:"rotate(-90deg)"}}),p("fileBrowser.upOneLevel","Up one level")]}),t.jsx("span",{className:"file-browser-path",children:n==="."?p("fileBrowser.root","Root"):cl(n)}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>O("create-file"),disabled:!d,children:[t.jsx(m0,{size:14}),p("fileBrowser.newFile","New File")]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>O("create-folder"),disabled:!d,children:[t.jsx(C0,{size:14}),p("fileBrowser.newFolder","New Folder")]})]})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:p("fileBrowser.emptyDirectory","(empty directory)")}):e.map(P=>{const Z=Zx(n,P.name),T=w&&j===Z;return t.jsxs("div",{className:`file-node file-node--${P.type} ${T?"file-node--long-pressing":""}`,onClick:()=>B(P,Z),onContextMenu:ie=>L(ie,P),onTouchStart:ie=>N(ie,P,Z),onTouchMove:$,onTouchEnd:R,onTouchCancel:R,children:[t.jsx("div",{className:"file-node-icon",children:P.type==="directory"?t.jsx(Zs,{size:16}):t.jsx(Nk,{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:A5(P.size)}),P.mtime&&t.jsx("div",{className:"file-node-time",children:T5(P.mtime)})]},P.name)})}),h.visible&&h.entry&&t.jsx(I5,{x:h.x,y:h.y,entry:h.entry,onAction:J,onClose:()=>{M.current=!1,u(Dl)}}),f.type&&t.jsx(D5,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:A,onCancel:de,loading:y,error:x})]})}function F5(e){if(!e)return null;const n=e.toLowerCase();return n.endsWith(".js")||n.endsWith(".mjs")||n.endsWith(".cjs")||n.endsWith(".jsx")?Xf({jsx:!0}):n.endsWith(".ts")||n.endsWith(".tsx")?Xf({jsx:!0,typescript:!0}):n.endsWith(".css")?GS():n.endsWith(".json")?KS():n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")?JS():null}function O5(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function ty(){return document.documentElement.dataset.theme!=="light"}function ny(e){return e?[YS]:[XS(QS)]}function $5({content:e,onChange:n,readOnly:s,filePath:i,showLineNumbers:r=!1,onToggleLineNumbers:o,canToggleLineNumbers:l=!0,toolbarExpanded:d,toolbarActionsId:c}){const{t:m}=st("app"),[p,h]=a.useState(!1),[u,f]=a.useState(!0),[b,y]=a.useState(!1),v=d!==void 0,x=v?d:b,k=a.useRef(null),w=a.useRef(null),g=a.useRef(!1),j=a.useRef(n);j.current=n;const S=a.useRef(new yl),C=a.useRef(new yl),E=a.useRef(new yl),F=a.useRef(new yl),M=a.useRef(new yl),D=O5(i),_=a.useId(),V=c??_,[N,$]=a.useState(()=>ty()),R=D&&(s?!0:p),L=r&&!s&&!R,O=!!o&&l&&!s&&!R,J=D||!s||O,A=a.useMemo(()=>F5(i),[i]),de=a.useCallback(()=>h(!1),[]),B=a.useCallback(()=>h(!0),[]),P=a.useCallback(()=>f(T=>!T),[]),Z=a.useCallback(()=>{v||y(T=>!T)},[v]);return a.useEffect(()=>{if(!k.current||R)return;const T=Pr.theme({"&":{height:"100%",fontFamily:"var(--font-mono)",backgroundColor:"var(--bg)",color:"var(--text)"},".cm-gutters":{backgroundColor:"var(--surface)",color:"var(--text-muted)",borderRight:"calc(var(--space-xs) * 0.25) solid var(--border)"},"&.cm-focused":{outline:"none"}}),ie=Hu.create({doc:e,extensions:[S.current.of(L?Qf():[]),C.current.of(u?Pr.lineWrapping:[]),E.current.of(s?[Hu.readOnly.of(!0),Pr.editable.of(!1)]:[]),F.current.of(A??[]),M.current.of(ny(N)),T,Pr.updateListener.of(be=>{!be.docChanged||g.current||j.current(be.state.doc.toString())})]}),le=new Pr({state:ie,parent:k.current});return w.current=le,()=>{w.current=null,le.destroy()}},[R]),a.useEffect(()=>{const T=new MutationObserver(()=>{$(ty())});return T.observe(document.documentElement,{attributes:!0,attributeFilter:["data-theme"]}),()=>T.disconnect()},[]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:S.current.reconfigure(L?Qf():[])})},[L]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:C.current.reconfigure(u?Pr.lineWrapping:[])})},[u]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:E.current.reconfigure(s?[Hu.readOnly.of(!0),Pr.editable.of(!1)]:[])})},[s]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:F.current.reconfigure(A??[])})},[A]),a.useEffect(()=>{const T=w.current;T&&T.dispatch({effects:M.current.reconfigure(ny(N))})},[N]),a.useEffect(()=>{const T=w.current;!T||T.state.doc.toString()===e||(g.current=!0,T.dispatch({changes:{from:0,to:T.state.doc.length,insert:e}}),g.current=!1)},[e]),t.jsxs("div",{className:"file-editor-container",children:[J&&(x||!v)?t.jsxs("div",{className:`file-editor-toolbar ${x?"file-editor-toolbar--expanded":""}`,children:[!v&&t.jsx("button",{className:"btn btn-sm btn-icon file-editor-toolbar-button",onClick:Z,"aria-label":m("fileEditor.toggleOptions","Toggle editor options"),title:m("fileEditor.toggleOptions","Toggle editor options"),"aria-expanded":x,"aria-controls":V,children:x?t.jsx(ra,{size:14}):t.jsx(Ln,{size:14})}),t.jsxs("div",{className:"file-editor-toolbar-actions",id:V,hidden:!x,children:[D?t.jsxs(t.Fragment,{children:[!s&&t.jsxs("button",{className:`btn btn-sm file-editor-toolbar-button ${R?"":"btn-primary"}`,onClick:de,disabled:!R,"aria-label":m("fileEditor.editMode","Edit mode"),children:[t.jsx(jk,{size:14}),m("fileEditor.edit","Edit")]}),t.jsxs("button",{className:`btn btn-sm file-editor-toolbar-button ${R?"btn-primary":""}`,onClick:B,disabled:R,"aria-label":m("fileEditor.previewMode","Preview mode"),children:[t.jsx(bc,{size:14}),m("fileEditor.preview","Preview")]})]}):null,O&&t.jsxs("button",{className:`btn btn-sm file-editor-toolbar-button ${r?"btn-primary":""}`,onClick:o,"aria-label":m("fileEditor.toggleLineNumbers","Toggle line numbers"),"aria-pressed":r,title:m("fileEditor.toggleLineNumbers","Toggle line numbers"),children:[t.jsx(t1,{size:14}),t.jsx("span",{children:m("fileEditor.lineNumber","Line #")})]}),!s&&t.jsxs("button",{className:`btn btn-sm file-editor-toolbar-button ${u?"btn-primary":""}`,onClick:P,"aria-label":m("fileEditor.toggleWordWrap","Toggle word wrap"),title:m("fileEditor.toggleWordWrap","Toggle word wrap"),children:[t.jsx(Cp,{size:14}),t.jsx("span",{children:m("fileEditor.wrap","Wrap")})]})]})]}):null,R?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(Di,{remarkPlugins:[Li],children:e})}):t.jsx("div",{className:"file-editor-codemirror",ref:k,"aria-label":i?m("fileEditor.editorFor",`Editor for ${i}`):m("fileEditor.fileEditor","File editor")})]})}function z5(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function B5({currentWorkspace:e,projectName:n,workspaces:s,onSelect:i}){const{t:r}=st("app"),[o,l]=a.useState(!1),d=typeof e=="string"?e:"project",c=a.useMemo(()=>d==="project"?n||r("workspace.projectRoot","Project Root"):s.find(p=>p.id===d)?.label??d,[d,n,s,r]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>l(m=>!m),"aria-haspopup":"listbox","aria-expanded":o,children:[d==="project"?t.jsx(ng,{size:14}):t.jsx(wh,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:c}),t.jsx(Ln,{size:14,className:`workspace-selector-trigger-icon${o?" open":""}`})]}),o&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":r("workspace.selectWorkspace","Select workspace"),children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${d==="project"?" active":""}`,onClick:()=>{i("project"),l(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(ng,{size:14}),t.jsx("span",{children:r("workspace.projectRoot","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:r("workspace.taskWorktrees","Task Worktrees")}),s.map(m=>t.jsxs("button",{type:"button",className:`workspace-selector-option${d===m.id?" active":""}`,onClick:()=>{i(m.id),l(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(wh,{size:14}),t.jsx("span",{children:m.id})]}),m.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:m.title,children:z5(m.title)})]},m.id))]})]})]})}const U5=768,H5=280,bd=180,vd=500,sy="fusion:file-browser-sidebar-width",iy="kb-files-line-numbers",RN=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),V5=new Set([...RN,".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 Ll(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return V5.has(n)}function q5(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return RN.has(n)}function W5(e){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,""),s=n.lastIndexOf("/");return s>0?n.slice(0,s):"."}function G5({initialWorkspace:e="project",initialFile:n=null,onClose:s,onWorkspaceChange:i,projectId:r}){const{t:o}=st("app"),{projectName:l,workspaces:d}=M5(r),c=a.useRef(null);La(c,!0,"fusion:files-modal-size");const m=yr(s),[p,h]=a.useState(e),[u,f]=a.useState(null),[b,y]=a.useState(!1),[v,x]=a.useState("list"),[k,w]=a.useState(H5),[g,j]=a.useState(!1),[S,C]=a.useState(!1),E=a.useId(),{entries:F,currentPath:M,setPath:D,loading:_,error:V,refresh:N}=N5(p,!0,r),{content:$,setContent:R,originalContent:L,loading:O,saving:J,error:A,save:de,hasChanges:B,mtime:P}=S5(p,u,!0,r);a.useEffect(()=>{h(e)},[e]),a.useEffect(()=>{const pe=()=>{y(window.innerWidth<=U5)};return pe(),window.addEventListener("resize",pe),()=>window.removeEventListener("resize",pe)},[]),a.useEffect(()=>{u||x("list"),C(!1)},[u]),a.useEffect(()=>{if(!n){f(null);return}f(n),D(W5(n)),b&&x("editor")},[n,b,D]),a.useEffect(()=>{try{const pe=localStorage.getItem(sy);if(!pe)return;const te=Number.parseInt(pe,10);if(!Number.isNaN(te)){const me=Math.max(bd,Math.min(vd,te));w(me)}}catch{}},[]),a.useEffect(()=>{const pe=cs(iy,r);j(pe==="true")},[r]),a.useEffect(()=>{const pe=te=>{te.key==="Escape"&&s(),(te.metaKey||te.ctrlKey)&&te.key==="s"&&(te.preventDefault(),B&&!J&&de())};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[s,B,J,de]);const Z=a.useCallback(pe=>{f(pe),b&&x("editor")},[b]),T=a.useCallback(()=>{x("list")},[]),ie=a.useCallback(()=>{R(L)},[L,R]),le=a.useCallback(pe=>{h(pe),f(null),x("list"),i?.(pe)},[i]),be=a.useCallback(pe=>{try{localStorage.setItem(sy,String(pe))}catch{}},[]),Le=a.useCallback(pe=>{if(b)return;pe.preventDefault(),pe.stopPropagation();const te=pe.currentTarget;typeof te.setPointerCapture=="function"&&te.setPointerCapture(pe.pointerId);const me=pe.clientX,se=k;let z=se;document.body.style.userSelect="none";const Y=X=>{const ye=X.clientX-me,ot=Math.max(bd,Math.min(vd,se+ye));z=ot,w(ot)},he=X=>{typeof te.releasePointerCapture=="function"&&te.releasePointerCapture(X.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Y),document.removeEventListener("pointerup",he),be(z)};document.addEventListener("pointermove",Y),document.addEventListener("pointerup",he)},[b,be,k]),xe=a.useCallback(pe=>{if(b)return;const te=20;if(pe.key!=="ArrowLeft"&&pe.key!=="ArrowRight")return;pe.preventDefault();const me=pe.key==="ArrowLeft"?-te:te,se=Math.max(bd,Math.min(vd,k+me));w(se),be(se)},[b,be,k]),q=a.useCallback(()=>{j(pe=>{const te=!pe;return _s(iy,String(te),r),te})},[r]),ce=a.useMemo(()=>p==="project"?o("fileBrowser.workspaceProject","Project"):d.find(pe=>pe.id===p)?.id??p,[p,d,o]),De=o("fileBrowser.modalTitle","Files — {{workspace}}",{workspace:ce}),He=a.useMemo(()=>!u||!q5(u)?null:Xk(p,u,r),[u,p,r]),qe=pe=>{const te=new Blob([pe]).size;return te<1024?`${te} B`:`${(te/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...m,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:c,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(Zs,{size:18}),t.jsx("span",{children:De}),u&&t.jsx("span",{className:"file-browser-header-path",children:u})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(B5,{currentWorkspace:p,projectName:l,workspaces:d,onSelect:le}),t.jsx("button",{className:"modal-close",onClick:s,"aria-label":o("actions.close","Close"),children:t.jsx(Fn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${b?"mobile":""} ${v==="list"?"active":""}`,style:b?void 0:{width:`${k}px`},children:t.jsx(L5,{entries:F,currentPath:M,onSelectFile:Z,onNavigate:D,loading:_,error:V,onRetry:N,workspace:p,onRefresh:N,projectId:r})}),!b&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":bd,"aria-valuemax":vd,"aria-valuenow":k,"aria-label":o("fileBrowser.resizeSidebar","Resize sidebar"),tabIndex:0,onPointerDown:Le,onKeyDown:xe}),t.jsx("div",{className:`file-browser-content ${b?"mobile":""} ${v==="editor"?"active":""}`,children:u?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[b&&v==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:T,"aria-label":o("fileBrowser.back","Back to file list"),children:[t.jsx(Zr,{size:16}),t.jsx("span",{children:o("actions.back","Back")})]}),!Ll(u)&&t.jsx("button",{className:"btn btn-sm btn-icon file-editor-toolbar-button",onClick:()=>C(pe=>!pe),"aria-label":o("fileBrowser.toggleEditorOptions","Toggle editor options"),title:o("fileBrowser.toggleEditorOptions","Toggle editor options"),"aria-expanded":S,"aria-controls":E,children:S?t.jsx(ra,{size:14}):t.jsx(Ln,{size:14})}),u,Ll(u)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(x0,{size:12}),o("fileBrowser.binaryReadOnly","Binary file — read only")]}),P&&t.jsx("span",{className:"file-browser-mtime",children:o("fileBrowser.modified","Modified: {{date}}",{date:new Date(P).toLocaleString()})}),O&&t.jsx("span",{className:"file-browser-loading",children:o("fileBrowser.loading","Loading…")})]}),t.jsx("div",{className:"file-browser-actions",children:!He&&B&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:ie,disabled:J,children:[t.jsx(L1,{size:14}),o("actions.discard","Discard")]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void de(),disabled:J,children:[t.jsx(Tk,{size:14}),J?o("fileBrowser.saving","Saving…"):o("actions.save","Save")]})]})})]}),A&&!He&&t.jsx("div",{className:"file-browser-error-banner",children:A}),He?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:He,alt:u??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx($5,{content:$,onChange:R,filePath:u,readOnly:Ll(u),showLineNumbers:g&&!Ll(u),onToggleLineNumbers:q,canToggleLineNumbers:!Ll(u),toolbarExpanded:S,toolbarActionsId:E})}),!He&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:qe($)}),B&&t.jsx("span",{className:"file-browser-unsaved",children:o("fileBrowser.unsavedChanges","Unsaved changes")})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(Zs,{size:48,opacity:.3}),t.jsx("p",{children:o("fileBrowser.selectFileToEdit","Select a file to edit")})]})})]})]})})}const K5=a.lazy(()=>ln(()=>import("./TodoView-B8IK_BPM.js"),__vite__mapDeps([18,1,4,5,6,2,3,7,19])).then(e=>({default:e.TodoView})));function J5({onClose:e,projectId:n,addToast:s,onPlanningMode:i}){const{t:r}=st("app"),o=yr(e),d=Ji()==="mobile",{keyboardOverlap:c,viewportHeight:m,viewportOffsetTop:p,keyboardOpen:h}=Xa({enabled:d});ga(d);const u=h?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${p}px`,...m!==null?{"--vv-height":`${m}px`}:{}}:{};return a.useEffect(()=>{const f=b=>{b.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...o,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:u,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(Ek,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:r("todo.todos","Todos")}),t.jsx("p",{children:r("todo.manageDescription","Manage reusable todo lists for your project.")})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":r("common.close","Close"),children:t.jsx(Fn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(K5,{projectId:n,addToast:s,onPlanningMode:i,onClose:e,mobileKeyboardActive:d&&h})})})]})})}function Y5(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[i,r]=a.useState({providers:[],loading:!0,error:null,lastUpdated:null,hasFetched:!1}),o=a.useRef(null),l=a.useRef(null),d=a.useRef(i),c=ul();a.useEffect(()=>{d.current=i},[i]);const m=a.useCallback(u=>d.current.hasFetched&&_c(u,c.wasRecentlyHidden()),[c]),p=a.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(f=>({...f,loading:!0,error:null}));try{const{providers:f}=await qE();r({providers:f,loading:!1,error:null,lastUpdated:new Date,hasFetched:!0})}catch(f){if(f instanceof Error&&f.name==="AbortError")return;const b=Re(f)||"Failed to fetch usage data";if(m(b)){r(y=>({...y,loading:!1}));return}r(y=>({...y,loading:!1,error:b,hasFetched:!0}))}},[m]);a.useEffect(()=>{p()},[p]),a.useEffect(()=>{if(s)return o.current=setInterval(()=>{p(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,p]),a.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const h=a.useCallback(()=>p(!0),[p]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,hasFetched:i.hasFetched,refresh:h}}function X5(e){const n=new Date(e),s=new Date,i=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return i;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),d=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return d>=1&&d<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${i}`}function Q5(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const PN="kb-usage-hidden-windows",IN="kb-usage-modal-size",DN="kb-usage-provider-order";function ay(e){const n=cs(IN,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 ry(e){const n=cs(PN,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((i,[r,o])=>{if(Array.isArray(o)){const l=o.filter(d=>typeof d=="string");l.length>0&&(i[r]=l)}return i},{})}catch{return{}}}function Z5(e,n){_s(PN,JSON.stringify(e),n)}function oy(e){const n=cs(DN,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(i=>typeof i=="string"):[]}catch{return[]}}function ly(e,n){_s(DN,JSON.stringify(e),n)}const eU="::";function LN(e,n){return`${n}${eU}${e}`}function Pf(e,n,s){return e===LN(n,s)||e===n}function If(e,n,s,i){return(i[e]??[]).some(r=>Pf(r,n,s))}function tU(e,n,s){return(n??[]).reduce((i,r,o)=>i+(If(e,r.label,o,s)?1:0),0)}function nU(e,n,s){const i=n??[],r=tU(e,i,s),o=s[e]??[];if(o.length===0)return r;const l=o.reduce((d,c)=>{const m=i.some((p,h)=>Pf(c,p.label,h));return d+(m?0:1)},0);return r+l}function sU({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const{t:r}=st("app"),o=Q5(e.percentUsed),l=n==="remaining",d=Math.round(l?e.percentLeft:e.percentUsed),c=l?r("usage.percentRemaining","{{percent}}% remaining",{percent:Math.round(e.percentLeft)}):r("usage.percentUsed","{{percent}}% used",{percent:Math.round(e.percentUsed)}),m=l?r("usage.percentUsed","{{percent}}% used",{percent:Math.round(e.percentUsed)}):r("usage.percentLeft","{{percent}}% left",{percent:Math.round(e.percentLeft)});let p=e.resetText;if(!p&&e.resetAt){const x=new Date(e.resetAt).getTime()-Date.now();if(x>0){const k=Math.floor(x/36e5),w=Math.floor(k/24),g=k%24;if(w>0&&g>0)p=r("usage.resetsInDaysHours","resets in {{days}}d {{hours}}h",{days:w,hours:g});else if(w>0)p=r("usage.resetsInDays","resets in {{days}}d",{days:w});else if(k>0)p=r("usage.resetsInHours","resets in {{hours}}h",{hours:k});else{const j=Math.floor(x/6e4);p=r("usage.resetsInMinutes","resets in {{mins}}m",{mins:j})}}}const h=e.pace,u=h!==void 0;let f=0;u&&(f=l?100-h.percentElapsed:h.percentElapsed);const b=h?.status==="ahead",y=h?.status==="behind",v=h?.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",{type:"button",className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":r("usage.hideWindow","Hide {{label}}",{label:e.label}),"data-testid":"usage-window-hide-btn",children:t.jsx(bc,{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 ${o}`,style:{width:`${d}%`},role:"progressbar","aria-valuenow":d,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),u&&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:m}),t.jsxs("span",{className:"usage-window-reset-group",children:[p&&t.jsx("span",{className:"usage-window-reset",children:p}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:X5(e.resetAt)})]})]}),u&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[b&&t.jsxs(t.Fragment,{children:[t.jsx(oa,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:h.message})]}),y&&t.jsxs(t.Fragment,{children:[t.jsx(r_,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:h.message})]}),v&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:h.message})]})]})]})}function iU(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 aU({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:d,onDragStart:c,onDragOver:m,onDragLeave:p,onDrop:h,onDragEnd:u,isTouchReorderMode:f,canMoveUp:b,canMoveDown:y,onMoveUp:v,onMoveDown:x}){const{t:k}=st("app"),w=e.windows??[],g=nU(e.name,w,s),j=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:k("usage.statusError","Error")});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:k("usage.statusNotConfigured","Not configured")})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&d==="before"?" usage-provider--drag-over-before":""}${l&&d==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!f,onDragStart:f?void 0:c,onDragOver:f?void 0:m,onDragLeave:f?void 0:p,onDrop:f?void 0:h,onDragEnd:f?void 0:u,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(hs,{provider:iU(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),g>0&&t.jsx("button",{type:"button",className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:k("usage.showHidden","Show hidden ({{count}})",{count:g})})]}),t.jsxs("div",{className:"usage-provider-actions",children:[f&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":k("usage.reorderProvider","Reorder {{provider}}",{provider:e.name}),children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:v,disabled:!b,"aria-label":k("usage.moveProviderUp","Move {{provider}} up",{provider:e.name}),children:t.jsx(ra,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:x,disabled:!y,"aria-label":k("usage.moveProviderDown","Move {{provider}} down",{provider:e.name}),children:t.jsx(Ln,{size:14})})]}),j(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(pu,{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})}),w.length>0?t.jsx("div",{className:"usage-provider-windows",children:w.map((S,C)=>{const E=If(e.name,S.label,C,s);return t.jsx(sU,{window:S,viewMode:n,isHidden:E,onToggleHidden:()=>i(e.name,S.label,C)},`${e.name}-${S.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:k("usage.noDataAvailable","No usage data available")}):null]})}function rU(){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 oU({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{t:r}=st("app"),{providers:o,loading:l,error:d,lastUpdated:c,hasFetched:m,refresh:p}=Y5({autoRefresh:e}),[h,u]=a.useState(!1),[f,b]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[y,v]=a.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[x,k]=a.useState("used"),[w,g]=a.useState(()=>ry(s)),[j,S]=a.useState(()=>oy(s)),[C,E]=a.useState(null),[F,M]=a.useState(null),[D,_]=a.useState(null),V=a.useRef(null),N=a.useRef(null),$=a.useRef(e),[R,L]=a.useState(()=>ay(s));a.useEffect(()=>{L(ay(s))},[s]),a.useEffect(()=>{if(!e||!f)return;const se=N.current;if(!se||typeof ResizeObserver>"u")return;let z=null;const Y=new ResizeObserver(he=>{const X=he[0];if(!X)return;const{width:ye,height:ot}=X.contentRect;ye<=0||ot<=0||(z&&clearTimeout(z),z=setTimeout(()=>{_s(IN,JSON.stringify({width:Math.round(ye),height:Math.round(ot)}),s)},250))});return Y.observe(se),()=>{z&&clearTimeout(z),Y.disconnect()}},[e,f,s]),a.useEffect(()=>{if(typeof window>"u")return;const se=window.matchMedia?.("(pointer: coarse)"),z=()=>{b(window.innerWidth>=769),v(se?.matches??!1)};return z(),window.addEventListener("resize",z),se?.addEventListener?.("change",z),()=>{window.removeEventListener("resize",z),se?.removeEventListener?.("change",z)}},[]),a.useEffect(()=>{!$.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&p(),$.current=e},[e,c,p]),a.useEffect(()=>{const se=cs("kb-usage-view-mode",s);if(se==="used"||se==="remaining"){k(se);return}k("used")},[s]);const O=a.useCallback(se=>{k(se),_s("kb-usage-view-mode",se,s)},[s]);a.useEffect(()=>{g(ry(s)),S(oy(s))},[s]),a.useEffect(()=>{Z5(w,s)},[w,s]);const J=a.useCallback((se,z,Y)=>{g(he=>{const X=LN(z,Y),ye=he[se]??[];if(If(se,z,Y,he)){const ot=ye.filter(ue=>!Pf(ue,z,Y));if(ot.length===0){const{[se]:ue,...je}=he;return je}return{...he,[se]:ot}}return{...he,[se]:[...ye,X]}})},[]),A=a.useCallback(se=>{g(z=>{if(!z[se])return z;const{[se]:Y,...he}=z;return he})},[]),de=a.useCallback(se=>{if(j.length===0)return se;const z=new Map(se.map(he=>[he.name,he])),Y=[];for(const he of j){const X=z.get(he);X&&(Y.push(X),z.delete(he))}return[...Y,...z.values()]},[j]),B=a.useCallback((se,z)=>{se.dataTransfer.effectAllowed="move",se.dataTransfer.setData("text/plain",z),E(z)},[]),P=a.useCallback((se,z)=>{if(!C||C===z)return;se.preventDefault(),se.dataTransfer.dropEffect="move";const{top:Y,height:he}=se.currentTarget.getBoundingClientRect(),X=Y+he/2,ye=se.clientY<X?"before":"after";M(z),_(ye)},[C]),Z=a.useCallback((se,z)=>{se.preventDefault();const Y=C??se.dataTransfer.getData("text/plain");if(!Y||Y===z){M(null),_(null);return}const X=de(o).map(ue=>ue.name).filter(ue=>ue!==Y),ye=X.indexOf(z);if(ye<0){M(null),_(null);return}const ot=D==="after"?ye+1:ye;X.splice(ot,0,Y),ly(X,s),S(X),M(null),_(null)},[C,D,s,o,de]),T=a.useCallback(()=>{E(null),M(null),_(null)},[]),ie=a.useCallback((se,z)=>{const Y=de(o).map(ue=>ue.name),he=Y.indexOf(se),X=he+z;if(he<0||X<0||X>=Y.length)return;const ye=[...Y],[ot]=ye.splice(he,1);ye.splice(X,0,ot),ly(ye,s),S(ye)},[s,o,de]),le=a.useCallback(async()=>{u(!0),await p(),u(!1)},[p]);a.useEffect(()=>{if(!e)return;const se=z=>{z.key==="Escape"&&n()};return document.addEventListener("keydown",se),()=>document.removeEventListener("keydown",se)},[e,n]);const be=a.useCallback(se=>{se.target===se.currentTarget&&n()},[n]);if(!e)return null;const Le=!!(i&&f),xe=8,q=12,De=R?.width??420,He=Le?Math.min((i?.bottom??0)+xe,window.innerHeight-q):void 0,qe=Le?Math.max(8,(i?.right??0)-De):void 0,pe=f&&R?{width:R.width,height:R.height}:{},te=de(o),me=t.jsxs("div",{ref:N,className:`usage-modal${Le?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:Le?{position:"fixed",top:He,left:qe,...pe}:pe,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ci,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:r("usage.title","Usage")})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":r("usage.viewModeLabel","Usage view mode"),children:[t.jsx("button",{className:`usage-view-toggle-btn ${x==="used"?"active":""}`,onClick:()=>O("used"),"aria-pressed":x==="used","data-testid":"usage-view-toggle-used",children:r("usage.viewModeUsed","Used")}),t.jsx("button",{className:`usage-view-toggle-btn ${x==="remaining"?"active":""}`,onClick:()=>O("remaining"),"aria-pressed":x==="remaining","data-testid":"usage-view-toggle-remaining",children:r("usage.viewModeRemaining","Remaining")})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":r("actions.closeModal","Close usage modal"),"data-testid":"usage-modal-close",children:t.jsx(Fn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:V,children:!m&&!d&&o.length===0?t.jsx(rU,{}):d&&o.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:r("usage.failedToLoad","Failed to load usage data")}),t.jsx("p",{className:"usage-error-message",children:d}),t.jsx("button",{className:"btn btn-sm",onClick:le,children:r("actions.retry","Retry")})]}):o.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:r("usage.noProvidersConfigured","No AI providers configured")}),t.jsx("p",{className:"usage-empty-hint",children:r("usage.configureAuthHint","Configure authentication in Settings to see usage data.")})]}):t.jsx("div",{className:"usage-providers",children:te.map((se,z)=>t.jsx(aU,{provider:se,viewMode:x,hiddenWindows:w,onToggleWindow:J,onShowAllHidden:A,isDragging:C===se.name,isDragOver:F===se.name,dragOverPosition:F===se.name?D:null,onDragStart:Y=>B(Y,se.name),onDragOver:Y=>P(Y,se.name),onDragLeave:()=>{F===se.name&&(M(null),_(null))},onDrop:Y=>Z(Y,se.name),onDragEnd:T,isTouchReorderMode:y,canMoveUp:z>0,canMoveDown:z<te.length-1,onMoveUp:()=>ie(se.name,-1),onMoveDown:()=>ie(se.name,1)},se.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.jsx("span",{children:r("usage.lastUpdated","Last updated: {{time}}",{time:c.toLocaleTimeString()})})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:le,disabled:l||h,"data-testid":"usage-refresh-btn",children:[t.jsx(xs,{size:14,className:h?"spin":"",style:{marginRight:6}}),r("actions.refresh","Refresh")]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:r("actions.close","Close")})]})]})]});return Le?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),me]}):t.jsx("div",{className:"modal-overlay open",onClick:be,"data-testid":"usage-modal-overlay",children:me})}function FN(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),i=n%60;if(s<60)return i>0?`${s}m ${i}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function au(e){const n=Date.now(),s=new Date(e).getTime(),i=n-s;if(i<0){const r=Math.abs(i);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return i<6e4?"just now":i<36e5?`${Math.floor(i/6e4)}m ago`:i<864e5?`${Math.floor(i/36e5)}h ago`:`${Math.floor(i/864e5)}d ago`}const lU={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},ON={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},cU={cron:xk,webhook:Rk,api:kk,manual:Ws},dU={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},uU={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function mU({result:e}){const{t:n}=st("app"),s=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(Es,{size:12}):t.jsx(vr,{size:12}),t.jsx("span",{children:e.success?n("routine.resultSuccess","Success"):n("routine.resultFailed","Failed")}),s>0&&t.jsx("span",{className:"schedule-run-duration",children:FN(s)})]})}function hU({result:e,index:n}){const[s,i]=a.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>i(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${au(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Es,{size:12}):t.jsx(vr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:au(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:ON[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:FN(r)}),s?t.jsx(ra,{size:12}):t.jsx(Ln,{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 pU({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const{t:d}=st("app"),[c,m]=a.useState(!1),{confirm:p}=Yi(),h=a.useCallback(async()=>{await p({title:d("routine.deleteTitle","Delete Routine"),message:d("routine.deleteMessage",'Delete routine "{{name}}"? This cannot be undone.',{name:e.name}),danger:!0})&&s(e)},[e,s,p,d]),u=lU[e.trigger.type],f=cU[e.trigger.type],b=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:u,color:u},children:[t.jsx(f,{size:10}),ON[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(Np,{size:10}):t.jsx(Zs,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>i(e),disabled:o,title:o?d("routine.running","Running…"):d("routine.runNow","Run now"),"aria-label":o?d("routine.running","Running…"):d("routine.runNameNow","Run {{name}} now",{name:e.name}),children:o?t.jsx(Et,{className:"spinner"}):t.jsx(Ds,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?d("routine.disable","Disable"):d("routine.enable","Enable"),"aria-label":e.enabled?d("routine.disableName","Disable {{name}}",{name:e.name}):d("routine.enableName","Enable {{name}}",{name:e.name}),"aria-pressed":e.enabled,children:e.enabled?t.jsx(ia,{}):t.jsx(Ds,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:d("routine.edit","Edit"),"aria-label":d("routine.editName","Edit {{name}}",{name:e.name}),children:t.jsx(Si,{})}),t.jsx("button",{className:"btn-icon",onClick:h,title:d("routine.delete","Delete"),"aria-label":d("routine.deleteName","Delete {{name}}",{name:e.name}),children:t.jsx(as,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Vr,{size:12}),t.jsx("span",{className:"routine-policy-badge",children:d("routine.stepCount","{{count}} step",{count:e.steps.length,defaultValue_one:"{{count}} step",defaultValue_other:"{{count}} steps"})})]}):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"&&b&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ha,{size:12}),t.jsx("code",{className:"routine-cron",children:b})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:dU[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:uU[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:au(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:au(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(mU,{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:()=>m(y=>!y),"aria-expanded":c,children:[c?t.jsx(ra,{size:12}):t.jsx(Ln,{size:12}),t.jsx("span",{children:d("routine.runHistory","Run History ({{count}})",{count:e.runHistory.length})})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((y,v)=>t.jsx(hU,{result:y,index:v},`${y.startedAt}-${v}`)),e.runHistory.length>10&&t.jsx("div",{className:"schedule-history-more",children:d("routine.andMore","…and {{count}} more",{count:e.runHistory.length-10})})]})]})]})}function fU({type:e,size:n=12}){const{t:s}=st("app");return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:s("stepType.commandStepTitle","Command step"),children:[t.jsx(ua,{size:n}),t.jsx("span",{children:s("stepType.command","Command")})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:s("stepType.createTaskStepTitle","Create Task step"),children:[t.jsx(s1,{size:n}),t.jsx("span",{children:s("stepType.createTask","Create Task")})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:s("stepType.aiPromptStepTitle","AI Prompt step"),children:[t.jsx($s,{size:n}),t.jsx("span",{children:s("stepType.aiPrompt","AI Prompt")})]})}function sh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function gU(e){return e==="command"?{id:sh(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:sh(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:sh(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function bU({step:e,onSave:n,onCancel:s}){const{t:i}=st("app"),[r,o]=a.useState(e.name),[l,d]=a.useState(e.type),[c,m]=a.useState(e.command??""),[p,h]=a.useState(e.prompt??""),[u,f]=a.useState(e.modelProvider??""),[b,y]=a.useState(e.modelId??""),[v,x]=a.useState(e.taskTitle??""),[k,w]=a.useState(e.taskDescription??""),[g,j]=a.useState(e.taskColumn??"triage"),[S,C]=a.useState(e.timeoutMs),[E,F]=a.useState(e.continueOnFailure??!1),[M,D]=a.useState({}),[_,V]=a.useState([]),[N,$]=a.useState(!1),[R,L]=a.useState(null);a.useEffect(()=>{let B=!1;return $(!0),L(null),fa().then(P=>{B||V(P.models)}).catch(P=>{B||L(P instanceof Error?P.message:"Failed to load models")}).finally(()=>{B||$(!1)}),()=>{B=!0}},[]);const O=a.useCallback(()=>{const B={};return r.trim()||(B.name=i("schedule.stepNameRequired","Step name is required")),l==="command"&&!c.trim()&&(B.command=i("schedule.commandRequired","Command is required")),l==="ai-prompt"&&!p.trim()&&(B.prompt=i("schedule.promptRequired","Prompt is required")),l==="create-task"&&!k.trim()&&(B.taskDescription=i("schedule.taskDescriptionRequired","Task description is required")),(l==="ai-prompt"||l==="create-task")&&(u||b)&&(!u||!b)&&(B.modelProvider=i("schedule.modelProviderRequired","Both model provider and model ID must be set together")),S!==void 0&&S<1e3&&(B.timeoutMs=i("schedule.timeoutMinimum","Timeout must be at least 1 second (1000ms)")),D(B),Object.keys(B).length===0},[r,l,c,p,k,u,b,S,i]),J=u&&b?`${u}/${b}`:"",A=a.useCallback(B=>{if(!B)f(""),y("");else{const P=B.indexOf("/");P!==-1&&(f(B.slice(0,P)),y(B.slice(P+1)))}},[]),de=a.useCallback(()=>{if(!O())return;const B={...e,name:r.trim(),type:l,command:l==="command"?c.trim():void 0,prompt:l==="ai-prompt"?p.trim():void 0,taskTitle:l==="create-task"&&v.trim()?v.trim():void 0,taskDescription:l==="create-task"&&k.trim()?k.trim():void 0,taskColumn:l==="create-task"?g:void 0,modelProvider:(l==="ai-prompt"||l==="create-task")&&u.trim()?u.trim():void 0,modelId:(l==="ai-prompt"||l==="create-task")&&b.trim()?b.trim():void 0,timeoutMs:S||void 0,continueOnFailure:E};l!=="ai-prompt"&&delete B.prompt,l!=="create-task"&&(delete B.taskTitle,delete B.taskDescription,delete B.taskColumn),n(B)},[O,n,e,r,l,c,p,v,k,g,u,b,S,E]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:i("schedule.stepName","Step Name")}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:i("schedule.stepNamePlaceholder","e.g. Run tests"),value:r,onChange:B=>o(B.target.value),"aria-invalid":!!M.name}),M.name&&t.jsx("small",{className:"field-error",children:M.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:i("schedule.stepType","Step Type")}),t.jsxs("select",{id:`step-type-${e.id}`,value:l,onChange:B=>d(B.target.value),children:[t.jsx("option",{value:"command",children:i("schedule.commandType","Command")}),t.jsx("option",{value:"ai-prompt",children:i("schedule.aiPromptType","AI Prompt")}),t.jsx("option",{value:"create-task",children:i("schedule.createTaskType","Create Task")})]})]}),l==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:i("schedule.command","Command")}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:i("schedule.commandPlaceholder","e.g. npm test"),value:c,onChange:B=>m(B.target.value),rows:2,"aria-invalid":!!M.command}),M.command&&t.jsx("small",{className:"field-error",children:M.command})]}),l==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:i("schedule.prompt","Prompt")}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:i("schedule.promptPlaceholder","e.g. Summarize the test results and highlight any failures"),value:p,onChange:B=>h(B.target.value),rows:3,"aria-invalid":!!M.prompt}),M.prompt&&t.jsx("small",{className:"field-error",children:M.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:i("schedule.modelOptional","Model (optional)")}),t.jsx(wi,{id:`step-model-${e.id}`,label:i("schedule.model","Model"),models:_,value:J,onChange:A,placeholder:i("schedule.useDefault","Use default"),disabled:N}),R&&t.jsx("small",{className:"field-error",children:R}),t.jsx("small",{children:i("schedule.modelHelp","AI model for this step. Uses default if not selected.")})]})]}),l==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:i("schedule.taskTitleOptional","Task Title (optional)")}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:i("schedule.taskTitlePlaceholder","e.g. Review weekly dependencies"),value:v,onChange:B=>x(B.target.value)}),t.jsx("small",{children:i("schedule.taskTitleHelp","Leave blank to auto-summarize from description")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:i("schedule.taskDescription","Task Description *")}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:i("schedule.taskDescriptionPlaceholder","e.g. Check all npm dependencies for security vulnerabilities and update outdated packages"),value:k,onChange:B=>w(B.target.value),rows:4,"aria-invalid":!!M.taskDescription}),M.taskDescription&&t.jsx("small",{className:"field-error",children:M.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:i("schedule.targetColumn","Target Column")}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:g,onChange:B=>j(B.target.value),children:[t.jsx("option",{value:"triage",children:i("schedule.triageColumn","Triage")}),t.jsx("option",{value:"todo",children:i("schedule.todoColumn","To Do")})]}),t.jsx("small",{children:i("schedule.targetColumnHelp","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:i("schedule.executorModelOptional","Executor Model (optional)")}),t.jsx(wi,{id:`step-task-model-${e.id}`,label:i("schedule.model","Model"),models:_,value:J,onChange:A,placeholder:i("schedule.useDefault","Use default"),disabled:N}),R&&t.jsx("small",{className:"field-error",children:R}),M.modelProvider&&t.jsx("small",{className:"field-error",children:M.modelProvider}),t.jsx("small",{children:i("schedule.executorModelHelp","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:i("schedule.timeoutOptional","Timeout (ms, optional)")}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:i("schedule.timeoutPlaceholder","Override schedule timeout"),value:S??"",onChange:B=>C(B.target.value?Number(B.target.value):void 0),"aria-invalid":!!M.timeoutMs}),M.timeoutMs&&t.jsx("small",{className:"field-error",children:M.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:E,onChange:B=>F(B.target.checked)}),i("schedule.continueOnFailure","Continue on failure")]}),t.jsx("small",{children:i("schedule.continueOnFailureHelp","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:i("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:de,children:i("schedule.saveStep","Save Step")})]})]})}function vU({steps:e,onChange:n,onEditingChange:s}){const{t:i}=st("app"),[r,o]=a.useState(null);a.useEffect(()=>{s?.(r!==null)},[r,s]);const l=a.useCallback(p=>{const h=gU(p);n([...e,h]),o(h.id)},[e,n]),d=a.useCallback(p=>{n(e.filter(h=>h.id!==p)),r===p&&o(null)},[e,n,r]),c=a.useCallback((p,h)=>{const u=e.findIndex(y=>y.id===p);if(u<0)return;const f=h==="up"?u-1:u+1;if(f<0||f>=e.length)return;const b=[...e];[b[u],b[f]]=[b[f],b[u]],n(b)},[e,n]),m=a.useCallback(p=>{n(e.map(h=>h.id===p.id?p:h)),o(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:[i("schedule.steps","Steps")," (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:i("schedule.noStepsEmpty","No steps added yet. Add a command or AI prompt step to get started.")})}),t.jsx("div",{className:"steps-list",children:e.map((p,h)=>t.jsx("div",{className:"step-card",children:r===p.id?t.jsx(bU,{step:p,onSave:m,onCancel:()=>o(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(pu,{size:14})}),t.jsx("span",{className:"step-card-index",children:h+1}),t.jsx(fU,{type:p.type}),t.jsx("span",{className:"step-card-name",children:p.name}),p.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:i("schedule.continuesOnFailure","Continues on failure"),children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(p.id,"up"),disabled:h===0,title:i("schedule.moveUp","Move up"),"aria-label":i("schedule.moveStepUp","Move {{name}} up",{name:p.name}),children:t.jsx(ra,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(p.id,"down"),disabled:h===e.length-1,title:i("schedule.moveDown","Move down"),"aria-label":i("schedule.moveStepDown","Move {{name}} down",{name:p.name}),children:t.jsx(Ln,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>o(p.id),title:i("actions.edit","Edit"),"aria-label":i("schedule.editStep","Edit {{name}}",{name:p.name}),children:t.jsx(Si,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>d(p.id),title:i("actions.delete","Delete"),"aria-label":i("schedule.deleteStep","Delete {{name}}",{name:p.name}),children:t.jsx(as,{})})]})]})},p.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("command"),children:[t.jsx(ys,{size:14}),i("schedule.addCommandStep","Add Command Step")]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("ai-prompt"),children:[t.jsx(ys,{size:14}),i("schedule.addAiPromptStep","Add AI Prompt Step")]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>l("create-task"),children:[t.jsx(ys,{size:14}),i("schedule.addCreateTaskStep","Add Create Task Step")]})]})]})}const $N={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"};function xU(e){const n=e.trim();for(const[s,i]of Object.entries($N))if(i===n)return s;return"custom"}function yU(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function kU(e,n,s,i,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:i||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function wU(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:""}}}function cy(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function dy({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const{t:l}=st("app"),d=!!e,c={hourly:l("schedule.cronPresetHourly","Every hour"),daily:l("schedule.cronPresetDaily","Every day (midnight)"),weekly:l("schedule.cronPresetWeekly","Every week (Monday)"),monthly:l("schedule.cronPresetMonthly","Every month (1st)"),custom:l("schedule.cronPresetCustom","Custom cron expression")},m=[{value:"parallel",label:l("schedule.executionPolicyParallel","Allow concurrent runs")},{value:"queue",label:l("schedule.executionPolicyQueue","Queue after current (one at a time)")},{value:"reject",label:l("schedule.executionPolicyReject","Reject new runs while running")}],p=[{value:"skip",label:l("schedule.catchUpPolicySkip","Skip missed runs")},{value:"run_one",label:l("schedule.catchUpPolicyRunOne","Run the most recent missed run")},{value:"run",label:l("schedule.catchUpPolicyRunAll","Run all missed runs")}],h=e?wU(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,f]=a.useState(e?.name??""),[b,y]=a.useState(e?.description??""),[v,x]=a.useState(h.triggerType),[k,w]=a.useState(h.cronExpression),[g,j]=a.useState(()=>h.triggerType!=="cron"?"custom":xU(h.cronExpression)),[S,C]=a.useState(h.webhookPath),[E,F]=a.useState(h.webhookSecret),[M,D]=a.useState(h.endpoint),[_,V]=a.useState(e?.executionPolicy??"queue"),[N,$]=a.useState(e?.catchUpPolicy??"run_one"),[R,L]=a.useState(e?.enabled??!0),O=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,J=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[A,de]=a.useState(e?.steps&&e.steps.length>0&&!O&&!J?"advanced":"simple"),[B,P]=a.useState(()=>O?"ai-prompt":J?"create-task":"command"),[Z,T]=a.useState(e?.command??""),[ie,le]=a.useState(e?.steps??[]),[be,Le]=a.useState(!1),[xe,q]=a.useState(e?.timeoutMs??3e5),[ce,De]=a.useState(O?e.steps?.[0]?.prompt??"":""),[He,qe]=a.useState(J?e.steps?.[0]?.taskTitle??"":""),[pe,te]=a.useState(J?e.steps?.[0]?.taskDescription??"":""),[me,se]=a.useState(J?e.steps?.[0]?.taskColumn??"triage":"triage"),[z,Y]=a.useState(O||J?e.steps?.[0]?.modelProvider??"":""),[he,X]=a.useState(O||J?e.steps?.[0]?.modelId??"":""),[ye,ot]=a.useState([]),[ue,je]=a.useState(!1),[$e,Ce]=a.useState(null),[We,ke]=a.useState(i??"global"),[Ee,Ze]=a.useState({}),[Ke,dt]=a.useState(!1),Fe=a.useRef(!0);a.useEffect(()=>()=>{Fe.current=!1},[]),a.useEffect(()=>{i&&ke(i)},[i]),a.useEffect(()=>{let _e=!1;return je(!0),Ce(null),fa().then(fe=>{_e||ot(fe.models)}).catch(fe=>{_e||Ce(fe instanceof Error?fe.message:l("schedule.errorLoadModels","Failed to load models"))}).finally(()=>{_e||je(!1)}),()=>{_e=!0}},[]);const nt=z&&he?`${z}/${he}`:"",Nt=a.useCallback(_e=>{if(!_e){Y(""),X("");return}const fe=_e.indexOf("/");fe!==-1&&(Y(_e.slice(0,fe)),X(_e.slice(fe+1)))},[]),Ft=a.useCallback(()=>{const _e={};if(u.trim()||(_e.name=l("schedule.errorNameRequired","Name is required")),We==="project"&&!r&&(_e.scope=l("schedule.errorScopeNoProject","Project-specific entries require an active project.")),v==="cron"&&g==="custom"&&(k.trim()?yU(k)||(_e.cronExpression=l("schedule.errorCronInvalid","Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')")):_e.cronExpression=l("schedule.errorCronRequired","Cron expression is required")),v==="webhook"&&!S.trim()&&(_e.webhookPath=l("schedule.errorWebhookPathRequired","Webhook path is required")),v==="api"&&!M.trim()&&(_e.endpoint=l("schedule.errorApiEndpointRequired","API endpoint is required")),A==="simple")B==="command"&&!Z.trim()&&(_e.command=l("schedule.errorCommandRequired","Command is required")),B==="ai-prompt"&&!ce.trim()&&(_e.prompt=l("schedule.errorPromptRequired","Prompt is required")),B==="create-task"&&!pe.trim()&&(_e.taskDescription=l("schedule.errorTaskDescriptionRequired","Task description is required")),(z.trim()&&!he.trim()||!z.trim()&&he.trim())&&(_e.model=l("schedule.errorModelIncomplete","Both model provider and model ID must be set, or both must be empty"));else{ie.length===0&&(_e.steps=l("schedule.errorStepsRequired","At least one step is required")),be&&(_e.stepsEditing=l("schedule.errorStepsEditing","Please save or cancel all step edits before saving the routine"));const fe=[];ie.forEach((Xe,kt)=>{Xe.name?.trim()||fe.push(l("schedule.errorStepNameRequired","Step {{n}}: Name is required",{n:kt+1})),Xe.type==="command"&&!Xe.command?.trim()&&fe.push(l("schedule.errorStepCommandRequired","Step {{n}}: Command is required",{n:kt+1})),Xe.type==="ai-prompt"&&!Xe.prompt?.trim()&&fe.push(l("schedule.errorStepPromptRequired","Step {{n}}: Prompt is required",{n:kt+1})),Xe.type==="create-task"&&!Xe.taskDescription?.trim()&&fe.push(l("schedule.errorStepTaskDescRequired","Step {{n}}: Task description is required",{n:kt+1}))}),fe.length>0&&(_e.steps=fe.join("; "))}return xe<1e3&&(_e.timeoutMs=l("schedule.errorTimeoutMin","Timeout must be at least 1 second (1000ms)")),Ze(_e),Object.keys(_e).length===0},[u,v,k,g,S,M,We,r,A,B,Z,ce,pe,z,he,ie,be,xe]),ze=a.useCallback(async _e=>{if(_e.preventDefault(),!!Ft()){dt(!0);try{let fe=e?.scope??We??(r?"project":"global");fe==="project"&&!r&&(fe="global");const Xe=kU(v,k,S,E,M);let kt,Rt;A==="simple"?B==="command"?kt=Z.trim()||void 0:B==="ai-prompt"?Rt=[{id:cy(),type:"ai-prompt",name:u.trim(),prompt:ce.trim(),modelProvider:z.trim()||void 0,modelId:he.trim()||void 0}]:Rt=[{id:cy(),type:"create-task",name:u.trim(),taskTitle:He.trim()||void 0,taskDescription:pe.trim(),taskColumn:me,modelProvider:z.trim()||void 0,modelId:he.trim()||void 0}]:Rt=ie;const Vt={name:u.trim(),agentId:e?.agentId??"",description:b.trim()||void 0,trigger:Xe,command:kt,steps:Rt,timeoutMs:xe,executionPolicy:_,catchUpPolicy:N,enabled:R,scope:fe};await n(Vt)}finally{Fe.current&&dt(!1)}}},[Ft,n,u,b,v,k,S,E,M,A,B,Z,ce,z,he,He,pe,me,ie,xe,_,N,R,We,r,e?.scope,e?.agentId]),it="routine-name-error",Mt="routine-cron-error",Ht="routine-webhook-error",Me="routine-endpoint-error",Ae="routine-command-error",ee="routine-prompt-error",Ie="routine-task-description-error",Pe="routine-model-error",oe="routine-timeout-error",re=a.useCallback(_e=>{j(_e),_e!=="custom"&&w($N[_e])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ze,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:d?l("schedule.editRoutineHeading","Edit Routine"):l("schedule.newRoutineHeading","New Routine")}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:l("schedule.nameLabel","Name")}),t.jsx("input",{id:"routine-name",type:"text",placeholder:l("schedule.namePlaceholder","e.g. Daily standup reminder"),value:u,onChange:_e=>f(_e.target.value),"aria-invalid":!!Ee.name,"aria-describedby":Ee.name?it:void 0}),Ee.name&&t.jsx("small",{id:it,className:"field-error",children:Ee.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:l("schedule.descriptionLabel","Description (optional)")}),t.jsx("textarea",{id:"routine-description",placeholder:l("schedule.descriptionPlaceholder","What does this routine do?"),value:b,onChange:_e=>y(_e.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("schedule.scopeLabel","Scope")}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":l("schedule.scopeAriaLabel","Routine scope"),children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${We==="global"?" active":""}`,onClick:()=>{ke("global"),o?.("global")},role:"radio","aria-checked":We==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?l("schedule.scopeLockedTitle","Scope is locked to {{scope}} for existing routines",{scope:e.scope}):l("schedule.globalScopeTitle","Global scope"),children:[t.jsx(Np,{size:12}),l("schedule.globalScope","Global")]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${We==="project"?" active":""}`,onClick:()=>{ke("project"),o?.("project")},role:"radio","aria-checked":We==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?l("schedule.scopeLockedTitle","Scope is locked to {{scope}} for existing routines",{scope:e.scope}):r?l("schedule.projectScopeTitle","Project scope"):l("schedule.selectProjectTitle","Select a project to enable project scope"),children:[t.jsx(Zs,{size:12}),l("schedule.projectScope","Project")]})]}),t.jsx("small",{children:!r&&!e?.scope?l("schedule.scopeHintNoProject","No active project. Routines will be created at global scope."):We==="project"&&r?l("schedule.scopeHintProject","This routine will be scoped to the current project."):l("schedule.scopeHintGlobal","This routine will be created at global scope.")}),Ee.scope&&t.jsx("small",{className:"field-error",children:Ee.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("schedule.triggerTypeLabel","Trigger Type")}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":l("schedule.triggerTypeAriaLabel","Trigger type"),children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${v==="cron"?" active":""}`,onClick:()=>x("cron"),role:"radio","aria-checked":v==="cron",children:[t.jsx(xk,{size:14}),l("schedule.triggerCron","Cron")]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${v==="webhook"?" active":""}`,onClick:()=>x("webhook"),role:"radio","aria-checked":v==="webhook",children:[t.jsx(Rk,{size:14}),l("schedule.triggerWebhook","Webhook")]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${v==="api"?" active":""}`,onClick:()=>x("api"),role:"radio","aria-checked":v==="api",children:[t.jsx(kk,{size:14}),l("schedule.triggerApi","API")]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${v==="manual"?" active":""}`,onClick:()=>x("manual"),role:"radio","aria-checked":v==="manual",children:[t.jsx(Ws,{size:14}),l("schedule.triggerManual","Manual")]})]})]}),v==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:l("schedule.frequencyLabel","Frequency")}),t.jsx("select",{id:"routine-frequency",value:g,onChange:_e=>re(_e.target.value),children:Object.entries(c).map(([_e,fe])=>t.jsx("option",{value:_e,children:fe},_e))}),t.jsx("label",{htmlFor:"routine-cron",children:l("schedule.cronExpressionLabel","Cron Expression")}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:k,onChange:_e=>w(_e.target.value),disabled:g!=="custom","aria-invalid":!!Ee.cronExpression,"aria-describedby":Ee.cronExpression?Mt:void 0}),Ee.cronExpression?t.jsx("small",{id:Mt,className:"field-error",children:Ee.cronExpression}):t.jsx("small",{children:g==="custom"?t.jsxs(t.Fragment,{children:[l("schedule.cronCustomHint","min hour day month weekday")," — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):l("schedule.cronAutoFilledHint","Auto-filled from preset: {{expression}}",{expression:k})})]}),v==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:l("schedule.webhookPathLabel","Webhook Path")}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:l("schedule.webhookPathPlaceholder","/trigger/my-routine"),value:S,onChange:_e=>C(_e.target.value),"aria-invalid":!!Ee.webhookPath,"aria-describedby":Ee.webhookPath?Ht:void 0}),Ee.webhookPath?t.jsx("small",{id:Ht,className:"field-error",children:Ee.webhookPath}):t.jsx("small",{children:l("schedule.webhookPathHint","URL path for the webhook endpoint")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:l("schedule.webhookSecretLabel","Webhook Secret (optional)")}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:l("schedule.webhookSecretPlaceholder","Optional — leave empty for unauthenticated webhooks"),value:E,onChange:_e=>F(_e.target.value)}),t.jsx("small",{children:l("schedule.webhookSecretHint","HMAC secret for signature verification. Leave empty for unauthenticated webhooks.")})]})]}),v==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:l("schedule.apiEndpointLabel","API Endpoint")}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:l("schedule.apiEndpointPlaceholder","/api/routine/my-routine"),value:M,onChange:_e=>D(_e.target.value),"aria-invalid":!!Ee.endpoint,"aria-describedby":Ee.endpoint?Me:void 0}),Ee.endpoint?t.jsx("small",{id:Me,className:"field-error",children:Ee.endpoint}):t.jsx("small",{children:l("schedule.apiEndpointHint","API endpoint path that triggers this routine")})]}),v==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:l("schedule.manualTriggerInfo","This routine will be triggered manually via the dashboard or API.")})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("schedule.actionModeLabel","Action Mode")}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":l("schedule.actionModeAriaLabel","Action mode"),children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${A==="simple"?" active":""}`,onClick:()=>de("simple"),role:"radio","aria-checked":A==="simple",children:l("schedule.actionModeSimple","Simple")}),t.jsx("button",{type:"button",className:`schedule-mode-btn${A==="advanced"?" active":""}`,onClick:()=>de("advanced"),role:"radio","aria-checked":A==="advanced",children:l("schedule.actionModeAdvanced","Multi-Step")})]}),t.jsx("small",{children:A==="simple"?l("schedule.actionModeSimpleHint","Run one command, prompt, or task creation action"):l("schedule.actionModeAdvancedHint","Run multiple actions sequentially")})]}),A==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("schedule.actionTypeLabel","Action Type")}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":l("schedule.actionTypeAriaLabel","Action type"),children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${B==="command"?" active":""}`,onClick:()=>P("command"),role:"radio","aria-checked":B==="command",children:l("schedule.actionTypeCommand","Command")}),t.jsx("button",{type:"button",className:`schedule-mode-btn${B==="ai-prompt"?" active":""}`,onClick:()=>P("ai-prompt"),role:"radio","aria-checked":B==="ai-prompt",children:l("schedule.actionTypeAiPrompt","AI Prompt")}),t.jsx("button",{type:"button",className:`schedule-mode-btn${B==="create-task"?" active":""}`,onClick:()=>P("create-task"),role:"radio","aria-checked":B==="create-task",children:l("schedule.actionTypeCreateTask","Create Task")})]})]}),B==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:l("schedule.commandLabel","Command")}),t.jsx("input",{id:"routine-command",type:"text",placeholder:l("schedule.commandPlaceholder","e.g. npx runfusion.ai backup --create"),value:Z,onChange:_e=>T(_e.target.value),"aria-invalid":!!Ee.command,"aria-describedby":Ee.command?Ae:void 0}),Ee.command?t.jsx("small",{id:Ae,className:"field-error",children:Ee.command}):t.jsx("small",{children:l("schedule.commandHint","Shell command to execute.")})]}):B==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:l("schedule.promptLabel","Prompt")}),t.jsx("textarea",{id:"routine-prompt",placeholder:l("schedule.promptPlaceholder","e.g. Summarize recent activity and create action items"),value:ce,onChange:_e=>De(_e.target.value),rows:3,"aria-invalid":!!Ee.prompt,"aria-describedby":Ee.prompt?ee:void 0}),Ee.prompt?t.jsx("small",{id:ee,className:"field-error",children:Ee.prompt}):t.jsx("small",{children:l("schedule.promptHint","AI prompt to execute.")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:l("schedule.modelLabel","Model (optional)")}),t.jsx(wi,{id:"routine-model",label:l("schedule.modelDropdownLabel","Model"),models:ye,value:nt,onChange:Nt,placeholder:l("schedule.modelPlaceholder","Use default"),disabled:ue}),$e&&t.jsx("small",{className:"field-error",children:$e}),Ee.model&&t.jsx("small",{id:Pe,className:"field-error",children:Ee.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:l("schedule.taskTitleLabel","Task Title (optional)")}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:l("schedule.taskTitlePlaceholder","e.g. Review weekly dependencies"),value:He,onChange:_e=>qe(_e.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:l("schedule.taskDescriptionLabel","Task Description")}),t.jsx("textarea",{id:"routine-task-description",placeholder:l("schedule.taskDescriptionPlaceholder","e.g. Check npm dependencies for security vulnerabilities"),value:pe,onChange:_e=>te(_e.target.value),rows:4,"aria-invalid":!!Ee.taskDescription,"aria-describedby":Ee.taskDescription?Ie:void 0}),Ee.taskDescription?t.jsx("small",{id:Ie,className:"field-error",children:Ee.taskDescription}):t.jsx("small",{children:l("schedule.taskDescriptionHint","Describes the task that will be created.")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:l("schedule.taskColumnLabel","Target Column")}),t.jsxs("select",{id:"routine-task-column",value:me,onChange:_e=>se(_e.target.value),children:[t.jsx("option",{value:"triage",children:l("schedule.taskColumnTriage","Triage")}),t.jsx("option",{value:"todo",children:l("schedule.taskColumnTodo","To Do")})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:l("schedule.executorModelLabel","Executor Model (optional)")}),t.jsx(wi,{id:"routine-task-model",label:l("schedule.executorModelDropdownLabel","Executor Model"),models:ye,value:nt,onChange:Nt,placeholder:l("schedule.modelPlaceholder","Use default"),disabled:ue}),$e&&t.jsx("small",{className:"field-error",children:$e}),Ee.model&&t.jsx("small",{id:Pe,className:"field-error",children:Ee.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(vU,{steps:ie,onChange:le,onEditingChange:Le}),Ee.steps&&t.jsx("small",{className:"field-error",children:Ee.steps}),Ee.stepsEditing&&t.jsx("small",{className:"field-error",children:Ee.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:l("schedule.timeoutLabel","Timeout (ms)")}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:xe,onChange:_e=>q(Number(_e.target.value)),"aria-invalid":!!Ee.timeoutMs,"aria-describedby":Ee.timeoutMs?oe:void 0}),Ee.timeoutMs?t.jsx("small",{id:oe,className:"field-error",children:Ee.timeoutMs}):t.jsx("small",{children:l("schedule.timeoutHint","Maximum execution time in milliseconds.")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:l("schedule.executionPolicyLabel","Execution Policy")}),t.jsx("select",{id:"routine-execution-policy",value:_,onChange:_e=>V(_e.target.value),children:m.map(_e=>t.jsx("option",{value:_e.value,children:_e.label},_e.value))}),t.jsx("small",{children:l("schedule.executionPolicyHint","How to handle concurrent executions of this routine")})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:l("schedule.catchUpPolicyLabel","Catch-up Policy")}),t.jsx("select",{id:"routine-catchup-policy",value:N,onChange:_e=>$(_e.target.value),children:p.map(_e=>t.jsx("option",{value:_e.value,children:_e.label},_e.value))}),t.jsx("small",{children:l("schedule.catchUpPolicyHint","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:R,onChange:_e=>L(_e.target.checked)}),l("schedule.enabledLabel","Enabled")]}),t.jsx("small",{children:l("schedule.enabledHint","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:Ke,children:l("common.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ke,children:Ke?l("common.saving","Saving…"):d?l("schedule.saveChanges","Save Changes"):l("schedule.createRoutine","Create Routine")})]})]})}const jU=3e4;function NU({onClose:e,addToast:n,projectId:s}){const{t:i}=st("app"),[r,o]=a.useState(()=>s?"project":"global"),[l,d]=a.useState([]),[c,m]=a.useState("list"),[p,h]=a.useState(),[u,f]=a.useState(null),[b,y]=a.useState({}),v=a.useRef(null);La(v,!0,"fusion:automation-modal-size");const x=a.useMemo(()=>({scope:r,projectId:r==="project"?s:void 0}),[r,s]),k=a.useCallback(async()=>{try{const $=await CA(x);d($),y(R=>{const L={...R};for(const O of $){const J=L[O.id];if(!J||!O.lastRunResult)continue;const A=O.lastRunResult;A.success===J.success&&(A.output||"")===J.output&&(A.error||"")===(J.error||"")&&delete L[O.id]}return L})}catch($){n(Re($)||i("schedule.loadRoutinesError","Failed to load routines"),"error")}},[n,x]);a.useEffect(()=>{k()},[k]),a.useEffect(()=>{const $=setInterval(()=>{k()},jU);return()=>clearInterval($)},[k]),a.useEffect(()=>{const $=R=>{R.key==="Escape"&&(c!=="list"?(m("list"),h(void 0)):e())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,c]);const w=yr(e),g=a.useCallback(async $=>{try{await _A($,x),n(i("schedule.routineCreated","Routine created"),"success"),m("list"),await k()}catch(R){n(Re(R)||i("schedule.createError","Failed to create routine"),"error")}},[n,k,x,i]),j=a.useCallback($=>{h($),m("edit")},[]),S=a.useCallback(async $=>{if(p)try{await Lg(p.id,$,x),n(i("schedule.routineUpdated","Routine updated"),"success"),m("list"),h(void 0),await k()}catch(R){n(Re(R)||i("schedule.updateError","Failed to update routine"),"error")}},[p,n,k,x,i]),C=a.useCallback(async $=>{try{await EA($.id,x),n(i("schedule.routineDeleted",'Deleted "{{name}}"',{name:$.name}),"success"),await k()}catch(R){n(Re(R)||i("schedule.deleteError","Failed to delete routine"),"error")}},[n,k,x,i]),E=a.useCallback(async $=>{f($.id);try{const{result:R}=await MA($.id,x);y(L=>({...L,[$.id]:{output:R.output||"",error:R.error,success:R.success}})),R.success?n(i("schedule.routineSuccess",'"{{name}}" completed successfully',{name:$.name}),"success"):n(i("schedule.routineFailed",'"{{name}}" failed: {{error}}',{name:$.name,error:R.error||i("schedule.unknownError","Unknown error")}),"error"),await k()}catch(R){n(Re(R)||i("schedule.runError","Failed to run routine"),"error")}finally{f(null)}},[n,k,x,i]),F=a.useCallback(async $=>{try{await Lg($.id,{enabled:!$.enabled},x),n(i(`schedule.routine${$.enabled?"Disabled":"Enabled"}`,`"{{name}}" ${$.enabled?"disabled":"enabled"}`,{name:$.name}),"success"),await k()}catch(R){n(Re(R)||i("schedule.toggleError","Failed to toggle routine"),"error")}},[n,k,x,i]),M=a.useCallback(()=>{m("list"),h(void 0)},[]);a.useEffect(()=>{c!=="list"&&y({})},[c]);const D=a.useCallback($=>{o($),m("list"),h(void 0),y({})},[]),_=()=>c==="create"?t.jsx(dy,{onSubmit:g,onCancel:M,scope:r,projectId:s}):c==="edit"&&p?t.jsx(dy,{routine:p,onSubmit:S,onCancel:M,scope:r,projectId:s}):l.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Ws,{size:48,strokeWidth:1}),t.jsx("h4",{children:i("schedule.noAutomations","No automations yet")}),t.jsx("p",{children:i("schedule.emptyStateDescription","Create an automation with a schedule, webhook, API, or manual trigger.")}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m("create"),children:[t.jsx(ys,{size:14}),i("schedule.createFirst","Create your first automation")]})]}):t.jsx("div",{className:"routine-list",children:l.map($=>t.jsx(pU,{routine:$,onEdit:j,onDelete:C,onRun:E,onToggle:F,running:u===$.id,lastRunOutput:b[$.id]??null},$.id))}),V=()=>_(),N=c==="list"&&l.length>0;return t.jsx("div",{className:"modal-overlay open",...w,children:t.jsxs("div",{ref:v,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(Ws,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:i("schedule.title","Automations")})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":i("common.close","Close"),children:t.jsx(Fn,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":i("schedule.scopeGroup","Scheduling scope"),children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${r==="global"?" active":""}`,onClick:()=>D("global"),"aria-pressed":r==="global",title:i("schedule.globalScope","Global (user-level) automations"),children:[t.jsx(Np,{size:14}),i("schedule.global","Global")]}),t.jsxs("button",{type:"button",className:`scope-btn${r==="project"?" active":""}`,onClick:()=>D("project"),"aria-pressed":r==="project",title:i("schedule.projectScope","Project-scoped automations"),children:[t.jsx(Zs,{size:14}),i("schedule.project","Project")]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Ws,{size:14}),i("schedule.automationCount","{{count}} automation{{plural}}",{count:l.length,plural:l.length===1?"":"s"})]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:N&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m("create"),"aria-label":i("schedule.createNew","Create new automation"),children:[t.jsx(ys,{size:14}),i("schedule.newAutomation","New Automation")]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:V()})]})})}const SU=3e4,mp=new Map,ih=new Map;function uy(e){return e??"default"}function my(e){const n=mp.get(e);return n?Date.now()>=n.expiresAt?(mp.delete(e),null):n:null}function CU(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),i=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:i}}async function _U(e){const n=ih.get(e);if(n)return n;const s=Yo().then(({providers:i,ghCli:r})=>{const l={...CU(i,r),ghCli:r,expiresAt:Date.now()+SU};return mp.set(e,l),l}).finally(()=>{ih.delete(e)});return ih.set(e,s),s}function zN(e){const n=uy(e),s=my(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,d]=a.useState(s?.ghCli),[c,m]=a.useState(s==null),p=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const u=uy(e),f=my(u);if(f)return r(f.hasAiProvider),l(f.hasGithub),d(f.ghCli),m(!1),p.current=!0,()=>{h=!0};p.current=!1;async function b(){!p.current&&m(!0);try{const v=await _U(u);if(h)return;r(v.hasAiProvider),l(v.hasGithub),d(v.ghCli)}catch{}finally{h||(p.current=!0,m(!1))}}return b(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:c,hasWarnings:!i||!o}),[i,o,c])}function BN({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:i}){const{t:r}=st("app");if(e&&n)return null;const o=i?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":r("setup.dismissWarning","Dismiss setup warning"),onClick:i,children:t.jsx(Fn,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:r("setup.compactWarning","⚠ Setup incomplete — AI and/or GitHub features will be limited.")}),o]});const l=[];return e||l.push({key:"ai",title:r("setup.noAiProvider","No AI provider connected"),description:r("setup.noAiProviderDesc","AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup.")}),n||l.push({key:"github",title:r("setup.noGithub","GitHub not connected"),description:r("setup.noGithubDesc","You won't be able to import issues from GitHub, but you can still create tasks manually.")}),t.jsxs("div",{className:`setup-warning-banner${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[o,l.map(d=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:d.title}),t.jsx("p",{className:"setup-warning-banner__description",children:d.description})]},d.key))]})}function EU({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o}){const{t:l}=st("app"),{confirm:d}=Yi(),c=Ji();ga(e);const{keyboardOverlap:m,viewportHeight:p,viewportOffsetTop:h,keyboardOpen:u}=Xa({enabled:c==="mobile"}),f=u?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${h}px`,...p!==null?{"--vv-height":`${p}px`}:{}}:{},[b,y]=a.useState(""),[v,x]=a.useState([]),[k,w]=a.useState("project-default"),[g,j]=a.useState(""),[S,C]=a.useState(""),[E,F]=a.useState([]),[M,D]=a.useState(!1),[_,V]=a.useState(""),[N,$]=a.useState(""),[R,L]=a.useState(""),[O,J]=a.useState(""),[A,de]=a.useState(""),[B,P]=a.useState("default"),[Z,T]=a.useState(!1),[ie,le]=a.useState(void 0),[be,Le]=a.useState(void 0),[xe,q]=a.useState(void 0),[ce,De]=a.useState(yi),[He,qe]=a.useState(void 0),[pe,te]=a.useState(!1),[me,se]=a.useState(""),[z,Y]=a.useState(null),{agents:he,loading:X}=vw(s),[ye,ot]=a.useState(!1),ue=a.useRef(null),[je,$e]=a.useState(!1),[Ce,We]=a.useState(""),ke=a.useRef(null),{hasAiProvider:Ee,hasGithub:Ze,loading:Ke}=zN(s),{nodes:dt}=Nu(),Fe=a.useCallback(()=>{ot(!0)},[]);a.useEffect(()=>{if(!ye)return;const re=_e=>{ue.current&&!ue.current.contains(_e.target)&&ot(!1)};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[ye]),a.useEffect(()=>{if(!je)return;const re=_e=>{ke.current&&!ke.current.contains(_e.target)&&($e(!1),We(""))};return document.addEventListener("mousedown",re),()=>document.removeEventListener("mousedown",re)},[je]);const nt=i.filter(re=>!v.includes(re.id)).sort((re,_e)=>{const fe=_e.createdAt.localeCompare(re.createdAt);if(fe!==0)return fe;const Xe=parseInt(re.id.slice(re.id.lastIndexOf("-")+1),10)||0;return(parseInt(_e.id.slice(_e.id.lastIndexOf("-")+1),10)||0)-Xe}),Nt=Ce?nt.filter(re=>re.id.toLowerCase().includes(Ce.toLowerCase())||re.title&&re.title.toLowerCase().includes(Ce.toLowerCase())||re.description&&re.description.toLowerCase().includes(Ce.toLowerCase())):nt,Ft=(re,_e)=>re.length>_e?re.slice(0,_e)+"…":re,ze=me.trim(),it=ze.length>0&&!xu.test(ze),Mt=k==="existing"||k==="custom-new"||k==="shared-group",Ht=Mt&&!g.trim();a.useEffect(()=>{const re=b.trim()!==""||v.length>0||E.length>0||ie!==void 0||_!==""||N!==""||R!==""||O!==""||z!==null||be!==void 0||xe!==void 0||ce!==yi||He!==void 0||k!=="project-default"||g!==""||S!==""||pe||ze!=="";T(re)},[b,v,E,ie,_,N,R,O,z,be,xe,ce,He,k,g,S,pe,ze]);const Me=a.useCallback(async()=>{Z&&!await d({title:l("newTaskModal.discardChanges","Discard Changes"),message:l("newTaskModal.unsavedChanges","You have unsaved changes. Discard them?"),danger:!0})||(E.forEach(re=>URL.revokeObjectURL(re.previewUrl)),F([]),y(""),x([]),V(""),$(""),L(""),J(""),de(""),P("default"),le(void 0),Y(null),ot(!1),Le(void 0),q(void 0),De(yi),qe(void 0),w("project-default"),j(""),C(""),T(!1),te(!1),se(""),n())},[Z,n,E,d,l]),Ae=a.useCallback(async()=>{const re=b.trim();if(!(!re||M||it||Ht)){D(!0);try{const _e=_.indexOf("/"),fe=N.indexOf("/"),Xe=R.indexOf("/"),kt={title:void 0,description:re,column:"triage",dependencies:v.length?v:void 0,...ie!==void 0?{workflowId:ie}:{},...z?{assignedAgentId:z}:{},modelPresetId:B==="preset"&&A||void 0,modelProvider:_&&_e!==-1?_.slice(0,_e):void 0,modelId:_&&_e!==-1?_.slice(_e+1):void 0,validatorModelProvider:N&&fe!==-1?N.slice(0,fe):void 0,validatorModelId:N&&fe!==-1?N.slice(fe+1):void 0,planningModelProvider:R&&Xe!==-1?R.slice(0,Xe):void 0,planningModelId:R&&Xe!==-1?R.slice(Xe+1):void 0,thinkingLevel:O!==""?O:void 0,reviewLevel:be,...xe!==void 0?{autoMerge:xe}:{},priority:ce,nodeId:He,branchSelection:{mode:k,...Mt&&g.trim()?{branchName:g.trim()}:{},...S.trim()?{baseBranch:S.trim()}:{}},...pe||ze!==""?{githubTracking:{enabled:pe,...ze!==""?{repoOverride:ze}:{}}}:{}},Rt=await r(kt);if(E.length>0){const Vt=[];for(const Pt of E)try{await ku(Rt.id,Pt.file,s)}catch{Vt.push(Pt.file.name)}Vt.length>0&&o(l("newTaskModal.failedToUpload","Failed to upload: {{files}}",{files:Vt.join(", ")}),"error")}E.forEach(Vt=>URL.revokeObjectURL(Vt.previewUrl)),F([]),y(""),x([]),V(""),$(""),L(""),J(""),de(""),P("default"),le(void 0),Y(null),ot(!1),Le(void 0),q(void 0),De(yi),qe(void 0),w("project-default"),j(""),C(""),o(l("newTaskModal.taskCreated","Created {{taskId}}",{taskId:Rt.id}),"success"),n()}catch(_e){o(Re(_e)||l("newTaskModal.failedToCreate","Failed to create task"),"error")}finally{D(!1)}}},[b,v,E,_,N,R,O,M,it,Ht,r,o,n,s,B,A,ie,z,be,xe,ce,He,k,Mt,g,S,pe,ze,l]),ee=a.useCallback(re=>{re.key==="Escape"&&(re.preventDefault(),Me())},[Me]),Pe=(z?he.find(re=>re.id===z):void 0)?.name??z,oe=t.jsxs("div",{className:"new-task-quick-fields",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("newTaskModal.dependencies","Dependencies")}),t.jsxs("div",{className:"dep-trigger-wrap",ref:ke,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>$e(re=>!re),disabled:M,"data-testid":"dep-trigger",children:v.length>0?l("newTaskModal.selectedCount","{{count}} selected",{count:v.length}):l("newTaskModal.addDependencies","Add dependencies")}),je&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:l("newTaskModal.searchTasks","Search tasks…"),autoFocus:!0,value:Ce,onChange:re=>We(re.target.value),onClick:re=>re.stopPropagation()}),Nt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:l("newTaskModal.noAvailableTasks","No available tasks")}):Nt.map(re=>t.jsxs("div",{className:`dep-dropdown-item${v.includes(re.id)?" selected":""}`,onClick:()=>{x(v.includes(re.id)?v.filter(_e=>_e!==re.id):[...v,re.id]),$e(!1),We("")},onMouseDown:_e=>_e.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:re.id}),t.jsx("span",{className:"dep-dropdown-title",children:Ft(re.title||re.description||re.id,30)})]},re.id))]})]}),v.length>0&&t.jsx("div",{className:"selected-deps",children:v.map(re=>t.jsxs("span",{className:"dep-chip",children:[re,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>x(v.filter(_e=>_e!==re)),disabled:M,children:"×"})]},re))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:l("newTaskModal.assignAgent","Assign Agent")}),t.jsxs("div",{className:"agent-trigger-wrap",ref:ue,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ye?ot(!1):Fe()},disabled:M,"data-testid":"new-task-agent-button",children:[t.jsx(Is,{size:12,style:{verticalAlign:"middle"}}),Pe?` ${Pe}`:` ${l("newTaskModal.assignAgentButton","Assign agent")}`]}),ye&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:re=>re.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:l("newTaskModal.selectAgent","Select agent")}),X&&t.jsx("div",{className:"dep-dropdown-empty",children:l("newTaskModal.loadingAgents","Loading agents...")}),!X&&he.map(re=>t.jsxs("div",{className:`dep-dropdown-item${z===re.id?" selected":""}`,onMouseDown:_e=>_e.preventDefault(),onClick:()=>{Y(re.id===z?null:re.id),ot(!1)},"data-testid":`agent-option-${re.id}`,children:[t.jsx(Is,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:re.role}),t.jsx("span",{className:"dep-dropdown-title",children:re.name})]},re.id)),!X&&he.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:l("newTaskModal.noAgentsAvailable","No agents available")}),z&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:re=>re.preventDefault(),onClick:()=>{Y(null),ot(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:l("newTaskModal.clearSelection","Clear selection")})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Me,onKeyDown:ee,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:re=>re.stopPropagation(),style:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:l("newTaskModal.title","New Task")}),t.jsx("button",{className:"modal-close",onClick:Me,disabled:M,"aria-label":l("actions.close","Close"),children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Ke&&t.jsx(BN,{hasAiProvider:Ee,hasGithub:Ze}),t.jsx(iN,{mode:"create",description:b,onDescriptionChange:y,dependencies:v,onDependenciesChange:x,executorModel:_,onExecutorModelChange:V,validatorModel:N,onValidatorModelChange:$,presetMode:B,onPresetModeChange:P,selectedPresetId:A,onSelectedPresetIdChange:de,selectedWorkflowId:ie,onWorkflowIdChange:le,pendingImages:E,onImagesChange:F,tasks:i,projectId:s,disabled:M,addToast:o,isActive:e,onClose:Me,planningModel:R,onPlanningModelChange:L,thinkingLevel:O,onThinkingLevelChange:J,reviewLevel:be,onReviewLevelChange:Le,autoMerge:xe,onAutoMergeChange:q,priority:ce,onPriorityChange:De,branch:g,onBranchChange:j,branchMode:k,onBranchModeChange:w,baseBranch:S,onBaseBranchChange:C,nodeId:He,onNodeIdChange:qe,nodeOptions:dt,githubTrackingEnabled:pe,onGithubTrackingEnabledChange:te,githubRepoOverride:me,onGithubRepoOverrideChange:se,renderBelowPrimary:oe,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),Ht&&t.jsx("div",{className:"form-error new-task-branch-error",children:l("newTaskModal.branchRequired","Branch name is required for this branch strategy.")}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Me,disabled:M,children:l("actions.cancel","Cancel")}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ae,disabled:!b.trim()||M||it||Ht,children:M?l("newTaskModal.creating","Creating..."):l("newTaskModal.createTask","Create Task")})]})]})}):null}function ca(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 hy(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function MU(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function AU(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function TU(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function RU(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 xd(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function PU(e,n){if(!e)return n;const s=new Date(e);return Number.isNaN(s.getTime())?n:s.toLocaleString()}function IU({isOpen:e,onClose:n,projectId:s}){const{t:i}=st("app"),[r,o]=a.useState(null),[l,d]=a.useState(!1),[c,m]=a.useState(null),[p,h]=a.useState(!0),[u,f]=a.useState(90),[b,y]=a.useState(!1),[v,x]=a.useState(!1),[k,w]=a.useState(null),[g,j]=a.useState(null),[S,C]=a.useState(null),E=a.useCallback(async q=>{d(!0);try{const ce=await uT(s);o(ce),m(null),C(Date.now()),q?.preserveKillResult||w(null)}catch(ce){m(ce instanceof Error?ce.message:i("systemStats.errorLoadStats","Failed to load system stats"))}finally{d(!1)}},[s]);a.useEffect(()=>{if(!e)return;E();const q=window.setInterval(()=>{E()},5e3);return()=>{window.clearInterval(q)}},[e,E]),a.useEffect(()=>{if(!e)return;(async()=>{try{const ce=await Ja();h(ce.vitestAutoKillEnabled??!0),f(ce.vitestKillThresholdPct??90),j(null)}catch(ce){j(ce instanceof Error?ce.message:i("systemStats.errorLoadVitestSettings","Failed to load vitest settings"))}})()},[e]),a.useEffect(()=>{if(!e)return;const q=ce=>{ce.key==="Escape"&&n()};return document.addEventListener("keydown",q),()=>document.removeEventListener("keydown",q)},[e,n]);const F=a.useMemo(()=>{if(!r)return[];const q=r.systemStats,ce=xd(MU(q.heapUsed,q.heapLimit)),De=xd(AU(q.rss,q.systemTotalMem));return[{label:i("systemStats.rowRss","RSS"),value:ca(q.rss),detail:hy(q.rss,q.systemTotalMem),className:De},{label:i("systemStats.rowHeapUsed","Heap Used"),value:ca(q.heapUsed),detail:i("systemStats.rowHeapUsedDetail","of {{total}}",{total:ca(q.heapTotal)}),className:ce},{label:i("systemStats.rowHeapLimit","Heap Limit"),value:ca(q.heapLimit),detail:i("systemStats.rowHeapLimitDetail","V8 limit")},{label:i("systemStats.rowExternal","External"),value:ca(q.external)},{label:i("systemStats.rowArrayBuffers","Array Buffers"),value:ca(q.arrayBuffers)}]},[r]),M=a.useCallback(async q=>{h(q);try{await Ms({vitestAutoKillEnabled:q}),j(null)}catch(ce){j(ce instanceof Error?ce.message:i("systemStats.errorSaveVitestSettings","Failed to save vitest settings"))}},[]),D=a.useCallback(async q=>{const ce=Math.min(99,Math.max(50,Number.isFinite(q)?Math.round(q):90));f(ce);try{await Ms({vitestKillThresholdPct:ce}),j(null)}catch(De){j(De instanceof Error?De.message:i("systemStats.errorSaveVitestSettings","Failed to save vitest settings"))}},[]),_=a.useCallback(async()=>{if(!b){if(!v){x(!0);return}y(!0);try{const q=await mT(s);w(q),x(!1),await E({preserveKillResult:!0})}catch(q){m(q instanceof Error?q.message:i("systemStats.errorKillVitest","Failed to kill vitest processes"))}finally{y(!1)}}},[v,b,E,s]);if(!e)return null;const V=r?.systemStats,N=l&&!!r,$=S?i("systemStats.updatedAt","Updated {{time}}",{time:new Date(S).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}):i("systemStats.waitingFirstUpdate","Waiting for first update"),R=r?.taskStats,L=V?V.systemTotalMem-V.systemFreeMem:0,O=V?TU(L,V.systemTotalMem):"normal",J=V?xd(O):"",A=V&&Number.isFinite(V.systemTotalMem)&&V.systemTotalMem>0?Math.max(0,Math.min(100,L/V.systemTotalMem*100)):0,de=V?i("systemStats.systemMemProgressLabel","System memory used: {{percent}}% ({{used}} of {{total}})",{percent:A.toFixed(1),used:ca(L),total:ca(V.systemTotalMem)}):i("systemStats.systemMemUnavailable","System memory usage unavailable"),B=r?.vitestProcessCount,P=RU(V?.cpuPercent??null,V?.cpuCount??0),Z=xd(P),T=V?.cpuPercent??null,ie=T===null?0:Math.max(0,Math.min(100,T)),le=T===null?i("systemStats.cpuSampling","Sampling…"):`${T.toFixed(1)}%`,be=T===null?i("systemStats.cpuProgressUnavailable","App CPU usage unavailable: waiting for another sample"):i("systemStats.cpuProgressLabel","App CPU usage: {{percent}}%",{percent:T.toFixed(1)}),Le=k?k.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",xe=PU(r?.vitestLastAutoKillAt,i("systemStats.notYet","Not yet"));return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:q=>{q.target===q.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(Ko,{}),t.jsx("span",{children:i("systemStats.title","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:i("systemStats.autoRefresh","Auto-refresh · 5s")}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:$})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void E(),title:i("systemStats.refreshTitle","Refresh"),"aria-label":i("systemStats.refreshAriaLabel","Refresh system stats"),children:t.jsx(xs,{size:16,className:N?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":i("systemStats.closeAriaLabel","Close"),children:t.jsx(Fn,{})})]})]}),l&&!r&&t.jsx("div",{className:"system-stats-modal__state",children:i("systemStats.loading","Loading system stats…")}),c&&!r&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),r&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionProcessAriaLabel","Process stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionProcess","Process")}),t.jsx("dl",{className:"system-stats-modal__grid",children:F.map(q=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:q.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${q.className}`.trim(),children:q.value}),q.detail?t.jsx("span",{className:"system-stats-modal__detail",children:q.detail}):null]})]},q.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionCpuAriaLabel","CPU and load stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionCpu","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:i("systemStats.rowAppCpu","App CPU")}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${Z}`.trim(),children:le}),t.jsx("span",{className:"system-stats-modal__detail",children:T===null?i("systemStats.cpuFirstSamplePending","First sample pending"):i("systemStats.cpuProcessUsage","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--${P}`,role:"progressbar","aria-valuenow":Math.round(ie),"aria-valuemin":0,"aria-valuemax":100,"aria-label":be,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${P}`,style:{width:`${ie}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowLoadAvg","Load Avg")}),t.jsx("dd",{children:V?.loadAvg.map(q=>q.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowCores","Cores")}),t.jsx("dd",{children:V?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowPlatform","Platform")}),t.jsx("dd",{children:V?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowNode","Node")}),t.jsx("dd",{children:V?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowPid","PID")}),t.jsx("dd",{children:V?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionSystemMemAriaLabel","System memory stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionSystem","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:i("systemStats.rowMemoryUsed","Memory Used")}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${J}`.trim(),children:V?ca(L):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:V?`${hy(L,V.systemTotalMem)} of ${ca(V.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--${O}`,role:"progressbar","aria-valuenow":Math.round(A),"aria-valuemin":0,"aria-valuemax":100,"aria-label":de,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${O}`,style:{width:`${A}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowMemoryFree","Memory Free")}),t.jsx("dd",{children:V?ca(V.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionTasksAriaLabel","Task stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionTasks","Tasks")}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.rowTotal","Total")}),t.jsx("dd",{children:R?.total??0})]}),Object.entries(R?.byColumn??{}).map(([q,ce])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:q}),t.jsx("dd",{children:ce})]},q))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionAgentsAriaLabel","Agent stats"),children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:i("systemStats.sectionAgents","Agents")}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.agentIdle","idle")}),t.jsx("dd",{children:R?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.agentActive","active")}),t.jsx("dd",{children:R?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.agentRunning","running")}),t.jsx("dd",{children:R?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:i("systemStats.agentError","error")}),t.jsx("dd",{children:R?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":i("systemStats.sectionVitestAriaLabel","Vitest controls"),children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(V1,{}),t.jsx("span",{children:i("systemStats.sectionVitest","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:i("systemStats.vitestProcesses","Vitest Processes")}),t.jsx("dd",{children:B??"—"})]})}),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 _(),disabled:b||B===0,children:[t.jsx(K1,{}),t.jsx("span",{children:v?i("systemStats.confirmKill","Confirm Kill?"):i("systemStats.killVitest","Kill Vitest Processes")})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:p,onChange:q=>{M(q.target.checked)}}),t.jsx("span",{children:i("systemStats.autoKillLabel","Auto-kill vitest on memory pressure")})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:i("systemStats.killThresholdLabel","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:u,"aria-label":i("systemStats.killThresholdSliderAriaLabel","Kill threshold slider (%)"),onChange:q=>{const ce=Number.parseInt(q.target.value,10);D(Number.isNaN(ce)?90:ce)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:u,"aria-label":i("systemStats.killThresholdInputAriaLabel","Kill threshold (%)"),onChange:q=>{const ce=Number.parseInt(q.target.value,10);D(Number.isNaN(ce)?90:ce)},onBlur:()=>{D(u)}})]})]}),k&&t.jsx("p",{className:Le,children:i("systemStats.killedProcesses","Killed {{count}} processes",{count:k.killed})}),t.jsx("p",{className:"system-stats-modal__last-kill",children:i("systemStats.lastAutoKill","Last auto-kill: {{time}}",{time:xe})}),g&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:g})]})]})]}),c&&r&&t.jsx("div",{className:"system-stats-modal__footer-error",children:i("systemStats.footerRefreshFailed","Latest refresh failed: {{error}}",{error:c})})]})})}const DU=5e3;function LU(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,d]=a.useState([]),[c,m]=a.useState(!1),[p,h]=a.useState(null),[u,f]=a.useState(!1),b=a.useRef(null),y=a.useRef(void 0),v=a.useCallback(async()=>{try{m(!0),h(null);let w;o?w=await Hg({limit:i,projectId:n,type:s}):w=(await Fg({limit:i,type:s,projectId:n})).map(j=>({...j,projectId:n??"",projectName:""})),d(w),f(w.length===i),w.length>0&&(y.current=w[w.length-1].timestamp)}catch(w){h(w instanceof Error?w.message:"Failed to load activity log")}finally{m(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(y.current)try{m(!0);let w;o?w=await Hg({limit:i,projectId:n,type:s,since:y.current}):w=(await Fg({limit:i,type:s,since:y.current,projectId:n})).map(j=>({...j,projectId:n??"",projectName:""})),d(g=>[...g,...w]),f(w.length===i),w.length>0&&(y.current=w[w.length-1].timestamp)}catch(w){h(w instanceof Error?w.message:"Failed to load more entries")}finally{m(!1)}},[i,n,s,o]),k=a.useCallback(()=>{d([]),f(!1),y.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return b.current=setInterval(()=>{v()},DU),()=>{b.current&&(clearInterval(b.current),b.current=null)}},[r,v]),{entries:l,loading:c,error:p,refresh:v,clear:k,hasMore:u,loadMore:x}}function FU(e){return{"task:created":e("activityLog.eventType.taskCreated","Task Created"),"task:moved":e("activityLog.eventType.taskMoved","Task Moved"),"task:updated":e("activityLog.eventType.taskUpdated","Task Updated"),"task:deleted":e("activityLog.eventType.taskDeleted","Task Deleted"),"task:merged":e("activityLog.eventType.taskMerged","Task Merged"),"task:failed":e("activityLog.eventType.taskFailed","Task Failed"),"task:duplicate-warning-overridden":e("activityLog.eventType.duplicateWarningOverridden","Duplicate Warning Overridden"),"task:auto-archived-ghost-bug":e("activityLog.eventType.autoArchivedGhostBug","Task Auto-Archived (Ghost Bug)"),"task:auto-archived-duplicate":e("activityLog.eventType.autoArchivedDuplicate","Task Auto-Archived (Duplicate)"),"task:merge-worktree-reacquired":e("activityLog.eventType.mergeWorktreeReacquired","Merge Worktree Reacquired"),"task:auto-archived-deterministic-duplicate":e("activityLog.eventType.autoArchivedDeterministicDuplicate","Task Auto-Archived (Deterministic Duplicate)"),"task:auto-archived-near-duplicate":e("activityLog.eventType.autoArchivedNearDuplicate","Task Auto-Archived (Near-Duplicate)"),"task:near-duplicate-flagged":e("activityLog.eventType.nearDuplicateFlagged","Near-Duplicate Flagged"),"settings:updated":e("activityLog.eventType.settingsUpdated","Settings Updated"),"project:isolation-transition":e("activityLog.eventType.projectIsolationTransition","Project Isolation Transition")}}const OU={"task:created":t.jsx(ys,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(fc,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(xs,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Fn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Es,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(vr,{size:14,className:"activity-icon failed"}),"task:duplicate-warning-overridden":t.jsx(oi,{size:14,className:"activity-icon updated"}),"task:auto-archived-ghost-bug":t.jsx(oi,{size:14,className:"activity-icon failed"}),"task:auto-archived-duplicate":t.jsx(as,{size:14,className:"activity-icon deleted"}),"task:auto-archived-deterministic-duplicate":t.jsx(as,{size:14,className:"activity-icon deleted"}),"task:auto-archived-near-duplicate":t.jsx(as,{size:14,className:"activity-icon deleted"}),"task:near-duplicate-flagged":t.jsx(oi,{size:14,className:"activity-icon updated"}),"task:merge-worktree-reacquired":t.jsx(xs,{size:14,className:"activity-icon updated"}),"settings:updated":t.jsx(Ql,{size:14,className:"activity-icon settings"}),"project:isolation-transition":t.jsx(Zs,{size:14,className:"activity-icon settings"})};function $U(e,n){const s=new Date(e),r=new Date().getTime()-s.getTime(),o=Math.floor(r/6e4),l=Math.floor(r/36e5),d=Math.floor(r/864e5);return o<1?n("activityLog.time.justNow","Just now"):o<60?n("activityLog.time.minutesAgo","{{count}}m ago",{count:o}):l<24?n("activityLog.time.hoursAgo","{{count}}h ago",{count:l}):d<7?n("activityLog.time.daysAgo","{{count}}d ago",{count:d}):s.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function zU({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:d}){const{t:c}=st("app"),m=FU(c),[p,h]=a.useState("all"),[u,f]=a.useState(r||"all"),[b,y]=a.useState(!1);a.useEffect(()=>{f(r||"all")},[r]);const v=p==="all"?void 0:p,x=u==="all"?void 0:u,k=!d&&o.length>0,{entries:w,loading:g,error:j,refresh:S,hasMore:C}=LU({projectId:x,type:v,limit:100,autoRefresh:e,useCentralFeed:k}),E=w.map(V=>({id:V.id,timestamp:V.timestamp,type:V.type,taskId:V.taskId,taskTitle:V.taskTitle,details:V.details,metadata:V.metadata,projectId:V.projectId,projectName:V.projectName})),F=async()=>{try{await AA(),S(),y(!1)}catch{y(!1)}},M=V=>{i&&i(V)},D=V=>{f(V),l?.(V==="all"?void 0:V)};a.useEffect(()=>{if(!e)return;const V=N=>{N.key==="Escape"&&(b?y(!1):n())};return document.addEventListener("keydown",V),()=>document.removeEventListener("keydown",V)},[e,n,b]);const _=p!=="all"||u!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:V=>{V.target===V.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(Ur,{size:18}),t.jsx("span",{children:c("activityLog.title","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(Zs,{size:14}),t.jsxs("select",{value:u,onChange:V=>D(V.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:c("activityLog.allProjects","All Projects")}),o.map(V=>t.jsx("option",{value:V.id,children:V.name},V.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Ld,{size:14}),t.jsxs("select",{value:p,onChange:V=>h(V.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:c("activityLog.allEvents","All Events")}),Object.entries(m).map(([V,N])=>t.jsx("option",{value:V,children:N},V))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>S(),title:c("activityLog.refresh","Refresh"),"data-testid":"activity-refresh",children:g?t.jsx(Et,{size:14,className:"spin"}):t.jsx(xs,{size:14})}),E.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>y(!0),title:c("activityLog.clearLog","Clear Log"),"data-testid":"activity-clear",children:t.jsx(as,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":c("actions.close","Close"),title:c("actions.close","Close"),"data-testid":"activity-close",children:"×"})]}),_&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:c("activityLog.activeFilters","Active filters:")}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(V=>V.id===u)?.name||u]}),p!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",m[p]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{h("all"),f("all"),l?.(void 0)},children:c("activityLog.clearFilters","Clear all")})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[j&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(oi,{size:16}),t.jsx("span",{children:j})]}),E.length===0&&!g&&!j&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Ur,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:_?c("activityLog.noMatchingActivity","No activity matches the current filters"):c("activityLog.noActivityRecorded","No activity recorded yet")}),_&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{h("all"),f("all"),l?.(void 0)},children:c("activityLog.clearFiltersBtnLabel","Clear Filters")})]}),t.jsx("div",{className:"activity-log-list",children:E.map(V=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:OU[V.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:m[V.type]}),t.jsx("span",{className:"activity-log-entry-time",children:$U(V.timestamp,c)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[V.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>M(V.taskId),"data-testid":"activity-task-link",children:V.taskId}),V.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:V.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:Hs(V.details??"")})]}),V.metadata&&Object.keys(V.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof V.metadata.from=="string"&&typeof V.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[V.metadata.from," → ",V.metadata.to]}),typeof V.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${V.metadata.merged?"success":"error"}`,children:V.metadata.merged?c("activityLog.merged","Merged"):c("activityLog.notMerged","Not merged")})]})]})]},V.id))}),C&&!g&&t.jsx("button",{className:"activity-log-load-more",onClick:S,"data-testid":"activity-load-more",children:c("activityLog.loadMore","Load More")}),g&&E.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(Et,{size:20,className:"spin"})})]}),b&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:c("activityLog.confirmClear","Clear Activity Log?")}),t.jsx("p",{children:c("activityLog.confirmClearMessage","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:()=>y(!1),children:c("actions.cancel","Cancel")}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:F,children:c("activityLog.confirmClearButton","Clear Log")})]})]})})]})}):null}const Fl=[{id:"status",label:"Status",icon:Ak},{id:"changes",label:"Changes",icon:kh},{id:"commits",label:"Commits",icon:vc},{id:"branches",label:"Branches",icon:ui},{id:"worktrees",label:"Worktrees",icon:O0},{id:"stashes",label:"Stashes",icon:Qr},{id:"remotes",label:"Remotes",icon:rc}];function py({status:e}){switch(e){case"added":case"untracked":return t.jsx(p0,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(jk,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(c0,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Hr,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(g0,{size:14,className:"gm-file-icon"})}}function fy({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 BU(e){const{t:n}=st("app");return a.useCallback(async(s,i)=>{try{await navigator.clipboard.writeText(s),e(i?n("git.copiedLabel","Copied {{label}}",{label:i}):n("git.copiedToClipboard","Copied to clipboard"),"success")}catch{e(n("git.failedToCopy","Failed to copy"),"error")}},[e,n])}function sl(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function UU({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const{t:o}=st("app"),l=Yi(),d=Ji();ga(e);const{keyboardOverlap:c,viewportHeight:m,viewportOffsetTop:p,keyboardOpen:h}=Xa({enabled:d==="mobile"}),u=h?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${p}px`,...m!==null?{"--vv-height":`${m}px`}:{}}:{},f=a.useCallback(()=>{if(d==="mobile"){const G=document.activeElement;G instanceof HTMLElement&&G.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,d]),[b,y]=a.useState("status"),[v,x]=a.useState(!1),[k,w]=a.useState(null),g=a.useRef(null);La(g,e,"fusion:git-modal-size");const j=yr(f),S=BU(i),[C,E]=a.useState(null),[F,M]=a.useState(null),[D,_]=a.useState([]),[V,N]=a.useState(new Set),[$,R]=a.useState(""),[L,O]=a.useState(!1),[J,A]=a.useState(null),[de,B]=a.useState(!1),[P,Z]=a.useState(null),[T,ie]=a.useState(null),le=a.useRef(0),[be,Le]=a.useState([]),[xe,q]=a.useState(null),[ce,De]=a.useState(null),[He,qe]=a.useState(!1),[pe,te]=a.useState(20),[me,se]=a.useState(""),[z,Y]=a.useState([]),[he,X]=a.useState(""),[ye,ot]=a.useState(""),[ue,je]=a.useState(""),[$e,Ce]=a.useState(null),[We,ke]=a.useState([]),[Ee,Ze]=a.useState(!1),[Ke,dt]=a.useState(null),[Fe,nt]=a.useState(null),[Nt,Ft]=a.useState(!1),[ze,it]=a.useState([]),[Mt,Ht]=a.useState([]),[Me,Ae]=a.useState(""),[ee,Ie]=a.useState(null),[Pe,oe]=a.useState(null),[re,_e]=a.useState(null),[fe,Xe]=a.useState(!1),[kt,Rt]=a.useState(null),Vt=a.useRef(0),[Pt,bt]=a.useState(null),[pt,ft]=a.useState(null),_t=a.useCallback(async()=>{if(e){x(!0),w(null);try{switch(b){case"status":{const G=await Ui(r,{extended:!0});E(G);break}case"changes":{const[G,Oe]=await Promise.all([Ui(r,{extended:!0}),bo(r)]);E(G),_(Oe),N(new Set),ie(null),A(null),Z(null);break}case"commits":{const G=await PM(pe,r);Le(G);break}case"branches":{const[G,Oe]=await Promise.all([Ro(r),Ui(r,{extended:!0})]);Y(G),E(Oe);break}case"worktrees":{const G=await FM(r);it(G);break}case"stashes":{const G=await Hc(r);Ht(G),oe(null),_e(null),Rt(null),Vt.current+=1;break}case"remotes":{const G=await Ui(r,{extended:!0});E(G);break}}}catch(G){w(Re(G)||o("git.failedToFetchData","Failed to fetch git data")),i(Re(G)||o("git.failedToFetchData","Failed to fetch git data"),"error")}finally{x(!1)}}},[b,e,pe,i,r]);a.useEffect(()=>{e&&_t()},[_t,e]),a.useEffect(()=>{if(!e)return;const G=Oe=>{if(Oe.key==="Escape"){f();return}if((Oe.key==="ArrowUp"||Oe.key==="ArrowDown")&&Oe.altKey){Oe.preventDefault();const yt=Fl.findIndex(Gt=>Gt.id===b);Oe.key==="ArrowUp"&&yt>0?y(Fl[yt-1].id):Oe.key==="ArrowDown"&&yt<Fl.length-1&&y(Fl[yt+1].id)}};return document.addEventListener("keydown",G),()=>document.removeEventListener("keydown",G)},[e,f,b]);const Yt=a.useCallback(async G=>{try{await Tg(G,r),i(o("git.stagedFiles","Staged {{count}} file(s)",{count:G.length}),"success");const Oe=await bo(r);_(Oe),N(new Set),ie(null),A(null),Z(null)}catch(Oe){i(Re(Oe)||o("git.failedToStageFiles","Failed to stage files"),"error")}},[i,r]),on=a.useCallback(async G=>{try{await WM(G,r),i(o("git.unstagedFiles","Unstaged {{count}} file(s)",{count:G.length}),"success");const Oe=await bo(r);_(Oe),N(new Set),ie(null),A(null),Z(null)}catch(Oe){i(Re(Oe)||o("git.failedToUnstageFiles","Failed to unstage files"),"error")}},[i,r]),An=a.useCallback(async G=>{if(await l.confirm({title:o("git.discardChangesTitle","Discard Changes"),message:o("git.discardChangesMessage","Discard changes to {{count}} file(s)? This cannot be undone.",{count:G.length}),danger:!0}))try{await GM(G,r),i(o("git.discardedFiles","Discarded changes to {{count}} file(s)",{count:G.length}),"success");const[yt,Gt]=await Promise.all([bo(r),Ui(r,{extended:!0})]);_(yt),E(Gt),N(new Set),ie(null),A(null),Z(null)}catch(yt){i(Re(yt)||o("git.failedToDiscardChanges","Failed to discard changes"),"error")}},[i,r,l]),vn=a.useCallback(async G=>{if(G.preventDefault(),!!$.trim()){O(!0);try{const Oe=await Rg($.trim(),r);i(o("git.committedHash","Committed: {{hash}}",{hash:Oe.hash}),"success"),R("");const[yt,Gt]=await Promise.all([bo(r),Ui(r,{extended:!0})]);_(yt),E(Gt),ie(null),A(null),Z(null)}catch(Oe){i(Re(Oe)||o("git.failedToCommit","Failed to commit"),"error")}finally{O(!1)}}},[$,i,r,o]),Qt=a.useCallback(async()=>{if($.trim()){O(!0);try{const G=D.filter(Sn=>!Sn.staged).map(Sn=>Sn.file);G.length>0&&await Tg(G,r);const Oe=await Rg($.trim(),r);i(o("git.committedHash","Committed: {{hash}}",{hash:Oe.hash}),"success"),R("");const[yt,Gt]=await Promise.all([bo(r),Ui(r,{extended:!0})]);_(yt),E(Gt),ie(null),A(null),Z(null)}catch(G){i(Re(G)||o("git.failedToCommit","Failed to commit"),"error")}finally{O(!1)}}},[$,D,i,r,o]),sn=a.useCallback(async(G,Oe)=>{ie({file:G,staged:Oe}),B(!0),Z(null);const yt=le.current+1;le.current=yt;try{const Gt=await qM(G,Oe,r);if(le.current!==yt)return;A(Gt)}catch(Gt){if(le.current!==yt)return;const Sn=Re(Gt)||o("git.failedToLoadFileDiff","Failed to load file diff");A(null),Z(Sn),i(Sn,"error")}finally{le.current===yt&&B(!1)}},[i,r,o]),mn=a.useCallback(G=>{N(Oe=>{const yt=new Set(Oe);return yt.has(G)?yt.delete(G):yt.add(G),yt})},[]),Kt=a.useCallback(async G=>{if(xe===G){q(null),De(null);return}q(G),qe(!0);try{const Oe=await Ud(G,r);De(Oe)}catch(Oe){i(Re(Oe)||o("git.failedToLoadDiff","Failed to load diff"),"error"),De(null)}finally{qe(!1)}},[xe,i,r]),fn=a.useCallback(()=>{te(G=>Math.min(G+20,100))},[]),$n=a.useMemo(()=>{if(!me.trim())return be;const G=me.toLowerCase();return be.filter(Oe=>Oe.message.toLowerCase().includes(G)||Oe.author.toLowerCase().includes(G)||Oe.shortHash.toLowerCase().includes(G))},[be,me]),On=a.useCallback(async G=>{if(G.preventDefault(),!!he.trim()){x(!0);try{await OM(he.trim(),ye.trim()||void 0,r),i(o("git.createdBranch","Created branch {{name}}",{name:he}),"success"),X(""),ot("");const Oe=await Ro(r);Y(Oe)}catch(Oe){i(Re(Oe)||o("git.failedToCreateBranch","Failed to create branch"),"error")}finally{x(!1)}}},[he,ye,i,r]),xn=a.useCallback(async G=>{x(!0);try{await $M(G,r),i(o("git.switchedToBranch","Switched to {{name}}",{name:G}),"success");const[Oe,yt]=await Promise.all([Ui(r,{extended:!0}),Ro(r)]);E(Oe),Y(yt)}catch(Oe){i(Re(Oe)||o("git.failedToCheckoutBranch","Failed to checkout branch"),"error")}finally{x(!1)}},[i,r]),Vn=a.useCallback(async G=>{if(await l.confirm({title:o("git.deleteBranchTitle","Delete Branch"),message:o("git.deleteBranchMessage",'Delete branch "{{name}}"?',{name:G}),danger:!0})){x(!0);try{await Eg(G,void 0,r),i(o("git.deletedBranch","Deleted branch {{name}}",{name:G}),"success");const yt=await Ro(r);Y(yt)}catch(yt){if(Re(yt).includes("not fully merged")){if(await l.confirm({title:o("git.forceDeleteBranchTitle","Force Delete Branch"),message:o("git.forceDeleteBranchMessage","Branch has unmerged commits. Force delete?"),danger:!0}))try{await Eg(G,!0,r),i(o("git.forceDeletedBranch","Force deleted branch {{name}}",{name:G}),"success");const Sn=await Ro(r);Y(Sn)}catch(Sn){i(Re(Sn)||o("git.failedToDeleteBranch","Failed to delete branch"),"error")}}else i(Re(yt)||o("git.failedToDeleteBranch","Failed to delete branch"),"error")}finally{x(!1)}}},[i,r,l]),Rn=a.useMemo(()=>{if(!ue.trim())return z;const G=ue.toLowerCase();return z.filter(Oe=>Oe.name.toLowerCase().includes(G))},[z,ue]),Pn=a.useCallback(async G=>{if($e===G){Ce(null),ke([]),dt(null),nt(null);return}Ce(G),ke([]),dt(null),nt(null),Ze(!0);try{const Oe=await LM(G,10,r);ke(Oe)}catch{ke([])}finally{Ze(!1)}},[$e,r]),zn=a.useCallback(async G=>{if(Ke===G){dt(null),nt(null);return}dt(G),nt(null),Ft(!0);try{const Oe=await Ud(G,r);nt(Oe)}catch{nt(null)}finally{Ft(!1)}},[Ke,r]),Nn=a.useCallback(()=>{Ce(null),ke([]),dt(null),nt(null)},[]),dn=a.useCallback(()=>{Vt.current+=1,oe(null),_e(null),Rt(null),Xe(!1)},[]),Tt=a.useCallback(async G=>{G.preventDefault(),Ie("create"),dn();try{await BM(Me.trim()||void 0,r),i(o("git.changesStashed","Changes stashed"),"success"),Ae("");const Oe=await Hc(r);Ht(Oe)}catch(Oe){i(Re(Oe)||o("git.failedToStashChanges","Failed to stash changes"),"error")}finally{Ie(null)}},[Me,i,r,dn]),Yn=a.useCallback(async(G,Oe=!1)=>{Ie(`apply-${G}`),dn();try{await UM(G,Oe,r),i(Oe?o("git.stashPopped","Stash popped"):o("git.stashApplied","Stash applied"),"success");const yt=await Hc(r);Ht(yt)}catch(yt){i(Re(yt)||o("git.failedToApplyStash","Failed to apply stash"),"error")}finally{Ie(null)}},[i,r,dn]),cn=a.useCallback(async G=>{if(await l.confirm({title:o("git.dropStashTitle","Drop Stash"),message:o("git.dropStashMessage","Drop stash@{{{index}}}? This cannot be undone.",{index:G}),danger:!0})){Ie(`drop-${G}`),dn();try{await HM(G,r),i(o("git.stashDropped","Stash dropped"),"success");const yt=await Hc(r);Ht(yt)}catch(yt){i(Re(yt)||o("git.failedToDropStash","Failed to drop stash"),"error")}finally{Ie(null)}}},[i,r,l,dn]),Bn=a.useCallback(async G=>{if(Pe===G){dn();return}const Oe=Vt.current+1;Vt.current=Oe,oe(G),_e(null),Rt(null),Xe(!0);try{const yt=await VM(G,r);if(Vt.current!==Oe)return;_e(yt)}catch(yt){if(Vt.current!==Oe)return;_e(null),Rt(Re(yt)||o("git.failedToLoadStashDiff","Failed to load stash diff"))}finally{Vt.current===Oe&&Xe(!1)}},[Pe,r,dn]),kn=a.useCallback(async()=>{bt("fetch");try{const G=await zM(void 0,r);ft(G),i(G.message||o("git.fetchCompleted","Fetch completed"),G.fetched?"success":"info");const Oe=await Ui(r,{extended:!0});E(Oe)}catch(G){i(Re(G)||o("git.fetchFailed","Fetch failed"),"error")}finally{bt(null)}},[i,r]),pn=a.useCallback(async G=>{bt("pull");try{const Oe=await Mg(G,r);if(ft(Oe),Oe.conflict)i(o("git.mergeConflictDetected","Merge conflict detected. Resolve manually."),"error");else{const Gt=G?.rebase?o("git.pullRebaseCompleted","Pull --rebase completed"):o("git.pullCompleted","Pull completed");i(Oe.message||Gt,"success")}const yt=await Ui(r,{extended:!0});E(yt)}catch(Oe){i(Re(Oe)||o("git.pullFailed","Pull failed"),"error")}finally{bt(null)}},[i,r]),un=a.useCallback(async()=>{bt("push");try{const G=await Ag(r);ft(G),i(G.message||o("git.pushCompleted","Push completed"),"success");const Oe=await Ui(r,{extended:!0});E(Oe)}catch(G){i(Re(G)||o("git.pushFailed","Push failed"),"error")}finally{bt(null)}},[i,r]),At=a.useCallback(async()=>{bt("sync");try{const G=await Mg({rebase:!0},r);if(ft(G),G.conflict){i(o("git.mergeConflictDetected","Merge conflict detected. Resolve manually."),"error");return}const Oe=await Ag(r);ft(Oe),i(o("git.syncedWithOrigin","Synced with origin (pull --rebase + push)"),"success");const yt=await Ui(r,{extended:!0});E(yt)}catch(G){i(Re(G)||o("git.syncWithOriginFailed","Sync with origin failed"),"error")}finally{bt(null)}},[i,r]);a.useEffect(()=>{Jk(r).then(G=>M(G.rootDir)).catch(()=>M(null))},[r]);const an=a.useCallback(async()=>{if(!C?.integrationBranch||C.isOnIntegrationBranch===!1)return;const G=F;if(!G){i(o("git.projectRootNotAvailable","Project root path not available"),"error");return}bt("sync-integration");try{const Oe=r?`?projectId=${encodeURIComponent(r)}`:"";await I(`/git/pull${Oe}`,{method:"POST",body:JSON.stringify({worktreePath:G,integrationBranch:C.integrationBranch,taskId:void 0,skipOriginFetch:!0})}),i(o("git.syncedWorktreeToIntegrationTip","Synced worktree to local integration tip"),"success");const yt=await Ui(r,{extended:!0});E(yt)}catch(Oe){i(Re(Oe)||o("git.syncFailed","Sync failed"),"error")}finally{bt(null)}},[i,r,F,C?.integrationBranch,C?.isOnIntegrationBranch,o]),Wn=a.useMemo(()=>D.filter(G=>G.staged),[D]),Xn=a.useMemo(()=>D.filter(G=>!G.staged),[D]);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:g,style:u,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(wh,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),o("git.modalTitle","Git Manager")]}),t.jsxs("div",{className:"gm-header-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:_t,disabled:v,title:o("git.refresh","Refresh"),children:t.jsx(xs,{size:14,className:v?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":o("git.close","Close"),children:t.jsx(Fn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":o("git.sidebarAriaLabel","Git Manager Sections"),children:Fl.map(G=>{const Oe=G.icon,yt={status:o("git.sectionStatus","Status"),changes:o("git.sectionChanges","Changes"),commits:o("git.sectionCommits","Commits"),branches:o("git.sectionBranches","Branches"),worktrees:o("git.sectionWorktrees","Worktrees"),stashes:o("git.sectionStashes","Stashes"),remotes:o("git.sectionRemotes","Remotes")}[G.id]??G.label;return t.jsxs("button",{role:"tab","aria-selected":b===G.id,className:`gm-nav-item${b===G.id?" active":""}`,onClick:()=>y(G.id),children:[t.jsx(Oe,{size:16}),t.jsx("span",{className:"gm-nav-label",children:yt})]},G.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[v&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(Et,{size:24,className:"spin"}),t.jsx("span",{children:o("git.loading","Loading...")})]}),k&&!v&&t.jsxs("div",{className:"gm-error",children:[t.jsx(oi,{size:18}),t.jsx("span",{children:k}),t.jsx("button",{className:"btn btn-sm",onClick:_t,children:o("git.retry","Retry")})]}),b==="status"&&!v&&C&&t.jsx(HU,{status:C,copyToClipboard:S,onSyncWorkingTree:an,syncing:Pt==="sync-integration"}),b==="changes"&&!v&&t.jsx(VU,{status:C,stagedFiles:Wn,unstagedFiles:Xn,selectedFiles:V,toggleFileSelection:mn,onStageFiles:Yt,onUnstageFiles:on,onDiscardChanges:An,onSelectDiffFile:sn,selectedDiffTarget:T,changeDiff:J,loadingChangeDiff:de,changeDiffError:P,commitMessage:$,setCommitMessage:R,onCommit:vn,onStageAllAndCommit:Qt,committing:L}),b==="commits"&&!v&&t.jsx(qU,{commits:$n,commitSearch:me,setCommitSearch:se,selectedCommit:xe,commitDiff:ce,loadingDiff:He,onCommitClick:Kt,onLoadMore:fn,canLoadMore:be.length>=pe&&pe<100,copyToClipboard:S}),b==="branches"&&!v&&t.jsx(WU,{branches:Rn,branchSearch:ue,setBranchSearch:je,newBranchName:he,setNewBranchName:X,branchBase:ye,setBranchBase:ot,onCreateBranch:On,onCheckoutBranch:xn,onDeleteBranch:Vn,loading:v,allBranches:z,selectedBranch:$e,branchCommits:We,loadingBranchCommits:Ee,expandedBranchCommit:Ke,branchCommitDiff:Fe,loadingBranchCommitDiff:Nt,onSelectBranch:Pn,onBranchCommitClick:zn,onCloseBranchDetails:Nn}),b==="worktrees"&&!v&&t.jsx(GU,{worktrees:ze}),b==="stashes"&&!v&&t.jsx(KU,{stashes:Mt,stashMessage:Me,setStashMessage:Ae,onCreateStash:Tt,onApplyStash:Yn,onDropStash:cn,onToggleStashDiff:Bn,stashLoading:ee,expandedStashIndex:Pe,stashDiff:re,loadingStashDiff:fe,stashDiffError:kt}),b==="remotes"&&!v&&t.jsx(JU,{status:C,remoteLoading:Pt,lastRemoteResult:pt,onFetch:kn,onPull:pn,onPush:un,onSync:At,onSyncIntegrationTip:an,syncIntegrationDisabled:!C?.integrationBranch||C?.isOnIntegrationBranch===!1||Pt!==null,addToast:i,projectId:r,copyToClipboard:S})]})]})]})}):null}function HU({status:e,copyToClipboard:n,onSyncWorkingTree:s,syncing:i}){const{t:r}=st("app"),[o,l]=a.useState(!1),[d,c]=a.useState(new Set),m=(e.recentMergeAdvances??[]).filter(b=>!d.has(b.toSha)),p=m.filter(b=>b.resolution==="pending"),h=p.length>0,u=e.aheadOfIntegration===0&&e.behindIntegration===0,f=h&&!u;return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:r("git.repositoryStatus","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:r("git.statusLabelBranch","Branch")}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:e.branch}),e.integrationBranch&&e.isOnIntegrationBranch===!1&&t.jsxs("span",{className:"gm-status-sub",title:r("git.notOnIntegrationBranchTitle","Currently on a non-integration branch"),children:[" ",r("git.notOnIntegrationBranch","(not on {{branch}})",{branch:e.integrationBranch})]})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelCommit","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,r("git.copyCommitHashLabel","commit hash")),title:e.headSha?r("git.copyShortHashTitleWithFull","Copy short commit hash (use the full SHA below for git operations)"):r("git.copyShortHashTitle","Copy short commit hash"),children:t.jsx(Pa,{size:12})}),e.headSha&&t.jsxs("button",{className:"gm-icon-btn",onClick:()=>n(e.headSha,r("git.copyFullCommitHashLabel","full commit hash")),title:r("git.copyFullShaTitle","Copy full 40-char SHA"),children:[t.jsx(Pa,{size:12}),t.jsx("span",{style:{fontSize:10,marginLeft:2},children:r("git.fullShaAbbrev","full")})]})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelWorkingTree","Working Tree")}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(oi,{size:12}),r("git.workingTreeModified","Modified")]}):t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:12}),r("git.workingTreeClean","Clean")]})}),e.dirtyDetails&&e.dirtyDetails.staged+e.dirtyDetails.modified+e.dirtyDetails.untracked+e.dirtyDetails.conflicted>0&&t.jsxs("span",{className:"gm-status-sub",children:[e.dirtyDetails.staged>0&&t.jsx("span",{title:r("git.staged","Staged"),children:r("git.stagedCount","{{count}} staged",{count:e.dirtyDetails.staged})}),e.dirtyDetails.staged>0&&e.dirtyDetails.modified+e.dirtyDetails.untracked+e.dirtyDetails.conflicted>0&&" · ",e.dirtyDetails.modified>0&&t.jsx("span",{title:r("git.modified","Modified"),children:r("git.modifiedCount","{{count}} modified",{count:e.dirtyDetails.modified})}),e.dirtyDetails.modified>0&&e.dirtyDetails.untracked+e.dirtyDetails.conflicted>0&&" · ",e.dirtyDetails.untracked>0&&t.jsx("span",{title:r("git.untracked","Untracked"),children:r("git.untrackedCount","{{count}} untracked",{count:e.dirtyDetails.untracked})}),e.dirtyDetails.untracked>0&&e.dirtyDetails.conflicted>0&&" · ",e.dirtyDetails.conflicted>0&&t.jsx("span",{title:r("git.unresolvedMergeConflicts","Unresolved merge conflicts"),className:"gm-status-conflict",children:r("git.conflictedCount","{{count}} conflicted",{count:e.dirtyDetails.conflicted})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelVsOrigin","vs origin")}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:r("git.aheadOfUpstream","{{count}} commit(s) ahead of upstream",{count:e.ahead}),children:[t.jsx(Ma,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:r("git.behindUpstream","{{count}} commit(s) behind upstream",{count:e.behind}),children:[t.jsx(hr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Es,{size:12}),r("git.upToDate","Up to date")]})]})]})]}),e.integrationBranch&&t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card","data-testid":"integration-branch-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelIntegrationBranch","Integration branch")}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(ui,{size:14}),t.jsx("span",{children:e.integrationBranch}),e.integrationBranchSource&&t.jsxs("span",{className:"gm-status-sub",title:r("git.resolvedFrom","Resolved from {{source}}",{source:e.integrationBranchSource}),children:[" ","(",e.integrationBranchSource,")"]})]}),e.integrationTipSha&&t.jsxs("span",{className:"gm-status-sub",children:[r("git.tip","tip")," ",t.jsx("code",{className:"gm-hash",children:e.integrationTipSha.slice(0,8)}),e.integrationTipSource==="remote-only"&&t.jsxs(t.Fragment,{children:[" ",t.jsx("span",{title:r("git.remoteOnlyIntegrationTipTitle","No local refs/heads/<branch>; using refs/remotes/origin/<branch> as the integration tip."),children:r("git.remoteOnlyTrackLocally","(remote-only — run git switch {{branch}} to track locally)",{branch:e.integrationBranch})})]})]}),e.integrationTipSource==="missing"&&t.jsx("span",{className:"gm-status-sub gm-status-conflict",title:r("git.noRefFoundTitle","Neither refs/heads nor refs/remotes/origin has this branch"),children:r("git.noRefFound","no ref found for {{branch}}",{branch:e.integrationBranch})})]}),e.integrationTipSha!==void 0&&(e.aheadOfIntegration!==void 0||e.behindIntegration!==void 0)&&t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.headVsIntegration","HEAD vs {{branch}}",{branch:e.integrationBranch})}),t.jsx("span",{className:"gm-status-value",children:(e.aheadOfIntegration??0)===0&&(e.behindIntegration??0)===0?t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Es,{size:12}),r("git.aligned","Aligned")]}):t.jsxs(t.Fragment,{children:[(e.aheadOfIntegration??0)>0&&t.jsxs("span",{className:"gm-ahead",title:r("git.headAheadOfIntegration","HEAD has {{count}} commit(s) not on {{branch}}",{count:e.aheadOfIntegration,branch:e.integrationBranch}),children:[t.jsx(Ma,{size:12}),e.aheadOfIntegration]}),(e.behindIntegration??0)>0&&t.jsxs("span",{className:"gm-behind",title:r("git.integrationAheadOfHead","{{branch}} has {{count}} commit(s) HEAD doesn't",{branch:e.integrationBranch,count:e.behindIntegration}),children:[t.jsx(hr,{size:12}),e.behindIntegration]})]})})]}),e.originIntegrationTipSha!==void 0&&t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.localVsOrigin","Local {{branch}} vs origin",{branch:e.integrationBranch})}),t.jsx("span",{className:"gm-status-value",children:e.originIntegrationTipSha===null?t.jsx("span",{className:"gm-status-sub",children:r("git.noOriginTracking","no origin tracking")}):e.integrationTipSource==="remote-only"?t.jsx("span",{className:"gm-status-sub",title:r("git.noLocalRefTitle","No local refs/heads/<branch> exists; nothing to compare against origin."),children:r("git.noLocalTracking","no local tracking")}):(e.aheadOfOriginIntegration??0)===0&&(e.behindOriginIntegration??0)===0?t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Es,{size:12}),r("git.synced","Synced")]}):t.jsxs(t.Fragment,{children:[(e.aheadOfOriginIntegration??0)>0&&t.jsxs("span",{className:"gm-ahead",title:r("git.localAheadOfOriginIntegration","Local {{branch}} is {{count}} commit(s) ahead of origin/{{branch}}",{branch:e.integrationBranch,count:e.aheadOfOriginIntegration}),children:[t.jsx(Ma,{size:12}),e.aheadOfOriginIntegration]}),(e.behindOriginIntegration??0)>0&&t.jsxs("span",{className:"gm-behind",title:r("git.localBehindOriginIntegration","Local {{branch}} is {{count}} commit(s) behind origin/{{branch}}",{branch:e.integrationBranch,count:e.behindOriginIntegration}),children:[t.jsx(hr,{size:12}),e.behindOriginIntegration]})]})})]}),e.integrationTipSource==="remote-only"&&e.aheadOfIntegrationRemote!==void 0&&t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.headVsOriginIntegration","HEAD vs origin/{{branch}}",{branch:e.integrationBranch})}),t.jsx("span",{className:"gm-status-value",children:(e.aheadOfIntegrationRemote??0)===0&&(e.behindIntegrationRemote??0)===0?t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Es,{size:12}),r("git.aligned","Aligned")]}):t.jsxs(t.Fragment,{children:[(e.aheadOfIntegrationRemote??0)>0&&t.jsxs("span",{className:"gm-ahead",title:r("git.headAheadOfOriginIntegration","HEAD has {{count}} commit(s) not on origin/{{branch}}",{count:e.aheadOfIntegrationRemote,branch:e.integrationBranch}),children:[t.jsx(Ma,{size:12}),e.aheadOfIntegrationRemote]}),(e.behindIntegrationRemote??0)>0&&t.jsxs("span",{className:"gm-behind",title:r("git.originIntegrationAheadOfHead","origin/{{branch}} has {{count}} commit(s) HEAD doesn't",{branch:e.integrationBranch,count:e.behindIntegrationRemote}),children:[t.jsx(hr,{size:12}),e.behindIntegrationRemote]})]})})]}),(e.stashCount??0)>0&&t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:r("git.statusLabelStashes","Stashes")}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Qr,{size:14}),t.jsx("span",{children:e.stashCount})]})]})]}),e.indexStaleVsHead===!0&&t.jsxs("div",{className:"gm-status-warning","data-testid":"index-stale-warning",role:"alert",children:[t.jsx(oi,{size:14}),t.jsx("div",{children:t.jsx(Ga,{i18nKey:"app:git.staleIndexWarning",defaults:'<strong>Stale index detected.</strong> HEAD has advanced (typically because Fusion\'s merger updated the integration-branch ref) but the index still reflects the previous tip — `git status` will report the new commits inverted as "staged changes." Enable <mergeCode>mergeAdvanceAutoSync</mergeCode> in Settings to have the merger reconcile automatically, or run <resetCode>git reset --hard HEAD</resetCode> to snap forward manually.',components:{strong:t.jsx("strong",{}),mergeCode:t.jsx("code",{}),resetCode:t.jsx("code",{})}})})]}),m.length>0&&t.jsxs("div",{className:"gm-status-advances","data-testid":"recent-merge-advances",children:[t.jsxs("div",{className:"gm-status-advances-header",children:[t.jsxs("span",{children:[r("git.recentIntegrationAdvances","Recent integration-branch advances"),t.jsxs("span",{className:"gm-status-sub",children:[" ","(",r("git.advancesNeedAction","{{count}} need action",{count:p.length}),")"]}),t.jsx("button",{type:"button",className:"gm-icon-btn",style:{marginLeft:6},"aria-expanded":o,"aria-label":o?r("git.hideExplanation","Hide explanation"):r("git.whatDoesThisMean","What does this mean?"),onClick:()=>l(b=>!b),title:r("git.whatDoesThisMean","What does this mean?"),children:t.jsx(q0,{size:13})})]}),f&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:i,"data-testid":"sync-working-tree-btn",title:r("git.syncWorkingTreeTitle","Pull the integration branch into your working tree (auto-stashes uncommitted edits and restores them)"),children:i?r("git.syncing","Syncing…"):r("git.syncWorkingTree","Sync working tree")})]}),o&&t.jsxs("div",{className:"gm-status-advances-help","data-testid":"recent-merge-advances-help",children:[t.jsx("p",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpIntro",defaults:"Each entry is a Fusion task whose squash commit advanced the integration branch ref (<branchCode>{{integrationBranch}}</branchCode>). The <em>auto-sync outcome</em> says whether your working tree was also fast-forwarded to that new tip.",values:{integrationBranch:e.integrationBranch??"main"},components:{branchCode:t.jsx("code",{}),em:t.jsx("em",{})}})}),t.jsxs("ul",{className:"gm-status-advances-help-list",children:[t.jsx("li",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpItem1",defaults:"<c1>clean-sync</c1> / <c2>synced-with-edits-restored</c2> — working tree is in sync; nothing to do.",components:{c1:t.jsx("code",{}),c2:t.jsx("code",{})}})}),t.jsx("li",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpItem2",defaults:"<c1>reachable</c1> / <c2>subsumed</c2> / <c3>orphaned</c3> / <c4>superseded</c4> — already handled (including history rewrites where equivalent content already landed, original SHAs disappeared, or HEAD is already aligned to the rewritten integration tip).",components:{c1:t.jsx("code",{}),c2:t.jsx("code",{}),c3:t.jsx("code",{}),c4:t.jsx("code",{})}})}),t.jsx("li",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpItem3",defaults:"<c1>pending</c1> + <c2>off / not run</c2> — auto-sync is disabled in Settings; the branch ref moved but your worktree didn't follow.",components:{c1:t.jsx("code",{}),c2:t.jsx("code",{})}})}),t.jsx("li",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpItem4",defaults:"<c1>pending</c1> + <c2>stash-failed</c2> / <c3>would-conflict</c3> / similar — auto-sync tried but couldn't reconcile (usually local edits collide with the new commit).",components:{c1:t.jsx("code",{}),c2:t.jsx("code",{}),c3:t.jsx("code",{})}})})]}),t.jsx("p",{children:t.jsx(Ga,{i18nKey:"app:git.advancesHelpFix",defaults:"<strong>Fix:</strong> Fusion only shows <em>Sync working tree</em> when at least one advance is genuinely <code>pending</code> and HEAD is not aligned with the integration tip. If entries are already handled (subsumed/orphaned/reachable/superseded), no sync action is offered.",components:{strong:t.jsx("strong",{}),em:t.jsx("em",{}),code:t.jsx("code",{})}})})]}),t.jsx("ul",{children:m.map(b=>t.jsxs("li",{className:b.needsAction?"gm-advance-needs-action":"gm-advance-handled",children:[t.jsx("code",{className:"gm-hash",children:b.toSha.slice(0,8)})," ",t.jsx("strong",{children:b.taskId}),b.autoSyncOutcome?t.jsxs("span",{className:"gm-status-sub",children:[" ",r("git.autoSyncOutcome","auto-sync: {{outcome}}",{outcome:b.autoSyncOutcome})]}):t.jsxs("span",{className:"gm-status-sub",children:[" ",r("git.autoSyncOffNotRun","auto-sync: off / not run")]}),t.jsxs("span",{className:"gm-status-sub",children:[" ","· ",new Date(b.advancedAt).toLocaleTimeString()," · ",b.resolution]}),(b.resolution==="orphaned"||b.resolution==="subsumed"||b.resolution==="superseded")&&t.jsx("button",{type:"button",className:"btn btn-xs",onClick:()=>{c(y=>{const v=new Set(y);return v.add(b.toSha),v})},"data-testid":`dismiss-advance-${b.toSha}`,children:r("git.dismiss","Dismiss")})]},`${b.taskId}-${b.toSha}`))})]})]})}function VU({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:d,onSelectDiffFile:c,selectedDiffTarget:m,changeDiff:p,loadingChangeDiff:h,changeDiffError:u,commitMessage:f,setCommitMessage:b,onCommit:y,onStageAllAndCommit:v,committing:x}){const{t:k}=st("app"),w=s.filter(j=>i.has(`unstaged:${j.file}`)),g=n.filter(j=>i.has(`staged:${j.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(ui,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:k("git.workingTreeModified","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.jsx("h5",{children:k("git.unstagedChanges","Unstaged Changes ({{count}})",{count:s.length})}),t.jsxs("div",{className:"gm-file-section-actions",children:[w.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(w.map(j=>j.file)),title:k("git.stageSelected","Stage selected"),children:[t.jsx(ys,{size:12})," ",k("git.stageCount","Stage ({{count}})",{count:w.length})]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>d(w.map(j=>j.file)),title:k("git.discardSelected","Discard selected"),children:t.jsx(vr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.file)),title:k("git.stageAll","Stage all"),children:k("git.stageAll","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:k("git.noUnstagedChanges","No unstaged changes")}):s.map(j=>{const S=m?.file===j.file&&m.staged===!1;return t.jsxs("div",{className:`gm-file-item${S?" active":""}`,onClick:()=>c(j.file,!1),role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),c(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:C=>C.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(py,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(fy,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:C=>{C.stopPropagation(),o([j.file])},title:k("git.stageFile","Stage file"),children:t.jsx(ys,{size:12})})]},`unstaged:${j.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsx("h5",{children:k("git.stagedChanges","Staged Changes ({{count}})",{count:n.length})}),t.jsxs("div",{className:"gm-file-section-actions",children:[g.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(g.map(j=>j.file)),title:k("git.unstageSelected","Unstage selected"),children:k("git.unstageCount","Unstage ({{count}})",{count:g.length})}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.file)),title:k("git.unstageAll","Unstage all"),children:k("git.unstageAll","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:k("git.noStagedChanges","No staged changes")}):n.map(j=>{const S=m?.file===j.file&&m.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${S?" active":""}`,onClick:()=>c(j.file,!0),role:"button",tabIndex:0,onKeyDown:C=>{(C.key==="Enter"||C.key===" ")&&(C.preventDefault(),c(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:C=>C.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(py,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(fy,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:C=>{C.stopPropagation(),l([j.file])},title:k("git.unstageFile","Unstage file"),children:t.jsx(Fn,{size:12})})]},`staged:${j.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:m||h||p||u?t.jsxs("div",{className:"gm-diff-section",children:[m&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(kh,{size:14}),t.jsxs("span",{children:[m.staged?k("git.staged","Staged"):k("git.unstaged","Unstaged")," ",k("git.diffColon","diff:")," "]}),t.jsx("code",{children:m.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),k("git.loadingDiff","Loading diff...")]}),u&&!h&&t.jsx("div",{className:"gm-diff-error",children:u}),p&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[p.stat&&t.jsx("pre",{className:"gm-diff-stat",children:p.stat}),t.jsx("pre",{className:"gm-diff-patch",children:p.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(kh,{size:20}),t.jsx("span",{children:k("git.selectFileToViewDiff","Select a file to view its diff")})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:y,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:k("git.commitMessagePlaceholder","Commit message..."),value:f,onChange:j=>b(j.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!f.trim()||n.length===0,title:n.length===0?k("git.noStagedChangesToCommit","No staged changes to commit"):k("git.commitStagedChanges","Commit staged changes"),children:[x?t.jsx(Et,{size:14,className:"spin"}):t.jsx(zr,{size:14}),k("git.commit","Commit")]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:x||!f.trim(),title:k("git.stageAllAndCommitTitle","Stage all and commit"),children:k("git.stageAllAndCommit","Stage All & Commit")})]})]})]})}function qU({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:i,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:d,canLoadMore:c,copyToClipboard:m}){const{t:p}=st("app");return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:p("git.sectionCommits","Commits")}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(na,{size:14}),t.jsx("input",{type:"text",placeholder:p("git.searchCommits","Search commits..."),value:n,onChange:h=>s(h.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?p("git.noMatchingCommits","No matching commits"):p("git.noCommitsFound","No commits found")}):e.map((h,u)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),u<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(h.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:h.shortHash}),t.jsx("span",{className:"gm-commit-message",title:h.message,children:h.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:h.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:sl(h.date)}),h.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:p("git.mergeBadge","merge")})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>m(h.hash,p("git.copyCommitHashLabel","commit hash")),title:p("git.copyFullHash","Copy full hash"),children:t.jsx(Pa,{size:12})})}),i===h.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),p("git.loadingDiff","Loading diff...")]}):r?t.jsxs(t.Fragment,{children:[h.body&&t.jsx("div",{className:"gm-commit-message-full",children:h.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:p("git.failedToLoadDiff","Failed to load diff")})})]})]},h.hash))}),c&&t.jsx("button",{className:"gm-load-more",onClick:d,children:p("git.loadMoreCommits","Load more commits")})]})}function WU({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:d,onCheckoutBranch:c,onDeleteBranch:m,loading:p,allBranches:h,selectedBranch:u,branchCommits:f,loadingBranchCommits:b,expandedBranchCommit:y,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:k,onBranchCommitClick:w,onCloseBranchDetails:g}){const{t:j}=st("app");return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:j("git.sectionBranches","Branches")}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(na,{size:14}),t.jsx("input",{type:"text",placeholder:j("git.filterBranches","Filter branches..."),value:n,onChange:S=>s(S.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:d,children:[t.jsx("input",{type:"text",placeholder:j("git.newBranchName","New branch name"),value:i,onChange:S=>r(S.target.value),disabled:p}),t.jsxs("select",{value:o,onChange:S=>l(S.target.value),disabled:p,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:j("git.baseHead","Base: HEAD")}),h.map(S=>t.jsx("option",{value:S.name,children:S.name},S.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:p||!i.trim(),children:[t.jsx(ys,{size:14}),j("git.create","Create")]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?j("git.noMatchingBranches","No matching branches"):j("git.noBranchesFound","No branches found")}):e.map(S=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${S.isCurrent?" current":""}${u===S.name?" selected":""}`,onClick:()=>k(S.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[S.isCurrent&&t.jsx(Qs,{size:14,className:"gm-current-icon"}),S.name]}),S.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",S.remote]}),S.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:sl(S.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!S.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:C=>{C.stopPropagation(),c(S.name)},disabled:p,title:j("git.checkout","Checkout"),children:t.jsx(ui,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:C=>{C.stopPropagation(),m(S.name)},disabled:p,title:j("git.deleteBranch","Delete"),children:t.jsx(as,{size:14})})]})})]}),u===S.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(vc,{size:14}),j("git.commitsOnBranch","Commits on {{name}}",{name:S.name})]}),t.jsx("button",{className:"gm-icon-btn",onClick:g,title:j("git.close","Close"),"data-testid":"close-branch-details",children:t.jsx(Fn,{size:14})})]}),b?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(Et,{size:16,className:"spin"}),j("git.loadingCommits","Loading commits...")]}):f.length===0?t.jsx("div",{className:"gm-empty",children:j("git.noCommitsFound","No commits found")}):t.jsx("div",{className:"gm-branch-commits-list",children:f.map(C=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>w(C.hash),"data-testid":`branch-commit-${C.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:C.shortHash}),t.jsx("span",{className:"gm-commit-message",title:C.message,children:C.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:C.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:sl(C.date)}),C.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:j("git.mergeBadge","merge")})]})]}),y===C.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),j("git.loadingDiff","Loading diff...")]}):v?t.jsxs(t.Fragment,{children:[(C.body||C.message)&&t.jsx("div",{className:"gm-commit-message-full",children:C.body||C.message}),v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:j("git.failedToLoadDiff","Failed to load diff")})})]},C.hash))})]})]},S.name))})]})}function GU({worktrees:e}){const{t:n}=st("app");return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:n("git.sectionWorktrees","Worktrees")}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsx("span",{children:n("git.worktreesTotal","{{count}} total",{count:e.length})}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsx("span",{children:n("git.worktreesInUse","{{count}} in use",{count:e.filter(s=>s.taskId).length})})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(s=>t.jsx("div",{className:`gm-worktree-item${s.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[s.isMain&&t.jsx("span",{className:"gm-badge main",children:n("git.worktreeBadgeMain","main")}),s.isBare&&t.jsx("span",{className:"gm-badge bare",children:n("git.worktreeBadgeBare","bare")}),t.jsx("span",{className:"gm-worktree-path",title:s.path,children:Lp(s.path)||s.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[s.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(ui,{size:12}),s.branch]}),s.taskId&&t.jsx("span",{className:"gm-worktree-task",children:s.taskId})]})]})},s.path))})]})}function KU({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:d,expandedStashIndex:c,stashDiff:m,loadingStashDiff:p,stashDiffError:h}){const{t:u}=st("app");return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:u("git.sectionStashes","Stashes")})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:u("git.stashMessagePlaceholder","Stash message (optional)"),value:n,onChange:f=>s(f.target.value),disabled:d!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:d!==null,children:[d==="create"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(Qr,{size:14}),u("git.stash","Stash")]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:u("git.noStashes","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(ui,{size:12}),f.branch]}),t.jsx("span",{children:sl(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:d!==null,children:c===f.index?u("git.hide","Hide"):u("git.view","View")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:d!==null,title:u("git.applyStashKeep","Apply stash (keep)"),children:d===`apply-${f.index}`?t.jsx(Et,{size:14,className:"spin"}):u("git.apply","Apply")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:d!==null,title:u("git.popStashTitle","Pop stash (apply and drop)"),children:u("git.pop","Pop")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:d!==null,title:u("git.dropStash","Drop stash"),children:d===`drop-${f.index}`?t.jsx(Et,{size:14,className:"spin"}):t.jsx(as,{size:14})})]})]}),c===f.index&&t.jsx("div",{className:"gm-stash-diff",children:p?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:14,className:"spin"}),u("git.loadingStashDiff","Loading stash diff…")]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):m?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})]}):null})]},f.index))})]})}function JU({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,onSync:l,onSyncIntegrationTip:d,syncIntegrationDisabled:c,addToast:m,projectId:p,copyToClipboard:h}){const{t:u}=st("app"),f=Fe=>{try{return new URL(Fe).hostname}catch{return Fe.replace(/^git@/,"").split(":")[0]||Fe}},[b,y]=a.useState([]),[v,x]=a.useState(!1),[k,w]=a.useState(null),[g,j]=a.useState(""),[S,C]=a.useState(""),[E,F]=a.useState(null),[M,D]=a.useState(""),[_,V]=a.useState(""),[N,$]=a.useState(!1),[R,L]=a.useState(!1),O=a.useRef(null),[J,A]=a.useState([]),[de,B]=a.useState(!1),[P,Z]=a.useState(null),[T,ie]=a.useState([]),[le,be]=a.useState(!1),[Le,xe]=a.useState(null),q=a.useRef(0),ce=b.find(Fe=>Fe.name===P);a.useEffect(()=>{(n!==null||v)&&L(!1)},[n,v]),a.useEffect(()=>{if(!R)return;const Fe=Nt=>{O.current?.contains(Nt.target)||L(!1)},nt=Nt=>{Nt.key==="Escape"&&L(!1)};return document.addEventListener("mousedown",Fe),document.addEventListener("keydown",nt),()=>{document.removeEventListener("mousedown",Fe),document.removeEventListener("keydown",nt)}},[R]);const[De,He]=a.useState(null),[qe,pe]=a.useState(null),[te,me]=a.useState(!1),[se,z]=a.useState(null),[Y,he]=a.useState(null),[X,ye]=a.useState(!1);a.useEffect(()=>{ot()},[]),a.useEffect(()=>{e&&e.ahead>0?ue():e&&e.ahead===0&&A([])},[e?.ahead]),a.useEffect(()=>{b.length>0&&!P&&Z(b[0].name)},[b]),a.useEffect(()=>{P?je(P):(ie([]),xe(null))},[P]),a.useEffect(()=>{!P||!s||je(P)},[P,s]),a.useEffect(()=>{P&&!b.find(Fe=>Fe.name===P)&&Z(b.length>0?b[0].name:null)},[b,P]);const ot=async()=>{x(!0);try{const Fe=await bM(p);y(Fe)}catch(Fe){m(Re(Fe)||u("git.failedToLoadRemotes","Failed to load remotes"),"error")}finally{x(!1)}},ue=async()=>{B(!0);try{const Fe=await IM(p);A(Fe)}catch{A([])}finally{B(!1)}},je=async Fe=>{const nt=q.current+1;q.current=nt,be(!0),xe(null);try{const Nt=await DM(Fe,void 0,10,p);if(q.current!==nt)return;ie(Nt)}catch(Nt){if(q.current!==nt)return;xe(Re(Nt)||u("git.failedToLoadRemoteCommits","Failed to load remote commits")),ie([])}finally{q.current===nt&&be(!1)}},$e=Yi(),Ce=async Fe=>{if(Fe.preventDefault(),!(!g.trim()||!S.trim())){w("add");try{await vM(g.trim(),S.trim(),p),m(u("git.remoteAdded","Remote '{{name}}' added successfully",{name:g}),"success"),j(""),C(""),$(!1),await ot()}catch(nt){m(Re(nt)||u("git.failedToAddRemote","Failed to add remote"),"error")}finally{w(null)}}},We=async Fe=>{if(await $e.confirm({title:u("git.removeRemoteTitle","Remove Remote"),message:u("git.removeRemoteMessage","Are you sure you want to remove remote '{{name}}'?",{name:Fe}),danger:!0})){w(`remove-${Fe}`);try{await xM(Fe,p),m(u("git.remoteRemoved","Remote '{{name}}' removed",{name:Fe}),"success"),await ot()}catch(Nt){m(Re(Nt)||u("git.failedToRemoveRemote","Failed to remove remote"),"error")}finally{w(null)}}},ke=async Fe=>{if(_.trim()){w(`rename-${Fe}`);try{await yM(Fe,_.trim(),p),m(u("git.remoteRenamed","Remote renamed to '{{name}}'",{name:_.trim()}),"success"),F(null),V(""),await ot()}catch(nt){m(Re(nt)||u("git.failedToRenameRemote","Failed to rename remote"),"error")}finally{w(null)}}},Ee=async Fe=>{if(M.trim()){w(`url-${Fe}`);try{await kM(Fe,M.trim(),p),m(u("git.remoteUrlUpdated","Remote URL updated"),"success"),F(null),D(""),await ot()}catch(nt){m(Re(nt)||u("git.failedToUpdateRemoteUrl","Failed to update remote URL"),"error")}finally{w(null)}}},Ze=a.useCallback(async(Fe,nt)=>{if(nt==="ahead"){if(De===Fe){He(null),pe(null);return}He(Fe),pe(null),me(!0);try{const Nt=await Ud(Fe);pe(Nt)}catch{pe(null)}finally{me(!1)}}else{if(se===Fe){z(null),he(null);return}z(Fe),he(null),ye(!0);try{const Nt=await Ud(Fe);he(Nt)}catch{he(null)}finally{ye(!1)}}},[De,se]),Ke=Fe=>{F(`url-${Fe.name}`),D(Fe.pushUrl||Fe.fetchUrl)},dt=Fe=>{F(`name-${Fe.name}`),V(Fe.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:u("git.sectionRemotes","Remotes")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>$(!N),disabled:k!==null,title:N?u("git.cancel","Cancel"):u("git.addRemote","Add Remote"),children:N?t.jsx(Fn,{size:14}):t.jsx(ys,{size:14})})]}),N&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ce,children:[t.jsx("input",{type:"text",placeholder:u("git.remoteName","Remote name"),value:g,onChange:Fe=>j(Fe.target.value),disabled:k==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:u("git.repositoryUrl","Repository URL"),value:S,onChange:Fe=>C(Fe.target.value),disabled:k==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!g.trim()||!S.trim()||k==="add",children:[k==="add"?t.jsx(Et,{size:12,className:"spin"}):t.jsx(ys,{size:12}),u("git.add","Add")]})]}),v?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Et,{size:16,className:"spin"}),u("git.loading","Loading...")]}):b.length===0?t.jsx("div",{className:"gm-empty",children:u("git.noRemotes","No remotes")}):b.map(Fe=>t.jsxs("div",{className:`gm-remote-selector-item${P===Fe.name?" selected":""}`,onClick:()=>Z(Fe.name),role:"button",tabIndex:0,onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&(nt.preventDefault(),Z(Fe.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:Fe.name}),Fe.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:u("git.defaultBadge","default")})]}),t.jsx("span",{className:"gm-remote-selector-host",title:Fe.fetchUrl,children:f(Fe.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:nt=>{nt.stopPropagation(),We(Fe.name)},disabled:k!==null,title:u("git.removeRemote","Remove remote"),children:t.jsx(as,{size:14})})]},Fe.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[P&&ce?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:P}),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(Ma,{size:14}),u("git.commitsToPush","{{count}} to push",{count:e.ahead})]}),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(hr,{size:14}),u("git.commitsToPull","{{count}} to pull",{count:e.behind})]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||v,children:[n==="fetch"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(xs,{size:14}),u("git.fetch","Fetch")]}),t.jsxs("div",{className:"gm-pull-split",ref:O,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{L(!1),r({rebase:!1})},disabled:n!==null||v,children:[n==="pull"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(ai,{size:14}),u("git.pull","Pull")]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>L(Fe=>!Fe),disabled:n!==null||v,"aria-label":u("git.pullOptions","Pull options"),"aria-haspopup":"menu","aria-expanded":R,children:t.jsx(Ln,{size:14})}),R?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":u("git.pullOptionsMenu","Pull options menu"),children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{L(!1),r({rebase:!1})},children:u("git.pull","Pull")}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{L(!1),r({rebase:!0})},children:u("git.pullRebase","Pull --rebase")})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||v,children:[n==="push"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(Ma,{size:14}),u("git.push","Push")]}),t.jsxs("button",{className:"btn btn-primary",onClick:l,disabled:n!==null||v,title:u("git.syncOriginTitle","Pull --rebase from origin, then push current branch"),"data-testid":"remotes-sync-origin-btn",children:[n==="sync"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(rc,{size:14}),u("git.sync","Sync")]}),e?.integrationBranch&&t.jsxs("button",{className:"btn gm-sync-integration-btn",onClick:d,disabled:c,title:e.isOnIntegrationBranch===!1?u("git.notOnIntegrationBranchBtn","Not on integration branch ({{branch}})",{branch:e.integrationBranch}):u("git.syncLocalTipTitle","Sync working tree to local integration tip (same as banner Pull)"),"data-testid":"remotes-sync-integration-tip-btn",children:[n==="sync-integration"?t.jsx(Et,{size:14,className:"spin"}):t.jsx(rc,{size:14}),u("git.syncLocalTip","Sync local tip")]})]})]}),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:u("git.fetchLabel","Fetch:")}),E===`url-${P}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:M,onChange:Fe=>D(Fe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ee(P),disabled:k===`url-${P}`,children:k===`url-${P}`?t.jsx(Et,{size:12,className:"spin"}):t.jsx(Qs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{F(null),D("")},title:u("git.cancel","Cancel"),children:t.jsx(Fn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:ce.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:ce.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>h(ce.fetchUrl,u("git.fetchUrlLabel","fetch URL")),title:u("git.copyFetchUrl","Copy fetch URL"),children:t.jsx(Pa,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ke(ce),disabled:k!==null,title:u("git.editRemoteUrl","Edit remote URL"),children:t.jsx(Si,{size:14})})]})]})]}),ce.pushUrl&&ce.pushUrl!==ce.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:u("git.pushLabel","Push:")}),t.jsx("span",{className:"gm-url-value",title:ce.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:ce.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>h(ce.pushUrl,u("git.pushUrlLabel","push URL")),title:u("git.copyPushUrl","Copy push URL"),children:t.jsx(Pa,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:E===`name-${P}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:_,onChange:Fe=>V(Fe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>ke(P),disabled:k===`rename-${P}`,children:k===`rename-${P}`?t.jsx(Et,{size:12,className:"spin"}):t.jsx(Qs,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{F(null),V("")},title:u("git.cancel","Cancel"),children:t.jsx(Fn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>dt(ce),disabled:k!==null,title:u("git.editRemoteName","Edit remote name"),children:t.jsx(Si,{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(Ma,{size:14}),u("git.commitsToPushHeader","Commits to Push ({{count}})",{count:e.ahead})]})}),de?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Et,{size:14,className:"spin"}),u("git.loading","Loading...")]}):J.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:J.map(Fe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ze(Fe.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&(nt.preventDefault(),Ze(Fe.hash,"ahead"))},title:u("git.clickToViewDiff","Click to view diff"),children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Fe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Fe.message,children:Fe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Fe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:sl(Fe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:De===Fe.hash?t.jsx(Ln,{size:14}):t.jsx(ls,{size:14})})]}),De===Fe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:te?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),u("git.loadingDiff","Loading diff...")]}):qe?t.jsxs(t.Fragment,{children:[(Fe.body||Fe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:Fe.body||Fe.message}),qe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:qe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:qe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:u("git.failedToLoadDiff","Failed to load diff")})})]},Fe.hash))}):t.jsx("div",{className:"gm-empty",children:u("git.noAheadCommitsFound","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(Ak,{size:14}),u("git.recentCommitsOnRemote","Recent commits on {{remote}}",{remote:P})]})}),le?t.jsxs("div",{className:"gm-loading",children:[t.jsx(Et,{size:14,className:"spin"}),u("git.loadingCommits","Loading commits...")]}):Le?t.jsxs("div",{className:"gm-error",children:[t.jsx(oi,{size:14}),Le]}):T.length===0?t.jsx("div",{className:"gm-empty",children:u("git.noCommitsOnRemote","No commits found on {{remote}}. Try fetching first.",{remote:P})}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:T.map(Fe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ze(Fe.hash,"remote"),role:"button",tabIndex:0,onKeyDown:nt=>{(nt.key==="Enter"||nt.key===" ")&&(nt.preventDefault(),Ze(Fe.hash,"remote"))},title:u("git.clickToViewDiff","Click to view diff"),children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Fe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Fe.message,children:Fe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Fe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:sl(Fe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:se===Fe.hash?t.jsx(Ln,{size:14}):t.jsx(ls,{size:14})})]}),se===Fe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:X?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(Et,{size:16,className:"spin"}),u("git.loadingDiff","Loading diff...")]}):Y?t.jsxs(t.Fragment,{children:[(Fe.body||Fe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:Fe.body||Fe.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:u("git.failedToLoadDiff","Failed to load diff")})})]},Fe.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:u("git.selectRemoteToViewDetails","Select a remote to view details")}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const YU=36e5,XU=3e5,ah=[{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 QU(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 ZU(e){return typeof e!="number"||!Number.isFinite(e)?YU:Math.max(XU,Math.round(e))}function $K(e){if(ah.some(s=>s.value===e))return[...ah];const n={value:e,label:`${QU(e)} (custom)`};return[...ah,n].sort((s,i)=>s.value-i.value)}const e8=4,t8=5*6e4;function n8(e){const n=ZU(e?.heartbeatIntervalMs);return Math.max(n*e8,t8)}function gy(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),i=n%60;return s>0&&i>0?`${s}h ${i}m`:s>0?`${s}h`:`${i}m`}function s8(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 i8(e){const s=e.metadata?.heartbeatTimerRepair;if(!s||typeof s!="object")return{};const i=s;return{repairedAt:typeof i.repairedAt=="string"?i.repairedAt:void 0,staleAtRepair:typeof i.staleAtRepair=="boolean"?i.staleAtRepair:void 0,staleRepairReason:typeof i.staleRepairReason=="string"?i.staleRepairReason:void 0}}function a8(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=s8(e),d=l||o?.enabled!==!1;if(n==="error")return{label:i??"Error",icon:t.jsx(Ci,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(ia,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ci,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!d)return{label:"Heartbeat Disabled",icon:t.jsx(ia,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Is,{size:14}),color:"var(--text-muted)",stateDerived:!1};const c=i8(e);if(c.staleAtRepair&&c.repairedAt){const u=Date.parse(c.repairedAt),f=Date.parse(s);if(Number.isFinite(u)&&Number.isFinite(f)&&f<u)return{label:"Unresponsive",icon:t.jsx(Ci,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:c.staleRepairReason??"Heartbeat scheduler repaired a missing timer; waiting for recovery heartbeat"}}const m=new Date(s).getTime(),p=Date.now()-m,h=n8(o);if(p>h){const u=`No heartbeat for ${gy(p)} (threshold: ${gy(h)})`;return{label:"Unresponsive",icon:t.jsx(Ci,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:u}}return{label:"Healthy",icon:t.jsx(B0,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function ru({agent:e,size:n=36,className:s}){const[i,r]=a.useState(!1);a.useEffect(()=>{r(!1)},[e.imageUrl]);const o=a.useMemo(()=>{if(!e.imageUrl)return;const l=encodeURIComponent(e.updatedAt??""),d=e.imageUrl.includes("?")?"&":"?";return`${e.imageUrl}${d}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&&!i?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(Is,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const r8="https://github.com/Runfusion/Fusion/issues/new";function o8(e,n){const s=`[Agent Error] ${n.surface}${n.agentName?` - ${n.agentName}`:""}`,i=["## 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:i.join(`
|
|
792
792
|
`)});return`${r8}?${r.toString()}`}function l8({open:e,onClose:n,errorText:s,issueContext:i}){const[r,o]=a.useState(!1),{t:l}=st("app"),d=a.useMemo(()=>o8(s,i),[s,i]);return e?t.jsx("div",{className:"modal-overlay open",onClick:c=>c.target===c.currentTarget&&n(),role:"dialog","aria-modal":"true","aria-label":l("agentError.dialogLabel","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(oi,{size:16}),l("agentError.title","Agent Error Details")]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":l("common.close","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?l("agentError.copiedLabel","Copied error to clipboard"):l("agentError.copyLabel","Copy error to clipboard"),children:[r?t.jsx(Qs,{size:14}):t.jsx(Pa,{size:14}),r?l("agentError.copied","Copied"):l("agentError.copy","Copy")]}),t.jsxs("a",{className:"btn btn-sm btn-warning",href:d,target:"_blank",rel:"noreferrer",onClick:c=>{c.preventDefault(),window.open(d,"_blank","noopener,noreferrer")},children:[t.jsx(Vo,{size:14}),l("agentError.reportOnGithub","Report on GitHub")]})]})]})}):null}function c8({errorText:e,issueContext:n,summaryPrefix:s="Error"}){const[i,r]=a.useState(!1),{t:o}=st("app");return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"agent-error-indicator",onClick:()=>r(!0),"aria-label":o("agentError.openDetails","Open error details"),children:[t.jsx(oi,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(l8,{open:i,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const by=[{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 d8({isOpen:e,onClose:n,addToast:s,projectId:i}){const{t:r}=st("app"),[o,l]=a.useState([]),[d,c]=a.useState(!1),[m,p]=a.useState(!1),[h,u]=a.useState(""),[f,b]=a.useState("custom"),[y,v]=a.useState("all"),[x,k]=a.useState(()=>{if(typeof window>"u")return"list";const T=cs("fn-agent-view",i);return T==="board"||T==="list"?T:"list"});a.useEffect(()=>{const T=cs("fn-agent-view",i);if(T==="board"||T==="list"){k(T);return}k("list")},[i]),a.useEffect(()=>{_s("fn-agent-view",x,i)},[i,x]);const[w,g]=a.useState(null),j=a.useRef(null),[S,C]=a.useState(new Set),[E,F]=a.useState(new Map),{confirm:M}=Yi(),D=a.useMemo(()=>E.size===0?o:o.map(T=>{const ie=E.get(T.id);return ie?{...T,state:ie}:T}),[o,E]),_=a.useMemo(()=>y!=="all"?D:[...D].sort((T,ie)=>{const le=T.state==="paused"?1:0,be=ie.state==="paused"?1:0;return le!==be?le-be:(ie.updatedAt??"").localeCompare(T.updatedAt??"")}),[D,y]),V=a.useRef(0),N=a.useCallback(async(T=!1)=>{const ie=++V.current;c(!0);try{const le=y!=="all"?{state:y}:void 0,be=T?await br(le,i,{forceFresh:!0}):await br(le,i);if(ie!==V.current)return;l(be)}catch(le){s(r("agents.loadError","Failed to load agents: {{error}}",{error:Re(le)}),"error")}finally{ie===V.current&&c(!1)}},[y,s,i]);a.useEffect(()=>{e&&N()},[e,N]),a.useEffect(()=>{if(!e)return;const T=setInterval(()=>{N()},3e4);return()=>{clearInterval(T)}},[e,N]);const $=async()=>{if(h.trim())try{await WA({name:h.trim(),role:f},i),s(r("agents.createSuccess",'Agent "{{name}}" created',{name:h}),"success"),u(""),p(!1),N(!0)}catch(T){s(r("agents.createError","Failed to create agent: {{error}}",{error:Re(T)}),"error")}},R=async(T,ie)=>{if(!S.has(T)){C(le=>new Set(le).add(T)),F(le=>{const be=new Map(le);return be.set(T,ie),be});try{await KA(T,ie,i),s(r("agents.stateUpdateSuccess","Agent state updated to {{state}}",{state:ie}),"success"),await N(!0),F(le=>{const be=new Map(le);return be.delete(T),be})}catch(le){F(be=>{const Le=new Map(be);return Le.delete(T),Le}),s(r("agents.stateUpdateError","Failed to update state: {{error}}",{error:Re(le)}),"error")}finally{C(le=>{const be=new Set(le);return be.delete(T),be})}}},L=async(T,ie)=>{if(await M({title:r("agents.deleteTitle","Delete Agent"),message:r("agents.deleteMessage",'Delete agent "{{name}}"? This cannot be undone.',{name:ie}),danger:!0}))try{await JA(T,i),s(r("agents.deleteSuccess",'Agent "{{name}}" deleted',{name:ie}),"success"),N(!0)}catch(be){s(r("agents.deleteError","Failed to delete agent: {{error}}",{error:Re(be)}),"error")}},O=async(T,ie)=>{const le=o.find(be=>be.id===T);if(le){if(le.role===ie){g(null);return}try{await GA(T,{role:ie},i),s(r("agents.roleUpdateSuccess","Agent role updated to {{role}}",{role:de(ie)}),"success"),g(null),N(!0)}catch(be){s(r("agents.roleUpdateError","Failed to update role: {{error}}",{error:Re(be)}),"error")}}},J=(T,ie)=>{T.key==="Escape"&&g(null)},A={triage:{key:"agents.roleTriage",defaultValue:"Triage"},executor:{key:"agents.roleExecutor",defaultValue:"Executor"},reviewer:{key:"agents.roleReviewer",defaultValue:"Reviewer"},merger:{key:"agents.roleMerger",defaultValue:"Merger"},scheduler:{key:"agents.roleScheduler",defaultValue:"Scheduler"},engineer:{key:"agents.roleEngineer",defaultValue:"Engineer"},custom:{key:"agents.roleCustom",defaultValue:"Custom"}},de=T=>{const ie=A[T];return ie?r(ie.key,ie.defaultValue):T},B=T=>a8(T),P=T=>T.color==="var(--state-active-text)"?"active":T.color==="var(--state-paused-text)"?"paused":T.color==="var(--state-error-text)"?"error":"muted",Z=(T,ie)=>T.state==="error"?{title:void 0,label:r("agents.healthError","Error")}:{title:ie.reason??ie.label,label:ie.stateDerived?null:ie.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>T.target===T.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Is,{size:20}),r("agents.modalTitle","Agents")]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${x==="board"?" active":""}`,onClick:()=>k("board"),title:r("agents.boardView","Board view"),"aria-label":r("agents.boardView","Board view"),"aria-pressed":x==="board",children:t.jsx(Wo,{size:16})}),t.jsx("button",{className:`view-toggle-btn${x==="list"?" active":""}`,onClick:()=>k("list"),title:r("agents.listView","List view"),"aria-label":r("agents.listView","List view"),"aria-pressed":x==="list",children:t.jsx(jh,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void N(),title:r("agents.refresh","Refresh"),disabled:d,children:t.jsx(xs,{size:16,className:d?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":r("agents.close","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(Ld,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:y,onChange:T=>v(T.target.value),"aria-label":r("agents.filterByState","Filter agents by state"),children:[t.jsx("option",{value:"all",children:r("agents.filterAll","All States")}),t.jsx("option",{value:"idle",children:r("agents.stateIdle","Idle")}),t.jsx("option",{value:"active",children:r("agents.stateActive","Active")}),t.jsx("option",{value:"running",children:r("agents.stateRunning","Running")}),t.jsx("option",{value:"paused",children:r("agents.statePaused","Paused")}),t.jsx("option",{value:"error",children:r("agents.stateError","Error")})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>p(!m),children:[t.jsx(ys,{size:16}),m?r("agents.cancel","Cancel"):r("agents.newAgent","New Agent")]})]}),m&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:r("agents.namePlaceholder","Agent name..."),value:h,onChange:T=>u(T.target.value),onKeyDown:T=>T.key==="Enter"&&$(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:T=>b(T.target.value),children:by.map(T=>t.jsxs("option",{value:T.value,children:[T.icon," ",de(T.value)]},T.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void $(),children:r("agents.create","Create")})]}),t.jsx("div",{className:x==="board"?"agent-board":"agent-list",children:_.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Is,{size:48,opacity:.3}),t.jsx("p",{children:r("agents.emptyTitle","No agents found")}),t.jsx("p",{className:"text-secondary",children:r("agents.emptySubtitle","Create an agent to get started")})]}):x==="board"?_.map(T=>{const ie=B(T),le=Z(T,ie),be=P(ie);return t.jsxs("div",{className:"agent-board-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(ru,{agent:T,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":T.state,children:T.state}),t.jsx("span",{className:"agent-board-health","data-health":be,title:le.title,children:ie.icon})]}),t.jsx("div",{className:"agent-board-name",title:T.name,children:T.name}),t.jsx("div",{className:"agent-board-id",children:T.id}),t.jsxs("div",{className:"agent-board-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"active"),disabled:S.has(T.id),title:r("agents.activate","Activate"),children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,T.name),title:r("agents.delete","Delete"),children:t.jsx(as,{size:14})})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.pause","Pause"),children:t.jsx(ia,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.stop","Stop"),children:t.jsx(Ea,{size:14})})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"active"),disabled:S.has(T.id),title:r("agents.resume","Resume"),children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,T.name),title:r("agents.delete","Delete"),children:t.jsx(as,{size:14})})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.pause","Pause"),children:t.jsx(ia,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.stop","Stop"),children:t.jsx(Ea,{size:14})})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"active"),disabled:S.has(T.id),title:r("agents.retry","Retry"),children:t.jsx(Ds,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.stop","Stop"),children:t.jsx(Ea,{size:14})})]})]})]},T.id)}):_.map(T=>{const ie=B(T),le=Z(T,ie),be=P(ie);return t.jsxs("div",{className:"agent-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[w===T.id?t.jsx("select",{ref:j,className:"select agent-role-select",value:T.role,onChange:Le=>void O(T.id,Le.target.value),onKeyDown:Le=>J(Le,T.id),onBlur:()=>g(null),autoFocus:!0,children:by.map(Le=>t.jsxs("option",{value:Le.value,children:[Le.icon," ",de(Le.value)]},Le.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>g(T.id),title:r("agents.changeRole","Click to change role"),role:"button",tabIndex:0,onKeyDown:Le=>{(Le.key==="Enter"||Le.key===" ")&&g(T.id)},children:t.jsx(ru,{agent:T,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:T.name}),t.jsx("span",{className:"agent-id text-secondary",children:T.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":T.state,children:T.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":be,title:le.title,children:[ie.icon,le.label?` ${le.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:de(T.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[T.state==="error"&&T.lastError?t.jsx(c8,{errorText:T.lastError,issueContext:{surface:"AgentListModal list",agentId:T.id,agentName:T.name,agentState:T.state,taskId:T.taskId}}):null,T.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:r("agents.workingOn","Working on:")}),t.jsx("span",{className:"badge",children:T.taskId})]}),T.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:r("agents.lastHeartbeat","Last heartbeat:")}),t.jsx("span",{children:new Date(T.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"active"),disabled:S.has(T.id),title:r("agents.activate","Activate"),children:[t.jsx(Ds,{size:14})," ",r("agents.start","Start")]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,T.name),title:r("agents.delete","Delete"),children:[t.jsx(as,{size:14})," ",r("agents.delete","Delete")]})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.pause","Pause"),children:[t.jsx(ia,{size:14})," ",r("agents.pause","Pause")]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.stop","Stop"),children:[t.jsx(Ea,{size:14})," ",r("agents.stop","Stop")]})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"active"),disabled:S.has(T.id),title:r("agents.resume","Resume"),children:[t.jsx(Ds,{size:14})," ",r("agents.resume","Resume")]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void L(T.id,T.name),title:r("agents.delete","Delete"),children:[t.jsx(as,{size:14})," ",r("agents.delete","Delete")]})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.pause","Pause"),children:[t.jsx(ia,{size:14})," ",r("agents.pause","Pause")]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.stop","Stop"),children:[t.jsx(Ea,{size:14})," ",r("agents.stop","Stop")]})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void R(T.id,"active"),disabled:S.has(T.id),title:r("agents.retry","Retry"),children:[t.jsx(Ds,{size:14})," ",r("agents.retry","Retry")]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void R(T.id,"paused"),disabled:S.has(T.id),title:r("agents.stop","Stop"),children:[t.jsx(Ea,{size:14})," ",r("agents.stop","Stop")]})]})]})]},T.id)})})]})]})}):null}function u8({authenticated:e,onToggled:n,compact:s=!1}){const{t:i}=st("app"),[r,o]=a.useState(null),[l,d]=a.useState(null),[c,m]=a.useState(null),p=a.useRef(!0);a.useEffect(()=>(p.current=!0,()=>{p.current=!1}),[]);const h=a.useCallback(async()=>{try{const k=await WE();return p.current&&o(k),k}catch(k){return p.current&&m({kind:"error",message:k instanceof Error?k.message:String(k)}),null}},[]);a.useEffect(()=>{h()},[h]);const u=a.useCallback(async()=>{d("testing"),m(null),await h(),p.current&&d(null)},[h]),f=a.useCallback(async k=>{d(k?"enabling":"disabling"),m(null);try{const w=await QE(k);p.current&&m({kind:w.enabled?"enabled":"disabled",restartRequired:w.restartRequired}),n?.(w.enabled),await h()}catch(w){p.current&&m({kind:"error",message:w instanceof Error?w.message:String(w)})}finally{p.current&&d(null)}},[n,h]),b=r?.binary.available??!1,y=r?.enabled??e,v=t.jsx("span",{className:"onboarding-provider-card__description",children:i("setup.claudeCli.description","Route AI calls through your locally-installed claude CLI. Uses your existing Claude subscription / quota instead of an API key.")}),x=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:u,disabled:l!==null,children:l==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:12,className:"animate-spin"}),i("setup.claudeCli.testing","Testing…")]}):i("setup.claudeCli.test","Test")}),y?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:l!==null,children:l==="disabling"?i("setup.claudeCli.disabling","Disabling…"):i("setup.claudeCli.disable","Disable")}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:l!==null||!b,title:b?void 0:i("setup.claudeCli.binaryNotFound","`claude` binary not detected on PATH — install Claude CLI first."),children:l==="enabling"?i("setup.claudeCli.enabling","Enabling…"):i("setup.claudeCli.enable","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(hs,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:i("setup.claudeCli.name","Anthropic — via Claude CLI")}),t.jsx(m8,{status:r,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:x})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:i("setup.claudeCli.details","Details")}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[v,t.jsx(vy,{status:r,authenticated:e}),c&&t.jsx(xy,{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(hs,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:i("setup.claudeCli.name","Anthropic — via Claude CLI")}),v,t.jsx(vy,{status:r,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:x}),c&&t.jsx(xy,{action:c})]})}function m8({status:e,authenticated:n}){const{t:s}=st("app"),i=e?.enabled??n,r=e?.binary.available??!1;return i?t.jsx("span",{className:"auth-status-badge authenticated",children:s("setup.claudeCli.active","✓ Active")}):!r&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:s("setup.claudeCli.notInstalled","✗ Not installed")}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:s("setup.claudeCli.notConnected","✗ Not connected")})}function vy({status:e,authenticated:n}){const{t:s}=st("app");if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(Et,{size:10,className:"animate-spin"})," ",s("setup.claudeCli.probing","Probing local CLI…")]});const{binary:i,enabled:r,extension:o,ready:l}=e;return i.available?r?o&&o.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ ",s("setup.claudeCli.extensionFailed","Extension load failed: {{reason}}",{reason:o.reason??o.status})]}):l||n?t.jsx("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:s("setup.claudeCli.connected","✓ Connected{{version}}",{version:i.version?` — ${i.version}`:""})}):t.jsx("small",{className:"settings-muted",children:s("setup.claudeCli.validating","Enabled. Validating…")}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",i.version?`(${i.version})`:""," ",s("setup.claudeCli.detectedPrompt","detected{{path}}. Click Enable to route AI calls through it.",{path:i.binaryPath?` at ${i.binaryPath}`:""})]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",i.reason??s("setup.claudeCli.binaryNotFoundPath","`claude` not found on PATH")]})}function xy({action:e}){const{t:n}=st("app");if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const s=e.kind==="enabled"?n("setup.claudeCli.enabledVerb","Enabled"):n("setup.claudeCli.disabledVerb","Disabled");return t.jsxs("p",{className:"onboarding-helper-text",children:[s,"."," ",e.kind==="enabled"?n("setup.claudeCli.enabledMessage","Claude-CLI-routed models are now visible in the model picker."):n("setup.claudeCli.disabledMessage","Claude-CLI-routed models are hidden from the model picker.")]})}function h8({authenticated:e,compact:n=!1,onToggled:s}){const{t:i}=st("app"),[r,o]=a.useState(null),[l,d]=a.useState(null),c=a.useRef(!0);a.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const m=a.useCallback(async()=>{try{const y=await YE();return c.current&&o(y),y}catch{return null}},[]);a.useEffect(()=>{m()},[m]);const p=a.useCallback(async y=>{d(y?"enabling":"disabling");try{const v=await eM(y);s?.(v.enabled),await m()}finally{c.current&&d(null)}},[s,m]),h=r?.enabled??e,u=r?.binary.available??!1,f=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{d("testing"),m().finally(()=>{c.current&&d(null)})},disabled:l!==null,children:l==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:12,className:"animate-spin"})," ",i("setup.cursorCli.testing","Testing…")]}):i("setup.cursorCli.test","Test")}),h?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void p(!1),disabled:l!==null,children:l==="disabling"?i("setup.cursorCli.disabling","Disabling…"):i("setup.cursorCli.disable","Disable")}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void p(!0),disabled:l!==null||!u,children:l==="enabling"?i("setup.cursorCli.enabling","Enabling…"):i("setup.cursorCli.enable","Enable")})]}),b=r?r.binary.available?h?i("setup.cursorCli.connected","Connected{{version}}",{version:r.binary.version?` — ${r.binary.version}`:""}):i("setup.cursorCli.detectedPrompt","Detected. Click Enable to route calls through Cursor CLI."):r.binary.reason??i("setup.cursorCli.binaryNotFound","`cursor-agent` not found on PATH"):i("setup.cursorCli.probing","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(hs,{provider:"cursor-cli",size:"sm"}),t.jsx("strong",{children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:`auth-status-badge ${h?"authenticated":"not-authenticated"}`,children:h?i("setup.cursorCli.active","✓ Active"):i("setup.cursorCli.notConnected","✗ Not connected")})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:f})]}),t.jsx("small",{className:"settings-muted",children:b})]}):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(hs,{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:i("setup.cursorCli.description","Route AI calls through your local Cursor agent runtime.")}),t.jsx("small",{className:"settings-muted",children:b})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:f})]})}function p8({authenticated:e,onToggled:n,compact:s=!1}){const{t:i}=st("app"),[r,o]=a.useState(null),[l,d]=a.useState(null),c=a.useRef(!0);a.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const m=a.useCallback(async()=>{const v=await XE();return c.current&&o(v),v},[]);a.useEffect(()=>{m()},[m]);const p=a.useCallback(async v=>{d(v?"enabling":"disabling");try{const x=await tM(v);n?.(x.enabled),await m()}finally{c.current&&d(null)}},[n,m]),h=a.useCallback(async()=>{d("testing");try{await m()}finally{c.current&&d(null)}},[m]),u=r?.enabled??e,f=r?.server.available??!1,b=r?r.server.available?i("providers.llamaCpp.reachable","Server reachable at {{url}}",{url:r.server.url}):i("providers.llamaCpp.unavailable","Server unavailable: {{reason}}",{reason:r.server.reason??"not reachable"}):i("providers.llamaCpp.probing","Probing llama.cpp server…"),y=t.jsxs("div",{className:"auth-provider-cli-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void h(),disabled:l!==null,children:l==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:12,className:"animate-spin"}),i("providers.llamaCpp.testing","Testing…")]}):i("providers.llamaCpp.test","Test")}),u?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void p(!1),disabled:l!==null,children:l==="disabling"?i("providers.llamaCpp.disabling","Disabling…"):i("providers.llamaCpp.disable","Disable")}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void p(!0),disabled:l!==null||!f,children:l==="enabling"?i("providers.llamaCpp.enabling","Enabling…"):i("providers.llamaCpp.enable","Enable")})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli llama-cpp-provider-card llama-cpp-provider-card--compact${u?" 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(hs,{provider:"llama-cpp",size:"sm"}),t.jsx("strong",{children:i("providers.llamaCpp.title","llama.cpp — via HTTP server")})]}),y]}),t.jsx("small",{className:`auth-hint llama-cpp-status${r?.ready?" llama-cpp-status--ok":""}`,children:b})]}):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(hs,{provider:"llama-cpp",size:"md"}),t.jsx("strong",{children:i("providers.llamaCpp.title","llama.cpp — via HTTP server")})]}),t.jsx("small",{className:`llama-cpp-status${r?.ready?" llama-cpp-status--ok":""}`,children:b}),y]})}function f8(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),i=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(i);if(l?.[1])return l[1];const d=e.match(r);return d?.[1]?d[1]:null}function rh({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=f8(e),o=a.useRef(null),l=a.useCallback(()=>{i(!0),setTimeout(()=>i(!1),2e3)},[]),d=a.useCallback(async()=>{const c=r??e;try{await navigator.clipboard.writeText(c),l()}catch{}},[r,e,l]);return a.useEffect(()=>{const c=o.current===null&&r!==null;if(o.current=r,!c)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((c,m,p)=>t.jsxs("span",{children:[c,m<p.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:d,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(Qs,{size:12}):t.jsx(Pa,{size:12})})]})]},m))}):e})}function g8({value:e,onChange:n,onSubmit:s,prompt:i,placeholder:r,helpText:o,disabled:l=!1,submitLabel:d="Submit code","data-testid":c}){const m=a.useRef(null),p=a.useRef(null),[h,u]=a.useState(!1),f=a.useCallback(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return!1;const v=window.matchMedia("(max-width: 768px)").matches,x=window.matchMedia("(pointer: coarse)").matches;return v||x},[]),b=a.useCallback(()=>typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",[]),y=a.useCallback(()=>{if(!f())return;const v=p.current??m.current;if(!v||typeof v.scrollIntoView!="function")return;const x=b();requestAnimationFrame(()=>{v.scrollIntoView({block:"center",behavior:x,inline:"nearest"}),window.setTimeout(()=>{v.scrollIntoView({block:"center",behavior:x,inline:"nearest"})},120)})},[b,f]);return a.useEffect(()=>{if(!h||!f())return;y();const v=window.visualViewport;if(!v)return;const x=()=>{document.activeElement===p.current&&y()};return v.addEventListener("resize",x),v.addEventListener("scroll",x),()=>{v.removeEventListener("resize",x),v.removeEventListener("scroll",x)}},[h,y,f]),t.jsxs("div",{ref:m,className:"oauth-manual-code","data-testid":c,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:i}),t.jsx("textarea",{ref:p,className:"form-input oauth-manual-code__input",value:e,onChange:v=>n(v.target.value),onFocus:()=>{u(!0),y()},onBlur:()=>u(!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:d})}),o&&t.jsx("p",{className:"oauth-manual-code__help",children:o})]})}const b8=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"]),v8=/^[a-z][a-z0-9-]*$/,yy=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function ky(){return{id:"",name:"",reasoning:!1}}function x8({initialConfig:e,onSave:n,onCancel:s,saving:i=!1,error:r}){const{t:o}=st("app"),l=!!e,[d,c]=a.useState(e?.id??""),[m,p]=a.useState(e?.name??""),[h,u]=a.useState(e?.baseUrl??""),[f,b]=a.useState(e?.api??"openai-completions"),[y,v]=a.useState(e?.apiKey??""),[x,k]=a.useState(e?.models?.length?e.models:[ky()]),[w,g]=a.useState(null),[j,S]=a.useState(!1),[C,E]=a.useState(null),F=x.length>1,M=a.useMemo(()=>w??r??null,[w,r]);function D(L,O){k(J=>J.map((A,de)=>de===L?{...A,...O}:A))}function _(L){k(O=>O.length<=1?O:O.filter((J,A)=>A!==L))}const V=f==="anthropic-messages"?"anthropic-compatible":f==="google-generative-ai"?"google-generative-ai":"openai-compatible",N=a.useCallback(async()=>{const L=h.trim();if(!L){E(o("providers.detectError.urlRequired","Base URL is required to detect models."));return}S(!0),E(null);try{const O=await aM({baseUrl:L,apiKey:y.trim()||void 0,apiType:V});if(O.models.length===0){E(o("providers.detectError.noModels","No models found. The provider may require an API key."));return}const J=new Set(x.map(de=>de.id.trim())),A=O.models.filter(de=>!J.has(de.id.trim())).map(de=>({id:de.id,name:de.name||de.id,reasoning:!!de.reasoning,contextWindow:de.contextWindow,maxTokens:de.maxTokens}));A.length>0?k(de=>[...de.filter(P=>P.id.trim().length>0),...A]):E(o("providers.detectError.allDuplicate","All discovered models are already in the list."))}catch(O){E(O instanceof Error?O.message:o("providers.detectError.failed","Failed to detect models"))}finally{S(!1)}},[h,y,V,x,o]);function $(){if(!d.trim())return o("providers.validation.idRequired","Provider ID is required.");if(!v8.test(d.trim()))return o("providers.validation.idKebabCase","Provider ID must be kebab-case.");if(!l&&b8.has(d.trim()))return o("providers.validation.idConflict","Provider ID conflicts with a built-in provider.");if(!h.trim())return o("providers.validation.urlRequired","Base URL is required.");try{const L=new URL(h.trim());if(L.protocol!=="http:"&&L.protocol!=="https:")return o("providers.validation.urlProtocol","Base URL must use http or https.")}catch{return o("providers.validation.urlValid","Base URL must be a valid URL.")}return yy.includes(f)?x.length===0?o("providers.validation.modelRequired","At least one model is required."):x.some(L=>!L.id?.trim())?o("providers.validation.modelId","Each model must have a model ID."):null:o("providers.validation.apiTypeRequired","API type is required.")}async function R(L){L.preventDefault();const O=$();g(O),!O&&await n({id:d.trim(),name:m.trim()||void 0,baseUrl:h.trim(),api:f,apiKey:y.trim()||void 0,models:x.map(J=>({id:J.id.trim(),name:J.name?.trim()||void 0,reasoning:!!J.reasoning,contextWindow:J.contextWindow,maxTokens:J.maxTokens}))})}return t.jsxs("form",{onSubmit:R,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:o("providers.fields.id","Provider ID")}),t.jsx("input",{id:"custom-provider-id",className:"input",value:d,onChange:L=>c(L.target.value),disabled:l||i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:o("providers.fields.name","Display Name")}),t.jsx("input",{id:"custom-provider-name",className:"input",value:m,onChange:L=>p(L.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:o("providers.fields.baseUrl","Base URL")}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:h,onChange:L=>u(L.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:o("providers.fields.apiType","API Type")}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:L=>b(L.target.value),disabled:i,children:yy.map(L=>t.jsx("option",{value:L,children:L},L))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:o("providers.fields.apiKey","API Key")}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:o("providers.placeholders.apiKey","sk-..., MY_API_KEY, or !command"),value:y,onChange:L=>v(L.target.value),disabled:i})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:o("providers.fields.models","Models")}),t.jsx("div",{className:"custom-provider-form__models",children:x.map((L,O)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`${o("providers.fields.modelId","Model ID")} ${O+1}`,placeholder:o("providers.fields.modelId","Model ID"),value:L.id,onChange:J=>D(O,{id:J.target.value}),disabled:i}),t.jsx("input",{className:"input","aria-label":`${o("providers.fields.modelNameLabel","Model name")} ${O+1}`,placeholder:o("providers.fields.modelName","Display name"),value:L.name??"",onChange:J=>D(O,{name:J.target.value}),disabled:i}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!L.reasoning,onChange:J=>D(O,{reasoning:J.target.checked}),disabled:i}),o("providers.fields.reasoning","Reasoning")]}),t.jsx("input",{className:"input","aria-label":`${o("providers.fields.contextWindow","Context window")} ${O+1}`,placeholder:o("providers.fields.contextWindow","Context window"),type:"number",value:L.contextWindow??"",onChange:J=>D(O,{contextWindow:J.target.value?Number(J.target.value):void 0}),disabled:i}),t.jsx("input",{className:"input","aria-label":`${o("providers.fields.maxTokens","Max tokens")} ${O+1}`,placeholder:o("providers.fields.maxTokens","Max tokens"),type:"number",value:L.maxTokens??"",onChange:J=>D(O,{maxTokens:J.target.value?Number(J.target.value):void 0}),disabled:i}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>_(O),disabled:i||!F,"aria-label":o("providers.actions.removeModel","Remove model",{count:O+1}),children:"×"})]},`${O}-model`))}),t.jsxs("div",{className:"custom-provider-form__model-actions",style:{display:"flex",gap:"8px",alignItems:"center"},children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>k(L=>[...L,ky()]),disabled:i,children:o("providers.actions.addModel","+ Add model")}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void N(),disabled:i||j||!h.trim(),title:o("providers.actions.detectModelsTitle","Call the provider's /models endpoint to discover available models"),children:j?t.jsxs(t.Fragment,{children:[t.jsx(Et,{className:"spin",size:14})," ",o("providers.actions.detecting","Detecting…")]}):t.jsxs(t.Fragment,{children:[t.jsx(na,{size:14})," ",o("providers.actions.detectModels","Detect Models")]})})]}),C?t.jsx("div",{className:"form-error",style:{marginTop:"4px"},children:C}):null]}),M?t.jsx("div",{className:"form-error",children:M}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:i,children:o("actions.cancel","Cancel")}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:i,children:i?o("providers.actions.saving","Saving..."):o("providers.actions.save","Save Provider")})]})]})}async function wy(e){if(typeof navigator<"u"&&typeof window<"u"&&window.isSecureContext!==!1&&navigator.clipboard?.writeText)try{return await navigator.clipboard.writeText(e),!0}catch{}if(typeof document>"u"||!document.body)return!1;const n=document.createElement("textarea");n.value=e,n.setAttribute("readonly",""),n.style.position="fixed",n.style.left="-9999px",n.style.top="0",n.style.opacity="0",n.style.pointerEvents="none",document.body.appendChild(n);try{return n.focus(),n.select(),n.setSelectionRange(0,e.length),document.execCommand("copy")}catch{return!1}finally{n.remove()}}const y8=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function k8(e){return!y8.has(e)}function jy(e){return e.filter(n=>k8(n.id))}const UN={host:"web",activeProfileId:null,profiles:[]},HN=a.createContext({shellApi:null,state:UN,ready:!0,openConnectionManagerSignal:0});function w8({children:e}){const n=a.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,i]=a.useState(UN),[r,o]=a.useState(!n),[l,d]=a.useState(0);return a.useEffect(()=>{if(!n)return;let c=!1;n.getState().then(h=>{c||(i(h),o(!0))});const m=n.subscribe(h=>{i(h)}),p=()=>{d(h=>h+1)};return window.addEventListener("shell:open-connection-manager",p),()=>{c=!0,m(),window.removeEventListener("shell:open-connection-manager",p)}},[n]),t.jsx(HN.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function j8(){return a.useContext(HN)}const N8={host:"web",activeProfileId:null,profiles:[]};function S8(e){if(!e)return N8;const n=Array.isArray(e.profiles)?e.profiles.filter(i=>!!(i&&i.id&&i.serverUrl)):[],s=e.activeProfileId&&n.some(i=>i.id===e.activeProfileId)?e.activeProfileId:null;return{...e,activeProfileId:s,profiles:n}}function Df(e){return new Error(`${e} is only available in native shell mode`)}async function C8(e,n){if(!e)throw Df("Saving connection profiles");return e.saveProfile(n)}async function _8(e,n){if(!e)throw Df("Deleting connection profiles");await e.deleteProfile(n)}async function E8(e,n){if(!e)throw Df("Switching connection profiles");return e.setActiveProfile(n)}function VN(){const e=j8(),n=a.useMemo(()=>S8(e.state),[e.state]),s=a.useCallback(o=>C8(e.shellApi,o),[e.shellApi]),i=a.useCallback(o=>_8(e.shellApi,o),[e.shellApi]),r=a.useCallback(o=>E8(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:i,setActiveProfile:r}}const Yr="fusion_model_onboarding_state",il=[],al=[],ou=!1,lu=!1,rl={},M8=void 0,dr=["ai-setup","github","project-setup","first-task"],A8={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function Gi(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Yr);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?T8(n):null}catch{return null}}function T8(e){const n=e.postOnboardingDismissedAt??M8;return{...e,completedSteps:e.completedSteps??il,skippedSteps:e.skippedSteps??al,dismissed:e.dismissed??ou,completed:e.completed??lu,stepData:e.stepData??rl,...n?{postOnboardingDismissedAt:n}:{}}}function yd(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:il,skippedSteps:al,dismissed:ou,completed:lu,stepData:rl};try{localStorage.setItem(Yr,JSON.stringify(s))}catch{}return}try{const s=Gi(),i=new Date().toISOString(),r=n.completed??lu;let o=n.dismissed??ou;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??il,d=n.skippedSteps??s?.skippedSteps??al,c={...s?.stepData??rl};if(n.stepData)for(const[p,h]of Object.entries(n.stepData))h!==void 0&&(c[p]={...c[p]??{},...h});const m={currentStep:e,updatedAt:i,completedSteps:l,skippedSteps:d,dismissed:o,completed:r,stepData:c};localStorage.setItem(Yr,JSON.stringify(m))}catch{}}}function R8(e){if(!(typeof window>"u"))try{const n=Gi(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:il,skippedSteps:[e],dismissed:ou,completed:lu,stepData:rl};localStorage.setItem(Yr,JSON.stringify(o));return}const i=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:i,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(Yr,JSON.stringify(r))}catch{}}function Ny(){if(!(typeof window>"u"))try{const e=Gi(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:il,skippedSteps:al,dismissed:!1,completed:!0,stepData:rl};localStorage.setItem(Yr,JSON.stringify(s))}catch{}}function ol(){const e=Gi();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function P8(){if(!(typeof window>"u"))try{const e=Gi(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:il,skippedSteps:al,dismissed:!1,completed:!1,stepData:rl,postOnboardingDismissedAt:n};localStorage.setItem(Yr,JSON.stringify(s))}catch{}}function qN(){const e=Gi();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function I8(){const e=Gi();return!e||ol()?!1:e.currentStep!=="complete"}function D8(){const e=Gi();if(!e||ol()||e.currentStep==="complete")return null;const n=e.currentStep,s=A8[n]??O8(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function L8(){const e=Gi();return e?e.skippedSteps:al}function F8(e){const n=Gi();return!n||!n.stepData?null:n.stepData[e]??null}function O8(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const WN="fusion_onboarding_events",Sy="fusion_onboarding_session_id",$8=200,z8=50;function Zi(e,n={}){if(!(typeof window>"u"))try{const s=U8(),i=q8(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:B8()},o=V8([...s,r]);H8(o)}catch{}}function B8(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Sy);if(e)return e;const n=Cy();return sessionStorage.setItem(Sy,n),n}catch{return Cy()}}function Cy(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function U8(){try{const e=localStorage.getItem(WN);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(W8):[]}catch{return[]}}function H8(e){try{localStorage.setItem(WN,JSON.stringify(e))}catch{}}function V8(e){const n=[...e];for(;n.length>$8;)n.splice(0,z8);return n}function q8(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function W8(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 G8=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}))??[]});function K8(e){return{anthropic:{description:e("setup.providerDesc.anthropic","Claude models — strong at reasoning, analysis, and code")},openai:{description:e("setup.providerDesc.openai","GPT models — versatile for a wide range of tasks"),apiKeyInfo:{fieldLabel:e("setup.apiKeyLabel.openai","OpenAI API Key"),setupInstructions:e("setup.apiKeySetup.openai","Create an API key from your OpenAI dashboard under API keys."),dashboardUrl:"https://platform.openai.com/api-keys",inputPlaceholder:"sk-...",usageDescription:e("setup.apiKeyUsage.openai","Used for GPT models in task execution and planning")}},"openai-codex":{description:e("setup.providerDesc.openaiCodex","Codex models by OpenAI — optimized for coding tasks")},google:{description:e("setup.providerDesc.google","Gemini models — multimodal with strong reasoning")},gemini:{description:e("setup.providerDesc.gemini","Gemini models — multimodal with strong reasoning")},ollama:{description:e("setup.providerDesc.ollama","Run open-source models locally on your machine"),apiKeyInfo:{fieldLabel:e("setup.apiKeyLabel.ollama","Ollama Endpoint"),setupInstructions:e("setup.apiKeySetup.ollama","Enter your Ollama endpoint URL (for example http://localhost:11434)."),inputPlaceholder:"http://localhost:11434",usageDescription:e("setup.apiKeyUsage.ollama","Connects to your local Ollama instance")}},minimax:{description:e("setup.providerDesc.minimax","MiniMax models — cost-effective for high-volume usage"),apiKeyInfo:{fieldLabel:e("setup.apiKeyLabel.minimax","MiniMax API Key"),setupInstructions:e("setup.apiKeySetup.minimax","Generate an API key from the MiniMax platform developer console."),dashboardUrl:"https://platform.minimaxi.com/",inputPlaceholder:e("setup.apiKeyPlaceholder.minimax","Enter your MiniMax API key"),usageDescription:e("setup.apiKeyUsage.minimax","Used for MiniMax models in task execution")}},zai:{description:e("setup.providerDesc.zai","GLM models by Zhipu AI — strong multilingual support"),apiKeyInfo:{fieldLabel:e("setup.apiKeyLabel.zai","Zhipu AI API Key"),setupInstructions:e("setup.apiKeySetup.zai","Create an API key in the Zhipu AI open platform account settings."),dashboardUrl:"https://open.bigmodel.cn/",inputPlaceholder:e("setup.apiKeyPlaceholder.zai","Enter your Zhipu AI API key"),usageDescription:e("setup.apiKeyUsage.zai","Used for GLM models in task execution")}},kimi:{description:e("setup.providerDesc.kimi","Kimi by Moonshot AI — long-context capabilities")},moonshot:{description:e("setup.providerDesc.moonshot","Kimi by Moonshot AI — long-context capabilities")},"kimi-coding":{description:e("setup.providerDesc.kimiCoding","Kimi by Moonshot AI — long-context capabilities"),apiKeyInfo:{fieldLabel:e("setup.apiKeyLabel.kimiCoding","Kimi API Key"),setupInstructions:e("setup.apiKeySetup.kimiCoding","Create your API key in the Moonshot platform account settings."),dashboardUrl:"https://platform.moonshot.cn/",inputPlaceholder:e("setup.apiKeyPlaceholder.kimiCoding","Enter your Kimi API key"),usageDescription:e("setup.apiKeyUsage.kimiCoding","Used for Kimi/Moonshot AI models in task execution and planning")}},openrouter:{description:e("setup.providerDesc.openrouter","OpenRouter — route requests across multiple AI providers"),apiKeyInfo:{fieldLabel:e("setup.apiKeyLabel.openrouter","OpenRouter API Key"),setupInstructions:e("setup.apiKeySetup.openrouter","Create an API key from your OpenRouter account key management page."),dashboardUrl:"https://openrouter.ai/keys",inputPlaceholder:"sk-or-v1-...",usageDescription:e("setup.apiKeyUsage.openrouter","Routes to multiple AI model providers through a single key")}}}}const GN={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:"..."}},J8={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},_y={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"},Y8=e=>`After you sign in with ${e}, the browser will try to redirect to a localhost address that this dashboard can't reach. The redirect tab will look like it failed. Before that happens, copy the full URL from the browser address bar — you'll paste it back here to finish login. Continue?`;function hp(e){if(_y[e])return _y[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 oh=["anthropic","openai","google","gemini","ollama"],X8=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],Q8={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"},Z8={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function pp(e){return Q8[e]??e}function Ey(e){const n=pp(e),s=X8.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function My(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Ey(e.id),i=Ey(n.id);if(s!==i)return s-i;const r=pp(e.id),o=pp(n.id);if(r!==o)return r.localeCompare(o);const l=Z8[r];if(l){const c=l.indexOf(e.id),m=l.indexOf(n.id);if(c!==m)return(c===-1?Number.POSITIVE_INFINITY:c)-(m===-1?Number.POSITIVE_INFINITY:m)}const d=e.name.localeCompare(n.name);return d!==0?d:e.id.localeCompare(n.id)}function eH(e,n,s){const i=n.trim();if(!i)return s("setup.apiKeyRequired","API key is required");const r=GN[e]??J8;if(r.pattern.test(i))return null;const o=hp(e);return s("setup.apiKeyFormatError","{{providerName}} keys should follow this format: {{hint}} (e.g. {{example}})",{providerName:o,hint:r.hint,example:r.example})}function KN(e){return{fieldLabel:e("setup.apiKeyLabel.fallback","API Key"),setupInstructions:e("setup.apiKeySetup.fallback","Enter your API key for this provider."),inputPlaceholder:e("setup.apiKeyPlaceholder.fallback","Enter API key"),usageDescription:e("setup.apiKeyUsage.fallback","Used by Fusion to authenticate requests to this provider")}}function fp(e,n){const s={description:n("setup.providerDesc.fallback","AI provider — connect to start using AI models"),apiKeyInfo:KN(n)};return K8(n)[e]??s}function tH(e,n){return fp(e.id,n).apiKeyInfo??KN(n)}function nH({items:e}){const{t:n}=st("app");return e.some(i=>i.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:n("setup.readinessSummaryHeader","Setup Summary")}),e.map(i=>{const r=i.status==="connected"?"✓":i.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${i.status}`,"data-status":i.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:r}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:i.label}),i.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:i.detail})]})]},i.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:n("setup.readinessAllConnected","✓ All integrations connected")})})}function sH({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:d,onSave:c,onClear:m}){const{t:p}=st("app"),h=`onboarding-apikey-input-${e.id}`,u=i||!s.trim(),f=GN[e.id],b=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,y=t.jsxs(t.Fragment,{children:[f&&t.jsx("small",{className:"onboarding-apikey-hint",children:p("setup.apiKeyFormatHint","Format: {{hint}}",{hint: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:p("setup.getApiKeyLink","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:p("setup.apiKeySaved","✓ API key saved")})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>m(e.id),disabled:i,children:i?p("setup.removingKey","Removing…"):p("setup.removeKey","Remove Key")}),t.jsx(ea,{summary:p("setup.advancedSetupDetails","Advanced setup details"),children:y}),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:h,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:h,type:"password",className:b,placeholder:n.inputPlaceholder??p("setup.enterApiKey","Enter API key"),value:s,onChange:v=>d(e.id,v.target.value),onKeyDown:v=>{v.key==="Enter"&&c(e.id,s)},"data-testid":h}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>c(e.id,s),disabled:u,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?p("setup.savingKey","Saving…"):p("setup.saveKey","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(ea,{summary:p("setup.advancedSetupDetails","Advanced setup details"),children:y})]})}const iH=150;function aH({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:d}){const{t:c}=st("app"),{confirm:m}=Yi(),p=Gi(),h=p?.currentStep,u=h==="complete"?"ai-setup":dr.includes(h)?h:"ai-setup",f=p?.completedSteps??[],b=p?.skippedSteps??L8(),[y,v]=a.useState(!0),[x,k]=a.useState(u),[w,g]=a.useState(f),[j,S]=a.useState(b),[C,E]=a.useState(!1),[F,M]=a.useState(""),[D,_]=a.useState(!1),[V,N]=a.useState(null),[$,R]=a.useState(null),[L,O]=a.useState([]),[J,A]=a.useState(void 0),[de,B]=a.useState(!0),[P,Z]=a.useState(null),[T,ie]=a.useState({}),[le,be]=a.useState({}),[Le,xe]=a.useState({}),[q,ce]=a.useState({}),[De,He]=a.useState(null),[qe,pe]=a.useState([]),[te,me]=a.useState(""),[se,z]=a.useState(!1),[Y,he]=a.useState({}),[X,ye]=a.useState({}),[ot,ue]=a.useState({}),[je,$e]=a.useState([]),[Ce,We]=a.useState(!1),[ke,Ee]=a.useState(!1),[Ze,Ke]=a.useState(),[dt,Fe]=a.useState("Remote Server"),[nt,Nt]=a.useState(""),[Ft,ze]=a.useState(""),[it,Mt]=a.useState(!1),[Ht,Me]=a.useState(null),Ae=a.useRef({}),ee=a.useRef(null),Ie=a.useRef(null),Pe=a.useRef(null),[oe,re]=a.useState({}),_e=a.useRef({}),[fe,Xe]=a.useState(()=>Gi()?.stepData?.github?.skipped===!0),kt=a.useRef(0),Rt=a.useRef(l),{shellApi:Vt,state:Pt}=VN(),bt=a.useRef(!1),pt=p?.currentStep,ft=!!p&&p.currentStep!=="complete";La(Ie,y,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const Q=ee.current;Q&&(Q.scrollTop=0)},[x]),a.useEffect(()=>{const Q=Le["github-copilot"];Q?.userCode&&_e.current["github-copilot"]!==Q.userCode&&(_e.current["github-copilot"]=Q.userCode,wy(Q.userCode))},[Le]);const[_t,Yt]=a.useState(()=>Gi()?.stepData?.["ai-setup"]?.skippedProviders??{}),on=[{key:"ai-setup",label:c("setup.stepAiSetup","AI Setup")},{key:"github",label:c("setup.stepGithub","GitHub")},{key:"project-setup",label:c("setup.stepProject","Project")},{key:"first-task",label:c("setup.stepFirstTask","First Task")}],An=on.findIndex(Q=>Q.key===x),vn=x==="complete"?on.length:An;a.useEffect(()=>{x!=="complete"&&yd(x,{completedSteps:w,skippedSteps:j})},[x,w,j]),a.useEffect(()=>{bt.current||(bt.current=!0,Zi("onboarding:wizard-opened",{source:ft?"resume":"initial",resumedFromStep:pt}))},[ft,pt]),a.useEffect(()=>{const Q=Rt.current!=null,Qe=l!=null;!Q&&Qe&&E(!0),Qe||E(!1),Rt.current=l},[l]);const Qt=a.useRef(u);a.useEffect(()=>{if(Qt.current==="ai-setup"&&x!=="ai-setup"&&!L.some(Qe=>Qe.id!=="github"&&Qe.authenticated)){const Qe={};for(const vt of L)vt.id!=="github"&&!vt.authenticated&&!_t[vt.id]&&(Qe[vt.id]=!0);if(Object.keys(Qe).length>0){const vt={..._t,...Qe};Yt(vt),yd(x,{stepData:{"ai-setup":{skippedProviders:vt}}})}}Qt.current=x},[x,L,_t]);const sn=a.useCallback(async()=>{try{const{providers:Q,ghCli:Qe}=await Yo(),vt=jy(Q);O(vt),A(Qe),ie(xt=>{const zt={};for(const[Wt,hn]of Object.entries(xt)){const In=vt.find(gs=>gs.id===Wt);In&&!In.authenticated&&In.loginInProgress&&(zt[Wt]=hn)}return Object.keys(zt).length===Object.keys(xt).length?xt:zt}),re(xt=>{let zt=!1;const Wt={...xt};for(const[hn,In]of Object.entries(xt)){if(In!=="pending")continue;vt.find(ks=>ks.id===hn)?.loginInProgress||(delete Wt[hn],zt=!0)}return zt?Wt:xt}),Yt(xt=>{const zt={...xt};for(const Wt of vt)Wt.authenticated&&zt[Wt.id]&&delete zt[Wt.id];return Object.keys(zt).length===Object.keys(xt).length?xt:zt})}catch{}},[]),mn=a.useCallback(async()=>{try{const Q=await nM();$e((Q.providers??[]).map(G8))}catch{}},[]),Kt=a.useCallback(async Q=>{Ee(!0),Ke(void 0);try{await iM(Q),await mn(),await fa().then(Qe=>pe(Qe.models??[])),We(!1)}catch(Qe){Ke(Re(Qe)||c("setup.failedToCreateCustomProvider","Failed to create custom provider"))}finally{Ee(!1)}},[mn]),fn=a.useRef(!1);a.useEffect(()=>{x==="ai-setup"&&mn(),fn.current&&sn(),fn.current=x!=="ai-setup"},[x,sn,mn]),a.useEffect(()=>{if(!L.some(vt=>vt.loginInProgress))return;const Qe=setInterval(()=>{sn()},2e3);return()=>clearInterval(Qe)},[L,sn]);const $n=L.find(Q=>Q.id==="github"),On=!!$n,xn=$n?.authenticated??!1,Vn=$n?.loginInProgress??!1,Rn=J?.authenticated??!1,Pn=xn||Rn,zn=!xn&&Rn,Nn=a.useCallback(Q=>{if(Q.authenticated)return"connected";const Qe=oe?.[Q.id];return Qe==="timeout"||Qe==="failed"?"retry":_t[Q.id]?"skipped":"not-connected"},[oe,_t]);function dn({status:Q}){const Qe={connected:{text:c("setup.statusConnected","✓ Connected"),className:"auth-status-badge connected"},"not-connected":{text:c("setup.statusNotConnected","Not connected"),className:"auth-status-badge not-connected"},skipped:{text:c("setup.statusSkipped","Skipped"),className:"auth-status-badge skipped"},retry:{text:c("setup.statusRetry","Retry"),className:"auth-status-badge retry"}},{text:vt,className:xt}=Qe[Q];return t.jsx("span",{"data-testid":"provider-status-badge",className:xt,"data-status":Q,children:vt})}const Tt=a.useCallback(()=>{if(Pn)return"connected";const Q=oe.github;return Q==="pending"?"pending":Q==="failed"||Q==="timeout"?"failed":fe?"skipped":"not-connected"},[Pn,oe,fe]);function Yn({status:Q}){const Qe={connected:{text:c("setup.statusConnected","✓ Connected"),className:"auth-status-badge connected"},pending:{text:c("setup.statusConnecting","⏳ Connecting…"),className:"auth-status-badge pending"},failed:{text:c("setup.statusConnectionFailed","✗ Connection failed"),className:"auth-status-badge retry"},skipped:{text:c("setup.statusSkipped","Skipped"),className:"auth-status-badge skipped"},"not-connected":{text:c("setup.statusNotConnected","Not connected"),className:"auth-status-badge not-connected"}},{text:vt,className:xt}=Qe[Q];return t.jsx("span",{"data-testid":"github-status-badge",className:xt,"data-status":Q,children:vt})}const cn=a.useCallback(async()=>{try{const Q=await fa();pe(Q.models)}catch{}},[]),Bn=a.useCallback(async()=>{try{const Q=await Ja();if(Q.defaultProvider&&Q.defaultModelId){const Qe=`${Q.defaultProvider}/${Q.defaultModelId}`;me(Qe)}}catch{}},[]);a.useEffect(()=>{Promise.all([sn(),cn(),Bn()]).finally(()=>B(!1))},[sn,cn,Bn]),a.useEffect(()=>{const Q=F8("ai-setup");if(Q?.loginOutcomes){const Qe=Q.loginOutcomes,vt={};for(const[xt,zt]of Object.entries(Qe))zt!=="pending"&&(vt[xt]=zt);Object.keys(vt).length>0&&re(vt)}},[]);const kn=a.useCallback((Q,Qe)=>{yd(x,{completedSteps:w,stepData:{"ai-setup":{loginOutcomes:{[Q]:Qe}}}})},[x,w]);a.useEffect(()=>{const Q=Object.entries(oe).filter(([Qe,vt])=>vt!=="pending");for(const[Qe,vt]of Q)kn(Qe,vt)},[oe,kn]),a.useEffect(()=>()=>{Pe.current&&clearInterval(Pe.current),Object.values(Ae.current).forEach(clearTimeout),Ae.current={}},[]);const pn=a.useCallback(Q=>{Xe(Q),yd(x,{completedSteps:w,stepData:{github:{skipped:Q}}})},[x,w]),un=a.useCallback(Q=>Q==="complete"?-1:dr.indexOf(Q),[]),At=a.useCallback(()=>{g(Qe=>[...new Set([...Qe,x])]),S(Qe=>Qe.filter(vt=>vt!==x)),Zi("onboarding:step-completed",{step:x}),x==="github"&&!xn&&pn(!1);const Q=un(x);Q>=0&&Q<dr.length-1&&k(dr[Q+1])},[x,xn,pn,un]),an=a.useCallback(()=>{S(Qe=>[...new Set([...Qe,x])]),R8(x),Zi("onboarding:step-skipped",{step:x}),x==="github"&&!xn&&pn(!0);const Q=un(x);Q>=0&&Q<dr.length-1&&k(dr[Q+1])},[x,xn,pn,un]),Wn=a.useCallback(()=>{const Q=x;g(vt=>vt.filter(xt=>xt!==Q)),S(vt=>vt.filter(xt=>xt!==Q)),Q==="github"&&!xn&&pn(!1);const Qe=un(x);Qe>0&&k(dr[Qe-1])},[x,xn,pn,un]),Xn=a.useCallback(()=>{an()},[an]),G=a.useCallback(async Q=>{const Qe=L.find(xt=>xt.id===Q);if(Qe?.requiresManualCode===!0&&!await m({title:c("setup.manualPastebackTitle","Heads up — manual paste-back required"),message:Y8(Qe.name),confirmLabel:c("setup.continueToLogin","Continue to login"),cancelLabel:c("setup.cancelLogin","Cancel")}))return;re(xt=>{const zt=xt[Q];if(zt&&zt!=="pending"){const{[Q]:Wt,...hn}=xt;return hn}return xt});const vt=()=>{if(Q in _e.current){const xt={..._e.current};delete xt[Q],_e.current=xt}ie(xt=>{if(!(Q in xt))return xt;const zt={...xt};return delete zt[Q],zt}),be(xt=>{if(!(Q in xt))return xt;const zt={...xt};return delete zt[Q],zt}),ce(xt=>{if(!(Q in xt))return xt;const zt={...xt};return delete zt[Q],zt}),xe(xt=>{if(!(Q in xt))return xt;const zt={...xt};return delete zt[Q],zt})};vt(),re(xt=>({...xt,[Q]:"pending"})),Z(Q),kt.current=0;try{const{url:xt,instructions:zt,manualCode:Wt,deviceCode:hn}=await rM(Q);zt?.trim()&&!(Q==="github-copilot"&&hn)&&ie(In=>({...In,[Q]:zt})),Wt&&be(In=>({...In,[Q]:Wt})),hn&&Q==="github-copilot"&&xe(In=>({...In,[Q]:hn})),(Q!=="github-copilot"||!hn)&&window.open(pa(hn?.verificationUri??xt),"_blank"),Pe.current=setInterval(async()=>{if(kt.current++,kt.current>=iH){Pe.current&&(clearInterval(Pe.current),Pe.current=null),Z(null),O(In=>In.map(gs=>gs.id===Q?{...gs,loginInProgress:!1}:gs)),re(In=>({...In,[Q]:"timeout"})),vt(),n(c("setup.loginTimedOut","Login timed out. Please try again."),"warning");return}try{const{providers:In,ghCli:gs}=await Yo(),ks=jy(In);O(ks),A(gs);const Te=ks.find(U=>U.id===Q);if(Te?.authenticated){Pe.current&&(clearInterval(Pe.current),Pe.current=null),Z(null),re(U=>({...U,[Q]:"success"})),vt(),Q==="github"&&pn(!1),n(c("setup.loginSuccessful","Login successful"),"success"),window.dispatchEvent(new CustomEvent(Ah,{detail:{providerId:Q}}));return}Te?.loginInProgress||(Pe.current&&(clearInterval(Pe.current),Pe.current=null),Z(null),re(U=>({...U,[Q]:"failed"})),vt(),n(c("setup.loginDidNotComplete","Login did not complete. Please try again."),"error"))}catch{}},2e3)}catch(xt){xt instanceof Error&&xt.message.includes("already in progress")||xt&&typeof xt=="object"&&"status"in xt&&xt.status===409?(n(c("setup.loginAlreadyInProgress","Login already in progress. Cancel it to retry."),"warning"),re(Wt=>({...Wt,[Q]:"pending"})),sn()):(n(xt instanceof Error?xt.message:c("setup.loginFailed","Login failed"),"error"),re(Wt=>({...Wt,[Q]:"failed"}))),Z(null),vt()}},[n,L,m,sn,pn]),Oe=a.useCallback(async Q=>{const Qe=q[Q]?.trim();if(!Qe){n(c("setup.pasteRedirectUrlFirst","Paste the full redirect URL or authorization code first."),"warning");return}He(Q);try{(await oM(Q,Qe)).submitted?(ce(xt=>{if(!(Q in xt))return xt;const zt={...xt};return delete zt[Q],zt}),n(c("setup.authCodeReceived","Authorization code received. Finishing login…"),"success")):n(c("setup.authCodeAlreadySubmitted","That authorization code was already submitted. Waiting for login…"),"warning")}catch(vt){n(Re(vt)||c("setup.failedToSubmitAuthCode","Failed to submit authorization code"),"error")}finally{He(null)}},[n,q]),yt=a.useCallback(async Q=>{Pe.current&&(clearInterval(Pe.current),Pe.current=null),Z(Q),kt.current=0,O(Qe=>Qe.map(vt=>vt.id===Q?{...vt,loginInProgress:!1}:vt)),re(Qe=>({...Qe,[Q]:"cancelled"}));try{await cM(Q),await sn().catch(()=>{}),n(c("setup.loginCancelled","Login cancelled"),"success")}catch(Qe){n(Re(Qe)||c("setup.failedToCancelLogin","Failed to cancel login"),"error")}finally{Z(null),ie(Qe=>{if(!(Q in Qe))return Qe;const vt={...Qe};return delete vt[Q],vt}),be(Qe=>{if(!(Q in Qe))return Qe;const vt={...Qe};return delete vt[Q],vt}),ce(Qe=>{if(!(Q in Qe))return Qe;const vt={...Qe};return delete vt[Q],vt}),He(Qe=>Qe===Q?null:Qe),xe(Qe=>{if(!(Q in Qe))return Qe;const vt={...Qe};return delete vt[Q],vt})}},[n,sn]),Gt=a.useCallback((Q,Qe)=>{he(xt=>({...xt,[Q]:Qe}));const vt=Ae.current[Q];vt&&(clearTimeout(vt),delete Ae.current[Q]),ye(xt=>{if(!xt[Q])return xt;const zt={...xt};return delete zt[Q],zt}),ue(xt=>{if(!xt[Q])return xt;const zt={...xt};return delete zt[Q],zt})},[]),Sn=a.useCallback(()=>{const Q=ee.current;if(!Q)return;const Qe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof Q.scrollTo=="function"){Q.scrollTo({top:0,behavior:Qe?"auto":"smooth"});return}}catch{}Q.scrollTop=0},[]),Un=a.useCallback(async(Q,Qe)=>{const vt=(Qe??Y[Q]??"").trim(),xt=eH(Q,vt,c);if(xt){ye(Wt=>({...Wt,[Q]:xt}));return}const zt=Ae.current[Q];zt&&(clearTimeout(zt),delete Ae.current[Q]),Z(Q),ye(Wt=>{const hn={...Wt};return delete hn[Q],hn}),ue(Wt=>{if(!Wt[Q])return Wt;const hn={...Wt};return delete hn[Q],hn});try{await dM(Q,vt),await sn(),Sn(),he(Wt=>{const hn={...Wt};return delete hn[Q],hn}),ye(Wt=>{if(!Wt[Q])return Wt;const hn={...Wt};return delete hn[Q],hn}),ue(Wt=>({...Wt,[Q]:c("setup.keySavedInline","✓ Key saved")})),Ae.current[Q]=setTimeout(()=>{ue(Wt=>{if(!Wt[Q])return Wt;const hn={...Wt};return delete hn[Q],hn}),delete Ae.current[Q]},3e3),n(c("setup.apiKeySavedToast","API key saved"),"success")}catch(Wt){const hn=Wt instanceof TypeError&&Wt.message.includes("Failed to fetch")?c("setup.couldNotReachServer","Could not reach the server. Check your connection and try again."):Wt instanceof Error?Wt.message:c("setup.failedToSaveApiKey","Failed to save API key");ye(In=>({...In,[Q]:hn})),ue(In=>{if(!In[Q])return In;const gs={...In};return delete gs[Q],gs}),n(hn,"error")}finally{Z(null)}},[Y,n,sn,Sn]),bn=a.useCallback(async Q=>{Z(Q);try{await uM(Q),await sn(),n(c("setup.apiKeyRemoved","API key removed"),"success")}catch(Qe){n(Qe instanceof Error?Qe.message:c("setup.failedToClearApiKey","Failed to clear API key"),"error")}finally{Z(null)}},[n,sn]),gn=a.useCallback(async Q=>{Z(Q);try{await lM(Q),await sn(),n(c("setup.loggedOut","Logged out"),"success")}catch(Qe){n(Qe instanceof Error?Qe.message:c("setup.logoutFailed","Logout failed"),"error")}finally{Z(null)}},[n,sn]),ps=a.useCallback(Q=>{me(Q)},[]),Ne=a.useCallback(async()=>{try{const Q={modelOnboardingComplete:!0};if(te){const Qe=te.indexOf("/"),vt=Qe!==-1?te.slice(0,Qe):void 0,xt=Qe!==-1?te.slice(Qe+1):te,zt=qe.find(Wt=>Wt.id===xt);zt?(Q.defaultProvider=zt.provider,Q.defaultModelId=zt.id):vt&&xt&&(Q.defaultProvider=vt,Q.defaultModelId=xt)}await Ms(Q),Ny()}catch{}},[te,qe,Ms,Ny]),ae=a.useCallback(async()=>{const Q=[...new Set([...w,"first-task"])];z(!0);try{await Ne(),Zi("onboarding:completed",{completedSteps:Q,skippedSteps:j}),g(Q),S(Qe=>Qe.filter(vt=>vt!=="first-task")),k("complete")}finally{z(!1)}},[Ne,w,j]),Se=a.useCallback(async()=>{if(!s)return;const Q=F.trim();if(!Q){N(c("setup.pleaseEnterTaskDescription","Please enter a task description."));return}N(null),_(!0);let Qe=!1;try{const vt=await Hk({description:Q,source:{sourceType:"dashboard_ui"}},s);R(vt),E(!0),Zi("onboarding:first-task-created",{taskId:vt?.id}),n(c("setup.taskCreated","Task created"),"success"),Qe=!0}catch(vt){const xt=vt instanceof Error?vt.message:c("setup.taskCreationFailed","Something went wrong creating your task. Please try again.");N(xt),n(xt,"error")}finally{_(!1)}Qe&&Ne()},[s,F,n,Ne]),ut=a.useCallback(async()=>{z(!0);try{await Ne()}finally{z(!1)}Zi("onboarding:open-new-task",{}),r?.()},[Ne,r]),It=a.useCallback(async()=>{if(Pn){z(!0);try{await Ne()}finally{z(!1)}v(!1),e(),Zi("onboarding:open-github-import",{}),o?.()}},[Ne,Pn,e,o]),ht=a.useCallback(async()=>{Zi("onboarding:dismissed",{currentStep:x,completedSteps:w,skippedSteps:j}),z(!0);try{await Ms({modelOnboardingComplete:!0})}catch{}v(!1),e()},[x,w,j,e]),et=a.useCallback(()=>{Zi("onboarding:finished",{}),v(!1),e()},[e]),Ut=a.useCallback(()=>{const Q=l??$;Q&&(Ne(),d?.(Q),e())},[l,$,Ne,d,e]),$t=a.useCallback(()=>{Ne(),e()},[Ne,e]),rn=Tt(),Cn=L.filter(Q=>Q.id!=="github"),ve=Pt.host!=="web"&&!Pt.activeProfileId,at=[...Cn].sort(My),Ge=at.some(Q=>!Q.type||Q.type==="oauth"),tt=at.some(Q=>Q.type==="api_key"),gt=Cn.filter(Q=>Q.authenticated),St=gt.length>0,Xt=!!s,ss=x==="github"&&!St,Ts=a.useCallback(async()=>{if(Vt){Me(null),Mt(!0);try{const Q=await Vt.saveProfile({name:dt,serverUrl:nt,authToken:Ft.trim()?Ft:null});try{await Vt.setActiveProfile(Q.id)}catch(Qe){Me(Re(Qe)||c("setup.savedProfileButFailedToActivate","Saved profile but failed to activate it"));return}Nt(""),ze(""),n(c("setup.remoteServerProfileSaved","Remote server profile saved"),"success")}catch(Q){Me(Re(Q)||c("setup.failedToSaveShellConnection","Failed to save shell connection"))}finally{Mt(!1)}}},[Vt,dt,nt,Ft,n]);if(!y)return null;const Ls=(()=>{if(!te)return"";const Q=te.indexOf("/"),Qe=Q===-1?void 0:te.slice(0,Q),vt=Q===-1?te:te.slice(Q+1),xt=qe.find(zt=>zt.id===vt&&(!Qe||zt.provider===Qe));return xt?.name?xt.name:Qe?`${hp(Qe)} ${vt}`:te})(),rs=[];if(Xt?rs.push({label:c("setup.readinessProjectLabel","Project"),status:"connected",detail:c("setup.readinessProjectConnected","Project selected — task creation and imports are available")}):rs.push({label:c("setup.readinessProjectLabel","Project"),status:"missing",detail:c("setup.readinessProjectMissing","Register a project to enable task creation and imports")}),St){const Q=hp(gt[0]?.id??"");rs.push({label:c("setup.readinessAiProviderLabel","AI Provider"),status:"connected",detail:c("setup.readinessAiProviderConnected","{{name}} connected — AI agents can work on tasks",{name:Q})})}else Cn.length>0&&Cn.some(Q=>_t[Q.id])?rs.push({label:c("setup.readinessAiProviderLabel","AI Provider"),status:"skipped",detail:c("setup.readinessAiProviderSkipped","AI agents won't be available until you connect a provider")}):rs.push({label:c("setup.readinessAiProviderLabel","AI Provider"),status:"missing",detail:c("setup.readinessAiProviderMissing","Connect a provider in Settings → AI Setup")});Pn?rs.push({label:c("setup.readinessGitHubLabel","GitHub"),status:"connected",detail:zn?c("setup.readinessGitHubViaCli","Connected via GitHub CLI — imports and PR tracking are available"):c("setup.readinessGitHubConnected","Issues and PRs can be imported")}):!On||fe?rs.push({label:c("setup.readinessGitHubLabel","GitHub"),status:"skipped",detail:c("setup.readinessGitHubSkipped","You can connect anytime from Settings")}):rs.push({label:c("setup.readinessGitHubLabel","GitHub"),status:"missing",detail:c("setup.readinessGitHubMissing","Connect to import issues as tasks")}),Ls&&rs.push({label:c("setup.readinessDefaultModelLabel","Default Model"),status:"connected",detail:Ls});const ei=l??$,Mi=ei?.description?.split(`
|
|
793
|
-
`)[0]?.trim()||ei?.title||"",ti=new Set(oh),mi=at.filter(Q=>ti.has(Q.id)).sort((Q,Qe)=>{const vt=oh.indexOf(Q.id),xt=oh.indexOf(Qe.id);return vt!==xt?vt-xt:My(Q,Qe)}),zs=at.filter(Q=>Q.authenticated&&!ti.has(Q.id)),Qn=at.filter(Q=>!Q.authenticated&&!ti.has(Q.id)),Zt=Q=>{const Qe=oe[Q.id]==="timeout"||oe[Q.id]==="failed"||oe[Q.id]==="cancelled",vt=Q.loginInProgress&&!Qe;if(Q.id==="llama-cpp"&&Q.type==="cli")return t.jsx(p8,{authenticated:Q.authenticated,onToggled:()=>{sn()}},Q.id);if(Q.id==="claude-cli"&&Q.type==="cli")return t.jsx(u8,{authenticated:Q.authenticated,onToggled:()=>{sn()}},Q.id);if(Q.id==="cursor-cli"&&Q.type==="cli")return t.jsx(h8,{authenticated:Q.authenticated,onToggled:()=>{sn()}},Q.id);if(Q.type==="api_key"){const xt=fp(Q.id,c),zt=tH(Q,c);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Q.id}`,"aria-hidden":"true",children:t.jsx(hs,{provider:Q.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(_k,{size:14,className:"onboarding-provider-key-icon"}),Q.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:xt.description}),t.jsx(dn,{status:Nn(Q)}),Q.authenticated&&Q.keyHint&&t.jsx("span",{className:"auth-key-hint",children:c("setup.apiKeyHint","Key: {{keyHint}}",{keyHint:Q.keyHint})})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(sH,{provider:Q,apiKeyInfo:zt,inputValue:Y[Q.id]??"",isSaving:P===Q.id,error:X[Q.id],success:ot[Q.id],isConnected:Q.authenticated,onInputChange:Gt,onSave:Un,onClear:bn})})]},Q.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Q.id}`,"aria-hidden":"true",children:t.jsx(hs,{provider:Q.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:Q.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:fp(Q.id,c).description}),t.jsx(dn,{status:Nn(Q)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:P===Q.id?Q.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.loggingOut","Logging out…")}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.waitingForLogin","Waiting for login…")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void yt(Q.id),children:c("setup.cancelLogin","Cancel")})]}):vt?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.waitingForLogin","Waiting for login…")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void yt(Q.id),children:c("setup.cancelLogin","Cancel")})]}):Q.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>gn(Q.id),children:c("setup.logout","Logout")}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>G(Q.id),children:c("setup.login","Login")})}),(P===Q.id||vt)&&Q.id==="github-copilot"&&Le[Q.id]&&t.jsxs("div",{className:"auth-device-code-panel","data-testid":`onboarding-device-code-${Q.id}`,children:[t.jsx("strong",{children:c("setup.enterCodeOnGitHub","Enter this code on GitHub")}),t.jsx("div",{className:"auth-device-code-pill",children:Le[Q.id].userCode}),t.jsxs("div",{className:"auth-provider-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{(async()=>{if(await wy(Le[Q.id].userCode)){n(c("setup.copiedCodeToClipboard","Copied code to clipboard"),"success");return}n(c("setup.failedToCopyCode","Failed to copy code — copy it manually from the box above"),"error")})()},children:c("setup.copyCode","Copy code")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>window.open(pa(Le[Q.id].verificationUri),"_blank"),children:c("setup.openGitHub","Open GitHub")})]})]}),(P===Q.id||vt)&&T[Q.id]&&t.jsx(rh,{instructions:T[Q.id],"data-testid":`onboarding-login-instructions-${Q.id}`}),(P===Q.id||vt)&&le[Q.id]&&t.jsx(g8,{value:q[Q.id]??"",onChange:xt=>ce(zt=>({...zt,[Q.id]:xt})),onSubmit:()=>void Oe(Q.id),prompt:le[Q.id].prompt,placeholder:le[Q.id].placeholder,helpText:le[Q.id].helpText,disabled:De===Q.id,submitLabel:De===Q.id?c("setup.submittingCode","Submitting…"):c("setup.submitCode","Submit code"),"data-testid":`onboarding-manual-code-${Q.id}`}),oe[Q.id]==="timeout"&&P!==Q.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:c("setup.loginTimedOutInline","Login timed out. Please try again.")}),oe[Q.id]==="failed"&&P!==Q.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:c("setup.loginFailedInline","Login failed. Please try again.")})]},Q.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:Ie,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(Ws,{size:24})," ",c("setup.titleAiSetup","Set Up AI")," ",t.jsx("span",{className:"onboarding-optional-badge",children:c("setup.optionalBadge","Optional")})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(ai,{size:24})," ",c("setup.titleConnectGitHub","Connect GitHub")," ",t.jsx("span",{className:"onboarding-optional-badge",children:c("setup.optionalBadge","Optional")})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(sg,{size:24})," ",c("setup.titleSetUpProject","Set Up Your Project")]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(sg,{size:24})," ",c("setup.titleCreateFirstTask","Create Your First Task")]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:24})," ",c("setup.titleAllSet","All Set!")]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:ht,"aria-label":c("setup.skipOnboardingAriaLabel","Skip onboarding"),title:c("setup.skipForNow","Skip for now"),children:t.jsx(Fn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:on.map((Q,Qe)=>{const vt=vn>Qe,xt=w.includes(Q.key)&&vt,zt=j.includes(Q.key)&&!w.includes(Q.key)&&vt,Wt=xt||zt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Qe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Qe<=vn?"done":""}`}),Wt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===Q.key?"active":""} ${xt?"done":""} ${zt?"skipped":""}`,onClick:()=>k(Q.key),"aria-label":c("setup.goBackToStep","Go back to {{label}}",{label:Q.label}),title:c("setup.reviewStep","Review {{label}}",{label:Q.label}),children:[t.jsx("span",{className:"step-number",children:xt?t.jsx(Es,{size:14}):zt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Qe+1}),t.jsx("span",{className:"step-label",children:Q.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===Q.key?"active":""} ${xt?"done":""} ${zt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:xt?t.jsx(Es,{size:14}):zt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Qe+1}),t.jsx("span",{className:"step-label",children:Q.label})]})]},Q.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:ee,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:c("setup.aiSetupDescription","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:c("setup.onlyNeedOneProvider","You only need one provider to get started.")}),t.jsx("p",{className:"onboarding-helper-text",children:c("setup.researchRunsNote","Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features.")}),ve&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:c("setup.connectRemoteServer","Connect remote Fusion server")}),t.jsx("p",{className:"onboarding-helper-text",children:c("setup.remoteServerNote","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:c("setup.profileName","Profile name")}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:dt,onChange:Q=>Fe(Q.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-server-url",className:"onboarding-apikey-field-label",children:c("setup.serverUrl","Server URL")}),t.jsx("input",{id:"onboarding-shell-server-url",className:"input",placeholder:c("setup.serverUrlPlaceholder","https://your-fusion-host"),value:nt,onChange:Q=>Nt(Q.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-token",className:"onboarding-apikey-field-label",children:c("setup.authTokenOptional","Auth token (optional)")}),t.jsx("input",{id:"onboarding-shell-token",className:"input",type:"password",value:Ft,onChange:Q=>ze(Q.target.value)}),Ht&&t.jsx("small",{className:"field-error",children:Ht}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Vt?.openConnectionManager(),children:c("setup.openManager","Open manager")}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void Ts(),disabled:!nt.trim()||it,children:it?c("setup.savingRemoteServer","Saving…"):c("setup.saveRemoteServer","Save remote server")})]})]}),!de&&L.length>0&&(()=>{const Q=L.filter(Wt=>Wt.id!=="github"&&Wt.authenticated).length,Qe=L.filter(Wt=>Wt.id!=="github").length,vt=Object.keys(_t).filter(Wt=>!L.find(hn=>hn.id===Wt)?.authenticated).length;if(Qe===0)return null;let xt="onboarding-provider-summary",zt="";return Q>0?(xt+=" onboarding-provider-summary--connected",zt=c("setup.providersConnectedSummary","✓ {{connected}} of {{total}} providers connected",{connected:Q,total:Qe})):vt>0?(xt+=" onboarding-provider-summary--skipped",zt=vt===1?c("setup.providersSkippedSummary_one","{{count}} provider skipped",{count:vt}):c("setup.providersSkippedSummary_other","{{count}} providers skipped",{count:vt})):(xt+=" onboarding-provider-summary--none",zt=c("setup.noProvidersConnectedYet","No providers connected yet")),t.jsx("div",{className:xt,"data-testid":"provider-summary",children:zt})})(),t.jsx(fr,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(ea,{summary:c("setup.whatAreAiProviders","What are AI providers?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatAreAiProvidersBody","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.")})}),L.length>0&&!L.some(Q=>Q.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:c("setup.skipProviderHint","Skip this step if you'd like — you can always add providers later from Settings.")}),de?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(Et,{size:24,className:"animate-spin"}),t.jsx("span",{children:c("setup.loadingProviders","Loading providers…")})]}):L.length===0?t.jsx("div",{className:"model-onboarding-empty",children:c("setup.noProvidersConfigured","No AI providers are configured. Please check your Fusion configuration.")}):t.jsxs(t.Fragment,{children:[t.jsx(fr,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{sn()}}}),t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:c("setup.quickStartProviders","Quick start providers")}),mi.length>0?t.jsx("div",{className:"model-onboarding-providers",children:mi.map(Q=>Zt(Q))}):t.jsx("p",{className:"onboarding-helper-text",children:c("setup.noQuickStartProviders","No quick-start providers are available in this environment.")})]}),zs.length>0&&t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:c("setup.connectedProviders","Connected providers")}),t.jsx("div",{className:"model-onboarding-providers",children:zs.map(Q=>Zt(Q))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:c("setup.defaultModelOptional","Default Model (Optional)")}),t.jsx("p",{className:"model-onboarding-description",children:c("setup.defaultModelDescription","Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost.")}),t.jsx(ea,{summary:c("setup.howDoIChooseModel","How do I choose a model?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.howDoIChooseModelBody","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.")})}),qe.length===0?t.jsx("div",{className:"model-onboarding-empty",children:c("setup.noModelsAvailable","No models available yet. Connect a provider above to see model options.")}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(wi,{models:qe,value:te,onChange:ps,placeholder:c("setup.selectDefaultModel","Select a default model…"),label:c("setup.defaultModelLabel","Default model")})}),te&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:[c("setup.selectedModel","Selected:")," "," ",qe.find(Q=>Q.id===te)?.name??te]})})]}),t.jsx(ea,{summary:c("setup.advancedProviderSettings","Advanced provider settings"),className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Qn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Qn.map(Q=>Zt(Q))}):t.jsx("p",{className:"onboarding-helper-text",children:c("setup.allProvidersShown","All currently available providers are already shown above.")}),je.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:je.map(Q=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(hs,{provider:Q.id,size:"sm"}),t.jsx("span",{children:Q.name||Q.id})]},Q.id))}):null,Ce?t.jsx(x8,{onSave:Kt,onCancel:()=>{We(!1),Ke(void 0)},saving:ke,error:Ze}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>We(!0),children:c("setup.addCustomProvider","Add custom provider")})]})}),Ge&&t.jsx(ea,{summary:c("setup.howDoesLoginWork","How does login work?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.howDoesLoginWorkBody","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.")})}),tt&&t.jsx(ea,{summary:c("setup.whatIsApiKey","What is an API key?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatIsApiKeyBody","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(fr,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Pn?t.jsx("p",{className:"model-onboarding-description",children:zn?c("setup.githubCliAlreadyAuth","GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed."):c("setup.githubConnected","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:c("setup.githubConnectionDescription","Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it.")}),!Pn&&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:c("setup.withoutGitHubHeading","Without GitHub (available now):")})}),t.jsx("li",{className:"onboarding-helper-text",children:c("setup.withoutGitHub1","Create tasks manually")}),t.jsx("li",{className:"onboarding-helper-text",children:c("setup.withoutGitHub2","Describe work for AI agents")}),t.jsx("li",{className:"onboarding-helper-text",children:c("setup.withoutGitHub3","Track progress on the board")}),t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:c("setup.withGitHubHeading","With GitHub (after connecting):")})}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:c("setup.withGitHub1","Import issues as tasks")}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:c("setup.withGitHub2","Sync pull request status")}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:c("setup.withGitHub3","Link code changes to tasks")})]})}),ss&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:c("setup.noAiProviderConnected","No AI provider connected")}),t.jsx("p",{children:c("setup.noAiProviderBody","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(ea,{summary:c("setup.whatDoesGitHubIntegrationDo","What does GitHub integration do?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatDoesGitHubIntegrationDoBody","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.")})}),On?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(ai,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Yn,{status:rn})})]}),xn&&(P==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.loggingOut","Logging out…")}):t.jsx("button",{className:"btn btn-sm",onClick:()=>gn("github"),children:c("setup.disconnect","Disconnect")}))]}),(rn==="not-connected"||rn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[P==="github"||Vn?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.waitingForLogin","Waiting for login…")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void yt("github"),children:c("setup.cancelLogin","Cancel")})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>G("github"),children:[t.jsx(ai,{size:16}),c("setup.connect","Connect")]}),(P==="github"||Vn)&&T.github&&t.jsx(rh,{instructions:T.github,"data-testid":"onboarding-login-instructions-github"})]}),rn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:zn?c("setup.githubCliAuthSuccess","GitHub CLI is authenticated. Imports and pull request tracking are available. Connect OAuth in Settings → Authentication if you want dashboard-managed sign-in controls."):c("setup.githubOauthConnected","GitHub OAuth is connected. You can import issues and track pull requests.")}),rn==="failed"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[t.jsx("p",{children:c("setup.githubConnectionFailed","Connection failed or timed out.")}),t.jsxs("div",{className:"onboarding-github-feedback-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>G("github"),children:c("setup.retry","Retry")}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Xn,children:c("setup.skipForNow","Skip for now")})]})]}),rn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:c("setup.waitingForGitHubAuth","Waiting for GitHub authorization…")}),rn==="skipped"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[t.jsx("p",{children:c("setup.githubSkipped","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:()=>G("github"),children:c("setup.connectAnyway","Connect anyway")})})]}),rn==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:c("setup.connectGitHubAnytime","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(hs,{provider:"github",size:"lg"})}),zn?t.jsx("p",{children:c("setup.githubCliAuthNote","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:c("setup.githubOauthNotConnected","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:()=>k("project-setup"),children:zn?c("setup.continueWithGhCli","Continue with gh CLI auth →"):c("setup.continueWithoutGitHub","Continue without GitHub →")}),zn&&(P==="github"||Vn?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(Et,{size:14,className:"onboarding-spinner"}),c("setup.waitingForOauthLogin","Waiting for OAuth login…")]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>G("github"),children:[t.jsx(hs,{provider:"github",size:"sm"}),c("setup.connectOauthOptional","Connect OAuth (optional)")]}))]}),zn&&(P==="github"||Vn)&&T.github&&t.jsx(rh,{instructions:T.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:c("setup.projectSetupDescription","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.")}),Xt?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:c("setup.projectSelected","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:c("setup.projectRequired","A project is required before first-task actions are available.")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:c("setup.setUpProject","Set Up Project")}),t.jsx("p",{className:"onboarding-helper-text",children:c("setup.setupWizardHint","In the setup wizard, pick an existing directory or paste a GitHub clone URL.")})]}),t.jsx(ea,{summary:c("setup.whatDoesProjectSetupDo","What does project setup do?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatDoesProjectSetupDoBody","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:c("setup.firstTaskDescription","Create your first task to start the board and launch AI execution.")}),C&&ei?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Es,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:c("setup.firstTaskReady","Your first task is ready!")}),t.jsx("div",{className:"onboarding-task-created__task-id",children:ei.id}),Mi&&t.jsx("p",{className:"onboarding-task-created__description",children:Mi}),t.jsx("p",{className:"onboarding-task-created__hint",children:c("setup.taskCreatedHint","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:Ut,children:c("setup.viewTask","View Task")}),t.jsx("button",{type:"button",className:"btn",onClick:$t,children:c("setup.goToDashboard","Go to Dashboard")})]})]}):t.jsxs(t.Fragment,{children:[Xt?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:c("setup.describeFirstTask","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:F,onChange:Q=>{M(Q.target.value),N(null)},placeholder:c("setup.firstTaskPlaceholder","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:Se,disabled:D,"data-testid":"onboarding-first-task-submit",children:D?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:16,className:"animate-spin"}),t.jsx("span",{children:c("setup.creatingTask","Creating task…")})]}):c("setup.createFirstTask","Create First Task")})})]}),V&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:V}),t.jsx("p",{className:"onboarding-helper-text",children:c("setup.taskErrorHint","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:c("setup.projectMustBeSelected","A project must be selected before you can create tasks or import from GitHub.")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:c("setup.setUpProject","Set Up Project")})]}),t.jsx(nH,{items:rs}),Xt&&t.jsxs(t.Fragment,{children:[t.jsx(ea,{summary:c("setup.whatHappensWhenCreateTask","What happens when I create a task?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatHappensWhenCreateTaskBody","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:ut,disabled:se,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ys,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:c("setup.createNewTask","Create a New Task")}),t.jsx("span",{children:c("setup.createNewTaskSubtitle","Describe what you need built and AI will work on it")})]})]}),t.jsxs("button",{className:`onboarding-cta-card${Pn?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:It,disabled:se||!Pn,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ai,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:c("setup.importFromGitHub","Import from GitHub")}),t.jsx("span",{children:c("setup.importFromGitHubSubtitle","Turn GitHub issues into tasks you can track here")}),!Pn&&t.jsx("small",{className:"onboarding-cta-note",children:c("setup.requiresGitHubConnection","Requires GitHub connection")})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:[c("setup.createTasksAnytimeNote","You can create tasks anytime from the board, or use")," "," ",t.jsx("code",{children:"fn task create"})," ",c("setup.createTasksAnytimeNoteTerminal","in the terminal.")]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Es,{size:48,className:"success-icon"}),t.jsx("p",{children:c("setup.setupComplete","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:ht,disabled:se,children:c("setup.skipForNow","Skip for now")}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:an,children:c("setup.skipSetup","Skip setup →")}),t.jsx("button",{className:"btn btn-primary",onClick:At,children:c("setup.next","Next →")})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Wn,children:c("setup.back","← Back")}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:an,children:c("setup.skipGitHub","Skip GitHub →")}),t.jsx("button",{className:"btn btn-primary",onClick:At,children:c("setup.next","Next →")})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Wn,children:c("setup.back","← Back")}),t.jsx("button",{className:"btn btn-primary",onClick:At,disabled:!Xt,children:c("setup.next","Next →")})]}),x==="first-task"&&!C&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Wn,children:c("setup.back","← Back")}),t.jsx("button",{className:"btn btn-primary",onClick:ae,disabled:se,children:se?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:16,className:"animate-spin"}),t.jsx("span",{children:c("setup.saving","Saving…")})]}):c("setup.finishSetup","Finish Setup")})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:et,children:[t.jsx(Es,{size:16}),t.jsx("span",{children:c("setup.getStarted","Get Started")})]})]})]})})}function JN({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))})}function rH({isOpen:e,onClose:n,groupId:s,projectId:i,onOpenMemberTask:r}){const{t:o}=st("app"),[l,d]=a.useState(null),[c,m]=a.useState(!1),[p,h]=a.useState(!1),[u,f]=a.useState(!1),[b,y]=a.useState(null),v=a.useCallback(async()=>{if(s){m(!0);try{const j=await Vk(s,i);d(j.group),y(null)}catch(j){y(j instanceof Error?j.message:o("groupTask.errorLoading","Failed to load branch group"))}finally{m(!1)}}},[s,i]);a.useEffect(()=>{!e||!s||v()},[s,e,v]),a.useEffect(()=>{if(!e||!s)return;const j=i?`?projectId=${encodeURIComponent(i)}`:"";return li(`/api/events${j}`,{events:{"task:updated":S=>{try{const C=JSON.parse(S.data);if(i&&C.projectId&&C.projectId!==i)return}catch{}v()}},onReconnect:()=>{v()}})},[s,e,v,i]);const x=a.useMemo(()=>l?o("groupTask.completionText","{{landed}} of {{total}} members finished",{landed:l.completion.landed,total:l.completion.total}):"",[l,o]),k=a.useMemo(()=>!l||l.completion.total<=0?0:l.completion.landed/l.completion.total*100,[l]),w=a.useCallback(async()=>{if(s){h(!0);try{await qk(s,i),await v()}finally{h(!1)}}},[s,v,i]),g=a.useCallback(async()=>{if(s){f(!0);try{await Wk(s,i),await v()}finally{f(!1)}}},[s,v,i]);return!e||!s?null:t.jsx("div",{className:"modal-overlay open",onClick:n,children:t.jsxs("div",{className:"modal modal-lg group-task-modal",role:"dialog","aria-modal":"true","aria-label":o("groupTask.ariaLabel","Branch group details"),onClick:j=>j.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:o("groupTask.title","Branch Group {{id}}",{id:s})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":o("actions.closeModal","Close modal"),children:t.jsx(Fn,{})})]}),t.jsxs("div",{className:"modal-body group-task-modal-body",children:[c&&t.jsxs("div",{className:"card group-task-modal-state",children:[t.jsx(Et,{className:"spin"})," ",o("groupTask.loading","Loading branch group…")]}),!c&&b&&t.jsx("div",{className:"card group-task-modal-state group-task-modal-error",children:b}),!c&&!b&&!l&&t.jsx("div",{className:"card group-task-modal-state",children:o("groupTask.unavailable","Branch group unavailable")}),!c&&!b&&l&&t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"card group-task-modal-summary",children:[t.jsxs("div",{className:"group-task-modal-summary-row",children:[t.jsx("span",{className:"group-task-modal-label",children:o("groupTask.sharedBranch","Shared branch")}),t.jsx("strong",{children:l.branchName})]}),t.jsxs("div",{className:"group-task-modal-summary-row",children:[t.jsx("span",{className:"group-task-modal-label",children:o("groupTask.status","Status")}),t.jsx("span",{className:"badge",children:l.status})]}),t.jsx("div",{className:"group-task-modal-progress-text",children:x}),t.jsx("div",{className:"branch-group-card-progress",role:"progressbar","aria-valuenow":l.completion.landed,"aria-valuemin":0,"aria-valuemax":l.completion.total,children:t.jsx("span",{className:"branch-group-card-progress-fill",style:{width:`${k}%`}})})]}),t.jsxs("section",{className:"card group-task-modal-members-card",children:[t.jsx("h3",{children:o("groupTask.members","Members")}),t.jsx("ul",{className:"group-task-modal-members",children:l.members.map(j=>t.jsxs("li",{className:"group-task-modal-member",children:[t.jsx("span",{className:`status-dot ${j.landed?"status-dot--online":"status-dot--pending"}`}),t.jsxs("span",{className:"group-task-modal-member-main",children:[j.taskId," · ",j.title]}),t.jsx("span",{className:"badge",children:j.column}),t.jsx("span",{className:"group-task-modal-member-status",children:j.landed?t.jsx(gc,{}):t.jsx(yk,{})}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>r(j.taskId),children:o("groupTask.openTask","Open task")})]},j.taskId))})]}),l.prUrl&&t.jsx("section",{className:"card group-task-modal-pr",children:t.jsxs("a",{className:"btn",href:l.prUrl,target:"_blank",rel:"noreferrer",children:["PR #",l.prNumber??"—"," (",l.prState,") ",t.jsx(Vo,{})]})}),(l.prState==="merged"||l.prState==="closed")&&t.jsx("section",{className:"card group-task-modal-actions",children:t.jsx("span",{className:"badge",children:l.prState==="merged"?o("groupTask.prMerged","Group PR merged"):o("groupTask.prClosed","Group PR closed")})}),(l.completion.complete||l.prState==="open")&&l.prState!=="merged"&&l.prState!=="closed"&&t.jsxs("section",{className:"card group-task-modal-actions",children:[l.completion.complete&&(l.autoMerge?t.jsx("span",{className:"badge",children:o("groupTask.autoMergeEnabled","Auto-merge enabled")}):t.jsxs("button",{type:"button",className:"btn",onClick:()=>void w(),disabled:p,children:[p?t.jsx(Et,{className:"spin"}):null,l.prState==="none"?o("groupTask.openPR","Open PR"):o("groupTask.mergeIntoMain","Merge group into main")]})),l.prState==="open"&&t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void g(),disabled:u,children:[u?t.jsx(Et,{className:"spin"}):null,o("groupTask.abandonGroup","Abandon group")]})]})]})]})]})})}const oH=a.lazy(()=>ln(()=>import("./SetupWizardModal-Cw3RdN83.js"),__vite__mapDeps([20,1,21,4,22,23,24,5,6,2,3,7,25])).then(e=>({default:e.SetupWizardModal}))),lH=a.lazy(()=>ln(()=>import("./SettingsModal-Dje7N0hv.js"),__vite__mapDeps([26,1,4,27,5,6,2,3,7,28,12,13,29,30,31,32])).then(e=>({default:e.SettingsModal}))),cH=a.lazy(()=>ln(()=>import("./WorkflowNodeEditor-vnXnKvAr.js"),__vite__mapDeps([33,1,5,4,6,34,2,3,7,35])).then(e=>({default:e.WorkflowNodeEditor})));function dH(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{ln(()=>import("./SettingsModal-Dje7N0hv.js"),__vite__mapDeps([26,1,4,27,5,6,2,3,7,28,12,13,29,30,31,32]))},{timeout:1500})}function uH({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:d,projectActions:c,taskHandlers:m,taskOperations:p,deepLink:h,settings:u,onSettingsClose:f,onReopenOnboarding:b,onOpenApprovals:y}){const{pushNav:v,removeNav:x}=Mf(),[k,w]=a.useState(null),g=d.detailTask?(()=>{const q=n.find(ce=>ce.id===d.detailTask?.id);return q?"prompt"in d.detailTask?{...d.detailTask,...q,prompt:d.detailTask.prompt,log:d.detailTask.log}:q:d.detailTask})():null,j=f??d.closeSettings,S=a.useCallback(()=>{x(d.closeDetailTask),h.handleDetailClose()},[h,d.closeDetailTask,x]),C=a.useCallback(()=>{x(d.closeGroupModal),d.closeGroupModal()},[d.closeGroupModal,x]),E=a.useCallback(()=>{x(j),j()},[j,x]),F=a.useCallback(()=>{x(d.closeGitHubImport),d.closeGitHubImport()},[d.closeGitHubImport,x]),M=a.useCallback(()=>{x(d.closePlanning),d.closePlanning()},[d.closePlanning,x]),D=a.useCallback(()=>{x(d.closeSubtask),d.closeSubtask()},[d.closeSubtask,x]),_=a.useCallback(()=>{x(d.closeTerminal),d.closeTerminal()},[d.closeTerminal,x]),V=a.useCallback(()=>{x(d.closeScripts),d.closeScripts()},[d.closeScripts,x]),N=a.useCallback(()=>{x(d.closeFiles),d.closeFiles()},[d.closeFiles,x]),$=a.useCallback(()=>{x(d.closeTodos),d.closeTodos()},[d.closeTodos,x]),R=a.useCallback(()=>{x(d.closeUsage),d.closeUsage()},[d.closeUsage,x]),L=a.useCallback(()=>{x(d.closeSystemStats),d.closeSystemStats()},[d.closeSystemStats,x]),O=a.useCallback(()=>{x(d.closeSchedules),d.closeSchedules()},[d.closeSchedules,x]),J=a.useCallback(()=>{x(d.closeNewTask),d.closeNewTask()},[d.closeNewTask,x]),A=a.useCallback(()=>{x(d.closeActivityLog),d.closeActivityLog()},[d.closeActivityLog,x]),de=a.useCallback(()=>{x(d.closeGitManager),d.closeGitManager()},[d.closeGitManager,x]),B=a.useCallback(()=>{x(d.closeWorkflowEditor),d.closeWorkflowEditor()},[d.closeWorkflowEditor,x]),P=a.useCallback(()=>{x(d.closeAgents),d.closeAgents()},[d.closeAgents,x]),Z=a.useCallback(()=>{x(d.closeSetupWizard),d.closeSetupWizard()},[d.closeSetupWizard,x]),T=a.useCallback(()=>{d.openNewTask()},[d]),ie=a.useCallback(()=>{d.openGitHubImport()},[d]),le=a.useCallback((q,ce)=>{d.openDetailTask(q,ce),v({type:"modal",close:d.closeDetailTask})},[d,v]),be=a.useCallback(q=>{d.openGroupModal(q),v({type:"modal",close:d.closeGroupModal})},[d,v]),Le=a.useCallback(q=>{w(null),d.closeModelOnboarding(),le(q)},[d,le]),xe=a.useCallback(async q=>{const ce=await m.handleModalCreate(q);return d.modelOnboardingOpen&&w(ce),ce},[m.handleModalCreate,d.modelOnboardingOpen]);return a.useEffect(()=>{!d.modelOnboardingOpen&&k&&w(null)},[d.modelOnboardingOpen,k]),a.useEffect(()=>{dH()},[]),t.jsxs(t.Fragment,{children:[g&&t.jsx(ir,{children:t.jsx(m6,{task:g,projectId:e,tasks:n,onClose:S,onOpenDetail:le,mobileHeaderMode:d.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:p.moveTask,onDeleteTask:p.deleteTask,onMergeTask:p.mergeTask,onArchiveTask:p.archiveTask,onRetryTask:p.retryTask,onResetTask:p.resetTask,onDuplicateTask:p.duplicateTask,onTaskUpdated:d.updateDetailTask,addToast:r,prAuthAvailable:u.prAuthAvailable,onOpenWorkflowEditor:()=>d.openWorkflowEditor(),initialTab:d.detailTaskInitialTab})}),d.groupModalGroupId&&t.jsx(ir,{children:t.jsx(rH,{isOpen:!!d.groupModalGroupId,onClose:C,groupId:d.groupModalGroupId,projectId:e,onOpenMemberTask:q=>{const ce=n.find(De=>De.id===q);ce&&le(ce)}})}),d.settingsOpen&&t.jsx(ir,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(lH,{onClose:E,addToast:r,initialSection:d.settingsInitialSection,projectId:e,themeMode:u.themeMode,colorTheme:u.colorTheme,onThemeModeChange:u.setThemeMode,onColorThemeChange:u.setColorTheme,dashboardFontScalePct:u.dashboardFontScalePct,onDashboardFontScaleChange:u.setDashboardFontScalePct,onReopenOnboarding:b,onOpenApprovals:y,onOpenWorkflowSettings:()=>{E(),d.openWorkflowEditor("settings")}})})}),t.jsx(I3,{isOpen:d.githubImportOpen,onClose:F,onImport:m.handleGitHubImport,tasks:n,projectId:e}),t.jsx(ir,{children:t.jsx(U3,{isOpen:d.isPlanningOpen,onClose:M,onTaskCreated:m.handlePlanningTaskCreated,onTasksCreated:m.handlePlanningTasksCreated,tasks:n,initialPlan:d.planningInitialPlan??void 0,projectId:e,resumeSessionId:d.planningResumeSessionId})}),t.jsx(ir,{children:t.jsx(Q3,{isOpen:d.isSubtaskOpen,onClose:D,initialDescription:d.subtaskInitialDescription??"",onTasksCreated:m.handleSubtaskTasksCreated,projectId:e,resumeSessionId:d.subtaskResumeSessionId,onOpenGroupModal:be})}),t.jsx(k5,{isOpen:d.terminalOpen,onClose:_,initialCommand:d.terminalInitialCommand,projectId:e}),t.jsx(j5,{isOpen:d.scriptsOpen,onClose:V,addToast:r,onRunScript:d.runScript,projectId:e}),d.filesOpen&&t.jsx(G5,{initialWorkspace:d.fileBrowserWorkspace,initialFile:d.fileBrowserInitialFile,isOpen:!0,onClose:N,onWorkspaceChange:d.setFileWorkspace,projectId:e}),d.todosOpen&&t.jsx(J5,{isOpen:!0,onClose:$,addToast:r,projectId:e,onPlanningMode:d.openPlanningWithInitialPlan}),t.jsx(oU,{isOpen:d.usageOpen,onClose:R,projectId:e,anchorRect:d.usageAnchorRect}),t.jsx(IU,{isOpen:d.systemStatsOpen,onClose:L,projectId:e}),d.schedulesOpen&&t.jsx(NU,{onClose:O,addToast:r,projectId:e}),t.jsx(ir,{children:t.jsx(EU,{isOpen:d.newTaskModalOpen,onClose:J,tasks:n,onCreateTask:xe,addToast:r,projectId:e})}),t.jsx(zU,{isOpen:d.activityLogOpen,onClose:A,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:q=>{const ce=n.find(De=>De.id===q);ce&&le(ce)}}),t.jsx(ir,{children:t.jsx(UU,{isOpen:d.gitManagerOpen,onClose:de,tasks:n,addToast:r,projectId:e})}),d.workflowEditorOpen&&t.jsx(ir,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(cH,{isOpen:d.workflowEditorOpen,onClose:B,addToast:r,projectId:e,initialPanel:d.workflowEditorInitialPanel,initialAction:d.workflowEditorInitialAction,initialWorkflowId:d.workflowEditorInitialWorkflowId})})}),t.jsx(d8,{isOpen:d.agentsOpen,onClose:P,addToast:r,projectId:e}),d.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(oH,{onProjectRegistered:c.handleSetupComplete,onClose:Z})}),d.modelOnboardingOpen&&t.jsx(aH,{onComplete:c.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:c.handleAddProject,onOpenNewTask:T,onOpenGitHubImport:ie,firstCreatedTask:k,onViewTask:Le}),t.jsx(JN,{toasts:o,onRemove:l})]})}function mH(){return typeof window>"u"?!1:typeof window.fusionShell?.resetDesktopMode=="function"}async function hH(){const e=typeof window<"u"?window.fusionShell:void 0;try{await e?.resetDesktopMode?.()}catch{}const n=new URL(window.location.href);n.searchParams.delete("serverBaseUrl"),n.searchParams.delete("shellMode"),window.location.replace(n.toString())}function pH({errorMessage:e,isRetrying:n,onRetry:s,onManageConnection:i}){const{t:r}=st("app"),o=mH();return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:r("backend.connectionError","Can't reach the Fusion backend")}),t.jsx("p",{className:"settings-muted",children:r("backend.couldNotLoad","Fusion couldn't load your projects right now. Please make sure the backend is running and try again.")}),t.jsx("p",{className:"settings-muted",children:r("backend.error","Error: {{error}}",{error:e})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?r("backend.retrying","Retrying…"):r("backend.retryConnection","Retry Connection")}),o&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void hH(),children:r("backend.changeLaunchMode","Change Launch Mode…")}),i&&t.jsx("button",{type:"button",className:"btn",onClick:i,children:r("backend.manageConnection","Manage Connection")})]})]})}const gp=[{id:"projects",label:"dashboard.loaderSteps.projects"},{id:"project",label:"dashboard.loaderSteps.project"},{id:"tasks",label:"dashboard.loaderSteps.tasks"}];function fH(e,n){if(n==="ready")return"done";const s=gp.findIndex(r=>r.id===n),i=gp.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function gH({stage:e}){const{t:n}=st("app"),[s]=a.useState(()=>{const i=b_();return i&&(vs(Tn.TASKS_PREFIX),vs(Tn.PROJECTS),vs(Tn.CURRENT_PROJECT_ID),vs(Tn.AGENTS),vs(Tn.AGENT_STATS),vs(Tn.DOCUMENTS_PREFIX),vs(Tn.TODO_LISTS_PREFIX),vs(Tn.CHAT_ROOMS),vs(Tn.ACTIVE_CHAT_ROOM_ID),vs(Tn.CHAT_SESSIONS_PREFIX),vs(Tn.CHAT_MESSAGES_PREFIX),vs(Tn.CHAT_AGENTS_MAP_PREFIX),vs(Tn.MODELS),vs(Tn.DISCOVERED_SKILLS_PREFIX),vs(Tn.INSIGHTS_PREFIX),vs(Tn.INSIGHT_LATEST_RUN_PREFIX),vs(Tn.RESEARCH_RUNS_PREFIX),vs(Tn.RESEARCH_SELECTED_ID_PREFIX),vs(Tn.EVALS_RUNS_PREFIX),vs(Tn.EVALS_RESULTS_PREFIX),vs(Tn.MISSIONS_PREFIX),vs(Tn.MISSIONS_SELECTED_ID_PREFIX),vs(Tn.MAILBOX_INBOX_PREFIX),vs(Tn.MAILBOX_OUTBOX_PREFIX),vs(Tn.MAILBOX_UNREAD_COUNT_PREFIX)),i});return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":s?n("dashboard.updatingMessage","Updating Fusion dashboard"):n("dashboard.loadingMessage","Loading Fusion dashboard"),"data-stage":e,"data-version-update":s?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),s?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:n("dashboard.updatingVersion","Updating to a new frontend version...")}):t.jsx("p",{className:"dashboard-loader__message",children:n("dashboard.initializingDashboard","Initializing dashboard...")}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":n("dashboard.loadingProgress","Dashboard loading progress"),children:gp.map(i=>{const r=fH(i.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${r}`,"data-testid":`dashboard-loader-step-${i.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:r==="done"?"✓":r==="active"?t.jsx(Et,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:n(i.label,i.label==="dashboard.loaderSteps.projects"?"Loading projects":i.label==="dashboard.loaderSteps.project"?"Selecting project":"Fetching tasks")})]},i.id)})})]})})}function bH({visible:e}){const{t:n}=st("app");return t.jsx("div",{className:"top-progress-bar","data-visible":e?"true":"false",role:"progressbar","aria-busy":e,"aria-label":n("common.loading","Loading"),children:t.jsx("div",{className:"top-progress-bar__indicator"})})}const vH=5e3;function xH(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function yH(e,n,s){let i=0,r=0,o=0,l=0,d=0;for(const c of e){switch(c.column){case"in-progress":i++,Wd(c,n,s)&&o++;break;case"todo":l++;break;case"in-review":d++;break}c.blockedBy&&c.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:d}}function kH(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,d]=a.useState(!0),[c,m]=a.useState(null),p=a.useRef(null),h=a.useRef(null),u=a.useRef(!1),f=ul(),b=a.useCallback(w=>u.current&&_c(w,f.wasRecentlyHidden()),[f]),y=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{d(!0),m(null);const w=await dT(n);u.current=!0,o(w)}catch(w){if(w instanceof Error&&w.name==="AbortError")return;const g=w instanceof Error?w.message:"Failed to fetch executor stats";b(g)||m(g)}finally{d(!1)}},[n,b]);a.useEffect(()=>(y(),()=>{h.current&&h.current.abort()}),[y]),a.useEffect(()=>(p.current&&clearInterval(p.current),p.current=setInterval(()=>{y()},vH),()=>{p.current&&(clearInterval(p.current),p.current=null)}),[y]);const v=yH(e,s,i),x=xH(r.globalPause,r.enginePaused,v.runningTaskCount);return{stats:{...v,executorState:x,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:c,refresh:y}}const wH={planning:Ia,subtask:Vr,mission_interview:ri,milestone_interview:ri,slice_interview:ri,"cli-agent":ua};function jH({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{t:o}=st("app"),{confirm:l}=Yi(),[d,c]=a.useState(!1),[m,p]=a.useState(new Set),h=a.useRef(null),u=a.useRef(new Map),f=a.useRef(null),{activeTabMap:b}=pl(),y=a.useMemo(()=>so(),[]),v=a.useMemo(()=>({planning:o("backgroundTasks.typeLabel.planning","Planning"),subtask:o("backgroundTasks.typeLabel.subtask","Subtask Breakdown"),mission_interview:o("backgroundTasks.typeLabel.missionInterview","Mission Interview"),milestone_interview:o("backgroundTasks.typeLabel.milestoneInterview","Milestone Interview"),slice_interview:o("backgroundTasks.typeLabel.sliceInterview","Slice Interview"),"cli-agent":o("backgroundTasks.typeLabel.cliAgent","CLI Agent")}),[o]);if(a.useEffect(()=>{if(!d)return;const w=g=>{h.current&&!h.current.contains(g.target)&&c(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[d]),a.useEffect(()=>{const w=new Set,g=new Map;for(const j of e){const S=b.get(j.id),C=[j.status,j.updatedAt,S?.tabId??j.lockedByTab??"",S?.stale?"stale":"fresh"].join("|"),E=u.current.get(j.id);E&&E!==C&&w.add(j.id),g.set(j.id,C)}if(u.current=g,w.size!==0)return p(w),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{p(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[b,e]),e.length===0)return null;const x=e.length,k=s>0;return t.jsxs("div",{ref:h,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${k?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(w=>!w),title:s>0?o("backgroundTasks.pillTitleWithInput","{{count}} background AI task ({{needsInput}} needs input)",{count:x,needsInput:s}):o("backgroundTasks.pillTitle","{{count}} background AI task",{count:x}),children:[n>0&&t.jsx(Et,{size:12,className:"animate-spin"}),s>0&&n===0&&t.jsx(xh,{size:12}),t.jsx("span",{children:o("backgroundTasks.pillLabel","AI {{count}}",{count:x})})]}),d&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:o("backgroundTasks.popoverHeader","Background Tasks")}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(w=>{const g=wH[w.type],j=w.status==="generating",S=w.status==="awaiting_input",C=w.status==="error",E=b.get(w.id),F=E?.tabId??w.lockedByTab??null,M=!!(F&&F!==y&&!E?.stale),D=m.has(w.id);return t.jsxs("div",{className:`background-tasks-indicator__item${D?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:D?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:D?"translateY(-1px)":void 0},onClick:async()=>{M&&!await l({title:o("backgroundTasks.confirmTitle","Open Active Session"),message:o("backgroundTasks.confirmMessage","This session is active in another tab. Open anyway?")})||(i(w),c(!1))},children:[C?t.jsx(oi,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(g,{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:w.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?o("backgroundTasks.status.failed","Failed"):v[w.type],j&&` — ${o("backgroundTasks.status.generating","generating...")}`,S&&!M&&` — ${o("backgroundTasks.status.needsInput","needs input")}`,S&&M&&` — ${o("backgroundTasks.status.activeElsewhere","active in another tab")}`]})]}),j&&t.jsx(Et,{size:14,className:"background-tasks-indicator__session-icon animate-spin",style:{color:"var(--color-success)"}}),S&&!M&&t.jsx(xh,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),S&&M&&t.jsx(ll,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(w.id)},title:o("backgroundTasks.dismissButton","Dismiss"),children:t.jsx(Fn,{size:12})})]},w.id)})})]})]})}function NH(e,n){if(!e)return n("executor.noActivity","no activity");const s=Date.now(),i=new Date(e).getTime(),r=s-i,o=Math.floor(r/1e3),l=Math.floor(o/60),d=Math.floor(l/60),c=Math.floor(d/24);return c>0?n("executor.daysAgo","{{count}}d ago",{count:c}):d>0?n("executor.hoursAgo","{{count}}h ago",{count:d}):l>0?n("executor.minutesAgo","{{count}}m ago",{count:l}):o>10?n("executor.secondsAgo","{{count}}s ago",{count:o}):n("executor.justNow","just now")}function SH(e,n){switch(e){case"running":return{label:n("executor.stateRunning","Running"),color:"var(--color-success)",icon:Ds};case"paused":return{label:n("executor.statePaused","Paused"),color:"var(--triage)",icon:ia};case"idle":default:return{label:n("executor.stateIdle","Idle"),color:"var(--text-muted)",icon:Ws}}}function CH({tasks:e,projectId:n,taskStuckTimeoutMs:s,staleHighFanoutBlockerAgeThresholdMs:i,backgroundSessions:r,backgroundGenerating:o,backgroundNeedsInput:l,onOpenBackgroundSession:d,onDismissBackgroundSession:c,lastFetchTimeMs:m,currentProjectPath:p,onOpenProjectDirectory:h,keyboardOpen:u,hideWhenKeyboardOpen:f}){const{t:b}=st("app"),{stats:y,loading:v,error:x}=kH(e,n,s,m),[k,w]=a.useState(!1),g=a.useMemo(()=>SH(y.executorState,b),[y.executorState,b]),j=a.useMemo(()=>NH(y.lastActivityAt,b),[y.lastActivityAt,b]),S=a.useMemo(()=>{const E=Jp(e,{staleHighFanoutAgeThresholdMs:i??Pk});return Array.from(E.entries()).map(([M,D])=>({blockerId:M,entry:D})).filter(({entry:M})=>M.isHighFanout).sort((M,D)=>{if(D.entry.overlapBlockedTodoCount!==M.entry.overlapBlockedTodoCount)return D.entry.overlapBlockedTodoCount-M.entry.overlapBlockedTodoCount;const _=M.entry.escalation?.blockingAgeMs??0,V=D.entry.escalation?.blockingAgeMs??0;return V!==_?V-_:M.blockerId.localeCompare(D.blockerId,"en",{numeric:!0,sensitivity:"base"})})[0]??null},[e,i]),C=g.icon;return f?null:x?ju(x)?t.jsx("div",{className:"executor-status-bar executor-status-bar--connecting",role:"status","aria-label":b("executor.status","Executor status"),children:t.jsxs("span",{className:"executor-status-bar__connecting",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--connecting executor-status-bar__indicator--active","aria-hidden":"true"}),b("executor.connecting","Connecting…")]})}):t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":b("executor.status","Executor status"),children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(oa,{size:14}),x]})}):v&&y.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":b("executor.status","Executor status"),children:t.jsx("span",{className:"executor-status-bar__loading-text",children:b("executor.loading","Loading...")})}):t.jsxs("div",{className:`executor-status-bar ${y.executorState==="running"?"executor-status-bar--running":""}${u?" executor-status-bar--keyboard-open":""}`,role:"status","aria-label":b("executor.status","Executor status"),children:[r&&r.length>0&&d&&c&&t.jsxs(t.Fragment,{children:[t.jsx(jH,{sessions:r,generating:o??0,needsInput:l??0,onOpenSession:d,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:b("executor.queued","Queued")}),t.jsx("span",{className:"executor-status-bar__count",children:y.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 ${y.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:b("executor.running","Running")}),t.jsx("span",{className:"executor-status-bar__count",children:y.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:y.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),y.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:b("executor.stuck","Stuck")}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:y.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 ${y.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:b("executor.blocked","Blocked")}),t.jsx("span",{className:`executor-status-bar__count ${y.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:y.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:b("executor.inReview","In Review")}),t.jsx("span",{className:"executor-status-bar__count",children:y.inReviewCount})]}),S&&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:b("executor.overlapQueue","Overlap queue")}),t.jsxs("span",{className:"executor-status-bar__fanout-summary",title:b("executor.overlapBottleneck","{{status}} overlap bottleneck {{blockerId}}: {{count}} todo blocked via blockedBy (threshold {{threshold}})",{status:S.entry.escalation?b("executor.escalated","Escalated"):b("executor.temporary","Temporary"),blockerId:S.blockerId,count:S.entry.overlapBlockedTodoCount,threshold:Pp}),children:[S.blockerId," · ",S.entry.overlapBlockedTodoCount," todo",S.entry.escalation?b("executor.escalatedSuffix"," (escalated)"):""]})]})]}),p&&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${k?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>w(E=>!E),"aria-label":k?b("executor.hideProjectDir","Hide project directory"):b("executor.showProjectDir","Show project directory"),"aria-expanded":k,"data-testid":"executor-project-path-toggle",title:k?b("executor.hideProjectDir","Hide project directory"):b("executor.showProjectDir","Show project directory"),children:t.jsx(Zs,{size:12,"aria-hidden":"true"})}),k&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:h,title:p,"data-testid":"executor-project-path-link",children:p})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(ha,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:j})]}),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:g.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:g.color},children:g.label})]})]})}const _H={planning:Ia,subtask:Vr,mission_interview:ri,milestone_interview:ri,slice_interview:ri,"cli-agent":ua},Ay={planning:{key:"sessionBanner.typeLabel.planning",defaultVal:"Planning"},subtask:{key:"sessionBanner.typeLabel.subtask",defaultVal:"Subtask Breakdown"},mission_interview:{key:"sessionBanner.typeLabel.missionInterview",defaultVal:"Mission Interview"},milestone_interview:{key:"sessionBanner.typeLabel.milestoneInterview",defaultVal:"Milestone Interview"},slice_interview:{key:"sessionBanner.typeLabel.sliceInterview",defaultVal:"Slice Interview"},"cli-agent":{key:"sessionBanner.typeLabel.cliAgent",defaultVal:"CLI Agent"}},Ty={advance:{key:"sessionBanner.cli.advance",defaultVal:"Advance"},retry:{key:"sessionBanner.cli.retry",defaultVal:"Retry"},cancel:{key:"sessionBanner.cli.cancelTask",defaultVal:"Cancel task"},reauthenticate:{key:"sessionBanner.cli.reauthenticate",defaultVal:"Re-authenticate"},relaunch:{key:"sessionBanner.cli.relaunch",defaultVal:"Relaunch fresh"}},EH={userExited:{messageKey:"sessionBanner.cli.userExited",messageDefault:"Agent exited before completing",actions:["advance","retry","cancel"]},authFailed:{messageKey:"sessionBanner.cli.authFailed",messageDefault:"CLI authentication failed",actions:["reauthenticate","retry"]},"resume-exhausted":{messageKey:"sessionBanner.cli.resumeExhausted",messageDefault:"Couldn't resume the session",actions:["relaunch","cancel"]}},YN="fusion:session-banner-dismissed";function Yl(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function MH(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(YN);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[i,r]of Object.entries(n)){const o=typeof r=="number"?r:Yl(r);s.set(i,o)}return s}catch{return new Map}}function AH(e){if(!(typeof window>"u"))try{const n={};for(const[s,i]of e)n[s]=i;window.localStorage.setItem(YN,JSON.stringify(n))}catch{}}function Ry(e){return e==="awaiting_input"||e==="error"||e==="waiting_on_input"||e==="needs_attention"}const qa=MH();function TH({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i,onCliAction:r}){const{t:o}=st("app"),[l,d]=a.useState(0),c=()=>{AH(qa),d(v=>v+1)};a.useEffect(()=>{if(qa.size===0)return;const v=new Map(e.map(k=>[k.id,k]));let x=!1;for(const[k,w]of qa){const g=v.get(k);if(!g)continue;if(!Ry(g.status)){qa.delete(k),x=!0;continue}Yl(g.updatedAt)>w&&(qa.delete(k),x=!0)}x&&c()},[e]);const m=a.useMemo(()=>e.filter(v=>{if(!Ry(v.status))return!1;const x=qa.get(v.id);return x===void 0?!0:Yl(v.updatedAt)>x}),[e,l]);if(m.length===0)return null;const p=m.filter(v=>v.status==="awaiting_input"||v.status==="waiting_on_input").length,h=m.filter(v=>v.status==="error"||v.status==="needs_attention").length;let u="";p>0&&h>0?u=o(p===1?"sessionBanner.headerAwaitingAndErrorSingular":"sessionBanner.headerAwaitingAndErrorPlural",p===1?"{{awaitingCount}} AI session needs your input, {{errorCount}} failed":"{{awaitingCount}} AI sessions need your input, {{errorCount}} failed",{awaitingCount:p,errorCount:h}):p>0?u=o(p===1?"sessionBanner.headerAwaitingSingular":"sessionBanner.headerAwaitingPlural",p===1?"{{count}} AI session needs your input":"{{count}} AI sessions need your input",{count:p}):h>0&&(u=o(h===1?"sessionBanner.headerErrorSingular":"sessionBanner.headerErrorPlural",h===1?"{{count}} AI session failed":"{{count}} AI sessions failed",{count:h}));const f=v=>{qa.set(v.id,Math.max(Yl(v.updatedAt),Date.now())),c()},b=v=>{qa.delete(v.id),c(),n(v)},y=()=>{const v=Date.now();for(const x of m)qa.set(x.id,Math.max(Yl(x.updatedAt),v));c(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":o("sessionBanner.regionLabel","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(oi,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:u})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:y,children:[t.jsx(Fn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:o("sessionBanner.dismissAll","Dismiss all")})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:m.map(v=>{const x=_H[v.type],k=v.status==="error",w=v.type==="cli-agent"&&v.cliVariant?EH[v.cliVariant]:null;return w?t.jsxs("article",{className:"session-notification-banner__item session-notification-banner__item--cli session-notification-banner__item--error","data-session-type":v.type,"data-session-status":v.status,"data-cli-variant":v.cliVariant,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[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:v.title,children:v.title}),t.jsx("p",{className:"session-notification-banner__meta",children:o(w.messageKey,w.messageDefault)})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[w.actions.map(g=>t.jsx("button",{className:"session-notification-banner__resume","data-cli-action":g,onClick:()=>{r?.(v,g),(g==="cancel"||g==="advance")&&(f(v),s(v.id))},children:o(Ty[g].key,Ty[g].defaultVal)},g)),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{f(v),s(v.id)},"aria-label":o("sessionBanner.dismissItem","Dismiss {{title}}",{title:v.title}),children:t.jsx(Fn,{size:14,"aria-hidden":"true"})})]})]},v.id):t.jsxs("article",{className:`session-notification-banner__item${k?" session-notification-banner__item--error":""}`,"data-session-type":v.type,"data-session-status":v.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[k?t.jsx(oi,{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:v.title,children:v.title}),t.jsx("p",{className:"session-notification-banner__meta",children:k?o("sessionBanner.failed","Failed"):o(Ay[v.type].key,Ay[v.type].defaultVal)})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>b(v),children:k?o("sessionBanner.retry","Retry"):o("sessionBanner.resume","Resume")}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{f(v),s(v.id)},"aria-label":o("sessionBanner.dismissItem","Dismiss {{title}}",{title:v.title}),children:t.jsx(Fn,{size:14,"aria-hidden":"true"})})]})]},v.id)})})]})}const XN="fusion:cli-binary-banner-dismissed";function RH(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(XN)==="1"}catch{return!1}}function PH(){if(!(typeof window>"u"))try{window.localStorage.setItem(XN,"1")}catch{}}function IH({onOpenSettings:e}){const{t:n}=st("app"),[s,i]=a.useState(null),[r,o]=a.useState(()=>RH()),[l,d]=a.useState(!1),[c,m]=a.useState(null);a.useEffect(()=>{if(r)return;let w=!1;return GE().then(g=>{w||i(g)}).catch(()=>{}),()=>{w=!0}},[r]);const p=a.useCallback(async()=>{d(!0),m(null);try{const w=await KE();i({binary:w.binary,expectedVersion:w.expectedVersion,state:w.state,install:w.install}),w.installResult.success||m(w.installResult.permissionsHint||w.installResult.stderr||`Install failed (exit ${w.installResult.exitCode??"n/a"})`)}catch(w){m(w instanceof Error?w.message:String(w))}finally{d(!1)}},[]),h=a.useCallback(()=>{PH(),o(!0)},[]);if(r||!s||s.state==="installed"||s.state==="skipped")return null;const u=s.state==="version-mismatch",f=s.binary.version,b=s.expectedVersion,y=u?n("cli.updateTitle","Update the Fusion CLI"):n("cli.installTitle","Install the Fusion CLI"),v=u?t.jsxs(t.Fragment,{children:[n("cli.versionMismatchPrefix","Your installed")," ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," ",n("cli.versionMismatchInfix","but this dashboard expects")," "," ",t.jsxs("strong",{children:["v",b]}),". ",n("cli.versionMismatchSuffix","Update to stay in sync.")]}):t.jsx(t.Fragment,{children:n("cli.installBody","Get the {{fn}} and {{fusion}} commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell.",{fn:"fn",fusion:"fusion"})}),x=u?n("cli.updateButton","Update with npm"):n("cli.installButton","Install with npm"),k=u?n("cli.updating","Updating…"):n("cli.installing","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:y}),t.jsx("div",{className:"cli-binary-banner__text",children:v}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void p(),disabled:l,children:l?k:x}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:n("cli.openSettings","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":n("actions.dismiss","Dismiss"),onClick:h,children:t.jsx(Fn,{size:16})})]})}function DH({signal:e,onDismiss:n}){const{t:s}=st("app");return!e||!e.atRisk?null:t.jsxs("div",{className:`capacity-risk-banner${n?" capacity-risk-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsxs("div",{className:"capacity-risk-banner__content",children:[t.jsx("strong",{children:s("capacity.risk","Capacity risk:")})," ",s("capacity.status","Todo {{todoCount}} (threshold {{threshold}}) · In Progress {{inProgress}} · In Review {{inReview}} · Idle agents {{idleAgents}}",{todoCount:e.todoCount,threshold:e.threshold,inProgress:e.inProgressCount,inReview:e.inReviewCount,idleAgents:e.idleNonEphemeralAgentCount})]}),n?t.jsx("button",{type:"button",className:"capacity-risk-banner__dismiss touch-target","aria-label":s("capacity.dismiss","Dismiss capacity warning"),onClick:n,children:t.jsx(Fn,{"aria-hidden":"true"})}):null]})}function LH({isActive:e}){const{t:n}=st("app");return e?t.jsxs("div",{className:"test-mode-banner",role:"status","aria-live":"polite",children:[t.jsx(j0,{"aria-hidden":"true"}),t.jsx("span",{children:n("app.testMode","Test mode — no real AI calls")})]}):null}const QN="fusion:oauth-relogin-dismissed";function FH(){if(typeof window>"u")return new Set;try{const e=JSON.parse(window.localStorage.getItem(QN)??"[]");return Array.isArray(e)?new Set(e.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Py(e){typeof window>"u"||window.localStorage.setItem(QN,JSON.stringify(Array.from(e)))}function OH({onReLogin:e,pollIntervalMs:n}){const{t:s}=st("app"),[i,r]=a.useState([]),[o,l]=a.useState(()=>FH()),d=a.useCallback(async()=>{try{const{providers:u}=await Yo(),f=u.filter(b=>b.type==="oauth"&&b.expired===!0).map(b=>({id:b.id,name:b.name}));r(f),l(b=>{const y=new Set(f.map(x=>x.id)),v=new Set(Array.from(b).filter(x=>y.has(x)));return v.size===b.size?b:(Py(v),v)})}catch{}},[]);a.useEffect(()=>{d();const u=window.setInterval(d,n??3600*1e3);return()=>{window.clearInterval(u)}},[n,d]),a.useEffect(()=>{const u=f=>{const{detail:b}=f;b?.providerId&&r(y=>y.filter(v=>v.id!==b.providerId)),d()};return window.addEventListener(Ah,u),()=>{window.removeEventListener(Ah,u)}},[d]);const c=a.useMemo(()=>i.filter(u=>!o.has(u.id)),[o,i]);if(c.length===0)return null;const m=c.length===1,p=c.map(u=>u.name).join(", "),h=()=>{const u=new Set(o);for(const f of c)u.add(f.id);l(u),Py(u)};return t.jsxs("section",{className:"oauth-relogin-banner",role:"status","aria-live":"polite",children:[t.jsxs("div",{className:"oauth-relogin-banner__content",children:[t.jsx(oa,{"aria-hidden":"true"}),t.jsx("p",{className:"oauth-relogin-banner__message",children:m?s("auth.reloginRequired","Re-login required: {{provider}}. Your {{provider}} session expired — sign in again to keep agents running.",{provider:p}):s("auth.reloginRequiredMultiple","Re-login required: {{providers}}",{providers:p})})]}),t.jsxs("div",{className:"oauth-relogin-banner__actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>e(m?c[0]?.id:void 0),children:s("auth.relogin","Re-login")}),t.jsx("button",{type:"button",className:"btn-icon oauth-relogin-banner__dismiss","aria-label":s("actions.dismissOAuth","Dismiss OAuth re-login banner"),onClick:h,children:t.jsx(Fn,{"aria-hidden":"true"})})]})]})}function $H(e,n){switch(e){case"duplicate_active_id":return n("health.anomaly.duplicateActiveId","Duplicate active task ID");case"id_in_active_and_archived":return n("health.anomaly.idInBothStorages","Task ID present in active and archived storage");case"next_sequence_at_or_below_used":return n("health.anomaly.sequenceOverlap","Allocator next sequence overlaps an existing task ID");case"task_row_outside_known_prefix":return n("health.anomaly.unknownPrefix","Task row uses a prefix outside allocator state");default:return e}}function zH(e){return e.length<=5?e.join(", "):`${e.slice(0,5).join(", ")} +${e.length-5} more`}function BH({report:e,recommendedAction:n,onRefresh:s}){const{t:i}=st("app"),[r,o]=a.useState(!1),[l,d]=a.useState(null);if(e.status!=="anomaly")return null;const c=async()=>{o(!0),d(null);try{const m=await Bk();s?.(m.taskIdIntegrity,m.taskIdIntegrity.recommendedAction)}catch(m){d(m instanceof Error?m.message:i("health.refreshFailed","Failed to refresh integrity status."))}finally{o(!1)}};return t.jsxs("section",{className:"task-id-integrity-banner",role:"alert","aria-live":"assertive",children:[t.jsxs("div",{className:"task-id-integrity-banner__header",children:[t.jsxs("div",{className:"task-id-integrity-banner__headline-wrap",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx(oa,{"aria-hidden":"true"}),t.jsx("h2",{className:"task-id-integrity-banner__headline",children:i("health.anomalyDetected","Task ID integrity anomaly detected")})]}),t.jsxs("button",{type:"button",className:"btn btn-sm task-id-integrity-banner__refresh",onClick:()=>{c()},disabled:r,children:[t.jsx(xs,{className:r?"task-id-integrity-banner__refresh-icon task-id-integrity-banner__refresh-icon--spinning":"task-id-integrity-banner__refresh-icon","aria-hidden":"true"}),r?i("health.rechecking","Re-checking…"):i("health.recheck","Re-check")]})]}),t.jsx("p",{className:"task-id-integrity-banner__body",children:i("health.anomalyBody","Fusion found allocator state that can cause task IDs to be reused or overwrite live task records.")}),t.jsx("ul",{className:"task-id-integrity-banner__list",children:e.anomalies.map(m=>t.jsxs("li",{className:"task-id-integrity-banner__item",children:[t.jsx("strong",{className:"task-id-integrity-banner__item-title",children:$H(m.kind,i)}),t.jsx("span",{className:"task-id-integrity-banner__item-detail",children:m.details}),t.jsx("code",{className:"task-id-integrity-banner__ids",children:zH(m.affectedIds)})]},`${m.kind}:${m.prefix}:${m.affectedIds.join(",")}`))}),t.jsx("p",{className:"task-id-integrity-banner__footer",children:n}),l?t.jsx("p",{className:"task-id-integrity-banner__error",children:l}):null]})}function UH({errors:e,lastCheckedAt:n,onRefresh:s,refreshing:i,refreshError:r}){const{t:o}=st("app");if(e.length===0)return null;const l=e.slice(0,5),d=n?new Date(n).toLocaleString():null;return t.jsxs("section",{className:"db-corruption-banner",role:"alert","aria-live":"assertive",children:[t.jsxs("div",{className:"db-corruption-banner__header",children:[t.jsxs("div",{className:"db-corruption-banner__headline-wrap",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx(oa,{"aria-hidden":"true"}),t.jsxs("div",{className:"db-corruption-banner__headline-copy",children:[t.jsx("h2",{className:"db-corruption-banner__headline",children:o("dbBanner.title","Database corruption detected")}),d?t.jsx("p",{className:"db-corruption-banner__meta",children:o("dbBanner.lastChecked","Last checked: {{checkedAtLabel}}",{checkedAtLabel:d})}):null]})]}),t.jsxs("button",{type:"button",className:"btn btn-sm db-corruption-banner__refresh",onClick:()=>{s()},disabled:i,children:[t.jsx(xs,{className:i?"db-corruption-banner__refresh-icon db-corruption-banner__refresh-icon--spinning":"db-corruption-banner__refresh-icon","aria-hidden":"true"}),i?o("dbBanner.refreshing","Refreshing…"):o("dbBanner.refreshHealth","Refresh health")]})]}),t.jsx("p",{className:"db-corruption-banner__body",children:o("dbBanner.body","Fusion's background SQLite integrity check reported corruption. Review the failing objects below before continuing critical operations.")}),t.jsx("ul",{className:"db-corruption-banner__list",children:l.map((c,m)=>t.jsx("li",{className:"db-corruption-banner__item",children:t.jsx("code",{className:"db-corruption-banner__error-code",children:c})},`${m}:${c}`))}),t.jsxs("p",{className:"db-corruption-banner__footer",children:[t.jsx("strong",{className:"db-corruption-banner__footer-label",children:o("dbBanner.whatToDo","What to do:")})," ",t.jsx(Ga,{i18nKey:"app:dbBanner.instructions",defaults:"Back up the project, try <cmd>fn db --vacuum</cmd> if the database still opens cleanly, and restore from a known-good backup if corruption persists. See <docsLink>docs/storage.md</docsLink> for the storage layout and recovery guidance.",components:{cmd:t.jsx("code",{}),docsLink:t.jsx("a",{href:"docs/storage.md"})}})]}),r?t.jsx("p",{className:"db-corruption-banner__error",children:r}):null]})}function HH({latestVersion:e,currentVersion:n,onDismiss:s}){const{t:i}=st("app");return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:[t.jsx(Ga,{i18nKey:"app:updateBanner.message",defaults:"Update available: v{{latestVersion}} (current: v{{currentVersion}}). Run <code>fn update</code> for an installed CLI, or pull this source checkout.",values:{latestVersion:e,currentVersion:n},components:{code:t.jsx("code",{})}})," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:i("updateBanner.releaseNotes","Release notes")})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:i("updateBanner.learnMore","Learn more")})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":i("updateBanner.dismissLabel","Dismiss update notice"),onClick:s,children:t.jsx(Fn,{size:16,"aria-hidden":"true"})})]})}function VH(e){return e.length>7?e.slice(0,7):e}function lh(e){return e instanceof Ka?e.message||"Request failed":e instanceof Error&&e.message?e.message:"Request failed"}function Iy(e){const n=["button","[href]","input","select","textarea",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(e.querySelectorAll(n)).filter(s=>!(s.hasAttribute("disabled")||s.getAttribute("aria-hidden")==="true"))}function qH({open:e,onClose:n,worktreePath:s,integrationBranch:i,stashSha:r,stashLabel:o,conflictedFiles:l,autostashOutcome:d,taskId:c}){const{t:m}=st("app"),p=Kj(),h=a.useRef(null),u=a.useRef(null),[f,b]=a.useState(d==="failed"?[]:l),[y,v]=a.useState(!1),[x,k]=a.useState(null),[w,g]=a.useState("idle");a.useEffect(()=>{e&&(b(d==="failed"?[]:l),k(null),g("idle"))},[d,l,e]),a.useEffect(()=>{if(!e)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const M=h.current;if(M){const _=Iy(M),V=_.find(N=>N.getAttribute("aria-label")==="Copy stash reference")??_[0];V?V.focus():M.focus()}const D=_=>{if(_.key==="Escape"){_.preventDefault(),n(!1);return}if(_.key!=="Tab")return;const V=h.current;if(!V)return;const N=Iy(V);if(N.length===0){_.preventDefault(),V.focus();return}const $=N[0],R=N[N.length-1],L=document.activeElement;_.shiftKey&&L===$?(_.preventDefault(),R.focus()):!_.shiftKey&&L===R&&(_.preventDefault(),$.focus())};return document.addEventListener("keydown",D),()=>{document.removeEventListener("keydown",D);const _=u.current;_&&_.isConnected&&_.focus(),u.current=null}},[e,n]);const j=a.useMemo(()=>`Stash ref: ${VH(r)} (${o})`,[o,r]);if(!e)return null;const S=async(M,D)=>{v(!0),k(null);try{const _=await I("/git/stash-resolve",{method:"POST",body:JSON.stringify({worktreePath:s,stashSha:r,file:M,choice:D,taskId:c})});b(Array.isArray(_.remainingConflicts)?_.remainingConflicts:[])}catch(_){k(lh(_))}finally{v(!1)}},C=async()=>{v(!0),k(null);try{(await I("/git/stash-drop",{method:"POST",body:JSON.stringify({worktreePath:s,stashSha:r,taskId:c})})).dropped&&n(!0)}catch(M){k(lh(M))}finally{v(!1)}},E=async()=>{v(!0),k(null);try{const M=await I("/git/stash-apply",{method:"POST",body:JSON.stringify({worktreePath:s,stashSha:r,taskId:c})});M.conflict&&b(Array.isArray(M.conflictedFiles)?M.conflictedFiles:[])}catch(M){k(lh(M))}finally{v(!1)}},F=async()=>{try{await navigator.clipboard.writeText(r),g("copied")}catch{g("failed")}};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"stash-conflict-modal-title",children:t.jsxs("div",{className:"modal stash-conflict-modal",ref:h,tabIndex:-1,children:[t.jsx("div",{className:"modal-header",children:t.jsx("h3",{id:"stash-conflict-modal-title",children:m("git.stashConflict.title","Resolve auto-stash conflicts")})}),t.jsx("p",{className:"stash-conflict-modal__summary",children:m("git.stashConflict.summary","Pulled {{branch}}, but restoring local edits from stash produced conflicts.",{branch:i})}),d==="failed"?t.jsx("p",{className:"stash-conflict-modal__warning",children:m("git.stashConflict.failedWarning","Automatic restore failed. Your changes are preserved in the stash above; use git stash apply <ref> to recover manually, or use Retry below.")}):null,t.jsxs("div",{className:"stash-conflict-modal__stash-row",children:[t.jsx("span",{children:j}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:F,"aria-label":"Copy stash reference",children:t.jsx(Pa,{"aria-hidden":"true"})})]}),w==="copied"?t.jsx("p",{className:"stash-conflict-modal__hint",role:"status",children:m("git.stashConflict.copied","Stash SHA copied.")}):null,w==="failed"?t.jsx("p",{className:"stash-conflict-modal__error",role:"alert",children:m("git.stashConflict.copyFailed","Could not copy stash SHA.")}):null,f.length>0?t.jsx("div",{className:"stash-conflict-modal__list",role:"list",children:f.map(M=>t.jsxs("div",{className:"stash-conflict-row",role:"listitem",children:[t.jsx("code",{className:"stash-conflict-row__path",children:M}),t.jsxs("div",{className:"stash-conflict-row__actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",disabled:y,onClick:()=>void S(M,"ours"),children:m("git.stashConflict.keepMine","Keep mine")}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:y,onClick:()=>void S(M,"theirs"),children:m("git.stashConflict.keepIncoming","Keep incoming")}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:y,onClick:()=>p?.openFile(M,{workspace:s}),children:m("git.stashConflict.openInEditor","Open in editor")})]})]},M))}):null,x?t.jsx("p",{className:"stash-conflict-modal__error",role:"alert",children:x}):null,t.jsxs("div",{className:"modal-actions",children:[t.jsx("div",{className:"modal-actions-left",children:t.jsx("button",{type:"button",className:"btn",disabled:y,onClick:()=>void E(),children:m("git.stashConflict.retryRestore","Retry restore")})}),t.jsxs("div",{className:"modal-actions-right",children:[t.jsx("button",{type:"button",className:"btn",disabled:y,onClick:()=>n(!1),children:m("actions.close","Close")}),t.jsx("button",{type:"button",className:"btn btn-warning",disabled:y||f.length>0,onClick:()=>void C(),children:m("git.stashConflict.dropStash","Drop stash")})]})]})]})})}function ZN(e){return`kb:merge-advance-notice-dismissed:${e??"default"}`}function eS(e){return`kb:${e??"default"}:merge-advance-force-with-lease`}function Dy(e){try{const n=window.localStorage.getItem(ZN(e));if(!n)return[];const s=JSON.parse(n);return Array.isArray(s)?s.filter(i=>typeof i=="string"):[]}catch{return[]}}function WH(e,n){try{window.localStorage.setItem(ZN(e),JSON.stringify(n.slice(-50)))}catch{}}function Ly(e){try{return window.sessionStorage.getItem(eS(e))==="1"}catch{return!1}}function GH(e,n){try{window.sessionStorage.setItem(eS(e),n?"1":"0")}catch{}}function KH({projectId:e,apiBase:n="/api"}){const[s,i]=a.useState([]),[r,o]=a.useState(()=>Dy(e)),[l,d]=a.useState("idle"),[c,m]=a.useState(null),[p,h]=a.useState(null),[u,f]=a.useState("idle"),[b,y]=a.useState(()=>Ly(e)),v=a.useRef(null);a.useEffect(()=>{o(Dy(e)),y(Ly(e))},[e]),a.useEffect(()=>()=>{v.current!==null&&window.clearTimeout(v.current)},[]);const x=a.useCallback(async()=>{try{const F=new URLSearchParams({limit:"5"});e&&F.set("projectId",e);const M=await I(`/tasks/merge-advance-events?${F.toString()}`);i(Array.isArray(M.events)?M.events:[])}catch{i([])}},[e]),k=a.useCallback(async()=>{if(!e){h(null);return}try{const F=await I(`/projects/${encodeURIComponent(e)}/merge-advance/push-status`);h(F)}catch{h(null)}},[e]);a.useEffect(()=>{x(),k();const F=e?`?projectId=${encodeURIComponent(e)}`:"",M=li(`${n}/events${F}`,{events:{"task:merged":()=>{x(),k()}}});return()=>M()},[n,x,k,e]);const w=a.useMemo(()=>{const F=new Set(r);return s.find(M=>{if(M.succeeded!==!0||M.userCheckout===null||M.userCheckout.worktreePath.trim().length===0||F.has(M.toSha))return!1;const D=M.userCheckout.worktreePath,_=new Set(["clean-sync","synced-with-edits-restored"]);return!(M.autoSync??[]).some(N=>N.worktreePath===D&&_.has(N.outcome))})},[r,s]),g=a.useCallback(()=>{if(!w)return;const F=[...r.filter(M=>M!==w.toSha),w.toSha].slice(-50);o(F),WH(e,F)},[r,w,e]),j=a.useCallback(async()=>{if(w?.userCheckout){d(w.userCheckout.dirty||w.userCheckout.untrackedCount>0?"stashing":"pending");try{const F=e?`?projectId=${encodeURIComponent(e)}`:"",M=await I(`/git/pull${F}`,{method:"POST",body:JSON.stringify({worktreePath:w.userCheckout.worktreePath,integrationBranch:w.integrationBranch,taskId:w.taskId})});M.kind==="stash-conflict"?m({stashSha:M.stashSha,stashLabel:M.stashLabel,conflictedFiles:M.conflictedFiles,autostashOutcome:M.autostashOutcome}):g(),d("idle"),await k()}catch(F){F instanceof Ka?d({error:F.message||"Pull failed"}):F instanceof Error&&F.message?d({error:F.message}):d({error:"Pull failed"})}}},[g,k,w,e]),S=a.useCallback(F=>{y(F),GH(e,F)},[e]),C=a.useCallback(()=>{f("idle")},[]),E=a.useCallback(async()=>{if(e){f("pending");try{const F=await I(`/projects/${encodeURIComponent(e)}/merge-advance/push-origin`,{method:"POST",body:JSON.stringify({forceWithLease:b,expectedLocalSha:p?.localSha})});if(F.ok){f("ok"),await k(),v.current!==null&&window.clearTimeout(v.current),v.current=window.setTimeout(()=>f("idle"),2e3);return}f({error:F.message??F.outcome,outcome:F.outcome==="ok"?"failed":F.outcome,stderr:F.stderrPreview})}catch(F){const M=F instanceof Error?F.message:"Push failed";f({error:M,outcome:"failed"})}}},[k,b,e,p?.localSha]);return{notice:w,dismiss:g,pull:j,pullState:l,conflictState:c,setConflictState:m,pushStatus:p,pushState:u,push:E,clearPushError:C,forceWithLease:b,setForceWithLease:S}}function Fy(e){return e?e.length>7?e.slice(0,7):e:""}function JH({projectId:e,apiBase:n="/api"}){const{t:s}=st("app"),i=a.useRef(null),{notice:r,dismiss:o,pull:l,pullState:d,conflictState:c,setConflictState:m,pushStatus:p,pushState:h,push:u,clearPushError:f,forceWithLease:b,setForceWithLease:y}=KH({projectId:e,apiBase:n});if(!r||!r.userCheckout)return null;const v=r.userCheckout,x=v.dirty||v.untrackedCount>0,k=d==="pending"||d==="stashing",w=typeof d=="object"?d.error:null,g=()=>{const S=document.activeElement,C=S instanceof HTMLElement&&i.current?.contains(S);o(),C&&document.body.focus()},j=()=>{if(!p||p.aheadCount<=0)return null;const S=h==="pending"||p.canPush===!1||k,C=b?s("merge.pushForceWithLease","Push (force-with-lease)"):s("merge.pushToOrigin","Push to origin");return t.jsxs("section",{className:"merge-advance-notice__push",children:[t.jsx("p",{className:"merge-advance-notice__push-heading",children:s("merge.pushHeading","Push {{branch}} to origin — ahead by {{count}} commit{{plural}}.",{branch:p.integrationBranch,count:p.aheadCount,plural:p.aheadCount===1?"":"s"})}),t.jsxs("div",{className:"merge-advance-notice__push-actions",children:[h==="ok"?t.jsx("span",{children:s("merge.pushSuccess","Pushed to origin/{{branch}} @ {{sha}}.",{branch:p.integrationBranch,sha:Fy(p.remoteSha)})}):t.jsx("button",{type:"button",className:`btn btn-sm ${b?"btn-warning":""}`.trim(),disabled:S,onClick:()=>{u()},children:h==="pending"?s("merge.pushing","Pushing…"):C}),!p.canPush&&p.disabledReason?t.jsx("span",{className:"merge-advance-notice__push-error",children:p.disabledReason==="no-remote"?s("merge.disabledNoRemote","No `origin` remote configured."):p.disabledReason==="no-upstream"?s("merge.disabledNoUpstream","Branch has no upstream on origin."):p.disabledReason==="merge-locked"?s("merge.disabledMergeLocked","Push paused — a Fusion merge is in progress."):null}):null]}),typeof h=="object"&&(h.outcome==="rejected-non-ff"||h.outcome==="sha-mismatch")?t.jsxs("div",{className:"merge-advance-notice__push-error",role:"alert",children:[t.jsx("span",{children:h.error})," ",t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l()},children:s("merge.smartPull","Smart Pull")})]}):null,typeof h=="object"&&(h.outcome==="rejected-other"||h.outcome==="failed")?t.jsxs("div",{className:"merge-advance-notice__push-error",role:"alert",children:[t.jsx("span",{children:h.error}),h.stderr?t.jsx("pre",{children:h.stderr}):null,t.jsx("button",{type:"button",className:"btn btn-sm",onClick:f,children:s("actions.dismiss","Dismiss")})]}):null,t.jsxs("details",{className:"merge-advance-notice__push-advanced",children:[t.jsx("summary",{children:s("merge.advanced","Advanced")}),t.jsxs("label",{children:[t.jsx("input",{type:"checkbox",checked:b,onChange:E=>y(E.target.checked)})," ",s("merge.forceWithLeaseLabel","Allow force-with-lease (use only when you know origin diverged intentionally)")]})]})]})};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:i,className:"merge-advance-notice",role:"status","aria-live":"polite",children:[t.jsxs("div",{className:"merge-advance-notice__content",children:[t.jsx("strong",{children:s("merge.advancedTo","{{branch}} advanced to {{sha}}.",{branch:r.integrationBranch,sha:Fy(r.toSha)})})," ",s("merge.checkedOutBehind","Your checked-out copy at {{path}} is behind.",{path:v.worktreePath}),x?s("merge.changesWillAutoStash"," (local changes will be auto-stashed and restored)"):"",w?t.jsxs("span",{className:"merge-advance-notice__error",role:"alert",children:[" ",w]}):null,k?t.jsxs("span",{className:"merge-advance-notice__hint",children:[" ",s("merge.pulling","Pulling…")]}):null,j()]}),t.jsxs("div",{className:"merge-advance-notice__actions",children:[c?null:t.jsx("button",{type:"button",className:"btn btn-sm",disabled:k,onClick:()=>{l()},children:s("actions.pull","Pull")}),t.jsx("button",{type:"button",className:"merge-advance-notice__dismiss touch-target","aria-label":s("merge.dismissNotice","Dismiss merge advance notice"),onClick:g,children:t.jsx(Fn,{"aria-hidden":"true"})})]})]}),t.jsx(qH,{open:c!==null,onClose:S=>{m(null),S&&g()},worktreePath:v.worktreePath,integrationBranch:r.integrationBranch,stashSha:c?.stashSha??"",stashLabel:c?.stashLabel??"",conflictedFiles:c?.conflictedFiles??[],autostashOutcome:c?.autostashOutcome??"conflict-needs-manual",taskId:r.taskId})]})}function YH({pendingCount:e,onOpenMailbox:n,onDismiss:s}){const{t:i}=st("app"),r=e===1?i("approval.requestSingular","request"):i("approval.requestPlural","requests");return t.jsx("section",{className:"approval-notification-banner",role:"region","aria-live":"polite","aria-label":i("approval.requests","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(oa,{"aria-hidden":"true"}),t.jsx("span",{children:i("approval.needAttention","{{count}} approval {{noun}} need your attention",{count:e,noun:r})})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(mr,{"aria-hidden":"true"}),t.jsx("span",{children:i("approval.openMailbox","Open Mailbox")})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":i("approval.dismissBanner","Dismiss approval notification banner"),children:t.jsx(Fn,{"aria-hidden":"true"})})]})]})})}const XH="https://github.com/Runfusion/Fusion";function QH({onStar:e,onDismiss:n}){const s=()=>{e?.(),n()};return t.jsxs("section",{className:"card github-star-prompt",role:"region","aria-live":"polite","aria-label":"GitHub star prompt",children:[t.jsxs("div",{className:"github-star-prompt__header",children:[t.jsxs("div",{className:"github-star-prompt__title-wrap",children:[t.jsx(Od,{"aria-hidden":"true"}),t.jsx("h3",{children:"Enjoying Fusion?"})]}),t.jsx("button",{type:"button",className:"btn-icon github-star-prompt__dismiss",onClick:n,"aria-label":"Dismiss GitHub star prompt",children:t.jsx(Fn,{"aria-hidden":"true"})})]}),t.jsx("p",{children:"If Fusion has saved you time, a GitHub star goes a long way. It helps other developers discover the project and keeps the team motivated to ship improvements."}),t.jsx("div",{className:"github-star-prompt__actions",children:t.jsxs("a",{className:"btn btn-sm github-star-prompt__cta",href:XH,target:"_blank",rel:"noopener noreferrer",onClick:s,children:[t.jsx(Od,{"aria-hidden":"true"}),t.jsx("span",{children:"Star on GitHub"})]})})]})}function ZH({onResume:e}){const{t:n}=st("app"),s=D8();if(!s)return null;const i=s.completedSteps.length,r=dr.length,o=i>0?n("onboarding.progressText","{{completed}} of {{total}} step{{pluralS}} complete — You're on the ",{completed:i,total:r,pluralS:i!==1?"s":""}):n("onboarding.onTheStep","You're on the ");return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":n("onboarding.resumeOnboarding","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($s,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:n("onboarding.continueSetup","Continue Setup")}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[o,t.jsx("strong",{children:s.label})," ",n("onboarding.stepContinue","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:()=>{Zi("onboarding:resumed",{source:"resume-card",resumedFromStep:s.currentStep}),e()},children:[t.jsx(Ds,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:n("onboarding.continueOnboarding","Continue onboarding")})]})})]})}function e9({onOpenSettings:e,onOpenModelOnboarding:n}){const{t:s}=st("app"),i=ol(),r=qN(),[o,l]=a.useState(!0),[d,c]=a.useState(!1),[m,p]=a.useState(!1),[h,u]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!i||r){l(!1);return}let k=!1;return(async()=>{try{l(!0),c(!1);const[g,j]=await Promise.all([Yo(),Ja()]);if(k)return;const S=g.providers??[],C=S.find(_=>_.id==="github"),F=!S.some(_=>_.id!=="github"&&_.authenticated),M=!j.defaultProvider&&!j.defaultModelId,D=C?!C.authenticated:!1;u({needsAiProvider:F,needsDefaultModel:M,needsGitHub:D})}catch{k||c(!0)}finally{k||l(!1)}})(),()=>{k=!0}},[i,r]);const f=a.useCallback(()=>{P8(),p(!0)},[]),b=a.useCallback(()=>{n()},[n]),y=a.useCallback(()=>{e("global-models")},[e]),v=a.useCallback(()=>{e("authentication")},[e]),x=a.useMemo(()=>{const k=[];return h.needsAiProvider&&k.push({id:"ai-provider",title:s("setup.connectAiProvider","Connect AI Provider"),description:s("setup.connectAiProviderDesc","Connect an AI provider to enable AI agents for task planning and code generation"),actionLabel:s("setup.setUpAi","Set Up AI"),onAction:b,icon:Ws}),h.needsDefaultModel&&k.push({id:"default-model",title:s("setup.selectDefaultModel","Select Default Model"),description:s("setup.selectDefaultModelDesc","Choose a default AI model for task execution"),actionLabel:s("setup.chooseModel","Choose Model"),onAction:y,icon:_k}),h.needsGitHub&&k.push({id:"github",title:s("setup.connectGitHub","Connect GitHub"),description:s("setup.connectGitHubDesc","Connect GitHub to import issues and track pull requests"),actionLabel:s("setup.connectGitHubButton","Connect GitHub"),onAction:v,icon:ai}),k},[h.needsAiProvider,h.needsDefaultModel,h.needsGitHub,v,y,b]);return!i||r||m||o||d||x.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":s("setup.ariaSetupRecommendations","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(Ia,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:s("setup.recommendedNextSteps","Recommended Next Steps")}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:s("setup.completeSetup","Complete these setup items to get the most out of Fusion.")}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:x.map(k=>{const w=k.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(w,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:k.title}),t.jsx("span",{children:k.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:k.onAction,children:k.actionLabel})]},k.id)})}),t.jsx(fr,{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":s("setup.ariaDismissRecommendations","Dismiss recommendations"),children:t.jsx(Fn,{size:16,"aria-hidden":!0})})]})}function t9({navOffsetHeight:e,paddingBottom:n,tabHeights:s}){const i=Math.max(0,...s.filter(l=>Number.isFinite(l)));if(i>0)return Math.max(44,Math.ceil(i));const r=Number.isFinite(n)?n:0,o=e-r;return Math.max(44,Math.ceil(o))}function n9({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 Ol(e){return e>99?"99+":String(e)}function s9({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:d,onOpenMailbox:c,mailboxUnreadCount:m=0,mailboxPendingApprovalCount:p=0,chatHasUnreadResponse:h=!1,stashOrphanCount:u=0,onOpenGitManager:f,onOpenWorkflowEditor:b,onOpenSchedules:y,onOpenScripts:v,onToggleTerminal:x,onOpenFiles:k,onOpenTodos:w,todosOpen:g=!1,onOpenGitHubImport:j,onOpenPlanning:S,onResumePlanning:C,activePlanningSessionCount:E=0,onOpenUsage:F,onRunScript:M,projectId:D,onViewAllProjects:_,showSkillsTab:V,experimentalFeatures:N,onOpenNodes:$,pluginDashboardViews:R=[],shellConnectionControl:L}){const{t:O}=st("app"),J=Ji(),[A,de]=a.useState(!1),[B,P]=a.useState(!1),[Z,T]=a.useState({}),[ie,le]=a.useState(!1),be=a.useRef(null),Le=a.useMemo(()=>Object.entries(Z).sort(([X],[ye])=>X.localeCompare(ye)),[Z]);a.useEffect(()=>{if(!B)return;let X=!1;return le(!0),Hd(D).then(ye=>{X||T(ye)}).catch(()=>{X||T({})}).finally(()=>{X||le(!1)}),()=>{X=!0}},[B,D]);const xe=a.useCallback(()=>de(!1),[]),q=a.useCallback(X=>{xe(),X?.()},[xe]);if(a.useEffect(()=>{if(!A)return;const X=ye=>{ye.key==="Escape"&&de(!1)};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[A]),a.useLayoutEffect(()=>{const X=be.current;if(!X||typeof document>"u")return;const ye=()=>{const ue=window.getComputedStyle(X),je=Number.parseFloat(ue.paddingBottom),$e=Array.from(X.querySelectorAll(".mobile-nav-tab"),We=>We.getBoundingClientRect().height),Ce=t9({navOffsetHeight:X.offsetHeight,paddingBottom:je,tabHeights:$e});document.documentElement.style.setProperty("--mobile-nav-height",`${Ce}px`)};ye();let ot=null;return typeof ResizeObserver<"u"&&(ot=new ResizeObserver(()=>{ye()}),ot.observe(X)),()=>{ot?.disconnect(),document.documentElement.style.removeProperty("--mobile-nav-height")}},[]),J!=="mobile"||i)return null;const ce=E>0&&C?C:S,De=!!V,He=!!N?.todoView,qe=De,pe=De&&!qe,se=R.filter(X=>X.view.placement==="primary").sort((X,ye)=>(X.view.order??Number.MAX_SAFE_INTEGER)-(ye.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),z=new Set(se.map(X=>`${X.pluginId}:${X.view.viewId}`)),Y=R.filter(X=>!z.has(`${X.pluginId}:${X.view.viewId}`)).sort((X,ye)=>(X.view.order??Number.MAX_SAFE_INTEGER)-(ye.view.order??Number.MAX_SAFE_INTEGER)),he=e==="documents"||e==="reliability"||!!N?.evalsView&&e==="evals"||!!N?.goalsView&&e==="goalsView"||e==="research"||e==="insights"||e==="memory"||e==="secrets"||e==="devserver"||e==="dev-server"||g&&He||e==="skills"&&!qe||e==="graph"||e==="stash-recovery"||Fo(e)&&!se.some(X=>Zl(X.pluginId,X.view.viewId)===e);return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{ref:be,className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}${r?" mobile-nav-bar--keyboard-open":""}`,role:"tablist","aria-label":O("nav.primaryNavAriaLabel","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(Wo,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.tasks","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(Is,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.agents","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(ri,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.missions","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(Ra,{}),h&&e!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":O("nav.chatUnreadAriaLabel","Unread chat response")})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.chat","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(qr,{}),p>0&&e!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":O("nav.mailboxPendingAriaLabel","Pending approvals")})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.mailbox","Mailbox")}),m>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Ol(m)})]}),qe&&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(Ws,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.skills","Skills")})]}),se.map(X=>{const ye=Zl(X.pluginId,X.view.viewId),ot=qd(X.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===ye||e==="graph"&&X.pluginId==="fusion-plugin-dependency-graph"&&X.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${X.pluginId}-${X.view.viewId}`,role:"tab","aria-selected":e===ye||e==="graph"&&X.pluginId==="fusion-plugin-dependency-graph"&&X.view.viewId==="graph",onClick:()=>n(X.pluginId==="fusion-plugin-dependency-graph"&&X.view.viewId==="graph"?"graph":ye),children:[t.jsx(ot,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:X.view.label})]},`${X.pluginId}:${X.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${he?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>de(X=>!X),children:[t.jsx(yh,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.more","More")})]})]}),A&&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:O("nav.moreSheetTitle","Navigate")}),L?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:L}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>q(c),children:[t.jsx(qr,{}),t.jsx("span",{children:O("nav.mailbox","Mailbox")}),m>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Ol(m)}),p>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Ol(p)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>q(l),children:[t.jsx(Ci,{}),t.jsx("span",{children:O("nav.activityLog","Activity Log")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>q(d),children:[t.jsx(Ko,{}),t.jsx("span",{children:O("nav.systemStats","System Stats")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>q(f),children:[t.jsx(ui,{}),t.jsx("span",{children:O("nav.gitManager","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:()=>q(x),children:[t.jsx(ua,{}),t.jsx("span",{children:O("nav.terminal","Terminal")})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>P(X=>!X),"aria-expanded":B,"aria-haspopup":"menu","aria-label":O("nav.showScriptsAriaLabel","Show scripts"),children:t.jsx(ls,{size:14,className:`mobile-more-chevron${B?" mobile-more-chevron--open":""}`})})]}),B&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":O("nav.scriptsSubmenuAriaLabel","Scripts submenu"),children:ie?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(Et,{className:"animate-spin"}),t.jsx("span",{children:O("nav.loadingScripts","Loading scripts…")})]}):Le.length>0?t.jsxs(t.Fragment,{children:[Le.map(([X,ye])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${X}`,onClick:()=>{M&&M(X,ye),xe(),P(!1)},children:[t.jsx(Ds,{}),t.jsx("span",{children:X})]},X)),v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{xe(),P(!1),v()},children:[t.jsx(da,{}),t.jsx("span",{children:O("nav.manageScripts","Manage Scripts…")})]})]}):v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{xe(),P(!1),v()},children:[t.jsx(da,{}),t.jsx("span",{children:O("nav.noScriptsAddOne","No scripts — add one…")})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>q(k),children:[t.jsx(Zs,{}),t.jsx("span",{children:O("nav.files","Files")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>q(ce),children:[t.jsx(Ia,{}),t.jsx("span",{children:O("nav.planning","Planning")}),E>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Ol(E)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>q(b),children:[t.jsx(lc,{}),t.jsx("span",{children:O("nav.workflows","Workflows")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>q(y),children:[t.jsx(ha,{}),t.jsx("span",{children:O("nav.automation","Automation")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>q(j),children:[t.jsx(n9,{}),t.jsx("span",{children:O("nav.importFromGitHub","Import from GitHub")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>q(F),children:[t.jsx(Ci,{}),t.jsx("span",{children:O("nav.usage","Usage")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>q(_),children:[t.jsx(qo,{}),t.jsx("span",{children:O("nav.projects","Projects")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>q(()=>n("documents")),children:[t.jsx(Hr,{}),t.jsx("span",{children:O("nav.documents","Documents")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-reliability",onClick:()=>q(()=>n("reliability")),children:[t.jsx(Ci,{}),t.jsx("span",{children:O("nav.reliability","Reliability")})]}),N?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>q(()=>n("evals")),children:[t.jsx(ri,{}),t.jsx("span",{children:O("nav.evals","Evals")})]}),N?.goalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-goals",onClick:()=>q(()=>n("goalsView")),children:[t.jsx(ri,{}),t.jsx("span",{children:O("nav.goals","Goals")})]}),pe&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>q(()=>n("skills")),children:[t.jsx(Ws,{}),t.jsx("span",{children:O("nav.skills","Skills")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>q(()=>n("stash-recovery")),children:[t.jsx(Ur,{}),t.jsx("span",{children:O("nav.stashRecovery","Stash Recovery")}),u>0?t.jsx("span",{className:"mobile-more-item-badge",children:Ol(u)}):null]}),N?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>q(()=>n("research")),children:[t.jsx(na,{}),t.jsx("span",{children:O("nav.research","Research")})]}),N?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>q(()=>n("insights")),children:[t.jsx($s,{}),t.jsx("span",{children:O("nav.insights","Insights")})]}),N?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>q(()=>n("memory")),children:[t.jsx(ac,{}),t.jsx("span",{children:O("nav.memory","Memory")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-secrets",onClick:()=>q(()=>n("secrets")),children:[t.jsx(ll,{}),t.jsx("span",{children:O("nav.secrets","Secrets")})]}),N?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{q(()=>n("dev-server"))},children:[t.jsx(Ko,{}),t.jsx("span",{children:O("nav.devServer","Dev Server")})]}),N?.nodesView&&$&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>q($),children:[t.jsx(N1,{}),t.jsx("span",{children:O("nav.nodes","Nodes")})]}),He&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>q(()=>w?.()),children:[t.jsx(Sp,{}),t.jsx("span",{children:O("nav.todos","Todos")})]}),Y.map(X=>{const ye=Zl(X.pluginId,X.view.viewId),ot=qd(X.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${X.pluginId}-${X.view.viewId}`,onClick:()=>q(()=>n(X.pluginId==="fusion-plugin-dependency-graph"&&X.view.viewId==="graph"?"graph":ye)),children:[t.jsx(ot,{}),t.jsx("span",{children:X.view.label})]},`${X.pluginId}:${X.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:()=>q(o),children:[t.jsx(Ql,{}),t.jsx("span",{children:O("nav.settings","Settings")})]})]})]})]})}function Oy(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function tS(e,n){const s=n.trim();if(!s)return!0;const i=Oy(s);return Oy(e).includes(i)||e.toLowerCase().includes(s.toLowerCase())}function i9({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below",roomMemberIds:l,roomName:d}){const{t:c}=st("app"),m=a.useMemo(()=>e.filter(y=>tS(y.name,n)),[e,n]),p=!!l,h=p&&n.trim().length>0,u=a.useMemo(()=>p?m.filter(y=>l?.has(y.id)):m,[m,l,p]),f=a.useMemo(()=>p?m.filter(y=>!l?.has(y.id)):[],[m,l,p]),b=h?[...u,...f]:u;return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":c("agentMention.suggestionsLabel","Agent mention suggestions"),children:b.length===0?t.jsx("div",{className:"agent-mention-empty",children:c("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[p&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:d?c("agentMention.membersOf","Members of #{{roomName}}",{roomName:d}):c("agentMention.roomMembers","Room members")}),u.map((y,v)=>t.jsxs("button",{type:"button",className:`agent-mention-item${v===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${y.id}`,onMouseDown:x=>x.preventDefault(),onClick:()=>r(y),role:"option","aria-selected":v===s,children:[t.jsx(ru,{agent:y,size:20}),p&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":c("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:y.name}),t.jsx("span",{className:"agent-mention-role",children:y.role})]},y.id)),p&&!h&&f.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:c("agentMention.typeToSearch","Type to search other agents")}),p&&h&&f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:c("agentMention.otherAgents","Other agents")}),f.map((y,v)=>{const x=u.length+v;return t.jsxs("button",{type:"button",className:`agent-mention-item${x===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${y.id}`,onMouseDown:k=>k.preventDefault(),onClick:()=>r(y),role:"option","aria-selected":x===s,children:[t.jsx(ru,{agent:y,size:20}),t.jsx("span",{className:"agent-mention-name",children:y.name}),t.jsx("span",{className:"agent-mention-role",children:y.role})]},y.id)})]})]})}):null}function $y(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:i,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:d,onDone:c,onError:m,onFallbackSession:p}=e;let h="",u="",f=[],b,y=null,v=null;const x=()=>{y=null,i(h)},k=()=>{v=null,r(u)},w=()=>{y!==null&&(cancelAnimationFrame(y),y=null),v!==null&&(cancelAnimationFrame(v),v=null)};return l.current=w,{handlers:{onThinking:j=>{u+=j,v===null&&(v=requestAnimationFrame(k))},onText:j=>{h+=j,y===null&&(y=requestAnimationFrame(x))},onToolStart:j=>{f=[...f,{toolName:j.toolName,args:j.args,isError:!1,status:"running"}],o(f)},onToolEnd:j=>{const S=[...f];for(let C=S.length-1;C>=0;C--){const E=S[C];if(E?.toolName===j.toolName&&E.status==="running"){S[C]={...E,status:"completed",isError:j.isError,result:j.result},f=S,o(S);return}}f=[...S,{toolName:j.toolName,isError:j.isError,result:j.result,status:"completed"}],o(f)},onFallback:j=>{b=j,p?.(j,n),d?.(`Primary model unavailable. Switched to fallback ${j.fallbackModel}.`,"warning")},onDone:j=>{w(),c({messageId:j.messageId,message:j.message,accumulated:{text:h,thinking:u,toolCalls:f,fallbackInfo:b}})},onError:j=>{w(),m(j,s)}},cancelFlushes:w}}const a9="fusion:chat-pending:";function Lf(e){return e?`${a9}${e}`:null}function r9(e){const n=Lf(e);if(!n||typeof window>"u")return"";try{return localStorage.getItem(n)??""}catch{return""}}function o9(e,n){const s=Lf(e);if(!(!s||typeof window>"u"))try{localStorage.setItem(s,n)}catch{}}function ch(e){const n=Lf(e);if(!(!n||typeof window>"u"))try{localStorage.removeItem(n)}catch{}}const l9="fusion:quick-chat-last-session:";function nS(e){return`${l9}${e||"default"}`}function c9(e){if(typeof window>"u")return null;try{return localStorage.getItem(nS(e))}catch{return null}}function d9(e,n){if(!(typeof window>"u"))try{localStorage.setItem(nS(e),n)}catch{}}const $r="__fn_agent__";function sS(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function kd(e,n,s){const i=typeof e=="string"?e.trim():"",r=sS(n,s),o=i||(r.modelProvider&&r.modelId?$r:"");return o?{agentId:o,...r}:null}function wd(e,n,s){const i=sS(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function zy(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 u9(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(i=>{if(!i||typeof i!="object")return null;const r=i,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(i=>i!==null);return s.length>0?s:void 0}function m9(e){const n=e?.fallback;if(!n||typeof n!="object")return;const s=n,i=typeof s.primaryModel=="string"?s.primaryModel:"",r=typeof s.fallbackModel=="string"?s.fallbackModel:"",o=s.triggerPoint;if(!(!i||!r||o!=="session-creation"&&o!=="prompt-time"))return{primaryModel:i,fallbackModel:r,triggerPoint:o}}function Co(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:u9(e.metadata),fallbackInfo:m9(e.metadata),createdAt:e.createdAt}}function h9(e,n){const{t:s}=st("app"),[i,r]=a.useState(null),[o,l]=a.useState([]),[d,c]=a.useState(!1),[m,p]=a.useState([]),[h,u]=a.useState(!1),[f,b]=a.useState(!1),[y,v]=a.useState(""),[x,k]=a.useState(""),[w,g]=a.useState([]),[j,S]=a.useState(""),C=a.useRef(null),E=a.useRef(null),F=a.useRef(!1),M=a.useRef(null),D=a.useRef(""),_=a.useRef(f);_.current=f;const V=a.useRef(null),N=a.useRef(null),$=a.useRef(""),R=a.useRef(null),L=a.useRef(i);L.current=i;const O=a.useRef(0),J=3,A=a.useRef(!1);a.useEffect(()=>{D.current=j},[j]),a.useEffect(()=>{E.current=null},[e]),a.useEffect(()=>{i?.id&&d9(e,i.id)},[i?.id,e]);const de=a.useCallback(async()=>{c(!0);try{const se=await Kg(e);l(se.sessions)}catch(se){console.error("[useQuickChat] Failed to refresh sessions:",se),n?.(s("quickChat.errorRefreshingSessions","Failed to refresh chat sessions"),"error")}finally{c(!1)}},[e,s,n]),B=a.useCallback(async se=>{const z={agentId:se.agentId};return se.modelProvider&&se.modelId&&(z.modelProvider=se.modelProvider,z.modelId=se.modelId),(await DR(z,e)).session},[e]),P=a.useCallback(()=>{ch(L.current?.id),D.current="",S("")},[]),Z=a.useCallback(()=>{const se=D.current.trim();if(!se)return;ch(L.current?.id),D.current="",S("");const z=N.current;N.current=null;const Y=qe.current(se);z&&Y.then(z.resolve).catch(z.reject)},[]),T=a.useCallback((se,z,Y)=>{if(C.current||!se)return!0;F.current=!1,z&&(v(z.streamingText),k(z.streamingThinking),g(z.toolCalls)),b(!0);const{handlers:he}=$y({sessionId:se,tempUserMessageId:"",setStreamingText:v,setStreamingThinking:k,setStreamingToolCalls:g,cancelStreamingFlushesRef:M,addToast:Y?.silent?void 0:n,onFallbackSession:(X,ye)=>{const ot=zy(X.fallbackModel);l(ue=>ue.map(je=>je.id===ye?{...je,...ot}:je)),r(ue=>ue&&ue.id===ye?{...ue,...ot}:ue)},onDone:()=>{v(""),k(""),g([]),b(!1),_.current=!1,C.current=null,E.current=null,wl(se,{limit:50,order:"desc"},e).then(X=>{L.current?.id===se&&p(X.messages.slice().reverse().map(Co))}).catch(()=>{}),Z()},onError:X=>{v(""),k(""),g([]),b(!1),_.current=!1,C.current=null,E.current=null;const ye=typeof X=="string"&&X.trim()?X:s("quickChat.errorGettingResponse","Failed to get response");Y?.silent||n?.(ye,"error"),wl(se,{limit:50,order:"desc"},e).then(ot=>{L.current?.id===se&&p(ot.messages.slice().reverse().map(Co))}).catch(()=>{}),Z()}});return C.current=GR(se,he,e,{...typeof z?.replayFromEventId=="number"?{lastEventId:z.replayFromEventId}:{}}),E.current={sessionId:se,replayFromEventId:typeof z?.replayFromEventId=="number"?z.replayFromEventId:null},!0},[n,e,Z]),ie=a.useCallback(async(se,z,Y)=>{const he=kd(se,z,Y);if(!he)return;const X=wd(he.agentId,he.modelProvider,he.modelId);c(!0);try{const{session:ye}=await IR({agentId:he.agentId,modelProvider:he.modelProvider,modelId:he.modelId},e);if(ye)r(ye),$.current=X,ye.isGenerating&&T(ye.id,ye.inFlightGeneration);else{const ot=await B(he);r(ot),$.current=X}O.current=0}catch(ye){console.error("[useQuickChat] Failed to initialize session:",ye),O.current+=1,O.current<=J&&n?.(s("quickChat.errorInitializingChat","Failed to initialize chat"),"error")}finally{c(!1)}},[T,e,n,B]),le=a.useCallback(async()=>{if(i){u(!0);try{const se=i.id,z=await wl(se,{limit:50,order:"desc"},e);L.current?.id===se&&p(z.messages.slice().reverse().map(Co))}catch(se){console.error("[useQuickChat] Failed to load messages:",se)}finally{u(!1)}}},[i,e]);a.useEffect(()=>{i?le():p([])},[i,le]),a.useEffect(()=>{if(!i?.isGenerating||(C.current||T(i.id,i.inFlightGeneration),!_.current||C.current||!i))return;const se=setInterval(async()=>{if(!_.current||C.current||!i){clearInterval(se);return}try{if(!(await kl(i.id,e)).session.isGenerating){clearInterval(se);const Y=i.id,he=await wl(Y,{limit:50,order:"desc"},e);L.current?.id===Y&&p(he.messages.slice().reverse().map(Co)),v(""),k(""),g([]),b(!1),_.current=!1,Z()}}catch{}},3e3);return()=>clearInterval(se)},[i,T,e,Z]);const be=a.useCallback(async()=>{if(i){u(!0);try{const se=i.id,z=await wl(se,{limit:50,order:"desc"},e);L.current?.id===se&&p(z.messages.slice().reverse().map(Co))}catch(se){console.error("[useQuickChat] Failed to reload messages:",se)}finally{u(!1)}}},[i,e]),Le=a.useCallback(()=>{M.current?.(),M.current=null,D.current="",S(""),N.current?.resolve(),N.current=null,v(""),k(""),g([]),b(!1)},[]);a.useEffect(()=>{C.current&&(C.current.close(),C.current=null),E.current=null,$.current="",R.current=null,L.current=null,r(null),p([]),l([]),Le()},[e,Le]);const xe=a.useCallback(async(se,z,Y)=>{const he=kd(se,z,Y);if(!he)return;const X=wd(he.agentId,he.modelProvider,he.modelId);R.current=he;const ye=X===$.current&&L.current;if(ye||(C.current&&(C.current.close(),C.current=null),E.current=null,Le()),ye){await be();return}r(null),p([]),$.current=X,await ie(he.agentId,he.modelProvider,he.modelId)},[ie,be,Le]),q=a.useCallback(async se=>{const z=kd(se.agentId,se.modelProvider??void 0,se.modelId??void 0);z&&(R.current=z,$.current=wd(z.agentId,z.modelProvider,z.modelId),C.current&&(C.current.close(),C.current=null),E.current=null,Le(),r(se),Promise.resolve(kl(se.id,e)).then(({session:Y})=>{!Y.isGenerating||!Y.inFlightGeneration||r(he=>!he||he.id!==se.id?he:{...he,...Y})}).catch(()=>{}),se.isGenerating&&T(se.id,se.inFlightGeneration))},[T,e,Le]);a.useEffect(()=>{const se=i?.id;if(!se)return;const z=r9(se);if(!z)return;D.current=z,S(z);let Y=!1;return kl(se,e).then(({session:he})=>{if(!(Y||L.current?.id!==se||D.current.trim().length===0)){if(he.isGenerating){C.current||T(se,he.inFlightGeneration);return}!_.current&&!C.current&&Z()}}).catch(()=>{}),()=>{Y=!0}},[i?.id,T,Z,e]);const ce=a.useCallback(async(se,z)=>{await xe($r,se,z)},[xe]),De=a.useCallback(async(se,z,Y)=>{const X=kd(se??"",z,Y)??R.current;if(!X)return;R.current=X;const ye=wd(X.agentId,X.modelProvider,X.modelId);A.current=!0,O.current=0,C.current&&(C.current.close(),C.current=null),E.current=null,ch(L.current?.id),Le(),p([]),r(null),c(!0);try{const ot=await B(X);r(ot),$.current=ye;const ue=await Kg(e);l(ue.sessions)}catch(ot){console.error("[useQuickChat] Failed to start a fresh session:",ot),n?.(s("quickChat.errorStartingNewChat","Failed to start a new chat"),"error")}finally{A.current=!1,c(!1)}},[n,B,e,Le]),He=a.useCallback(()=>{i&&(F.current=!0,M.current?.(),M.current=null,C.current?.close(),C.current=null,E.current=null,VR(i.id,e).catch(()=>{}),b(!1),_.current=!1,v(""),k(""),g([]),Z())},[i,e,Z]),qe=a.useRef(()=>Promise.resolve()),pe=ul(),te=a.useCallback(async se=>{try{await de();const Y=(await kl(se,e)).session;L.current?.id===se&&r(he=>!he||he.id!==se?he:{...he,...Y}),Y.isGenerating?(v(""),k(""),g([]),b(!0),_.current=!0,T(se,Y.inFlightGeneration,{silent:!0})):(v(""),k(""),g([]),b(!1),_.current=!1,await be())}catch{}},[T,e,de,be]),me=a.useCallback((se,z)=>{if(!se.trim()&&(!z||z.length===0))return Promise.resolve();if(!i)return z&&z.length>0?Promise.reject(new Error(s("quickChat.errorAttachmentsBeforeSession","Cannot send attachments before chat session is ready"))):new Promise((he,X)=>{N.current?.resolve(),N.current={resolve:he,reject:X},D.current=se,S(se),L.current&&!_.current&&!C.current&&queueMicrotask(()=>{!_.current&&!C.current&&Z()})});if(_.current)return z&&z.length>0?Promise.reject(new Error(s("quickChat.errorAttachmentsWhileStreaming","Cannot send attachments while a response is streaming"))):(D.current=se,S(se),o9(i.id,se),Promise.resolve());const Y=new Promise((he,X)=>{V.current={resolve:he,reject:X},F.current=!1,C.current&&(C.current.close(),C.current=null),E.current=null;const ye=`temp-${Date.now()}`,ot={id:ye,sessionId:i.id,role:"user",content:se,createdAt:new Date().toISOString()};p(je=>[...je,ot]),v(""),k(""),g([]),b(!0);const{handlers:ue}=$y({sessionId:i.id,tempUserMessageId:ye,setStreamingText:v,setStreamingThinking:k,setStreamingToolCalls:g,cancelStreamingFlushesRef:M,addToast:n,onFallbackSession:(je,$e)=>{const Ce=zy(je.fallbackModel);l(We=>We.map(ke=>ke.id===$e?{...ke,...Ce}:ke)),r(We=>We&&We.id===$e?{...We,...Ce}:We)},onDone:({messageId:je,message:$e,accumulated:Ce})=>{const We=$e?{...Co($e),...Ce.text.length>0?{content:Ce.text}:{}}:{id:je||`msg-${Date.now()}`,sessionId:i.id,role:"assistant",content:Ce.text,thinkingOutput:Ce.thinking||void 0,toolCalls:Ce.toolCalls.length>0?Ce.toolCalls:void 0,fallbackInfo:Ce.fallbackInfo,createdAt:new Date().toISOString()};p(ke=>[...ke,We]),v(""),k(""),g([]),b(!1),_.current=!1,C.current=null,E.current=null,V.current?.resolve(),V.current=null,Z()},onError:je=>{v(""),k(""),g([]),b(!1),_.current=!1,C.current=null,E.current=null,console.error("[useQuickChat] Stream error:",je);const $e=typeof je=="string"&&je.trim()?je:s("quickChat.errorGettingResponse","Failed to get response"),Ce=ju($e);if(Ce)console.info("[useQuickChat] Suppressed tab-suspension stream error:",je),i?.id&&(v(""),k(""),g([]),b(!0),_.current=!0,te(i.id)),V.current?.resolve();else{const We=$e||s("quickChat.errorGettingResponse","Failed to get response");n?.(We,"error"),V.current?.reject(new Error(We))}V.current=null,F.current||Z(),Ce||be()}});C.current=WR(i.id,se,ue,z,e)});return Y.catch(()=>{}),Y},[i,e,n,be,te,Z]);return qe.current=me,a.useEffect(()=>{if(!i?.id||i.isGenerating!==!0||C.current)return;const se=typeof i.inFlightGeneration?.replayFromEventId=="number"?i.inFlightGeneration.replayFromEventId:null,z=E.current;z?.sessionId===i.id&&z.replayFromEventId===se||T(i.id,i.inFlightGeneration,{silent:!0})},[i?.id,i?.isGenerating,i?.inFlightGeneration,T]),a.useEffect(()=>pe.onBecameVisible(()=>{if(A.current)return;const z=L.current;!z||C.current||Promise.resolve(kl(z.id,e)).then(Y=>{if(!(C.current||L.current?.id!==z.id)){if(Y.session.isGenerating){v(""),k(""),g([]),b(!0),_.current=!0,T(z.id,Y.session.inFlightGeneration,{silent:!0});return}_.current&&(v(""),k(""),g([]),b(!1),_.current=!1,Z(),be())}}).catch(()=>{})}),[T,e,be,pe,Z]),a.useEffect(()=>{!i||_.current||C.current||N.current&&D.current.trim().length!==0&&Z()},[i,Z]),a.useEffect(()=>()=>{C.current&&(C.current.close(),C.current=null),E.current=null},[]),a.useMemo(()=>({activeSession:i,sessions:o,sessionsLoading:d,messages:m,messagesLoading:h,isStreaming:f,streamingText:y,streamingThinking:x,streamingToolCalls:w,pendingMessage:j,sendMessage:me,stopStreaming:He,clearPendingMessage:P,switchSession:xe,selectSession:q,startModelChat:ce,startFreshSession:De,refreshSessions:de,loadMessages:le,reloadMessages:be,skipNextSessionInitRef:A}),[i,o,d,m,h,f,y,x,w,j,me,He,P,xe,q,ce,De,de,le,be])}const p9=250;function iS(e,n){const[s,i]=a.useState(()=>{const v=ki(Tn.AGENTS,{maxAgeMs:Gr});return Array.isArray(v)?v:[]}),[r,o]=a.useState(()=>ki(Tn.AGENT_STATS,{maxAgeMs:Gr})??null),[l,d]=a.useState(!1),c=a.useRef(s.length>0||r!==null),m=a.useRef(0),p=a.useRef(0),h=a.useCallback(async(v,x)=>{const k=++m.current;c.current||d(!0);try{const w=n?.filterState,g=w&&w!=="all"?{state:w}:void 0,j=n?.showSystemAgents??!1,S={...g,...v,includeEphemeral:v?.includeEphemeral??j},C=x?.forceFresh?await br(S,e,{forceFresh:!0}):await br(S,e);if(k!==m.current)return;const E=Array.from(new Map(C.map(F=>[F.id,F])).values());i(E),es(Tn.AGENTS,E,{maxBytes:5e5}),c.current=c.current||E.length>0}catch(w){console.error("Failed to load agents:",w)}finally{k===m.current&&d(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=a.useCallback(async v=>{const x=++p.current;try{const k=v?.forceFresh?await Og(e,{forceFresh:!0}):await Og(e);if(x!==p.current)return;o(k),es(Tn.AGENT_STATS,k,{maxBytes:5e5}),c.current=!0}catch(k){console.error("Failed to load agent stats:",k)}},[e]);a.useEffect(()=>{h(),u()},[h,u]),a.useEffect(()=>{const v=e?`?projectId=${encodeURIComponent(e)}`:"";let x=null,k=!1,w=!1,g=!1;const j=async()=>{k=!0,w=!1;try{await Promise.all([h(void 0,{forceFresh:!0}),u({forceFresh:!0})])}finally{k=!1,!g&&w&&S()}},S=()=>{if(x||k){k&&(w=!0);return}x=setTimeout(()=>{x=null,j()},p9)},C=()=>{if(k){w=!0;return}S()},E=li(`/api/events${v}`,{events:{"agent:created":C,"agent:updated":C,"agent:deleted":C,"agent:stateChanged":C,"approval:requested":C,"approval:updated":C,"approval:decided":C}});return()=>{g=!0,x&&clearTimeout(x),E()}},[e,h,u]);const f=a.useCallback(async()=>{await Promise.all([h(void 0,{forceFresh:!0}),u({forceFresh:!0})])},[h,u]),b=n?.showSystemAgents??!1,y=s.filter(v=>v.state!=="active"&&v.state!=="running"?!1:b||!Y_(v));return{agents:s,activeAgents:y,stats:r,isLoading:l,loadAgents:h,loadStats:u,refreshAgents:f}}const dh=new Map,Id=new Map;function Ff(e){return e??"global"}function bp(e){return`${Tn.DISCOVERED_SKILLS_PREFIX}${Ff(e)}`}function _o(e){return ki(bp(e),{maxAgeMs:Gr})}function f9(e,n){for(const s of Id.get(e)??[])s(n)}async function g9(e){const n=Ff(e),s=dh.get(n);if(s)return s;const i=PR(e).finally(()=>{dh.delete(n)});return dh.set(n,i),i}function b9(e){const[n,s]=a.useState(()=>_o(e)??[]),[i,r]=a.useState(()=>_o(e)===null),o=a.useRef(_o(e)!==null),l=Ff(e);a.useEffect(()=>{const m=_o(e)??[];s(m),r(_o(e)===null),o.current=_o(e)!==null},[e]),a.useEffect(()=>{const m=Id.get(l)??new Set;return m.add(s),Id.set(l,m),()=>{m.delete(s),m.size===0&&Id.delete(l)}},[l]);const d=a.useCallback(async()=>{try{const m=await g9(e);o.current=!0,es(bp(e),m,{maxBytes:5e5}),f9(l,m)}catch{o.current||vs(bp(e))}finally{r(!1)}},[e,l]);a.useEffect(()=>{d()},[d]);const c=a.useCallback(async()=>{r(!0),await d()},[d]);return{skills:n,loading:i,refresh:c}}function v9(e,n){return e+n}function x9({visible:e,position:n,tasks:s,files:i,selectedIndex:r,onSelectTask:o,onSelectFile:l,loading:d}){const{t:c}=st("app");if(!e)return null;const m=s.length>0,p=i.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:h=>{h.preventDefault()},children:[d&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!d&&!m&&!p&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:c("fileMention.empty","No tasks or files found")}),!d&&(m||p)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[m&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:c("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":c("fileMention.taskMatches","Task matches"),children:s.map((h,u)=>{const f=u;return t.jsxs("li",{className:`file-mention-popup-item${f===r?" file-mention-popup-item--selected":""}`,onClick:()=>o(h),role:"option","aria-selected":f===r,"data-testid":`task-mention-item-${f}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Ck,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsxs("div",{className:"file-mention-popup-task-row",children:[t.jsx("span",{className:"file-mention-popup-task-id",children:h.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${h.column}`,children:h.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:h.title})]})]},h.id)})})]}),p&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:c("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":c("fileMention.fileMatches","File matches"),children:i.map((h,u)=>{const f=v9(s.length,u),b=X_(h.path);return t.jsxs("li",{className:`file-mention-popup-item${f===r?" file-mention-popup-item--selected":""}`,onClick:()=>l(h),role:"option","aria-selected":f===r,"data-testid":`file-mention-item-${f}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Nk,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:h.name}),b&&t.jsx("span",{className:"file-mention-popup-item-path",children:b})]})]},h.path)})})]})]})]})}const y9=200,k9=8,w9=8;function By(){return new DOMException("The operation was aborted.","AbortError")}function Uy(e,n){return n.aborted?Promise.reject(By()):new Promise((s,i)=>{const r=()=>i(By());n.addEventListener("abort",r,{once:!0}),e.then(o=>{n.removeEventListener("abort",r),s(o)},o=>{n.removeEventListener("abort",r),i(o)})})}function Hy(e,n,s){const i=e.slice(0,n),r=e.slice(n+1),o=r.match(/[\s]|$/),l=o?o.index??r.length:r.length,d=r.slice(l);return`${i}${s}${d}`}function j9(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[d,c]=a.useState(-1),[m,p]=a.useState([]),[h,u]=a.useState([]),[f,b]=a.useState(!1),[y,v]=a.useState(0),x=a.useRef(null),k=a.useRef(null),w=[...m.map(M=>({kind:"task",task:M})),...h.map(M=>({kind:"file",file:M}))];a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),k.current?.abort()},[]);const g=a.useCallback((M,D)=>{if(D<0||D>M.length){r(!1);return}const _=V=>/[a-zA-Z0-9/_.-]/.test(V);for(let V=D-1;V>=0;V--){if(M[V]==="#"){if(V===0){const $=M.slice(V+1,D);c(V),l($),v(0),r(!0);return}const N=M[V-1];if(/[\s,.;:!?'"()[\]{}]/.test(N)){const $=M.slice(V+1,D);c(V),l($),v(0),r(!0);return}r(!1);return}if(!_(M[V])){r(!1);return}}r(!1)},[]),j=a.useCallback(()=>{k.current?.abort(),r(!1),l(""),c(-1),p([]),u([]),v(0),b(!1)},[]),S=a.useCallback(async M=>{if(!M.trim()){p([]),u([]),b(!1);return}k.current?.abort();const D=new AbortController;k.current=D;try{b(!0);const[_,V]=await Promise.allSettled([Uy(Uk(20,0,n,M),D.signal),Uy(QM(M,s,n),D.signal)]);if(D.signal.aborted)return;const N=_.status==="fulfilled"?_.value.slice(0,k9).map(R=>({id:R.id,title:R.title??"",column:R.column})):[],$=V.status==="fulfilled"?V.value.files.slice(0,w9):[];p(N),u($),v(0)}catch(_){_.name!=="AbortError"&&(p([]),u([]))}finally{D.signal.aborted||b(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},y9),()=>{x.current&&clearTimeout(x.current)}},[o,i,S]);const C=a.useCallback((M,D)=>!i||d<0?D:Hy(D,d,`#${M.id}`),[i,d]),E=a.useCallback((M,D)=>!i||d<0?D:Hy(D,d,`#${M.path}`),[i,d]),F=a.useCallback((M,D)=>{if(!i||w.length===0)return!1;switch(M.key){case"ArrowDown":return M.preventDefault(),v(_=>Math.min(_+1,w.length-1)),!0;case"ArrowUp":return M.preventDefault(),v(_=>Math.max(_-1,0)),!0;case"Enter":case"Tab":return w[y]?(M.preventDefault(),!0):!1;case"Escape":return M.preventDefault(),j(),!0;default:return!1}},[i,w,y,j]);return{mentionActive:i,tasks:m,files:h,combinedItems:w,loading:f,mentionQuery:o,selectedIndex:y,setSelectedIndex:v,detectMention:g,selectTask:C,selectFile:E,dismissMention:j,handleKeyDown:F}}function aS(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[d,c]=a.useState(!1),[m,p]=a.useState(!1),[h,u]=a.useState(!1),[f,b]=a.useState(!1),[y,v]=a.useState(void 0),[x,k]=a.useState(7200*1e3),[w,g]=a.useState(!1),[j,S]=a.useState(20),[C,E]=a.useState(!1),[F,M]=a.useState(25),[D,_]=a.useState(!1),[V,N]=a.useState(!1),[$,R]=a.useState({}),[L,O]=a.useState(!1),[J,A]=a.useState(!1),[de,B]=a.useState(!1),[P,Z]=a.useState(!1),[T,ie]=a.useState(!1),[le,be]=a.useState(!0),Le=a.useRef(o),xe=a.useCallback(async()=>{const[pe,te]=await Promise.allSettled([Jk(e),yu(e)]);if(pe.status==="fulfilled"&&(s(pe.value.maxConcurrent),r(pe.value.rootDir)),te.status==="fulfilled"){const me=te.value;l(!!me.autoMerge);const se=me.testMode===!0,z=se||me.defaultProvider?.trim().toLowerCase()==="mock";c(se),p(z),u(!!me.globalPause),b(!!me.enginePaused),_(!!me.prAuthAvailable),v(me.taskStuckTimeoutMs),k(me.staleHighFanoutBlockerAgeThresholdMs??7200*1e3),E(me.showQuickChatFAB===!0),M(me.maxTotalRetriesBeforeFail??25),g(me.capacityRiskBannerEnabled===!0),S(me.capacityRiskTodoThreshold??20),R(me.experimentalFeatures??{});const Y=me.experimentalFeatures??{};O(Y.insights===!0),A(Y.memoryView===!0),B(Y.devServerView===!0||Y.devServer===!0),Z(Y.todoView===!0),ie(Y.goalsView===!0);const he=me.autoReloadOnVersionChange!==!1;be(he),qu(he)}N(!0)},[e]);a.useEffect(()=>{N(!1),R({}),O(!1),A(!1),B(!1),Z(!1),ie(!1),xe()},[xe]),a.useEffect(()=>{Le.current=o},[o]);const q=a.useCallback(async()=>{const pe=Le.current,te=!pe;Le.current=te,l(te);try{await Bc({autoMerge:te},e)}catch{Le.current=pe,l(pe)}},[e]),ce=a.useCallback(async()=>{const pe=!h;u(pe);try{await Bc({globalPause:pe,globalPauseReason:pe?"manual":void 0},e)}catch{u(!pe)}},[h,e]),De=a.useCallback(async()=>{const pe=!f;b(pe);try{await Bc({enginePaused:pe},e)}catch{b(!pe)}},[f,e]),He=a.useCallback(async()=>{const pe=!C;E(pe);try{await Bc({showQuickChatFAB:pe},e)}catch{E(!pe)}},[C,e]),qe=a.useCallback(async()=>{const pe=!le;be(pe),qu(pe);try{await Ms({autoReloadOnVersionChange:pe})}catch{be(!pe),qu(!pe)}},[le]);return{maxConcurrent:n,rootDir:i,autoMerge:o,testMode:d,isTestMode:m,globalPaused:h,enginePaused:f,taskStuckTimeoutMs:y,staleHighFanoutBlockerAgeThresholdMs:x,capacityRiskBannerEnabled:w,capacityRiskTodoThreshold:j,showQuickChatFAB:C,maxTotalRetriesBeforeFail:F,prAuthAvailable:D,settingsLoaded:V,experimentalFeatures:$,insightsEnabled:L,memoryEnabled:J,devServerEnabled:de,todosEnabled:P,goalsEnabled:T,autoReloadOnVersionChange:le,toggleAutoMerge:q,toggleGlobalPause:ce,toggleEnginePause:De,toggleShowQuickChatFAB:He,toggleAutoReloadOnVersionChange:qe,refresh:xe}}function jd(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function N9(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function uh(e,n){const s=N9(),i=n?.warm===!0,r=jd(),o=new Map;let l=!1,d=!1;return{mark(m){l||d||!s||o.has(m)||o.set(m,jd())},complete:m=>{if(!s||l||d){l=!0;return}l=!0,o.set("complete",jd());const p=Array.from(o.entries()).sort((b,y)=>b[1]-y[1]);let h=r;const u={};for(const[b,y]of p)u[b]=Math.max(0,y-h),h=y;const f=Math.max(0,jd()-r);try{console.debug("[room-open]",{roomId:e,warm:i,totalMs:f,phases:u,...m??{}})}catch{}},cancel(){d=!0,l=!0}}}const cr="fusion:chat-active-room";class S9 extends Error{roomId;constructor(n,s){super(n),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=s}}function vp(e){return[...e].sort((n,s)=>new Date(s.updatedAt).getTime()-new Date(n.updatedAt).getTime())}function Eo(e,n){const s=e.findIndex(r=>r.id===n.id);if(s===-1)return vp([n,...e]);const i=[...e];return i[s]=n,vp(i)}function Wa(e){try{return JSON.parse(e.data)}catch{return null}}function C9(e,n,s){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:e,role:"user",content:n,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...s?.length?{attachments:s}:{},createdAt:new Date().toISOString()}}function Vy(e,n,s){if(e.some(r=>r.id===n.id))return e;const i=s?e.findIndex(r=>r.id===s):-1;if(i>=0){const r=[...e];return r[i]=n,r}if(n.role==="user"){const r=e.findIndex(o=>o.role==="user"&&o.id.startsWith("temp-")&&o.content.trim()===n.content.trim());if(r>=0){const o=[...e];return o[r]=n,o}}return[...e,n]}function _9(e,n){const{t:s}=st("app"),i=`${Tn.CHAT_ROOMS}:${e??"global"}`,r=`${Tn.ACTIVE_CHAT_ROOM_ID}:${e??"global"}`,o=a.useCallback(R=>`${Tn.CHAT_ROOM_MESSAGES_PREFIX}${e??"global"}:${R}`,[e]),l=a.useCallback(R=>`${Tn.CHAT_ROOM_MEMBERS_PREFIX}${e??"global"}:${R}`,[e]),[d,c]=a.useState(()=>{const R=ki(i,{maxAgeMs:Gr});return Array.isArray(R)?R:[]}),[m,p]=a.useState(()=>d.length===0),[h,u]=a.useState(null),[f,b]=a.useState(()=>{const R=ki(r,{maxAgeMs:Fh});return R?d.find(L=>L.id===R)??null:null}),[y,v]=a.useState([]),[x,k]=a.useState([]),[w,g]=a.useState(!1),j=a.useRef(d),S=a.useRef(f),C=a.useRef(0),E=a.useRef(e);j.current=d,S.current=f,E.current!==e&&(E.current=e,C.current+=1);const F=a.useCallback(async R=>{if(!R){v([]),k([]),g(!1);return}const L=uh(R.id,{warm:!1});L.mark("select");const O=ki(o(R.id),{maxAgeMs:VP}),J=ki(l(R.id),{maxAgeMs:Gr}),A=Array.isArray(O)&&O.length>0,de=Array.isArray(J)&&J.length>0;A||de?(L.mark("cache-hit"),A&&(k(O),L.mark("hydrate")),de&&v(J),g(!1)):(k([]),g(!0));try{const[B,P]=await Promise.all([$R(R.id,e),Ju(R.id,{limit:100,order:"desc"},e)]);L.mark("members-fetch"),L.mark("messages-fetch"),es(l(R.id),B.members,{maxBytes:5e5}),es(o(R.id),P.messages,{maxBytes:5e5}),S.current?.id===R.id&&(v(B.members),k(P.messages),L.mark("hydrate"))}catch{!A&&!de&&(v([]),k([]))}finally{g(!1),L.complete({warm:A,membersCached:de})}},[l,o,e]),M=a.useCallback(async()=>{j.current.length===0&&p(!0);try{const R=await LR({},e),L=vp(R.rooms);c(L),es(i,L,{maxBytes:5e5}),u(null);const O=ki(r,{maxAgeMs:Fh})??cs(cr,e);if(O){const J=L.find(A=>A.id===O)??null;J?(b(J),F(J)):(sa(cr,e),es(r,"",{maxBytes:5e5}))}}catch(R){const L=R instanceof Error?R.message:s("chatRooms.error.failedToLoad","Failed to load chat rooms");u(L),n?.(L,"error")}finally{p(!1)}},[r,n,F,e,i]),D=a.useCallback(R=>{if(!R){S.current=null,b(null),sa(cr,e),es(r,"",{maxBytes:5e5}),F(null);return}const L=j.current.find(O=>O.id===R)??null;S.current=L,b(L),L&&(_s(cr,L.id,e),es(r,L.id,{maxBytes:5e5}),F(L))},[r,F,e]),_=a.useCallback(async R=>{const O=(await FR({name:R.name,memberAgentIds:R.memberAgentIds},e)).room;return c(J=>Eo(J,O)),S.current=O,b(O),_s(cr,O.id,e),es(r,O.id,{maxBytes:5e5}),await F(O),O},[r,F,e]),V=a.useCallback(async R=>{await OR(R,e),c(L=>L.filter(O=>O.id!==R)),es(o(R),[],{maxBytes:5e5}),es(l(R),[],{maxBytes:5e5}),S.current?.id===R&&(S.current=null,b(null),v([]),k([]),sa(cr,e),es(r,"",{maxBytes:5e5}))},[r,l,o,e]),N=a.useCallback(async(R,L)=>{const O=S.current,J=O?.id;if(!J)throw new Error(s("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const A=uh(J,{warm:!1}),de=L?.files?.map(Z=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,filename:Z.name,originalName:Z.name,mimeType:Z.type||"application/octet-stream",size:Z.size,createdAt:new Date().toISOString()})),B=C9(J,R,de?.length?de:L?.attachments);S.current?.id===J&&k(Z=>{const T=[...Z,B];return es(o(J),T,{maxBytes:5e5}),T});let P=!1;try{const Z=[];if(L?.files?.length)for(const be of L.files)try{const Le=await zR(J,be,e);Z.push(Le.attachment)}catch{throw new Error(s("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:be.name}))}const T=[...L?.attachments??[],...Z],ie=await UR(J,{content:R,...T.length?{attachments:T}:{}},e);P=!0,ie.message?.createdAt&&O&&c(be=>Eo(be,{...O,updatedAt:ie.message.createdAt})),S.current?.id===J&&k(be=>{const Le=Vy(be,ie.message,B.id);return es(o(J),Le,{maxBytes:5e5}),Le});const le=await Ju(J,{limit:100,order:"desc"},e);if(es(o(J),le.messages,{maxBytes:5e5}),S.current?.id!==J)return;k(le.messages),A.mark("hydrate")}catch(Z){let T=null;try{const le=await Ju(J,{limit:100,order:"desc"},e);T=le.messages,es(o(J),le.messages,{maxBytes:5e5}),S.current?.id===J&&(k(le.messages),A.mark("hydrate"))}catch{S.current?.id===J&&k(le=>{const be=le.filter(Le=>Le.id!==B.id);return es(o(J),be,{maxBytes:5e5}),be})}const ie=T?.some(le=>le.role==="user"&&le.content.trim()===B.content.trim());if(P||ie){const le=Z instanceof Error&&Z.message.trim()?Z.message:s("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new S9(le,J)}throw Z}finally{A.complete({source:"send-room-message"})}},[o,e]),$=a.useCallback(async R=>{!R||!j.current.some(L=>L.id===R)||(await HR(R,e),es(o(R),[],{maxBytes:5e5}),S.current?.id===R&&k([]))},[o,e]);return a.useEffect(()=>{M()},[M]),a.useEffect(()=>{const R=C.current,L=e?`/api/events?projectId=${encodeURIComponent(e)}`:"/api/events";return li(L,{onReconnect:()=>{Gs({view:"useChatRooms",trigger:"sse-reconnect",projectId:e,replayAttempted:!1});const O=S.current?.id;if(O){const J=uh(O,{warm:!0});J.mark("sse-reconnect-refresh"),M().finally(()=>J.complete({source:"sse-reconnect"}));return}M()},events:{"chat:room:created":O=>{if(C.current!==R)return;const J=Wa(O);J&&c(A=>Eo(A,J))},"chat:room:updated":O=>{if(C.current!==R)return;const J=Wa(O);J&&(c(A=>Eo(A,J)),S.current?.id===J.id&&b(J))},"chat:room:deleted":O=>{if(C.current!==R)return;const J=Wa(O);J?.id&&(c(A=>A.filter(de=>de.id!==J.id)),es(o(J.id),[],{maxBytes:5e5}),es(l(J.id),[],{maxBytes:5e5}),S.current?.id===J.id&&(S.current=null,b(null),v([]),k([]),sa(cr,e),es(r,"",{maxBytes:5e5})))},"chat:room:member:added":O=>{if(C.current!==R)return;const J=Wa(O);!J||S.current?.id!==J.roomId||v(A=>{if(A.some(B=>B.agentId===J.agentId))return A;const de=[...A,J];return es(l(J.roomId),de,{maxBytes:5e5}),de})},"chat:room:member:removed":O=>{if(C.current!==R)return;const J=Wa(O);!J||S.current?.id!==J.roomId||v(A=>{const de=A.filter(B=>B.agentId!==J.agentId);return es(l(J.roomId),de,{maxBytes:5e5}),de})},"chat:room:message:added":O=>{if(C.current!==R)return;const J=Wa(O);J&&(c(A=>{const de=A.find(B=>B.id===J.roomId);return de?Eo(A,{...de,updatedAt:J.createdAt}):A}),S.current?.id===J.roomId&&k(A=>{const de=Vy(A,J);return de===A?A:(es(o(J.roomId),de,{maxBytes:5e5}),de)}))},"chat:room:message:updated":O=>{if(C.current!==R)return;const J=Wa(O);!J||S.current?.id!==J.roomId||k(A=>{const de=A.map(B=>B.id===J.id?J:B);return es(o(J.roomId),de,{maxBytes:5e5}),de})},"chat:room:message:deleted":O=>{if(C.current!==R)return;const J=Wa(O);J?.id&&k(A=>{const de=A.filter(P=>P.id!==J.id),B=S.current?.id;return B&&es(o(B),de,{maxBytes:5e5}),de})},"chat:room:messages:cleared":O=>{if(C.current!==R)return;const J=Wa(O);J?.roomId&&(es(o(J.roomId),[],{maxBytes:5e5}),S.current?.id===J.roomId&&k([]),c(A=>{const de=A.find(B=>B.id===J.roomId);return de?Eo(A,{...de,updatedAt:new Date().toISOString()}):A}))}}})},[r,l,o,e,M]),a.useEffect(()=>{f&&(d.some(R=>R.id===f.id)||(S.current=null,b(null),v([]),k([]),sa(cr,e),es(r,"",{maxBytes:5e5})))},[f,r,e,d]),{rooms:d,roomsLoading:m,roomsError:h,activeRoom:f,activeRoomMembers:y,messages:x,messagesLoading:w,selectRoom:D,createRoom:_,deleteRoom:V,sendRoomMessage:N,clearRoom:$,refreshRooms:M}}const $l={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},qy=200;function xp(e){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?n:null}function rS(e){const n=Object.entries(e);if(n.length<=qy)return e;const s=n.map(([i,r])=>({id:i,timestamp:r,value:xp(r)??0})).sort((i,r)=>r.value-i.value).slice(0,qy);return Object.fromEntries(s.map(({id:i,timestamp:r})=>[i,r]))}function Nd(e){if(!e)return{};try{const n=JSON.parse(e);if(!n||typeof n!="object")return{};const s={};for(const[i,r]of Object.entries(n))typeof i=="string"&&typeof r=="string"&&(s[i]=r);return rS(s)}catch{return{}}}function E9(e){const[n,s]=a.useState(()=>{try{return Nd(cs($l.direct,e))}catch{return{}}}),[i,r]=a.useState(()=>{try{return Nd(cs($l.room,e))}catch{return{}}});a.useEffect(()=>{try{s(Nd(cs($l.direct,e)))}catch{s({})}try{r(Nd(cs($l.room,e)))}catch{r({})}},[e]);const o=a.useMemo(()=>({direct:n,room:i}),[n,i]),l=a.useCallback((h,u)=>{const f=rS(u);try{_s($l[h],JSON.stringify(f),e)}catch{}return f},[e]),d=a.useCallback((h,u)=>{if(h==="direct"){s(f=>l(h,u(f)));return}r(f=>l(h,u(f)))},[l]),c=a.useCallback((h,u,f)=>{const b=xp(f);if(b===null)return!1;const y=o[h][u],v=xp(y);return v===null?!0:b>v},[o]),m=a.useCallback((h,u,f)=>{if(!u)return;const b=f??new Date().toISOString();d(h,y=>({...y,[u]:b}))},[d]),p=a.useCallback((h,u)=>{u.length!==0&&d(h,f=>{const b={...f};for(const y of u)y.id&&(b[y.id]=y.lastActivityAt??new Date().toISOString());return b})},[d]);return{isUnread:c,markRead:m,markAllRead:p}}function M9(e){return`${e.name?.trim()||e.id} (${e.role})`}function zl(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 A9(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 T9(e){return Math.max(40,Math.min(e,640))}function Dd(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function R9(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{const r=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${s}=${Dd(r,50)}`}).join(", ")}function P9(e){if(e===void 0)return null;if(typeof e=="string")return Dd(e,200);try{return Dd(JSON.stringify(e),200)}catch{return Dd(String(e),200)}}function oS(e,n,s){if(!e||e.length===0)return null;const i=(f,b)=>{const y=f.status==="running",v=f.status==="completed"&&f.isError,x=R9(f.args),k=P9(f.result),w=null,g=y?"running":v?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${y?" chat-tool-call--running":""}${v?" chat-tool-call--error":""}`,open:y,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}),w,t.jsx("span",{className:"chat-tool-call-status-text",children:g})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[x&&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:x})]}),k&&t.jsxs("div",{className:`chat-tool-call-row${v?" 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:k})]})]})]},`${f.toolName}-${b}`)},r="chat-tool-calls chat-tool-calls--compact";if(e.length===1)return t.jsxs("div",{className:r,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(rg,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.toolCalls","Tool calls")})]}),i(e[0],0)]});const o=e.filter(f=>f.status==="running").length,l=e.filter(f=>f.status==="completed"&&f.isError).length,d=o>0,c=Array.from(new Set(e.map(f=>f.toolName))),m=c.slice(0,5),p=Math.max(0,c.length-m.length),h=p>0?`${m.join(", ")}, +${p} more`:m.join(", "),u=d?`(${o} running)`:l>0?`(${l} ${l===1?"error":"errors"})`:null;return t.jsx("div",{className:r,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group chat-tool-calls-group--compact","data-testid":"chat-tool-calls-group",open:d,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(rg,{size:12,"aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-calls-count",children:s("chat.toolCallsCount","{{count}} tool calls",{count:e.length})}),t.jsx("span",{className:"chat-tool-calls-names",title:h,children:h}),u&&t.jsx("span",{className:"chat-tool-calls-group-status",children:u})]}),e.map((f,b)=>i(f,b))]})})}const lS={p:({children:e,...n})=>t.jsx("p",{...n,children:hi(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:hi(e)}),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 Wy(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",i=n[2]??"",r=n.index+s.length;return{filter:i,start:r,end:e.length}}function I9(e,n){const s=e.slice(0,n),i=/(^|[\s])@([\w-]*)$/.exec(s);if(!i)return null;const r=i[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Sd={width:320,height:400},D9=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"]),L9=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function F9(e){return e.type.startsWith("image/")}function O9(e){if(D9.has(e.type))return!0;const n=e.name.toLowerCase();return L9.some(s=>n.endsWith(s))}const Mo={width:280,height:260},Ni=768,Ao=8;function $9(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const g=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return g&&parseFloat(g)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const g=`fusion-quick-chat-position-${e||"default"}`;try{const j=localStorage.getItem(g);if(j){const S=JSON.parse(j);if(typeof S.x=="number"&&typeof S.y=="number"&&!isNaN(S.x)&&!isNaN(S.y))return S}}catch{}return i()}),[l,d]=a.useState(!1),c=a.useRef(null),m=a.useRef(r),p=a.useRef(null),h=a.useRef(null),u=n??a.useRef(!1);a.useEffect(()=>{m.current=r},[r]);const f=a.useCallback(g=>{if(typeof window>"u")return g;const j=48,S=window.innerWidth<=768?4:8,C=window.innerWidth<=768?44:0,E=window.innerWidth>768?s():0,F=window.innerWidth-j-S,M=window.innerHeight-j-S-C-E;return{x:Math.max(S,Math.min(F,g.x)),y:Math.max(S,Math.min(M,g.y))}},[s]),b=a.useCallback(g=>{if(typeof window>"u")return;const j=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(j,JSON.stringify(g))}catch{}},[e]),y=a.useCallback(()=>{if(!c.current)return;const g=h.current,j=p.current;g&&j!==null&&typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(j),c.current=null,p.current=null,h.current=null,d(!1),document.body.style.userSelect="",u.current&&b(m.current),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x),document.removeEventListener("pointercancel",k)},[b]),v=a.useCallback(g=>{if(!c.current||p.current!==null&&g.pointerId!==p.current)return;const j=g.clientX-c.current.pointerX,S=g.clientY-c.current.pointerY;if((Math.abs(j)>=5||Math.abs(S)>=5)&&(u.current=!0),!u.current)return;const C=c.current.x-j,E=c.current.y-S,F=f({x:C,y:E});m.current=F,o(F)},[f]),x=a.useCallback(g=>{p.current!==null&&g.pointerId!==p.current||y()},[y]),k=a.useCallback(g=>{p.current!==null&&g.pointerId!==p.current||y()},[y]),w=a.useCallback(g=>{if(g.button!==0&&g.pointerType==="mouse")return;const j=g.currentTarget;g.preventDefault(),typeof j.setPointerCapture=="function"&&j.setPointerCapture(g.pointerId);const S=m.current;c.current={x:S.x,y:S.y,pointerX:g.clientX,pointerY:g.clientY},p.current=g.pointerId,h.current=j,u.current=!1,d(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",v,{passive:!0}),document.addEventListener("pointerup",x),document.addEventListener("pointercancel",k)},[k,v,x]);return a.useEffect(()=>()=>{document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x),document.removeEventListener("pointercancel",k),document.body.style.userSelect=""},[k,v,x]),{position:r,isDragging:l,handlePointerDown:w}}function z9(e,n,s,i){const r=`fusion:quick-chat-size-${e||"default"}`,o=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Ni,[]),l=a.useCallback((f,b,y)=>{if(typeof window>"u")return f;const v=Math.max(Mo.width,window.innerWidth-b-Ao),x=Math.max(Mo.height,window.innerHeight-y-Ao);return{width:Math.max(Mo.width,Math.min(v,f.width)),height:Math.max(Mo.height,Math.min(x,f.height))}},[]),d=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ni)return Sd;try{const f=localStorage.getItem(r);if(!f)return Sd;const b=JSON.parse(f);return typeof b.width!="number"||typeof b.height!="number"?Sd:{width:b.width,height:b.height}}catch{return Sd}},[r]),[c,m]=a.useState(d),[p,h]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!i||!o())return;const f={right:n+p.right,bottom:s+p.bottom};m(b=>l(b,f.right,f.bottom))},[p,l,s,n,o,i]),a.useEffect(()=>{if(!(!i||!o()))try{localStorage.setItem(r,JSON.stringify(c))}catch{}},[o,i,c,r]);const u=a.useCallback(f=>{if(!o())return;const b=f.currentTarget.dataset.resizeDirection;if(!b)return;f.preventDefault(),f.stopPropagation();const y=f.currentTarget;typeof y.setPointerCapture=="function"&&y.setPointerCapture(f.pointerId);const v={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:p.right,anchorBottom:p.bottom};document.body.style.userSelect="none";const x=w=>{const g=w.clientX-v.pointerX,j=w.clientY-v.pointerY;let S=v.width,C=v.height,E=v.anchorRight,F=v.anchorBottom;if(b.includes("w")&&(S=v.width-g),b.includes("e")){const $=g;S=v.width+$,E=v.anchorRight-$}if(b.includes("n")&&(C=v.height-j),b.includes("s")){const $=j;C=v.height+$,F=v.anchorBottom-$}const M=n+E,D=s+F,_=l({width:S,height:C},M,D),V=Math.max(Ao-n,Math.min(window.innerWidth-n-Mo.width-Ao,E)),N=Math.max(Ao-s,Math.min(window.innerHeight-s-Mo.height-Ao,F));m(_),h({right:V,bottom:N})},k=w=>{typeof y.releasePointerCapture=="function"&&y.releasePointerCapture(w.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",k);try{localStorage.setItem(r,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",x),document.addEventListener("pointerup",k)},[p.bottom,p.right,l,s,n,o,c.height,c.width,r]);return{panelSize:c,anchorOffset:p,handleResizeStart:u}}const mh=a.memo(function({message:n,forcePlain:s,mentionAgentsByName:i,roomContext:r,projectId:o,onToggleRender:l}){const{t:d}=st("app"),c=n.role==="user",m=a.useMemo(()=>{if(!c)return null;const u=n.content,f=/@([\w-]+)/g,b=[];let y=0,v=f.exec(u);for(;v;){const[x,k=""]=v,w=v.index;w>y&&b.push(u.slice(y,w));const g=k.replace(/_/g," ").toLowerCase(),j=i.get(g);if(j){const S=!!(r&&!r.memberIds.has(j.id)),C=S?`Not a member of ${r?.roomName}`:void 0;b.push(t.jsxs("span",{className:`chat-mention-chip${S?" chat-mention-chip--non-member":""}`,title:C,"aria-label":C,children:["@",j.name.replace(/\s+/g,"_")]},`${j.id}-${w}`))}else b.push(x);y=w+x.length,v=f.exec(u)}return y<u.length&&b.push(u.slice(y)),b.length===0?u:b},[c,n.content,i,r]),p=a.useMemo(()=>c?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Hs(n.content)}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Di,{remarkPlugins:[Li],components:lS,children:n.content})}),[c,s,n.content]),h=a.useMemo(()=>{if(!n.attachments?.length||!n.roomId)return null;const u=BR(n.roomId,o);return t.jsx("div",{className:"chat-message-attachments",children:n.attachments.map(f=>{const b=`${u}${encodeURIComponent(f.filename)}`,y=f.mimeType.startsWith("image/");return t.jsx("a",{className:"chat-message-attachment",href:b,target:"_blank",rel:"noreferrer","data-testid":"quick-chat-message-attachment",children:y?t.jsx("img",{src:b,alt:f.originalName,className:"chat-attachment-image",loading:"lazy"}):t.jsx("span",{children:f.originalName})},f.id)})})},[n.attachments,n.roomId,o]);return t.jsxs("div",{className:`quick-chat-panel-message ${c?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[c?t.jsx("p",{children:m}):t.jsxs(t.Fragment,{children:[p,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?d("chat.showRenderedMarkdown","Show rendered markdown"):d("chat.showPlainText","Show plain text"),onClick:()=>l(n.id),children:s?t.jsx(jp,{size:14}):t.jsx(bc,{size:14})})]}),h,oS(n.toolCalls,!0,d)]})});function B9({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:d,onToggleModelFavorite:c,roomContext:m=null}){const{t:p}=st("app"),{agents:h}=iS(e),{models:u,defaultProvider:f,defaultModelId:b,loading:y}=kf(),{skills:v,loading:x}=b9(e),[k,w]=a.useState(!1),g=i!==void 0,j=g?i:k,S=g?ne=>{r?.(typeof ne=="function"?ne(j):ne)}:w,{keyboardOpen:C}=Xa({enabled:j}),E=Ji(),F=E==="mobile",[M,D]=a.useState("agent"),[_,V]=a.useState(""),[N,$]=a.useState(!1),[R,L]=a.useState(!1),[O,J]=a.useState("model"),[A,de]=a.useState(""),[B,P]=a.useState(""),[Z,T]=a.useState(""),[ie,le]=a.useState(""),[be,Le]=a.useState(""),[xe,q]=a.useState(!1),[ce,De]=a.useState(""),[He,qe]=a.useState(0),[pe,te]=a.useState(""),[me,se]=a.useState(!1),[z,Y]=a.useState(0),[he,X]=a.useState(-1),[ye,ot]=a.useState(()=>new Set),[ue,je]=a.useState(!1),[$e,Ce]=a.useState([]),[We,ke]=a.useState(!1),[Ee,Ze]=a.useState(!1),[,Ke]=a.useState(!1),[dt,Fe]=a.useState({top:0,left:0}),nt=j9({projectId:e}),Nt=a.useCallback(ne=>{if(!ne||!nt.mentionActive)return;const Ue=ne.getBoundingClientRect();Fe({top:Ue.top-260,left:Ue.left+8})},[nt.mentionActive]),Ft=a.useRef(!1),ze=a.useRef(!1),it=a.useRef(!1),Mt=a.useRef(""),Ht=a.useRef(!1),Me=a.useRef(!1),Ae=a.useRef(_),ee=a.useRef(Z),Ie=a.useRef(0),Pe=a.useRef(null),oe=a.useRef(null),re=a.useRef(0),{position:_e,isDragging:fe,handlePointerDown:Xe}=$9(e,Ft),kt=_e.y+60,{panelSize:Rt,anchorOffset:Vt,handleResizeStart:Pt}=z9(e,_e.x,kt,j),bt=typeof window<"u"&&window.innerWidth>Ni,{activeSession:pt,messages:ft,isStreaming:_t,streamingText:Yt,streamingThinking:on,streamingToolCalls:An,sessions:vn,sessionsLoading:Qt,messagesLoading:sn,sendMessage:mn,stopStreaming:Kt,pendingMessage:fn,clearPendingMessage:$n,switchSession:On,selectSession:xn,startModelChat:Vn,startFreshSession:Rn,refreshSessions:Pn,skipNextSessionInitRef:zn}=h9(e,n),{experimentalFeatures:Nn}=aS(),dn=Nn?.chatRooms===!0,Tt=_9(e,n),{isUnread:Yn,markRead:cn}=E9(e),Bn=a.useRef(null),kn=a.useRef(null),pn=a.useRef(null),un=a.useRef(null),At=a.useRef(null),an=a.useRef(null),Wn=a.useRef([]),Xn=a.useRef(!1),G=a.useRef(!1),Oe=a.useRef(!1),yt=a.useRef(null),Gt=a.useRef(!1),Sn=a.useRef(!1),Un=a.useRef({isOpen:!1,sessionId:null});a.useEffect(()=>{if(!j||typeof window>"u"||typeof document>"u"||window.innerWidth>Ni)return;const ne=window.scrollY,Ue=document.documentElement,Je=document.body,qt={htmlOverflow:Ue.style.overflow,bodyOverflow:Je.style.overflow};return window.scrollTo(0,0),Ue.style.overflow="hidden",Je.style.overflow="hidden",()=>{Ue.style.overflow=qt.htmlOverflow,Je.style.overflow=qt.bodyOverflow,window.scrollTo(0,ne)}},[j]),a.useLayoutEffect(()=>{if(!j||typeof window>"u"||!window.visualViewport)return;const ne=Bn.current;if(!ne)return;const Ue=window.visualViewport,Je=()=>{Gt.current||(ne.style.setProperty("--vv-height",`${Ue.height}px`),ne.style.setProperty("--vv-offset-top",`${Ue.offsetTop||0}px`))};return Je(),Ue.addEventListener("resize",Je),Ue.addEventListener("scroll",Je),()=>{Ue.removeEventListener("resize",Je),Ue.removeEventListener("scroll",Je)}},[j]);const bn=Z||ie,gn=a.useMemo(()=>zl(bn),[bn]),ps=a.useMemo(()=>M==="model"&&pt?.modelProvider&&pt?.modelId?`${pt.modelProvider}/${pt.modelId}`:bn,[pt?.modelId,pt?.modelProvider,M,bn]),Ne=a.useMemo(()=>zl(ps),[ps]),ae=a.useMemo(()=>u.find(ne=>`${ne.provider}/${ne.id}`===ps)??null,[ps,u]),Se=a.useMemo(()=>A9(ae,Ne),[ae,Ne]),ut=a.useMemo(()=>M==="model"?gn?`${$r}::${gn.modelProvider}/${gn.modelId}`:"":_?`${_}::`:"",[M,_,gn]),It=M==="agent"?!!_:!!gn,ht=dn&&!!Tt.activeRoom,et=a.useMemo(()=>ht?Tt.messages.map(ne=>({id:ne.id,sessionId:ne.roomId,roomId:ne.roomId,role:ne.role,content:ne.content,thinkingOutput:ne.thinkingOutput,toolCalls:void 0,attachments:ne.attachments,createdAt:ne.createdAt})):ft,[ft,ht,Tt.messages]),Ut=ht?!1:!It||!pt,$t=be.trim().length===0&&$e.length===0||!ht&&!It||!ht&&!pt,rn=a.useMemo(()=>!!_&&vn.some(ne=>!ne.modelProvider&&!ne.modelId&&ne.agentId===_),[_,vn]);a.useEffect(()=>{Ae.current=_},[_]),a.useEffect(()=>{ee.current=Z},[Z]),a.useEffect(()=>{if(h.length===0){V(""),D("model");return}if(Ht.current&&rn)return;h.some(Ue=>Ue.id===_)||V(h[0]?.id??"")},[h,rn,_]),a.useEffect(()=>{if(j&&(ze.current||(ze.current=!0,it.current=!1),!(y||!ze.current||it.current))){if(!ee.current&&u.length>0){if(f&&b){const Ue=`${f}/${b}`;if(u.some(qt=>`${qt.provider}/${qt.id}`===Ue)){le(Ue),ee.current||T(Ue),Ht.current||D("model"),it.current=!0;return}}le("");const ne=u[0];ne&&!ee.current&&T(`${ne.provider}/${ne.id}`)}it.current=!0}},[b,f,j,u,y]),a.useEffect(()=>{j&&Pn()},[j,Pn]),a.useEffect(()=>{if(!j||Qt||Ht.current||vn.length===0)return;const ne=vn.filter(os=>os.status!=="archived"),Ue=c9(e),Je=Ue?ne.find(os=>os.id===Ue)??null:null,qt=os=>{if(!os)return 0;const fs=Date.parse(os);return Number.isFinite(fs)?fs:0},En=[...ne].sort((os,fs)=>{const ws=Math.max(qt(os.lastMessageAt),qt(os.updatedAt));return Math.max(qt(fs.lastMessageAt),qt(fs.updatedAt))-ws})[0],yn=Je??En;yn?(yn.modelProvider&&yn.modelId?(D("model"),T(`${yn.modelProvider}/${yn.modelId}`)):(D("agent"),V(yn.agentId)),Me.current=!0,xn(yn)):Me.current=!1,Ht.current=!0},[j,e,xn,vn,Qt]),a.useEffect(()=>{if(!j||!Ht.current&&vn.length===0&&ze.current&&!it.current)return;if(!ut){Mt.current="";return}if(zn.current){Mt.current=ut;return}const Ue=ut===Mt.current&&!pt&&!Qt;if(Me.current){Me.current=!1,Mt.current=ut;return}if(!(ut===Mt.current&&!Ue)){if(Mt.current=ut,M==="model"&&gn){Vn(gn.modelProvider,gn.modelId);return}M==="agent"&&_&&On(_)}},[j,M,gn,_,ut,pt,Qt,Vn,On,zn]),a.useEffect(()=>{j||(se(!1),te(""),X(-1),q(!1),De(""),qe(0),Wn.current.forEach(ne=>{ne.previewUrl&&URL.revokeObjectURL(ne.previewUrl)}),Ce([]))},[j]),a.useEffect(()=>{Ht.current=!1,Me.current=!1,ze.current=!1,it.current=!1,Mt.current=""},[e]),a.useEffect(()=>{Wn.current=$e},[$e]),a.useEffect(()=>{if(!j){Xn.current=!1;return}typeof window>"u"||(Xn.current=window.innerWidth<=Ni)},[j]),a.useEffect(()=>{if(!j||Ut||!Xn.current)return;const ne=un.current;if(!ne)return;const Ue=document.activeElement,Je=Ue?Bn.current?.contains(Ue):!1,qt=Ue===document.body,En=Ue===yt.current;if(!Je&&!qt&&!En){Xn.current=!1;return}if(En){ne.focus({preventScroll:!0}),Xn.current=!1;return}const yn=requestAnimationFrame(()=>{ne.focus(),Xn.current=!1});return()=>cancelAnimationFrame(yn)},[j,Ut]),a.useEffect(()=>()=>{Wn.current.forEach(ne=>{ne.previewUrl&&URL.revokeObjectURL(ne.previewUrl)})},[]);const Cn=a.useCallback(()=>{$(!0),J("model"),de(h[0]?.id??""),P(Z||ie||"")},[h,ie,Z]),ve=a.useMemo(()=>h.find(ne=>ne.id===_)??null,[h,_]),at=a.useMemo(()=>{const ne=ce.trim().toLowerCase();return(ne?v.filter(Je=>Je.name.toLowerCase().includes(ne)):v).slice(0,10)},[v,ce]),Ge=a.useMemo(()=>{const ne=h.filter(qt=>tS(qt.name,pe));if(!m)return ne;const Ue=ne.filter(qt=>m.memberIds.has(qt.id));if(pe.trim().length===0)return Ue;const Je=ne.filter(qt=>!m.memberIds.has(qt.id));return[...Ue,...Je]},[h,pe,m]),tt=a.useMemo(()=>{const ne=new Map;for(const Ue of h)ne.set(Ue.name.toLowerCase(),Ue);return ne},[h]),gt=a.useMemo(()=>at.map(ne=>ne.id).join(" "),[at]);a.useEffect(()=>{qe(0)},[gt]),a.useEffect(()=>{Y(0)},[pe,me]),a.useEffect(()=>()=>{Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null),oe.current!==null&&(window.clearTimeout(oe.current),oe.current=null)},[]),a.useEffect(()=>{if(!j)return;const ne=Je=>{const qt=Je.target;Bn.current?.contains(qt)||kn.current?.contains(qt)||qt.closest(".model-combobox-dropdown--portal")||S(!1)},Ue=Je=>{Je.key==="Escape"&&S(!1)};return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Ue),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Ue)}},[j,S]);const St=a.useCallback(()=>{const ne=pn.current;if(!ne)return;const Je=ne.scrollTop+ne.clientHeight>=ne.scrollHeight-50;Ze(!Je),Sn.current=!Je},[]),Xt=a.useCallback(ne=>{if(!ne.isConnected)return;let Ue=0,Je=0,qt=-1;const En=6,yn=()=>{if(ne.isConnected){if(ne.scrollTop=ne.scrollHeight,ne.scrollHeight===qt?Je+=1:(Je=0,qt=ne.scrollHeight),Ue+=1,Ue>=En||Je>=2){Ze(!1),Sn.current=!1;return}window.requestAnimationFrame(yn)}};yn()},[]),ss=a.useCallback(()=>{const ne=pn.current;ne&&Xt(ne)},[Xt]);a.useLayoutEffect(()=>{const ne=ht?Tt.activeRoom?.id??null:pt?.id??null,Ue=Un.current;if(Un.current={isOpen:j,sessionId:ne},!j||!ne)return;const Je=!Ue.isOpen&&j,qt=Ue.isOpen&&Ue.sessionId!==ne;if(!Je&&!qt)return;const En=pn.current;En&&Xt(En)},[j,pt?.id,Xt,ht,Tt.activeRoom?.id]),a.useEffect(()=>{if(!F||!j||!pt)return;const ne=()=>{const Je=pn.current;Je&&Xt(Je)},Ue=()=>{document.visibilityState==="visible"&&ne()};return document.addEventListener("visibilitychange",Ue),window.addEventListener("pageshow",ne),()=>{document.removeEventListener("visibilitychange",Ue),window.removeEventListener("pageshow",ne)}},[F,j,pt,Xt]),a.useEffect(()=>{j&&(Sn.current||ss())},[et,Yt,on,_t,j,ht,ss]),a.useEffect(()=>{pt?.id&&cn("direct",pt.id,pt.lastMessageAt??pt.updatedAt)},[pt?.id,pt?.lastMessageAt,pt?.updatedAt,cn]),a.useEffect(()=>{Tt.activeRoom?.id&&cn("room",Tt.activeRoom.id,Tt.activeRoom.updatedAt)},[cn,Tt.activeRoom?.id,Tt.activeRoom?.updatedAt]),a.useEffect(()=>{if(j){if(Tt.activeRoom?.id){cn("room",Tt.activeRoom.id,Tt.activeRoom.updatedAt);return}pt?.id&&cn("direct",pt.id,pt.lastMessageAt??pt.updatedAt)}},[pt?.id,pt?.lastMessageAt,pt?.updatedAt,j,cn,Tt.activeRoom?.id,Tt.activeRoom?.updatedAt]),a.useEffect(()=>{if(!_t){if(Tt.activeRoom?.id&&Tt.messages.length>0){const ne=Tt.messages[Tt.messages.length-1];cn("room",Tt.activeRoom.id,ne?.createdAt??Tt.activeRoom.updatedAt);return}if(pt?.id&&ft.length>0){const ne=ft[ft.length-1];cn("direct",pt.id,ne?.createdAt??pt.lastMessageAt??pt.updatedAt)}}},[pt?.id,pt?.lastMessageAt,pt?.updatedAt,_t,cn,ft,Tt.activeRoom?.id,Tt.activeRoom?.updatedAt,Tt.messages]);const Ts=a.useMemo(()=>{const ne=new Map(h.map(Je=>[Je.id,Je.name?.trim()||Je.id])),Ue=new Map(u.map(Je=>[`${Je.provider}/${Je.id}`,Je.name?.trim()||""]));return vn.map((Je,qt)=>{const En=Je.title?.trim()||`Session ${qt+1}`;let yn=null;if(Je.agentId&&Je.agentId!==$r)yn=ne.get(Je.agentId)||Je.agentId;else if(Je.modelProvider&&Je.modelId){const os=`${Je.modelProvider}/${Je.modelId}`,fs=Ue.get(os);yn=fs?`${fs} [${os}]`:os}return{id:Je.id,label:yn?`${En} — ${yn}`:En}})},[h,u,vn]),Ls=a.useMemo(()=>dn?Tt.rooms:[],[dn,Tt.rooms]),rs=dn&&Ls.length>0,ei=a.useMemo(()=>{if(rs&&ht&&Tt.activeRoom)return`#${Tt.activeRoom.name}`;const ne=Ts.find(Ue=>Ue.id===pt?.id);return ne?ne.label:Qt?p("chat.loadingSessions","Loading sessions…"):p("chat.selectSession","Select a session")},[pt?.id,ht,Tt.activeRoom,Ts,Qt,rs]);a.useEffect(()=>{j||L(!1)},[j]),a.useEffect(()=>{if(!R)return;const ne=Je=>{const qt=Je.target;At.current?.contains(qt)||L(!1)},Ue=Je=>{Je.key==="Escape"&&L(!1)};return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Ue),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Ue)}},[R]);const Mi=a.useMemo(()=>ht&&Tt.activeRoom?p("chat.messageRoomPlaceholder","Message #{{name}}",{name:Tt.activeRoom.name}):M==="agent"?ve?p("chat.messageAgentPlaceholder","Message {{name}}",{name:ve.name||ve.id}):p("chat.selectAgentPlaceholder","Select an agent to start chatting"):Se?p("chat.messageModelPlaceholder","Message {{name}}",{name:Se}):p("chat.selectModelPlaceholder","Select a model to start chatting"),[M,ht,Tt.activeRoom,ve,Se,p]),ti=a.useCallback(ne=>{const Ue=vn.find(Je=>Je.id===ne);if(Ue){if(ht&&Tt.selectRoom(null),cn("direct",Ue.id,Ue.lastMessageAt??Ue.updatedAt),Ht.current=!0,Ue.modelProvider&&Ue.modelId){const Je=`${$r}::${Ue.modelProvider}/${Ue.modelId}`;Me.current=!0,Mt.current=Je,D("model"),T(`${Ue.modelProvider}/${Ue.modelId}`)}else{const Je=`${Ue.agentId}::`;Me.current=!0,Mt.current=Je,D("agent"),V(Ue.agentId)}xn(Ue),L(!1)}},[cn,ht,Tt,xn,vn]),mi=a.useCallback(ne=>{const Ue=Tt.rooms.find(Je=>Je.id===ne);cn("room",ne,Ue?.updatedAt),Tt.selectRoom(ne),Ht.current=!0,L(!1)},[cn,Tt]),zs=a.useCallback(async()=>{if(!Qt){if(Ht.current=!0,O==="agent"){if(!A)return;D("agent"),V(A),await Rn(A)}else{const ne=zl(B||Z||ie);if(!ne)return;D("model"),T(`${ne.modelProvider}/${ne.modelId}`),await Rn($r,ne.modelProvider,ne.modelId)}await Pn(),$(!1),J("model")}},[ie,A,O,B,Pn,Z,Qt,Rn]),Qn=fn.length>50?`${fn.slice(0,50)}…`:fn,Zt=a.useCallback(ne=>{if(!ne||ne.length===0)return;const Ue=[];for(let Je=0;Je<ne.length;Je+=1){const qt=ne[Je];O9(qt)&&Ue.push({file:qt,previewUrl:F9(qt)?URL.createObjectURL(qt):""})}Ue.length>0&&Ce(Je=>[...Je,...Ue])},[]),Q=a.useCallback(ne=>{Ce(Ue=>{const Je=Ue[ne];return Je?.previewUrl&&URL.revokeObjectURL(Je.previewUrl),Ue.filter((qt,En)=>En!==ne)})},[]),Qe=a.useCallback(ne=>{Zt(ne.clipboardData?.files)},[Zt]),vt=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ni)return;const ne=un.current;!ne||ne.disabled||ne.focus({preventScroll:!0})},[]),xt=a.useCallback(()=>{typeof window>"u"||window.innerWidth>Ni||(Oe.current=!0)},[]),zt=a.useCallback(async()=>{const ne=be.trim(),Ue=Wn.current;if(!(!ne&&Ue.length===0)&&!Ut){if(Le(""),se(!1),te(""),X(-1),ne==="/help"){je(!0),vt(),Oe.current=!1;return}if(ne==="/clear"||ne==="/new"){Ue.forEach(Je=>{Je.previewUrl&&URL.revokeObjectURL(Je.previewUrl)}),Ce(Je=>Je.filter(qt=>!Ue.includes(qt)));try{if(ht&&Tt.activeRoom?.id)await Tt.clearRoom(Tt.activeRoom.id),je(!1);else if(M==="model"){$n(),Kt();const Je=zl(bn);if(!Je)return;await Rn($r,Je.modelProvider,Je.modelId)}else _&&($n(),Kt(),await Rn(_))}catch{n(p("chat.clearConversationFailed","Failed to clear conversation"),"error")}finally{vt(),Oe.current=!1}return}try{je(!1),dn&&Tt.activeRoom?await Tt.sendRoomMessage(ne,{files:Ue.map(Je=>Je.file)}):await mn(ne,Ue.map(Je=>Je.file)),Ue.forEach(Je=>{Je.previewUrl&&URL.revokeObjectURL(Je.previewUrl)}),Ce(Je=>Je.filter(qt=>!Ue.includes(qt)))}catch(Je){const qt=Je instanceof Error&&Je.message.trim()?Je.message:dn&&Tt.activeRoom?p("chat.sendRoomMessageFailed","Failed to send room message"):p("chat.sendMessageFailed","Failed to send message");n(qt,"error")}finally{vt(),Oe.current=!1}}},[n,M,dn,$n,vt,Ut,be,bn,ht,Tt,_,mn,Rn,Kt]),Wt=a.useCallback(ne=>{ne.preventDefault(),re.current+=1,ke(!0)},[]),hn=a.useCallback(ne=>{ne.preventDefault(),ne.dataTransfer.dropEffect="copy",ke(!0)},[]),In=a.useCallback(ne=>{ne.preventDefault(),re.current=Math.max(0,re.current-1),re.current===0&&ke(!1)},[]),gs=a.useCallback(ne=>{ne.preventDefault(),re.current=0,ke(!1),Zt(ne.dataTransfer?.files)},[Zt]),ks=a.useCallback((ne,Ue)=>{const Je=I9(ne,Ue);if(Je){se(!0),te(Je.filter),X(Je.start);return}se(!1),te(""),X(-1)},[]),Te=a.useCallback((ne=un.current)=>{ne&&(ne.style.height="auto",ne.style.height=`${T9(ne.scrollHeight)}px`)},[]),U=a.useCallback(ne=>{Le(Ue=>{const Je=Wy(Ue);if(!Je)return Ue;const qt=`/skill:${ne.name} `,En=Ue.slice(0,Je.start)+qt+Ue.slice(Je.end);return window.requestAnimationFrame(()=>{un.current&&(Te(un.current),un.current.focus())}),En}),q(!1),De(""),qe(0)},[Te]),ge=a.useCallback(ne=>{const Ue=un.current;if(!Ue||he<0)return;const Je=Ue.selectionStart??Ie.current,qt=Ue.selectionEnd??Je,En=Math.max(Je,qt),yn=Math.min(he,En),fs=`${`@${ne.name.replace(/\s+/g,"_")}`} `,ws=be.slice(0,yn)+fs+be.slice(En),js=yn+fs.length;Le(ws),se(!1),te(""),Y(0),X(-1),window.requestAnimationFrame(()=>{un.current&&(Te(un.current),un.current.focus(),un.current.setSelectionRange(js,js))})},[he,be,Te]),rt=a.useCallback((ne,Ue)=>{const qt=un.current?.selectionStart??Ie.current,En=be.lastIndexOf("#",qt),yn=En>=0?En+Ue.length:ne.length;Le(ne),nt.dismissMention(),Ke(!1),window.requestAnimationFrame(()=>{un.current&&(Te(un.current),un.current.focus(),un.current.setSelectionRange(yn,yn))})},[nt,be,Te]),Lt=a.useCallback(ne=>{const Ue=ne.target.value,Je=ne.target.selectionStart??Ue.length;Te(ne.target),Ie.current=Je,Le(Ue),ue&&Ue.trim().length>0&&je(!1),ks(Ue,Je);const qt=Wy(Ue);qt?(q(!0),De(qt.filter)):(q(!1),De("")),nt.detectMention(Ue,Je),Ke(nt.mentionActive),nt.mentionActive&&Nt(ne.target)},[nt,ue,Te,Nt,ks]);a.useLayoutEffect(()=>{Te()},[be,Te]);const Dt=a.useCallback(()=>{if(Oe.current){window.requestAnimationFrame(()=>{vt()});return}typeof window<"u"&&window.innerWidth<=Ni&&Bn.current&&(Gt.current=!0,Bn.current.style.removeProperty("--vv-height"),Bn.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Gt.current=!1},450)),Pe.current!==null&&window.clearTimeout(Pe.current),Pe.current=window.setTimeout(()=>{se(!1),te(""),X(-1),Ke(!1),nt.dismissMention(),Pe.current=null},120),oe.current!==null&&window.clearTimeout(oe.current),oe.current=window.setTimeout(()=>{q(!1),oe.current=null},120)},[nt,vt]),en=a.useCallback(()=>{Gt.current=!1,Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null),oe.current!==null&&(window.clearTimeout(oe.current),oe.current=null)},[]),tn=a.useCallback(ne=>{const Ue=ne.currentTarget,Je=Ue.selectionStart??Ue.value.length;Ie.current=Je,ks(Ue.value,Je),nt.detectMention(Ue.value,Je),Ke(nt.mentionActive),nt.mentionActive&&Nt(Ue)},[ks,nt,Nt]),Dn=a.useCallback(ne=>{ne.key!=="Escape"&&tn(ne)},[tn]),_n=a.useCallback(ne=>{ot(Ue=>{const Je=new Set(Ue);return Je.has(ne)?Je.delete(ne):Je.add(ne),Je})},[]),is=a.useCallback((ne,Ue=!1)=>Ue?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Hs(ne)}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Di,{remarkPlugins:[Li],components:lS,children:ne})}),[]),Ss=a.useCallback(ne=>{if(Ie.current=ne.currentTarget.selectionStart??Ie.current,nt.mentionActive&&nt.combinedItems.length>0){if(nt.handleKeyDown(ne,be),ne.key==="Enter"||ne.key==="Tab"){const Ue=nt.combinedItems[nt.selectedIndex];Ue?.kind==="task"?rt(nt.selectTask(Ue.task,be),`#${Ue.task.id}`):Ue?.kind==="file"&&rt(nt.selectFile(Ue.file,be),`#${Ue.file.path}`)}return}if(me&&ne.key==="ArrowDown"){ne.preventDefault(),Ge.length>0&&Y(Ue=>(Ue+1)%Ge.length);return}if(me&&ne.key==="ArrowUp"){ne.preventDefault(),Ge.length>0&&Y(Ue=>Ue===0?Ge.length-1:Ue-1);return}if(me&&ne.key==="Enter"){ne.preventDefault();const Ue=Ge[z]??Ge[0];Ue&&ge(Ue);return}if(me&&ne.key==="Escape"){ne.preventDefault(),ne.stopPropagation(),se(!1),te(""),X(-1);return}if(xe&&at.length>0&&ne.key==="ArrowDown"){ne.preventDefault(),qe(Ue=>(Ue+1)%at.length);return}if(xe&&at.length>0&&ne.key==="ArrowUp"){ne.preventDefault(),qe(Ue=>Ue===0?at.length-1:Ue-1);return}if(xe&&(ne.key==="Enter"||ne.key==="Tab")){ne.preventDefault();const Ue=at[He]??at[0];Ue&&U(Ue);return}if(xe&&ne.key==="Escape"){ne.preventDefault(),q(!1),De("");return}ne.key!=="Enter"||ne.shiftKey||(ne.preventDefault(),zt())},[me,Ge,z,ge,zt,nt,rt,be,xe,at,He,U]),Rs=a.useCallback(()=>{if(Ft.current){Ft.current=!1;return}if(j){S(!1);return}typeof window<"u"&&window.innerWidth<=Ni&&yt.current?.focus({preventScroll:!0}),S(!0)},[j,S]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:yt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:kn,type:"button",className:"quick-chat-fab","aria-label":p("chat.openQuickChat","Open quick chat"),"data-testid":"quick-chat-fab","data-dragging":fe?"true":"false",style:{right:_e.x,bottom:_e.y},onPointerDown:Xe,onClick:Rs,children:t.jsx(Ra,{size:24})}),j&&t.jsxs("div",{className:`quick-chat-panel${F&&C?" quick-chat-panel--keyboard-open":""}`,ref:Bn,"data-testid":"quick-chat-panel",style:{...bt?{right:_e.x+Vt.right,bottom:kt+Vt.bottom,width:Rt.width,height:Rt.height}:{}},children:[bt&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Pt,role:"separator","aria-orientation":"horizontal","aria-label":p("chat.resizePanelTop","Resize panel from top")}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:Pt,role:"separator","aria-orientation":"horizontal","aria-label":p("chat.resizePanelBottom","Resize panel from bottom")}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:Pt,role:"separator","aria-orientation":"vertical","aria-label":p("chat.resizePanelRight","Resize panel from right")}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:Pt,role:"separator","aria-orientation":"vertical","aria-label":p("chat.resizePanelLeft","Resize panel from left")}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:Pt,role:"separator","aria-label":p("chat.resizePanelTopLeft","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:Pt,role:"separator","aria-label":p("chat.resizePanelTopRight","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:Pt,role:"separator","aria-label":p("chat.resizePanelBottomLeft","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:Pt,role:"separator","aria-label":p("chat.resizePanelBottomRight","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:p("chat.quickChatTitle","Quick Chat")}),ht&&Tt.activeRoom?t.jsxs("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-room-tag",title:`#${Tt.activeRoom.name}`,children:["#",Tt.activeRoom.name]}):M==="model"&&Se&&(()=>{const ne=ae?.provider??Ne?.modelProvider??"";return E==="mobile"&&Se.length>12&&ne?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Se,"aria-label":Se,children:t.jsx(hs,{provider:ne,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Se,children:Se})})()]}),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":p("chat.startNewChat","Start a new chat"),onClick:Cn,disabled:Qt,children:t.jsx(ys,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":p("chat.closeQuickChat","Close quick chat"),"data-testid":"quick-chat-close",onClick:()=>S(!1),children:t.jsx(Fn,{size:16})})]})]}),t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:t.jsxs("div",{className:"quick-chat-session-menu",ref:At,children:[t.jsx("label",{htmlFor:"quick-chat-session-dropdown-trigger",className:"visually-hidden",children:p("chat.selectSessionLabel","Select session")}),t.jsx("input",{type:"hidden","data-testid":"quick-chat-session-dropdown",value:rs&&ht?"":pt?.id??"",readOnly:!0}),t.jsxs("button",{id:"quick-chat-session-dropdown-trigger",type:"button",className:"btn quick-chat-session-trigger","aria-haspopup":"menu","aria-expanded":R,"data-testid":"quick-chat-session-dropdown-trigger",onClick:()=>L(ne=>!ne),children:[ht&&Tt.activeRoom?t.jsx(Ck,{size:16,"aria-hidden":"true"}):pt?.modelProvider?t.jsx(hs,{provider:pt.modelProvider,size:"sm"}):t.jsx(Ra,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:ei}),t.jsx(Ln,{size:16,"aria-hidden":"true"})]}),R&&t.jsxs("div",{className:"quick-chat-session-dropdown",role:"menu","data-testid":"quick-chat-session-dropdown-menu",children:[rs&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-session-dropdown-group-label",children:p("chat.roomsGroupLabel","Rooms")}),Ls.map(ne=>{const Ue=Tt.activeRoom?.id===ne.id,Je=!Ue&&Yn("room",ne.id,ne.updatedAt);return t.jsxs("button",{type:"button",role:"menuitem","data-testid":`quick-chat-session-option-room-${ne.slug}`,className:`quick-chat-session-option${Ue?" quick-chat-session-option--active":""}`,onClick:()=>mi(ne.id),children:[t.jsxs("span",{children:["#",ne.name]}),Je?t.jsx("span",{className:"chat-unread-dot quick-chat-session-unread-dot","data-testid":`quick-chat-unread-dot-${ne.id}`,"aria-label":p("chat.unreadMessages","Unread messages")}):null]},ne.id)}),t.jsx("div",{className:"quick-chat-session-dropdown-group-label",children:p("chat.sessionsGroupLabel","Sessions")})]}),Ts.map(ne=>{const Ue=!ht&&pt?.id===ne.id,Je=vn.find(En=>En.id===ne.id),qt=!Ue&&Yn("direct",ne.id,Je?.lastMessageAt??Je?.updatedAt);return t.jsxs("button",{type:"button",role:"menuitem","data-testid":`quick-chat-session-option-${ne.id}`,className:`quick-chat-session-option${Ue?" quick-chat-session-option--active":""}`,onClick:()=>ti(ne.id),children:[t.jsx("span",{children:ne.label}),qt?t.jsx("span",{className:"chat-unread-dot quick-chat-session-unread-dot","data-testid":`quick-chat-unread-dot-${ne.id}`,"aria-label":p("chat.unreadMessages","Unread messages")}):null]},ne.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${O==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>J("model"),children:p("chat.modeModel","Model")}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${O==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>J("agent"),children:p("chat.modeAgent","Agent")})]}),O==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:p("chat.selectAgentForNewChat","Select agent for new chat")}),t.jsx("select",{id:"quick-chat-new-agent-select",value:A,onChange:ne=>de(ne.target.value),"data-testid":"quick-chat-new-agent-select",children:h.map(ne=>t.jsx("option",{value:ne.id,children:M9(ne)},ne.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(wi,{id:"quick-chat-new-model-select",models:u,value:B,onChange:P,label:p("chat.selectModelOverrideLabel","Select model override"),placeholder:y?p("chat.loadingModels","Loading models…"):p("chat.selectModelPlaceholder2","Select a model"),disabled:y||u.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:d,onToggleModelFavorite:c})}),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:()=>{$(!1),J("model")},children:p("chat.cancelButton","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void zs(),disabled:Qt||(O==="agent"?!A:!zl(B||Z||ie)),children:p("chat.createButton","Create")})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:pn,"data-testid":"quick-chat-messages",onScroll:St,children:Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.loadingConversation","Loading conversation…")}):!ht&&_t?t.jsxs(t.Fragment,{children:[et.map(ne=>t.jsx(mh,{message:ne,forcePlain:ne.role!=="user"&&ye.has(ne.id),mentionAgentsByName:tt,roomContext:m,projectId:e,onToggleRender:_n},ne.id)),ue&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:is(p("chat.helpMessageContent","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:[Yt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:is(Yt,ye.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${ye.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":ye.has("__streaming__")?p("chat.showRenderedMarkdown","Show rendered markdown"):p("chat.showPlainText","Show plain text"),onClick:()=>_n("__streaming__"),children:ye.has("__streaming__")?t.jsx(jp,{size:14}):t.jsx(bc,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:on?p("chat.thinkingStatus","Thinking…"):p("chat.connectingStatus","Connecting…")}),oS(An,!0,p),on&&t.jsxs("details",{className:"chat-message-thinking","data-testid":"quick-chat-streaming-thinking",children:[t.jsx("summary",{children:p("chat.thinkingLabel","Thinking")}),t.jsx("pre",{className:"chat-message-thinking-content",children:Hs(on)})]})]})]}):ht?Tt.messagesLoading?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.loadingConversation","Loading conversation…")}):et.length===0&&!ue?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsxs(t.Fragment,{children:[et.map(ne=>t.jsx(mh,{message:ne,forcePlain:ne.role!=="user"&&ye.has(ne.id),mentionAgentsByName:tt,roomContext:m,projectId:e,onToggleRender:_n},ne.id)),ue&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:is(p("chat.helpMessageContent","Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help"))})]}):sn?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.loadingConversation","Loading conversation…")}):et.length===0&&!Yt&&!on&&!_t&&!ue?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsxs(t.Fragment,{children:[et.map(ne=>t.jsx(mh,{message:ne,forcePlain:ne.role!=="user"&&ye.has(ne.id),mentionAgentsByName:tt,roomContext:m,projectId:e,onToggleRender:_n},ne.id)),ue&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:is(p("chat.helpMessageContent","Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help"))})]})}),Ee&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:ss,children:[t.jsx(Ln,{size:14}),p("chat.jumpToLatest","Latest")]}),$e.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:$e.map((ne,Ue)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Ue}`,children:[ne.previewUrl?t.jsx("img",{src:ne.previewUrl,alt:ne.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ne.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Ue}`,"aria-label":p("chat.removeAttachment","Remove {{name}}",{name:ne.file.name}),onClick:()=>Q(Ue),children:"×"})]},`${ne.file.name}-${Ue}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${We?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Wt,onDragOver:hn,onDragLeave:In,onDrop:gs,children:[t.jsx("input",{ref:an,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:ne=>{Zt(ne.target.files),ne.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":p("chat.attachFiles","Attach files"),onClick:()=>an.current?.click(),children:t.jsx(Mk,{size:16})}),t.jsx("textarea",{ref:un,rows:1,className:"quick-chat-textarea",value:be,onChange:Lt,onKeyDown:Ss,onKeyUp:Dn,onClick:tn,onBlur:Dt,onFocus:en,onPaste:Qe,onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Ni||tf()&&document.activeElement!==ne.currentTarget&&(ne.preventDefault(),ne.currentTarget.focus({preventScroll:!0}))},placeholder:Mi,disabled:Ut,"data-testid":"quick-chat-input"}),_t?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:ne=>{typeof window>"u"||window.innerWidth>Ni||(ne.preventDefault(),ne.pointerType&&ne.pointerType!=="mouse"&&(G.current=!0,Kt()))},onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Ni||(ne.preventDefault(),G.current=!0,Kt())},onMouseDown:ne=>{typeof window>"u"||window.innerWidth>Ni||ne.preventDefault()},onClick:()=>{if(G.current){G.current=!1;return}Kt()},"aria-label":p("chat.stopGeneration","Stop generation"),"data-testid":"quick-chat-stop",children:t.jsx(Ea,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:ne=>{typeof window>"u"||window.innerWidth>Ni||(ne.preventDefault(),ne.pointerType&&ne.pointerType!=="mouse"&&(G.current=!0,xt(),vt(),zt()))},onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Ni||(ne.preventDefault(),G.current=!0,xt(),vt(),zt())},onMouseDown:ne=>{typeof window>"u"||window.innerWidth>Ni||ne.preventDefault()},onClick:()=>{if(G.current){G.current=!1;return}zt()},disabled:$t,"data-testid":"quick-chat-send",children:t.jsx(zr,{size:16})})]}),t.jsx(i9,{agents:h,filter:pe,highlightedIndex:z,visible:me,onSelect:ge,position:"above",roomMemberIds:m?.memberIds,roomName:m?.roomName}),t.jsx(x9,{visible:nt.mentionActive&&!me,position:dt,tasks:nt.tasks,files:nt.files,selectedIndex:nt.selectedIndex,onSelectTask:ne=>{rt(nt.selectTask(ne,be),`#${ne.id}`)},onSelectFile:ne=>{rt(nt.selectFile(ne,be),`#${ne.path}`)},loading:nt.loading}),xe&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:x?t.jsx("div",{className:"chat-skill-menu-empty",children:p("chat.loadingSkills","Loading skills…")}):at.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:ce?p("chat.noSkillsFound","No skills found"):p("chat.noSkillsAvailable","No skills available")}):at.map((ne,Ue)=>t.jsxs("button",{type:"button",role:"option","aria-selected":Ue===He,className:`chat-skill-menu-item${Ue===He?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Je=>Je.preventDefault(),onMouseEnter:()=>qe(Ue),onClick:()=>U(ne),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:ne.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:ne.relativePath,children:ne.relativePath})]},ne.id))}),!ht&&fn&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:p("chat.queuedMessage","Queued: {{preview}}",{preview:Qn})}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":p("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":"chat-pending-dismiss",onClick:$n,children:"×"})]})]})})]})]})}function Bl(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Gy(e){return e.status==="generating"||e.status==="awaiting_input"}function Ul(e){return e==="complete"||e==="error"}function U9(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:d,requestSync:c}=pl(),m=a.useCallback(()=>{Up(e).then(f=>{const b=f.filter(v=>{const x=Bl(v.updatedAt),k=r.current.get(v.id);return k===void 0?!0:x<=k?!1:(r.current.delete(v.id),!0)}),y=new Map;for(const v of b)y.set(v.id,Bl(v.updatedAt));i.current=y,s(b)}).catch(f=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",f)})},[e]);a.useEffect(()=>{c(),m()},[m,c]),a.useEffect(()=>{s(f=>{if(o.size===0)return f;let b=!1;const y=new Map(f.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,k=i.current.get(v.sessionId)??0;if(x<k)continue;const w=r.current.get(v.sessionId);if(w!==void 0&&x<=w)continue;if(w!==void 0&&x>w&&!Ul(v.status)&&r.current.delete(v.sessionId),Ul(v.status)){y.delete(v.sessionId)&&(b=!0),i.current.set(v.sessionId,x);continue}const g=y.get(v.sessionId),j=v.type??g?.type,S=v.title??g?.title;if(!g&&(!j||!S))continue;const C={id:v.sessionId,type:j??"planning",status:v.status,title:S??"AI Session",projectId:v.projectId??g?.projectId??e??null,lockedByTab:v.owningTabId??g?.lockedByTab??null,updatedAt:v.updatedAt??g?.updatedAt??new Date(x).toISOString()},E=y.get(v.sessionId);(!E||E.status!==C.status||E.title!==C.title||E.type!==C.type||E.projectId!==C.projectId||E.lockedByTab!==C.lockedByTab||E.updatedAt!==C.updatedAt)&&(y.set(v.sessionId,C),i.current.set(v.sessionId,x),b=!0)}return b?[...y.values()].sort((v,x)=>Bl(x.updatedAt)-Bl(v.updatedAt)):f})},[e,o]),a.useEffect(()=>{const f=e?`?projectId=${encodeURIComponent(e)}`:"",b=k=>{try{const w=JSON.parse(k.data),g=Bl(w.updatedAt)||Date.now();s(j=>{const S=i.current.get(w.id)??0;if(g<S)return j;const C=r.current.get(w.id);if(C!==void 0&&g<=C)return j;if(C!==void 0&&g>C&&!Ul(w.status)&&r.current.delete(w.id),i.current.set(w.id,g),Ul(w.status))return j.filter(F=>F.id!==w.id);const E=j.findIndex(F=>F.id===w.id);if(E>=0){const F=[...j];return F[E]=w,F}return Gy(w)?[w,...j]:j}),l({sessionId:w.id,status:w.status,needsInput:w.status==="awaiting_input",type:w.type,title:w.title,projectId:w.projectId,owningTabId:w.lockedByTab,updatedAt:w.updatedAt,timestamp:g}),Ul(w.status)&&d({sessionId:w.id,status:w.status,timestamp:g})}catch{}},y=k=>{try{const w=JSON.parse(k.data),g=Date.now();r.current.set(w,g),i.current.set(w,Math.max(i.current.get(w)??0,g)),d({sessionId:w,status:"complete",timestamp:g}),s(j=>j.filter(S=>S.id!==w))}catch{}},v=`/api/events${f}`,x=li(v,{events:{"ai_session:updated":b,"ai_session:deleted":y},onReconnect:()=>{Gs({view:"useBackgroundSessions",trigger:"sse-reconnect",projectId:e,replayAttempted:!1,sseChannel:v}),m()}});return Gs({view:"useBackgroundSessions",trigger:"sse-open",projectId:e,replayAttempted:!1,sseChannel:v}),x},[d,l,e,m]);const p=a.useCallback(async f=>{const y=n.find(w=>w.id===f)?.type,v=so();let x=!1;if(y==="planning")try{await Qk(f,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${f} despite lock by another tab`)}else if(y==="subtask")try{await nw(f,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${f} despite lock by another tab`)}else if(y==="mission_interview")try{await XT(f,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${f} despite lock by another tab`)}x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${f}, attempting delete anyway`);const k=Date.now();r.current.set(f,k),i.current.set(f,Math.max(i.current.get(f)??0,k)),d({sessionId:f,status:"complete",timestamp:k});try{await ow(f)}catch{}s(w=>w.filter(g=>g.id!==f))},[d,e,n]),h=a.useMemo(()=>n.filter(f=>Gy(f)),[n]),u=a.useMemo(()=>h.filter(f=>f.type==="planning"),[h]);return{sessions:h,generating:h.filter(f=>f.status==="generating").length,needsInput:h.filter(f=>f.status==="awaiting_input").length,planningSessions:u,dismissSession:p,refresh:m}}const Of="fusion:github-star-prompt-shown",yp="fusion:github-star-prompt-changed";function H9(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Of)==="1"}catch{return!1}}function V9(e){if(typeof window>"u")return()=>{};const n=i=>{i.key===Of&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(yp,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(yp,s)}}function q9(){if(!(typeof window>"u"))try{window.localStorage.setItem(Of,"1"),window.dispatchEvent(new Event(yp))}catch{}}function W9(){return a.useSyncExternalStore(V9,H9,()=>!1)}const cu="fusion:hide-session-banners",kp="fusion:session-banner-pref-changed";function G9(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(cu)==="1"}catch{return!1}}function K9(e){if(typeof window>"u")return()=>{};const n=i=>{i.key===cu&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(kp,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(kp,s)}}function zK(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(cu,"1"):window.localStorage.removeItem(cu),window.dispatchEvent(new Event(kp))}catch{}}function J9(){return a.useSyncExternalStore(K9,G9,()=>!1)}const Cd=new Set;function Xs(e){return{...e,column:G_(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Xl(e){return!!e.deletedAt}function _d(e){return e.filter(n=>!Xl(n))}function Ky(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function Y9(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,firstExecutionAt:e.firstExecutionAt??n.firstExecutionAt,cumulativeActiveMs:n.cumulativeActiveMs??e.cumulativeActiveMs,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 hh(e,n){if(Ky(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return Y9(e,n);const i=Ky(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:i>=0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function X9(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState(()=>{if(!n)return[];const T=ki(`${Tn.TASKS_PREFIX}${n}`,{maxAgeMs:Lh});return Array.isArray(T)&&T.length>0&&!Cd.has(n)&&(Cd.add(n),console.info("[swr-cache] hit tasks=",T.length,"projectId=",n)),Array.isArray(T)?_d(T.map(Xs)):[]}),[l,d]=a.useState(!0),[c,m]=a.useState(null),[p,h]=a.useState(!1),u=a.useRef(p);u.current=p;const f=a.useRef(r),b=a.useRef(0),y=a.useRef(0),v=a.useRef(0),x=a.useRef(y.current),k=a.useRef(0),w=a.useRef(s),g=a.useRef(null),j=a.useRef(void 0),S=a.useRef(n);f.current=r,w.current=s,S.current!==n&&(S.current=n,y.current++);const C=1e3,E=a.useCallback(async T=>{const ie=++b.current,le=n,be=T?.searchQueryOverride??w.current,Le=T?.includeArchivedOverride??u.current;try{const xe=await Uk(void 0,void 0,le,be,Le);if(b.current!==ie||n!==le)return;const q=_d(xe.map(Xs));if(o(q),le){const ce=xe.length>500?xe.slice(0,500):xe;es(`${Tn.TASKS_PREFIX}${le}`,ce,{maxBytes:5e5})}d(!1),m(null),j.current=Date.now()}catch{if(b.current!==ie||n!==le)return;if(m(Date.now()),le&&vs(`${Tn.TASKS_PREFIX}${le}`),T?.clearOnError){o([]);return}}},[n]);g.current=E;const F=a.useCallback(async()=>{u.current||(h(!0),u.current=!0,await g.current({includeArchivedOverride:!0}))},[]),M=a.useRef(s);a.useEffect(()=>{if(s===void 0&&M.current===void 0)return;M.current=s;const T=setTimeout(()=>{E({searchQueryOverride:s})},300);return()=>clearTimeout(T)},[s]),a.useEffect(()=>{if(!n)return;const T=ki(`${Tn.TASKS_PREFIX}${n}`,{maxAgeMs:Lh});Array.isArray(T)&&(T.length>0&&!Cd.has(n)&&(Cd.add(n),console.info("[swr-cache] hit tasks=",T.length,"projectId=",n)),o(_d(T.map(Xs)))),d(!0)},[n]),a.useEffect(()=>{d(!0),E({clearOnError:!0});const T=()=>{if(document.visibilityState!=="visible"){x.current=y.current;return}const ie=x.current,le=ie!==y.current;if(x.current=y.current,le){v.current=Date.now(),di("useTasks","visibility-context-version-changed",{projectId:n,previousContextVersion:ie,currentContextVersion:y.current}),Gs({view:"useTasks",trigger:"visibility",projectId:n,replayAttempted:!1,reason:"context-version-changed"}),E();return}const be=Date.now();be-v.current<C||(v.current=be,Gs({view:"useTasks",trigger:"visibility",projectId:n,replayAttempted:!1,reason:"debounced-refresh"}),E())};return document.addEventListener("visibilitychange",T),()=>{document.removeEventListener("visibilitychange",T)}},[E]),a.useEffect(()=>{if(i===!1)return;let T=y.current;const ie=n?`?projectId=${encodeURIComponent(n)}`:"",le=()=>y.current!==T,be=()=>{k.current+=1,di("useTasks","dropped-stale-event",{count:k.current,contextVersionAtStart:T,currentContextVersion:y.current,projectId:n})};let Le=!0;const xe=pe=>{if(le()){be();return}const te=Xs(JSON.parse(pe.data));if(w.current){g.current({searchQueryOverride:w.current});return}if(Xl(te)){o(me=>me.filter(se=>se.id!==te.id)),di("useTasks","soft-deleted-task-suppressed",{event:"task:created",id:te.id});return}o(me=>{const se=me.findIndex(X=>X.id===te.id);if(se===-1)return[...me,te];const z=me[se],Y=hh(z,te);if(Y===z)return me;const he=[...me];return he[se]=Y,he}),j.current=Date.now()},q=pe=>{if(le()){be();return}if(w.current){g.current({searchQueryOverride:w.current});return}const{task:te,to:me}=JSON.parse(pe.data),se=Xs(te);if(Xl(se)){o(he=>he.filter(X=>X.id!==se.id)),di("useTasks","soft-deleted-task-suppressed",{event:"task:moved",id:se.id});return}const z=typeof me=="string"&&me?me:se.column,Y={...se,column:z};o(he=>{const X=he.findIndex(ot=>ot.id===Y.id);if(X===-1)return[...he,Y];const ye=[...he];return ye[X]=Y,ye}),j.current=Date.now()},ce=pe=>{if(le()){be();return}if(w.current){g.current({searchQueryOverride:w.current});return}const te=Xs(JSON.parse(pe.data));if(Xl(te)){o(me=>me.filter(se=>se.id!==te.id)),di("useTasks","soft-deleted-task-suppressed",{event:"task:updated",id:te.id});return}o(me=>{const se=me.findIndex(X=>X.id===te.id);if(se===-1)return[...me,te];const z=me[se],Y=hh(z,te);if(Y===z)return me;const he=[...me];return he[se]=Y,he}),j.current=Date.now()},De=pe=>{if(le()){be();return}if(w.current){g.current({searchQueryOverride:w.current});return}const te=Xs(JSON.parse(pe.data));o(me=>me.filter(se=>se.id!==te.id))},He=pe=>{if(le()){be();return}if(w.current){g.current({searchQueryOverride:w.current});return}const{task:te}=JSON.parse(pe.data),me=Xs(te);if(Xl(me)){o(z=>z.filter(Y=>Y.id!==me.id)),di("useTasks","soft-deleted-task-suppressed",{event:"task:merged",id:me.id});return}const se={...me,column:"done"};o(z=>{const Y=z.findIndex(X=>X.id===se.id);if(Y===-1)return[...z,se];const he=[...z];return he[Y]=se,he})},qe=li(`/api/events${ie}`,{events:{"task:created":xe,"task:moved":q,"task:updated":ce,"task:deleted":De,"task:merged":He},onReconnect:()=>{if(T=y.current,!!Le){if(le()){be();return}Gs({view:"useTasks",trigger:"sse-reconnect",projectId:n,replayAttempted:!1}),g.current()}}});return()=>{Le=!1,qe()}},[n,i]);const D=a.useCallback(async T=>{const ie=Xs(await Hk(T,n));return o(le=>le.some(be=>be.id===ie.id)?le:[...le,ie]),ie},[n]),_=a.useCallback(async(T,ie,le)=>Xs(await yE(T,ie,n,le)),[n]),V=a.useCallback(async T=>Xs(await Gk(T,n)),[n]),N=a.useCallback(async T=>Xs(await Kk(T,n)),[n]),$=a.useCallback(async(T,ie)=>Xs(await jE(T,n,ie)),[n]),R=a.useCallback(async T=>NE(T,n),[n]),L=a.useCallback(async T=>Xs(await SE(T,n)),[n]),O=a.useCallback(async T=>Xs(await _E(T,n)),[n]),J=a.useCallback(async T=>{const ie=Xs(await EE(T,n));return o(le=>le.some(be=>be.id===ie.id)?le:[...le,ie]),ie},[n]),A=a.useCallback(async(T,ie)=>{const le=f.current.find(Le=>Le.id===T),be=le?{...le,...ie,updatedAt:new Date().toISOString()}:void 0;be&&o(Le=>Le.map(xe=>xe.id===T?be:xe));try{const Le=Xs(await si(T,ie,n));return o(xe=>xe.map(q=>q.id===T?Le:q)),Le}catch(Le){throw le&&o(xe=>xe.map(q=>q.id===T?le:q)),Le}},[n]),de=a.useCallback(async(T,ie)=>{const le=Xs(await ME(T,n,ie));return o(be=>be.map(Le=>Le.id===T?le:Le)),le},[n]),B=a.useCallback(async T=>{const ie=Xs(await AE(T,n));return o(le=>le.map(be=>be.id===T?ie:be)),ie},[n]),P=a.useCallback(async()=>{const ie=(await TE(n)).map(Xs);return o(le=>le.map(be=>ie.find(xe=>xe.id===be.id)||be)),ie},[n]),Z=a.useCallback(T=>{if(T.length===0)return;if(w.current){g.current({searchQueryOverride:w.current});return}const ie=_d(T.map(Xs));o(le=>{let be=le;for(const Le of ie){const xe=be.findIndex(De=>De.id===Le.id);if(xe===-1){be===le&&(be=[...le]),be.push(Le);continue}const q=be[xe],ce=hh(q,Le);ce!==q&&(be===le&&(be=[...le]),be[xe]=ce)}return be}),j.current=Date.now()},[]);return{tasks:r,isStale:l,lastRefreshErrorAt:c,createTask:D,moveTask:_,pauseTask:V,unpauseTask:N,deleteTask:$,mergeTask:R,retryTask:L,resetTask:O,duplicateTask:J,updateTask:A,archiveTask:de,unarchiveTask:B,archiveAllDone:P,loadArchivedTasks:F,includeArchived:p,refreshTasks:E,ingestCreatedTasks:Z,lastFetchTimeMs:j.current}}const Q9=5e3,Z9=1e3;function eV(e){const s=(eT(e)?e.nodeMappings??e.projectNodeMappings??e.pathMappings??[]:[]).filter(i=>!!i?.nodeId&&!!i?.path).map(i=>({nodeId:i.nodeId,nodeName:i.nodeName,path:i.path,available:i.available!==!1}));return s.length>0?s:e.nodeId&&e.path?[{nodeId:e.nodeId,nodeName:e._sourceNodeName,path:e.path,available:!0}]:[]}function ph(e){return e.map(n=>({...n,nodeMappings:eV(n)}))}function tV(){const[e,n]=a.useState(()=>{const y=ki(Tn.PROJECTS,{maxAgeMs:Gr});return Array.isArray(y)?(y.length>0&&console.info("[swr-cache] hit projects=",y.length),ph(y)):[]}),[s,i]=a.useState(()=>e.length===0),[r,o]=a.useState(null),l=a.useRef(null),d=a.useRef(0),c=a.useRef(e),m=ul();a.useEffect(()=>{c.current=e},[e]);const p=a.useCallback(y=>c.current.length>0&&_c(y,m.wasRecentlyHidden()),[m]),h=a.useCallback(async()=>{try{o(null);const y=await zg(),v=ph(y);n(v),es(Tn.PROJECTS,v)}catch(y){const v=y instanceof Error?y.message:"Failed to fetch projects";p(v)||o(v)}},[p]);a.useEffect(()=>{let y=!1;async function v(){e.length>0||i(!0);const w=performance.now();try{const g=await zg(),j=ph(g),S=Math.round(performance.now()-w);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${S}ms (${j.length} projects)`),y||(n(j),o(null),es(Tn.PROJECTS,j))}catch(g){const j=Math.round(performance.now()-w),S=g instanceof Error?g.message:"Failed to fetch projects";console.warn(`[useProjects] initial fetch failed after ${j}ms: ${S}`),!y&&!p(S)&&o(S)}finally{y||i(!1)}}v();const x=()=>{if(document.visibilityState!=="visible")return;const k=Date.now(),w=k-d.current;if(w<Z9){Gs({view:"useProjects",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounce-skipped",detail:{timeSinceLastRefreshMs:w}});return}d.current=k,Gs({view:"useProjects",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounced-refresh"}),h()};return document.addEventListener("visibilitychange",x),()=>{y=!0,document.removeEventListener("visibilitychange",x)}},[e.length,h,p]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{h()},Q9),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,h]);const u=a.useCallback(async y=>{const v=await lT(y);return n(x=>[...x,v]),v},[]),f=a.useCallback(async(y,v)=>{const x=await fT(y,v);return n(k=>k.map(w=>w.id===y?x:w)),x},[]),b=a.useCallback(async y=>{await iw(y),n(v=>{const x=v.filter(k=>k.id!==y);return es(Tn.PROJECTS,x),x}),vs(`${Tn.TASKS_PREFIX}${y}`)},[]);return{projects:e,loading:s,error:r,refresh:h,register:u,update:f,unregister:b}}const nV="kb-dashboard-current-project",Jy=3;function sV(e){return e??"local"}function iV(e,n={}){const{nodeId:s=null}=n,i=ki(Tn.CURRENT_PROJECT_ID,{maxAgeMs:Fh}),r=typeof i=="string"&&i.length>0?e.find(j=>j.id===i)??null:null,[o,l]=a.useState(r),[d,c]=a.useState(()=>r===null),m=a.useRef(!1),p=a.useRef(null),h=a.useRef(!1),u=a.useRef(null),f=a.useRef(0),b=a.useRef(0),y=sV(s),v=a.useCallback(j=>{es(Tn.CURRENT_PROJECT_ID,j??"")},[]),x=a.useCallback(j=>j.find(S=>S.status==="active")||j[0]||null,[]),k=a.useCallback(j=>{f.current=0,b.current=0,l(j),v(j?.id??null)},[v]);a.useEffect(()=>{let j=!1;if(p.current!==y&&(p.current=null,m.current=!1),m.current&&p.current===y)return c(!1),()=>{j=!0};typeof i=="string"&&i.length>0&&e.some(E=>E.id===i)||c(!0);async function C(){try{const E=await Ja();if(j)return;u.current=E.dashboardCurrentProjectIdByNode??{};const F=u.current[y];if(F){const M=e.find(D=>D.id===F);M&&(b.current=0,l(M),v(M.id))}if(!F)try{const M=localStorage.getItem(nV);if(M){const D=JSON.parse(M);D?.id&&e.some(V=>V.id===D.id)&&(b.current=0,l(D),v(D.id),u.current={...u.current,[y]:D.id},await Ms({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{j||(m.current=!0,p.current=y,c(!1))}}return C(),()=>{j=!0}},[e,i,y,v]),a.useEffect(()=>{f.current=0,b.current=0},[o?.id]),a.useEffect(()=>{if(!d)if(o){if(b.current=0,e.some(C=>C.id===o.id))f.current=0;else if(e.length===0)f.current=0;else{if(f.current+=1,f.current>=Jy){const C=x(e);k(C),C||v(null)}return}const S={...u.current,[y]:o.id};u.current=S,Ms({dashboardCurrentProjectIdByNode:S}).catch(()=>{}),v(o.id)}else{if(f.current=0,e.length===0){b.current=0;return}if(!h.current){const j=u.current?.[y];if(j){const S=e.find(C=>C.id===j)??null;if(S){b.current=0,k(S);return}}b.current+=1,b.current>=Jy&&(b.current=0,k(x(e)))}}},[e,o,d,y,v,x,k]);const w=a.useCallback(j=>{if(h.current=!1,f.current=0,b.current=0,l(j),v(j?.id??null),j){const S={...u.current,[y]:j.id};u.current=S,Ms({dashboardCurrentProjectIdByNode:S}).catch(()=>{})}},[y,v]),g=a.useCallback(()=>{h.current=!0,f.current=0,b.current=0,l(null),v(null);const j={...u.current};delete j[y],u.current=j,Ms({dashboardCurrentProjectIdByNode:j}).catch(()=>{})},[y,v]);return{currentProject:o,setCurrentProject:w,clearCurrentProject:g,loading:d}}const aV=(e,n,s)=>{const i=e[n];return i?typeof i=="function"?i():Promise.resolve(i):new Promise((r,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+n+(n.split("/").length!==s?". Note that variables only represent file names one level deep.":""))))})},rV=["common","app","errors"],oV={dashboard:rV},lV="common",cV=oV.dashboard,dV={"zh-Hans":["zh-CN"],"zh-Hant":["zh-TW"],zh:["zh-CN"],default:[J_]};function uV(e){if(!e)return;const n=e.replaceAll("_","-");if(pg(n))return n;const s=n.toLowerCase();if(s.startsWith("zh"))return s.includes("hans")?"zh-CN":s.includes("hant")||s.includes("-tw")||s.includes("-hk")||s.includes("-mo")?"zh-TW":"zh-CN";const i=s.split("-")[0];return pg(i)?i:void 0}function mV(){return{supportedLngs:[...Ik],fallbackLng:dV,load:"currentOnly",nonExplicitSupportedLngs:!1,interpolation:{escapeValue:!1},returnNull:!1,returnEmptyString:!1}}const hV="kb-dashboard-language";uu.use(BS).use(US((e,n)=>aV(Object.assign({"../locales/en/app.json":()=>ln(()=>import("./app-CVg6W-HU.js"),[]),"../locales/en/common.json":()=>ln(()=>import("./common-CN9QPI2d.js"),[]),"../locales/en/errors.json":()=>ln(()=>import("./errors-BPsCufin.js"),[]),"../locales/es/app.json":()=>ln(()=>import("./app-DhHgtB9j.js"),[]),"../locales/es/common.json":()=>ln(()=>import("./common-BRyX4VxB.js"),[]),"../locales/es/errors.json":()=>ln(()=>import("./errors-07IrmOYM.js"),[]),"../locales/fr/app.json":()=>ln(()=>import("./app-DNh04p5I.js"),[]),"../locales/fr/common.json":()=>ln(()=>import("./common-DFDqu_n0.js"),[]),"../locales/fr/errors.json":()=>ln(()=>import("./errors-CcVDgqlA.js"),[]),"../locales/ko/app.json":()=>ln(()=>import("./app-CY3pQXOr.js"),[]),"../locales/ko/common.json":()=>ln(()=>import("./common-X6PzBnVA.js"),[]),"../locales/ko/errors.json":()=>ln(()=>import("./errors-DOF5Td3F.js"),[]),"../locales/zh-CN/app.json":()=>ln(()=>import("./app-CTRT_hQh.js"),[]),"../locales/zh-CN/common.json":()=>ln(()=>import("./common-DgWWKG8Z.js"),[]),"../locales/zh-CN/errors.json":()=>ln(()=>import("./errors-D-i_Bxc6.js"),[]),"../locales/zh-TW/app.json":()=>ln(()=>import("./app-NL_hPGDS.js"),[]),"../locales/zh-TW/common.json":()=>ln(()=>import("./common-CNbjPELi.js"),[]),"../locales/zh-TW/errors.json":()=>ln(()=>import("./errors-DDdWAK-U.js"),[])}),`../locales/${e}/${n}.json`,4))).use(HS);const pV=uu.init({...mV(),ns:[...cV],defaultNS:lV,detection:{order:["localStorage","navigator","htmlTag"],lookupLocalStorage:hV,caches:[],convertDetectedLanguage:e=>uV(e)??e},react:{useSuspense:!1}});uu.on("languageChanged",e=>{typeof document<"u"&&(document.documentElement.lang=e)});const cS="kb-dashboard-theme-mode",dS="kb-dashboard-color-theme",uS="kb-dashboard-font-scale-pct",wp=100,fV=85,gV=125,mS=[...K_],Yy="theme-data",Hl="theme-data.css";function bV(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${Hl}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${Hl}`:e.replace(/\/[^/]+$/,`/${Hl}`):`/${Hl}`:`/${Hl}`}const qi=typeof window<"u",vV=qi?a.useLayoutEffect:a.useEffect;function hS(e){return e==="dark"||e==="light"||e==="system"}function Xy(){if(!qi)return"dark";try{const e=localStorage.getItem(cS);if(hS(e))return e}catch{}return"dark"}function Qy(){if(!qi)return"default";try{const e=localStorage.getItem(dS);if(e&&mS.includes(e))return e}catch{}return"default"}function Zy(e){if(qi)try{localStorage.setItem(cS,e)}catch{}}function ek(e){if(qi)try{localStorage.setItem(dS,e)}catch{}}function pc(e){return typeof e!="number"||!Number.isFinite(e)?wp:Math.min(gV,Math.max(fV,Math.round(e)))}function tk(){if(!qi)return wp;try{const e=Number(localStorage.getItem(uS));return pc(e)}catch{return wp}}function nk(e){if(qi)try{localStorage.setItem(uS,String(pc(e)))}catch{}}function xV(e,n){return e==="system"?n?"dark":"light":e}function yV(e,n,s,i){if(!qi)return;const r=xV(e,i);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${pc(s)}%`}function sk(){if(!qi)return;const e=bV(),n=document.getElementById(Yy);if(n){n.href!==e&&(n.href=e);return}const s=document.createElement("link");s.rel="stylesheet",s.href=e,s.id=Yy,document.head.appendChild(s)}function kV(){const[e,n]=a.useState(()=>Xy()),[s,i]=a.useState(()=>Qy()),[r,o]=a.useState(()=>tk()),[l,d]=a.useState(!0),[c,m]=a.useState(()=>qi?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),p=a.useRef(e),h=a.useRef(s),u=a.useRef(r),f=a.useRef(!1),b=a.useRef(!1),y=a.useRef(!1);a.useEffect(()=>{p.current=e},[e]),a.useEffect(()=>{h.current=s},[s]),a.useEffect(()=>{u.current=r},[r]),a.useEffect(()=>{if(!qi||!l)return;let w=!1;return Ja().then(g=>{if(!w&&(hS(g.themeMode)&&!f.current&&(p.current!==g.themeMode&&(p.current=g.themeMode,n(g.themeMode)),Xy()!==g.themeMode&&Zy(g.themeMode)),g.colorTheme&&mS.includes(g.colorTheme)&&!b.current&&(h.current!==g.colorTheme&&(h.current=g.colorTheme,i(g.colorTheme)),Qy()!==g.colorTheme&&ek(g.colorTheme)),!y.current)){const j=pc(g.dashboardFontScalePct);u.current!==j&&(u.current=j,o(j)),tk()!==j&&nk(j)}}).catch(g=>{console.warn("[useTheme] Failed to hydrate theme from global settings",g)}).finally(()=>{w||d(!1)}),()=>{w=!0}},[l]),a.useEffect(()=>{if(!qi)return;const w=window.matchMedia("(prefers-color-scheme: dark)"),g=j=>{m(j.matches)};return w.addEventListener("change",g),()=>w.removeEventListener("change",g)},[]),vV(()=>{yV(e,s,r,c)},[e,s,r,c]),a.useEffect(()=>{!qi||l||s!=="default"&&sk()},[s,l]);const v=a.useCallback(w=>{f.current=!0,p.current=w,n(w),Zy(w),Ms({themeMode:w}).catch(g=>{console.warn("[useTheme] Failed to persist themeMode to global settings",g)})},[]),x=a.useCallback(w=>{b.current=!0,h.current=w,i(w),ek(w),w!=="default"&&sk(),Ms({colorTheme:w}).catch(g=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",g)})},[]),k=a.useCallback(w=>{const g=pc(w);y.current=!0,u.current=g,o(g),nk(g),Ms({dashboardFontScalePct:g}).catch(j=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",j)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:x,setDashboardFontScalePct:k,isSystemDark:c}}function wV(e){const{t:n}=st("app"),{planningSessions:s}=e,[i,r]=a.useState(!1),[o,l]=a.useState(!1),[d,c]=a.useState(null),[m,p]=a.useState(void 0),[h,u]=a.useState(!1),[f,b]=a.useState(null),[y,v]=a.useState(void 0),[x,k]=a.useState(null),[w,g]=a.useState("definition"),[j,S]=a.useState(null),[C,E]=a.useState(null),[F,M]=a.useState(!1),[D,_]=a.useState(void 0),[V,N]=a.useState(!1),[$,R]=a.useState(!1),[L,O]=a.useState(!1),[J,A]=a.useState(null),[de,B]=a.useState(!1),[P,Z]=a.useState(!1),[T,ie]=a.useState(void 0),[le,be]=a.useState(!1),[Le,xe]=a.useState(!1),[q,ce]=a.useState("project"),[De,He]=a.useState(null),[qe,pe]=a.useState(!1),[te,me]=a.useState(!1),[se,z]=a.useState(!1),[Y,he]=a.useState(void 0),[X,ye]=a.useState(void 0),[ot,ue]=a.useState(void 0),[je,$e]=a.useState(!1),[Ce,We]=a.useState(!1),[ke,Ee]=a.useState(!1),[Ze,Ke]=a.useState(!1),dt=!!(x||C||F||i||o||h||P||le||Le||qe||te||se||Ce||je||L||de||V||$||ke||Ze),Fe=a.useCallback(()=>r(!0),[]),nt=a.useCallback(()=>r(!1),[]),Nt=a.useCallback(()=>l(!0),[]),Ft=a.useCallback(At=>{c(At),l(!0)},[]),ze=a.useCallback(()=>{const At=s[0];At&&(p(At.id),l(!0))},[s]),it=a.useCallback(At=>{p(At),l(!0)},[]),Mt=a.useCallback(()=>{l(!1),c(null),p(void 0)},[]),Ht=a.useCallback(At=>{b(At),u(!0)},[]),Me=a.useCallback(At=>{v(At),u(!0)},[]),Ae=a.useCallback(()=>{u(!1),b(null),v(void 0)},[]),ee=a.useCallback((At,an="definition",Wn)=>{k(At),g(an),S(Wn?.origin??null)},[]),Ie=a.useCallback(At=>{k(At),g("changes"),S(null)},[]),Pe=a.useCallback(At=>{k(an=>!an||At.id!==void 0&&At.id!==an.id?an:{...an,...At})},[]),oe=a.useCallback(()=>{k(null),S(null)},[]),re=a.useCallback(At=>{E(At)},[]),_e=a.useCallback(()=>{E(null)},[]),fe=a.useCallback(At=>{_(At),M(!0)},[]),Xe=a.useCallback(()=>{M(!1),_(void 0)},[]),kt=a.useCallback(()=>N(!0),[]),Rt=a.useCallback(()=>N(!1),[]),Vt=a.useCallback(()=>R(!0),[]),Pt=a.useCallback(()=>R(!1),[]),bt=a.useCallback(At=>{A(At??null),O(!0)},[]),pt=a.useCallback(()=>{O(!1),A(null)},[]),ft=a.useCallback(()=>B(!0),[]),_t=a.useCallback(()=>B(!1),[]),Yt=a.useCallback(()=>{Z(At=>!At)},[]),on=a.useCallback(()=>{Z(!1),ie(void 0)},[]),An=a.useCallback((At,an)=>{typeof At=="string"&&At&&ce(At),He(typeof an=="string"||an===null?an:null),be(!0)},[]),vn=a.useCallback(()=>{be(!1),He(null)},[]),Qt=a.useCallback(()=>xe(!0),[]),sn=a.useCallback(()=>xe(!1),[]),mn=a.useCallback(At=>{typeof At=="string"&&At&&ce(At)},[]),Kt=a.useCallback(()=>pe(!0),[]),fn=a.useCallback(()=>pe(!1),[]),$n=a.useCallback(()=>me(!0),[]),On=a.useCallback(()=>me(!1),[]),xn=a.useCallback((At,an)=>{const Wn=At==="settings",Xn=At==="create";he(Wn?"settings":void 0),ye(Xn?"create":void 0),ue(!Wn&&!Xn?an:void 0),z(!0)},[]),Vn=a.useCallback(()=>{z(!1),he(void 0),ye(void 0),ue(void 0)},[]),Rn=a.useCallback(()=>$e(!0),[]),Pn=a.useCallback(()=>$e(!1),[]),zn=a.useCallback(()=>We(!0),[]),Nn=a.useCallback(()=>We(!1),[]),dn=a.useCallback(async(At,an)=>{We(!1),ie(an),Z(!0)},[]),Tt=a.useCallback(()=>Ee(!0),[]),Yn=a.useCallback(()=>Ee(!1),[]),cn=a.useCallback(()=>Ke(!0),[]),Bn=a.useCallback(()=>Ke(!1),[]),kn=a.useCallback((At,an)=>{an(n("modalManager.createdFromPlanning","Created {{id}} from planning mode",{id:At.id}),"success"),l(!1),c(null)},[n]),pn=a.useCallback((At,an)=>{const Wn=At.map(Xn=>Xn.id).join(", ");an(n("modalManager.createdMultipleFromPlanning","Created {{ids}} from planning mode",{ids:Wn}),"success"),l(!1),c(null)},[n]),un=a.useCallback((At,an)=>{const Wn=At.map(Xn=>Xn.id).join(", ");an(n("modalManager.createdFromSubtask","Created {{ids}} from subtask breakdown",{ids:Wn}),"success"),u(!1),b(null)},[n]);return{newTaskModalOpen:i,isPlanningOpen:o,planningInitialPlan:d,planningResumeSessionId:m,isSubtaskOpen:h,subtaskInitialDescription:f,subtaskResumeSessionId:y,detailTask:x,detailTaskInitialTab:w,detailTaskOrigin:j,groupModalGroupId:C,settingsOpen:F,settingsInitialSection:D,schedulesOpen:V,githubImportOpen:$,usageOpen:L,usageAnchorRect:J,systemStatsOpen:de,terminalOpen:P,terminalInitialCommand:T,filesOpen:le,todosOpen:Le,fileBrowserWorkspace:q,fileBrowserInitialFile:De,activityLogOpen:qe,gitManagerOpen:te,workflowEditorOpen:se,workflowEditorInitialPanel:Y,workflowEditorInitialAction:X,workflowEditorInitialWorkflowId:ot,agentsOpen:je,scriptsOpen:Ce,setupWizardOpen:ke,modelOnboardingOpen:Ze,anyModalOpen:dt,openNewTask:Fe,closeNewTask:nt,openPlanning:Nt,openPlanningWithInitialPlan:Ft,resumePlanning:ze,openPlanningWithSession:it,closePlanning:Mt,openSubtaskBreakdown:Ht,openSubtaskWithSession:Me,closeSubtask:Ae,openDetailTask:ee,openDetailWithChangesTab:Ie,updateDetailTask:Pe,closeDetailTask:oe,openGroupModal:re,closeGroupModal:_e,openSettings:fe,closeSettings:Xe,openSchedules:kt,closeSchedules:Rt,openGitHubImport:Vt,closeGitHubImport:Pt,openUsage:bt,closeUsage:pt,openSystemStats:ft,closeSystemStats:_t,toggleTerminal:Yt,closeTerminal:on,openFiles:An,closeFiles:vn,openTodos:Qt,closeTodos:sn,setFileWorkspace:mn,openActivityLog:Kt,closeActivityLog:fn,openGitManager:$n,closeGitManager:On,openWorkflowEditor:xn,closeWorkflowEditor:Vn,openAgents:Rn,closeAgents:Pn,openScripts:zn,closeScripts:Nn,runScript:dn,openSetupWizard:Tt,closeSetupWizard:Yn,openModelOnboarding:cn,closeModelOnboarding:Bn,onPlanningTaskCreated:kn,onPlanningTasksCreated:pn,onSubtaskTasksCreated:un}}function jV(e){const{t:n}=st("app"),{projectId:s,projects:i,projectsLoading:r,currentProject:o,setCurrentProject:l,addToast:d,openTaskDetail:c,closeTaskDetail:m}=e,p=a.useRef(!1),h=a.useRef(!1),u=a.useRef(null),f=a.useRef(null),b=a.useRef(null);return a.useEffect(()=>{if(!h.current){const g=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(g){const j=g[1];if(/^[A-Z]+-\d+$/.test(j)){const S=new URLSearchParams(window.location.search);S.set("task",j);const C=S.toString(),E=window.history.state??{};window.history.replaceState(E,"",C?`/?${C}`:"/"),h.current=!0}}}const v=new URLSearchParams(window.location.search),x=v.get("project"),k=v.get("task");if(r)return;let w=s;if(x){const g=i.find(j=>j.id===x);if(!g){f.current!==x&&(d(n("deepLink.projectNotFound","Project '{{id}}' not found",{id:x}),"error"),f.current=x);return}f.current=null,w=g.id,o?.id!==g.id&&b.current!==g.id&&(l(g),b.current=g.id)}else f.current=null,b.current=null;k&&(p.current||(p.current=!0,pr(k,w).then(g=>{c(g),u.current=k}).catch(()=>{d(n("deepLink.taskNotFound","Task {{id}} not found",{id:k}),"error")})))},[s,i,r,o,l,d,c]),{handleDetailClose:a.useCallback(()=>{if(u.current){const v=new URLSearchParams(window.location.search);v.delete("task");const x=v.toString(),k=window.history.state??{};window.history.replaceState(k,"",x?`${window.location.pathname}?${x}`:window.location.pathname),u.current=null}m()},[m])}}function NV({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,d=!1;Yo().then(({providers:c})=>{const m=c.some(h=>h.authenticated);if(c.length>0&&!m||c.length>0&&m)return Ja().then(h=>{const u=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!m||!u)&&!ol()?l=!0:!m&&!ol()&&(d=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(Zi("onboarding:auto-triggered",{trigger:"first-run"}),s()):d&&(Zi("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}function SV({isMobile:e,keyboardOpen:n,anyModalOpen:s,isIOS:i}){const r=e&&n&&!s&&i,o=e&&n;return{footerHidden:r,navKeyboardOpen:o,footerKeyboardOpen:o&&i}}const ik="kb-update-banner-dismissed";function CV(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,d]=a.useState(null),[c,m]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(ik)==="true";m(h);let u=!1;return IE().then(f=>{u||f.disabled||(i(f.updateAvailable===!0),o(typeof f.latestVersion=="string"?f.latestVersion:null),d(typeof f.currentVersion=="string"?f.currentVersion:null))}).catch(()=>{}).finally(()=>{u||n(!1)}),()=>{u=!0}},[]);const p=a.useCallback(()=>{m(!0),sessionStorage.setItem(ik,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:c,dismiss:p}}const _V=["board","list","graph","agents","missions","chat","documents","research","evals","goalsView","skills","mailbox","insights","memory","reliability","secrets","devserver","dev-server","stash-recovery","pull-requests"];function EV(e){return e!==null&&_V.includes(e)}function fh(e){return e!==null&&(EV(e)||Fo(e))}const MV=Cc("fusion-plugin-roadmap","roadmaps");function ak(e){return e==="devserver"?"dev-server":e}function rk(e){return e!=="roadmaps"?"board":pw("fusion-plugin-roadmap","roadmaps")?MV:"board"}function AV(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:d,themeMode:c,setThemeMode:m}=e,[p,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[u,f]=a.useState(()=>{const x=cs("kb-dashboard-task-view");return x==="roadmaps"?rk(x):fh(x)?x:"board"}),b=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",p)},[p]),a.useEffect(()=>{const x=cs("kb-dashboard-task-view",r?.id);if(x==="roadmaps")f(rk(x));else if(fh(x)){const k=!b.current&&x==="devserver";f(k?"devserver":ak(x))}else f("board");r?.id&&(b.current=!0)},[r?.id]),a.useEffect(()=>{_s("kb-dashboard-task-view",u,r?.id)},[r?.id,u]),a.useEffect(()=>{if(typeof window>"u")return;const x=new URLSearchParams(window.location.search).get("view");x&&fh(x)&&f(ak(x))},[]),a.useEffect(()=>{n||i||r&&p==="overview"&&h("project")},[n,i,r,p]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const x=window.setTimeout(()=>{d()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,d]);const y=a.useCallback(x=>{f(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],k=x.indexOf(c),w=x[(k+1)%x.length];m(w)},[c,m]);return{viewMode:p,setViewMode:h,taskView:u,setTaskView:f,handleChangeTaskView:y,handleToggleTheme:v}}const gh=new Map,TV=6e4;function RV(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),[d,c]=a.useState(0),m=a.useRef(!1),p=a.useCallback(()=>{const h=e??"default";gh.delete(h),c(u=>u+1)},[e]);return a.useEffect(()=>{const h=e??"default";let u=!1;async function f(){const b=gh.get(h);if(b&&Date.now()<b.expiresAt){if(u)return;s(b.views),r(!1);return}m.current||r(!0),l(null);try{const y=await RR(e);if(u)return;gh.set(h,{views:y,expiresAt:Date.now()+TV}),s(y)}catch(y){if(u)return;l(y instanceof Error?y.message:"Failed to fetch plugin dashboard views")}finally{u||(r(!1),m.current=!0)}}return f(),()=>{u=!0}},[e,d]),a.useMemo(()=>({views:n,loading:i,error:o,refetch:p}),[n,i,o,p])}function PV({taskView:e,context:n}){return t.jsx(kP,{viewId:e,context:n})}let ok=!1;function Xr(e,n){return function(){return a.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function IV(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",i=(await ln(()=>import("./dashboard-view-DOEa6gWS.js"),__vite__mapDeps([36,1,37,38,4,5,6,2,3,7,39])))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}async function DV(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",i=(await ln(()=>import("./dashboard-view-DlKsVySD.js"),__vite__mapDeps([40,1,41,38,42])))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}async function LV(){const e="@fusion-plugin-examples/compound-engineering/dashboard-view",n="CompoundEngineeringDashboardView",i=(await ln(()=>import("./dashboard-view-O5j3PSGY.js"),__vite__mapDeps([43,1,38,41,37,44])))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}async function FV(){const e="@fusion-plugin-examples/cli-printing-press/dashboard-view",n="CliPrintingPressWizardView";try{const i=(await import(e))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}catch{return{default:Xr(e,n)}}}async function OV(){const e="@fusion-plugin-examples/cli-printing-press/manage-view",n="CliPrintingPressManageView";try{const i=(await import(e))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}catch{return{default:Xr(e,n)}}}function pS(){ok||(ok=!0,Nl("fusion-plugin-dependency-graph","graph",a.lazy(IV)),Nl("fusion-plugin-roadmap","roadmaps",a.lazy(DV)),Nl("fusion-plugin-compound-engineering","compound-engineering",a.lazy(LV)),Nl("fusion-plugin-cli-printing-press","wizard",a.lazy(FV)),Nl("fusion-plugin-cli-printing-press","manage",a.lazy(OV)))}function $V(e){const{t:n}=st("app"),{setCurrentProject:s,clearCurrentProject:i,setViewMode:r,currentProject:o,refreshProjects:l,toggleFavoriteProvider:d,toggleFavoriteModel:c,addToast:m,openSettings:p,openSetupWizard:h,closeSetupWizard:u,closeModelOnboarding:f}=e,b=a.useCallback(F=>{s(F),r("project")},[s,r]),y=a.useCallback(()=>{i(),r("overview")},[i,r]),v=a.useCallback(()=>{p()},[p]),x=a.useCallback(()=>{h()},[h]),k=a.useCallback(F=>{u(),s(F),r("project"),m(n("projects.setup.success","Project {{name}} registered successfully",{name:F.name}),"success"),l()},[u,s,r,m,l,n]),w=a.useCallback(()=>{f()},[f]),g=a.useCallback(async F=>{try{await hT(F.id),m(n("projects.actions.pauseSuccess","Project {{name}} paused",{name:F.name}),"success"),await l()}catch{m(n("projects.actions.pauseError","Failed to pause project {{name}}",{name:F.name}),"error")}},[m,l,n]),j=a.useCallback(async F=>{try{await pT(F.id),m(n("projects.actions.resumeSuccess","Project {{name}} resumed",{name:F.name}),"success"),await l()}catch{m(n("projects.actions.resumeError","Failed to resume project {{name}}",{name:F.name}),"error")}},[m,l,n]),S=a.useCallback(async F=>{try{await iw(F.id),m(n("projects.actions.removeSuccess","Project {{name}} removed",{name:F.name}),"success"),o?.id===F.id&&(i(),r("overview")),await l()}catch{m(n("projects.actions.removeError","Failed to remove project {{name}}",{name:F.name}),"error")}},[o,i,r,m,l,n]),C=a.useCallback(async F=>{try{await d(F)}catch{m(n("projects.actions.favoritesError","Failed to update favorites"),"error")}},[d,m,n]),E=a.useCallback(async F=>{try{await c(F)}catch{m(n("projects.actions.modelFavoritesError","Failed to update model favorites"),"error")}},[c,m,n]);return{handleSelectProject:b,handleViewAllProjects:y,handleOpenSettings:v,handleAddProject:x,handleSetupComplete:k,handleModelOnboardingComplete:w,handlePauseProject:g,handleResumeProject:j,handleRemoveProject:S,handleToggleFavorite:C,handleToggleModelFavorite:E}}function zV(e){const{t:n}=st("app"),{createTask:s,ingestCreatedTasks:i,onPlanningTaskCreated:r,onPlanningTasksCreated:o,onSubtaskTasksCreated:l,addToast:d}=e,c=a.useCallback(async b=>s({...b,column:b.column??"triage",source:{sourceType:"dashboard_ui"}}),[s]),m=a.useCallback(async b=>await s({...b,column:"triage",source:{sourceType:"dashboard_ui"}}),[s]),p=a.useCallback(b=>{i([b]),r(b,d)},[d,i,r]),h=a.useCallback(b=>{i(b),o(b,d)},[d,i,o]),u=a.useCallback(b=>{i(b),l(b,d)},[d,i,l]),f=a.useCallback(b=>{d(n("taskHandlers.githubImported","Imported {{id}} from GitHub",{id:b.id}),"success")},[d,n]);return{handleBoardQuickCreate:c,handleModalCreate:m,handlePlanningTaskCreated:p,handlePlanningTasksCreated:h,handleSubtaskTasksCreated:u,handleGitHubImport:f}}function BV(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,d]=a.useState([]),[c,m]=a.useState(null),[p,h]=a.useState(!1),[u,f]=a.useState(null),b=a.useRef(null),y=a.useCallback(async()=>{if(!e){o([]),d([]),m(null),h(!1),f(null);return}b.current?.abort();const x=new AbortController;b.current=x,h(!0),f(null);try{const k=[KR(e),JR(e)];s&&(k.push(YR(e,s,i)),k.push(XR(e,s)));const w=await Promise.allSettled(k);if(x.signal.aborted)return;const g=w[0],j=w[1];if(g.status==="rejected"){f(`Failed to fetch node health: ${g.reason}`),h(!1);return}if(m(g.value),j.status==="rejected"){f(`Failed to fetch projects: ${j.reason}`),h(!1);return}if(o(j.value),s&&w[2]){const S=w[2];if(S.status==="rejected"){f(`Failed to fetch tasks: ${S.reason}`),h(!1);return}S.status==="fulfilled"&&d(S.value)}h(!1)}catch(k){x.signal.aborted||(f(k instanceof Error?k.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(y(),()=>{b.current?.abort()}),[y]);const v=a.useCallback(()=>{y()},[y]);return{projects:r,tasks:l,health:c,loading:p,error:u,refresh:v}}function UV(e){const[n,s]=a.useState(!1),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return li(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:i}}const HV="fusion-dashboard-current-node",fS=a.createContext(null);function VV({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let p=!1;async function h(){try{const u=await Ja();if(p)return;l.current=u.dashboardCurrentNodeId;const f=u.dashboardCurrentNodeId;if(f&&(o.current=!0),!f)try{const b=localStorage.getItem(HV);if(b){const y=JSON.parse(b);y?.id&&y?.type==="remote"&&(l.current=y.id,await Ms({dashboardCurrentNodeId:y.id}).catch(()=>{}))}}catch{}}catch{}finally{p||r(!1)}}return h(),()=>{p=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const p=n.id;l.current!==p&&(l.current=p,Ms({dashboardCurrentNodeId:p}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Ms({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const d=a.useCallback(p=>{s(p)},[]),c=a.useCallback(()=>{s(null),l.current=void 0,Ms({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),m={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:d,clearCurrentNode:c};return t.jsx(fS.Provider,{value:m,children:e})}function qV(){const e=a.useContext(fS);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const WV=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],GV=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let du=null,lk=!1;function KV(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 JV(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 gS(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 YV(e){return e==="local"||e==="remote"?e:void 0}function bS(e){const n=YV(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,i=JV(e.serverUrl),r=KV(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...i?{serverUrl:i}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function XV(e){for(const n of GV){const s=e[n];if(!s||typeof s!="object")continue;const i=s,r=gS(i.kind??i.shellKind??i.hostKind);if(r)return r==="browser"?{kind:r}:bS({kind:r,mode:i.mode??i.shellMode,connectionId:i.connectionId??i.profileId,serverUrl:i.serverUrl??i.serverBaseUrl,canOpenConnectionManager:i.canOpenConnectionManager??i.shellCanOpenConnectionManager})}return null}function QV(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,i=gS(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return i?i==="browser"?{kind:i}:bS({kind:i,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 ZV(e){try{const n=new URL(e.location.href);let s=!1;for(const r of WV)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const i=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",i)}catch{}}function e7(e=window){const n=XV(e);if(n)return n;const s=QV(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function vS(e=window){return!lk&&typeof window<"u"&&(du=e7(e),ZV(e),lk=!0),du??{kind:"browser"}}function t7(){return du||(typeof window>"u"?{kind:"browser"}:vS(window))}const n7={kind:"browser"},xS=a.createContext({host:n7,isNativeShell:!1,kind:"browser"});function s7(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 i7({children:e}){const n=a.useMemo(()=>s7(t7()),[]);return t.jsx(xS.Provider,{value:n,children:e})}function a7(){return a.useContext(xS)}function r7(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function o7({open:e,shellApi:n,shellState:s,onComplete:i}){const{t:r}=st("app"),[o,l]=a.useState(s.desktopMode??"remote"),[d,c]=a.useState(r("onboarding.defaultName","Remote Server")),[m,p]=a.useState(""),[h,u]=a.useState(""),[f,b]=a.useState(null),[y,v]=a.useState(!1),[x,k]=a.useState(!1),w=s.host==="desktop-shell";a.useEffect(()=>{w&&l(s.desktopMode??"remote")},[w,s.desktopMode]);const g=a.useMemo(()=>w&&o==="local"?!0:m.trim().length>0,[w,o,m]);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:r("onboarding.welcome","Welcome to Fusion")})}),t.jsxs("div",{className:"native-shell-onboarding-body",children:[t.jsx("p",{children:r("onboarding.description","Fusion helps you plan, run, and review AI-assisted engineering work.")}),w&&t.jsxs("div",{className:"native-shell-onboarding-mode-row",children:[t.jsx("button",{type:"button",className:`btn ${o==="local"?"btn-primary":""}`,onClick:()=>l("local"),children:r("onboarding.localFusion","Local Fusion")}),t.jsx("button",{type:"button",className:`btn ${o==="remote"?"btn-primary":""}`,onClick:()=>l("remote"),children:r("onboarding.remoteServer","Remote Server")})]}),(!w||o==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{b(null),v(!0);try{const j=await n.startQrScan();p(j.serverUrl),u(j.authToken??"")}catch(j){b(j.message)}finally{v(!1)}},disabled:y,children:y?r("onboarding.scanning","Scanning…"):r("onboarding.scanQr","Scan QR")}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:r("onboarding.profileName","Profile name")}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:d,onChange:j=>c(j.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:r("onboarding.serverUrl","Server URL")}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:m,onChange:j=>p(j.target.value),placeholder:r("onboarding.serverUrlPlaceholder","https://your-fusion-host")}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:r("onboarding.authToken","Auth token (optional)")}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:h,onChange:j=>u(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:!g||x,onClick:async()=>{b(null),k(!0);try{if(w&&o==="local"){await n.setDesktopMode("local"),i();return}const j=await n.saveProfile({name:d.trim()||r("onboarding.defaultName","Remote Server"),serverUrl:m,authToken:h||null});if(w&&await n.setDesktopMode("remote"),await n.setActiveProfile(j.id),typeof window<"u"&&s.host!=="web"){window.location.href=r7(j.serverUrl,j.authToken??null);return}i()}catch(j){b(j.message)}finally{k(!1)}},children:x?r("onboarding.saving","Saving…"):r("onboarding.continue","Continue")})})]})}):null}function l7({open:e,shellApi:n,shellState:s,onClose:i}){const{t:r}=st("app"),o=a.useMemo(()=>s.profiles.find(C=>C.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[l,d]=a.useState(null),[c,m]=a.useState({}),[p,h]=a.useState(null),[u,f]=a.useState(null);if(!e)return null;const b=l==="__new__",y=b?null:s.profiles.find(C=>C.id===l)??o,v=c.name??y?.name??"",x=c.serverUrl??y?.serverUrl??"",k=c.authToken??y?.authToken??"",w=()=>{d(null),m({}),f(null)},g=async()=>{f(null);try{const C=new URL(x.trim());if(!/^https?:$/.test(C.protocol))throw new Error(r("shell.serverUrlProtocolError","Server URL must use http or https"));const E=await n.saveProfile({id:b?void 0:l??y?.id,name:v||r("shell.defaultProfileName","Remote Server"),serverUrl:x,authToken:k||null});await n.setActiveProfile(E.id),d(E.id),m({})}catch(C){f(C.message)}},j=async()=>{f(null);try{const C=await n.startQrScan();d("__new__"),m({name:"",serverUrl:C.serverUrl,authToken:C.authToken??""})}catch(C){f(C.message)}},S=async()=>{p&&(await n.deleteProfile(p.id),h(null),w())};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":r("shell.connectionManagerLabel","Connection Manager"),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:r("shell.connectionManager","Connection Manager")}),t.jsx("button",{type:"button",className:"modal-close",onClick:i,"aria-label":r("actions.close","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:r("shell.modeLocal","Local")}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:r("shell.modeRemote","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:r("shell.noServersSaved","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:()=>{d("__new__"),m({name:"",serverUrl:"",authToken:""}),f(null)},children:r("shell.addServer","Add server")}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void j(),children:r("shell.scanQr","Scan QR")})]})]}):s.profiles.map(C=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:C.name}),t.jsx("div",{className:"settings-muted",children:C.serverUrl}),C.id===s.activeProfileId&&t.jsx("span",{className:"native-shell-connection-manager__active-pill",children:r("shell.activePill","Active")})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":r("shell.editProfile","Edit {{name}}",{name:C.name}),onClick:()=>{d(C.id),m(C)},children:r("actions.edit","Edit")}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":r("shell.useProfile","Use {{name}}",{name:C.name}),onClick:()=>void n.setActiveProfile(C.id),children:r("shell.use","Use")}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":r("shell.deleteProfile","Delete {{name}}",{name:C.name}),onClick:()=>h(C),children:r("actions.delete","Delete")})]})]},C.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{d("__new__"),m({name:"",serverUrl:"",authToken:""}),f(null)},children:r("shell.addConnection","Add connection")}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void j(),children:r("shell.scanQr","Scan QR")})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:r("shell.nameLabel","Name")}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:v,onChange:C=>m(E=>({...E,name:C.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-url",children:r("shell.serverUrlLabel","Server URL")}),t.jsx("input",{id:"native-shell-connection-manager-url",className:"input",value:x,onChange:C=>m(E=>({...E,serverUrl:C.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-token",children:r("shell.authTokenLabel","Auth token (optional)")}),t.jsx("input",{id:"native-shell-connection-manager-token",className:"input",type:"password",value:k??"",onChange:C=>m(E=>({...E,authToken:C.target.value}))}),u&&t.jsx("p",{className:"form-error",role:"alert",children:u})]}),p&&t.jsxs("div",{className:"native-shell-connection-manager__delete-confirm",role:"alertdialog","aria-label":r("shell.deleteConfirmLabel","Delete server confirmation"),children:[t.jsx("p",{children:r("shell.deleteConfirmMessage","Delete {{name}}? This removes the saved profile.",{name:p.name})}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>h(null),children:r("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void S(),children:r("actions.delete","Delete")})]})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:i,children:r("actions.close","Close")}),t.jsx("button",{type:"button",className:"btn",onClick:w,children:r("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void g(),disabled:!x.trim(),children:r("actions.save","Save")})]})]})})}function c7(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,i=n&&s?`${n} · ${s}`:n??s;return e.mode==="remote"?{title:i??"Connection info unavailable",actionLabel:e.hostKind==="desktop-shell"?"Switch server":"Manage connections",dotClassName:i?"status-dot status-dot--online":"status-dot status-dot--pending"}:{title:i??"Connection info unavailable",actionLabel:"Manage connections",dotClassName:i?"status-dot status-dot--online":"status-dot status-dot--pending"}}function ck({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=c7(e),i=a.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 i(),"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 d7(e){if(e)try{return new URL(e).origin}catch{return}}function u7(e,n){const s=e.profiles.find(i=>i.id===e.activeProfileId)??null;return s||(n.kind==="browser"||!n.connectionId?null:e.profiles.find(i=>i.id===n.connectionId)??null)}async function m7(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function h7(e,n=window){const s=n.fusionAPI,i=n.fusionShell,r=await m7(i),o=r?u7(r,e):null,l=e.kind==="browser"?void 0:e.mode??r?.desktopMode,d=o?.id??(e.kind==="browser"?void 0:e.connectionId),c=o?.name,m=d7(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),p=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",h=e.kind==="mobile-shell"&&typeof i?.openConnectionManager=="function",u=p||h;return{hostKind:e.kind,available:u,...l?{mode:l}:{},...d?{profileId:d}:{},...c?{profileLabel:c}:{},...m?{serverOrigin:m}:{},openConnectionManager:async()=>{try{return p?(await s.openConnectionManager?.(),{ok:!0}):h?(await i.openConnectionManager(),{ok:!0}):{ok:!1,reason:"unsupported"}}catch(f){return{ok:!1,reason:"failed",error:f instanceof Error?f.message:String(f)}}}}}function p7({open:e}){const{t:n}=st("app"),[s,i]=a.useState(""),r=a.useRef(null);a.useEffect(()=>{e&&r.current?.focus()},[e]);const o=a.useCallback(()=>{const d=s.trim();d&&(rE(d),window.location.reload())},[s]),l=a.useCallback(()=>{oE(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:d=>{d.key==="Escape"&&(d.preventDefault(),d.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:n("auth.tokenRequired","Authentication token required")})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:n("auth.tokenRecoveryDescription","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:n("auth.replacementToken","Replacement token")}),t.jsx("input",{ref:r,id:"auth-token-recovery-input",className:"input",type:"password",value:s,onChange:d=>i(d.target.value),placeholder:n("auth.pasteToken","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:l,children:n("auth.clearAndRetry","Clear token and retry")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:o,disabled:s.trim().length===0,children:n("auth.setAndReload","Set token and reload")})]})]})}):null}const f7=a.lazy(()=>ln(()=>import("./AgentsView-COx3draV.js"),__vite__mapDeps([45,1,4,10,11,34,22,5,6,2,3,7,46])).then(e=>({default:e.AgentsView}))),g7=a.lazy(()=>ln(()=>import("./DocumentsView-DmNB9rJZ.js"),__vite__mapDeps([47,1,4,5,6,2,3,7,48])).then(e=>({default:e.DocumentsView}))),b7=a.lazy(()=>ln(()=>import("./InsightsView-_-wd4BOJ.js"),__vite__mapDeps([49,1,4,29,5,6,2,3,7,50])).then(e=>({default:e.InsightsView}))),v7=a.lazy(()=>ln(()=>import("./ResearchView-C2Gx8jC9.js"),__vite__mapDeps([51,1,4,5,6,2,3,7,52])).then(e=>({default:e.ResearchView}))),x7=a.lazy(()=>ln(()=>import("./EvalsView-72w3_AO6.js"),__vite__mapDeps([53,1,4,5,6,2,3,7,54])).then(e=>({default:e.EvalsView}))),y7=a.lazy(()=>ln(()=>import("./NodesView-DTQP1j4H.js"),__vite__mapDeps([55,1,4,24,34,5,6,2,3,7,56])).then(e=>({default:e.NodesView}))),k7=a.lazy(()=>ln(()=>import("./ChatView-CrVSqQK_.js"),__vite__mapDeps([57,1,4,0,2,3,5,6,7,8,58])).then(e=>({default:e.ChatView}))),w7=a.lazy(()=>ln(()=>import("./SkillsView-BGyynaI4.js"),__vite__mapDeps([59,1,4,5,6,2,3,7,60])).then(e=>({default:e.SkillsView}))),j7=a.lazy(()=>ln(()=>import("./MemoryView-BOCIc8HT.js"),__vite__mapDeps([61,1,30,31,4,5,6,2,3,7,62])).then(e=>({default:e.MemoryView}))),N7=a.lazy(()=>ln(()=>import("./SecretsView-Db2HAGi2.js"),__vite__mapDeps([27,1,4,5,6,2,3,7,28])).then(e=>({default:e.SecretsView}))),S7=a.lazy(()=>ln(()=>import("./ReliabilityView-B-i5SOoD.js"),__vite__mapDeps([63,1,4,5,6,2,3,7,64])).then(e=>({default:e.ReliabilityView}))),C7=a.lazy(()=>ln(()=>import("./DevServerView-DXQ1LX4H.js"),__vite__mapDeps([65,1,4,5,6,2,3,7,66])).then(e=>({default:e.DevServerView})));a.lazy(()=>ln(()=>import("./TodoView-Djjwcb49.js"),__vite__mapDeps([18,1,4,5,6,2,3,7,19])).then(e=>({default:e.TodoView})));const _7=a.lazy(()=>ln(()=>import("./GoalsView-DkEXO_mx.js"),__vite__mapDeps([67,1,4,5,6,2,3,7,68])).then(e=>({default:e.GoalsView}))),E7=a.lazy(()=>ln(()=>import("./StashRecoveryView-CFaU-hym.js"),__vite__mapDeps([69,1,4,5,6,2,3,7,70])).then(e=>({default:e.StashRecoveryView}))),M7=a.lazy(()=>ln(()=>import("./PullRequestView-Dk9a7jRZ.js"),__vite__mapDeps([71,1,4,5,6,2,3,7,72])).then(e=>({default:e.PullRequestView})));function A7(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{ln(()=>import("./AgentsView-COx3draV.js"),__vite__mapDeps([45,1,4,10,11,34,22,5,6,2,3,7,46])),ln(()=>import("./DocumentsView-DmNB9rJZ.js"),__vite__mapDeps([47,1,4,5,6,2,3,7,48])),ln(()=>import("./InsightsView-_-wd4BOJ.js"),__vite__mapDeps([49,1,4,29,5,6,2,3,7,50])),ln(()=>import("./ResearchView-C2Gx8jC9.js"),__vite__mapDeps([51,1,4,5,6,2,3,7,52])),ln(()=>import("./EvalsView-72w3_AO6.js"),__vite__mapDeps([53,1,4,5,6,2,3,7,54])),ln(()=>import("./NodesView-DTQP1j4H.js"),__vite__mapDeps([55,1,4,24,34,5,6,2,3,7,56])),ln(()=>import("./ChatView-CrVSqQK_.js"),__vite__mapDeps([57,1,4,0,2,3,5,6,7,8,58])),ln(()=>import("./SkillsView-BGyynaI4.js"),__vite__mapDeps([59,1,4,5,6,2,3,7,60])),ln(()=>import("./MemoryView-BOCIc8HT.js"),__vite__mapDeps([61,1,30,31,4,5,6,2,3,7,62])),ln(()=>import("./SecretsView-Db2HAGi2.js"),__vite__mapDeps([27,1,4,5,6,2,3,7,28])),ln(()=>import("./ReliabilityView-B-i5SOoD.js"),__vite__mapDeps([63,1,4,5,6,2,3,7,64])),ln(()=>import("./DevServerView-DXQ1LX4H.js"),__vite__mapDeps([65,1,4,5,6,2,3,7,66])),ln(()=>import("./TodoView-Djjwcb49.js"),__vite__mapDeps([18,1,4,5,6,2,3,7,19])),ln(()=>import("./GoalsView-DkEXO_mx.js"),__vite__mapDeps([67,1,4,5,6,2,3,7,68])),ln(()=>import("./StashRecoveryView-CFaU-hym.js"),__vite__mapDeps([69,1,4,5,6,2,3,7,70])),ln(()=>import("./PullRequestView-Dk9a7jRZ.js"),__vite__mapDeps([71,1,4,5,6,2,3,7,72]))})}pS();const bh="kb-setup-warning-dismissed",dk="kb-dashboard-working-branch-filter",uk="kb-dashboard-base-branch-filter",mk="__fusion:no-branch__",yS="fusion:approval-banner-dismissed",Ed="kb-capacity-risk-banner-dismissed",T7=.8;function R7(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function P7(e,n){return e==="done"&&n!==void 0&&n!=="done"}function hk(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function I7(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(yS);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[i,r]of Object.entries(n))typeof r=="number"&&Number.isFinite(r)&&s.set(i,r);return s}catch{return new Map}}function pk(e){if(!(typeof window>"u"))try{const n={};for(const[s,i]of e)n[s]=i;window.localStorage.setItem(yS,JSON.stringify(n))}catch{}}function D7(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function L7(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function F7(e,n){return e&&n===0}function O7(){const{t:e}=st("app"),{toasts:n,addToast:s,removeToast:i}=MN(),{shellApi:r,state:o,ready:l,openConnectionManagerSignal:d}=VN(),c=a7();a.useEffect(()=>{A7()},[]);const{projects:m,loading:p,error:h,refresh:u}=tV(),f=a.useRef(m.length>0),{nodes:b}=Nu();a.useEffect(()=>{m.length>0&&(f.current=!0)},[m.length]);const{currentNode:y,currentNodeId:v,isRemote:x,setCurrentNode:k,clearCurrentNode:w}=qV(),{currentProject:g,setCurrentProject:j,clearCurrentProject:S,loading:C}=iV(m,{nodeId:v}),{hasAiProvider:E,hasGithub:F,loading:M,hasWarnings:D}=zN(g?.id),{updateAvailable:_,latestVersion:V,currentVersion:N,dismissed:$,dismiss:R}=CV();a.useEffect(()=>{if(v&&!y&&b.length>0){const Ve=b.find(Bt=>Bt.id===v);if(Ve){k(Ve);return}}v&&b.length>0&&(b.some(Bt=>Bt.id===v)||w())},[v,y,b,k,w]);const[L,O]=a.useState(""),[J,A]=a.useState(""),[de,B]=a.useState("");a.useEffect(()=>{A(cs(dk,g?.id)??""),B(cs(uk,g?.id)??"")},[g?.id]);const P=a.useCallback(Ve=>{A(Ve),_s(dk,Ve,g?.id)},[g?.id]),Z=a.useCallback(Ve=>{B(Ve),_s(uk,Ve,g?.id)},[g?.id]),T=a.useCallback((Ve,Bt)=>{const wn=new URLSearchParams;g?.id&&wn.set("projectId",g.id);const Ns=wn.size>0?`?${wn.toString()}`:"";return li(`/api/events${Ns}`,{events:{"plugin:custom":Us=>{try{const bi=JSON.parse(Us.data);bi.pluginId===Ve&&typeof bi.event=="string"&&Bt({event:bi.event,payload:bi.payload})}catch{}}}})},[g?.id]),ie=BV(v,{projectId:g?.id,searchQuery:L||void 0});UV(v);const le=x&&ie.projects.length>0?ie.projects:m,{themeMode:be,colorTheme:Le,dashboardFontScalePct:xe,setThemeMode:q,setColorTheme:ce,setDashboardFontScalePct:De}=kV(),{sessions:He,generating:qe,needsInput:pe,planningSessions:te,dismissSession:me}=U9(g?.id),se=He.filter(Ve=>Ve.status==="awaiting_input"||Ve.status==="error"),z=J9(),Y=wV({projectId:g?.id,planningSessions:te}),X=Ji()==="mobile",{pushNav:ye,replaceCurrent:ot,removeNav:ue}=P6({enabled:!0}),{viewMode:je,setViewMode:$e,taskView:Ce,handleChangeTaskView:We}=AV({projectsLoading:p,projectsError:h,currentProjectLoading:C,currentProject:g,projectsLength:m.length,setupWizardOpen:Y.setupWizardOpen,openSetupWizard:Y.openSetupWizard,themeMode:be,setThemeMode:q}),{views:ke}=RV(g?.id),Ee=a.useMemo(()=>{const Ve=ke.find(Bt=>Bt.pluginId==="fusion-plugin-dependency-graph"&&Bt.view.viewId==="graph");return Ve?`plugin:${Ve.pluginId}:${Ve.view.viewId}`:pw("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[ke]),Ze=a.useCallback(Ve=>{Ve==="missions"&&(bn(void 0),ps(void 0),ht(void 0)),Ve!=="goalsView"&&ae(void 0);const Bt=Ce;We(Ve),Bt!==Ve&&ye({type:"view",revert:()=>We(Bt)})},[We,Ce,ye]),Ke=Ce==="board"||Ce==="list",{tasks:dt,isStale:Fe,createTask:nt,moveTask:Nt,pauseTask:Ft,unpauseTask:ze,deleteTask:it,mergeTask:Mt,retryTask:Ht,resetTask:Me,updateTask:Ae,duplicateTask:ee,archiveTask:Ie,unarchiveTask:Pe,archiveAllDone:oe,loadArchivedTasks:re,refreshTasks:_e,ingestCreatedTasks:fe,lastFetchTimeMs:Xe}=X9({...g?{projectId:g.id}:{},searchQuery:L||void 0,sseEnabled:Ke}),kt=a.useRef(Ce);a.useEffect(()=>{const Ve=kt.current;!(Ve==="board"||Ve==="list")&&(Ce==="board"||Ce==="list")&&_e(),kt.current=Ce},[Ce,_e]);const Rt=x&&ie.tasks.length>0?ie.tasks:dt,[Vt,Pt]=a.useState(0),bt=a.useRef(performance.now()),pt=a.useRef(!1),ft=a.useRef(!1),_t=a.useRef(!1),Yt=a.useMemo(()=>p?"projects":C?"project":"tasks",[p,C]);a.useEffect(()=>{if(!p&&!pt.current){pt.current=!0;const Ve=`projects loaded at ${Math.round(performance.now()-bt.current)}ms from mount`;console.log(`[App] ${Ve}`)}if(!C&&!ft.current){ft.current=!0;const Ve=`current-project resolved at ${Math.round(performance.now()-bt.current)}ms from mount`;console.log(`[App] ${Ve}`)}},[p,C]);const on=!p&&!C,An=F7(p,m.length);a.useEffect(()=>{if(!on||_t.current)return;_t.current=!0;const Ve=`dashboard ready at ${Math.round(performance.now()-bt.current)}ms from mount`;console.log(`[App] ${Ve}`)},[on]);const{keyboardOpen:vn}=Xa({enabled:X}),{footerHidden:Qt,navKeyboardOpen:sn,footerKeyboardOpen:mn}=SV({isMobile:X,keyboardOpen:vn,anyModalOpen:Y.anyModalOpen,isIOS:tf()}),Kt=Qt,fn=sn;ga(Kt);const[$n,On]=a.useState(0),[xn,Vn]=a.useState(0),[Rn,Pn]=a.useState(!1),[zn,Nn]=a.useState(0),[dn,Tt]=a.useState(null),[Yn,cn]=a.useState(!1),Bn=a.useRef(new Map),kn=a.useRef(new Set),pn=a.useRef(I7()),un=W9(),At=a.useCallback(()=>{lw(g?.id).then(Ve=>{On(Ve.unreadCount),Vn(Ve.pendingApprovalCount??0)}).catch(Ve=>{console.warn("[App] Failed to fetch mailbox unread count:",Ve)})},[g?.id]);a.useEffect(()=>{const Ve=new Map,Bt=new Set;for(const wn of dt)Ve.set(wn.id,wn.status),wn.status==="awaiting-approval"&&Bt.add(`task:${wn.id}`);Bn.current=Ve,kn.current=Bt},[dt]),a.useEffect(()=>{At();const Ve=new URLSearchParams;g?.id&&Ve.set("projectId",g.id);const Bt=Ve.size>0?`?${Ve.toString()}`:"",wn=Ns=>{const Us=pn.current.get(Ns.dedupeKey);Us!==void 0&&Ns.updatedAtMs<=Us||Tt(Ns)};return li(`/api/events${Bt}`,{onReconnect:At,events:{"message:sent":At,"message:received":At,"message:read":At,"message:deleted":At,"approval:requested":Ns=>{At();try{const Us=JSON.parse(Ns.data),bi=Us.id?`approval:${Us.id}`:Us.taskId?`task:${Us.taskId}`:void 0;if(!bi||kn.current.has(bi))return;kn.current.add(bi),wn({dedupeKey:bi,updatedAtMs:hk(Us.updatedAt??Us.createdAt)})}catch{}},"approval:updated":At,"approval:decided":At,"task:updated":Ns=>{try{const Us=JSON.parse(Ns.data);if(!Us?.id)return;const bi=`task:${Us.id}`,Tc=Bn.current.get(Us.id);if(Bn.current.set(Us.id,Us.status),!un&&P7(Us.status,Tc)&&cn(!0),Us.status!=="awaiting-approval"){kn.current.delete(bi),pn.current.delete(bi),pk(pn.current);return}if(kn.current.has(bi))return;R7(Us.status,Tc)&&(kn.current.add(bi),wn({dedupeKey:bi,updatedAtMs:hk(Us.updatedAt)}),At())}catch{}}}})},[g?.id,un,At]),a.useEffect(()=>{Ce==="chat"&&Pn(!1)},[Ce]),a.useEffect(()=>{let Ve=!1;const Bt=async()=>{try{const Ns=await I("/stash-recovery/orphans");Ve||Nn(Ns.count??0)}catch{Ve||Nn(0)}};Bt();const wn=window.setInterval(()=>void Bt(),3e4);return()=>{Ve=!0,window.clearInterval(wn)}},[g?.id]),a.useEffect(()=>{const Ve=new URLSearchParams;g?.id&&Ve.set("projectId",g.id);const Bt=Ve.size>0?`?${Ve.toString()}`:"";return li(`/api/events${Bt}`,{events:{"chat:message:added":wn=>{try{const Ns=JSON.parse(wn.data);if(Ns.role!=="assistant"||Ce==="chat"||Ns.projectId&&g?.id&&Ns.projectId!==g.id)return;Pn(!0)}catch{}},"chat:room:message:added":wn=>{try{const Ns=JSON.parse(wn.data);if(Ns.role==="user"||Ce==="chat"||Ns.projectId&&g?.id&&Ns.projectId!==g.id)return;Pn(!0)}catch{}}}})},[g?.id,Ce]);const an=a.useMemo(()=>Array.from(new Set(Rt.map(Ve=>Ve.branch?.trim()).filter(Ve=>!!(Ve&&Ve.length>0)))).sort((Ve,Bt)=>Ve.localeCompare(Bt)),[Rt]),Wn=a.useMemo(()=>Array.from(new Set(Rt.map(Ve=>Ve.baseBranch?.trim()).filter(Ve=>!!(Ve&&Ve.length>0)))).sort((Ve,Bt)=>Ve.localeCompare(Bt)),[Rt]),Xn=a.useMemo(()=>Rt.filter(Ve=>{const Bt=Ve.branch?.trim()??"",wn=Ve.baseBranch?.trim()??"";if(J===mk){if(Bt.length>0)return!1}else if(J.length>0&&Bt!==J)return!1;if(de===mk){if(wn.length>0)return!1}else if(de.length>0&&wn!==de)return!1;return!0}),[Rt,J,de]),[G,Oe]=a.useState(!1),yt=a.useCallback(()=>{Oe(!1)},[]),[Gt,Sn]=a.useState(!1),[Un,bn]=a.useState(void 0),[gn,ps]=a.useState(void 0),[Ne,ae]=a.useState(void 0),[Se,ut]=a.useState(()=>typeof window>"u"?void 0:new URL(window.location.href).searchParams.get("pr")??void 0),[It,ht]=a.useState(void 0);a.useEffect(()=>{Ce!=="goalsView"&&Ne!==void 0&&ae(void 0)},[Ne,Ce]),a.useEffect(()=>{Ce!=="pull-requests"&&Se!==void 0&&ut(void 0)},[Se,Ce]);const[et,Ut]=a.useState(!1),[$t,rn]=a.useState(!1),[Cn,ve]=a.useState(null),[at,Ge]=a.useState(!1),[tt,gt]=a.useState(null),[St,Xt]=a.useState(()=>cs(bh,g?.id)==="true"),[ss,Ts]=a.useState(()=>cs(Ed,g?.id)==="true");a.useEffect(()=>{Xt(cs(bh,g?.id)==="true")},[g?.id]),a.useEffect(()=>{Ts(cs(Ed,g?.id)==="true")},[g?.id]);const Ls=a.useCallback(async()=>{Ge(!0),gt(null);try{const Ve=await Bk();ve(Ve)}catch(Ve){gt(Ve instanceof Error?Ve.message:"Failed to refresh database health.")}finally{Ge(!1)}},[]);a.useEffect(()=>{let Ve=!1;return gE().then(Bt=>{Ve||ve(Bt)}).catch(()=>{Ve||ve(null)}),()=>{Ve=!0}},[]),a.useEffect(()=>{const Ve=()=>{rn(!0)};return window.addEventListener(Mh,Ve),()=>{window.removeEventListener(Mh,Ve)}},[]);const rs=a.useCallback(()=>{_s(bh,"true",g?.id),Xt(!0)},[g?.id]),ei=a.useCallback(()=>{_s(Ed,"true",g?.id),Ts(!0)},[g?.id]),{maxConcurrent:Mi,autoMerge:ti,globalPaused:mi,enginePaused:zs,isTestMode:Qn,taskStuckTimeoutMs:Zt,staleHighFanoutBlockerAgeThresholdMs:Q,capacityRiskBannerEnabled:Qe,capacityRiskTodoThreshold:vt,showQuickChatFAB:xt,maxTotalRetriesBeforeFail:zt,prAuthAvailable:Wt,settingsLoaded:hn,experimentalFeatures:In,insightsEnabled:gs,memoryEnabled:ks,devServerEnabled:Te,todosEnabled:U,goalsEnabled:ge,toggleAutoMerge:rt,toggleGlobalPause:Lt,toggleEnginePause:Dt,refresh:en}=aS(g?.id),{stats:tn}=iS(g?.id),Dn=a.useMemo(()=>Rt.filter(Ve=>Ve.column==="in-progress").length,[Rt]),_n=a.useMemo(()=>Rt.filter(Ve=>Ve.column==="in-review").length,[Rt]),is=a.useMemo(()=>L_({todoCount:tn?.todoTaskCount??0,inProgressCount:Dn,inReviewCount:_n,idleNonEphemeralAgentCount:tn?.idleNonEphemeralCount??0,threshold:vt??D_}),[tn?.todoTaskCount,tn?.idleNonEphemeralCount,Dn,_n,vt]),Ss=a.useRef(Qe),Rs=a.useRef(vt),ne=a.useRef(g?.id),Ue=a.useRef(!1);a.useEffect(()=>{if(!hn)return;if(!Ue.current||ne.current!==g?.id){Ue.current=!0,ne.current=g?.id,Ss.current=Qe,Rs.current=vt;return}const Ve=Ss.current,Bt=Rs.current;(!Ve&&Qe||Bt!==vt)&&(sa(Ed,g?.id),Ts(!1)),ne.current=g?.id,Ss.current=Qe,Rs.current=vt},[hn,Qe,vt,g?.id]);const Je=In.skillsView===!0,qt=In.nodesView===!0,En=In.researchView===!0,yn=In.evalsView===!0,os=In.agentOnboarding===!0,fs=!0,ws=a.useCallback(()=>{Y.closeSettings(),Pt(Ve=>Ve+1),en()},[Y,en]),js=a.useCallback(()=>{ue(ws),ws()},[ws,ue]);a.useEffect(()=>{if(hn&&!Fo(Ce)){if(Ce==="graph"&&!Ee){We("board");return}Ce==="skills"&&!Je&&We("board"),Ce==="insights"&&!gs&&We("board"),Ce==="memory"&&!ks&&We("board"),(Ce==="devserver"||Ce==="dev-server")&&!Te&&We("board"),Ce==="research"&&!En&&We("board"),Ce==="evals"&&!yn&&We("board"),Ce==="goalsView"&&!ge&&We("board")}},[Ce,hn,Je,gs,We,fs,ks,Te,En,yn,ge,Ee]),a.useEffect(()=>{G&&!qt&&(ue(yt),yt())},[yt,G,qt,ue]);const{availableModels:Vs,favoriteProviders:qs,favoriteModels:Ai,toggleFavoriteProvider:pi,toggleFavoriteModel:Fs}=eN();NV({projectId:g?.id,setupWizardOpen:Y.setupWizardOpen,openModelOnboarding:Y.openModelOnboarding,openSettings:Y.openSettings});const{handleSelectProject:ji,handleViewAllProjects:Oa,handleAddProject:wr,handleSetupComplete:fl,handleModelOnboardingComplete:fi,handlePauseProject:gl,handleResumeProject:la,handleRemoveProject:ba,handleToggleFavorite:va,handleToggleModelFavorite:Xi}=$V({setCurrentProject:j,clearCurrentProject:S,setViewMode:$e,currentProject:g,refreshProjects:u,toggleFavoriteProvider:pi,toggleFavoriteModel:Fs,addToast:s,openSettings:Y.openSettings,openSetupWizard:Y.openSetupWizard,closeSetupWizard:Y.closeSetupWizard,closeModelOnboarding:Y.closeModelOnboarding}),{handleDetailClose:jr}=jV({projectId:g?.id,projects:m,projectsLoading:p,currentProject:g,setCurrentProject:j,addToast:s,openTaskDetail:Y.openDetailTask,closeTaskDetail:Y.closeDetailTask}),bl=a.useCallback(async({insightId:Ve,title:Bt,description:wn})=>{await nt({title:Bt,description:wn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Ve}}})},[nt]),{handleBoardQuickCreate:Nr,handleModalCreate:Sr,handlePlanningTaskCreated:io,handlePlanningTasksCreated:vl,handleSubtaskTasksCreated:Qa,handleGitHubImport:$a}=zV({createTask:nt,ingestCreatedTasks:fe,onPlanningTaskCreated:Y.onPlanningTaskCreated,onPlanningTasksCreated:Y.onPlanningTasksCreated,onSubtaskTasksCreated:Y.onSubtaskTasksCreated,addToast:s}),za=a.useCallback((Ve,Bt)=>{Bt==="changes"?Y.openDetailWithChangesTab(Ve):Y.openDetailTask(Ve,Bt),ye({type:"modal",close:Y.closeDetailTask})},[Y,ye]),gi=a.useCallback(async Ve=>{try{const Bt=await pr(Ve,g?.id);Y.openDetailTask(Bt,"logs"),ye({type:"modal",close:Y.closeDetailTask})}catch(Bt){s(`Failed to open task logs: ${Bt.message}`,"error")}},[Y,g?.id,s,ye]),[zi,xa]=a.useState([]);a.useEffect(()=>{let Ve=!1;return zp(g?.id).then(Bt=>{Ve||xa(Bt)}).catch(()=>{Ve||xa([])}),()=>{Ve=!0}},[g?.id]);const Cr=a.useMemo(()=>new Map(zi.map(Ve=>[Ve.id,Ve.name])),[zi]);a.useCallback(()=>{qt&&Oe(Ve=>!Ve)},[qt]);const Ti=a.useCallback(()=>{ue(yt),yt()},[yt,ue]),ao=a.useCallback(()=>{qt&&(G?Ti():(Oe(!0),ye({type:"view",revert:yt})))},[yt,Ti,qt,G,ye]),Bi=a.useCallback((Ve,Bt,wn)=>{Y.openDetailTask(Ve,Bt,wn),ye({type:"modal",close:Y.closeDetailTask})},[Y,ye]),ro=a.useCallback(Ve=>{Y.openSettings(Ve),ye({type:"modal",close:ws})},[Y,ye,ws]),Za=a.useCallback(()=>{Y.openNewTask(),ye({type:"modal",close:Y.closeNewTask})},[Y,ye]),_r=a.useCallback(()=>{Y.openPlanning(),ye({type:"modal",close:Y.closePlanning})},[Y,ye]),Ba=a.useCallback(Ve=>{Y.openPlanningWithInitialPlan(Ve),ye({type:"modal",close:Y.closePlanning})},[Y,ye]),ya=a.useCallback(()=>{Y.resumePlanning(),ye({type:"modal",close:Y.closePlanning})},[Y,ye]),oo=a.useCallback(Ve=>{Y.openSubtaskBreakdown(Ve),ye({type:"modal",close:Y.closeSubtask})},[Y,ye]),Cs=a.useCallback(Ve=>{Y.openGroupModal(Ve),ye({type:"modal",close:Y.closeGroupModal})},[Y,ye]),ka=a.useCallback(()=>{Y.openGitHubImport(),ye({type:"modal",close:Y.closeGitHubImport})},[Y,ye]),wa=a.useCallback(()=>{Y.terminalOpen?(ue(Y.closeTerminal),Y.toggleTerminal()):(Y.toggleTerminal(),ye({type:"modal",close:Y.closeTerminal}))},[Y,ye,ue]),Er=a.useCallback((Ve,Bt)=>{Y.openFiles(Ve,Bt),ye({type:"modal",close:Y.closeFiles})},[Y,ye]),ja=a.useCallback((Ve,Bt)=>{Y.openFiles(Bt?.workspace,Ve),ye({type:"modal",close:Y.closeFiles})},[Y,ye]),lo=a.useCallback(()=>{Y.openTodos(),ye({type:"modal",close:Y.closeTodos})},[Y,ye]),co=a.useCallback(()=>{Y.openActivityLog(),ye({type:"modal",close:Y.closeActivityLog})},[Y,ye]),Mr=a.useCallback(()=>{Y.openGitManager(),ye({type:"modal",close:Y.closeGitManager})},[Y,ye]),Ar=a.useCallback(()=>{Y.openSystemStats(),ye({type:"modal",close:Y.closeSystemStats})},[Y,ye]),er=a.useCallback(()=>{Y.openSchedules(),ye({type:"modal",close:Y.closeSchedules})},[Y,ye]),Kn=a.useCallback(()=>{Y.openScripts(),ye({type:"modal",close:Y.closeScripts})},[Y,ye]),tr=a.useCallback(Ve=>{Y.openWorkflowEditor(void 0,Ve),ye({type:"modal",close:Y.closeWorkflowEditor})},[Y,ye]),nr=a.useCallback(()=>{Y.openWorkflowEditor("create"),ye({type:"modal",close:Y.closeWorkflowEditor})},[Y,ye]),sr=a.useCallback(Ve=>{Y.openUsage(Ve),ye({type:"modal",close:Y.closeUsage})},[Y,ye]),W=a.useCallback(async(Ve,Bt)=>{await Y.runScript(Ve,Bt),ot({type:"modal",close:Y.closeTerminal})},[Y,ot]),Be=a.useCallback(()=>{Y.closeSettings(),Y.openModelOnboarding(),ot({type:"modal",close:Y.closeModelOnboarding})},[Y,ot]),Ye=a.useCallback(()=>{Y.setFileWorkspace("project"),Y.openFiles()},[Y]),Ct=a.useCallback(async()=>{Sn(!0);try{await u()}finally{Sn(!1)}},[u]),qn=a.useCallback(Ve=>{ps(Ve),bn(void 0),We("missions")},[We]),Jt=a.useCallback(Ve=>{Ve.type==="planning"?Y.openPlanningWithSession(Ve.id):Ve.type==="subtask"?Y.openSubtaskWithSession(Ve.id):Ve.type==="mission_interview"?(ps(void 0),bn(Ve.id),ht(void 0),We("missions")):(Ve.type==="milestone_interview"||Ve.type==="slice_interview")&&(bn(void 0),ps(void 0),ht(Ve.id),We("missions"))},[We,Y]),Zn=a.useCallback(()=>{},[]),ts=a.useCallback(()=>{},[]),[ni,ct]=a.useState(!1),[jt,nn]=a.useState(!1),[Gn,bs]=a.useState(null),Bs=L7(o,l,ni);a.useEffect(()=>{!r||d===0||nn(!0)},[r,d]),a.useEffect(()=>{let Ve=!1;return h7(c.host).then(Bt=>{Ve||bs(Bt)}),()=>{Ve=!0}},[c.host,o.activeProfileId,o.desktopMode,o.host,o.profiles]),a.useEffect(()=>{o.host==="desktop-shell"&&o.desktopMode==="local"&&(o.localServer?.status!=="ready"||!o.localServer.port||window.location.port!==String(o.localServer.port)&&(window.location.href=`http://localhost:${o.localServer.port}`))},[o]),a.useEffect(()=>{if(o.host!=="desktop-shell"||o.desktopMode!=="remote")return;const Ve=o.profiles.find(wn=>wn.id===o.activeProfileId);if(!Ve||typeof window>"u")return;const Bt=D7(Ve.serverUrl,Ve.authToken??null);window.location.href!==Bt&&(window.location.href=Bt)},[o]);const Ri=!!h&&ju(h??"")&&f.current,uo=!p&&!C&&m.length===0&&!g&&!!h&&!Ri,us=()=>{if(uo)return t.jsx(pH,{errorMessage:h??e("app.backendError.failedFetch","Failed to fetch projects"),isRetrying:Gt,onRetry:Ct,onManageConnection:r?()=>{r.openConnectionManager()}:void 0});if(G)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(y7,{addToast:s,onClose:Ti})})})});if(je==="overview")return t.jsx(Ys,{children:t.jsx(A6,{projects:m,loading:p,onSelectProject:ji,onAddProject:wr,onPauseProject:gl,onResumeProject:la,onRemoveProject:ba,nodes:b})});const Ve=Ce==="graph"?Ee:Fo(Ce)?Ce:null;return Ve?t.jsx(Ys,{children:t.jsx(PV,{taskView:Ve,context:{projectId:g?.id,tasks:x&&ie.tasks.length>0?ie.tasks:dt,workflowSteps:zi,subscribePluginEvents:T,openTaskDetail:(Bt,wn)=>Bi(Bt,wn),openFile:ja,renderTaskCard:Bt=>t.jsx(cc,{task:Bt,projectId:g?.id,onOpenDetail:wn=>Bi(wn),addToast:s,workflowStepNameLookup:Cr,disableDrag:!0,prAuthAvailable:Wt,autoMergeEnabled:ti}),addToast:s}})}):Ce==="skills"?!hn||!Je?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(w7,{addToast:s,projectId:g?.id,onClose:()=>We("board")})})}):Ce==="chat"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(k7,{addToast:s,projectId:g?.id,experimentalFeatures:In})})}):Ce==="mailbox"?t.jsx(Ys,{children:t.jsx(R3,{projectId:g?.id,addToast:s,onUnreadCountChange:On})}):Ce==="missions"?t.jsx(Ys,{children:t.jsx(j3,{isInline:!0,isOpen:!0,onClose:()=>{ps(void 0),bn(void 0),ht(void 0),We("board")},addToast:s,projectId:g?.id,onSelectTask:Bt=>{const wn=dt.find(Ns=>Ns.id===Bt);wn&&Bi(wn)},availableTasks:dt.map(Bt=>({id:Bt.id,title:Bt.title})),resumeSessionId:Un,targetMissionId:gn,milestoneSliceResumeSessionId:It,onMilestoneSliceResumeFetchError:()=>ht(void 0),onNavigateToGoal:Bt=>{ae(Bt),We("goalsView")}})}):Ce==="agents"&&fs?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(f7,{addToast:s,projectId:g?.id,onOpenTaskLogs:gi,agentOnboardingEnabled:os})})}):Ce==="documents"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(g7,{projectId:g?.id,addToast:s,onOpenDetail:Bi})})}):Ce==="stash-recovery"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(E7,{})})}):Ce==="pull-requests"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(M7,{pullRequestId:Se,projectId:g?.id})})}):Ce==="insights"?!hn||!gs?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(b7,{projectId:g?.id,addToast:s,onClose:()=>We("board"),onCreateTask:bl})})}):Ce==="research"?!hn||!En?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(v7,{projectId:g?.id,addToast:s,onOpenSettings:Bt=>Y.openSettings(Bt),readinessVersion:Vt})})}):Ce==="evals"?!hn||!yn?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(x7,{projectId:g?.id,onOpenSettings:Bt=>Y.openSettings(Bt),onOpenTaskDetail:Bt=>{pr(Bt,g?.id).then(wn=>Bi(wn)).catch(wn=>s(wn instanceof Error?wn.message:"Failed to open task detail","error"))}})})}):Ce==="memory"?!hn||!ks?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(j7,{addToast:s,projectId:g?.id})})}):Ce==="secrets"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(N7,{addToast:s})})}):Ce==="goalsView"?!hn||!ge?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(_7,{anchorGoalId:Ne})})}):Ce==="reliability"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(S7,{})})}):Ce==="devserver"||Ce==="dev-server"?!hn||!Te?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(C7,{addToast:s,projectId:g?.id})})}):Ce==="board"?t.jsxs(Ys,{children:[Qe&&!ss?t.jsx(DH,{signal:is,onDismiss:ei}):null,t.jsx(vD,{tasks:Xn,projectId:g?.id,maxConcurrent:Mi,onMoveTask:Nt,onPauseTask:Ft,onOpenDetail:Bi,onOpenGroupModal:Cs,addToast:s,onQuickCreate:Nr,onNewTask:Za,onPlanningMode:Ba,onSubtaskBreakdown:oo,autoMerge:ti,onToggleAutoMerge:rt,globalPaused:mi,onUpdateTask:Ae,onRetryTask:Ht,onArchiveTask:Ie,onUnarchiveTask:Pe,onDeleteTask:it,onArchiveAllDone:oe,onLoadArchivedTasks:re,searchQuery:L,availableModels:Vs,onOpenDetailWithTab:za,favoriteProviders:qs,favoriteModels:Ai,onToggleFavorite:va,onToggleModelFavorite:Xi,taskStuckTimeoutMs:Zt,staleHighFanoutBlockerAgeThresholdMs:Q,onOpenMission:qn,lastFetchTimeMs:Xe,prAuthAvailable:Wt,onOpenWorkflowEditor:tr,onCreateWorkflow:nr})]}):t.jsx(Ys,{children:t.jsx(x6,{tasks:x&&ie.tasks.length>0?ie.tasks:dt,projectId:g?.id,onMoveTask:Nt,onRetryTask:Ht,onDeleteTask:it,onPauseTask:Ft,onUnpauseTask:ze,onArchiveTask:Ie,onMergeTask:Mt,onResetTask:Me,onDuplicateTask:ee,onOpenDetail:(Bt,wn)=>Bi(Bt,void 0,wn),addToast:s,globalPaused:mi,onNewTask:Za,onQuickCreate:Nr,onPlanningMode:Ba,onSubtaskBreakdown:oo,availableModels:Vs,favoriteProviders:qs,favoriteModels:Ai,onToggleFavorite:va,onToggleModelFavorite:Xi,taskStuckTimeoutMs:Zt,searchQuery:L,lastFetchTimeMs:Xe,prAuthAvailable:Wt,onCreateWorkflow:nr})})},ms=!Y.modelOnboardingOpen&&I8(),Hn=!Y.modelOnboardingOpen&&!ms&&ol()&&!qN(),Ks=p||C||Fe;return t.jsx(R6,{value:{pushNav:ye,replaceCurrent:ot,removeNav:ue},children:t.jsx(G$,{openFile:ja,children:t.jsx(mI,{value:zt*T7,children:An?t.jsxs(t.Fragment,{children:[t.jsx(gH,{stage:Yt}),t.jsx(JN,{toasts:n,onRemove:i})]}):t.jsxs(t.Fragment,{children:[t.jsx(bH,{visible:Ks}),t.jsx(SP,{shellHost:c.host,onOpenSettings:ro,onOpenGitHubImport:ka,onOpenPlanning:_r,onResumePlanning:ya,activePlanningSessionCount:te.length,onOpenUsage:sr,onOpenActivityLog:co,onOpenSystemStats:Ar,onOpenMailbox:()=>Ze("mailbox"),mailboxUnreadCount:$n,mailboxPendingApprovalCount:xn,chatHasUnreadResponse:Rn,stashOrphanCount:zn,onOpenSchedules:er,onOpenGitManager:Mr,onOpenNodes:ao,showNodesButton:qt,onOpenWorkflowEditor:tr,onOpenScripts:Kn,onRunScript:W,onToggleTerminal:wa,onOpenFiles:Er,filesOpen:Y.filesOpen,onOpenTodos:lo,todosOpen:Y.todosOpen,todosEnabled:U,globalPaused:mi,enginePaused:zs,onToggleGlobalPause:Lt,onToggleEnginePause:Dt,view:Ce,onChangeView:je==="project"&&g?Ze:void 0,showSkillsTab:Je,showAgentsTab:fs,searchQuery:L,onSearchChange:O,branchFilter:J,baseBranchFilter:de,branchOptions:an,baseBranchOptions:Wn,onBranchFilterChange:P,onBaseBranchFilterChange:Z,projects:le,currentProject:g,onSelectProject:ji,onViewAllProjects:Oa,projectId:g?.id,mobileNavEnabled:X,availableNodes:b,currentNode:y,onSelectNode:Ve=>{Ve===null?w():k(Ve)},isRemote:x,experimentalFeatures:{insights:gs,memoryView:ks,devServer:Te,devServerView:Te,researchView:En,evalsView:yn,goalsView:ge},pluginDashboardViews:ke,shellConnectionControl:!X&&Gn?t.jsx(ck,{status:Gn,onError:Ve=>s(Ve,"error")}):void 0}),je==="project"&&g&&t.jsxs(t.Fragment,{children:[t.jsx(LH,{isActive:Qn}),t.jsx(OH,{onReLogin:Ve=>Y.openSettings("authentication")})]}),je==="project"&&g&&!G&&Ce!=="missions"&&!Y.isPlanningOpen&&!z&&t.jsx(TH,{sessions:se,onResumeSession:Jt,onDismissSession:Zn,onDismissAll:ts}),je==="project"&&g&&t.jsx(IH,{onOpenSettings:()=>Y.openSettings("general")}),je==="project"&&g&&ms&&t.jsx(ZH,{onResume:Y.openModelOnboarding}),je==="project"&&g&&Hn&&t.jsx(e9,{onOpenModelOnboarding:Y.openModelOnboarding,onOpenSettings:Ve=>Y.openSettings(Ve)}),je==="project"&&g&&_&&V&&N&&!$&&t.jsx(HH,{latestVersion:V,currentVersion:N,onDismiss:R}),je==="project"&&g&&t.jsx(JH,{projectId:g.id}),je==="project"&&g&&Cn?.taskIdIntegrity?.status==="anomaly"&&Cn.taskIdIntegrity.recommendedAction&&t.jsx(BH,{report:Cn.taskIdIntegrity,recommendedAction:Cn.taskIdIntegrity.recommendedAction,onRefresh:(Ve,Bt)=>{ve(wn=>wn?{...wn,status:Ve.status==="anomaly"||!wn.database.healthy||wn.database.corruptionDetected?"degraded":"ok",taskIdIntegrity:{...Ve,recommendedAction:Bt}}:null)}}),je==="project"&&g&&Cn?.database?.corruptionDetected===!0&&t.jsx(UH,{errors:Cn.database.corruptionErrors,lastCheckedAt:Cn.database.lastCheckedAt,onRefresh:Ls,refreshing:at,refreshError:tt}),je==="project"&&g&&!M&&D&&!St&&t.jsx(BN,{hasAiProvider:E,hasGithub:F,onDismiss:rs}),je==="project"&&g&&dn&&t.jsx(YH,{pendingCount:Math.max(xn,1),onOpenMailbox:()=>Ze("mailbox"),onDismiss:()=>{pn.current.set(dn.dedupeKey,Math.max(Date.now(),dn.updatedAtMs)),pk(pn.current),Tt(null)}}),je==="project"&&g&&Yn&&!un&&t.jsx(QH,{onDismiss:()=>{q9(),cn(!1)}}),t.jsx("div",{className:`project-content${je==="project"&&g&&(!X||!Kt)?" project-content--with-footer":""}${X&&!Kt?" project-content--with-mobile-nav":""}`,children:us()}),je==="project"&&g&&!G&&t.jsx(CH,{tasks:x&&ie.tasks.length>0?ie.tasks:dt,projectId:g.id,taskStuckTimeoutMs:Zt,staleHighFanoutBlockerAgeThresholdMs:Q,backgroundSessions:He,backgroundGenerating:qe,backgroundNeedsInput:pe,onOpenBackgroundSession:Jt,onDismissBackgroundSession:me,lastFetchTimeMs:Xe,currentProjectPath:g.path,onOpenProjectDirectory:Ye,keyboardOpen:mn,hideWhenKeyboardOpen:Kt}),t.jsx(s9,{view:Ce,onChangeView:je==="project"&&g?Ze:()=>{},footerVisible:je==="project"&&!!g,modalOpen:Y.anyModalOpen,keyboardOpen:fn,onOpenSettings:ro,onOpenActivityLog:co,onOpenSystemStats:Ar,onOpenMailbox:()=>Ze("mailbox"),onOpenNodes:ao,mailboxUnreadCount:$n,mailboxPendingApprovalCount:xn,chatHasUnreadResponse:Rn,stashOrphanCount:zn,onOpenGitManager:Mr,onOpenWorkflowEditor:tr,onOpenSchedules:er,onOpenScripts:Kn,onToggleTerminal:wa,onOpenFiles:Er,onOpenTodos:lo,todosOpen:Y.todosOpen,onOpenGitHubImport:ka,onOpenPlanning:_r,onResumePlanning:ya,activePlanningSessionCount:te.length,onOpenUsage:()=>sr(null),onViewAllProjects:Oa,onRunScript:W,projectId:g?.id,showSkillsTab:Je,experimentalFeatures:{insights:gs,memoryView:ks,devServer:Te,devServerView:Te,todoView:U,researchView:En,evalsView:yn,goalsView:ge,nodesView:qt},pluginDashboardViews:ke,shellConnectionControl:X&&Gn?t.jsx(ck,{status:Gn,onError:Ve=>s(Ve,"error")}):void 0}),je==="project"&&g&&Ce!=="chat"&&Ce!=="mailbox"&&Ce!=="insights"&&Ce!=="evals"&&Ce!=="devserver"&&Ce!=="dev-server"&&Ce!=="graph"&&!Fo(Ce)&&t.jsx(B9,{projectId:g.id,addToast:s,showFAB:xt,open:et,onOpenChange:Ut,favoriteProviders:qs,favoriteModels:Ai,onToggleFavorite:va,onToggleModelFavorite:Xi}),t.jsx(uH,{projectId:g?.id,tasks:dt,projects:m,currentProject:g,addToast:s,toasts:n,removeToast:i,modalManager:Y,projectActions:{handleAddProject:wr,handleSetupComplete:fl,handleModelOnboardingComplete:fi},taskHandlers:{handleModalCreate:Sr,handlePlanningTaskCreated:io,handlePlanningTasksCreated:vl,handleSubtaskTasksCreated:Qa,handleGitHubImport:$a},taskOperations:{moveTask:Nt,deleteTask:it,mergeTask:Mt,archiveTask:Ie,retryTask:Ht,resetTask:Me,duplicateTask:ee},deepLink:{handleDetailClose:jr},settings:{prAuthAvailable:Wt,themeMode:be,colorTheme:Le,dashboardFontScalePct:xe,setThemeMode:q,setColorTheme:ce,setDashboardFontScalePct:De},onSettingsClose:js,onReopenOnboarding:Be,onOpenApprovals:Ve=>Ze("mailbox")}),t.jsx(p7,{open:$t}),r&&t.jsxs(t.Fragment,{children:[t.jsx(o7,{open:Bs,shellApi:r,shellState:o,onComplete:()=>ct(!0)}),t.jsx(l7,{open:jt,shellApi:r,shellState:o,onClose:()=>nn(!1)})]})]})})})})}function $7(){return t.jsx(VS,{i18n:uu,children:t.jsx(D3,{children:t.jsx(i7,{children:t.jsx(w8,{children:t.jsx(VV,{children:t.jsx(EP,{children:t.jsx(O7,{})})})})})})})}function kS(e){e.postMessage({type:"SKIP_WAITING"})}function fk(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&kS(e)})}function z7(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,Ep("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&kS(s.waiting),s.installing&&fk(s.installing),s.addEventListener("updatefound",()=>{const i=s.installing;i&&fk(i)})}).catch(s=>{console.log("SW registration failed:",s)})}pE();__();vS();pS();pV.finally(()=>{zS.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(E_,{children:t.jsx(T_,{children:t.jsx($7,{})})})})),z7()});export{KA as $,Ci as A,Is as B,Es as C,Y_ as D,GW as E,Hr as F,Np as G,w1 as H,jh as I,ys as J,Ld as K,Et as L,xc as M,N1 as N,ia as O,hs as P,Ds as Q,xs as R,na as S,oa as T,as as U,$K as V,c8 as W,Fn as X,ah as Y,Ws as Z,q0 as _,Ln as a,vh as a$,ln as a0,a8 as a1,JA as a2,GA as a3,XU as a4,QU as a5,VW as a6,ki as a7,Gr as a8,Tn as a9,Ia as aA,Vo as aB,ha as aC,oC as aD,lK as aE,dK as aF,Gs as aG,fK as aH,pK as aI,hK as aJ,mK as aK,uK as aL,cK as aM,Uk as aN,Yo as aO,aK as aP,oK as aQ,rK as aR,vK as aS,gK as aT,bK as aU,xK as aV,ul as aW,_c as aX,cG as aY,OK as aZ,oc as a_,Bq as aa,Uq as ab,es as ac,YM as ad,jp as ae,bc as af,Zr as ag,Di as ah,Li as ai,ra as aj,Fh as ak,XG as al,nK as am,tK as an,Ka as ao,sK as ap,QG as aq,iK as ar,ZG as as,eK as at,Ms as au,$s as av,Qr as aw,Ql as ax,oi as ay,r_ as az,ls as b,wq as b$,W1 as b0,Ea as b1,ig as b2,ZC as b3,Hs as b4,C6 as b5,Si as b6,Tk as b7,L1 as b8,aG as b9,E9 as bA,kf as bB,b9 as bC,Mf as bD,j9 as bE,Xa as bF,tS as bG,S9 as bH,Qs as bI,Pa as bJ,mu as bK,tf as bL,i9 as bM,zr as bN,hi as bO,Nk as bP,Mk as bQ,x9 as bR,rg as bS,PR as bT,GG as bU,qG as bV,WG as bW,KG as bX,kq as bY,yq as bZ,xq as b_,rG as ba,oG as bb,lG as bc,Nu as bd,tV as be,Lh as bf,vw as bg,Kg as bh,vs as bi,wl as bj,ch as bk,$y as bl,GR as bm,kl as bn,sa as bo,r9 as bp,DR as bq,JG as br,YG as bs,VR as bt,o9 as bu,WR as bv,ju as bw,Ra as bx,ua as by,_9 as bz,mt as c,J7 as c$,Tq as c0,Rq as c1,Eq as c2,Sq as c3,Cq as c4,_q as c5,Nq as c6,jq as c7,vq as c8,Mq as c9,kG as cA,pG as cB,Hk as cC,Ek as cD,AW as cE,tw as cF,I as cG,rc as cH,vr as cI,ai as cJ,Wd as cK,cc as cL,fW as cM,aa as cN,iW as cO,nW as cP,sW as cQ,pa as cR,Aq as cS,Jo as cT,lT as cU,rE as cV,oE as cW,dG as cX,uG as cY,aq as cZ,Zs as c_,$5 as ca,lW as cb,oW as cc,pW as cd,rW as ce,cW as cf,dW as cg,uW as ch,mW as ci,wA as cj,hW as ck,$p as cl,xA as cm,yA as cn,kA as co,vA as cp,aW as cq,gu as cr,V1 as cs,Ko as ct,fG as cu,gG as cv,bG as cw,vG as cx,xG as cy,yG as cz,ZW as d,jy as d$,Y7 as d0,J_ as d1,Ja as d2,pg as d3,hV as d4,Ik as d5,uV as d6,GE as d7,KE as d8,X7 as d9,OG as dA,qq as dB,Zq as dC,Yq as dD,Wq as dE,Xq as dF,Gq as dG,Qq as dH,Kq as dI,Jq as dJ,Bp as dK,kK as dL,kW as dM,wW as dN,Jv as dO,Wr as dP,iq as dQ,tq as dR,La as dS,J9 as dT,N5 as dU,Pq as dV,eq as dW,Z7 as dX,mG as dY,gE as dZ,rq as d_,mq as da,lq as db,hq as dc,uq as dd,pq as de,fq as df,gq as dg,bq as dh,Q7 as di,nM as dj,aM as dk,eW as dl,sM as dm,tW as dn,ea as dp,u8 as dq,h8 as dr,p8 as ds,fr as dt,wy as du,rh as dv,g8 as dw,FG as dx,Vq as dy,Hq as dz,XW as e,mN as e$,eG as e0,oq as e1,cq as e2,bM as e3,Ro as e4,gM as e5,iG as e6,rM as e7,Ah as e8,oM as e9,NK as eA,ip as eB,bB as eC,Hp as eD,aS as eE,bW as eF,EW as eG,MW as eH,EK as eI,MK as eJ,CW as eK,NW as eL,SW as eM,nB as eN,AK as eO,TK as eP,RK as eQ,Zz as eR,_K as eS,Qd as eT,oN as eU,rN as eV,cN as eW,lN as eX,DK as eY,LK as eZ,_W as e_,cM as ea,lM as eb,dM as ec,uM as ed,Lq as ee,tG as ef,nG as eg,sG as eh,yr as ei,hG as ej,dq as ek,Od as el,xh as em,L5 as en,zK as eo,yK as ep,nq as eq,sq as er,Qz as es,Nf as et,jK as eu,wK as ev,uN as ew,Tu as ex,gW as ey,ui as ez,pr as f,RG as f$,ap as f0,CK as f1,FK as f2,vW as f3,yW as f4,SK as f5,jW as f6,xW as f7,oB as f8,Wo as f9,qr as fA,B0 as fB,MG as fC,WW as fD,rz as fE,mr as fF,HW as fG,BW as fH,JW as fI,KW as fJ,jk as fK,OW as fL,FW as fM,TW as fN,RW as fO,YU as fP,Ir as fQ,qW as fR,DW as fS,IW as fT,XM as fU,LW as fV,$W as fW,AG as fX,NR as fY,PW as fZ,TG as f_,LC as fa,X1 as fb,h1 as fc,Fd as fd,UC as fe,GC as ff,bC as fg,vB as fh,hN as fi,jB as fj,lc as fk,IK as fl,PK as fm,wG as fn,NG as fo,_G as fp,SG as fq,jG as fr,CG as fs,EG as ft,Ph as fu,jg as fv,zW as fw,UW as fx,ER as fy,t0 as fz,QW as g,$G as g0,Nh as g1,UG as g2,HG as g3,BG as g4,DG as g5,IG as g6,LG as g7,PG as g8,zG as g9,Fq as ga,Iq as gb,Dq as gc,$q as gd,zq as ge,Oq as gf,eN as h,fa as i,br as j,ru as k,VG as l,wi as m,WA as n,YW as o,Ji as p,iS as q,ZU as r,li as s,cs as t,ga as u,Yi as v,_s as w,yu as x,Bc as y,Re as z};
|
|
793
|
+
`)[0]?.trim()||ei?.title||"",ti=new Set(oh),mi=at.filter(Q=>ti.has(Q.id)).sort((Q,Qe)=>{const vt=oh.indexOf(Q.id),xt=oh.indexOf(Qe.id);return vt!==xt?vt-xt:My(Q,Qe)}),zs=at.filter(Q=>Q.authenticated&&!ti.has(Q.id)),Qn=at.filter(Q=>!Q.authenticated&&!ti.has(Q.id)),Zt=Q=>{const Qe=oe[Q.id]==="timeout"||oe[Q.id]==="failed"||oe[Q.id]==="cancelled",vt=Q.loginInProgress&&!Qe;if(Q.id==="llama-cpp"&&Q.type==="cli")return t.jsx(p8,{authenticated:Q.authenticated,onToggled:()=>{sn()}},Q.id);if(Q.id==="claude-cli"&&Q.type==="cli")return t.jsx(u8,{authenticated:Q.authenticated,onToggled:()=>{sn()}},Q.id);if(Q.id==="cursor-cli"&&Q.type==="cli")return t.jsx(h8,{authenticated:Q.authenticated,onToggled:()=>{sn()}},Q.id);if(Q.type==="api_key"){const xt=fp(Q.id,c),zt=tH(Q,c);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Q.id}`,"aria-hidden":"true",children:t.jsx(hs,{provider:Q.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(_k,{size:14,className:"onboarding-provider-key-icon"}),Q.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:xt.description}),t.jsx(dn,{status:Nn(Q)}),Q.authenticated&&Q.keyHint&&t.jsx("span",{className:"auth-key-hint",children:c("setup.apiKeyHint","Key: {{keyHint}}",{keyHint:Q.keyHint})})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(sH,{provider:Q,apiKeyInfo:zt,inputValue:Y[Q.id]??"",isSaving:P===Q.id,error:X[Q.id],success:ot[Q.id],isConnected:Q.authenticated,onInputChange:Gt,onSave:Un,onClear:bn})})]},Q.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Q.id}`,className:`onboarding-provider-card${Q.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Q.id}`,"aria-hidden":"true",children:t.jsx(hs,{provider:Q.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:Q.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:fp(Q.id,c).description}),t.jsx(dn,{status:Nn(Q)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:P===Q.id?Q.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.loggingOut","Logging out…")}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.waitingForLogin","Waiting for login…")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void yt(Q.id),children:c("setup.cancelLogin","Cancel")})]}):vt?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.waitingForLogin","Waiting for login…")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void yt(Q.id),children:c("setup.cancelLogin","Cancel")})]}):Q.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>gn(Q.id),children:c("setup.logout","Logout")}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>G(Q.id),children:c("setup.login","Login")})}),(P===Q.id||vt)&&Q.id==="github-copilot"&&Le[Q.id]&&t.jsxs("div",{className:"auth-device-code-panel","data-testid":`onboarding-device-code-${Q.id}`,children:[t.jsx("strong",{children:c("setup.enterCodeOnGitHub","Enter this code on GitHub")}),t.jsx("div",{className:"auth-device-code-pill",children:Le[Q.id].userCode}),t.jsxs("div",{className:"auth-provider-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{(async()=>{if(await wy(Le[Q.id].userCode)){n(c("setup.copiedCodeToClipboard","Copied code to clipboard"),"success");return}n(c("setup.failedToCopyCode","Failed to copy code — copy it manually from the box above"),"error")})()},children:c("setup.copyCode","Copy code")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>window.open(pa(Le[Q.id].verificationUri),"_blank"),children:c("setup.openGitHub","Open GitHub")})]})]}),(P===Q.id||vt)&&T[Q.id]&&t.jsx(rh,{instructions:T[Q.id],"data-testid":`onboarding-login-instructions-${Q.id}`}),(P===Q.id||vt)&&le[Q.id]&&t.jsx(g8,{value:q[Q.id]??"",onChange:xt=>ce(zt=>({...zt,[Q.id]:xt})),onSubmit:()=>void Oe(Q.id),prompt:le[Q.id].prompt,placeholder:le[Q.id].placeholder,helpText:le[Q.id].helpText,disabled:De===Q.id,submitLabel:De===Q.id?c("setup.submittingCode","Submitting…"):c("setup.submitCode","Submit code"),"data-testid":`onboarding-manual-code-${Q.id}`}),oe[Q.id]==="timeout"&&P!==Q.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:c("setup.loginTimedOutInline","Login timed out. Please try again.")}),oe[Q.id]==="failed"&&P!==Q.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:c("setup.loginFailedInline","Login failed. Please try again.")})]},Q.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:Ie,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(Ws,{size:24})," ",c("setup.titleAiSetup","Set Up AI")," ",t.jsx("span",{className:"onboarding-optional-badge",children:c("setup.optionalBadge","Optional")})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(ai,{size:24})," ",c("setup.titleConnectGitHub","Connect GitHub")," ",t.jsx("span",{className:"onboarding-optional-badge",children:c("setup.optionalBadge","Optional")})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(sg,{size:24})," ",c("setup.titleSetUpProject","Set Up Your Project")]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(sg,{size:24})," ",c("setup.titleCreateFirstTask","Create Your First Task")]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Es,{size:24})," ",c("setup.titleAllSet","All Set!")]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:ht,"aria-label":c("setup.skipOnboardingAriaLabel","Skip onboarding"),title:c("setup.skipForNow","Skip for now"),children:t.jsx(Fn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:on.map((Q,Qe)=>{const vt=vn>Qe,xt=w.includes(Q.key)&&vt,zt=j.includes(Q.key)&&!w.includes(Q.key)&&vt,Wt=xt||zt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Qe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Qe<=vn?"done":""}`}),Wt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===Q.key?"active":""} ${xt?"done":""} ${zt?"skipped":""}`,onClick:()=>k(Q.key),"aria-label":c("setup.goBackToStep","Go back to {{label}}",{label:Q.label}),title:c("setup.reviewStep","Review {{label}}",{label:Q.label}),children:[t.jsx("span",{className:"step-number",children:xt?t.jsx(Es,{size:14}):zt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Qe+1}),t.jsx("span",{className:"step-label",children:Q.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===Q.key?"active":""} ${xt?"done":""} ${zt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:xt?t.jsx(Es,{size:14}):zt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Qe+1}),t.jsx("span",{className:"step-label",children:Q.label})]})]},Q.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:ee,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:c("setup.aiSetupDescription","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:c("setup.onlyNeedOneProvider","You only need one provider to get started.")}),t.jsx("p",{className:"onboarding-helper-text",children:c("setup.researchRunsNote","Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features.")}),ve&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:c("setup.connectRemoteServer","Connect remote Fusion server")}),t.jsx("p",{className:"onboarding-helper-text",children:c("setup.remoteServerNote","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:c("setup.profileName","Profile name")}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:dt,onChange:Q=>Fe(Q.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-server-url",className:"onboarding-apikey-field-label",children:c("setup.serverUrl","Server URL")}),t.jsx("input",{id:"onboarding-shell-server-url",className:"input",placeholder:c("setup.serverUrlPlaceholder","https://your-fusion-host"),value:nt,onChange:Q=>Nt(Q.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-token",className:"onboarding-apikey-field-label",children:c("setup.authTokenOptional","Auth token (optional)")}),t.jsx("input",{id:"onboarding-shell-token",className:"input",type:"password",value:Ft,onChange:Q=>ze(Q.target.value)}),Ht&&t.jsx("small",{className:"field-error",children:Ht}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Vt?.openConnectionManager(),children:c("setup.openManager","Open manager")}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void Ts(),disabled:!nt.trim()||it,children:it?c("setup.savingRemoteServer","Saving…"):c("setup.saveRemoteServer","Save remote server")})]})]}),!de&&L.length>0&&(()=>{const Q=L.filter(Wt=>Wt.id!=="github"&&Wt.authenticated).length,Qe=L.filter(Wt=>Wt.id!=="github").length,vt=Object.keys(_t).filter(Wt=>!L.find(hn=>hn.id===Wt)?.authenticated).length;if(Qe===0)return null;let xt="onboarding-provider-summary",zt="";return Q>0?(xt+=" onboarding-provider-summary--connected",zt=c("setup.providersConnectedSummary","✓ {{connected}} of {{total}} providers connected",{connected:Q,total:Qe})):vt>0?(xt+=" onboarding-provider-summary--skipped",zt=vt===1?c("setup.providersSkippedSummary_one","{{count}} provider skipped",{count:vt}):c("setup.providersSkippedSummary_other","{{count}} providers skipped",{count:vt})):(xt+=" onboarding-provider-summary--none",zt=c("setup.noProvidersConnectedYet","No providers connected yet")),t.jsx("div",{className:xt,"data-testid":"provider-summary",children:zt})})(),t.jsx(fr,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(ea,{summary:c("setup.whatAreAiProviders","What are AI providers?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatAreAiProvidersBody","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.")})}),L.length>0&&!L.some(Q=>Q.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:c("setup.skipProviderHint","Skip this step if you'd like — you can always add providers later from Settings.")}),de?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(Et,{size:24,className:"animate-spin"}),t.jsx("span",{children:c("setup.loadingProviders","Loading providers…")})]}):L.length===0?t.jsx("div",{className:"model-onboarding-empty",children:c("setup.noProvidersConfigured","No AI providers are configured. Please check your Fusion configuration.")}):t.jsxs(t.Fragment,{children:[t.jsx(fr,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{sn()}}}),t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:c("setup.quickStartProviders","Quick start providers")}),mi.length>0?t.jsx("div",{className:"model-onboarding-providers",children:mi.map(Q=>Zt(Q))}):t.jsx("p",{className:"onboarding-helper-text",children:c("setup.noQuickStartProviders","No quick-start providers are available in this environment.")})]}),zs.length>0&&t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:c("setup.connectedProviders","Connected providers")}),t.jsx("div",{className:"model-onboarding-providers",children:zs.map(Q=>Zt(Q))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:c("setup.defaultModelOptional","Default Model (Optional)")}),t.jsx("p",{className:"model-onboarding-description",children:c("setup.defaultModelDescription","Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost.")}),t.jsx(ea,{summary:c("setup.howDoIChooseModel","How do I choose a model?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.howDoIChooseModelBody","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.")})}),qe.length===0?t.jsx("div",{className:"model-onboarding-empty",children:c("setup.noModelsAvailable","No models available yet. Connect a provider above to see model options.")}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx(wi,{models:qe,value:te,onChange:ps,placeholder:c("setup.selectDefaultModel","Select a default model…"),label:c("setup.defaultModelLabel","Default model")})}),te&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:[c("setup.selectedModel","Selected:")," "," ",qe.find(Q=>Q.id===te)?.name??te]})})]}),t.jsx(ea,{summary:c("setup.advancedProviderSettings","Advanced provider settings"),className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[Qn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Qn.map(Q=>Zt(Q))}):t.jsx("p",{className:"onboarding-helper-text",children:c("setup.allProvidersShown","All currently available providers are already shown above.")}),je.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:je.map(Q=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(hs,{provider:Q.id,size:"sm"}),t.jsx("span",{children:Q.name||Q.id})]},Q.id))}):null,Ce?t.jsx(x8,{onSave:Kt,onCancel:()=>{We(!1),Ke(void 0)},saving:ke,error:Ze}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>We(!0),children:c("setup.addCustomProvider","Add custom provider")})]})}),Ge&&t.jsx(ea,{summary:c("setup.howDoesLoginWork","How does login work?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.howDoesLoginWorkBody","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.")})}),tt&&t.jsx(ea,{summary:c("setup.whatIsApiKey","What is an API key?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatIsApiKeyBody","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(fr,{slotId:"onboarding-setup-help",projectId:s})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[Pn?t.jsx("p",{className:"model-onboarding-description",children:zn?c("setup.githubCliAlreadyAuth","GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed."):c("setup.githubConnected","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:c("setup.githubConnectionDescription","Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it.")}),!Pn&&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:c("setup.withoutGitHubHeading","Without GitHub (available now):")})}),t.jsx("li",{className:"onboarding-helper-text",children:c("setup.withoutGitHub1","Create tasks manually")}),t.jsx("li",{className:"onboarding-helper-text",children:c("setup.withoutGitHub2","Describe work for AI agents")}),t.jsx("li",{className:"onboarding-helper-text",children:c("setup.withoutGitHub3","Track progress on the board")}),t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:c("setup.withGitHubHeading","With GitHub (after connecting):")})}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:c("setup.withGitHub1","Import issues as tasks")}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:c("setup.withGitHub2","Sync pull request status")}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:c("setup.withGitHub3","Link code changes to tasks")})]})}),ss&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:c("setup.noAiProviderConnected","No AI provider connected")}),t.jsx("p",{children:c("setup.noAiProviderBody","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(ea,{summary:c("setup.whatDoesGitHubIntegrationDo","What does GitHub integration do?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatDoesGitHubIntegrationDoBody","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.")})}),On?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(ai,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Yn,{status:rn})})]}),xn&&(P==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.loggingOut","Logging out…")}):t.jsx("button",{className:"btn btn-sm",onClick:()=>gn("github"),children:c("setup.disconnect","Disconnect")}))]}),(rn==="not-connected"||rn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[P==="github"||Vn?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:c("setup.waitingForLogin","Waiting for login…")}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void yt("github"),children:c("setup.cancelLogin","Cancel")})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>G("github"),children:[t.jsx(ai,{size:16}),c("setup.connect","Connect")]}),(P==="github"||Vn)&&T.github&&t.jsx(rh,{instructions:T.github,"data-testid":"onboarding-login-instructions-github"})]}),rn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:zn?c("setup.githubCliAuthSuccess","GitHub CLI is authenticated. Imports and pull request tracking are available. Connect OAuth in Settings → Authentication if you want dashboard-managed sign-in controls."):c("setup.githubOauthConnected","GitHub OAuth is connected. You can import issues and track pull requests.")}),rn==="failed"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[t.jsx("p",{children:c("setup.githubConnectionFailed","Connection failed or timed out.")}),t.jsxs("div",{className:"onboarding-github-feedback-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>G("github"),children:c("setup.retry","Retry")}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Xn,children:c("setup.skipForNow","Skip for now")})]})]}),rn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:c("setup.waitingForGitHubAuth","Waiting for GitHub authorization…")}),rn==="skipped"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[t.jsx("p",{children:c("setup.githubSkipped","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:()=>G("github"),children:c("setup.connectAnyway","Connect anyway")})})]}),rn==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:c("setup.connectGitHubAnytime","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(hs,{provider:"github",size:"lg"})}),zn?t.jsx("p",{children:c("setup.githubCliAuthNote","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:c("setup.githubOauthNotConnected","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:()=>k("project-setup"),children:zn?c("setup.continueWithGhCli","Continue with gh CLI auth →"):c("setup.continueWithoutGitHub","Continue without GitHub →")}),zn&&(P==="github"||Vn?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(Et,{size:14,className:"onboarding-spinner"}),c("setup.waitingForOauthLogin","Waiting for OAuth login…")]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>G("github"),children:[t.jsx(hs,{provider:"github",size:"sm"}),c("setup.connectOauthOptional","Connect OAuth (optional)")]}))]}),zn&&(P==="github"||Vn)&&T.github&&t.jsx(rh,{instructions:T.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:c("setup.projectSetupDescription","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.")}),Xt?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:c("setup.projectSelected","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:c("setup.projectRequired","A project is required before first-task actions are available.")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:c("setup.setUpProject","Set Up Project")}),t.jsx("p",{className:"onboarding-helper-text",children:c("setup.setupWizardHint","In the setup wizard, pick an existing directory or paste a GitHub clone URL.")})]}),t.jsx(ea,{summary:c("setup.whatDoesProjectSetupDo","What does project setup do?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatDoesProjectSetupDoBody","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:c("setup.firstTaskDescription","Create your first task to start the board and launch AI execution.")}),C&&ei?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Es,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:c("setup.firstTaskReady","Your first task is ready!")}),t.jsx("div",{className:"onboarding-task-created__task-id",children:ei.id}),Mi&&t.jsx("p",{className:"onboarding-task-created__description",children:Mi}),t.jsx("p",{className:"onboarding-task-created__hint",children:c("setup.taskCreatedHint","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:Ut,children:c("setup.viewTask","View Task")}),t.jsx("button",{type:"button",className:"btn",onClick:$t,children:c("setup.goToDashboard","Go to Dashboard")})]})]}):t.jsxs(t.Fragment,{children:[Xt?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:c("setup.describeFirstTask","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:F,onChange:Q=>{M(Q.target.value),N(null)},placeholder:c("setup.firstTaskPlaceholder","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:Se,disabled:D,"data-testid":"onboarding-first-task-submit",children:D?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:16,className:"animate-spin"}),t.jsx("span",{children:c("setup.creatingTask","Creating task…")})]}):c("setup.createFirstTask","Create First Task")})})]}),V&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:V}),t.jsx("p",{className:"onboarding-helper-text",children:c("setup.taskErrorHint","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:c("setup.projectMustBeSelected","A project must be selected before you can create tasks or import from GitHub.")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:c("setup.setUpProject","Set Up Project")})]}),t.jsx(nH,{items:rs}),Xt&&t.jsxs(t.Fragment,{children:[t.jsx(ea,{summary:c("setup.whatHappensWhenCreateTask","What happens when I create a task?"),children:t.jsx("p",{className:"onboarding-helper-text",children:c("setup.whatHappensWhenCreateTaskBody","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:ut,disabled:se,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ys,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:c("setup.createNewTask","Create a New Task")}),t.jsx("span",{children:c("setup.createNewTaskSubtitle","Describe what you need built and AI will work on it")})]})]}),t.jsxs("button",{className:`onboarding-cta-card${Pn?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:It,disabled:se||!Pn,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ai,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:c("setup.importFromGitHub","Import from GitHub")}),t.jsx("span",{children:c("setup.importFromGitHubSubtitle","Turn GitHub issues into tasks you can track here")}),!Pn&&t.jsx("small",{className:"onboarding-cta-note",children:c("setup.requiresGitHubConnection","Requires GitHub connection")})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:[c("setup.createTasksAnytimeNote","You can create tasks anytime from the board, or use")," "," ",t.jsx("code",{children:"fn task create"})," ",c("setup.createTasksAnytimeNoteTerminal","in the terminal.")]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Es,{size:48,className:"success-icon"}),t.jsx("p",{children:c("setup.setupComplete","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:ht,disabled:se,children:c("setup.skipForNow","Skip for now")}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:an,children:c("setup.skipSetup","Skip setup →")}),t.jsx("button",{className:"btn btn-primary",onClick:At,children:c("setup.next","Next →")})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Wn,children:c("setup.back","← Back")}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:an,children:c("setup.skipGitHub","Skip GitHub →")}),t.jsx("button",{className:"btn btn-primary",onClick:At,children:c("setup.next","Next →")})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Wn,children:c("setup.back","← Back")}),t.jsx("button",{className:"btn btn-primary",onClick:At,disabled:!Xt,children:c("setup.next","Next →")})]}),x==="first-task"&&!C&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Wn,children:c("setup.back","← Back")}),t.jsx("button",{className:"btn btn-primary",onClick:ae,disabled:se,children:se?t.jsxs(t.Fragment,{children:[t.jsx(Et,{size:16,className:"animate-spin"}),t.jsx("span",{children:c("setup.saving","Saving…")})]}):c("setup.finishSetup","Finish Setup")})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:et,children:[t.jsx(Es,{size:16}),t.jsx("span",{children:c("setup.getStarted","Get Started")})]})]})]})})}function JN({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))})}function rH({isOpen:e,onClose:n,groupId:s,projectId:i,onOpenMemberTask:r}){const{t:o}=st("app"),[l,d]=a.useState(null),[c,m]=a.useState(!1),[p,h]=a.useState(!1),[u,f]=a.useState(!1),[b,y]=a.useState(null),v=a.useCallback(async()=>{if(s){m(!0);try{const j=await Vk(s,i);d(j.group),y(null)}catch(j){y(j instanceof Error?j.message:o("groupTask.errorLoading","Failed to load branch group"))}finally{m(!1)}}},[s,i]);a.useEffect(()=>{!e||!s||v()},[s,e,v]),a.useEffect(()=>{if(!e||!s)return;const j=i?`?projectId=${encodeURIComponent(i)}`:"";return li(`/api/events${j}`,{events:{"task:updated":S=>{try{const C=JSON.parse(S.data);if(i&&C.projectId&&C.projectId!==i)return}catch{}v()}},onReconnect:()=>{v()}})},[s,e,v,i]);const x=a.useMemo(()=>l?o("groupTask.completionText","{{landed}} of {{total}} members finished",{landed:l.completion.landed,total:l.completion.total}):"",[l,o]),k=a.useMemo(()=>!l||l.completion.total<=0?0:l.completion.landed/l.completion.total*100,[l]),w=a.useCallback(async()=>{if(s){h(!0);try{await qk(s,i),await v()}finally{h(!1)}}},[s,v,i]),g=a.useCallback(async()=>{if(s){f(!0);try{await Wk(s,i),await v()}finally{f(!1)}}},[s,v,i]);return!e||!s?null:t.jsx("div",{className:"modal-overlay open",onClick:n,children:t.jsxs("div",{className:"modal modal-lg group-task-modal",role:"dialog","aria-modal":"true","aria-label":o("groupTask.ariaLabel","Branch group details"),onClick:j=>j.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:o("groupTask.title","Branch Group {{id}}",{id:s})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":o("actions.closeModal","Close modal"),children:t.jsx(Fn,{})})]}),t.jsxs("div",{className:"modal-body group-task-modal-body",children:[c&&t.jsxs("div",{className:"card group-task-modal-state",children:[t.jsx(Et,{className:"spin"})," ",o("groupTask.loading","Loading branch group…")]}),!c&&b&&t.jsx("div",{className:"card group-task-modal-state group-task-modal-error",children:b}),!c&&!b&&!l&&t.jsx("div",{className:"card group-task-modal-state",children:o("groupTask.unavailable","Branch group unavailable")}),!c&&!b&&l&&t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"card group-task-modal-summary",children:[t.jsxs("div",{className:"group-task-modal-summary-row",children:[t.jsx("span",{className:"group-task-modal-label",children:o("groupTask.sharedBranch","Shared branch")}),t.jsx("strong",{children:l.branchName})]}),t.jsxs("div",{className:"group-task-modal-summary-row",children:[t.jsx("span",{className:"group-task-modal-label",children:o("groupTask.status","Status")}),t.jsx("span",{className:"badge",children:l.status})]}),t.jsx("div",{className:"group-task-modal-progress-text",children:x}),t.jsx("div",{className:"branch-group-card-progress",role:"progressbar","aria-valuenow":l.completion.landed,"aria-valuemin":0,"aria-valuemax":l.completion.total,children:t.jsx("span",{className:"branch-group-card-progress-fill",style:{width:`${k}%`}})})]}),t.jsxs("section",{className:"card group-task-modal-members-card",children:[t.jsx("h3",{children:o("groupTask.members","Members")}),t.jsx("ul",{className:"group-task-modal-members",children:l.members.map(j=>t.jsxs("li",{className:"group-task-modal-member",children:[t.jsx("span",{className:`status-dot ${j.landed?"status-dot--online":"status-dot--pending"}`}),t.jsxs("span",{className:"group-task-modal-member-main",children:[j.taskId," · ",j.title]}),t.jsx("span",{className:"badge",children:j.column}),t.jsx("span",{className:"group-task-modal-member-status",children:j.landed?t.jsx(gc,{}):t.jsx(yk,{})}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>r(j.taskId),children:o("groupTask.openTask","Open task")})]},j.taskId))})]}),l.prUrl&&t.jsx("section",{className:"card group-task-modal-pr",children:t.jsxs("a",{className:"btn",href:l.prUrl,target:"_blank",rel:"noreferrer",children:["PR #",l.prNumber??"—"," (",l.prState,") ",t.jsx(Vo,{})]})}),(l.prState==="merged"||l.prState==="closed")&&t.jsx("section",{className:"card group-task-modal-actions",children:t.jsx("span",{className:"badge",children:l.prState==="merged"?o("groupTask.prMerged","Group PR merged"):o("groupTask.prClosed","Group PR closed")})}),(l.completion.complete||l.prState==="open")&&l.prState!=="merged"&&l.prState!=="closed"&&t.jsxs("section",{className:"card group-task-modal-actions",children:[l.completion.complete&&(l.autoMerge?t.jsx("span",{className:"badge",children:o("groupTask.autoMergeEnabled","Auto-merge enabled")}):t.jsxs("button",{type:"button",className:"btn",onClick:()=>void w(),disabled:p,children:[p?t.jsx(Et,{className:"spin"}):null,l.prState==="none"?o("groupTask.openPR","Open PR"):o("groupTask.mergeIntoMain","Merge group into main")]})),l.prState==="open"&&t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void g(),disabled:u,children:[u?t.jsx(Et,{className:"spin"}):null,o("groupTask.abandonGroup","Abandon group")]})]})]})]})]})})}const oH=a.lazy(()=>ln(()=>import("./SetupWizardModal-Db-Rxinm.js"),__vite__mapDeps([20,1,21,4,22,23,24,5,6,2,3,7,25])).then(e=>({default:e.SetupWizardModal}))),lH=a.lazy(()=>ln(()=>import("./SettingsModal-BAzm2kYd.js"),__vite__mapDeps([26,1,4,27,5,6,2,3,7,28,12,13,29,30,31,32])).then(e=>({default:e.SettingsModal}))),cH=a.lazy(()=>ln(()=>import("./WorkflowNodeEditor-DaPyvD_R.js"),__vite__mapDeps([33,1,5,4,6,34,2,3,7,35])).then(e=>({default:e.WorkflowNodeEditor})));function dH(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{ln(()=>import("./SettingsModal-BAzm2kYd.js"),__vite__mapDeps([26,1,4,27,5,6,2,3,7,28,12,13,29,30,31,32]))},{timeout:1500})}function uH({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:d,projectActions:c,taskHandlers:m,taskOperations:p,deepLink:h,settings:u,onSettingsClose:f,onReopenOnboarding:b,onOpenApprovals:y}){const{pushNav:v,removeNav:x}=Mf(),[k,w]=a.useState(null),g=d.detailTask?(()=>{const q=n.find(ce=>ce.id===d.detailTask?.id);return q?"prompt"in d.detailTask?{...d.detailTask,...q,prompt:d.detailTask.prompt,log:d.detailTask.log}:q:d.detailTask})():null,j=f??d.closeSettings,S=a.useCallback(()=>{x(d.closeDetailTask),h.handleDetailClose()},[h,d.closeDetailTask,x]),C=a.useCallback(()=>{x(d.closeGroupModal),d.closeGroupModal()},[d.closeGroupModal,x]),E=a.useCallback(()=>{x(j),j()},[j,x]),F=a.useCallback(()=>{x(d.closeGitHubImport),d.closeGitHubImport()},[d.closeGitHubImport,x]),M=a.useCallback(()=>{x(d.closePlanning),d.closePlanning()},[d.closePlanning,x]),D=a.useCallback(()=>{x(d.closeSubtask),d.closeSubtask()},[d.closeSubtask,x]),_=a.useCallback(()=>{x(d.closeTerminal),d.closeTerminal()},[d.closeTerminal,x]),V=a.useCallback(()=>{x(d.closeScripts),d.closeScripts()},[d.closeScripts,x]),N=a.useCallback(()=>{x(d.closeFiles),d.closeFiles()},[d.closeFiles,x]),$=a.useCallback(()=>{x(d.closeTodos),d.closeTodos()},[d.closeTodos,x]),R=a.useCallback(()=>{x(d.closeUsage),d.closeUsage()},[d.closeUsage,x]),L=a.useCallback(()=>{x(d.closeSystemStats),d.closeSystemStats()},[d.closeSystemStats,x]),O=a.useCallback(()=>{x(d.closeSchedules),d.closeSchedules()},[d.closeSchedules,x]),J=a.useCallback(()=>{x(d.closeNewTask),d.closeNewTask()},[d.closeNewTask,x]),A=a.useCallback(()=>{x(d.closeActivityLog),d.closeActivityLog()},[d.closeActivityLog,x]),de=a.useCallback(()=>{x(d.closeGitManager),d.closeGitManager()},[d.closeGitManager,x]),B=a.useCallback(()=>{x(d.closeWorkflowEditor),d.closeWorkflowEditor()},[d.closeWorkflowEditor,x]),P=a.useCallback(()=>{x(d.closeAgents),d.closeAgents()},[d.closeAgents,x]),Z=a.useCallback(()=>{x(d.closeSetupWizard),d.closeSetupWizard()},[d.closeSetupWizard,x]),T=a.useCallback(()=>{d.openNewTask()},[d]),ie=a.useCallback(()=>{d.openGitHubImport()},[d]),le=a.useCallback((q,ce)=>{d.openDetailTask(q,ce),v({type:"modal",close:d.closeDetailTask})},[d,v]),be=a.useCallback(q=>{d.openGroupModal(q),v({type:"modal",close:d.closeGroupModal})},[d,v]),Le=a.useCallback(q=>{w(null),d.closeModelOnboarding(),le(q)},[d,le]),xe=a.useCallback(async q=>{const ce=await m.handleModalCreate(q);return d.modelOnboardingOpen&&w(ce),ce},[m.handleModalCreate,d.modelOnboardingOpen]);return a.useEffect(()=>{!d.modelOnboardingOpen&&k&&w(null)},[d.modelOnboardingOpen,k]),a.useEffect(()=>{dH()},[]),t.jsxs(t.Fragment,{children:[g&&t.jsx(ir,{children:t.jsx(m6,{task:g,projectId:e,tasks:n,onClose:S,onOpenDetail:le,mobileHeaderMode:d.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:p.moveTask,onDeleteTask:p.deleteTask,onMergeTask:p.mergeTask,onArchiveTask:p.archiveTask,onRetryTask:p.retryTask,onResetTask:p.resetTask,onDuplicateTask:p.duplicateTask,onTaskUpdated:d.updateDetailTask,addToast:r,prAuthAvailable:u.prAuthAvailable,onOpenWorkflowEditor:()=>d.openWorkflowEditor(),initialTab:d.detailTaskInitialTab})}),d.groupModalGroupId&&t.jsx(ir,{children:t.jsx(rH,{isOpen:!!d.groupModalGroupId,onClose:C,groupId:d.groupModalGroupId,projectId:e,onOpenMemberTask:q=>{const ce=n.find(De=>De.id===q);ce&&le(ce)}})}),d.settingsOpen&&t.jsx(ir,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(lH,{onClose:E,addToast:r,initialSection:d.settingsInitialSection,projectId:e,themeMode:u.themeMode,colorTheme:u.colorTheme,onThemeModeChange:u.setThemeMode,onColorThemeChange:u.setColorTheme,dashboardFontScalePct:u.dashboardFontScalePct,onDashboardFontScaleChange:u.setDashboardFontScalePct,onReopenOnboarding:b,onOpenApprovals:y,onOpenWorkflowSettings:()=>{E(),d.openWorkflowEditor("settings")}})})}),t.jsx(I3,{isOpen:d.githubImportOpen,onClose:F,onImport:m.handleGitHubImport,tasks:n,projectId:e}),t.jsx(ir,{children:t.jsx(U3,{isOpen:d.isPlanningOpen,onClose:M,onTaskCreated:m.handlePlanningTaskCreated,onTasksCreated:m.handlePlanningTasksCreated,tasks:n,initialPlan:d.planningInitialPlan??void 0,projectId:e,resumeSessionId:d.planningResumeSessionId})}),t.jsx(ir,{children:t.jsx(Q3,{isOpen:d.isSubtaskOpen,onClose:D,initialDescription:d.subtaskInitialDescription??"",onTasksCreated:m.handleSubtaskTasksCreated,projectId:e,resumeSessionId:d.subtaskResumeSessionId,onOpenGroupModal:be})}),t.jsx(k5,{isOpen:d.terminalOpen,onClose:_,initialCommand:d.terminalInitialCommand,projectId:e}),t.jsx(j5,{isOpen:d.scriptsOpen,onClose:V,addToast:r,onRunScript:d.runScript,projectId:e}),d.filesOpen&&t.jsx(G5,{initialWorkspace:d.fileBrowserWorkspace,initialFile:d.fileBrowserInitialFile,isOpen:!0,onClose:N,onWorkspaceChange:d.setFileWorkspace,projectId:e}),d.todosOpen&&t.jsx(J5,{isOpen:!0,onClose:$,addToast:r,projectId:e,onPlanningMode:d.openPlanningWithInitialPlan}),t.jsx(oU,{isOpen:d.usageOpen,onClose:R,projectId:e,anchorRect:d.usageAnchorRect}),t.jsx(IU,{isOpen:d.systemStatsOpen,onClose:L,projectId:e}),d.schedulesOpen&&t.jsx(NU,{onClose:O,addToast:r,projectId:e}),t.jsx(ir,{children:t.jsx(EU,{isOpen:d.newTaskModalOpen,onClose:J,tasks:n,onCreateTask:xe,addToast:r,projectId:e})}),t.jsx(zU,{isOpen:d.activityLogOpen,onClose:A,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:q=>{const ce=n.find(De=>De.id===q);ce&&le(ce)}}),t.jsx(ir,{children:t.jsx(UU,{isOpen:d.gitManagerOpen,onClose:de,tasks:n,addToast:r,projectId:e})}),d.workflowEditorOpen&&t.jsx(ir,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(cH,{isOpen:d.workflowEditorOpen,onClose:B,addToast:r,projectId:e,initialPanel:d.workflowEditorInitialPanel,initialAction:d.workflowEditorInitialAction,initialWorkflowId:d.workflowEditorInitialWorkflowId})})}),t.jsx(d8,{isOpen:d.agentsOpen,onClose:P,addToast:r,projectId:e}),d.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(oH,{onProjectRegistered:c.handleSetupComplete,onClose:Z})}),d.modelOnboardingOpen&&t.jsx(aH,{onComplete:c.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:c.handleAddProject,onOpenNewTask:T,onOpenGitHubImport:ie,firstCreatedTask:k,onViewTask:Le}),t.jsx(JN,{toasts:o,onRemove:l})]})}function mH(){return typeof window>"u"?!1:typeof window.fusionShell?.resetDesktopMode=="function"}async function hH(){const e=typeof window<"u"?window.fusionShell:void 0;try{await e?.resetDesktopMode?.()}catch{}const n=new URL(window.location.href);n.searchParams.delete("serverBaseUrl"),n.searchParams.delete("shellMode"),window.location.replace(n.toString())}function pH({errorMessage:e,isRetrying:n,onRetry:s,onManageConnection:i}){const{t:r}=st("app"),o=mH();return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:r("backend.connectionError","Can't reach the Fusion backend")}),t.jsx("p",{className:"settings-muted",children:r("backend.couldNotLoad","Fusion couldn't load your projects right now. Please make sure the backend is running and try again.")}),t.jsx("p",{className:"settings-muted",children:r("backend.error","Error: {{error}}",{error:e})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?r("backend.retrying","Retrying…"):r("backend.retryConnection","Retry Connection")}),o&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void hH(),children:r("backend.changeLaunchMode","Change Launch Mode…")}),i&&t.jsx("button",{type:"button",className:"btn",onClick:i,children:r("backend.manageConnection","Manage Connection")})]})]})}const gp=[{id:"projects",label:"dashboard.loaderSteps.projects"},{id:"project",label:"dashboard.loaderSteps.project"},{id:"tasks",label:"dashboard.loaderSteps.tasks"}];function fH(e,n){if(n==="ready")return"done";const s=gp.findIndex(r=>r.id===n),i=gp.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function gH({stage:e}){const{t:n}=st("app"),[s]=a.useState(()=>{const i=b_();return i&&(vs(Tn.TASKS_PREFIX),vs(Tn.PROJECTS),vs(Tn.CURRENT_PROJECT_ID),vs(Tn.AGENTS),vs(Tn.AGENT_STATS),vs(Tn.DOCUMENTS_PREFIX),vs(Tn.TODO_LISTS_PREFIX),vs(Tn.CHAT_ROOMS),vs(Tn.ACTIVE_CHAT_ROOM_ID),vs(Tn.CHAT_SESSIONS_PREFIX),vs(Tn.CHAT_MESSAGES_PREFIX),vs(Tn.CHAT_AGENTS_MAP_PREFIX),vs(Tn.MODELS),vs(Tn.DISCOVERED_SKILLS_PREFIX),vs(Tn.INSIGHTS_PREFIX),vs(Tn.INSIGHT_LATEST_RUN_PREFIX),vs(Tn.RESEARCH_RUNS_PREFIX),vs(Tn.RESEARCH_SELECTED_ID_PREFIX),vs(Tn.EVALS_RUNS_PREFIX),vs(Tn.EVALS_RESULTS_PREFIX),vs(Tn.MISSIONS_PREFIX),vs(Tn.MISSIONS_SELECTED_ID_PREFIX),vs(Tn.MAILBOX_INBOX_PREFIX),vs(Tn.MAILBOX_OUTBOX_PREFIX),vs(Tn.MAILBOX_UNREAD_COUNT_PREFIX)),i});return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":s?n("dashboard.updatingMessage","Updating Fusion dashboard"):n("dashboard.loadingMessage","Loading Fusion dashboard"),"data-stage":e,"data-version-update":s?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),s?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:n("dashboard.updatingVersion","Updating to a new frontend version...")}):t.jsx("p",{className:"dashboard-loader__message",children:n("dashboard.initializingDashboard","Initializing dashboard...")}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":n("dashboard.loadingProgress","Dashboard loading progress"),children:gp.map(i=>{const r=fH(i.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${r}`,"data-testid":`dashboard-loader-step-${i.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:r==="done"?"✓":r==="active"?t.jsx(Et,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:n(i.label,i.label==="dashboard.loaderSteps.projects"?"Loading projects":i.label==="dashboard.loaderSteps.project"?"Selecting project":"Fetching tasks")})]},i.id)})})]})})}function bH({visible:e}){const{t:n}=st("app");return t.jsx("div",{className:"top-progress-bar","data-visible":e?"true":"false",role:"progressbar","aria-busy":e,"aria-label":n("common.loading","Loading"),children:t.jsx("div",{className:"top-progress-bar__indicator"})})}const vH=5e3;function xH(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function yH(e,n,s){let i=0,r=0,o=0,l=0,d=0;for(const c of e){switch(c.column){case"in-progress":i++,Wd(c,n,s)&&o++;break;case"todo":l++;break;case"in-review":d++;break}c.blockedBy&&c.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:d}}function kH(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,d]=a.useState(!0),[c,m]=a.useState(null),p=a.useRef(null),h=a.useRef(null),u=a.useRef(!1),f=ul(),b=a.useCallback(w=>u.current&&_c(w,f.wasRecentlyHidden()),[f]),y=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{d(!0),m(null);const w=await dT(n);u.current=!0,o(w)}catch(w){if(w instanceof Error&&w.name==="AbortError")return;const g=w instanceof Error?w.message:"Failed to fetch executor stats";b(g)||m(g)}finally{d(!1)}},[n,b]);a.useEffect(()=>(y(),()=>{h.current&&h.current.abort()}),[y]),a.useEffect(()=>(p.current&&clearInterval(p.current),p.current=setInterval(()=>{y()},vH),()=>{p.current&&(clearInterval(p.current),p.current=null)}),[y]);const v=yH(e,s,i),x=xH(r.globalPause,r.enginePaused,v.runningTaskCount);return{stats:{...v,executorState:x,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:c,refresh:y}}const wH={planning:Ia,subtask:Vr,mission_interview:ri,milestone_interview:ri,slice_interview:ri,"cli-agent":ua};function jH({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{t:o}=st("app"),{confirm:l}=Yi(),[d,c]=a.useState(!1),[m,p]=a.useState(new Set),h=a.useRef(null),u=a.useRef(new Map),f=a.useRef(null),{activeTabMap:b}=pl(),y=a.useMemo(()=>so(),[]),v=a.useMemo(()=>({planning:o("backgroundTasks.typeLabel.planning","Planning"),subtask:o("backgroundTasks.typeLabel.subtask","Subtask Breakdown"),mission_interview:o("backgroundTasks.typeLabel.missionInterview","Mission Interview"),milestone_interview:o("backgroundTasks.typeLabel.milestoneInterview","Milestone Interview"),slice_interview:o("backgroundTasks.typeLabel.sliceInterview","Slice Interview"),"cli-agent":o("backgroundTasks.typeLabel.cliAgent","CLI Agent")}),[o]);if(a.useEffect(()=>{if(!d)return;const w=g=>{h.current&&!h.current.contains(g.target)&&c(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[d]),a.useEffect(()=>{const w=new Set,g=new Map;for(const j of e){const S=b.get(j.id),C=[j.status,j.updatedAt,S?.tabId??j.lockedByTab??"",S?.stale?"stale":"fresh"].join("|"),E=u.current.get(j.id);E&&E!==C&&w.add(j.id),g.set(j.id,C)}if(u.current=g,w.size!==0)return p(w),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{p(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[b,e]),e.length===0)return null;const x=e.length,k=s>0;return t.jsxs("div",{ref:h,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${k?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(w=>!w),title:s>0?o("backgroundTasks.pillTitleWithInput","{{count}} background AI task ({{needsInput}} needs input)",{count:x,needsInput:s}):o("backgroundTasks.pillTitle","{{count}} background AI task",{count:x}),children:[n>0&&t.jsx(Et,{size:12,className:"animate-spin"}),s>0&&n===0&&t.jsx(xh,{size:12}),t.jsx("span",{children:o("backgroundTasks.pillLabel","AI {{count}}",{count:x})})]}),d&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:o("backgroundTasks.popoverHeader","Background Tasks")}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(w=>{const g=wH[w.type],j=w.status==="generating",S=w.status==="awaiting_input",C=w.status==="error",E=b.get(w.id),F=E?.tabId??w.lockedByTab??null,M=!!(F&&F!==y&&!E?.stale),D=m.has(w.id);return t.jsxs("div",{className:`background-tasks-indicator__item${D?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:D?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:D?"translateY(-1px)":void 0},onClick:async()=>{M&&!await l({title:o("backgroundTasks.confirmTitle","Open Active Session"),message:o("backgroundTasks.confirmMessage","This session is active in another tab. Open anyway?")})||(i(w),c(!1))},children:[C?t.jsx(oi,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(g,{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:w.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?o("backgroundTasks.status.failed","Failed"):v[w.type],j&&` — ${o("backgroundTasks.status.generating","generating...")}`,S&&!M&&` — ${o("backgroundTasks.status.needsInput","needs input")}`,S&&M&&` — ${o("backgroundTasks.status.activeElsewhere","active in another tab")}`]})]}),j&&t.jsx(Et,{size:14,className:"background-tasks-indicator__session-icon animate-spin",style:{color:"var(--color-success)"}}),S&&!M&&t.jsx(xh,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),S&&M&&t.jsx(ll,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:_=>{_.stopPropagation(),r(w.id)},title:o("backgroundTasks.dismissButton","Dismiss"),children:t.jsx(Fn,{size:12})})]},w.id)})})]})]})}function NH(e,n){if(!e)return n("executor.noActivity","no activity");const s=Date.now(),i=new Date(e).getTime(),r=s-i,o=Math.floor(r/1e3),l=Math.floor(o/60),d=Math.floor(l/60),c=Math.floor(d/24);return c>0?n("executor.daysAgo","{{count}}d ago",{count:c}):d>0?n("executor.hoursAgo","{{count}}h ago",{count:d}):l>0?n("executor.minutesAgo","{{count}}m ago",{count:l}):o>10?n("executor.secondsAgo","{{count}}s ago",{count:o}):n("executor.justNow","just now")}function SH(e,n){switch(e){case"running":return{label:n("executor.stateRunning","Running"),color:"var(--color-success)",icon:Ds};case"paused":return{label:n("executor.statePaused","Paused"),color:"var(--triage)",icon:ia};case"idle":default:return{label:n("executor.stateIdle","Idle"),color:"var(--text-muted)",icon:Ws}}}function CH({tasks:e,projectId:n,taskStuckTimeoutMs:s,staleHighFanoutBlockerAgeThresholdMs:i,backgroundSessions:r,backgroundGenerating:o,backgroundNeedsInput:l,onOpenBackgroundSession:d,onDismissBackgroundSession:c,lastFetchTimeMs:m,currentProjectPath:p,onOpenProjectDirectory:h,keyboardOpen:u,hideWhenKeyboardOpen:f}){const{t:b}=st("app"),{stats:y,loading:v,error:x}=kH(e,n,s,m),[k,w]=a.useState(!1),g=a.useMemo(()=>SH(y.executorState,b),[y.executorState,b]),j=a.useMemo(()=>NH(y.lastActivityAt,b),[y.lastActivityAt,b]),S=a.useMemo(()=>{const E=Jp(e,{staleHighFanoutAgeThresholdMs:i??Pk});return Array.from(E.entries()).map(([M,D])=>({blockerId:M,entry:D})).filter(({entry:M})=>M.isHighFanout).sort((M,D)=>{if(D.entry.overlapBlockedTodoCount!==M.entry.overlapBlockedTodoCount)return D.entry.overlapBlockedTodoCount-M.entry.overlapBlockedTodoCount;const _=M.entry.escalation?.blockingAgeMs??0,V=D.entry.escalation?.blockingAgeMs??0;return V!==_?V-_:M.blockerId.localeCompare(D.blockerId,"en",{numeric:!0,sensitivity:"base"})})[0]??null},[e,i]),C=g.icon;return f?null:x?ju(x)?t.jsx("div",{className:"executor-status-bar executor-status-bar--connecting",role:"status","aria-label":b("executor.status","Executor status"),children:t.jsxs("span",{className:"executor-status-bar__connecting",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--connecting executor-status-bar__indicator--active","aria-hidden":"true"}),b("executor.connecting","Connecting…")]})}):t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":b("executor.status","Executor status"),children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(oa,{size:14}),x]})}):v&&y.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":b("executor.status","Executor status"),children:t.jsx("span",{className:"executor-status-bar__loading-text",children:b("executor.loading","Loading...")})}):t.jsxs("div",{className:`executor-status-bar ${y.executorState==="running"?"executor-status-bar--running":""}${u?" executor-status-bar--keyboard-open":""}`,role:"status","aria-label":b("executor.status","Executor status"),children:[r&&r.length>0&&d&&c&&t.jsxs(t.Fragment,{children:[t.jsx(jH,{sessions:r,generating:o??0,needsInput:l??0,onOpenSession:d,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:b("executor.queued","Queued")}),t.jsx("span",{className:"executor-status-bar__count",children:y.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 ${y.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:b("executor.running","Running")}),t.jsx("span",{className:"executor-status-bar__count",children:y.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:y.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),y.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:b("executor.stuck","Stuck")}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:y.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 ${y.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:b("executor.blocked","Blocked")}),t.jsx("span",{className:`executor-status-bar__count ${y.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:y.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:b("executor.inReview","In Review")}),t.jsx("span",{className:"executor-status-bar__count",children:y.inReviewCount})]}),S&&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:b("executor.overlapQueue","Overlap queue")}),t.jsxs("span",{className:"executor-status-bar__fanout-summary",title:b("executor.overlapBottleneck","{{status}} overlap bottleneck {{blockerId}}: {{count}} todo blocked via blockedBy (threshold {{threshold}})",{status:S.entry.escalation?b("executor.escalated","Escalated"):b("executor.temporary","Temporary"),blockerId:S.blockerId,count:S.entry.overlapBlockedTodoCount,threshold:Pp}),children:[S.blockerId," · ",S.entry.overlapBlockedTodoCount," todo",S.entry.escalation?b("executor.escalatedSuffix"," (escalated)"):""]})]})]}),p&&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${k?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>w(E=>!E),"aria-label":k?b("executor.hideProjectDir","Hide project directory"):b("executor.showProjectDir","Show project directory"),"aria-expanded":k,"data-testid":"executor-project-path-toggle",title:k?b("executor.hideProjectDir","Hide project directory"):b("executor.showProjectDir","Show project directory"),children:t.jsx(Zs,{size:12,"aria-hidden":"true"})}),k&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:h,title:p,"data-testid":"executor-project-path-link",children:p})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(ha,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:j})]}),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:g.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:g.color},children:g.label})]})]})}const _H={planning:Ia,subtask:Vr,mission_interview:ri,milestone_interview:ri,slice_interview:ri,"cli-agent":ua},Ay={planning:{key:"sessionBanner.typeLabel.planning",defaultVal:"Planning"},subtask:{key:"sessionBanner.typeLabel.subtask",defaultVal:"Subtask Breakdown"},mission_interview:{key:"sessionBanner.typeLabel.missionInterview",defaultVal:"Mission Interview"},milestone_interview:{key:"sessionBanner.typeLabel.milestoneInterview",defaultVal:"Milestone Interview"},slice_interview:{key:"sessionBanner.typeLabel.sliceInterview",defaultVal:"Slice Interview"},"cli-agent":{key:"sessionBanner.typeLabel.cliAgent",defaultVal:"CLI Agent"}},Ty={advance:{key:"sessionBanner.cli.advance",defaultVal:"Advance"},retry:{key:"sessionBanner.cli.retry",defaultVal:"Retry"},cancel:{key:"sessionBanner.cli.cancelTask",defaultVal:"Cancel task"},reauthenticate:{key:"sessionBanner.cli.reauthenticate",defaultVal:"Re-authenticate"},relaunch:{key:"sessionBanner.cli.relaunch",defaultVal:"Relaunch fresh"}},EH={userExited:{messageKey:"sessionBanner.cli.userExited",messageDefault:"Agent exited before completing",actions:["advance","retry","cancel"]},authFailed:{messageKey:"sessionBanner.cli.authFailed",messageDefault:"CLI authentication failed",actions:["reauthenticate","retry"]},"resume-exhausted":{messageKey:"sessionBanner.cli.resumeExhausted",messageDefault:"Couldn't resume the session",actions:["relaunch","cancel"]}},YN="fusion:session-banner-dismissed";function Yl(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function MH(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(YN);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[i,r]of Object.entries(n)){const o=typeof r=="number"?r:Yl(r);s.set(i,o)}return s}catch{return new Map}}function AH(e){if(!(typeof window>"u"))try{const n={};for(const[s,i]of e)n[s]=i;window.localStorage.setItem(YN,JSON.stringify(n))}catch{}}function Ry(e){return e==="awaiting_input"||e==="error"||e==="waiting_on_input"||e==="needs_attention"}const qa=MH();function TH({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i,onCliAction:r}){const{t:o}=st("app"),[l,d]=a.useState(0),c=()=>{AH(qa),d(v=>v+1)};a.useEffect(()=>{if(qa.size===0)return;const v=new Map(e.map(k=>[k.id,k]));let x=!1;for(const[k,w]of qa){const g=v.get(k);if(!g)continue;if(!Ry(g.status)){qa.delete(k),x=!0;continue}Yl(g.updatedAt)>w&&(qa.delete(k),x=!0)}x&&c()},[e]);const m=a.useMemo(()=>e.filter(v=>{if(!Ry(v.status))return!1;const x=qa.get(v.id);return x===void 0?!0:Yl(v.updatedAt)>x}),[e,l]);if(m.length===0)return null;const p=m.filter(v=>v.status==="awaiting_input"||v.status==="waiting_on_input").length,h=m.filter(v=>v.status==="error"||v.status==="needs_attention").length;let u="";p>0&&h>0?u=o(p===1?"sessionBanner.headerAwaitingAndErrorSingular":"sessionBanner.headerAwaitingAndErrorPlural",p===1?"{{awaitingCount}} AI session needs your input, {{errorCount}} failed":"{{awaitingCount}} AI sessions need your input, {{errorCount}} failed",{awaitingCount:p,errorCount:h}):p>0?u=o(p===1?"sessionBanner.headerAwaitingSingular":"sessionBanner.headerAwaitingPlural",p===1?"{{count}} AI session needs your input":"{{count}} AI sessions need your input",{count:p}):h>0&&(u=o(h===1?"sessionBanner.headerErrorSingular":"sessionBanner.headerErrorPlural",h===1?"{{count}} AI session failed":"{{count}} AI sessions failed",{count:h}));const f=v=>{qa.set(v.id,Math.max(Yl(v.updatedAt),Date.now())),c()},b=v=>{qa.delete(v.id),c(),n(v)},y=()=>{const v=Date.now();for(const x of m)qa.set(x.id,Math.max(Yl(x.updatedAt),v));c(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":o("sessionBanner.regionLabel","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(oi,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:u})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:y,children:[t.jsx(Fn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:o("sessionBanner.dismissAll","Dismiss all")})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:m.map(v=>{const x=_H[v.type],k=v.status==="error",w=v.type==="cli-agent"&&v.cliVariant?EH[v.cliVariant]:null;return w?t.jsxs("article",{className:"session-notification-banner__item session-notification-banner__item--cli session-notification-banner__item--error","data-session-type":v.type,"data-session-status":v.status,"data-cli-variant":v.cliVariant,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[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:v.title,children:v.title}),t.jsx("p",{className:"session-notification-banner__meta",children:o(w.messageKey,w.messageDefault)})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[w.actions.map(g=>t.jsx("button",{className:"session-notification-banner__resume","data-cli-action":g,onClick:()=>{r?.(v,g),(g==="cancel"||g==="advance")&&(f(v),s(v.id))},children:o(Ty[g].key,Ty[g].defaultVal)},g)),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{f(v),s(v.id)},"aria-label":o("sessionBanner.dismissItem","Dismiss {{title}}",{title:v.title}),children:t.jsx(Fn,{size:14,"aria-hidden":"true"})})]})]},v.id):t.jsxs("article",{className:`session-notification-banner__item${k?" session-notification-banner__item--error":""}`,"data-session-type":v.type,"data-session-status":v.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[k?t.jsx(oi,{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:v.title,children:v.title}),t.jsx("p",{className:"session-notification-banner__meta",children:k?o("sessionBanner.failed","Failed"):o(Ay[v.type].key,Ay[v.type].defaultVal)})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>b(v),children:k?o("sessionBanner.retry","Retry"):o("sessionBanner.resume","Resume")}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{f(v),s(v.id)},"aria-label":o("sessionBanner.dismissItem","Dismiss {{title}}",{title:v.title}),children:t.jsx(Fn,{size:14,"aria-hidden":"true"})})]})]},v.id)})})]})}const XN="fusion:cli-binary-banner-dismissed";function RH(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(XN)==="1"}catch{return!1}}function PH(){if(!(typeof window>"u"))try{window.localStorage.setItem(XN,"1")}catch{}}function IH({onOpenSettings:e}){const{t:n}=st("app"),[s,i]=a.useState(null),[r,o]=a.useState(()=>RH()),[l,d]=a.useState(!1),[c,m]=a.useState(null);a.useEffect(()=>{if(r)return;let w=!1;return GE().then(g=>{w||i(g)}).catch(()=>{}),()=>{w=!0}},[r]);const p=a.useCallback(async()=>{d(!0),m(null);try{const w=await KE();i({binary:w.binary,expectedVersion:w.expectedVersion,state:w.state,install:w.install}),w.installResult.success||m(w.installResult.permissionsHint||w.installResult.stderr||`Install failed (exit ${w.installResult.exitCode??"n/a"})`)}catch(w){m(w instanceof Error?w.message:String(w))}finally{d(!1)}},[]),h=a.useCallback(()=>{PH(),o(!0)},[]);if(r||!s||s.state==="installed"||s.state==="skipped")return null;const u=s.state==="version-mismatch",f=s.binary.version,b=s.expectedVersion,y=u?n("cli.updateTitle","Update the Fusion CLI"):n("cli.installTitle","Install the Fusion CLI"),v=u?t.jsxs(t.Fragment,{children:[n("cli.versionMismatchPrefix","Your installed")," ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," ",n("cli.versionMismatchInfix","but this dashboard expects")," "," ",t.jsxs("strong",{children:["v",b]}),". ",n("cli.versionMismatchSuffix","Update to stay in sync.")]}):t.jsx(t.Fragment,{children:n("cli.installBody","Get the {{fn}} and {{fusion}} commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell.",{fn:"fn",fusion:"fusion"})}),x=u?n("cli.updateButton","Update with npm"):n("cli.installButton","Install with npm"),k=u?n("cli.updating","Updating…"):n("cli.installing","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:y}),t.jsx("div",{className:"cli-binary-banner__text",children:v}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void p(),disabled:l,children:l?k:x}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:n("cli.openSettings","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":n("actions.dismiss","Dismiss"),onClick:h,children:t.jsx(Fn,{size:16})})]})}function DH({signal:e,onDismiss:n}){const{t:s}=st("app");return!e||!e.atRisk?null:t.jsxs("div",{className:`capacity-risk-banner${n?" capacity-risk-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsxs("div",{className:"capacity-risk-banner__content",children:[t.jsx("strong",{children:s("capacity.risk","Capacity risk:")})," ",s("capacity.status","Todo {{todoCount}} (threshold {{threshold}}) · In Progress {{inProgress}} · In Review {{inReview}} · Idle agents {{idleAgents}}",{todoCount:e.todoCount,threshold:e.threshold,inProgress:e.inProgressCount,inReview:e.inReviewCount,idleAgents:e.idleNonEphemeralAgentCount})]}),n?t.jsx("button",{type:"button",className:"capacity-risk-banner__dismiss touch-target","aria-label":s("capacity.dismiss","Dismiss capacity warning"),onClick:n,children:t.jsx(Fn,{"aria-hidden":"true"})}):null]})}function LH({isActive:e}){const{t:n}=st("app");return e?t.jsxs("div",{className:"test-mode-banner",role:"status","aria-live":"polite",children:[t.jsx(j0,{"aria-hidden":"true"}),t.jsx("span",{children:n("app.testMode","Test mode — no real AI calls")})]}):null}const QN="fusion:oauth-relogin-dismissed";function FH(){if(typeof window>"u")return new Set;try{const e=JSON.parse(window.localStorage.getItem(QN)??"[]");return Array.isArray(e)?new Set(e.filter(n=>typeof n=="string")):new Set}catch{return new Set}}function Py(e){typeof window>"u"||window.localStorage.setItem(QN,JSON.stringify(Array.from(e)))}function OH({onReLogin:e,pollIntervalMs:n}){const{t:s}=st("app"),[i,r]=a.useState([]),[o,l]=a.useState(()=>FH()),d=a.useCallback(async()=>{try{const{providers:u}=await Yo(),f=u.filter(b=>b.type==="oauth"&&b.expired===!0).map(b=>({id:b.id,name:b.name}));r(f),l(b=>{const y=new Set(f.map(x=>x.id)),v=new Set(Array.from(b).filter(x=>y.has(x)));return v.size===b.size?b:(Py(v),v)})}catch{}},[]);a.useEffect(()=>{d();const u=window.setInterval(d,n??3600*1e3);return()=>{window.clearInterval(u)}},[n,d]),a.useEffect(()=>{const u=f=>{const{detail:b}=f;b?.providerId&&r(y=>y.filter(v=>v.id!==b.providerId)),d()};return window.addEventListener(Ah,u),()=>{window.removeEventListener(Ah,u)}},[d]);const c=a.useMemo(()=>i.filter(u=>!o.has(u.id)),[o,i]);if(c.length===0)return null;const m=c.length===1,p=c.map(u=>u.name).join(", "),h=()=>{const u=new Set(o);for(const f of c)u.add(f.id);l(u),Py(u)};return t.jsxs("section",{className:"oauth-relogin-banner",role:"status","aria-live":"polite",children:[t.jsxs("div",{className:"oauth-relogin-banner__content",children:[t.jsx(oa,{"aria-hidden":"true"}),t.jsx("p",{className:"oauth-relogin-banner__message",children:m?s("auth.reloginRequired","Re-login required: {{provider}}. Your {{provider}} session expired — sign in again to keep agents running.",{provider:p}):s("auth.reloginRequiredMultiple","Re-login required: {{providers}}",{providers:p})})]}),t.jsxs("div",{className:"oauth-relogin-banner__actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>e(m?c[0]?.id:void 0),children:s("auth.relogin","Re-login")}),t.jsx("button",{type:"button",className:"btn-icon oauth-relogin-banner__dismiss","aria-label":s("actions.dismissOAuth","Dismiss OAuth re-login banner"),onClick:h,children:t.jsx(Fn,{"aria-hidden":"true"})})]})]})}function $H(e,n){switch(e){case"duplicate_active_id":return n("health.anomaly.duplicateActiveId","Duplicate active task ID");case"id_in_active_and_archived":return n("health.anomaly.idInBothStorages","Task ID present in active and archived storage");case"next_sequence_at_or_below_used":return n("health.anomaly.sequenceOverlap","Allocator next sequence overlaps an existing task ID");case"task_row_outside_known_prefix":return n("health.anomaly.unknownPrefix","Task row uses a prefix outside allocator state");default:return e}}function zH(e){return e.length<=5?e.join(", "):`${e.slice(0,5).join(", ")} +${e.length-5} more`}function BH({report:e,recommendedAction:n,onRefresh:s}){const{t:i}=st("app"),[r,o]=a.useState(!1),[l,d]=a.useState(null);if(e.status!=="anomaly")return null;const c=async()=>{o(!0),d(null);try{const m=await Bk();s?.(m.taskIdIntegrity,m.taskIdIntegrity.recommendedAction)}catch(m){d(m instanceof Error?m.message:i("health.refreshFailed","Failed to refresh integrity status."))}finally{o(!1)}};return t.jsxs("section",{className:"task-id-integrity-banner",role:"alert","aria-live":"assertive",children:[t.jsxs("div",{className:"task-id-integrity-banner__header",children:[t.jsxs("div",{className:"task-id-integrity-banner__headline-wrap",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx(oa,{"aria-hidden":"true"}),t.jsx("h2",{className:"task-id-integrity-banner__headline",children:i("health.anomalyDetected","Task ID integrity anomaly detected")})]}),t.jsxs("button",{type:"button",className:"btn btn-sm task-id-integrity-banner__refresh",onClick:()=>{c()},disabled:r,children:[t.jsx(xs,{className:r?"task-id-integrity-banner__refresh-icon task-id-integrity-banner__refresh-icon--spinning":"task-id-integrity-banner__refresh-icon","aria-hidden":"true"}),r?i("health.rechecking","Re-checking…"):i("health.recheck","Re-check")]})]}),t.jsx("p",{className:"task-id-integrity-banner__body",children:i("health.anomalyBody","Fusion found allocator state that can cause task IDs to be reused or overwrite live task records.")}),t.jsx("ul",{className:"task-id-integrity-banner__list",children:e.anomalies.map(m=>t.jsxs("li",{className:"task-id-integrity-banner__item",children:[t.jsx("strong",{className:"task-id-integrity-banner__item-title",children:$H(m.kind,i)}),t.jsx("span",{className:"task-id-integrity-banner__item-detail",children:m.details}),t.jsx("code",{className:"task-id-integrity-banner__ids",children:zH(m.affectedIds)})]},`${m.kind}:${m.prefix}:${m.affectedIds.join(",")}`))}),t.jsx("p",{className:"task-id-integrity-banner__footer",children:n}),l?t.jsx("p",{className:"task-id-integrity-banner__error",children:l}):null]})}function UH({errors:e,lastCheckedAt:n,onRefresh:s,refreshing:i,refreshError:r}){const{t:o}=st("app");if(e.length===0)return null;const l=e.slice(0,5),d=n?new Date(n).toLocaleString():null;return t.jsxs("section",{className:"db-corruption-banner",role:"alert","aria-live":"assertive",children:[t.jsxs("div",{className:"db-corruption-banner__header",children:[t.jsxs("div",{className:"db-corruption-banner__headline-wrap",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx(oa,{"aria-hidden":"true"}),t.jsxs("div",{className:"db-corruption-banner__headline-copy",children:[t.jsx("h2",{className:"db-corruption-banner__headline",children:o("dbBanner.title","Database corruption detected")}),d?t.jsx("p",{className:"db-corruption-banner__meta",children:o("dbBanner.lastChecked","Last checked: {{checkedAtLabel}}",{checkedAtLabel:d})}):null]})]}),t.jsxs("button",{type:"button",className:"btn btn-sm db-corruption-banner__refresh",onClick:()=>{s()},disabled:i,children:[t.jsx(xs,{className:i?"db-corruption-banner__refresh-icon db-corruption-banner__refresh-icon--spinning":"db-corruption-banner__refresh-icon","aria-hidden":"true"}),i?o("dbBanner.refreshing","Refreshing…"):o("dbBanner.refreshHealth","Refresh health")]})]}),t.jsx("p",{className:"db-corruption-banner__body",children:o("dbBanner.body","Fusion's background SQLite integrity check reported corruption. Review the failing objects below before continuing critical operations.")}),t.jsx("ul",{className:"db-corruption-banner__list",children:l.map((c,m)=>t.jsx("li",{className:"db-corruption-banner__item",children:t.jsx("code",{className:"db-corruption-banner__error-code",children:c})},`${m}:${c}`))}),t.jsxs("p",{className:"db-corruption-banner__footer",children:[t.jsx("strong",{className:"db-corruption-banner__footer-label",children:o("dbBanner.whatToDo","What to do:")})," ",t.jsx(Ga,{i18nKey:"app:dbBanner.instructions",defaults:"Back up the project, try <cmd>fn db --vacuum</cmd> if the database still opens cleanly, and restore from a known-good backup if corruption persists. See <docsLink>docs/storage.md</docsLink> for the storage layout and recovery guidance.",components:{cmd:t.jsx("code",{}),docsLink:t.jsx("a",{href:"docs/storage.md"})}})]}),r?t.jsx("p",{className:"db-corruption-banner__error",children:r}):null]})}function HH({latestVersion:e,currentVersion:n,onDismiss:s}){const{t:i}=st("app");return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:[t.jsx(Ga,{i18nKey:"app:updateBanner.message",defaults:"Update available: v{{latestVersion}} (current: v{{currentVersion}}). Run <code>fn update</code> for an installed CLI, or pull this source checkout.",values:{latestVersion:e,currentVersion:n},components:{code:t.jsx("code",{})}})," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:i("updateBanner.releaseNotes","Release notes")})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:i("updateBanner.learnMore","Learn more")})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":i("updateBanner.dismissLabel","Dismiss update notice"),onClick:s,children:t.jsx(Fn,{size:16,"aria-hidden":"true"})})]})}function VH(e){return e.length>7?e.slice(0,7):e}function lh(e){return e instanceof Ka?e.message||"Request failed":e instanceof Error&&e.message?e.message:"Request failed"}function Iy(e){const n=["button","[href]","input","select","textarea",'[tabindex]:not([tabindex="-1"])'].join(",");return Array.from(e.querySelectorAll(n)).filter(s=>!(s.hasAttribute("disabled")||s.getAttribute("aria-hidden")==="true"))}function qH({open:e,onClose:n,worktreePath:s,integrationBranch:i,stashSha:r,stashLabel:o,conflictedFiles:l,autostashOutcome:d,taskId:c}){const{t:m}=st("app"),p=Kj(),h=a.useRef(null),u=a.useRef(null),[f,b]=a.useState(d==="failed"?[]:l),[y,v]=a.useState(!1),[x,k]=a.useState(null),[w,g]=a.useState("idle");a.useEffect(()=>{e&&(b(d==="failed"?[]:l),k(null),g("idle"))},[d,l,e]),a.useEffect(()=>{if(!e)return;u.current=document.activeElement instanceof HTMLElement?document.activeElement:null;const M=h.current;if(M){const _=Iy(M),V=_.find(N=>N.getAttribute("aria-label")==="Copy stash reference")??_[0];V?V.focus():M.focus()}const D=_=>{if(_.key==="Escape"){_.preventDefault(),n(!1);return}if(_.key!=="Tab")return;const V=h.current;if(!V)return;const N=Iy(V);if(N.length===0){_.preventDefault(),V.focus();return}const $=N[0],R=N[N.length-1],L=document.activeElement;_.shiftKey&&L===$?(_.preventDefault(),R.focus()):!_.shiftKey&&L===R&&(_.preventDefault(),$.focus())};return document.addEventListener("keydown",D),()=>{document.removeEventListener("keydown",D);const _=u.current;_&&_.isConnected&&_.focus(),u.current=null}},[e,n]);const j=a.useMemo(()=>`Stash ref: ${VH(r)} (${o})`,[o,r]);if(!e)return null;const S=async(M,D)=>{v(!0),k(null);try{const _=await I("/git/stash-resolve",{method:"POST",body:JSON.stringify({worktreePath:s,stashSha:r,file:M,choice:D,taskId:c})});b(Array.isArray(_.remainingConflicts)?_.remainingConflicts:[])}catch(_){k(lh(_))}finally{v(!1)}},C=async()=>{v(!0),k(null);try{(await I("/git/stash-drop",{method:"POST",body:JSON.stringify({worktreePath:s,stashSha:r,taskId:c})})).dropped&&n(!0)}catch(M){k(lh(M))}finally{v(!1)}},E=async()=>{v(!0),k(null);try{const M=await I("/git/stash-apply",{method:"POST",body:JSON.stringify({worktreePath:s,stashSha:r,taskId:c})});M.conflict&&b(Array.isArray(M.conflictedFiles)?M.conflictedFiles:[])}catch(M){k(lh(M))}finally{v(!1)}},F=async()=>{try{await navigator.clipboard.writeText(r),g("copied")}catch{g("failed")}};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"stash-conflict-modal-title",children:t.jsxs("div",{className:"modal stash-conflict-modal",ref:h,tabIndex:-1,children:[t.jsx("div",{className:"modal-header",children:t.jsx("h3",{id:"stash-conflict-modal-title",children:m("git.stashConflict.title","Resolve auto-stash conflicts")})}),t.jsx("p",{className:"stash-conflict-modal__summary",children:m("git.stashConflict.summary","Pulled {{branch}}, but restoring local edits from stash produced conflicts.",{branch:i})}),d==="failed"?t.jsx("p",{className:"stash-conflict-modal__warning",children:m("git.stashConflict.failedWarning","Automatic restore failed. Your changes are preserved in the stash above; use git stash apply <ref> to recover manually, or use Retry below.")}):null,t.jsxs("div",{className:"stash-conflict-modal__stash-row",children:[t.jsx("span",{children:j}),t.jsx("button",{type:"button",className:"btn btn-sm btn-icon",onClick:F,"aria-label":"Copy stash reference",children:t.jsx(Pa,{"aria-hidden":"true"})})]}),w==="copied"?t.jsx("p",{className:"stash-conflict-modal__hint",role:"status",children:m("git.stashConflict.copied","Stash SHA copied.")}):null,w==="failed"?t.jsx("p",{className:"stash-conflict-modal__error",role:"alert",children:m("git.stashConflict.copyFailed","Could not copy stash SHA.")}):null,f.length>0?t.jsx("div",{className:"stash-conflict-modal__list",role:"list",children:f.map(M=>t.jsxs("div",{className:"stash-conflict-row",role:"listitem",children:[t.jsx("code",{className:"stash-conflict-row__path",children:M}),t.jsxs("div",{className:"stash-conflict-row__actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",disabled:y,onClick:()=>void S(M,"ours"),children:m("git.stashConflict.keepMine","Keep mine")}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:y,onClick:()=>void S(M,"theirs"),children:m("git.stashConflict.keepIncoming","Keep incoming")}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:y,onClick:()=>p?.openFile(M,{workspace:s}),children:m("git.stashConflict.openInEditor","Open in editor")})]})]},M))}):null,x?t.jsx("p",{className:"stash-conflict-modal__error",role:"alert",children:x}):null,t.jsxs("div",{className:"modal-actions",children:[t.jsx("div",{className:"modal-actions-left",children:t.jsx("button",{type:"button",className:"btn",disabled:y,onClick:()=>void E(),children:m("git.stashConflict.retryRestore","Retry restore")})}),t.jsxs("div",{className:"modal-actions-right",children:[t.jsx("button",{type:"button",className:"btn",disabled:y,onClick:()=>n(!1),children:m("actions.close","Close")}),t.jsx("button",{type:"button",className:"btn btn-warning",disabled:y||f.length>0,onClick:()=>void C(),children:m("git.stashConflict.dropStash","Drop stash")})]})]})]})})}function ZN(e){return`kb:merge-advance-notice-dismissed:${e??"default"}`}function eS(e){return`kb:${e??"default"}:merge-advance-force-with-lease`}function Dy(e){try{const n=window.localStorage.getItem(ZN(e));if(!n)return[];const s=JSON.parse(n);return Array.isArray(s)?s.filter(i=>typeof i=="string"):[]}catch{return[]}}function WH(e,n){try{window.localStorage.setItem(ZN(e),JSON.stringify(n.slice(-50)))}catch{}}function Ly(e){try{return window.sessionStorage.getItem(eS(e))==="1"}catch{return!1}}function GH(e,n){try{window.sessionStorage.setItem(eS(e),n?"1":"0")}catch{}}function KH({projectId:e,apiBase:n="/api"}){const[s,i]=a.useState([]),[r,o]=a.useState(()=>Dy(e)),[l,d]=a.useState("idle"),[c,m]=a.useState(null),[p,h]=a.useState(null),[u,f]=a.useState("idle"),[b,y]=a.useState(()=>Ly(e)),v=a.useRef(null);a.useEffect(()=>{o(Dy(e)),y(Ly(e))},[e]),a.useEffect(()=>()=>{v.current!==null&&window.clearTimeout(v.current)},[]);const x=a.useCallback(async()=>{try{const F=new URLSearchParams({limit:"5"});e&&F.set("projectId",e);const M=await I(`/tasks/merge-advance-events?${F.toString()}`);i(Array.isArray(M.events)?M.events:[])}catch{i([])}},[e]),k=a.useCallback(async()=>{if(!e){h(null);return}try{const F=await I(`/projects/${encodeURIComponent(e)}/merge-advance/push-status`);h(F)}catch{h(null)}},[e]);a.useEffect(()=>{x(),k();const F=e?`?projectId=${encodeURIComponent(e)}`:"",M=li(`${n}/events${F}`,{events:{"task:merged":()=>{x(),k()}}});return()=>M()},[n,x,k,e]);const w=a.useMemo(()=>{const F=new Set(r);return s.find(M=>{if(M.succeeded!==!0||M.userCheckout===null||M.userCheckout.worktreePath.trim().length===0||F.has(M.toSha))return!1;const D=M.userCheckout.worktreePath,_=new Set(["clean-sync","synced-with-edits-restored"]);return!(M.autoSync??[]).some(N=>N.worktreePath===D&&_.has(N.outcome))})},[r,s]),g=a.useCallback(()=>{if(!w)return;const F=[...r.filter(M=>M!==w.toSha),w.toSha].slice(-50);o(F),WH(e,F)},[r,w,e]),j=a.useCallback(async()=>{if(w?.userCheckout){d(w.userCheckout.dirty||w.userCheckout.untrackedCount>0?"stashing":"pending");try{const F=e?`?projectId=${encodeURIComponent(e)}`:"",M=await I(`/git/pull${F}`,{method:"POST",body:JSON.stringify({worktreePath:w.userCheckout.worktreePath,integrationBranch:w.integrationBranch,taskId:w.taskId})});M.kind==="stash-conflict"?m({stashSha:M.stashSha,stashLabel:M.stashLabel,conflictedFiles:M.conflictedFiles,autostashOutcome:M.autostashOutcome}):g(),d("idle"),await k()}catch(F){F instanceof Ka?d({error:F.message||"Pull failed"}):F instanceof Error&&F.message?d({error:F.message}):d({error:"Pull failed"})}}},[g,k,w,e]),S=a.useCallback(F=>{y(F),GH(e,F)},[e]),C=a.useCallback(()=>{f("idle")},[]),E=a.useCallback(async()=>{if(e){f("pending");try{const F=await I(`/projects/${encodeURIComponent(e)}/merge-advance/push-origin`,{method:"POST",body:JSON.stringify({forceWithLease:b,expectedLocalSha:p?.localSha})});if(F.ok){f("ok"),await k(),v.current!==null&&window.clearTimeout(v.current),v.current=window.setTimeout(()=>f("idle"),2e3);return}f({error:F.message??F.outcome,outcome:F.outcome==="ok"?"failed":F.outcome,stderr:F.stderrPreview})}catch(F){const M=F instanceof Error?F.message:"Push failed";f({error:M,outcome:"failed"})}}},[k,b,e,p?.localSha]);return{notice:w,dismiss:g,pull:j,pullState:l,conflictState:c,setConflictState:m,pushStatus:p,pushState:u,push:E,clearPushError:C,forceWithLease:b,setForceWithLease:S}}function Fy(e){return e?e.length>7?e.slice(0,7):e:""}function JH({projectId:e,apiBase:n="/api"}){const{t:s}=st("app"),i=a.useRef(null),{notice:r,dismiss:o,pull:l,pullState:d,conflictState:c,setConflictState:m,pushStatus:p,pushState:h,push:u,clearPushError:f,forceWithLease:b,setForceWithLease:y}=KH({projectId:e,apiBase:n});if(!r||!r.userCheckout)return null;const v=r.userCheckout,x=v.dirty||v.untrackedCount>0,k=d==="pending"||d==="stashing",w=typeof d=="object"?d.error:null,g=()=>{const S=document.activeElement,C=S instanceof HTMLElement&&i.current?.contains(S);o(),C&&document.body.focus()},j=()=>{if(!p||p.aheadCount<=0)return null;const S=h==="pending"||p.canPush===!1||k,C=b?s("merge.pushForceWithLease","Push (force-with-lease)"):s("merge.pushToOrigin","Push to origin");return t.jsxs("section",{className:"merge-advance-notice__push",children:[t.jsx("p",{className:"merge-advance-notice__push-heading",children:s("merge.pushHeading","Push {{branch}} to origin — ahead by {{count}} commit{{plural}}.",{branch:p.integrationBranch,count:p.aheadCount,plural:p.aheadCount===1?"":"s"})}),t.jsxs("div",{className:"merge-advance-notice__push-actions",children:[h==="ok"?t.jsx("span",{children:s("merge.pushSuccess","Pushed to origin/{{branch}} @ {{sha}}.",{branch:p.integrationBranch,sha:Fy(p.remoteSha)})}):t.jsx("button",{type:"button",className:`btn btn-sm ${b?"btn-warning":""}`.trim(),disabled:S,onClick:()=>{u()},children:h==="pending"?s("merge.pushing","Pushing…"):C}),!p.canPush&&p.disabledReason?t.jsx("span",{className:"merge-advance-notice__push-error",children:p.disabledReason==="no-remote"?s("merge.disabledNoRemote","No `origin` remote configured."):p.disabledReason==="no-upstream"?s("merge.disabledNoUpstream","Branch has no upstream on origin."):p.disabledReason==="merge-locked"?s("merge.disabledMergeLocked","Push paused — a Fusion merge is in progress."):null}):null]}),typeof h=="object"&&(h.outcome==="rejected-non-ff"||h.outcome==="sha-mismatch")?t.jsxs("div",{className:"merge-advance-notice__push-error",role:"alert",children:[t.jsx("span",{children:h.error})," ",t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l()},children:s("merge.smartPull","Smart Pull")})]}):null,typeof h=="object"&&(h.outcome==="rejected-other"||h.outcome==="failed")?t.jsxs("div",{className:"merge-advance-notice__push-error",role:"alert",children:[t.jsx("span",{children:h.error}),h.stderr?t.jsx("pre",{children:h.stderr}):null,t.jsx("button",{type:"button",className:"btn btn-sm",onClick:f,children:s("actions.dismiss","Dismiss")})]}):null,t.jsxs("details",{className:"merge-advance-notice__push-advanced",children:[t.jsx("summary",{children:s("merge.advanced","Advanced")}),t.jsxs("label",{children:[t.jsx("input",{type:"checkbox",checked:b,onChange:E=>y(E.target.checked)})," ",s("merge.forceWithLeaseLabel","Allow force-with-lease (use only when you know origin diverged intentionally)")]})]})]})};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{ref:i,className:"merge-advance-notice",role:"status","aria-live":"polite",children:[t.jsxs("div",{className:"merge-advance-notice__content",children:[t.jsx("strong",{children:s("merge.advancedTo","{{branch}} advanced to {{sha}}.",{branch:r.integrationBranch,sha:Fy(r.toSha)})})," ",s("merge.checkedOutBehind","Your checked-out copy at {{path}} is behind.",{path:v.worktreePath}),x?s("merge.changesWillAutoStash"," (local changes will be auto-stashed and restored)"):"",w?t.jsxs("span",{className:"merge-advance-notice__error",role:"alert",children:[" ",w]}):null,k?t.jsxs("span",{className:"merge-advance-notice__hint",children:[" ",s("merge.pulling","Pulling…")]}):null,j()]}),t.jsxs("div",{className:"merge-advance-notice__actions",children:[c?null:t.jsx("button",{type:"button",className:"btn btn-sm",disabled:k,onClick:()=>{l()},children:s("actions.pull","Pull")}),t.jsx("button",{type:"button",className:"merge-advance-notice__dismiss touch-target","aria-label":s("merge.dismissNotice","Dismiss merge advance notice"),onClick:g,children:t.jsx(Fn,{"aria-hidden":"true"})})]})]}),t.jsx(qH,{open:c!==null,onClose:S=>{m(null),S&&g()},worktreePath:v.worktreePath,integrationBranch:r.integrationBranch,stashSha:c?.stashSha??"",stashLabel:c?.stashLabel??"",conflictedFiles:c?.conflictedFiles??[],autostashOutcome:c?.autostashOutcome??"conflict-needs-manual",taskId:r.taskId})]})}function YH({pendingCount:e,onOpenMailbox:n,onDismiss:s}){const{t:i}=st("app"),r=e===1?i("approval.requestSingular","request"):i("approval.requestPlural","requests");return t.jsx("section",{className:"approval-notification-banner",role:"region","aria-live":"polite","aria-label":i("approval.requests","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(oa,{"aria-hidden":"true"}),t.jsx("span",{children:i("approval.needAttention","{{count}} approval {{noun}} need your attention",{count:e,noun:r})})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(mr,{"aria-hidden":"true"}),t.jsx("span",{children:i("approval.openMailbox","Open Mailbox")})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":i("approval.dismissBanner","Dismiss approval notification banner"),children:t.jsx(Fn,{"aria-hidden":"true"})})]})]})})}const XH="https://github.com/Runfusion/Fusion";function QH({onStar:e,onDismiss:n}){const s=()=>{e?.(),n()};return t.jsxs("section",{className:"card github-star-prompt",role:"region","aria-live":"polite","aria-label":"GitHub star prompt",children:[t.jsxs("div",{className:"github-star-prompt__header",children:[t.jsxs("div",{className:"github-star-prompt__title-wrap",children:[t.jsx(Od,{"aria-hidden":"true"}),t.jsx("h3",{children:"Enjoying Fusion?"})]}),t.jsx("button",{type:"button",className:"btn-icon github-star-prompt__dismiss",onClick:n,"aria-label":"Dismiss GitHub star prompt",children:t.jsx(Fn,{"aria-hidden":"true"})})]}),t.jsx("p",{children:"If Fusion has saved you time, a GitHub star goes a long way. It helps other developers discover the project and keeps the team motivated to ship improvements."}),t.jsx("div",{className:"github-star-prompt__actions",children:t.jsxs("a",{className:"btn btn-sm github-star-prompt__cta",href:XH,target:"_blank",rel:"noopener noreferrer",onClick:s,children:[t.jsx(Od,{"aria-hidden":"true"}),t.jsx("span",{children:"Star on GitHub"})]})})]})}function ZH({onResume:e}){const{t:n}=st("app"),s=D8();if(!s)return null;const i=s.completedSteps.length,r=dr.length,o=i>0?n("onboarding.progressText","{{completed}} of {{total}} step{{pluralS}} complete — You're on the ",{completed:i,total:r,pluralS:i!==1?"s":""}):n("onboarding.onTheStep","You're on the ");return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":n("onboarding.resumeOnboarding","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($s,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:n("onboarding.continueSetup","Continue Setup")}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[o,t.jsx("strong",{children:s.label})," ",n("onboarding.stepContinue","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:()=>{Zi("onboarding:resumed",{source:"resume-card",resumedFromStep:s.currentStep}),e()},children:[t.jsx(Ds,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:n("onboarding.continueOnboarding","Continue onboarding")})]})})]})}function e9({onOpenSettings:e,onOpenModelOnboarding:n}){const{t:s}=st("app"),i=ol(),r=qN(),[o,l]=a.useState(!0),[d,c]=a.useState(!1),[m,p]=a.useState(!1),[h,u]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!i||r){l(!1);return}let k=!1;return(async()=>{try{l(!0),c(!1);const[g,j]=await Promise.all([Yo(),Ja()]);if(k)return;const S=g.providers??[],C=S.find(_=>_.id==="github"),F=!S.some(_=>_.id!=="github"&&_.authenticated),M=!j.defaultProvider&&!j.defaultModelId,D=C?!C.authenticated:!1;u({needsAiProvider:F,needsDefaultModel:M,needsGitHub:D})}catch{k||c(!0)}finally{k||l(!1)}})(),()=>{k=!0}},[i,r]);const f=a.useCallback(()=>{P8(),p(!0)},[]),b=a.useCallback(()=>{n()},[n]),y=a.useCallback(()=>{e("global-models")},[e]),v=a.useCallback(()=>{e("authentication")},[e]),x=a.useMemo(()=>{const k=[];return h.needsAiProvider&&k.push({id:"ai-provider",title:s("setup.connectAiProvider","Connect AI Provider"),description:s("setup.connectAiProviderDesc","Connect an AI provider to enable AI agents for task planning and code generation"),actionLabel:s("setup.setUpAi","Set Up AI"),onAction:b,icon:Ws}),h.needsDefaultModel&&k.push({id:"default-model",title:s("setup.selectDefaultModel","Select Default Model"),description:s("setup.selectDefaultModelDesc","Choose a default AI model for task execution"),actionLabel:s("setup.chooseModel","Choose Model"),onAction:y,icon:_k}),h.needsGitHub&&k.push({id:"github",title:s("setup.connectGitHub","Connect GitHub"),description:s("setup.connectGitHubDesc","Connect GitHub to import issues and track pull requests"),actionLabel:s("setup.connectGitHubButton","Connect GitHub"),onAction:v,icon:ai}),k},[h.needsAiProvider,h.needsDefaultModel,h.needsGitHub,v,y,b]);return!i||r||m||o||d||x.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":s("setup.ariaSetupRecommendations","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(Ia,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:s("setup.recommendedNextSteps","Recommended Next Steps")}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:s("setup.completeSetup","Complete these setup items to get the most out of Fusion.")}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:x.map(k=>{const w=k.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(w,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:k.title}),t.jsx("span",{children:k.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:k.onAction,children:k.actionLabel})]},k.id)})}),t.jsx(fr,{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":s("setup.ariaDismissRecommendations","Dismiss recommendations"),children:t.jsx(Fn,{size:16,"aria-hidden":!0})})]})}function t9({navOffsetHeight:e,paddingBottom:n,tabHeights:s}){const i=Math.max(0,...s.filter(l=>Number.isFinite(l)));if(i>0)return Math.max(44,Math.ceil(i));const r=Number.isFinite(n)?n:0,o=e-r;return Math.max(44,Math.ceil(o))}function n9({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 Ol(e){return e>99?"99+":String(e)}function s9({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:d,onOpenMailbox:c,mailboxUnreadCount:m=0,mailboxPendingApprovalCount:p=0,chatHasUnreadResponse:h=!1,stashOrphanCount:u=0,onOpenGitManager:f,onOpenWorkflowEditor:b,onOpenSchedules:y,onOpenScripts:v,onToggleTerminal:x,onOpenFiles:k,onOpenTodos:w,todosOpen:g=!1,onOpenGitHubImport:j,onOpenPlanning:S,onResumePlanning:C,activePlanningSessionCount:E=0,onOpenUsage:F,onRunScript:M,projectId:D,onViewAllProjects:_,showSkillsTab:V,experimentalFeatures:N,onOpenNodes:$,pluginDashboardViews:R=[],shellConnectionControl:L}){const{t:O}=st("app"),J=Ji(),[A,de]=a.useState(!1),[B,P]=a.useState(!1),[Z,T]=a.useState({}),[ie,le]=a.useState(!1),be=a.useRef(null),Le=a.useMemo(()=>Object.entries(Z).sort(([X],[ye])=>X.localeCompare(ye)),[Z]);a.useEffect(()=>{if(!B)return;let X=!1;return le(!0),Hd(D).then(ye=>{X||T(ye)}).catch(()=>{X||T({})}).finally(()=>{X||le(!1)}),()=>{X=!0}},[B,D]);const xe=a.useCallback(()=>de(!1),[]),q=a.useCallback(X=>{xe(),X?.()},[xe]);if(a.useEffect(()=>{if(!A)return;const X=ye=>{ye.key==="Escape"&&de(!1)};return document.addEventListener("keydown",X),()=>document.removeEventListener("keydown",X)},[A]),a.useLayoutEffect(()=>{const X=be.current;if(!X||typeof document>"u")return;const ye=()=>{const ue=window.getComputedStyle(X),je=Number.parseFloat(ue.paddingBottom),$e=Array.from(X.querySelectorAll(".mobile-nav-tab"),We=>We.getBoundingClientRect().height),Ce=t9({navOffsetHeight:X.offsetHeight,paddingBottom:je,tabHeights:$e});document.documentElement.style.setProperty("--mobile-nav-height",`${Ce}px`)};ye();let ot=null;return typeof ResizeObserver<"u"&&(ot=new ResizeObserver(()=>{ye()}),ot.observe(X)),()=>{ot?.disconnect(),document.documentElement.style.removeProperty("--mobile-nav-height")}},[]),J!=="mobile"||i)return null;const ce=E>0&&C?C:S,De=!!V,He=!!N?.todoView,qe=De,pe=De&&!qe,se=R.filter(X=>X.view.placement==="primary").sort((X,ye)=>(X.view.order??Number.MAX_SAFE_INTEGER)-(ye.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),z=new Set(se.map(X=>`${X.pluginId}:${X.view.viewId}`)),Y=R.filter(X=>!z.has(`${X.pluginId}:${X.view.viewId}`)).sort((X,ye)=>(X.view.order??Number.MAX_SAFE_INTEGER)-(ye.view.order??Number.MAX_SAFE_INTEGER)),he=e==="documents"||e==="reliability"||!!N?.evalsView&&e==="evals"||!!N?.goalsView&&e==="goalsView"||e==="research"||e==="insights"||e==="memory"||e==="secrets"||e==="devserver"||e==="dev-server"||g&&He||e==="skills"&&!qe||e==="graph"||e==="stash-recovery"||Fo(e)&&!se.some(X=>Zl(X.pluginId,X.view.viewId)===e);return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{ref:be,className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}${r?" mobile-nav-bar--keyboard-open":""}`,role:"tablist","aria-label":O("nav.primaryNavAriaLabel","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(Wo,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.tasks","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(Is,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.agents","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(ri,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.missions","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(Ra,{}),h&&e!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":O("nav.chatUnreadAriaLabel","Unread chat response")})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.chat","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(qr,{}),p>0&&e!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":O("nav.mailboxPendingAriaLabel","Pending approvals")})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.mailbox","Mailbox")}),m>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Ol(m)})]}),qe&&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(Ws,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.skills","Skills")})]}),se.map(X=>{const ye=Zl(X.pluginId,X.view.viewId),ot=qd(X.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===ye||e==="graph"&&X.pluginId==="fusion-plugin-dependency-graph"&&X.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${X.pluginId}-${X.view.viewId}`,role:"tab","aria-selected":e===ye||e==="graph"&&X.pluginId==="fusion-plugin-dependency-graph"&&X.view.viewId==="graph",onClick:()=>n(X.pluginId==="fusion-plugin-dependency-graph"&&X.view.viewId==="graph"?"graph":ye),children:[t.jsx(ot,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:X.view.label})]},`${X.pluginId}:${X.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${he?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>de(X=>!X),children:[t.jsx(yh,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:O("nav.more","More")})]})]}),A&&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:O("nav.moreSheetTitle","Navigate")}),L?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:L}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>q(c),children:[t.jsx(qr,{}),t.jsx("span",{children:O("nav.mailbox","Mailbox")}),m>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Ol(m)}),p>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Ol(p)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>q(l),children:[t.jsx(Ci,{}),t.jsx("span",{children:O("nav.activityLog","Activity Log")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>q(d),children:[t.jsx(Ko,{}),t.jsx("span",{children:O("nav.systemStats","System Stats")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>q(f),children:[t.jsx(ui,{}),t.jsx("span",{children:O("nav.gitManager","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:()=>q(x),children:[t.jsx(ua,{}),t.jsx("span",{children:O("nav.terminal","Terminal")})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>P(X=>!X),"aria-expanded":B,"aria-haspopup":"menu","aria-label":O("nav.showScriptsAriaLabel","Show scripts"),children:t.jsx(ls,{size:14,className:`mobile-more-chevron${B?" mobile-more-chevron--open":""}`})})]}),B&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":O("nav.scriptsSubmenuAriaLabel","Scripts submenu"),children:ie?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(Et,{className:"animate-spin"}),t.jsx("span",{children:O("nav.loadingScripts","Loading scripts…")})]}):Le.length>0?t.jsxs(t.Fragment,{children:[Le.map(([X,ye])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${X}`,onClick:()=>{M&&M(X,ye),xe(),P(!1)},children:[t.jsx(Ds,{}),t.jsx("span",{children:X})]},X)),v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{xe(),P(!1),v()},children:[t.jsx(da,{}),t.jsx("span",{children:O("nav.manageScripts","Manage Scripts…")})]})]}):v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{xe(),P(!1),v()},children:[t.jsx(da,{}),t.jsx("span",{children:O("nav.noScriptsAddOne","No scripts — add one…")})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>q(k),children:[t.jsx(Zs,{}),t.jsx("span",{children:O("nav.files","Files")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>q(ce),children:[t.jsx(Ia,{}),t.jsx("span",{children:O("nav.planning","Planning")}),E>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Ol(E)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>q(b),children:[t.jsx(lc,{}),t.jsx("span",{children:O("nav.workflows","Workflows")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>q(y),children:[t.jsx(ha,{}),t.jsx("span",{children:O("nav.automation","Automation")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>q(j),children:[t.jsx(n9,{}),t.jsx("span",{children:O("nav.importFromGitHub","Import from GitHub")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>q(F),children:[t.jsx(Ci,{}),t.jsx("span",{children:O("nav.usage","Usage")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>q(_),children:[t.jsx(qo,{}),t.jsx("span",{children:O("nav.projects","Projects")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>q(()=>n("documents")),children:[t.jsx(Hr,{}),t.jsx("span",{children:O("nav.documents","Documents")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-reliability",onClick:()=>q(()=>n("reliability")),children:[t.jsx(Ci,{}),t.jsx("span",{children:O("nav.reliability","Reliability")})]}),N?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>q(()=>n("evals")),children:[t.jsx(ri,{}),t.jsx("span",{children:O("nav.evals","Evals")})]}),N?.goalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-goals",onClick:()=>q(()=>n("goalsView")),children:[t.jsx(ri,{}),t.jsx("span",{children:O("nav.goals","Goals")})]}),pe&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>q(()=>n("skills")),children:[t.jsx(Ws,{}),t.jsx("span",{children:O("nav.skills","Skills")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>q(()=>n("stash-recovery")),children:[t.jsx(Ur,{}),t.jsx("span",{children:O("nav.stashRecovery","Stash Recovery")}),u>0?t.jsx("span",{className:"mobile-more-item-badge",children:Ol(u)}):null]}),N?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>q(()=>n("research")),children:[t.jsx(na,{}),t.jsx("span",{children:O("nav.research","Research")})]}),N?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>q(()=>n("insights")),children:[t.jsx($s,{}),t.jsx("span",{children:O("nav.insights","Insights")})]}),N?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>q(()=>n("memory")),children:[t.jsx(ac,{}),t.jsx("span",{children:O("nav.memory","Memory")})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-secrets",onClick:()=>q(()=>n("secrets")),children:[t.jsx(ll,{}),t.jsx("span",{children:O("nav.secrets","Secrets")})]}),N?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{q(()=>n("dev-server"))},children:[t.jsx(Ko,{}),t.jsx("span",{children:O("nav.devServer","Dev Server")})]}),N?.nodesView&&$&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>q($),children:[t.jsx(N1,{}),t.jsx("span",{children:O("nav.nodes","Nodes")})]}),He&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>q(()=>w?.()),children:[t.jsx(Sp,{}),t.jsx("span",{children:O("nav.todos","Todos")})]}),Y.map(X=>{const ye=Zl(X.pluginId,X.view.viewId),ot=qd(X.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${X.pluginId}-${X.view.viewId}`,onClick:()=>q(()=>n(X.pluginId==="fusion-plugin-dependency-graph"&&X.view.viewId==="graph"?"graph":ye)),children:[t.jsx(ot,{}),t.jsx("span",{children:X.view.label})]},`${X.pluginId}:${X.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:()=>q(o),children:[t.jsx(Ql,{}),t.jsx("span",{children:O("nav.settings","Settings")})]})]})]})]})}function Oy(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function tS(e,n){const s=n.trim();if(!s)return!0;const i=Oy(s);return Oy(e).includes(i)||e.toLowerCase().includes(s.toLowerCase())}function i9({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below",roomMemberIds:l,roomName:d}){const{t:c}=st("app"),m=a.useMemo(()=>e.filter(y=>tS(y.name,n)),[e,n]),p=!!l,h=p&&n.trim().length>0,u=a.useMemo(()=>p?m.filter(y=>l?.has(y.id)):m,[m,l,p]),f=a.useMemo(()=>p?m.filter(y=>!l?.has(y.id)):[],[m,l,p]),b=h?[...u,...f]:u;return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":c("agentMention.suggestionsLabel","Agent mention suggestions"),children:b.length===0?t.jsx("div",{className:"agent-mention-empty",children:c("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[p&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:d?c("agentMention.membersOf","Members of #{{roomName}}",{roomName:d}):c("agentMention.roomMembers","Room members")}),u.map((y,v)=>t.jsxs("button",{type:"button",className:`agent-mention-item${v===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${y.id}`,onMouseDown:x=>x.preventDefault(),onClick:()=>r(y),role:"option","aria-selected":v===s,children:[t.jsx(ru,{agent:y,size:20}),p&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":c("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:y.name}),t.jsx("span",{className:"agent-mention-role",children:y.role})]},y.id)),p&&!h&&f.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:c("agentMention.typeToSearch","Type to search other agents")}),p&&h&&f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:c("agentMention.otherAgents","Other agents")}),f.map((y,v)=>{const x=u.length+v;return t.jsxs("button",{type:"button",className:`agent-mention-item${x===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${y.id}`,onMouseDown:k=>k.preventDefault(),onClick:()=>r(y),role:"option","aria-selected":x===s,children:[t.jsx(ru,{agent:y,size:20}),t.jsx("span",{className:"agent-mention-name",children:y.name}),t.jsx("span",{className:"agent-mention-role",children:y.role})]},y.id)})]})]})}):null}function $y(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:i,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:d,onDone:c,onError:m,onFallbackSession:p}=e;let h="",u="",f=[],b,y=null,v=null;const x=()=>{y=null,i(h)},k=()=>{v=null,r(u)},w=()=>{y!==null&&(cancelAnimationFrame(y),y=null),v!==null&&(cancelAnimationFrame(v),v=null)};return l.current=w,{handlers:{onThinking:j=>{u+=j,v===null&&(v=requestAnimationFrame(k))},onText:j=>{h+=j,y===null&&(y=requestAnimationFrame(x))},onToolStart:j=>{f=[...f,{toolName:j.toolName,args:j.args,isError:!1,status:"running"}],o(f)},onToolEnd:j=>{const S=[...f];for(let C=S.length-1;C>=0;C--){const E=S[C];if(E?.toolName===j.toolName&&E.status==="running"){S[C]={...E,status:"completed",isError:j.isError,result:j.result},f=S,o(S);return}}f=[...S,{toolName:j.toolName,isError:j.isError,result:j.result,status:"completed"}],o(f)},onFallback:j=>{b=j,p?.(j,n),d?.(`Primary model unavailable. Switched to fallback ${j.fallbackModel}.`,"warning")},onDone:j=>{w(),c({messageId:j.messageId,message:j.message,accumulated:{text:h,thinking:u,toolCalls:f,fallbackInfo:b}})},onError:j=>{w(),m(j,s)}},cancelFlushes:w}}const a9="fusion:chat-pending:";function Lf(e){return e?`${a9}${e}`:null}function r9(e){const n=Lf(e);if(!n||typeof window>"u")return"";try{return localStorage.getItem(n)??""}catch{return""}}function o9(e,n){const s=Lf(e);if(!(!s||typeof window>"u"))try{localStorage.setItem(s,n)}catch{}}function ch(e){const n=Lf(e);if(!(!n||typeof window>"u"))try{localStorage.removeItem(n)}catch{}}const l9="fusion:quick-chat-last-session:";function nS(e){return`${l9}${e||"default"}`}function c9(e){if(typeof window>"u")return null;try{return localStorage.getItem(nS(e))}catch{return null}}function d9(e,n){if(!(typeof window>"u"))try{localStorage.setItem(nS(e),n)}catch{}}const $r="__fn_agent__";function sS(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function kd(e,n,s){const i=typeof e=="string"?e.trim():"",r=sS(n,s),o=i||(r.modelProvider&&r.modelId?$r:"");return o?{agentId:o,...r}:null}function wd(e,n,s){const i=sS(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function zy(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 u9(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(i=>{if(!i||typeof i!="object")return null;const r=i,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(i=>i!==null);return s.length>0?s:void 0}function m9(e){const n=e?.fallback;if(!n||typeof n!="object")return;const s=n,i=typeof s.primaryModel=="string"?s.primaryModel:"",r=typeof s.fallbackModel=="string"?s.fallbackModel:"",o=s.triggerPoint;if(!(!i||!r||o!=="session-creation"&&o!=="prompt-time"))return{primaryModel:i,fallbackModel:r,triggerPoint:o}}function Co(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:u9(e.metadata),fallbackInfo:m9(e.metadata),createdAt:e.createdAt}}function h9(e,n){const{t:s}=st("app"),[i,r]=a.useState(null),[o,l]=a.useState([]),[d,c]=a.useState(!1),[m,p]=a.useState([]),[h,u]=a.useState(!1),[f,b]=a.useState(!1),[y,v]=a.useState(""),[x,k]=a.useState(""),[w,g]=a.useState([]),[j,S]=a.useState(""),C=a.useRef(null),E=a.useRef(null),F=a.useRef(!1),M=a.useRef(null),D=a.useRef(""),_=a.useRef(f);_.current=f;const V=a.useRef(null),N=a.useRef(null),$=a.useRef(""),R=a.useRef(null),L=a.useRef(i);L.current=i;const O=a.useRef(0),J=3,A=a.useRef(!1);a.useEffect(()=>{D.current=j},[j]),a.useEffect(()=>{E.current=null},[e]),a.useEffect(()=>{i?.id&&d9(e,i.id)},[i?.id,e]);const de=a.useCallback(async()=>{c(!0);try{const se=await Kg(e);l(se.sessions)}catch(se){console.error("[useQuickChat] Failed to refresh sessions:",se),n?.(s("quickChat.errorRefreshingSessions","Failed to refresh chat sessions"),"error")}finally{c(!1)}},[e,s,n]),B=a.useCallback(async se=>{const z={agentId:se.agentId};return se.modelProvider&&se.modelId&&(z.modelProvider=se.modelProvider,z.modelId=se.modelId),(await DR(z,e)).session},[e]),P=a.useCallback(()=>{ch(L.current?.id),D.current="",S("")},[]),Z=a.useCallback(()=>{const se=D.current.trim();if(!se)return;ch(L.current?.id),D.current="",S("");const z=N.current;N.current=null;const Y=qe.current(se);z&&Y.then(z.resolve).catch(z.reject)},[]),T=a.useCallback((se,z,Y)=>{if(C.current||!se)return!0;F.current=!1,z&&(v(z.streamingText),k(z.streamingThinking),g(z.toolCalls)),b(!0);const{handlers:he}=$y({sessionId:se,tempUserMessageId:"",setStreamingText:v,setStreamingThinking:k,setStreamingToolCalls:g,cancelStreamingFlushesRef:M,addToast:Y?.silent?void 0:n,onFallbackSession:(X,ye)=>{const ot=zy(X.fallbackModel);l(ue=>ue.map(je=>je.id===ye?{...je,...ot}:je)),r(ue=>ue&&ue.id===ye?{...ue,...ot}:ue)},onDone:()=>{v(""),k(""),g([]),b(!1),_.current=!1,C.current=null,E.current=null,wl(se,{limit:50,order:"desc"},e).then(X=>{L.current?.id===se&&p(X.messages.slice().reverse().map(Co))}).catch(()=>{}),Z()},onError:X=>{v(""),k(""),g([]),b(!1),_.current=!1,C.current=null,E.current=null;const ye=typeof X=="string"&&X.trim()?X:s("quickChat.errorGettingResponse","Failed to get response");Y?.silent||n?.(ye,"error"),wl(se,{limit:50,order:"desc"},e).then(ot=>{L.current?.id===se&&p(ot.messages.slice().reverse().map(Co))}).catch(()=>{}),Z()}});return C.current=GR(se,he,e,{...typeof z?.replayFromEventId=="number"?{lastEventId:z.replayFromEventId}:{}}),E.current={sessionId:se,replayFromEventId:typeof z?.replayFromEventId=="number"?z.replayFromEventId:null},!0},[n,e,Z]),ie=a.useCallback(async(se,z,Y)=>{const he=kd(se,z,Y);if(!he)return;const X=wd(he.agentId,he.modelProvider,he.modelId);c(!0);try{const{session:ye}=await IR({agentId:he.agentId,modelProvider:he.modelProvider,modelId:he.modelId},e);if(ye)r(ye),$.current=X,ye.isGenerating&&T(ye.id,ye.inFlightGeneration);else{const ot=await B(he);r(ot),$.current=X}O.current=0}catch(ye){console.error("[useQuickChat] Failed to initialize session:",ye),O.current+=1,O.current<=J&&n?.(s("quickChat.errorInitializingChat","Failed to initialize chat"),"error")}finally{c(!1)}},[T,e,n,B]),le=a.useCallback(async()=>{if(i){u(!0);try{const se=i.id,z=await wl(se,{limit:50,order:"desc"},e);L.current?.id===se&&p(z.messages.slice().reverse().map(Co))}catch(se){console.error("[useQuickChat] Failed to load messages:",se)}finally{u(!1)}}},[i,e]);a.useEffect(()=>{i?le():p([])},[i,le]),a.useEffect(()=>{if(!i?.isGenerating||(C.current||T(i.id,i.inFlightGeneration),!_.current||C.current||!i))return;const se=setInterval(async()=>{if(!_.current||C.current||!i){clearInterval(se);return}try{if(!(await kl(i.id,e)).session.isGenerating){clearInterval(se);const Y=i.id,he=await wl(Y,{limit:50,order:"desc"},e);L.current?.id===Y&&p(he.messages.slice().reverse().map(Co)),v(""),k(""),g([]),b(!1),_.current=!1,Z()}}catch{}},3e3);return()=>clearInterval(se)},[i,T,e,Z]);const be=a.useCallback(async()=>{if(i){u(!0);try{const se=i.id,z=await wl(se,{limit:50,order:"desc"},e);L.current?.id===se&&p(z.messages.slice().reverse().map(Co))}catch(se){console.error("[useQuickChat] Failed to reload messages:",se)}finally{u(!1)}}},[i,e]),Le=a.useCallback(()=>{M.current?.(),M.current=null,D.current="",S(""),N.current?.resolve(),N.current=null,v(""),k(""),g([]),b(!1)},[]);a.useEffect(()=>{C.current&&(C.current.close(),C.current=null),E.current=null,$.current="",R.current=null,L.current=null,r(null),p([]),l([]),Le()},[e,Le]);const xe=a.useCallback(async(se,z,Y)=>{const he=kd(se,z,Y);if(!he)return;const X=wd(he.agentId,he.modelProvider,he.modelId);R.current=he;const ye=X===$.current&&L.current;if(ye||(C.current&&(C.current.close(),C.current=null),E.current=null,Le()),ye){await be();return}r(null),p([]),$.current=X,await ie(he.agentId,he.modelProvider,he.modelId)},[ie,be,Le]),q=a.useCallback(async se=>{const z=kd(se.agentId,se.modelProvider??void 0,se.modelId??void 0);z&&(R.current=z,$.current=wd(z.agentId,z.modelProvider,z.modelId),C.current&&(C.current.close(),C.current=null),E.current=null,Le(),r(se),Promise.resolve(kl(se.id,e)).then(({session:Y})=>{!Y.isGenerating||!Y.inFlightGeneration||r(he=>!he||he.id!==se.id?he:{...he,...Y})}).catch(()=>{}),se.isGenerating&&T(se.id,se.inFlightGeneration))},[T,e,Le]);a.useEffect(()=>{const se=i?.id;if(!se)return;const z=r9(se);if(!z)return;D.current=z,S(z);let Y=!1;return kl(se,e).then(({session:he})=>{if(!(Y||L.current?.id!==se||D.current.trim().length===0)){if(he.isGenerating){C.current||T(se,he.inFlightGeneration);return}!_.current&&!C.current&&Z()}}).catch(()=>{}),()=>{Y=!0}},[i?.id,T,Z,e]);const ce=a.useCallback(async(se,z)=>{await xe($r,se,z)},[xe]),De=a.useCallback(async(se,z,Y)=>{const X=kd(se??"",z,Y)??R.current;if(!X)return;R.current=X;const ye=wd(X.agentId,X.modelProvider,X.modelId);A.current=!0,O.current=0,C.current&&(C.current.close(),C.current=null),E.current=null,ch(L.current?.id),Le(),p([]),r(null),c(!0);try{const ot=await B(X);r(ot),$.current=ye;const ue=await Kg(e);l(ue.sessions)}catch(ot){console.error("[useQuickChat] Failed to start a fresh session:",ot),n?.(s("quickChat.errorStartingNewChat","Failed to start a new chat"),"error")}finally{A.current=!1,c(!1)}},[n,B,e,Le]),He=a.useCallback(()=>{i&&(F.current=!0,M.current?.(),M.current=null,C.current?.close(),C.current=null,E.current=null,VR(i.id,e).catch(()=>{}),b(!1),_.current=!1,v(""),k(""),g([]),Z())},[i,e,Z]),qe=a.useRef(()=>Promise.resolve()),pe=ul(),te=a.useCallback(async se=>{try{await de();const Y=(await kl(se,e)).session;L.current?.id===se&&r(he=>!he||he.id!==se?he:{...he,...Y}),Y.isGenerating?(v(""),k(""),g([]),b(!0),_.current=!0,T(se,Y.inFlightGeneration,{silent:!0})):(v(""),k(""),g([]),b(!1),_.current=!1,await be())}catch{}},[T,e,de,be]),me=a.useCallback((se,z)=>{if(!se.trim()&&(!z||z.length===0))return Promise.resolve();if(!i)return z&&z.length>0?Promise.reject(new Error(s("quickChat.errorAttachmentsBeforeSession","Cannot send attachments before chat session is ready"))):new Promise((he,X)=>{N.current?.resolve(),N.current={resolve:he,reject:X},D.current=se,S(se),L.current&&!_.current&&!C.current&&queueMicrotask(()=>{!_.current&&!C.current&&Z()})});if(_.current)return z&&z.length>0?Promise.reject(new Error(s("quickChat.errorAttachmentsWhileStreaming","Cannot send attachments while a response is streaming"))):(D.current=se,S(se),o9(i.id,se),Promise.resolve());const Y=new Promise((he,X)=>{V.current={resolve:he,reject:X},F.current=!1,C.current&&(C.current.close(),C.current=null),E.current=null;const ye=`temp-${Date.now()}`,ot={id:ye,sessionId:i.id,role:"user",content:se,createdAt:new Date().toISOString()};p(je=>[...je,ot]),v(""),k(""),g([]),b(!0);const{handlers:ue}=$y({sessionId:i.id,tempUserMessageId:ye,setStreamingText:v,setStreamingThinking:k,setStreamingToolCalls:g,cancelStreamingFlushesRef:M,addToast:n,onFallbackSession:(je,$e)=>{const Ce=zy(je.fallbackModel);l(We=>We.map(ke=>ke.id===$e?{...ke,...Ce}:ke)),r(We=>We&&We.id===$e?{...We,...Ce}:We)},onDone:({messageId:je,message:$e,accumulated:Ce})=>{const We=$e?{...Co($e),...Ce.text.length>0?{content:Ce.text}:{}}:{id:je||`msg-${Date.now()}`,sessionId:i.id,role:"assistant",content:Ce.text,thinkingOutput:Ce.thinking||void 0,toolCalls:Ce.toolCalls.length>0?Ce.toolCalls:void 0,fallbackInfo:Ce.fallbackInfo,createdAt:new Date().toISOString()};p(ke=>[...ke,We]),v(""),k(""),g([]),b(!1),_.current=!1,C.current=null,E.current=null,V.current?.resolve(),V.current=null,Z()},onError:je=>{v(""),k(""),g([]),b(!1),_.current=!1,C.current=null,E.current=null,console.error("[useQuickChat] Stream error:",je);const $e=typeof je=="string"&&je.trim()?je:s("quickChat.errorGettingResponse","Failed to get response"),Ce=ju($e);if(Ce)console.info("[useQuickChat] Suppressed tab-suspension stream error:",je),i?.id&&(v(""),k(""),g([]),b(!0),_.current=!0,te(i.id)),V.current?.resolve();else{const We=$e||s("quickChat.errorGettingResponse","Failed to get response");n?.(We,"error"),V.current?.reject(new Error(We))}V.current=null,F.current||Z(),Ce||be()}});C.current=WR(i.id,se,ue,z,e)});return Y.catch(()=>{}),Y},[i,e,n,be,te,Z]);return qe.current=me,a.useEffect(()=>{if(!i?.id||i.isGenerating!==!0||C.current)return;const se=typeof i.inFlightGeneration?.replayFromEventId=="number"?i.inFlightGeneration.replayFromEventId:null,z=E.current;z?.sessionId===i.id&&z.replayFromEventId===se||T(i.id,i.inFlightGeneration,{silent:!0})},[i?.id,i?.isGenerating,i?.inFlightGeneration,T]),a.useEffect(()=>pe.onBecameVisible(()=>{if(A.current)return;const z=L.current;!z||C.current||Promise.resolve(kl(z.id,e)).then(Y=>{if(!(C.current||L.current?.id!==z.id)){if(Y.session.isGenerating){v(""),k(""),g([]),b(!0),_.current=!0,T(z.id,Y.session.inFlightGeneration,{silent:!0});return}_.current&&(v(""),k(""),g([]),b(!1),_.current=!1,Z(),be())}}).catch(()=>{})}),[T,e,be,pe,Z]),a.useEffect(()=>{!i||_.current||C.current||N.current&&D.current.trim().length!==0&&Z()},[i,Z]),a.useEffect(()=>()=>{C.current&&(C.current.close(),C.current=null),E.current=null},[]),a.useMemo(()=>({activeSession:i,sessions:o,sessionsLoading:d,messages:m,messagesLoading:h,isStreaming:f,streamingText:y,streamingThinking:x,streamingToolCalls:w,pendingMessage:j,sendMessage:me,stopStreaming:He,clearPendingMessage:P,switchSession:xe,selectSession:q,startModelChat:ce,startFreshSession:De,refreshSessions:de,loadMessages:le,reloadMessages:be,skipNextSessionInitRef:A}),[i,o,d,m,h,f,y,x,w,j,me,He,P,xe,q,ce,De,de,le,be])}const p9=250;function iS(e,n){const[s,i]=a.useState(()=>{const v=ki(Tn.AGENTS,{maxAgeMs:Gr});return Array.isArray(v)?v:[]}),[r,o]=a.useState(()=>ki(Tn.AGENT_STATS,{maxAgeMs:Gr})??null),[l,d]=a.useState(!1),c=a.useRef(s.length>0||r!==null),m=a.useRef(0),p=a.useRef(0),h=a.useCallback(async(v,x)=>{const k=++m.current;c.current||d(!0);try{const w=n?.filterState,g=w&&w!=="all"?{state:w}:void 0,j=n?.showSystemAgents??!1,S={...g,...v,includeEphemeral:v?.includeEphemeral??j},C=x?.forceFresh?await br(S,e,{forceFresh:!0}):await br(S,e);if(k!==m.current)return;const E=Array.from(new Map(C.map(F=>[F.id,F])).values());i(E),es(Tn.AGENTS,E,{maxBytes:5e5}),c.current=c.current||E.length>0}catch(w){console.error("Failed to load agents:",w)}finally{k===m.current&&d(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=a.useCallback(async v=>{const x=++p.current;try{const k=v?.forceFresh?await Og(e,{forceFresh:!0}):await Og(e);if(x!==p.current)return;o(k),es(Tn.AGENT_STATS,k,{maxBytes:5e5}),c.current=!0}catch(k){console.error("Failed to load agent stats:",k)}},[e]);a.useEffect(()=>{h(),u()},[h,u]),a.useEffect(()=>{const v=e?`?projectId=${encodeURIComponent(e)}`:"";let x=null,k=!1,w=!1,g=!1;const j=async()=>{k=!0,w=!1;try{await Promise.all([h(void 0,{forceFresh:!0}),u({forceFresh:!0})])}finally{k=!1,!g&&w&&S()}},S=()=>{if(x||k){k&&(w=!0);return}x=setTimeout(()=>{x=null,j()},p9)},C=()=>{if(k){w=!0;return}S()},E=li(`/api/events${v}`,{events:{"agent:created":C,"agent:updated":C,"agent:deleted":C,"agent:stateChanged":C,"approval:requested":C,"approval:updated":C,"approval:decided":C}});return()=>{g=!0,x&&clearTimeout(x),E()}},[e,h,u]);const f=a.useCallback(async()=>{await Promise.all([h(void 0,{forceFresh:!0}),u({forceFresh:!0})])},[h,u]),b=n?.showSystemAgents??!1,y=s.filter(v=>v.state!=="active"&&v.state!=="running"?!1:b||!Y_(v));return{agents:s,activeAgents:y,stats:r,isLoading:l,loadAgents:h,loadStats:u,refreshAgents:f}}const dh=new Map,Id=new Map;function Ff(e){return e??"global"}function bp(e){return`${Tn.DISCOVERED_SKILLS_PREFIX}${Ff(e)}`}function _o(e){return ki(bp(e),{maxAgeMs:Gr})}function f9(e,n){for(const s of Id.get(e)??[])s(n)}async function g9(e){const n=Ff(e),s=dh.get(n);if(s)return s;const i=PR(e).finally(()=>{dh.delete(n)});return dh.set(n,i),i}function b9(e){const[n,s]=a.useState(()=>_o(e)??[]),[i,r]=a.useState(()=>_o(e)===null),o=a.useRef(_o(e)!==null),l=Ff(e);a.useEffect(()=>{const m=_o(e)??[];s(m),r(_o(e)===null),o.current=_o(e)!==null},[e]),a.useEffect(()=>{const m=Id.get(l)??new Set;return m.add(s),Id.set(l,m),()=>{m.delete(s),m.size===0&&Id.delete(l)}},[l]);const d=a.useCallback(async()=>{try{const m=await g9(e);o.current=!0,es(bp(e),m,{maxBytes:5e5}),f9(l,m)}catch{o.current||vs(bp(e))}finally{r(!1)}},[e,l]);a.useEffect(()=>{d()},[d]);const c=a.useCallback(async()=>{r(!0),await d()},[d]);return{skills:n,loading:i,refresh:c}}function v9(e,n){return e+n}function x9({visible:e,position:n,tasks:s,files:i,selectedIndex:r,onSelectTask:o,onSelectFile:l,loading:d}){const{t:c}=st("app");if(!e)return null;const m=s.length>0,p=i.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:h=>{h.preventDefault()},children:[d&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!d&&!m&&!p&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:c("fileMention.empty","No tasks or files found")}),!d&&(m||p)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[m&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:c("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":c("fileMention.taskMatches","Task matches"),children:s.map((h,u)=>{const f=u;return t.jsxs("li",{className:`file-mention-popup-item${f===r?" file-mention-popup-item--selected":""}`,onClick:()=>o(h),role:"option","aria-selected":f===r,"data-testid":`task-mention-item-${f}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Ck,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsxs("div",{className:"file-mention-popup-task-row",children:[t.jsx("span",{className:"file-mention-popup-task-id",children:h.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${h.column}`,children:h.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:h.title})]})]},h.id)})})]}),p&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:c("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":c("fileMention.fileMatches","File matches"),children:i.map((h,u)=>{const f=v9(s.length,u),b=X_(h.path);return t.jsxs("li",{className:`file-mention-popup-item${f===r?" file-mention-popup-item--selected":""}`,onClick:()=>l(h),role:"option","aria-selected":f===r,"data-testid":`file-mention-item-${f}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Nk,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:h.name}),b&&t.jsx("span",{className:"file-mention-popup-item-path",children:b})]})]},h.path)})})]})]})]})}const y9=200,k9=8,w9=8;function By(){return new DOMException("The operation was aborted.","AbortError")}function Uy(e,n){return n.aborted?Promise.reject(By()):new Promise((s,i)=>{const r=()=>i(By());n.addEventListener("abort",r,{once:!0}),e.then(o=>{n.removeEventListener("abort",r),s(o)},o=>{n.removeEventListener("abort",r),i(o)})})}function Hy(e,n,s){const i=e.slice(0,n),r=e.slice(n+1),o=r.match(/[\s]|$/),l=o?o.index??r.length:r.length,d=r.slice(l);return`${i}${s}${d}`}function j9(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[d,c]=a.useState(-1),[m,p]=a.useState([]),[h,u]=a.useState([]),[f,b]=a.useState(!1),[y,v]=a.useState(0),x=a.useRef(null),k=a.useRef(null),w=[...m.map(M=>({kind:"task",task:M})),...h.map(M=>({kind:"file",file:M}))];a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),k.current?.abort()},[]);const g=a.useCallback((M,D)=>{if(D<0||D>M.length){r(!1);return}const _=V=>/[a-zA-Z0-9/_.-]/.test(V);for(let V=D-1;V>=0;V--){if(M[V]==="#"){if(V===0){const $=M.slice(V+1,D);c(V),l($),v(0),r(!0);return}const N=M[V-1];if(/[\s,.;:!?'"()[\]{}]/.test(N)){const $=M.slice(V+1,D);c(V),l($),v(0),r(!0);return}r(!1);return}if(!_(M[V])){r(!1);return}}r(!1)},[]),j=a.useCallback(()=>{k.current?.abort(),r(!1),l(""),c(-1),p([]),u([]),v(0),b(!1)},[]),S=a.useCallback(async M=>{if(!M.trim()){p([]),u([]),b(!1);return}k.current?.abort();const D=new AbortController;k.current=D;try{b(!0);const[_,V]=await Promise.allSettled([Uy(Uk(20,0,n,M),D.signal),Uy(QM(M,s,n),D.signal)]);if(D.signal.aborted)return;const N=_.status==="fulfilled"?_.value.slice(0,k9).map(R=>({id:R.id,title:R.title??"",column:R.column})):[],$=V.status==="fulfilled"?V.value.files.slice(0,w9):[];p(N),u($),v(0)}catch(_){_.name!=="AbortError"&&(p([]),u([]))}finally{D.signal.aborted||b(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},y9),()=>{x.current&&clearTimeout(x.current)}},[o,i,S]);const C=a.useCallback((M,D)=>!i||d<0?D:Hy(D,d,`#${M.id}`),[i,d]),E=a.useCallback((M,D)=>!i||d<0?D:Hy(D,d,`#${M.path}`),[i,d]),F=a.useCallback((M,D)=>{if(!i||w.length===0)return!1;switch(M.key){case"ArrowDown":return M.preventDefault(),v(_=>Math.min(_+1,w.length-1)),!0;case"ArrowUp":return M.preventDefault(),v(_=>Math.max(_-1,0)),!0;case"Enter":case"Tab":return w[y]?(M.preventDefault(),!0):!1;case"Escape":return M.preventDefault(),j(),!0;default:return!1}},[i,w,y,j]);return{mentionActive:i,tasks:m,files:h,combinedItems:w,loading:f,mentionQuery:o,selectedIndex:y,setSelectedIndex:v,detectMention:g,selectTask:C,selectFile:E,dismissMention:j,handleKeyDown:F}}function aS(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[d,c]=a.useState(!1),[m,p]=a.useState(!1),[h,u]=a.useState(!1),[f,b]=a.useState(!1),[y,v]=a.useState(void 0),[x,k]=a.useState(7200*1e3),[w,g]=a.useState(!1),[j,S]=a.useState(20),[C,E]=a.useState(!1),[F,M]=a.useState(25),[D,_]=a.useState(!1),[V,N]=a.useState(!1),[$,R]=a.useState({}),[L,O]=a.useState(!1),[J,A]=a.useState(!1),[de,B]=a.useState(!1),[P,Z]=a.useState(!1),[T,ie]=a.useState(!1),[le,be]=a.useState(!0),Le=a.useRef(o),xe=a.useCallback(async()=>{const[pe,te]=await Promise.allSettled([Jk(e),yu(e)]);if(pe.status==="fulfilled"&&(s(pe.value.maxConcurrent),r(pe.value.rootDir)),te.status==="fulfilled"){const me=te.value;l(!!me.autoMerge);const se=me.testMode===!0,z=se||me.defaultProvider?.trim().toLowerCase()==="mock";c(se),p(z),u(!!me.globalPause),b(!!me.enginePaused),_(!!me.prAuthAvailable),v(me.taskStuckTimeoutMs),k(me.staleHighFanoutBlockerAgeThresholdMs??7200*1e3),E(me.showQuickChatFAB===!0),M(me.maxTotalRetriesBeforeFail??25),g(me.capacityRiskBannerEnabled===!0),S(me.capacityRiskTodoThreshold??20),R(me.experimentalFeatures??{});const Y=me.experimentalFeatures??{};O(Y.insights===!0),A(Y.memoryView===!0),B(Y.devServerView===!0||Y.devServer===!0),Z(Y.todoView===!0),ie(Y.goalsView===!0);const he=me.autoReloadOnVersionChange!==!1;be(he),qu(he)}N(!0)},[e]);a.useEffect(()=>{N(!1),R({}),O(!1),A(!1),B(!1),Z(!1),ie(!1),xe()},[xe]),a.useEffect(()=>{Le.current=o},[o]);const q=a.useCallback(async()=>{const pe=Le.current,te=!pe;Le.current=te,l(te);try{await Bc({autoMerge:te},e)}catch{Le.current=pe,l(pe)}},[e]),ce=a.useCallback(async()=>{const pe=!h;u(pe);try{await Bc({globalPause:pe,globalPauseReason:pe?"manual":void 0},e)}catch{u(!pe)}},[h,e]),De=a.useCallback(async()=>{const pe=!f;b(pe);try{await Bc({enginePaused:pe},e)}catch{b(!pe)}},[f,e]),He=a.useCallback(async()=>{const pe=!C;E(pe);try{await Bc({showQuickChatFAB:pe},e)}catch{E(!pe)}},[C,e]),qe=a.useCallback(async()=>{const pe=!le;be(pe),qu(pe);try{await Ms({autoReloadOnVersionChange:pe})}catch{be(!pe),qu(!pe)}},[le]);return{maxConcurrent:n,rootDir:i,autoMerge:o,testMode:d,isTestMode:m,globalPaused:h,enginePaused:f,taskStuckTimeoutMs:y,staleHighFanoutBlockerAgeThresholdMs:x,capacityRiskBannerEnabled:w,capacityRiskTodoThreshold:j,showQuickChatFAB:C,maxTotalRetriesBeforeFail:F,prAuthAvailable:D,settingsLoaded:V,experimentalFeatures:$,insightsEnabled:L,memoryEnabled:J,devServerEnabled:de,todosEnabled:P,goalsEnabled:T,autoReloadOnVersionChange:le,toggleAutoMerge:q,toggleGlobalPause:ce,toggleEnginePause:De,toggleShowQuickChatFAB:He,toggleAutoReloadOnVersionChange:qe,refresh:xe}}function jd(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function N9(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function uh(e,n){const s=N9(),i=n?.warm===!0,r=jd(),o=new Map;let l=!1,d=!1;return{mark(m){l||d||!s||o.has(m)||o.set(m,jd())},complete:m=>{if(!s||l||d){l=!0;return}l=!0,o.set("complete",jd());const p=Array.from(o.entries()).sort((b,y)=>b[1]-y[1]);let h=r;const u={};for(const[b,y]of p)u[b]=Math.max(0,y-h),h=y;const f=Math.max(0,jd()-r);try{console.debug("[room-open]",{roomId:e,warm:i,totalMs:f,phases:u,...m??{}})}catch{}},cancel(){d=!0,l=!0}}}const cr="fusion:chat-active-room";class S9 extends Error{roomId;constructor(n,s){super(n),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=s}}function vp(e){return[...e].sort((n,s)=>new Date(s.updatedAt).getTime()-new Date(n.updatedAt).getTime())}function Eo(e,n){const s=e.findIndex(r=>r.id===n.id);if(s===-1)return vp([n,...e]);const i=[...e];return i[s]=n,vp(i)}function Wa(e){try{return JSON.parse(e.data)}catch{return null}}function C9(e,n,s){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:e,role:"user",content:n,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...s?.length?{attachments:s}:{},createdAt:new Date().toISOString()}}function Vy(e,n,s){if(e.some(r=>r.id===n.id))return e;const i=s?e.findIndex(r=>r.id===s):-1;if(i>=0){const r=[...e];return r[i]=n,r}if(n.role==="user"){const r=e.findIndex(o=>o.role==="user"&&o.id.startsWith("temp-")&&o.content.trim()===n.content.trim());if(r>=0){const o=[...e];return o[r]=n,o}}return[...e,n]}function _9(e,n){const{t:s}=st("app"),i=`${Tn.CHAT_ROOMS}:${e??"global"}`,r=`${Tn.ACTIVE_CHAT_ROOM_ID}:${e??"global"}`,o=a.useCallback(R=>`${Tn.CHAT_ROOM_MESSAGES_PREFIX}${e??"global"}:${R}`,[e]),l=a.useCallback(R=>`${Tn.CHAT_ROOM_MEMBERS_PREFIX}${e??"global"}:${R}`,[e]),[d,c]=a.useState(()=>{const R=ki(i,{maxAgeMs:Gr});return Array.isArray(R)?R:[]}),[m,p]=a.useState(()=>d.length===0),[h,u]=a.useState(null),[f,b]=a.useState(()=>{const R=ki(r,{maxAgeMs:Fh});return R?d.find(L=>L.id===R)??null:null}),[y,v]=a.useState([]),[x,k]=a.useState([]),[w,g]=a.useState(!1),j=a.useRef(d),S=a.useRef(f),C=a.useRef(0),E=a.useRef(e);j.current=d,S.current=f,E.current!==e&&(E.current=e,C.current+=1);const F=a.useCallback(async R=>{if(!R){v([]),k([]),g(!1);return}const L=uh(R.id,{warm:!1});L.mark("select");const O=ki(o(R.id),{maxAgeMs:VP}),J=ki(l(R.id),{maxAgeMs:Gr}),A=Array.isArray(O)&&O.length>0,de=Array.isArray(J)&&J.length>0;A||de?(L.mark("cache-hit"),A&&(k(O),L.mark("hydrate")),de&&v(J),g(!1)):(k([]),g(!0));try{const[B,P]=await Promise.all([$R(R.id,e),Ju(R.id,{limit:100,order:"desc"},e)]);L.mark("members-fetch"),L.mark("messages-fetch"),es(l(R.id),B.members,{maxBytes:5e5}),es(o(R.id),P.messages,{maxBytes:5e5}),S.current?.id===R.id&&(v(B.members),k(P.messages),L.mark("hydrate"))}catch{!A&&!de&&(v([]),k([]))}finally{g(!1),L.complete({warm:A,membersCached:de})}},[l,o,e]),M=a.useCallback(async()=>{j.current.length===0&&p(!0);try{const R=await LR({},e),L=vp(R.rooms);c(L),es(i,L,{maxBytes:5e5}),u(null);const O=ki(r,{maxAgeMs:Fh})??cs(cr,e);if(O){const J=L.find(A=>A.id===O)??null;J?(b(J),F(J)):(sa(cr,e),es(r,"",{maxBytes:5e5}))}}catch(R){const L=R instanceof Error?R.message:s("chatRooms.error.failedToLoad","Failed to load chat rooms");u(L),n?.(L,"error")}finally{p(!1)}},[r,n,F,e,i]),D=a.useCallback(R=>{if(!R){S.current=null,b(null),sa(cr,e),es(r,"",{maxBytes:5e5}),F(null);return}const L=j.current.find(O=>O.id===R)??null;S.current=L,b(L),L&&(_s(cr,L.id,e),es(r,L.id,{maxBytes:5e5}),F(L))},[r,F,e]),_=a.useCallback(async R=>{const O=(await FR({name:R.name,memberAgentIds:R.memberAgentIds},e)).room;return c(J=>Eo(J,O)),S.current=O,b(O),_s(cr,O.id,e),es(r,O.id,{maxBytes:5e5}),await F(O),O},[r,F,e]),V=a.useCallback(async R=>{await OR(R,e),c(L=>L.filter(O=>O.id!==R)),es(o(R),[],{maxBytes:5e5}),es(l(R),[],{maxBytes:5e5}),S.current?.id===R&&(S.current=null,b(null),v([]),k([]),sa(cr,e),es(r,"",{maxBytes:5e5}))},[r,l,o,e]),N=a.useCallback(async(R,L)=>{const O=S.current,J=O?.id;if(!J)throw new Error(s("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const A=uh(J,{warm:!1}),de=L?.files?.map(Z=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,filename:Z.name,originalName:Z.name,mimeType:Z.type||"application/octet-stream",size:Z.size,createdAt:new Date().toISOString()})),B=C9(J,R,de?.length?de:L?.attachments);S.current?.id===J&&k(Z=>{const T=[...Z,B];return es(o(J),T,{maxBytes:5e5}),T});let P=!1;try{const Z=[];if(L?.files?.length)for(const be of L.files)try{const Le=await zR(J,be,e);Z.push(Le.attachment)}catch{throw new Error(s("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:be.name}))}const T=[...L?.attachments??[],...Z],ie=await UR(J,{content:R,...T.length?{attachments:T}:{}},e);P=!0,ie.message?.createdAt&&O&&c(be=>Eo(be,{...O,updatedAt:ie.message.createdAt})),S.current?.id===J&&k(be=>{const Le=Vy(be,ie.message,B.id);return es(o(J),Le,{maxBytes:5e5}),Le});const le=await Ju(J,{limit:100,order:"desc"},e);if(es(o(J),le.messages,{maxBytes:5e5}),S.current?.id!==J)return;k(le.messages),A.mark("hydrate")}catch(Z){let T=null;try{const le=await Ju(J,{limit:100,order:"desc"},e);T=le.messages,es(o(J),le.messages,{maxBytes:5e5}),S.current?.id===J&&(k(le.messages),A.mark("hydrate"))}catch{S.current?.id===J&&k(le=>{const be=le.filter(Le=>Le.id!==B.id);return es(o(J),be,{maxBytes:5e5}),be})}const ie=T?.some(le=>le.role==="user"&&le.content.trim()===B.content.trim());if(P||ie){const le=Z instanceof Error&&Z.message.trim()?Z.message:s("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new S9(le,J)}throw Z}finally{A.complete({source:"send-room-message"})}},[o,e]),$=a.useCallback(async R=>{!R||!j.current.some(L=>L.id===R)||(await HR(R,e),es(o(R),[],{maxBytes:5e5}),S.current?.id===R&&k([]))},[o,e]);return a.useEffect(()=>{M()},[M]),a.useEffect(()=>{const R=C.current,L=e?`/api/events?projectId=${encodeURIComponent(e)}`:"/api/events";return li(L,{onReconnect:()=>{Gs({view:"useChatRooms",trigger:"sse-reconnect",projectId:e,replayAttempted:!1});const O=S.current?.id;if(O){const J=uh(O,{warm:!0});J.mark("sse-reconnect-refresh"),M().finally(()=>J.complete({source:"sse-reconnect"}));return}M()},events:{"chat:room:created":O=>{if(C.current!==R)return;const J=Wa(O);J&&c(A=>Eo(A,J))},"chat:room:updated":O=>{if(C.current!==R)return;const J=Wa(O);J&&(c(A=>Eo(A,J)),S.current?.id===J.id&&b(J))},"chat:room:deleted":O=>{if(C.current!==R)return;const J=Wa(O);J?.id&&(c(A=>A.filter(de=>de.id!==J.id)),es(o(J.id),[],{maxBytes:5e5}),es(l(J.id),[],{maxBytes:5e5}),S.current?.id===J.id&&(S.current=null,b(null),v([]),k([]),sa(cr,e),es(r,"",{maxBytes:5e5})))},"chat:room:member:added":O=>{if(C.current!==R)return;const J=Wa(O);!J||S.current?.id!==J.roomId||v(A=>{if(A.some(B=>B.agentId===J.agentId))return A;const de=[...A,J];return es(l(J.roomId),de,{maxBytes:5e5}),de})},"chat:room:member:removed":O=>{if(C.current!==R)return;const J=Wa(O);!J||S.current?.id!==J.roomId||v(A=>{const de=A.filter(B=>B.agentId!==J.agentId);return es(l(J.roomId),de,{maxBytes:5e5}),de})},"chat:room:message:added":O=>{if(C.current!==R)return;const J=Wa(O);J&&(c(A=>{const de=A.find(B=>B.id===J.roomId);return de?Eo(A,{...de,updatedAt:J.createdAt}):A}),S.current?.id===J.roomId&&k(A=>{const de=Vy(A,J);return de===A?A:(es(o(J.roomId),de,{maxBytes:5e5}),de)}))},"chat:room:message:updated":O=>{if(C.current!==R)return;const J=Wa(O);!J||S.current?.id!==J.roomId||k(A=>{const de=A.map(B=>B.id===J.id?J:B);return es(o(J.roomId),de,{maxBytes:5e5}),de})},"chat:room:message:deleted":O=>{if(C.current!==R)return;const J=Wa(O);J?.id&&k(A=>{const de=A.filter(P=>P.id!==J.id),B=S.current?.id;return B&&es(o(B),de,{maxBytes:5e5}),de})},"chat:room:messages:cleared":O=>{if(C.current!==R)return;const J=Wa(O);J?.roomId&&(es(o(J.roomId),[],{maxBytes:5e5}),S.current?.id===J.roomId&&k([]),c(A=>{const de=A.find(B=>B.id===J.roomId);return de?Eo(A,{...de,updatedAt:new Date().toISOString()}):A}))}}})},[r,l,o,e,M]),a.useEffect(()=>{f&&(d.some(R=>R.id===f.id)||(S.current=null,b(null),v([]),k([]),sa(cr,e),es(r,"",{maxBytes:5e5})))},[f,r,e,d]),{rooms:d,roomsLoading:m,roomsError:h,activeRoom:f,activeRoomMembers:y,messages:x,messagesLoading:w,selectRoom:D,createRoom:_,deleteRoom:V,sendRoomMessage:N,clearRoom:$,refreshRooms:M}}const $l={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},qy=200;function xp(e){if(!e)return null;const n=new Date(e).getTime();return Number.isFinite(n)?n:null}function rS(e){const n=Object.entries(e);if(n.length<=qy)return e;const s=n.map(([i,r])=>({id:i,timestamp:r,value:xp(r)??0})).sort((i,r)=>r.value-i.value).slice(0,qy);return Object.fromEntries(s.map(({id:i,timestamp:r})=>[i,r]))}function Nd(e){if(!e)return{};try{const n=JSON.parse(e);if(!n||typeof n!="object")return{};const s={};for(const[i,r]of Object.entries(n))typeof i=="string"&&typeof r=="string"&&(s[i]=r);return rS(s)}catch{return{}}}function E9(e){const[n,s]=a.useState(()=>{try{return Nd(cs($l.direct,e))}catch{return{}}}),[i,r]=a.useState(()=>{try{return Nd(cs($l.room,e))}catch{return{}}});a.useEffect(()=>{try{s(Nd(cs($l.direct,e)))}catch{s({})}try{r(Nd(cs($l.room,e)))}catch{r({})}},[e]);const o=a.useMemo(()=>({direct:n,room:i}),[n,i]),l=a.useCallback((h,u)=>{const f=rS(u);try{_s($l[h],JSON.stringify(f),e)}catch{}return f},[e]),d=a.useCallback((h,u)=>{if(h==="direct"){s(f=>l(h,u(f)));return}r(f=>l(h,u(f)))},[l]),c=a.useCallback((h,u,f)=>{const b=xp(f);if(b===null)return!1;const y=o[h][u],v=xp(y);return v===null?!0:b>v},[o]),m=a.useCallback((h,u,f)=>{if(!u)return;const b=f??new Date().toISOString();d(h,y=>({...y,[u]:b}))},[d]),p=a.useCallback((h,u)=>{u.length!==0&&d(h,f=>{const b={...f};for(const y of u)y.id&&(b[y.id]=y.lastActivityAt??new Date().toISOString());return b})},[d]);return{isUnread:c,markRead:m,markAllRead:p}}function M9(e){return`${e.name?.trim()||e.id} (${e.role})`}function zl(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 A9(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 T9(e){return Math.max(40,Math.min(e,640))}function Dd(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function R9(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{const r=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${s}=${Dd(r,50)}`}).join(", ")}function P9(e){if(e===void 0)return null;if(typeof e=="string")return Dd(e,200);try{return Dd(JSON.stringify(e),200)}catch{return Dd(String(e),200)}}function oS(e,n,s){if(!e||e.length===0)return null;const i=(f,b)=>{const y=f.status==="running",v=f.status==="completed"&&f.isError,x=R9(f.args),k=P9(f.result),w=null,g=y?"running":v?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${y?" chat-tool-call--running":""}${v?" chat-tool-call--error":""}`,open:y,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}),w,t.jsx("span",{className:"chat-tool-call-status-text",children:g})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[x&&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:x})]}),k&&t.jsxs("div",{className:`chat-tool-call-row${v?" 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:k})]})]})]},`${f.toolName}-${b}`)},r="chat-tool-calls chat-tool-calls--compact";if(e.length===1)return t.jsxs("div",{className:r,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(rg,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.toolCalls","Tool calls")})]}),i(e[0],0)]});const o=e.filter(f=>f.status==="running").length,l=e.filter(f=>f.status==="completed"&&f.isError).length,d=o>0,c=Array.from(new Set(e.map(f=>f.toolName))),m=c.slice(0,5),p=Math.max(0,c.length-m.length),h=p>0?`${m.join(", ")}, +${p} more`:m.join(", "),u=d?`(${o} running)`:l>0?`(${l} ${l===1?"error":"errors"})`:null;return t.jsx("div",{className:r,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group chat-tool-calls-group--compact","data-testid":"chat-tool-calls-group",open:d,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(rg,{size:12,"aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-calls-count",children:s("chat.toolCallsCount","{{count}} tool calls",{count:e.length})}),t.jsx("span",{className:"chat-tool-calls-names",title:h,children:h}),u&&t.jsx("span",{className:"chat-tool-calls-group-status",children:u})]}),e.map((f,b)=>i(f,b))]})})}const lS={p:({children:e,...n})=>t.jsx("p",{...n,children:hi(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:hi(e)}),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 Wy(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",i=n[2]??"",r=n.index+s.length;return{filter:i,start:r,end:e.length}}function I9(e,n){const s=e.slice(0,n),i=/(^|[\s])@([\w-]*)$/.exec(s);if(!i)return null;const r=i[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Sd={width:320,height:400},D9=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"]),L9=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function F9(e){return e.type.startsWith("image/")}function O9(e){if(D9.has(e.type))return!0;const n=e.name.toLowerCase();return L9.some(s=>n.endsWith(s))}const Mo={width:280,height:260},Ni=768,Ao=8;function $9(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const g=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return g&&parseFloat(g)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const g=`fusion-quick-chat-position-${e||"default"}`;try{const j=localStorage.getItem(g);if(j){const S=JSON.parse(j);if(typeof S.x=="number"&&typeof S.y=="number"&&!isNaN(S.x)&&!isNaN(S.y))return S}}catch{}return i()}),[l,d]=a.useState(!1),c=a.useRef(null),m=a.useRef(r),p=a.useRef(null),h=a.useRef(null),u=n??a.useRef(!1);a.useEffect(()=>{m.current=r},[r]);const f=a.useCallback(g=>{if(typeof window>"u")return g;const j=48,S=window.innerWidth<=768?4:8,C=window.innerWidth<=768?44:0,E=window.innerWidth>768?s():0,F=window.innerWidth-j-S,M=window.innerHeight-j-S-C-E;return{x:Math.max(S,Math.min(F,g.x)),y:Math.max(S,Math.min(M,g.y))}},[s]),b=a.useCallback(g=>{if(typeof window>"u")return;const j=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(j,JSON.stringify(g))}catch{}},[e]),y=a.useCallback(()=>{if(!c.current)return;const g=h.current,j=p.current;g&&j!==null&&typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(j),c.current=null,p.current=null,h.current=null,d(!1),document.body.style.userSelect="",u.current&&b(m.current),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x),document.removeEventListener("pointercancel",k)},[b]),v=a.useCallback(g=>{if(!c.current||p.current!==null&&g.pointerId!==p.current)return;const j=g.clientX-c.current.pointerX,S=g.clientY-c.current.pointerY;if((Math.abs(j)>=5||Math.abs(S)>=5)&&(u.current=!0),!u.current)return;const C=c.current.x-j,E=c.current.y-S,F=f({x:C,y:E});m.current=F,o(F)},[f]),x=a.useCallback(g=>{p.current!==null&&g.pointerId!==p.current||y()},[y]),k=a.useCallback(g=>{p.current!==null&&g.pointerId!==p.current||y()},[y]),w=a.useCallback(g=>{if(g.button!==0&&g.pointerType==="mouse")return;const j=g.currentTarget;g.preventDefault(),typeof j.setPointerCapture=="function"&&j.setPointerCapture(g.pointerId);const S=m.current;c.current={x:S.x,y:S.y,pointerX:g.clientX,pointerY:g.clientY},p.current=g.pointerId,h.current=j,u.current=!1,d(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",v,{passive:!0}),document.addEventListener("pointerup",x),document.addEventListener("pointercancel",k)},[k,v,x]);return a.useEffect(()=>()=>{document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",x),document.removeEventListener("pointercancel",k),document.body.style.userSelect=""},[k,v,x]),{position:r,isDragging:l,handlePointerDown:w}}function z9(e,n,s,i){const r=`fusion:quick-chat-size-${e||"default"}`,o=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Ni,[]),l=a.useCallback((f,b,y)=>{if(typeof window>"u")return f;const v=Math.max(Mo.width,window.innerWidth-b-Ao),x=Math.max(Mo.height,window.innerHeight-y-Ao);return{width:Math.max(Mo.width,Math.min(v,f.width)),height:Math.max(Mo.height,Math.min(x,f.height))}},[]),d=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ni)return Sd;try{const f=localStorage.getItem(r);if(!f)return Sd;const b=JSON.parse(f);return typeof b.width!="number"||typeof b.height!="number"?Sd:{width:b.width,height:b.height}}catch{return Sd}},[r]),[c,m]=a.useState(d),[p,h]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!i||!o())return;const f={right:n+p.right,bottom:s+p.bottom};m(b=>l(b,f.right,f.bottom))},[p,l,s,n,o,i]),a.useEffect(()=>{if(!(!i||!o()))try{localStorage.setItem(r,JSON.stringify(c))}catch{}},[o,i,c,r]);const u=a.useCallback(f=>{if(!o())return;const b=f.currentTarget.dataset.resizeDirection;if(!b)return;f.preventDefault(),f.stopPropagation();const y=f.currentTarget;typeof y.setPointerCapture=="function"&&y.setPointerCapture(f.pointerId);const v={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:p.right,anchorBottom:p.bottom};document.body.style.userSelect="none";const x=w=>{const g=w.clientX-v.pointerX,j=w.clientY-v.pointerY;let S=v.width,C=v.height,E=v.anchorRight,F=v.anchorBottom;if(b.includes("w")&&(S=v.width-g),b.includes("e")){const $=g;S=v.width+$,E=v.anchorRight-$}if(b.includes("n")&&(C=v.height-j),b.includes("s")){const $=j;C=v.height+$,F=v.anchorBottom-$}const M=n+E,D=s+F,_=l({width:S,height:C},M,D),V=Math.max(Ao-n,Math.min(window.innerWidth-n-Mo.width-Ao,E)),N=Math.max(Ao-s,Math.min(window.innerHeight-s-Mo.height-Ao,F));m(_),h({right:V,bottom:N})},k=w=>{typeof y.releasePointerCapture=="function"&&y.releasePointerCapture(w.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",x),document.removeEventListener("pointerup",k);try{localStorage.setItem(r,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",x),document.addEventListener("pointerup",k)},[p.bottom,p.right,l,s,n,o,c.height,c.width,r]);return{panelSize:c,anchorOffset:p,handleResizeStart:u}}const mh=a.memo(function({message:n,forcePlain:s,mentionAgentsByName:i,roomContext:r,projectId:o,onToggleRender:l}){const{t:d}=st("app"),c=n.role==="user",m=a.useMemo(()=>{if(!c)return null;const u=n.content,f=/@([\w-]+)/g,b=[];let y=0,v=f.exec(u);for(;v;){const[x,k=""]=v,w=v.index;w>y&&b.push(u.slice(y,w));const g=k.replace(/_/g," ").toLowerCase(),j=i.get(g);if(j){const S=!!(r&&!r.memberIds.has(j.id)),C=S?`Not a member of ${r?.roomName}`:void 0;b.push(t.jsxs("span",{className:`chat-mention-chip${S?" chat-mention-chip--non-member":""}`,title:C,"aria-label":C,children:["@",j.name.replace(/\s+/g,"_")]},`${j.id}-${w}`))}else b.push(x);y=w+x.length,v=f.exec(u)}return y<u.length&&b.push(u.slice(y)),b.length===0?u:b},[c,n.content,i,r]),p=a.useMemo(()=>c?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Hs(n.content)}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Di,{remarkPlugins:[Li],components:lS,children:n.content})}),[c,s,n.content]),h=a.useMemo(()=>{if(!n.attachments?.length||!n.roomId)return null;const u=BR(n.roomId,o);return t.jsx("div",{className:"chat-message-attachments",children:n.attachments.map(f=>{const b=`${u}${encodeURIComponent(f.filename)}`,y=f.mimeType.startsWith("image/");return t.jsx("a",{className:"chat-message-attachment",href:b,target:"_blank",rel:"noreferrer","data-testid":"quick-chat-message-attachment",children:y?t.jsx("img",{src:b,alt:f.originalName,className:"chat-attachment-image",loading:"lazy"}):t.jsx("span",{children:f.originalName})},f.id)})})},[n.attachments,n.roomId,o]);return t.jsxs("div",{className:`quick-chat-panel-message ${c?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[c?t.jsx("p",{children:m}):t.jsxs(t.Fragment,{children:[p,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?d("chat.showRenderedMarkdown","Show rendered markdown"):d("chat.showPlainText","Show plain text"),onClick:()=>l(n.id),children:s?t.jsx(jp,{size:14}):t.jsx(bc,{size:14})})]}),h,oS(n.toolCalls,!0,d)]})});function B9({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:d,onToggleModelFavorite:c,roomContext:m=null}){const{t:p}=st("app"),{agents:h}=iS(e),{models:u,defaultProvider:f,defaultModelId:b,loading:y}=kf(),{skills:v,loading:x}=b9(e),[k,w]=a.useState(!1),g=i!==void 0,j=g?i:k,S=g?ne=>{r?.(typeof ne=="function"?ne(j):ne)}:w,{keyboardOpen:C}=Xa({enabled:j}),E=Ji(),F=E==="mobile",[M,D]=a.useState("agent"),[_,V]=a.useState(""),[N,$]=a.useState(!1),[R,L]=a.useState(!1),[O,J]=a.useState("model"),[A,de]=a.useState(""),[B,P]=a.useState(""),[Z,T]=a.useState(""),[ie,le]=a.useState(""),[be,Le]=a.useState(""),[xe,q]=a.useState(!1),[ce,De]=a.useState(""),[He,qe]=a.useState(0),[pe,te]=a.useState(""),[me,se]=a.useState(!1),[z,Y]=a.useState(0),[he,X]=a.useState(-1),[ye,ot]=a.useState(()=>new Set),[ue,je]=a.useState(!1),[$e,Ce]=a.useState([]),[We,ke]=a.useState(!1),[Ee,Ze]=a.useState(!1),[,Ke]=a.useState(!1),[dt,Fe]=a.useState({top:0,left:0}),nt=j9({projectId:e}),Nt=a.useCallback(ne=>{if(!ne||!nt.mentionActive)return;const Ue=ne.getBoundingClientRect();Fe({top:Ue.top-260,left:Ue.left+8})},[nt.mentionActive]),Ft=a.useRef(!1),ze=a.useRef(!1),it=a.useRef(!1),Mt=a.useRef(""),Ht=a.useRef(!1),Me=a.useRef(!1),Ae=a.useRef(_),ee=a.useRef(Z),Ie=a.useRef(0),Pe=a.useRef(null),oe=a.useRef(null),re=a.useRef(0),{position:_e,isDragging:fe,handlePointerDown:Xe}=$9(e,Ft),kt=_e.y+60,{panelSize:Rt,anchorOffset:Vt,handleResizeStart:Pt}=z9(e,_e.x,kt,j),bt=typeof window<"u"&&window.innerWidth>Ni,{activeSession:pt,messages:ft,isStreaming:_t,streamingText:Yt,streamingThinking:on,streamingToolCalls:An,sessions:vn,sessionsLoading:Qt,messagesLoading:sn,sendMessage:mn,stopStreaming:Kt,pendingMessage:fn,clearPendingMessage:$n,switchSession:On,selectSession:xn,startModelChat:Vn,startFreshSession:Rn,refreshSessions:Pn,skipNextSessionInitRef:zn}=h9(e,n),{experimentalFeatures:Nn}=aS(),dn=Nn?.chatRooms===!0,Tt=_9(e,n),{isUnread:Yn,markRead:cn}=E9(e),Bn=a.useRef(null),kn=a.useRef(null),pn=a.useRef(null),un=a.useRef(null),At=a.useRef(null),an=a.useRef(null),Wn=a.useRef([]),Xn=a.useRef(!1),G=a.useRef(!1),Oe=a.useRef(!1),yt=a.useRef(null),Gt=a.useRef(!1),Sn=a.useRef(!1),Un=a.useRef({isOpen:!1,sessionId:null});a.useEffect(()=>{if(!j||typeof window>"u"||typeof document>"u"||window.innerWidth>Ni)return;const ne=window.scrollY,Ue=document.documentElement,Je=document.body,qt={htmlOverflow:Ue.style.overflow,bodyOverflow:Je.style.overflow};return window.scrollTo(0,0),Ue.style.overflow="hidden",Je.style.overflow="hidden",()=>{Ue.style.overflow=qt.htmlOverflow,Je.style.overflow=qt.bodyOverflow,window.scrollTo(0,ne)}},[j]),a.useLayoutEffect(()=>{if(!j||typeof window>"u"||!window.visualViewport)return;const ne=Bn.current;if(!ne)return;const Ue=window.visualViewport,Je=()=>{Gt.current||(ne.style.setProperty("--vv-height",`${Ue.height}px`),ne.style.setProperty("--vv-offset-top",`${Ue.offsetTop||0}px`))};return Je(),Ue.addEventListener("resize",Je),Ue.addEventListener("scroll",Je),()=>{Ue.removeEventListener("resize",Je),Ue.removeEventListener("scroll",Je)}},[j]);const bn=Z||ie,gn=a.useMemo(()=>zl(bn),[bn]),ps=a.useMemo(()=>M==="model"&&pt?.modelProvider&&pt?.modelId?`${pt.modelProvider}/${pt.modelId}`:bn,[pt?.modelId,pt?.modelProvider,M,bn]),Ne=a.useMemo(()=>zl(ps),[ps]),ae=a.useMemo(()=>u.find(ne=>`${ne.provider}/${ne.id}`===ps)??null,[ps,u]),Se=a.useMemo(()=>A9(ae,Ne),[ae,Ne]),ut=a.useMemo(()=>M==="model"?gn?`${$r}::${gn.modelProvider}/${gn.modelId}`:"":_?`${_}::`:"",[M,_,gn]),It=M==="agent"?!!_:!!gn,ht=dn&&!!Tt.activeRoom,et=a.useMemo(()=>ht?Tt.messages.map(ne=>({id:ne.id,sessionId:ne.roomId,roomId:ne.roomId,role:ne.role,content:ne.content,thinkingOutput:ne.thinkingOutput,toolCalls:void 0,attachments:ne.attachments,createdAt:ne.createdAt})):ft,[ft,ht,Tt.messages]),Ut=ht?!1:!It||!pt,$t=be.trim().length===0&&$e.length===0||!ht&&!It||!ht&&!pt,rn=a.useMemo(()=>!!_&&vn.some(ne=>!ne.modelProvider&&!ne.modelId&&ne.agentId===_),[_,vn]);a.useEffect(()=>{Ae.current=_},[_]),a.useEffect(()=>{ee.current=Z},[Z]),a.useEffect(()=>{if(h.length===0){V(""),D("model");return}if(Ht.current&&rn)return;h.some(Ue=>Ue.id===_)||V(h[0]?.id??"")},[h,rn,_]),a.useEffect(()=>{if(j&&(ze.current||(ze.current=!0,it.current=!1),!(y||!ze.current||it.current))){if(!ee.current&&u.length>0){if(f&&b){const Ue=`${f}/${b}`;if(u.some(qt=>`${qt.provider}/${qt.id}`===Ue)){le(Ue),ee.current||T(Ue),Ht.current||D("model"),it.current=!0;return}}le("");const ne=u[0];ne&&!ee.current&&T(`${ne.provider}/${ne.id}`)}it.current=!0}},[b,f,j,u,y]),a.useEffect(()=>{j&&Pn()},[j,Pn]),a.useEffect(()=>{if(!j||Qt||Ht.current||vn.length===0)return;const ne=vn.filter(os=>os.status!=="archived"),Ue=c9(e),Je=Ue?ne.find(os=>os.id===Ue)??null:null,qt=os=>{if(!os)return 0;const fs=Date.parse(os);return Number.isFinite(fs)?fs:0},En=[...ne].sort((os,fs)=>{const ws=Math.max(qt(os.lastMessageAt),qt(os.updatedAt));return Math.max(qt(fs.lastMessageAt),qt(fs.updatedAt))-ws})[0],yn=Je??En;yn?(yn.modelProvider&&yn.modelId?(D("model"),T(`${yn.modelProvider}/${yn.modelId}`)):(D("agent"),V(yn.agentId)),Me.current=!0,xn(yn)):Me.current=!1,Ht.current=!0},[j,e,xn,vn,Qt]),a.useEffect(()=>{if(!j||!Ht.current&&vn.length===0&&ze.current&&!it.current)return;if(!ut){Mt.current="";return}if(zn.current){Mt.current=ut;return}const Ue=ut===Mt.current&&!pt&&!Qt;if(Me.current){Me.current=!1,Mt.current=ut;return}if(!(ut===Mt.current&&!Ue)){if(Mt.current=ut,M==="model"&&gn){Vn(gn.modelProvider,gn.modelId);return}M==="agent"&&_&&On(_)}},[j,M,gn,_,ut,pt,Qt,Vn,On,zn]),a.useEffect(()=>{j||(se(!1),te(""),X(-1),q(!1),De(""),qe(0),Wn.current.forEach(ne=>{ne.previewUrl&&URL.revokeObjectURL(ne.previewUrl)}),Ce([]))},[j]),a.useEffect(()=>{Ht.current=!1,Me.current=!1,ze.current=!1,it.current=!1,Mt.current=""},[e]),a.useEffect(()=>{Wn.current=$e},[$e]),a.useEffect(()=>{if(!j){Xn.current=!1;return}typeof window>"u"||(Xn.current=window.innerWidth<=Ni)},[j]),a.useEffect(()=>{if(!j||Ut||!Xn.current)return;const ne=un.current;if(!ne)return;const Ue=document.activeElement,Je=Ue?Bn.current?.contains(Ue):!1,qt=Ue===document.body,En=Ue===yt.current;if(!Je&&!qt&&!En){Xn.current=!1;return}if(En){ne.focus({preventScroll:!0}),Xn.current=!1;return}const yn=requestAnimationFrame(()=>{ne.focus(),Xn.current=!1});return()=>cancelAnimationFrame(yn)},[j,Ut]),a.useEffect(()=>()=>{Wn.current.forEach(ne=>{ne.previewUrl&&URL.revokeObjectURL(ne.previewUrl)})},[]);const Cn=a.useCallback(()=>{$(!0),J("model"),de(h[0]?.id??""),P(Z||ie||"")},[h,ie,Z]),ve=a.useMemo(()=>h.find(ne=>ne.id===_)??null,[h,_]),at=a.useMemo(()=>{const ne=ce.trim().toLowerCase();return(ne?v.filter(Je=>Je.name.toLowerCase().includes(ne)):v).slice(0,10)},[v,ce]),Ge=a.useMemo(()=>{const ne=h.filter(qt=>tS(qt.name,pe));if(!m)return ne;const Ue=ne.filter(qt=>m.memberIds.has(qt.id));if(pe.trim().length===0)return Ue;const Je=ne.filter(qt=>!m.memberIds.has(qt.id));return[...Ue,...Je]},[h,pe,m]),tt=a.useMemo(()=>{const ne=new Map;for(const Ue of h)ne.set(Ue.name.toLowerCase(),Ue);return ne},[h]),gt=a.useMemo(()=>at.map(ne=>ne.id).join(" "),[at]);a.useEffect(()=>{qe(0)},[gt]),a.useEffect(()=>{Y(0)},[pe,me]),a.useEffect(()=>()=>{Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null),oe.current!==null&&(window.clearTimeout(oe.current),oe.current=null)},[]),a.useEffect(()=>{if(!j)return;const ne=Je=>{const qt=Je.target;Bn.current?.contains(qt)||kn.current?.contains(qt)||qt.closest(".model-combobox-dropdown--portal")||S(!1)},Ue=Je=>{Je.key==="Escape"&&S(!1)};return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Ue),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Ue)}},[j,S]);const St=a.useCallback(()=>{const ne=pn.current;if(!ne)return;const Je=ne.scrollTop+ne.clientHeight>=ne.scrollHeight-50;Ze(!Je),Sn.current=!Je},[]),Xt=a.useCallback(ne=>{if(!ne.isConnected)return;let Ue=0,Je=0,qt=-1;const En=6,yn=()=>{if(ne.isConnected){if(ne.scrollTop=ne.scrollHeight,ne.scrollHeight===qt?Je+=1:(Je=0,qt=ne.scrollHeight),Ue+=1,Ue>=En||Je>=2){Ze(!1),Sn.current=!1;return}window.requestAnimationFrame(yn)}};yn()},[]),ss=a.useCallback(()=>{const ne=pn.current;ne&&Xt(ne)},[Xt]);a.useLayoutEffect(()=>{const ne=ht?Tt.activeRoom?.id??null:pt?.id??null,Ue=Un.current;if(Un.current={isOpen:j,sessionId:ne},!j||!ne)return;const Je=!Ue.isOpen&&j,qt=Ue.isOpen&&Ue.sessionId!==ne;if(!Je&&!qt)return;const En=pn.current;En&&Xt(En)},[j,pt?.id,Xt,ht,Tt.activeRoom?.id]),a.useEffect(()=>{if(!F||!j||!pt)return;const ne=()=>{const Je=pn.current;Je&&Xt(Je)},Ue=()=>{document.visibilityState==="visible"&&ne()};return document.addEventListener("visibilitychange",Ue),window.addEventListener("pageshow",ne),()=>{document.removeEventListener("visibilitychange",Ue),window.removeEventListener("pageshow",ne)}},[F,j,pt,Xt]),a.useEffect(()=>{j&&(Sn.current||ss())},[et,Yt,on,_t,j,ht,ss]),a.useEffect(()=>{pt?.id&&cn("direct",pt.id,pt.lastMessageAt??pt.updatedAt)},[pt?.id,pt?.lastMessageAt,pt?.updatedAt,cn]),a.useEffect(()=>{Tt.activeRoom?.id&&cn("room",Tt.activeRoom.id,Tt.activeRoom.updatedAt)},[cn,Tt.activeRoom?.id,Tt.activeRoom?.updatedAt]),a.useEffect(()=>{if(j){if(Tt.activeRoom?.id){cn("room",Tt.activeRoom.id,Tt.activeRoom.updatedAt);return}pt?.id&&cn("direct",pt.id,pt.lastMessageAt??pt.updatedAt)}},[pt?.id,pt?.lastMessageAt,pt?.updatedAt,j,cn,Tt.activeRoom?.id,Tt.activeRoom?.updatedAt]),a.useEffect(()=>{if(!_t){if(Tt.activeRoom?.id&&Tt.messages.length>0){const ne=Tt.messages[Tt.messages.length-1];cn("room",Tt.activeRoom.id,ne?.createdAt??Tt.activeRoom.updatedAt);return}if(pt?.id&&ft.length>0){const ne=ft[ft.length-1];cn("direct",pt.id,ne?.createdAt??pt.lastMessageAt??pt.updatedAt)}}},[pt?.id,pt?.lastMessageAt,pt?.updatedAt,_t,cn,ft,Tt.activeRoom?.id,Tt.activeRoom?.updatedAt,Tt.messages]);const Ts=a.useMemo(()=>{const ne=new Map(h.map(Je=>[Je.id,Je.name?.trim()||Je.id])),Ue=new Map(u.map(Je=>[`${Je.provider}/${Je.id}`,Je.name?.trim()||""]));return vn.map((Je,qt)=>{const En=Je.title?.trim()||`Session ${qt+1}`;let yn=null;if(Je.agentId&&Je.agentId!==$r)yn=ne.get(Je.agentId)||Je.agentId;else if(Je.modelProvider&&Je.modelId){const os=`${Je.modelProvider}/${Je.modelId}`,fs=Ue.get(os);yn=fs?`${fs} [${os}]`:os}return{id:Je.id,label:yn?`${En} — ${yn}`:En}})},[h,u,vn]),Ls=a.useMemo(()=>dn?Tt.rooms:[],[dn,Tt.rooms]),rs=dn&&Ls.length>0,ei=a.useMemo(()=>{if(rs&&ht&&Tt.activeRoom)return`#${Tt.activeRoom.name}`;const ne=Ts.find(Ue=>Ue.id===pt?.id);return ne?ne.label:Qt?p("chat.loadingSessions","Loading sessions…"):p("chat.selectSession","Select a session")},[pt?.id,ht,Tt.activeRoom,Ts,Qt,rs]);a.useEffect(()=>{j||L(!1)},[j]),a.useEffect(()=>{if(!R)return;const ne=Je=>{const qt=Je.target;At.current?.contains(qt)||L(!1)},Ue=Je=>{Je.key==="Escape"&&L(!1)};return document.addEventListener("mousedown",ne),document.addEventListener("keydown",Ue),()=>{document.removeEventListener("mousedown",ne),document.removeEventListener("keydown",Ue)}},[R]);const Mi=a.useMemo(()=>ht&&Tt.activeRoom?p("chat.messageRoomPlaceholder","Message #{{name}}",{name:Tt.activeRoom.name}):M==="agent"?ve?p("chat.messageAgentPlaceholder","Message {{name}}",{name:ve.name||ve.id}):p("chat.selectAgentPlaceholder","Select an agent to start chatting"):Se?p("chat.messageModelPlaceholder","Message {{name}}",{name:Se}):p("chat.selectModelPlaceholder","Select a model to start chatting"),[M,ht,Tt.activeRoom,ve,Se,p]),ti=a.useCallback(ne=>{const Ue=vn.find(Je=>Je.id===ne);if(Ue){if(ht&&Tt.selectRoom(null),cn("direct",Ue.id,Ue.lastMessageAt??Ue.updatedAt),Ht.current=!0,Ue.modelProvider&&Ue.modelId){const Je=`${$r}::${Ue.modelProvider}/${Ue.modelId}`;Me.current=!0,Mt.current=Je,D("model"),T(`${Ue.modelProvider}/${Ue.modelId}`)}else{const Je=`${Ue.agentId}::`;Me.current=!0,Mt.current=Je,D("agent"),V(Ue.agentId)}xn(Ue),L(!1)}},[cn,ht,Tt,xn,vn]),mi=a.useCallback(ne=>{const Ue=Tt.rooms.find(Je=>Je.id===ne);cn("room",ne,Ue?.updatedAt),Tt.selectRoom(ne),Ht.current=!0,L(!1)},[cn,Tt]),zs=a.useCallback(async()=>{if(!Qt){if(Ht.current=!0,O==="agent"){if(!A)return;D("agent"),V(A),await Rn(A)}else{const ne=zl(B||Z||ie);if(!ne)return;D("model"),T(`${ne.modelProvider}/${ne.modelId}`),await Rn($r,ne.modelProvider,ne.modelId)}await Pn(),$(!1),J("model")}},[ie,A,O,B,Pn,Z,Qt,Rn]),Qn=fn.length>50?`${fn.slice(0,50)}…`:fn,Zt=a.useCallback(ne=>{if(!ne||ne.length===0)return;const Ue=[];for(let Je=0;Je<ne.length;Je+=1){const qt=ne[Je];O9(qt)&&Ue.push({file:qt,previewUrl:F9(qt)?URL.createObjectURL(qt):""})}Ue.length>0&&Ce(Je=>[...Je,...Ue])},[]),Q=a.useCallback(ne=>{Ce(Ue=>{const Je=Ue[ne];return Je?.previewUrl&&URL.revokeObjectURL(Je.previewUrl),Ue.filter((qt,En)=>En!==ne)})},[]),Qe=a.useCallback(ne=>{Zt(ne.clipboardData?.files)},[Zt]),vt=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ni)return;const ne=un.current;!ne||ne.disabled||ne.focus({preventScroll:!0})},[]),xt=a.useCallback(()=>{typeof window>"u"||window.innerWidth>Ni||(Oe.current=!0)},[]),zt=a.useCallback(async()=>{const ne=be.trim(),Ue=Wn.current;if(!(!ne&&Ue.length===0)&&!Ut){if(Le(""),se(!1),te(""),X(-1),ne==="/help"){je(!0),vt(),Oe.current=!1;return}if(ne==="/clear"||ne==="/new"){Ue.forEach(Je=>{Je.previewUrl&&URL.revokeObjectURL(Je.previewUrl)}),Ce(Je=>Je.filter(qt=>!Ue.includes(qt)));try{if(ht&&Tt.activeRoom?.id)await Tt.clearRoom(Tt.activeRoom.id),je(!1);else if(M==="model"){$n(),Kt();const Je=zl(bn);if(!Je)return;await Rn($r,Je.modelProvider,Je.modelId)}else _&&($n(),Kt(),await Rn(_))}catch{n(p("chat.clearConversationFailed","Failed to clear conversation"),"error")}finally{vt(),Oe.current=!1}return}try{je(!1),dn&&Tt.activeRoom?await Tt.sendRoomMessage(ne,{files:Ue.map(Je=>Je.file)}):await mn(ne,Ue.map(Je=>Je.file)),Ue.forEach(Je=>{Je.previewUrl&&URL.revokeObjectURL(Je.previewUrl)}),Ce(Je=>Je.filter(qt=>!Ue.includes(qt)))}catch(Je){const qt=Je instanceof Error&&Je.message.trim()?Je.message:dn&&Tt.activeRoom?p("chat.sendRoomMessageFailed","Failed to send room message"):p("chat.sendMessageFailed","Failed to send message");n(qt,"error")}finally{vt(),Oe.current=!1}}},[n,M,dn,$n,vt,Ut,be,bn,ht,Tt,_,mn,Rn,Kt]),Wt=a.useCallback(ne=>{ne.preventDefault(),re.current+=1,ke(!0)},[]),hn=a.useCallback(ne=>{ne.preventDefault(),ne.dataTransfer.dropEffect="copy",ke(!0)},[]),In=a.useCallback(ne=>{ne.preventDefault(),re.current=Math.max(0,re.current-1),re.current===0&&ke(!1)},[]),gs=a.useCallback(ne=>{ne.preventDefault(),re.current=0,ke(!1),Zt(ne.dataTransfer?.files)},[Zt]),ks=a.useCallback((ne,Ue)=>{const Je=I9(ne,Ue);if(Je){se(!0),te(Je.filter),X(Je.start);return}se(!1),te(""),X(-1)},[]),Te=a.useCallback((ne=un.current)=>{ne&&(ne.style.height="auto",ne.style.height=`${T9(ne.scrollHeight)}px`)},[]),U=a.useCallback(ne=>{Le(Ue=>{const Je=Wy(Ue);if(!Je)return Ue;const qt=`/skill:${ne.name} `,En=Ue.slice(0,Je.start)+qt+Ue.slice(Je.end);return window.requestAnimationFrame(()=>{un.current&&(Te(un.current),un.current.focus())}),En}),q(!1),De(""),qe(0)},[Te]),ge=a.useCallback(ne=>{const Ue=un.current;if(!Ue||he<0)return;const Je=Ue.selectionStart??Ie.current,qt=Ue.selectionEnd??Je,En=Math.max(Je,qt),yn=Math.min(he,En),fs=`${`@${ne.name.replace(/\s+/g,"_")}`} `,ws=be.slice(0,yn)+fs+be.slice(En),js=yn+fs.length;Le(ws),se(!1),te(""),Y(0),X(-1),window.requestAnimationFrame(()=>{un.current&&(Te(un.current),un.current.focus(),un.current.setSelectionRange(js,js))})},[he,be,Te]),rt=a.useCallback((ne,Ue)=>{const qt=un.current?.selectionStart??Ie.current,En=be.lastIndexOf("#",qt),yn=En>=0?En+Ue.length:ne.length;Le(ne),nt.dismissMention(),Ke(!1),window.requestAnimationFrame(()=>{un.current&&(Te(un.current),un.current.focus(),un.current.setSelectionRange(yn,yn))})},[nt,be,Te]),Lt=a.useCallback(ne=>{const Ue=ne.target.value,Je=ne.target.selectionStart??Ue.length;Te(ne.target),Ie.current=Je,Le(Ue),ue&&Ue.trim().length>0&&je(!1),ks(Ue,Je);const qt=Wy(Ue);qt?(q(!0),De(qt.filter)):(q(!1),De("")),nt.detectMention(Ue,Je),Ke(nt.mentionActive),nt.mentionActive&&Nt(ne.target)},[nt,ue,Te,Nt,ks]);a.useLayoutEffect(()=>{Te()},[be,Te]);const Dt=a.useCallback(()=>{if(Oe.current){window.requestAnimationFrame(()=>{vt()});return}typeof window<"u"&&window.innerWidth<=Ni&&Bn.current&&(Gt.current=!0,Bn.current.style.removeProperty("--vv-height"),Bn.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Gt.current=!1},450)),Pe.current!==null&&window.clearTimeout(Pe.current),Pe.current=window.setTimeout(()=>{se(!1),te(""),X(-1),Ke(!1),nt.dismissMention(),Pe.current=null},120),oe.current!==null&&window.clearTimeout(oe.current),oe.current=window.setTimeout(()=>{q(!1),oe.current=null},120)},[nt,vt]),en=a.useCallback(()=>{Gt.current=!1,Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null),oe.current!==null&&(window.clearTimeout(oe.current),oe.current=null)},[]),tn=a.useCallback(ne=>{const Ue=ne.currentTarget,Je=Ue.selectionStart??Ue.value.length;Ie.current=Je,ks(Ue.value,Je),nt.detectMention(Ue.value,Je),Ke(nt.mentionActive),nt.mentionActive&&Nt(Ue)},[ks,nt,Nt]),Dn=a.useCallback(ne=>{ne.key!=="Escape"&&tn(ne)},[tn]),_n=a.useCallback(ne=>{ot(Ue=>{const Je=new Set(Ue);return Je.has(ne)?Je.delete(ne):Je.add(ne),Je})},[]),is=a.useCallback((ne,Ue=!1)=>Ue?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Hs(ne)}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Di,{remarkPlugins:[Li],components:lS,children:ne})}),[]),Ss=a.useCallback(ne=>{if(Ie.current=ne.currentTarget.selectionStart??Ie.current,nt.mentionActive&&nt.combinedItems.length>0){if(nt.handleKeyDown(ne,be),ne.key==="Enter"||ne.key==="Tab"){const Ue=nt.combinedItems[nt.selectedIndex];Ue?.kind==="task"?rt(nt.selectTask(Ue.task,be),`#${Ue.task.id}`):Ue?.kind==="file"&&rt(nt.selectFile(Ue.file,be),`#${Ue.file.path}`)}return}if(me&&ne.key==="ArrowDown"){ne.preventDefault(),Ge.length>0&&Y(Ue=>(Ue+1)%Ge.length);return}if(me&&ne.key==="ArrowUp"){ne.preventDefault(),Ge.length>0&&Y(Ue=>Ue===0?Ge.length-1:Ue-1);return}if(me&&ne.key==="Enter"){ne.preventDefault();const Ue=Ge[z]??Ge[0];Ue&&ge(Ue);return}if(me&&ne.key==="Escape"){ne.preventDefault(),ne.stopPropagation(),se(!1),te(""),X(-1);return}if(xe&&at.length>0&&ne.key==="ArrowDown"){ne.preventDefault(),qe(Ue=>(Ue+1)%at.length);return}if(xe&&at.length>0&&ne.key==="ArrowUp"){ne.preventDefault(),qe(Ue=>Ue===0?at.length-1:Ue-1);return}if(xe&&(ne.key==="Enter"||ne.key==="Tab")){ne.preventDefault();const Ue=at[He]??at[0];Ue&&U(Ue);return}if(xe&&ne.key==="Escape"){ne.preventDefault(),q(!1),De("");return}ne.key!=="Enter"||ne.shiftKey||(ne.preventDefault(),zt())},[me,Ge,z,ge,zt,nt,rt,be,xe,at,He,U]),Rs=a.useCallback(()=>{if(Ft.current){Ft.current=!1;return}if(j){S(!1);return}typeof window<"u"&&window.innerWidth<=Ni&&yt.current?.focus({preventScroll:!0}),S(!0)},[j,S]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:yt,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:kn,type:"button",className:"quick-chat-fab","aria-label":p("chat.openQuickChat","Open quick chat"),"data-testid":"quick-chat-fab","data-dragging":fe?"true":"false",style:{right:_e.x,bottom:_e.y},onPointerDown:Xe,onClick:Rs,children:t.jsx(Ra,{size:24})}),j&&t.jsxs("div",{className:`quick-chat-panel${F&&C?" quick-chat-panel--keyboard-open":""}`,ref:Bn,"data-testid":"quick-chat-panel",style:{...bt?{right:_e.x+Vt.right,bottom:kt+Vt.bottom,width:Rt.width,height:Rt.height}:{}},children:[bt&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Pt,role:"separator","aria-orientation":"horizontal","aria-label":p("chat.resizePanelTop","Resize panel from top")}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:Pt,role:"separator","aria-orientation":"horizontal","aria-label":p("chat.resizePanelBottom","Resize panel from bottom")}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:Pt,role:"separator","aria-orientation":"vertical","aria-label":p("chat.resizePanelRight","Resize panel from right")}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:Pt,role:"separator","aria-orientation":"vertical","aria-label":p("chat.resizePanelLeft","Resize panel from left")}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:Pt,role:"separator","aria-label":p("chat.resizePanelTopLeft","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:Pt,role:"separator","aria-label":p("chat.resizePanelTopRight","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:Pt,role:"separator","aria-label":p("chat.resizePanelBottomLeft","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:Pt,role:"separator","aria-label":p("chat.resizePanelBottomRight","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:p("chat.quickChatTitle","Quick Chat")}),ht&&Tt.activeRoom?t.jsxs("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-room-tag",title:`#${Tt.activeRoom.name}`,children:["#",Tt.activeRoom.name]}):M==="model"&&Se&&(()=>{const ne=ae?.provider??Ne?.modelProvider??"";return E==="mobile"&&Se.length>12&&ne?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Se,"aria-label":Se,children:t.jsx(hs,{provider:ne,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Se,children:Se})})()]}),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":p("chat.startNewChat","Start a new chat"),onClick:Cn,disabled:Qt,children:t.jsx(ys,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":p("chat.closeQuickChat","Close quick chat"),"data-testid":"quick-chat-close",onClick:()=>S(!1),children:t.jsx(Fn,{size:16})})]})]}),t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:t.jsxs("div",{className:"quick-chat-session-menu",ref:At,children:[t.jsx("label",{htmlFor:"quick-chat-session-dropdown-trigger",className:"visually-hidden",children:p("chat.selectSessionLabel","Select session")}),t.jsx("input",{type:"hidden","data-testid":"quick-chat-session-dropdown",value:rs&&ht?"":pt?.id??"",readOnly:!0}),t.jsxs("button",{id:"quick-chat-session-dropdown-trigger",type:"button",className:"btn quick-chat-session-trigger","aria-haspopup":"menu","aria-expanded":R,"data-testid":"quick-chat-session-dropdown-trigger",onClick:()=>L(ne=>!ne),children:[ht&&Tt.activeRoom?t.jsx(Ck,{size:16,"aria-hidden":"true"}):pt?.modelProvider?t.jsx(hs,{provider:pt.modelProvider,size:"sm"}):t.jsx(Ra,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:ei}),t.jsx(Ln,{size:16,"aria-hidden":"true"})]}),R&&t.jsxs("div",{className:"quick-chat-session-dropdown",role:"menu","data-testid":"quick-chat-session-dropdown-menu",children:[rs&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-session-dropdown-group-label",children:p("chat.roomsGroupLabel","Rooms")}),Ls.map(ne=>{const Ue=Tt.activeRoom?.id===ne.id,Je=!Ue&&Yn("room",ne.id,ne.updatedAt);return t.jsxs("button",{type:"button",role:"menuitem","data-testid":`quick-chat-session-option-room-${ne.slug}`,className:`quick-chat-session-option${Ue?" quick-chat-session-option--active":""}`,onClick:()=>mi(ne.id),children:[t.jsxs("span",{children:["#",ne.name]}),Je?t.jsx("span",{className:"chat-unread-dot quick-chat-session-unread-dot","data-testid":`quick-chat-unread-dot-${ne.id}`,"aria-label":p("chat.unreadMessages","Unread messages")}):null]},ne.id)}),t.jsx("div",{className:"quick-chat-session-dropdown-group-label",children:p("chat.sessionsGroupLabel","Sessions")})]}),Ts.map(ne=>{const Ue=!ht&&pt?.id===ne.id,Je=vn.find(En=>En.id===ne.id),qt=!Ue&&Yn("direct",ne.id,Je?.lastMessageAt??Je?.updatedAt);return t.jsxs("button",{type:"button",role:"menuitem","data-testid":`quick-chat-session-option-${ne.id}`,className:`quick-chat-session-option${Ue?" quick-chat-session-option--active":""}`,onClick:()=>ti(ne.id),children:[t.jsx("span",{children:ne.label}),qt?t.jsx("span",{className:"chat-unread-dot quick-chat-session-unread-dot","data-testid":`quick-chat-unread-dot-${ne.id}`,"aria-label":p("chat.unreadMessages","Unread messages")}):null]},ne.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${O==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>J("model"),children:p("chat.modeModel","Model")}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${O==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>J("agent"),children:p("chat.modeAgent","Agent")})]}),O==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:p("chat.selectAgentForNewChat","Select agent for new chat")}),t.jsx("select",{id:"quick-chat-new-agent-select",value:A,onChange:ne=>de(ne.target.value),"data-testid":"quick-chat-new-agent-select",children:h.map(ne=>t.jsx("option",{value:ne.id,children:M9(ne)},ne.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(wi,{id:"quick-chat-new-model-select",models:u,value:B,onChange:P,label:p("chat.selectModelOverrideLabel","Select model override"),placeholder:y?p("chat.loadingModels","Loading models…"):p("chat.selectModelPlaceholder2","Select a model"),disabled:y||u.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:d,onToggleModelFavorite:c})}),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:()=>{$(!1),J("model")},children:p("chat.cancelButton","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void zs(),disabled:Qt||(O==="agent"?!A:!zl(B||Z||ie)),children:p("chat.createButton","Create")})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:pn,"data-testid":"quick-chat-messages",onScroll:St,children:Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.loadingConversation","Loading conversation…")}):!ht&&_t?t.jsxs(t.Fragment,{children:[et.map(ne=>t.jsx(mh,{message:ne,forcePlain:ne.role!=="user"&&ye.has(ne.id),mentionAgentsByName:tt,roomContext:m,projectId:e,onToggleRender:_n},ne.id)),ue&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:is(p("chat.helpMessageContent","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:[Yt?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:is(Yt,ye.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${ye.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":ye.has("__streaming__")?p("chat.showRenderedMarkdown","Show rendered markdown"):p("chat.showPlainText","Show plain text"),onClick:()=>_n("__streaming__"),children:ye.has("__streaming__")?t.jsx(jp,{size:14}):t.jsx(bc,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:on?p("chat.thinkingStatus","Thinking…"):p("chat.connectingStatus","Connecting…")}),oS(An,!0,p),on&&t.jsxs("details",{className:"chat-message-thinking","data-testid":"quick-chat-streaming-thinking",children:[t.jsx("summary",{children:p("chat.thinkingLabel","Thinking")}),t.jsx("pre",{className:"chat-message-thinking-content",children:Hs(on)})]})]})]}):ht?Tt.messagesLoading?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.loadingConversation","Loading conversation…")}):et.length===0&&!ue?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsxs(t.Fragment,{children:[et.map(ne=>t.jsx(mh,{message:ne,forcePlain:ne.role!=="user"&&ye.has(ne.id),mentionAgentsByName:tt,roomContext:m,projectId:e,onToggleRender:_n},ne.id)),ue&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:is(p("chat.helpMessageContent","Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help"))})]}):sn?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.loadingConversation","Loading conversation…")}):et.length===0&&!Yt&&!on&&!_t&&!ue?t.jsx("div",{className:"quick-chat-panel-empty",children:p("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsxs(t.Fragment,{children:[et.map(ne=>t.jsx(mh,{message:ne,forcePlain:ne.role!=="user"&&ye.has(ne.id),mentionAgentsByName:tt,roomContext:m,projectId:e,onToggleRender:_n},ne.id)),ue&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:is(p("chat.helpMessageContent","Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help"))})]})}),Ee&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:ss,children:[t.jsx(Ln,{size:14}),p("chat.jumpToLatest","Latest")]}),$e.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:$e.map((ne,Ue)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${Ue}`,children:[ne.previewUrl?t.jsx("img",{src:ne.previewUrl,alt:ne.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ne.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${Ue}`,"aria-label":p("chat.removeAttachment","Remove {{name}}",{name:ne.file.name}),onClick:()=>Q(Ue),children:"×"})]},`${ne.file.name}-${Ue}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${We?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:Wt,onDragOver:hn,onDragLeave:In,onDrop:gs,children:[t.jsx("input",{ref:an,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:ne=>{Zt(ne.target.files),ne.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":p("chat.attachFiles","Attach files"),onClick:()=>an.current?.click(),children:t.jsx(Mk,{size:16})}),t.jsx("textarea",{ref:un,rows:1,className:"quick-chat-textarea",value:be,onChange:Lt,onKeyDown:Ss,onKeyUp:Dn,onClick:tn,onBlur:Dt,onFocus:en,onPaste:Qe,onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Ni||tf()&&document.activeElement!==ne.currentTarget&&(ne.preventDefault(),ne.currentTarget.focus({preventScroll:!0}))},placeholder:Mi,disabled:Ut,"data-testid":"quick-chat-input"}),_t?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:ne=>{typeof window>"u"||window.innerWidth>Ni||(ne.preventDefault(),ne.pointerType&&ne.pointerType!=="mouse"&&(G.current=!0,Kt()))},onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Ni||(ne.preventDefault(),G.current=!0,Kt())},onMouseDown:ne=>{typeof window>"u"||window.innerWidth>Ni||ne.preventDefault()},onClick:()=>{if(G.current){G.current=!1;return}Kt()},"aria-label":p("chat.stopGeneration","Stop generation"),"data-testid":"quick-chat-stop",children:t.jsx(Ea,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:ne=>{typeof window>"u"||window.innerWidth>Ni||(ne.preventDefault(),ne.pointerType&&ne.pointerType!=="mouse"&&(G.current=!0,xt(),vt(),zt()))},onTouchStart:ne=>{typeof window>"u"||window.innerWidth>Ni||(ne.preventDefault(),G.current=!0,xt(),vt(),zt())},onMouseDown:ne=>{typeof window>"u"||window.innerWidth>Ni||ne.preventDefault()},onClick:()=>{if(G.current){G.current=!1;return}zt()},disabled:$t,"data-testid":"quick-chat-send",children:t.jsx(zr,{size:16})})]}),t.jsx(i9,{agents:h,filter:pe,highlightedIndex:z,visible:me,onSelect:ge,position:"above",roomMemberIds:m?.memberIds,roomName:m?.roomName}),t.jsx(x9,{visible:nt.mentionActive&&!me,position:dt,tasks:nt.tasks,files:nt.files,selectedIndex:nt.selectedIndex,onSelectTask:ne=>{rt(nt.selectTask(ne,be),`#${ne.id}`)},onSelectFile:ne=>{rt(nt.selectFile(ne,be),`#${ne.path}`)},loading:nt.loading}),xe&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:x?t.jsx("div",{className:"chat-skill-menu-empty",children:p("chat.loadingSkills","Loading skills…")}):at.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:ce?p("chat.noSkillsFound","No skills found"):p("chat.noSkillsAvailable","No skills available")}):at.map((ne,Ue)=>t.jsxs("button",{type:"button",role:"option","aria-selected":Ue===He,className:`chat-skill-menu-item${Ue===He?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Je=>Je.preventDefault(),onMouseEnter:()=>qe(Ue),onClick:()=>U(ne),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:ne.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:ne.relativePath,children:ne.relativePath})]},ne.id))}),!ht&&fn&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:p("chat.queuedMessage","Queued: {{preview}}",{preview:Qn})}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":p("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":"chat-pending-dismiss",onClick:$n,children:"×"})]})]})})]})]})}function Bl(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Gy(e){return e.status==="generating"||e.status==="awaiting_input"}function Ul(e){return e==="complete"||e==="error"}function U9(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:d,requestSync:c}=pl(),m=a.useCallback(()=>{Up(e).then(f=>{const b=f.filter(v=>{const x=Bl(v.updatedAt),k=r.current.get(v.id);return k===void 0?!0:x<=k?!1:(r.current.delete(v.id),!0)}),y=new Map;for(const v of b)y.set(v.id,Bl(v.updatedAt));i.current=y,s(b)}).catch(f=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",f)})},[e]);a.useEffect(()=>{c(),m()},[m,c]),a.useEffect(()=>{s(f=>{if(o.size===0)return f;let b=!1;const y=new Map(f.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,k=i.current.get(v.sessionId)??0;if(x<k)continue;const w=r.current.get(v.sessionId);if(w!==void 0&&x<=w)continue;if(w!==void 0&&x>w&&!Ul(v.status)&&r.current.delete(v.sessionId),Ul(v.status)){y.delete(v.sessionId)&&(b=!0),i.current.set(v.sessionId,x);continue}const g=y.get(v.sessionId),j=v.type??g?.type,S=v.title??g?.title;if(!g&&(!j||!S))continue;const C={id:v.sessionId,type:j??"planning",status:v.status,title:S??"AI Session",projectId:v.projectId??g?.projectId??e??null,lockedByTab:v.owningTabId??g?.lockedByTab??null,updatedAt:v.updatedAt??g?.updatedAt??new Date(x).toISOString()},E=y.get(v.sessionId);(!E||E.status!==C.status||E.title!==C.title||E.type!==C.type||E.projectId!==C.projectId||E.lockedByTab!==C.lockedByTab||E.updatedAt!==C.updatedAt)&&(y.set(v.sessionId,C),i.current.set(v.sessionId,x),b=!0)}return b?[...y.values()].sort((v,x)=>Bl(x.updatedAt)-Bl(v.updatedAt)):f})},[e,o]),a.useEffect(()=>{const f=e?`?projectId=${encodeURIComponent(e)}`:"",b=k=>{try{const w=JSON.parse(k.data),g=Bl(w.updatedAt)||Date.now();s(j=>{const S=i.current.get(w.id)??0;if(g<S)return j;const C=r.current.get(w.id);if(C!==void 0&&g<=C)return j;if(C!==void 0&&g>C&&!Ul(w.status)&&r.current.delete(w.id),i.current.set(w.id,g),Ul(w.status))return j.filter(F=>F.id!==w.id);const E=j.findIndex(F=>F.id===w.id);if(E>=0){const F=[...j];return F[E]=w,F}return Gy(w)?[w,...j]:j}),l({sessionId:w.id,status:w.status,needsInput:w.status==="awaiting_input",type:w.type,title:w.title,projectId:w.projectId,owningTabId:w.lockedByTab,updatedAt:w.updatedAt,timestamp:g}),Ul(w.status)&&d({sessionId:w.id,status:w.status,timestamp:g})}catch{}},y=k=>{try{const w=JSON.parse(k.data),g=Date.now();r.current.set(w,g),i.current.set(w,Math.max(i.current.get(w)??0,g)),d({sessionId:w,status:"complete",timestamp:g}),s(j=>j.filter(S=>S.id!==w))}catch{}},v=`/api/events${f}`,x=li(v,{events:{"ai_session:updated":b,"ai_session:deleted":y},onReconnect:()=>{Gs({view:"useBackgroundSessions",trigger:"sse-reconnect",projectId:e,replayAttempted:!1,sseChannel:v}),m()}});return Gs({view:"useBackgroundSessions",trigger:"sse-open",projectId:e,replayAttempted:!1,sseChannel:v}),x},[d,l,e,m]);const p=a.useCallback(async f=>{const y=n.find(w=>w.id===f)?.type,v=so();let x=!1;if(y==="planning")try{await Qk(f,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${f} despite lock by another tab`)}else if(y==="subtask")try{await nw(f,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${f} despite lock by another tab`)}else if(y==="mission_interview")try{await XT(f,e,v)}catch(w){x=!0,w instanceof Error&&w.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${f} despite lock by another tab`)}x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${f}, attempting delete anyway`);const k=Date.now();r.current.set(f,k),i.current.set(f,Math.max(i.current.get(f)??0,k)),d({sessionId:f,status:"complete",timestamp:k});try{await ow(f)}catch{}s(w=>w.filter(g=>g.id!==f))},[d,e,n]),h=a.useMemo(()=>n.filter(f=>Gy(f)),[n]),u=a.useMemo(()=>h.filter(f=>f.type==="planning"),[h]);return{sessions:h,generating:h.filter(f=>f.status==="generating").length,needsInput:h.filter(f=>f.status==="awaiting_input").length,planningSessions:u,dismissSession:p,refresh:m}}const Of="fusion:github-star-prompt-shown",yp="fusion:github-star-prompt-changed";function H9(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Of)==="1"}catch{return!1}}function V9(e){if(typeof window>"u")return()=>{};const n=i=>{i.key===Of&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(yp,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(yp,s)}}function q9(){if(!(typeof window>"u"))try{window.localStorage.setItem(Of,"1"),window.dispatchEvent(new Event(yp))}catch{}}function W9(){return a.useSyncExternalStore(V9,H9,()=>!1)}const cu="fusion:hide-session-banners",kp="fusion:session-banner-pref-changed";function G9(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(cu)==="1"}catch{return!1}}function K9(e){if(typeof window>"u")return()=>{};const n=i=>{i.key===cu&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(kp,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(kp,s)}}function zK(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(cu,"1"):window.localStorage.removeItem(cu),window.dispatchEvent(new Event(kp))}catch{}}function J9(){return a.useSyncExternalStore(K9,G9,()=>!1)}const Cd=new Set;function Xs(e){return{...e,column:G_(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Xl(e){return!!e.deletedAt}function _d(e){return e.filter(n=>!Xl(n))}function Ky(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function Y9(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,firstExecutionAt:e.firstExecutionAt??n.firstExecutionAt,cumulativeActiveMs:n.cumulativeActiveMs??e.cumulativeActiveMs,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 hh(e,n){if(Ky(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return Y9(e,n);const i=Ky(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:i>=0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function X9(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState(()=>{if(!n)return[];const T=ki(`${Tn.TASKS_PREFIX}${n}`,{maxAgeMs:Lh});return Array.isArray(T)&&T.length>0&&!Cd.has(n)&&(Cd.add(n),console.info("[swr-cache] hit tasks=",T.length,"projectId=",n)),Array.isArray(T)?_d(T.map(Xs)):[]}),[l,d]=a.useState(!0),[c,m]=a.useState(null),[p,h]=a.useState(!1),u=a.useRef(p);u.current=p;const f=a.useRef(r),b=a.useRef(0),y=a.useRef(0),v=a.useRef(0),x=a.useRef(y.current),k=a.useRef(0),w=a.useRef(s),g=a.useRef(null),j=a.useRef(void 0),S=a.useRef(n);f.current=r,w.current=s,S.current!==n&&(S.current=n,y.current++);const C=1e3,E=a.useCallback(async T=>{const ie=++b.current,le=n,be=T?.searchQueryOverride??w.current,Le=T?.includeArchivedOverride??u.current;try{const xe=await Uk(void 0,void 0,le,be,Le);if(b.current!==ie||n!==le)return;const q=_d(xe.map(Xs));if(o(q),le){const ce=xe.length>500?xe.slice(0,500):xe;es(`${Tn.TASKS_PREFIX}${le}`,ce,{maxBytes:5e5})}d(!1),m(null),j.current=Date.now()}catch{if(b.current!==ie||n!==le)return;if(m(Date.now()),le&&vs(`${Tn.TASKS_PREFIX}${le}`),T?.clearOnError){o([]);return}}},[n]);g.current=E;const F=a.useCallback(async()=>{u.current||(h(!0),u.current=!0,await g.current({includeArchivedOverride:!0}))},[]),M=a.useRef(s);a.useEffect(()=>{if(s===void 0&&M.current===void 0)return;M.current=s;const T=setTimeout(()=>{E({searchQueryOverride:s})},300);return()=>clearTimeout(T)},[s]),a.useEffect(()=>{if(!n)return;const T=ki(`${Tn.TASKS_PREFIX}${n}`,{maxAgeMs:Lh});Array.isArray(T)&&(T.length>0&&!Cd.has(n)&&(Cd.add(n),console.info("[swr-cache] hit tasks=",T.length,"projectId=",n)),o(_d(T.map(Xs)))),d(!0)},[n]),a.useEffect(()=>{d(!0),E({clearOnError:!0});const T=()=>{if(document.visibilityState!=="visible"){x.current=y.current;return}const ie=x.current,le=ie!==y.current;if(x.current=y.current,le){v.current=Date.now(),di("useTasks","visibility-context-version-changed",{projectId:n,previousContextVersion:ie,currentContextVersion:y.current}),Gs({view:"useTasks",trigger:"visibility",projectId:n,replayAttempted:!1,reason:"context-version-changed"}),E();return}const be=Date.now();be-v.current<C||(v.current=be,Gs({view:"useTasks",trigger:"visibility",projectId:n,replayAttempted:!1,reason:"debounced-refresh"}),E())};return document.addEventListener("visibilitychange",T),()=>{document.removeEventListener("visibilitychange",T)}},[E]),a.useEffect(()=>{if(i===!1)return;let T=y.current;const ie=n?`?projectId=${encodeURIComponent(n)}`:"",le=()=>y.current!==T,be=()=>{k.current+=1,di("useTasks","dropped-stale-event",{count:k.current,contextVersionAtStart:T,currentContextVersion:y.current,projectId:n})};let Le=!0;const xe=pe=>{if(le()){be();return}const te=Xs(JSON.parse(pe.data));if(w.current){g.current({searchQueryOverride:w.current});return}if(Xl(te)){o(me=>me.filter(se=>se.id!==te.id)),di("useTasks","soft-deleted-task-suppressed",{event:"task:created",id:te.id});return}o(me=>{const se=me.findIndex(X=>X.id===te.id);if(se===-1)return[...me,te];const z=me[se],Y=hh(z,te);if(Y===z)return me;const he=[...me];return he[se]=Y,he}),j.current=Date.now()},q=pe=>{if(le()){be();return}if(w.current){g.current({searchQueryOverride:w.current});return}const{task:te,to:me}=JSON.parse(pe.data),se=Xs(te);if(Xl(se)){o(he=>he.filter(X=>X.id!==se.id)),di("useTasks","soft-deleted-task-suppressed",{event:"task:moved",id:se.id});return}const z=typeof me=="string"&&me?me:se.column,Y={...se,column:z};o(he=>{const X=he.findIndex(ot=>ot.id===Y.id);if(X===-1)return[...he,Y];const ye=[...he];return ye[X]=Y,ye}),j.current=Date.now()},ce=pe=>{if(le()){be();return}if(w.current){g.current({searchQueryOverride:w.current});return}const te=Xs(JSON.parse(pe.data));if(Xl(te)){o(me=>me.filter(se=>se.id!==te.id)),di("useTasks","soft-deleted-task-suppressed",{event:"task:updated",id:te.id});return}o(me=>{const se=me.findIndex(X=>X.id===te.id);if(se===-1)return[...me,te];const z=me[se],Y=hh(z,te);if(Y===z)return me;const he=[...me];return he[se]=Y,he}),j.current=Date.now()},De=pe=>{if(le()){be();return}if(w.current){g.current({searchQueryOverride:w.current});return}const te=Xs(JSON.parse(pe.data));o(me=>me.filter(se=>se.id!==te.id))},He=pe=>{if(le()){be();return}if(w.current){g.current({searchQueryOverride:w.current});return}const{task:te}=JSON.parse(pe.data),me=Xs(te);if(Xl(me)){o(z=>z.filter(Y=>Y.id!==me.id)),di("useTasks","soft-deleted-task-suppressed",{event:"task:merged",id:me.id});return}const se={...me,column:"done"};o(z=>{const Y=z.findIndex(X=>X.id===se.id);if(Y===-1)return[...z,se];const he=[...z];return he[Y]=se,he})},qe=li(`/api/events${ie}`,{events:{"task:created":xe,"task:moved":q,"task:updated":ce,"task:deleted":De,"task:merged":He},onReconnect:()=>{if(T=y.current,!!Le){if(le()){be();return}Gs({view:"useTasks",trigger:"sse-reconnect",projectId:n,replayAttempted:!1}),g.current()}}});return()=>{Le=!1,qe()}},[n,i]);const D=a.useCallback(async T=>{const ie=Xs(await Hk(T,n));return o(le=>le.some(be=>be.id===ie.id)?le:[...le,ie]),ie},[n]),_=a.useCallback(async(T,ie,le)=>Xs(await yE(T,ie,n,le)),[n]),V=a.useCallback(async T=>Xs(await Gk(T,n)),[n]),N=a.useCallback(async T=>Xs(await Kk(T,n)),[n]),$=a.useCallback(async(T,ie)=>Xs(await jE(T,n,ie)),[n]),R=a.useCallback(async T=>NE(T,n),[n]),L=a.useCallback(async T=>Xs(await SE(T,n)),[n]),O=a.useCallback(async T=>Xs(await _E(T,n)),[n]),J=a.useCallback(async T=>{const ie=Xs(await EE(T,n));return o(le=>le.some(be=>be.id===ie.id)?le:[...le,ie]),ie},[n]),A=a.useCallback(async(T,ie)=>{const le=f.current.find(Le=>Le.id===T),be=le?{...le,...ie,updatedAt:new Date().toISOString()}:void 0;be&&o(Le=>Le.map(xe=>xe.id===T?be:xe));try{const Le=Xs(await si(T,ie,n));return o(xe=>xe.map(q=>q.id===T?Le:q)),Le}catch(Le){throw le&&o(xe=>xe.map(q=>q.id===T?le:q)),Le}},[n]),de=a.useCallback(async(T,ie)=>{const le=Xs(await ME(T,n,ie));return o(be=>be.map(Le=>Le.id===T?le:Le)),le},[n]),B=a.useCallback(async T=>{const ie=Xs(await AE(T,n));return o(le=>le.map(be=>be.id===T?ie:be)),ie},[n]),P=a.useCallback(async()=>{const ie=(await TE(n)).map(Xs);return o(le=>le.map(be=>ie.find(xe=>xe.id===be.id)||be)),ie},[n]),Z=a.useCallback(T=>{if(T.length===0)return;if(w.current){g.current({searchQueryOverride:w.current});return}const ie=_d(T.map(Xs));o(le=>{let be=le;for(const Le of ie){const xe=be.findIndex(De=>De.id===Le.id);if(xe===-1){be===le&&(be=[...le]),be.push(Le);continue}const q=be[xe],ce=hh(q,Le);ce!==q&&(be===le&&(be=[...le]),be[xe]=ce)}return be}),j.current=Date.now()},[]);return{tasks:r,isStale:l,lastRefreshErrorAt:c,createTask:D,moveTask:_,pauseTask:V,unpauseTask:N,deleteTask:$,mergeTask:R,retryTask:L,resetTask:O,duplicateTask:J,updateTask:A,archiveTask:de,unarchiveTask:B,archiveAllDone:P,loadArchivedTasks:F,includeArchived:p,refreshTasks:E,ingestCreatedTasks:Z,lastFetchTimeMs:j.current}}const Q9=5e3,Z9=1e3;function eV(e){const s=(eT(e)?e.nodeMappings??e.projectNodeMappings??e.pathMappings??[]:[]).filter(i=>!!i?.nodeId&&!!i?.path).map(i=>({nodeId:i.nodeId,nodeName:i.nodeName,path:i.path,available:i.available!==!1}));return s.length>0?s:e.nodeId&&e.path?[{nodeId:e.nodeId,nodeName:e._sourceNodeName,path:e.path,available:!0}]:[]}function ph(e){return e.map(n=>({...n,nodeMappings:eV(n)}))}function tV(){const[e,n]=a.useState(()=>{const y=ki(Tn.PROJECTS,{maxAgeMs:Gr});return Array.isArray(y)?(y.length>0&&console.info("[swr-cache] hit projects=",y.length),ph(y)):[]}),[s,i]=a.useState(()=>e.length===0),[r,o]=a.useState(null),l=a.useRef(null),d=a.useRef(0),c=a.useRef(e),m=ul();a.useEffect(()=>{c.current=e},[e]);const p=a.useCallback(y=>c.current.length>0&&_c(y,m.wasRecentlyHidden()),[m]),h=a.useCallback(async()=>{try{o(null);const y=await zg(),v=ph(y);n(v),es(Tn.PROJECTS,v)}catch(y){const v=y instanceof Error?y.message:"Failed to fetch projects";p(v)||o(v)}},[p]);a.useEffect(()=>{let y=!1;async function v(){e.length>0||i(!0);const w=performance.now();try{const g=await zg(),j=ph(g),S=Math.round(performance.now()-w);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${S}ms (${j.length} projects)`),y||(n(j),o(null),es(Tn.PROJECTS,j))}catch(g){const j=Math.round(performance.now()-w),S=g instanceof Error?g.message:"Failed to fetch projects";console.warn(`[useProjects] initial fetch failed after ${j}ms: ${S}`),!y&&!p(S)&&o(S)}finally{y||i(!1)}}v();const x=()=>{if(document.visibilityState!=="visible")return;const k=Date.now(),w=k-d.current;if(w<Z9){Gs({view:"useProjects",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounce-skipped",detail:{timeSinceLastRefreshMs:w}});return}d.current=k,Gs({view:"useProjects",trigger:"visibility",projectId:void 0,replayAttempted:!1,reason:"debounced-refresh"}),h()};return document.addEventListener("visibilitychange",x),()=>{y=!0,document.removeEventListener("visibilitychange",x)}},[e.length,h,p]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{h()},Q9),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,h]);const u=a.useCallback(async y=>{const v=await lT(y);return n(x=>[...x,v]),v},[]),f=a.useCallback(async(y,v)=>{const x=await fT(y,v);return n(k=>k.map(w=>w.id===y?x:w)),x},[]),b=a.useCallback(async y=>{await iw(y),n(v=>{const x=v.filter(k=>k.id!==y);return es(Tn.PROJECTS,x),x}),vs(`${Tn.TASKS_PREFIX}${y}`)},[]);return{projects:e,loading:s,error:r,refresh:h,register:u,update:f,unregister:b}}const nV="kb-dashboard-current-project",Jy=3;function sV(e){return e??"local"}function iV(e,n={}){const{nodeId:s=null}=n,i=ki(Tn.CURRENT_PROJECT_ID,{maxAgeMs:Fh}),r=typeof i=="string"&&i.length>0?e.find(j=>j.id===i)??null:null,[o,l]=a.useState(r),[d,c]=a.useState(()=>r===null),m=a.useRef(!1),p=a.useRef(null),h=a.useRef(!1),u=a.useRef(null),f=a.useRef(0),b=a.useRef(0),y=sV(s),v=a.useCallback(j=>{es(Tn.CURRENT_PROJECT_ID,j??"")},[]),x=a.useCallback(j=>j.find(S=>S.status==="active")||j[0]||null,[]),k=a.useCallback(j=>{f.current=0,b.current=0,l(j),v(j?.id??null)},[v]);a.useEffect(()=>{let j=!1;if(p.current!==y&&(p.current=null,m.current=!1),m.current&&p.current===y)return c(!1),()=>{j=!0};typeof i=="string"&&i.length>0&&e.some(E=>E.id===i)||c(!0);async function C(){try{const E=await Ja();if(j)return;u.current=E.dashboardCurrentProjectIdByNode??{};const F=u.current[y];if(F){const M=e.find(D=>D.id===F);M&&(b.current=0,l(M),v(M.id))}if(!F)try{const M=localStorage.getItem(nV);if(M){const D=JSON.parse(M);D?.id&&e.some(V=>V.id===D.id)&&(b.current=0,l(D),v(D.id),u.current={...u.current,[y]:D.id},await Ms({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{j||(m.current=!0,p.current=y,c(!1))}}return C(),()=>{j=!0}},[e,i,y,v]),a.useEffect(()=>{f.current=0,b.current=0},[o?.id]),a.useEffect(()=>{if(!d)if(o){if(b.current=0,e.some(C=>C.id===o.id))f.current=0;else if(e.length===0)f.current=0;else{if(f.current+=1,f.current>=Jy){const C=x(e);k(C),C||v(null)}return}const S={...u.current,[y]:o.id};u.current=S,Ms({dashboardCurrentProjectIdByNode:S}).catch(()=>{}),v(o.id)}else{if(f.current=0,e.length===0){b.current=0;return}if(!h.current){const j=u.current?.[y];if(j){const S=e.find(C=>C.id===j)??null;if(S){b.current=0,k(S);return}}b.current+=1,b.current>=Jy&&(b.current=0,k(x(e)))}}},[e,o,d,y,v,x,k]);const w=a.useCallback(j=>{if(h.current=!1,f.current=0,b.current=0,l(j),v(j?.id??null),j){const S={...u.current,[y]:j.id};u.current=S,Ms({dashboardCurrentProjectIdByNode:S}).catch(()=>{})}},[y,v]),g=a.useCallback(()=>{h.current=!0,f.current=0,b.current=0,l(null),v(null);const j={...u.current};delete j[y],u.current=j,Ms({dashboardCurrentProjectIdByNode:j}).catch(()=>{})},[y,v]);return{currentProject:o,setCurrentProject:w,clearCurrentProject:g,loading:d}}const aV=(e,n,s)=>{const i=e[n];return i?typeof i=="function"?i():Promise.resolve(i):new Promise((r,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+n+(n.split("/").length!==s?". Note that variables only represent file names one level deep.":""))))})},rV=["common","app","errors"],oV={dashboard:rV},lV="common",cV=oV.dashboard,dV={"zh-Hans":["zh-CN"],"zh-Hant":["zh-TW"],zh:["zh-CN"],default:[J_]};function uV(e){if(!e)return;const n=e.replaceAll("_","-");if(pg(n))return n;const s=n.toLowerCase();if(s.startsWith("zh"))return s.includes("hans")?"zh-CN":s.includes("hant")||s.includes("-tw")||s.includes("-hk")||s.includes("-mo")?"zh-TW":"zh-CN";const i=s.split("-")[0];return pg(i)?i:void 0}function mV(){return{supportedLngs:[...Ik],fallbackLng:dV,load:"currentOnly",nonExplicitSupportedLngs:!1,interpolation:{escapeValue:!1},returnNull:!1,returnEmptyString:!1}}const hV="kb-dashboard-language";uu.use(BS).use(US((e,n)=>aV(Object.assign({"../locales/en/app.json":()=>ln(()=>import("./app-CVg6W-HU.js"),[]),"../locales/en/common.json":()=>ln(()=>import("./common-CN9QPI2d.js"),[]),"../locales/en/errors.json":()=>ln(()=>import("./errors-BPsCufin.js"),[]),"../locales/es/app.json":()=>ln(()=>import("./app-DhHgtB9j.js"),[]),"../locales/es/common.json":()=>ln(()=>import("./common-BRyX4VxB.js"),[]),"../locales/es/errors.json":()=>ln(()=>import("./errors-07IrmOYM.js"),[]),"../locales/fr/app.json":()=>ln(()=>import("./app-DNh04p5I.js"),[]),"../locales/fr/common.json":()=>ln(()=>import("./common-DFDqu_n0.js"),[]),"../locales/fr/errors.json":()=>ln(()=>import("./errors-CcVDgqlA.js"),[]),"../locales/ko/app.json":()=>ln(()=>import("./app-CY3pQXOr.js"),[]),"../locales/ko/common.json":()=>ln(()=>import("./common-X6PzBnVA.js"),[]),"../locales/ko/errors.json":()=>ln(()=>import("./errors-DOF5Td3F.js"),[]),"../locales/zh-CN/app.json":()=>ln(()=>import("./app-CTRT_hQh.js"),[]),"../locales/zh-CN/common.json":()=>ln(()=>import("./common-DgWWKG8Z.js"),[]),"../locales/zh-CN/errors.json":()=>ln(()=>import("./errors-D-i_Bxc6.js"),[]),"../locales/zh-TW/app.json":()=>ln(()=>import("./app-NL_hPGDS.js"),[]),"../locales/zh-TW/common.json":()=>ln(()=>import("./common-CNbjPELi.js"),[]),"../locales/zh-TW/errors.json":()=>ln(()=>import("./errors-DDdWAK-U.js"),[])}),`../locales/${e}/${n}.json`,4))).use(HS);const pV=uu.init({...mV(),ns:[...cV],defaultNS:lV,detection:{order:["localStorage","navigator","htmlTag"],lookupLocalStorage:hV,caches:[],convertDetectedLanguage:e=>uV(e)??e},react:{useSuspense:!1}});uu.on("languageChanged",e=>{typeof document<"u"&&(document.documentElement.lang=e)});const cS="kb-dashboard-theme-mode",dS="kb-dashboard-color-theme",uS="kb-dashboard-font-scale-pct",wp=100,fV=85,gV=125,mS=[...K_],Yy="theme-data",Hl="theme-data.css";function bV(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${Hl}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${Hl}`:e.replace(/\/[^/]+$/,`/${Hl}`):`/${Hl}`:`/${Hl}`}const qi=typeof window<"u",vV=qi?a.useLayoutEffect:a.useEffect;function hS(e){return e==="dark"||e==="light"||e==="system"}function Xy(){if(!qi)return"dark";try{const e=localStorage.getItem(cS);if(hS(e))return e}catch{}return"dark"}function Qy(){if(!qi)return"default";try{const e=localStorage.getItem(dS);if(e&&mS.includes(e))return e}catch{}return"default"}function Zy(e){if(qi)try{localStorage.setItem(cS,e)}catch{}}function ek(e){if(qi)try{localStorage.setItem(dS,e)}catch{}}function pc(e){return typeof e!="number"||!Number.isFinite(e)?wp:Math.min(gV,Math.max(fV,Math.round(e)))}function tk(){if(!qi)return wp;try{const e=Number(localStorage.getItem(uS));return pc(e)}catch{return wp}}function nk(e){if(qi)try{localStorage.setItem(uS,String(pc(e)))}catch{}}function xV(e,n){return e==="system"?n?"dark":"light":e}function yV(e,n,s,i){if(!qi)return;const r=xV(e,i);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${pc(s)}%`}function sk(){if(!qi)return;const e=bV(),n=document.getElementById(Yy);if(n){n.href!==e&&(n.href=e);return}const s=document.createElement("link");s.rel="stylesheet",s.href=e,s.id=Yy,document.head.appendChild(s)}function kV(){const[e,n]=a.useState(()=>Xy()),[s,i]=a.useState(()=>Qy()),[r,o]=a.useState(()=>tk()),[l,d]=a.useState(!0),[c,m]=a.useState(()=>qi?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),p=a.useRef(e),h=a.useRef(s),u=a.useRef(r),f=a.useRef(!1),b=a.useRef(!1),y=a.useRef(!1);a.useEffect(()=>{p.current=e},[e]),a.useEffect(()=>{h.current=s},[s]),a.useEffect(()=>{u.current=r},[r]),a.useEffect(()=>{if(!qi||!l)return;let w=!1;return Ja().then(g=>{if(!w&&(hS(g.themeMode)&&!f.current&&(p.current!==g.themeMode&&(p.current=g.themeMode,n(g.themeMode)),Xy()!==g.themeMode&&Zy(g.themeMode)),g.colorTheme&&mS.includes(g.colorTheme)&&!b.current&&(h.current!==g.colorTheme&&(h.current=g.colorTheme,i(g.colorTheme)),Qy()!==g.colorTheme&&ek(g.colorTheme)),!y.current)){const j=pc(g.dashboardFontScalePct);u.current!==j&&(u.current=j,o(j)),tk()!==j&&nk(j)}}).catch(g=>{console.warn("[useTheme] Failed to hydrate theme from global settings",g)}).finally(()=>{w||d(!1)}),()=>{w=!0}},[l]),a.useEffect(()=>{if(!qi)return;const w=window.matchMedia("(prefers-color-scheme: dark)"),g=j=>{m(j.matches)};return w.addEventListener("change",g),()=>w.removeEventListener("change",g)},[]),vV(()=>{yV(e,s,r,c)},[e,s,r,c]),a.useEffect(()=>{!qi||l||s!=="default"&&sk()},[s,l]);const v=a.useCallback(w=>{f.current=!0,p.current=w,n(w),Zy(w),Ms({themeMode:w}).catch(g=>{console.warn("[useTheme] Failed to persist themeMode to global settings",g)})},[]),x=a.useCallback(w=>{b.current=!0,h.current=w,i(w),ek(w),w!=="default"&&sk(),Ms({colorTheme:w}).catch(g=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",g)})},[]),k=a.useCallback(w=>{const g=pc(w);y.current=!0,u.current=g,o(g),nk(g),Ms({dashboardFontScalePct:g}).catch(j=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",j)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:x,setDashboardFontScalePct:k,isSystemDark:c}}function wV(e){const{t:n}=st("app"),{planningSessions:s}=e,[i,r]=a.useState(!1),[o,l]=a.useState(!1),[d,c]=a.useState(null),[m,p]=a.useState(void 0),[h,u]=a.useState(!1),[f,b]=a.useState(null),[y,v]=a.useState(void 0),[x,k]=a.useState(null),[w,g]=a.useState("definition"),[j,S]=a.useState(null),[C,E]=a.useState(null),[F,M]=a.useState(!1),[D,_]=a.useState(void 0),[V,N]=a.useState(!1),[$,R]=a.useState(!1),[L,O]=a.useState(!1),[J,A]=a.useState(null),[de,B]=a.useState(!1),[P,Z]=a.useState(!1),[T,ie]=a.useState(void 0),[le,be]=a.useState(!1),[Le,xe]=a.useState(!1),[q,ce]=a.useState("project"),[De,He]=a.useState(null),[qe,pe]=a.useState(!1),[te,me]=a.useState(!1),[se,z]=a.useState(!1),[Y,he]=a.useState(void 0),[X,ye]=a.useState(void 0),[ot,ue]=a.useState(void 0),[je,$e]=a.useState(!1),[Ce,We]=a.useState(!1),[ke,Ee]=a.useState(!1),[Ze,Ke]=a.useState(!1),dt=!!(x||C||F||i||o||h||P||le||Le||qe||te||se||Ce||je||L||de||V||$||ke||Ze),Fe=a.useCallback(()=>r(!0),[]),nt=a.useCallback(()=>r(!1),[]),Nt=a.useCallback(()=>l(!0),[]),Ft=a.useCallback(At=>{c(At),l(!0)},[]),ze=a.useCallback(()=>{const At=s[0];At&&(p(At.id),l(!0))},[s]),it=a.useCallback(At=>{p(At),l(!0)},[]),Mt=a.useCallback(()=>{l(!1),c(null),p(void 0)},[]),Ht=a.useCallback(At=>{b(At),u(!0)},[]),Me=a.useCallback(At=>{v(At),u(!0)},[]),Ae=a.useCallback(()=>{u(!1),b(null),v(void 0)},[]),ee=a.useCallback((At,an="definition",Wn)=>{k(At),g(an),S(Wn?.origin??null)},[]),Ie=a.useCallback(At=>{k(At),g("changes"),S(null)},[]),Pe=a.useCallback(At=>{k(an=>!an||At.id!==void 0&&At.id!==an.id?an:{...an,...At})},[]),oe=a.useCallback(()=>{k(null),S(null)},[]),re=a.useCallback(At=>{E(At)},[]),_e=a.useCallback(()=>{E(null)},[]),fe=a.useCallback(At=>{_(At),M(!0)},[]),Xe=a.useCallback(()=>{M(!1),_(void 0)},[]),kt=a.useCallback(()=>N(!0),[]),Rt=a.useCallback(()=>N(!1),[]),Vt=a.useCallback(()=>R(!0),[]),Pt=a.useCallback(()=>R(!1),[]),bt=a.useCallback(At=>{A(At??null),O(!0)},[]),pt=a.useCallback(()=>{O(!1),A(null)},[]),ft=a.useCallback(()=>B(!0),[]),_t=a.useCallback(()=>B(!1),[]),Yt=a.useCallback(()=>{Z(At=>!At)},[]),on=a.useCallback(()=>{Z(!1),ie(void 0)},[]),An=a.useCallback((At,an)=>{typeof At=="string"&&At&&ce(At),He(typeof an=="string"||an===null?an:null),be(!0)},[]),vn=a.useCallback(()=>{be(!1),He(null)},[]),Qt=a.useCallback(()=>xe(!0),[]),sn=a.useCallback(()=>xe(!1),[]),mn=a.useCallback(At=>{typeof At=="string"&&At&&ce(At)},[]),Kt=a.useCallback(()=>pe(!0),[]),fn=a.useCallback(()=>pe(!1),[]),$n=a.useCallback(()=>me(!0),[]),On=a.useCallback(()=>me(!1),[]),xn=a.useCallback((At,an)=>{const Wn=At==="settings",Xn=At==="create";he(Wn?"settings":void 0),ye(Xn?"create":void 0),ue(!Wn&&!Xn?an:void 0),z(!0)},[]),Vn=a.useCallback(()=>{z(!1),he(void 0),ye(void 0),ue(void 0)},[]),Rn=a.useCallback(()=>$e(!0),[]),Pn=a.useCallback(()=>$e(!1),[]),zn=a.useCallback(()=>We(!0),[]),Nn=a.useCallback(()=>We(!1),[]),dn=a.useCallback(async(At,an)=>{We(!1),ie(an),Z(!0)},[]),Tt=a.useCallback(()=>Ee(!0),[]),Yn=a.useCallback(()=>Ee(!1),[]),cn=a.useCallback(()=>Ke(!0),[]),Bn=a.useCallback(()=>Ke(!1),[]),kn=a.useCallback((At,an)=>{an(n("modalManager.createdFromPlanning","Created {{id}} from planning mode",{id:At.id}),"success"),l(!1),c(null)},[n]),pn=a.useCallback((At,an)=>{const Wn=At.map(Xn=>Xn.id).join(", ");an(n("modalManager.createdMultipleFromPlanning","Created {{ids}} from planning mode",{ids:Wn}),"success"),l(!1),c(null)},[n]),un=a.useCallback((At,an)=>{const Wn=At.map(Xn=>Xn.id).join(", ");an(n("modalManager.createdFromSubtask","Created {{ids}} from subtask breakdown",{ids:Wn}),"success"),u(!1),b(null)},[n]);return{newTaskModalOpen:i,isPlanningOpen:o,planningInitialPlan:d,planningResumeSessionId:m,isSubtaskOpen:h,subtaskInitialDescription:f,subtaskResumeSessionId:y,detailTask:x,detailTaskInitialTab:w,detailTaskOrigin:j,groupModalGroupId:C,settingsOpen:F,settingsInitialSection:D,schedulesOpen:V,githubImportOpen:$,usageOpen:L,usageAnchorRect:J,systemStatsOpen:de,terminalOpen:P,terminalInitialCommand:T,filesOpen:le,todosOpen:Le,fileBrowserWorkspace:q,fileBrowserInitialFile:De,activityLogOpen:qe,gitManagerOpen:te,workflowEditorOpen:se,workflowEditorInitialPanel:Y,workflowEditorInitialAction:X,workflowEditorInitialWorkflowId:ot,agentsOpen:je,scriptsOpen:Ce,setupWizardOpen:ke,modelOnboardingOpen:Ze,anyModalOpen:dt,openNewTask:Fe,closeNewTask:nt,openPlanning:Nt,openPlanningWithInitialPlan:Ft,resumePlanning:ze,openPlanningWithSession:it,closePlanning:Mt,openSubtaskBreakdown:Ht,openSubtaskWithSession:Me,closeSubtask:Ae,openDetailTask:ee,openDetailWithChangesTab:Ie,updateDetailTask:Pe,closeDetailTask:oe,openGroupModal:re,closeGroupModal:_e,openSettings:fe,closeSettings:Xe,openSchedules:kt,closeSchedules:Rt,openGitHubImport:Vt,closeGitHubImport:Pt,openUsage:bt,closeUsage:pt,openSystemStats:ft,closeSystemStats:_t,toggleTerminal:Yt,closeTerminal:on,openFiles:An,closeFiles:vn,openTodos:Qt,closeTodos:sn,setFileWorkspace:mn,openActivityLog:Kt,closeActivityLog:fn,openGitManager:$n,closeGitManager:On,openWorkflowEditor:xn,closeWorkflowEditor:Vn,openAgents:Rn,closeAgents:Pn,openScripts:zn,closeScripts:Nn,runScript:dn,openSetupWizard:Tt,closeSetupWizard:Yn,openModelOnboarding:cn,closeModelOnboarding:Bn,onPlanningTaskCreated:kn,onPlanningTasksCreated:pn,onSubtaskTasksCreated:un}}function jV(e){const{t:n}=st("app"),{projectId:s,projects:i,projectsLoading:r,currentProject:o,setCurrentProject:l,addToast:d,openTaskDetail:c,closeTaskDetail:m}=e,p=a.useRef(!1),h=a.useRef(!1),u=a.useRef(null),f=a.useRef(null),b=a.useRef(null);return a.useEffect(()=>{if(!h.current){const g=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(g){const j=g[1];if(/^[A-Z]+-\d+$/.test(j)){const S=new URLSearchParams(window.location.search);S.set("task",j);const C=S.toString(),E=window.history.state??{};window.history.replaceState(E,"",C?`/?${C}`:"/"),h.current=!0}}}const v=new URLSearchParams(window.location.search),x=v.get("project"),k=v.get("task");if(r)return;let w=s;if(x){const g=i.find(j=>j.id===x);if(!g){f.current!==x&&(d(n("deepLink.projectNotFound","Project '{{id}}' not found",{id:x}),"error"),f.current=x);return}f.current=null,w=g.id,o?.id!==g.id&&b.current!==g.id&&(l(g),b.current=g.id)}else f.current=null,b.current=null;k&&(p.current||(p.current=!0,pr(k,w).then(g=>{c(g),u.current=k}).catch(()=>{d(n("deepLink.taskNotFound","Task {{id}} not found",{id:k}),"error")})))},[s,i,r,o,l,d,c]),{handleDetailClose:a.useCallback(()=>{if(u.current){const v=new URLSearchParams(window.location.search);v.delete("task");const x=v.toString(),k=window.history.state??{};window.history.replaceState(k,"",x?`${window.location.pathname}?${x}`:window.location.pathname),u.current=null}m()},[m])}}function NV({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,d=!1;Yo().then(({providers:c})=>{const m=c.some(h=>h.authenticated);if(c.length>0&&!m||c.length>0&&m)return Ja().then(h=>{const u=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!m||!u)&&!ol()?l=!0:!m&&!ol()&&(d=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(Zi("onboarding:auto-triggered",{trigger:"first-run"}),s()):d&&(Zi("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}function SV({isMobile:e,keyboardOpen:n,anyModalOpen:s,isIOS:i}){const r=e&&n&&!s&&i,o=e&&n;return{footerHidden:r,navKeyboardOpen:o,footerKeyboardOpen:o&&i}}const ik="kb-update-banner-dismissed";function CV(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,d]=a.useState(null),[c,m]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(ik)==="true";m(h);let u=!1;return IE().then(f=>{u||f.disabled||(i(f.updateAvailable===!0),o(typeof f.latestVersion=="string"?f.latestVersion:null),d(typeof f.currentVersion=="string"?f.currentVersion:null))}).catch(()=>{}).finally(()=>{u||n(!1)}),()=>{u=!0}},[]);const p=a.useCallback(()=>{m(!0),sessionStorage.setItem(ik,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:c,dismiss:p}}const _V=["board","list","graph","agents","missions","chat","documents","research","evals","goalsView","skills","mailbox","insights","memory","reliability","secrets","devserver","dev-server","stash-recovery","pull-requests"];function EV(e){return e!==null&&_V.includes(e)}function fh(e){return e!==null&&(EV(e)||Fo(e))}const MV=Cc("fusion-plugin-roadmap","roadmaps");function ak(e){return e==="devserver"?"dev-server":e}function rk(e){return e!=="roadmaps"?"board":pw("fusion-plugin-roadmap","roadmaps")?MV:"board"}function AV(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:d,themeMode:c,setThemeMode:m}=e,[p,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[u,f]=a.useState(()=>{const x=cs("kb-dashboard-task-view");return x==="roadmaps"?rk(x):fh(x)?x:"board"}),b=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",p)},[p]),a.useEffect(()=>{const x=cs("kb-dashboard-task-view",r?.id);if(x==="roadmaps")f(rk(x));else if(fh(x)){const k=!b.current&&x==="devserver";f(k?"devserver":ak(x))}else f("board");r?.id&&(b.current=!0)},[r?.id]),a.useEffect(()=>{_s("kb-dashboard-task-view",u,r?.id)},[r?.id,u]),a.useEffect(()=>{if(typeof window>"u")return;const x=new URLSearchParams(window.location.search).get("view");x&&fh(x)&&f(ak(x))},[]),a.useEffect(()=>{n||i||r&&p==="overview"&&h("project")},[n,i,r,p]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const x=window.setTimeout(()=>{d()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,d]);const y=a.useCallback(x=>{f(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],k=x.indexOf(c),w=x[(k+1)%x.length];m(w)},[c,m]);return{viewMode:p,setViewMode:h,taskView:u,setTaskView:f,handleChangeTaskView:y,handleToggleTheme:v}}const gh=new Map,TV=6e4;function RV(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),[d,c]=a.useState(0),m=a.useRef(!1),p=a.useCallback(()=>{const h=e??"default";gh.delete(h),c(u=>u+1)},[e]);return a.useEffect(()=>{const h=e??"default";let u=!1;async function f(){const b=gh.get(h);if(b&&Date.now()<b.expiresAt){if(u)return;s(b.views),r(!1);return}m.current||r(!0),l(null);try{const y=await RR(e);if(u)return;gh.set(h,{views:y,expiresAt:Date.now()+TV}),s(y)}catch(y){if(u)return;l(y instanceof Error?y.message:"Failed to fetch plugin dashboard views")}finally{u||(r(!1),m.current=!0)}}return f(),()=>{u=!0}},[e,d]),a.useMemo(()=>({views:n,loading:i,error:o,refetch:p}),[n,i,o,p])}function PV({taskView:e,context:n}){return t.jsx(kP,{viewId:e,context:n})}let ok=!1;function Xr(e,n){return function(){return a.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function IV(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",i=(await ln(()=>import("./dashboard-view-Dn4CztR6.js"),__vite__mapDeps([36,1,37,38,4,5,6,2,3,7,39])))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}async function DV(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",i=(await ln(()=>import("./dashboard-view-DlKsVySD.js"),__vite__mapDeps([40,1,41,38,42])))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}async function LV(){const e="@fusion-plugin-examples/compound-engineering/dashboard-view",n="CompoundEngineeringDashboardView",i=(await ln(()=>import("./dashboard-view-O5j3PSGY.js"),__vite__mapDeps([43,1,38,41,37,44])))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}async function FV(){const e="@fusion-plugin-examples/cli-printing-press/dashboard-view",n="CliPrintingPressWizardView";try{const i=(await import(e))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}catch{return{default:Xr(e,n)}}}async function OV(){const e="@fusion-plugin-examples/cli-printing-press/manage-view",n="CliPrintingPressManageView";try{const i=(await import(e))[n];return i?{default:i}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Xr(e,n)})}catch{return{default:Xr(e,n)}}}function pS(){ok||(ok=!0,Nl("fusion-plugin-dependency-graph","graph",a.lazy(IV)),Nl("fusion-plugin-roadmap","roadmaps",a.lazy(DV)),Nl("fusion-plugin-compound-engineering","compound-engineering",a.lazy(LV)),Nl("fusion-plugin-cli-printing-press","wizard",a.lazy(FV)),Nl("fusion-plugin-cli-printing-press","manage",a.lazy(OV)))}function $V(e){const{t:n}=st("app"),{setCurrentProject:s,clearCurrentProject:i,setViewMode:r,currentProject:o,refreshProjects:l,toggleFavoriteProvider:d,toggleFavoriteModel:c,addToast:m,openSettings:p,openSetupWizard:h,closeSetupWizard:u,closeModelOnboarding:f}=e,b=a.useCallback(F=>{s(F),r("project")},[s,r]),y=a.useCallback(()=>{i(),r("overview")},[i,r]),v=a.useCallback(()=>{p()},[p]),x=a.useCallback(()=>{h()},[h]),k=a.useCallback(F=>{u(),s(F),r("project"),m(n("projects.setup.success","Project {{name}} registered successfully",{name:F.name}),"success"),l()},[u,s,r,m,l,n]),w=a.useCallback(()=>{f()},[f]),g=a.useCallback(async F=>{try{await hT(F.id),m(n("projects.actions.pauseSuccess","Project {{name}} paused",{name:F.name}),"success"),await l()}catch{m(n("projects.actions.pauseError","Failed to pause project {{name}}",{name:F.name}),"error")}},[m,l,n]),j=a.useCallback(async F=>{try{await pT(F.id),m(n("projects.actions.resumeSuccess","Project {{name}} resumed",{name:F.name}),"success"),await l()}catch{m(n("projects.actions.resumeError","Failed to resume project {{name}}",{name:F.name}),"error")}},[m,l,n]),S=a.useCallback(async F=>{try{await iw(F.id),m(n("projects.actions.removeSuccess","Project {{name}} removed",{name:F.name}),"success"),o?.id===F.id&&(i(),r("overview")),await l()}catch{m(n("projects.actions.removeError","Failed to remove project {{name}}",{name:F.name}),"error")}},[o,i,r,m,l,n]),C=a.useCallback(async F=>{try{await d(F)}catch{m(n("projects.actions.favoritesError","Failed to update favorites"),"error")}},[d,m,n]),E=a.useCallback(async F=>{try{await c(F)}catch{m(n("projects.actions.modelFavoritesError","Failed to update model favorites"),"error")}},[c,m,n]);return{handleSelectProject:b,handleViewAllProjects:y,handleOpenSettings:v,handleAddProject:x,handleSetupComplete:k,handleModelOnboardingComplete:w,handlePauseProject:g,handleResumeProject:j,handleRemoveProject:S,handleToggleFavorite:C,handleToggleModelFavorite:E}}function zV(e){const{t:n}=st("app"),{createTask:s,ingestCreatedTasks:i,onPlanningTaskCreated:r,onPlanningTasksCreated:o,onSubtaskTasksCreated:l,addToast:d}=e,c=a.useCallback(async b=>s({...b,column:b.column??"triage",source:{sourceType:"dashboard_ui"}}),[s]),m=a.useCallback(async b=>await s({...b,column:"triage",source:{sourceType:"dashboard_ui"}}),[s]),p=a.useCallback(b=>{i([b]),r(b,d)},[d,i,r]),h=a.useCallback(b=>{i(b),o(b,d)},[d,i,o]),u=a.useCallback(b=>{i(b),l(b,d)},[d,i,l]),f=a.useCallback(b=>{d(n("taskHandlers.githubImported","Imported {{id}} from GitHub",{id:b.id}),"success")},[d,n]);return{handleBoardQuickCreate:c,handleModalCreate:m,handlePlanningTaskCreated:p,handlePlanningTasksCreated:h,handleSubtaskTasksCreated:u,handleGitHubImport:f}}function BV(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,d]=a.useState([]),[c,m]=a.useState(null),[p,h]=a.useState(!1),[u,f]=a.useState(null),b=a.useRef(null),y=a.useCallback(async()=>{if(!e){o([]),d([]),m(null),h(!1),f(null);return}b.current?.abort();const x=new AbortController;b.current=x,h(!0),f(null);try{const k=[KR(e),JR(e)];s&&(k.push(YR(e,s,i)),k.push(XR(e,s)));const w=await Promise.allSettled(k);if(x.signal.aborted)return;const g=w[0],j=w[1];if(g.status==="rejected"){f(`Failed to fetch node health: ${g.reason}`),h(!1);return}if(m(g.value),j.status==="rejected"){f(`Failed to fetch projects: ${j.reason}`),h(!1);return}if(o(j.value),s&&w[2]){const S=w[2];if(S.status==="rejected"){f(`Failed to fetch tasks: ${S.reason}`),h(!1);return}S.status==="fulfilled"&&d(S.value)}h(!1)}catch(k){x.signal.aborted||(f(k instanceof Error?k.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(y(),()=>{b.current?.abort()}),[y]);const v=a.useCallback(()=>{y()},[y]);return{projects:r,tasks:l,health:c,loading:p,error:u,refresh:v}}function UV(e){const[n,s]=a.useState(!1),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return li(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:i}}const HV="fusion-dashboard-current-node",fS=a.createContext(null);function VV({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let p=!1;async function h(){try{const u=await Ja();if(p)return;l.current=u.dashboardCurrentNodeId;const f=u.dashboardCurrentNodeId;if(f&&(o.current=!0),!f)try{const b=localStorage.getItem(HV);if(b){const y=JSON.parse(b);y?.id&&y?.type==="remote"&&(l.current=y.id,await Ms({dashboardCurrentNodeId:y.id}).catch(()=>{}))}}catch{}}catch{}finally{p||r(!1)}}return h(),()=>{p=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const p=n.id;l.current!==p&&(l.current=p,Ms({dashboardCurrentNodeId:p}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Ms({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const d=a.useCallback(p=>{s(p)},[]),c=a.useCallback(()=>{s(null),l.current=void 0,Ms({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),m={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:d,clearCurrentNode:c};return t.jsx(fS.Provider,{value:m,children:e})}function qV(){const e=a.useContext(fS);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const WV=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],GV=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let du=null,lk=!1;function KV(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 JV(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 gS(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 YV(e){return e==="local"||e==="remote"?e:void 0}function bS(e){const n=YV(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,i=JV(e.serverUrl),r=KV(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...i?{serverUrl:i}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function XV(e){for(const n of GV){const s=e[n];if(!s||typeof s!="object")continue;const i=s,r=gS(i.kind??i.shellKind??i.hostKind);if(r)return r==="browser"?{kind:r}:bS({kind:r,mode:i.mode??i.shellMode,connectionId:i.connectionId??i.profileId,serverUrl:i.serverUrl??i.serverBaseUrl,canOpenConnectionManager:i.canOpenConnectionManager??i.shellCanOpenConnectionManager})}return null}function QV(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,i=gS(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return i?i==="browser"?{kind:i}:bS({kind:i,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 ZV(e){try{const n=new URL(e.location.href);let s=!1;for(const r of WV)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const i=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",i)}catch{}}function e7(e=window){const n=XV(e);if(n)return n;const s=QV(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function vS(e=window){return!lk&&typeof window<"u"&&(du=e7(e),ZV(e),lk=!0),du??{kind:"browser"}}function t7(){return du||(typeof window>"u"?{kind:"browser"}:vS(window))}const n7={kind:"browser"},xS=a.createContext({host:n7,isNativeShell:!1,kind:"browser"});function s7(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 i7({children:e}){const n=a.useMemo(()=>s7(t7()),[]);return t.jsx(xS.Provider,{value:n,children:e})}function a7(){return a.useContext(xS)}function r7(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function o7({open:e,shellApi:n,shellState:s,onComplete:i}){const{t:r}=st("app"),[o,l]=a.useState(s.desktopMode??"remote"),[d,c]=a.useState(r("onboarding.defaultName","Remote Server")),[m,p]=a.useState(""),[h,u]=a.useState(""),[f,b]=a.useState(null),[y,v]=a.useState(!1),[x,k]=a.useState(!1),w=s.host==="desktop-shell";a.useEffect(()=>{w&&l(s.desktopMode??"remote")},[w,s.desktopMode]);const g=a.useMemo(()=>w&&o==="local"?!0:m.trim().length>0,[w,o,m]);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:r("onboarding.welcome","Welcome to Fusion")})}),t.jsxs("div",{className:"native-shell-onboarding-body",children:[t.jsx("p",{children:r("onboarding.description","Fusion helps you plan, run, and review AI-assisted engineering work.")}),w&&t.jsxs("div",{className:"native-shell-onboarding-mode-row",children:[t.jsx("button",{type:"button",className:`btn ${o==="local"?"btn-primary":""}`,onClick:()=>l("local"),children:r("onboarding.localFusion","Local Fusion")}),t.jsx("button",{type:"button",className:`btn ${o==="remote"?"btn-primary":""}`,onClick:()=>l("remote"),children:r("onboarding.remoteServer","Remote Server")})]}),(!w||o==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{b(null),v(!0);try{const j=await n.startQrScan();p(j.serverUrl),u(j.authToken??"")}catch(j){b(j.message)}finally{v(!1)}},disabled:y,children:y?r("onboarding.scanning","Scanning…"):r("onboarding.scanQr","Scan QR")}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:r("onboarding.profileName","Profile name")}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:d,onChange:j=>c(j.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:r("onboarding.serverUrl","Server URL")}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:m,onChange:j=>p(j.target.value),placeholder:r("onboarding.serverUrlPlaceholder","https://your-fusion-host")}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:r("onboarding.authToken","Auth token (optional)")}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:h,onChange:j=>u(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:!g||x,onClick:async()=>{b(null),k(!0);try{if(w&&o==="local"){await n.setDesktopMode("local"),i();return}const j=await n.saveProfile({name:d.trim()||r("onboarding.defaultName","Remote Server"),serverUrl:m,authToken:h||null});if(w&&await n.setDesktopMode("remote"),await n.setActiveProfile(j.id),typeof window<"u"&&s.host!=="web"){window.location.href=r7(j.serverUrl,j.authToken??null);return}i()}catch(j){b(j.message)}finally{k(!1)}},children:x?r("onboarding.saving","Saving…"):r("onboarding.continue","Continue")})})]})}):null}function l7({open:e,shellApi:n,shellState:s,onClose:i}){const{t:r}=st("app"),o=a.useMemo(()=>s.profiles.find(C=>C.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[l,d]=a.useState(null),[c,m]=a.useState({}),[p,h]=a.useState(null),[u,f]=a.useState(null);if(!e)return null;const b=l==="__new__",y=b?null:s.profiles.find(C=>C.id===l)??o,v=c.name??y?.name??"",x=c.serverUrl??y?.serverUrl??"",k=c.authToken??y?.authToken??"",w=()=>{d(null),m({}),f(null)},g=async()=>{f(null);try{const C=new URL(x.trim());if(!/^https?:$/.test(C.protocol))throw new Error(r("shell.serverUrlProtocolError","Server URL must use http or https"));const E=await n.saveProfile({id:b?void 0:l??y?.id,name:v||r("shell.defaultProfileName","Remote Server"),serverUrl:x,authToken:k||null});await n.setActiveProfile(E.id),d(E.id),m({})}catch(C){f(C.message)}},j=async()=>{f(null);try{const C=await n.startQrScan();d("__new__"),m({name:"",serverUrl:C.serverUrl,authToken:C.authToken??""})}catch(C){f(C.message)}},S=async()=>{p&&(await n.deleteProfile(p.id),h(null),w())};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":r("shell.connectionManagerLabel","Connection Manager"),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:r("shell.connectionManager","Connection Manager")}),t.jsx("button",{type:"button",className:"modal-close",onClick:i,"aria-label":r("actions.close","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:r("shell.modeLocal","Local")}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:r("shell.modeRemote","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:r("shell.noServersSaved","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:()=>{d("__new__"),m({name:"",serverUrl:"",authToken:""}),f(null)},children:r("shell.addServer","Add server")}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void j(),children:r("shell.scanQr","Scan QR")})]})]}):s.profiles.map(C=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:C.name}),t.jsx("div",{className:"settings-muted",children:C.serverUrl}),C.id===s.activeProfileId&&t.jsx("span",{className:"native-shell-connection-manager__active-pill",children:r("shell.activePill","Active")})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":r("shell.editProfile","Edit {{name}}",{name:C.name}),onClick:()=>{d(C.id),m(C)},children:r("actions.edit","Edit")}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":r("shell.useProfile","Use {{name}}",{name:C.name}),onClick:()=>void n.setActiveProfile(C.id),children:r("shell.use","Use")}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":r("shell.deleteProfile","Delete {{name}}",{name:C.name}),onClick:()=>h(C),children:r("actions.delete","Delete")})]})]},C.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{d("__new__"),m({name:"",serverUrl:"",authToken:""}),f(null)},children:r("shell.addConnection","Add connection")}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void j(),children:r("shell.scanQr","Scan QR")})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:r("shell.nameLabel","Name")}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:v,onChange:C=>m(E=>({...E,name:C.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-url",children:r("shell.serverUrlLabel","Server URL")}),t.jsx("input",{id:"native-shell-connection-manager-url",className:"input",value:x,onChange:C=>m(E=>({...E,serverUrl:C.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-token",children:r("shell.authTokenLabel","Auth token (optional)")}),t.jsx("input",{id:"native-shell-connection-manager-token",className:"input",type:"password",value:k??"",onChange:C=>m(E=>({...E,authToken:C.target.value}))}),u&&t.jsx("p",{className:"form-error",role:"alert",children:u})]}),p&&t.jsxs("div",{className:"native-shell-connection-manager__delete-confirm",role:"alertdialog","aria-label":r("shell.deleteConfirmLabel","Delete server confirmation"),children:[t.jsx("p",{children:r("shell.deleteConfirmMessage","Delete {{name}}? This removes the saved profile.",{name:p.name})}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>h(null),children:r("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void S(),children:r("actions.delete","Delete")})]})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:i,children:r("actions.close","Close")}),t.jsx("button",{type:"button",className:"btn",onClick:w,children:r("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void g(),disabled:!x.trim(),children:r("actions.save","Save")})]})]})})}function c7(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,i=n&&s?`${n} · ${s}`:n??s;return e.mode==="remote"?{title:i??"Connection info unavailable",actionLabel:e.hostKind==="desktop-shell"?"Switch server":"Manage connections",dotClassName:i?"status-dot status-dot--online":"status-dot status-dot--pending"}:{title:i??"Connection info unavailable",actionLabel:"Manage connections",dotClassName:i?"status-dot status-dot--online":"status-dot status-dot--pending"}}function ck({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=c7(e),i=a.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 i(),"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 d7(e){if(e)try{return new URL(e).origin}catch{return}}function u7(e,n){const s=e.profiles.find(i=>i.id===e.activeProfileId)??null;return s||(n.kind==="browser"||!n.connectionId?null:e.profiles.find(i=>i.id===n.connectionId)??null)}async function m7(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function h7(e,n=window){const s=n.fusionAPI,i=n.fusionShell,r=await m7(i),o=r?u7(r,e):null,l=e.kind==="browser"?void 0:e.mode??r?.desktopMode,d=o?.id??(e.kind==="browser"?void 0:e.connectionId),c=o?.name,m=d7(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),p=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",h=e.kind==="mobile-shell"&&typeof i?.openConnectionManager=="function",u=p||h;return{hostKind:e.kind,available:u,...l?{mode:l}:{},...d?{profileId:d}:{},...c?{profileLabel:c}:{},...m?{serverOrigin:m}:{},openConnectionManager:async()=>{try{return p?(await s.openConnectionManager?.(),{ok:!0}):h?(await i.openConnectionManager(),{ok:!0}):{ok:!1,reason:"unsupported"}}catch(f){return{ok:!1,reason:"failed",error:f instanceof Error?f.message:String(f)}}}}}function p7({open:e}){const{t:n}=st("app"),[s,i]=a.useState(""),r=a.useRef(null);a.useEffect(()=>{e&&r.current?.focus()},[e]);const o=a.useCallback(()=>{const d=s.trim();d&&(rE(d),window.location.reload())},[s]),l=a.useCallback(()=>{oE(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:d=>{d.key==="Escape"&&(d.preventDefault(),d.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:n("auth.tokenRequired","Authentication token required")})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:n("auth.tokenRecoveryDescription","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:n("auth.replacementToken","Replacement token")}),t.jsx("input",{ref:r,id:"auth-token-recovery-input",className:"input",type:"password",value:s,onChange:d=>i(d.target.value),placeholder:n("auth.pasteToken","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:l,children:n("auth.clearAndRetry","Clear token and retry")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:o,disabled:s.trim().length===0,children:n("auth.setAndReload","Set token and reload")})]})]})}):null}const f7=a.lazy(()=>ln(()=>import("./AgentsView-ChXccELt.js"),__vite__mapDeps([45,1,4,10,11,34,22,5,6,2,3,7,46])).then(e=>({default:e.AgentsView}))),g7=a.lazy(()=>ln(()=>import("./DocumentsView-CbbZwzbH.js"),__vite__mapDeps([47,1,4,5,6,2,3,7,48])).then(e=>({default:e.DocumentsView}))),b7=a.lazy(()=>ln(()=>import("./InsightsView-C5vLvWVE.js"),__vite__mapDeps([49,1,4,29,5,6,2,3,7,50])).then(e=>({default:e.InsightsView}))),v7=a.lazy(()=>ln(()=>import("./ResearchView-C1QghmLI.js"),__vite__mapDeps([51,1,4,5,6,2,3,7,52])).then(e=>({default:e.ResearchView}))),x7=a.lazy(()=>ln(()=>import("./EvalsView-BL_ue7fJ.js"),__vite__mapDeps([53,1,4,5,6,2,3,7,54])).then(e=>({default:e.EvalsView}))),y7=a.lazy(()=>ln(()=>import("./NodesView-DfBNNm9c.js"),__vite__mapDeps([55,1,4,24,34,5,6,2,3,7,56])).then(e=>({default:e.NodesView}))),k7=a.lazy(()=>ln(()=>import("./ChatView-Dz_xBKit.js"),__vite__mapDeps([57,1,4,0,2,3,5,6,7,8,58])).then(e=>({default:e.ChatView}))),w7=a.lazy(()=>ln(()=>import("./SkillsView-CIEY1-DE.js"),__vite__mapDeps([59,1,4,5,6,2,3,7,60])).then(e=>({default:e.SkillsView}))),j7=a.lazy(()=>ln(()=>import("./MemoryView-BL3W3yOv.js"),__vite__mapDeps([61,1,30,31,4,5,6,2,3,7,62])).then(e=>({default:e.MemoryView}))),N7=a.lazy(()=>ln(()=>import("./SecretsView-Y2MQ-9n5.js"),__vite__mapDeps([27,1,4,5,6,2,3,7,28])).then(e=>({default:e.SecretsView}))),S7=a.lazy(()=>ln(()=>import("./ReliabilityView-DbqEwoRs.js"),__vite__mapDeps([63,1,4,5,6,2,3,7,64])).then(e=>({default:e.ReliabilityView}))),C7=a.lazy(()=>ln(()=>import("./DevServerView-DGOahw1o.js"),__vite__mapDeps([65,1,4,5,6,2,3,7,66])).then(e=>({default:e.DevServerView})));a.lazy(()=>ln(()=>import("./TodoView-B8IK_BPM.js"),__vite__mapDeps([18,1,4,5,6,2,3,7,19])).then(e=>({default:e.TodoView})));const _7=a.lazy(()=>ln(()=>import("./GoalsView-CO4FVL3E.js"),__vite__mapDeps([67,1,4,5,6,2,3,7,68])).then(e=>({default:e.GoalsView}))),E7=a.lazy(()=>ln(()=>import("./StashRecoveryView-B6iDu5tI.js"),__vite__mapDeps([69,1,4,5,6,2,3,7,70])).then(e=>({default:e.StashRecoveryView}))),M7=a.lazy(()=>ln(()=>import("./PullRequestView-C2jQX8xZ.js"),__vite__mapDeps([71,1,4,5,6,2,3,7,72])).then(e=>({default:e.PullRequestView})));function A7(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{ln(()=>import("./AgentsView-ChXccELt.js"),__vite__mapDeps([45,1,4,10,11,34,22,5,6,2,3,7,46])),ln(()=>import("./DocumentsView-CbbZwzbH.js"),__vite__mapDeps([47,1,4,5,6,2,3,7,48])),ln(()=>import("./InsightsView-C5vLvWVE.js"),__vite__mapDeps([49,1,4,29,5,6,2,3,7,50])),ln(()=>import("./ResearchView-C1QghmLI.js"),__vite__mapDeps([51,1,4,5,6,2,3,7,52])),ln(()=>import("./EvalsView-BL_ue7fJ.js"),__vite__mapDeps([53,1,4,5,6,2,3,7,54])),ln(()=>import("./NodesView-DfBNNm9c.js"),__vite__mapDeps([55,1,4,24,34,5,6,2,3,7,56])),ln(()=>import("./ChatView-Dz_xBKit.js"),__vite__mapDeps([57,1,4,0,2,3,5,6,7,8,58])),ln(()=>import("./SkillsView-CIEY1-DE.js"),__vite__mapDeps([59,1,4,5,6,2,3,7,60])),ln(()=>import("./MemoryView-BL3W3yOv.js"),__vite__mapDeps([61,1,30,31,4,5,6,2,3,7,62])),ln(()=>import("./SecretsView-Y2MQ-9n5.js"),__vite__mapDeps([27,1,4,5,6,2,3,7,28])),ln(()=>import("./ReliabilityView-DbqEwoRs.js"),__vite__mapDeps([63,1,4,5,6,2,3,7,64])),ln(()=>import("./DevServerView-DGOahw1o.js"),__vite__mapDeps([65,1,4,5,6,2,3,7,66])),ln(()=>import("./TodoView-B8IK_BPM.js"),__vite__mapDeps([18,1,4,5,6,2,3,7,19])),ln(()=>import("./GoalsView-CO4FVL3E.js"),__vite__mapDeps([67,1,4,5,6,2,3,7,68])),ln(()=>import("./StashRecoveryView-B6iDu5tI.js"),__vite__mapDeps([69,1,4,5,6,2,3,7,70])),ln(()=>import("./PullRequestView-C2jQX8xZ.js"),__vite__mapDeps([71,1,4,5,6,2,3,7,72]))})}pS();const bh="kb-setup-warning-dismissed",dk="kb-dashboard-working-branch-filter",uk="kb-dashboard-base-branch-filter",mk="__fusion:no-branch__",yS="fusion:approval-banner-dismissed",Ed="kb-capacity-risk-banner-dismissed",T7=.8;function R7(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function P7(e,n){return e==="done"&&n!==void 0&&n!=="done"}function hk(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function I7(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(yS);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[i,r]of Object.entries(n))typeof r=="number"&&Number.isFinite(r)&&s.set(i,r);return s}catch{return new Map}}function pk(e){if(!(typeof window>"u"))try{const n={};for(const[s,i]of e)n[s]=i;window.localStorage.setItem(yS,JSON.stringify(n))}catch{}}function D7(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function L7(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function F7(e,n){return e&&n===0}function O7(){const{t:e}=st("app"),{toasts:n,addToast:s,removeToast:i}=MN(),{shellApi:r,state:o,ready:l,openConnectionManagerSignal:d}=VN(),c=a7();a.useEffect(()=>{A7()},[]);const{projects:m,loading:p,error:h,refresh:u}=tV(),f=a.useRef(m.length>0),{nodes:b}=Nu();a.useEffect(()=>{m.length>0&&(f.current=!0)},[m.length]);const{currentNode:y,currentNodeId:v,isRemote:x,setCurrentNode:k,clearCurrentNode:w}=qV(),{currentProject:g,setCurrentProject:j,clearCurrentProject:S,loading:C}=iV(m,{nodeId:v}),{hasAiProvider:E,hasGithub:F,loading:M,hasWarnings:D}=zN(g?.id),{updateAvailable:_,latestVersion:V,currentVersion:N,dismissed:$,dismiss:R}=CV();a.useEffect(()=>{if(v&&!y&&b.length>0){const Ve=b.find(Bt=>Bt.id===v);if(Ve){k(Ve);return}}v&&b.length>0&&(b.some(Bt=>Bt.id===v)||w())},[v,y,b,k,w]);const[L,O]=a.useState(""),[J,A]=a.useState(""),[de,B]=a.useState("");a.useEffect(()=>{A(cs(dk,g?.id)??""),B(cs(uk,g?.id)??"")},[g?.id]);const P=a.useCallback(Ve=>{A(Ve),_s(dk,Ve,g?.id)},[g?.id]),Z=a.useCallback(Ve=>{B(Ve),_s(uk,Ve,g?.id)},[g?.id]),T=a.useCallback((Ve,Bt)=>{const wn=new URLSearchParams;g?.id&&wn.set("projectId",g.id);const Ns=wn.size>0?`?${wn.toString()}`:"";return li(`/api/events${Ns}`,{events:{"plugin:custom":Us=>{try{const bi=JSON.parse(Us.data);bi.pluginId===Ve&&typeof bi.event=="string"&&Bt({event:bi.event,payload:bi.payload})}catch{}}}})},[g?.id]),ie=BV(v,{projectId:g?.id,searchQuery:L||void 0});UV(v);const le=x&&ie.projects.length>0?ie.projects:m,{themeMode:be,colorTheme:Le,dashboardFontScalePct:xe,setThemeMode:q,setColorTheme:ce,setDashboardFontScalePct:De}=kV(),{sessions:He,generating:qe,needsInput:pe,planningSessions:te,dismissSession:me}=U9(g?.id),se=He.filter(Ve=>Ve.status==="awaiting_input"||Ve.status==="error"),z=J9(),Y=wV({projectId:g?.id,planningSessions:te}),X=Ji()==="mobile",{pushNav:ye,replaceCurrent:ot,removeNav:ue}=P6({enabled:!0}),{viewMode:je,setViewMode:$e,taskView:Ce,handleChangeTaskView:We}=AV({projectsLoading:p,projectsError:h,currentProjectLoading:C,currentProject:g,projectsLength:m.length,setupWizardOpen:Y.setupWizardOpen,openSetupWizard:Y.openSetupWizard,themeMode:be,setThemeMode:q}),{views:ke}=RV(g?.id),Ee=a.useMemo(()=>{const Ve=ke.find(Bt=>Bt.pluginId==="fusion-plugin-dependency-graph"&&Bt.view.viewId==="graph");return Ve?`plugin:${Ve.pluginId}:${Ve.view.viewId}`:pw("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[ke]),Ze=a.useCallback(Ve=>{Ve==="missions"&&(bn(void 0),ps(void 0),ht(void 0)),Ve!=="goalsView"&&ae(void 0);const Bt=Ce;We(Ve),Bt!==Ve&&ye({type:"view",revert:()=>We(Bt)})},[We,Ce,ye]),Ke=Ce==="board"||Ce==="list",{tasks:dt,isStale:Fe,createTask:nt,moveTask:Nt,pauseTask:Ft,unpauseTask:ze,deleteTask:it,mergeTask:Mt,retryTask:Ht,resetTask:Me,updateTask:Ae,duplicateTask:ee,archiveTask:Ie,unarchiveTask:Pe,archiveAllDone:oe,loadArchivedTasks:re,refreshTasks:_e,ingestCreatedTasks:fe,lastFetchTimeMs:Xe}=X9({...g?{projectId:g.id}:{},searchQuery:L||void 0,sseEnabled:Ke}),kt=a.useRef(Ce);a.useEffect(()=>{const Ve=kt.current;!(Ve==="board"||Ve==="list")&&(Ce==="board"||Ce==="list")&&_e(),kt.current=Ce},[Ce,_e]);const Rt=x&&ie.tasks.length>0?ie.tasks:dt,[Vt,Pt]=a.useState(0),bt=a.useRef(performance.now()),pt=a.useRef(!1),ft=a.useRef(!1),_t=a.useRef(!1),Yt=a.useMemo(()=>p?"projects":C?"project":"tasks",[p,C]);a.useEffect(()=>{if(!p&&!pt.current){pt.current=!0;const Ve=`projects loaded at ${Math.round(performance.now()-bt.current)}ms from mount`;console.log(`[App] ${Ve}`)}if(!C&&!ft.current){ft.current=!0;const Ve=`current-project resolved at ${Math.round(performance.now()-bt.current)}ms from mount`;console.log(`[App] ${Ve}`)}},[p,C]);const on=!p&&!C,An=F7(p,m.length);a.useEffect(()=>{if(!on||_t.current)return;_t.current=!0;const Ve=`dashboard ready at ${Math.round(performance.now()-bt.current)}ms from mount`;console.log(`[App] ${Ve}`)},[on]);const{keyboardOpen:vn}=Xa({enabled:X}),{footerHidden:Qt,navKeyboardOpen:sn,footerKeyboardOpen:mn}=SV({isMobile:X,keyboardOpen:vn,anyModalOpen:Y.anyModalOpen,isIOS:tf()}),Kt=Qt,fn=sn;ga(Kt);const[$n,On]=a.useState(0),[xn,Vn]=a.useState(0),[Rn,Pn]=a.useState(!1),[zn,Nn]=a.useState(0),[dn,Tt]=a.useState(null),[Yn,cn]=a.useState(!1),Bn=a.useRef(new Map),kn=a.useRef(new Set),pn=a.useRef(I7()),un=W9(),At=a.useCallback(()=>{lw(g?.id).then(Ve=>{On(Ve.unreadCount),Vn(Ve.pendingApprovalCount??0)}).catch(Ve=>{console.warn("[App] Failed to fetch mailbox unread count:",Ve)})},[g?.id]);a.useEffect(()=>{const Ve=new Map,Bt=new Set;for(const wn of dt)Ve.set(wn.id,wn.status),wn.status==="awaiting-approval"&&Bt.add(`task:${wn.id}`);Bn.current=Ve,kn.current=Bt},[dt]),a.useEffect(()=>{At();const Ve=new URLSearchParams;g?.id&&Ve.set("projectId",g.id);const Bt=Ve.size>0?`?${Ve.toString()}`:"",wn=Ns=>{const Us=pn.current.get(Ns.dedupeKey);Us!==void 0&&Ns.updatedAtMs<=Us||Tt(Ns)};return li(`/api/events${Bt}`,{onReconnect:At,events:{"message:sent":At,"message:received":At,"message:read":At,"message:deleted":At,"approval:requested":Ns=>{At();try{const Us=JSON.parse(Ns.data),bi=Us.id?`approval:${Us.id}`:Us.taskId?`task:${Us.taskId}`:void 0;if(!bi||kn.current.has(bi))return;kn.current.add(bi),wn({dedupeKey:bi,updatedAtMs:hk(Us.updatedAt??Us.createdAt)})}catch{}},"approval:updated":At,"approval:decided":At,"task:updated":Ns=>{try{const Us=JSON.parse(Ns.data);if(!Us?.id)return;const bi=`task:${Us.id}`,Tc=Bn.current.get(Us.id);if(Bn.current.set(Us.id,Us.status),!un&&P7(Us.status,Tc)&&cn(!0),Us.status!=="awaiting-approval"){kn.current.delete(bi),pn.current.delete(bi),pk(pn.current);return}if(kn.current.has(bi))return;R7(Us.status,Tc)&&(kn.current.add(bi),wn({dedupeKey:bi,updatedAtMs:hk(Us.updatedAt)}),At())}catch{}}}})},[g?.id,un,At]),a.useEffect(()=>{Ce==="chat"&&Pn(!1)},[Ce]),a.useEffect(()=>{let Ve=!1;const Bt=async()=>{try{const Ns=await I("/stash-recovery/orphans");Ve||Nn(Ns.count??0)}catch{Ve||Nn(0)}};Bt();const wn=window.setInterval(()=>void Bt(),3e4);return()=>{Ve=!0,window.clearInterval(wn)}},[g?.id]),a.useEffect(()=>{const Ve=new URLSearchParams;g?.id&&Ve.set("projectId",g.id);const Bt=Ve.size>0?`?${Ve.toString()}`:"";return li(`/api/events${Bt}`,{events:{"chat:message:added":wn=>{try{const Ns=JSON.parse(wn.data);if(Ns.role!=="assistant"||Ce==="chat"||Ns.projectId&&g?.id&&Ns.projectId!==g.id)return;Pn(!0)}catch{}},"chat:room:message:added":wn=>{try{const Ns=JSON.parse(wn.data);if(Ns.role==="user"||Ce==="chat"||Ns.projectId&&g?.id&&Ns.projectId!==g.id)return;Pn(!0)}catch{}}}})},[g?.id,Ce]);const an=a.useMemo(()=>Array.from(new Set(Rt.map(Ve=>Ve.branch?.trim()).filter(Ve=>!!(Ve&&Ve.length>0)))).sort((Ve,Bt)=>Ve.localeCompare(Bt)),[Rt]),Wn=a.useMemo(()=>Array.from(new Set(Rt.map(Ve=>Ve.baseBranch?.trim()).filter(Ve=>!!(Ve&&Ve.length>0)))).sort((Ve,Bt)=>Ve.localeCompare(Bt)),[Rt]),Xn=a.useMemo(()=>Rt.filter(Ve=>{const Bt=Ve.branch?.trim()??"",wn=Ve.baseBranch?.trim()??"";if(J===mk){if(Bt.length>0)return!1}else if(J.length>0&&Bt!==J)return!1;if(de===mk){if(wn.length>0)return!1}else if(de.length>0&&wn!==de)return!1;return!0}),[Rt,J,de]),[G,Oe]=a.useState(!1),yt=a.useCallback(()=>{Oe(!1)},[]),[Gt,Sn]=a.useState(!1),[Un,bn]=a.useState(void 0),[gn,ps]=a.useState(void 0),[Ne,ae]=a.useState(void 0),[Se,ut]=a.useState(()=>typeof window>"u"?void 0:new URL(window.location.href).searchParams.get("pr")??void 0),[It,ht]=a.useState(void 0);a.useEffect(()=>{Ce!=="goalsView"&&Ne!==void 0&&ae(void 0)},[Ne,Ce]),a.useEffect(()=>{Ce!=="pull-requests"&&Se!==void 0&&ut(void 0)},[Se,Ce]);const[et,Ut]=a.useState(!1),[$t,rn]=a.useState(!1),[Cn,ve]=a.useState(null),[at,Ge]=a.useState(!1),[tt,gt]=a.useState(null),[St,Xt]=a.useState(()=>cs(bh,g?.id)==="true"),[ss,Ts]=a.useState(()=>cs(Ed,g?.id)==="true");a.useEffect(()=>{Xt(cs(bh,g?.id)==="true")},[g?.id]),a.useEffect(()=>{Ts(cs(Ed,g?.id)==="true")},[g?.id]);const Ls=a.useCallback(async()=>{Ge(!0),gt(null);try{const Ve=await Bk();ve(Ve)}catch(Ve){gt(Ve instanceof Error?Ve.message:"Failed to refresh database health.")}finally{Ge(!1)}},[]);a.useEffect(()=>{let Ve=!1;return gE().then(Bt=>{Ve||ve(Bt)}).catch(()=>{Ve||ve(null)}),()=>{Ve=!0}},[]),a.useEffect(()=>{const Ve=()=>{rn(!0)};return window.addEventListener(Mh,Ve),()=>{window.removeEventListener(Mh,Ve)}},[]);const rs=a.useCallback(()=>{_s(bh,"true",g?.id),Xt(!0)},[g?.id]),ei=a.useCallback(()=>{_s(Ed,"true",g?.id),Ts(!0)},[g?.id]),{maxConcurrent:Mi,autoMerge:ti,globalPaused:mi,enginePaused:zs,isTestMode:Qn,taskStuckTimeoutMs:Zt,staleHighFanoutBlockerAgeThresholdMs:Q,capacityRiskBannerEnabled:Qe,capacityRiskTodoThreshold:vt,showQuickChatFAB:xt,maxTotalRetriesBeforeFail:zt,prAuthAvailable:Wt,settingsLoaded:hn,experimentalFeatures:In,insightsEnabled:gs,memoryEnabled:ks,devServerEnabled:Te,todosEnabled:U,goalsEnabled:ge,toggleAutoMerge:rt,toggleGlobalPause:Lt,toggleEnginePause:Dt,refresh:en}=aS(g?.id),{stats:tn}=iS(g?.id),Dn=a.useMemo(()=>Rt.filter(Ve=>Ve.column==="in-progress").length,[Rt]),_n=a.useMemo(()=>Rt.filter(Ve=>Ve.column==="in-review").length,[Rt]),is=a.useMemo(()=>L_({todoCount:tn?.todoTaskCount??0,inProgressCount:Dn,inReviewCount:_n,idleNonEphemeralAgentCount:tn?.idleNonEphemeralCount??0,threshold:vt??D_}),[tn?.todoTaskCount,tn?.idleNonEphemeralCount,Dn,_n,vt]),Ss=a.useRef(Qe),Rs=a.useRef(vt),ne=a.useRef(g?.id),Ue=a.useRef(!1);a.useEffect(()=>{if(!hn)return;if(!Ue.current||ne.current!==g?.id){Ue.current=!0,ne.current=g?.id,Ss.current=Qe,Rs.current=vt;return}const Ve=Ss.current,Bt=Rs.current;(!Ve&&Qe||Bt!==vt)&&(sa(Ed,g?.id),Ts(!1)),ne.current=g?.id,Ss.current=Qe,Rs.current=vt},[hn,Qe,vt,g?.id]);const Je=In.skillsView===!0,qt=In.nodesView===!0,En=In.researchView===!0,yn=In.evalsView===!0,os=In.agentOnboarding===!0,fs=!0,ws=a.useCallback(()=>{Y.closeSettings(),Pt(Ve=>Ve+1),en()},[Y,en]),js=a.useCallback(()=>{ue(ws),ws()},[ws,ue]);a.useEffect(()=>{if(hn&&!Fo(Ce)){if(Ce==="graph"&&!Ee){We("board");return}Ce==="skills"&&!Je&&We("board"),Ce==="insights"&&!gs&&We("board"),Ce==="memory"&&!ks&&We("board"),(Ce==="devserver"||Ce==="dev-server")&&!Te&&We("board"),Ce==="research"&&!En&&We("board"),Ce==="evals"&&!yn&&We("board"),Ce==="goalsView"&&!ge&&We("board")}},[Ce,hn,Je,gs,We,fs,ks,Te,En,yn,ge,Ee]),a.useEffect(()=>{G&&!qt&&(ue(yt),yt())},[yt,G,qt,ue]);const{availableModels:Vs,favoriteProviders:qs,favoriteModels:Ai,toggleFavoriteProvider:pi,toggleFavoriteModel:Fs}=eN();NV({projectId:g?.id,setupWizardOpen:Y.setupWizardOpen,openModelOnboarding:Y.openModelOnboarding,openSettings:Y.openSettings});const{handleSelectProject:ji,handleViewAllProjects:Oa,handleAddProject:wr,handleSetupComplete:fl,handleModelOnboardingComplete:fi,handlePauseProject:gl,handleResumeProject:la,handleRemoveProject:ba,handleToggleFavorite:va,handleToggleModelFavorite:Xi}=$V({setCurrentProject:j,clearCurrentProject:S,setViewMode:$e,currentProject:g,refreshProjects:u,toggleFavoriteProvider:pi,toggleFavoriteModel:Fs,addToast:s,openSettings:Y.openSettings,openSetupWizard:Y.openSetupWizard,closeSetupWizard:Y.closeSetupWizard,closeModelOnboarding:Y.closeModelOnboarding}),{handleDetailClose:jr}=jV({projectId:g?.id,projects:m,projectsLoading:p,currentProject:g,setCurrentProject:j,addToast:s,openTaskDetail:Y.openDetailTask,closeTaskDetail:Y.closeDetailTask}),bl=a.useCallback(async({insightId:Ve,title:Bt,description:wn})=>{await nt({title:Bt,description:wn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Ve}}})},[nt]),{handleBoardQuickCreate:Nr,handleModalCreate:Sr,handlePlanningTaskCreated:io,handlePlanningTasksCreated:vl,handleSubtaskTasksCreated:Qa,handleGitHubImport:$a}=zV({createTask:nt,ingestCreatedTasks:fe,onPlanningTaskCreated:Y.onPlanningTaskCreated,onPlanningTasksCreated:Y.onPlanningTasksCreated,onSubtaskTasksCreated:Y.onSubtaskTasksCreated,addToast:s}),za=a.useCallback((Ve,Bt)=>{Bt==="changes"?Y.openDetailWithChangesTab(Ve):Y.openDetailTask(Ve,Bt),ye({type:"modal",close:Y.closeDetailTask})},[Y,ye]),gi=a.useCallback(async Ve=>{try{const Bt=await pr(Ve,g?.id);Y.openDetailTask(Bt,"logs"),ye({type:"modal",close:Y.closeDetailTask})}catch(Bt){s(`Failed to open task logs: ${Bt.message}`,"error")}},[Y,g?.id,s,ye]),[zi,xa]=a.useState([]);a.useEffect(()=>{let Ve=!1;return zp(g?.id).then(Bt=>{Ve||xa(Bt)}).catch(()=>{Ve||xa([])}),()=>{Ve=!0}},[g?.id]);const Cr=a.useMemo(()=>new Map(zi.map(Ve=>[Ve.id,Ve.name])),[zi]);a.useCallback(()=>{qt&&Oe(Ve=>!Ve)},[qt]);const Ti=a.useCallback(()=>{ue(yt),yt()},[yt,ue]),ao=a.useCallback(()=>{qt&&(G?Ti():(Oe(!0),ye({type:"view",revert:yt})))},[yt,Ti,qt,G,ye]),Bi=a.useCallback((Ve,Bt,wn)=>{Y.openDetailTask(Ve,Bt,wn),ye({type:"modal",close:Y.closeDetailTask})},[Y,ye]),ro=a.useCallback(Ve=>{Y.openSettings(Ve),ye({type:"modal",close:ws})},[Y,ye,ws]),Za=a.useCallback(()=>{Y.openNewTask(),ye({type:"modal",close:Y.closeNewTask})},[Y,ye]),_r=a.useCallback(()=>{Y.openPlanning(),ye({type:"modal",close:Y.closePlanning})},[Y,ye]),Ba=a.useCallback(Ve=>{Y.openPlanningWithInitialPlan(Ve),ye({type:"modal",close:Y.closePlanning})},[Y,ye]),ya=a.useCallback(()=>{Y.resumePlanning(),ye({type:"modal",close:Y.closePlanning})},[Y,ye]),oo=a.useCallback(Ve=>{Y.openSubtaskBreakdown(Ve),ye({type:"modal",close:Y.closeSubtask})},[Y,ye]),Cs=a.useCallback(Ve=>{Y.openGroupModal(Ve),ye({type:"modal",close:Y.closeGroupModal})},[Y,ye]),ka=a.useCallback(()=>{Y.openGitHubImport(),ye({type:"modal",close:Y.closeGitHubImport})},[Y,ye]),wa=a.useCallback(()=>{Y.terminalOpen?(ue(Y.closeTerminal),Y.toggleTerminal()):(Y.toggleTerminal(),ye({type:"modal",close:Y.closeTerminal}))},[Y,ye,ue]),Er=a.useCallback((Ve,Bt)=>{Y.openFiles(Ve,Bt),ye({type:"modal",close:Y.closeFiles})},[Y,ye]),ja=a.useCallback((Ve,Bt)=>{Y.openFiles(Bt?.workspace,Ve),ye({type:"modal",close:Y.closeFiles})},[Y,ye]),lo=a.useCallback(()=>{Y.openTodos(),ye({type:"modal",close:Y.closeTodos})},[Y,ye]),co=a.useCallback(()=>{Y.openActivityLog(),ye({type:"modal",close:Y.closeActivityLog})},[Y,ye]),Mr=a.useCallback(()=>{Y.openGitManager(),ye({type:"modal",close:Y.closeGitManager})},[Y,ye]),Ar=a.useCallback(()=>{Y.openSystemStats(),ye({type:"modal",close:Y.closeSystemStats})},[Y,ye]),er=a.useCallback(()=>{Y.openSchedules(),ye({type:"modal",close:Y.closeSchedules})},[Y,ye]),Kn=a.useCallback(()=>{Y.openScripts(),ye({type:"modal",close:Y.closeScripts})},[Y,ye]),tr=a.useCallback(Ve=>{Y.openWorkflowEditor(void 0,Ve),ye({type:"modal",close:Y.closeWorkflowEditor})},[Y,ye]),nr=a.useCallback(()=>{Y.openWorkflowEditor("create"),ye({type:"modal",close:Y.closeWorkflowEditor})},[Y,ye]),sr=a.useCallback(Ve=>{Y.openUsage(Ve),ye({type:"modal",close:Y.closeUsage})},[Y,ye]),W=a.useCallback(async(Ve,Bt)=>{await Y.runScript(Ve,Bt),ot({type:"modal",close:Y.closeTerminal})},[Y,ot]),Be=a.useCallback(()=>{Y.closeSettings(),Y.openModelOnboarding(),ot({type:"modal",close:Y.closeModelOnboarding})},[Y,ot]),Ye=a.useCallback(()=>{Y.setFileWorkspace("project"),Y.openFiles()},[Y]),Ct=a.useCallback(async()=>{Sn(!0);try{await u()}finally{Sn(!1)}},[u]),qn=a.useCallback(Ve=>{ps(Ve),bn(void 0),We("missions")},[We]),Jt=a.useCallback(Ve=>{Ve.type==="planning"?Y.openPlanningWithSession(Ve.id):Ve.type==="subtask"?Y.openSubtaskWithSession(Ve.id):Ve.type==="mission_interview"?(ps(void 0),bn(Ve.id),ht(void 0),We("missions")):(Ve.type==="milestone_interview"||Ve.type==="slice_interview")&&(bn(void 0),ps(void 0),ht(Ve.id),We("missions"))},[We,Y]),Zn=a.useCallback(()=>{},[]),ts=a.useCallback(()=>{},[]),[ni,ct]=a.useState(!1),[jt,nn]=a.useState(!1),[Gn,bs]=a.useState(null),Bs=L7(o,l,ni);a.useEffect(()=>{!r||d===0||nn(!0)},[r,d]),a.useEffect(()=>{let Ve=!1;return h7(c.host).then(Bt=>{Ve||bs(Bt)}),()=>{Ve=!0}},[c.host,o.activeProfileId,o.desktopMode,o.host,o.profiles]),a.useEffect(()=>{o.host==="desktop-shell"&&o.desktopMode==="local"&&(o.localServer?.status!=="ready"||!o.localServer.port||window.location.port!==String(o.localServer.port)&&(window.location.href=`http://localhost:${o.localServer.port}`))},[o]),a.useEffect(()=>{if(o.host!=="desktop-shell"||o.desktopMode!=="remote")return;const Ve=o.profiles.find(wn=>wn.id===o.activeProfileId);if(!Ve||typeof window>"u")return;const Bt=D7(Ve.serverUrl,Ve.authToken??null);window.location.href!==Bt&&(window.location.href=Bt)},[o]);const Ri=!!h&&ju(h??"")&&f.current,uo=!p&&!C&&m.length===0&&!g&&!!h&&!Ri,us=()=>{if(uo)return t.jsx(pH,{errorMessage:h??e("app.backendError.failedFetch","Failed to fetch projects"),isRetrying:Gt,onRetry:Ct,onManageConnection:r?()=>{r.openConnectionManager()}:void 0});if(G)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(y7,{addToast:s,onClose:Ti})})})});if(je==="overview")return t.jsx(Ys,{children:t.jsx(A6,{projects:m,loading:p,onSelectProject:ji,onAddProject:wr,onPauseProject:gl,onResumeProject:la,onRemoveProject:ba,nodes:b})});const Ve=Ce==="graph"?Ee:Fo(Ce)?Ce:null;return Ve?t.jsx(Ys,{children:t.jsx(PV,{taskView:Ve,context:{projectId:g?.id,tasks:x&&ie.tasks.length>0?ie.tasks:dt,workflowSteps:zi,subscribePluginEvents:T,openTaskDetail:(Bt,wn)=>Bi(Bt,wn),openFile:ja,renderTaskCard:Bt=>t.jsx(cc,{task:Bt,projectId:g?.id,onOpenDetail:wn=>Bi(wn),addToast:s,workflowStepNameLookup:Cr,disableDrag:!0,prAuthAvailable:Wt,autoMergeEnabled:ti}),addToast:s}})}):Ce==="skills"?!hn||!Je?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(w7,{addToast:s,projectId:g?.id,onClose:()=>We("board")})})}):Ce==="chat"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(k7,{addToast:s,projectId:g?.id,experimentalFeatures:In})})}):Ce==="mailbox"?t.jsx(Ys,{children:t.jsx(R3,{projectId:g?.id,addToast:s,onUnreadCountChange:On})}):Ce==="missions"?t.jsx(Ys,{children:t.jsx(j3,{isInline:!0,isOpen:!0,onClose:()=>{ps(void 0),bn(void 0),ht(void 0),We("board")},addToast:s,projectId:g?.id,onSelectTask:Bt=>{const wn=dt.find(Ns=>Ns.id===Bt);wn&&Bi(wn)},availableTasks:dt.map(Bt=>({id:Bt.id,title:Bt.title})),resumeSessionId:Un,targetMissionId:gn,milestoneSliceResumeSessionId:It,onMilestoneSliceResumeFetchError:()=>ht(void 0),onNavigateToGoal:Bt=>{ae(Bt),We("goalsView")}})}):Ce==="agents"&&fs?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(f7,{addToast:s,projectId:g?.id,onOpenTaskLogs:gi,agentOnboardingEnabled:os})})}):Ce==="documents"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(g7,{projectId:g?.id,addToast:s,onOpenDetail:Bi})})}):Ce==="stash-recovery"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(E7,{})})}):Ce==="pull-requests"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(M7,{pullRequestId:Se,projectId:g?.id})})}):Ce==="insights"?!hn||!gs?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(b7,{projectId:g?.id,addToast:s,onClose:()=>We("board"),onCreateTask:bl})})}):Ce==="research"?!hn||!En?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(v7,{projectId:g?.id,addToast:s,onOpenSettings:Bt=>Y.openSettings(Bt),readinessVersion:Vt})})}):Ce==="evals"?!hn||!yn?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(x7,{projectId:g?.id,onOpenSettings:Bt=>Y.openSettings(Bt),onOpenTaskDetail:Bt=>{pr(Bt,g?.id).then(wn=>Bi(wn)).catch(wn=>s(wn instanceof Error?wn.message:"Failed to open task detail","error"))}})})}):Ce==="memory"?!hn||!ks?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(j7,{addToast:s,projectId:g?.id})})}):Ce==="secrets"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(N7,{addToast:s})})}):Ce==="goalsView"?!hn||!ge?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(_7,{anchorGoalId:Ne})})}):Ce==="reliability"?t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(S7,{})})}):Ce==="devserver"||Ce==="dev-server"?!hn||!Te?null:t.jsx(Ys,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(C7,{addToast:s,projectId:g?.id})})}):Ce==="board"?t.jsxs(Ys,{children:[Qe&&!ss?t.jsx(DH,{signal:is,onDismiss:ei}):null,t.jsx(vD,{tasks:Xn,projectId:g?.id,maxConcurrent:Mi,onMoveTask:Nt,onPauseTask:Ft,onOpenDetail:Bi,onOpenGroupModal:Cs,addToast:s,onQuickCreate:Nr,onNewTask:Za,onPlanningMode:Ba,onSubtaskBreakdown:oo,autoMerge:ti,onToggleAutoMerge:rt,globalPaused:mi,onUpdateTask:Ae,onRetryTask:Ht,onArchiveTask:Ie,onUnarchiveTask:Pe,onDeleteTask:it,onArchiveAllDone:oe,onLoadArchivedTasks:re,searchQuery:L,availableModels:Vs,onOpenDetailWithTab:za,favoriteProviders:qs,favoriteModels:Ai,onToggleFavorite:va,onToggleModelFavorite:Xi,taskStuckTimeoutMs:Zt,staleHighFanoutBlockerAgeThresholdMs:Q,onOpenMission:qn,lastFetchTimeMs:Xe,prAuthAvailable:Wt,onOpenWorkflowEditor:tr,onCreateWorkflow:nr})]}):t.jsx(Ys,{children:t.jsx(x6,{tasks:x&&ie.tasks.length>0?ie.tasks:dt,projectId:g?.id,onMoveTask:Nt,onRetryTask:Ht,onDeleteTask:it,onPauseTask:Ft,onUnpauseTask:ze,onArchiveTask:Ie,onMergeTask:Mt,onResetTask:Me,onDuplicateTask:ee,onOpenDetail:(Bt,wn)=>Bi(Bt,void 0,wn),addToast:s,globalPaused:mi,onNewTask:Za,onQuickCreate:Nr,onPlanningMode:Ba,onSubtaskBreakdown:oo,availableModels:Vs,favoriteProviders:qs,favoriteModels:Ai,onToggleFavorite:va,onToggleModelFavorite:Xi,taskStuckTimeoutMs:Zt,searchQuery:L,lastFetchTimeMs:Xe,prAuthAvailable:Wt,onCreateWorkflow:nr})})},ms=!Y.modelOnboardingOpen&&I8(),Hn=!Y.modelOnboardingOpen&&!ms&&ol()&&!qN(),Ks=p||C||Fe;return t.jsx(R6,{value:{pushNav:ye,replaceCurrent:ot,removeNav:ue},children:t.jsx(G$,{openFile:ja,children:t.jsx(mI,{value:zt*T7,children:An?t.jsxs(t.Fragment,{children:[t.jsx(gH,{stage:Yt}),t.jsx(JN,{toasts:n,onRemove:i})]}):t.jsxs(t.Fragment,{children:[t.jsx(bH,{visible:Ks}),t.jsx(SP,{shellHost:c.host,onOpenSettings:ro,onOpenGitHubImport:ka,onOpenPlanning:_r,onResumePlanning:ya,activePlanningSessionCount:te.length,onOpenUsage:sr,onOpenActivityLog:co,onOpenSystemStats:Ar,onOpenMailbox:()=>Ze("mailbox"),mailboxUnreadCount:$n,mailboxPendingApprovalCount:xn,chatHasUnreadResponse:Rn,stashOrphanCount:zn,onOpenSchedules:er,onOpenGitManager:Mr,onOpenNodes:ao,showNodesButton:qt,onOpenWorkflowEditor:tr,onOpenScripts:Kn,onRunScript:W,onToggleTerminal:wa,onOpenFiles:Er,filesOpen:Y.filesOpen,onOpenTodos:lo,todosOpen:Y.todosOpen,todosEnabled:U,globalPaused:mi,enginePaused:zs,onToggleGlobalPause:Lt,onToggleEnginePause:Dt,view:Ce,onChangeView:je==="project"&&g?Ze:void 0,showSkillsTab:Je,showAgentsTab:fs,searchQuery:L,onSearchChange:O,branchFilter:J,baseBranchFilter:de,branchOptions:an,baseBranchOptions:Wn,onBranchFilterChange:P,onBaseBranchFilterChange:Z,projects:le,currentProject:g,onSelectProject:ji,onViewAllProjects:Oa,projectId:g?.id,mobileNavEnabled:X,availableNodes:b,currentNode:y,onSelectNode:Ve=>{Ve===null?w():k(Ve)},isRemote:x,experimentalFeatures:{insights:gs,memoryView:ks,devServer:Te,devServerView:Te,researchView:En,evalsView:yn,goalsView:ge},pluginDashboardViews:ke,shellConnectionControl:!X&&Gn?t.jsx(ck,{status:Gn,onError:Ve=>s(Ve,"error")}):void 0}),je==="project"&&g&&t.jsxs(t.Fragment,{children:[t.jsx(LH,{isActive:Qn}),t.jsx(OH,{onReLogin:Ve=>Y.openSettings("authentication")})]}),je==="project"&&g&&!G&&Ce!=="missions"&&!Y.isPlanningOpen&&!z&&t.jsx(TH,{sessions:se,onResumeSession:Jt,onDismissSession:Zn,onDismissAll:ts}),je==="project"&&g&&t.jsx(IH,{onOpenSettings:()=>Y.openSettings("general")}),je==="project"&&g&&ms&&t.jsx(ZH,{onResume:Y.openModelOnboarding}),je==="project"&&g&&Hn&&t.jsx(e9,{onOpenModelOnboarding:Y.openModelOnboarding,onOpenSettings:Ve=>Y.openSettings(Ve)}),je==="project"&&g&&_&&V&&N&&!$&&t.jsx(HH,{latestVersion:V,currentVersion:N,onDismiss:R}),je==="project"&&g&&t.jsx(JH,{projectId:g.id}),je==="project"&&g&&Cn?.taskIdIntegrity?.status==="anomaly"&&Cn.taskIdIntegrity.recommendedAction&&t.jsx(BH,{report:Cn.taskIdIntegrity,recommendedAction:Cn.taskIdIntegrity.recommendedAction,onRefresh:(Ve,Bt)=>{ve(wn=>wn?{...wn,status:Ve.status==="anomaly"||!wn.database.healthy||wn.database.corruptionDetected?"degraded":"ok",taskIdIntegrity:{...Ve,recommendedAction:Bt}}:null)}}),je==="project"&&g&&Cn?.database?.corruptionDetected===!0&&t.jsx(UH,{errors:Cn.database.corruptionErrors,lastCheckedAt:Cn.database.lastCheckedAt,onRefresh:Ls,refreshing:at,refreshError:tt}),je==="project"&&g&&!M&&D&&!St&&t.jsx(BN,{hasAiProvider:E,hasGithub:F,onDismiss:rs}),je==="project"&&g&&dn&&t.jsx(YH,{pendingCount:Math.max(xn,1),onOpenMailbox:()=>Ze("mailbox"),onDismiss:()=>{pn.current.set(dn.dedupeKey,Math.max(Date.now(),dn.updatedAtMs)),pk(pn.current),Tt(null)}}),je==="project"&&g&&Yn&&!un&&t.jsx(QH,{onDismiss:()=>{q9(),cn(!1)}}),t.jsx("div",{className:`project-content${je==="project"&&g&&(!X||!Kt)?" project-content--with-footer":""}${X&&!Kt?" project-content--with-mobile-nav":""}`,children:us()}),je==="project"&&g&&!G&&t.jsx(CH,{tasks:x&&ie.tasks.length>0?ie.tasks:dt,projectId:g.id,taskStuckTimeoutMs:Zt,staleHighFanoutBlockerAgeThresholdMs:Q,backgroundSessions:He,backgroundGenerating:qe,backgroundNeedsInput:pe,onOpenBackgroundSession:Jt,onDismissBackgroundSession:me,lastFetchTimeMs:Xe,currentProjectPath:g.path,onOpenProjectDirectory:Ye,keyboardOpen:mn,hideWhenKeyboardOpen:Kt}),t.jsx(s9,{view:Ce,onChangeView:je==="project"&&g?Ze:()=>{},footerVisible:je==="project"&&!!g,modalOpen:Y.anyModalOpen,keyboardOpen:fn,onOpenSettings:ro,onOpenActivityLog:co,onOpenSystemStats:Ar,onOpenMailbox:()=>Ze("mailbox"),onOpenNodes:ao,mailboxUnreadCount:$n,mailboxPendingApprovalCount:xn,chatHasUnreadResponse:Rn,stashOrphanCount:zn,onOpenGitManager:Mr,onOpenWorkflowEditor:tr,onOpenSchedules:er,onOpenScripts:Kn,onToggleTerminal:wa,onOpenFiles:Er,onOpenTodos:lo,todosOpen:Y.todosOpen,onOpenGitHubImport:ka,onOpenPlanning:_r,onResumePlanning:ya,activePlanningSessionCount:te.length,onOpenUsage:()=>sr(null),onViewAllProjects:Oa,onRunScript:W,projectId:g?.id,showSkillsTab:Je,experimentalFeatures:{insights:gs,memoryView:ks,devServer:Te,devServerView:Te,todoView:U,researchView:En,evalsView:yn,goalsView:ge,nodesView:qt},pluginDashboardViews:ke,shellConnectionControl:X&&Gn?t.jsx(ck,{status:Gn,onError:Ve=>s(Ve,"error")}):void 0}),je==="project"&&g&&Ce!=="chat"&&Ce!=="mailbox"&&Ce!=="insights"&&Ce!=="evals"&&Ce!=="devserver"&&Ce!=="dev-server"&&Ce!=="graph"&&!Fo(Ce)&&t.jsx(B9,{projectId:g.id,addToast:s,showFAB:xt,open:et,onOpenChange:Ut,favoriteProviders:qs,favoriteModels:Ai,onToggleFavorite:va,onToggleModelFavorite:Xi}),t.jsx(uH,{projectId:g?.id,tasks:dt,projects:m,currentProject:g,addToast:s,toasts:n,removeToast:i,modalManager:Y,projectActions:{handleAddProject:wr,handleSetupComplete:fl,handleModelOnboardingComplete:fi},taskHandlers:{handleModalCreate:Sr,handlePlanningTaskCreated:io,handlePlanningTasksCreated:vl,handleSubtaskTasksCreated:Qa,handleGitHubImport:$a},taskOperations:{moveTask:Nt,deleteTask:it,mergeTask:Mt,archiveTask:Ie,retryTask:Ht,resetTask:Me,duplicateTask:ee},deepLink:{handleDetailClose:jr},settings:{prAuthAvailable:Wt,themeMode:be,colorTheme:Le,dashboardFontScalePct:xe,setThemeMode:q,setColorTheme:ce,setDashboardFontScalePct:De},onSettingsClose:js,onReopenOnboarding:Be,onOpenApprovals:Ve=>Ze("mailbox")}),t.jsx(p7,{open:$t}),r&&t.jsxs(t.Fragment,{children:[t.jsx(o7,{open:Bs,shellApi:r,shellState:o,onComplete:()=>ct(!0)}),t.jsx(l7,{open:jt,shellApi:r,shellState:o,onClose:()=>nn(!1)})]})]})})})})}function $7(){return t.jsx(VS,{i18n:uu,children:t.jsx(D3,{children:t.jsx(i7,{children:t.jsx(w8,{children:t.jsx(VV,{children:t.jsx(EP,{children:t.jsx(O7,{})})})})})})})}function kS(e){e.postMessage({type:"SKIP_WAITING"})}function fk(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&kS(e)})}function z7(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,Ep("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&kS(s.waiting),s.installing&&fk(s.installing),s.addEventListener("updatefound",()=>{const i=s.installing;i&&fk(i)})}).catch(s=>{console.log("SW registration failed:",s)})}pE();__();vS();pS();pV.finally(()=>{zS.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(E_,{children:t.jsx(T_,{children:t.jsx($7,{})})})})),z7()});export{KA as $,Ci as A,Is as B,Es as C,Y_ as D,GW as E,Hr as F,Np as G,w1 as H,jh as I,ys as J,Ld as K,Et as L,xc as M,N1 as N,ia as O,hs as P,Ds as Q,xs as R,na as S,oa as T,as as U,$K as V,c8 as W,Fn as X,ah as Y,Ws as Z,q0 as _,Ln as a,vh as a$,ln as a0,a8 as a1,JA as a2,GA as a3,XU as a4,QU as a5,VW as a6,ki as a7,Gr as a8,Tn as a9,Ia as aA,Vo as aB,ha as aC,oC as aD,lK as aE,dK as aF,Gs as aG,fK as aH,pK as aI,hK as aJ,mK as aK,uK as aL,cK as aM,Uk as aN,Yo as aO,aK as aP,oK as aQ,rK as aR,vK as aS,gK as aT,bK as aU,xK as aV,ul as aW,_c as aX,cG as aY,OK as aZ,oc as a_,Bq as aa,Uq as ab,es as ac,YM as ad,jp as ae,bc as af,Zr as ag,Di as ah,Li as ai,ra as aj,Fh as ak,XG as al,nK as am,tK as an,Ka as ao,sK as ap,QG as aq,iK as ar,ZG as as,eK as at,Ms as au,$s as av,Qr as aw,Ql as ax,oi as ay,r_ as az,ls as b,wq as b$,W1 as b0,Ea as b1,ig as b2,ZC as b3,Hs as b4,C6 as b5,Si as b6,Tk as b7,L1 as b8,aG as b9,E9 as bA,kf as bB,b9 as bC,Mf as bD,j9 as bE,Xa as bF,tS as bG,S9 as bH,Qs as bI,Pa as bJ,mu as bK,tf as bL,i9 as bM,zr as bN,hi as bO,Nk as bP,Mk as bQ,x9 as bR,rg as bS,PR as bT,GG as bU,qG as bV,WG as bW,KG as bX,kq as bY,yq as bZ,xq as b_,rG as ba,oG as bb,lG as bc,Nu as bd,tV as be,Lh as bf,vw as bg,Kg as bh,vs as bi,wl as bj,ch as bk,$y as bl,GR as bm,kl as bn,sa as bo,r9 as bp,DR as bq,JG as br,YG as bs,VR as bt,o9 as bu,WR as bv,ju as bw,Ra as bx,ua as by,_9 as bz,mt as c,J7 as c$,Tq as c0,Rq as c1,Eq as c2,Sq as c3,Cq as c4,_q as c5,Nq as c6,jq as c7,vq as c8,Mq as c9,kG as cA,pG as cB,Hk as cC,Ek as cD,AW as cE,tw as cF,I as cG,rc as cH,vr as cI,ai as cJ,Wd as cK,cc as cL,fW as cM,aa as cN,iW as cO,nW as cP,sW as cQ,pa as cR,Aq as cS,Jo as cT,lT as cU,rE as cV,oE as cW,dG as cX,uG as cY,aq as cZ,Zs as c_,$5 as ca,lW as cb,oW as cc,pW as cd,rW as ce,cW as cf,dW as cg,uW as ch,mW as ci,wA as cj,hW as ck,$p as cl,xA as cm,yA as cn,kA as co,vA as cp,aW as cq,gu as cr,V1 as cs,Ko as ct,fG as cu,gG as cv,bG as cw,vG as cx,xG as cy,yG as cz,ZW as d,jy as d$,Y7 as d0,J_ as d1,Ja as d2,pg as d3,hV as d4,Ik as d5,uV as d6,GE as d7,KE as d8,X7 as d9,OG as dA,qq as dB,Zq as dC,Yq as dD,Wq as dE,Xq as dF,Gq as dG,Qq as dH,Kq as dI,Jq as dJ,Bp as dK,kK as dL,kW as dM,wW as dN,Jv as dO,Wr as dP,iq as dQ,tq as dR,La as dS,J9 as dT,N5 as dU,Pq as dV,eq as dW,Z7 as dX,mG as dY,gE as dZ,rq as d_,mq as da,lq as db,hq as dc,uq as dd,pq as de,fq as df,gq as dg,bq as dh,Q7 as di,nM as dj,aM as dk,eW as dl,sM as dm,tW as dn,ea as dp,u8 as dq,h8 as dr,p8 as ds,fr as dt,wy as du,rh as dv,g8 as dw,FG as dx,Vq as dy,Hq as dz,XW as e,mN as e$,eG as e0,oq as e1,cq as e2,bM as e3,Ro as e4,gM as e5,iG as e6,rM as e7,Ah as e8,oM as e9,NK as eA,ip as eB,bB as eC,Hp as eD,aS as eE,bW as eF,EW as eG,MW as eH,EK as eI,MK as eJ,CW as eK,NW as eL,SW as eM,nB as eN,AK as eO,TK as eP,RK as eQ,Zz as eR,_K as eS,Qd as eT,oN as eU,rN as eV,cN as eW,lN as eX,DK as eY,LK as eZ,_W as e_,cM as ea,lM as eb,dM as ec,uM as ed,Lq as ee,tG as ef,nG as eg,sG as eh,yr as ei,hG as ej,dq as ek,Od as el,xh as em,L5 as en,zK as eo,yK as ep,nq as eq,sq as er,Qz as es,Nf as et,jK as eu,wK as ev,uN as ew,Tu as ex,gW as ey,ui as ez,pr as f,RG as f$,ap as f0,CK as f1,FK as f2,vW as f3,yW as f4,SK as f5,jW as f6,xW as f7,oB as f8,Wo as f9,qr as fA,B0 as fB,MG as fC,WW as fD,rz as fE,mr as fF,HW as fG,BW as fH,JW as fI,KW as fJ,jk as fK,OW as fL,FW as fM,TW as fN,RW as fO,YU as fP,Ir as fQ,qW as fR,DW as fS,IW as fT,XM as fU,LW as fV,$W as fW,AG as fX,NR as fY,PW as fZ,TG as f_,LC as fa,X1 as fb,h1 as fc,Fd as fd,UC as fe,GC as ff,bC as fg,vB as fh,hN as fi,jB as fj,lc as fk,IK as fl,PK as fm,wG as fn,NG as fo,_G as fp,SG as fq,jG as fr,CG as fs,EG as ft,Ph as fu,jg as fv,zW as fw,UW as fx,ER as fy,t0 as fz,QW as g,$G as g0,Nh as g1,UG as g2,HG as g3,BG as g4,DG as g5,IG as g6,LG as g7,PG as g8,zG as g9,Fq as ga,Iq as gb,Dq as gc,$q as gd,zq as ge,Oq as gf,eN as h,fa as i,br as j,ru as k,VG as l,wi as m,WA as n,YW as o,Ji as p,iS as q,ZU as r,li as s,cs as t,ga as u,Yi as v,_s as w,yu as x,Bc as y,Re as z};
|