@runfusion/fusion 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +809 -533
- package/dist/client/assets/{AgentDetailView-C3Xcrxnp.js → AgentDetailView-CLzxf6Z7.js} +1 -1
- package/dist/client/assets/{AgentsView-EjE4y4rM.js → AgentsView-CXaYJX_G.js} +3 -3
- package/dist/client/assets/{ChatView-DQLvKCYj.js → ChatView-iXxGAaN1.js} +1 -1
- package/dist/client/assets/{DevServerView-CX7paFRQ.js → DevServerView-BeXfFkF4.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-_cBPx6Nx.js → DirectoryPicker-BMn5fjn9.js} +1 -1
- package/dist/client/assets/{DocumentsView-Wz33aYqp.js → DocumentsView-CjrtI3TX.js} +1 -1
- package/dist/client/assets/{InsightsView-C7YPnS92.js → InsightsView-BkfQ-TV1.js} +1 -1
- package/dist/client/assets/{MemoryView-DKQtFzFQ.js → MemoryView-1G0zWu1i.js} +1 -1
- package/dist/client/assets/{NodesView-CI4rUQC4.js → NodesView-Bn_1R73N.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-BFmdKgHZ.js → PiExtensionsManager-CqGOtQnR.js} +1 -1
- package/dist/client/assets/{PluginManager-BGQU1IIw.js → PluginManager-CM5QGvSG.js} +1 -1
- package/dist/client/assets/{RoadmapsView-Cts3hoIS.js → RoadmapsView-B4VnQP83.js} +1 -1
- package/dist/client/assets/{SettingsModal-DvRd0ZOE.js → SettingsModal-BiLA-BeG.js} +4 -4
- package/dist/client/assets/{SettingsModal-DXvBGZHf.js → SettingsModal-C3LckzfT.js} +1 -1
- package/dist/client/assets/SetupWizardModal-Bk_8HfLm.js +1 -0
- package/dist/client/assets/{SkillsView-BXvrHzEZ.js → SkillsView-CRvqF8P1.js} +1 -1
- package/dist/client/assets/{TodoView-NZHkv9YQ.js → TodoView-Vzui5Eha.js} +1 -1
- package/dist/client/assets/{folder-open-Kh0ScTc5.js → folder-open-CMF89prE.js} +1 -1
- package/dist/client/assets/{index-D1gavMG-.js → index-B8kH5y4Q.js} +3 -3
- package/dist/client/assets/{index-CWz44REw.css → index-D2fXOwWF.css} +1 -1
- package/dist/client/assets/{list-checks-CvoT0bwU.js → list-checks-M95d1uAy.js} +1 -1
- package/dist/client/assets/{star-BdfwSLBU.js → star-DHhJD6ow.js} +1 -1
- package/dist/client/assets/{upload-Bx8Yk_7Q.js → upload-CEq8jic8.js} +1 -1
- package/dist/client/assets/{users-DgVaFEsz.js → users-CUA8Tv-d.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +187 -41
- package/dist/pi-claude-cli/package.json +4 -1
- package/dist/pi-claude-cli/src/process-manager.ts +1 -1
- package/package.json +1 -1
- package/dist/client/assets/SetupWizardModal-Y2ewEE8Y.js +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-xterm-DzcZoU0P.js","assets/vendor-react-K0fH_qHe.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/vendor-xterm-DzcZoU0P.js","assets/vendor-react-K0fH_qHe.js","assets/vendor-xterm-LZoznX6r.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/SetupWizardModal-Bk_8HfLm.js","assets/DirectoryPicker-BMn5fjn9.js","assets/folder-open-CMF89prE.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-DRF5fOoR.css","assets/SettingsModal-BiLA-BeG.js","assets/SettingsModal-C3LckzfT.js","assets/SettingsModal-D5hLoLXp.css","assets/users-CUA8Tv-d.js","assets/star-DHhJD6ow.js","assets/SettingsModal-YjpwLH2V.css","assets/AgentsView-CXaYJX_G.js","assets/upload-CEq8jic8.js","assets/AgentsView-C2f7esMv.css","assets/DocumentsView-CjrtI3TX.js","assets/DocumentsView-BrhyOdeE.css","assets/InsightsView-BkfQ-TV1.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-Bn_1R73N.js","assets/NodesView-DCoS6iYh.css","assets/ChatView-iXxGAaN1.js","assets/RoadmapsView-B4VnQP83.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-CRvqF8P1.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-1G0zWu1i.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-BeXfFkF4.js","assets/DevServerView-DlZpuAnj.css","assets/TodoView-Vzui5Eha.js","assets/list-checks-M95d1uAy.js","assets/TodoView-C1g65hJo.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{r as a,j as t,R as lo,a as Xa,g as $h,c as hg}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))i(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&i(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function i(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
|
|
3
3
|
* @license lucide-react v1.7.0 - ISC
|
|
4
4
|
*
|
|
@@ -609,7 +609,7 @@ import{r as a,j as t,R as lo,a as Xa,g as $h,c as hg}from"./vendor-react-K0fH_qH
|
|
|
609
609
|
*
|
|
610
610
|
* This source code is licensed under the ISC license.
|
|
611
611
|
* See the LICENSE file in the root directory of this source tree.
|
|
612
|
-
*/const ev=[["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"}]],Pn=Ue("zap",ev),yc="fusion:version-reload",kc="fusion:version-update";function tv(){try{if(sessionStorage.getItem(kc))return sessionStorage.removeItem(kc),!0}catch{}return!1}function Yh(e){if(sessionStorage.getItem(yc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(yc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function nv(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError/i.test(n)}function sv(e){return nv(e)?(Yh(`chunk load error: ${e?.message??e}`),!0):!1}async function iv(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}let al=!1;async function rl(){if(!(al||document.visibilityState!=="visible")){al=!0;try{const e=await iv();if(e&&e!=="mojfmkla-bfbaa5e5"){try{sessionStorage.setItem(kc,"1")}catch{}Yh(`build version changed: mojfmkla-bfbaa5e5 -> ${e}`)}}finally{al=!1}}}function av(){window.setTimeout(()=>sessionStorage.removeItem(yc),5e3),document.addEventListener("visibilitychange",()=>{rl()}),window.addEventListener("focus",()=>{rl()}),window.setTimeout(()=>void rl(),2e3)}class Do 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),!sv(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(Yc,{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 Jn({children:e,onError:n}){return t.jsx(Do,{level:"page",onError:n,children:e})}function Ti({children:e,onError:n}){return t.jsx(Do,{level:"modal",onError:n,children:e})}function rv({children:e,onError:n}){return t.jsx(Do,{level:"root",onError:n,children:e})}const ov="modulepreload",lv=function(e){return"/"+e},Ad={},nn=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");r=l(s.map(d=>{if(d=lv(d),d in Ad)return;Ad[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":ov,m||(g.as="script"),g.crossOrigin="",g.href=d,u&&g.setAttribute("nonce",u),document.head.appendChild(g),m)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},Qc="fn.authToken",Rd="token",cv="fn_token";let la,Td=!1,po=!1;const jc="fn:auth-token-recovery-required";function dv(){try{const e=window.localStorage.getItem(Qc);return e&&e.length>0?e:void 0}catch{return}}function Qh(e){try{window.localStorage.setItem(Qc,e)}catch{}}function uv(){if(!(Td||typeof window>"u")){Td=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Rd);if(!n)return;Qh(n),e.searchParams.delete(Rd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ha(){if(la!==void 0)return la;const e=uv();if(e)return la=e,e;const n=dv();if(n)return la=n,n}function mv(e){la=e,po=!1,Qh(e)}function hv(){la=void 0,po=!1;try{window.localStorage.removeItem(Qc)}catch{}}function Pd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function pv(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function fv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!pv(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Pd(e.protocol)===Pd(n.protocol);return s&&i&&r}function gv(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 Qs(e){const n=ha();if(!n||typeof window>"u")return e;const s=gv(e);return!s||!fv(s.parsed)?e:(s.parsed.searchParams.set(cv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ki(e){const n=ha();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function xv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function bv(){typeof window>"u"||po||(po=!0,window.dispatchEvent(new CustomEvent(jc)))}async function vv(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();xv(i)&&bv()}catch{}}function yv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ha();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=ha(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const u=new URL(o,window.location.origin);return u.origin!==window.location.origin?!1:u.pathname.startsWith("/api/")||u.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,i);const c=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...i,headers:c}).then(u=>(vv(u),u))}}class kv extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function jv(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Zn(e){return`/api${e}`}async function L(e,n={}){const s=Zn(e),i=ha(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),ki(g)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||jv(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!u){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new kv(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function UP(){return L("/health")}function BP(){return L("/updates/check")}function wv(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return L(`/tasks${l}`)}async function fo(e,n){const i=Zn(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")}function Xh(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:k}=e;return L(K("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:k})})}function Ks(e,n,s){return L(K(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Nv(e,n,s,i,r,o,l,c,u){return L(K("/tasks/batch-update-models",u),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Sv(e,n,s){return L(K(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Cv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return L(K(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Ev(e,n){return L(K(`/tasks/${e}/merge`,n),{method:"POST"})}function _v(e,n){return L(K(`/tasks/${e}/retry`,n),{method:"POST"})}function Mv(e,n){return L(K(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Zh(e,n){return L(K(`/tasks/${e}/pause`,n),{method:"POST"})}function Av(e,n){return L(K(`/tasks/${e}/unpause`,n),{method:"POST"})}function Rv(e,n){return L(K(`/tasks/${e}/archive`,n),{method:"POST"})}function Tv(e,n){return L(K(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Pv(e){return L(K("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Iv(e,n){return L(K(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function $v(e,n){return L(K(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Dv(e){return L(K("/config",e))}function Lo(e){return L(K("/settings",e))}function zr(e,n){return L(K("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Lv(e){return L(K("/update-check",e))}function HP(e){return L(K("/remote/settings",e))}function qP(e,n){return L(K("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function VP(e){return L(K("/remote/status",e))}function WP(e){return L(K("/remote/tunnel/start",e),{method:"POST"})}function KP(e){return L(K("/remote/tunnel/stop",e),{method:"POST"})}function GP(e){return L(K("/remote/token/persistent/regenerate",e),{method:"POST"})}function JP(e,n){return L(K("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function ep(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 YP(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=ep(null,s,i);return L(K(`/remote/url${r}`,n))}function QP(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=ep(e,i,r);return L(K(`/remote/qr${o}`,s))}function XP(e){return L(K("/memory",e))}function ZP(e,n){return L(K("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function eI(e){return L(K("/memory/files",e))}function tI(e,n){const s=`path=${encodeURIComponent(e)}`;return L(K(`/memory/file?${s}`,n))}function nI(e,n,s){return L(K("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function sI(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 L(K("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function iI(e){return L(K("/memory/dream",e),{method:"POST"})}function aI(e){return L(K("/memory/insights",e))}function rI(e,n){return L(K("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function oI(e){return L(K("/memory/extract",e),{method:"POST"})}function lI(e){return L(K("/memory/audit",e))}function cI(e){return L(K("/memory/stats",e))}function dI(e){return L(K("/memory/backend",e))}function uI(e){return L(K("/memory/install-qmd",e),{method:"POST"})}function mI(e,n){return L(K("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Vi(){return L("/settings/global")}function sn(e){return L("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function hI(e){return L(K("/settings/scopes",e))}function pI(e){return L(K("/settings/pi-extensions",e))}function fI(e,n){return L(K("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function gI(e,n,s){return L(K("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function xI(){return L("/pi-settings")}async function bI(e){return L("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function vI(e){return L("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function yI(e){return L(K("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function ur(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Zn(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 zv(e,n,s){return L(K(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Id(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(Zn(o),{headers:ki()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),u=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,d=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:u,hasMore:d}}function Fv(e,n,s,i){return L(K(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Ov(e,n,s){return L(K(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Uv(e,n){return L(K(`/tasks/${e}/documents`,n))}function Bv(e,n,s){return L(K(`/tasks/${e}/documents/${n}/revisions`,s))}async function kI(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 L(K(r,n))}function jI(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return L(K(r,e))}function $d(e,n,s,i,r){return L(K(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Hv(e,n,s){return L(K(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function qv(e,n,s){return L(K(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Vv(e,n,s){return L(K(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Wv(e,n){return L(K(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Kv(e,n,s){return L(K(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function cs(){return L("/models")}function Gv(){return L("/usage")}function Jv(){return L("/providers/claude-cli/status")}async function wI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/hermes/status${n}`)}async function NI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await L(`/providers/hermes/profiles${n}`)).profiles??[]}async function SI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/openclaw/status${n}`)}async function CI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),L(`/providers/paperclip/status?${n.toString()}`)}async function EI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await L(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function _I(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await L(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function MI(e){return L("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function AI(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return L(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function RI(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 L(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function TI(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await L(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function PI(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return L(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Yv(e){return L("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function mr(){return L("/auth/status")}function Qv(e){return L("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function Xv(e){return L("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Zv(e,n){return L("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function ey(e){return L("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function ty(e,n,s,i){return L("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function ny(e,n,s,i){return L(K("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function sy(e,n,s){return L("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function iy(e,n,s,i){return L(K("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function ay(e){return L(K("/git/remotes",e))}function ry(e){return L(K("/git/remotes/detailed",e))}function oy(e,n,s){return L(K("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function ly(e,n){return L(K(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cy(e,n,s){return L(K(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function dy(e,n,s){return L(K(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function uy(e,n,s){return L(K(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function my(e,n){return L(K(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function hy(e,n){return(await L(K("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Fr(e,n,s,i){return L(K("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Dd(e,n){return L(K(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function py(e){return L(K("/terminal/sessions",e))}function Ps(e){return L(K("/git/status",e))}function fy(e,n){const s=e?`?limit=${e}`:"";return L(K(`/git/commits${s}`,n))}function go(e,n){return L(K(`/git/commits/${e}/diff`,n))}function gy(e){return L(K("/git/commits/ahead",e))}function xy(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return L(K(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Pa(e){return L(K("/git/branches",e))}function by(e,n,s){const i=`?limit=${n}`;return L(K(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function vy(e){return L(K("/git/worktrees",e))}function yy(e,n,s){return L(K("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function ky(e,n){return L(K(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Ld(e,n,s){const i=n?"?force=true":"";return L(K(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function jy(e,n){return L(K("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function wy(e){return L(K("/git/pull",e),{method:"POST"})}function Ny(e){return L(K("/git/push",e),{method:"POST"})}function Or(e){return L(K("/git/stashes",e))}function Sy(e,n){return L(K("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Cy(e,n,s){return L(K(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Ey(e,n){return L(K(`/git/stashes/${e}`,n),{method:"DELETE"})}function _y(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),L(K(`/git/diff/file?${i.toString()}`,s))}function Xi(e){return L(K("/git/changes",e))}function zd(e,n){return L(K("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function My(e,n){return L(K("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Fd(e,n){return L(K("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Ay(e,n){return L(K("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Ry(e){return L(K("/workspaces",e))}function Ty(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),L(`/files?${i.toString()}`)}function Py(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Iy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function $y(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),L(`/files/search?${i.toString()}`)}function Dy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Ly(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function zy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Fy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function tp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Oy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Uy(e,n,s){return L(K("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function By(e,n,s,i){return L(K("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Hy(e,n,s){return L(K(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function qy(e,n,s){return L(K(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function np(e,n,s){return L(K("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Vy(e,n,s){return L(K("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Wy(e,n,s){return L(K("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ky(e,n,s){return L(K("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const wc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(wc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Gy(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function kr(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const f=p.lastEventId;if(!f)return!0;const x=Number.parseInt(f,10);return Number.isFinite(x)?u!==null&&x<=u?!1:(u=x,!0):!0},h=()=>{if(o)return;const p=Gy(e,u),f=new EventSource(Qs(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))f.addEventListener(x,b=>{const y=b;m(y)&&v(y)});f.onerror=()=>{if(o||r!==f)return;if(f.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const g={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),wc.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return wc.add(g),g}function Od(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${i} (${l})`}}function pa(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 Jy(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 Yy(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Jy(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Qy(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,i=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((d,m)=>({id:m+1,text:d,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(d=>d.id>r).slice(0,s),totalLines:o};const c=Math.max(o-i,0),u=Math.max(c-s,0);return{lines:l.slice(u,c),totalLines:o}}function Ud(e){return Array.isArray(e)?e.map(Od):(e.candidates??[]).map(Od)}async function Xy(e){try{const n=await L(K("/dev-server/candidates",e));return Ud(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await L(K("/dev-server/detect",e));return Ud(s)}throw n}}function Xc(e){return L(K("/dev-server/status",e)).then(pa)}async function II(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 L(K(`/dev-server/logs/history${i}`,n));return Yy(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Xc(n);return Qy(o.logs,e)}throw r}}function Zy(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return L(K("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(pa)}function ek(e){return L(K("/dev-server/stop",e),{method:"POST"}).then(pa)}function tk(e){return L(K("/dev-server/restart",e),{method:"POST"}).then(pa)}async function nk(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await L(K("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return pa(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await L(K("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return pa(r)}throw i}}function $I(e){return Zn(K("/dev-server/logs/stream",e))}async function DI(e){try{return(await L(K("/devserver",e))).sessions??[]}catch{try{const n=await Xc(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 LI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Xc(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 zI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Zy({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 FI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await ek(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 OI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await tk(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 UI(e,n,s){try{const i=await L(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 nk({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function BI(e){try{return(await L(K("/devserver/detect",e))).candidates??[]}catch{try{return(await Xy(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function HI(e,n){return Zn(K(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function jr(e,n,s=25e3){const i=setInterval(()=>{Dj(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function sk(e,n){return Zn(K(`/planning/${encodeURIComponent(e)}/stream`,n))}function ik(e,n,s,i){const r=sk(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function wr(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 ak(e){return L(wr("/routines",e))}function rk(e,n){return L(wr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Bd(e,n,s){return L(wr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function ok(e,n){await L(wr(`/routines/${e}`,n),{method:"DELETE"})}function lk(e,n){return L(wr(`/routines/${e}/trigger`,n),{method:"POST"})}function Hd(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 L(`/activity${s}`)}function ck(e){const n=K("/activity",e);return L(n,{method:"DELETE"})}function zo(e){return L(K("/workflow-steps",e))}function qd(e,n){return L(K("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function dk(e,n,s){return L(K(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function uk(e,n){return L(K(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Vd(e,n){return L(K(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function mk(e,n){return L(K(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function hk(){return L("/workflow-step-templates")}function pk(e,n){return L(K(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function hr(e){return L(K("/scripts",e))}function fk(e,n,s){return L(K("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function gk(e,n){return L(K(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function sp(e,n,s){return(await L(K("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Ur={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 ip(e){if(!(e instanceof Error))return Ur.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Ur.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Ur.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Ur.NETWORK}function xk(e,n){return L(K("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function bk(e,n,s){return L(K(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function vk(e,n){return Zn(K(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function yk(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=kr(vk(e,n),{onOpen:()=>{l(),r=jr(e,n)},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},subtasks:u=>{try{s.onSubtasks?.(JSON.parse(u.data))}catch(d){console.error("[subtasks] Failed to parse subtasks event:",d)}},error:u=>{try{const d=JSON.parse(u.data),m=typeof d=="string"&&d.length>0?d:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{l(),s.onError?.(u)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function kk(e,n,s,i){return L(K("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function ap(e,n,s){return L(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 jk(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 Fo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=jk(e,s,i);return L(o,r)}function Na(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return L(`/agents${i}`)}function rp(e,n){return L(K(`/agents/${encodeURIComponent(e)}`,n))}function wk(e,n){return L(K("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Nk(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function qI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function VI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function WI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function KI(e,n){return L(K(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function GI(e,n,s){const i=`path=${encodeURIComponent(n)}`;return L(K(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function JI(e,n,s,i){return L(K(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Sk(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Ck(e,n){return L(K(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function YI(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 L(`/agents/${encodeURIComponent(e)}/runs${r}`)}function QI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function XI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function ZI(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return L(K(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function e$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Ek(e){return L(K("/agents/stats",e))}function t$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function n$(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return L(`/agents/org-tree${i?`?${i}`:""}`)}function s$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Wd(e,n,s){return L(K(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function i$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/tasks`,n))}function a$(){return L("/agents/companies")}function r$(e,n){return L(K("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function o$(e,n){return L(K("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function l$(e,n){return L(K(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function c$(e){return L(K("/backups",e))}function d$(e){return L(K("/backups",e),{method:"POST"})}function u$(e,n){const s=K("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return L(i)}function m$(e,n,s){return L(K("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function Kd(){return L("/projects/across-nodes")}function ir(e,n){L("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function xo(){return L("/nodes")}function _k(e){return L("/nodes",{method:"POST",body:JSON.stringify(e)})}function Mk(e,n){return L(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Ak(e){return L(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Rk(e){const n=await L(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function h$(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=ha();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return L(u)}function Tk(e){return L("/projects",{method:"POST",body:JSON.stringify(e)})}function op(e){return L(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function Gd(e){return L(`/projects/${encodeURIComponent(e)}/health`)}function Pk(e){return L(K("/executor/stats",e))}function Ik(e){return L(K("/system-stats",e))}function $k(e){return L(K("/kill-vitest",e),{method:"POST"})}function Jd(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 L(`/activity-feed${s}`)}function Dk(e){return L(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Lk(e){return L(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function p$(){return L("/global-concurrency")}function f$(e){return L("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function zk(e,n){return L(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function lp(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 L(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Fk(e){return L(K("/missions",e))}function Ok(e,n){return L(K("/missions",n),{method:"POST",body:JSON.stringify(e)})}function cp(e,n){return L(K(`/missions/${encodeURIComponent(e)}`,n))}function Uk(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Bk(e,n){return L(K(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hk(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 L(K(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function qk(e){return L(K("/missions/health",e))}function Vk(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Wk(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Kk(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gk(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Jk(e,n,s){return L(K(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Yk(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Qk(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Xk(e,n,s){return L(K(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Zk(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ej(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function tj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function nj(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function sj(e,n,s,i){return L(K(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function ij(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function ol(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function aj(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function rj(e,n,s){return L(K(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function oj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function lj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function cj(e,n){return L(K(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function ll(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function Yd(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function dj(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Qd(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function uj(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 L(K(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function mj(e,n){return L(K(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function hj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function pj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function fj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function gj(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function xj(e,n,s){return L(K("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function bj(e,n,s,i){return L(K("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function vj(e,n,s){return L(K(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dp(e,n,s){return L(K("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function yj(e,n,s){return L(K("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function kj(e,n,s,i){const r=Zn(K(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Nr(e,n,s){return K(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Sr(e,n,s){return K(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function jj(e,n){return L(Nr(e,"/start",n),{method:"POST"})}function wj(e,n,s,i){return L(Nr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Nj(e,n,s,i){const r=Zn(Nr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Sj(e,n,s){return L(Nr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Cj(e,n){return L(Nr(e,"/skip",n),{method:"POST"})}function Ej(e,n){return L(Sr(e,"/start",n),{method:"POST"})}function _j(e,n,s,i){return L(Sr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Mj(e,n,s,i){const r=Zn(Sr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Aj(e,n,s){return L(Sr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Rj(e,n){return L(Sr(e,"/skip",n),{method:"POST"})}async function Tj(e,n){try{return await L(K(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function g$(e){return L(K("/roadmaps",e))}function x$(e,n){return L(K("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function b$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}`,n))}function v$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function y$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function k$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function j$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function w$(e,n){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function N$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function S$(e,n,s){return L(K(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function C$(e,n){return L(K(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function E$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function _$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function M$(e,n,s,i){return L(K(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function A$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function R$(e,n,s,i){return L(K(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function T$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function P$(e){return L(K("/todos",e))}function I$(e,n){const s={title:e};return L(K("/todos",n),{method:"POST",body:JSON.stringify(s)})}function $$(e,n,s){const i={title:n};return L(K(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function D$(e,n){return L(K(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function L$(e,n,s){const i={text:n};return L(K(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function z$(e,n,s){const i=n;return L(K(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function F$(e,n){return L(K(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function O$(e,n,s){return L(K(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function fa(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Zc(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(Zn(`/ai-sessions${n}`),{headers:ki()});return s.ok?(await s.json()).sessions??[]:[]}async function oi(e){const n=await fetch(Zn(`/ai-sessions/${encodeURIComponent(e)}`),{headers:ki()});return n.ok?n.json():null}async function Pj(e,n){const s=await L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Ij(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function $j(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function up(e){await fetch(Zn(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:ki()})}function Dj(e,n){return L(K(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Lj(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 L(`/messages/inbox${i}`)}function zj(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 L(`/messages/outbox${i}`)}function mp(e){return L(K("/messages/unread-count",e))}function Fj(e,n){return L(K("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Oj(e,n){return L(K(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Uj(e){return L(K("/messages/read-all",e),{method:"POST"})}function Bj(e,n){return L(K(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hj(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return L(K(i,s))}function qj(e,n){return L(K(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function U$(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 L(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function B$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function H$(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/performance${r}`)}function q$(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 L(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function V$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function W$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function K$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function G$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/budget`,n))}function J$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function Y$(e){return L(K("/plugins",e))}async function Q$(e,n){return L(K("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function X$(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function Z$(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function eD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function tD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function nD(e,n,s){return L(K(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function sD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Vj(e){return L(K("/plugins/ui-slots",e))}async function iD(e){return L(K("/plugins/runtimes",e))}async function aD(e){return(await L(K("/skills/discovered",e))).skills}async function rD(e,n,s){return L(K("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function oD(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 L(K(`/skills/catalog${r}`,s))}async function lD(e,n){return(await L(K(`/skills/${encodeURIComponent(e)}/content`,n))).content}function cD(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return L(`/chat/sessions${i?`?${i}`:""}`)}async function Wj(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 L(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Kj(e,n){return L(K("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function dD(e,n,s){return L(K(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function uD(e,n){return L(K(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Xd(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return L(K(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Gj(e,n){return L(K(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Jj(e,n,s,i,r){const o=Zn(K(`/chat/sessions/${encodeURIComponent(e)}/messages`,i)),l=new AbortController;let c=!1;const u=(d,m)=>{if(!(!d||!m))switch(d){case"thinking":try{s.onThinking?.(JSON.parse(m))}catch{s.onThinking?.(m)}break;case"text":try{s.onText?.(JSON.parse(m))}catch{s.onText?.(m)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(m))}catch{}break;case"done":try{s.onDone?.(JSON.parse(m))}catch{s.onDone?.({messageId:""})}break;case"error":try{const h=JSON.parse(m);s.onError?.(h.message||h)}catch{s.onError?.(m||"Stream error")}break}};return(async()=>{try{const d=await fetch(o,{method:"POST",headers:ki({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:l.signal});if(!d.ok){const v=await d.text();let b=`Request failed: ${d.status}`;try{b=JSON.parse(v).error||b}catch{}s.onError?.(b);return}if(!d.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const m=d.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const x=(v,b=!1)=>{g+=v;const y=g.split(`
|
|
612
|
+
*/const ev=[["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"}]],Pn=Ue("zap",ev),yc="fusion:version-reload",kc="fusion:version-update";function tv(){try{if(sessionStorage.getItem(kc))return sessionStorage.removeItem(kc),!0}catch{}return!1}function Yh(e){if(sessionStorage.getItem(yc)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem(yc,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function nv(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError/i.test(n)}function sv(e){return nv(e)?(Yh(`chunk load error: ${e?.message??e}`),!0):!1}async function iv(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}let al=!1;async function rl(){if(!(al||document.visibilityState!=="visible")){al=!0;try{const e=await iv();if(e&&e!=="mojjkega-50ad5fc1"){try{sessionStorage.setItem(kc,"1")}catch{}Yh(`build version changed: mojjkega-50ad5fc1 -> ${e}`)}}finally{al=!1}}}function av(){window.setTimeout(()=>sessionStorage.removeItem(yc),5e3),document.addEventListener("visibilitychange",()=>{rl()}),window.addEventListener("focus",()=>{rl()}),window.setTimeout(()=>void rl(),2e3)}class Do 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),!sv(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(Yc,{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 Jn({children:e,onError:n}){return t.jsx(Do,{level:"page",onError:n,children:e})}function Ti({children:e,onError:n}){return t.jsx(Do,{level:"modal",onError:n,children:e})}function rv({children:e,onError:n}){return t.jsx(Do,{level:"root",onError:n,children:e})}const ov="modulepreload",lv=function(e){return"/"+e},Ad={},nn=function(n,s,i){let r=Promise.resolve();if(s&&s.length>0){let l=function(d){return Promise.all(d.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),u=c?.nonce||c?.getAttribute("nonce");r=l(s.map(d=>{if(d=lv(d),d in Ad)return;Ad[d]=!0;const m=d.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${d}"]${h}`))return;const g=document.createElement("link");if(g.rel=m?"stylesheet":ov,m||(g.as="script"),g.crossOrigin="",g.href=d,u&&g.setAttribute("nonce",u),document.head.appendChild(g),m)return new Promise((p,f)=>{g.addEventListener("load",p),g.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${d}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},Qc="fn.authToken",Rd="token",cv="fn_token";let la,Td=!1,po=!1;const jc="fn:auth-token-recovery-required";function dv(){try{const e=window.localStorage.getItem(Qc);return e&&e.length>0?e:void 0}catch{return}}function Qh(e){try{window.localStorage.setItem(Qc,e)}catch{}}function uv(){if(!(Td||typeof window>"u")){Td=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Rd);if(!n)return;Qh(n),e.searchParams.delete(Rd);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function ha(){if(la!==void 0)return la;const e=uv();if(e)return la=e,e;const n=dv();if(n)return la=n,n}function mv(e){la=e,po=!1,Qh(e)}function hv(){la=void 0,po=!1;try{window.localStorage.removeItem(Qc)}catch{}}function Pd(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function pv(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function fv(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!pv(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=Pd(e.protocol)===Pd(n.protocol);return s&&i&&r}function gv(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 Qs(e){const n=ha();if(!n||typeof window>"u")return e;const s=gv(e);return!s||!fv(s.parsed)?e:(s.parsed.searchParams.set(cv,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function ki(e){const n=ha();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function xv(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function bv(){typeof window>"u"||po||(po=!0,window.dispatchEvent(new CustomEvent(jc)))}async function vv(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const i=await n.json();xv(i)&&bv()}catch{}}function yv(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,ha();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=ha(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const u=new URL(o,window.location.origin);return u.origin!==window.location.origin?!1:u.pathname.startsWith("/api/")||u.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,i);const c=new Headers(i?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...i,headers:c}).then(u=>(vv(u),u))}}class kv extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function jv(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Zn(e){return`/api${e}`}async function L(e,n={}){const s=Zn(e),i=ha(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),ki(g)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),u=l.includes("application/json");if(l.includes("text/html")||jv(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!u){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new kv(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function UP(){return L("/health")}function BP(){return L("/updates/check")}function wv(e,n,s,i,r){const o=new URLSearchParams;s&&o.set("projectId",s),i&&o.set("q",i),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return L(`/tasks${l}`)}async function fo(e,n){const i=Zn(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")}function Xh(e,n){const{title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:k}=e;return L(K("/tasks",n),{method:"POST",body:JSON.stringify({title:s,description:i,column:r,dependencies:o,breakIntoSubtasks:l,enabledWorkflowSteps:c,assignedAgentId:u,modelPresetId:d,modelProvider:m,modelId:h,validatorModelProvider:g,validatorModelId:p,planningModelProvider:f,planningModelId:x,thinkingLevel:v,summarize:b,reviewLevel:y,executionMode:S,priority:k})})}function Ks(e,n,s){return L(K(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Nv(e,n,s,i,r,o,l,c,u){return L(K("/tasks/batch-update-models",u),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function Sv(e,n,s){return L(K(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function Cv(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return L(K(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Ev(e,n){return L(K(`/tasks/${e}/merge`,n),{method:"POST"})}function _v(e,n){return L(K(`/tasks/${e}/retry`,n),{method:"POST"})}function Mv(e,n){return L(K(`/tasks/${e}/duplicate`,n),{method:"POST"})}function Zh(e,n){return L(K(`/tasks/${e}/pause`,n),{method:"POST"})}function Av(e,n){return L(K(`/tasks/${e}/unpause`,n),{method:"POST"})}function Rv(e,n){return L(K(`/tasks/${e}/archive`,n),{method:"POST"})}function Tv(e,n){return L(K(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Pv(e){return L(K("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Iv(e,n){return L(K(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function $v(e,n){return L(K(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Dv(e){return L(K("/config",e))}function Lo(e){return L(K("/settings",e))}function zr(e,n){return L(K("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Lv(e){return L(K("/update-check",e))}function HP(e){return L(K("/remote/settings",e))}function qP(e,n){return L(K("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function VP(e){return L(K("/remote/status",e))}function WP(e){return L(K("/remote/tunnel/start",e),{method:"POST"})}function KP(e){return L(K("/remote/tunnel/stop",e),{method:"POST"})}function GP(e){return L(K("/remote/token/persistent/regenerate",e),{method:"POST"})}function JP(e,n){return L(K("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function ep(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 YP(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=ep(null,s,i);return L(K(`/remote/url${r}`,n))}function QP(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=ep(e,i,r);return L(K(`/remote/qr${o}`,s))}function XP(e){return L(K("/memory",e))}function ZP(e,n){return L(K("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function eI(e){return L(K("/memory/files",e))}function tI(e,n){const s=`path=${encodeURIComponent(e)}`;return L(K(`/memory/file?${s}`,n))}function nI(e,n,s){return L(K("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function sI(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 L(K("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function iI(e){return L(K("/memory/dream",e),{method:"POST"})}function aI(e){return L(K("/memory/insights",e))}function rI(e,n){return L(K("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function oI(e){return L(K("/memory/extract",e),{method:"POST"})}function lI(e){return L(K("/memory/audit",e))}function cI(e){return L(K("/memory/stats",e))}function dI(e){return L(K("/memory/backend",e))}function uI(e){return L(K("/memory/install-qmd",e),{method:"POST"})}function mI(e,n){return L(K("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function Vi(){return L("/settings/global")}function sn(e){return L("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function hI(e){return L(K("/settings/scopes",e))}function pI(e){return L(K("/settings/pi-extensions",e))}function fI(e,n){return L(K("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function gI(e,n,s){return L(K("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function xI(){return L("/pi-settings")}async function bI(e){return L("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function vI(e){return L("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function yI(e){return L(K("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function ur(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Zn(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 zv(e,n,s){return L(K(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function Id(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(Zn(o),{headers:ki()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),u=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,d=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:u,hasMore:d}}function Fv(e,n,s,i){return L(K(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function Ov(e,n,s){return L(K(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Uv(e,n){return L(K(`/tasks/${e}/documents`,n))}function Bv(e,n,s){return L(K(`/tasks/${e}/documents/${n}/revisions`,s))}async function kI(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 L(K(r,n))}function jI(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return L(K(r,e))}function $d(e,n,s,i,r){return L(K(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function Hv(e,n,s){return L(K(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function qv(e,n,s){return L(K(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Vv(e,n,s){return L(K(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Wv(e,n){return L(K(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Kv(e,n,s){return L(K(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function cs(){return L("/models")}function Gv(){return L("/usage")}function Jv(){return L("/providers/claude-cli/status")}async function wI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/hermes/status${n}`)}async function NI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await L(`/providers/hermes/profiles${n}`)).profiles??[]}async function SI(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return L(`/providers/openclaw/status${n}`)}async function CI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),L(`/providers/paperclip/status?${n.toString()}`)}async function EI(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await L(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function _I(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await L(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function MI(e){return L("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function AI(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return L(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function RI(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 L(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function TI(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await L(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function PI(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return L(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function Yv(e){return L("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function mr(){return L("/auth/status")}function Qv(e){return L("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function Xv(e){return L("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Zv(e,n){return L("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function ey(e){return L("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function ty(e,n,s,i){return L("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function ny(e,n,s,i){return L(K("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function sy(e,n,s){return L("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function iy(e,n,s,i){return L(K("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function ay(e){return L(K("/git/remotes",e))}function ry(e){return L(K("/git/remotes/detailed",e))}function oy(e,n,s){return L(K("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function ly(e,n){return L(K(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cy(e,n,s){return L(K(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function dy(e,n,s){return L(K(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function uy(e,n,s){return L(K(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function my(e,n){return L(K(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function hy(e,n){return(await L(K("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function Fr(e,n,s,i){return L(K("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Dd(e,n){return L(K(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function py(e){return L(K("/terminal/sessions",e))}function Ps(e){return L(K("/git/status",e))}function fy(e,n){const s=e?`?limit=${e}`:"";return L(K(`/git/commits${s}`,n))}function go(e,n){return L(K(`/git/commits/${e}/diff`,n))}function gy(e){return L(K("/git/commits/ahead",e))}function xy(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return L(K(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function Pa(e){return L(K("/git/branches",e))}function by(e,n,s){const i=`?limit=${n}`;return L(K(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function vy(e){return L(K("/git/worktrees",e))}function yy(e,n,s){return L(K("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function ky(e,n){return L(K(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Ld(e,n,s){const i=n?"?force=true":"";return L(K(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function jy(e,n){return L(K("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function wy(e){return L(K("/git/pull",e),{method:"POST"})}function Ny(e){return L(K("/git/push",e),{method:"POST"})}function Or(e){return L(K("/git/stashes",e))}function Sy(e,n){return L(K("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function Cy(e,n,s){return L(K(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function Ey(e,n){return L(K(`/git/stashes/${e}`,n),{method:"DELETE"})}function _y(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),L(K(`/git/diff/file?${i.toString()}`,s))}function Xi(e){return L(K("/git/changes",e))}function zd(e,n){return L(K("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function My(e,n){return L(K("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Fd(e,n){return L(K("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Ay(e,n){return L(K("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Ry(e){return L(K("/workspaces",e))}function Ty(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),L(`/files?${i.toString()}`)}function Py(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function Iy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function $y(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),L(`/files/search?${i.toString()}`)}function Dy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Ly(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function zy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),L(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Fy(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),L(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function tp(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function Oy(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Uy(e,n,s){return L(K("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function By(e,n,s,i){return L(K("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Hy(e,n,s){return L(K(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function qy(e,n,s){return L(K(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function np(e,n,s){return L(K("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Vy(e,n,s){return L(K("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Wy(e,n,s){return L(K("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ky(e,n,s){return L(K("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const wc=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(wc))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Gy(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function kr(e,n,s={}){const i=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,u=null,d=!1;const m=p=>{const f=p.lastEventId;if(!f)return!0;const x=Number.parseInt(f,10);return Number.isFinite(x)?u!==null&&x<=u?!1:(u=x,!0):!0},h=()=>{if(o)return;const p=Gy(e,u),f=new EventSource(Qs(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=x=>{const v=x;m(v)&&n.onMessage?.(v)};for(const[x,v]of Object.entries(n.events??{}))f.addEventListener(x,b=>{const y=b;m(y)&&v(y)});f.onerror=()=>{if(o||r!==f)return;if(f.readyState===EventSource.CONNECTING){d||(d=!0,s.onConnectionStateChange?.("reconnecting"));return}if(f.close(),l>=i){s.onFatalError?.("Connection lost");return}d=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const g={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),wc.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return wc.add(g),g}function Od(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,i=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:i,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${i} (${l})`}}function pa(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 Jy(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 Yy(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Jy(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Qy(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,i=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((d,m)=>({id:m+1,text:d,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(d=>d.id>r).slice(0,s),totalLines:o};const c=Math.max(o-i,0),u=Math.max(c-s,0);return{lines:l.slice(u,c),totalLines:o}}function Ud(e){return Array.isArray(e)?e.map(Od):(e.candidates??[]).map(Od)}async function Xy(e){try{const n=await L(K("/dev-server/candidates",e));return Ud(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await L(K("/dev-server/detect",e));return Ud(s)}throw n}}function Xc(e){return L(K("/dev-server/status",e)).then(pa)}async function II(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 L(K(`/dev-server/logs/history${i}`,n));return Yy(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Xc(n);return Qy(o.logs,e)}throw r}}function Zy(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return L(K("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(pa)}function ek(e){return L(K("/dev-server/stop",e),{method:"POST"}).then(pa)}function tk(e){return L(K("/dev-server/restart",e),{method:"POST"}).then(pa)}async function nk(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await L(K("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return pa(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await L(K("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return pa(r)}throw i}}function $I(e){return Zn(K("/dev-server/logs/stream",e))}async function DI(e){try{return(await L(K("/devserver",e))).sessions??[]}catch{try{const n=await Xc(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 LI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Xc(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 zI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Zy({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 FI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await ek(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 OI(e,n){try{return await L(K(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await tk(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 UI(e,n,s){try{const i=await L(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 nk({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function BI(e){try{return(await L(K("/devserver/detect",e))).candidates??[]}catch{try{return(await Xy(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function HI(e,n){return Zn(K(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function jr(e,n,s=25e3){const i=setInterval(()=>{Dj(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function sk(e,n){return Zn(K(`/planning/${encodeURIComponent(e)}/stream`,n))}function ik(e,n,s,i){const r=sk(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function wr(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 ak(e){return L(wr("/routines",e))}function rk(e,n){return L(wr("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Bd(e,n,s){return L(wr(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function ok(e,n){await L(wr(`/routines/${e}`,n),{method:"DELETE"})}function lk(e,n){return L(wr(`/routines/${e}/trigger`,n),{method:"POST"})}function Hd(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 L(`/activity${s}`)}function ck(e){const n=K("/activity",e);return L(n,{method:"DELETE"})}function zo(e){return L(K("/workflow-steps",e))}function qd(e,n){return L(K("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function dk(e,n,s){return L(K(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function uk(e,n){return L(K(`/workflow-steps/${e}`,n),{method:"DELETE"})}function Vd(e,n){return L(K(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function mk(e,n){return L(K(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function hk(){return L("/workflow-step-templates")}function pk(e,n){return L(K(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function hr(e){return L(K("/scripts",e))}function fk(e,n,s){return L(K("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function gk(e,n){return L(K(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function sp(e,n,s){return(await L(K("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const Ur={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 ip(e){if(!(e instanceof Error))return Ur.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?Ur.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?Ur.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:Ur.NETWORK}function xk(e,n){return L(K("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function bk(e,n,s){return L(K(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function vk(e,n){return Zn(K(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function yk(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=kr(vk(e,n),{onOpen:()=>{l(),r=jr(e,n)},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},subtasks:u=>{try{s.onSubtasks?.(JSON.parse(u.data))}catch(d){console.error("[subtasks] Failed to parse subtasks event:",d)}},error:u=>{try{const d=JSON.parse(u.data),m=typeof d=="string"&&d.length>0?d:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{l(),s.onError?.(u)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function kk(e,n,s,i){return L(K("/subtasks/create-tasks",i),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,subtasks:n.map(r=>({tempId:r.id,title:r.title,description:r.description,size:r.suggestedSize,dependsOn:r.dependsOn}))})})}function ap(e,n,s){return L(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 jk(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 Fo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=jk(e,s,i);return L(o,r)}function Na(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const i=s.size>0?`?${s.toString()}`:"";return L(`/agents${i}`)}function rp(e,n){return L(K(`/agents/${encodeURIComponent(e)}`,n))}function wk(e,n){return L(K("/agents",n),{method:"POST",body:JSON.stringify(e)})}function Nk(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function qI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function VI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function WI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function KI(e,n){return L(K(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function GI(e,n,s){const i=`path=${encodeURIComponent(n)}`;return L(K(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function JI(e,n,s,i){return L(K(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function Sk(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function Ck(e,n){return L(K(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function YI(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 L(`/agents/${encodeURIComponent(e)}/runs${r}`)}function QI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function XI(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function ZI(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return L(K(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function e$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function Ek(e){return L(K("/agents/stats",e))}function t$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function n$(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return L(`/agents/org-tree${i?`?${i}`:""}`)}function s$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function Wd(e,n,s){return L(K(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function i$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/tasks`,n))}function a$(){return L("/agents/companies")}function r$(e,n){return L(K("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function o$(e,n){return L(K("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function l$(e,n){return L(K(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function c$(e){return L(K("/backups",e))}function d$(e){return L(K("/backups",e),{method:"POST"})}function u$(e,n){const s=K("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return L(i)}function m$(e,n,s){return L(K("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function Kd(){return L("/projects/across-nodes")}function ir(e,n){L("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function xo(){return L("/nodes")}function _k(e){return L("/nodes",{method:"POST",body:JSON.stringify(e)})}function Mk(e,n){return L(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Ak(e){return L(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Rk(e){const n=await L(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}function h$(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=ha();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return L(u)}function Tk(e){return L("/projects",{method:"POST",body:JSON.stringify(e)})}function op(e){return L(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function Gd(e){return L(`/projects/${encodeURIComponent(e)}/health`)}function Pk(e){return L(K("/executor/stats",e))}function Ik(e){return L(K("/system-stats",e))}function $k(e){return L(K("/kill-vitest",e),{method:"POST"})}function Jd(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 L(`/activity-feed${s}`)}function Dk(e){return L(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function Lk(e){return L(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function p$(){return L("/global-concurrency")}function f$(e){return L("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function zk(e,n){return L(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function lp(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 L(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Fk(e){return L(K("/missions",e))}function Ok(e,n){return L(K("/missions",n),{method:"POST",body:JSON.stringify(e)})}function cp(e,n){return L(K(`/missions/${encodeURIComponent(e)}`,n))}function Uk(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Bk(e,n){return L(K(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hk(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 L(K(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function qk(e){return L(K("/missions/health",e))}function Vk(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function Wk(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Kk(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gk(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Jk(e,n,s){return L(K(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Yk(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Qk(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function Xk(e,n,s){return L(K(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Zk(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ej(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function tj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function nj(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function sj(e,n,s,i){return L(K(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function ij(e,n){return L(K(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function ol(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function aj(e,n,s){return L(K(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function rj(e,n,s){return L(K(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function oj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function lj(e,n,s){return L(K(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function cj(e,n){return L(K(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function ll(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function Yd(e,n){return L(K(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function dj(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function Qd(e,n){return L(K(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function uj(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 L(K(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function mj(e,n){return L(K(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function hj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function pj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function fj(e,n){return L(K(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function gj(e,n,s){return L(K(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function xj(e,n,s){return L(K("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function bj(e,n,s,i){return L(K("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function vj(e,n,s){return L(K(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function dp(e,n,s){return L(K("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function yj(e,n,s){return L(K("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function kj(e,n,s,i){const r=Zn(K(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Nr(e,n,s){return K(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Sr(e,n,s){return K(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function jj(e,n){return L(Nr(e,"/start",n),{method:"POST"})}function wj(e,n,s,i){return L(Nr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Nj(e,n,s,i){const r=Zn(Nr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Sj(e,n,s){return L(Nr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Cj(e,n){return L(Nr(e,"/skip",n),{method:"POST"})}function Ej(e,n){return L(Sr(e,"/start",n),{method:"POST"})}function _j(e,n,s,i){return L(Sr(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function Mj(e,n,s,i){const r=Zn(Sr(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=kr(r,{onOpen:()=>{c(),o=jr(e,n)},onMessage:d=>{d.data.startsWith(":")},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},question:d=>{try{s.onQuestion?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:d=>{try{s.onSummary?.(JSON.parse(d.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:d=>{try{const m=JSON.parse(d.data);s.onError?.(m.message||m)}catch{s.onError?.(d.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:i?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{c(),s.onError?.(d)}});return l={close:()=>{c(),u.close()},isConnected:u.isConnected},l}function Aj(e,n,s){return L(Sr(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function Rj(e,n){return L(Sr(e,"/skip",n),{method:"POST"})}async function Tj(e,n){try{return await L(K(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function g$(e){return L(K("/roadmaps",e))}function x$(e,n){return L(K("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function b$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}`,n))}function v$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function y$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function k$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function j$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function w$(e,n){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function N$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function S$(e,n,s){return L(K(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function C$(e,n){return L(K(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function E$(e,n,s){return L(K(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function _$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function M$(e,n,s,i){return L(K(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function A$(e,n){return L(K(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function R$(e,n,s,i){return L(K(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function T$(e,n,s){return L(K(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function P$(e){return L(K("/todos",e))}function I$(e,n){const s={title:e};return L(K("/todos",n),{method:"POST",body:JSON.stringify(s)})}function $$(e,n,s){const i={title:n};return L(K(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function D$(e,n){return L(K(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function L$(e,n,s){const i={text:n};return L(K(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(i)})}function z$(e,n,s){const i=n;return L(K(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(i)})}function F$(e,n){return L(K(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function O$(e,n,s){return L(K(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function fa(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Zc(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(Zn(`/ai-sessions${n}`),{headers:ki()});return s.ok?(await s.json()).sessions??[]:[]}async function oi(e){const n=await fetch(Zn(`/ai-sessions/${encodeURIComponent(e)}`),{headers:ki()});return n.ok?n.json():null}async function Pj(e,n){const s=await L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Ij(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function $j(e,n){return L(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function up(e){await fetch(Zn(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:ki()})}function Dj(e,n){return L(K(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Lj(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 L(`/messages/inbox${i}`)}function zj(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 L(`/messages/outbox${i}`)}function mp(e){return L(K("/messages/unread-count",e))}function Fj(e,n){return L(K("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Oj(e,n){return L(K(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Uj(e){return L(K("/messages/read-all",e),{method:"POST"})}function Bj(e,n){return L(K(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hj(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return L(K(i,s))}function qj(e,n){return L(K(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function U$(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 L(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function B$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function H$(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return L(`/agents/${encodeURIComponent(e)}/performance${r}`)}function q$(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 L(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function V$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function W$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function K$(e,n,s){return L(K(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function G$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/budget`,n))}function J$(e,n){return L(K(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function Y$(e){return L(K("/plugins",e))}async function Q$(e,n){return L(K("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function X$(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function Z$(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function eD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function tD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function nD(e,n,s){return L(K(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function sD(e,n){return L(K(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function Vj(e){return L(K("/plugins/ui-slots",e))}async function iD(e){return L(K("/plugins/runtimes",e))}async function aD(e){return(await L(K("/skills/discovered",e))).skills}async function rD(e,n,s){return L(K("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function oD(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 L(K(`/skills/catalog${r}`,s))}async function lD(e,n){return(await L(K(`/skills/${encodeURIComponent(e)}/content`,n))).content}function cD(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return L(`/chat/sessions${i?`?${i}`:""}`)}async function Wj(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 L(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Kj(e,n){return L(K("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function dD(e,n,s){return L(K(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function uD(e,n){return L(K(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Xd(e,n,s){const i=new URLSearchParams;n?.limit!==void 0&&i.set("limit",String(n.limit)),n?.offset!==void 0&&i.set("offset",String(n.offset)),n?.before&&i.set("before",n.before);const r=i.toString();return L(K(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Gj(e,n){return L(K(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Jj(e,n,s,i,r){const o=Zn(K(`/chat/sessions/${encodeURIComponent(e)}/messages`,i)),l=new AbortController;let c=!1;const u=(d,m)=>{if(!(!d||!m))switch(d){case"thinking":try{s.onThinking?.(JSON.parse(m))}catch{s.onThinking?.(m)}break;case"text":try{s.onText?.(JSON.parse(m))}catch{s.onText?.(m)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(m))}catch{}break;case"done":try{s.onDone?.(JSON.parse(m))}catch{s.onDone?.({messageId:""})}break;case"error":try{const h=JSON.parse(m);s.onError?.(h.message||h)}catch{s.onError?.(m||"Stream error")}break}};return(async()=>{try{const d=await fetch(o,{method:"POST",headers:ki({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:l.signal});if(!d.ok){const v=await d.text();let b=`Request failed: ${d.status}`;try{b=JSON.parse(v).error||b}catch{}s.onError?.(b);return}if(!d.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected");const m=d.body.getReader(),h=new TextDecoder;let g="",p="",f=[];const x=(v,b=!1)=>{g+=v;const y=g.split(`
|
|
613
613
|
`);g=y.pop()||"",b&&g.length>0&&(y.push(g),g="");for(const S of y){const k=S.endsWith("\r")?S.slice(0,-1):S;if(k.startsWith("event:"))p=k.slice(6).trim();else if(k.startsWith("data:")){const R=k.slice(5);f.push(R.startsWith(" ")?R.slice(1):R)}else if(k===""){const R=f.join(`
|
|
614
614
|
`);u(p,R),p="",f=[]}}if(b&&p&&f.length>0){const S=f.join(`
|
|
615
615
|
`);u(p,S),p="",f=[]}};for(;;){const{done:v,value:b}=await m.read();if(v){x(h.decode(),!0);break}x(h.decode(b,{stream:!0}))}}catch(d){if(d instanceof DOMException&&d.name==="AbortError"){c||s.onError?.("Connection aborted");return}if(c)return;s.onError?.(d instanceof Error?d.message:"Connection error")}})(),{close:()=>{c=!0,l.abort()},isConnected:()=>!c}}function mD(e={},n){const s=new URLSearchParams;e.category&&s.set("category",e.category),e.status&&s.set("status",e.status),e.runId&&s.set("runId",e.runId),e.limit!==void 0&&s.set("limit",String(e.limit)),e.offset!==void 0&&s.set("offset",String(e.offset));const i=s.size>0?`?${s.toString()}`:"";return L(K(`/insights${i}`,n))}function hD(e,n){return L(K(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function pD(e="manual",n,s){return L(K("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function fD(e){return L(K("/insights/runs",e))}function gD(e,n){return L(K(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function Yj(e){switch(e){case"online":return{label:"Online",dotClass:"node-status-indicator__dot--online"};case"offline":return{label:"Offline",dotClass:"node-status-indicator__dot--offline"};case"connecting":return{label:"Connecting",dotClass:"node-status-indicator__dot--connecting"};case"error":return{label:"Error",dotClass:"node-status-indicator__dot--error"};default:return{label:"Unknown",dotClass:"node-status-indicator__dot--offline"}}}function Qj({node:e,showDetails:n=!1}){if(!e||e.type==="local")return t.jsx("div",{className:"node-status-indicator node-status-indicator--local",children:t.jsx("span",{className:"node-status-indicator__label",children:"Local"})});const{label:s,dotClass:i}=Yj(e.status),r=e.status==="connecting";return t.jsxs("div",{className:"node-status-indicator node-status-indicator--remote",children:[t.jsx("span",{className:`node-status-indicator__dot ${i}`,children:r&&t.jsx("span",{className:"node-status-indicator__spinner"})}),t.jsx("span",{className:"node-status-indicator__name",children:e.name}),n&&t.jsxs("span",{className:"node-status-indicator__details",children:[e.type," · ",s]})]})}const Zd=new Map,Xj=6e4;function hp(e){const[n,s]=a.useState([]),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(!1),u=a.useRef(!1),d=a.useCallback(m=>n.filter(h=>h.slot.slotId===m),[n]);return a.useEffect(()=>{const m=e??"default";let h=!1;async function g(){const p=Zd.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const x=await Vj(e);if(h||u.current)return;Zd.set(m,{slots:x,expiresAt:Date.now()+Xj}),s(x),c.current=!0}catch(x){if(h||u.current)return;l(x instanceof Error?x.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return g(),()=>{h=!0}},[e]),a.useEffect(()=>{c.current=!1,u.current=!1},[e]),a.useEffect(()=>()=>{u.current=!0},[]),a.useMemo(()=>({slots:n,getSlotsForId:d,loading:i,error:o}),[n,d,i,o])}function Oo({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=hp(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(Do,{level:"page",children:t.jsx(t.Fragment,{children:o.map(l=>t.jsx("div",{"data-plugin-slot":!0,"data-slot-id":l.slot.slotId,"data-plugin-id":l.pluginId,"data-component-path":l.slot.componentPath,"aria-label":l.slot.label},`${l.pluginId}-${l.slot.slotId}`))})})}function Zj(){return typeof window>"u"?"desktop":window.matchMedia("(max-width: 768px)").matches?"mobile":window.matchMedia("(min-width: 769px) and (max-width: 1024px)").matches?"tablet":"desktop"}function Cr(){const[e,n]=a.useState(Zj);return a.useEffect(()=>{if(typeof window>"u")return;const s=window.matchMedia("(max-width: 768px)"),i=window.matchMedia("(min-width: 769px) and (max-width: 1024px)"),r=()=>{s.matches?n("mobile"):i.matches?n("tablet"):n("desktop")};return s.addEventListener("change",r),i.addEventListener("change",r),()=>{s.removeEventListener("change",r),i.removeEventListener("change",r)}},[]),e}const pp={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function ew({projects:e,currentProject:n,onViewAll:s,onSelectProject:i}){const[r,o]=a.useState(!1),l=a.useRef(null);a.useEffect(()=>{if(!r)return;const u=d=>{l.current&&!l.current.contains(d.target)&&o(!1)};return document.addEventListener("mousedown",u),()=>document.removeEventListener("mousedown",u)},[r]),a.useEffect(()=>{if(!r)return;const u=d=>{d.key==="Escape"&&o(!1)};return document.addEventListener("keydown",u),()=>document.removeEventListener("keydown",u)},[r]);const c=a.useCallback(u=>{i?.(u),o(!1)},[i]);return t.jsx("div",{className:"project-selector",ref:l,children:e.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:`project-selector-trigger${r?" project-selector-trigger--open":""}`,onClick:()=>o(u=>!u),title:n?.name?`Switch project (current: ${n.name})`:"Switch project","aria-label":"Switch project","aria-expanded":r,"aria-haspopup":"listbox","data-testid":"project-selector-trigger",children:[t.jsx("span",{className:"project-selector-trigger-label",children:n?.name??"Projects"}),t.jsx(qt,{size:12,className:`project-selector-chevron${r?" project-selector-chevron--open":""}`})]}),r&&t.jsxs("div",{className:"project-selector-dropdown",role:"listbox","aria-label":"Select project","data-testid":"project-selector-dropdown",children:[e.map(u=>{const d=n?.id===u.id,m=pp[u.status]?.color;return t.jsxs("button",{className:`project-selector-item${d?" project-selector-item--current":""}`,onClick:()=>c(u),role:"option","aria-selected":d,children:[t.jsx("span",{className:"project-selector-dot",style:{backgroundColor:m||"var(--text-muted)"}}),t.jsxs("div",{className:"project-selector-info",children:[t.jsx("span",{className:"project-selector-name",children:u.name}),t.jsx("span",{className:"project-selector-path",children:u.path.split("/").slice(-2).join("/")})]}),d&&t.jsx(Mn,{size:14,className:"project-selector-check"})]},u.id)}),t.jsx("div",{className:"project-selector-divider",role:"presentation"}),t.jsx("button",{className:"project-selector-manage",onClick:()=>{s(),o(!1)},"data-testid":"manage-projects-action",children:"Manage Projects"})]})]})})}function eu({size:e=16}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"currentColor","aria-hidden":"true",children:t.jsx("path",{d:"M12 2C6.477 2 2 6.484 2 12.017c0 4.425 2.865 8.18 6.839 9.504.5.092.682-.217.682-.483 0-.237-.008-.868-.013-1.703-2.782.605-3.369-1.343-3.369-1.343-.454-1.158-1.11-1.466-1.11-1.466-.908-.62.069-.608.069-.608 1.003.07 1.531 1.032 1.531 1.032.892 1.53 2.341 1.088 2.91.832.092-.647.35-1.088.636-1.338-2.22-.253-4.555-1.113-4.555-4.951 0-1.093.39-1.988 1.029-2.688-.103-.253-.446-1.272.098-2.65 0 0 .84-.27 2.75 1.026A9.564 9.564 0 0112 6.844c.85.004 1.705.115 2.504.337 1.909-1.296 2.747-1.027 2.747-1.027.546 1.379.203 2.398.1 2.651.64.7 1.028 1.595 1.028 2.688 0 3.848-2.339 4.695-4.566 4.942.359.309.678.92.678 1.855 0 1.338-.012 2.419-.012 2.747 0 .268.18.58.688.482A10.019 10.019 0 0022 12.017C22 6.484 17.522 2 12 2z"})})}function tw({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:u,mailboxUnreadCount:d=0,onOpenSchedules:m,onOpenGitManager:h,onOpenNodes:g,showNodesButton:p,onOpenWorkflowSteps:f,onOpenScripts:x,onRunScript:v,onToggleTerminal:b,onOpenFiles:y,filesOpen:S,globalPaused:k,enginePaused:R,onToggleGlobalPause:N,onToggleEnginePause:M,view:C="board",onChangeView:z,showSkillsTab:A,showAgentsTab:P,searchQuery:F="",onSearchChange:W,projects:$=[],currentProject:_,onSelectProject:I,onViewAllProjects:O,projectId:J,isElectron:Q=!1,mobileNavEnabled:E,availableNodes:D=[],currentNode:T,onSelectNode:w,isRemote:q=!1,experimentalFeatures:G}){const me=Cr(),ce=me==="mobile",pe=ce||me==="tablet",U=ce&&E,[Ne,ne]=a.useState(!1),[xe,le]=a.useState(!1),[ve,ee]=a.useState(!1),[Ee,Fe]=a.useState(!1),[Ke,Ze]=a.useState(!1),[Xe,Qe]=a.useState(!1),[it,Ie]=a.useState(!1),[Ge,se]=a.useState(!1),[ye,Z]=a.useState(!1),[Te,ze]=a.useState(!1),[be,Me]=a.useState(!1),[Be,lt]=a.useState({}),[je,ie]=a.useState(!1),[Ae,he]=a.useState(-1),[Re,Je]=a.useState(null),[$e,de]=a.useState({}),[re,ue]=a.useState(!1),Pe=a.useRef(null),Se=a.useRef(null),fe=a.useRef(null),tt=a.useRef(null),ut=a.useRef(null),vt=a.useRef(null),gt=a.useRef(!1),dt=a.useRef(null),wt=a.useRef(null),Mt=a.useRef(null),yt=a.useRef(null),Et=a.useRef(null),Nt=a.useRef(null),Tt=a.useRef(null),Ht=a.useRef(null),Ut=a.useRef(!1),Vt=a.useMemo(()=>D.filter(we=>we.type==="remote"),[D]),zt=Vt.length>0,Ct=a.useMemo(()=>Object.entries(Be).sort(([we],[rt])=>we.localeCompare(rt)),[Be]),At=Ct.length>0,kt=Ct.length+(At?1:0),Kt=a.useMemo(()=>Object.entries($e).sort(([we],[rt])=>we.localeCompare(rt)),[$e]),$t=a.useMemo(()=>!!(G?.todoView||G?.insights||G?.roadmap||A||G?.memoryView||G?.devServerView),[G,A]),B=a.useCallback(()=>{const we=window.visualViewport;return we&&we.width>0&&we.height>0?{width:we.width,height:we.height,offsetTop:we.offsetTop,offsetLeft:we.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),ge=a.useCallback(()=>{const we=Tt.current;if(!we)return;const rt=we.getBoundingClientRect(),Jt=Ht.current,{width:Sn,height:Cn,offsetTop:pn,offsetLeft:bn}=B(),Rn=16,vn=16,Y=6,Oe=Jt?.offsetWidth||Math.max(rt.width,260),Ye=Math.min(Oe,Math.max(Sn-Rn*2,160)),st=Jt?.offsetHeight||280,pt=Math.min(st,Math.max(Cn-vn*2,160)),jt=rt.top-pn,_t=rt.bottom-pn,yn=rt.right-bn,en=Cn-_t,xt=jt,ts=en<pt&&xt>en,ns=Math.min(Math.max(yn-Ye,Rn),Sn-Rn-Ye)+bn,ss=ts?Math.max(vn+pn,jt-pt-Y+pn):Math.min(_t+Y+pn,Cn+pn-vn-pt);Je({top:ss,left:ns,width:Ye})},[B]),te=a.useCallback((we,rt)=>{v?.(we,rt),Me(!1),he(-1)},[v]),j=a.useCallback(()=>{x?.(),Me(!1),he(-1)},[x]),V=a.useCallback(we=>{switch(we.key){case"ArrowDown":we.preventDefault(),kt>0&&he(rt=>rt<kt-1?rt+1:0);break;case"ArrowUp":we.preventDefault(),kt>0&&he(rt=>rt>0?rt-1:kt-1);break;case"Enter":if(we.preventDefault(),Ae>=0)if(Ae<Ct.length){const[rt,Jt]=Ct[Ae];te(rt,Jt)}else At&&Ae===Ct.length&&j();break;case"Home":we.preventDefault(),kt>0&&he(0);break;case"End":we.preventDefault(),kt>0&&he(kt-1);break}},[j,te,Ae,Ct,At,kt]);a.useEffect(()=>{gt.current=Ke},[Ke]),a.useEffect(()=>{Ut.current=be},[be]),a.useEffect(()=>{if(!Ke||!pe)return;let we=!1;return ue(!0),hr(J).then(rt=>{we||de(rt)}).catch(()=>{we||de({})}).finally(()=>{we||ue(!1)}),()=>{we=!0}},[Ke,pe,J]),a.useEffect(()=>{if(!be||pe)return;let we=!1;return ie(!0),hr(J).then(rt=>{we||lt(rt)}).catch(()=>{we||lt({})}).finally(()=>{we||ie(!1)}),()=>{we=!0}},[be,pe,J]),a.useEffect(()=>{if(!be)return;const we=rt=>{Nt.current&&!Nt.current.contains(rt.target)&&Me(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[be]),a.useEffect(()=>{if(!be)return;const we=rt=>{rt.key==="Escape"&&(Me(!1),Tt.current?.focus())};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[be]),a.useEffect(()=>{if(be){he(-1);const we=window.setTimeout(()=>Ht.current?.focus(),0);return()=>window.clearTimeout(we)}Je(null)},[be]),a.useEffect(()=>{if(!be)return;const we=requestAnimationFrame(()=>{ge()});return()=>cancelAnimationFrame(we)},[be,je,Ct.length,At,ge]),a.useEffect(()=>{if(!be)return;const we=()=>ge();window.addEventListener("resize",we),window.addEventListener("scroll",we,!0);const rt=window.visualViewport;return rt&&(rt.addEventListener("resize",we),rt.addEventListener("scroll",we)),()=>{window.removeEventListener("resize",we),window.removeEventListener("scroll",we,!0),rt&&(rt.removeEventListener("resize",we),rt.removeEventListener("scroll",we))}},[be,ge]),a.useEffect(()=>{pe&&(Me(!1),he(-1))},[pe]);const De=Ne||F.length>0,nt=(xe||F.length>0)&&!ve,St=(C==="board"||C==="list")&&!ce&&W&&!ve&&F.length===0,Pt=(C==="board"||C==="list")&&!ce&&W;a.useEffect(()=>{F===""&&ee(!1)},[F]),a.useEffect(()=>{if(!Ee)return;const we=rt=>{Se.current&&!Se.current.contains(rt.target)&&Pe.current&&!Pe.current.contains(rt.target)&&Fe(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Ee]),a.useEffect(()=>{if(!ye)return;const we=rt=>{tt.current&&!tt.current.contains(rt.target)&&fe.current&&!fe.current.contains(rt.target)&&Z(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[ye]),a.useEffect(()=>{if(!Xe)return;const we=rt=>{dt.current&&!dt.current.contains(rt.target)&&Qe(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Xe]),a.useEffect(()=>{const we=rt=>{if(rt.key==="Escape"){if(se(!1),Z(!1),gt.current){Ze(!1);return}if(Ut.current){Me(!1),Tt.current?.focus();return}Fe(!1),ne(!1),Qe(!1),Ie(!1)}};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[]),a.useEffect(()=>{if(!it)return;const we=rt=>{wt.current&&!wt.current.contains(rt.target)&&Ie(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[it]),a.useEffect(()=>{if(!Te)return;const we=rt=>{Et.current&&!Et.current.contains(rt.target)&&ze(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Te]),a.useEffect(()=>{if(!Te)return;const we=rt=>{rt.key==="Escape"&&ze(!1)};return document.addEventListener("keydown",we),()=>document.removeEventListener("keydown",we)},[Te]),a.useEffect(()=>{if(!Ge)return;const we=rt=>{Mt.current&&!Mt.current.contains(rt.target)&&yt.current&&!yt.current.contains(rt.target)&&se(!1)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[Ge]);const Rt=a.useCallback(()=>{ne(we=>!we)},[]),un=a.useCallback(()=>{le(!0),ee(!1)},[]),mn=a.useCallback(()=>{le(!1),ee(!0),W&&W("")},[W]),wn=a.useCallback(()=>{Fe(we=>!we)},[]),Gt=a.useCallback(we=>{we&&we(),Fe(!1),Ze(!1)},[]),es=a.useCallback(()=>{ne(!1),W&&W("")},[W]);return t.jsxs("div",{className:"header-wrapper",children:[t.jsxs("header",{className:"header",children:[t.jsxs("div",{className:"header-left",children:[t.jsxs("div",{className:"header-brand",children:[t.jsxs("svg",{className:"header-logo",width:24,height:24,viewBox:"0 0 128 128",fill:"none","aria-label":"Fusion logo",role:"img",children:[t.jsx("circle",{cx:"64",cy:"64",r:"52",stroke:"currentColor",strokeWidth:"8"}),t.jsx("path",{d:"M26 101C44 82 62 64 82 45C90 37 98 30 104 24C96 35 89 47 81 60C70 79 57 95 43 108C38 112 32 108 26 101Z",fill:"currentColor"})]}),t.jsx("h1",{className:"logo",children:"Fusion"})]}),ce&&$.length>=1&&I&&t.jsxs("div",{className:"mobile-project-switch",ref:wt,children:[t.jsx("button",{className:`mobile-project-switch-trigger${it?" mobile-project-switch-trigger--open":""}`,onClick:()=>Ie(we=>!we),title:"Switch project","aria-label":"Switch project","aria-expanded":it,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(qt,{size:14,className:`mobile-project-switch-chevron${it?" mobile-project-switch-chevron--open":""}`})}),it&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:$.map(we=>{const rt=_?.id===we.id,Jt=pp[we.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${rt?" mobile-project-switch-item--current":""}`,onClick:()=>{I(we),Ie(!1)},role:"option","aria-selected":rt,"data-testid":`mobile-project-switch-item-${we.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:Jt||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:we.name}),t.jsx("span",{className:"mobile-project-switch-path",children:we.path.split("/").slice(-2).join("/")})]}),rt&&t.jsx(Mn,{size:14,className:"mobile-project-switch-check"})]},we.id)})})]}),!pe&&$.length>=1&&O&&t.jsx(ew,{projects:$,currentProject:_??null,onViewAll:O,onSelectProject:I}),zt&&t.jsxs("div",{className:`header-node-selector${ce?" header-node-selector--mobile":""}`,ref:ce?void 0:dt,children:[t.jsx(Qj,{node:T??null,showDetails:!ce}),!ce&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Xe?" node-selector-trigger--open":""}`,onClick:()=>Qe(we=>!we),title:"Switch node","aria-label":"Switch node","aria-expanded":Xe,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(hn,{size:12,className:`node-selector-chevron${Xe?" node-selector-chevron--open":""}`})}),Xe&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${q?"":" node-selector-option--active"}`,onClick:()=>{w?.(null),Qe(!1)},role:"option","aria-selected":!q,"data-testid":"node-option-local",children:[t.jsx("span",{className:"node-selector-option-dot node-selector-option-dot--local"}),t.jsx("span",{className:"node-selector-option-label",children:"Local"})]}),Vt.map(we=>t.jsxs("button",{className:`node-selector-option${T?.id===we.id?" node-selector-option--active":""}`,onClick:()=>{w?.(we),Qe(!1)},role:"option","aria-selected":T?.id===we.id,"data-testid":`node-option-${we.id}`,children:[t.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${we.status}`}),t.jsx("span",{className:"node-selector-option-label",children:we.name}),t.jsx("span",{className:"node-selector-option-status",children:we.status})]},we.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[U&&z&&(C==="board"||C==="list")&&t.jsxs("div",{className:"view-toggle","data-testid":"mobile-view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>z("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(gc,{size:16})})]}),W&&ce&&(U||C==="board"||C==="list")&&!De&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Rt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(oa,{size:16})}),St&&t.jsx("button",{className:"btn-icon",onClick:un,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(oa,{size:16})}),ce&&U&&o&&t.jsx("button",{className:"btn-icon",onClick:we=>o(we.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Cs,{size:16})}),!U&&z&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>z("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(Bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>z("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(gc,{size:16})}),P&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>z("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(gn,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>z("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(ls,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>z("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>z("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Oi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>z("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(ma,{size:16})}),$t&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:yt,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)||G?.todoView&&C==="todos"?" active":""}`,onClick:()=>se(we=>!we),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":Ge,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(qt,{size:12})}),Ge&&t.jsxs("div",{ref:Mt,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[G?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{z("insights"),se(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(qn,{size:14}),t.jsx("span",{children:"Insights"})]}),G?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{z("roadmaps"),se(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(xc,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),A&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{z("skills"),se(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(Pn,{size:14}),t.jsx("span",{children:"Skills"})]}),G?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{z("memory"),se(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(co,{size:14}),t.jsx("span",{children:"Memory"})]}),G?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{z("devserver"),se(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]}),G?.todoView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="todos"?" active":""}`,onClick:()=>{z("todos"),se(!1)},role:"menuitem","data-testid":"view-overflow-todos",children:[t.jsx(Gh,{size:14}),t.jsx("span",{children:"Todos"})]})]})]})]}),!pe&&o&&t.jsx("button",{className:"btn-icon",onClick:we=>o(we.currentTarget.getBoundingClientRect()),title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Cs,{size:16})}),!pe&&c&&t.jsx("button",{className:"btn-icon",onClick:c,title:"System Stats","data-testid":"desktop-header-system-stats-btn",children:t.jsx(dr,{size:16})}),!pe&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(cr,{size:16})}),!pe&&!Q&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(eu,{size:16})}),!pe&&t.jsxs("button",{className:`btn-icon${r>0?" btn-icon--has-indicator":""}`,onClick:r>0&&i?i:s,title:r>0?"Resume planning session":"Create a task with AI planning","data-testid":"planning-btn",style:{position:"relative"},children:[t.jsx(Ys,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"planning-badge","aria-label":`${r} active planning session${r!==1?"s":""}`,children:r})]}),!pe&&t.jsxs("div",{className:"terminal-split-btn",ref:Nt,children:[t.jsx("button",{className:"btn-icon btn-icon--terminal terminal-split-btn__main",onClick:b,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(ri,{size:16})}),x&&v&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"terminal-split-btn__divider"}),t.jsx("button",{ref:Tt,className:`btn-icon terminal-split-btn__chevron${be?" btn-icon--active":""}`,onClick:()=>Me(we=>!we),title:"Scripts","aria-haspopup":"listbox","aria-expanded":be,"aria-label":"Quick scripts","data-testid":"scripts-btn",children:t.jsx(qt,{size:12,className:`quick-scripts-dropdown__trigger-chevron${be?" rotate":""}`})}),be&&t.jsx("div",{ref:Ht,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:V,"data-testid":"quick-scripts-dropdown",style:Re?{position:"fixed",top:`${Re.top}px`,left:`${Re.left}px`,width:`${Re.width}px`,right:"auto"}:void 0,children:je?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):Ct.length===0?t.jsxs("div",{className:"quick-scripts-dropdown__empty","data-testid":"quick-scripts-empty",children:[t.jsx("div",{className:"quick-scripts-dropdown__empty-icon",children:t.jsx(ri,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:j,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:Ct.map(([we,rt],Jt)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${Ae===Jt?"highlighted":""}`,onClick:()=>te(we,rt),role:"option","aria-selected":Ae===Jt,"data-testid":`quick-script-item-${we}`,children:[t.jsx(xn,{size:14,className:"quick-scripts-dropdown__item-icon"}),t.jsxs("div",{className:"quick-scripts-dropdown__item-info",children:[t.jsx("span",{className:"quick-scripts-dropdown__item-name",children:we}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:rt,children:rt.length>50?`${rt.slice(0,50)}...`:rt})]})]},we))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${At&&Ae===Ct.length?"highlighted":""}`,onClick:j,"data-testid":"quick-scripts-manage",children:[t.jsx(sr,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})]}),!pe&&y&&t.jsx("button",{className:`btn-icon${S?" btn-icon--active":""}`,onClick:y,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(In,{size:16})}),!pe&&h&&t.jsx("button",{className:"btn-icon",onClick:h,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Js,{size:16})}),!pe&&f&&t.jsx("button",{className:"btn-icon",onClick:f,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(vc,{size:16})}),!pe&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:fe,className:"btn-icon",onClick:()=>Z(we=>!we),title:"More actions","aria-label":"More actions","aria-expanded":ye,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(hc,{size:16})}),ye&&t.jsxs("div",{ref:tt,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[g&&p!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{g(),Z(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(mo,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{Gt(m),Z(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(yi,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:Et,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${k?" btn-icon--stopped":""}`,onClick:N,title:k?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:k?t.jsx(xn,{size:16}):t.jsx(ms,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${Te?" btn-icon--active":""}`,onClick:()=>ze(we=>!we),title:"Engine options","aria-haspopup":"menu","aria-expanded":Te,"data-testid":"engine-control-chevron-btn",children:t.jsx(qt,{size:12})}),Te&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${R?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{M?.(),ze(!1)},role:"menuitem",title:R?"Resume scheduling":"Pause triage",disabled:!!k,"data-testid":"engine-control-pause-triage-btn",children:[R?t.jsx(xn,{size:14}):t.jsx(Gs,{size:14}),t.jsx("span",{children:R?"Resume scheduling":"Pause triage"})]})})]}),!pe&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(sr,{size:16})}),t.jsx(Oo,{slotId:"header-action",projectId:J}),pe&&!U&&t.jsx("button",{ref:Pe,className:"btn-icon compact-overflow-trigger",onClick:wn,title:"More header actions","aria-label":"More header actions","aria-expanded":Ee,"aria-haspopup":"menu",children:t.jsx(hc,{size:16})}),pe&&!U&&Ee&&t.jsxs("div",{ref:Se,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[$.length>=1&&O&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(O),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(qh,{size:16}),t.jsx("span",{children:"Projects"})]}),y&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(y),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(In,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>Gt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Ys,{size:16}),r>0&&t.jsx("span",{className:"header-badge header-badge--pulse","data-testid":"overflow-planning-badge",children:r})]}),t.jsx("span",{children:r>0?`Resume planning session (${r})`:"Create a task with AI planning"})]}),h&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(h),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Js,{size:16}),t.jsx("span",{children:"Git Manager"})]}),g&&p!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(g),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(mo,{size:16}),t.jsx("span",{children:"Nodes"})]}),!Q&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(n),role:"menuitem",children:[t.jsx(eu,{size:16}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("div",{className:"mobile-overflow-group","data-testid":"overflow-terminal-group",children:[t.jsxs("div",{className:"mobile-overflow-split-row",children:[t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-split-primary",onClick:()=>Gt(b),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(ri,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>Ze(we=>!we),role:"menuitem","aria-expanded":Ke,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(hn,{size:14,className:`mobile-overflow-chevron${Ke?" mobile-overflow-chevron--open":""}`})})]}),Ke&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:re?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(ot,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Kt.length>0?t.jsxs(t.Fragment,{children:[Kt.map(([we,rt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{v&&v(we,rt),Fe(!1),Ze(!1)},role:"menuitem","data-testid":`overflow-script-item-${we}`,children:[t.jsx(xn,{size:14}),t.jsx("span",{children:we})]},we)),x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>Gt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):x&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>Gt(x),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(m),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(yi,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(cr,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),u&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(u),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(ma,{size:16}),t.jsxs("span",{children:["Mailbox",d>0?` (${d})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:we=>Gt(()=>o(we.currentTarget.getBoundingClientRect())),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Cs,{size:16}),t.jsx("span",{children:"View Usage"})]}),f&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(f),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(vc,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>Gt(e),role:"menuitem",children:[t.jsx(sr,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Pt&&nt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(oa,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:we=>W(we.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:mn,"aria-label":"Close search",children:t.jsx(Ot,{size:14})})]})}),W&&ce&&De&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:ut,className:"header-search mobile-search-expanded",children:[t.jsx(oa,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:vt,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:F,onChange:we=>W(we.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:es,"aria-label":"Close search",children:t.jsx(Ot,{size:14})})]})})]})}const nw={themeMode:"dark",colorTheme:"default",defaultProvider:void 0,defaultModelId:void 0,fallbackProvider:void 0,fallbackModelId:void 0,defaultThinkingLevel:void 0,ntfyEnabled:!1,ntfyTopic:void 0,ntfyBaseUrl:void 0,ntfyEvents:["in-review","merged","failed","awaiting-approval","awaiting-user-review","planning-awaiting-input","gridlock"],ntfyDashboardHost:void 0,webhookEnabled:!1,webhookUrl:void 0,webhookFormat:"generic",webhookEvents:[],notificationProviders:[],defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!0,updateCheckEnabled:!0,updateCheckFrequency:"daily",showGitHubStarButton:!0,modelOnboardingComplete:void 0,useClaudeCli:void 0,executionGlobalProvider:void 0,executionGlobalModelId:void 0,planningGlobalProvider:void 0,planningGlobalModelId:void 0,validatorGlobalProvider:void 0,validatorGlobalModelId:void 0,titleSummarizerGlobalProvider:void 0,titleSummarizerGlobalModelId:void 0,daemonToken:void 0,daemonPort:4040,daemonHost:"127.0.0.1",settingsSyncEnabled:!1,settingsSyncAuth:!1,settingsSyncInterval:9e5,settingsSyncConflictResolution:"last-write-wins",dashboardCurrentNodeId:void 0,dashboardCurrentProjectIdByNode:void 0,vitestAutoKillEnabled:!0,vitestKillThresholdPct:90},sw={globalPause:!1,globalPauseReason:void 0,enginePaused:!1,maxConcurrent:2,maxTriageConcurrent:2,globalMaxConcurrent:4,maxWorktrees:4,pollIntervalMs:15e3,heartbeatMultiplier:1,groupOverlappingFiles:!0,overlapIgnorePaths:[],autoMerge:!0,mergeStrategy:"direct",pushAfterMerge:!1,pushRemote:"origin",unavailableNodePolicy:"block",defaultNodeId:void 0,worktreeInitCommand:void 0,testCommand:void 0,buildCommand:void 0,recycleWorktrees:!1,worktreeNaming:"random",taskPrefix:"FN",includeTaskIdInCommit:!0,commitAuthorEnabled:!0,commitAuthorName:"Fusion",commitAuthorEmail:"noreply@runfusion.ai",planningProvider:void 0,planningModelId:void 0,planningFallbackProvider:void 0,planningFallbackModelId:void 0,defaultProviderOverride:void 0,defaultModelIdOverride:void 0,executionProvider:void 0,executionModelId:void 0,validatorProvider:void 0,validatorModelId:void 0,validatorFallbackProvider:void 0,validatorFallbackModelId:void 0,modelPresets:[],autoSelectModelPreset:!1,defaultPresetBySize:{},autoResolveConflicts:!0,smartConflictResolution:!0,worktreeRebaseBeforeMerge:!0,worktreeRebaseRemote:"",worktreeRebaseLocalBase:!0,mergeConflictStrategy:"smart-prefer-main",workflowStepTimeoutMs:36e4,strictScopeEnforcement:!1,buildRetryCount:0,verificationFixRetries:3,buildTimeoutMs:3e5,requirePlanApproval:!1,specStalenessEnabled:!1,specStalenessMaxAgeMs:360*60*1e3,taskStuckTimeoutMs:void 0,aiSessionTtlMs:10080*60*1e3,aiSessionCleanupIntervalMs:3600*1e3,autoUnpauseEnabled:!0,autoUnpauseBaseDelayMs:3e5,autoUnpauseMaxDelayMs:36e5,maxStuckKills:6,maxPostReviewFixes:1,maxSpawnedAgentsPerParent:5,maxSpawnedAgentsGlobal:20,maintenanceIntervalMs:9e5,autoArchiveDoneTasksEnabled:!0,autoArchiveDoneAfterMs:2880*60*1e3,archiveAgentLogMode:"compact",autoUpdatePrStatus:!1,autoCreatePr:!1,githubCommentOnDone:!1,githubCommentTemplate:void 0,autoBackupEnabled:!1,autoBackupSchedule:"0 2 * * *",autoBackupRetention:7,autoBackupDir:".fusion/backups",autoSummarizeTitles:!1,titleSummarizerProvider:void 0,titleSummarizerModelId:void 0,titleSummarizerFallbackProvider:void 0,titleSummarizerFallbackModelId:void 0,scripts:void 0,setupScript:void 0,insightExtractionEnabled:!1,insightExtractionSchedule:"0 2 * * *",insightExtractionMinIntervalMs:864e5,memoryEnabled:!0,memoryBackendType:"qmd",memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *",tokenCap:void 0,runStepsInNewSessions:!1,maxParallelSteps:2,missionStaleThresholdMs:6e5,missionMaxTaskRetries:3,missionHealthCheckIntervalMs:3e5,agentPrompts:void 0,promptOverrides:void 0,remoteAccess:{activeProvider:null,providers:{tailscale:{enabled:!1,hostname:"",targetPort:0,acceptRoutes:!1},cloudflare:{enabled:!1,quickTunnel:!0,tunnelName:"",tunnelToken:null,ingressUrl:""}},tokenStrategy:{persistent:{enabled:!0,token:null},shortLived:{enabled:!1,ttlMs:9e5,maxTtlMs:864e5}},lifecycle:{rememberLastRunning:!1,wasRunningOnShutdown:!1,lastRunningProvider:null}},reflectionEnabled:!1,reflectionIntervalMs:36e5,reflectionAfterTask:!0,reviewHandoffPolicy:"disabled",showQuickChatFAB:!1,experimentalFeatures:{}},iw=Object.freeze(Object.keys(nw)),aw=Object.freeze(Object.keys(sw));function xD(e){return iw.includes(e)}function bD(e){return aw.includes(e)}function ke(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}function rw(e){return!!(e?.provider&&e?.modelId)}function ji(...e){for(const n of e)if(rw(n))return{provider:n.provider,modelId:n.modelId};return{}}function Uo(e){return ji({provider:e?.defaultProviderOverride,modelId:e?.defaultModelIdOverride},{provider:e?.defaultProvider,modelId:e?.defaultModelId})}function ow(e){return ji({provider:e?.executionProvider,modelId:e?.executionModelId},{provider:e?.executionGlobalProvider,modelId:e?.executionGlobalModelId},Uo(e))}function lw(e){return ji({provider:e?.planningProvider,modelId:e?.planningModelId},{provider:e?.planningGlobalProvider,modelId:e?.planningGlobalModelId},Uo(e))}function cw(e){return ji({provider:e?.validatorProvider,modelId:e?.validatorModelId},{provider:e?.validatorGlobalProvider,modelId:e?.validatorGlobalModelId},Uo(e))}function vD(e){return ji({provider:e?.titleSummarizerProvider,modelId:e?.titleSummarizerModelId},{provider:e?.titleSummarizerGlobalProvider,modelId:e?.titleSummarizerGlobalModelId},{provider:e?.planningProvider,modelId:e?.planningModelId},Uo(e))}function fp(e,n){return ji({provider:e.modelProvider,modelId:e.modelId},ow(n))}function gp(e,n){return ji({provider:e.validatorModelProvider,modelId:e.validatorModelId},cw(n))}function xp(e,n){return ji({provider:e.planningModelProvider,modelId:e.planningModelId},lw(n))}const yD=["off","minimal","low","medium","high"],zi=["triage","todo","in-progress","in-review","done","archived"],ed=["low","normal","high","urgent"],ps="normal",dw=["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"],_n={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},uw={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"},Nc={triage:["todo"],todo:["in-progress","triage"],"in-progress":["in-review","todo","triage","done"],"in-review":["done","in-progress","todo"],done:["todo","triage","archived"],archived:["done"]};function mw(e){const n=e.metadata??{};return!!(n.agentKind==="task-worker"||n.taskWorker===!0||n.managedBy==="task-executor"||n.type==="spawned"||n.internal===!0||e.role==="executor"&&typeof e.name=="string"&&e.name.startsWith("executor-")&&e.reportsTo==null||e.role==="executor"&&e.name==="verification-agent"&&e.reportsTo==null)}function hw(e,n=1400){const s=a.useRef(null),[i,r]=a.useState(!1),o=a.useRef(null);return a.useEffect(()=>(s.current!==null&&e>s.current&&(r(!0),o.current=setTimeout(()=>r(!1),n)),s.current=e,()=>{o.current!==null&&clearTimeout(o.current)}),[e,n]),i}function pw({isOpen:e,options:n,onConfirm:s,onCancel:i}){const r=a.useRef(null);return a.useEffect(()=>{if(!e)return;r.current?.focus();const o=l=>{l.key==="Escape"&&(l.preventDefault(),i())};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[e,i]),!e||!n?null:t.jsx("div",{className:"modal-overlay open",onClick:i,children:t.jsxs("div",{className:"modal confirm-dialog",onClick:o=>o.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":n.title,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:n.title}),t.jsx("button",{className:"modal-close",onClick:i,"aria-label":"Close confirmation dialog",children:"×"})]}),t.jsx("div",{className:"confirm-dialog__body",children:n.message}),t.jsxs("div",{className:"modal-actions confirm-dialog__actions",children:[t.jsx("button",{ref:r,className:"btn",onClick:i,children:n.cancelLabel??"Cancel"}),t.jsx("button",{className:`btn ${n.danger?"btn-danger":"btn-primary"}`,onClick:s,children:n.confirmLabel??"Confirm"})]})]})})}const bp=a.createContext(null);function fw({children:e}){const[n,s]=a.useState([]),i=a.useRef([]),r=a.useCallback(d=>{s(m=>{const h=d(m);return i.current=h,h})},[]),o=a.useCallback(d=>new Promise(m=>{r(h=>[...h,{options:d,resolve:m}])}),[r]),l=a.useCallback(d=>{const m=i.current[0];m&&(m.resolve(d),r(h=>h.slice(1)))},[r]),c=n[0]??null,u=a.useMemo(()=>({confirm:o}),[o]);return lo.createElement(bp.Provider,{value:u},e,lo.createElement(pw,{isOpen:c!==null,options:c?.options??null,onConfirm:()=>l(!0),onCancel:()=>l(!1)}))}function Ds(){const e=a.useContext(bp);return e||{confirm:async n=>!1}}function gw(e,n){return e==="open"?"card-github-badge--open":n==="completed"?"card-github-badge--completed":n==="not_planned"?"card-github-badge--not-planned":"card-github-badge--closed"}function vp({prInfo:e,issueInfo:n,onIssueRefresh:s}){const i=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:i,children:[t.jsx(hs,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${gw(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(Ro,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function Br(e,n){return`${e??"default"}:${n}`}class xw{ws=null;listeners=new Set;badgeUpdates=new Map;subscriptionsByTask=new Map;reconnectTimeout=null;reconnectDelayMs=1e3;shouldReconnect=!1;isConnected=!1;projectId=null;snapshot={badgeUpdates:new Map,isConnected:!1};previousProjectIdRef=null;projectContextVersionRef=0;contextVersionAtStart=0;subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}setProjectId(n){if(this.projectId===n)return;this.previousProjectIdRef=this.projectId,this.projectContextVersionRef++,this.contextVersionAtStart=this.projectContextVersionRef;const s=this.subscriptionsByTask.size>0,i=[];for(const[r,o]of this.subscriptionsByTask){const l=r.split(":").slice(1).join(":");for(const c of o)i.push({hookId:c,taskId:l})}if(this.projectId=n,this.reset(),s){for(const{hookId:r,taskId:o}of i){const l=Br(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=Br(this.projectId,s),r=this.subscriptionsByTask.get(i)??new Set,o=!r.has(n);r.add(n),this.subscriptionsByTask.set(i,r),this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect(),o&&this.send({type:"subscribe",taskId:s,projectId:this.projectId})}unsubscribeTask(n,s){const i=Br(this.projectId,s),r=this.subscriptionsByTask.get(i);r&&(r.delete(n),r.size===0&&(this.subscriptionsByTask.delete(i),this.badgeUpdates.delete(i),this.send({type:"unsubscribe",taskId:s,projectId:this.projectId}),this.emit()),this.shouldReconnect=this.subscriptionsByTask.size>0,this.shouldReconnect||this.disconnect())}cleanupHook(n){for(const s of[...this.subscriptionsByTask.keys()]){const i=s.split(":").slice(1).join(":");this.unsubscribeTask(n,i)}}reset(){this.disconnect(),this.badgeUpdates.clear(),this.subscriptionsByTask.clear(),this.shouldReconnect=!1,this.emit()}connect(){if(!this.shouldReconnect||typeof window>"u"||this.ws&&(this.ws.readyState===WebSocket.OPEN||this.ws.readyState===WebSocket.CONNECTING))return;const n=this.projectContextVersionRef;let i=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/ws`;this.projectId&&(i+=`?projectId=${encodeURIComponent(this.projectId)}`);const r=new WebSocket(Qs(i));this.ws=r,r.onopen=()=>{if(this.projectContextVersionRef!==n){r.close();return}this.isConnected=!0,this.reconnectDelayMs=1e3,this.emit();const o=new Set;for(const l of this.subscriptionsByTask.keys()){const c=l.split(":").slice(1).join(":");o.add(c)}for(const l of o)this.send({type:"subscribe",taskId:l,projectId:this.projectId})},r.onmessage=o=>{if(this.projectContextVersionRef===n)try{const l=JSON.parse(o.data);if(l.type!=="badge:updated"||l.projectId!==void 0&&l.projectId!==this.projectId)return;const c=Br(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:tu(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:tu(l,"issueInfo")?l.issueInfo??null:u?.issueInfo,timestamp:l.timestamp}),this.emit()}catch{}},r.onclose=()=>{this.projectContextVersionRef===n&&(this.ws=null,this.isConnected&&(this.isConnected=!1,this.emit()),this.shouldReconnect&&this.scheduleReconnect(n))},r.onerror=()=>{}}disconnect(){if(this.reconnectTimeout&&(clearTimeout(this.reconnectTimeout),this.reconnectTimeout=null),this.ws){const n=this.ws;this.ws=null,n.close()}this.isConnected&&(this.isConnected=!1,this.emit())}scheduleReconnect(n){if(this.reconnectTimeout)return;const s=n??this.projectContextVersionRef,i=Math.min(this.reconnectDelayMs,5e3);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null,this.projectContextVersionRef===s&&this.shouldReconnect&&this.connect()},i),this.reconnectDelayMs=Math.min(this.reconnectDelayMs*2,5e3)}send(n){!this.ws||this.ws.readyState!==WebSocket.OPEN||this.ws.send(JSON.stringify(n))}emit(){this.snapshot={badgeUpdates:new Map(this.badgeUpdates),isConnected:this.isConnected};for(const n of this.listeners)n()}}const Pi=new xw;let bw=0;function tu(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function yp(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${bw++}`);const s=a.useSyncExternalStore(o=>Pi.subscribe(o),()=>Pi.getSnapshot(),()=>Pi.getSnapshot()),i=a.useCallback(o=>{Pi.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{Pi.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{Pi.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{Pi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function bo(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function vw({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=yp(o),d=!!(n||s);a.useEffect(()=>{if(!d||!r){u(e);return}return c(e),()=>{u(e)}},[d,r,o,c,e,u]);const m=l.get(`${o??"default"}:${e}`),h=bo(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=bo(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(vp,{prInfo:h,issueInfo:g})}const yw=a.memo(vw);yw.displayName="TaskCardBadge";const kw={sm:16,md:20,lg:24};function jw({size:e,color:n,label:s="Anthropic"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"anthropic-icon","aria-label":s,children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})})}function nu({size:e,color:n,label:s="OpenAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openai-icon","aria-label":s,children:t.jsx("path",{d:"M22.282 9.821a6 6 0 0 0-.516-4.91a6.05 6.05 0 0 0-6.51-2.9A6.065 6.065 0 0 0 4.981 4.18a6 6 0 0 0-3.998 2.9a6.05 6.05 0 0 0 .743 7.097a5.98 5.98 0 0 0 .51 4.911a6.05 6.05 0 0 0 6.515 2.9A6 6 0 0 0 13.26 24a6.06 6.06 0 0 0 5.772-4.206a6 6 0 0 0 3.997-2.9a6.06 6.06 0 0 0-.747-7.073M13.26 22.43a4.48 4.48 0 0 1-2.876-1.04l.141-.081l4.779-2.758a.8.8 0 0 0 .392-.681v-6.737l2.02 1.168a.07.07 0 0 1 .038.052v5.583a4.504 4.504 0 0 1-4.494 4.494M3.6 18.304a4.47 4.47 0 0 1-.535-3.014l.142.085l4.783 2.759a.77.77 0 0 0 .78 0l5.843-3.369v2.332a.08.08 0 0 1-.033.062L9.74 19.95a4.5 4.5 0 0 1-6.14-1.646M2.34 7.896a4.5 4.5 0 0 1 2.366-1.973V11.6a.77.77 0 0 0 .388.677l5.815 3.354l-2.02 1.168a.08.08 0 0 1-.071 0l-4.83-2.786A4.504 4.504 0 0 1 2.34 7.872zm16.597 3.855l-5.833-3.387L15.119 7.2a.08.08 0 0 1 .071 0l4.83 2.791a4.494 4.494 0 0 1-.676 8.105v-5.678a.79.79 0 0 0-.407-.667m2.01-3.023l-.141-.085l-4.774-2.782a.78.78 0 0 0-.785 0L9.409 9.23V6.897a.07.07 0 0 1 .028-.061l4.83-2.787a4.5 4.5 0 0 1 6.68 4.66zm-12.64 4.135l-2.02-1.164a.08.08 0 0 1-.038-.057V6.075a4.5 4.5 0 0 1 7.375-3.453l-.142.08L8.704 5.46a.8.8 0 0 0-.393.681zm1.097-2.365l2.602-1.5l2.607 1.5v2.999l-2.597 1.5l-2.607-1.5Z",fill:n})})}function Bs({size:e,color:n,label:s="Google Gemini"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"gemini-icon","aria-label":s,children:t.jsx("path",{d:"M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81",fill:n})})}function ww({size:e,color:n,label:s="Ollama"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"ollama-icon","aria-label":s,children:t.jsx("path",{d:"M16.361 10.26a.894.894 0 0 0-.558.47l-.072.148.001.207c0 .193.004.217.059.353.076.193.152.312.291.448.24.238.51.3.872.205a.86.86 0 0 0 .517-.436.752.752 0 0 0 .08-.498c-.064-.453-.33-.782-.724-.897a1.06 1.06 0 0 0-.466 0zm-9.203.005c-.305.096-.533.32-.65.639a1.187 1.187 0 0 0-.06.52c.057.309.31.59.598.667.362.095.632.033.872-.205.14-.136.215-.255.291-.448.055-.136.059-.16.059-.353l.001-.207-.072-.148a.894.894 0 0 0-.565-.472 1.02 1.02 0 0 0-.474.007Zm4.184 2c-.131.071-.223.25-.195.383.031.143.157.288.353.407.105.063.112.072.117.136.004.038-.01.146-.029.243-.02.094-.036.194-.036.222.002.074.07.195.143.253.064.052.076.054.255.059.164.005.198.001.264-.03.169-.082.212-.234.15-.525-.052-.243-.042-.28.087-.355.137-.08.281-.219.324-.314a.365.365 0 0 0-.175-.48.394.394 0 0 0-.181-.033c-.126 0-.207.03-.355.124l-.085.053-.053-.032c-.219-.13-.259-.145-.391-.143a.396.396 0 0 0-.193.032zm.39-2.195c-.373.036-.475.05-.654.086-.291.06-.68.195-.951.328-.94.46-1.589 1.226-1.787 2.114-.04.176-.045.234-.045.53 0 .294.005.357.043.524.264 1.16 1.332 2.017 2.714 2.173.3.033 1.596.033 1.896 0 1.11-.125 2.064-.727 2.493-1.571.114-.226.169-.372.22-.602.039-.167.044-.23.044-.523 0-.297-.005-.355-.045-.531-.288-1.29-1.539-2.304-3.072-2.497a6.873 6.873 0 0 0-.855-.031zm.645.937a3.283 3.283 0 0 1 1.44.514c.223.148.537.458.671.662.166.251.26.508.303.82.02.143.01.251-.043.482-.08.345-.332.705-.672.957a3.115 3.115 0 0 1-.689.348c-.382.122-.632.144-1.525.138-.582-.006-.686-.01-.853-.042-.57-.107-1.022-.334-1.35-.68-.264-.28-.385-.535-.45-.946-.03-.192.025-.509.137-.776.136-.326.488-.73.836-.963.403-.269.934-.46 1.422-.512.187-.02.586-.02.773-.002zm-5.503-11a1.653 1.653 0 0 0-.683.298C5.617.74 5.173 1.666 4.985 2.819c-.07.436-.119 1.04-.119 1.503 0 .544.064 1.24.155 1.721.02.107.031.202.023.208a8.12 8.12 0 0 1-.187.152 5.324 5.324 0 0 0-.949 1.02 5.49 5.49 0 0 0-.94 2.339 6.625 6.625 0 0 0-.023 1.357c.091.78.325 1.438.727 2.04l.13.195-.037.064c-.269.452-.498 1.105-.605 1.732-.084.496-.095.629-.095 1.294 0 .67.009.803.088 1.266.095.555.288 1.143.503 1.534.071.128.243.393.264.407.007.003-.014.067-.046.141a7.405 7.405 0 0 0-.548 1.873c-.062.417-.071.552-.071.991 0 .56.031.832.148 1.279L3.42 24h1.478l-.05-.091c-.297-.552-.325-1.575-.068-2.597.117-.472.25-.819.498-1.296l.148-.29v-.177c0-.165-.003-.184-.057-.293a.915.915 0 0 0-.194-.25 1.74 1.74 0 0 1-.385-.543c-.424-.92-.506-2.286-.208-3.451.124-.486.329-.918.544-1.154a.787.787 0 0 0 .223-.531c0-.195-.07-.355-.224-.522a3.136 3.136 0 0 1-.817-1.729c-.14-.96.114-2.005.69-2.834.563-.814 1.353-1.336 2.237-1.475.199-.033.57-.028.776.01.226.04.367.028.512-.041.179-.085.268-.19.374-.431.093-.215.165-.333.36-.576.234-.29.46-.489.822-.729.413-.27.884-.467 1.352-.561.17-.035.25-.04.569-.04.319 0 .398.005.569.04a4.07 4.07 0 0 1 1.914.997c.117.109.398.457.488.602.034.057.095.177.132.267.105.241.195.346.374.43.14.068.286.082.503.045.343-.058.607-.053.943.016 1.144.23 2.14 1.173 2.581 2.437.385 1.108.276 2.267-.296 3.153-.097.15-.193.27-.333.419-.301.322-.301.722-.001 1.053.493.539.801 1.866.708 3.036-.062.772-.26 1.463-.533 1.854a2.096 2.096 0 0 1-.224.258.916.916 0 0 0-.194.25c-.054.109-.057.128-.057.293v.178l.148.29c.248.476.38.823.498 1.295.253 1.008.231 2.01-.059 2.581a.845.845 0 0 0-.044.098c0 .006.329.009.732.009h.73l.02-.074.036-.134c.019-.076.057-.3.088-.516.029-.217.029-1.016 0-1.258-.11-.875-.295-1.57-.597-2.226-.032-.074-.053-.138-.046-.141.008-.005.057-.074.108-.152.376-.569.607-1.284.724-2.228.031-.26.031-1.378 0-1.628-.083-.645-.182-1.082-.348-1.525a6.083 6.083 0 0 0-.329-.7l-.038-.064.131-.194c.402-.604.636-1.262.727-2.04a6.625 6.625 0 0 0-.024-1.358 5.512 5.512 0 0 0-.939-2.339 5.325 5.325 0 0 0-.95-1.02 8.097 8.097 0 0 1-.186-.152.692.692 0 0 1 .023-.208c.208-1.087.201-2.443-.017-3.503-.19-.924-.535-1.658-.98-2.082-.354-.338-.716-.482-1.15-.455-.996.059-1.8 1.205-2.116 3.01a6.805 6.805 0 0 0-.097.726c0 .036-.007.066-.015.066a.96.96 0 0 1-.149-.078A4.857 4.857 0 0 0 12 3.03c-.832 0-1.687.243-2.456.698a.958.958 0 0 1-.148.078c-.008 0-.015-.03-.015-.066a6.71 6.71 0 0 0-.097-.725C8.997 1.392 8.337.319 7.46.048a2.096 2.096 0 0 0-.585-.041Zm.293 1.402c.248.197.523.759.682 1.388.03.113.06.244.069.292.007.047.026.152.041.233.067.365.098.76.102 1.24l.002.475-.12.175-.118.178h-.278c-.324 0-.646.041-.954.124l-.238.06c-.033.007-.038-.003-.057-.144a8.438 8.438 0 0 1 .016-2.323c.124-.788.413-1.501.696-1.711.067-.05.079-.049.157.013zm9.825-.012c.17.126.358.46.498.888.28.854.36 2.028.212 3.145-.019.14-.024.151-.057.144l-.238-.06a3.693 3.693 0 0 0-.954-.124h-.278l-.119-.178-.119-.175.002-.474c.004-.669.066-1.19.214-1.772.157-.623.434-1.185.68-1.382.078-.062.09-.063.159-.012z",fill:n})})}function su({size:e,color:n,label:s="MiniMax"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"minimax-icon","aria-label":s,children:t.jsx("path",{d:"M11.43 3.92a.86.86 0 1 0-1.718 0v14.236a1.999 1.999 0 0 1-3.997 0V9.022a.86.86 0 1 0-1.718 0v3.87a1.999 1.999 0 0 1-3.997 0V11.49a.57.57 0 0 1 1.139 0v1.404a.86.86 0 0 0 1.719 0V9.022a1.999 1.999 0 0 1 3.997 0v9.134a.86.86 0 0 0 1.719 0V3.92a1.998 1.998 0 1 1 3.996 0v11.788a.57.57 0 1 1-1.139 0zm10.572 3.105a2 2 0 0 0-1.999 1.997v7.63a.86.86 0 0 1-1.718 0V3.923a1.999 1.999 0 0 0-3.997 0v16.16a.86.86 0 0 1-1.719 0V18.08a.57.57 0 1 0-1.138 0v2a1.998 1.998 0 0 0 3.996 0V3.92a.86.86 0 0 1 1.719 0v12.73a1.999 1.999 0 0 0 3.996 0V9.023a.86.86 0 1 1 1.72 0v6.686a.57.57 0 0 0 1.138 0V9.022a2 2 0 0 0-1.998-1.997",fill:n})})}function Nw({size:e,color:n,label:s="Z.ai"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"zai-icon","aria-label":s,children:t.jsx("path",{d:"M3 5H21V8.5L7 17.5H21V21H3V17.5L17 8.5H3Z",fill:n})})}function cl({size:e,color:n,label:s="Kimi"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"kimi-icon","aria-label":s,children:t.jsx("path",{d:"M12 3a9 9 0 1 0 9 9c0-.46-.04-.92-.1-1.36a5.39 5.39 0 0 1-4.4 2.26 5.4 5.4 0 0 1-3.14-9.8c.2-.07.4-.1.64-.1z",fill:n})})}function iu({size:e,color:n,label:s="Amazon Bedrock"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"bedrock-icon","aria-label":s,children:t.jsx("path",{d:"M.045 18.02c.072-.116.187-.124.348-.022 2.344 1.476 4.878 2.212 7.607 2.212 1.86 0 3.68-.398 5.453-1.198.386-.168.71-.298.972-.39.26-.092.478-.113.654-.06.176.052.263.2.263.443 0 .222-.12.453-.358.693-.96.962-2.16 1.71-3.592 2.242A12.126 12.126 0 0 1 7.297 23c-2.456 0-4.583-.665-6.378-1.992a.39.39 0 0 1-.098-.096c-.05-.078-.05-.156 0-.234zm6.609-3.26c0-.37.093-.665.282-.886.188-.222.43-.332.727-.332.282 0 .524.105.726.314.2.21.3.498.3.866v4.116c0 .382-.098.676-.294.882-.196.206-.436.31-.72.31-.294 0-.54-.108-.738-.324-.198-.216-.296-.506-.296-.868v-4.078h.014zm-2.986 2.3c0-.376.096-.672.288-.89.192-.216.434-.324.726-.324.292 0 .534.108.726.324.192.218.288.514.288.89v1.778c0 .376-.096.672-.288.89-.192.216-.434.324-.726.324-.292 0-.534-.108-.726-.324-.192-.218-.288-.514-.288-.89v-1.778zm-2.92 1.334c0-.36.09-.65.27-.868.18-.218.42-.328.722-.328s.544.11.73.328c.186.218.278.508.278.868v.444c0 .36-.092.65-.278.868-.186.218-.428.328-.73.328s-.542-.11-.722-.328c-.18-.218-.27-.508-.27-.868v-.444zM21.93 16.4c.804.456 1.39.87 1.758 1.242.368.372.552.7.552.984 0 .208-.102.37-.308.488-.206.118-.462.128-.768.032-.306-.096-.674-.316-1.104-.66a12.728 12.728 0 0 1-1.864-1.75c-1.592.644-3.342.966-5.25.966-1.354 0-2.604-.178-3.752-.534a8.103 8.103 0 0 1-.09-.032l.03.012c-.136-.048.056.022-.042-.014-.04-.016-.04-.016 0 0l.012.004-.012-.004c-.32-.122-.528-.222-.624-.3-.096-.078-.144-.178-.144-.3 0-.098.04-.186.122-.264.082-.078.19-.116.326-.116.076 0 .284.054.624.162 1.078.34 2.264.51 3.558.51 1.642 0 3.194-.286 4.658-.856a17.018 17.018 0 0 1-1.904-3.326c-.416-.94-.726-1.86-.93-2.758-.206-.898-.308-1.728-.308-2.49 0-.664.094-1.194.28-1.592.188-.396.456-.594.804-.594.2 0 .392.074.576.224.184.148.312.354.384.614.1.358.178.758.234 1.198.056.44.084.876.084 1.306 0 .898-.116 1.862-.348 2.894-.232 1.032-.614 2.11-1.146 3.234a16.217 16.217 0 0 0 1.916 1.694z",fill:n})})}function au({size:e,color:n,label:s="xAI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"xai-icon","aria-label":s,children:t.jsx("path",{d:"M2.21 3l7.964 11.386L2.13 21h1.974l6.843-7.07L17.165 21H22.1l-8.392-11.97L21.17 3h-1.974l-6.349 6.56L6.845 3z",fill:n})})}function ru({size:e,color:n,label:s="Opencode"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"opencode-icon","aria-label":s,children:t.jsx("path",{d:"M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6z",fill:n})})}function Ia({size:e,color:n,label:s="Qwen"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"qwen-icon","aria-label":s,children:[t.jsx("circle",{cx:"11",cy:"12",r:"7.5",stroke:n,strokeWidth:"2",fill:"none"}),t.jsx("path",{d:"M14 15 L21 22",stroke:n,strokeWidth:"2.6",strokeLinecap:"round"})]})}function ou({size:e,color:n,label:s="LM Studio"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"lmstudio-icon","aria-label":s,children:[t.jsx("rect",{x:"2",y:"2",width:"20",height:"20",rx:"4.5",fill:n}),t.jsx("text",{x:"12",y:"16",textAnchor:"middle",fontFamily:"-apple-system, system-ui, sans-serif",fontSize:"9.5",fontWeight:"700",fill:"var(--provider-icon-contrast)",letterSpacing:"-0.4",children:"LM"})]})}function dl({size:e,color:n,label:s="Hugging Face"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"huggingface-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"9",fill:n}),t.jsx("circle",{cx:"8.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("circle",{cx:"15.5",cy:"10.5",r:"1.4",fill:"var(--provider-icon-contrast)"}),t.jsx("path",{d:"M7.5 14.5 Q12 18.5 16.5 14.5",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.6",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M3.5 16 Q5 13.5 7 14.5 M20.5 16 Q19 13.5 17 14.5",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"})]})}function lu({size:e,color:n,label:s="Mistral AI"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"mistral-icon","aria-label":s,children:t.jsx("path",{d:"M2 4h3v16H2zM7 4h3v12H7zM12 4h3v16h-3zM17 4h3v8h-3zM7 16h3v4H7zM17 8h3v12h-3z",fill:n})})}function ul({size:e,color:n,label:s="Azure"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"azure-icon","aria-label":s,children:t.jsx("path",{d:"M10.4 3.2 4.5 16.6l3.5.5L13 6 9.6 19.5h9.9zM3 19.5l4.6.6 8.6-1.7-7-1.6z",fill:n})})}function Sw({size:e,color:n,label:s="Cerebras"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"cerebras-icon","aria-label":s,children:[t.jsx("path",{d:"M19.5 6.5A8.5 8.5 0 1 0 19.5 17.5",stroke:n,strokeWidth:"2.4",strokeLinecap:"round",fill:"none"}),t.jsx("path",{d:"M16.5 9A4.6 4.6 0 1 0 16.5 15",stroke:n,strokeWidth:"1.8",strokeLinecap:"round",fill:"none"}),t.jsx("circle",{cx:"11",cy:"12",r:"1.6",fill:n})]})}function Cw({size:e,color:n,label:s="Groq"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"groq-icon","aria-label":s,children:t.jsx("path",{d:"M14 2 4 13h6l-2 9 10-11h-6z",fill:n})})}function cu({size:e,color:n,label:s="Vercel"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"vercel-icon","aria-label":s,children:t.jsx("path",{d:"M12 2 22 21H2z",fill:n})})}function ml({size:e,color:n,label:s="Fireworks AI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"fireworks-icon","aria-label":s,children:[t.jsx("circle",{cx:"12",cy:"12",r:"2.4",fill:n}),t.jsx("circle",{cx:"12",cy:"3.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"12",cy:"20.5",r:"1.4",fill:n}),t.jsx("circle",{cx:"3.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"20.5",cy:"12",r:"1.4",fill:n}),t.jsx("circle",{cx:"6",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"6",r:"1.2",fill:n}),t.jsx("circle",{cx:"6",cy:"18",r:"1.2",fill:n}),t.jsx("circle",{cx:"18",cy:"18",r:"1.2",fill:n}),t.jsx("path",{d:"M12 5.5v3M12 15.5v3M5.5 12h3M15.5 12h3",stroke:n,strokeWidth:"1.4",strokeLinecap:"round"})]})}function Ew({size:e,color:n,label:s="OpenRouter"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"openrouter-icon","aria-label":s,children:t.jsx("path",{d:"M12 2.5a9.5 9.5 0 1 0 9.5 9.5h-2.7a6.8 6.8 0 1 1-2-4.8l-3.1 3.1H22V2.5l-3.2 3.2A9.45 9.45 0 0 0 12 2.5",fill:n})})}function du({size:e,color:n,label:s="GitHub"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"github-icon","aria-label":s,children:t.jsx("path",{d:"M12 0a12 12 0 0 0-3.79 23.39c.6.11.82-.26.82-.58v-2.23c-3.34.73-4.04-1.41-4.04-1.41-.55-1.39-1.34-1.76-1.34-1.76-1.09-.75.08-.74.08-.74 1.2.08 1.84 1.24 1.84 1.24 1.08 1.84 2.82 1.31 3.5 1 .1-.78.42-1.31.77-1.62-2.67-.3-5.47-1.34-5.47-5.95 0-1.31.47-2.38 1.24-3.22-.12-.31-.54-1.56.12-3.24 0 0 1.01-.32 3.3 1.23a11.3 11.3 0 0 1 6 0c2.29-1.55 3.3-1.23 3.3-1.23.66 1.68.24 2.93.12 3.24.77.84 1.24 1.91 1.24 3.22 0 4.62-2.8 5.64-5.48 5.94.43.37.82 1.1.82 2.22v3.29c0 .32.22.69.83.58A12 12 0 0 0 12 0",fill:n})})}function hl({size:e,color:n,label:s="Hermes"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 64 64",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:[t.jsx("rect",{x:"30",y:"10",width:"4",height:"46",rx:"2",fill:n}),t.jsx("path",{d:"M30 18 C24 14, 14 14, 10 18 C14 16, 22 16, 28 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M30 22 C26 19, 18 19, 14 22 C18 20, 24 20, 28 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M34 18 C40 14, 50 14, 54 18 C50 16, 42 16, 36 20",fill:n,opacity:"0.9"}),t.jsx("path",{d:"M34 22 C38 19, 46 19, 50 22 C46 20, 40 20, 36 24",fill:n,opacity:"0.7"}),t.jsx("path",{d:"M32 48 C22 44, 20 38, 26 34 C20 36, 18 42, 24 46 C18 40, 22 30, 30 28 C24 32, 22 38, 28 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round"}),t.jsx("path",{d:"M32 48 C42 44, 44 38, 38 34 C44 36, 46 42, 40 46 C46 40, 42 30, 34 28 C40 32, 42 38, 36 42",fill:"none",stroke:n,strokeWidth:"2.5",strokeLinecap:"round",opacity:"0.8"}),t.jsx("circle",{cx:"32",cy:"10",r:"4",fill:n})]})}function uu({size:e,label:n="OpenClaw"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 16 16",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":n,children:[t.jsx("rect",{width:"16",height:"16",fill:"none"}),t.jsxs("g",{fill:"#3a0a0d",children:[t.jsx("rect",{x:"1",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"2",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"4",y:"10",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"2",width:"6",height:"1"}),t.jsx("rect",{x:"11",y:"2",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"3",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"9",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"8",width:"1",height:"1"}),t.jsx("rect",{x:"14",y:"5",width:"1",height:"3"}),t.jsx("rect",{x:"5",y:"11",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"11",y:"12",width:"1",height:"1"}),t.jsx("rect",{x:"3",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"12",y:"13",width:"1",height:"1"}),t.jsx("rect",{x:"5",y:"14",width:"6",height:"1"})]}),t.jsxs("g",{fill:"#ff4f40",children:[t.jsx("rect",{x:"5",y:"3",width:"6",height:"1"}),t.jsx("rect",{x:"4",y:"4",width:"8",height:"1"}),t.jsx("rect",{x:"3",y:"5",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"6",width:"10",height:"1"}),t.jsx("rect",{x:"3",y:"7",width:"10",height:"1"}),t.jsx("rect",{x:"4",y:"8",width:"8",height:"1"}),t.jsx("rect",{x:"5",y:"9",width:"6",height:"1"}),t.jsx("rect",{x:"5",y:"12",width:"6",height:"1"}),t.jsx("rect",{x:"6",y:"13",width:"4",height:"1"})]}),t.jsxs("g",{fill:"#ff775f",children:[t.jsx("rect",{x:"1",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"2",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"2",y:"7",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"6",width:"2",height:"1"}),t.jsx("rect",{x:"13",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"13",y:"7",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#081016",children:[t.jsx("rect",{x:"6",y:"5",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"5",width:"1",height:"1"})]}),t.jsxs("g",{fill:"#f5fbff",children:[t.jsx("rect",{x:"6",y:"4",width:"1",height:"1"}),t.jsx("rect",{x:"9",y:"4",width:"1",height:"1"})]})]})}function pl({size:e,color:n,label:s="Paperclip"}){return t.jsx("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg",role:"img","aria-label":s,children:t.jsx("path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551",stroke:n,strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round"})})}function mu({size:e,color:n,label:s="Anthropic — via Claude CLI"}){return t.jsxs("svg",{width:e,height:e,viewBox:"0 0 24 24",fill:"none",xmlns:"http://www.w3.org/2000/svg","data-testid":"claude-cli-icon","aria-label":s,children:[t.jsx("g",{transform:"translate(-1 -1.5) scale(0.82)",children:t.jsx("path",{d:"M17.3041 3.541h-3.6718l6.696 16.918H24Zm-10.6082 0L0 20.459h3.7442l1.3693-3.5527h7.0052l1.3693 3.5528h3.7442L10.5363 3.5409Zm-.3712 10.2232 2.2914-5.9456 2.2914 5.9456Z",fill:n})}),t.jsx("rect",{x:"13",y:"13",width:"10",height:"9",rx:"1.5",fill:n}),t.jsx("path",{d:"M15.2 16.2l1.6 1.4-1.6 1.4M18.6 19.6h2.4",stroke:"var(--provider-icon-contrast)",strokeWidth:"1.2",strokeLinecap:"round",strokeLinejoin:"round",fill:"none"})]})}const _w={anthropic:{component:jw,color:"var(--provider-anthropic)"},"claude-cli":{component:mu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:mu,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:nu,color:"var(--provider-openai)"},"openai-codex":{component:nu,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Bs,color:"var(--provider-gemini)"},gemini:{component:Bs,color:"var(--provider-gemini)"},"google-antigravity":{component:Bs,color:"var(--provider-gemini)",label:"Google Gemini"},antigravity:{component:Bs,color:"var(--provider-gemini)",label:"Google Gemini"},"google-vertex":{component:Bs,color:"var(--provider-gemini)",label:"Google Vertex AI"},vertex:{component:Bs,color:"var(--provider-gemini)",label:"Google Vertex AI"},"google-cloud-code":{component:Bs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"cloud-code":{component:Bs,color:"var(--provider-gemini)",label:"Google Cloud Code"},"google-gemini-cli":{component:Bs,color:"var(--provider-gemini)",label:"Google Gemini CLI"},"google-generative-ai":{component:Bs,color:"var(--provider-gemini)",label:"Google Generative AI"},ollama:{component:ww,color:"var(--text)"},github:{component:du,color:"var(--text)"},"github-copilot":{component:du,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:Ew,color:"var(--provider-openrouter)"},minimax:{component:su,color:"var(--provider-minimax)"},"minimax-cn":{component:su,color:"var(--provider-minimax)",label:"MiniMax (CN)"},zai:{component:Nw,color:"var(--provider-zai)"},kimi:{component:cl,color:"var(--provider-kimi)"},moonshot:{component:cl,color:"var(--provider-kimi)"},"kimi-coding":{component:cl,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:iu,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:iu,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:au,color:"var(--text)"},grok:{component:au,color:"var(--text)",label:"xAI"},opencode:{component:ru,color:"var(--provider-opencode)"},"opencode-go":{component:ru,color:"var(--provider-opencode)",label:"Opencode (Go)"},qwen:{component:Ia,color:"var(--provider-qwen)"},"qwen-ai":{component:Ia,color:"var(--provider-qwen)",label:"Qwen"},"qwen-coder":{component:Ia,color:"var(--provider-qwen)",label:"Qwen Coder"},alibaba:{component:Ia,color:"var(--provider-qwen)",label:"Qwen"},tongyi:{component:Ia,color:"var(--provider-qwen)",label:"Qwen"},lmstudio:{component:ou,color:"var(--provider-lmstudio)",label:"LM Studio"},"lm-studio":{component:ou,color:"var(--provider-lmstudio)",label:"LM Studio"},huggingface:{component:dl,color:"var(--provider-huggingface)",label:"Hugging Face"},"hugging-face":{component:dl,color:"var(--provider-huggingface)",label:"Hugging Face"},hf:{component:dl,color:"var(--provider-huggingface)",label:"Hugging Face"},mistral:{component:lu,color:"var(--provider-mistral)",label:"Mistral AI"},"mistral-ai":{component:lu,color:"var(--provider-mistral)",label:"Mistral AI"},azure:{component:ul,color:"var(--provider-azure)"},"azure-openai":{component:ul,color:"var(--provider-azure)",label:"Azure OpenAI"},"azure-openai-responses":{component:ul,color:"var(--provider-azure)",label:"Azure OpenAI"},fireworks:{component:ml,color:"var(--provider-fireworks)",label:"Fireworks AI"},"fireworks-ai":{component:ml,color:"var(--provider-fireworks)",label:"Fireworks AI"},fireworksai:{component:ml,color:"var(--provider-fireworks)",label:"Fireworks AI"},cerebras:{component:Sw,color:"var(--provider-cerebras)"},groq:{component:Cw,color:"var(--provider-groq)"},vercel:{component:cu,color:"var(--provider-vercel)"},"vercel-ai-gateway":{component:cu,color:"var(--provider-vercel)",label:"Vercel AI Gateway"},hermes:{component:hl,color:"var(--provider-hermes)",label:"Hermes"},"hermes-agent":{component:hl,color:"var(--provider-hermes)",label:"Hermes"},hermesagent:{component:hl,color:"var(--provider-hermes)",label:"Hermes"},openclaw:{component:uu,color:"var(--provider-openclaw)",label:"OpenClaw"},"open-claw":{component:uu,color:"var(--provider-openclaw)",label:"OpenClaw"},paperclip:{component:pl,color:"var(--provider-paperclip)",label:"Paperclip"},paperclipai:{component:pl,color:"var(--provider-paperclip)",label:"Paperclip"},"paperclip-ai":{component:pl,color:"var(--provider-paperclip)",label:"Paperclip"}};function An({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=_w[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=kw[n];return t.jsx("span",{className:"provider-icon",style:{color:o},"data-provider":s,children:r?t.jsx(r,{size:c,color:o,label:l}):t.jsx(tx,{size:c})})}const js={data:new Map,pendingPromise:null,lastFetchTime:null},Mw=5e3;function ao(e,n){return n?`${n}::${e}`:e}function Aw(e,n){const s=js.data.get(ao(e,n));if(!(!s||Date.now()-s.timestamp>Mw))return s}function Rw(e){const[n,s]=a.useState(!1),i=a.useRef(null),r=a.useCallback(async c=>{let d=null;for(let m=0;m<3;m++)try{return await hy(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=ke(h);if(g?.includes("429")||g?.toLowerCase().includes("rate limit")){const p=Math.min(1e3*Math.pow(2,m),3e4);await new Promise(f=>setTimeout(f,p));continue}break}if(d)throw d;return{}},[e]),o=a.useCallback(async c=>{if(c.length===0)return;const d=Date.now()-5e3;if(c.every(g=>{const p=js.data.get(ao(g,e));return p&&p.timestamp>d})&&js.lastFetchTime&&js.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),js.pendingPromise){s(!0);try{await js.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);js.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,x]of Object.entries(g))js.data.set(ao(f,e),{result:x,timestamp:p});js.lastFetchTime=p}catch{}finally{js.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>js.data.get(ao(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:js.lastFetchTime,getBatchData:l}}const Sc=new Map,Tw=3e4;function kp(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function Pw(e,n,s,i){const r=kp(e,n,s,i),o=Sc.get(r);return o?Date.now()>o.expiresAt?(Sc.delete(r),null):o.stats:null}function Iw(e,n,s,i,r){const o=kp(e,n,s,i);Sc.set(o,{stats:r,expiresAt:Date.now()+Tw})}function $w(e,n,s,i,r={}){const o=r.enabled??!0,l=r.worktree,c=r.stepVersion,u=r.pollIntervalMs,[d,m]=a.useState(null),[h,g]=a.useState(!1);return a.useEffect(()=>{if(!o){m(null),g(!1);return}const p=n==="done"&&!!s,f=(n==="in-progress"||n==="in-review")&&!!l;if(!e||!p&&!f){m(null),g(!1);return}const x=f?l:void 0,v=c!==void 0?String(c):void 0;let b=!1;async function y(k=!1){if(!k){const R=Pw(e,i,x,v);if(R){b||(m(R),g(!1));return}}g(!0);try{const R=await lp(e,x,i);b||(m(R.stats),Iw(e,i,x,v,R.stats))}catch{b||m(null)}finally{b||g(!1)}}y();let S;return u&&f&&(S=setInterval(()=>{y(!0)},u)),()=>{b=!0,S&&clearInterval(S)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const Dw=new Set(["failed","stuck-killed"]);function vo(e,n,s){if(e.column!=="in-progress"||e.status&&Dw.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Lw(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function zw(e){return e==="done"||e==="skipped"}function Fw(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function jp(e,n){const s=(e.steps??[]).map((u,d)=>({id:`step-${d}`,name:u.name,status:u.status,source:"step",phase:"pre-merge"})),i=new Map((e.workflowStepResults??[]).map(u=>[u.workflowStepId,u])),r=(e.enabledWorkflowSteps??[]).map(u=>{const d=i.get(u);return{id:`workflow-${u}`,name:Fw(u,d,n),status:d?Lw(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>zw(u.status)).length;return{total:l,completed:c,items:o}}function Ow(e){return(e.action||e.outcome||"").replace(/^\[timing\]\s*/i,"").replace(/^\[[^\]]+\]\s*/i,"").replace(/\s+in\s+\d+(?:\.\d+)?ms\b/i,"").replace(/\s+after\s+\d+(?:\.\d+)?ms\b/i,"").trim()||"Timing event"}function wp(e){return e.filter(n=>{const s=typeof n.action=="string"?n.action:"",i=typeof n.outcome=="string"?n.outcome:"";return s.includes("[timing]")||i.includes("[timing]")}).map(n=>{const i=`${n.action??""}
|
|
@@ -653,4 +653,4 @@ Delete anyway by removing these dependency references first?`,danger:!0}))return
|
|
|
653
653
|
\x1B[33m[Process exited with code ${ue}]\x1B[0m\r
|
|
654
654
|
`))});return()=>{Je(),$e(),de(),re()}},[u,q?.sessionId,q?.id,q,le,Ee,Ze,Fe,Ke,U]),a.useEffect(()=>{le==="connected"&&s&&W.current!==s&&q&&(W.current=s,setTimeout(()=>{ve(s+`
|
|
655
655
|
`)},500))},[le,s,ve,q,g]),a.useEffect(()=>{if(!u||!P.current)return;P.current.options.fontSize=y,E.current!==null&&(cancelAnimationFrame(E.current),E.current=null);const he=requestAnimationFrame(()=>{E.current=null,it()});return E.current=he,()=>{E.current===he&&(cancelAnimationFrame(he),E.current=null)}},[y,u,it]),a.useEffect(()=>{if(!e)return;const he=Re=>{if(!(!Re.ctrlKey&&!Re.metaKey)){if(Re.code==="Equal"||Re.code==="NumpadAdd"){Re.preventDefault(),S(Je=>nr(Je+1));return}if(Re.code==="Minus"||Re.code==="NumpadSubtract"){Re.preventDefault(),S(Je=>nr(Je-1));return}if(Re.code==="Digit0"||Re.code==="Numpad0"){Re.preventDefault(),S(tr);return}}};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e,it]),a.useEffect(()=>{if(!e)return;const he=Re=>{Re.key==="Escape"&&n()};return document.addEventListener("keydown",he),()=>document.removeEventListener("keydown",he)},[e,n]),a.useEffect(()=>{le==="connected"&&P.current&&setTimeout(()=>{if(!P.current||!C.current)return;const he=C.current.querySelector(".xterm-helper-textarea");he&&he.focus();try{C.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[le]);const Ie=a.useCallback(()=>{if(!C.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;P.current?.focus();const Re=C.current.querySelector(".xterm-helper-textarea");if(!Re)return;Re.autocapitalize="off",Re.autocomplete="off",Re.autocorrect="off",Re.spellcheck=!1,Re.setAttribute("inputmode","text");try{Re.focus({preventScroll:!0})}catch{Re.focus()}const Je=Re.value.length;Re.setSelectionRange(Je,Je)},[]);a.useEffect(()=>Qe(()=>{P.current?.clear(),c(null),W.current=!1,P.current&&(P.current.dispose(),P.current=null),F.current=null,$.current=!1,O.current&&(window.removeEventListener("resize",O.current),O.current=null),d(!1),h(null),xe().catch(Re=>{console.error("Failed to replace invalid terminal session:",Re)})}),[Qe,xe]);const Ge=a.useCallback(he=>{he.target===he.currentTarget&&(A.current=!0)},[]),se=a.useCallback(he=>{A.current&&he.target===he.currentTarget&&n(),A.current=!1},[n]),ye=a.useCallback(()=>{P.current?.clear()},[]),Z=a.useCallback(async()=>{P.current?.clear(),c(null),W.current=!1;try{await Ne()}catch(he){o(ke(he)||"Failed to restart terminal session")}},[Ne]),Te=a.useCallback(()=>{P.current&&(P.current.dispose(),P.current=null),F.current=null,$.current=!1,O.current&&(window.removeEventListener("resize",O.current),O.current=null),h(null),d(!1)},[]),ze=a.useCallback(()=>{window.location.reload()},[]),be=a.useCallback(()=>{S(he=>nr(he+1))},[]),Me=a.useCallback(()=>{S(he=>nr(he-1))},[]),Be=a.useCallback(he=>{M(Re=>Re===he?null:he)},[]),lt=a.useCallback(he=>{if(N==="ctrl"){ve(CA(he)),M(null);return}if(N==="alt"){ve(EA(he)),M(null);return}ve(he)},[ve,N]),je=a.useCallback(he=>{ve(he),M(null)},[ve]);if(!e)return null;const ie=()=>{switch(le){case"connected":return t.jsx("span",{className:"terminal-status connected",title:"Connected"});case"connecting":case"reconnecting":return t.jsx("span",{className:"terminal-status connecting",title:"Connecting..."});case"disconnected":return t.jsx("span",{className:"terminal-status disconnected",title:"Disconnected"});default:return null}},Ae=!G||!q&&!me;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Ge,onMouseUp:se,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:z,className:"modal terminal-modal","data-testid":"terminal-modal",style:f>0?{"--keyboard-overlap":`${f}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[w.map(he=>t.jsxs("div",{className:`terminal-tab ${he.isActive?"terminal-tab--active":""}`,onClick:()=>pe(he.id),title:he.title,role:"tab","aria-selected":he.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:he.title}),w.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Re=>{Re.stopPropagation(),ae(he.id)},title:"Close tab",children:"×"})]},he.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:ce,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ri,{size:16}),ie()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[le==="disconnected"&&q&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Xe,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(Nn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Z,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(Nn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:ye,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Xt,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:()=>R(he=>!he),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":k,children:[t.jsx(Hx,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Shortcuts"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(Ot,{size:20})})]})]}),r&&t.jsx("div",{className:"terminal-error","data-testid":"terminal-error",children:r}),t.jsxs("div",{className:"terminal-container","data-testid":"terminal-container",children:[Ae&&!me&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),me&&!q&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-bootstrap-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Failed to start terminal: ",me]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:ne,"data-testid":"terminal-retry-btn",children:[t.jsx(Nn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:ze,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(Nn,{size:14}),"Refresh page"]})]})]})}),m&&q&&t.jsx("div",{className:"terminal-loading","data-testid":"terminal-xterm-init-error",children:t.jsxs("div",{className:"terminal-error-content",children:[t.jsxs("span",{children:["Terminal UI failed to initialize: ",m]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Te,"data-testid":"terminal-reinit-btn",children:[t.jsx(Nn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:ze,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(Nn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:C,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Ie,onTouchStart:Ie},q?.sessionId)]}),k&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Be("ctrl"),"aria-pressed":N==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${N==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Be("alt"),"aria-pressed":N==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>je("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>je(" "),children:"Tab"})]}),_A.map(he=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>lt(he.key),title:he.description,children:he.label},he.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${le}`,children:[le==="connected"&&"Connected",le==="connecting"&&"Connecting...",le==="reconnecting"&&"Reconnecting...",le==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:Me,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(lb,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:be,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx(Zt,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const Va={name:"",command:""};function nh(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function DA(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function LA({isOpen:e,onClose:n,addToast:s,projectId:i,onRunScript:r}){const[o,l]=a.useState({}),[c,u]=a.useState(!0),[d,m]=a.useState(!1),[h,g]=a.useState(null),[p,f]=a.useState(Va),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,k]=a.useState(null),R=wi(n),N=a.useCallback(async()=>{try{u(!0);const I=await hr(i);l(I)}catch(I){s(ke(I)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&N()},[e,N]);const M=a.useCallback(()=>{m(!0),g(null),f(Va),k(null)},[]),C=a.useCallback((I,O)=>{g(I),m(!1),f({name:I,command:O}),k(null)},[]),z=a.useCallback(()=>{g(null),m(!1),f(Va),k(null)},[]),A=a.useCallback(I=>{f(O=>({...O,name:I})),I&&!nh(I)?k("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):k(null)},[]),P=a.useCallback(async()=>{const I=p.name.trim(),O=p.command.trim();if(!I){s("Script name is required","error");return}if(!nh(I)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!O){s("Script command is required","error");return}v(!0);try{await fk(I,O,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Va),k(null),await N()}catch(J){const Q=ke(J);Q?.includes("already exists")?s("A script with this name already exists","error"):s(Q||"Failed to save script","error")}finally{v(!1)}},[p,h,s,N,i]),F=a.useCallback(async I=>{try{await gk(I,i),s("Script deleted","success"),y(null),h===I&&(g(null),f(Va)),await N()}catch(O){s(ke(O)||"Failed to delete script","error")}},[h,s,N,i]),W=a.useCallback((I,O)=>{r&&r(I,O)},[r]);if(!e)return null;const $=d||h!==null,_=Object.entries(o).map(([I,O])=>({name:I,command:O}));return t.jsx("div",{className:"modal-overlay open",...R,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(ri,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(ot,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):$?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:I=>A(I.target.value),placeholder:"e.g., build, test, lint",disabled:x||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:I=>f(O=>({...O,command:I.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:x,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:z,disabled:x,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:P,disabled:x||!!S,"data-testid":"script-save-btn",children:x?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:_.length===0?"No scripts defined":`${_.length} script${_.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:M,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Zt,{size:14}),"Add Script"]})]}),_.length===0?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)",fontSize:"14px",border:"1px dashed var(--border)",borderRadius:"8px"},"data-testid":"empty-state",children:[t.jsx(ri,{size:32,style:{margin:"0 auto 12px",opacity:.5}}),t.jsx("div",{children:"No scripts defined yet."}),t.jsx("div",{style:{marginTop:"4px",fontSize:"12px"},children:"Add scripts to quickly run common commands from the dashboard."})]}):t.jsx("div",{className:"scripts-modal-list",style:{display:"flex",flexDirection:"column",gap:"8px"},children:_.map(I=>t.jsx("div",{className:"script-card","data-testid":`script-${I.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:I.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:I.command,children:DA(I.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:()=>W(I.name,I.command),title:"Run script","aria-label":`Run ${I.name}`,"data-testid":`run-script-${I.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(xn,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>C(I.name,I.command),title:"Edit","aria-label":`Edit ${I.name}`,"data-testid":`edit-script-${I.name}`,children:t.jsx(Zt,{size:14,style:{transform:"rotate(45deg)"}})}),b===I.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>F(I.name),title:"Confirm delete","aria-label":`Confirm delete ${I.name}`,"data-testid":`confirm-delete-script-${I.name}`,style:{color:"var(--color-error)"},children:t.jsx(Xt,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${I.name}`,children:t.jsx(Ot,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(I.name),title:"Delete","aria-label":`Delete ${I.name}`,"data-testid":`delete-script-${I.name}`,children:t.jsx(Xt,{size:14})})]})]})},I.name))})]})})]})})}function zA(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState("."),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(0),p=a.useCallback(()=>{g(x=>x+1)},[]),f=a.useCallback(x=>{l(x),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let x=!1;async function v(){u(!0),m(null);try{const b=await Ty(e,o==="."?void 0:o,s);x||r(b.entries)}catch(b){x||(m(ke(b)||"Failed to load files"),r([]))}finally{x||u(!1)}}return v(),()=>{x=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:f,loading:c,error:d,refresh:p}}function FA(e,n,s,i){const[r,o]=a.useState(""),[l,c]=a.useState(""),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(!1),[f,x]=a.useState(null),v=a.useCallback(S=>{o(S),x(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),x(null);return}let S=!1;async function k(){h(!0),x(null);try{const R=await Py(e,n,i);S||(o(R.content),c(R.content),d(R.mtime))}catch(R){S||(x(ke(R)||"Failed to load file"),o(""),c(""),d(null))}finally{S||h(!1)}}return k(),()=>{S=!0}},[e,n,s,i]);const b=r!==l,y=a.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),x(null);try{const S=await Iy(e,n,r,i);c(r),d(S.mtime)}catch(S){throw x(ke(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:y,hasChanges:b,mtime:u}}const OA=1e4;function UA(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function BA(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function HA(e){const[n,s]=a.useState("Project Root"),[i,r]=a.useState([]),[o,l]=a.useState(!0),[c,u]=a.useState(null);return a.useEffect(()=>{let d=!1;async function m(){try{const g=await Ry(e);if(d)return;s(UA(g.project)),r(g.tasks.map(BA)),u(null)}catch(g){d||u(ke(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},OA);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function qA(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function VA(e){return e?new Date(e).toLocaleDateString():""}function sh(e,n){return e==="."?n:`${e}/${n}`}const Wa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Xl={type:null,entry:null,entryFullPath:""},WA=200,KA=500,ih=10;function GA({x:e,y:n,entry:s,onAction:i,onClose:r}){const o=a.useRef(null),[l,c]=a.useState({x:e,y:n});a.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),g=window.visualViewport,p=g?.width&&g.width>0?g.width:window.innerWidth,f=g?.height&&g.height>0?g.height:window.innerHeight,x=g?.offsetLeft??0,v=g?.offsetTop??0,b=8;let y=e-x,S=n-v;y+h.width>p-b&&(y=p-b-h.width),S+h.height>f-b&&(S=f-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+x,y:S+v})},[e,n]),a.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const u=s.type==="directory",d=[{id:"copy",label:"Copy",icon:Fi,disabled:!1},{id:"move",label:"Move",icon:ub,disabled:!1},{id:"rename",label:"Rename",icon:Yn,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Mo,disabled:!1}]:[{id:"download",label:"Download",icon:sx,disabled:!1}],{id:"divider",label:"",icon:Fi,disabled:!0},{id:"delete",label:"Delete",icon:Xt,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:o,className:"file-browser-context-menu",role:"menu","aria-label":"File operations",style:{left:l.x,top:l.y},onClick:m=>m.stopPropagation(),children:d.map(m=>m.id==="divider"?t.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):t.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${m.disabled?"file-browser-context-menu__disabled":""} ${m.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:m.disabled,onClick:()=>i(m.id),children:[t.jsx(m.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:m.label})]},m.id))})})}function JA({type:e,entry:n,entryFullPath:s,onConfirm:i,onCancel:r,loading:o,error:l}){const c=a.useRef(null),u=e==="rename"?n.name:"",[d,m]=a.useState(u);a.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),a.useEffect(()=>{if(e==="rename"&&c.current){const f=n.name.lastIndexOf(".");f>0?c.current.setSelectionRange(0,f):c.current.select()}},[e,n.name]);const h=f=>{f.key==="Enter"&&d.trim()&&i(d.trim()),f.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>i(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:f=>f.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:d,onChange:f=>m(f.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>i(d.trim()),disabled:o||!d.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function YA({entries:e,currentPath:n,onSelectFile:s,onNavigate:i,loading:r,error:o,onRetry:l,workspace:c,onRefresh:u,projectId:d}){const[m,h]=a.useState(Wa),[g,p]=a.useState(Xl),[f,x]=a.useState(!1),[v,b]=a.useState(null),[y,S]=a.useState(!1),[k,R]=a.useState(null),N=a.useRef(null),M=a.useRef(null),C=a.useRef(null),z=a.useRef(!1),A=a.useCallback(()=>{N.current!==null&&(window.clearTimeout(N.current),N.current=null),M.current!==null&&(window.clearTimeout(M.current),M.current=null)},[]),P=a.useCallback(()=>{A(),C.current=null,S(!1),R(null)},[A]);a.useEffect(()=>()=>{A()},[A]);const F=a.useCallback((D,T,w,q)=>{h({visible:!0,x:D,y:T,entry:w,entryFullPath:q})},[]),W=a.useCallback((D,T,w)=>{if(D.touches.length!==1)return;const q=D.touches[0];q&&(P(),C.current={x:q.clientX,y:q.clientY},M.current=window.setTimeout(()=>{S(!0),R(w)},WA),N.current=window.setTimeout(()=>{const G=C.current;G&&(z.current=!0,S(!1),R(null),A(),F(G.x,G.y,T,w))},KA))},[P,A,F]),$=a.useCallback(D=>{const T=C.current,w=D.touches[0];!T||!w||(Math.abs(w.clientX-T.x)>ih||Math.abs(w.clientY-T.y)>ih)&&P()},[P]),_=a.useCallback(()=>{P()},[P]);a.useEffect(()=>{if(!m.visible)return;const D=document.querySelector(".file-browser-list"),T=()=>{z.current=!1,P(),h(Wa)};return D?.addEventListener("scroll",T),()=>D?.removeEventListener("scroll",T)},[P,m.visible]),a.useEffect(()=>{if(!m.visible)return;const D=T=>{T.key==="Escape"&&(z.current=!1,h(Wa))};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[m.visible]);const I=a.useCallback((D,T)=>{D.preventDefault(),D.stopPropagation(),P(),z.current=!1,F(D.clientX,D.clientY,T,sh(n,T.name))},[P,n,F]),O=a.useCallback(D=>{if(!m.entry)return;z.current=!1;const T=m.entry,w=m.entryFullPath;if(h(Wa),D==="download"){if(!c)return;const q=tp(c,w,d);window.open(Qs(q),"_blank");return}if(D==="download-zip"){if(!c)return;const q=Oy(c,w,d);window.open(Qs(q),"_blank");return}p({type:D,entry:T,entryFullPath:w}),b(null)},[m,c,d]),J=a.useCallback(async D=>{if(!(!g.type||!g.entry||!c)){x(!0),b(null);try{switch(g.type){case"copy":await Dy(c,g.entryFullPath,D,d);break;case"move":await Ly(c,g.entryFullPath,D,d);break;case"rename":await Fy(c,g.entryFullPath,D,d);break;case"delete":await zy(c,g.entryFullPath,d);break}p(Xl),u?.()}catch(T){b(ke(T)||"Operation failed")}finally{x(!1)}}},[g,c,u,d]),Q=a.useCallback(()=>{p(Xl),b(null)},[]),E=a.useCallback((D,T)=>{if(z.current){z.current=!1;return}m.visible||(D.type==="directory"?i(T):s(T))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(ot,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{const D=n.split("/").filter(Boolean);D.pop(),i(D.length===0?".":D.join("/"))},children:[t.jsx(hn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":n})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(D=>{const T=sh(n,D.name),w=y&&k===T;return t.jsxs("div",{className:`file-node file-node--${D.type} ${w?"file-node--long-pressing":""}`,onClick:()=>E(D,T),onContextMenu:q=>I(q,D),onTouchStart:q=>W(q,D,T),onTouchMove:$,onTouchEnd:_,onTouchCancel:_,children:[t.jsx("div",{className:"file-node-icon",children:D.type==="directory"?t.jsx(In,{size:16}):t.jsx(Bh,{size:16})}),t.jsx("div",{className:"file-node-name",children:D.name}),D.type==="file"&&D.size!==void 0&&t.jsx("div",{className:"file-node-size",children:qA(D.size)}),D.mtime&&t.jsx("div",{className:"file-node-time",children:VA(D.mtime)})]},D.name)})}),m.visible&&m.entry&&t.jsx(GA,{x:m.x,y:m.y,entry:m.entry,onAction:O,onClose:()=>{z.current=!1,h(Wa)}}),g.type&&g.entry&&t.jsx(JA,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:J,onCancel:Q,loading:f,error:v})]})}function QA(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function XA({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=QA(i),d=u&&(s?!0:r),m=a.useCallback(()=>{o(!1)},[]),h=a.useCallback(()=>{o(!0)},[]),g=a.useCallback(()=>{c(p=>!p)},[]);return t.jsxs("div",{className:"file-editor-container",children:[u?t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsxs("div",{className:"file-editor-mode-toggle",children:[!s&&t.jsxs("button",{className:`btn btn-sm ${d?"":"btn-primary"}`,onClick:m,disabled:!d,"aria-label":"Edit mode",children:[t.jsx(Uh,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(da,{size:14}),"Preview"]})]}),!s&&t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(ho,{size:14})})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsx("button",{className:`btn btn-sm ${l?"btn-primary":""}`,onClick:g,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(ho,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(ci,{remarkPlugins:[di],children:e})}):t.jsx("textarea",{className:`file-editor-textarea ${l?"file-editor-textarea--wrap":""}`,value:e,onChange:p=>n(p.target.value),readOnly:s,spellCheck:!1,"aria-label":i?`Editor for ${i}`:"File editor"})]})}function ZA(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function eR({currentWorkspace:e,projectName:n,workspaces:s,onSelect:i}){const[r,o]=a.useState(!1),l=a.useMemo(()=>e==="project"?n||"Project Root":s.find(u=>u.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(Ed,{size:14}):t.jsx(fc,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(qt,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{i("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Ed,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{i(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(fc,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:ZA(c.title)})]},c.id))]})]})]})}const tR=768,Kf=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),nR=new Set([...Kf,".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 ah(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return nR.has(n)}function sR(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Kf.has(n)}function iR({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=HA(i),l=a.useRef(null);Xs(l,!0,"fusion:files-modal-size");const c=wi(n),[u,d]=a.useState(e),[m,h]=a.useState(null),[g,p]=a.useState(!1),[f,x]=a.useState("list"),{entries:v,currentPath:b,setPath:y,loading:S,error:k,refresh:R}=zA(u,!0,i),{content:N,setContent:M,originalContent:C,loading:z,saving:A,error:P,save:F,hasChanges:W,mtime:$}=FA(u,m,!0,i);a.useEffect(()=>{d(e)},[e]),a.useEffect(()=>{const w=()=>{p(window.innerWidth<=tR)};return w(),window.addEventListener("resize",w),()=>window.removeEventListener("resize",w)},[]),a.useEffect(()=>{m||x("list")},[m]),a.useEffect(()=>{const w=q=>{q.key==="Escape"&&n(),(q.metaKey||q.ctrlKey)&&q.key==="s"&&(q.preventDefault(),W&&!A&&F())};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[n,W,A,F]);const _=a.useCallback(w=>{h(w),g&&x("editor")},[g]),I=a.useCallback(()=>{x("list")},[]),O=a.useCallback(()=>{M(C)},[C,M]),J=a.useCallback(w=>{d(w),h(null),x("list"),s?.(w)},[s]),E=`Files — ${a.useMemo(()=>u==="project"?"Project":o.find(w=>w.id===u)?.id??u,[u,o])}`,D=a.useMemo(()=>!m||!sR(m)?null:tp(u,m,i),[m,u,i]),T=w=>{const q=new Blob([w]).size;return q<1024?`${q} B`:`${(q/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...c,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:l,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(In,{size:18}),t.jsx("span",{children:E}),m&&t.jsx("span",{className:"file-browser-header-path",children:m})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(eR,{currentWorkspace:u,projectName:r,workspaces:o,onSelect:J}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ot,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${g?"mobile":""} ${f==="list"?"active":""}`,children:t.jsx(YA,{entries:v,currentPath:b,onSelectFile:_,onNavigate:y,loading:S,error:k,onRetry:R,workspace:u,onRefresh:R,projectId:i})}),t.jsx("div",{className:`file-browser-content ${g?"mobile":""} ${f==="editor"?"active":""}`,children:m?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[g&&f==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:I,"aria-label":"Back to file list",children:[t.jsx(wa,{size:16}),t.jsx("span",{children:"Back"})]}),m,ah(m)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(jx,{size:12}),"Binary file — read only"]}),$&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date($).toLocaleString()]}),z&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!D&&W&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:O,disabled:A,children:[t.jsx(wb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void F(),disabled:A,children:[t.jsx(Kh,{size:14}),A?"Saving...":"Save"]})]})})]}),P&&!D&&t.jsx("div",{className:"file-browser-error-banner",children:P}),D?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:D,alt:m??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(XA,{content:N,onChange:M,filePath:m,readOnly:ah(m)})}),!D&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:T(N)}),W&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(In,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function aR(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[i,r]=a.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=a.useRef(null),l=a.useRef(null),c=a.useCallback(async(d=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,d&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await Gv();r({providers:m,loading:!1,error:null,lastUpdated:new Date})}catch(m){if(m instanceof Error&&m.name==="AbortError")return;r(h=>({...h,loading:!1,error:ke(m)||"Failed to fetch usage data"}))}},[]);a.useEffect(()=>{c()},[c]),a.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),a.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const u=a.useCallback(()=>c(!0),[c]);return{providers:i.providers,loading:i.loading,error:i.error,lastUpdated:i.lastUpdated,refresh:u}}function rR(e){const n=new Date(e),s=new Date,i=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return i;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${i}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${i}`}function oR(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Gf="kb-usage-hidden-windows";function rh(e){const n=Dn(Gf,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((i,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(i[r]=l)}return i},{})}catch{return{}}}function lR(e,n){os(Gf,JSON.stringify(e),n)}function Jf(e,n,s){return s[e]?.includes(n)??!1}function cR({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=oR(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?d=`resets in ${y}d ${S}h`:y>0?d=`resets in ${y}d`:b>0?d=`resets in ${b}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let g=0;h&&(g=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",f=m?.status==="behind",x=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(da,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${g}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:u}),t.jsxs("span",{className:"usage-window-reset-group",children:[d&&t.jsx("span",{className:"usage-window-reset",children:d}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:rR(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(Yc,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),f&&t.jsxs(t.Fragment,{children:[t.jsx(Vb,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),x&&t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function dR(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 uR({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r}){const o=s[e.name]?.length??0,l=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:"usage-provider","data-provider":e.name,"data-status":e.status,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(An,{provider:dR(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),o>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",o,")"]})]}),t.jsx("div",{className:"usage-provider-actions",children:l()})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((c,u)=>{const d=Jf(e.name,c.label,s);return t.jsx(cR,{window:c,viewMode:n,isHidden:d,onToggleHidden:()=>i(e.name,c.label)},`${e.name}-${c.label}-${u}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function mR(){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 hR({isOpen:e,onClose:n,projectId:s,anchorRect:i}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:u}=aR({autoRefresh:e}),[d,m]=a.useState(!1),[h,g]=a.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,f]=a.useState("used"),[x,v]=a.useState(()=>rh(s)),b=a.useRef(null),y=a.useRef(e),S=a.useRef(!1);a.useEffect(()=>{e||(S.current=!1)},[e]),a.useEffect(()=>{r.length>0&&(S.current=!0)},[r.length]),a.useEffect(()=>{if(typeof window>"u")return;const _=()=>{g(window.innerWidth>=769)};return window.addEventListener("resize",_),()=>window.removeEventListener("resize",_)},[]),a.useEffect(()=>{!y.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&u(),y.current=e},[e,c,u]),a.useEffect(()=>{const _=Dn("kb-usage-view-mode",s);if(_==="used"||_==="remaining"){f(_);return}f("used")},[s]);const k=a.useCallback(_=>{f(_),os("kb-usage-view-mode",_,s)},[s]);a.useEffect(()=>{v(rh(s))},[s]),a.useEffect(()=>{lR(x,s)},[x,s]);const R=a.useCallback((_,I)=>{v(O=>{if(Jf(_,I,O)){const J=(O[_]??[]).filter(Q=>Q!==I);if(J.length===0){const{[_]:Q,...E}=O;return E}return{...O,[_]:J}}return{...O,[_]:[...O[_]??[],I]}})},[]),N=a.useCallback(_=>{v(I=>{if(!I[_])return I;const{[_]:O,...J}=I;return J})},[]),M=a.useCallback(async()=>{m(!0),await u(),m(!1)},[u]);a.useEffect(()=>{if(!e)return;const _=I=>{I.key==="Escape"&&n()};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n]);const C=a.useCallback(_=>{_.target===_.currentTarget&&n()},[n]);if(!e)return null;const z=!!(i&&h),F=z?Math.min((i?.bottom??0)+8,window.innerHeight-12):void 0,W=z?Math.max(window.innerWidth-(i?.right??0),0):void 0,$=t.jsxs("div",{className:`usage-modal${z?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:z?{position:"fixed",top:F,right:W}:void 0,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Cs,{size:18,className:"usage-header-icon"}),t.jsx("h3",{children:"Usage"})]}),t.jsxs("div",{className:"usage-header-actions",children:[t.jsxs("div",{className:"usage-view-toggle",role:"group","aria-label":"Usage view mode",children:[t.jsx("button",{className:`usage-view-toggle-btn ${p==="used"?"active":""}`,onClick:()=>k("used"),"aria-pressed":p==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${p==="remaining"?"active":""}`,onClick:()=>k("remaining"),"aria-pressed":p==="remaining","data-testid":"usage-view-toggle-remaining",children:"Remaining"})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close usage modal","data-testid":"usage-modal-close",children:t.jsx(Ot,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:b,children:(o||!S.current&&!l)&&r.length===0?t.jsx(mR,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:M,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:r.map(_=>t.jsx(uR,{provider:_,viewMode:p,hiddenWindows:x,onToggleWindow:R,onShowAllHidden:N},_.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:M,disabled:o||d,"data-testid":"usage-refresh-btn",children:[t.jsx(Nn,{size:14,className:d?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return z?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),$]}):t.jsx("div",{className:"modal-overlay open",onClick:C,"data-testid":"usage-modal-overlay",children:$})}function Yf(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 Co(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 pR={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},Qf={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},fR={cron:zh,webhook:Jh,api:Fh,manual:Pn},gR={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},xR={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function bR({result:e}){const n=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("span",{className:`schedule-run-badge ${e.success?"success":"failure"}`,children:[e.success?t.jsx(dn,{size:12}):t.jsx(vr,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Yf(n)})]})}function vR({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"} ${Co(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(dn,{size:12}):t.jsx(vr,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Co(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:Qf[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Yf(r)}),s?t.jsx(li,{size:12}):t.jsx(qt,{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 yR({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o,lastRunOutput:l}){const[c,u]=a.useState(!1),{confirm:d}=Ds(),m=a.useCallback(async()=>{await d({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,d]),h=pR[e.trigger.type],g=fR[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:h,color:h},children:[t.jsx(g,{size:10}),Qf[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(To,{size:10}):t.jsx(In,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>i(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(ot,{size:14,className:"spinner"}):t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>r(e),title:e.enabled?"Disable":"Enable","aria-label":e.enabled?`Disable ${e.name}`:`Enable ${e.name}`,"aria-pressed":e.enabled,children:e.enabled?t.jsx(Gs,{size:14}):t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Yn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Xt,{size:14})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Ui,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(yi,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:gR[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:xR[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:Co(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:Co(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(bR,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>u(f=>!f),"aria-expanded":c,children:[c?t.jsx(li,{size:12}):t.jsx(qt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((f,x)=>t.jsx(vR,{result:f,index:x},`${f.startedAt}-${x}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function kR({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(ri,{size:n}),t.jsx("span",{children:"Command"})]}):e==="create-task"?t.jsxs("span",{className:"step-type-badge step-type-create-task",title:"Create Task step",children:[t.jsx(Jx,{size:n}),t.jsx("span",{children:"Create Task"})]}):t.jsxs("span",{className:"step-type-badge step-type-ai-prompt",title:"AI Prompt step",children:[t.jsx(qn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function Zl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function jR(e){return e==="command"?{id:Zl(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:Zl(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:Zl(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function wR({step:e,onSave:n,onCancel:s}){const[i,r]=a.useState(e.name),[o,l]=a.useState(e.type),[c,u]=a.useState(e.command??""),[d,m]=a.useState(e.prompt??""),[h,g]=a.useState(e.modelProvider??""),[p,f]=a.useState(e.modelId??""),[x,v]=a.useState(e.taskTitle??""),[b,y]=a.useState(e.taskDescription??""),[S,k]=a.useState(e.taskColumn??"triage"),[R,N]=a.useState(e.timeoutMs),[M,C]=a.useState(e.continueOnFailure??!1),[z,A]=a.useState({}),[P,F]=a.useState([]),[W,$]=a.useState(!1),[_,I]=a.useState(null);a.useEffect(()=>{let D=!1;return $(!0),I(null),cs().then(T=>{D||F(T.models)}).catch(T=>{D||I(T instanceof Error?T.message:"Failed to load models")}).finally(()=>{D||$(!1)}),()=>{D=!0}},[]);const O=a.useCallback(()=>{const D={};return i.trim()||(D.name="Step name is required"),o==="command"&&!c.trim()&&(D.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(D.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(D.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(D.modelProvider="Both model provider and model ID must be set together"),R!==void 0&&R<1e3&&(D.timeoutMs="Timeout must be at least 1 second (1000ms)"),A(D),Object.keys(D).length===0},[i,o,c,d,b,h,p,R]),J=h&&p?`${h}/${p}`:"",Q=a.useCallback(D=>{if(!D)g(""),f("");else{const T=D.indexOf("/");T!==-1&&(g(D.slice(0,T)),f(D.slice(T+1)))}},[]),E=a.useCallback(()=>{if(!O())return;const D={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&x.trim()?x.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:R||void 0,continueOnFailure:M};o!=="ai-prompt"&&delete D.prompt,o!=="create-task"&&(delete D.taskTitle,delete D.taskDescription,delete D.taskColumn),n(D)},[O,n,e,i,o,c,d,x,b,S,h,p,R,M]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:i,onChange:D=>r(D.target.value),"aria-invalid":!!z.name}),z.name&&t.jsx("small",{className:"field-error",children:z.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:D=>l(D.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:D=>u(D.target.value),rows:2,"aria-invalid":!!z.command}),z.command&&t.jsx("small",{className:"field-error",children:z.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:d,onChange:D=>m(D.target.value),rows:3,"aria-invalid":!!z.prompt}),z.prompt&&t.jsx("small",{className:"field-error",children:z.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx($n,{id:`step-model-${e.id}`,label:"Model",models:P,value:J,onChange:Q,placeholder:"Use default",disabled:W}),_&&t.jsx("small",{className:"field-error",children:_}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:x,onChange:D=>v(D.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:D=>y(D.target.value),rows:4,"aria-invalid":!!z.taskDescription}),z.taskDescription&&t.jsx("small",{className:"field-error",children:z.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:D=>k(D.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx($n,{id:`step-task-model-${e.id}`,label:"Model",models:P,value:J,onChange:Q,placeholder:"Use default",disabled:W}),_&&t.jsx("small",{className:"field-error",children:_}),z.modelProvider&&t.jsx("small",{className:"field-error",children:z.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:R??"",onChange:D=>N(D.target.value?Number(D.target.value):void 0),"aria-invalid":!!z.timeoutMs}),z.timeoutMs&&t.jsx("small",{className:"field-error",children:z.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:M,onChange:D=>C(D.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:E,children:"Save Step"})]})]})}function NR({steps:e,onChange:n,onEditingChange:s}){const[i,r]=a.useState(null);a.useEffect(()=>{s?.(i!==null)},[i,s]);const o=a.useCallback(d=>{const m=jR(d);n([...e,m]),r(m.id)},[e,n]),l=a.useCallback(d=>{n(e.filter(m=>m.id!==d)),i===d&&r(null)},[e,n,i]),c=a.useCallback((d,m)=>{const h=e.findIndex(f=>f.id===d);if(h<0)return;const g=m==="up"?h-1:h+1;if(g<0||g>=e.length)return;const p=[...e];[p[h],p[g]]=[p[g],p[h]],n(p)},[e,n]),u=a.useCallback(d=>{n(e.map(m=>m.id===d.id?d:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((d,m)=>t.jsx("div",{className:"step-card",children:i===d.id?t.jsx(wR,{step:d,onSave:u,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(Jc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(kR,{type:d.type}),t.jsx("span",{className:"step-card-name",children:d.name}),d.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${d.name} up`,children:t.jsx(li,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(d.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${d.name} down`,children:t.jsx(qt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(Yn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(Xt,{size:14})})]})]})},d.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx(Zt,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Zt,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Zt,{size:14}),"Add Create Task Step"]})]})]})}const Xf={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},SR={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function CR(e){const n=e.trim();for(const[s,i]of Object.entries(Xf))if(i===n)return s;return"custom"}function ER(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function _R(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 MR(e){const n=e.trigger;switch(n.type){case"cron":return{triggerType:"cron",cronExpression:n.cronExpression,webhookPath:"",webhookSecret:"",endpoint:""};case"webhook":return{triggerType:"webhook",cronExpression:"",webhookPath:n.webhookPath,webhookSecret:n.secret||"",endpoint:""};case"api":return{triggerType:"api",cronExpression:"",webhookPath:"",webhookSecret:"",endpoint:n.endpoint};case"manual":return{triggerType:"manual",cronExpression:"",webhookPath:"",webhookSecret:"",endpoint:""}}}const AR=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],RR=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function oh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function lh({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?MR(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[u,d]=a.useState(e?.name??""),[m,h]=a.useState(e?.description??""),[g,p]=a.useState(c.triggerType),[f,x]=a.useState(c.cronExpression),[v,b]=a.useState(()=>c.triggerType!=="cron"?"custom":CR(c.cronExpression)),[y,S]=a.useState(c.webhookPath),[k,R]=a.useState(c.webhookSecret),[N,M]=a.useState(c.endpoint),[C,z]=a.useState(e?.executionPolicy??"queue"),[A,P]=a.useState(e?.catchUpPolicy??"run_one"),[F,W]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,_=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[I,O]=a.useState(e?.steps&&e.steps.length>0&&!$&&!_?"advanced":"simple"),[J,Q]=a.useState(()=>$?"ai-prompt":_?"create-task":"command"),[E,D]=a.useState(e?.command??""),[T,w]=a.useState(e?.steps??[]),[q,G]=a.useState(!1),[me,ce]=a.useState(e?.timeoutMs??3e5),[ae,pe]=a.useState($?e.steps?.[0]?.prompt??"":""),[U,Ne]=a.useState(_?e.steps?.[0]?.taskTitle??"":""),[ne,xe]=a.useState(_?e.steps?.[0]?.taskDescription??"":""),[le,ve]=a.useState(_?e.steps?.[0]?.taskColumn??"triage":"triage"),[ee,Ee]=a.useState($||_?e.steps?.[0]?.modelProvider??"":""),[Fe,Ke]=a.useState($||_?e.steps?.[0]?.modelId??"":""),[Ze,Xe]=a.useState([]),[Qe,it]=a.useState(!1),[Ie,Ge]=a.useState(null),[se,ye]=a.useState(i??"global"),[Z,Te]=a.useState({}),[ze,be]=a.useState(!1),Me=a.useRef(!0);a.useEffect(()=>()=>{Me.current=!1},[]),a.useEffect(()=>{i&&ye(i)},[i]),a.useEffect(()=>{let fe=!1;return it(!0),Ge(null),cs().then(tt=>{fe||Xe(tt.models)}).catch(tt=>{fe||Ge(tt instanceof Error?tt.message:"Failed to load models")}).finally(()=>{fe||it(!1)}),()=>{fe=!0}},[]);const Be=ee&&Fe?`${ee}/${Fe}`:"",lt=a.useCallback(fe=>{if(!fe){Ee(""),Ke("");return}const tt=fe.indexOf("/");tt!==-1&&(Ee(fe.slice(0,tt)),Ke(fe.slice(tt+1)))},[]),je=a.useCallback(()=>{const fe={};if(u.trim()||(fe.name="Name is required"),se==="project"&&!r&&(fe.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?ER(f)||(fe.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):fe.cronExpression="Cron expression is required"),g==="webhook"&&!y.trim()&&(fe.webhookPath="Webhook path is required"),g==="api"&&!N.trim()&&(fe.endpoint="API endpoint is required"),I==="simple")J==="command"&&!E.trim()&&(fe.command="Command is required"),J==="ai-prompt"&&!ae.trim()&&(fe.prompt="Prompt is required"),J==="create-task"&&!ne.trim()&&(fe.taskDescription="Task description is required"),(ee.trim()&&!Fe.trim()||!ee.trim()&&Fe.trim())&&(fe.model="Both model provider and model ID must be set, or both must be empty");else{T.length===0&&(fe.steps="At least one step is required"),q&&(fe.stepsEditing="Please save or cancel all step edits before saving the routine");const tt=[];T.forEach((ut,vt)=>{ut.name?.trim()||tt.push(`Step ${vt+1}: Name is required`),ut.type==="command"&&!ut.command?.trim()&&tt.push(`Step ${vt+1}: Command is required`),ut.type==="ai-prompt"&&!ut.prompt?.trim()&&tt.push(`Step ${vt+1}: Prompt is required`),ut.type==="create-task"&&!ut.taskDescription?.trim()&&tt.push(`Step ${vt+1}: Task description is required`)}),tt.length>0&&(fe.steps=tt.join("; "))}return me<1e3&&(fe.timeoutMs="Timeout must be at least 1 second (1000ms)"),Te(fe),Object.keys(fe).length===0},[u,g,f,v,y,N,se,r,I,J,E,ae,ne,ee,Fe,T,q,me]),ie=a.useCallback(async fe=>{if(fe.preventDefault(),!!je()){be(!0);try{let tt=e?.scope??se??(r?"project":"global");tt==="project"&&!r&&(tt="global");const ut=_R(g,f,y,k,N);let vt,gt;I==="simple"?J==="command"?vt=E.trim()||void 0:J==="ai-prompt"?gt=[{id:oh(),type:"ai-prompt",name:u.trim(),prompt:ae.trim(),modelProvider:ee.trim()||void 0,modelId:Fe.trim()||void 0}]:gt=[{id:oh(),type:"create-task",name:u.trim(),taskTitle:U.trim()||void 0,taskDescription:ne.trim(),taskColumn:le,modelProvider:ee.trim()||void 0,modelId:Fe.trim()||void 0}]:gt=T;const dt={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:ut,command:vt,steps:gt,timeoutMs:me,executionPolicy:C,catchUpPolicy:A,enabled:F,scope:tt};await n(dt)}finally{Me.current&&be(!1)}}},[je,n,u,m,g,f,y,k,N,I,J,E,ae,ee,Fe,U,ne,le,T,me,C,A,F,se,r,e?.scope,e?.agentId]),Ae="routine-name-error",he="routine-cron-error",Re="routine-webhook-error",Je="routine-endpoint-error",$e="routine-command-error",de="routine-prompt-error",re="routine-task-description-error",ue="routine-model-error",Pe="routine-timeout-error",Se=a.useCallback(fe=>{b(fe),fe!=="custom"&&x(Xf[fe])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:ie,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:u,onChange:fe=>d(fe.target.value),"aria-invalid":!!Z.name,"aria-describedby":Z.name?Ae:void 0}),Z.name&&t.jsx("small",{id:Ae,className:"field-error",children:Z.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-description",children:"Description (optional)"}),t.jsx("textarea",{id:"routine-description",placeholder:"What does this routine do?",value:m,onChange:fe=>h(fe.target.value),rows:2})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Scope"}),t.jsxs("div",{className:"routine-scope-toggle",role:"radiogroup","aria-label":"Routine scope",children:[t.jsxs("button",{type:"button",className:`routine-scope-btn${se==="global"?" active":""}`,onClick:()=>{ye("global"),o?.("global")},role:"radio","aria-checked":se==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(To,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${se==="project"?" active":""}`,onClick:()=>{ye("project"),o?.("project")},role:"radio","aria-checked":se==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(In,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":se==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Z.scope&&t.jsx("small",{className:"field-error",children:Z.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":g==="cron",children:[t.jsx(zh,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":g==="webhook",children:[t.jsx(Jh,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":g==="api",children:[t.jsx(Fh,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${g==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":g==="manual",children:[t.jsx(Pn,{size:14}),"Manual"]})]})]}),g==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:fe=>Se(fe.target.value),children:Object.entries(SR).map(([fe,tt])=>t.jsx("option",{value:fe,children:tt},fe))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:fe=>x(fe.target.value),disabled:v!=="custom","aria-invalid":!!Z.cronExpression,"aria-describedby":Z.cronExpression?he:void 0}),Z.cronExpression?t.jsx("small",{id:he,className:"field-error",children:Z.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${f}`})]}),g==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:fe=>S(fe.target.value),"aria-invalid":!!Z.webhookPath,"aria-describedby":Z.webhookPath?Re:void 0}),Z.webhookPath?t.jsx("small",{id:Re,className:"field-error",children:Z.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:k,onChange:fe=>R(fe.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),g==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:N,onChange:fe=>M(fe.target.value),"aria-invalid":!!Z.endpoint,"aria-describedby":Z.endpoint?Je:void 0}),Z.endpoint?t.jsx("small",{id:Je,className:"field-error",children:Z.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),g==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${I==="simple"?" active":""}`,onClick:()=>O("simple"),role:"radio","aria-checked":I==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${I==="advanced"?" active":""}`,onClick:()=>O("advanced"),role:"radio","aria-checked":I==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:I==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),I==="simple"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Type"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action type",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="command"?" active":""}`,onClick:()=>Q("command"),role:"radio","aria-checked":J==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="ai-prompt"?" active":""}`,onClick:()=>Q("ai-prompt"),role:"radio","aria-checked":J==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${J==="create-task"?" active":""}`,onClick:()=>Q("create-task"),role:"radio","aria-checked":J==="create-task",children:"Create Task"})]})]}),J==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:E,onChange:fe=>D(fe.target.value),"aria-invalid":!!Z.command,"aria-describedby":Z.command?$e:void 0}),Z.command?t.jsx("small",{id:$e,className:"field-error",children:Z.command}):t.jsx("small",{children:"Shell command to execute."})]}):J==="ai-prompt"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-prompt",children:"Prompt"}),t.jsx("textarea",{id:"routine-prompt",placeholder:"e.g. Summarize recent activity and create action items",value:ae,onChange:fe=>pe(fe.target.value),rows:3,"aria-invalid":!!Z.prompt,"aria-describedby":Z.prompt?de:void 0}),Z.prompt?t.jsx("small",{id:de,className:"field-error",children:Z.prompt}):t.jsx("small",{children:"AI prompt to execute."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-model",children:"Model (optional)"}),t.jsx($n,{id:"routine-model",label:"Model",models:Ze,value:Be,onChange:lt,placeholder:"Use default",disabled:Qe}),Ie&&t.jsx("small",{className:"field-error",children:Ie}),Z.model&&t.jsx("small",{id:ue,className:"field-error",children:Z.model})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-title",children:"Task Title (optional)"}),t.jsx("input",{id:"routine-task-title",type:"text",placeholder:"e.g. Review weekly dependencies",value:U,onChange:fe=>Ne(fe.target.value)})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-description",children:"Task Description"}),t.jsx("textarea",{id:"routine-task-description",placeholder:"e.g. Check npm dependencies for security vulnerabilities",value:ne,onChange:fe=>xe(fe.target.value),rows:4,"aria-invalid":!!Z.taskDescription,"aria-describedby":Z.taskDescription?re:void 0}),Z.taskDescription?t.jsx("small",{id:re,className:"field-error",children:Z.taskDescription}):t.jsx("small",{children:"Describes the task that will be created."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-column",children:"Target Column"}),t.jsxs("select",{id:"routine-task-column",value:le,onChange:fe=>ve(fe.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-task-model",children:"Executor Model (optional)"}),t.jsx($n,{id:"routine-task-model",label:"Executor Model",models:Ze,value:Be,onChange:lt,placeholder:"Use default",disabled:Qe}),Ie&&t.jsx("small",{className:"field-error",children:Ie}),Z.model&&t.jsx("small",{id:ue,className:"field-error",children:Z.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(NR,{steps:T,onChange:w,onEditingChange:G}),Z.steps&&t.jsx("small",{className:"field-error",children:Z.steps}),Z.stepsEditing&&t.jsx("small",{className:"field-error",children:Z.stepsEditing})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-timeout",children:"Timeout (ms)"}),t.jsx("input",{id:"routine-timeout",type:"number",min:1e3,step:1e3,value:me,onChange:fe=>ce(Number(fe.target.value)),"aria-invalid":!!Z.timeoutMs,"aria-describedby":Z.timeoutMs?Pe:void 0}),Z.timeoutMs?t.jsx("small",{id:Pe,className:"field-error",children:Z.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:C,onChange:fe=>z(fe.target.value),children:AR.map(fe=>t.jsx("option",{value:fe.value,children:fe.label},fe.value))}),t.jsx("small",{children:"How to handle concurrent executions of this routine"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-catchup-policy",children:"Catch-up Policy"}),t.jsx("select",{id:"routine-catchup-policy",value:A,onChange:fe=>P(fe.target.value),children:RR.map(fe=>t.jsx("option",{value:fe.value,children:fe.label},fe.value))}),t.jsx("small",{children:"What to do when a scheduled run is missed"})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"routine-enabled",className:"checkbox-label",children:[t.jsx("input",{id:"routine-enabled",type:"checkbox",checked:F,onChange:fe=>W(fe.target.checked)}),"Enabled"]}),t.jsx("small",{children:"When disabled, the routine will not run automatically"})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:ze,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:ze,children:ze?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const TR=3e4;function PR({onClose:e,addToast:n,projectId:s}){const[i,r]=a.useState(()=>s?"project":"global"),[o,l]=a.useState([]),[c,u]=a.useState("list"),[d,m]=a.useState(),[h,g]=a.useState(null),[p,f]=a.useState({}),x=a.useRef(null);Xs(x,!0,"fusion:automation-modal-size");const v=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),b=a.useCallback(async()=>{try{const $=await ak(v);l($),f(_=>{const I={..._};for(const O of $){const J=I[O.id];if(!J||!O.lastRunResult)continue;const Q=O.lastRunResult;Q.success===J.success&&(Q.output||"")===J.output&&(Q.error||"")===(J.error||"")&&delete I[O.id]}return I})}catch($){n(ke($)||"Failed to load routines","error")}},[n,v]);a.useEffect(()=>{b()},[b]),a.useEffect(()=>{const $=setInterval(()=>{b()},TR);return()=>clearInterval($)},[b]),a.useEffect(()=>{const $=_=>{_.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",$),()=>document.removeEventListener("keydown",$)},[e,c]);const y=wi(e),S=a.useCallback(async $=>{try{await rk($,v),n("Routine created","success"),u("list"),await b()}catch(_){n(ke(_)||"Failed to create routine","error")}},[n,b,v]),k=a.useCallback($=>{m($),u("edit")},[]),R=a.useCallback(async $=>{if(d)try{await Bd(d.id,$,v),n("Routine updated","success"),u("list"),m(void 0),await b()}catch(_){n(ke(_)||"Failed to update routine","error")}},[d,n,b,v]),N=a.useCallback(async $=>{try{await ok($.id,v),n(`Deleted "${$.name}"`,"success"),await b()}catch(_){n(ke(_)||"Failed to delete routine","error")}},[n,b,v]),M=a.useCallback(async $=>{g($.id);try{const{result:_}=await lk($.id,v);f(I=>({...I,[$.id]:{output:_.output||"",error:_.error,success:_.success}})),_.success?n(`"${$.name}" completed successfully`,"success"):n(`"${$.name}" failed: ${_.error||"Unknown error"}`,"error"),await b()}catch(_){n(ke(_)||"Failed to run routine","error")}finally{g(null)}},[n,b,v]),C=a.useCallback(async $=>{try{await Bd($.id,{enabled:!$.enabled},v),n(`"${$.name}" ${$.enabled?"disabled":"enabled"}`,"success"),await b()}catch(_){n(ke(_)||"Failed to toggle routine","error")}},[n,b,v]),z=a.useCallback(()=>{u("list"),m(void 0)},[]);a.useEffect(()=>{c!=="list"&&f({})},[c]);const A=a.useCallback($=>{r($),u("list"),m(void 0),f({})},[]),P=()=>c==="create"?t.jsx(lh,{onSubmit:S,onCancel:z,scope:i,projectId:s}):c==="edit"&&d?t.jsx(lh,{routine:d,onSubmit:R,onCancel:z,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(Pn,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),children:[t.jsx(Zt,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map($=>t.jsx(yR,{routine:$,onEdit:k,onDelete:N,onRun:M,onToggle:C,running:h===$.id,lastRunOutput:p[$.id]??null},$.id))}),F=()=>P(),W=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:x,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Pn,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(Ot,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${i==="global"?" active":""}`,onClick:()=>A("global"),"aria-pressed":i==="global",title:"Global (user-level) automations",children:[t.jsx(To,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${i==="project"?" active":""}`,onClick:()=>A("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(In,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(Pn,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:W&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(Zt,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:F()})]})})}const IR=3e4,Bc=new Map,ec=new Map;function ch(e){return e??"default"}function dh(e){const n=Bc.get(e);return n?Date.now()>=n.expiresAt?(Bc.delete(e),null):n:null}function $R(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 DR(e){const n=ec.get(e);if(n)return n;const s=mr().then(({providers:i,ghCli:r})=>{const l={...$R(i,r),ghCli:r,expiresAt:Date.now()+IR};return Bc.set(e,l),l}).finally(()=>{ec.delete(e)});return ec.set(e,s),s}function Zf(e){const n=ch(e),s=dh(n),[i,r]=a.useState(s?.hasAiProvider??!1),[o,l]=a.useState(s?.hasGithub??!1),[,c]=a.useState(s?.ghCli),[u,d]=a.useState(s==null),m=a.useRef(!!s);return a.useEffect(()=>{let h=!1;const g=ch(e),p=dh(g);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),d(!1),m.current=!0,()=>{h=!0};m.current=!1;async function f(){!m.current&&d(!0);try{const v=await DR(g);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,d(!1))}}return f(),()=>{h=!0}},[e]),a.useMemo(()=>({hasAiProvider:i,hasGithub:o,loading:u,hasWarnings:!i||!o}),[i,o,u])}function eg({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:i}){if(e&&n)return null;const r=i?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:i,children:t.jsx(Ot,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${i?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function LR({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:u}=Ds(),[d,m]=a.useState(""),[h,g]=a.useState([]),[p,f]=a.useState([]),[x,v]=a.useState(!1),[b,y]=a.useState(""),[S,k]=a.useState(""),[R,N]=a.useState(""),[M,C]=a.useState(""),[z,A]=a.useState(""),[P,F]=a.useState("default"),[W,$]=a.useState(!1),[_,I]=a.useState([]),[O,J]=a.useState(!1),[Q,E]=a.useState(void 0),[D,T]=a.useState(ps),[w,q]=a.useState(void 0),[G,me]=a.useState(null),[ce,ae]=a.useState([]),[pe,U]=a.useState(!1),[Ne,ne]=a.useState(!1),xe=a.useRef(null),[le,ve]=a.useState(!1),[ee,Ee]=a.useState(""),Fe=a.useRef(null),{hasAiProvider:Ke,hasGithub:Ze,loading:Xe}=Zf(s),{nodes:Qe}=Bo(),it=a.useCallback(je=>{J(!0),I(je)},[]),Ie=a.useCallback(()=>{J(!1)},[]),Ge=a.useCallback(async()=>{if(ce.length>0){U(!0);return}ne(!0);try{const je=await Na(void 0,s);ae(je),U(!0)}catch(je){const ie=ke(je);o(ie?`Failed to load agents: ${ie}`:"Failed to load agents","error"),U(!1)}finally{ne(!1)}},[ce.length,s,o]);a.useEffect(()=>{if(!pe)return;const je=ie=>{xe.current&&!xe.current.contains(ie.target)&&U(!1)};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[pe]),a.useEffect(()=>{if(!le)return;const je=ie=>{Fe.current&&!Fe.current.contains(ie.target)&&(ve(!1),Ee(""))};return document.addEventListener("mousedown",je),()=>document.removeEventListener("mousedown",je)},[le]);const se=i.filter(je=>!h.includes(je.id)).sort((je,ie)=>{const Ae=ie.createdAt.localeCompare(je.createdAt);if(Ae!==0)return Ae;const he=parseInt(je.id.slice(je.id.lastIndexOf("-")+1),10)||0;return(parseInt(ie.id.slice(ie.id.lastIndexOf("-")+1),10)||0)-he}),ye=ee?se.filter(je=>je.id.toLowerCase().includes(ee.toLowerCase())||je.title&&je.title.toLowerCase().includes(ee.toLowerCase())||je.description&&je.description.toLowerCase().includes(ee.toLowerCase())):se,Z=(je,ie)=>je.length>ie?je.slice(0,ie)+"…":je;a.useEffect(()=>{const je=d.trim()!==""||h.length>0||p.length>0||b!==""||S!==""||R!==""||M!==""||_.length>0||G!==null||Q!==void 0||D!==ps||w!==void 0;$(je)},[d,h,p,b,S,R,M,_,G,Q,D,w]);const Te=a.useCallback(async()=>{W&&!await u({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(p.forEach(je=>URL.revokeObjectURL(je.previewUrl)),f([]),m(""),g([]),y(""),k(""),N(""),C(""),A(""),F("default"),I([]),J(!1),me(null),U(!1),E(void 0),T(ps),q(void 0),$(!1),n())},[W,n,p,u]),ze=a.useCallback(async()=>{const je=d.trim();if(!(!je||x)){v(!0);try{const ie=b.indexOf("/"),Ae=S.indexOf("/"),he=R.indexOf("/"),Re=await r({title:void 0,description:je,column:"triage",dependencies:h.length?h:void 0,enabledWorkflowSteps:O?_.length>0?_:[]:void 0,...G?{assignedAgentId:G}:{},modelPresetId:P==="preset"&&z||void 0,modelProvider:b&&ie!==-1?b.slice(0,ie):void 0,modelId:b&&ie!==-1?b.slice(ie+1):void 0,validatorModelProvider:S&&Ae!==-1?S.slice(0,Ae):void 0,validatorModelId:S&&Ae!==-1?S.slice(Ae+1):void 0,planningModelProvider:R&&he!==-1?R.slice(0,he):void 0,planningModelId:R&&he!==-1?R.slice(he+1):void 0,thinkingLevel:M!==""?M:void 0,reviewLevel:Q,priority:D,nodeId:w});if(p.length>0){const Je=[];for(const $e of p)try{await ur(Re.id,$e.file,s)}catch{Je.push($e.file.name)}Je.length>0&&o(`Failed to upload: ${Je.join(", ")}`,"error")}p.forEach(Je=>URL.revokeObjectURL(Je.previewUrl)),f([]),m(""),g([]),y(""),k(""),N(""),C(""),A(""),F("default"),I([]),J(!1),me(null),U(!1),E(void 0),T(ps),q(void 0),o(`Created ${Re.id}`,"success"),n()}catch(ie){o(ke(ie)||"Failed to create task","error")}finally{v(!1)}}},[d,h,p,b,S,R,M,x,r,o,n,s,P,z,_,O,G,Q,D,w]),be=a.useCallback(je=>{je.key==="Escape"&&(je.preventDefault(),Te())},[Te]),Be=(G?ce.find(je=>je.id===G):void 0)?.name??G,lt=t.jsxs("div",{className:"new-task-quick-fields",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:Fe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ve(je=>!je),disabled:x,"data-testid":"dep-trigger",children:h.length>0?`${h.length} selected`:"Add dependencies"}),le&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ee,onChange:je=>Ee(je.target.value),onClick:je=>je.stopPropagation()}),ye.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):ye.map(je=>t.jsxs("div",{className:`dep-dropdown-item${h.includes(je.id)?" selected":""}`,onClick:()=>{g(h.includes(je.id)?h.filter(ie=>ie!==je.id):[...h,je.id]),ve(!1),Ee("")},onMouseDown:ie=>ie.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:je.id}),t.jsx("span",{className:"dep-dropdown-title",children:Z(je.title||je.description||je.id,30)})]},je.id))]})]}),h.length>0&&t.jsx("div",{className:"selected-deps",children:h.map(je=>t.jsxs("span",{className:"dep-chip",children:[je,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>g(h.filter(ie=>ie!==je)),disabled:x,children:"×"})]},je))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:xe,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{pe?U(!1):Ge()},disabled:x,"data-testid":"new-task-agent-button",children:[t.jsx(gn,{size:12,style:{verticalAlign:"middle"}}),Be?` ${Be}`:" Assign agent"]}),pe&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:je=>je.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Ne&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Ne&&ce.filter(je=>je.state!=="terminated").map(je=>t.jsxs("div",{className:`dep-dropdown-item${G===je.id?" selected":""}`,onMouseDown:ie=>ie.preventDefault(),onClick:()=>{me(je.id===G?null:je.id),U(!1)},"data-testid":`agent-option-${je.id}`,children:[t.jsx(gn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:je.role}),t.jsx("span",{className:"dep-dropdown-title",children:je.name})]},je.id)),!Ne&&ce.filter(je=>je.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),G&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:je=>je.preventDefault(),onClick:()=>{me(null),U(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:Te,onKeyDown:be,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:je=>je.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:Te,disabled:x,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Xe&&t.jsx(eg,{hasAiProvider:Ke,hasGithub:Ze}),t.jsx(qf,{mode:"create",description:d,onDescriptionChange:m,dependencies:h,onDependenciesChange:g,executorModel:b,onExecutorModelChange:y,validatorModel:S,onValidatorModelChange:k,presetMode:P,onPresetModeChange:F,selectedPresetId:z,onSelectedPresetIdChange:A,selectedWorkflowSteps:_,onWorkflowStepsChange:it,onDefaultOnApplied:Ie,pendingImages:p,onImagesChange:f,tasks:i,projectId:s,disabled:x,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:Te,planningModel:R,onPlanningModelChange:N,thinkingLevel:M,onThinkingLevelChange:C,reviewLevel:Q,onReviewLevelChange:E,priority:D,onPriorityChange:T,nodeId:w,onNodeIdChange:q,nodeOptions:Qe,renderBelowPrimary:lt,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Te,disabled:x,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:ze,disabled:!d.trim()||x,children:x?"Creating...":"Create Task"})]})]})}):null}function ai(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 uh(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function zR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function FR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function OR(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function tc(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function UR(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function BR({isOpen:e,onClose:n,projectId:s}){const[i,r]=a.useState(null),[o,l]=a.useState(!1),[c,u]=a.useState(null),[d,m]=a.useState(!0),[h,g]=a.useState(90),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState(null),[S,k]=a.useState(null),[R,N]=a.useState(null),M=a.useCallback(async D=>{l(!0);try{const T=await Ik(s);r(T),u(null),N(Date.now()),D?.preserveKillResult||y(null)}catch(T){u(T instanceof Error?T.message:"Failed to load system stats")}finally{l(!1)}},[s]);a.useEffect(()=>{if(!e)return;M();const D=window.setInterval(()=>{M()},5e3);return()=>{window.clearInterval(D)}},[e,M]),a.useEffect(()=>{if(!e)return;(async()=>{try{const T=await Vi();m(T.vitestAutoKillEnabled??!0),g(T.vitestKillThresholdPct??90),k(null)}catch(T){k(T instanceof Error?T.message:"Failed to load vitest settings")}})()},[e]),a.useEffect(()=>{if(!e)return;const D=T=>{T.key==="Escape"&&n()};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[e,n]);const C=a.useMemo(()=>{if(!i)return[];const D=i.systemStats,T=tc(zR(D.heapUsed,D.heapLimit)),w=tc(FR(D.rss,D.systemTotalMem));return[{label:"RSS",value:ai(D.rss),detail:uh(D.rss,D.systemTotalMem),className:w},{label:"Heap Used",value:ai(D.heapUsed),detail:`of ${ai(D.heapTotal)}`,className:T},{label:"Heap Limit",value:ai(D.heapLimit),detail:"V8 limit"},{label:"External",value:ai(D.external)},{label:"Array Buffers",value:ai(D.arrayBuffers)}]},[i]),z=a.useCallback(async D=>{m(D);try{await sn({vitestAutoKillEnabled:D}),k(null)}catch(T){k(T instanceof Error?T.message:"Failed to save vitest settings")}},[]),A=a.useCallback(async D=>{const T=Math.min(99,Math.max(50,Number.isFinite(D)?Math.round(D):90));g(T);try{await sn({vitestKillThresholdPct:T}),k(null)}catch(w){k(w instanceof Error?w.message:"Failed to save vitest settings")}},[]),P=a.useCallback(async()=>{if(!p){if(!x){v(!0);return}f(!0);try{const D=await $k(s);y(D),v(!1),await M({preserveKillResult:!0})}catch(D){u(D instanceof Error?D.message:"Failed to kill vitest processes")}finally{f(!1)}}},[x,p,M,s]);if(!e)return null;const F=i?.systemStats,W=o&&!!i,$=R?`Updated ${new Date(R).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",_=i?.taskStats,I=F?F.systemTotalMem-F.systemFreeMem:0,O=F?tc(OR(I,F.systemTotalMem)):"",J=i?.vitestProcessCount,Q=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",E=UR(i?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:D=>{D.target===D.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(dr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:$})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void M(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(Nn,{size:16,className:W?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ot,{})})]})]}),o&&!i&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!i&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),i&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:C.map(D=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:D.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${D.className}`.trim(),children:D.value}),D.detail?t.jsx("span",{className:"system-stats-modal__detail",children:D.detail}):null]})]},D.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:F?.loadAvg.map(D=>D.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:F?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:F?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:F?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:F?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${O}`.trim(),children:F?ai(I):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:F?`${uh(I,F.systemTotalMem)} of ${ai(F.systemTotalMem)}`:""})]})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:F?ai(F.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:_?.total??0})]}),Object.entries(_?.byColumn??{}).map(([D,T])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:D}),t.jsx("dd",{children:T})]},D))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:_?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:_?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:_?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:_?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(Tb,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:J??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void P(),disabled:p||J===0,children:[t.jsx(Db,{}),t.jsx("span",{children:x?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:d,onChange:D=>{z(D.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:D=>{const T=Number.parseInt(D.target.value,10);A(Number.isNaN(T)?90:T)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:D=>{const T=Number.parseInt(D.target.value,10);A(Number.isNaN(T)?90:T)},onBlur:()=>{A(h)}})]})]}),b&&t.jsxs("p",{className:Q,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",E]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&i&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const HR=5e3;function qR(e={}){const{projectId:n,type:s,limit:i=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(null),[g,p]=a.useState(!1),f=a.useRef(null),x=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let S;o?S=await Jd({limit:i,projectId:n,type:s}):S=(await Hd({limit:i,type:s,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(S),p(S.length===i),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),b=a.useCallback(async()=>{if(x.current)try{d(!0);let S;o?S=await Jd({limit:i,projectId:n,type:s,since:x.current}):S=(await Hd({limit:i,type:s,since:x.current,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(k=>[...k,...S]),p(S.length===i),S.length>0&&(x.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),y=a.useCallback(()=>{c([]),p(!1),x.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},HR),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:y,hasMore:g,loadMore:b}}const nc={"task:created":"Task Created","task:moved":"Task Moved","task:updated":"Task Updated","task:deleted":"Task Deleted","task:merged":"Task Merged","task:failed":"Task Failed","settings:updated":"Settings Updated"},VR={"task:created":t.jsx(Zt,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(br,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(Nn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Ot,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(dn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(vr,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(sr,{size:14,className:"activity-icon settings"})};function WR(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function KR({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:i,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[u,d]=a.useState("all"),[m,h]=a.useState(r||"all"),[g,p]=a.useState(!1);a.useEffect(()=>{h(r||"all")},[r]);const f=u==="all"?void 0:u,x=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:k,hasMore:R}=qR({projectId:x,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),N=b.map(P=>({id:P.id,timestamp:P.timestamp,type:P.type,taskId:P.taskId,taskTitle:P.taskTitle,details:P.details,metadata:P.metadata,projectId:P.projectId,projectName:P.projectName})),M=async()=>{try{await ck(),k(),p(!1)}catch{p(!1)}},C=P=>{i&&i(P)},z=P=>{h(P),l?.(P==="all"?void 0:P)};a.useEffect(()=>{if(!e)return;const P=F=>{F.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[e,n,g]);const A=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:P=>{P.target===P.currentTarget&&n()},role:"dialog","aria-modal":"true","data-testid":"activity-log-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg activity-log-modal","data-testid":"activity-log-modal",children:[t.jsxs("div",{className:"modal-header activity-log-header",children:[t.jsxs("div",{className:"activity-log-title",children:[t.jsx(cr,{size:18}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("div",{className:"activity-log-actions",children:[o.length>0&&t.jsxs("div",{className:"activity-log-filter activity-log-filter--project",children:[t.jsx(In,{size:14}),t.jsxs("select",{value:m,onChange:P=>z(P.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(P=>t.jsx("option",{value:P.id,children:P.name},P.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(uo,{size:14}),t.jsxs("select",{value:u,onChange:P=>d(P.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(nc).map(([P,F])=>t.jsx("option",{value:P,children:F},P))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>k(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14})}),N.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Xt,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),A&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(P=>P.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",nc[u]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Xn,{size:16}),t.jsx("span",{children:S})]}),N.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(cr,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:A?"No activity matches the current filters":"No activity recorded yet"}),A&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{d("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:N.map(P=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:VR[P.type]}),t.jsxs("div",{className:"activity-log-entry-content",children:[t.jsxs("div",{className:"activity-log-entry-header",children:[t.jsx("span",{className:"activity-log-entry-type",children:nc[P.type]}),t.jsx("span",{className:"activity-log-entry-time",children:WR(P.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[P.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>C(P.taskId),"data-testid":"activity-task-link",children:P.taskId}),P.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:P.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:P.details})]}),P.metadata&&Object.keys(P.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof P.metadata.from=="string"&&typeof P.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[P.metadata.from," → ",P.metadata.to]}),typeof P.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${P.metadata.merged?"success":"error"}`,children:P.metadata.merged?"Merged":"Not merged"})]})]})]},P.id))}),R&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:k,"data-testid":"activity-load-more",children:"Load More"}),y&&N.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(ot,{size:20,className:"spin"})})]}),g&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:M,children:"Clear Log"})]})]})})]})}):null}const Ka=[{id:"status",label:"Status",icon:Wh},{id:"changes",label:"Changes",icon:Oh},{id:"commits",label:"Commits",icon:lr},{id:"branches",label:"Branches",icon:Js},{id:"worktrees",label:"Worktrees",icon:Dx},{id:"stashes",label:"Stashes",icon:Mo},{id:"remotes",label:"Remotes",icon:Hh}];function mh({status:e}){switch(e){case"added":case"untracked":return t.jsx(xx,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(Uh,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(px,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Oi,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(vx,{size:14,className:"gm-file-icon"})}}function hh({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 GR(e){return a.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function ba(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 JR({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const o=Ds(),[l,c]=a.useState("status"),[u,d]=a.useState(!1),[m,h]=a.useState(null),g=a.useRef(null);Xs(g,e,"fusion:git-modal-size");const p=wi(n),f=GR(i),[x,v]=a.useState(null),[b,y]=a.useState([]),[S,k]=a.useState(new Set),[R,N]=a.useState(""),[M,C]=a.useState(!1),[z,A]=a.useState(null),[P,F]=a.useState(!1),[W,$]=a.useState(null),[_,I]=a.useState(null),O=a.useRef(0),[J,Q]=a.useState([]),[E,D]=a.useState(null),[T,w]=a.useState(null),[q,G]=a.useState(!1),[me,ce]=a.useState(20),[ae,pe]=a.useState(""),[U,Ne]=a.useState([]),[ne,xe]=a.useState(""),[le,ve]=a.useState(""),[ee,Ee]=a.useState(""),[Fe,Ke]=a.useState(null),[Ze,Xe]=a.useState([]),[Qe,it]=a.useState(!1),[Ie,Ge]=a.useState(null),[se,ye]=a.useState(null),[Z,Te]=a.useState(!1),[ze,be]=a.useState([]),[Me,Be]=a.useState([]),[lt,je]=a.useState(""),[ie,Ae]=a.useState(null),[he,Re]=a.useState(null),[Je,$e]=a.useState(null),de=a.useCallback(async()=>{if(e){d(!0),h(null);try{switch(l){case"status":{const B=await Ps(r);v(B);break}case"changes":{const[B,ge]=await Promise.all([Ps(r),Xi(r)]);v(B),y(ge),k(new Set),I(null),A(null),$(null);break}case"commits":{const B=await fy(me,r);Q(B);break}case"branches":{const[B,ge]=await Promise.all([Pa(r),Ps(r)]);Ne(B),v(ge);break}case"worktrees":{const B=await vy(r);be(B);break}case"stashes":{const B=await Or(r);Be(B);break}case"remotes":{const B=await Ps(r);v(B);break}}}catch(B){h(ke(B)||"Failed to fetch git data"),i(ke(B)||"Failed to fetch git data","error")}finally{d(!1)}}},[l,e,me,i,r]);a.useEffect(()=>{e&&de()},[de,e]),a.useEffect(()=>{if(!e)return;const B=ge=>{if(ge.key==="Escape"){n();return}if((ge.key==="ArrowUp"||ge.key==="ArrowDown")&&ge.altKey){ge.preventDefault();const te=Ka.findIndex(j=>j.id===l);ge.key==="ArrowUp"&&te>0?c(Ka[te-1].id):ge.key==="ArrowDown"&&te<Ka.length-1&&c(Ka[te+1].id)}};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n,l]);const re=a.useCallback(async B=>{try{await zd(B,r),i(`Staged ${B.length} file(s)`,"success");const ge=await Xi(r);y(ge),k(new Set),I(null),A(null),$(null)}catch(ge){i(ke(ge)||"Failed to stage files","error")}},[i,r]),ue=a.useCallback(async B=>{try{await My(B,r),i(`Unstaged ${B.length} file(s)`,"success");const ge=await Xi(r);y(ge),k(new Set),I(null),A(null),$(null)}catch(ge){i(ke(ge)||"Failed to unstage files","error")}},[i,r]),Pe=a.useCallback(async B=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${B.length} file(s)? This cannot be undone.`,danger:!0}))try{await Ay(B,r),i(`Discarded changes to ${B.length} file(s)`,"success");const[te,j]=await Promise.all([Xi(r),Ps(r)]);y(te),v(j),k(new Set),I(null),A(null),$(null)}catch(te){i(ke(te)||"Failed to discard changes","error")}},[i,r,confirm]),Se=a.useCallback(async B=>{if(B.preventDefault(),!!R.trim()){C(!0);try{const ge=await Fd(R.trim(),r);i(`Committed: ${ge.hash}`,"success"),N("");const[te,j]=await Promise.all([Xi(r),Ps(r)]);y(te),v(j),I(null),A(null),$(null)}catch(ge){i(ke(ge)||"Failed to commit","error")}finally{C(!1)}}},[R,i,r]),fe=a.useCallback(async()=>{if(R.trim()){C(!0);try{const B=b.filter(V=>!V.staged).map(V=>V.file);B.length>0&&await zd(B,r);const ge=await Fd(R.trim(),r);i(`Committed: ${ge.hash}`,"success"),N("");const[te,j]=await Promise.all([Xi(r),Ps(r)]);y(te),v(j),I(null),A(null),$(null)}catch(B){i(ke(B)||"Failed to commit","error")}finally{C(!1)}}},[R,b,i,r]),tt=a.useCallback(async(B,ge)=>{I({file:B,staged:ge}),F(!0),$(null);const te=O.current+1;O.current=te;try{const j=await _y(B,ge,r);if(O.current!==te)return;A(j)}catch(j){if(O.current!==te)return;const V=ke(j)||"Failed to load file diff";A(null),$(V),i(V,"error")}finally{O.current===te&&F(!1)}},[i,r]),ut=a.useCallback(B=>{k(ge=>{const te=new Set(ge);return te.has(B)?te.delete(B):te.add(B),te})},[]),vt=a.useCallback(async B=>{if(E===B){D(null),w(null);return}D(B),G(!0);try{const ge=await go(B,r);w(ge)}catch(ge){i(ke(ge)||"Failed to load diff","error"),w(null)}finally{G(!1)}},[E,i,r]),gt=a.useCallback(()=>{ce(B=>Math.min(B+20,100))},[]),dt=a.useMemo(()=>{if(!ae.trim())return J;const B=ae.toLowerCase();return J.filter(ge=>ge.message.toLowerCase().includes(B)||ge.author.toLowerCase().includes(B)||ge.shortHash.toLowerCase().includes(B))},[J,ae]),wt=a.useCallback(async B=>{if(B.preventDefault(),!!ne.trim()){d(!0);try{await yy(ne.trim(),le.trim()||void 0,r),i(`Created branch ${ne}`,"success"),xe(""),ve("");const ge=await Pa(r);Ne(ge)}catch(ge){i(ke(ge)||"Failed to create branch","error")}finally{d(!1)}}},[ne,le,i,r]),Mt=a.useCallback(async B=>{d(!0);try{await ky(B,r),i(`Switched to ${B}`,"success");const[ge,te]=await Promise.all([Ps(r),Pa(r)]);v(ge),Ne(te)}catch(ge){i(ke(ge)||"Failed to checkout branch","error")}finally{d(!1)}},[i,r]),yt=a.useCallback(async B=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${B}"?`,danger:!0})){d(!0);try{await Ld(B,void 0,r),i(`Deleted branch ${B}`,"success");const te=await Pa(r);Ne(te)}catch(te){if(ke(te).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Ld(B,!0,r),i(`Force deleted branch ${B}`,"success");const V=await Pa(r);Ne(V)}catch(V){i(ke(V)||"Failed to delete branch","error")}}else i(ke(te)||"Failed to delete branch","error")}finally{d(!1)}}},[i,r,confirm]),Et=a.useMemo(()=>{if(!ee.trim())return U;const B=ee.toLowerCase();return U.filter(ge=>ge.name.toLowerCase().includes(B))},[U,ee]),Nt=a.useCallback(async B=>{if(Fe===B){Ke(null),Xe([]),Ge(null),ye(null);return}Ke(B),Xe([]),Ge(null),ye(null),it(!0);try{const ge=await by(B,10,r);Xe(ge)}catch{Xe([])}finally{it(!1)}},[Fe,r]),Tt=a.useCallback(async B=>{if(Ie===B){Ge(null),ye(null);return}Ge(B),ye(null),Te(!0);try{const ge=await go(B,r);ye(ge)}catch{ye(null)}finally{Te(!1)}},[Ie,r]),Ht=a.useCallback(()=>{Ke(null),Xe([]),Ge(null),ye(null)},[]),Ut=a.useCallback(async B=>{B.preventDefault(),Ae("create");try{await Sy(lt.trim()||void 0,r),i("Changes stashed","success"),je("");const ge=await Or(r);Be(ge)}catch(ge){i(ke(ge)||"Failed to stash changes","error")}finally{Ae(null)}},[lt,i,r]),Vt=a.useCallback(async(B,ge=!1)=>{Ae(`apply-${B}`);try{await Cy(B,ge,r),i(ge?"Stash popped":"Stash applied","success");const te=await Or(r);Be(te)}catch(te){i(ke(te)||"Failed to apply stash","error")}finally{Ae(null)}},[i,r]),zt=a.useCallback(async B=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${B}}? This cannot be undone.`,danger:!0})){Ae(`drop-${B}`);try{await Ey(B,r),i("Stash dropped","success");const te=await Or(r);Be(te)}catch(te){i(ke(te)||"Failed to drop stash","error")}finally{Ae(null)}}},[i,r,confirm]),Ct=a.useCallback(async()=>{Re("fetch");try{const B=await jy(void 0,r);$e(B),i(B.message||"Fetch completed",B.fetched?"success":"info");const ge=await Ps(r);v(ge)}catch(B){i(ke(B)||"Fetch failed","error")}finally{Re(null)}},[i,r]),At=a.useCallback(async()=>{Re("pull");try{const B=await wy(r);$e(B),B.conflict?i("Merge conflict detected. Resolve manually.","error"):i(B.message||"Pull completed","success");const ge=await Ps(r);v(ge)}catch(B){i(ke(B)||"Pull failed","error")}finally{Re(null)}},[i,r]),kt=a.useCallback(async()=>{Re("push");try{const B=await Ny(r);$e(B),i(B.message||"Push completed","success");const ge=await Ps(r);v(ge)}catch(B){i(ke(B)||"Push failed","error")}finally{Re(null)}},[i,r]),Kt=a.useMemo(()=>b.filter(B=>B.staged),[b]),$t=a.useMemo(()=>b.filter(B=>!B.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(fc,{size:18,style:{marginRight:8,verticalAlign:"middle"}}),"Git Manager"]}),t.jsxs("div",{className:"gm-header-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:de,disabled:u,title:"Refresh",children:t.jsx(Nn,{size:14,className:u?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Ot,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Ka.map(B=>{const ge=B.icon;return t.jsxs("button",{role:"tab","aria-selected":l===B.id,className:`gm-nav-item${l===B.id?" active":""}`,onClick:()=>c(B.id),children:[t.jsx(ge,{size:16}),t.jsx("span",{className:"gm-nav-label",children:B.label})]},B.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[u&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),m&&!u&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Xn,{size:18}),t.jsx("span",{children:m}),t.jsx("button",{className:"btn btn-sm",onClick:de,children:"Retry"})]}),l==="status"&&!u&&x&&t.jsx(YR,{status:x,copyToClipboard:f}),l==="changes"&&!u&&t.jsx(QR,{status:x,stagedFiles:Kt,unstagedFiles:$t,selectedFiles:S,toggleFileSelection:ut,onStageFiles:re,onUnstageFiles:ue,onDiscardChanges:Pe,onSelectDiffFile:tt,selectedDiffTarget:_,changeDiff:z,loadingChangeDiff:P,changeDiffError:W,commitMessage:R,setCommitMessage:N,onCommit:Se,onStageAllAndCommit:fe,committing:M}),l==="commits"&&!u&&t.jsx(XR,{commits:dt,commitSearch:ae,setCommitSearch:pe,selectedCommit:E,commitDiff:T,loadingDiff:q,onCommitClick:vt,onLoadMore:gt,canLoadMore:J.length>=me&&me<100,copyToClipboard:f}),l==="branches"&&!u&&t.jsx(ZR,{branches:Et,branchSearch:ee,setBranchSearch:Ee,newBranchName:ne,setNewBranchName:xe,branchBase:le,setBranchBase:ve,onCreateBranch:wt,onCheckoutBranch:Mt,onDeleteBranch:yt,loading:u,allBranches:U,selectedBranch:Fe,branchCommits:Ze,loadingBranchCommits:Qe,expandedBranchCommit:Ie,branchCommitDiff:se,loadingBranchCommitDiff:Z,onSelectBranch:Nt,onBranchCommitClick:Tt,onCloseBranchDetails:Ht}),l==="worktrees"&&!u&&t.jsx(e4,{worktrees:ze}),l==="stashes"&&!u&&t.jsx(t4,{stashes:Me,stashMessage:lt,setStashMessage:je,onCreateStash:Ut,onApplyStash:Vt,onDropStash:zt,stashLoading:ie}),l==="remotes"&&!u&&t.jsx(n4,{status:x,remoteLoading:he,lastRemoteResult:Je,onFetch:Ct,onPull:At,onPush:kt,addToast:i,projectId:r,copyToClipboard:f})]})]})]})}):null}function YR({status:e,copyToClipboard:n}){return t.jsxs("div",{className:"gm-panel","data-testid":"status-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Repository Status"})}),t.jsxs("div",{className:"gm-status-grid",children:[t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Branch"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx(Js,{size:14}),t.jsx("span",{children:e.branch})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Commit"}),t.jsxs("span",{className:"gm-status-value",children:[t.jsx("code",{className:"gm-hash",children:e.commit}),t.jsx("button",{className:"gm-icon-btn",onClick:()=>n(e.commit,"commit hash"),title:"Copy commit hash",children:t.jsx(Fi,{size:12})})]})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Working Tree"}),t.jsx("span",{className:`gm-status-badge ${e.isDirty?"dirty":"clean"}`,children:e.isDirty?t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:12}),"Clean"]})})]}),t.jsxs("div",{className:"gm-status-card",children:[t.jsx("span",{className:"gm-status-label",children:"Remote Sync"}),t.jsxs("span",{className:"gm-status-value",children:[e.ahead>0&&t.jsxs("span",{className:"gm-ahead",title:`${e.ahead} commit(s) ahead`,children:[t.jsx(Li,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(xr,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(dn,{size:12}),"Up to date"]})]})]})]})]})}function QR({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:i,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:u,selectedDiffTarget:d,changeDiff:m,loadingChangeDiff:h,changeDiffError:g,commitMessage:p,setCommitMessage:f,onCommit:x,onStageAllAndCommit:v,committing:b}){const y=s.filter(k=>i.has(`unstaged:${k.file}`)),S=n.filter(k=>i.has(`staged:${k.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(Js,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(k=>k.file)),title:"Stage selected",children:[t.jsx(Zt,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(k=>k.file)),title:"Discard selected",children:t.jsx(vr,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(k=>k.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(k=>{const R=d?.file===k.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${R?" active":""}`,onClick:()=>u(k.file,!1),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),u(k.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${k.file}`),onChange:()=>r(`unstaged:${k.file}`)})}),t.jsx(mh,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:k.file}),t.jsx(hh,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),o([k.file])},title:"Stage file",children:t.jsx(Zt,{size:12})})]},`unstaged:${k.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(k=>k.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(k=>k.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(k=>{const R=d?.file===k.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${R?" active":""}`,onClick:()=>u(k.file,!0),role:"button",tabIndex:0,onKeyDown:N=>{(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),u(k.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:N=>N.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${k.file}`),onChange:()=>r(`staged:${k.file}`)})}),t.jsx(mh,{status:k.status}),t.jsx("span",{className:"gm-file-name",title:k.file,children:k.file}),t.jsx(hh,{status:k.status}),t.jsx("button",{className:"gm-icon-btn",onClick:N=>{N.stopPropagation(),l([k.file])},title:"Unstage file",children:t.jsx(Ot,{size:12})})]},`staged:${k.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(Oh,{size:14}),t.jsxs("span",{children:[d.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:d.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}),g&&!h&&t.jsx("div",{className:"gm-diff-error",children:g}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:x,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:k=>f(k.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Di,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function XR({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:i,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:u,copyToClipboard:d}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(oa,{size:14}),t.jsx("input",{type:"text",placeholder:"Search commits...",value:n,onChange:m=>s(m.target.value)})]})]}),t.jsx("div",{className:"gm-commits-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching commits":"No commits found"}):e.map((m,h)=>t.jsxs("div",{className:"gm-commit-item",children:[t.jsxs("div",{className:"gm-commit-graph",children:[t.jsx("div",{className:"gm-commit-dot"}),h<e.length-1&&t.jsx("div",{className:"gm-commit-line"})]}),t.jsxs("div",{className:"gm-commit-body",children:[t.jsxs("button",{className:"gm-commit-header",onClick:()=>l(m.hash),children:[t.jsxs("div",{className:"gm-commit-top-row",children:[t.jsx("code",{className:"gm-hash",children:m.shortHash}),t.jsx("span",{className:"gm-commit-message",title:m.message,children:m.message})]}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:m.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ba(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>d(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(Fi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),u&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function ZR({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:i,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:u,onDeleteBranch:d,loading:m,allBranches:h,selectedBranch:g,branchCommits:p,loadingBranchCommits:f,expandedBranchCommit:x,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:k}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(oa,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:R=>s(R.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:i,onChange:R=>r(R.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:R=>l(R.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(R=>t.jsx("option",{value:R.name,children:R.name},R.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!i.trim(),children:[t.jsx(Zt,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(R=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${R.isCurrent?" current":""}${g===R.name?" selected":""}`,onClick:()=>y(R.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[R.isCurrent&&t.jsx(Mn,{size:14,className:"gm-current-icon"}),R.name]}),R.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",R.remote]}),R.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:ba(R.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!R.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:N=>{N.stopPropagation(),u(R.name)},disabled:m,title:"Checkout",children:t.jsx(Js,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:N=>{N.stopPropagation(),d(R.name)},disabled:m,title:"Delete",children:t.jsx(Xt,{size:14})})]})})]}),g===R.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(lr,{size:14}),"Commits on ",R.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:k,title:"Close","data-testid":"close-branch-details",children:t.jsx(Ot,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(N=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(N.hash),"data-testid":`branch-commit-${N.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:N.shortHash}),t.jsx("span",{className:"gm-commit-message",title:N.message,children:N.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:N.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ba(N.date)}),N.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),x===N.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},N.hash))})]})]},R.name))})]})}function e4({worktrees:e}){return t.jsxs("div",{className:"gm-panel","data-testid":"worktrees-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Worktrees"}),t.jsxs("div",{className:"gm-worktree-stats",children:[t.jsxs("span",{children:[e.length," total"]}),t.jsx("span",{className:"gm-stat-separator",children:"•"}),t.jsxs("span",{children:[e.filter(n=>n.taskId).length," in use"]})]})]}),t.jsx("div",{className:"gm-worktrees-list",children:e.map(n=>t.jsx("div",{className:`gm-worktree-item${n.isMain?" main":""}`,children:t.jsxs("div",{className:"gm-worktree-info",children:[t.jsxs("div",{className:"gm-worktree-path-row",children:[n.isMain&&t.jsx("span",{className:"gm-badge main",children:"main"}),n.isBare&&t.jsx("span",{className:"gm-badge bare",children:"bare"}),t.jsx("span",{className:"gm-worktree-path",title:n.path,children:n.path.split("/").pop()||n.path})]}),t.jsxs("div",{className:"gm-worktree-detail",children:[n.branch&&t.jsxs("span",{className:"gm-worktree-branch",children:[t.jsx(Js,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function t4({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:i,onApplyStash:r,onDropStash:o,stashLoading:l}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:i,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:c=>s(c.target.value),disabled:l!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:l!==null,children:[l==="create"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Mo,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(c=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${c.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:c.message}),t.jsxs("div",{className:"gm-stash-meta",children:[c.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Js,{size:12}),c.branch]}),t.jsx("span",{children:ba(c.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(c.index,!1),disabled:l!==null,title:"Apply stash (keep)",children:l===`apply-${c.index}`?t.jsx(ot,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(c.index,!0),disabled:l!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(c.index),disabled:l!==null,title:"Drop stash",children:l===`drop-${c.index}`?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Xt,{size:14})})]})]},c.index))})]})}function n4({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=Z=>{try{return new URL(Z).hostname}catch{return Z.replace(/^git@/,"").split(":")[0]||Z}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,x]=a.useState(null),[v,b]=a.useState(""),[y,S]=a.useState(""),[k,R]=a.useState(null),[N,M]=a.useState(""),[C,z]=a.useState(""),[A,P]=a.useState(!1),[F,W]=a.useState([]),[$,_]=a.useState(!1),[I,O]=a.useState(null),[J,Q]=a.useState([]),[E,D]=a.useState(!1),[T,w]=a.useState(null),q=m.find(Z=>Z.name===I),[G,me]=a.useState(null),[ce,ae]=a.useState(null),[pe,U]=a.useState(!1),[Ne,ne]=a.useState(null),[xe,le]=a.useState(null),[ve,ee]=a.useState(!1);a.useEffect(()=>{Ee()},[]),a.useEffect(()=>{e&&e.ahead>0?Fe():e&&e.ahead===0&&W([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!I&&O(m[0].name)},[m]),a.useEffect(()=>{I?Ke(I):(Q([]),w(null))},[I]),a.useEffect(()=>{I&&!m.find(Z=>Z.name===I)&&O(m.length>0?m[0].name:null)},[m,I]);const Ee=async()=>{p(!0);try{const Z=await ry(c);h(Z)}catch(Z){l(ke(Z)||"Failed to load remotes","error")}finally{p(!1)}},Fe=async()=>{_(!0);try{const Z=await gy(c);W(Z)}catch{W([])}finally{_(!1)}},Ke=async Z=>{D(!0),w(null);try{const Te=await xy(Z,void 0,10,c);Q(Te)}catch(Te){w(ke(Te)||"Failed to load remote commits"),Q([])}finally{D(!1)}},Ze=Ds(),Xe=async Z=>{if(Z.preventDefault(),!(!v.trim()||!y.trim())){x("add");try{await oy(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),P(!1),await Ee()}catch(Te){l(ke(Te)||"Failed to add remote","error")}finally{x(null)}}},Qe=async Z=>{if(await Ze.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${Z}'?`,danger:!0})){x(`remove-${Z}`);try{await ly(Z,c),l(`Remote '${Z}' removed`,"success"),await Ee()}catch(ze){l(ke(ze)||"Failed to remove remote","error")}finally{x(null)}}},it=async Z=>{if(C.trim()){x(`rename-${Z}`);try{await cy(Z,C.trim(),c),l(`Remote renamed to '${C.trim()}'`,"success"),R(null),z(""),await Ee()}catch(Te){l(ke(Te)||"Failed to rename remote","error")}finally{x(null)}}},Ie=async Z=>{if(N.trim()){x(`url-${Z}`);try{await dy(Z,N.trim(),c),l("Remote URL updated","success"),R(null),M(""),await Ee()}catch(Te){l(ke(Te)||"Failed to update remote URL","error")}finally{x(null)}}},Ge=a.useCallback(async(Z,Te)=>{if(Te==="ahead"){if(G===Z){me(null),ae(null);return}me(Z),ae(null),U(!0);try{const ze=await go(Z);ae(ze)}catch{ae(null)}finally{U(!1)}}else{if(Ne===Z){ne(null),le(null);return}ne(Z),le(null),ee(!0);try{const ze=await go(Z);le(ze)}catch{le(null)}finally{ee(!1)}}},[G,Ne]),se=Z=>{R(`url-${Z.name}`),M(Z.pushUrl||Z.fetchUrl)},ye=Z=>{R(`name-${Z.name}`),z(Z.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>P(!A),disabled:f!==null,title:A?"Cancel":"Add Remote",children:A?t.jsx(Ot,{size:14}):t.jsx(Zt,{size:14})})]}),A&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Xe,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:Z=>b(Z.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:Z=>S(Z.target.value),disabled:f==="add",className:"gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||f==="add",children:[f==="add"?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Zt,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(Z=>t.jsxs("div",{className:`gm-remote-selector-item${I===Z.name?" selected":""}`,onClick:()=>O(Z.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[Z.name,Z.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(Z.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:Te=>{Te.stopPropagation(),Qe(Z.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(Xt,{size:14})})]},Z.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[I&&q?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"gm-remote-sync-card","data-testid":"remote-sync-card",children:[t.jsxs("div",{className:"gm-remote-sync-card-header",children:[t.jsx("span",{className:"gm-remote-sync-card-title",children:I}),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(Li,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(xr,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:i,disabled:n!==null||g,children:[n==="fetch"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Nn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(hs,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(ot,{size:14,className:"spin"}):t.jsx(Li,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),k===`url-${I}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:N,onChange:Z=>M(Z.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Ie(I),disabled:f===`url-${I}`,children:f===`url-${I}`?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Mn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),M("")},title:"Cancel",children:t.jsx(Ot,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:q.fetchUrl,children:q.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(q.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(Fi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>se(q),disabled:f!==null,title:"Edit remote URL",children:t.jsx(Yn,{size:14})})]})]}),q.pushUrl&&q.pushUrl!==q.fetchUrl&&t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Push:"}),t.jsx("span",{className:"gm-url-value",title:q.pushUrl,children:q.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(q.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(Fi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:k===`name-${I}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:C,onChange:Z=>z(Z.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>it(I),disabled:f===`rename-${I}`,children:f===`rename-${I}`?t.jsx(ot,{size:12,className:"spin"}):t.jsx(Mn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),z("")},title:"Cancel",children:t.jsx(Ot,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ye(q),disabled:f!==null,title:"Edit remote name",children:t.jsx(Yn,{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(Li,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:14,className:"spin"}),"Loading..."]}):F.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:F.map(Z=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ge(Z.hash,"ahead"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Z.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Z.message,children:Z.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Z.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ba(Z.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:G===Z.hash?t.jsx(qt,{size:14}):t.jsx(hn,{size:14})})]}),G===Z.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:pe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):ce?t.jsxs(t.Fragment,{children:[Z.message&&t.jsx("div",{className:"gm-commit-message-full",children:Z.message}),ce.stat&&t.jsx("pre",{className:"gm-diff-stat",children:ce.stat}),t.jsx("pre",{className:"gm-diff-patch",children:ce.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Z.hash))}):t.jsx("div",{className:"gm-empty",children:"No ahead commits found (may need to fetch first)"})]}),t.jsxs("div",{className:"gm-remote-section","data-testid":"remote-commits-section",children:[t.jsx("div",{className:"gm-section-subheader",children:t.jsxs("h5",{children:[t.jsx(Wh,{size:14}),"Recent commits on ",I]})}),E?t.jsxs("div",{className:"gm-loading",children:[t.jsx(ot,{size:14,className:"spin"}),"Loading commits..."]}):T?t.jsxs("div",{className:"gm-error",children:[t.jsx(Xn,{size:14}),T]}):J.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",I,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:J.map(Z=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>Ge(Z.hash,"remote"),role:"button",tabIndex:0,title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:Z.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:Z.message,children:Z.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:Z.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:ba(Z.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Ne===Z.hash?t.jsx(qt,{size:14}):t.jsx(hn,{size:14})})]}),Ne===Z.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ve?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(ot,{size:16,className:"spin"}),"Loading diff..."]}):xe?t.jsxs(t.Fragment,{children:[Z.message&&t.jsx("div",{className:"gm-commit-message-full",children:Z.message}),xe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:xe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:xe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},Z.hash))})]})]}):t.jsx("div",{className:"gm-empty",children:"Select a remote to view details"}),s&&t.jsx("div",{className:"gm-remote-result",children:s.message})]})]})})}const Ga={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function s4(e,n){return e&&n?`${e}/${n}`:""}function i4(e){if(!e)return{provider:"",modelId:""};const n=e.indexOf("/");return n===-1?{provider:"",modelId:""}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function a4(e){switch(e){case"file-text":return Oi;case"check-circle":return dn;case"shield":return Ib;case"zap":return Pn;case"eye":return da;case"globe":return To;case"layout-grid":return Bi;default:return dn}}function r4(e){switch(e.toLowerCase()){case"quality":return"wfm-badge-category wfm-badge-category-quality";case"security":return"wfm-badge-category wfm-badge-category-security";default:return"wfm-badge-category"}}function o4({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(!0),[m,h]=a.useState(!0),[g,p]=a.useState("my-steps"),[f,x]=a.useState(null),[v,b]=a.useState(!1),[y,S]=a.useState(Ga),[k,R]=a.useState(!1),[N,M]=a.useState(!1),[C,z]=a.useState(null),[A,P]=a.useState(null),[F,W]=a.useState({}),[$,_]=a.useState([]),I=a.useRef(null);Xs(I,e,"fusion:workflow-steps-modal-size");const O=a.useCallback(async()=>{try{d(!0);const U=await zo(i);o(U)}catch(U){s(ke(U)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),J=a.useCallback(async()=>{try{const U=await hr(i);W(U||{})}catch{}},[i]),Q=a.useCallback(async()=>{try{const U=await cs();_(U.models||[])}catch{}},[]),E=a.useCallback(async()=>{try{h(!0);const U=await hk();c(U.templates)}catch(U){s(ke(U)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(O(),E(),J(),Q())},[e,O,E,J,Q]);const D=a.useCallback(()=>{b(!0),x(null),S(Ga)},[]),T=a.useCallback(U=>{x(U.id),b(!1),S({name:U.name,description:U.description,mode:U.mode||"prompt",phase:U.phase||"pre-merge",prompt:U.prompt,scriptName:U.scriptName||"",enabled:U.enabled,defaultOn:U.defaultOn||!1,modelProvider:U.modelProvider||"",modelId:U.modelId||""})},[]),w=a.useCallback(()=>{x(null),b(!1),S(Ga)},[]),q=a.useCallback(async()=>{if(!y.name.trim()||!y.description.trim()){s("Name and description are required","error");return}R(!0);try{const U=y.mode==="prompt"&&y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:y.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const Ne={name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"&&y.prompt.trim()||void 0,scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...U};await qd(Ne,i),s("Workflow step created","success")}else f&&(await dk(f,{name:y.name.trim(),description:y.description.trim(),mode:y.mode,phase:y.phase,prompt:y.mode==="prompt"?y.prompt:"",scriptName:y.mode==="script"?y.scriptName.trim():void 0,enabled:y.enabled,defaultOn:y.defaultOn,...U},i),s("Workflow step updated","success"));b(!1),x(null),S(Ga),await O()}catch(U){s(ke(U)||"Failed to save workflow step","error")}finally{R(!1)}},[y,v,f,s,O]),G=a.useCallback(async U=>{try{await uk(U,i),s("Workflow step deleted","success"),z(null),f===U&&(x(null),S(Ga)),await O()}catch(Ne){s(ke(Ne)||"Failed to delete workflow step","error")}},[f,s,O]),me=a.useCallback(async()=>{if(!(!f&&!v)&&y.mode==="prompt"){if(v){if(!y.name.trim()||!y.description.trim()){s("Name and description are required before refining","error");return}R(!0);try{const U=y.modelProvider&&y.modelId?{modelProvider:y.modelProvider,modelId:y.modelId}:{},Ne={name:y.name.trim(),description:y.description.trim(),mode:"prompt",prompt:y.prompt.trim()||void 0,enabled:y.enabled,defaultOn:y.defaultOn||void 0,...U},ne=await qd(Ne,i);b(!1),x(ne.id),M(!0);const xe=await Vd(ne.id,i);S(le=>({...le,prompt:xe.prompt})),s("Prompt refined with AI","success"),await O()}catch(U){s(ke(U)||"Failed to refine prompt","error")}finally{R(!1),M(!1)}return}if(f){M(!0);try{const U=await Vd(f,i);S(Ne=>({...Ne,prompt:U.prompt})),s("Prompt refined with AI","success"),await O()}catch(U){s(ke(U)||"Failed to refine prompt","error")}finally{M(!1)}}}},[f,v,y,s,O]),ce=a.useCallback(async U=>{P(U.id);try{await pk(U.id,i),s(`Added ${U.name} workflow step`,"success"),await O(),p("my-steps")}catch(Ne){const ne=ke(Ne);ne?.includes("already exists")?s(`A workflow step named '${U.name}' already exists`,"error"):s(ne||"Failed to add workflow step from template","error")}finally{P(null)}},[s,O]),ae=wi(n);if(!e)return null;const pe=v||f!==null;return t.jsx("div",{className:"modal-overlay open",...ae,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:I,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:u?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!pe&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(_g,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>p("templates"),"data-testid":"tab-templates",children:[t.jsx(Bi,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!pe&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(U=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${U.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:U.name}),t.jsx("span",{className:`wfm-badge ${U.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:U.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(U.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(U.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(U.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(U.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),U.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:U.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>T(U),title:"Edit","aria-label":`Edit ${U.name}`,children:t.jsx(Yn,{size:14})}),C===U.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>G(U.id),title:"Confirm delete","aria-label":`Confirm delete ${U.name}`,children:t.jsx(Mn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>z(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Ot,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>z(U.id),title:"Delete","aria-label":`Delete ${U.name}`,children:t.jsx(Xt,{size:14})})]})]})},U.id))})]}),g==="templates"&&!pe&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(ot,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(U=>{const Ne=a4(U.icon),ne=r4(U.category),xe=A===U.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${U.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(Ne,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:U.name}),t.jsx("span",{className:ne,children:U.category})]}),t.jsx("div",{className:"wfm-template-desc",children:U.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ce(U),disabled:xe,"data-testid":`add-template-${U.id}`,children:xe?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Zt,{size:12}),"Add"]})})]})]})},U.id)})})}),pe&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:v?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:y.name,onChange:U=>S(Ne=>({...Ne,name:U.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:y.description,onChange:U=>S(Ne=>({...Ne,description:U.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${y.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(U=>({...U,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(bi,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${y.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(U=>({...U,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(ri,{size:14}),"Run Script"]})]})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Phase"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-phase-selector",children:[t.jsx("button",{className:`btn ${y.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(U=>({...U,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${y.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>S(U=>({...U,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:y.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field",children:[t.jsxs("div",{className:"wfm-prompt-header",children:[t.jsx("label",{children:"Agent Prompt"}),t.jsxs("button",{className:"btn-icon wfm-refine-btn",onClick:me,disabled:!y.description.trim()||N,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[N?t.jsx(ot,{size:12,className:"spin"}):t.jsx(qn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:y.prompt,onChange:U=>S(Ne=>({...Ne,prompt:U.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),y.mode==="prompt"&&t.jsxs("div",{className:"wfm-field","data-testid":"workflow-step-model-field",children:[t.jsxs("div",{className:"wfm-model-header",children:[t.jsx("label",{children:"Model Override"}),y.modelProvider&&y.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>S(U=>({...U,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Ot,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:y.modelProvider&&y.modelId?`Using ${y.modelProvider}/${y.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx($n,{models:$,value:s4(y.modelProvider,y.modelId),onChange:U=>{const Ne=i4(U);S(ne=>({...ne,modelProvider:Ne.provider,modelId:Ne.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),y.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(F).length===0?t.jsx("div",{className:"wfm-no-scripts","data-testid":"no-scripts-message",children:"No scripts configured. Add scripts in Settings → Scripts first."}):t.jsxs("select",{value:y.scriptName,onChange:U=>S(Ne=>({...Ne,scriptName:U.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(F).map(([U,Ne])=>t.jsxs("option",{value:U,children:[U," (",Ne,")"]},U))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.enabled,onChange:U=>S(Ne=>({...Ne,enabled:U.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:y.defaultOn,onChange:U=>S(Ne=>({...Ne,defaultOn:U.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:w,disabled:k,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:q,disabled:k||!y.name.trim()||!y.description.trim()||y.mode==="script"&&!y.scriptName.trim(),"data-testid":"save-workflow-step",children:k?"Saving...":v?"Create":"Save"})]})]})]})]})}),!pe&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:D,"data-testid":"add-workflow-step",children:[t.jsx(Zt,{size:14}),"Add Workflow Step"]})})]})})}const l4=36e5,c4=3e5,sc=[{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 d4(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 u4(e){return typeof e!="number"||!Number.isFinite(e)?l4:Math.max(c4,Math.round(e))}function jD(e){if(sc.some(s=>s.value===e))return[...sc];const n={value:e,label:`${d4(e)} (custom)`};return[...sc,n].sort((s,i)=>s.value-i.value)}const m4=4,h4=5*6e4;function p4(e){const n=u4(e?.heartbeatIntervalMs);return Math.max(n*m4,h4)}function f4(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 g4(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=f4(e);if(n==="terminated")return{label:"Terminated",icon:t.jsx(ms,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Cs,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Gs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Cs,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(gn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const c=new Date(s).getTime(),u=Date.now()-c,d=p4(o);return u>d?{label:"Unresponsive",icon:t.jsx(Cs,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(zx,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Ja=[{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 x4({isOpen:e,onClose:n,addToast:s,projectId:i}){const[r,o]=a.useState([]),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState(""),[g,p]=a.useState("custom"),[f,x]=a.useState("all"),[v,b]=a.useState(()=>{if(typeof window>"u")return"list";const T=Dn("fn-agent-view",i);return T==="board"||T==="list"?T:"list"});a.useEffect(()=>{const T=Dn("fn-agent-view",i);if(T==="board"||T==="list"){b(T);return}b("list")},[i]),a.useEffect(()=>{os("fn-agent-view",v,i)},[i,v]);const[y,S]=a.useState(null),k=a.useRef(null),[R,N]=a.useState(new Set),[M,C]=a.useState(new Map),{confirm:z}=Ds(),A=a.useMemo(()=>M.size===0?r:r.map(T=>{const w=M.get(T.id);return w?{...T,state:w}:T}),[r,M]),P=a.useMemo(()=>f==="all"?A.filter(T=>T.state!=="terminated"):A,[A,f]),F=a.useCallback(async()=>{c(!0);try{const w=await Na(f!=="all"?{state:f}:void 0,i);o(w)}catch(T){s(`Failed to load agents: ${ke(T)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&F()},[e,F]),a.useEffect(()=>{if(!e)return;const T=setInterval(()=>{F()},3e4);return()=>{clearInterval(T)}},[e,F]);const W=async()=>{if(m.trim())try{await wk({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),F()}catch(T){s(`Failed to create agent: ${ke(T)}`,"error")}},$=async(T,w)=>{if(!R.has(T)){N(q=>new Set(q).add(T)),C(q=>{const G=new Map(q);return G.set(T,w),G});try{await Sk(T,w,i),s(`Agent state updated to ${w}`,"success"),await F(),C(q=>{const G=new Map(q);return G.delete(T),G})}catch(q){C(G=>{const me=new Map(G);return me.delete(T),me}),s(`Failed to update state: ${ke(q)}`,"error")}finally{N(q=>{const G=new Set(q);return G.delete(T),G})}}},_=async(T,w)=>{if(await z({title:"Delete Agent",message:`Delete agent "${w}"? This cannot be undone.`,danger:!0}))try{await Ck(T,i),s(`Agent "${w}" deleted`,"success"),F()}catch(G){s(`Failed to delete agent: ${ke(G)}`,"error")}},I=async(T,w)=>{const q=r.find(G=>G.id===T);if(q){if(q.role===w){S(null);return}try{await Nk(T,{role:w},i),s(`Agent role updated to ${Ja.find(G=>G.value===w)?.label??w}`,"success"),S(null),F()}catch(G){s(`Failed to update role: ${ke(G)}`,"error")}}},O=(T,w)=>{T.key==="Escape"&&S(null)},J=T=>Ja.find(w=>w.value===T)?.label??T,Q=T=>Ja.find(w=>w.value===T)?.icon??"◆",E=T=>g4(T),D=T=>T.color==="var(--state-active-text)"?"active":T.color==="var(--state-paused-text)"?"paused":T.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:T=>T.target===T.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(gn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(Bi,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(gc,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void F(),title:"Refresh",disabled:l,children:t.jsx(Nn,{size:16,className:l?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]})]}),t.jsxs("div",{className:"modal-content agent-modal-content",children:[t.jsxs("div",{className:"agent-controls",children:[t.jsxs("div",{className:"agent-state-filter",children:[t.jsx(uo,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:T=>x(T.target.value),"aria-label":"Filter agents by state",children:[t.jsx("option",{value:"all",children:"All States"}),t.jsx("option",{value:"idle",children:"Idle"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"running",children:"Running"}),t.jsx("option",{value:"paused",children:"Paused"}),t.jsx("option",{value:"error",children:"Error"}),t.jsx("option",{value:"terminated",children:"Terminated"})]})]}),t.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>d(!u),children:[t.jsx(Zt,{size:16}),u?"Cancel":"New Agent"]})]}),u&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:T=>h(T.target.value),onKeyDown:T=>T.key==="Enter"&&W(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:T=>p(T.target.value),children:Ja.map(T=>t.jsxs("option",{value:T.value,children:[T.icon," ",T.label]},T.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void W(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:P.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(gn,{size:48,opacity:.3}),t.jsx("p",{children:"No agents found"}),t.jsx("p",{className:"text-secondary",children:"Create an agent to get started"})]}):v==="board"?P.map(T=>{const w=E(T),q=D(w);return t.jsxs("div",{className:"agent-board-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:Q(T.role)}),t.jsx("span",{className:"agent-board-badge","data-state":T.state,children:T.state}),t.jsx("span",{className:"agent-board-health","data-health":q,title:w.label,children:w.icon})]}),t.jsx("div",{className:"agent-board-name",title:T.name,children:T.name}),t.jsx("div",{className:"agent-board-id",children:T.id}),t.jsxs("div",{className:"agent-board-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Activate",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(T.id,T.name),title:"Delete",children:t.jsx(Xt,{size:14})})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:t.jsx(Gs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Resume",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:t.jsx(Gs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Retry",children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:t.jsx(ms,{size:14})})]}),T.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(T.id,T.name),title:"Delete",children:t.jsx(Xt,{size:14})})]})]},T.id)}):P.map(T=>{const w=E(T),q=D(w);return t.jsxs("div",{className:"agent-card","data-state":T.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===T.id?t.jsx("select",{ref:k,className:"select agent-role-select",value:T.role,onChange:G=>void I(T.id,G.target.value),onKeyDown:G=>O(G,T.id),onBlur:()=>S(null),autoFocus:!0,children:Ja.map(G=>t.jsxs("option",{value:G.value,children:[G.icon," ",G.label]},G.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S(T.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:G=>{(G.key==="Enter"||G.key===" ")&&S(T.id)},children:Q(T.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:T.name}),t.jsx("span",{className:"agent-id text-secondary",children:T.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":T.state,children:T.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":q,title:w.label,children:[w.icon,!w.stateDerived&&` ${w.label}`]}),t.jsx("span",{className:"badge text-secondary",children:J(T.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[T.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:T.taskId})]}),T.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(T.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[T.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Activate",children:[t.jsx(xn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(T.id,T.name),title:"Delete",children:[t.jsx(Xt,{size:14})," Delete"]})]}),T.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:[t.jsx(Gs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),T.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Resume",children:[t.jsx(xn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),T.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"paused"),disabled:R.has(T.id),title:"Pause",children:[t.jsx(Gs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),T.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Retry",children:[t.jsx(xn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void $(T.id,"terminated"),disabled:R.has(T.id),title:"Stop",children:[t.jsx(ms,{size:14})," Stop"]})]}),T.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn-task-create",onClick:()=>void $(T.id,"active"),disabled:R.has(T.id),title:"Start",children:[t.jsx(xn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void _(T.id,T.name),title:"Delete",children:[t.jsx(Xt,{size:14})," Delete"]})]})]})]},T.id)})})]})]})}):null}function b4({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const b=await Jv();return d.current&&r(b),b}catch(b){return d.current&&u({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),g=a.useCallback(async b=>{l(b?"enabling":"disabling"),u(null);try{const y=await Yv(b);d.current&&u({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){d.current&&u({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,f=i?.enabled??e,x=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),f?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void g(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void g(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(An,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(v4,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[x,t.jsx(ph,{status:i,authenticated:e}),c&&t.jsx(fh,{action:c})]})]})]}):t.jsxs("div",{className:`onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(An,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),x,t.jsx(ph,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(fh,{action:c})]})}function v4({status:e,authenticated:n}){const s=e?.enabled??n,i=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!i&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function ph({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(ot,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:i,extension:r,ready:o}=e;return s.available?i?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function fh({action:e}){if(e.kind==="error")return t.jsx("p",{className:"onboarding-helper-text onboarding-helper-text--error",children:e.message});const n=e.kind==="enabled"?"Enabled":"Disabled";return t.jsxs("p",{className:"onboarding-helper-text",children:[n,"."," ",e.kind==="enabled"?"Claude-CLI-routed models are now visible in the model picker.":"Claude-CLI-routed models are hidden from the model picker."]})}function y4(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),i=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(i);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function ic({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=y4(e),o=a.useRef(null),l=a.useCallback(()=>{i(!0),setTimeout(()=>i(!1),2e3)},[]),c=a.useCallback(async()=>{const u=r??e;try{await navigator.clipboard.writeText(u),l()}catch{}},[r,e,l]);return a.useEffect(()=>{const u=o.current===null&&r!==null;if(o.current=r,!u)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((u,d,m)=>t.jsxs("span",{children:[u,d<m.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(Mn,{size:12}):t.jsx(Fi,{size:12})})]})]},d))}):e})}const qi="fusion_model_onboarding_state",va=[],ya=[],Eo=!1,_o=!1,ka={},k4=void 0,xi=["ai-setup","github","project-setup","first-task"],j4={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function gs(){if(typeof window>"u")return null;try{const e=localStorage.getItem(qi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?w4(n):null}catch{return null}}function w4(e){const n=e.postOnboardingDismissedAt??k4;return{...e,completedSteps:e.completedSteps??va,skippedSteps:e.skippedSteps??ya,dismissed:e.dismissed??Eo,completed:e.completed??_o,stepData:e.stepData??ka,...n?{postOnboardingDismissedAt:n}:{}}}function so(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:va,skippedSteps:ya,dismissed:Eo,completed:_o,stepData:ka};try{localStorage.setItem(qi,JSON.stringify(s))}catch{}return}try{const s=gs(),i=new Date().toISOString(),r=n.completed??_o;let o=n.dismissed??Eo;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??va,c=n.skippedSteps??s?.skippedSteps??ya,u={...s?.stepData??ka};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(u[m]={...u[m]??{},...h});const d={currentStep:e,updatedAt:i,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:u};localStorage.setItem(qi,JSON.stringify(d))}catch{}}}function N4(e){if(!(typeof window>"u"))try{const n=gs(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:va,skippedSteps:[e],dismissed:Eo,completed:_o,stepData:ka};localStorage.setItem(qi,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(qi,JSON.stringify(r))}catch{}}function gh(){if(!(typeof window>"u"))try{const e=gs(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:va,skippedSteps:ya,dismissed:!1,completed:!0,stepData:ka};localStorage.setItem(qi,JSON.stringify(s))}catch{}}function ja(){const e=gs();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function S4(){if(!(typeof window>"u"))try{const e=gs(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:va,skippedSteps:ya,dismissed:!1,completed:!1,stepData:ka,postOnboardingDismissedAt:n};localStorage.setItem(qi,JSON.stringify(s))}catch{}}function tg(){const e=gs();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function C4(){const e=gs();return!e||ja()?!1:e.currentStep!=="complete"}function E4(){const e=gs();if(!e||ja()||e.currentStep==="complete")return null;const n=e.currentStep,s=j4[n]??A4(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function _4(){const e=gs();return e?e.skippedSteps:ya}function M4(e){const n=gs();return!n||!n.stepData?null:n.stepData[e]??null}function A4(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const ng="fusion_onboarding_events",xh="fusion_onboarding_session_id",R4=200,T4=50;function ws(e,n={}){if(!(typeof window>"u"))try{const s=I4(),i=L4(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:P4()},o=D4([...s,r]);$4(o)}catch{}}function P4(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(xh);if(e)return e;const n=bh();return sessionStorage.setItem(xh,n),n}catch{return bh()}}function bh(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function I4(){try{const e=localStorage.getItem(ng);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(z4):[]}catch{return[]}}function $4(e){try{localStorage.setItem(ng,JSON.stringify(e))}catch{}}function D4(e){const n=[...e];for(;n.length>R4;)n.splice(0,T4);return n}function L4(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function z4(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 F4={anthropic:{description:"Claude models — strong at reasoning, analysis, and code"},openai:{description:"GPT models — versatile for a wide range of tasks",apiKeyInfo:{fieldLabel:"OpenAI API Key",setupInstructions:"Create an API key from your OpenAI dashboard under API keys.",dashboardUrl:"https://platform.openai.com/api-keys",inputPlaceholder:"sk-...",usageDescription:"Used for GPT models in task execution and planning"}},"openai-codex":{description:"Codex models by OpenAI — optimized for coding tasks"},google:{description:"Gemini models — multimodal with strong reasoning"},gemini:{description:"Gemini models — multimodal with strong reasoning"},ollama:{description:"Run open-source models locally on your machine",apiKeyInfo:{fieldLabel:"Ollama Endpoint",setupInstructions:"Enter your Ollama endpoint URL (for example http://localhost:11434).",inputPlaceholder:"http://localhost:11434",usageDescription:"Connects to your local Ollama instance"}},minimax:{description:"MiniMax models — cost-effective for high-volume usage",apiKeyInfo:{fieldLabel:"MiniMax API Key",setupInstructions:"Generate an API key from the MiniMax platform developer console.",dashboardUrl:"https://platform.minimaxi.com/",inputPlaceholder:"Enter your MiniMax API key",usageDescription:"Used for MiniMax models in task execution"}},zai:{description:"GLM models by Zhipu AI — strong multilingual support",apiKeyInfo:{fieldLabel:"Zhipu AI API Key",setupInstructions:"Create an API key in the Zhipu AI open platform account settings.",dashboardUrl:"https://open.bigmodel.cn/",inputPlaceholder:"Enter your Zhipu AI API key",usageDescription:"Used for GLM models in task execution"}},kimi:{description:"Kimi by Moonshot AI — long-context capabilities"},moonshot:{description:"Kimi by Moonshot AI — long-context capabilities"},"kimi-coding":{description:"Kimi by Moonshot AI — long-context capabilities",apiKeyInfo:{fieldLabel:"Kimi API Key",setupInstructions:"Create your API key in the Moonshot platform account settings.",dashboardUrl:"https://platform.moonshot.cn/",inputPlaceholder:"Enter your Kimi API key",usageDescription:"Used for Kimi/Moonshot AI models in task execution and planning"}},openrouter:{description:"OpenRouter — route requests across multiple AI providers",apiKeyInfo:{fieldLabel:"OpenRouter API Key",setupInstructions:"Create an API key from your OpenRouter account key management page.",dashboardUrl:"https://openrouter.ai/keys",inputPlaceholder:"sk-or-v1-...",usageDescription:"Routes to multiple AI model providers through a single key"}}},sg={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:"..."}},O4={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},vh={anthropic:"Anthropic",openai:"OpenAI","openai-codex":"OpenAI Codex",openrouter:"OpenRouter",google:"Google",gemini:"Gemini",minimax:"MiniMax",ollama:"Ollama",zai:"Zhipu AI",kimi:"Kimi","kimi-coding":"Kimi Coding",moonshot:"Moonshot"};function Hc(e){if(vh[e])return vh[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 ac=["anthropic","openai","google","gemini","ollama"],U4=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],B4={anthropic:"anthropic","claude-cli":"claude-cli","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},H4={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function qc(e){return B4[e]??e}function yh(e){const n=qc(e),s=U4.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function kh(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=yh(e.id),i=yh(n.id);if(s!==i)return s-i;const r=qc(e.id),o=qc(n.id);if(r!==o)return r.localeCompare(o);const l=H4[r];if(l){const u=l.indexOf(e.id),d=l.indexOf(n.id);if(u!==d)return(u===-1?Number.POSITIVE_INFINITY:u)-(d===-1?Number.POSITIVE_INFINITY:d)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function q4(e,n){const s=n.trim();if(!s)return"API key is required";const i=sg[e]??O4;return i.pattern.test(s)?null:`${Hc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const ig={fieldLabel:"API Key",setupInstructions:"Enter your API key for this provider.",inputPlaceholder:"Enter API key",usageDescription:"Used by Fusion to authenticate requests to this provider"},V4={description:"AI provider — connect to start using AI models",apiKeyInfo:ig};function Vc(e){return F4[e]??V4}function W4(e){return Vc(e.id).apiKeyInfo??ig}function Ws({summary:e,children:n,className:s=""}){const[i,r]=a.useState(!1);return t.jsxs("div",{className:`onboarding-disclosure ${s}`,children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>r(!i),"aria-expanded":i,type:"button",children:[t.jsx(hn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),i&&t.jsx("div",{className:"onboarding-disclosure-content",children:n})]})}function K4({items:e}){return e.some(s=>s.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),e.map(s=>{const i=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:i}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function G4({provider:e,apiKeyInfo:n,inputValue:s,isSaving:i,error:r,success:o,isConnected:l,onInputChange:c,onSave:u,onClear:d}){const m=`onboarding-apikey-input-${e.id}`,h=i||!s.trim(),g=sg[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,f=t.jsxs(t.Fragment,{children:[g&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",g.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>d(e.id),disabled:i,children:i?"Removing…":"Remove Key"}),t.jsx(Ws,{summary:"Advanced setup details",children:f}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:x=>c(e.id,x.target.value),onKeyDown:x=>{x.key==="Enter"&&u(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>u(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(Ws,{summary:"Advanced setup details",children:f})]})}const J4=150;function Y4({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=gs(),d=u?.currentStep,m=d==="complete"?"ai-setup":xi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??_4(),[p,f]=a.useState(!0),[x,v]=a.useState(m),[b,y]=a.useState(h),[S,k]=a.useState(g),[R,N]=a.useState(!1),[M,C]=a.useState(""),[z,A]=a.useState(!1),[P,F]=a.useState(null),[W,$]=a.useState(null),[_,I]=a.useState([]),[O,J]=a.useState(void 0),[Q,E]=a.useState(!0),[D,T]=a.useState(null),[w,q]=a.useState({}),[G,me]=a.useState([]),[ce,ae]=a.useState(""),[pe,U]=a.useState(!1),[Ne,ne]=a.useState({}),[xe,le]=a.useState({}),[ve,ee]=a.useState({}),Ee=a.useRef({}),Fe=a.useRef(null),Ke=a.useRef(null),Ze=a.useRef(null),[Xe,Qe]=a.useState({}),[it,Ie]=a.useState(()=>gs()?.stepData?.github?.skipped===!0),Ge=a.useRef(0),se=a.useRef(l),ye=a.useRef(!1),Z=u?.currentStep,Te=!!u&&u.currentStep!=="complete";Xs(Ke,p,"fusion:model-onboarding-modal-size"),a.useEffect(()=>{const Y=Fe.current;Y&&(Y.scrollTop=0)},[x]);const[ze,be]=a.useState(()=>gs()?.stepData?.["ai-setup"]?.skippedProviders??{}),Me=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Be=Me.findIndex(Y=>Y.key===x),lt=x==="complete"?Me.length:Be;a.useEffect(()=>{x!=="complete"&&so(x,{completedSteps:b,skippedSteps:S})},[x,b,S]),a.useEffect(()=>{ye.current||(ye.current=!0,ws("onboarding:wizard-opened",{source:Te?"resume":"initial",resumedFromStep:Z}))},[Te,Z]),a.useEffect(()=>{const Y=se.current!=null,Oe=l!=null;!Y&&Oe&&N(!0),Oe||N(!1),se.current=l},[l]);const je=a.useRef(m);a.useEffect(()=>{if(je.current==="ai-setup"&&x!=="ai-setup"&&!_.some(Oe=>Oe.id!=="github"&&Oe.authenticated)){const Oe={};for(const Ye of _)Ye.id!=="github"&&!Ye.authenticated&&!ze[Ye.id]&&(Oe[Ye.id]=!0);if(Object.keys(Oe).length>0){const Ye={...ze,...Oe};be(Ye),so(x,{stepData:{"ai-setup":{skippedProviders:Ye}}})}}je.current=x},[x,_,ze]);const ie=a.useCallback(async()=>{try{const{providers:Y,ghCli:Oe}=await mr();I(Y),J(Oe),q(Ye=>{const st={};for(const[pt,jt]of Object.entries(Ye)){const _t=Y.find(yn=>yn.id===pt);_t&&!_t.authenticated&&(st[pt]=jt)}return Object.keys(st).length===Object.keys(Ye).length?Ye:st}),be(Ye=>{const st={...Ye};for(const pt of Y)pt.authenticated&&st[pt.id]&&delete st[pt.id];return Object.keys(st).length===Object.keys(Ye).length?Ye:st})}catch{}},[]),Ae=a.useRef(!1);a.useEffect(()=>{Ae.current&&ie(),Ae.current=x!=="ai-setup"},[x,ie]);const he=_.find(Y=>Y.id==="github"),Re=!!he,Je=he?.authenticated??!1,$e=O?.authenticated??!1,de=Je||$e,re=!Je&&$e,ue=a.useCallback(Y=>{if(Y.authenticated)return"connected";const Oe=Xe?.[Y.id];return Oe==="timeout"||Oe==="failed"?"retry":ze[Y.id]?"skipped":"not-connected"},[Xe,ze]);function Pe({status:Y}){const Oe={connected:{text:"✓ Connected",className:"auth-status-badge connected"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},retry:{text:"Retry",className:"auth-status-badge retry"}},{text:Ye,className:st}=Oe[Y];return t.jsx("span",{"data-testid":"provider-status-badge",className:st,"data-status":Y,children:Ye})}const Se=a.useCallback(()=>{if(de)return"connected";const Y=Xe.github;return Y==="pending"?"pending":Y==="failed"||Y==="timeout"?"failed":it?"skipped":"not-connected"},[de,Xe,it]);function fe({status:Y}){const Oe={connected:{text:"✓ Connected",className:"auth-status-badge connected"},pending:{text:"⏳ Connecting…",className:"auth-status-badge pending"},failed:{text:"✗ Connection failed",className:"auth-status-badge retry"},skipped:{text:"Skipped",className:"auth-status-badge skipped"},"not-connected":{text:"Not connected",className:"auth-status-badge not-connected"}},{text:Ye,className:st}=Oe[Y];return t.jsx("span",{"data-testid":"github-status-badge",className:st,"data-status":Y,children:Ye})}const tt=a.useCallback(async()=>{try{const Y=await cs();me(Y.models)}catch{}},[]),ut=a.useCallback(async()=>{try{const Y=await Vi();if(Y.defaultProvider&&Y.defaultModelId){const Oe=`${Y.defaultProvider}/${Y.defaultModelId}`;ae(Oe)}}catch{}},[]);a.useEffect(()=>{Promise.all([ie(),tt(),ut()]).finally(()=>E(!1))},[ie,tt,ut]),a.useEffect(()=>{const Y=M4("ai-setup");if(Y?.loginOutcomes){const Oe=Y.loginOutcomes,Ye={};for(const[st,pt]of Object.entries(Oe))pt!=="pending"&&(Ye[st]=pt);Object.keys(Ye).length>0&&Qe(Ye)}},[]);const vt=a.useCallback((Y,Oe)=>{so(x,{completedSteps:b,stepData:{"ai-setup":{loginOutcomes:{[Y]:Oe}}}})},[x,b]);a.useEffect(()=>{const Y=Object.entries(Xe).filter(([Oe,Ye])=>Ye!=="pending");for(const[Oe,Ye]of Y)vt(Oe,Ye)},[Xe,vt]),a.useEffect(()=>()=>{Ze.current&&clearInterval(Ze.current),Object.values(Ee.current).forEach(clearTimeout),Ee.current={}},[]);const gt=a.useCallback(Y=>{Ie(Y),so(x,{completedSteps:b,stepData:{github:{skipped:Y}}})},[x,b]),dt=a.useCallback(Y=>Y==="complete"?-1:xi.indexOf(Y),[]),wt=a.useCallback(()=>{y(Oe=>[...new Set([...Oe,x])]),k(Oe=>Oe.filter(Ye=>Ye!==x)),ws("onboarding:step-completed",{step:x}),x==="github"&&!Je&>(!1);const Y=dt(x);Y>=0&&Y<xi.length-1&&v(xi[Y+1])},[x,Je,gt,dt]),Mt=a.useCallback(()=>{k(Oe=>[...new Set([...Oe,x])]),N4(x),ws("onboarding:step-skipped",{step:x}),x==="github"&&!Je&>(!0);const Y=dt(x);Y>=0&&Y<xi.length-1&&v(xi[Y+1])},[x,Je,gt,dt]),yt=a.useCallback(()=>{const Y=x;y(Ye=>Ye.filter(st=>st!==Y)),k(Ye=>Ye.filter(st=>st!==Y)),Y==="github"&&!Je&>(!1);const Oe=dt(x);Oe>0&&v(xi[Oe-1])},[x,Je,gt,dt]),Et=a.useCallback(()=>{Mt()},[Mt]),Nt=a.useCallback(async Y=>{Qe(Oe=>{const Ye=Oe[Y];if(Ye&&Ye!=="pending"){const{[Y]:st,...pt}=Oe;return pt}return Oe}),q(Oe=>{if(!(Y in Oe))return Oe;const Ye={...Oe};return delete Ye[Y],Ye}),Qe(Oe=>({...Oe,[Y]:"pending"})),T(Y),Ge.current=0;try{const{url:Oe,instructions:Ye}=await Qv(Y);Ye?.trim()&&q(st=>({...st,[Y]:Ye})),window.open(Qs(Oe),"_blank"),Ze.current=setInterval(async()=>{if(Ge.current++,Ge.current>=J4){Ze.current&&(clearInterval(Ze.current),Ze.current=null),T(null),Qe(st=>({...st,[Y]:"timeout"})),q(st=>{if(!(Y in st))return st;const pt={...st};return delete pt[Y],pt}),n("Login timed out. Please try again.","warning");return}try{const{providers:st,ghCli:pt}=await mr();I(st),J(pt),st.find(_t=>_t.id===Y)?.authenticated&&(Ze.current&&(clearInterval(Ze.current),Ze.current=null),T(null),Qe(_t=>({..._t,[Y]:"success"})),q(_t=>{if(!(Y in _t))return _t;const yn={..._t};return delete yn[Y],yn}),Y==="github"&>(!1),n("Login successful","success"))}catch{}},2e3)}catch(Oe){Oe instanceof Error&&Oe.message.includes("already in progress")||Oe&&typeof Oe=="object"&&"status"in Oe&&Oe.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Qe(st=>({...st,[Y]:"failed"}))):(n(Oe instanceof Error?Oe.message:"Login failed","error"),Qe(st=>({...st,[Y]:"failed"}))),T(null),q(st=>{if(!(Y in st))return st;const pt={...st};return delete pt[Y],pt})}},[n,gt]),Tt=a.useCallback(Y=>{Ze.current&&(clearInterval(Ze.current),Ze.current=null),T(null),Ge.current=0,Qe(Oe=>({...Oe,[Y]:"cancelled"})),q(Oe=>{if(!(Y in Oe))return Oe;const Ye={...Oe};return delete Ye[Y],Ye})},[]),Ht=a.useCallback((Y,Oe)=>{ne(st=>({...st,[Y]:Oe}));const Ye=Ee.current[Y];Ye&&(clearTimeout(Ye),delete Ee.current[Y]),le(st=>{if(!st[Y])return st;const pt={...st};return delete pt[Y],pt}),ee(st=>{if(!st[Y])return st;const pt={...st};return delete pt[Y],pt})},[]),Ut=a.useCallback(()=>{const Y=Fe.current;if(!Y)return;const Oe=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof Y.scrollTo=="function"){Y.scrollTo({top:0,behavior:Oe?"auto":"smooth"});return}}catch{}Y.scrollTop=0},[]),Vt=a.useCallback(async(Y,Oe)=>{const Ye=(Oe??Ne[Y]??"").trim(),st=q4(Y,Ye);if(st){le(jt=>({...jt,[Y]:st}));return}const pt=Ee.current[Y];pt&&(clearTimeout(pt),delete Ee.current[Y]),T(Y),le(jt=>{const _t={...jt};return delete _t[Y],_t}),ee(jt=>{if(!jt[Y])return jt;const _t={...jt};return delete _t[Y],_t});try{await Zv(Y,Ye),await ie(),Ut(),ne(jt=>{const _t={...jt};return delete _t[Y],_t}),le(jt=>{if(!jt[Y])return jt;const _t={...jt};return delete _t[Y],_t}),ee(jt=>({...jt,[Y]:"✓ Key saved"})),Ee.current[Y]=setTimeout(()=>{ee(jt=>{if(!jt[Y])return jt;const _t={...jt};return delete _t[Y],_t}),delete Ee.current[Y]},3e3),n("API key saved","success")}catch(jt){const _t=jt instanceof TypeError&&jt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":jt instanceof Error?jt.message:"Failed to save API key";le(yn=>({...yn,[Y]:_t})),ee(yn=>{if(!yn[Y])return yn;const en={...yn};return delete en[Y],en}),n(_t,"error")}finally{T(null)}},[Ne,n,ie,Ut]),zt=a.useCallback(async Y=>{T(Y);try{await ey(Y),await ie(),n("API key removed","success")}catch(Oe){n(Oe instanceof Error?Oe.message:"Failed to clear API key","error")}finally{T(null)}},[n,ie]),Ct=a.useCallback(async Y=>{T(Y);try{await Xv(Y),await ie(),n("Logged out","success")}catch(Oe){n(Oe instanceof Error?Oe.message:"Logout failed","error")}finally{T(null)}},[n,ie]),At=a.useCallback(Y=>{ae(Y)},[]),kt=a.useCallback(async()=>{try{const Y={modelOnboardingComplete:!0};if(ce){const Oe=ce.indexOf("/"),Ye=Oe!==-1?ce.slice(0,Oe):void 0,st=Oe!==-1?ce.slice(Oe+1):ce,pt=G.find(jt=>jt.id===st);pt?(Y.defaultProvider=pt.provider,Y.defaultModelId=pt.id):Ye&&st&&(Y.defaultProvider=Ye,Y.defaultModelId=st)}await sn(Y),gh()}catch{}},[ce,G,sn,gh]),Kt=a.useCallback(async()=>{const Y=[...new Set([...b,"first-task"])];U(!0);try{await kt(),ws("onboarding:completed",{completedSteps:Y,skippedSteps:S}),y(Y),k(Oe=>Oe.filter(Ye=>Ye!=="first-task")),v("complete")}finally{U(!1)}},[kt,b,S]),$t=a.useCallback(async()=>{if(!s)return;const Y=M.trim();if(!Y){F("Please enter a task description.");return}F(null),A(!0);let Oe=!1;try{const Ye=await Xh({description:Y},s);$(Ye),N(!0),ws("onboarding:first-task-created",{taskId:Ye?.id}),n("Task created","success"),Oe=!0}catch(Ye){const st=Ye instanceof Error?Ye.message:"Something went wrong creating your task. Please try again.";F(st),n(st,"error")}finally{A(!1)}Oe&&kt()},[s,M,n,kt]),B=a.useCallback(async()=>{U(!0);try{await kt()}finally{U(!1)}ws("onboarding:open-new-task",{}),r?.()},[kt,r]),ge=a.useCallback(async()=>{if(de){U(!0);try{await kt()}finally{U(!1)}f(!1),e(),ws("onboarding:open-github-import",{}),o?.()}},[kt,de,e,o]),te=a.useCallback(async()=>{ws("onboarding:dismissed",{currentStep:x,completedSteps:b,skippedSteps:S}),U(!0);try{await sn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[x,b,S,e]),j=a.useCallback(()=>{ws("onboarding:finished",{}),f(!1),e()},[e]),V=a.useCallback(()=>{const Y=l??W;Y&&(kt(),c?.(Y),e())},[l,W,kt,c,e]),De=a.useCallback(()=>{kt(),e()},[kt,e]);if(!p)return null;const nt=Se(),St=_.filter(Y=>Y.id!=="github"),Pt=[...St].sort(kh),Rt=Pt.some(Y=>!Y.type||Y.type==="oauth"),un=Pt.some(Y=>Y.type==="api_key"),mn=St.filter(Y=>Y.authenticated),wn=mn.length>0,Gt=!!s,es=x==="github"&&!wn,we=(()=>{if(!ce)return"";const Y=ce.indexOf("/"),Oe=Y===-1?void 0:ce.slice(0,Y),Ye=Y===-1?ce:ce.slice(Y+1),st=G.find(pt=>pt.id===Ye&&(!Oe||pt.provider===Oe));return st?.name?st.name:Oe?`${Hc(Oe)} ${Ye}`:ce})(),rt=[];if(Gt?rt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):rt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),wn){const Y=Hc(mn[0]?.id??"");rt.push({label:"AI Provider",status:"connected",detail:`${Y} connected — AI agents can work on tasks`})}else St.length>0&&St.some(Y=>ze[Y.id])?rt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):rt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});de?rt.push({label:"GitHub",status:"connected",detail:re?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Re||it?rt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):rt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),we&&rt.push({label:"Default Model",status:"connected",detail:we});const Jt=l??W,Sn=Jt?.description?.split(`
|
|
656
|
-
`)[0]?.trim()||Jt?.title||"",Cn=new Set(ac),pn=Pt.filter(Y=>Cn.has(Y.id)).sort((Y,Oe)=>{const Ye=ac.indexOf(Y.id),st=ac.indexOf(Oe.id);return Ye!==st?Ye-st:kh(Y,Oe)}),bn=Pt.filter(Y=>Y.authenticated&&!Cn.has(Y.id)),Rn=Pt.filter(Y=>!Y.authenticated&&!Cn.has(Y.id)),vn=Y=>{if(Y.id==="claude-cli"&&Y.type==="cli")return t.jsx(b4,{authenticated:Y.authenticated,onToggled:()=>{ie()}},Y.id);if(Y.type==="api_key"){const Oe=Vc(Y.id),Ye=W4(Y);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Y.id}`,className:`onboarding-provider-card${Y.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Y.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:Y.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Vh,{size:14,className:"onboarding-provider-key-icon"}),Y.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Oe.description}),t.jsx(Pe,{status:ue(Y)}),Y.authenticated&&Y.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",Y.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(G4,{provider:Y,apiKeyInfo:Ye,inputValue:Ne[Y.id]??"",isSaving:D===Y.id,error:xe[Y.id],success:ve[Y.id],isConnected:Y.authenticated,onInputChange:Ht,onSave:Vt,onClear:zt})})]},Y.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Y.id}`,className:`onboarding-provider-card${Y.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Y.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:Y.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:Y.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Vc(Y.id).description}),t.jsx(Pe,{status:ue(Y)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:D===Y.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:Y.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Tt(Y.id),children:"Cancel"})]}):Y.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct(Y.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Nt(Y.id),children:"Login"})}),D===Y.id&&w[Y.id]&&t.jsx(ic,{instructions:w[Y.id],"data-testid":`onboarding-login-instructions-${Y.id}`}),Xe[Y.id]==="timeout"&&D!==Y.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Xe[Y.id]==="failed"&&D!==Y.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},Y.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:Ke,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(Pn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(hs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(_d,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(_d,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:te,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Ot,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Me.map((Y,Oe)=>{const Ye=lt>Oe,st=b.includes(Y.key)&&Ye,pt=S.includes(Y.key)&&!b.includes(Y.key)&&Ye,jt=st||pt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Oe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Oe<=lt?"done":""}`}),jt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===Y.key?"active":""} ${st?"done":""} ${pt?"skipped":""}`,onClick:()=>v(Y.key),"aria-label":`Go back to ${Y.label}`,title:`Review ${Y.label}`,children:[t.jsx("span",{className:"step-number",children:st?t.jsx(dn,{size:14}):pt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Oe+1}),t.jsx("span",{className:"step-label",children:Y.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===Y.key?"active":""} ${st?"done":""} ${pt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:st?t.jsx(dn,{size:14}):pt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Oe+1}),t.jsx("span",{className:"step-label",children:Y.label})]})]},Y.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Fe,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!Q&&_.length>0&&(()=>{const Y=_.filter(jt=>jt.id!=="github"&&jt.authenticated).length,Oe=_.filter(jt=>jt.id!=="github").length,Ye=Object.keys(ze).filter(jt=>!_.find(_t=>_t.id===jt)?.authenticated).length;if(Oe===0)return null;let st="onboarding-provider-summary",pt="";return Y>0?(st+=" onboarding-provider-summary--connected",pt=`✓ ${Y} of ${Oe} provider${Oe!==1?"s":""} connected`):Ye>0?(st+=" onboarding-provider-summary--skipped",pt=`${Ye} provider${Ye!==1?"s":""} skipped`):(st+=" onboarding-provider-summary--none",pt="No providers connected yet"),t.jsx("div",{className:st,"data-testid":"provider-summary",children:pt})})(),t.jsx(Ws,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),_.length>0&&!_.some(Y=>Y.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),Q?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(ot,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):_.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),pn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:pn.map(Y=>vn(Y))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),bn.length>0&&t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connected providers"}),t.jsx("div",{className:"model-onboarding-providers",children:bn.map(Y=>vn(Y))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(Ws,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),G.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx($n,{models:G,value:ce,onChange:At,placeholder:"Select a default model…",label:"Default model"})}),ce&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",G.find(Y=>Y.id===ce)?.name??ce]})})]}),t.jsx(Ws,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:Rn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Rn.map(Y=>vn(Y))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),Rt&&t.jsx(Ws,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),un&&t.jsx(Ws,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[de?t.jsx("p",{className:"model-onboarding-description",children:re?"GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed.":"GitHub is connected — issue imports and pull request tracking are available. You're all set; no further action needed."}):t.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),!de&&t.jsx("div",{className:"onboarding-feature-list",children:t.jsxs("ul",{children:[t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"Without GitHub (available now):"})}),t.jsx("li",{className:"onboarding-helper-text",children:"Create tasks manually"}),t.jsx("li",{className:"onboarding-helper-text",children:"Describe work for AI agents"}),t.jsx("li",{className:"onboarding-helper-text",children:"Track progress on the board"}),t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"With GitHub (after connecting):"})}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Import issues as tasks"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Sync pull request status"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Link code changes to tasks"})]})}),es&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:"No AI provider connected"}),t.jsx("p",{children:"AI features like task planning and code generation won't be available until you connect one. You can set this up later in Settings."})]}),t.jsx(Ws,{summary:"What does GitHub integration do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Without GitHub, you can still create and manage tasks manually. GitHub integration adds the ability to import issues as tasks, track pull request status alongside your work, and automatically link commits to tasks. Connect anytime from Settings → Authentication."})}),Re?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(hs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(fe,{status:nt})})]}),Je&&(D==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct("github"),children:"Disconnect"}))]}),(nt==="not-connected"||nt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[D==="github"?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Tt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Nt("github"),children:[t.jsx(hs,{size:16}),"Connect"]}),D==="github"&&w.github&&t.jsx(ic,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]}),nt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:re?"GitHub CLI is authenticated. Imports and pull request tracking are available. Connect OAuth in Settings → Authentication if you want dashboard-managed sign-in controls.":"GitHub OAuth is connected. You can import issues and track pull requests."}),nt==="failed"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[t.jsx("p",{children:"Connection failed or timed out."}),t.jsxs("div",{className:"onboarding-github-feedback-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Et,children:"Skip for now"})]})]}),nt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),nt==="skipped"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[t.jsx("p",{children:"GitHub was skipped. You can connect anytime from Settings → Authentication."}),t.jsx("div",{className:"onboarding-github-feedback-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:"Connect anyway"})})]}),nt==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(An,{provider:"github",size:"lg"})}),re?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:re?"Continue with gh CLI auth →":"Continue without GitHub →"}),re&&(D==="github"?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(ot,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:[t.jsx(An,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),re&&D==="github"&&w.github&&t.jsx(ic,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),Gt?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(Ws,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),R&&Jt?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(dn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:Jt.id}),Sn&&t.jsx("p",{className:"onboarding-task-created__description",children:Sn}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:V,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:De,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Gt?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:M,onChange:Y=>{C(Y.target.value),F(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:$t,disabled:z,"data-testid":"onboarding-first-task-submit",children:z?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),P&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:P}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(K4,{items:rt}),Gt&&t.jsxs(t.Fragment,{children:[t.jsx(Ws,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:B,disabled:pe,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Zt,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Create a New Task"}),t.jsx("span",{children:"Describe what you need built and AI will work on it"})]})]}),t.jsxs("button",{className:`onboarding-cta-card${de?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:ge,disabled:pe||!de,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(hs,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!de&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(dn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:te,disabled:pe,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Mt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Mt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,disabled:!Gt,children:"Next →"})]}),x==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Kt,disabled:pe,children:pe?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:j,children:[t.jsx(dn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function ag({toasts:e}){return t.jsx("div",{className:"toast-container",id:"toasts",children:e.map(n=>t.jsx("div",{className:`toast toast-${n.type}`,children:n.message},n.id))})}const Q4=a.lazy(()=>nn(()=>import("./SetupWizardModal-Y2ewEE8Y.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),X4=a.lazy(()=>nn(()=>import("./SettingsModal-DvRd0ZOE.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function Z4(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{nn(()=>import("./SettingsModal-DvRd0ZOE.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function eT({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[x,v]=a.useState(null),b=c.detailTask?(()=>{const M=n.find(C=>C.id===c.detailTask?.id);return M?"prompt"in c.detailTask?{...c.detailTask,...M,prompt:c.detailTask.prompt,log:c.detailTask.log}:M:c.detailTask})():null,y=p??c.closeSettings,S=a.useCallback(()=>{c.openNewTask()},[c]),k=a.useCallback(()=>{c.openGitHubImport()},[c]),R=a.useCallback(M=>{v(null),c.closeModelOnboarding(),c.openDetailTask(M)},[c]),N=a.useCallback(async M=>{const C=await d.handleModalCreate(M);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),a.useEffect(()=>{Z4()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ti,{children:t.jsx(XM,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:g.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ti,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(X4,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(eA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ti,{children:t.jsx(iA,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:d.handlePlanningTaskCreated,onTasksCreated:d.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(Ti,{children:t.jsx(pA,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx($A,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(LA,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(iR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(hR,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(BR,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(PR,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ti,{children:t.jsx(LR,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:N,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(KR,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:M=>{const C=n.find(z=>z.id===M);C&&c.openDetailTask(C)}}),t.jsx(Ti,{children:t.jsx(JR,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ti,{children:t.jsx(o4,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(x4,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(Q4,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(Y4,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:k,firstCreatedTask:x,onViewTask:R}),t.jsx(ag,{toasts:o,onRemove:l})]})}function tT({errorMessage:e,isRetrying:n,onRetry:s}){return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:"Can't reach the Fusion backend"}),t.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),t.jsxs("p",{className:"settings-muted",children:["Error: ",e]}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"})]})}const Wc=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function nT(e,n){if(n==="ready")return"done";const s=Wc.findIndex(r=>r.id===n),i=Wc.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function sT({stage:e}){const[n]=a.useState(()=>tv());return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":n?"Updating Fusion dashboard":"Loading Fusion dashboard","data-stage":e,"data-version-update":n?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),n?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:"Updating to a new frontend version..."}):t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:Wc.map(s=>{const i=nT(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${i}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:i==="done"?"✓":i==="active"?t.jsx(ot,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const iT=5e3;function aT(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function rT(e,n,s){let i=0,r=0,o=0,l=0,c=0;for(const u of e){switch(u.column){case"in-progress":i++,vo(u,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}u.blockedBy&&u.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function oT(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),g=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await Pk(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(g(),()=>{h.current&&h.current.abort()}),[g]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{g()},iT),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=rT(e,s,i),f=aT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const lT={planning:Ys,subtask:Ui,mission_interview:ls,milestone_interview:ls,slice_interview:ls},cT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function dT({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Ds(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),g=a.useRef(null),{activeTabMap:p}=Sa(),f=a.useMemo(()=>Wi(),[]);if(a.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),a.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const k=p.get(S.id),R=[S.status,S.updatedAt,k?.tabId??S.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),N=h.current.get(S.id);N&&N!==R&&b.add(S.id),y.set(S.id,R)}if(h.current=y,b.size!==0)return d(b),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{d(new Set),g.current=null},500),()=>{g.current&&(clearTimeout(g.current),g.current=null)}},[p,e]),e.length===0)return null;const x=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(ot,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(mc,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=lT[b.type],S=b.status==="generating",k=b.status==="awaiting_input",R=b.status==="error",N=p.get(b.id),M=N?.tabId??b.lockedByTab??null,C=!!(M&&M!==f&&!N?.stale),z=u.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${z?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:z?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:z?"translateY(-1px)":void 0},onClick:async()=>{C&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(b),c(!1))},children:[R?t.jsx(Xn,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[R?"Failed":cT[b.type],S&&" — generating...",k&&!C&&" — needs input",k&&C&&" — active in another tab"]})]}),S&&t.jsx(ot,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!C&&t.jsx(mc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&C&&t.jsx(Io,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:A=>{A.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(Ot,{size:12})})]},b.id)})})]})]})}function uT(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),i=n-s,r=Math.floor(i/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function mT(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:xn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Gs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Pn}}}function hT({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:g,error:p}=oT(e,n,s,u),[f,x]=a.useState(!1),v=a.useMemo(()=>mT(h.executorState),[h.executorState]),b=a.useMemo(()=>uT(h.lastActivityAt),[h.lastActivityAt]),y=v.icon;return p?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(Yc,{size:14}),p]})}):g&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(dT,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${f?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>x(S=>!S),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:t.jsx(In,{size:12,"aria-hidden":"true"})}),f&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(yi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:b})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const pT={planning:Ys,subtask:Ui,mission_interview:ls,milestone_interview:ls,slice_interview:ls},fT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},$i=new Set;function gT({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if($i.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let x=!1;for(const v of $i){const b=f.get(v);b&&b.status!=="awaiting_input"&&b.status!=="error"&&($i.delete(v),x=!0)}x&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!$i.has(f.id)),[e,r]);if(c.length===0)return null;const u=c.filter(f=>f.status==="awaiting_input").length,d=c.filter(f=>f.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=f=>{$i.add(f),l()},g=f=>{$i.delete(f.id),l(),n(f)},p=()=>{for(const f of c)$i.add(f.id);l(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(Xn,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Ot,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const x=pT[f.type],v=f.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(Xn,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":fT[f.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:t.jsx(Ot,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function xT({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/releases",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(Ot,{size:16,"aria-hidden":"true"})})]})}function bT({onResume:e}){const n=E4();if(!n)return null;const s=n.completedSteps.length,i=xi.length,r=s>0?`${s} of ${i} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(qn,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[r,t.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),t.jsx("div",{className:"onboarding-resume-card__actions",children:t.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{ws("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function vT({onOpenSettings:e,onOpenModelOnboarding:n}){const s=ja(),i=tg(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,k]=await Promise.all([mr(),Vi()]);if(b)return;const R=S.providers??[],N=R.find(P=>P.id==="github"),C=!R.some(P=>P.id!=="github"&&P.authenticated),z=!k.defaultProvider&&!k.defaultModelId,A=N?!N.authenticated:!1;h({needsAiProvider:C,needsDefaultModel:z,needsGitHub:A})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,i]);const g=a.useCallback(()=>{S4(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),x=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Pn}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:Vh}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:hs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,f,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Ys,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(Xn,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Ot,{size:16,"aria-hidden":!0})})]})}function yT({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 rc(e){return e>99?"99+":String(e)}function kT({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:o,onOpenSystemStats:l,onOpenMailbox:c,mailboxUnreadCount:u=0,onOpenGitManager:d,onOpenWorkflowSteps:m,onOpenSchedules:h,onOpenScripts:g,onToggleTerminal:p,onOpenFiles:f,onOpenGitHubImport:x,onOpenPlanning:v,onResumePlanning:b,activePlanningSessionCount:y=0,onOpenUsage:S,onRunScript:k,projectId:R,onViewAllProjects:N,showSkillsTab:M,experimentalFeatures:C}){const z=Cr(),[A,P]=a.useState(!1),[F,W]=a.useState(!1),[$,_]=a.useState({}),[I,O]=a.useState(!1),J=a.useMemo(()=>Object.entries($).sort(([pe],[U])=>pe.localeCompare(U)),[$]);a.useEffect(()=>{if(!F)return;let pe=!1;return O(!0),hr(R).then(U=>{pe||_(U)}).catch(()=>{pe||_({})}).finally(()=>{pe||O(!1)}),()=>{pe=!0}},[F,R]);const Q=a.useCallback(()=>P(!1),[]),E=a.useCallback(pe=>{Q(),pe?.()},[Q]);if(a.useEffect(()=>{if(!A)return;const pe=U=>{U.key==="Escape"&&P(!1)};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[A]),z!=="mobile"||i)return null;const D=y>0&&b?b:v,T=!!C?.roadmap,w=!!M,q=!!C?.todoView,G=T&&(!w||e==="roadmaps"),me=w&&(!T||e!=="roadmaps"),ce=w&&!me,ae=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&q||e==="roadmaps"&&!G||e==="skills"&&!me;return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(Bi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":e==="agents",onClick:()=>n("agents"),children:[t.jsx(gn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(ls,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsx(bi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsx(ma,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:rc(u)})]}),me&&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(Pn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),G&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="roadmaps"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-roadmaps",role:"tab","aria-selected":e==="roadmaps",onClick:()=>n("roadmaps"),children:[t.jsx(xc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ae?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>P(pe=>!pe),children:[t.jsx(hc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),A&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:Q}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>E(c),children:[t.jsx(ma,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:rc(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>E(o),children:[t.jsx(Cs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>E(l),children:[t.jsx(dr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>E(d),children:[t.jsx(Js,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>E(p),children:[t.jsx(ri,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>W(pe=>!pe),"aria-expanded":F,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(hn,{size:14,className:`mobile-more-chevron${F?" mobile-more-chevron--open":""}`})})]}),F&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:I?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(ot,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):J.length>0?t.jsxs(t.Fragment,{children:[J.map(([pe,U])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${pe}`,onClick:()=>{k&&k(pe,U),Q(),W(!1)},children:[t.jsx(xn,{size:14}),t.jsx("span",{children:pe})]},pe)),g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{Q(),W(!1),g()},children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{Q(),W(!1),g()},children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>E(f),children:[t.jsx(In,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>E(D),children:[t.jsx(Ys,{}),t.jsx("span",{children:"Planning"}),y>0&&t.jsx("span",{className:"mobile-more-item-badge",children:rc(y)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>E(m),children:[t.jsx(vc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>E(h),children:[t.jsx(yi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>E(x),children:[t.jsx(yT,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>E(S),children:[t.jsx(Cs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>E(N),children:[t.jsx(qh,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>E(()=>n("documents")),children:[t.jsx(Oi,{}),t.jsx("span",{children:"Documents"})]}),ce&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>E(()=>n("skills")),children:[t.jsx(Pn,{}),t.jsx("span",{children:"Skills"})]}),T&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>E(()=>n("roadmaps")),children:[t.jsx(xc,{}),t.jsx("span",{children:"Roadmaps"})]}),C?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>E(()=>n("insights")),children:[t.jsx(qn,{}),t.jsx("span",{children:"Insights"})]}),C?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>E(()=>n("memory")),children:[t.jsx(co,{}),t.jsx("span",{children:"Memory"})]}),C?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{E(()=>n("dev-server"))},children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>E(()=>n("todos")),children:[t.jsx(Gh,{size:14}),t.jsx("span",{children:"Todos"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>E(r),children:[t.jsx(sr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function jT({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(gn,{size:14,"aria-hidden":"true"}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}const Sd="__fn_agent__";function rg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function jh(e,n,s){const i=typeof e=="string"?e.trim():"",r=rg(n,s),o=i||(r.modelProvider&&r.modelId?Sd:"");return o?{agentId:o,...r}:null}function oc(e,n,s){const i=rg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function wT(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 wh(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:wT(e.metadata),createdAt:e.createdAt}}function NT(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[g,p]=a.useState(""),[f,x]=a.useState(""),[v,b]=a.useState([]),[y,S]=a.useState(""),k=a.useRef(null),R=a.useRef(!1),N=a.useRef(""),M=a.useRef(""),C=a.useRef(null);a.useEffect(()=>{N.current=y},[y]);const z=a.useCallback(async Q=>{const E={agentId:Q.agentId};return Q.modelProvider&&Q.modelId&&(E.modelProvider=Q.modelProvider,E.modelId=Q.modelId),(await Kj(E,e)).session},[e]),A=a.useCallback(async(Q,E,D)=>{const T=jh(Q,E,D);if(!T)return;const w=oc(T.agentId,T.modelProvider,T.modelId);o(!0);try{const{session:q}=await Wj({agentId:T.agentId,modelProvider:T.modelProvider,modelId:T.modelId},e);if(q)i(q),M.current=w;else{const G=await z(T);i(G),M.current=w}}catch(q){console.error("[useQuickChat] Failed to initialize session:",q),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,z]),P=a.useCallback(async()=>{if(s){d(!0);try{const Q=await Xd(s.id,{limit:50},e);c(Q.messages.map(wh))}catch(Q){console.error("[useQuickChat] Failed to load messages:",Q)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?P():c([])},[s,P]);const F=a.useCallback(async()=>{if(s){d(!0);try{const Q=await Xd(s.id,{limit:50},e);c(Q.messages.map(wh))}catch(Q){console.error("[useQuickChat] Failed to reload messages:",Q)}finally{d(!1)}}},[s,e]),W=a.useCallback(async(Q,E,D)=>{const T=jh(Q,E,D);if(!T)return;const w=oc(T.agentId,T.modelProvider,T.modelId);if(C.current=T,k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1),w===M.current&&s){await F();return}i(null),c([]),M.current=w,await A(T.agentId,T.modelProvider,T.modelId)},[A,F,s]),$=a.useCallback(async(Q,E)=>{await W(Sd,Q,E)},[W]),_=a.useCallback(async()=>{const Q=C.current;if(!Q)return;const E=oc(Q.agentId,Q.modelProvider,Q.modelId);k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1),c([]),i(null),o(!0);try{const D=await z(Q);i(D),M.current=E}catch(D){console.error("[useQuickChat] Failed to start a fresh session:",D),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,z]),I=a.useCallback(()=>{s&&(R.current=!0,k.current?.close(),k.current=null,Gj(s.id,e).catch(()=>{}),h(!1),p(""),x(""),b([]))},[s,e]),O=a.useCallback(()=>{N.current="",S("")},[]),J=a.useCallback(Q=>{if(!s||!Q.trim())return;if(m){N.current=Q,S(Q);return}R.current=!1,k.current&&(k.current.close(),k.current=null);const D={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:Q,createdAt:new Date().toISOString()};c(me=>[...me,D]),p(""),x(""),b([]),h(!0);let T="",w="",q=[];const G={onThinking:me=>{w+=me,x(w)},onText:me=>{T+=me,p(T)},onToolStart:me=>{q=[...q,{toolName:me.toolName,args:me.args,isError:!1,status:"running"}],b(q)},onToolEnd:me=>{const ce=[...q];for(let ae=ce.length-1;ae>=0;ae--){const pe=ce[ae];if(pe?.toolName===me.toolName&&pe.status==="running"){ce[ae]={...pe,status:"completed",isError:me.isError,result:me.result},q=ce,b(ce);return}}q=[...ce,{toolName:me.toolName,isError:me.isError,result:me.result,status:"completed"}],b(q)},onDone:me=>{const ce={id:me.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:T,thinkingOutput:w||void 0,toolCalls:q.length>0?q:void 0,createdAt:new Date().toISOString()};c(pe=>[...pe,ce]),p(""),x(""),b([]),h(!1),k.current=null;const ae=N.current.trim();ae&&(N.current="",S(""),J(ae))},onError:me=>{if(p(""),x(""),b([]),h(!1),k.current=null,console.error("[useQuickChat] Stream error:",me),n?.("Failed to get response","error"),!R.current){const ce=N.current.trim();ce&&(N.current="",S(""),J(ce))}F()}};k.current=Jj(s.id,Q,G,e)},[s,m,e,n,F]);return a.useEffect(()=>()=>{k.current&&(k.current.close(),k.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:y,sendMessage:J,stopStreaming:I,clearPendingMessage:O,switchSession:W,startModelChat:$,startFreshSession:_,loadMessages:P,reloadMessages:F}),[s,r,l,u,m,g,f,v,y,J,I,O,W,$,_,P,F])}function ST(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async g=>{c(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,x=n?.showSystemAgents??!1,v=await Na({...f,...g,includeEphemeral:g?.includeEphemeral??x},e),b=Array.from(new Map(v.map(y=>[y.id,y])).values());i(b)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await Ek(e);o(g)}catch(g){console.error("Failed to load agent stats:",g)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const g=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return Ls(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:m||!mw(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function CT({visible:e,position:n,files:s,selectedIndex:i,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const u=l.path.includes("/")?l.path.slice(0,l.path.lastIndexOf("/")+1):"",d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Bh,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:d}),u&&t.jsx("span",{className:"file-mention-popup-item-path",children:u})]})]},l.path)})})]}):null}const ET=200;function _T(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),x=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=a.useCallback((N,M)=>{if(M<0||M>N.length){r(!1);return}const C=z=>/[a-zA-Z0-9/_.-]/.test(z);for(let z=M-1;z>=0;z--){if(N[z]==="#")if(z===0){const A=N.slice(z+1,M);u(z),l(A),f(0),r(!0);return}else{const A=N[z-1];if(/[\s,.;:!?'"()[\]{}]/.test(A)){const P=N.slice(z+1,M);u(z),l(P),f(0),r(!0);return}r(!1);return}if(!C(N[z])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),S=a.useCallback(async N=>{if(!N.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const M=await $y(N,s,n);m(M.files),f(0)}catch(M){M.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},ET),()=>{x.current&&clearTimeout(x.current)}},[o,i,S]);const k=a.useCallback((N,M)=>{if(!i||c<0)return M;const C=M.slice(0,c),z=M.slice(c+1),A=z.match(/[\s]|$/),P=A?A.index:z.length,F=z.slice(P);return`${C}#${N.path}${F}`},[i,c]),R=a.useCallback((N,M)=>{if(!i||d.length===0)return!1;switch(N.key){case"ArrowDown":return N.preventDefault(),f(C=>Math.min(C+1,d.length-1)),!0;case"ArrowUp":return N.preventDefault(),f(C=>Math.max(C-1,0)),!0;case"Enter":case"Tab":return d[p]?(N.preventDefault(),!0):!1;case"Escape":return N.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:b,selectFile:k,dismissMention:y,handleKeyDown:R}}function MT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let lc=null;function AT(){return lc===null&&(lc=window.innerHeight),lc}function RT(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const i=AT()-e.offsetTop-e.height;return i>=30&&i>80?i:0}function TT({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e||!MT()){s(0),r(null);return}const o=window.visualViewport;if(!o){s(0),r(null);return}const l=()=>{const c=RT();s(c),r(c>0?o.height:null)};return l(),o.addEventListener("resize",l),o.addEventListener("scroll",l),()=>{o.removeEventListener("resize",l),o.removeEventListener("scroll",l),s(0),r(null)}},[e]),{keyboardOverlap:n,viewportHeight:i}}function PT(e){return`${e.name?.trim()||e.id} (${e.role})`}function IT(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 $T(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 oo(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function DT(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{let r="";if(typeof i=="string")r=i;else try{r=JSON.stringify(i)}catch{r=String(i)}return`${s}=${oo(r,50)}`}).join(", ")}function LT(e){if(e===void 0)return null;if(typeof e=="string")return oo(e,200);try{return oo(JSON.stringify(e),200)}catch{return oo(String(e),200)}}function Nh(e,n=!1){return!e||e.length===0?null:t.jsxs("div",{className:`chat-tool-calls${n?" chat-tool-calls--compact":""}`,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Xb,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),e.map((s,i)=>{const r=s.status==="running",o=s.status==="completed"&&s.isError,l=DT(s.args),c=LT(s.result),u=r?l:c?`result: ${c}`:l?`args: ${l}`:null,d=r?"running":o?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${r?" chat-tool-call--running":""}${o?" chat-tool-call--error":""}`,open:r,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",children:s.toolName}),u&&t.jsx("span",{className:"chat-tool-call-preview",title:u,children:u}),t.jsx("span",{className:"chat-tool-call-status-text",children:d})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[l&&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:l})]}),c&&t.jsxs("div",{className:`chat-tool-call-row${o?" 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:c})]})]})]},`${s.toolName}-${i}`)})]})}const zT={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 FT(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 io={width:320,height:400},ia={width:280,height:260},Kc=768,aa=8;function OT(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const x=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return x&&parseFloat(x)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const x=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(x);if(v){const b=JSON.parse(v);if(typeof b.x=="number"&&typeof b.y=="number"&&!isNaN(b.x)&&!isNaN(b.y))return b}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(x=>{if(typeof window>"u")return x;const v=48,b=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,S=window.innerWidth>768?s():0,k=window.innerWidth-v-b,R=window.innerHeight-v-b-y-S;return{x:Math.max(b,Math.min(k,x.x)),y:Math.max(b,Math.min(R,x.y))}},[s]),h=a.useCallback(x=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(x))}catch{}},[e]),g=a.useCallback(x=>{if(x.button!==0&&x.pointerType==="mouse")return;const b=x.target.closest(".quick-chat-fab");b&&(x.preventDefault(),typeof b.setPointerCapture=="function"&&b.setPointerCapture(x.pointerId),u.current={x:r.x,y:r.y,pointerX:x.clientX,pointerY:x.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(x=>{if(!u.current||!l)return;const v=x.clientX-u.current.pointerX,b=x.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(b)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,S=u.current.y-b,k=m({x:y,y:S});o(k)}},[l,m]),f=a.useCallback(x=>{if(!u.current)return;const v=x.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(x.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function UT(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Kc,[]),o=a.useCallback((g,p,f)=>{if(typeof window>"u")return g;const x=Math.max(ia.width,window.innerWidth-p-aa),v=Math.max(ia.height,window.innerHeight-f-aa);return{width:Math.max(ia.width,Math.min(x,g.width)),height:Math.max(ia.height,Math.min(v,g.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Kc)return io;try{const g=localStorage.getItem(i);if(!g)return io;const p=JSON.parse(g);return typeof p.width!="number"||typeof p.height!="number"?io:{width:p.width,height:p.height}}catch{return io}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const g={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,g.right,g.bottom))},[o,r,n,s,d]),a.useEffect(()=>{if(r())try{localStorage.setItem(i,JSON.stringify(c))}catch{}},[r,c,i]);const h=a.useCallback(g=>{if(!r())return;const p=g.currentTarget.dataset.resizeDirection;if(!p)return;g.preventDefault(),g.stopPropagation();const f=g.currentTarget;typeof f.setPointerCapture=="function"&&f.setPointerCapture(g.pointerId);const x={pointerX:g.clientX,pointerY:g.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-x.pointerX,k=y.clientY-x.pointerY;let R=x.width,N=x.height,M=x.anchorRight,C=x.anchorBottom;if(p.includes("w")&&(R=x.width-S),p.includes("e")){const $=S;R=x.width+$,M=x.anchorRight-$}if(p.includes("n")&&(N=x.height-k),p.includes("s")){const $=k;N=x.height+$,C=x.anchorBottom-$}const z=n+M,A=s+C,P=o({width:R,height:N},z,A),F=Math.max(aa-n,Math.min(window.innerWidth-n-ia.width-aa,M)),W=Math.max(aa-s,Math.min(window.innerHeight-s-ia.height-aa,C));u(P),m({right:F,bottom:W})},b=y=>{typeof f.releasePointerCapture=="function"&&f.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}function BT({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=ST(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?te=>{r?.(typeof te=="function"?te(p):te)}:h,{keyboardOverlap:x,viewportHeight:v}=TT({enabled:p}),b=x>0?{"--keyboard-overlap":`${x}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[y,S]=a.useState("agent"),[k,R]=a.useState(""),[N,M]=a.useState([]),[C,z]=a.useState(!1),[A,P]=a.useState(""),[F,W]=a.useState(""),[$,_]=a.useState(""),[I,O]=a.useState(!1),[J,Q]=a.useState(0),[E,D]=a.useState(-1),[T,w]=a.useState(()=>new Set),[,q]=a.useState(!1),[G,me]=a.useState({top:0,left:0}),ce=_T({projectId:e}),ae=a.useCallback(te=>{if(!te||!ce.mentionActive)return;const j=te.getBoundingClientRect();me({top:j.top-260,left:j.left+8})},[ce.mentionActive]),pe=a.useRef(!1),U=a.useRef(!1),Ne=a.useRef(""),ne=a.useRef(0),xe=a.useRef(null),{position:le,isDragging:ve,handlePointerDown:ee,handlePointerMove:Ee,handlePointerUp:Fe}=OT(e,pe),Ke=le.y+60,{panelSize:Ze,anchorOffset:Xe,handleResizeStart:Qe}=UT(e,le.x,Ke),it=typeof window<"u"&&window.innerWidth>Kc,{activeSession:Ie,messages:Ge,isStreaming:se,streamingText:ye,streamingThinking:Z,streamingToolCalls:Te,sessionsLoading:ze,messagesLoading:be,sendMessage:Me,stopStreaming:Be,pendingMessage:lt,clearPendingMessage:je,switchSession:ie,startModelChat:Ae,startFreshSession:he}=NT(e,n),Re=a.useRef(null),Je=a.useRef(null),$e=a.useRef(null),de=a.useRef(null),re=a.useMemo(()=>IT(A),[A]),ue=a.useMemo(()=>N.find(te=>`${te.provider}/${te.id}`===A)??null,[N,A]),Pe=a.useMemo(()=>$T(ue,re),[ue,re]),Se=a.useMemo(()=>y==="model"?re?`${Sd}::${re.modelProvider}/${re.modelId}`:"":k?`${k}::`:"",[y,re,k]),fe=y==="agent"?!!k:!!re;a.useEffect(()=>{if(d.length===0){R(""),S("model");return}d.some(j=>j.id===k)||R(d[0]?.id??"")},[d,k]),a.useEffect(()=>{!p||U.current||(U.current=!0,z(!0),cs().then(te=>{const j=te.models??[];if(M(j),A||j.length===0)return;const V=te.defaultProvider,De=te.defaultModelId;if(V&&De){const nt=`${V}/${De}`;if(j.some(Pt=>`${Pt.provider}/${Pt.id}`===nt)){P(nt),S("model");return}}if(d.length===0){const nt=j[0];nt&&P(`${nt.provider}/${nt.id}`)}}).catch(te=>{console.error("[QuickChatFAB] Failed to load models:",te),M([])}).finally(()=>{z(!1)}))},[p,d.length,A]),a.useEffect(()=>{if(!p){Ne.current="";return}if(!Se){Ne.current="";return}const te=Se===Ne.current&&!Ie&&!ze;if(!(Se===Ne.current&&!te)){if(Ne.current=Se,y==="model"&&re){Ae(re.modelProvider,re.modelId);return}y==="agent"&&k&&ie(k)}},[p,y,re,k,Se,Ie,ze,Ae,ie]),a.useEffect(()=>{p||(O(!1),_(""),D(-1))},[p]);const tt=a.useCallback(te=>{R(te)},[]),ut=a.useCallback(te=>{P(te)},[]),vt=a.useCallback(()=>{!fe||ze||he()},[fe,ze,he]),gt=a.useMemo(()=>d.find(te=>te.id===k)??null,[d,k]),dt=a.useMemo(()=>{const te=$.trim().toLowerCase();return te?d.filter(j=>j.name.toLowerCase().includes(te)):d},[d,$]),wt=a.useMemo(()=>{const te=new Map;for(const j of d)te.set(j.name.toLowerCase(),j);return te},[d]);a.useEffect(()=>{Q(0)},[$,I]),a.useEffect(()=>()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),a.useEffect(()=>{if(!p)return;const te=V=>{const De=V.target;Re.current?.contains(De)||Je.current?.contains(De)||De.closest(".model-combobox-dropdown--portal")||f(!1)},j=V=>{V.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",te),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",te),document.removeEventListener("keydown",j)}},[p,f]),a.useEffect(()=>{if(!p)return;const te=$e.current;te&&(te.scrollTop=te.scrollHeight)},[Ge,ye,Z,p]);const Mt=a.useMemo(()=>y==="agent"?gt?`Message ${gt.name||gt.id}`:"Select an agent to start chatting":Pe?`Message ${Pe}`:"Select a model to start chatting",[y,gt,Pe]),yt=!fe||!Ie,Et=lt.length>50?`${lt.slice(0,50)}…`:lt,Nt=a.useCallback(()=>{const te=F.trim();!te||yt||(W(""),O(!1),_(""),D(-1),Me(te))},[Me,yt,F]),Tt=a.useCallback((te,j)=>{const V=FT(te,j);if(V){O(!0),_(V.filter),D(V.start);return}O(!1),_(""),D(-1)},[]),Ht=a.useCallback(te=>{const j=de.current;if(!j||E<0)return;const V=j.selectionStart??ne.current,De=j.selectionEnd??V,nt=Math.max(V,De),St=Math.min(E,nt),Rt=`${`@${te.name.replace(/\s+/g,"_")}`} `,un=F.slice(0,St)+Rt+F.slice(nt),mn=St+Rt.length;W(un),O(!1),_(""),Q(0),D(-1),window.requestAnimationFrame(()=>{de.current&&(de.current.focus(),de.current.setSelectionRange(mn,mn))})},[E,F]),Ut=a.useCallback(te=>{const j=te.target.value,V=te.target.selectionStart??j.length;ne.current=V,W(j),Tt(j,V),ce.detectMention(j,V),q(ce.mentionActive),ce.mentionActive&&ae(te.target)},[Tt,ce,ae]),Vt=a.useCallback(()=>{xe.current!==null&&window.clearTimeout(xe.current),xe.current=window.setTimeout(()=>{O(!1),_(""),D(-1),q(!1),ce.dismissMention(),xe.current=null},120)},[ce]),zt=a.useCallback(()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),Ct=a.useCallback(te=>{const j=te.currentTarget,V=j.selectionStart??j.value.length;ne.current=V,Tt(j.value,V),ce.detectMention(j.value,V),q(ce.mentionActive),ce.mentionActive&&ae(j)},[Tt,ce,ae]),At=a.useCallback(te=>{te.key!=="Escape"&&Ct(te)},[Ct]),kt=a.useCallback(te=>{const j=/@([\w-]+)/g,V=[];let De=0,nt=j.exec(te);for(;nt;){const[St,Pt=""]=nt,Rt=nt.index;Rt>De&&V.push(te.slice(De,Rt));const un=Pt.replace(/_/g," ").toLowerCase(),mn=wt.get(un);mn?V.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",mn.name.replace(/\s+/g,"_")]},`${mn.id}-${Rt}`)):V.push(St),De=Rt+St.length,nt=j.exec(te)}return De<te.length&&V.push(te.slice(De)),V.length===0?te:V},[wt]),Kt=a.useCallback(te=>{w(j=>{const V=new Set(j);return V.has(te)?V.delete(te):V.add(te),V})},[]),$t=a.useCallback((te,j=!1)=>j?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:te}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ci,{remarkPlugins:[di],components:zT,children:te})}),[]),B=a.useCallback(te=>{if(ne.current=te.currentTarget.selectionStart??ne.current,ce.mentionActive&&ce.files.length>0){if(ce.handleKeyDown(te,F),te.key==="Enter"||te.key==="Tab"){const j=ce.files[ce.selectedIndex];if(j){const V=ce.selectFile(j,F);W(V),ce.dismissMention(),q(!1)}}return}if(I&&te.key==="ArrowDown"){te.preventDefault(),dt.length>0&&Q(j=>(j+1)%dt.length);return}if(I&&te.key==="ArrowUp"){te.preventDefault(),dt.length>0&&Q(j=>j===0?dt.length-1:j-1);return}if(I&&te.key==="Enter"){te.preventDefault();const j=dt[J]??dt[0];j&&Ht(j);return}if(I&&te.key==="Escape"){te.preventDefault(),te.stopPropagation(),O(!1),_(""),D(-1);return}te.key!=="Enter"||te.shiftKey||(te.preventDefault(),Nt())},[I,dt,J,Ht,Nt,ce,F]),ge=a.useCallback(()=>{if(pe.current){pe.current=!1;return}f(te=>!te)},[f]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Je,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":ve?"true":"false",style:{right:le.x,bottom:le.y},onPointerDown:ee,onPointerMove:Ee,onPointerUp:Fe,onClick:ge,children:t.jsx(bi,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:Re,"data-testid":"quick-chat-panel",style:{right:le.x+Xe.right,bottom:Ke+Xe.bottom,...it?{width:Ze.width,height:Ze.height}:{},...b},children:[it&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Qe,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:Qe,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:Qe,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:Qe,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:Qe,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:Qe,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:Qe,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:Qe,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),Pe&&t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Pe,children:Pe})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:vt,disabled:!fe||ze,children:"New chat"}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(Ot,{size:16})})]})]}),d.length>0&&t.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{S("agent"),P("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{S("model"),R("")},children:"Model"})]}),y==="agent"&&d.length>0&&t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),t.jsx("select",{id:"quick-chat-agent-select",value:k,onChange:te=>tt(te.target.value),"data-testid":"quick-chat-agent-select",children:d.map(te=>t.jsx("option",{value:te.id,children:PT(te)},te.id))})]}),y==="model"&&t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-model-select",children:[t.jsx("label",{htmlFor:"quick-chat-model-override",className:"visually-hidden",children:"Select model override"}),t.jsx($n,{id:"quick-chat-model-override",models:N,value:A,onChange:ut,label:"Select model override",placeholder:C?"Loading models…":"Select a model",disabled:C||N.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:$e,"data-testid":"quick-chat-messages",children:ze||be?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ge.length===0&&!ye&&!Z&&!se?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Ge.map(te=>{const j=te.role==="user",V=!j&&T.has(te.id);return t.jsxs("div",{className:`quick-chat-panel-message ${j?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${te.id}`,children:[j?t.jsx("p",{children:kt(te.content)}):t.jsxs(t.Fragment,{children:[$t(te.content,V),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${V?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":V?"Show rendered markdown":"Show plain text",onClick:()=>Kt(te.id),children:V?t.jsx(pc,{size:14}):t.jsx(da,{size:14})})]}),Nh(te.toolCalls,!0)]},te.id)}),se&&t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[ye?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:$t(ye,T.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${T.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":T.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Kt("__streaming__"),children:T.has("__streaming__")?t.jsx(pc,{size:14}):t.jsx(da,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Z?"Thinking…":"Connecting…"}),Nh(Te,!0),Z&&t.jsxs("details",{className:"chat-message-thinking","data-testid":"quick-chat-streaming-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:Z})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:de,type:"text",value:F,onChange:Ut,onKeyDown:B,onKeyUp:At,onClick:Ct,onBlur:Vt,onFocus:zt,placeholder:Mt,disabled:yt,"data-testid":"quick-chat-input"}),t.jsx(jT,{agents:d,filter:$,highlightedIndex:J,visible:I,onSelect:Ht,position:"above"}),t.jsx(CT,{visible:ce.mentionActive&&!I,position:G,files:ce.files,selectedIndex:ce.selectedIndex,onSelect:te=>{const j=ce.selectFile(te,F);W(j),ce.dismissMention(),q(!1),de.current?.focus()},loading:ce.loading}),lt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Et}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:je,children:"×"})]})]}),se?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:Be,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ms,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void Nt(),disabled:yt||F.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(Di,{size:16})})]})]})]})}function Ya(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Sh(e){return e.status==="generating"||e.status==="awaiting_input"}function Qa(e){return e==="complete"||e==="error"}function HT(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Sa(),d=a.useCallback(()=>{Zc(e).then(p=>{const f=p.filter(v=>{const b=Ya(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of f)x.set(v.id,Ya(v.updatedAt));i.current=x,s(f)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let f=!1;const x=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(b<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!Qa(v.status)&&r.current.delete(v.sessionId),Qa(v.status)){x.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,b);continue}const k=x.get(v.sessionId),R=v.type??k?.type,N=v.title??k?.title;if(!k&&(!R||!N))continue;const M={id:v.sessionId,type:R??"planning",status:v.status,title:N??"AI Session",projectId:v.projectId??k?.projectId??e??null,lockedByTab:v.owningTabId??k?.lockedByTab??null,updatedAt:v.updatedAt??k?.updatedAt??new Date(b).toISOString()},C=x.get(v.sessionId);(!C||C.status!==M.status||C.title!==M.title||C.type!==M.type||C.projectId!==M.projectId||C.lockedByTab!==M.lockedByTab||C.updatedAt!==M.updatedAt)&&(x.set(v.sessionId,M),i.current.set(v.sessionId,b),f=!0)}return f?[...x.values()].sort((v,b)=>Ya(b.updatedAt)-Ya(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const b=JSON.parse(v.data),y=Ya(b.updatedAt)||Date.now();s(S=>{const k=i.current.get(b.id)??0;if(y<k)return S;const R=r.current.get(b.id);if(R!==void 0&&y<=R)return S;if(R!==void 0&&y>R&&!Qa(b.status)&&r.current.delete(b.id),i.current.set(b.id,y),Qa(b.status))return S.filter(M=>M.id!==b.id);const N=S.findIndex(M=>M.id===b.id);if(N>=0){const M=[...S];return M[N]=b,M}return Sh(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),Qa(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),i.current.set(b,Math.max(i.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(k=>k.id!==b))}catch{}};return Ls(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":x},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,v=Wi();let b=!1;if(x==="planning")try{await np(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await ap(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await dp(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await up(p)}catch{}s(S=>S.filter(k=>k.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Sh(p)),[n]),g=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:g,dismissSession:m,refresh:d}}function Bn(e){return{...e,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Ch(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function qT(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),x=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=a.useCallback(async _=>{const I=++m.current,O=n,J=_?.searchQueryOverride??s,Q=_?.includeArchivedOverride??u.current;try{const E=await wv(void 0,void 0,O,J,Q);if(m.current!==I||n!==O)return;o(E.map(Bn)),f.current=Date.now()}catch{if(m.current!==I||n!==O)return;if(_?.clearOnError){o([]);return}o(E=>E)}},[n,s]);p.current=y;const S=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const _=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(_)},[s]),a.useEffect(()=>{y({clearOnError:!0});const _=()=>{if(document.visibilityState!=="visible")return;const I=Date.now();I-h.current<b||(h.current=I,y())};return document.addEventListener("visibilitychange",_),()=>{document.removeEventListener("visibilitychange",_)}},[y]),a.useEffect(()=>{if(i===!1)return;const _=x.current,I=n?`?projectId=${encodeURIComponent(n)}`:"",O=()=>x.current!==_;let J=!0;const Q=G=>{if(O())return;const me=Bn(JSON.parse(G.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(ce=>ce.some(ae=>ae.id===me.id)?ce:[...ce,me])},E=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:me,to:ce}=JSON.parse(G.data),ae=Bn(me);o(pe=>pe.map(U=>U.id===ae.id?{...ae,column:ce}:U)),f.current=Date.now()},D=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const me=Bn(JSON.parse(G.data));o(ce=>ce.map(ae=>{if(ae.id!==me.id||Ch(me.updatedAt,ae.updatedAt)<0)return ae;if(ae.column===me.column)return me;const U=Ch(ae.columnMovedAt,me.columnMovedAt);return ae.columnMovedAt&&!me.columnMovedAt?{...me,column:ae.column,columnMovedAt:ae.columnMovedAt}:U>0?{...me,column:ae.column,columnMovedAt:ae.columnMovedAt}:me})),f.current=Date.now()},T=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const me=Bn(JSON.parse(G.data));o(ce=>ce.filter(ae=>ae.id!==me.id))},w=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:me}=JSON.parse(G.data),ce=Bn(me);o(ae=>ae.map(pe=>pe.id===ce.id?{...ce,column:"done"}:pe))},q=Ls(`/api/events${I}`,{events:{"task:created":Q,"task:moved":E,"task:updated":D,"task:deleted":T,"task:merged":w},onReconnect:()=>{J&&(O()||p.current())}});return()=>{J=!1,q()}},[n,i]);const k=a.useCallback(async _=>{const I=Bn(await Xh(_,n));return o(O=>O.some(J=>J.id===I.id)?O:[...O,I]),I},[n]),R=a.useCallback(async(_,I)=>Bn(await Sv(_,I,n)),[n]),N=a.useCallback(async _=>Bn(await Zh(_,n)),[n]),M=a.useCallback(async _=>Bn(await Cv(_,n)),[n]),C=a.useCallback(async _=>Ev(_,n),[n]),z=a.useCallback(async _=>Bn(await _v(_,n)),[n]),A=a.useCallback(async _=>{const I=Bn(await Mv(_,n));return o(O=>O.some(J=>J.id===I.id)?O:[...O,I]),I},[n]),P=a.useCallback(async(_,I)=>{const O=d.current.find(Q=>Q.id===_),J=O?{...O,...I,updatedAt:new Date().toISOString()}:void 0;J&&o(Q=>Q.map(E=>E.id===_?J:E));try{const Q=Bn(await Ks(_,I,n));return o(E=>E.map(D=>D.id===_?Q:D)),Q}catch(Q){throw O&&o(E=>E.map(D=>D.id===_?O:D)),Q}},[n]),F=a.useCallback(async _=>{const I=Bn(await Rv(_,n));return o(O=>O.map(J=>J.id===_?I:J)),I},[n]),W=a.useCallback(async _=>{const I=Bn(await Tv(_,n));return o(O=>O.map(J=>J.id===_?I:J)),I},[n]),$=a.useCallback(async()=>{const I=(await Pv(n)).map(Bn);return o(O=>O.map(J=>I.find(E=>E.id===J.id)||J)),I},[n]);return{tasks:r,createTask:k,moveTask:R,pauseTask:N,deleteTask:M,mergeTask:C,retryTask:z,duplicateTask:A,updateTask:P,archiveTask:F,unarchiveTask:W,archiveAllDone:$,loadArchivedTasks:S,includeArchived:l,lastFetchTimeMs:f.current}}const VT=5e3,WT=1e3;function KT(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const g=await Kd();n(g)}catch(g){o(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const x=performance.now();try{const v=await Kd(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),ir("[useProjects]",y),g||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-x)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),ir("[useProjects]",y),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<WT||(c.current=x,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},VT),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Tk(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await zk(g,p);return n(x=>x.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await op(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const GT="kb-dashboard-current-project";function JT(e){return e??"local"}function YT(e,n={}){const{nodeId:s=null}=n,[i,r]=a.useState(null),[o,l]=a.useState(!0),c=a.useRef(!1),u=a.useRef(!1),d=a.useRef(null),m=JT(s);a.useEffect(()=>{let p=!1;async function f(){try{const x=await Vi();if(p)return;d.current=x.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(GT);if(b){const y=JSON.parse(b);y?.id&&e.some(k=>k.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await sn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return f(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(x=>x.id===i.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,sn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(f=>f.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const f={...d.current,[m]:p.id};d.current=f,sn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,sn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const og=a.createContext(null);function QT({children:e}){const[n,s]=a.useState([]),i=a.useRef(0),r=a.useRef(new Map),o=a.useCallback(c=>{const u=r.current.get(c);u!==void 0&&(clearTimeout(u),r.current.delete(c)),s(d=>d.filter(m=>m.id!==c))},[]),l=a.useCallback((c,u="info")=>{const d=i.current++;s(h=>[...h,{id:d,message:c,type:u}]);const m=setTimeout(()=>o(d),4e3);r.current.set(d,m)},[o]);return a.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),lo.createElement(og.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function XT(){const e=a.useContext(og);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const lg="kb-dashboard-theme-mode",cg="kb-dashboard-color-theme",dg=[...dw],Gc="theme-data",cc="theme-data.css";function ZT(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${cc}`:e.replace(/\/[^/]+$/,`/${cc}`):`/${cc}`}const Ss=typeof window<"u",eP=Ss?a.useLayoutEffect:a.useEffect;function ug(e){return e==="dark"||e==="light"||e==="system"}function Eh(){if(!Ss)return"dark";try{const e=localStorage.getItem(lg);if(ug(e))return e}catch{}return"dark"}function _h(){if(!Ss)return"default";try{const e=localStorage.getItem(cg);if(e&&dg.includes(e))return e}catch{}return"default"}function Mh(e){if(Ss)try{localStorage.setItem(lg,e)}catch{}}function Ah(e){if(Ss)try{localStorage.setItem(cg,e)}catch{}}function tP(e,n){return e==="system"?n?"dark":"light":e}function nP(e,n,s){if(!Ss)return;const i=tP(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Rh(){if(!Ss)return;const e=ZT(),n=document.getElementById(Gc);if(n){n.href!==e&&(n.href=e),n.parentNode===document.head&&document.head.lastChild!==n&&document.head.appendChild(n);return}const s=document.createElement("link");s.rel="stylesheet",s.href=e,s.id=Gc,document.head.appendChild(s)}function Th(){if(!Ss)return;const e=document.getElementById(Gc);e&&e.remove()}function sP(){const[e,n]=a.useState(()=>Eh()),[s,i]=a.useState(()=>_h()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ss?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),u=a.useRef(e),d=a.useRef(s),m=a.useRef(!1),h=a.useRef(!1);a.useEffect(()=>{u.current=e},[e]),a.useEffect(()=>{d.current=s},[s]),a.useEffect(()=>{if(!Ss||!r)return;let f=!1;return Vi().then(x=>{f||(ug(x.themeMode)&&!m.current&&(u.current!==x.themeMode&&(u.current=x.themeMode,n(x.themeMode)),Eh()!==x.themeMode&&Mh(x.themeMode)),x.colorTheme&&dg.includes(x.colorTheme)&&!h.current&&(d.current!==x.colorTheme&&(d.current=x.colorTheme,i(x.colorTheme)),_h()!==x.colorTheme&&Ah(x.colorTheme)))}).catch(x=>{console.warn("[useTheme] Failed to hydrate theme from global settings",x)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Ss)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),x=v=>{c(v.matches)};return f.addEventListener("change",x),()=>f.removeEventListener("change",x)},[]),eP(()=>{nP(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ss||r||(s!=="default"?Rh():Th())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Mh(f),sn({themeMode:f}).catch(x=>{console.warn("[useTheme] Failed to persist themeMode to global settings",x)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),Ah(f),f!=="default"?Rh():Th(),sn({colorTheme:f}).catch(x=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",x)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function iP(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,x]=a.useState(void 0),[v,b]=a.useState(null),[y,S]=a.useState("definition"),[k,R]=a.useState(!1),[N,M]=a.useState(void 0),[C,z]=a.useState(!1),[A,P]=a.useState(!1),[F,W]=a.useState(!1),[$,_]=a.useState(null),[I,O]=a.useState(!1),[J,Q]=a.useState(!1),[E,D]=a.useState(void 0),[T,w]=a.useState(!1),[q,G]=a.useState("project"),[me,ce]=a.useState(!1),[ae,pe]=a.useState(!1),[U,Ne]=a.useState(!1),[ne,xe]=a.useState(!1),[le,ve]=a.useState(!1),[ee,Ee]=a.useState(!1),[Fe,Ke]=a.useState(!1),Ze=!!(v||k||s||r||m||J||T||me||ae||U||le||ne||F||I||C||A||ee||Fe),Xe=a.useCallback(()=>i(!0),[]),Qe=a.useCallback(()=>i(!1),[]),it=a.useCallback(()=>o(!0),[]),Ie=a.useCallback(B=>{c(B),o(!0)},[]),Ge=a.useCallback(()=>{const B=n[0];B&&(d(B.id),o(!0))},[n]),se=a.useCallback(B=>{d(B),o(!0)},[]),ye=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),Z=a.useCallback(B=>{p(B),h(!0)},[]),Te=a.useCallback(B=>{x(B),h(!0)},[]),ze=a.useCallback(()=>{h(!1),p(null),x(void 0)},[]),be=a.useCallback((B,ge="definition")=>{b(B),S(ge)},[]),Me=a.useCallback(B=>{b(B),S("changes")},[]),Be=a.useCallback(B=>{b(ge=>ge&&{...ge,...B})},[]),lt=a.useCallback(()=>{b(null)},[]),je=a.useCallback(B=>{M(B),R(!0)},[]),ie=a.useCallback(()=>{R(!1),M(void 0)},[]),Ae=a.useCallback(()=>z(!0),[]),he=a.useCallback(()=>z(!1),[]),Re=a.useCallback(()=>P(!0),[]),Je=a.useCallback(()=>P(!1),[]),$e=a.useCallback(B=>{_(B??null),W(!0)},[]),de=a.useCallback(()=>{W(!1),_(null)},[]),re=a.useCallback(()=>O(!0),[]),ue=a.useCallback(()=>O(!1),[]),Pe=a.useCallback(()=>{Q(B=>!B)},[]),Se=a.useCallback(()=>{Q(!1),D(void 0)},[]),fe=a.useCallback(()=>w(!0),[]),tt=a.useCallback(()=>w(!1),[]),ut=a.useCallback(B=>{G(B)},[]),vt=a.useCallback(()=>ce(!0),[]),gt=a.useCallback(()=>ce(!1),[]),dt=a.useCallback(()=>pe(!0),[]),wt=a.useCallback(()=>pe(!1),[]),Mt=a.useCallback(()=>Ne(!0),[]),yt=a.useCallback(()=>Ne(!1),[]),Et=a.useCallback(()=>xe(!0),[]),Nt=a.useCallback(()=>xe(!1),[]),Tt=a.useCallback(()=>ve(!0),[]),Ht=a.useCallback(()=>ve(!1),[]),Ut=a.useCallback(async(B,ge)=>{ve(!1),D(ge),Q(!0)},[]),Vt=a.useCallback(()=>Ee(!0),[]),zt=a.useCallback(()=>Ee(!1),[]),Ct=a.useCallback(()=>Ke(!0),[]),At=a.useCallback(()=>Ke(!1),[]),kt=a.useCallback((B,ge)=>{ge(`Created ${B.id} from planning mode`,"success"),o(!1),c(null)},[]),Kt=a.useCallback((B,ge)=>{const te=B.map(j=>j.id).join(", ");ge(`Created ${te} from planning mode`,"success"),o(!1),c(null)},[]),$t=a.useCallback((B,ge)=>{const te=B.map(j=>j.id).join(", ");ge(`Created ${te} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:y,settingsOpen:k,settingsInitialSection:N,schedulesOpen:C,githubImportOpen:A,usageOpen:F,usageAnchorRect:$,systemStatsOpen:I,terminalOpen:J,terminalInitialCommand:E,filesOpen:T,fileBrowserWorkspace:q,activityLogOpen:me,gitManagerOpen:ae,workflowStepsOpen:U,agentsOpen:ne,scriptsOpen:le,setupWizardOpen:ee,modelOnboardingOpen:Fe,anyModalOpen:Ze,openNewTask:Xe,closeNewTask:Qe,openPlanning:it,openPlanningWithInitialPlan:Ie,resumePlanning:Ge,openPlanningWithSession:se,closePlanning:ye,openSubtaskBreakdown:Z,openSubtaskWithSession:Te,closeSubtask:ze,openDetailTask:be,openDetailWithChangesTab:Me,updateDetailTask:Be,closeDetailTask:lt,openSettings:je,closeSettings:ie,openSchedules:Ae,closeSchedules:he,openGitHubImport:Re,closeGitHubImport:Je,openUsage:$e,closeUsage:de,openSystemStats:re,closeSystemStats:ue,toggleTerminal:Pe,closeTerminal:Se,openFiles:fe,closeFiles:tt,setFileWorkspace:ut,openActivityLog:vt,closeActivityLog:gt,openGitManager:dt,closeGitManager:wt,openWorkflowSteps:Mt,closeWorkflowSteps:yt,openAgents:Et,closeAgents:Nt,openScripts:Tt,closeScripts:Ht,runScript:Ut,openSetupWizard:Vt,closeSetupWizard:zt,openModelOnboarding:Ct,closeModelOnboarding:At,onPlanningTaskCreated:kt,onPlanningTasksCreated:Kt,onSubtaskTasksCreated:$t}}function aP(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState({}),[S,k]=a.useState(!1),[R,N]=a.useState(!1),[M,C]=a.useState(!1),[z,A]=a.useState(!1),[P,F]=a.useState(!1),W=a.useCallback(async()=>{const[J,Q]=await Promise.allSettled([Dv(e),Lo(e)]);if(J.status==="fulfilled"&&(s(J.value.maxConcurrent),r(J.value.rootDir)),Q.status==="fulfilled"){const E=Q.value;l(!!E.autoMerge),u(!!E.globalPause),m(!!E.enginePaused),v(!!E.prAuthAvailable),g(E.taskStuckTimeoutMs),f(E.showQuickChatFAB===!0),y(E.experimentalFeatures??{});const D=E.experimentalFeatures??{};k(D.insights===!0),N(D.roadmap===!0),C(D.memoryView===!0),A(D.devServerView===!0||D.devServer===!0),F(D.todoView===!0)}},[e]);a.useEffect(()=>{W()},[W]);const $=a.useCallback(async()=>{const J=!o;l(J);try{await zr({autoMerge:J},e)}catch{l(!J)}},[o,e]),_=a.useCallback(async()=>{const J=!c;u(J);try{await zr({globalPause:J,globalPauseReason:J?"manual":void 0},e)}catch{u(!J)}},[c,e]),I=a.useCallback(async()=>{const J=!d;m(J);try{await zr({enginePaused:J},e)}catch{m(!J)}},[d,e]),O=a.useCallback(async()=>{const J=!p;f(J);try{await zr({showQuickChatFAB:J},e)}catch{f(!J)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,experimentalFeatures:b,insightsEnabled:S,roadmapEnabled:R,memoryEnabled:M,devServerEnabled:z,todosEnabled:P,toggleAutoMerge:$,toggleGlobalPause:_,toggleEnginePause:I,toggleShowQuickChatFAB:O,refresh:W}}function rP(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const g=new URLSearchParams(window.location.search),p=g.get("project"),f=g.get("task");if(!f||i)return;if(p){const v=s.find(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,fo(f,p??n).then(v=>{c(v),m.current=f}).catch(()=>{l(`Task ${f} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const g=new URLSearchParams(window.location.search);g.delete("task");const p=g.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function oP(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{cs().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];l.current=p,i(()=>p);try{await sn({favoriteProviders:p,favoriteModels:c.current})}catch(f){throw l.current=h,i(()=>h),f}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];c.current=p,o(()=>p);try{await sn({favoriteProviders:l.current,favoriteModels:p})}catch(f){throw c.current=h,o(()=>h),f}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function lP({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;mr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Vi().then(h=>{const g=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!g)&&!ja()?l=!0:!d&&!ja()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ws("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ws("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Ph="kb-update-banner-dismissed";function cP(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(Ph)==="true";d(h);let g=!1;return Lv().then(p=>{g||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{g||n(!1)}),()=>{g=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(Ph,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const dP=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Ih(e){return e!==null&&dP.includes(e)}function uP(e){return e==="devserver"?"dev-server":e}function mP(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[g,p]=a.useState(()=>{const b=Dn("kb-dashboard-task-view");return Ih(b)?b:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const b=Dn("kb-dashboard-task-view",r?.id);if(Ih(b)){const y=!f.current&&b==="devserver";p(y?"devserver":uP(b))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{os("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,i,r,l,c]);const x=a.useCallback(b=>{p(b)},[]),v=a.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(u),S=b[(y+1)%b.length];d(S)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function hP(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:g}=e,p=a.useCallback(C=>{n(C),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),x=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),b=a.useCallback(C=>{h(),n(C),i("project"),u(`Project ${C.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{g()},[g]),S=a.useCallback(async C=>{try{await Dk(C.id),u(`Project ${C.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${C.name}`,"error")}},[u,o]),k=a.useCallback(async C=>{try{await Lk(C.id),u(`Project ${C.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${C.name}`,"error")}},[u,o]),R=a.useCallback(async C=>{try{await op(C.id),u(`Project ${C.name} removed`,"success"),r?.id===C.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${C.name}`,"error")}},[r,s,i,u,o]),N=a.useCallback(async C=>{try{await l(C)}catch{u("Failed to update favorites","error")}},[l,u]),M=a.useCallback(async C=>{try{await c(C)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:k,handleRemoveProject:R,handleToggleFavorite:N,handleToggleModelFavorite:M}}function pP(e){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:o}=e,l=a.useCallback(async g=>n({...g,column:"triage"}),[n]),c=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),u=a.useCallback(g=>{s(g,o)},[s,o]),d=a.useCallback(g=>{i(g,o)},[i,o]),m=a.useCallback(g=>{r(g,o)},[r,o]),h=a.useCallback(g=>{o(`Imported ${g.id} from GitHub`,"success")},[o]);return{handleBoardQuickCreate:l,handleModalCreate:c,handlePlanningTaskCreated:u,handlePlanningTasksCreated:d,handleSubtaskTasksCreated:m,handleGitHubImport:h}}async function fP(e){return Fo("/health",{nodeId:e})}async function gP(e){return Fo("/projects",{nodeId:e})}async function xP(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Fo(`/tasks?${i.toString()}`,{nodeId:e})}async function bP(e,n){return Fo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function wD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function ND(e){return L(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function SD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function CD(e){return L(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function vP(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),x=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const b=new AbortController;f.current=b,h(!0),p(null);try{const y=[fP(e),gP(e)];s&&(y.push(xP(e,s,i)),y.push(bP(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const k=S[0],R=S[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(d(k.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&S[2]){const N=S[2];if(N.status==="rejected"){p(`Failed to fetch tasks: ${N.reason}`),h(!1);return}N.status==="fulfilled"&&c(N.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(x(),()=>{f.current?.abort()}),[x]);const v=a.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function yP(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 Ls(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 kP="fusion-dashboard-current-node",mg=a.createContext(null);function jP({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const g=await Vi();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(kP);if(f){const x=JSON.parse(f);x?.id&&x?.type==="remote"&&(l.current=x.id,await sn({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,sn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,sn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,sn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(mg.Provider,{value:d,children:e})}function wP(){const e=a.useContext(mg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function NP({open:e}){const[n,s]=a.useState(""),i=a.useRef(null);a.useEffect(()=>{e&&i.current?.focus()},[e]);const r=a.useCallback(()=>{const l=n.trim();l&&(mv(l),window.location.reload())},[n]),o=a.useCallback(()=>{hv(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:i,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const SP=200,CP=a.lazy(()=>nn(()=>import("./AgentsView-EjE4y4rM.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),EP=a.lazy(()=>nn(()=>import("./DocumentsView-Wz33aYqp.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),_P=a.lazy(()=>nn(()=>import("./InsightsView-C7YPnS92.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),MP=a.lazy(()=>nn(()=>import("./NodesView-CI4rUQC4.js"),__vite__mapDeps([24,1,18,0,2,25])).then(e=>({default:e.NodesView}))),AP=a.lazy(()=>nn(()=>import("./ChatView-DQLvKCYj.js"),__vite__mapDeps([26,1,0,2])).then(e=>({default:e.ChatView}))),RP=a.lazy(()=>nn(()=>import("./RoadmapsView-Cts3hoIS.js"),__vite__mapDeps([27,1,0,2,28])).then(e=>({default:e.RoadmapsView}))),TP=a.lazy(()=>nn(()=>import("./SkillsView-BXvrHzEZ.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.SkillsView}))),PP=a.lazy(()=>nn(()=>import("./MemoryView-DKQtFzFQ.js"),__vite__mapDeps([31,1,12,13,0,2,32])).then(e=>({default:e.MemoryView}))),IP=a.lazy(()=>nn(()=>import("./DevServerView-CX7paFRQ.js"),__vite__mapDeps([33,1,0,2,34])).then(e=>({default:e.DevServerView}))),$P=a.lazy(()=>nn(()=>import("./TodoView-NZHkv9YQ.js"),__vite__mapDeps([35,1,36,0,2,37])).then(e=>({default:e.TodoView})));function DP(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{nn(()=>import("./AgentsView-EjE4y4rM.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),nn(()=>import("./DocumentsView-Wz33aYqp.js"),__vite__mapDeps([20,1,0,2,21])),nn(()=>import("./InsightsView-C7YPnS92.js"),__vite__mapDeps([22,1,14,0,2,23])),nn(()=>import("./NodesView-CI4rUQC4.js"),__vite__mapDeps([24,1,18,0,2,25])),nn(()=>import("./ChatView-DQLvKCYj.js"),__vite__mapDeps([26,1,0,2])),nn(()=>import("./RoadmapsView-Cts3hoIS.js"),__vite__mapDeps([27,1,0,2,28])),nn(()=>import("./SkillsView-BXvrHzEZ.js"),__vite__mapDeps([29,1,0,2,30])),nn(()=>import("./MemoryView-DKQtFzFQ.js"),__vite__mapDeps([31,1,12,13,0,2,32])),nn(()=>import("./DevServerView-CX7paFRQ.js"),__vite__mapDeps([33,1,0,2,34])),nn(()=>import("./TodoView-NZHkv9YQ.js"),__vite__mapDeps([35,1,36,0,2,37]))})}const dc="kb-setup-warning-dismissed";function LP(){const{toasts:e,addToast:n,removeToast:s}=XT(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{DP()},[]);const{projects:r,loading:o,error:l,refresh:c}=KT(),{nodes:u}=Bo(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=wP(),{currentProject:f,setCurrentProject:x,clearCurrentProject:v,loading:b}=YT(r,{nodeId:m}),{hasAiProvider:y,hasGithub:S,loading:k,hasWarnings:R}=Zf(f?.id),{updateAvailable:N,latestVersion:M,currentVersion:C,dismissed:z,dismiss:A}=cP();a.useEffect(()=>{if(m&&!d&&u.length>0){const We=u.find(mt=>mt.id===m);if(We){g(We);return}}m&&u.length>0&&(u.some(mt=>mt.id===m)||p())},[m,d,u,g,p]);const[P,F]=a.useState(""),W=vP(m,{projectId:f?.id,searchQuery:P||void 0});yP(m);const $=h&&W.projects.length>0?W.projects:r,{themeMode:_,colorTheme:I,setThemeMode:O,setColorTheme:J}=sP(),{sessions:Q,generating:E,needsInput:D,planningSessions:T,dismissSession:w}=HT(f?.id),q=Q.filter(We=>We.status==="awaiting_input"||We.status==="error"),G=iP({projectId:f?.id,planningSessions:T}),{viewMode:me,setViewMode:ce,taskView:ae,handleChangeTaskView:pe}=mP({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:f,projectsLength:r.length,setupWizardOpen:G.setupWizardOpen,openSetupWizard:G.openSetupWizard,themeMode:_,setThemeMode:O}),U=a.useCallback(We=>{We==="missions"&&(de(void 0),ue(void 0),Se(void 0)),pe(We)},[pe]),Ne=ae==="board"||ae==="list",{tasks:ne,createTask:xe,moveTask:le,pauseTask:ve,deleteTask:ee,mergeTask:Ee,retryTask:Fe,updateTask:Ke,duplicateTask:Ze,archiveTask:Xe,unarchiveTask:Qe,archiveAllDone:it,loadArchivedTasks:Ie,lastFetchTimeMs:Ge}=qT({...f?{projectId:f.id}:{},searchQuery:P||void 0,sseEnabled:Ne}),[se,ye]=a.useState(!1),Z=a.useRef(performance.now()),Te=a.useRef(!1),ze=a.useRef(!1),be=a.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);a.useEffect(()=>{if(!o&&!Te.current){Te.current=!0;const We=`projects loaded at ${Math.round(performance.now()-Z.current)}ms from mount`;console.log(`[App] ${We}`),ir("[App]",We)}if(!b&&!ze.current){ze.current=!0;const We=`current-project resolved at ${Math.round(performance.now()-Z.current)}ms from mount`;console.log(`[App] ${We}`),ir("[App]",We)}},[o,b]),a.useEffect(()=>{if(se||o||b)return;const We=performance.now(),mt=window.setTimeout(()=>{const fn=`dashboard ready at ${Math.round(performance.now()-Z.current)}ms from mount (settle delay=${Math.round(performance.now()-We)}ms)`;console.log(`[App] ${fn}`),ir("[App]",fn),ye(!0)},SP);return()=>{window.clearTimeout(mt)}},[se,o,b]);const Be=Cr()==="mobile",[lt,je]=a.useState(0),ie=a.useCallback(()=>{mp(f?.id).then(We=>{je(We.unreadCount)}).catch(We=>{console.warn("[App] Failed to fetch mailbox unread count:",We)})},[f?.id]);a.useEffect(()=>{ie();const We=new URLSearchParams;f?.id&&We.set("projectId",f.id);const mt=We.size>0?`?${We.toString()}`:"";return Ls(`/api/events${mt}`,{events:{"message:sent":ie,"message:received":ie,"message:read":ie,"message:deleted":ie}})},[f?.id,ie]);const[Ae,he]=a.useState(!1),[Re,Je]=a.useState(!1),[$e,de]=a.useState(void 0),[re,ue]=a.useState(void 0),[Pe,Se]=a.useState(void 0),[fe,tt]=a.useState(!1),[ut,vt]=a.useState(!1),[gt,dt]=a.useState(()=>Dn(dc,f?.id)==="true");a.useEffect(()=>{dt(Dn(dc,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const We=()=>{vt(!0)};return window.addEventListener(jc,We),()=>{window.removeEventListener(jc,We)}},[]);const wt=a.useCallback(()=>{os(dc,"true",f?.id),dt(!0)},[f?.id]),{maxConcurrent:Mt,autoMerge:yt,globalPaused:Et,enginePaused:Nt,taskStuckTimeoutMs:Tt,showQuickChatFAB:Ht,prAuthAvailable:Ut,experimentalFeatures:Vt,insightsEnabled:zt,roadmapEnabled:Ct,memoryEnabled:At,devServerEnabled:kt,todosEnabled:Kt,toggleAutoMerge:$t,toggleGlobalPause:B,toggleEnginePause:ge,refresh:te}=aP(f?.id),j=Vt.skillsView===!0,V=Vt.nodesView===!0,De=!0;a.useEffect(()=>{Object.keys(Vt).length!==0&&(ae==="insights"&&!zt&&pe("board"),ae==="roadmaps"&&!Ct&&pe("board"),ae==="memory"&&!At&&pe("board"),(ae==="devserver"||ae==="dev-server")&&!kt&&pe("board"),ae==="todos"&&!Kt&&pe("board"))},[ae,zt,Ct,Vt,pe,De,At,kt,Kt]),a.useEffect(()=>{Ae&&!V&&he(!1)},[Ae,V]);const{availableModels:nt,favoriteProviders:St,favoriteModels:Pt,toggleFavoriteProvider:Rt,toggleFavoriteModel:un}=oP();lP({projectId:f?.id,setupWizardOpen:G.setupWizardOpen,openModelOnboarding:G.openModelOnboarding,openSettings:G.openSettings});const{handleSelectProject:mn,handleViewAllProjects:wn,handleOpenSettings:Gt,handleAddProject:es,handleSetupComplete:we,handleModelOnboardingComplete:rt,handlePauseProject:Jt,handleResumeProject:Sn,handleRemoveProject:Cn,handleToggleFavorite:pn,handleToggleModelFavorite:bn}=hP({setCurrentProject:x,clearCurrentProject:v,setViewMode:ce,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Rt,toggleFavoriteModel:un,addToast:n,openSettings:G.openSettings,openSetupWizard:G.openSetupWizard,closeSetupWizard:G.closeSetupWizard,closeModelOnboarding:G.closeModelOnboarding}),{handleDetailClose:Rn}=rP({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:x,addToast:n,openTaskDetail:G.openDetailTask,closeTaskDetail:G.closeDetailTask}),{handleBoardQuickCreate:vn,handleModalCreate:Y,handlePlanningTaskCreated:Oe,handlePlanningTasksCreated:Ye,handleSubtaskTasksCreated:st,handleGitHubImport:pt}=pP({createTask:xe,onPlanningTaskCreated:G.onPlanningTaskCreated,onPlanningTasksCreated:G.onPlanningTasksCreated,onSubtaskTasksCreated:G.onSubtaskTasksCreated,addToast:n}),jt=a.useCallback((We,mt)=>{if(mt==="changes"){G.openDetailWithChangesTab(We);return}G.openDetailTask(We,mt)},[G]),_t=a.useCallback(()=>{V&&he(We=>!We)},[V]),yn=a.useCallback(()=>{G.setFileWorkspace("project"),G.openFiles()},[G]),en=a.useCallback(async()=>{Je(!0);try{await c()}finally{Je(!1)}},[c]),xt=a.useCallback(We=>{ue(We),de(void 0),pe("missions")},[pe]),ts=a.useCallback(We=>{We.type==="planning"?G.openPlanningWithSession(We.id):We.type==="subtask"?G.openSubtaskWithSession(We.id):We.type==="mission_interview"?(ue(void 0),de(We.id),Se(void 0),pe("missions")):(We.type==="milestone_interview"||We.type==="slice_interview")&&(de(void 0),ue(void 0),Se(We.id),pe("missions"))},[pe,G]),ns=a.useCallback(()=>{},[]),ss=a.useCallback(()=>{},[]),Si=!o&&!b&&r.length===0&&!f&&!!l,oe=()=>Si?t.jsx(tT,{errorMessage:l??"Failed to fetch projects",isRetrying:Re,onRetry:en}):Ae?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(MP,{addToast:n,onClose:()=>he(!1)})})})}):me==="overview"?t.jsx(Jn,{children:t.jsx(ON,{projects:r,loading:o,onSelectProject:mn,onAddProject:es,onPauseProject:Jt,onResumeProject:Sn,onRemoveProject:Cn,nodes:u})}):ae==="skills"?j?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(TP,{addToast:n,projectId:f?.id,onClose:()=>pe("board")})})}):(pe("board"),null):ae==="chat"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(AP,{addToast:n,projectId:f?.id})})}):ae==="mailbox"?t.jsx(Jn,{children:t.jsx(T1,{projectId:f?.id,addToast:n,onUnreadCountChange:je})}):ae==="roadmaps"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(RP,{addToast:n,projectId:f?.id})})}):ae==="missions"?t.jsx(Jn,{children:t.jsx(_1,{isInline:!0,isOpen:!0,onClose:()=>{ue(void 0),de(void 0),Se(void 0),pe("board")},addToast:n,projectId:f?.id,onSelectTask:We=>{const mt=ne.find(fn=>fn.id===We);mt&&G.openDetailTask(mt)},availableTasks:ne.map(We=>({id:We.id,title:We.title})),resumeSessionId:$e,targetMissionId:re,milestoneSliceResumeSessionId:Pe,onMilestoneSliceResumeFetchError:()=>Se(void 0)})}):ae==="agents"&&De?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(CP,{addToast:n,projectId:f?.id})})}):ae==="documents"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(EP,{projectId:f?.id,addToast:n,onOpenDetail:G.openDetailTask})})}):ae==="insights"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(_P,{projectId:f?.id,addToast:n,onClose:()=>pe("board")})})}):ae==="memory"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(PP,{addToast:n,projectId:f?.id})})}):ae==="todos"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx($P,{addToast:n,projectId:f?.id})})}):ae==="devserver"||ae==="dev-server"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(IP,{addToast:n,projectId:f?.id})})}):ae==="board"?t.jsx(Jn,{children:t.jsx(EN,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f?.id,maxConcurrent:Mt,onMoveTask:le,onPauseTask:ve,onOpenDetail:G.openDetailTask,addToast:n,onQuickCreate:vn,onNewTask:G.openNewTask,onPlanningMode:G.openPlanningWithInitialPlan,onSubtaskBreakdown:G.openSubtaskBreakdown,autoMerge:yt,onToggleAutoMerge:$t,globalPaused:Et,onUpdateTask:Ke,onRetryTask:Fe,onArchiveTask:Xe,onUnarchiveTask:Qe,onDeleteTask:ee,onArchiveAllDone:it,onLoadArchivedTasks:Ie,searchQuery:P,availableModels:nt,onOpenDetailWithTab:jt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn,taskStuckTimeoutMs:Tt,onOpenMission:xt,lastFetchTimeMs:Ge})}):t.jsx(Jn,{children:t.jsx(AN,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f?.id,onMoveTask:le,onRetryTask:Fe,onOpenDetail:G.openDetailTask,addToast:n,globalPaused:Et,onNewTask:G.openNewTask,onQuickCreate:vn,onPlanningMode:G.openPlanningWithInitialPlan,onSubtaskBreakdown:G.openSubtaskBreakdown,availableModels:nt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn,taskStuckTimeoutMs:Tt,searchQuery:P,lastFetchTimeMs:Ge})});if(!se)return t.jsxs(t.Fragment,{children:[t.jsx(sT,{stage:be}),t.jsx(ag,{toasts:e,onRemove:s})]});const _e=!G.modelOnboardingOpen&&C4(),at=!G.modelOnboardingOpen&&!_e&&ja()&&!tg();return t.jsxs(t.Fragment,{children:[t.jsx(tw,{isElectron:i,onOpenSettings:Gt,onOpenGitHubImport:G.openGitHubImport,onOpenPlanning:G.openPlanning,onResumePlanning:G.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:G.openUsage,onOpenActivityLog:G.openActivityLog,onOpenSystemStats:G.openSystemStats,onOpenMailbox:()=>U("mailbox"),mailboxUnreadCount:lt,onOpenSchedules:G.openSchedules,onOpenGitManager:G.openGitManager,onOpenNodes:_t,showNodesButton:V,onOpenWorkflowSteps:G.openWorkflowSteps,onOpenScripts:G.openScripts,onRunScript:G.runScript,onToggleTerminal:G.toggleTerminal,onOpenFiles:G.openFiles,filesOpen:G.filesOpen,globalPaused:Et,enginePaused:Nt,onToggleGlobalPause:B,onToggleEnginePause:ge,view:ae,onChangeView:me==="project"&&f?U:void 0,showSkillsTab:j,showAgentsTab:De,searchQuery:P,onSearchChange:F,projects:$,currentProject:f,onSelectProject:mn,onViewAllProjects:wn,projectId:f?.id,mobileNavEnabled:Be,availableNodes:u,currentNode:d,onSelectNode:We=>{We===null?p():g(We)},isRemote:h,experimentalFeatures:{insights:zt,roadmap:Ct,memoryView:At,devServer:kt,devServerView:kt,todoView:Kt}}),me==="project"&&f&&!Ae&&ae!=="missions"&&!G.isPlanningOpen&&t.jsx(gT,{sessions:q,onResumeSession:ts,onDismissSession:ns,onDismissAll:ss}),me==="project"&&f&&_e&&t.jsx(bT,{onResume:G.openModelOnboarding}),me==="project"&&f&&at&&t.jsx(vT,{onOpenModelOnboarding:G.openModelOnboarding,onOpenSettings:We=>G.openSettings(We)}),me==="project"&&f&&N&&M&&C&&!z&&t.jsx(xT,{latestVersion:M,currentVersion:C,onDismiss:A}),me==="project"&&f&&!k&&R&&!gt&&t.jsx(eg,{hasAiProvider:y,hasGithub:S,onDismiss:wt}),t.jsx("div",{className:`project-content${me==="project"&&f?" project-content--with-footer":""}${Be?" project-content--with-mobile-nav":""}`,children:oe()}),me==="project"&&f&&!Ae&&t.jsx(hT,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f.id,taskStuckTimeoutMs:Tt,backgroundSessions:Q,backgroundGenerating:E,backgroundNeedsInput:D,onOpenBackgroundSession:ts,onDismissBackgroundSession:w,lastFetchTimeMs:Ge,currentProjectPath:f.path,onOpenProjectDirectory:yn}),t.jsx(kT,{view:ae,onChangeView:me==="project"&&f?U:()=>{},footerVisible:me==="project"&&!!f,modalOpen:G.anyModalOpen,onOpenSettings:Gt,onOpenActivityLog:G.openActivityLog,onOpenSystemStats:G.openSystemStats,onOpenMailbox:()=>U("mailbox"),mailboxUnreadCount:lt,onOpenGitManager:G.openGitManager,onOpenWorkflowSteps:G.openWorkflowSteps,onOpenSchedules:G.openSchedules,onOpenScripts:G.openScripts,onToggleTerminal:G.toggleTerminal,onOpenFiles:G.openFiles,onOpenGitHubImport:G.openGitHubImport,onOpenPlanning:G.openPlanning,onResumePlanning:G.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:()=>G.openUsage(null),onViewAllProjects:wn,onRunScript:G.runScript,projectId:f?.id,showSkillsTab:j,experimentalFeatures:{insights:zt,roadmap:Ct,memoryView:At,devServer:kt,devServerView:kt,todoView:Kt}}),me==="project"&&f&&ae!=="chat"&&ae!=="mailbox"&&ae!=="insights"&&ae!=="devserver"&&ae!=="dev-server"&&t.jsx(BT,{projectId:f.id,addToast:n,showFAB:Ht,open:fe,onOpenChange:tt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn}),t.jsx(eT,{projectId:f?.id,tasks:ne,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:G,projectActions:{handleAddProject:es,handleSetupComplete:we,handleModelOnboardingComplete:rt},taskHandlers:{handleModalCreate:Y,handlePlanningTaskCreated:Oe,handlePlanningTasksCreated:Ye,handleSubtaskTasksCreated:st,handleGitHubImport:pt},taskOperations:{moveTask:le,deleteTask:ee,mergeTask:Ee,retryTask:Fe,duplicateTask:Ze},deepLink:{handleDetailClose:Rn},settings:{prAuthAvailable:Ut,themeMode:_,colorTheme:I,setThemeMode:O,setColorTheme:J},onSettingsClose:()=>{G.closeSettings(),te()},onReopenOnboarding:()=>{G.closeSettings(),G.openModelOnboarding()}}),t.jsx(NP,{open:ut})]})}function zP(){return t.jsx(QT,{children:t.jsx(jP,{children:t.jsx(fw,{children:t.jsx(LP,{})})})})}yv();av();hg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(rv,{children:t.jsx(zP,{})})}));"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{console.log("SW registered:",e.scope)}).catch(e=>{console.log("SW registration failed:",e)});export{nn as $,Cs as A,gn as B,dn as C,u4 as D,jD as E,Oi as F,To as G,hn as H,sc as I,xn as J,Gs as K,ot as L,Xt as M,qt as N,g4 as O,An as P,Nk as Q,Nn as R,oa as S,Yc as T,c4 as U,d4 as V,Sk as W,Ot as X,ZI as Y,Pn as Z,Ck as _,os as a,E$ as a$,kI as a0,jI as a1,fo as a2,Py as a3,pc as a4,da as a5,wa as a6,ci as a7,di as a8,li as a9,pr as aA,Kj as aB,dD as aC,uD as aD,Gj as aE,Jj as aF,_T as aG,Cr as aH,TT as aI,Ao as aJ,jT as aK,CT as aL,ms as aM,Di as aN,bi as aO,Xb as aP,g$ as aQ,b$ as aR,x$ as aS,v$ as aT,y$ as aU,k$ as aV,j$ as aW,w$ as aX,N$ as aY,S$ as aZ,C$ as a_,mD as aa,fD as ab,pD as ac,hD as ad,gD as ae,qn as af,Xn as ag,Vb as ah,Ys as ai,lx as aj,Mo as ak,yi as al,SD as am,wD as an,ND as ao,CD as ap,mo as aq,Ib as ar,sr as as,sx as at,Yn as au,Kh as av,Bo as aw,KT as ax,cD as ay,Xd as az,l$ as b,nD as b$,_$ as b0,M$ as b1,R$ as b2,T$ as b3,A$ as b4,Mn as b5,Jc as b6,Fi as b7,oD as b8,rD as b9,Xc as bA,Zy as bB,ek as bC,tk as bD,Xy as bE,II as bF,yr as bG,$o as bH,Tb as bI,dr as bJ,Sb as bK,I$ as bL,$$ as bM,D$ as bN,L$ as bO,z$ as bP,F$ as bQ,O$ as bR,P$ as bS,Xh as bT,ha as bU,Tk as bV,mv as bW,hv as bX,tD as bY,NI as bZ,wI as b_,lD as ba,tI as bb,eI as bc,ZP as bd,nI as be,uI as bf,mI as bg,lI as bh,aI as bi,rI as bj,oI as bk,iI as bl,sI as bm,XP as bn,cI as bo,XA as bp,LI as bq,DI as br,HI as bs,$I as bt,zI as bu,FI as bv,OI as bw,UI as bx,nk as by,BI as bz,Ue as c,zx as c$,SI as c0,PI as c1,AI as c2,CI as c3,RI as c4,EI as c5,TI as c6,_I as c7,MI as c8,_g as c9,YA as cA,b4 as cB,ic as cC,Oo as cD,KP as cE,qP as cF,WP as cG,GP as cH,JP as cI,YP as cJ,QP as cK,lw as cL,Uo as cM,vD as cN,Bm as cO,yD as cP,kD as cQ,dI as cR,U$ as cS,H$ as cT,W$ as cU,q$ as cV,B$ as cW,V$ as cX,K$ as cY,rp as cZ,Id as c_,Xs as ca,zA as cb,hI as cc,p$ as cd,UP as ce,BP as cf,mr as cg,c$ as ch,HP as ci,VP as cj,ry as ck,Qv as cl,Qs as cm,Xv as cn,Zv as co,ey as cp,gI as cq,d$ as cr,u$ as cs,m$ as ct,wi as cu,xD as cv,bD as cw,f$ as cx,mc as cy,In as cz,r$ as d,G$ as d0,t$ as d1,YI as d2,XI as d3,QI as d4,i$ as d5,s$ as d6,Uh as d7,GI as d8,KI as d9,l4 as da,e$ as db,vr as dc,oM as dd,VI as de,qI as df,Iy as dg,WI as dh,JI as di,J$ as dj,Y$ as dk,wb as dl,bc as dm,sD as dn,Z$ as dp,X$ as dq,eD as dr,Q$ as ds,h$ as dt,xI as du,pI as dv,fI as dw,vI as dx,yI as dy,bI as dz,o$ as e,aD as f,Dn as g,cs as h,Na as i,iD as j,$n as k,wk as l,a$ as m,ST as n,Ds as o,Lo as p,zr as q,ke as r,Ls as s,mw as t,sn as u,n$ as v,gc as w,Js as x,Zt as y,uo as z};
|
|
656
|
+
`)[0]?.trim()||Jt?.title||"",Cn=new Set(ac),pn=Pt.filter(Y=>Cn.has(Y.id)).sort((Y,Oe)=>{const Ye=ac.indexOf(Y.id),st=ac.indexOf(Oe.id);return Ye!==st?Ye-st:kh(Y,Oe)}),bn=Pt.filter(Y=>Y.authenticated&&!Cn.has(Y.id)),Rn=Pt.filter(Y=>!Y.authenticated&&!Cn.has(Y.id)),vn=Y=>{if(Y.id==="claude-cli"&&Y.type==="cli")return t.jsx(b4,{authenticated:Y.authenticated,onToggled:()=>{ie()}},Y.id);if(Y.type==="api_key"){const Oe=Vc(Y.id),Ye=W4(Y);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Y.id}`,className:`onboarding-provider-card${Y.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Y.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:Y.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(Vh,{size:14,className:"onboarding-provider-key-icon"}),Y.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:Oe.description}),t.jsx(Pe,{status:ue(Y)}),Y.authenticated&&Y.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",Y.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(G4,{provider:Y,apiKeyInfo:Ye,inputValue:Ne[Y.id]??"",isSaving:D===Y.id,error:xe[Y.id],success:ve[Y.id],isConnected:Y.authenticated,onInputChange:Ht,onSave:Vt,onClear:zt})})]},Y.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${Y.id}`,className:`onboarding-provider-card${Y.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${Y.id}`,"aria-hidden":"true",children:t.jsx(An,{provider:Y.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:Y.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:Vc(Y.id).description}),t.jsx(Pe,{status:ue(Y)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:D===Y.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:Y.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Tt(Y.id),children:"Cancel"})]}):Y.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct(Y.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Nt(Y.id),children:"Login"})}),D===Y.id&&w[Y.id]&&t.jsx(ic,{instructions:w[Y.id],"data-testid":`onboarding-login-instructions-${Y.id}`}),Xe[Y.id]==="timeout"&&D!==Y.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Xe[Y.id]==="failed"&&D!==Y.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},Y.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:Ke,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(Pn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(hs,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(_d,{size:24})," Set Up Your Project"]}),x==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(_d,{size:24})," Create Your First Task"]}),x==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(dn,{size:24})," All Set!"]})]}),x!=="complete"&&t.jsx("button",{className:"modal-close",onClick:te,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Ot,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:Me.map((Y,Oe)=>{const Ye=lt>Oe,st=b.includes(Y.key)&&Ye,pt=S.includes(Y.key)&&!b.includes(Y.key)&&Ye,jt=st||pt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Oe>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Oe<=lt?"done":""}`}),jt?t.jsxs("button",{className:`model-onboarding-step-indicator ${x===Y.key?"active":""} ${st?"done":""} ${pt?"skipped":""}`,onClick:()=>v(Y.key),"aria-label":`Go back to ${Y.label}`,title:`Review ${Y.label}`,children:[t.jsx("span",{className:"step-number",children:st?t.jsx(dn,{size:14}):pt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Oe+1}),t.jsx("span",{className:"step-label",children:Y.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${x===Y.key?"active":""} ${st?"done":""} ${pt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:st?t.jsx(dn,{size:14}):pt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Oe+1}),t.jsx("span",{className:"step-label",children:Y.label})]})]},Y.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Fe,children:[x==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!Q&&_.length>0&&(()=>{const Y=_.filter(jt=>jt.id!=="github"&&jt.authenticated).length,Oe=_.filter(jt=>jt.id!=="github").length,Ye=Object.keys(ze).filter(jt=>!_.find(_t=>_t.id===jt)?.authenticated).length;if(Oe===0)return null;let st="onboarding-provider-summary",pt="";return Y>0?(st+=" onboarding-provider-summary--connected",pt=`✓ ${Y} of ${Oe} provider${Oe!==1?"s":""} connected`):Ye>0?(st+=" onboarding-provider-summary--skipped",pt=`${Ye} provider${Ye!==1?"s":""} skipped`):(st+=" onboarding-provider-summary--none",pt="No providers connected yet"),t.jsx("div",{className:st,"data-testid":"provider-summary",children:pt})})(),t.jsx(Ws,{summary:"What are AI providers?",children:t.jsx("p",{className:"onboarding-helper-text",children:"AI providers like OpenAI and Anthropic power the AI capabilities in Fusion. Connecting a provider lets Fusion's agents use AI models to help with your tasks."})}),_.length>0&&!_.some(Y=>Y.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),Q?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(ot,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):_.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-quick-start-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Quick start providers"}),pn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:pn.map(Y=>vn(Y))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),bn.length>0&&t.jsxs("section",{className:"onboarding-provider-section","data-testid":"onboarding-connected-providers",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connected providers"}),t.jsx("div",{className:"model-onboarding-providers",children:bn.map(Y=>vn(Y))})]}),t.jsxs("div",{className:"onboarding-model-section",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Default Model (Optional)"}),t.jsx("p",{className:"model-onboarding-description",children:"Pick a default model for AI tasks, or leave this blank to choose later. Models vary in speed, capability, and cost."}),t.jsx(Ws,{summary:"How do I choose a model?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Models vary in speed, capability, and cost. A good default is usually the latest model from your connected provider. You can always change this later in Settings."})}),G.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No models available yet. Connect a provider above to see model options."}):t.jsx("div",{className:"onboarding-model-selector",children:t.jsx($n,{models:G,value:ce,onChange:At,placeholder:"Select a default model…",label:"Default model"})}),ce&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",G.find(Y=>Y.id===ce)?.name??ce]})})]}),t.jsx(Ws,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:Rn.length>0?t.jsx("div",{className:"model-onboarding-providers",children:Rn.map(Y=>vn(Y))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),Rt&&t.jsx(Ws,{summary:"How does login work?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Clicking Login opens the provider's website in a new tab where you sign in. Once you authorize Fusion, this page will automatically detect the connection. Your credentials are never stored in Fusion."})}),un&&t.jsx(Ws,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]})]}),x==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[de?t.jsx("p",{className:"model-onboarding-description",children:re?"GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed.":"GitHub is connected — issue imports and pull request tracking are available. You're all set; no further action needed."}):t.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),!de&&t.jsx("div",{className:"onboarding-feature-list",children:t.jsxs("ul",{children:[t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"Without GitHub (available now):"})}),t.jsx("li",{className:"onboarding-helper-text",children:"Create tasks manually"}),t.jsx("li",{className:"onboarding-helper-text",children:"Describe work for AI agents"}),t.jsx("li",{className:"onboarding-helper-text",children:"Track progress on the board"}),t.jsx("li",{className:"onboarding-feature-list-heading",children:t.jsx("strong",{children:"With GitHub (after connecting):"})}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Import issues as tasks"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Sync pull request status"}),t.jsx("li",{className:"onboarding-helper-text onboarding-feature-list-item--with-github",children:"Link code changes to tasks"})]})}),es&&t.jsxs("div",{className:"onboarding-skip-banner",role:"status",children:[t.jsx("strong",{children:"No AI provider connected"}),t.jsx("p",{children:"AI features like task planning and code generation won't be available until you connect one. You can set this up later in Settings."})]}),t.jsx(Ws,{summary:"What does GitHub integration do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Without GitHub, you can still create and manage tasks manually. GitHub integration adds the ability to import issues as tasks, track pull request status alongside your work, and automatically link commits to tasks. Connect anytime from Settings → Authentication."})}),Re?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(hs,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(fe,{status:nt})})]}),Je&&(D==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct("github"),children:"Disconnect"}))]}),(nt==="not-connected"||nt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[D==="github"?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Tt("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Nt("github"),children:[t.jsx(hs,{size:16}),"Connect"]}),D==="github"&&w.github&&t.jsx(ic,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]}),nt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:re?"GitHub CLI is authenticated. Imports and pull request tracking are available. Connect OAuth in Settings → Authentication if you want dashboard-managed sign-in controls.":"GitHub OAuth is connected. You can import issues and track pull requests."}),nt==="failed"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--error",children:[t.jsx("p",{children:"Connection failed or timed out."}),t.jsxs("div",{className:"onboarding-github-feedback-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Et,children:"Skip for now"})]})]}),nt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),nt==="skipped"&&t.jsxs("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:[t.jsx("p",{children:"GitHub was skipped. You can connect anytime from Settings → Authentication."}),t.jsx("div",{className:"onboarding-github-feedback-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:"Connect anyway"})})]}),nt==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(An,{provider:"github",size:"lg"})}),re?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:re?"Continue with gh CLI auth →":"Continue without GitHub →"}),re&&(D==="github"?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(ot,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>Nt("github"),children:[t.jsx(An,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),re&&D==="github"&&w.github&&t.jsx(ic,{instructions:w.github,"data-testid":"onboarding-login-instructions-github"})]})]}),x==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),Gt?t.jsx("div",{className:"onboarding-project-ready","data-testid":"onboarding-project-ready",role:"status",children:t.jsx("p",{children:"Project selected — task creation and imports are available."})}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project is required before first-task actions are available."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(Ws,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),x==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),R&&Jt?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(dn,{size:56,className:"success-icon"}),t.jsx("h3",{className:"onboarding-task-created__title",children:"Your first task is ready!"}),t.jsx("div",{className:"onboarding-task-created__task-id",children:Jt.id}),Sn&&t.jsx("p",{className:"onboarding-task-created__description",children:Sn}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:V,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:De,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[Gt?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-first-task-form",children:[t.jsx("label",{className:"onboarding-first-task-form__label",htmlFor:"onboarding-first-task-input",children:"Describe your first task"}),t.jsx("textarea",{id:"onboarding-first-task-input",className:"input onboarding-first-task-form__input","data-testid":"onboarding-first-task-input",value:M,onChange:Y=>{C(Y.target.value),F(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:$t,disabled:z,"data-testid":"onboarding-first-task-submit",children:z?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),P&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:P}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:i,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx(K4,{items:rt}),Gt&&t.jsxs(t.Fragment,{children:[t.jsx(Ws,{summary:"What happens when I create a task?",children:t.jsx("p",{className:"onboarding-helper-text",children:"A task describes something you want done. Fusion's AI agents will read your description and work on implementing it. You can track progress on the board and review the results."})}),t.jsxs("div",{className:"onboarding-cta-options",children:[t.jsxs("button",{className:"onboarding-cta-card primary",onClick:B,disabled:pe,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Zt,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Create a New Task"}),t.jsx("span",{children:"Describe what you need built and AI will work on it"})]})]}),t.jsxs("button",{className:`onboarding-cta-card${de?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:ge,disabled:pe||!de,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(hs,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!de&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),x==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(dn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[x==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:te,disabled:pe,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Mt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,children:"Next →"})]}),x==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Mt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,children:"Next →"})]}),x==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:wt,disabled:!Gt,children:"Next →"})]}),x==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:yt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:Kt,disabled:pe,children:pe?t.jsxs(t.Fragment,{children:[t.jsx(ot,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),x==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:j,children:[t.jsx(dn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function ag({toasts:e}){return t.jsx("div",{className:"toast-container",id:"toasts",children:e.map(n=>t.jsx("div",{className:`toast toast-${n.type}`,children:n.message},n.id))})}const Q4=a.lazy(()=>nn(()=>import("./SetupWizardModal-Bk_8HfLm.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),X4=a.lazy(()=>nn(()=>import("./SettingsModal-BiLA-BeG.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16])).then(e=>({default:e.SettingsModal})));function Z4(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{nn(()=>import("./SettingsModal-BiLA-BeG.js"),__vite__mapDeps([11,1,12,13,14,15,0,2,16]))},{timeout:1500})}function eT({projectId:e,tasks:n,projects:s,currentProject:i,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:u,taskHandlers:d,taskOperations:m,deepLink:h,settings:g,onSettingsClose:p,onReopenOnboarding:f}){const[x,v]=a.useState(null),b=c.detailTask?(()=>{const M=n.find(C=>C.id===c.detailTask?.id);return M?"prompt"in c.detailTask?{...c.detailTask,...M,prompt:c.detailTask.prompt,log:c.detailTask.log}:M:c.detailTask})():null,y=p??c.closeSettings,S=a.useCallback(()=>{c.openNewTask()},[c]),k=a.useCallback(()=>{c.openGitHubImport()},[c]),R=a.useCallback(M=>{v(null),c.closeModelOnboarding(),c.openDetailTask(M)},[c]),N=a.useCallback(async M=>{const C=await d.handleModalCreate(M);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&x&&v(null)},[c.modelOnboardingOpen,x]),a.useEffect(()=>{Z4()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ti,{children:t.jsx(XM,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:g.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ti,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(X4,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(eA,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ti,{children:t.jsx(iA,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:d.handlePlanningTaskCreated,onTasksCreated:d.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(Ti,{children:t.jsx(pA,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx($A,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(LA,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(iR,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(hR,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(BR,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(PR,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ti,{children:t.jsx(LR,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:N,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(KR,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:M=>{const C=n.find(z=>z.id===M);C&&c.openDetailTask(C)}}),t.jsx(Ti,{children:t.jsx(JR,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ti,{children:t.jsx(o4,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(x4,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(Q4,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(Y4,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:k,firstCreatedTask:x,onViewTask:R}),t.jsx(ag,{toasts:o,onRemove:l})]})}function tT({errorMessage:e,isRetrying:n,onRetry:s}){return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:"Can't reach the Fusion backend"}),t.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),t.jsxs("p",{className:"settings-muted",children:["Error: ",e]}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"})]})}const Wc=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function nT(e,n){if(n==="ready")return"done";const s=Wc.findIndex(r=>r.id===n),i=Wc.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function sT({stage:e}){const[n]=a.useState(()=>tv());return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":n?"Updating Fusion dashboard":"Loading Fusion dashboard","data-stage":e,"data-version-update":n?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),n?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:"Updating to a new frontend version..."}):t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:Wc.map(s=>{const i=nT(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${i}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:i==="done"?"✓":i==="active"?t.jsx(ot,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const iT=5e3;function aT(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function rT(e,n,s){let i=0,r=0,o=0,l=0,c=0;for(const u of e){switch(u.column){case"in-progress":i++,vo(u,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}u.blockedBy&&u.blockedBy.length>0&&r++}return{runningTaskCount:i,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function oT(e,n,s,i){const[r,o]=a.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=a.useState(!0),[u,d]=a.useState(null),m=a.useRef(null),h=a.useRef(null),g=a.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),d(null);const v=await Pk(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;d(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);a.useEffect(()=>(g(),()=>{h.current&&h.current.abort()}),[g]),a.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{g()},iT),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=rT(e,s,i),f=aT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const lT={planning:Ys,subtask:Ui,mission_interview:ls,milestone_interview:ls,slice_interview:ls},cT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function dT({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const{confirm:o}=Ds(),[l,c]=a.useState(!1),[u,d]=a.useState(new Set),m=a.useRef(null),h=a.useRef(new Map),g=a.useRef(null),{activeTabMap:p}=Sa(),f=a.useMemo(()=>Wi(),[]);if(a.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),a.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const k=p.get(S.id),R=[S.status,S.updatedAt,k?.tabId??S.lockedByTab??"",k?.stale?"stale":"fresh"].join("|"),N=h.current.get(S.id);N&&N!==R&&b.add(S.id),y.set(S.id,R)}if(h.current=y,b.size!==0)return d(b),g.current&&clearTimeout(g.current),g.current=setTimeout(()=>{d(new Set),g.current=null},500),()=>{g.current&&(clearTimeout(g.current),g.current=null)}},[p,e]),e.length===0)return null;const x=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${x} background AI task${x!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(ot,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(mc,{size:12}),t.jsxs("span",{children:["AI ",x]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=lT[b.type],S=b.status==="generating",k=b.status==="awaiting_input",R=b.status==="error",N=p.get(b.id),M=N?.tabId??b.lockedByTab??null,C=!!(M&&M!==f&&!N?.stale),z=u.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${z?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:z?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:z?"translateY(-1px)":void 0},onClick:async()=>{C&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(i(b),c(!1))},children:[R?t.jsx(Xn,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[R?"Failed":cT[b.type],S&&" — generating...",k&&!C&&" — needs input",k&&C&&" — active in another tab"]})]}),S&&t.jsx(ot,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),k&&!C&&t.jsx(mc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),k&&C&&t.jsx(Io,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:A=>{A.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(Ot,{size:12})})]},b.id)})})]})]})}function uT(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),i=n-s,r=Math.floor(i/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function mT(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:xn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Gs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:Pn}}}function hT({tasks:e,projectId:n,taskStuckTimeoutMs:s,backgroundSessions:i,backgroundGenerating:r,backgroundNeedsInput:o,onOpenBackgroundSession:l,onDismissBackgroundSession:c,lastFetchTimeMs:u,currentProjectPath:d,onOpenProjectDirectory:m}){const{stats:h,loading:g,error:p}=oT(e,n,s,u),[f,x]=a.useState(!1),v=a.useMemo(()=>mT(h.executorState),[h.executorState]),b=a.useMemo(()=>uT(h.lastActivityAt),[h.lastActivityAt]),y=v.icon;return p?t.jsx("div",{className:"executor-status-bar executor-status-bar--error",role:"status","aria-label":"Executor status",children:t.jsxs("span",{className:"executor-status-bar__error",children:[t.jsx(Yc,{size:14}),p]})}):g&&h.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${h.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[i&&i.length>0&&l&&c&&t.jsxs(t.Fragment,{children:[t.jsx(dT,{sessions:i,generating:r??0,needsInput:o??0,onOpenSession:l,onDismissSession:c}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:h.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${h.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:h.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:h.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),h.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:h.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${h.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${h.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:h.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:h.inReviewCount})]}),d&&m&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${f?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>x(S=>!S),"aria-label":f?"Hide project directory":"Show project directory","aria-expanded":f,"data-testid":"executor-project-path-toggle",title:f?"Hide project directory":"Show project directory",children:t.jsx(In,{size:12,"aria-hidden":"true"})}),f&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:m,title:d,"data-testid":"executor-project-path-link",children:d})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(yi,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:b})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(y,{size:12,style:{color:v.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:v.color},children:v.label})]})]})}const pT={planning:Ys,subtask:Ui,mission_interview:ls,milestone_interview:ls,slice_interview:ls},fT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},$i=new Set;function gT({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if($i.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let x=!1;for(const v of $i){const b=f.get(v);b&&b.status!=="awaiting_input"&&b.status!=="error"&&($i.delete(v),x=!0)}x&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!$i.has(f.id)),[e,r]);if(c.length===0)return null;const u=c.filter(f=>f.status==="awaiting_input").length,d=c.filter(f=>f.status==="error").length;let m="";u>0&&d>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input, ${d} failed`:u>0?m=`${u} AI session${u===1?"":"s"} need${u===1?"s":""} your input`:d>0&&(m=`${d} AI session${d===1?"":"s"} failed`);const h=f=>{$i.add(f),l()},g=f=>{$i.delete(f.id),l(),n(f)},p=()=>{for(const f of c)$i.add(f.id);l(),i()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(Xn,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Ot,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const x=pT[f.type],v=f.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":f.type,"data-session-status":f.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(Xn,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(x,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":fT[f.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>g(f),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(f.id),s(f.id)},"aria-label":`Dismiss ${f.title}`,children:t.jsx(Ot,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function xT({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"npm i -g @runfusion/fusion"})," to update. "," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/releases",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(Ot,{size:16,"aria-hidden":"true"})})]})}function bT({onResume:e}){const n=E4();if(!n)return null;const s=n.completedSteps.length,i=xi.length,r=s>0?`${s} of ${i} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(qn,{size:20})}),t.jsxs("div",{className:"onboarding-resume-card__content",children:[t.jsx("h2",{className:"onboarding-resume-card__title",children:"Continue Setup"}),t.jsxs("p",{className:"onboarding-resume-card__description",children:[r,t.jsx("strong",{children:n.label})," step. Continue where you left off to complete your dashboard setup."]})]})]}),t.jsx("div",{className:"onboarding-resume-card__actions",children:t.jsxs("button",{className:"onboarding-resume-card__resume-btn btn btn-primary btn-sm",onClick:()=>{ws("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function vT({onOpenSettings:e,onOpenModelOnboarding:n}){const s=ja(),i=tg(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,k]=await Promise.all([mr(),Vi()]);if(b)return;const R=S.providers??[],N=R.find(P=>P.id==="github"),C=!R.some(P=>P.id!=="github"&&P.authenticated),z=!k.defaultProvider&&!k.defaultModelId,A=N?!N.authenticated:!1;h({needsAiProvider:C,needsDefaultModel:z,needsGitHub:A})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,i]);const g=a.useCallback(()=>{S4(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),x=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:Pn}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:Vh}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:x,icon:hs}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,x,f,p]);return!s||i||u||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Ys,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(Xn,{size:14,"aria-hidden":!0}),t.jsx(y,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Ot,{size:16,"aria-hidden":!0})})]})}function yT({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 rc(e){return e>99?"99+":String(e)}function kT({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:o,onOpenSystemStats:l,onOpenMailbox:c,mailboxUnreadCount:u=0,onOpenGitManager:d,onOpenWorkflowSteps:m,onOpenSchedules:h,onOpenScripts:g,onToggleTerminal:p,onOpenFiles:f,onOpenGitHubImport:x,onOpenPlanning:v,onResumePlanning:b,activePlanningSessionCount:y=0,onOpenUsage:S,onRunScript:k,projectId:R,onViewAllProjects:N,showSkillsTab:M,experimentalFeatures:C}){const z=Cr(),[A,P]=a.useState(!1),[F,W]=a.useState(!1),[$,_]=a.useState({}),[I,O]=a.useState(!1),J=a.useMemo(()=>Object.entries($).sort(([pe],[U])=>pe.localeCompare(U)),[$]);a.useEffect(()=>{if(!F)return;let pe=!1;return O(!0),hr(R).then(U=>{pe||_(U)}).catch(()=>{pe||_({})}).finally(()=>{pe||O(!1)}),()=>{pe=!0}},[F,R]);const Q=a.useCallback(()=>P(!1),[]),E=a.useCallback(pe=>{Q(),pe?.()},[Q]);if(a.useEffect(()=>{if(!A)return;const pe=U=>{U.key==="Escape"&&P(!1)};return document.addEventListener("keydown",pe),()=>document.removeEventListener("keydown",pe)},[A]),z!=="mobile"||i)return null;const D=y>0&&b?b:v,T=!!C?.roadmap,w=!!M,q=!!C?.todoView,G=T&&(!w||e==="roadmaps"),me=w&&(!T||e!=="roadmaps"),ce=w&&!me,ae=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="todos"&&q||e==="roadmaps"&&!G||e==="skills"&&!me;return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(Bi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Tasks"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="agents"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-agents",role:"tab","aria-selected":e==="agents",onClick:()=>n("agents"),children:[t.jsx(gn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Agents"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="missions"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-missions",role:"tab","aria-selected":e==="missions",onClick:()=>n("missions"),children:[t.jsx(ls,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsx(bi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsx(ma,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:rc(u)})]}),me&&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(Pn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),G&&t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="roadmaps"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-roadmaps",role:"tab","aria-selected":e==="roadmaps",onClick:()=>n("roadmaps"),children:[t.jsx(xc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ae?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>P(pe=>!pe),children:[t.jsx(hc,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),A&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:Q}),t.jsxs("div",{className:"mobile-more-sheet",children:[t.jsx("div",{className:"mobile-more-sheet-handle"}),t.jsx("div",{className:"mobile-more-sheet-title",children:"Navigate"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>E(c),children:[t.jsx(ma,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:rc(u)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>E(o),children:[t.jsx(Cs,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>E(l),children:[t.jsx(dr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>E(d),children:[t.jsx(Js,{}),t.jsx("span",{children:"Git Manager"})]}),t.jsxs("div",{className:"mobile-more-split-row",children:[t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-split-primary","data-testid":"mobile-more-item-terminal",onClick:()=>E(p),children:[t.jsx(ri,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>W(pe=>!pe),"aria-expanded":F,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(hn,{size:14,className:`mobile-more-chevron${F?" mobile-more-chevron--open":""}`})})]}),F&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:I?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(ot,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):J.length>0?t.jsxs(t.Fragment,{children:[J.map(([pe,U])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${pe}`,onClick:()=>{k&&k(pe,U),Q(),W(!1)},children:[t.jsx(xn,{size:14}),t.jsx("span",{children:pe})]},pe)),g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{Q(),W(!1),g()},children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):g&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{Q(),W(!1),g()},children:[t.jsx(Is,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>E(f),children:[t.jsx(In,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>E(D),children:[t.jsx(Ys,{}),t.jsx("span",{children:"Planning"}),y>0&&t.jsx("span",{className:"mobile-more-item-badge",children:rc(y)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>E(m),children:[t.jsx(vc,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>E(h),children:[t.jsx(yi,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>E(x),children:[t.jsx(yT,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>E(S),children:[t.jsx(Cs,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>E(N),children:[t.jsx(qh,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>E(()=>n("documents")),children:[t.jsx(Oi,{}),t.jsx("span",{children:"Documents"})]}),ce&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>E(()=>n("skills")),children:[t.jsx(Pn,{}),t.jsx("span",{children:"Skills"})]}),T&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>E(()=>n("roadmaps")),children:[t.jsx(xc,{}),t.jsx("span",{children:"Roadmaps"})]}),C?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>E(()=>n("insights")),children:[t.jsx(qn,{}),t.jsx("span",{children:"Insights"})]}),C?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>E(()=>n("memory")),children:[t.jsx(co,{}),t.jsx("span",{children:"Memory"})]}),C?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{E(()=>n("dev-server"))},children:[t.jsx(dr,{size:14}),t.jsx("span",{children:"Dev Server"})]}),q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>E(()=>n("todos")),children:[t.jsx(Gh,{size:14}),t.jsx("span",{children:"Todos"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>E(r),children:[t.jsx(sr,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function jT({agents:e,filter:n,highlightedIndex:s,visible:i,onSelect:r,position:o="below"}){const l=a.useMemo(()=>{const c=n.trim().toLowerCase();return c?e.filter(u=>u.name.toLowerCase().includes(c)):e},[e,n]);return i?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:l.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):l.map((c,u)=>t.jsxs("button",{type:"button",className:`agent-mention-item${u===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${c.id}`,onMouseDown:d=>d.preventDefault(),onClick:()=>r(c),role:"option","aria-selected":u===s,children:[t.jsx(gn,{size:14,"aria-hidden":"true"}),t.jsx("span",{className:"agent-mention-name",children:c.name}),t.jsx("span",{className:"agent-mention-role",children:c.role})]},c.id))}):null}const Sd="__fn_agent__";function rg(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function jh(e,n,s){const i=typeof e=="string"?e.trim():"",r=rg(n,s),o=i||(r.modelProvider&&r.modelId?Sd:"");return o?{agentId:o,...r}:null}function oc(e,n,s){const i=rg(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function wT(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 wh(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:wT(e.metadata),createdAt:e.createdAt}}function NT(e,n){const[s,i]=a.useState(null),[r,o]=a.useState(!1),[l,c]=a.useState([]),[u,d]=a.useState(!1),[m,h]=a.useState(!1),[g,p]=a.useState(""),[f,x]=a.useState(""),[v,b]=a.useState([]),[y,S]=a.useState(""),k=a.useRef(null),R=a.useRef(!1),N=a.useRef(""),M=a.useRef(""),C=a.useRef(null);a.useEffect(()=>{N.current=y},[y]);const z=a.useCallback(async Q=>{const E={agentId:Q.agentId};return Q.modelProvider&&Q.modelId&&(E.modelProvider=Q.modelProvider,E.modelId=Q.modelId),(await Kj(E,e)).session},[e]),A=a.useCallback(async(Q,E,D)=>{const T=jh(Q,E,D);if(!T)return;const w=oc(T.agentId,T.modelProvider,T.modelId);o(!0);try{const{session:q}=await Wj({agentId:T.agentId,modelProvider:T.modelProvider,modelId:T.modelId},e);if(q)i(q),M.current=w;else{const G=await z(T);i(G),M.current=w}}catch(q){console.error("[useQuickChat] Failed to initialize session:",q),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,z]),P=a.useCallback(async()=>{if(s){d(!0);try{const Q=await Xd(s.id,{limit:50},e);c(Q.messages.map(wh))}catch(Q){console.error("[useQuickChat] Failed to load messages:",Q)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?P():c([])},[s,P]);const F=a.useCallback(async()=>{if(s){d(!0);try{const Q=await Xd(s.id,{limit:50},e);c(Q.messages.map(wh))}catch(Q){console.error("[useQuickChat] Failed to reload messages:",Q)}finally{d(!1)}}},[s,e]),W=a.useCallback(async(Q,E,D)=>{const T=jh(Q,E,D);if(!T)return;const w=oc(T.agentId,T.modelProvider,T.modelId);C.current=T;const q=w===M.current&&s;if(q||(k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1)),q){await F();return}i(null),c([]),M.current=w,await A(T.agentId,T.modelProvider,T.modelId)},[A,F,s]),$=a.useCallback(async(Q,E)=>{await W(Sd,Q,E)},[W]),_=a.useCallback(async()=>{const Q=C.current;if(!Q)return;const E=oc(Q.agentId,Q.modelProvider,Q.modelId);k.current&&(k.current.close(),k.current=null),p(""),x(""),b([]),h(!1),c([]),i(null),o(!0);try{const D=await z(Q);i(D),M.current=E}catch(D){console.error("[useQuickChat] Failed to start a fresh session:",D),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,z]),I=a.useCallback(()=>{s&&(R.current=!0,k.current?.close(),k.current=null,Gj(s.id,e).catch(()=>{}),h(!1),p(""),x(""),b([]))},[s,e]),O=a.useCallback(()=>{N.current="",S("")},[]),J=a.useCallback(Q=>{if(!s||!Q.trim())return;if(m){N.current=Q,S(Q);return}R.current=!1,k.current&&(k.current.close(),k.current=null);const D={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:Q,createdAt:new Date().toISOString()};c(me=>[...me,D]),p(""),x(""),b([]),h(!0);let T="",w="",q=[];const G={onThinking:me=>{w+=me,x(w)},onText:me=>{T+=me,p(T)},onToolStart:me=>{q=[...q,{toolName:me.toolName,args:me.args,isError:!1,status:"running"}],b(q)},onToolEnd:me=>{const ce=[...q];for(let ae=ce.length-1;ae>=0;ae--){const pe=ce[ae];if(pe?.toolName===me.toolName&&pe.status==="running"){ce[ae]={...pe,status:"completed",isError:me.isError,result:me.result},q=ce,b(ce);return}}q=[...ce,{toolName:me.toolName,isError:me.isError,result:me.result,status:"completed"}],b(q)},onDone:me=>{const ce={id:me.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:T,thinkingOutput:w||void 0,toolCalls:q.length>0?q:void 0,createdAt:new Date().toISOString()};c(pe=>[...pe,ce]),p(""),x(""),b([]),h(!1),k.current=null;const ae=N.current.trim();ae&&(N.current="",S(""),J(ae))},onError:me=>{if(p(""),x(""),b([]),h(!1),k.current=null,console.error("[useQuickChat] Stream error:",me),n?.("Failed to get response","error"),!R.current){const ce=N.current.trim();ce&&(N.current="",S(""),J(ce))}F()}};k.current=Jj(s.id,Q,G,e)},[s,m,e,n,F]);return a.useEffect(()=>()=>{k.current&&(k.current.close(),k.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:y,sendMessage:J,stopStreaming:I,clearPendingMessage:O,switchSession:W,startModelChat:$,startFreshSession:_,loadMessages:P,reloadMessages:F}),[s,r,l,u,m,g,f,v,y,J,I,O,W,$,_,P,F])}function ST(e,n){const[s,i]=a.useState([]),[r,o]=a.useState(null),[l,c]=a.useState(!1),u=a.useCallback(async g=>{c(!0);try{const p=n?.filterState,f=p&&p!=="all"?{state:p}:void 0,x=n?.showSystemAgents??!1,v=await Na({...f,...g,includeEphemeral:g?.includeEphemeral??x},e),b=Array.from(new Map(v.map(y=>[y.id,y])).values());i(b)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await Ek(e);o(g)}catch(g){console.error("Failed to load agent stats:",g)}},[e]);a.useEffect(()=>{u(),d()},[u,d]),a.useEffect(()=>{const g=e?`?projectId=${encodeURIComponent(e)}`:"",p=()=>{u(),d()};return Ls(`/api/events${g}`,{events:{"agent:created":p,"agent:updated":p,"agent:deleted":p,"agent:stateChanged":p}})},[e,u,d]);const m=n?.showSystemAgents??!1,h=s.filter(g=>g.state!=="active"&&g.state!=="running"?!1:m||!mw(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function CT({visible:e,position:n,files:s,selectedIndex:i,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const u=l.path.includes("/")?l.path.slice(0,l.path.lastIndexOf("/")+1):"",d=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===i?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===i,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Bh,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:d}),u&&t.jsx("span",{className:"file-mention-popup-item-path",children:u})]})]},l.path)})})]}):null}const ET=200;function _T(e={}){const{projectId:n,workspace:s="project"}=e,[i,r]=a.useState(!1),[o,l]=a.useState(""),[c,u]=a.useState(-1),[d,m]=a.useState([]),[h,g]=a.useState(!1),[p,f]=a.useState(0),x=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{x.current&&clearTimeout(x.current),v.current?.abort()},[]);const b=a.useCallback((N,M)=>{if(M<0||M>N.length){r(!1);return}const C=z=>/[a-zA-Z0-9/_.-]/.test(z);for(let z=M-1;z>=0;z--){if(N[z]==="#")if(z===0){const A=N.slice(z+1,M);u(z),l(A),f(0),r(!0);return}else{const A=N[z-1];if(/[\s,.;:!?'"()[\]{}]/.test(A)){const P=N.slice(z+1,M);u(z),l(P),f(0),r(!0);return}r(!1);return}if(!C(N[z])){r(!1);return}}r(!1)},[]),y=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),S=a.useCallback(async N=>{if(!N.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const M=await $y(N,s,n);m(M.files),f(0)}catch(M){M.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{S(o)},ET),()=>{x.current&&clearTimeout(x.current)}},[o,i,S]);const k=a.useCallback((N,M)=>{if(!i||c<0)return M;const C=M.slice(0,c),z=M.slice(c+1),A=z.match(/[\s]|$/),P=A?A.index:z.length,F=z.slice(P);return`${C}#${N.path}${F}`},[i,c]),R=a.useCallback((N,M)=>{if(!i||d.length===0)return!1;switch(N.key){case"ArrowDown":return N.preventDefault(),f(C=>Math.min(C+1,d.length-1)),!0;case"ArrowUp":return N.preventDefault(),f(C=>Math.max(C-1,0)),!0;case"Enter":case"Tab":return d[p]?(N.preventDefault(),!0):!1;case"Escape":return N.preventDefault(),y(),!0;default:return!1}},[i,d,p,y]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:b,selectFile:k,dismissMention:y,handleKeyDown:R}}function MT(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let lc=null;function AT(){return lc===null&&(lc=window.innerHeight),lc}function RT(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const i=AT()-e.offsetTop-e.height;return i>=30&&i>80?i:0}function TT({enabled:e=!0}={}){const[n,s]=a.useState(0),[i,r]=a.useState(null);return a.useEffect(()=>{if(!e||!MT()){s(0),r(null);return}const o=window.visualViewport;if(!o){s(0),r(null);return}const l=()=>{const c=RT();s(c),r(c>0?o.height:null)};return l(),o.addEventListener("resize",l),o.addEventListener("scroll",l),()=>{o.removeEventListener("resize",l),o.removeEventListener("scroll",l),s(0),r(null)}},[e]),{keyboardOverlap:n,viewportHeight:i}}function PT(e){return`${e.name?.trim()||e.id} (${e.role})`}function IT(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 $T(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 oo(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function DT(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,i])=>{let r="";if(typeof i=="string")r=i;else try{r=JSON.stringify(i)}catch{r=String(i)}return`${s}=${oo(r,50)}`}).join(", ")}function LT(e){if(e===void 0)return null;if(typeof e=="string")return oo(e,200);try{return oo(JSON.stringify(e),200)}catch{return oo(String(e),200)}}function Nh(e,n=!1){return!e||e.length===0?null:t.jsxs("div",{className:`chat-tool-calls${n?" chat-tool-calls--compact":""}`,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Xb,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),e.map((s,i)=>{const r=s.status==="running",o=s.status==="completed"&&s.isError,l=DT(s.args),c=LT(s.result),u=r?l:c?`result: ${c}`:l?`args: ${l}`:null,d=r?"running":o?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${r?" chat-tool-call--running":""}${o?" chat-tool-call--error":""}`,open:r,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",children:s.toolName}),u&&t.jsx("span",{className:"chat-tool-call-preview",title:u,children:u}),t.jsx("span",{className:"chat-tool-call-status-text",children:d})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[l&&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:l})]}),c&&t.jsxs("div",{className:`chat-tool-call-row${o?" 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:c})]})]})]},`${s.toolName}-${i}`)})]})}const zT={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 FT(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 io={width:320,height:400},ia={width:280,height:260},Kc=768,aa=8;function OT(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const x=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return x&&parseFloat(x)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const x=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(x);if(v){const b=JSON.parse(v);if(typeof b.x=="number"&&typeof b.y=="number"&&!isNaN(b.x)&&!isNaN(b.y))return b}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(x=>{if(typeof window>"u")return x;const v=48,b=window.innerWidth<=768?4:8,y=window.innerWidth<=768?44:0,S=window.innerWidth>768?s():0,k=window.innerWidth-v-b,R=window.innerHeight-v-b-y-S;return{x:Math.max(b,Math.min(k,x.x)),y:Math.max(b,Math.min(R,x.y))}},[s]),h=a.useCallback(x=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(x))}catch{}},[e]),g=a.useCallback(x=>{if(x.button!==0&&x.pointerType==="mouse")return;const b=x.target.closest(".quick-chat-fab");b&&(x.preventDefault(),typeof b.setPointerCapture=="function"&&b.setPointerCapture(x.pointerId),u.current={x:r.x,y:r.y,pointerX:x.clientX,pointerY:x.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(x=>{if(!u.current||!l)return;const v=x.clientX-u.current.pointerX,b=x.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(b)>=5)&&(d.current=!0),d.current){const y=u.current.x-v,S=u.current.y-b,k=m({x:y,y:S});o(k)}},[l,m]),f=a.useCallback(x=>{if(!u.current)return;const v=x.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(x.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function UT(e,n,s){const i=`fusion:quick-chat-size-${e||"default"}`,r=a.useCallback(()=>typeof window<"u"&&window.innerWidth>Kc,[]),o=a.useCallback((g,p,f)=>{if(typeof window>"u")return g;const x=Math.max(ia.width,window.innerWidth-p-aa),v=Math.max(ia.height,window.innerHeight-f-aa);return{width:Math.max(ia.width,Math.min(x,g.width)),height:Math.max(ia.height,Math.min(v,g.height))}},[]),l=a.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Kc)return io;try{const g=localStorage.getItem(i);if(!g)return io;const p=JSON.parse(g);return typeof p.width!="number"||typeof p.height!="number"?io:{width:p.width,height:p.height}}catch{return io}},[i]),[c,u]=a.useState(l),[d,m]=a.useState({right:0,bottom:0});a.useEffect(()=>{if(!r())return;const g={right:n+d.right,bottom:s+d.bottom};u(p=>o(p,g.right,g.bottom))},[o,r,n,s,d]),a.useEffect(()=>{if(r())try{localStorage.setItem(i,JSON.stringify(c))}catch{}},[r,c,i]);const h=a.useCallback(g=>{if(!r())return;const p=g.currentTarget.dataset.resizeDirection;if(!p)return;g.preventDefault(),g.stopPropagation();const f=g.currentTarget;typeof f.setPointerCapture=="function"&&f.setPointerCapture(g.pointerId);const x={pointerX:g.clientX,pointerY:g.clientY,width:c.width,height:c.height,anchorRight:d.right,anchorBottom:d.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-x.pointerX,k=y.clientY-x.pointerY;let R=x.width,N=x.height,M=x.anchorRight,C=x.anchorBottom;if(p.includes("w")&&(R=x.width-S),p.includes("e")){const $=S;R=x.width+$,M=x.anchorRight-$}if(p.includes("n")&&(N=x.height-k),p.includes("s")){const $=k;N=x.height+$,C=x.anchorBottom-$}const z=n+M,A=s+C,P=o({width:R,height:N},z,A),F=Math.max(aa-n,Math.min(window.innerWidth-n-ia.width-aa,M)),W=Math.max(aa-s,Math.min(window.innerHeight-s-ia.height-aa,C));u(P),m({right:F,bottom:W})},b=y=>{typeof f.releasePointerCapture=="function"&&f.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(i,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[d.bottom,d.right,o,s,n,r,c.height,c.width,i]);return{panelSize:c,anchorOffset:d,handleResizeStart:h}}function BT({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=ST(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?te=>{r?.(typeof te=="function"?te(p):te)}:h,{keyboardOverlap:x,viewportHeight:v}=TT({enabled:p}),b=x>0?{"--keyboard-overlap":`${x}px`,...v!==null?{"--vv-height":`${v}px`}:{}}:{},[y,S]=a.useState("agent"),[k,R]=a.useState(""),[N,M]=a.useState([]),[C,z]=a.useState(!1),[A,P]=a.useState(""),[F,W]=a.useState(""),[$,_]=a.useState(""),[I,O]=a.useState(!1),[J,Q]=a.useState(0),[E,D]=a.useState(-1),[T,w]=a.useState(()=>new Set),[,q]=a.useState(!1),[G,me]=a.useState({top:0,left:0}),ce=_T({projectId:e}),ae=a.useCallback(te=>{if(!te||!ce.mentionActive)return;const j=te.getBoundingClientRect();me({top:j.top-260,left:j.left+8})},[ce.mentionActive]),pe=a.useRef(!1),U=a.useRef(!1),Ne=a.useRef(""),ne=a.useRef(0),xe=a.useRef(null),{position:le,isDragging:ve,handlePointerDown:ee,handlePointerMove:Ee,handlePointerUp:Fe}=OT(e,pe),Ke=le.y+60,{panelSize:Ze,anchorOffset:Xe,handleResizeStart:Qe}=UT(e,le.x,Ke),it=typeof window<"u"&&window.innerWidth>Kc,{activeSession:Ie,messages:Ge,isStreaming:se,streamingText:ye,streamingThinking:Z,streamingToolCalls:Te,sessionsLoading:ze,messagesLoading:be,sendMessage:Me,stopStreaming:Be,pendingMessage:lt,clearPendingMessage:je,switchSession:ie,startModelChat:Ae,startFreshSession:he}=NT(e,n),Re=a.useRef(null),Je=a.useRef(null),$e=a.useRef(null),de=a.useRef(null),re=a.useMemo(()=>IT(A),[A]),ue=a.useMemo(()=>N.find(te=>`${te.provider}/${te.id}`===A)??null,[N,A]),Pe=a.useMemo(()=>$T(ue,re),[ue,re]),Se=a.useMemo(()=>y==="model"?re?`${Sd}::${re.modelProvider}/${re.modelId}`:"":k?`${k}::`:"",[y,re,k]),fe=y==="agent"?!!k:!!re;a.useEffect(()=>{if(d.length===0){R(""),S("model");return}d.some(j=>j.id===k)||R(d[0]?.id??"")},[d,k]),a.useEffect(()=>{!p||U.current||(U.current=!0,z(!0),cs().then(te=>{const j=te.models??[];if(M(j),A||j.length===0)return;const V=te.defaultProvider,De=te.defaultModelId;if(V&&De){const nt=`${V}/${De}`;if(j.some(Pt=>`${Pt.provider}/${Pt.id}`===nt)){P(nt),S("model");return}}if(d.length===0){const nt=j[0];nt&&P(`${nt.provider}/${nt.id}`)}}).catch(te=>{console.error("[QuickChatFAB] Failed to load models:",te),M([])}).finally(()=>{z(!1)}))},[p,d.length,A]),a.useEffect(()=>{if(!p){Ne.current="";return}if(!Se){Ne.current="";return}const te=Se===Ne.current&&!Ie&&!ze;if(!(Se===Ne.current&&!te)){if(Ne.current=Se,y==="model"&&re){Ae(re.modelProvider,re.modelId);return}y==="agent"&&k&&ie(k)}},[p,y,re,k,Se,Ie,ze,Ae,ie]),a.useEffect(()=>{p||(O(!1),_(""),D(-1))},[p]);const tt=a.useCallback(te=>{R(te)},[]),ut=a.useCallback(te=>{P(te)},[]),vt=a.useCallback(()=>{!fe||ze||he()},[fe,ze,he]),gt=a.useMemo(()=>d.find(te=>te.id===k)??null,[d,k]),dt=a.useMemo(()=>{const te=$.trim().toLowerCase();return te?d.filter(j=>j.name.toLowerCase().includes(te)):d},[d,$]),wt=a.useMemo(()=>{const te=new Map;for(const j of d)te.set(j.name.toLowerCase(),j);return te},[d]);a.useEffect(()=>{Q(0)},[$,I]),a.useEffect(()=>()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),a.useEffect(()=>{if(!p)return;const te=V=>{const De=V.target;Re.current?.contains(De)||Je.current?.contains(De)||De.closest(".model-combobox-dropdown--portal")||f(!1)},j=V=>{V.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",te),document.addEventListener("keydown",j),()=>{document.removeEventListener("mousedown",te),document.removeEventListener("keydown",j)}},[p,f]),a.useEffect(()=>{if(!p)return;const te=$e.current;te&&(te.scrollTop=te.scrollHeight)},[Ge,ye,Z,p]);const Mt=a.useMemo(()=>y==="agent"?gt?`Message ${gt.name||gt.id}`:"Select an agent to start chatting":Pe?`Message ${Pe}`:"Select a model to start chatting",[y,gt,Pe]),yt=!fe||!Ie,Et=lt.length>50?`${lt.slice(0,50)}…`:lt,Nt=a.useCallback(()=>{const te=F.trim();!te||yt||(W(""),O(!1),_(""),D(-1),Me(te))},[Me,yt,F]),Tt=a.useCallback((te,j)=>{const V=FT(te,j);if(V){O(!0),_(V.filter),D(V.start);return}O(!1),_(""),D(-1)},[]),Ht=a.useCallback(te=>{const j=de.current;if(!j||E<0)return;const V=j.selectionStart??ne.current,De=j.selectionEnd??V,nt=Math.max(V,De),St=Math.min(E,nt),Rt=`${`@${te.name.replace(/\s+/g,"_")}`} `,un=F.slice(0,St)+Rt+F.slice(nt),mn=St+Rt.length;W(un),O(!1),_(""),Q(0),D(-1),window.requestAnimationFrame(()=>{de.current&&(de.current.focus(),de.current.setSelectionRange(mn,mn))})},[E,F]),Ut=a.useCallback(te=>{const j=te.target.value,V=te.target.selectionStart??j.length;ne.current=V,W(j),Tt(j,V),ce.detectMention(j,V),q(ce.mentionActive),ce.mentionActive&&ae(te.target)},[Tt,ce,ae]),Vt=a.useCallback(()=>{xe.current!==null&&window.clearTimeout(xe.current),xe.current=window.setTimeout(()=>{O(!1),_(""),D(-1),q(!1),ce.dismissMention(),xe.current=null},120)},[ce]),zt=a.useCallback(()=>{xe.current!==null&&(window.clearTimeout(xe.current),xe.current=null)},[]),Ct=a.useCallback(te=>{const j=te.currentTarget,V=j.selectionStart??j.value.length;ne.current=V,Tt(j.value,V),ce.detectMention(j.value,V),q(ce.mentionActive),ce.mentionActive&&ae(j)},[Tt,ce,ae]),At=a.useCallback(te=>{te.key!=="Escape"&&Ct(te)},[Ct]),kt=a.useCallback(te=>{const j=/@([\w-]+)/g,V=[];let De=0,nt=j.exec(te);for(;nt;){const[St,Pt=""]=nt,Rt=nt.index;Rt>De&&V.push(te.slice(De,Rt));const un=Pt.replace(/_/g," ").toLowerCase(),mn=wt.get(un);mn?V.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",mn.name.replace(/\s+/g,"_")]},`${mn.id}-${Rt}`)):V.push(St),De=Rt+St.length,nt=j.exec(te)}return De<te.length&&V.push(te.slice(De)),V.length===0?te:V},[wt]),Kt=a.useCallback(te=>{w(j=>{const V=new Set(j);return V.has(te)?V.delete(te):V.add(te),V})},[]),$t=a.useCallback((te,j=!1)=>j?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:te}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(ci,{remarkPlugins:[di],components:zT,children:te})}),[]),B=a.useCallback(te=>{if(ne.current=te.currentTarget.selectionStart??ne.current,ce.mentionActive&&ce.files.length>0){if(ce.handleKeyDown(te,F),te.key==="Enter"||te.key==="Tab"){const j=ce.files[ce.selectedIndex];if(j){const V=ce.selectFile(j,F);W(V),ce.dismissMention(),q(!1)}}return}if(I&&te.key==="ArrowDown"){te.preventDefault(),dt.length>0&&Q(j=>(j+1)%dt.length);return}if(I&&te.key==="ArrowUp"){te.preventDefault(),dt.length>0&&Q(j=>j===0?dt.length-1:j-1);return}if(I&&te.key==="Enter"){te.preventDefault();const j=dt[J]??dt[0];j&&Ht(j);return}if(I&&te.key==="Escape"){te.preventDefault(),te.stopPropagation(),O(!1),_(""),D(-1);return}te.key!=="Enter"||te.shiftKey||(te.preventDefault(),Nt())},[I,dt,J,Ht,Nt,ce,F]),ge=a.useCallback(()=>{if(pe.current){pe.current=!1;return}f(te=>!te)},[f]);return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Je,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":ve?"true":"false",style:{right:le.x,bottom:le.y},onPointerDown:ee,onPointerMove:Ee,onPointerUp:Fe,onClick:ge,children:t.jsx(bi,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:Re,"data-testid":"quick-chat-panel",style:{right:le.x+Xe.right,bottom:Ke+Xe.bottom,...it?{width:Ze.width,height:Ze.height}:{},...b},children:[it&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:Qe,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:Qe,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:Qe,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:Qe,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:Qe,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:Qe,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:Qe,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:Qe,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),Pe&&t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Pe,children:Pe})]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","data-testid":"quick-chat-new-thread",onClick:vt,disabled:!fe||ze,children:"New chat"}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>f(!1),children:t.jsx(Ot,{size:16})})]})]}),d.length>0&&t.jsxs("div",{className:"quick-chat-mode-toggle","data-testid":"quick-chat-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{S("agent"),P("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${y==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{S("model"),R("")},children:"Model"})]}),y==="agent"&&d.length>0&&t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-agent-select",className:"visually-hidden",children:"Select agent"}),t.jsx("select",{id:"quick-chat-agent-select",value:k,onChange:te=>tt(te.target.value),"data-testid":"quick-chat-agent-select",children:d.map(te=>t.jsx("option",{value:te.id,children:PT(te)},te.id))})]}),y==="model"&&t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-model-select",children:[t.jsx("label",{htmlFor:"quick-chat-model-override",className:"visually-hidden",children:"Select model override"}),t.jsx($n,{id:"quick-chat-model-override",models:N,value:A,onChange:ut,label:"Select model override",placeholder:C?"Loading models…":"Select a model",disabled:C||N.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:$e,"data-testid":"quick-chat-messages",children:ze||be?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):Ge.length===0&&!ye&&!Z&&!se?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[Ge.map(te=>{const j=te.role==="user",V=!j&&T.has(te.id);return t.jsxs("div",{className:`quick-chat-panel-message ${j?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${te.id}`,children:[j?t.jsx("p",{children:kt(te.content)}):t.jsxs(t.Fragment,{children:[$t(te.content,V),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${V?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":V?"Show rendered markdown":"Show plain text",onClick:()=>Kt(te.id),children:V?t.jsx(pc,{size:14}):t.jsx(da,{size:14})})]}),Nh(te.toolCalls,!0)]},te.id)}),se&&t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[ye?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:$t(ye,T.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${T.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":T.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Kt("__streaming__"),children:T.has("__streaming__")?t.jsx(pc,{size:14}):t.jsx(da,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:"Thinking…"}),Nh(Te,!0),Z&&t.jsxs("details",{className:"chat-message-thinking","data-testid":"quick-chat-streaming-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:Z})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:de,type:"text",value:F,onChange:Ut,onKeyDown:B,onKeyUp:At,onClick:Ct,onBlur:Vt,onFocus:zt,placeholder:Mt,disabled:yt,"data-testid":"quick-chat-input"}),t.jsx(jT,{agents:d,filter:$,highlightedIndex:J,visible:I,onSelect:Ht,position:"above"}),t.jsx(CT,{visible:ce.mentionActive&&!I,position:G,files:ce.files,selectedIndex:ce.selectedIndex,onSelect:te=>{const j=ce.selectFile(te,F);W(j),ce.dismissMention(),q(!1),de.current?.focus()},loading:ce.loading}),lt&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Et}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:je,children:"×"})]})]}),se?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:Be,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ms,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void Nt(),disabled:yt||F.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(Di,{size:16})})]})]})]})}function Ya(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Sh(e){return e.status==="generating"||e.status==="awaiting_input"}function Qa(e){return e==="complete"||e==="error"}function HT(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=Sa(),d=a.useCallback(()=>{Zc(e).then(p=>{const f=p.filter(v=>{const b=Ya(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),x=new Map;for(const v of f)x.set(v.id,Ya(v.updatedAt));i.current=x,s(f)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);a.useEffect(()=>{u(),d()},[d,u]),a.useEffect(()=>{s(p=>{if(o.size===0)return p;let f=!1;const x=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=i.current.get(v.sessionId)??0;if(b<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!Qa(v.status)&&r.current.delete(v.sessionId),Qa(v.status)){x.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,b);continue}const k=x.get(v.sessionId),R=v.type??k?.type,N=v.title??k?.title;if(!k&&(!R||!N))continue;const M={id:v.sessionId,type:R??"planning",status:v.status,title:N??"AI Session",projectId:v.projectId??k?.projectId??e??null,lockedByTab:v.owningTabId??k?.lockedByTab??null,updatedAt:v.updatedAt??k?.updatedAt??new Date(b).toISOString()},C=x.get(v.sessionId);(!C||C.status!==M.status||C.title!==M.title||C.type!==M.type||C.projectId!==M.projectId||C.lockedByTab!==M.lockedByTab||C.updatedAt!==M.updatedAt)&&(x.set(v.sessionId,M),i.current.set(v.sessionId,b),f=!0)}return f?[...x.values()].sort((v,b)=>Ya(b.updatedAt)-Ya(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const b=JSON.parse(v.data),y=Ya(b.updatedAt)||Date.now();s(S=>{const k=i.current.get(b.id)??0;if(y<k)return S;const R=r.current.get(b.id);if(R!==void 0&&y<=R)return S;if(R!==void 0&&y>R&&!Qa(b.status)&&r.current.delete(b.id),i.current.set(b.id,y),Qa(b.status))return S.filter(M=>M.id!==b.id);const N=S.findIndex(M=>M.id===b.id);if(N>=0){const M=[...S];return M[N]=b,M}return Sh(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),Qa(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},x=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),i.current.set(b,Math.max(i.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(k=>k.id!==b))}catch{}};return Ls(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":x},onReconnect:()=>{d()}})},[c,l,e,d]);const m=a.useCallback(async p=>{const x=n.find(S=>S.id===p)?.type,v=Wi();let b=!1;if(x==="planning")try{await np(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(x==="subtask")try{await ap(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(x==="mission_interview")try{await dp(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),i.current.set(p,Math.max(i.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await up(p)}catch{}s(S=>S.filter(k=>k.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Sh(p)),[n]),g=a.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:g,dismissSession:m,refresh:d}}function Bn(e){return{...e,dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Ch(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function qT(e){const n=e?.projectId,s=e?.searchQuery,i=e?.sseEnabled??!0,[r,o]=a.useState([]),[l,c]=a.useState(!1),u=a.useRef(l);u.current=l;const d=a.useRef(r),m=a.useRef(0),h=a.useRef(0),g=a.useRef(s),p=a.useRef(null),f=a.useRef(void 0),x=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,x.current++);const b=1e3,y=a.useCallback(async _=>{const I=++m.current,O=n,J=_?.searchQueryOverride??s,Q=_?.includeArchivedOverride??u.current;try{const E=await wv(void 0,void 0,O,J,Q);if(m.current!==I||n!==O)return;o(E.map(Bn)),f.current=Date.now()}catch{if(m.current!==I||n!==O)return;if(_?.clearOnError){o([]);return}o(E=>E)}},[n,s]);p.current=y;const S=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const _=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(_)},[s]),a.useEffect(()=>{y({clearOnError:!0});const _=()=>{if(document.visibilityState!=="visible")return;const I=Date.now();I-h.current<b||(h.current=I,y())};return document.addEventListener("visibilitychange",_),()=>{document.removeEventListener("visibilitychange",_)}},[y]),a.useEffect(()=>{if(i===!1)return;const _=x.current,I=n?`?projectId=${encodeURIComponent(n)}`:"",O=()=>x.current!==_;let J=!0;const Q=G=>{if(O())return;const me=Bn(JSON.parse(G.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(ce=>ce.some(ae=>ae.id===me.id)?ce:[...ce,me])},E=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:me,to:ce}=JSON.parse(G.data),ae=Bn(me);o(pe=>pe.map(U=>U.id===ae.id?{...ae,column:ce}:U)),f.current=Date.now()},D=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const me=Bn(JSON.parse(G.data));o(ce=>ce.map(ae=>{if(ae.id!==me.id||Ch(me.updatedAt,ae.updatedAt)<0)return ae;if(ae.column===me.column)return me;const U=Ch(ae.columnMovedAt,me.columnMovedAt);return ae.columnMovedAt&&!me.columnMovedAt?{...me,column:ae.column,columnMovedAt:ae.columnMovedAt}:U>0?{...me,column:ae.column,columnMovedAt:ae.columnMovedAt}:me})),f.current=Date.now()},T=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const me=Bn(JSON.parse(G.data));o(ce=>ce.filter(ae=>ae.id!==me.id))},w=G=>{if(O())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:me}=JSON.parse(G.data),ce=Bn(me);o(ae=>ae.map(pe=>pe.id===ce.id?{...ce,column:"done"}:pe))},q=Ls(`/api/events${I}`,{events:{"task:created":Q,"task:moved":E,"task:updated":D,"task:deleted":T,"task:merged":w},onReconnect:()=>{J&&(O()||p.current())}});return()=>{J=!1,q()}},[n,i]);const k=a.useCallback(async _=>{const I=Bn(await Xh(_,n));return o(O=>O.some(J=>J.id===I.id)?O:[...O,I]),I},[n]),R=a.useCallback(async(_,I)=>Bn(await Sv(_,I,n)),[n]),N=a.useCallback(async _=>Bn(await Zh(_,n)),[n]),M=a.useCallback(async _=>Bn(await Cv(_,n)),[n]),C=a.useCallback(async _=>Ev(_,n),[n]),z=a.useCallback(async _=>Bn(await _v(_,n)),[n]),A=a.useCallback(async _=>{const I=Bn(await Mv(_,n));return o(O=>O.some(J=>J.id===I.id)?O:[...O,I]),I},[n]),P=a.useCallback(async(_,I)=>{const O=d.current.find(Q=>Q.id===_),J=O?{...O,...I,updatedAt:new Date().toISOString()}:void 0;J&&o(Q=>Q.map(E=>E.id===_?J:E));try{const Q=Bn(await Ks(_,I,n));return o(E=>E.map(D=>D.id===_?Q:D)),Q}catch(Q){throw O&&o(E=>E.map(D=>D.id===_?O:D)),Q}},[n]),F=a.useCallback(async _=>{const I=Bn(await Rv(_,n));return o(O=>O.map(J=>J.id===_?I:J)),I},[n]),W=a.useCallback(async _=>{const I=Bn(await Tv(_,n));return o(O=>O.map(J=>J.id===_?I:J)),I},[n]),$=a.useCallback(async()=>{const I=(await Pv(n)).map(Bn);return o(O=>O.map(J=>I.find(E=>E.id===J.id)||J)),I},[n]);return{tasks:r,createTask:k,moveTask:R,pauseTask:N,deleteTask:M,mergeTask:C,retryTask:z,duplicateTask:A,updateTask:P,archiveTask:F,unarchiveTask:W,archiveAllDone:$,loadArchivedTasks:S,includeArchived:l,lastFetchTimeMs:f.current}}const VT=5e3,WT=1e3;function KT(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const g=await Kd();n(g)}catch(g){o(g instanceof Error?g.message:"Failed to fetch projects")}},[]);a.useEffect(()=>{let g=!1;async function p(){i(!0);const x=performance.now();try{const v=await Kd(),y=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-x)}ms (${v.length} projects)`;console.log(`[useProjects] ${y}`),ir("[useProjects]",y),g||(n(v),o(null))}catch(v){const y=`initial fetch failed after ${Math.round(performance.now()-x)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${y}`),ir("[useProjects]",y),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const x=Date.now();x-c.current<WT||(c.current=x,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},VT),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Tk(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await zk(g,p);return n(x=>x.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await op(g),n(p=>p.filter(f=>f.id!==g))},[]);return{projects:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h}}const GT="kb-dashboard-current-project";function JT(e){return e??"local"}function YT(e,n={}){const{nodeId:s=null}=n,[i,r]=a.useState(null),[o,l]=a.useState(!0),c=a.useRef(!1),u=a.useRef(!1),d=a.useRef(null),m=JT(s);a.useEffect(()=>{let p=!1;async function f(){try{const x=await Vi();if(p)return;d.current=x.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(GT);if(b){const y=JSON.parse(b);y?.id&&e.some(k=>k.id===y.id)&&(r(y),c.current=!0,d.current={...d.current,[m]:y.id},await sn({dashboardCurrentProjectIdByNode:d.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return f(),()=>{p=!0}},[m,e]),a.useEffect(()=>{if(!o){if(i){if(!e.some(x=>x.id===i.id)&&e.length>0){const x=e.find(v=>v.status==="active");r(x||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,sn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}else if(e.length>0&&!u.current){const p=e.find(f=>f.status==="active");p&&r(p)}}},[i,e,o,m]);const h=a.useCallback(p=>{if(u.current=!1,r(p),p){const f={...d.current,[m]:p.id};d.current=f,sn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,sn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const og=a.createContext(null);function QT({children:e}){const[n,s]=a.useState([]),i=a.useRef(0),r=a.useRef(new Map),o=a.useCallback(c=>{const u=r.current.get(c);u!==void 0&&(clearTimeout(u),r.current.delete(c)),s(d=>d.filter(m=>m.id!==c))},[]),l=a.useCallback((c,u="info")=>{const d=i.current++;s(h=>[...h,{id:d,message:c,type:u}]);const m=setTimeout(()=>o(d),4e3);r.current.set(d,m)},[o]);return a.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),lo.createElement(og.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function XT(){const e=a.useContext(og);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const lg="kb-dashboard-theme-mode",cg="kb-dashboard-color-theme",dg=[...dw],Gc="theme-data",cc="theme-data.css";function ZT(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${cc}`:e.replace(/\/[^/]+$/,`/${cc}`):`/${cc}`}const Ss=typeof window<"u",eP=Ss?a.useLayoutEffect:a.useEffect;function ug(e){return e==="dark"||e==="light"||e==="system"}function Eh(){if(!Ss)return"dark";try{const e=localStorage.getItem(lg);if(ug(e))return e}catch{}return"dark"}function _h(){if(!Ss)return"default";try{const e=localStorage.getItem(cg);if(e&&dg.includes(e))return e}catch{}return"default"}function Mh(e){if(Ss)try{localStorage.setItem(lg,e)}catch{}}function Ah(e){if(Ss)try{localStorage.setItem(cg,e)}catch{}}function tP(e,n){return e==="system"?n?"dark":"light":e}function nP(e,n,s){if(!Ss)return;const i=tP(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Rh(){if(!Ss)return;const e=ZT(),n=document.getElementById(Gc);if(n){n.href!==e&&(n.href=e),n.parentNode===document.head&&document.head.lastChild!==n&&document.head.appendChild(n);return}const s=document.createElement("link");s.rel="stylesheet",s.href=e,s.id=Gc,document.head.appendChild(s)}function Th(){if(!Ss)return;const e=document.getElementById(Gc);e&&e.remove()}function sP(){const[e,n]=a.useState(()=>Eh()),[s,i]=a.useState(()=>_h()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ss?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),u=a.useRef(e),d=a.useRef(s),m=a.useRef(!1),h=a.useRef(!1);a.useEffect(()=>{u.current=e},[e]),a.useEffect(()=>{d.current=s},[s]),a.useEffect(()=>{if(!Ss||!r)return;let f=!1;return Vi().then(x=>{f||(ug(x.themeMode)&&!m.current&&(u.current!==x.themeMode&&(u.current=x.themeMode,n(x.themeMode)),Eh()!==x.themeMode&&Mh(x.themeMode)),x.colorTheme&&dg.includes(x.colorTheme)&&!h.current&&(d.current!==x.colorTheme&&(d.current=x.colorTheme,i(x.colorTheme)),_h()!==x.colorTheme&&Ah(x.colorTheme)))}).catch(x=>{console.warn("[useTheme] Failed to hydrate theme from global settings",x)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Ss)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),x=v=>{c(v.matches)};return f.addEventListener("change",x),()=>f.removeEventListener("change",x)},[]),eP(()=>{nP(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ss||r||(s!=="default"?Rh():Th())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Mh(f),sn({themeMode:f}).catch(x=>{console.warn("[useTheme] Failed to persist themeMode to global settings",x)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),Ah(f),f!=="default"?Rh():Th(),sn({colorTheme:f}).catch(x=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",x)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function iP(e){const{planningSessions:n}=e,[s,i]=a.useState(!1),[r,o]=a.useState(!1),[l,c]=a.useState(null),[u,d]=a.useState(void 0),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,x]=a.useState(void 0),[v,b]=a.useState(null),[y,S]=a.useState("definition"),[k,R]=a.useState(!1),[N,M]=a.useState(void 0),[C,z]=a.useState(!1),[A,P]=a.useState(!1),[F,W]=a.useState(!1),[$,_]=a.useState(null),[I,O]=a.useState(!1),[J,Q]=a.useState(!1),[E,D]=a.useState(void 0),[T,w]=a.useState(!1),[q,G]=a.useState("project"),[me,ce]=a.useState(!1),[ae,pe]=a.useState(!1),[U,Ne]=a.useState(!1),[ne,xe]=a.useState(!1),[le,ve]=a.useState(!1),[ee,Ee]=a.useState(!1),[Fe,Ke]=a.useState(!1),Ze=!!(v||k||s||r||m||J||T||me||ae||U||le||ne||F||I||C||A||ee||Fe),Xe=a.useCallback(()=>i(!0),[]),Qe=a.useCallback(()=>i(!1),[]),it=a.useCallback(()=>o(!0),[]),Ie=a.useCallback(B=>{c(B),o(!0)},[]),Ge=a.useCallback(()=>{const B=n[0];B&&(d(B.id),o(!0))},[n]),se=a.useCallback(B=>{d(B),o(!0)},[]),ye=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),Z=a.useCallback(B=>{p(B),h(!0)},[]),Te=a.useCallback(B=>{x(B),h(!0)},[]),ze=a.useCallback(()=>{h(!1),p(null),x(void 0)},[]),be=a.useCallback((B,ge="definition")=>{b(B),S(ge)},[]),Me=a.useCallback(B=>{b(B),S("changes")},[]),Be=a.useCallback(B=>{b(ge=>ge&&{...ge,...B})},[]),lt=a.useCallback(()=>{b(null)},[]),je=a.useCallback(B=>{M(B),R(!0)},[]),ie=a.useCallback(()=>{R(!1),M(void 0)},[]),Ae=a.useCallback(()=>z(!0),[]),he=a.useCallback(()=>z(!1),[]),Re=a.useCallback(()=>P(!0),[]),Je=a.useCallback(()=>P(!1),[]),$e=a.useCallback(B=>{_(B??null),W(!0)},[]),de=a.useCallback(()=>{W(!1),_(null)},[]),re=a.useCallback(()=>O(!0),[]),ue=a.useCallback(()=>O(!1),[]),Pe=a.useCallback(()=>{Q(B=>!B)},[]),Se=a.useCallback(()=>{Q(!1),D(void 0)},[]),fe=a.useCallback(()=>w(!0),[]),tt=a.useCallback(()=>w(!1),[]),ut=a.useCallback(B=>{G(B)},[]),vt=a.useCallback(()=>ce(!0),[]),gt=a.useCallback(()=>ce(!1),[]),dt=a.useCallback(()=>pe(!0),[]),wt=a.useCallback(()=>pe(!1),[]),Mt=a.useCallback(()=>Ne(!0),[]),yt=a.useCallback(()=>Ne(!1),[]),Et=a.useCallback(()=>xe(!0),[]),Nt=a.useCallback(()=>xe(!1),[]),Tt=a.useCallback(()=>ve(!0),[]),Ht=a.useCallback(()=>ve(!1),[]),Ut=a.useCallback(async(B,ge)=>{ve(!1),D(ge),Q(!0)},[]),Vt=a.useCallback(()=>Ee(!0),[]),zt=a.useCallback(()=>Ee(!1),[]),Ct=a.useCallback(()=>Ke(!0),[]),At=a.useCallback(()=>Ke(!1),[]),kt=a.useCallback((B,ge)=>{ge(`Created ${B.id} from planning mode`,"success"),o(!1),c(null)},[]),Kt=a.useCallback((B,ge)=>{const te=B.map(j=>j.id).join(", ");ge(`Created ${te} from planning mode`,"success"),o(!1),c(null)},[]),$t=a.useCallback((B,ge)=>{const te=B.map(j=>j.id).join(", ");ge(`Created ${te} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:u,isSubtaskOpen:m,subtaskInitialDescription:g,subtaskResumeSessionId:f,detailTask:v,detailTaskInitialTab:y,settingsOpen:k,settingsInitialSection:N,schedulesOpen:C,githubImportOpen:A,usageOpen:F,usageAnchorRect:$,systemStatsOpen:I,terminalOpen:J,terminalInitialCommand:E,filesOpen:T,fileBrowserWorkspace:q,activityLogOpen:me,gitManagerOpen:ae,workflowStepsOpen:U,agentsOpen:ne,scriptsOpen:le,setupWizardOpen:ee,modelOnboardingOpen:Fe,anyModalOpen:Ze,openNewTask:Xe,closeNewTask:Qe,openPlanning:it,openPlanningWithInitialPlan:Ie,resumePlanning:Ge,openPlanningWithSession:se,closePlanning:ye,openSubtaskBreakdown:Z,openSubtaskWithSession:Te,closeSubtask:ze,openDetailTask:be,openDetailWithChangesTab:Me,updateDetailTask:Be,closeDetailTask:lt,openSettings:je,closeSettings:ie,openSchedules:Ae,closeSchedules:he,openGitHubImport:Re,closeGitHubImport:Je,openUsage:$e,closeUsage:de,openSystemStats:re,closeSystemStats:ue,toggleTerminal:Pe,closeTerminal:Se,openFiles:fe,closeFiles:tt,setFileWorkspace:ut,openActivityLog:vt,closeActivityLog:gt,openGitManager:dt,closeGitManager:wt,openWorkflowSteps:Mt,closeWorkflowSteps:yt,openAgents:Et,closeAgents:Nt,openScripts:Tt,closeScripts:Ht,runScript:Ut,openSetupWizard:Vt,closeSetupWizard:zt,openModelOnboarding:Ct,closeModelOnboarding:At,onPlanningTaskCreated:kt,onPlanningTasksCreated:Kt,onSubtaskTasksCreated:$t}}function aP(e){const[n,s]=a.useState(2),[i,r]=a.useState("."),[o,l]=a.useState(!0),[c,u]=a.useState(!1),[d,m]=a.useState(!1),[h,g]=a.useState(void 0),[p,f]=a.useState(!1),[x,v]=a.useState(!1),[b,y]=a.useState({}),[S,k]=a.useState(!1),[R,N]=a.useState(!1),[M,C]=a.useState(!1),[z,A]=a.useState(!1),[P,F]=a.useState(!1),W=a.useCallback(async()=>{const[J,Q]=await Promise.allSettled([Dv(e),Lo(e)]);if(J.status==="fulfilled"&&(s(J.value.maxConcurrent),r(J.value.rootDir)),Q.status==="fulfilled"){const E=Q.value;l(!!E.autoMerge),u(!!E.globalPause),m(!!E.enginePaused),v(!!E.prAuthAvailable),g(E.taskStuckTimeoutMs),f(E.showQuickChatFAB===!0),y(E.experimentalFeatures??{});const D=E.experimentalFeatures??{};k(D.insights===!0),N(D.roadmap===!0),C(D.memoryView===!0),A(D.devServerView===!0||D.devServer===!0),F(D.todoView===!0)}},[e]);a.useEffect(()=>{W()},[W]);const $=a.useCallback(async()=>{const J=!o;l(J);try{await zr({autoMerge:J},e)}catch{l(!J)}},[o,e]),_=a.useCallback(async()=>{const J=!c;u(J);try{await zr({globalPause:J,globalPauseReason:J?"manual":void 0},e)}catch{u(!J)}},[c,e]),I=a.useCallback(async()=>{const J=!d;m(J);try{await zr({enginePaused:J},e)}catch{m(!J)}},[d,e]),O=a.useCallback(async()=>{const J=!p;f(J);try{await zr({showQuickChatFAB:J},e)}catch{f(!J)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:x,experimentalFeatures:b,insightsEnabled:S,roadmapEnabled:R,memoryEnabled:M,devServerEnabled:z,todosEnabled:P,toggleAutoMerge:$,toggleGlobalPause:_,toggleEnginePause:I,toggleShowQuickChatFAB:O,refresh:W}}function rP(e){const{projectId:n,projects:s,projectsLoading:i,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:u}=e,d=a.useRef(!1),m=a.useRef(null);return a.useEffect(()=>{const g=new URLSearchParams(window.location.search),p=g.get("project"),f=g.get("task");if(!f||i)return;if(p){const v=s.find(b=>b.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,fo(f,p??n).then(v=>{c(v),m.current=f}).catch(()=>{l(`Task ${f} not found`,"error")})},[n,s,i,r,o,l,c]),{handleDetailClose:a.useCallback(()=>{if(m.current){const g=new URLSearchParams(window.location.search);g.delete("task");const p=g.toString();window.history.replaceState(null,"",p?`${window.location.pathname}?${p}`:window.location.pathname),m.current=null}u()},[u])}}function oP(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{cs().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,i(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),a.useEffect(()=>{l.current=s},[s]),a.useEffect(()=>{c.current=r},[r]);const u=a.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];l.current=p,i(()=>p);try{await sn({favoriteProviders:p,favoriteModels:c.current})}catch(f){throw l.current=h,i(()=>h),f}},[]),d=a.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(f=>f!==m):[m,...h];c.current=p,o(()=>p);try{await sn({favoriteProviders:l.current,favoriteModels:p})}catch(f){throw c.current=h,o(()=>h),f}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:u,toggleFavoriteModel:d}}function lP({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:i}){const r=a.useRef(!1),o=a.useRef(n);o.current=n,a.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;mr().then(({providers:u})=>{const d=u.some(h=>h.authenticated);if(u.length>0&&!d||u.length>0&&d)return Vi().then(h=>{const g=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!d||!g)&&!ja()?l=!0:!d&&!ja()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(ws("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(ws("onboarding:auto-triggered",{trigger:"missing-provider"}),i("authentication"))}).catch(()=>{})},[e,n,s,i])}const Ph="kb-update-banner-dismissed";function cP(){const[e,n]=a.useState(!0),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(null),[u,d]=a.useState(!1);a.useEffect(()=>{const h=sessionStorage.getItem(Ph)==="true";d(h);let g=!1;return Lv().then(p=>{g||p.disabled||(i(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{g||n(!1)}),()=>{g=!0}},[]);const m=a.useCallback(()=>{d(!0),sessionStorage.setItem(Ph,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:u,dismiss:m}}const dP=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server","todos"];function Ih(e){return e!==null&&dP.includes(e)}function uP(e){return e==="devserver"?"dev-server":e}function mP(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[g,p]=a.useState(()=>{const b=Dn("kb-dashboard-task-view");return Ih(b)?b:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const b=Dn("kb-dashboard-task-view",r?.id);if(Ih(b)){const y=!f.current&&b==="devserver";p(y?"devserver":uP(b))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{os("kb-dashboard-task-view",g,r?.id)},[r?.id,g]),a.useEffect(()=>{n||i||r&&m==="overview"&&h("project")},[n,i,r,m]),a.useEffect(()=>{if(n||i||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,i,r,l,c]);const x=a.useCallback(b=>{p(b)},[]),v=a.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(u),S=b[(y+1)%b.length];d(S)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:x,handleToggleTheme:v}}function hP(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:i,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:u,openSettings:d,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:g}=e,p=a.useCallback(C=>{n(C),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),x=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),b=a.useCallback(C=>{h(),n(C),i("project"),u(`Project ${C.name} registered successfully`,"success"),o()},[h,n,i,u,o]),y=a.useCallback(()=>{g()},[g]),S=a.useCallback(async C=>{try{await Dk(C.id),u(`Project ${C.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${C.name}`,"error")}},[u,o]),k=a.useCallback(async C=>{try{await Lk(C.id),u(`Project ${C.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${C.name}`,"error")}},[u,o]),R=a.useCallback(async C=>{try{await op(C.id),u(`Project ${C.name} removed`,"success"),r?.id===C.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${C.name}`,"error")}},[r,s,i,u,o]),N=a.useCallback(async C=>{try{await l(C)}catch{u("Failed to update favorites","error")}},[l,u]),M=a.useCallback(async C=>{try{await c(C)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:x,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:k,handleRemoveProject:R,handleToggleFavorite:N,handleToggleModelFavorite:M}}function pP(e){const{createTask:n,onPlanningTaskCreated:s,onPlanningTasksCreated:i,onSubtaskTasksCreated:r,addToast:o}=e,l=a.useCallback(async g=>n({...g,column:"triage"}),[n]),c=a.useCallback(async g=>await n({...g,column:"triage"}),[n]),u=a.useCallback(g=>{s(g,o)},[s,o]),d=a.useCallback(g=>{i(g,o)},[i,o]),m=a.useCallback(g=>{r(g,o)},[r,o]),h=a.useCallback(g=>{o(`Imported ${g.id} from GitHub`,"success")},[o]);return{handleBoardQuickCreate:l,handleModalCreate:c,handlePlanningTaskCreated:u,handlePlanningTasksCreated:d,handleSubtaskTasksCreated:m,handleGitHubImport:h}}async function fP(e){return Fo("/health",{nodeId:e})}async function gP(e){return Fo("/projects",{nodeId:e})}async function xP(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),Fo(`/tasks?${i.toString()}`,{nodeId:e})}async function bP(e,n){return Fo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function wD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function ND(e){return L(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function SD(e){return L(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function CD(e){return L(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function vP(e,n){const{projectId:s,searchQuery:i}=n??{},[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState(null),f=a.useRef(null),x=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const b=new AbortController;f.current=b,h(!0),p(null);try{const y=[fP(e),gP(e)];s&&(y.push(xP(e,s,i)),y.push(bP(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const k=S[0],R=S[1];if(k.status==="rejected"){p(`Failed to fetch node health: ${k.reason}`),h(!1);return}if(d(k.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&S[2]){const N=S[2];if(N.status==="rejected"){p(`Failed to fetch tasks: ${N.reason}`),h(!1);return}N.status==="fulfilled"&&c(N.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(x(),()=>{f.current?.abort()}),[x]);const v=a.useCallback(()=>{x()},[x]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function yP(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 Ls(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 kP="fusion-dashboard-current-node",mg=a.createContext(null);function jP({children:e}){const[n,s]=a.useState(null),[i,r]=a.useState(!0),o=a.useRef(!1),l=a.useRef(void 0);a.useEffect(()=>{let m=!1;async function h(){try{const g=await Vi();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(kP);if(f){const x=JSON.parse(f);x?.id&&x?.type==="remote"&&(l.current=x.id,await sn({dashboardCurrentNodeId:x.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,sn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,sn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,sn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(mg.Provider,{value:d,children:e})}function wP(){const e=a.useContext(mg);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function NP({open:e}){const[n,s]=a.useState(""),i=a.useRef(null);a.useEffect(()=>{e&&i.current?.focus()},[e]);const r=a.useCallback(()=>{const l=n.trim();l&&(mv(l),window.location.reload())},[n]),o=a.useCallback(()=>{hv(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:i,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const SP=200,CP=a.lazy(()=>nn(()=>import("./AgentsView-CXaYJX_G.js").then(e=>e.A),__vite__mapDeps([17,1,18,8,19])).then(e=>({default:e.AgentsView}))),EP=a.lazy(()=>nn(()=>import("./DocumentsView-CjrtI3TX.js"),__vite__mapDeps([20,1,0,2,21])).then(e=>({default:e.DocumentsView}))),_P=a.lazy(()=>nn(()=>import("./InsightsView-BkfQ-TV1.js"),__vite__mapDeps([22,1,14,0,2,23])).then(e=>({default:e.InsightsView}))),MP=a.lazy(()=>nn(()=>import("./NodesView-Bn_1R73N.js"),__vite__mapDeps([24,1,18,0,2,25])).then(e=>({default:e.NodesView}))),AP=a.lazy(()=>nn(()=>import("./ChatView-iXxGAaN1.js"),__vite__mapDeps([26,1,0,2])).then(e=>({default:e.ChatView}))),RP=a.lazy(()=>nn(()=>import("./RoadmapsView-B4VnQP83.js"),__vite__mapDeps([27,1,0,2,28])).then(e=>({default:e.RoadmapsView}))),TP=a.lazy(()=>nn(()=>import("./SkillsView-CRvqF8P1.js"),__vite__mapDeps([29,1,0,2,30])).then(e=>({default:e.SkillsView}))),PP=a.lazy(()=>nn(()=>import("./MemoryView-1G0zWu1i.js"),__vite__mapDeps([31,1,12,13,0,2,32])).then(e=>({default:e.MemoryView}))),IP=a.lazy(()=>nn(()=>import("./DevServerView-BeXfFkF4.js"),__vite__mapDeps([33,1,0,2,34])).then(e=>({default:e.DevServerView}))),$P=a.lazy(()=>nn(()=>import("./TodoView-Vzui5Eha.js"),__vite__mapDeps([35,1,36,0,2,37])).then(e=>({default:e.TodoView})));function DP(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{nn(()=>import("./AgentsView-CXaYJX_G.js").then(n=>n.A),__vite__mapDeps([17,1,18,8,19])),nn(()=>import("./DocumentsView-CjrtI3TX.js"),__vite__mapDeps([20,1,0,2,21])),nn(()=>import("./InsightsView-BkfQ-TV1.js"),__vite__mapDeps([22,1,14,0,2,23])),nn(()=>import("./NodesView-Bn_1R73N.js"),__vite__mapDeps([24,1,18,0,2,25])),nn(()=>import("./ChatView-iXxGAaN1.js"),__vite__mapDeps([26,1,0,2])),nn(()=>import("./RoadmapsView-B4VnQP83.js"),__vite__mapDeps([27,1,0,2,28])),nn(()=>import("./SkillsView-CRvqF8P1.js"),__vite__mapDeps([29,1,0,2,30])),nn(()=>import("./MemoryView-1G0zWu1i.js"),__vite__mapDeps([31,1,12,13,0,2,32])),nn(()=>import("./DevServerView-BeXfFkF4.js"),__vite__mapDeps([33,1,0,2,34])),nn(()=>import("./TodoView-Vzui5Eha.js"),__vite__mapDeps([35,1,36,0,2,37]))})}const dc="kb-setup-warning-dismissed";function LP(){const{toasts:e,addToast:n,removeToast:s}=XT(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{DP()},[]);const{projects:r,loading:o,error:l,refresh:c}=KT(),{nodes:u}=Bo(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=wP(),{currentProject:f,setCurrentProject:x,clearCurrentProject:v,loading:b}=YT(r,{nodeId:m}),{hasAiProvider:y,hasGithub:S,loading:k,hasWarnings:R}=Zf(f?.id),{updateAvailable:N,latestVersion:M,currentVersion:C,dismissed:z,dismiss:A}=cP();a.useEffect(()=>{if(m&&!d&&u.length>0){const We=u.find(mt=>mt.id===m);if(We){g(We);return}}m&&u.length>0&&(u.some(mt=>mt.id===m)||p())},[m,d,u,g,p]);const[P,F]=a.useState(""),W=vP(m,{projectId:f?.id,searchQuery:P||void 0});yP(m);const $=h&&W.projects.length>0?W.projects:r,{themeMode:_,colorTheme:I,setThemeMode:O,setColorTheme:J}=sP(),{sessions:Q,generating:E,needsInput:D,planningSessions:T,dismissSession:w}=HT(f?.id),q=Q.filter(We=>We.status==="awaiting_input"||We.status==="error"),G=iP({projectId:f?.id,planningSessions:T}),{viewMode:me,setViewMode:ce,taskView:ae,handleChangeTaskView:pe}=mP({projectsLoading:o,projectsError:l,currentProjectLoading:b,currentProject:f,projectsLength:r.length,setupWizardOpen:G.setupWizardOpen,openSetupWizard:G.openSetupWizard,themeMode:_,setThemeMode:O}),U=a.useCallback(We=>{We==="missions"&&(de(void 0),ue(void 0),Se(void 0)),pe(We)},[pe]),Ne=ae==="board"||ae==="list",{tasks:ne,createTask:xe,moveTask:le,pauseTask:ve,deleteTask:ee,mergeTask:Ee,retryTask:Fe,updateTask:Ke,duplicateTask:Ze,archiveTask:Xe,unarchiveTask:Qe,archiveAllDone:it,loadArchivedTasks:Ie,lastFetchTimeMs:Ge}=qT({...f?{projectId:f.id}:{},searchQuery:P||void 0,sseEnabled:Ne}),[se,ye]=a.useState(!1),Z=a.useRef(performance.now()),Te=a.useRef(!1),ze=a.useRef(!1),be=a.useMemo(()=>o?"projects":b?"project":"tasks",[o,b]);a.useEffect(()=>{if(!o&&!Te.current){Te.current=!0;const We=`projects loaded at ${Math.round(performance.now()-Z.current)}ms from mount`;console.log(`[App] ${We}`),ir("[App]",We)}if(!b&&!ze.current){ze.current=!0;const We=`current-project resolved at ${Math.round(performance.now()-Z.current)}ms from mount`;console.log(`[App] ${We}`),ir("[App]",We)}},[o,b]),a.useEffect(()=>{if(se||o||b)return;const We=performance.now(),mt=window.setTimeout(()=>{const fn=`dashboard ready at ${Math.round(performance.now()-Z.current)}ms from mount (settle delay=${Math.round(performance.now()-We)}ms)`;console.log(`[App] ${fn}`),ir("[App]",fn),ye(!0)},SP);return()=>{window.clearTimeout(mt)}},[se,o,b]);const Be=Cr()==="mobile",[lt,je]=a.useState(0),ie=a.useCallback(()=>{mp(f?.id).then(We=>{je(We.unreadCount)}).catch(We=>{console.warn("[App] Failed to fetch mailbox unread count:",We)})},[f?.id]);a.useEffect(()=>{ie();const We=new URLSearchParams;f?.id&&We.set("projectId",f.id);const mt=We.size>0?`?${We.toString()}`:"";return Ls(`/api/events${mt}`,{events:{"message:sent":ie,"message:received":ie,"message:read":ie,"message:deleted":ie}})},[f?.id,ie]);const[Ae,he]=a.useState(!1),[Re,Je]=a.useState(!1),[$e,de]=a.useState(void 0),[re,ue]=a.useState(void 0),[Pe,Se]=a.useState(void 0),[fe,tt]=a.useState(!1),[ut,vt]=a.useState(!1),[gt,dt]=a.useState(()=>Dn(dc,f?.id)==="true");a.useEffect(()=>{dt(Dn(dc,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const We=()=>{vt(!0)};return window.addEventListener(jc,We),()=>{window.removeEventListener(jc,We)}},[]);const wt=a.useCallback(()=>{os(dc,"true",f?.id),dt(!0)},[f?.id]),{maxConcurrent:Mt,autoMerge:yt,globalPaused:Et,enginePaused:Nt,taskStuckTimeoutMs:Tt,showQuickChatFAB:Ht,prAuthAvailable:Ut,experimentalFeatures:Vt,insightsEnabled:zt,roadmapEnabled:Ct,memoryEnabled:At,devServerEnabled:kt,todosEnabled:Kt,toggleAutoMerge:$t,toggleGlobalPause:B,toggleEnginePause:ge,refresh:te}=aP(f?.id),j=Vt.skillsView===!0,V=Vt.nodesView===!0,De=!0;a.useEffect(()=>{Object.keys(Vt).length!==0&&(ae==="insights"&&!zt&&pe("board"),ae==="roadmaps"&&!Ct&&pe("board"),ae==="memory"&&!At&&pe("board"),(ae==="devserver"||ae==="dev-server")&&!kt&&pe("board"),ae==="todos"&&!Kt&&pe("board"))},[ae,zt,Ct,Vt,pe,De,At,kt,Kt]),a.useEffect(()=>{Ae&&!V&&he(!1)},[Ae,V]);const{availableModels:nt,favoriteProviders:St,favoriteModels:Pt,toggleFavoriteProvider:Rt,toggleFavoriteModel:un}=oP();lP({projectId:f?.id,setupWizardOpen:G.setupWizardOpen,openModelOnboarding:G.openModelOnboarding,openSettings:G.openSettings});const{handleSelectProject:mn,handleViewAllProjects:wn,handleOpenSettings:Gt,handleAddProject:es,handleSetupComplete:we,handleModelOnboardingComplete:rt,handlePauseProject:Jt,handleResumeProject:Sn,handleRemoveProject:Cn,handleToggleFavorite:pn,handleToggleModelFavorite:bn}=hP({setCurrentProject:x,clearCurrentProject:v,setViewMode:ce,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Rt,toggleFavoriteModel:un,addToast:n,openSettings:G.openSettings,openSetupWizard:G.openSetupWizard,closeSetupWizard:G.closeSetupWizard,closeModelOnboarding:G.closeModelOnboarding}),{handleDetailClose:Rn}=rP({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:x,addToast:n,openTaskDetail:G.openDetailTask,closeTaskDetail:G.closeDetailTask}),{handleBoardQuickCreate:vn,handleModalCreate:Y,handlePlanningTaskCreated:Oe,handlePlanningTasksCreated:Ye,handleSubtaskTasksCreated:st,handleGitHubImport:pt}=pP({createTask:xe,onPlanningTaskCreated:G.onPlanningTaskCreated,onPlanningTasksCreated:G.onPlanningTasksCreated,onSubtaskTasksCreated:G.onSubtaskTasksCreated,addToast:n}),jt=a.useCallback((We,mt)=>{if(mt==="changes"){G.openDetailWithChangesTab(We);return}G.openDetailTask(We,mt)},[G]),_t=a.useCallback(()=>{V&&he(We=>!We)},[V]),yn=a.useCallback(()=>{G.setFileWorkspace("project"),G.openFiles()},[G]),en=a.useCallback(async()=>{Je(!0);try{await c()}finally{Je(!1)}},[c]),xt=a.useCallback(We=>{ue(We),de(void 0),pe("missions")},[pe]),ts=a.useCallback(We=>{We.type==="planning"?G.openPlanningWithSession(We.id):We.type==="subtask"?G.openSubtaskWithSession(We.id):We.type==="mission_interview"?(ue(void 0),de(We.id),Se(void 0),pe("missions")):(We.type==="milestone_interview"||We.type==="slice_interview")&&(de(void 0),ue(void 0),Se(We.id),pe("missions"))},[pe,G]),ns=a.useCallback(()=>{},[]),ss=a.useCallback(()=>{},[]),Si=!o&&!b&&r.length===0&&!f&&!!l,oe=()=>Si?t.jsx(tT,{errorMessage:l??"Failed to fetch projects",isRetrying:Re,onRetry:en}):Ae?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(MP,{addToast:n,onClose:()=>he(!1)})})})}):me==="overview"?t.jsx(Jn,{children:t.jsx(ON,{projects:r,loading:o,onSelectProject:mn,onAddProject:es,onPauseProject:Jt,onResumeProject:Sn,onRemoveProject:Cn,nodes:u})}):ae==="skills"?j?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(TP,{addToast:n,projectId:f?.id,onClose:()=>pe("board")})})}):(pe("board"),null):ae==="chat"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(AP,{addToast:n,projectId:f?.id})})}):ae==="mailbox"?t.jsx(Jn,{children:t.jsx(T1,{projectId:f?.id,addToast:n,onUnreadCountChange:je})}):ae==="roadmaps"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(RP,{addToast:n,projectId:f?.id})})}):ae==="missions"?t.jsx(Jn,{children:t.jsx(_1,{isInline:!0,isOpen:!0,onClose:()=>{ue(void 0),de(void 0),Se(void 0),pe("board")},addToast:n,projectId:f?.id,onSelectTask:We=>{const mt=ne.find(fn=>fn.id===We);mt&&G.openDetailTask(mt)},availableTasks:ne.map(We=>({id:We.id,title:We.title})),resumeSessionId:$e,targetMissionId:re,milestoneSliceResumeSessionId:Pe,onMilestoneSliceResumeFetchError:()=>Se(void 0)})}):ae==="agents"&&De?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(CP,{addToast:n,projectId:f?.id})})}):ae==="documents"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(EP,{projectId:f?.id,addToast:n,onOpenDetail:G.openDetailTask})})}):ae==="insights"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(_P,{projectId:f?.id,addToast:n,onClose:()=>pe("board")})})}):ae==="memory"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(PP,{addToast:n,projectId:f?.id})})}):ae==="todos"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx($P,{addToast:n,projectId:f?.id})})}):ae==="devserver"||ae==="dev-server"?t.jsx(Jn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(IP,{addToast:n,projectId:f?.id})})}):ae==="board"?t.jsx(Jn,{children:t.jsx(EN,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f?.id,maxConcurrent:Mt,onMoveTask:le,onPauseTask:ve,onOpenDetail:G.openDetailTask,addToast:n,onQuickCreate:vn,onNewTask:G.openNewTask,onPlanningMode:G.openPlanningWithInitialPlan,onSubtaskBreakdown:G.openSubtaskBreakdown,autoMerge:yt,onToggleAutoMerge:$t,globalPaused:Et,onUpdateTask:Ke,onRetryTask:Fe,onArchiveTask:Xe,onUnarchiveTask:Qe,onDeleteTask:ee,onArchiveAllDone:it,onLoadArchivedTasks:Ie,searchQuery:P,availableModels:nt,onOpenDetailWithTab:jt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn,taskStuckTimeoutMs:Tt,onOpenMission:xt,lastFetchTimeMs:Ge})}):t.jsx(Jn,{children:t.jsx(AN,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f?.id,onMoveTask:le,onRetryTask:Fe,onOpenDetail:G.openDetailTask,addToast:n,globalPaused:Et,onNewTask:G.openNewTask,onQuickCreate:vn,onPlanningMode:G.openPlanningWithInitialPlan,onSubtaskBreakdown:G.openSubtaskBreakdown,availableModels:nt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn,taskStuckTimeoutMs:Tt,searchQuery:P,lastFetchTimeMs:Ge})});if(!se)return t.jsxs(t.Fragment,{children:[t.jsx(sT,{stage:be}),t.jsx(ag,{toasts:e,onRemove:s})]});const _e=!G.modelOnboardingOpen&&C4(),at=!G.modelOnboardingOpen&&!_e&&ja()&&!tg();return t.jsxs(t.Fragment,{children:[t.jsx(tw,{isElectron:i,onOpenSettings:Gt,onOpenGitHubImport:G.openGitHubImport,onOpenPlanning:G.openPlanning,onResumePlanning:G.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:G.openUsage,onOpenActivityLog:G.openActivityLog,onOpenSystemStats:G.openSystemStats,onOpenMailbox:()=>U("mailbox"),mailboxUnreadCount:lt,onOpenSchedules:G.openSchedules,onOpenGitManager:G.openGitManager,onOpenNodes:_t,showNodesButton:V,onOpenWorkflowSteps:G.openWorkflowSteps,onOpenScripts:G.openScripts,onRunScript:G.runScript,onToggleTerminal:G.toggleTerminal,onOpenFiles:G.openFiles,filesOpen:G.filesOpen,globalPaused:Et,enginePaused:Nt,onToggleGlobalPause:B,onToggleEnginePause:ge,view:ae,onChangeView:me==="project"&&f?U:void 0,showSkillsTab:j,showAgentsTab:De,searchQuery:P,onSearchChange:F,projects:$,currentProject:f,onSelectProject:mn,onViewAllProjects:wn,projectId:f?.id,mobileNavEnabled:Be,availableNodes:u,currentNode:d,onSelectNode:We=>{We===null?p():g(We)},isRemote:h,experimentalFeatures:{insights:zt,roadmap:Ct,memoryView:At,devServer:kt,devServerView:kt,todoView:Kt}}),me==="project"&&f&&!Ae&&ae!=="missions"&&!G.isPlanningOpen&&t.jsx(gT,{sessions:q,onResumeSession:ts,onDismissSession:ns,onDismissAll:ss}),me==="project"&&f&&_e&&t.jsx(bT,{onResume:G.openModelOnboarding}),me==="project"&&f&&at&&t.jsx(vT,{onOpenModelOnboarding:G.openModelOnboarding,onOpenSettings:We=>G.openSettings(We)}),me==="project"&&f&&N&&M&&C&&!z&&t.jsx(xT,{latestVersion:M,currentVersion:C,onDismiss:A}),me==="project"&&f&&!k&&R&&!gt&&t.jsx(eg,{hasAiProvider:y,hasGithub:S,onDismiss:wt}),t.jsx("div",{className:`project-content${me==="project"&&f?" project-content--with-footer":""}${Be?" project-content--with-mobile-nav":""}`,children:oe()}),me==="project"&&f&&!Ae&&t.jsx(hT,{tasks:h&&W.tasks.length>0?W.tasks:ne,projectId:f.id,taskStuckTimeoutMs:Tt,backgroundSessions:Q,backgroundGenerating:E,backgroundNeedsInput:D,onOpenBackgroundSession:ts,onDismissBackgroundSession:w,lastFetchTimeMs:Ge,currentProjectPath:f.path,onOpenProjectDirectory:yn}),t.jsx(kT,{view:ae,onChangeView:me==="project"&&f?U:()=>{},footerVisible:me==="project"&&!!f,modalOpen:G.anyModalOpen,onOpenSettings:Gt,onOpenActivityLog:G.openActivityLog,onOpenSystemStats:G.openSystemStats,onOpenMailbox:()=>U("mailbox"),mailboxUnreadCount:lt,onOpenGitManager:G.openGitManager,onOpenWorkflowSteps:G.openWorkflowSteps,onOpenSchedules:G.openSchedules,onOpenScripts:G.openScripts,onToggleTerminal:G.toggleTerminal,onOpenFiles:G.openFiles,onOpenGitHubImport:G.openGitHubImport,onOpenPlanning:G.openPlanning,onResumePlanning:G.resumePlanning,activePlanningSessionCount:T.length,onOpenUsage:()=>G.openUsage(null),onViewAllProjects:wn,onRunScript:G.runScript,projectId:f?.id,showSkillsTab:j,experimentalFeatures:{insights:zt,roadmap:Ct,memoryView:At,devServer:kt,devServerView:kt,todoView:Kt}}),me==="project"&&f&&ae!=="chat"&&ae!=="mailbox"&&ae!=="insights"&&ae!=="devserver"&&ae!=="dev-server"&&t.jsx(BT,{projectId:f.id,addToast:n,showFAB:Ht,open:fe,onOpenChange:tt,favoriteProviders:St,favoriteModels:Pt,onToggleFavorite:pn,onToggleModelFavorite:bn}),t.jsx(eT,{projectId:f?.id,tasks:ne,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:G,projectActions:{handleAddProject:es,handleSetupComplete:we,handleModelOnboardingComplete:rt},taskHandlers:{handleModalCreate:Y,handlePlanningTaskCreated:Oe,handlePlanningTasksCreated:Ye,handleSubtaskTasksCreated:st,handleGitHubImport:pt},taskOperations:{moveTask:le,deleteTask:ee,mergeTask:Ee,retryTask:Fe,duplicateTask:Ze},deepLink:{handleDetailClose:Rn},settings:{prAuthAvailable:Ut,themeMode:_,colorTheme:I,setThemeMode:O,setColorTheme:J},onSettingsClose:()=>{G.closeSettings(),te()},onReopenOnboarding:()=>{G.closeSettings(),G.openModelOnboarding()}}),t.jsx(NP,{open:ut})]})}function zP(){return t.jsx(QT,{children:t.jsx(jP,{children:t.jsx(fw,{children:t.jsx(LP,{})})})})}yv();av();hg.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(rv,{children:t.jsx(zP,{})})}));"serviceWorker"in navigator&&navigator.serviceWorker.register("/sw.js").then(e=>{console.log("SW registered:",e.scope)}).catch(e=>{console.log("SW registration failed:",e)});export{nn as $,Cs as A,gn as B,dn as C,u4 as D,jD as E,Oi as F,To as G,hn as H,sc as I,xn as J,Gs as K,ot as L,Xt as M,qt as N,g4 as O,An as P,Nk as Q,Nn as R,oa as S,Yc as T,c4 as U,d4 as V,Sk as W,Ot as X,ZI as Y,Pn as Z,Ck as _,os as a,E$ as a$,kI as a0,jI as a1,fo as a2,Py as a3,pc as a4,da as a5,wa as a6,ci as a7,di as a8,li as a9,pr as aA,Kj as aB,dD as aC,uD as aD,Gj as aE,Jj as aF,_T as aG,Cr as aH,TT as aI,Ao as aJ,jT as aK,CT as aL,ms as aM,Di as aN,bi as aO,Xb as aP,g$ as aQ,b$ as aR,x$ as aS,v$ as aT,y$ as aU,k$ as aV,j$ as aW,w$ as aX,N$ as aY,S$ as aZ,C$ as a_,mD as aa,fD as ab,pD as ac,hD as ad,gD as ae,qn as af,Xn as ag,Vb as ah,Ys as ai,lx as aj,Mo as ak,yi as al,SD as am,wD as an,ND as ao,CD as ap,mo as aq,Ib as ar,sr as as,sx as at,Yn as au,Kh as av,Bo as aw,KT as ax,cD as ay,Xd as az,l$ as b,nD as b$,_$ as b0,M$ as b1,R$ as b2,T$ as b3,A$ as b4,Mn as b5,Jc as b6,Fi as b7,oD as b8,rD as b9,Xc as bA,Zy as bB,ek as bC,tk as bD,Xy as bE,II as bF,yr as bG,$o as bH,Tb as bI,dr as bJ,Sb as bK,I$ as bL,$$ as bM,D$ as bN,L$ as bO,z$ as bP,F$ as bQ,O$ as bR,P$ as bS,Xh as bT,ha as bU,Tk as bV,mv as bW,hv as bX,tD as bY,NI as bZ,wI as b_,lD as ba,tI as bb,eI as bc,ZP as bd,nI as be,uI as bf,mI as bg,lI as bh,aI as bi,rI as bj,oI as bk,iI as bl,sI as bm,XP as bn,cI as bo,XA as bp,LI as bq,DI as br,HI as bs,$I as bt,zI as bu,FI as bv,OI as bw,UI as bx,nk as by,BI as bz,Ue as c,zx as c$,SI as c0,PI as c1,AI as c2,CI as c3,RI as c4,EI as c5,TI as c6,_I as c7,MI as c8,_g as c9,YA as cA,b4 as cB,ic as cC,Oo as cD,KP as cE,qP as cF,WP as cG,GP as cH,JP as cI,YP as cJ,QP as cK,lw as cL,Uo as cM,vD as cN,Bm as cO,yD as cP,kD as cQ,dI as cR,U$ as cS,H$ as cT,W$ as cU,q$ as cV,B$ as cW,V$ as cX,K$ as cY,rp as cZ,Id as c_,Xs as ca,zA as cb,hI as cc,p$ as cd,UP as ce,BP as cf,mr as cg,c$ as ch,HP as ci,VP as cj,ry as ck,Qv as cl,Qs as cm,Xv as cn,Zv as co,ey as cp,gI as cq,d$ as cr,u$ as cs,m$ as ct,wi as cu,xD as cv,bD as cw,f$ as cx,mc as cy,In as cz,r$ as d,G$ as d0,t$ as d1,YI as d2,XI as d3,QI as d4,i$ as d5,s$ as d6,Uh as d7,GI as d8,KI as d9,l4 as da,e$ as db,vr as dc,oM as dd,VI as de,qI as df,Iy as dg,WI as dh,JI as di,J$ as dj,Y$ as dk,wb as dl,bc as dm,sD as dn,Z$ as dp,X$ as dq,eD as dr,Q$ as ds,h$ as dt,xI as du,pI as dv,fI as dw,vI as dx,yI as dy,bI as dz,o$ as e,aD as f,Dn as g,cs as h,Na as i,iD as j,$n as k,wk as l,a$ as m,ST as n,Ds as o,Lo as p,zr as q,ke as r,Ls as s,mw as t,sn as u,n$ as v,gc as w,Js as x,Zt as y,uo as z};
|