@runfusion/fusion 0.4.0 → 0.4.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/LICENSE +21 -0
- package/dist/bin.js +825 -749
- package/dist/client/assets/{AgentDetailView-DJwWfkpv.js → AgentDetailView-sy6Hg1Xr.js} +1 -1
- package/dist/client/assets/{AgentsView-DegK8aw-.js → AgentsView-DpEpW88a.js} +3 -3
- package/dist/client/assets/{ChatView-CYpEShLS.js → ChatView-BUt3C4cf.js} +1 -1
- package/dist/client/assets/{DevServerView-DfCTA9fx.js → DevServerView-BOyWtQJM.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-B0qNpfLW.js → DirectoryPicker-BJyEEso5.js} +1 -1
- package/dist/client/assets/{DocumentsView-CsQxuyz3.js → DocumentsView-Dx0M1YHw.js} +1 -1
- package/dist/client/assets/{InsightsView-Bzs7A2jv.js → InsightsView-BtXdAo7D.js} +1 -1
- package/dist/client/assets/{MemoryView-Cl5ASqjW.js → MemoryView-kKPuqmwf.js} +1 -1
- package/dist/client/assets/{NodesView-BpiqRlvc.js → NodesView-B_ZwUORz.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-Cr6EoC7S.js → PiExtensionsManager-Db0EGr0Q.js} +1 -1
- package/dist/client/assets/{PluginManager-DXtQdfns.js → PluginManager-mOwWndfg.js} +1 -1
- package/dist/client/assets/{RoadmapsView-CYPLTTB0.js → RoadmapsView-DbUzBLeF.js} +1 -1
- package/dist/client/assets/SettingsModal-Bs_lNs5B.js +31 -0
- package/dist/client/assets/{SettingsModal-CNdVTVqD.js → SettingsModal-TRJu_mTn.js} +1 -1
- package/dist/client/assets/{SetupWizardModal-BLiljNn7.js → SetupWizardModal-D1bmCQrf.js} +1 -1
- package/dist/client/assets/{SkillsView-Dlpw5LKI.js → SkillsView-Dzzpd5Md.js} +1 -1
- package/dist/client/assets/{folder-open-B_38R5AA.js → folder-open-BcuByk6U.js} +1 -1
- package/dist/client/assets/index-BipedNj4.css +1 -0
- package/dist/client/assets/{index-DQKtk17v.js → index-k2c4LrUr.js} +5 -5
- package/dist/client/assets/{upload-DNQF7XCK.js → upload-BzNbXYEj.js} +1 -1
- package/dist/client/assets/{users-CG2_rCdk.js → users-BvIqhSXp.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/extension.js +68 -12
- package/dist/pi-claude-cli/package.json +1 -1
- package/package.json +17 -17
- package/dist/client/assets/SettingsModal-CyCC7MzL.js +0 -31
- package/dist/client/assets/index-DjOxzdj3.css +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-D1bmCQrf.js","assets/DirectoryPicker-BJyEEso5.js","assets/folder-open-BcuByk6U.js","assets/DirectoryPicker-DzKVmxOf.css","assets/SetupWizardModal-BMa6p24b.css","assets/SettingsModal-Bs_lNs5B.js","assets/SettingsModal-TRJu_mTn.js","assets/SettingsModal-G0ESQXRD.css","assets/users-BvIqhSXp.js","assets/SettingsModal-CDWvhvrd.css","assets/AgentsView-DpEpW88a.js","assets/upload-BzNbXYEj.js","assets/AgentsView-DETxUmHS.css","assets/DocumentsView-Dx0M1YHw.js","assets/DocumentsView-DV2DrCZb.css","assets/InsightsView-BtXdAo7D.js","assets/InsightsView-Egu71gmh.css","assets/NodesView-B_ZwUORz.js","assets/NodesView-BYVG2yY-.css","assets/ChatView-BUt3C4cf.js","assets/RoadmapsView-DbUzBLeF.js","assets/RoadmapsView-BOYnyMCh.css","assets/SkillsView-Dzzpd5Md.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-kKPuqmwf.js","assets/MemoryView-DiajLXby.css","assets/DevServerView-BOyWtQJM.js","assets/DevServerView-ZeBGQkLI.css"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{r as a,j as t,a as Ta,g as Km,R as Jm,c as Sf}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
|
*
|
|
@@ -569,10 +569,10 @@ import{r as a,j as t,a as Ta,g as Km,R as Jm,c as Sf}from"./vendor-react-K0fH_qH
|
|
|
569
569
|
*
|
|
570
570
|
* This source code is licensed under the ISC license.
|
|
571
571
|
* See the LICENSE file in the root directory of this source tree.
|
|
572
|
-
*/const Qb=[["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"}]],vn=Ve("zap",Qb),$l="fusion:version-reload";function dh(e){if(sessionStorage.getItem($l)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem($l,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function Xb(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 Zb(e){return Xb(e)?(dh(`chunk load error: ${e?.message??e}`),!0):!1}async function ex(){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 Ao=!1;async function To(){if(!(Ao||document.visibilityState!=="visible")){Ao=!0;try{const e=await ex();e&&e!=="mog4dejv-658ae4e3"&&dh(`build version changed: mog4dejv-658ae4e3 -> ${e}`)}finally{Ao=!1}}}function tx(){window.setTimeout(()=>sessionStorage.removeItem($l),5e3),document.addEventListener("visibilitychange",()=>{To()}),window.addEventListener("focus",()=>{To()}),window.setTimeout(()=>void To(),2e3)}class ao 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),!Zb(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(lc,{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 Xn({children:e,onError:n}){return t.jsx(ao,{level:"page",onError:n,children:e})}function fi({children:e,onError:n}){return t.jsx(ao,{level:"modal",onError:n,children:e})}function nx({children:e,onError:n}){return t.jsx(ao,{level:"root",onError:n,children:e})}const sx="modulepreload",ix=function(e){return"/"+e},Qc={},Zt=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=ix(d),d in Qc)return;Qc[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":sx,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)})},cc="fn.authToken",Xc="token",ax="fn_token";let Hi,Zc=!1,Fr=!1;const Dl="fn:auth-token-recovery-required";function rx(){try{const e=window.localStorage.getItem(cc);return e&&e.length>0?e:void 0}catch{return}}function uh(e){try{window.localStorage.setItem(cc,e)}catch{}}function ox(){if(!(Zc||typeof window>"u")){Zc=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Xc);if(!n)return;uh(n),e.searchParams.delete(Xc);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Ki(){if(Hi!==void 0)return Hi;const e=ox();if(e)return Hi=e,e;const n=rx();if(n)return Hi=n,n}function lx(e){Hi=e,Fr=!1,uh(e)}function cx(){Hi=void 0,Fr=!1;try{window.localStorage.removeItem(cc)}catch{}}function ed(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function dx(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function ux(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!dx(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=ed(e.protocol)===ed(n.protocol);return s&&i&&r}function mx(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 Hs(e){const n=Ki();if(!n||typeof window>"u")return e;const s=mx(e);return!s||!ux(s.parsed)?e:(s.parsed.searchParams.set(ax,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function di(e){const n=Ki();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function hx(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function px(){typeof window>"u"||Fr||(Fr=!0,window.dispatchEvent(new CustomEvent(Dl)))}async function fx(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();hx(i)&&px()}catch{}}function gx(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Ki();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=Ki(),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=>(fx(u),u))}}class bx extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function xx(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Vn(e){return`/api${e}`}async function D(e,n={}){const s=Vn(e),i=Ki(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),di(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")||xx(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 bx(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function YR(){return D("/health")}function vx(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 D(`/tasks${l}`)}async function Or(e,n){const i=Vn(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:di({"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 mh(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:b,thinkingLevel:v,summarize:x,reviewLevel:k,executionMode:M,priority:y}=e;return D(V("/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:b,thinkingLevel:v,summarize:x,reviewLevel:k,executionMode:M,priority:y})})}function Ks(e,n,s){return D(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yx(e,n,s,i,r,o,l,c){return D(V("/tasks/batch-update-models",c),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l})})}function kx(e,n,s){return D(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function jx(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return D(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function wx(e,n){return D(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Nx(e,n){return D(V(`/tasks/${e}/retry`,n),{method:"POST"})}function Sx(e,n){return D(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function hh(e,n){return D(V(`/tasks/${e}/pause`,n),{method:"POST"})}function Cx(e,n){return D(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Ex(e,n){return D(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Mx(e,n){return D(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function _x(e){return D(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Ax(e,n){return D(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Tx(e,n){return D(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Rx(e){return D(V("/config",e))}function ro(e){return D(V("/settings",e))}function dr(e,n){return D(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function QR(e){return D(V("/remote/settings",e))}function XR(e,n){return D(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function ZR(e){return D(V("/remote/status",e))}function e4(e,n){return D(V("/remote/provider/activate",n),{method:"POST",body:JSON.stringify({provider:e})})}function t4(e){return D(V("/remote/tunnel/start",e),{method:"POST"})}function n4(e){return D(V("/remote/tunnel/stop",e),{method:"POST"})}function s4(e){return D(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function i4(e,n){return D(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function ph(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 a4(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=ph(null,s,i);return D(V(`/remote/url${r}`,n))}function r4(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=ph(e,i,r);return D(V(`/remote/qr${o}`,s))}function o4(e){return D(V("/memory",e))}function l4(e,n){return D(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function c4(e){return D(V("/memory/files",e))}function d4(e,n){const s=`path=${encodeURIComponent(e)}`;return D(V(`/memory/file?${s}`,n))}function u4(e,n,s){return D(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function m4(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 D(V("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function h4(e){return D(V("/memory/insights",e))}function p4(e,n){return D(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function f4(e){return D(V("/memory/extract",e),{method:"POST"})}function g4(e){return D(V("/memory/audit",e))}function b4(e){return D(V("/memory/stats",e))}function x4(e){return D(V("/memory/backend",e))}function v4(e){return D(V("/memory/install-qmd",e),{method:"POST"})}function y4(e,n){return D(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ra(){return D("/settings/global")}function nn(e){return D("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function k4(e){return D(V("/settings/scopes",e))}function j4(e){return D(V("/settings/pi-extensions",e))}function w4(e,n){return D(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function N4(e,n){return D(V("/settings/test-ntfy",n),{method:"POST",body:e?JSON.stringify(e):void 0})}function S4(){return D("/pi-settings")}async function C4(e){return D("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function E4(e){return D("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function M4(e){return D(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Ua(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Vn(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:di(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Ix(e,n,s){return D(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function td(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=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Vn(o),{headers:di()});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 Px(e,n,s,i){return D(V(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function $x(e,n,s){return D(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Dx(e,n){return D(V(`/tasks/${e}/documents`,n))}function Lx(e,n,s){return D(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function _4(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 D(V(r,n))}function A4(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return D(V(r,e))}function nd(e,n,s,i,r){return D(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function zx(e,n,s){return D(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Fx(e,n,s){return D(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Ox(e,n,s){return D(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ux(e,n){return D(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Bx(e,n,s){return D(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function is(){return D("/models")}function Hx(){return D("/usage")}function qx(){return D("/providers/claude-cli/status")}function Vx(e){return D("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Ba(){return D("/auth/status")}function Wx(e){return D("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function Gx(e){return D("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Kx(e,n){return D("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Jx(e){return D("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Yx(e,n,s,i){return D("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function Qx(e,n,s,i){return D(V("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Xx(e,n,s){return D("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Zx(e,n,s,i){return D(V("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function ev(e){return D(V("/git/remotes",e))}function tv(e){return D(V("/git/remotes/detailed",e))}function nv(e,n,s){return D(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function sv(e,n){return D(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function iv(e,n,s){return D(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function av(e,n,s){return D(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function rv(e,n,s){return D(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function ov(e,n){return D(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function lv(e,n){return(await D(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function ur(e,n,s,i){return D(V("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function sd(e,n){return D(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cv(e){return D(V("/terminal/sessions",e))}function As(e){return D(V("/git/status",e))}function dv(e,n){const s=e?`?limit=${e}`:"";return D(V(`/git/commits${s}`,n))}function Ur(e,n){return D(V(`/git/commits/${e}/diff`,n))}function uv(e){return D(V("/git/commits/ahead",e))}function mv(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return D(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function pa(e){return D(V("/git/branches",e))}function hv(e,n,s){const i=`?limit=${n}`;return D(V(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function pv(e){return D(V("/git/worktrees",e))}function fv(e,n,s){return D(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function gv(e,n){return D(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function id(e,n,s){const i=n?"?force=true":"";return D(V(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function bv(e,n){return D(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function xv(e){return D(V("/git/pull",e),{method:"POST"})}function vv(e){return D(V("/git/push",e),{method:"POST"})}function mr(e){return D(V("/git/stashes",e))}function yv(e,n){return D(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function kv(e,n,s){return D(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function jv(e,n){return D(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function wv(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),D(V(`/git/diff/file?${i.toString()}`,s))}function $i(e){return D(V("/git/changes",e))}function ad(e,n){return D(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Nv(e,n){return D(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function rd(e,n){return D(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Sv(e,n){return D(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Cv(e){return D(V("/workspaces",e))}function Ev(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),D(`/files?${i.toString()}`)}function Mv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function _v(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Av(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),D(`/files/search?${i.toString()}`)}function Tv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Rv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Iv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Pv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function fh(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function $v(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Dv(e,n,s){return D(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Lv(e,n,s,i){return D(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function zv(e,n,s){return D(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function gh(e,n,s){return D(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Fv(e,n,s){return D(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ov(e,n,s){return D(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Uv(e,n,s){return D(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Ll=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Ll))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Bv(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ja(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 b=Number.parseInt(f,10);return Number.isFinite(b)?u!==null&&b<=u?!1:(u=b,!0):!0},h=()=>{if(o)return;const p=Bv(e,u),f=new EventSource(Hs(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))f.addEventListener(b,x=>{const k=x;m(k)&&v(k)});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(),Ll.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Ll.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 Ji(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 Hv(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 qv(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Hv(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Vv(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 ld(e){return Array.isArray(e)?e.map(od):(e.candidates??[]).map(od)}async function Wv(e){try{const n=await D(V("/dev-server/candidates",e));return ld(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await D(V("/dev-server/detect",e));return ld(s)}throw n}}function dc(e){return D(V("/dev-server/status",e)).then(Ji)}async function T4(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 D(V(`/dev-server/logs/history${i}`,n));return qv(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await dc(n);return Vv(o.logs,e)}throw r}}function Gv(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return D(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(Ji)}function Kv(e){return D(V("/dev-server/stop",e),{method:"POST"}).then(Ji)}function Jv(e){return D(V("/dev-server/restart",e),{method:"POST"}).then(Ji)}async function Yv(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await D(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Ji(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await D(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Ji(r)}throw i}}function R4(e){return Vn(V("/dev-server/logs/stream",e))}async function I4(e){try{return(await D(V("/devserver",e))).sessions??[]}catch{try{const n=await dc(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 P4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await dc(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 $4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Gv({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 D4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Kv(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 L4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Jv(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 z4(e,n,s){try{const i=await D(V(`/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 Yv({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function F4(e){try{return(await D(V("/devserver/detect",e))).candidates??[]}catch{try{return(await Wv(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function O4(e,n){return Vn(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Ya(e,n,s=25e3){const i=setInterval(()=>{_k(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function Qv(e,n){return Vn(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function Xv(e,n,s,i){const r=Qv(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 Qa(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 Zv(e){return D(Qa("/routines",e))}function ey(e,n){return D(Qa("/routines",n),{method:"POST",body:JSON.stringify(e)})}function cd(e,n,s){return D(Qa(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function ty(e,n){await D(Qa(`/routines/${e}`,n),{method:"DELETE"})}function ny(e,n){return D(Qa(`/routines/${e}/trigger`,n),{method:"POST"})}function dd(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 D(`/activity${s}`)}function sy(e){const n=V("/activity",e);return D(n,{method:"DELETE"})}function oo(e){return D(V("/workflow-steps",e))}function ud(e,n){return D(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function iy(e,n,s){return D(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ay(e,n){return D(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function md(e,n){return D(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function ry(e,n){return D(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function oy(){return D("/workflow-step-templates")}function ly(e,n){return D(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Xa(e){return D(V("/scripts",e))}function cy(e,n,s){return D(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function dy(e,n){return D(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function bh(e,n,s){return(await D(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const hr={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 xh(e){if(!(e instanceof Error))return hr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?hr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?hr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:hr.NETWORK}function uy(e,n){return D(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function my(e,n,s){return D(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function hy(e,n){return Vn(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function py(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Ja(hy(e,n),{onOpen:()=>{l(),r=Ya(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 fy(e,n,s,i){return D(V("/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 vh(e,n,s){return D(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function gy(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 lo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=gy(e,s,i);return D(o,r)}function oa(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 D(`/agents${i}`)}function yh(e,n){return D(V(`/agents/${encodeURIComponent(e)}`,n))}function by(e,n){return D(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function xy(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function U4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function B4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function H4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function q4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function V4(e,n,s){const i=`path=${encodeURIComponent(n)}`;return D(V(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function W4(e,n,s,i){return D(V(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function vy(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function yy(e,n){return D(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function G4(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 D(`/agents/${encodeURIComponent(e)}/runs${r}`)}function K4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function J4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function Y4(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return D(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function Q4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function ky(e){return D(V("/agents/stats",e))}function X4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function Z4(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return D(`/agents/org-tree${i?`?${i}`:""}`)}function eI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function hd(e,n,s){return D(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function tI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function nI(){return D("/agents/companies")}function sI(e,n){return D(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function iI(e,n){return D(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function aI(e,n){return D(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rI(e){return D(V("/backups",e))}function oI(e){return D(V("/backups",e),{method:"POST"})}function lI(e,n){const s=V("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return D(i)}function cI(e,n,s){return D(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function pd(){return D("/projects/across-nodes")}function Pa(e,n){D("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function fd(){return D("/nodes")}function jy(e){return D("/nodes",{method:"POST",body:JSON.stringify(e)})}function wy(e,n){return D(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Ny(e){return D(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Sy(e){const n=await D(`/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 dI(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=Ki();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return D(u)}function Cy(e){return D("/projects",{method:"POST",body:JSON.stringify(e)})}function kh(e){return D(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function gd(e){return D(`/projects/${encodeURIComponent(e)}/health`)}function Ey(e){return D(V("/executor/stats",e))}function bd(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 D(`/activity-feed${s}`)}function My(e){return D(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function _y(e){return D(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function uI(){return D("/global-concurrency")}function mI(e){return D("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Ay(e,n){return D(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function jh(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 D(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Ty(e){return D(V("/missions",e))}function Ry(e,n){return D(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function wh(e,n){return D(V(`/missions/${encodeURIComponent(e)}`,n))}function Iy(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Py(e,n){return D(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $y(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 D(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Dy(e){return D(V("/missions/health",e))}function Ly(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function zy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Fy(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Oy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Uy(e,n,s){return D(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function By(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hy(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function qy(e,n,s){return D(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Vy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Wy(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Ky(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Jy(e,n,s,i){return D(V(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Yy(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function Ro(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Qy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Xy(e,n,s){return D(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function ek(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function tk(e,n){return D(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Io(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function xd(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function nk(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function vd(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function sk(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 D(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function ik(e,n){return D(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function ak(e,n){return D(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function rk(e,n){return D(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function ok(e,n){return D(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function lk(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function ck(e,n,s){return D(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function dk(e,n,s,i){return D(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function uk(e,n,s){return D(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Nh(e,n,s){return D(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function mk(e,n,s){return D(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function hk(e,n,s,i){const r=Vn(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 Za(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function er(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function pk(e,n){return D(Za(e,"/start",n),{method:"POST"})}function fk(e,n,s,i){return D(Za(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function gk(e,n,s,i){const r=Vn(Za(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 bk(e,n,s){return D(Za(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function xk(e,n){return D(Za(e,"/skip",n),{method:"POST"})}function vk(e,n){return D(er(e,"/start",n),{method:"POST"})}function yk(e,n,s,i){return D(er(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function kk(e,n,s,i){const r=Vn(er(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 jk(e,n,s){return D(er(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function wk(e,n){return D(er(e,"/skip",n),{method:"POST"})}async function Nk(e,n){try{return await D(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function hI(e){return D(V("/roadmaps",e))}function pI(e,n){return D(V("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function fI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}`,n))}function gI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function bI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function xI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function vI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yI(e,n){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function jI(e,n,s){return D(V(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function wI(e,n){return D(V(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function NI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function SI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function CI(e,n,s,i){return D(V(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function EI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function MI(e,n,s,i){return D(V(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function _I(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function Yi(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Sh(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(Vn(`/ai-sessions${n}`),{headers:di()});return s.ok?(await s.json()).sessions??[]:[]}async function Js(e){const n=await fetch(Vn(`/ai-sessions/${encodeURIComponent(e)}`),{headers:di()});return n.ok?n.json():null}async function Sk(e,n){const s=await D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Ck(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Ek(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Mk(e){await fetch(Vn(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:di()})}function _k(e,n){return D(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Ak(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 D(`/messages/inbox${i}`)}function Tk(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 D(`/messages/outbox${i}`)}function Ch(e){return D(V("/messages/unread-count",e))}function Rk(e,n){return D(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Ik(e,n){return D(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Pk(e){return D(V("/messages/read-all",e),{method:"POST"})}function $k(e,n){return D(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Dk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return D(V(i,s))}function Lk(e,n){return D(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function AI(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 D(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function TI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function RI(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/performance${r}`)}function II(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 D(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function PI(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function $I(e,n){return D(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function DI(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function LI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function zI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function FI(e){return D(V("/plugins",e))}async function OI(e,n){return D(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function UI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function BI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function HI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function qI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function VI(e,n,s){return D(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function WI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function zk(e){return D(V("/plugins/ui-slots",e))}async function GI(e){return(await D(V("/skills/discovered",e))).skills}async function KI(e,n,s){return D(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function JI(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 D(V(`/skills/catalog${r}`,s))}async function YI(e,n){return(await D(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function QI(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return D(`/chat/sessions${i?`?${i}`:""}`)}async function Fk(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 D(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Ok(e,n){return D(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function XI(e,n,s){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ZI(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yd(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 D(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Uk(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Bk(e,n,s,i,r){const o=Vn(V(`/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:di({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:l.signal});if(!d.ok){const v=await d.text();let x=`Request failed: ${d.status}`;try{x=JSON.parse(v).error||x}catch{}s.onError?.(x);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 b=(v,x=!1)=>{g+=v;const k=g.split(`
|
|
572
|
+
*/const Qb=[["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"}]],vn=Ve("zap",Qb),$l="fusion:version-reload";function dh(e){if(sessionStorage.getItem($l)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}sessionStorage.setItem($l,"1"),console.info("[versionCheck] reloading:",e),window.location.reload()}function Xb(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 Zb(e){return Xb(e)?(dh(`chunk load error: ${e?.message??e}`),!0):!1}async function ex(){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 Ao=!1;async function To(){if(!(Ao||document.visibilityState!=="visible")){Ao=!0;try{const e=await ex();e&&e!=="mog5pn44-24e04f4a"&&dh(`build version changed: mog5pn44-24e04f4a -> ${e}`)}finally{Ao=!1}}}function tx(){window.setTimeout(()=>sessionStorage.removeItem($l),5e3),document.addEventListener("visibilitychange",()=>{To()}),window.addEventListener("focus",()=>{To()}),window.setTimeout(()=>void To(),2e3)}class ao 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),!Zb(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(lc,{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 Xn({children:e,onError:n}){return t.jsx(ao,{level:"page",onError:n,children:e})}function fi({children:e,onError:n}){return t.jsx(ao,{level:"modal",onError:n,children:e})}function nx({children:e,onError:n}){return t.jsx(ao,{level:"root",onError:n,children:e})}const sx="modulepreload",ix=function(e){return"/"+e},Qc={},Zt=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=ix(d),d in Qc)return;Qc[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":sx,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)})},cc="fn.authToken",Xc="token",ax="fn_token";let Hi,Zc=!1,Fr=!1;const Dl="fn:auth-token-recovery-required";function rx(){try{const e=window.localStorage.getItem(cc);return e&&e.length>0?e:void 0}catch{return}}function uh(e){try{window.localStorage.setItem(cc,e)}catch{}}function ox(){if(!(Zc||typeof window>"u")){Zc=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Xc);if(!n)return;uh(n),e.searchParams.delete(Xc);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Ki(){if(Hi!==void 0)return Hi;const e=ox();if(e)return Hi=e,e;const n=rx();if(n)return Hi=n,n}function lx(e){Hi=e,Fr=!1,uh(e)}function cx(){Hi=void 0,Fr=!1;try{window.localStorage.removeItem(cc)}catch{}}function ed(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function dx(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function ux(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!dx(e.protocol))return!1;const s=e.hostname===n.hostname,i=e.port===n.port,r=ed(e.protocol)===ed(n.protocol);return s&&i&&r}function mx(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 Hs(e){const n=Ki();if(!n||typeof window>"u")return e;const s=mx(e);return!s||!ux(s.parsed)?e:(s.parsed.searchParams.set(ax,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function di(e){const n=Ki();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function hx(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function px(){typeof window>"u"||Fr||(Fr=!0,window.dispatchEvent(new CustomEvent(Dl)))}async function fx(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();hx(i)&&px()}catch{}}function gx(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Ki();const e=window.fetch.bind(window);window.fetch=function(s,i){const r=Ki(),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=>(fx(u),u))}}class bx extends Error{status;details;constructor(n,s,i){super(n),this.name="ApiRequestError",this.status=s,this.details=i}}function xx(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Vn(e){return`/api${e}`}async function D(e,n={}){const s=Vn(e),i=Ki(),r=(()=>{if(i){const g=new Headers(n.headers??{});return g.has("Content-Type")||g.set("Content-Type","application/json"),di(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")||xx(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 bx(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function YR(){return D("/health")}function vx(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 D(`/tasks${l}`)}async function Or(e,n){const i=Vn(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(i,{headers:di({"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 mh(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:b,thinkingLevel:v,summarize:x,reviewLevel:k,executionMode:M,priority:y}=e;return D(V("/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:b,thinkingLevel:v,summarize:x,reviewLevel:k,executionMode:M,priority:y})})}function Ks(e,n,s){return D(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yx(e,n,s,i,r,o,l,c){return D(V("/tasks/batch-update-models",c),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:i,validatorModelId:r,planningModelProvider:o,planningModelId:l})})}function kx(e,n,s){return D(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n})})}function jx(e,n,s){const i=new URLSearchParams,r=i.size>0?`?${i.toString()}`:"";return D(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function wx(e,n){return D(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Nx(e,n){return D(V(`/tasks/${e}/retry`,n),{method:"POST"})}function Sx(e,n){return D(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function hh(e,n){return D(V(`/tasks/${e}/pause`,n),{method:"POST"})}function Cx(e,n){return D(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Ex(e,n){return D(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Mx(e,n){return D(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function _x(e){return D(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Ax(e,n){return D(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Tx(e,n){return D(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Rx(e){return D(V("/config",e))}function ro(e){return D(V("/settings",e))}function dr(e,n){return D(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function QR(e){return D(V("/remote/settings",e))}function XR(e,n){return D(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function ZR(e){return D(V("/remote/status",e))}function e4(e,n){return D(V("/remote/provider/activate",n),{method:"POST",body:JSON.stringify({provider:e})})}function t4(e){return D(V("/remote/tunnel/start",e),{method:"POST"})}function n4(e){return D(V("/remote/tunnel/stop",e),{method:"POST"})}function s4(e){return D(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function i4(e,n){return D(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function ph(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 a4(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:i}=e,r=ph(null,s,i);return D(V(`/remote/url${r}`,n))}function r4(e="text",n={}){const{projectId:s,tokenType:i="persistent",ttlMs:r}=n,o=ph(e,i,r);return D(V(`/remote/qr${o}`,s))}function o4(e){return D(V("/memory",e))}function l4(e,n){return D(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function c4(e){return D(V("/memory/files",e))}function d4(e,n){const s=`path=${encodeURIComponent(e)}`;return D(V(`/memory/file?${s}`,n))}function u4(e,n,s){return D(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function m4(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 D(V("/memory/compact",i),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function h4(e){return D(V("/memory/insights",e))}function p4(e,n){return D(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function f4(e){return D(V("/memory/extract",e),{method:"POST"})}function g4(e){return D(V("/memory/audit",e))}function b4(e){return D(V("/memory/stats",e))}function x4(e){return D(V("/memory/backend",e))}function v4(e){return D(V("/memory/install-qmd",e),{method:"POST"})}function y4(e,n){return D(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function ra(){return D("/settings/global")}function nn(e){return D("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function k4(e){return D(V("/settings/scopes",e))}function j4(e){return D(V("/settings/pi-extensions",e))}function w4(e,n){return D(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function N4(e,n){return D(V("/settings/test-ntfy",n),{method:"POST",body:e?JSON.stringify(e):void 0})}function S4(){return D("/pi-settings")}async function C4(e){return D("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function E4(e){return D("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function M4(e){return D(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function Ua(e,n,s){const i=new FormData;i.append("file",n);const r=await fetch(Vn(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:di(),body:i}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function Ix(e,n,s){return D(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function td(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=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Vn(o),{headers:di()});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 Px(e,n,s,i){return D(V(`/tasks/${e}/comments/${n}`,i),{method:"PATCH",body:JSON.stringify({text:s})})}function $x(e,n,s){return D(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function Dx(e,n){return D(V(`/tasks/${e}/documents`,n))}function Lx(e,n,s){return D(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function _4(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 D(V(r,n))}function A4(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const i=s.toString(),r=`/files/markdown-list${i?`?${i}`:""}`;return D(V(r,e))}function nd(e,n,s,i,r){return D(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:i?.author,metadata:i?.metadata})})}function zx(e,n,s){return D(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function Fx(e,n,s){return D(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function Ox(e,n,s){return D(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ux(e,n){return D(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function Bx(e,n,s){return D(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function is(){return D("/models")}function Hx(){return D("/usage")}function qx(){return D("/providers/claude-cli/status")}function Vx(e){return D("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function Ba(){return D("/auth/status")}function Wx(e){return D("/auth/login",{method:"POST",body:JSON.stringify({provider:e})})}function Gx(e){return D("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function Kx(e,n){return D("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function Jx(e){return D("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function Yx(e,n,s,i){return D("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:i})})}function Qx(e,n,s,i){return D(V("/github/issues/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function Xx(e,n,s){return D("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function Zx(e,n,s,i){return D(V("/github/pulls/import",i),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function ev(e){return D(V("/git/remotes",e))}function tv(e){return D(V("/git/remotes/detailed",e))}function nv(e,n,s){return D(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function sv(e,n){return D(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function iv(e,n,s){return D(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function av(e,n,s){return D(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function rv(e,n,s){return D(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function ov(e,n){return D(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function lv(e,n){return(await D(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function ur(e,n,s,i){return D(V("/terminal/sessions",i),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function sd(e,n){return D(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function cv(e){return D(V("/terminal/sessions",e))}function As(e){return D(V("/git/status",e))}function dv(e,n){const s=e?`?limit=${e}`:"";return D(V(`/git/commits${s}`,n))}function Ur(e,n){return D(V(`/git/commits/${e}/diff`,n))}function uv(e){return D(V("/git/commits/ahead",e))}function mv(e,n,s,i){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return D(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,i))}function pa(e){return D(V("/git/branches",e))}function hv(e,n,s){const i=`?limit=${n}`;return D(V(`/git/branches/${encodeURIComponent(e)}/commits${i}`,s))}function pv(e){return D(V("/git/worktrees",e))}function fv(e,n,s){return D(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function gv(e,n){return D(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function id(e,n,s){const i=n?"?force=true":"";return D(V(`/git/branches/${encodeURIComponent(e)}${i}`,s),{method:"DELETE"})}function bv(e,n){return D(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function xv(e){return D(V("/git/pull",e),{method:"POST"})}function vv(e){return D(V("/git/push",e),{method:"POST"})}function mr(e){return D(V("/git/stashes",e))}function yv(e,n){return D(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function kv(e,n,s){return D(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function jv(e,n){return D(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function wv(e,n,s){const i=new URLSearchParams;return i.set("path",e),i.set("staged",String(n)),D(V(`/git/diff/file?${i.toString()}`,s))}function $i(e){return D(V("/git/changes",e))}function ad(e,n){return D(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function Nv(e,n){return D(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function rd(e,n){return D(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function Sv(e,n){return D(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function Cv(e){return D(V("/workspaces",e))}function Ev(e,n,s){const i=new URLSearchParams({workspace:e});return n&&i.set("path",n),s&&i.set("projectId",s),D(`/files?${i.toString()}`)}function Mv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}?${i.toString()}`)}function _v(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function Av(e,n,s){const i=new URLSearchParams({q:e});return n&&i.set("workspace",n),s&&i.set("projectId",s),D(`/files/search?${i.toString()}`)}function Tv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Rv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function Iv(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),D(`/files/${encodeURIComponent(n)}/delete?${i.toString()}`,{method:"POST"})}function Pv(e,n,s,i){const r=new URLSearchParams({workspace:e});return i&&r.set("projectId",i),D(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function fh(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${i.toString()}`}function $v(e,n,s){const i=new URLSearchParams({workspace:e});return s&&i.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${i.toString()}`}function Dv(e,n,s){return D(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function Lv(e,n,s,i){return D(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function zv(e,n,s){return D(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function gh(e,n,s){return D(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function Fv(e,n,s){return D(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Ov(e,n,s){return D(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function Uv(e,n,s){return D(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const Ll=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(Ll))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function Bv(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Ja(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 b=Number.parseInt(f,10);return Number.isFinite(b)?u!==null&&b<=u?!1:(u=b,!0):!0},h=()=>{if(o)return;const p=Bv(e,u),f=new EventSource(Hs(p));r=f,f.onopen=()=>{l=0,d=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},f.onmessage=b=>{const v=b;m(v)&&n.onMessage?.(v)};for(const[b,v]of Object.entries(n.events??{}))f.addEventListener(b,x=>{const k=x;m(k)&&v(k)});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(),Ll.delete(g)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return Ll.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 Ji(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 Hv(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 qv(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((i,r)=>Hv(i,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function Vv(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 ld(e){return Array.isArray(e)?e.map(od):(e.candidates??[]).map(od)}async function Wv(e){try{const n=await D(V("/dev-server/candidates",e));return ld(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await D(V("/dev-server/detect",e));return ld(s)}throw n}}function dc(e){return D(V("/dev-server/status",e)).then(Ji)}async function T4(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 D(V(`/dev-server/logs/history${i}`,n));return qv(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await dc(n);return Vv(o.logs,e)}throw r}}function Gv(e,n){const s=e.cwd??e.packagePath??".",i=e.scriptName;return D(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:i,scriptId:i,cwd:s,packagePath:e.packagePath})}).then(Ji)}function Kv(e){return D(V("/dev-server/stop",e),{method:"POST"}).then(Ji)}function Jv(e){return D(V("/dev-server/restart",e),{method:"POST"}).then(Ji)}async function Yv(e,n){const s=typeof e=="string"?{url:e}:e;try{const i=await D(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return Ji(i)}catch(i){if(i instanceof Error&&/\/dev-server\/preview-url/.test(i.message)){const r=await D(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return Ji(r)}throw i}}function R4(e){return Vn(V("/dev-server/logs/stream",e))}async function I4(e){try{return(await D(V("/devserver",e))).sessions??[]}catch{try{const n=await dc(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 P4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await dc(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 $4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await Gv({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 D4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await Kv(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 L4(e,n){try{return await D(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await Jv(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 z4(e,n,s){try{const i=await D(V(`/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 Yv({url:n},s);return{url:i.previewUrl??i.manualUrl??null,source:"manual"}}}async function F4(e){try{return(await D(V("/devserver/detect",e))).candidates??[]}catch{try{return(await Wv(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function O4(e,n){return Vn(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Ya(e,n,s=25e3){const i=setInterval(()=>{_k(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(i)}}}function Qv(e,n){return Vn(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function Xv(e,n,s,i){const r=Qv(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 Qa(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 Zv(e){return D(Qa("/routines",e))}function ey(e,n){return D(Qa("/routines",n),{method:"POST",body:JSON.stringify(e)})}function cd(e,n,s){return D(Qa(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function ty(e,n){await D(Qa(`/routines/${e}`,n),{method:"DELETE"})}function ny(e,n){return D(Qa(`/routines/${e}/trigger`,n),{method:"POST"})}function dd(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 D(`/activity${s}`)}function sy(e){const n=V("/activity",e);return D(n,{method:"DELETE"})}function oo(e){return D(V("/workflow-steps",e))}function ud(e,n){return D(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function iy(e,n,s){return D(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ay(e,n){return D(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function md(e,n){return D(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function ry(e,n){return D(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function oy(){return D("/workflow-step-templates")}function ly(e,n){return D(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function Xa(e){return D(V("/scripts",e))}function cy(e,n,s){return D(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function dy(e,n){return D(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function bh(e,n,s){return(await D(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const hr={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 xh(e){if(!(e instanceof Error))return hr.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?hr.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?hr.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:hr.NETWORK}function uy(e,n){return D(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function my(e,n,s){return D(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function hy(e,n){return Vn(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function py(e,n,s,i){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Ja(hy(e,n),{onOpen:()=>{l(),r=Ya(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 fy(e,n,s,i){return D(V("/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 vh(e,n,s){return D(V("/subtasks/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function V(e,n){if(!n)return e;const s=e.includes("?")?"&":"?";return`${e}${s}projectId=${encodeURIComponent(n)}`}function gy(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 lo(e,n){const{nodeId:s,localNodeId:i,...r}=n??{},o=gy(e,s,i);return D(o,r)}function oa(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 D(`/agents${i}`)}function yh(e,n){return D(V(`/agents/${encodeURIComponent(e)}`,n))}function by(e,n){return D(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function xy(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function U4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function B4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function H4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function q4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function V4(e,n,s){const i=`path=${encodeURIComponent(n)}`;return D(V(`/agents/${encodeURIComponent(e)}/memory/file?${i}`,s))}function W4(e,n,s,i){return D(V(`/agents/${encodeURIComponent(e)}/memory/file`,i),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function vy(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function yy(e,n){return D(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function G4(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 D(`/agents/${encodeURIComponent(e)}/runs${r}`)}function K4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function J4(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function Y4(e,n,s){const i=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return D(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:i,triggerDetail:r})})}function Q4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function ky(e){return D(V("/agents/stats",e))}function X4(e,n){return D(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function Z4(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const i=s.toString();return D(`/agents/org-tree${i?`?${i}`:""}`)}function eI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function hd(e,n,s){return D(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function tI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function nI(){return D("/agents/companies")}function sI(e,n){return D(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function iI(e,n){return D(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function aI(e,n){return D(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function rI(e){return D(V("/backups",e))}function oI(e){return D(V("/backups",e),{method:"POST"})}function lI(e,n){const s=V("/settings/export",n),i=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return D(i)}function cI(e,n,s){return D(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function pd(){return D("/projects/across-nodes")}function Pa(e,n){D("/_perf/dashboard-load",{method:"POST",body:JSON.stringify({source:e,message:n})}).catch(()=>{})}function fd(){return D("/nodes")}function jy(e){return D("/nodes",{method:"POST",body:JSON.stringify(e)})}function wy(e,n){return D(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function Ny(e){return D(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function Sy(e){const n=await D(`/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 dI(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=Ki();l&&o.set("fn_token",l);const c=o.toString(),u=`/browse-directory${c?`?${c}`:""}`;return D(u)}function Cy(e){return D("/projects",{method:"POST",body:JSON.stringify(e)})}function kh(e){return D(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function gd(e){return D(`/projects/${encodeURIComponent(e)}/health`)}function Ey(e){return D(V("/executor/stats",e))}function bd(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 D(`/activity-feed${s}`)}function My(e){return D(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function _y(e){return D(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function uI(){return D("/global-concurrency")}function mI(e){return D("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function Ay(e,n){return D(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function jh(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 D(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function Ty(e){return D(V("/missions",e))}function Ry(e,n){return D(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function wh(e,n){return D(V(`/missions/${encodeURIComponent(e)}`,n))}function Iy(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Py(e,n){return D(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function $y(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 D(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function Dy(e){return D(V("/missions/health",e))}function Ly(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function zy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Fy(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Oy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function Uy(e,n,s){return D(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function By(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Hy(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function qy(e,n,s){return D(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function Vy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Wy(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Gy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function Ky(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function Jy(e,n,s,i){return D(V(`/missions/features/${encodeURIComponent(e)}/triage`,i),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s})})}function Yy(e,n){return D(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST"})}function Ro(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function Qy(e,n,s){return D(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function Xy(e,n,s){return D(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Zy(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function ek(e,n,s){return D(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function tk(e,n){return D(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function Io(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function xd(e,n){return D(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function nk(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function vd(e,n){return D(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function sk(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 D(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function ik(e,n){return D(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function ak(e,n){return D(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function rk(e,n){return D(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function ok(e,n){return D(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function lk(e,n,s){return D(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function ck(e,n,s){return D(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function dk(e,n,s,i){return D(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function uk(e,n,s){return D(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function Nh(e,n,s){return D(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function mk(e,n,s){return D(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function hk(e,n,s,i){const r=Vn(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 Za(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function er(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function pk(e,n){return D(Za(e,"/start",n),{method:"POST"})}function fk(e,n,s,i){return D(Za(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function gk(e,n,s,i){const r=Vn(Za(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 bk(e,n,s){return D(Za(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function xk(e,n){return D(Za(e,"/skip",n),{method:"POST"})}function vk(e,n){return D(er(e,"/start",n),{method:"POST"})}function yk(e,n,s,i){return D(er(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:i})})}function kk(e,n,s,i){const r=Vn(er(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},u=Ja(r,{onOpen:()=>{c(),o=Ya(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 jk(e,n,s){return D(er(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function wk(e,n){return D(er(e,"/skip",n),{method:"POST"})}async function Nk(e,n){try{return await D(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function hI(e){return D(V("/roadmaps",e))}function pI(e,n){return D(V("/roadmaps",n),{method:"POST",body:JSON.stringify(e)})}function fI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}`,n))}function gI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function bI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function xI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function vI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function yI(e,n){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function kI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function jI(e,n,s){return D(V(`/roadmaps/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function wI(e,n){return D(V(`/roadmaps/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function NI(e,n,s){return D(V(`/roadmaps/${encodeURIComponent(e)}/milestones/reorder`,s),{method:"POST",body:JSON.stringify({orderedMilestoneIds:n})})}function SI(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/features/reorder`,s),{method:"POST",body:JSON.stringify({orderedFeatureIds:n})})}function CI(e,n,s,i){return D(V(`/roadmaps/features/${encodeURIComponent(e)}/move`,i),{method:"POST",body:JSON.stringify({targetMilestoneId:n,targetIndex:s})})}function EI(e,n){return D(V(`/roadmaps/${encodeURIComponent(e)}/handoff`,n))}function MI(e,n,s,i){return D(V(`/roadmaps/${encodeURIComponent(e)}/suggestions/milestones`,i),{method:"POST",body:JSON.stringify({goalPrompt:n.trim(),...s!==void 0?{count:s}:{}})})}function _I(e,n,s){return D(V(`/roadmaps/milestones/${encodeURIComponent(e)}/suggestions/features`,s),{method:"POST",body:JSON.stringify({...n?.prompt!==void 0?{prompt:n.prompt.trim()}:{},...n?.count!==void 0?{count:n.count}:{}})})}function Yi(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Sh(e){const n=e?`?projectId=${encodeURIComponent(e)}`:"",s=await fetch(Vn(`/ai-sessions${n}`),{headers:di()});return s.ok?(await s.json()).sessions??[]:[]}async function Js(e){const n=await fetch(Vn(`/ai-sessions/${encodeURIComponent(e)}`),{headers:di()});return n.ok?n.json():null}async function Sk(e,n){const s=await D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function Ck(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function Ek(e,n){return D(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function Mk(e){await fetch(Vn(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:di()})}function _k(e,n){return D(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function Ak(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 D(`/messages/inbox${i}`)}function Tk(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 D(`/messages/outbox${i}`)}function Ch(e){return D(V("/messages/unread-count",e))}function Rk(e,n){return D(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function Ik(e,n){return D(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function Pk(e){return D(V("/messages/read-all",e),{method:"POST"})}function $k(e,n){return D(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Dk(e,n,s){const i=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return D(V(i,s))}function Lk(e,n){return D(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function AI(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 D(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function TI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function RI(e,n,s){const i=new URLSearchParams;s&&i.set("projectId",s);const r=i.size>0?`?${i.toString()}`:"";return D(`/agents/${encodeURIComponent(e)}/performance${r}`)}function II(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 D(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function PI(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function $I(e,n){return D(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function DI(e,n,s){return D(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function LI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function zI(e,n){return D(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function FI(e){return D(V("/plugins",e))}async function OI(e,n){return D(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function UI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function BI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function HI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function qI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function VI(e,n,s){return D(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function WI(e,n){return D(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function zk(e){return D(V("/plugins/ui-slots",e))}async function GI(e){return(await D(V("/skills/discovered",e))).skills}async function KI(e,n,s){return D(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function JI(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 D(V(`/skills/catalog${r}`,s))}async function YI(e,n){return(await D(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function QI(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const i=s.toString();return D(`/chat/sessions${i?`?${i}`:""}`)}async function Fk(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 D(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function Ok(e,n){return D(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function XI(e,n,s){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function ZI(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function yd(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 D(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Uk(e,n){return D(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function Bk(e,n,s,i,r){const o=Vn(V(`/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:di({"Content-Type":"application/json"}),body:JSON.stringify({content:n}),signal:l.signal});if(!d.ok){const v=await d.text();let x=`Request failed: ${d.status}`;try{x=JSON.parse(v).error||x}catch{}s.onError?.(x);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 b=(v,x=!1)=>{g+=v;const k=g.split(`
|
|
573
573
|
`);g=k.pop()||"",x&&g.length>0&&(k.push(g),g="");for(const M of k){const y=M.endsWith("\r")?M.slice(0,-1):M;if(y.startsWith("event:"))p=y.slice(6).trim();else if(y.startsWith("data:")){const R=y.slice(5);f.push(R.startsWith(" ")?R.slice(1):R)}else if(y===""){const R=f.join(`
|
|
574
574
|
`);u(p,R),p="",f=[]}}if(x&&p&&f.length>0){const M=f.join(`
|
|
575
|
-
`);u(p,M),p="",f=[]}};for(;;){const{done:v,value:x}=await m.read();if(v){b(h.decode(),!0);break}b(h.decode(x,{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 eP(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 D(V(`/insights${i}`,n))}function tP(e,n){return D(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function nP(e="manual",n,s){return D(V("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function sP(e){return D(V("/insights/runs",e))}function iP(e,n){return D(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function Hk({onOpenScripts:e,onRunScript:n,projectId:s}){const[i,r]=a.useState(!1),[o,l]=a.useState({}),[c,u]=a.useState(!1),[d,m]=a.useState(-1),[h,g]=a.useState(null),p=a.useRef(null),f=a.useRef(null),b=a.useRef(null),v=a.useCallback(()=>{const P=window.visualViewport;return P&&P.width>0&&P.height>0?{width:P.width,height:P.height,offsetTop:P.offsetTop,offsetLeft:P.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),x=a.useCallback(()=>{const P=f.current;if(!P)return;const T=P.getBoundingClientRect(),_=b.current,{width:L,height:G,offsetTop:$,offsetLeft:I}=v(),w=16,q=16,W=6,B=_?.offsetWidth||Math.max(T.width,260),A=Math.min(B,Math.max(L-w*2,160)),z=_?.offsetHeight||280,X=Math.min(z,Math.max(G-q*2,160)),E=T.top-$,U=T.bottom-$,pe=T.left-I,ie=G-U,re=E,F=ie<X&&re>ie,ce=Math.min(Math.max(pe,w),L-w-A)+I,ae=F?Math.max(q+$,E-X-W+$):Math.min(U+W+$,G+$-q-X);g({top:ae,left:ce,width:A})},[v]),k=a.useMemo(()=>Object.entries(o).sort(([P],[T])=>P.localeCompare(T)),[o]),M=k.length>0,y=k.length+(M?1:0);a.useEffect(()=>{if(!i)return;let P=!1;return u(!0),Xa(s).then(T=>{P||l(T)}).catch(()=>{P||l({})}).finally(()=>{P||u(!1)}),()=>{P=!0}},[i,s]),a.useEffect(()=>{if(!i)return;const P=T=>{p.current&&!p.current.contains(T.target)&&f.current&&!f.current.contains(T.target)&&r(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[i]),a.useEffect(()=>{if(!i)return;const P=T=>{T.key==="Escape"&&(r(!1),f.current?.focus())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[i]),a.useEffect(()=>{if(i){m(-1);const P=window.setTimeout(()=>b.current?.focus(),0);return()=>window.clearTimeout(P)}g(null)},[i]),a.useEffect(()=>{if(!i)return;const P=requestAnimationFrame(()=>{x()});return()=>cancelAnimationFrame(P)},[i,c,k.length,M,x]),a.useEffect(()=>{if(!i)return;const P=()=>x();window.addEventListener("resize",P),window.addEventListener("scroll",P,!0);const T=window.visualViewport;return T&&(T.addEventListener("resize",P),T.addEventListener("scroll",P)),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0),T&&(T.removeEventListener("resize",P),T.removeEventListener("scroll",P))}},[i,x]);const R=a.useCallback(P=>{switch(P.key){case"ArrowDown":P.preventDefault(),m(T=>T<y-1?T+1:0);break;case"ArrowUp":P.preventDefault(),m(T=>T>0?T-1:y-1);break;case"Enter":if(P.preventDefault(),d>=0)if(d<k.length){const[T,_]=k[d];C(T,_)}else M&&d===k.length&&S();break;case"Home":P.preventDefault(),m(0);break;case"End":P.preventDefault(),m(y-1);break}},[d,y,k,M]),j=a.useCallback(()=>{r(P=>!P)},[]),C=a.useCallback((P,T)=>{n(P,T),r(!1)},[n]),S=a.useCallback(()=>{e(),r(!1)},[e]);return t.jsxs("div",{className:"quick-scripts-dropdown",ref:p,children:[t.jsxs("button",{ref:f,className:`btn-icon quick-scripts-dropdown__trigger ${i?"open btn-icon--active":""}`,onClick:j,"aria-expanded":i,"aria-haspopup":"listbox","aria-label":"Quick scripts","data-testid":"scripts-btn",title:"Scripts",children:[t.jsx(Bs,{size:16}),t.jsx(zt,{size:14,className:`quick-scripts-dropdown__trigger-chevron ${i?"rotate":""}`})]}),i&&t.jsx("div",{ref:b,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:R,"data-testid":"quick-scripts-dropdown",style:h?{position:"fixed",top:`${h.top}px`,left:`${h.left}px`,width:`${h.width}px`,right:"auto"}:void 0,children:c?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):k.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(Bs,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:S,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:k.map(([P,T],_)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${d===_?"highlighted":""}`,onClick:()=>C(P,T),role:"option","aria-selected":d===_,"data-testid":`quick-script-item-${P}`,children:[t.jsx(rn,{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:P}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:T,children:T.length>50?`${T.slice(0,50)}...`:T})]})]},P))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${M&&d===k.length?"highlighted":""}`,onClick:S,"data-testid":"quick-scripts-manage",children:[t.jsx(Oa,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})}function qk(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 Vk({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}=qk(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 kd=new Map,Wk=6e4;function Eh(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=kd.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const b=await zk(e);if(h||u.current)return;kd.set(m,{slots:b,expiresAt:Date.now()+Wk}),s(b),c.current=!0}catch(b){if(h||u.current)return;l(b instanceof Error?b.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return 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 co({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Eh(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(ao,{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 Gk(){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 tr(){const[e,n]=a.useState(Gk);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 Mh={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Kk({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(zt,{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=Mh[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(xn,{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 jd({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 Jk({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenMailbox:c,mailboxUnreadCount:u=0,onOpenSchedules:d,onOpenGitManager:m,onOpenNodes:h,showNodesButton:g,onOpenWorkflowSteps:p,onOpenScripts:f,onRunScript:b,onToggleTerminal:v,onOpenFiles:x,filesOpen:k,globalPaused:M,enginePaused:y,onToggleGlobalPause:R,onToggleEnginePause:j,view:C="board",onChangeView:S,showSkillsTab:P,showAgentsTab:T,searchQuery:_="",onSearchChange:L,projects:G=[],currentProject:$,onSelectProject:I,onViewAllProjects:w,projectId:q,isElectron:W=!1,mobileNavEnabled:B,availableNodes:A=[],currentNode:z,onSelectNode:X,isRemote:E=!1,experimentalFeatures:U}){const pe=tr(),ie=pe==="mobile",F=ie||pe==="tablet",ce=ie&&B,[ae,Q]=a.useState(!1),[de,Te]=a.useState(!1),[fe,Se]=a.useState(!1),[te,we]=a.useState(!1),[Pe,We]=a.useState(!1),[Ke,Ne]=a.useState(!1),[_e,Oe]=a.useState(!1),[ye,De]=a.useState(!1),[se,J]=a.useState(!1),[me,ee]=a.useState(!1),[he,le]=a.useState({}),[Ie,Ze]=a.useState(!1),at=a.useRef(null),oe=a.useRef(null),Z=a.useRef(null),ue=a.useRef(null),Ce=a.useRef(null),$e=a.useRef(null),ve=a.useRef(!1),Ge=a.useRef(null),je=a.useRef(null),Ue=a.useRef(null),He=a.useRef(null),ge=a.useRef(null),Fe=a.useMemo(()=>A.filter(Le=>Le.type==="remote"),[A]),be=Fe.length>0,Je=a.useMemo(()=>Object.entries(he).sort(([Le],[gt])=>Le.localeCompare(gt)),[he]),st=a.useMemo(()=>!!(U?.insights||U?.roadmap||P||U?.memoryView||U?.devServerView),[U,P]);a.useEffect(()=>{ve.current=Pe},[Pe]),a.useEffect(()=>{if(!Pe||!F)return;let Le=!1;return Ze(!0),Xa(q).then(gt=>{Le||le(gt)}).catch(()=>{Le||le({})}).finally(()=>{Le||Ze(!1)}),()=>{Le=!0}},[Pe,F,q]);const dt=ae||_.length>0,Tt=(de||_.length>0)&&!fe,$t=(C==="board"||C==="list")&&!ie&&L&&!fe&&_.length===0,Dt=(C==="board"||C==="list")&&!ie&&L;a.useEffect(()=>{_===""&&Se(!1)},[_]),a.useEffect(()=>{if(!te)return;const Le=gt=>{oe.current&&!oe.current.contains(gt.target)&&at.current&&!at.current.contains(gt.target)&&we(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[te]),a.useEffect(()=>{if(!se)return;const Le=gt=>{ue.current&&!ue.current.contains(gt.target)&&Z.current&&!Z.current.contains(gt.target)&&J(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[se]),a.useEffect(()=>{if(!Ke)return;const Le=gt=>{Ge.current&&!Ge.current.contains(gt.target)&&Ne(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[Ke]),a.useEffect(()=>{const Le=gt=>{if(gt.key==="Escape"){if(De(!1),J(!1),ve.current){We(!1);return}we(!1),Q(!1),Ne(!1),Oe(!1)}};return document.addEventListener("keydown",Le),()=>document.removeEventListener("keydown",Le)},[]),a.useEffect(()=>{if(!_e)return;const Le=gt=>{je.current&&!je.current.contains(gt.target)&&Oe(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[_e]),a.useEffect(()=>{if(!me)return;const Le=gt=>{ge.current&&!ge.current.contains(gt.target)&&ee(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[me]),a.useEffect(()=>{if(!me)return;const Le=gt=>{gt.key==="Escape"&&ee(!1)};return document.addEventListener("keydown",Le),()=>document.removeEventListener("keydown",Le)},[me]),a.useEffect(()=>{if(!ye)return;const Le=gt=>{Ue.current&&!Ue.current.contains(gt.target)&&He.current&&!He.current.contains(gt.target)&&De(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[ye]);const Bt=a.useCallback(()=>{Q(Le=>!Le)},[]),qt=a.useCallback(()=>{Te(!0),Se(!1)},[]),Lt=a.useCallback(()=>{Te(!1),Se(!0),L&&L("")},[L]),Ct=a.useCallback(()=>{we(Le=>!Le)},[]),xt=a.useCallback(Le=>{Le&&Le(),we(!1),We(!1)},[]),Et=a.useCallback(()=>{Q(!1),L&&L("")},[L]);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"})]}),ie&&G.length>=1&&I&&t.jsxs("div",{className:"mobile-project-switch",ref:je,children:[t.jsx("button",{className:`mobile-project-switch-trigger${_e?" mobile-project-switch-trigger--open":""}`,onClick:()=>Oe(Le=>!Le),title:"Switch project","aria-label":"Switch project","aria-expanded":_e,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(zt,{size:14,className:`mobile-project-switch-chevron${_e?" mobile-project-switch-chevron--open":""}`})}),_e&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:G.map(Le=>{const gt=$?.id===Le.id,ut=Mh[Le.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${gt?" mobile-project-switch-item--current":""}`,onClick:()=>{I(Le),Oe(!1)},role:"option","aria-selected":gt,"data-testid":`mobile-project-switch-item-${Le.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:ut||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:Le.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Le.path.split("/").slice(-2).join("/")})]}),gt&&t.jsx(xn,{size:14,className:"mobile-project-switch-check"})]},Le.id)})})]}),!F&&G.length>=1&&w&&t.jsx(Kk,{projects:G,currentProject:$??null,onViewAll:w,onSelectProject:I}),be&&t.jsxs("div",{className:`header-node-selector${ie?" header-node-selector--mobile":""}`,ref:ie?void 0:Ge,children:[t.jsx(Vk,{node:z??null,showDetails:!ie}),!ie&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Ke?" node-selector-trigger--open":""}`,onClick:()=>Ne(Le=>!Le),title:"Switch node","aria-label":"Switch node","aria-expanded":Ke,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(en,{size:12,className:`node-selector-chevron${Ke?" node-selector-chevron--open":""}`})}),Ke&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${E?"":" node-selector-option--active"}`,onClick:()=>{X?.(null),Ne(!1)},role:"option","aria-selected":!E,"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"})]}),Fe.map(Le=>t.jsxs("button",{className:`node-selector-option${z?.id===Le.id?" node-selector-option--active":""}`,onClick:()=>{X?.(Le),Ne(!1)},role:"option","aria-selected":z?.id===Le.id,"data-testid":`node-option-${Le.id}`,children:[t.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${Le.status}`}),t.jsx("span",{className:"node-selector-option-label",children:Le.name}),t.jsx("span",{className:"node-selector-option-status",children:Le.status})]},Le.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ce&&S&&(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:()=>S("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>S("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Tl,{size:16})})]}),L&&ie&&(ce||C==="board"||C==="list")&&!dt&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Bt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Bi,{size:16})}),$t&&t.jsx("button",{className:"btn-icon",onClick:qt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Bi,{size:16})}),ie&&ce&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ss,{size:16})}),!ce&&S&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>S("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>S("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(Tl,{size:16})}),T&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>S("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(an,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>S("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(ns,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>S("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(li,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>S("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Ni,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>S("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(Gi,{size:16})}),st&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:He,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)?" active":""}`,onClick:()=>De(Le=>!Le),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":ye,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(zt,{size:12})}),ye&&t.jsxs("div",{ref:Ue,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[U?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{S("insights"),De(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Dn,{size:14}),t.jsx("span",{children:"Insights"})]}),U?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{S("roadmaps"),De(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(Rl,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),P&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{S("skills"),De(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(vn,{size:14}),t.jsx("span",{children:"Skills"})]}),U?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{S("memory"),De(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Pr,{size:14}),t.jsx("span",{children:"Memory"})]}),U?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{S("devserver"),De(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(rh,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]})]})]})]}),!F&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ss,{size:16})}),!F&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Fa,{size:16})}),!F&&!W&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(jd,{size:16})}),!F&&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(Us,{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})]}),!F&&t.jsx("button",{className:"btn-icon btn-icon--terminal",onClick:v,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Bs,{size:16})}),!F&&x&&t.jsx("button",{className:`btn-icon${k?" btn-icon--active":""}`,onClick:x,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(jn,{size:16})}),!F&&m&&t.jsx("button",{className:"btn-icon",onClick:m,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Os,{size:16})}),!F&&p&&t.jsx("button",{className:"btn-icon",onClick:p,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Pl,{size:16})}),!F&&f&&b&&t.jsx(Hk,{onOpenScripts:f,onRunScript:b,projectId:q}),!F&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Z,className:"btn-icon",onClick:()=>J(Le=>!Le),title:"More actions","aria-label":"More actions","aria-expanded":se,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(_l,{size:16})}),se&&t.jsxs("div",{ref:ue,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[h&&g!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{h(),J(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Lr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{xt(d),J(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:ge,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${M?" btn-icon--stopped":""}`,onClick:R,title:M?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:M?t.jsx(rn,{size:16}):t.jsx(ls,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${me?" btn-icon--active":""}`,onClick:()=>ee(Le=>!Le),title:"Engine options","aria-haspopup":"menu","aria-expanded":me,"data-testid":"engine-control-chevron-btn",children:t.jsx(zt,{size:12})}),me&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${y?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{j?.(),ee(!1)},role:"menuitem",title:y?"Resume scheduling":"Pause triage",disabled:!!M,"data-testid":"engine-control-pause-triage-btn",children:[y?t.jsx(rn,{size:14}):t.jsx(Fs,{size:14}),t.jsx("span",{children:y?"Resume scheduling":"Pause triage"})]})})]}),!F&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Oa,{size:16})}),t.jsx(co,{slotId:"header-action",projectId:q}),F&&!ce&&t.jsx("button",{ref:at,className:"btn-icon compact-overflow-trigger",onClick:Ct,title:"More header actions","aria-label":"More header actions","aria-expanded":te,"aria-haspopup":"menu",children:t.jsx(_l,{size:16})}),F&&!ce&&te&&t.jsxs("div",{ref:oe,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[G.length>=1&&w&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(w),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(ih,{size:16}),t.jsx("span",{children:"Projects"})]}),x&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(x),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(jn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>xt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Us,{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"})]}),m&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(m),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Os,{size:16}),t.jsx("span",{children:"Git Manager"})]}),h&&g!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(h),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Lr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!W&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(n),role:"menuitem",children:[t.jsx(jd,{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:()=>xt(v),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Bs,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>We(Le=>!Le),role:"menuitem","aria-expanded":Pe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(en,{size:14,className:`mobile-overflow-chevron${Pe?" mobile-overflow-chevron--open":""}`})})]}),Pe&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Ie?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(it,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Je.length>0?t.jsxs(t.Fragment,{children:[Je.map(([Le,gt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(Le,gt),we(!1),We(!1)},role:"menuitem","data-testid":`overflow-script-item-${Le}`,children:[t.jsx(rn,{size:14}),t.jsx("span",{children:Le})]},Le)),f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>xt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>xt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(d),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(ji,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Fa,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),c&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(c),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Gi,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(o),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ss,{size:16}),t.jsx("span",{children:"View Usage"})]}),p&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(p),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Pl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(e),role:"menuitem",children:[t.jsx(Oa,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Dt&&Tt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Bi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:_,onChange:Le=>L(Le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Lt,"aria-label":"Close search",children:t.jsx(Pt,{size:14})})]})}),L&&ie&&dt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:Ce,className:"header-search mobile-search-expanded",children:[t.jsx(Bi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:$e,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:_,onChange:Le=>L(Le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Et,"aria-label":"Close search",children:t.jsx(Pt,{size:14})})]})})]})}const Yk={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"],ntfyDashboardHost:void 0,defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!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},Qk={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",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:"",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,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,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:{}},Xk=Object.freeze(Object.keys(Yk)),Zk=Object.freeze(Object.keys(Qk));function aP(e){return Xk.includes(e)}function rP(e){return Zk.includes(e)}function xe(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const oP=["off","minimal","low","medium","high"],ki=["triage","todo","in-progress","in-review","done","archived"],uc=["low","normal","high","urgent"],cs="normal",ej=["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"],Pn={triage:"Triage",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},tj={triage:"Raw ideas — AI will specify 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"},zl={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 nj(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 sj(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 ij(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 _h({prInfo:e,issueInfo:n,onIssueRefresh:s}){const i=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:i,children:[t.jsx(es,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${ij(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(eo,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function pr(e,n){return`${e??"default"}:${n}`}class aj{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=pr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=pr(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=pr(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(Hs(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=pr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:wd(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:wd(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 gi=new aj;let rj=0;function wd(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ah(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${rj++}`);const s=a.useSyncExternalStore(o=>gi.subscribe(o),()=>gi.getSnapshot(),()=>gi.getSnapshot()),i=a.useCallback(o=>{gi.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{gi.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{gi.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{gi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function Br(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function oj({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Ah(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=Br(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=Br(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(_h,{prInfo:h,issueInfo:g})}const lj=a.memo(oj);lj.displayName="TaskCardBadge";const cj={sm:16,md:20,lg:24};function dj({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 Nd({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 Sd({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 uj({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 mj({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 hj({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 Po({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 Cd({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 Ed({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 pj({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 fj({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 Md({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 _d({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 gj={anthropic:{component:dj,color:"var(--provider-anthropic)"},"claude-cli":{component:_d,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:_d,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:Nd,color:"var(--provider-openai)"},"openai-codex":{component:Nd,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Sd,color:"var(--provider-gemini)"},gemini:{component:Sd,color:"var(--provider-gemini)"},ollama:{component:uj,color:"var(--text)"},github:{component:Md,color:"var(--text)"},"github-copilot":{component:Md,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:fj,color:"var(--provider-openrouter)"},minimax:{component:mj,color:"var(--provider-minimax)"},zai:{component:hj,color:"var(--provider-zai)"},kimi:{component:Po,color:"var(--provider-kimi)"},moonshot:{component:Po,color:"var(--provider-kimi)"},"kimi-coding":{component:Po,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:Cd,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:Cd,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:Ed,color:"var(--text)"},grok:{component:Ed,color:"var(--text)",label:"xAI"},opencode:{component:pj,color:"var(--provider-opencode)"}};function Mn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=gj[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=cj[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(ug,{size:c})})}const ks={data:new Map,pendingPromise:null,lastFetchTime:null},bj=5e3;function Tr(e,n){return n?`${n}::${e}`:e}function xj(e,n){const s=ks.data.get(Tr(e,n));if(!(!s||Date.now()-s.timestamp>bj))return s}function vj(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 lv(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=xe(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=ks.data.get(Tr(g,e));return p&&p.timestamp>d})&&ks.lastFetchTime&&ks.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),ks.pendingPromise){s(!0);try{await ks.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);ks.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,b]of Object.entries(g))ks.data.set(Tr(f,e),{result:b,timestamp:p});ks.lastFetchTime=p}catch{}finally{ks.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>ks.data.get(Tr(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ks.lastFetchTime,getBatchData:l}}const Fl=new Map,yj=3e4;function Th(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function kj(e,n,s,i){const r=Th(e,n,s,i),o=Fl.get(r);return o?Date.now()>o.expiresAt?(Fl.delete(r),null):o.stats:null}function jj(e,n,s,i,r){const o=Th(e,n,s,i);Fl.set(o,{stats:r,expiresAt:Date.now()+yj})}function wj(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 b=f?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function k(y=!1){if(!y){const R=kj(e,i,b,v);if(R){x||(m(R),g(!1));return}}g(!0);try{const R=await jh(e,b,i);x||(m(R.stats),jj(e,i,b,v,R.stats))}catch{x||m(null)}finally{x||g(!1)}}k();let M;return u&&f&&(M=setInterval(()=>{k(!0)},u)),()=>{x=!0,M&&clearInterval(M)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const Nj=new Set(["failed","stuck-killed"]);function Hr(e,n,s){if(e.column!=="in-progress"||e.status&&Nj.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Sj(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Cj(e){return e==="done"||e==="skipped"}function Ej(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Rh(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:Ej(u,d,n),status:d?Sj(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>Cj(u.status)).length;return{total:l,completed:c,items:o}}const Ol=new Map;async function Mj(e,n){const s=Ol.get(e);if(s)return s;try{const i=await wh(e,n);return Ol.set(e,i.title),i.title}catch{return e}}const Ad=12;function _j(e){return e.length<=Ad?e:e.slice(0,Ad-3)+"..."}const Ul=new Map;async function Aj(e,n){const s=Ul.get(e);if(s)return s;try{const i=await yh(e,n);return Ul.set(e,i.name),i.name}catch{return e}}function Tj(e){return typeof e=="string"&&uc.includes(e)?e:cs}function Rj(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const Ij=new Set(["triage","todo"]),Td=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Pj={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},$j=new Set(["in-progress","done"]),Dj=3e4;function mc(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Rd(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=mc(n);if(s==null)return null;const i=Date.now();return s>i?null:s}function Lj(e){const n=mc(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function zj(e,n){return[e.createdAt].map(mc).filter(r=>r!=null).find(r=>r<=n)??null}function Id(e){if(!Number.isFinite(e)||e<0)return"";const n=Math.floor(e/6e4);if(n<1)return"<1m";if(n<60)return`${n}m`;const s=Math.floor(n/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Pd(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),i=Object.keys(n);return s.length!==i.length?!1:s.every(r=>e[r]===n[r])}function Fj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Oj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function Uj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function Bj(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Hj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.workflowStepId===r.workflowStepId&&s.workflowStepName===r.workflowStepName&&s.phase===r.phase&&s.status===r.status&&s.output===r.output&&s.startedAt===r.startedAt&&s.completedAt===r.completedAt:!1})}function qj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function Vj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function Wj(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&s.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&qj(s.attachments,i.attachments)&&Vj(s.comments,i.comments)&&Oj(s.dependencies,i.dependencies)&&Fj(s.steps,i.steps)&&Uj(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&Hj(s.workflowStepResults,i.workflowStepResults)&&Pd(s.prInfo,i.prInfo)&&Pd(s.issueInfo,i.issueInfo)}function Gj({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:h,onOpenMission:g,onMoveTask:p,lastFetchTimeMs:f,workflowStepNameLookup:b}){const[v,x]=a.useState(!1),[k,M]=a.useState(!1),[y,R]=a.useState(!1),[j,C]=a.useState(e.description||""),[S,P]=a.useState(!1),[T,_]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(N=>N.status==="done"||N.status==="skipped")),[L,G]=a.useState(null),[$,I]=a.useState(null),[w,q]=a.useState(!1),[W,B]=a.useState(()=>Date.now()),A=a.useRef(null),z=a.useRef(!1),X=a.useRef(null),E=a.useRef(null),[U,pe]=a.useState(!1),{badgeUpdates:ie,subscribeToBadge:re,unsubscribeFromBadge:F}=Ah(n),ce=a.useRef(null),ae=a.useRef(!1),Q=a.useCallback(N=>N instanceof Element?!!N.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{C(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!w)return;const N=H=>{E.current&&!E.current.contains(H.target)&&q(!1)};return document.addEventListener("click",N),()=>document.removeEventListener("click",N)},[w]),a.useEffect(()=>{if(!e.missionId){G(null);return}const N=Ol.get(e.missionId);if(N){G(N);return}let H=!1;return Mj(e.missionId,n).then(Ae=>{H||G(Ae)}),()=>{H=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){I(null);return}const N=Ul.get(e.assignedAgentId);if(N){I(N);return}I(null);let H=!1;return Aj(e.assignedAgentId,n).then(Ae=>{H||I(Ae)}),()=>{H=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(y&&A.current){const N=A.current;N.focus(),N.style.height="auto",N.style.height=N.scrollHeight+"px"}},[y]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){pe(!0);return}const N=X.current;if(!N)return;const H=new IntersectionObserver(([Ae])=>{pe(Ae?.isIntersecting??!0)},{rootMargin:"200px"});return H.observe(N),()=>H.disconnect()},[y,e.id]);const de=a.useCallback(N=>{N.dataTransfer.setData("text/plain",e.id),N.dataTransfer.effectAllowed="move",x(!0)},[e.id]),Te=a.useCallback(()=>{x(!1)},[]),fe=a.useCallback(N=>N.dataTransfer.types.includes("Files"),[]),Se=a.useCallback(N=>{fe(N)&&(N.preventDefault(),N.stopPropagation(),N.dataTransfer.dropEffect="copy",M(!0))},[fe]),te=a.useCallback(N=>{fe(N)&&(N.preventDefault(),N.stopPropagation(),M(!1))},[fe]),we=a.useCallback(async N=>{if(!fe(N))return;N.preventDefault(),N.stopPropagation(),M(!1);const H=Array.from(N.dataTransfer.files);for(const Ae of H)try{await Ua(e.id,Ae,n),r(`Attached ${Ae.name} to ${e.id}`,"success")}catch(ot){r(`Failed to attach ${Ae.name}: ${xe(ot)}`,"error")}},[e.id,fe,r]),Pe=a.useCallback(()=>{y||i(e)},[e,i,y]),We=a.useCallback(N=>{if(z.current){z.current=!1;return}Q(N.target)||Pe()},[Pe,Q]),Ke=a.useCallback(N=>{const H=N.touches[0];H&&(ce.current={x:H.clientX,y:H.clientY,time:Date.now()},ae.current=!1)},[]),Ne=a.useCallback(N=>{if(!ce.current)return;const H=N.touches[0];if(!H)return;const Ae=Math.abs(H.clientX-ce.current.x),ot=Math.abs(H.clientY-ce.current.y);(Ae>$d||ot>$d)&&(ae.current=!0)},[]),_e=a.useCallback(N=>{if(Q(N.target)||!ce.current)return;const Ae=Date.now()-ce.current.time<Kj,ot=!ae.current;Ae&&ot&&(z.current=!0,Pe()),ce.current=null,ae.current=!1},[Pe,Q]),Oe=a.useCallback(async(N,H)=>{N.stopPropagation();try{const Ae=await Or(H,n);i(Ae)}catch{r(`Failed to load dependency ${H}`,"error")}},[i,r]),ye=e.status==="failed",De=e.paused===!0,se=Tj(e.priority),J=se!==cs,me=Hr(e,h,f),ee=e.column==="triage"&&e.status==="awaiting-approval",he=e.column==="archived",le=!o&&!s&&!ye&&!De&&!me&&!ee&&(e.column==="in-progress"||Td.has(e.status)),Ie=!s&&!De&&!y&&!he,Ze=Ij.has(e.column)&&!le&&!De&&!s&&l,at=!!(e.prInfo||e.issueInfo),oe=!!(e.assignedAgentId&&$===null),Z=a.useMemo(()=>{const N=[];return e.modelProvider&&N.push(e.modelProvider),e.validatorModelProvider&&!N.includes(e.validatorModelProvider)&&N.push(e.validatorModelProvider),e.planningModelProvider&&!N.includes(e.planningModelProvider)&&N.push(e.planningModelProvider),N},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),ue=a.useMemo(()=>Rh(e,b),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,b]),Ce=ue.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"||Rd(e)==null)return;B(Date.now());const H=window.setInterval(()=>{B(Date.now())},Dj);return()=>window.clearInterval(H)},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt]);const $e=a.useMemo(()=>{if(!$j.has(e.column))return null;if(e.column==="in-progress"){const kt=Rd(e);if(kt==null)return null;const Ot=Id(W-kt);return Ot?{label:Ot,title:`In progress since ${new Date(kt).toLocaleString()}`,ariaLabel:`Elapsed time ${Ot}. In progress since ${new Date(kt).toLocaleString()}`}:null}const N=Lj(e);if(N==null)return null;const H=zj(e,N);if(H==null)return null;const Ae=Id(N-H);if(!Ae)return null;const ot=new Date(N).toLocaleString();return{label:Ae,title:`Processing took ${Ae}. Completed ${ot}`,ariaLabel:`Completed processing duration ${Ae}. Completed ${ot}`}},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt,W]);a.useEffect(()=>{if(!at||!U){F(e.id);return}return re(e.id),()=>{F(e.id)}},[at,U,re,e.id,F]);const ve=ie.get(`${n??"default"}:${e.id}`),Ge=e.column==="in-progress"||e.column==="in-review",je=a.useMemo(()=>e.steps.map(N=>`${N.name}:${N.status}`).join("|"),[e.steps]),{stats:Ue}=wj(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:U,worktree:e.worktree,stepVersion:Ge?je:void 0,pollIntervalMs:Ge?3e4:void 0}),He=a.useMemo(()=>xj(e.id,n),[e.id,n]),ge=a.useMemo(()=>{const N=ve?.prInfo,H=ve?.timestamp,Ae=He?.result?.prInfo,ot=He?.timestamp?new Date(He.timestamp).toISOString():void 0,kt=e.prInfo,Ot=e.prInfo?.lastCheckedAt??e.updatedAt;let sn=Br(N,H,kt,Ot);const Rt=H&&H>=Ot?H:Ot;return Ae&&ot&&(!Rt||ot>Rt)&&(sn=Ae),sn},[ve,He,e.prInfo,e.updatedAt]),Fe=a.useMemo(()=>{const N=ve?.issueInfo,H=ve?.timestamp,Ae=He?.result?.issueInfo,ot=He?.timestamp?new Date(He.timestamp).toISOString():void 0,kt=e.issueInfo,Ot=e.issueInfo?.lastCheckedAt??e.updatedAt;let sn=Br(N,H,kt,Ot);const Rt=H&&H>=Ot?H:Ot;return Ae&&ot&&(!Rt||ot>Rt)&&(sn=Ae),sn},[ve,He,e.issueInfo,e.updatedAt]),be=a.useCallback(N=>{N?.stopPropagation(),!(!Ze||S)&&(R(!0),C(e.description||""))},[Ze,S,e.description]),Je=a.useCallback(()=>{R(!1),C(e.description||"")},[e.description]),st=a.useCallback(()=>j!==(e.description||""),[j,e.description]),dt=a.useCallback(async()=>{if(!(!l||S)){if(!st()){Je();return}P(!0);try{await l(e.id,{description:j.trim()||void 0}),r(`Updated ${e.id}`,"success"),R(!1)}catch(N){r(`Failed to update ${e.id}: ${xe(N)}`,"error")}finally{P(!1)}}},[l,e.id,j,S,st,Je,r]),Tt=a.useCallback(N=>{N.key==="Enter"&&!N.shiftKey?(N.preventDefault(),dt()):N.key==="Escape"&&(N.preventDefault(),Je())},[dt,Je]),$t=a.useCallback(()=>{setTimeout(()=>{const N=document.activeElement;N===A.current||N?.closest(".card-editing-content")||(st()?dt():Je())},0)},[st,dt,Je]),Dt=a.useCallback(N=>{Ze&&(N.stopPropagation(),be(N))},[Ze,be]),Bt=a.useCallback(N=>{N.stopPropagation(),be(N)},[be]),qt=a.useCallback(N=>{C(N.target.value);const H=N.target;H.style.height="auto",H.style.height=H.scrollHeight+"px"},[]),Lt=a.useCallback(N=>{N.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(H=>{r(`Failed to archive ${e.id}: ${xe(H)}`,"error")})},[r,c,e.id]),Ct=a.useCallback(N=>{N.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(H=>{r(`Failed to unarchive ${e.id}: ${xe(H)}`,"error")})},[r,u,e.id]),xt=a.useCallback(N=>{N.stopPropagation(),d&&window.confirm(`Delete ${e.id}?`)&&d(e.id).then(()=>{r(`Deleted ${e.id}`,"success")}).catch(H=>{const Ae=Bj(H);if(!Ae||Ae.dependentIds.length===0){r(`Failed to delete ${e.id}: ${xe(H)}`,"error");return}const ot=Ae.dependentIds.join(", ");window.confirm(`${e.id} is a dependency of ${ot}.
|
|
575
|
+
`);u(p,M),p="",f=[]}};for(;;){const{done:v,value:x}=await m.read();if(v){b(h.decode(),!0);break}b(h.decode(x,{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 eP(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 D(V(`/insights${i}`,n))}function tP(e,n){return D(V(`/insights/${encodeURIComponent(e)}/dismiss`,n),{method:"POST"})}function nP(e="manual",n,s){return D(V("/insights/run",s),{method:"POST",body:JSON.stringify({trigger:e,inputMetadata:n})})}function sP(e){return D(V("/insights/runs",e))}function iP(e,n){return D(V(`/insights/${encodeURIComponent(e)}/create-task`,n),{method:"POST"})}function Hk({onOpenScripts:e,onRunScript:n,projectId:s}){const[i,r]=a.useState(!1),[o,l]=a.useState({}),[c,u]=a.useState(!1),[d,m]=a.useState(-1),[h,g]=a.useState(null),p=a.useRef(null),f=a.useRef(null),b=a.useRef(null),v=a.useCallback(()=>{const P=window.visualViewport;return P&&P.width>0&&P.height>0?{width:P.width,height:P.height,offsetTop:P.offsetTop,offsetLeft:P.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),x=a.useCallback(()=>{const P=f.current;if(!P)return;const T=P.getBoundingClientRect(),_=b.current,{width:L,height:G,offsetTop:$,offsetLeft:I}=v(),w=16,q=16,W=6,B=_?.offsetWidth||Math.max(T.width,260),A=Math.min(B,Math.max(L-w*2,160)),z=_?.offsetHeight||280,X=Math.min(z,Math.max(G-q*2,160)),E=T.top-$,U=T.bottom-$,pe=T.left-I,ie=G-U,re=E,F=ie<X&&re>ie,ce=Math.min(Math.max(pe,w),L-w-A)+I,ae=F?Math.max(q+$,E-X-W+$):Math.min(U+W+$,G+$-q-X);g({top:ae,left:ce,width:A})},[v]),k=a.useMemo(()=>Object.entries(o).sort(([P],[T])=>P.localeCompare(T)),[o]),M=k.length>0,y=k.length+(M?1:0);a.useEffect(()=>{if(!i)return;let P=!1;return u(!0),Xa(s).then(T=>{P||l(T)}).catch(()=>{P||l({})}).finally(()=>{P||u(!1)}),()=>{P=!0}},[i,s]),a.useEffect(()=>{if(!i)return;const P=T=>{p.current&&!p.current.contains(T.target)&&f.current&&!f.current.contains(T.target)&&r(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[i]),a.useEffect(()=>{if(!i)return;const P=T=>{T.key==="Escape"&&(r(!1),f.current?.focus())};return document.addEventListener("keydown",P),()=>document.removeEventListener("keydown",P)},[i]),a.useEffect(()=>{if(i){m(-1);const P=window.setTimeout(()=>b.current?.focus(),0);return()=>window.clearTimeout(P)}g(null)},[i]),a.useEffect(()=>{if(!i)return;const P=requestAnimationFrame(()=>{x()});return()=>cancelAnimationFrame(P)},[i,c,k.length,M,x]),a.useEffect(()=>{if(!i)return;const P=()=>x();window.addEventListener("resize",P),window.addEventListener("scroll",P,!0);const T=window.visualViewport;return T&&(T.addEventListener("resize",P),T.addEventListener("scroll",P)),()=>{window.removeEventListener("resize",P),window.removeEventListener("scroll",P,!0),T&&(T.removeEventListener("resize",P),T.removeEventListener("scroll",P))}},[i,x]);const R=a.useCallback(P=>{switch(P.key){case"ArrowDown":P.preventDefault(),m(T=>T<y-1?T+1:0);break;case"ArrowUp":P.preventDefault(),m(T=>T>0?T-1:y-1);break;case"Enter":if(P.preventDefault(),d>=0)if(d<k.length){const[T,_]=k[d];C(T,_)}else M&&d===k.length&&S();break;case"Home":P.preventDefault(),m(0);break;case"End":P.preventDefault(),m(y-1);break}},[d,y,k,M]),j=a.useCallback(()=>{r(P=>!P)},[]),C=a.useCallback((P,T)=>{n(P,T),r(!1)},[n]),S=a.useCallback(()=>{e(),r(!1)},[e]);return t.jsxs("div",{className:"quick-scripts-dropdown",ref:p,children:[t.jsxs("button",{ref:f,className:`btn-icon quick-scripts-dropdown__trigger ${i?"open btn-icon--active":""}`,onClick:j,"aria-expanded":i,"aria-haspopup":"listbox","aria-label":"Quick scripts","data-testid":"scripts-btn",title:"Scripts",children:[t.jsx(Bs,{size:16}),t.jsx(zt,{size:14,className:`quick-scripts-dropdown__trigger-chevron ${i?"rotate":""}`})]}),i&&t.jsx("div",{ref:b,tabIndex:-1,className:"quick-scripts-dropdown__menu",role:"listbox","aria-label":"Scripts",onKeyDown:R,"data-testid":"quick-scripts-dropdown",style:h?{position:"fixed",top:`${h.top}px`,left:`${h.left}px`,width:`${h.width}px`,right:"auto"}:void 0,children:c?t.jsxs("div",{className:"quick-scripts-dropdown__loading","data-testid":"quick-scripts-loading",children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts..."})]}):k.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(Bs,{size:16})}),t.jsx("p",{children:"No scripts configured"}),t.jsx("button",{className:"quick-scripts-dropdown__empty-action btn",onClick:S,children:"Add your first script"})]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-scripts-dropdown__list",children:k.map(([P,T],_)=>t.jsxs("button",{className:`quick-scripts-dropdown__item ${d===_?"highlighted":""}`,onClick:()=>C(P,T),role:"option","aria-selected":d===_,"data-testid":`quick-script-item-${P}`,children:[t.jsx(rn,{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:P}),t.jsx("span",{className:"quick-scripts-dropdown__item-command",title:T,children:T.length>50?`${T.slice(0,50)}...`:T})]})]},P))}),t.jsx("div",{className:"quick-scripts-dropdown__footer",children:t.jsxs("button",{className:`quick-scripts-dropdown__manage ${M&&d===k.length?"highlighted":""}`,onClick:S,"data-testid":"quick-scripts-manage",children:[t.jsx(Oa,{size:14}),t.jsx("span",{children:"Manage Scripts..."})]})})]})})]})}function qk(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 Vk({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}=qk(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 kd=new Map,Wk=6e4;function Eh(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=kd.get(m);if(p&&Date.now()<p.expiresAt){if(h||u.current)return;s(p.slots),r(!1);return}!c.current&&r(!0),l(null);try{const b=await zk(e);if(h||u.current)return;kd.set(m,{slots:b,expiresAt:Date.now()+Wk}),s(b),c.current=!0}catch(b){if(h||u.current)return;l(b instanceof Error?b.message:"Failed to fetch UI slots"),c.current=!0}finally{!h&&!u.current&&r(!1)}}return 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 co({slotId:e,projectId:n}){const{getSlotsForId:s,loading:i,error:r}=Eh(n);if(i||r||!e)return null;const o=s(e);return o.length===0?null:t.jsx(ao,{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 Gk(){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 tr(){const[e,n]=a.useState(Gk);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 Mh={active:{color:"var(--success)"},paused:{color:"var(--warning)"},errored:{color:"var(--color-error)"},initializing:{color:"var(--info)"}};function Kk({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(zt,{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=Mh[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(xn,{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 jd({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 Jk({onOpenSettings:e,onOpenGitHubImport:n,onOpenPlanning:s,onResumePlanning:i,activePlanningSessionCount:r=0,onOpenUsage:o,onOpenActivityLog:l,onOpenMailbox:c,mailboxUnreadCount:u=0,onOpenSchedules:d,onOpenGitManager:m,onOpenNodes:h,showNodesButton:g,onOpenWorkflowSteps:p,onOpenScripts:f,onRunScript:b,onToggleTerminal:v,onOpenFiles:x,filesOpen:k,globalPaused:M,enginePaused:y,onToggleGlobalPause:R,onToggleEnginePause:j,view:C="board",onChangeView:S,showSkillsTab:P,showAgentsTab:T,searchQuery:_="",onSearchChange:L,projects:G=[],currentProject:$,onSelectProject:I,onViewAllProjects:w,projectId:q,isElectron:W=!1,mobileNavEnabled:B,availableNodes:A=[],currentNode:z,onSelectNode:X,isRemote:E=!1,experimentalFeatures:U}){const pe=tr(),ie=pe==="mobile",F=ie||pe==="tablet",ce=ie&&B,[ae,Q]=a.useState(!1),[de,Te]=a.useState(!1),[fe,Se]=a.useState(!1),[te,we]=a.useState(!1),[Pe,We]=a.useState(!1),[Ke,Ne]=a.useState(!1),[_e,Oe]=a.useState(!1),[ye,De]=a.useState(!1),[se,J]=a.useState(!1),[me,ee]=a.useState(!1),[he,le]=a.useState({}),[Ie,Ze]=a.useState(!1),at=a.useRef(null),oe=a.useRef(null),Z=a.useRef(null),ue=a.useRef(null),Ce=a.useRef(null),$e=a.useRef(null),ve=a.useRef(!1),Ge=a.useRef(null),je=a.useRef(null),Ue=a.useRef(null),He=a.useRef(null),ge=a.useRef(null),Fe=a.useMemo(()=>A.filter(Le=>Le.type==="remote"),[A]),be=Fe.length>0,Je=a.useMemo(()=>Object.entries(he).sort(([Le],[gt])=>Le.localeCompare(gt)),[he]),st=a.useMemo(()=>!!(U?.insights||U?.roadmap||P||U?.memoryView||U?.devServerView),[U,P]);a.useEffect(()=>{ve.current=Pe},[Pe]),a.useEffect(()=>{if(!Pe||!F)return;let Le=!1;return Ze(!0),Xa(q).then(gt=>{Le||le(gt)}).catch(()=>{Le||le({})}).finally(()=>{Le||Ze(!1)}),()=>{Le=!0}},[Pe,F,q]);const dt=ae||_.length>0,Tt=(de||_.length>0)&&!fe,$t=(C==="board"||C==="list")&&!ie&&L&&!fe&&_.length===0,Dt=(C==="board"||C==="list")&&!ie&&L;a.useEffect(()=>{_===""&&Se(!1)},[_]),a.useEffect(()=>{if(!te)return;const Le=gt=>{oe.current&&!oe.current.contains(gt.target)&&at.current&&!at.current.contains(gt.target)&&we(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[te]),a.useEffect(()=>{if(!se)return;const Le=gt=>{ue.current&&!ue.current.contains(gt.target)&&Z.current&&!Z.current.contains(gt.target)&&J(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[se]),a.useEffect(()=>{if(!Ke)return;const Le=gt=>{Ge.current&&!Ge.current.contains(gt.target)&&Ne(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[Ke]),a.useEffect(()=>{const Le=gt=>{if(gt.key==="Escape"){if(De(!1),J(!1),ve.current){We(!1);return}we(!1),Q(!1),Ne(!1),Oe(!1)}};return document.addEventListener("keydown",Le),()=>document.removeEventListener("keydown",Le)},[]),a.useEffect(()=>{if(!_e)return;const Le=gt=>{je.current&&!je.current.contains(gt.target)&&Oe(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[_e]),a.useEffect(()=>{if(!me)return;const Le=gt=>{ge.current&&!ge.current.contains(gt.target)&&ee(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[me]),a.useEffect(()=>{if(!me)return;const Le=gt=>{gt.key==="Escape"&&ee(!1)};return document.addEventListener("keydown",Le),()=>document.removeEventListener("keydown",Le)},[me]),a.useEffect(()=>{if(!ye)return;const Le=gt=>{Ue.current&&!Ue.current.contains(gt.target)&&He.current&&!He.current.contains(gt.target)&&De(!1)};return document.addEventListener("mousedown",Le),()=>document.removeEventListener("mousedown",Le)},[ye]);const Bt=a.useCallback(()=>{Q(Le=>!Le)},[]),qt=a.useCallback(()=>{Te(!0),Se(!1)},[]),Lt=a.useCallback(()=>{Te(!1),Se(!0),L&&L("")},[L]),Ct=a.useCallback(()=>{we(Le=>!Le)},[]),xt=a.useCallback(Le=>{Le&&Le(),we(!1),We(!1)},[]),Et=a.useCallback(()=>{Q(!1),L&&L("")},[L]);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"})]}),ie&&G.length>=1&&I&&t.jsxs("div",{className:"mobile-project-switch",ref:je,children:[t.jsx("button",{className:`mobile-project-switch-trigger${_e?" mobile-project-switch-trigger--open":""}`,onClick:()=>Oe(Le=>!Le),title:"Switch project","aria-label":"Switch project","aria-expanded":_e,"aria-haspopup":"listbox","data-testid":"mobile-project-switch-trigger",children:t.jsx(zt,{size:14,className:`mobile-project-switch-chevron${_e?" mobile-project-switch-chevron--open":""}`})}),_e&&t.jsx("div",{className:"mobile-project-switch-dropdown",role:"listbox","aria-label":"Select project","data-testid":"mobile-project-switch-dropdown",children:G.map(Le=>{const gt=$?.id===Le.id,ut=Mh[Le.status]?.color;return t.jsxs("button",{className:`mobile-project-switch-item${gt?" mobile-project-switch-item--current":""}`,onClick:()=>{I(Le),Oe(!1)},role:"option","aria-selected":gt,"data-testid":`mobile-project-switch-item-${Le.id}`,children:[t.jsx("span",{className:"mobile-project-switch-dot",style:{backgroundColor:ut||"var(--text-muted)"}}),t.jsxs("div",{className:"mobile-project-switch-info",children:[t.jsx("span",{className:"mobile-project-switch-name",children:Le.name}),t.jsx("span",{className:"mobile-project-switch-path",children:Le.path.split("/").slice(-2).join("/")})]}),gt&&t.jsx(xn,{size:14,className:"mobile-project-switch-check"})]},Le.id)})})]}),!F&&G.length>=1&&w&&t.jsx(Kk,{projects:G,currentProject:$??null,onViewAll:w,onSelectProject:I}),be&&t.jsxs("div",{className:`header-node-selector${ie?" header-node-selector--mobile":""}`,ref:ie?void 0:Ge,children:[t.jsx(Vk,{node:z??null,showDetails:!ie}),!ie&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:`btn-icon node-selector-trigger${Ke?" node-selector-trigger--open":""}`,onClick:()=>Ne(Le=>!Le),title:"Switch node","aria-label":"Switch node","aria-expanded":Ke,"aria-haspopup":"listbox","data-testid":"node-selector-trigger",children:t.jsx(en,{size:12,className:`node-selector-chevron${Ke?" node-selector-chevron--open":""}`})}),Ke&&t.jsxs("div",{className:"node-selector-dropdown",role:"listbox","aria-label":"Select node",children:[t.jsxs("button",{className:`node-selector-option${E?"":" node-selector-option--active"}`,onClick:()=>{X?.(null),Ne(!1)},role:"option","aria-selected":!E,"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"})]}),Fe.map(Le=>t.jsxs("button",{className:`node-selector-option${z?.id===Le.id?" node-selector-option--active":""}`,onClick:()=>{X?.(Le),Ne(!1)},role:"option","aria-selected":z?.id===Le.id,"data-testid":`node-option-${Le.id}`,children:[t.jsx("span",{className:`node-selector-option-dot node-selector-option-dot--${Le.status}`}),t.jsx("span",{className:"node-selector-option-label",children:Le.name}),t.jsx("span",{className:"node-selector-option-status",children:Le.status})]},Le.id))]})]})]})]}),t.jsxs("div",{className:"header-actions",children:[ce&&S&&(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:()=>S("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board","data-testid":"mobile-view-toggle-board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>S("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list","data-testid":"mobile-view-toggle-list",children:t.jsx(Tl,{size:16})})]}),L&&ie&&(ce||C==="board"||C==="list")&&!dt&&t.jsx("button",{className:"btn-icon mobile-search-trigger",onClick:Bt,title:"Open search","aria-label":"Open search","aria-expanded":!1,"data-testid":"mobile-header-search-btn",children:t.jsx(Bi,{size:16})}),$t&&t.jsx("button",{className:"btn-icon",onClick:qt,title:"Open search","aria-label":"Open search","data-testid":"desktop-header-search-btn",children:t.jsx(Bi,{size:16})}),ie&&ce&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"mobile-header-usage-btn",children:t.jsx(Ss,{size:16})}),!ce&&S&&t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${C==="board"?" active":""}`,onClick:()=>S("board"),title:"Board view","aria-label":"Board view","aria-pressed":C==="board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="list"?" active":""}`,onClick:()=>S("list"),title:"List view","aria-label":"List view","aria-pressed":C==="list",children:t.jsx(Tl,{size:16})}),T&&t.jsx("button",{className:`view-toggle-btn${C==="agents"?" active":""}`,onClick:()=>S("agents"),title:"Agents view","aria-label":"Agents view","aria-pressed":C==="agents",children:t.jsx(an,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="missions"?" active":""}`,onClick:()=>S("missions"),title:"Missions view","aria-label":"Missions view","aria-pressed":C==="missions",children:t.jsx(ns,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="chat"?" active":""}`,onClick:()=>S("chat"),title:"Chat view","aria-label":"Chat view","aria-pressed":C==="chat",children:t.jsx(li,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="documents"?" active":""}`,onClick:()=>S("documents"),title:"Documents view","aria-label":"Documents view","aria-pressed":C==="documents",children:t.jsx(Ni,{size:16})}),t.jsx("button",{className:`view-toggle-btn${C==="mailbox"?" active":""}`,onClick:()=>S("mailbox"),title:"Mailbox view","aria-label":"Mailbox view","aria-pressed":C==="mailbox",children:t.jsx(Gi,{size:16})}),st&&t.jsxs(t.Fragment,{children:[t.jsx("button",{ref:He,className:`view-toggle-btn${["skills","roadmaps","insights","memory","dev-server","devserver"].includes(C)?" active":""}`,onClick:()=>De(Le=>!Le),title:"More views","aria-label":"More views","aria-haspopup":"menu","aria-expanded":ye,"data-testid":"view-toggle-overflow-trigger",children:t.jsx(zt,{size:12})}),ye&&t.jsxs("div",{ref:Ue,className:"view-toggle-overflow-menu",role:"menu","aria-label":"More views",children:[U?.insights&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="insights"?" active":""}`,onClick:()=>{S("insights"),De(!1)},role:"menuitem","data-testid":"view-overflow-insights",children:[t.jsx(Dn,{size:14}),t.jsx("span",{children:"Insights"})]}),U?.roadmap&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="roadmaps"?" active":""}`,onClick:()=>{S("roadmaps"),De(!1)},role:"menuitem","data-testid":"view-overflow-roadmaps",children:[t.jsx(Rl,{size:14}),t.jsx("span",{children:"Roadmaps"})]}),P&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="skills"?" active":""}`,onClick:()=>{S("skills"),De(!1)},role:"menuitem","data-testid":"view-overflow-skills",children:[t.jsx(vn,{size:14}),t.jsx("span",{children:"Skills"})]}),U?.memoryView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="memory"?" active":""}`,onClick:()=>{S("memory"),De(!1)},role:"menuitem","data-testid":"view-toggle-memory",children:[t.jsx(Pr,{size:14}),t.jsx("span",{children:"Memory"})]}),U?.devServerView&&t.jsxs("button",{className:`view-toggle-overflow-item${C==="dev-server"||C==="devserver"?" active":""}`,onClick:()=>{S("devserver"),De(!1)},role:"menuitem","data-testid":"view-toggle-devserver",children:[t.jsx(rh,{size:14}),t.jsx("span",{children:"Dev Server"}),t.jsx("span",{className:"visually-hidden","data-testid":"view-toggle-dev-server"})]})]})]})]}),!F&&o&&t.jsx("button",{className:"btn-icon",onClick:o,title:"View usage","data-testid":"desktop-header-usage-btn",children:t.jsx(Ss,{size:16})}),!F&&l&&t.jsx("button",{className:"btn-icon",onClick:l,title:"View Activity Log",children:t.jsx(Fa,{size:16})}),!F&&!W&&t.jsx("button",{className:"btn-icon",onClick:n,title:"Import from GitHub",children:t.jsx(jd,{size:16})}),!F&&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(Us,{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})]}),!F&&t.jsx("button",{className:"btn-icon btn-icon--terminal",onClick:v,title:"Open Terminal","data-testid":"terminal-toggle-btn",children:t.jsx(Bs,{size:16})}),!F&&x&&t.jsx("button",{className:`btn-icon${k?" btn-icon--active":""}`,onClick:x,title:"Browse files","data-testid":"files-toggle-btn",children:t.jsx(jn,{size:16})}),!F&&m&&t.jsx("button",{className:"btn-icon",onClick:m,title:"Git Manager","data-testid":"git-manager-btn",children:t.jsx(Os,{size:16})}),!F&&p&&t.jsx("button",{className:"btn-icon",onClick:p,title:"Workflow Steps","data-testid":"workflow-steps-btn",children:t.jsx(Pl,{size:16})}),!F&&f&&b&&t.jsx(Hk,{onOpenScripts:f,onRunScript:b,projectId:q}),!F&&t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{ref:Z,className:"btn-icon",onClick:()=>J(Le=>!Le),title:"More actions","aria-label":"More actions","aria-expanded":se,"aria-haspopup":"menu","data-testid":"desktop-overflow-trigger",children:t.jsx(_l,{size:16})}),se&&t.jsxs("div",{ref:ue,className:"desktop-overflow-menu",role:"menu","aria-label":"More actions",children:[h&&g!==!1&&t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{h(),J(!1)},role:"menuitem","data-testid":"desktop-overflow-nodes-btn",children:[t.jsx(Lr,{size:14}),t.jsx("span",{children:"Nodes"})]}),t.jsxs("button",{className:"view-toggle-overflow-item",onClick:()=>{xt(d),J(!1)},role:"menuitem","data-testid":"desktop-overflow-schedules-btn",children:[t.jsx(ji,{size:14}),t.jsx("span",{children:"Automation"})]})]})]}),t.jsxs("div",{className:"engine-control-split-btn",ref:ge,children:[t.jsx("button",{className:`btn-icon engine-control-split-btn__main${M?" btn-icon--stopped":""}`,onClick:R,title:M?"Start AI engine":"Stop AI engine","data-testid":"engine-control-main-btn",children:M?t.jsx(rn,{size:16}):t.jsx(ls,{size:16})}),t.jsx("span",{className:"engine-control-split-btn__divider"}),t.jsx("button",{className:`btn-icon engine-control-split-btn__chevron${me?" btn-icon--active":""}`,onClick:()=>ee(Le=>!Le),title:"Engine options","aria-haspopup":"menu","aria-expanded":me,"data-testid":"engine-control-chevron-btn",children:t.jsx(zt,{size:12})}),me&&t.jsx("div",{className:"engine-control-split-btn__menu",role:"menu",children:t.jsxs("button",{className:`engine-control-split-btn__menu-item${y?" engine-control-split-btn__menu-item--active":""}`,onClick:()=>{j?.(),ee(!1)},role:"menuitem",title:y?"Resume scheduling":"Pause triage",disabled:!!M,"data-testid":"engine-control-pause-triage-btn",children:[y?t.jsx(rn,{size:14}):t.jsx(Fs,{size:14}),t.jsx("span",{children:y?"Resume scheduling":"Pause triage"})]})})]}),!F&&t.jsx("button",{className:"btn-icon",onClick:e,title:"Settings",children:t.jsx(Oa,{size:16})}),t.jsx(co,{slotId:"header-action",projectId:q}),F&&!ce&&t.jsx("button",{ref:at,className:"btn-icon compact-overflow-trigger",onClick:Ct,title:"More header actions","aria-label":"More header actions","aria-expanded":te,"aria-haspopup":"menu",children:t.jsx(_l,{size:16})}),F&&!ce&&te&&t.jsxs("div",{ref:oe,className:"mobile-overflow-menu",role:"menu","aria-label":"Additional header actions",children:[G.length>=1&&w&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(w),role:"menuitem","data-testid":"overflow-project-selector-btn",children:[t.jsx(ih,{size:16}),t.jsx("span",{children:"Projects"})]}),x&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(x),role:"menuitem","data-testid":"overflow-files-btn",children:[t.jsx(jn,{size:16}),t.jsx("span",{children:"Browse Files"})]}),t.jsxs("button",{className:`mobile-overflow-item${r>0?" mobile-overflow-item--has-indicator":""}`,onClick:()=>xt(r>0&&i?i:s),role:"menuitem","data-testid":"overflow-planning-btn",children:[t.jsxs("span",{className:"mobile-overflow-icon-wrapper",children:[t.jsx(Us,{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"})]}),m&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(m),role:"menuitem","data-testid":"overflow-git-btn",children:[t.jsx(Os,{size:16}),t.jsx("span",{children:"Git Manager"})]}),h&&g!==!1&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(h),role:"menuitem","data-testid":"overflow-nodes-btn",children:[t.jsx(Lr,{size:16}),t.jsx("span",{children:"Nodes"})]}),!W&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(n),role:"menuitem",children:[t.jsx(jd,{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:()=>xt(v),role:"menuitem","data-testid":"overflow-terminal-primary-btn",children:[t.jsx(Bs,{size:16}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{className:"mobile-overflow-split-toggle",onClick:()=>We(Le=>!Le),role:"menuitem","aria-expanded":Pe,"aria-haspopup":"menu","aria-label":"Show scripts","data-testid":"overflow-terminal-submenu-toggle",children:t.jsx(en,{size:14,className:`mobile-overflow-chevron${Pe?" mobile-overflow-chevron--open":""}`})})]}),Pe&&t.jsx("div",{className:"mobile-overflow-submenu",role:"menu","aria-label":"Scripts submenu",children:Ie?t.jsxs("div",{className:"mobile-overflow-submenu-loading","data-testid":"overflow-scripts-loading",children:[t.jsx(it,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):Je.length>0?t.jsxs(t.Fragment,{children:[Je.map(([Le,gt])=>t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>{b&&b(Le,gt),we(!1),We(!1)},role:"menuitem","data-testid":`overflow-script-item-${Le}`,children:[t.jsx(rn,{size:14}),t.jsx("span",{children:Le})]},Le)),f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem mobile-overflow-subitem--manage",onClick:()=>xt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):f&&t.jsxs("button",{className:"mobile-overflow-item mobile-overflow-subitem",onClick:()=>xt(f),role:"menuitem","data-testid":"overflow-scripts-manage",children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(d),role:"menuitem","data-testid":"overflow-schedules-btn",children:[t.jsx(ji,{size:16}),t.jsx("span",{children:"Automation"})]}),l&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(l),role:"menuitem","data-testid":"overflow-activity-log-btn",children:[t.jsx(Fa,{size:16}),t.jsx("span",{children:"View Activity Log"})]}),c&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(c),role:"menuitem","data-testid":"overflow-mailbox-btn",children:[t.jsx(Gi,{size:16}),t.jsxs("span",{children:["Mailbox",u>0?` (${u})`:""]})]}),o&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(o),role:"menuitem","data-testid":"overflow-usage-btn",children:[t.jsx(Ss,{size:16}),t.jsx("span",{children:"View Usage"})]}),p&&t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(p),role:"menuitem","data-testid":"overflow-workflow-steps-btn",children:[t.jsx(Pl,{size:16}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{className:"mobile-overflow-item",onClick:()=>xt(e),role:"menuitem",children:[t.jsx(Oa,{size:16}),t.jsx("span",{children:"Settings"})]})]})]})]}),Dt&&Tt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{className:"header-search",children:[t.jsx(Bi,{size:14,className:"header-search-icon"}),t.jsx("input",{autoFocus:!0,type:"text",placeholder:"Search tasks...",value:_,onChange:Le=>L(Le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Lt,"aria-label":"Close search",children:t.jsx(Pt,{size:14})})]})}),L&&ie&&dt&&t.jsx("div",{className:"header-floating-search",children:t.jsxs("div",{ref:Ce,className:"header-search mobile-search-expanded",children:[t.jsx(Bi,{size:14,className:"header-search-icon"}),t.jsx("input",{ref:$e,autoFocus:!0,type:"text",placeholder:"Search tasks...",value:_,onChange:Le=>L(Le.target.value),className:"header-search-input"}),t.jsx("button",{className:"header-search-clear",onClick:Et,"aria-label":"Close search",children:t.jsx(Pt,{size:14})})]})})]})}const Yk={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"],ntfyDashboardHost:void 0,defaultProjectId:void 0,setupComplete:void 0,favoriteProviders:void 0,favoriteModels:void 0,openrouterModelSync:!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},Qk={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",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:"",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,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:!1,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:{}},Xk=Object.freeze(Object.keys(Yk)),Zk=Object.freeze(Object.keys(Qk));function aP(e){return Xk.includes(e)}function rP(e){return Zk.includes(e)}function xe(e){if(e instanceof Error)return e.message;if(typeof e=="string")return e;try{return JSON.stringify(e)}catch{return String(e)}}const oP=["off","minimal","low","medium","high"],ki=["triage","todo","in-progress","in-review","done","archived"],uc=["low","normal","high","urgent"],cs="normal",ej=["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"],Pn={triage:"Planning",todo:"Todo","in-progress":"In Progress","in-review":"In Review",done:"Done",archived:"Archived"},tj={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"},zl={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 nj(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 sj(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 ij(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 _h({prInfo:e,issueInfo:n,onIssueRefresh:s}){const i=()=>{e?.url&&window.open(e.url,"_blank","noopener,noreferrer")},r=()=>{n?.url&&window.open(n.url,"_blank","noopener,noreferrer")};return t.jsxs(t.Fragment,{children:[e&&t.jsxs("span",{className:`card-github-badge card-github-badge--${e.status}`,title:`PR #${e.number}: ${e.title}`,onClick:i,children:[t.jsx(es,{size:12}),t.jsxs("span",{children:["#",e.number]})]}),n&&t.jsxs("span",{className:`card-github-badge ${ij(n.state,n.stateReason)}`,title:`Issue #${n.number}: ${n.title}`,onClick:r,children:[t.jsx(eo,{size:12}),t.jsxs("span",{children:["#",n.number]})]})]})}function pr(e,n){return`${e??"default"}:${n}`}class aj{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=pr(this.projectId,o);this.subscriptionsByTask.set(l,new Set([r]))}this.shouldReconnect=this.subscriptionsByTask.size>0,this.connect()}}subscribeTask(n,s){const i=pr(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=pr(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(Hs(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=pr(this.projectId,l.taskId),u=this.badgeUpdates.get(c);this.badgeUpdates.set(c,{prInfo:wd(l,"prInfo")?l.prInfo??null:u?.prInfo,issueInfo:wd(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 gi=new aj;let rj=0;function wd(e,n){return Object.prototype.hasOwnProperty.call(e,n)}function Ah(e){const n=a.useRef(null);n.current===null&&(n.current=`badge-hook-${rj++}`);const s=a.useSyncExternalStore(o=>gi.subscribe(o),()=>gi.getSnapshot(),()=>gi.getSnapshot()),i=a.useCallback(o=>{gi.subscribeTask(n.current,o)},[]),r=a.useCallback(o=>{gi.unsubscribeTask(n.current,o)},[]);return a.useEffect(()=>{gi.setProjectId(e??null)},[e]),a.useEffect(()=>()=>{gi.cleanupHook(n.current)},[]),{badgeUpdates:s.badgeUpdates,isConnected:s.isConnected,subscribeToBadge:i,unsubscribeFromBadge:r}}function Br(e,n,s,i){return e===void 0||!n?s:!i||n>=i?e??void 0:s}function oj({taskId:e,prInfo:n,issueInfo:s,updatedAt:i,isInViewport:r,projectId:o}){const{badgeUpdates:l,subscribeToBadge:c,unsubscribeFromBadge:u}=Ah(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=Br(m?.prInfo,m?.timestamp,n,n?.lastCheckedAt??i),g=Br(m?.issueInfo,m?.timestamp,s,s?.lastCheckedAt??i);return!h&&!g?null:t.jsx(_h,{prInfo:h,issueInfo:g})}const lj=a.memo(oj);lj.displayName="TaskCardBadge";const cj={sm:16,md:20,lg:24};function dj({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 Nd({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 Sd({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 uj({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 mj({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 hj({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 Po({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 Cd({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 Ed({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 pj({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 fj({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 Md({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 _d({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 gj={anthropic:{component:dj,color:"var(--provider-anthropic)"},"claude-cli":{component:_d,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},"pi-claude-cli":{component:_d,color:"var(--provider-anthropic)",label:"Anthropic — via Claude CLI"},openai:{component:Nd,color:"var(--provider-openai)"},"openai-codex":{component:Nd,color:"var(--provider-openai)",label:"OpenAI Codex"},google:{component:Sd,color:"var(--provider-gemini)"},gemini:{component:Sd,color:"var(--provider-gemini)"},ollama:{component:uj,color:"var(--text)"},github:{component:Md,color:"var(--text)"},"github-copilot":{component:Md,color:"var(--text)",label:"GitHub Copilot"},openrouter:{component:fj,color:"var(--provider-openrouter)"},minimax:{component:mj,color:"var(--provider-minimax)"},zai:{component:hj,color:"var(--provider-zai)"},kimi:{component:Po,color:"var(--provider-kimi)"},moonshot:{component:Po,color:"var(--provider-kimi)"},"kimi-coding":{component:Po,color:"var(--provider-kimi)",label:"Kimi"},bedrock:{component:Cd,color:"var(--provider-bedrock)"},"amazon-bedrock":{component:Cd,color:"var(--provider-bedrock)",label:"Amazon Bedrock"},xai:{component:Ed,color:"var(--text)"},grok:{component:Ed,color:"var(--text)",label:"xAI"},opencode:{component:pj,color:"var(--provider-opencode)"}};function Mn({provider:e,size:n="sm"}){const s=e.toLowerCase(),i=gj[s],r=i?.component,o=i?.color??"var(--text-muted)",l=i?.label,c=cj[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(ug,{size:c})})}const ks={data:new Map,pendingPromise:null,lastFetchTime:null},bj=5e3;function Tr(e,n){return n?`${n}::${e}`:e}function xj(e,n){const s=ks.data.get(Tr(e,n));if(!(!s||Date.now()-s.timestamp>bj))return s}function vj(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 lv(c,e)}catch(h){d=h instanceof Error?h:new Error(String(h));const g=xe(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=ks.data.get(Tr(g,e));return p&&p.timestamp>d})&&ks.lastFetchTime&&ks.lastFetchTime>d)return;if(i.current&&(clearTimeout(i.current),i.current=null),ks.pendingPromise){s(!0);try{await ks.pendingPromise}finally{s(!1)}return}s(!0);const h=r(c);ks.pendingPromise=h;try{const g=await h,p=Date.now();for(const[f,b]of Object.entries(g))ks.data.set(Tr(f,e),{result:b,timestamp:p});ks.lastFetchTime=p}catch{}finally{ks.pendingPromise=null,s(!1)}},[r,e]),l=a.useCallback(c=>ks.data.get(Tr(c,e)),[e]);return{fetchBatch:o,isLoading:n,lastFetchTime:ks.lastFetchTime,getBatchData:l}}const Fl=new Map,yj=3e4;function Th(e,n,s,i){return`${e}:${n??""}:${s??""}:${i??""}`}function kj(e,n,s,i){const r=Th(e,n,s,i),o=Fl.get(r);return o?Date.now()>o.expiresAt?(Fl.delete(r),null):o.stats:null}function jj(e,n,s,i,r){const o=Th(e,n,s,i);Fl.set(o,{stats:r,expiresAt:Date.now()+yj})}function wj(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 b=f?l:void 0,v=c!==void 0?String(c):void 0;let x=!1;async function k(y=!1){if(!y){const R=kj(e,i,b,v);if(R){x||(m(R),g(!1));return}}g(!0);try{const R=await jh(e,b,i);x||(m(R.stats),jj(e,i,b,v,R.stats))}catch{x||m(null)}finally{x||g(!1)}}k();let M;return u&&f&&(M=setInterval(()=>{k(!0)},u)),()=>{x=!0,M&&clearInterval(M)}},[e,n,s,i,o,l,c,u]),{stats:d,loading:h}}const Nj=new Set(["failed","stuck-killed"]);function Hr(e,n,s){if(e.column!=="in-progress"||e.status&&Nj.has(e.status)||!n||n<=0)return!1;const i=new Date(e.updatedAt).getTime();return(s??Date.now())-i>n}function Sj(e){switch(e){case"passed":return"done";case"failed":return"failed";case"skipped":return"skipped";case"pending":default:return"pending"}}function Cj(e){return e==="done"||e==="skipped"}function Ej(e,n,s){const i=s?.get(e)?.trim();if(i)return i;const r=n?.workflowStepName?.trim();return r||e}function Rh(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:Ej(u,d,n),status:d?Sj(d.status):"pending",source:"workflow",phase:d?.phase??"pre-merge"}}),o=[...s,...r],l=o.length,c=o.filter(u=>Cj(u.status)).length;return{total:l,completed:c,items:o}}const Ol=new Map;async function Mj(e,n){const s=Ol.get(e);if(s)return s;try{const i=await wh(e,n);return Ol.set(e,i.title),i.title}catch{return e}}const Ad=12;function _j(e){return e.length<=Ad?e:e.slice(0,Ad-3)+"..."}const Ul=new Map;async function Aj(e,n){const s=Ul.get(e);if(s)return s;try{const i=await yh(e,n);return Ul.set(e,i.name),i.name}catch{return e}}function Tj(e){return typeof e=="string"&&uc.includes(e)?e:cs}function Rj(e,n){return e.length<=n?e:e.slice(0,n-3)+"..."}const Ij=new Set(["triage","todo"]),Td=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Pj={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-muted)"},$j=new Set(["in-progress","done"]),Dj=3e4;function mc(e){if(!e)return null;const n=Date.parse(e);return Number.isFinite(n)?n:null}function Rd(e){const n=e.columnMovedAt??e.updatedAt??e.createdAt,s=mc(n);if(s==null)return null;const i=Date.now();return s>i?null:s}function Lj(e){const n=mc(e.columnMovedAt??e.updatedAt);if(n==null)return null;const s=Date.now();return n>s?null:n}function zj(e,n){return[e.createdAt].map(mc).filter(r=>r!=null).find(r=>r<=n)??null}function Id(e){if(!Number.isFinite(e)||e<0)return"";const n=Math.floor(e/6e4);if(n<1)return"<1m";if(n<60)return`${n}m`;const s=Math.floor(n/60);return s<24?`${s}h`:`${Math.floor(s/24)}d`}function Pd(e,n){if(!e&&!n)return!0;if(!e||!n)return!1;const s=Object.keys(e),i=Object.keys(n);return s.length!==i.length?!1:s.every(r=>e[r]===n[r])}function Fj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s.name===n[i]?.name&&s.status===n[i]?.status)}function Oj(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function Uj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>s===n[i])}function Bj(e){if(!(e instanceof Error))return null;const n=e.details;if(n?.code==="TASK_HAS_DEPENDENTS"&&Array.isArray(n.dependentIds))return{dependentIds:n.dependentIds.filter(i=>typeof i=="string")};const s=e.message.match(/[A-Z]+-\d+/g)??[];return s.length>1?{dependentIds:[...new Set(s.slice(1))]}:null}function Hj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.workflowStepId===r.workflowStepId&&s.workflowStepName===r.workflowStepName&&s.phase===r.phase&&s.status===r.status&&s.output===r.output&&s.startedAt===r.startedAt&&s.completedAt===r.completedAt:!1})}function qj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.filename===r.filename&&s.mimeType===r.mimeType&&s.size===r.size:!1})}function Vj(e,n){return!e&&!n?!0:!e||!n||e.length!==n.length?!1:e.every((s,i)=>{const r=n[i];return r?s.author===r.author&&s.text===r.text&&s.createdAt===r.createdAt:!1})}function Wj(e,n){const s=e.task,i=n.task;return e.queued===n.queued&&e.projectId===n.projectId&&e.globalPaused===n.globalPaused&&e.taskStuckTimeoutMs===n.taskStuckTimeoutMs&&e.onOpenDetail===n.onOpenDetail&&e.addToast===n.addToast&&e.onUpdateTask===n.onUpdateTask&&e.onArchiveTask===n.onArchiveTask&&e.onUnarchiveTask===n.onUnarchiveTask&&e.onDeleteTask===n.onDeleteTask&&e.onOpenDetailWithTab===n.onOpenDetailWithTab&&e.onOpenMission===n.onOpenMission&&e.onMoveTask===n.onMoveTask&&e.workflowStepNameLookup===n.workflowStepNameLookup&&s.id===i.id&&s.title===i.title&&s.description===i.description&&s.column===i.column&&s.columnMovedAt===i.columnMovedAt&&s.updatedAt===i.updatedAt&&s.createdAt===i.createdAt&&s.status===i.status&&s.priority===i.priority&&s.executionMode===i.executionMode&&s.paused===i.paused&&s.error===i.error&&s.size===i.size&&s.blockedBy===i.blockedBy&&s.worktree===i.worktree&&s.baseBranch===i.baseBranch&&s.breakIntoSubtasks===i.breakIntoSubtasks&&s.currentStep===i.currentStep&&s.modelProvider===i.modelProvider&&s.modelId===i.modelId&&s.validatorModelProvider===i.validatorModelProvider&&s.validatorModelId===i.validatorModelId&&s.planningModelProvider===i.planningModelProvider&&s.planningModelId===i.planningModelId&&s.reviewLevel===i.reviewLevel&&s.missionId===i.missionId&&s.assignedAgentId===i.assignedAgentId&&s.mergeRetries===i.mergeRetries&&qj(s.attachments,i.attachments)&&Vj(s.comments,i.comments)&&Oj(s.dependencies,i.dependencies)&&Fj(s.steps,i.steps)&&Uj(s.enabledWorkflowSteps,i.enabledWorkflowSteps)&&Hj(s.workflowStepResults,i.workflowStepResults)&&Pd(s.prInfo,i.prInfo)&&Pd(s.issueInfo,i.issueInfo)}function Gj({task:e,projectId:n,queued:s,onOpenDetail:i,addToast:r,globalPaused:o,onUpdateTask:l,onArchiveTask:c,onUnarchiveTask:u,onDeleteTask:d,onOpenDetailWithTab:m,taskStuckTimeoutMs:h,onOpenMission:g,onMoveTask:p,lastFetchTimeMs:f,workflowStepNameLookup:b}){const[v,x]=a.useState(!1),[k,M]=a.useState(!1),[y,R]=a.useState(!1),[j,C]=a.useState(e.description||""),[S,P]=a.useState(!1),[T,_]=a.useState(e.column==="in-progress"||e.column==="triage"&&e.steps.some(N=>N.status==="done"||N.status==="skipped")),[L,G]=a.useState(null),[$,I]=a.useState(null),[w,q]=a.useState(!1),[W,B]=a.useState(()=>Date.now()),A=a.useRef(null),z=a.useRef(!1),X=a.useRef(null),E=a.useRef(null),[U,pe]=a.useState(!1),{badgeUpdates:ie,subscribeToBadge:re,unsubscribeFromBadge:F}=Ah(n),ce=a.useRef(null),ae=a.useRef(!1),Q=a.useCallback(N=>N instanceof Element?!!N.closest("button, a, input, textarea, select, label, [role='button']"):!1,[]);a.useEffect(()=>{C(e.description||"")},[e.id,e.description]),a.useEffect(()=>{if(!w)return;const N=H=>{E.current&&!E.current.contains(H.target)&&q(!1)};return document.addEventListener("click",N),()=>document.removeEventListener("click",N)},[w]),a.useEffect(()=>{if(!e.missionId){G(null);return}const N=Ol.get(e.missionId);if(N){G(N);return}let H=!1;return Mj(e.missionId,n).then(Ae=>{H||G(Ae)}),()=>{H=!0}},[e.missionId,n]),a.useEffect(()=>{if(!e.assignedAgentId){I(null);return}const N=Ul.get(e.assignedAgentId);if(N){I(N);return}I(null);let H=!1;return Aj(e.assignedAgentId,n).then(Ae=>{H||I(Ae)}),()=>{H=!0}},[e.assignedAgentId,n]),a.useEffect(()=>{if(y&&A.current){const N=A.current;N.focus(),N.style.height="auto",N.style.height=N.scrollHeight+"px"}},[y]),a.useEffect(()=>{if(typeof IntersectionObserver>"u"){pe(!0);return}const N=X.current;if(!N)return;const H=new IntersectionObserver(([Ae])=>{pe(Ae?.isIntersecting??!0)},{rootMargin:"200px"});return H.observe(N),()=>H.disconnect()},[y,e.id]);const de=a.useCallback(N=>{N.dataTransfer.setData("text/plain",e.id),N.dataTransfer.effectAllowed="move",x(!0)},[e.id]),Te=a.useCallback(()=>{x(!1)},[]),fe=a.useCallback(N=>N.dataTransfer.types.includes("Files"),[]),Se=a.useCallback(N=>{fe(N)&&(N.preventDefault(),N.stopPropagation(),N.dataTransfer.dropEffect="copy",M(!0))},[fe]),te=a.useCallback(N=>{fe(N)&&(N.preventDefault(),N.stopPropagation(),M(!1))},[fe]),we=a.useCallback(async N=>{if(!fe(N))return;N.preventDefault(),N.stopPropagation(),M(!1);const H=Array.from(N.dataTransfer.files);for(const Ae of H)try{await Ua(e.id,Ae,n),r(`Attached ${Ae.name} to ${e.id}`,"success")}catch(ot){r(`Failed to attach ${Ae.name}: ${xe(ot)}`,"error")}},[e.id,fe,r]),Pe=a.useCallback(()=>{y||i(e)},[e,i,y]),We=a.useCallback(N=>{if(z.current){z.current=!1;return}Q(N.target)||Pe()},[Pe,Q]),Ke=a.useCallback(N=>{const H=N.touches[0];H&&(ce.current={x:H.clientX,y:H.clientY,time:Date.now()},ae.current=!1)},[]),Ne=a.useCallback(N=>{if(!ce.current)return;const H=N.touches[0];if(!H)return;const Ae=Math.abs(H.clientX-ce.current.x),ot=Math.abs(H.clientY-ce.current.y);(Ae>$d||ot>$d)&&(ae.current=!0)},[]),_e=a.useCallback(N=>{if(Q(N.target)||!ce.current)return;const Ae=Date.now()-ce.current.time<Kj,ot=!ae.current;Ae&&ot&&(z.current=!0,Pe()),ce.current=null,ae.current=!1},[Pe,Q]),Oe=a.useCallback(async(N,H)=>{N.stopPropagation();try{const Ae=await Or(H,n);i(Ae)}catch{r(`Failed to load dependency ${H}`,"error")}},[i,r]),ye=e.status==="failed",De=e.paused===!0,se=Tj(e.priority),J=se!==cs,me=Hr(e,h,f),ee=e.column==="triage"&&e.status==="awaiting-approval",he=e.column==="archived",le=!o&&!s&&!ye&&!De&&!me&&!ee&&(e.column==="in-progress"||Td.has(e.status)),Ie=!s&&!De&&!y&&!he,Ze=Ij.has(e.column)&&!le&&!De&&!s&&l,at=!!(e.prInfo||e.issueInfo),oe=!!(e.assignedAgentId&&$===null),Z=a.useMemo(()=>{const N=[];return e.modelProvider&&N.push(e.modelProvider),e.validatorModelProvider&&!N.includes(e.validatorModelProvider)&&N.push(e.validatorModelProvider),e.planningModelProvider&&!N.includes(e.planningModelProvider)&&N.push(e.planningModelProvider),N},[e.modelProvider,e.validatorModelProvider,e.planningModelProvider]),ue=a.useMemo(()=>Rh(e,b),[e.steps,e.enabledWorkflowSteps,e.workflowStepResults,b]),Ce=ue.total>0&&(e.status==="executing"||e.column==="in-progress");a.useEffect(()=>{if(e.column!=="in-progress"||Rd(e)==null)return;B(Date.now());const H=window.setInterval(()=>{B(Date.now())},Dj);return()=>window.clearInterval(H)},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt]);const $e=a.useMemo(()=>{if(!$j.has(e.column))return null;if(e.column==="in-progress"){const kt=Rd(e);if(kt==null)return null;const Ot=Id(W-kt);return Ot?{label:Ot,title:`In progress since ${new Date(kt).toLocaleString()}`,ariaLabel:`Elapsed time ${Ot}. In progress since ${new Date(kt).toLocaleString()}`}:null}const N=Lj(e);if(N==null)return null;const H=zj(e,N);if(H==null)return null;const Ae=Id(N-H);if(!Ae)return null;const ot=new Date(N).toLocaleString();return{label:Ae,title:`Processing took ${Ae}. Completed ${ot}`,ariaLabel:`Completed processing duration ${Ae}. Completed ${ot}`}},[e.column,e.columnMovedAt,e.updatedAt,e.createdAt,W]);a.useEffect(()=>{if(!at||!U){F(e.id);return}return re(e.id),()=>{F(e.id)}},[at,U,re,e.id,F]);const ve=ie.get(`${n??"default"}:${e.id}`),Ge=e.column==="in-progress"||e.column==="in-review",je=a.useMemo(()=>e.steps.map(N=>`${N.name}:${N.status}`).join("|"),[e.steps]),{stats:Ue}=wj(e.id,e.column,e.mergeDetails?.commitSha,n,{enabled:U,worktree:e.worktree,stepVersion:Ge?je:void 0,pollIntervalMs:Ge?3e4:void 0}),He=a.useMemo(()=>xj(e.id,n),[e.id,n]),ge=a.useMemo(()=>{const N=ve?.prInfo,H=ve?.timestamp,Ae=He?.result?.prInfo,ot=He?.timestamp?new Date(He.timestamp).toISOString():void 0,kt=e.prInfo,Ot=e.prInfo?.lastCheckedAt??e.updatedAt;let sn=Br(N,H,kt,Ot);const Rt=H&&H>=Ot?H:Ot;return Ae&&ot&&(!Rt||ot>Rt)&&(sn=Ae),sn},[ve,He,e.prInfo,e.updatedAt]),Fe=a.useMemo(()=>{const N=ve?.issueInfo,H=ve?.timestamp,Ae=He?.result?.issueInfo,ot=He?.timestamp?new Date(He.timestamp).toISOString():void 0,kt=e.issueInfo,Ot=e.issueInfo?.lastCheckedAt??e.updatedAt;let sn=Br(N,H,kt,Ot);const Rt=H&&H>=Ot?H:Ot;return Ae&&ot&&(!Rt||ot>Rt)&&(sn=Ae),sn},[ve,He,e.issueInfo,e.updatedAt]),be=a.useCallback(N=>{N?.stopPropagation(),!(!Ze||S)&&(R(!0),C(e.description||""))},[Ze,S,e.description]),Je=a.useCallback(()=>{R(!1),C(e.description||"")},[e.description]),st=a.useCallback(()=>j!==(e.description||""),[j,e.description]),dt=a.useCallback(async()=>{if(!(!l||S)){if(!st()){Je();return}P(!0);try{await l(e.id,{description:j.trim()||void 0}),r(`Updated ${e.id}`,"success"),R(!1)}catch(N){r(`Failed to update ${e.id}: ${xe(N)}`,"error")}finally{P(!1)}}},[l,e.id,j,S,st,Je,r]),Tt=a.useCallback(N=>{N.key==="Enter"&&!N.shiftKey?(N.preventDefault(),dt()):N.key==="Escape"&&(N.preventDefault(),Je())},[dt,Je]),$t=a.useCallback(()=>{setTimeout(()=>{const N=document.activeElement;N===A.current||N?.closest(".card-editing-content")||(st()?dt():Je())},0)},[st,dt,Je]),Dt=a.useCallback(N=>{Ze&&(N.stopPropagation(),be(N))},[Ze,be]),Bt=a.useCallback(N=>{N.stopPropagation(),be(N)},[be]),qt=a.useCallback(N=>{C(N.target.value);const H=N.target;H.style.height="auto",H.style.height=H.scrollHeight+"px"},[]),Lt=a.useCallback(N=>{N.stopPropagation(),c&&c(e.id).then(()=>{r(`Archived ${e.id}`,"success")}).catch(H=>{r(`Failed to archive ${e.id}: ${xe(H)}`,"error")})},[r,c,e.id]),Ct=a.useCallback(N=>{N.stopPropagation(),u&&u(e.id).then(()=>{r(`Unarchived ${e.id}`,"success")}).catch(H=>{r(`Failed to unarchive ${e.id}: ${xe(H)}`,"error")})},[r,u,e.id]),xt=a.useCallback(N=>{N.stopPropagation(),d&&window.confirm(`Delete ${e.id}?`)&&d(e.id).then(()=>{r(`Deleted ${e.id}`,"success")}).catch(H=>{const Ae=Bj(H);if(!Ae||Ae.dependentIds.length===0){r(`Failed to delete ${e.id}: ${xe(H)}`,"error");return}const ot=Ae.dependentIds.join(", ");window.confirm(`${e.id} is a dependency of ${ot}.
|
|
576
576
|
|
|
577
577
|
Delete anyway by removing these dependency references first?`)&&d(e.id,{removeDependencyReferences:!0}).then(()=>{r(`Deleted ${e.id} after removing dependency references`,"success")}).catch(Ot=>{r(`Failed to delete ${e.id}: ${xe(Ot)}`,"error")})})},[r,d,e.id]),Et=a.useCallback(N=>{N.stopPropagation(),m?.(e,"changes")},[e,m]),Le=a.useCallback(N=>{N.stopPropagation(),_(H=>!H)},[]),gt=a.useCallback(N=>{N.stopPropagation(),e.missionId&&g&&g(e.missionId)},[e.missionId,g]),ut=a.useCallback(N=>{N.stopPropagation(),q(H=>!H)},[]),Me=a.useCallback((N,H)=>{N.stopPropagation(),q(!1),p&&p(e.id,H).then(()=>{r(`Moved ${e.id} to ${Pn[H]}`,"success")}).catch(Ae=>{r(`Failed to move ${e.id}: ${xe(Ae)}`,"error")})},[r,p,e.id]),Qe=`card${v?" dragging":""}${s?" queued":""}${le?" agent-active":""}${ye?" failed":""}${De?" paused":""}${me?" stuck":""}${ee?" awaiting-approval":""}${k?" file-drop-target":""}${y?" card-editing":""}${S?" card-saving":""}`,rt=(()=>{if(e.worktree&&e.column==="in-progress"){const N=Ue?.filesChanged;return N==null||N===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Et,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[N," ",N===1?"file":"files"," changed"]})]})}if(e.column==="in-review"){const N=Ue?.filesChanged,H=N==null?e.modifiedFiles?.length:void 0,Ae=N??H;return Ae==null||Ae===0?null:t.jsxs("button",{type:"button",className:"card-session-files",onClick:Et,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[Ae," ",Ae===1?"file":"files"," changed"]})]})}if(e.column==="done"){const N=Ue?.filesChanged,H=e.mergeDetails?.filesChanged,Ae=N??H;if(Ae!=null&&Ae>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Et,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[Ae," ",Ae===1?"file":"files"," changed"]})]});const ot=e.modifiedFiles?.length;if(ot!=null&&ot>0)return t.jsxs("button",{type:"button",className:"card-session-files",onClick:Et,disabled:!m,children:[t.jsx(jn,{size:12}),t.jsxs("span",{children:[ot," ",ot===1?"file":"files"," changed"]})]})}return null})();return y?t.jsx("div",{ref:X,className:Qe,"data-id":e.id,onDoubleClick:Dt,children:t.jsxs("div",{className:"card-editing-content",children:[t.jsx("textarea",{ref:A,className:"card-edit-desc-textarea",placeholder:"Task description",value:j,onChange:qt,onKeyDown:Tt,onBlur:$t,disabled:S,rows:4}),S&&t.jsxs("div",{className:"card-edit-loading",children:[t.jsx("span",{className:"card-edit-loading-spinner"}),t.jsx("span",{className:"card-edit-loading-text",children:"Saving..."})]})]})}):t.jsxs("div",{ref:X,className:Qe,"data-id":e.id,draggable:Ie,onDragStart:Ie?de:void 0,onDragEnd:Ie?Te:void 0,onDragOver:Se,onDragLeave:te,onDrop:we,onClick:We,onTouchStart:Ke,onTouchMove:Ne,onTouchEnd:_e,onDoubleClick:Dt,children:[t.jsxs("div",{className:"card-header",children:[t.jsx("span",{className:"card-id",children:e.id}),De&&t.jsx("span",{className:"card-status-badge paused",children:"paused"}),!De&&e.status&&e.status!=="queued"&&t.jsx("span",{className:`card-status-badge card-status-badge--${e.column}${ee?" awaiting-approval":""}${Td.has(e.status)?" pulsing":""}${ye?" failed":""}${me?" stuck":""}`,children:me?"Stuck":ee?"Awaiting Approval":e.status}),me&&(De||!e.status||e.status==="queued")&&t.jsx("span",{className:"card-status-badge stuck",children:"Stuck"}),at&&t.jsx(_h,{prInfo:ge,issueInfo:Fe}),J&&t.jsx("span",{className:`card-priority-badge card-priority-badge--${se}`,children:se}),e.executionMode==="fast"&&t.jsx("span",{className:"card-execution-mode-badge card-execution-mode-badge--fast",children:"Fast"}),e.missionId&&t.jsxs("span",{className:"card-mission-badge",onClick:gt,title:`Mission: ${L??e.missionId}`,role:g?"button":void 0,tabIndex:g?0:void 0,style:{overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[t.jsx(ns,{size:11}),_j(L??e.missionId)]}),t.jsxs("div",{className:"card-header-actions",children:[Ze&&t.jsx("button",{className:"card-edit-btn",onClick:Bt,title:"Edit task","aria-label":"Edit task",children:t.jsx(Hn,{size:12})}),e.column==="triage"&&d&&t.jsx("button",{className:"card-delete-btn",onClick:xt,title:"Delete task","aria-label":"Delete task",children:t.jsx(Ht,{size:12})}),e.column==="done"&&c&&t.jsx("button",{className:"card-archive-btn",onClick:Lt,title:"Archive task","aria-label":"Archive task",children:"Archive"}),e.column==="archived"&&u&&t.jsx("button",{className:"card-unarchive-btn",onClick:Ct,title:"Unarchive task","aria-label":"Unarchive task",children:"Unarchive"}),e.column==="in-progress"&&p&&t.jsxs("div",{className:"card-send-back",ref:E,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ut,title:"Send back","aria-label":"Send back","aria-haspopup":"menu","aria-expanded":w,children:["Send back",t.jsx(zt,{size:10})]}),w&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:zl["in-progress"].filter(N=>N!=="in-review").map(N=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:H=>Me(H,N),children:Pn[N]},N))})]}),e.column==="in-review"&&p&&t.jsxs("div",{className:"card-send-back",ref:E,children:[t.jsxs("button",{className:"card-send-back-btn",onClick:ut,title:"Move task","aria-label":"Move task","aria-haspopup":"menu","aria-expanded":w,children:["Move",t.jsx(zt,{size:10})]}),w&&t.jsx("div",{className:"card-send-back-menu",role:"menu",children:zl["in-review"].map(N=>t.jsx("button",{className:"card-send-back-menu-item",role:"menuitem",onClick:H=>Me(H,N),children:N==="done"?"Done (no merge)":Pn[N]},N))})]}),e.size&&t.jsx("span",{className:`card-size-badge size-${e.size.toLowerCase()}`,children:e.size})]})]}),ye&&e.error&&t.jsxs("div",{className:"card-error",title:e.error,children:[t.jsx("span",{className:"card-error-icon",children:"⚠"}),t.jsx("span",{className:"card-error-text",children:e.error.length>60?e.error.slice(0,60)+"…":e.error})]}),t.jsx("div",{className:"card-title",title:e.title||e.description||void 0,children:Ld(e.title,Dd)||Ld(e.description,Dd)||e.id}),Ce&&(()=>{const N=ue.completed/ue.total*100;return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"card-progress",children:[t.jsx("div",{className:"card-progress-bar",children:t.jsx("div",{className:"card-progress-fill",style:{width:`${N}%`,backgroundColor:Pj[e.column]}})}),t.jsxs("span",{className:"card-progress-label",children:[ue.completed,"/",ue.total]})]}),t.jsxs("button",{type:"button",className:"card-steps-toggle",onClick:Le,"aria-expanded":T,"aria-label":T?"Hide steps":"Show steps",children:[t.jsxs("span",{children:[ue.total," step",ue.total===1?"":"s"]}),t.jsx(zt,{size:14,className:`card-steps-toggle-icon${T?" expanded":""}`})]}),T&&t.jsx("div",{className:"card-steps-list",children:ue.items.map(H=>{const Ae=H.source==="workflow"&&H.status==="failed";return t.jsxs("div",{className:"card-step-item",children:[t.jsx("span",{className:`card-step-dot card-step-dot--${H.status}${Ae?" card-step-dot--workflow-failed":""}`,"aria-hidden":"true"}),t.jsx("span",{className:`card-step-name${H.status==="done"?" completed":""}`,children:H.name}),H.source==="workflow"&&t.jsx("span",{className:`card-step-workflow-badge card-step-workflow-badge--${H.phase}`,title:"Workflow check",children:"workflow"})]},H.id)})})]})})(),(rt||$e)&&t.jsxs("div",{className:"card-footer-row",children:[rt,$e&&t.jsxs("span",{className:"card-time-indicator",title:$e.title,"aria-label":$e.ariaLabel,children:[t.jsx(ji,{size:12}),t.jsx("span",{children:$e.label})]})]}),(e.dependencies&&e.dependencies.length>0||s||e.status==="queued"||e.blockedBy)&&t.jsxs("div",{className:"card-meta",children:[e.dependencies&&e.dependencies.length>0&&t.jsx("div",{className:"card-dep-list",children:e.dependencies.map(N=>t.jsxs("span",{className:"card-dep-badge clickable",onClick:H=>void Oe(H,N),title:`Click to view ${N}`,children:[t.jsx(Wi,{size:12,style:{verticalAlign:"middle"}})," ",N]},N))}),e.blockedBy&&t.jsxs("span",{className:"card-scope-badge","data-tooltip":`Blocked by ${e.blockedBy} (file overlap)`,children:[t.jsx(Si,{size:12,style:{verticalAlign:"middle"}})," ",e.blockedBy]}),(s||e.status==="queued")&&e.column!=="in-progress"&&t.jsxs("span",{className:"queued-badge",children:[t.jsx(ji,{size:12,style:{verticalAlign:"middle"}})," Queued"]})]}),(e.assignedAgentId||Z.length>0)&&t.jsxs("div",{className:"card-agent-row",children:[Z.length>0&&t.jsx("span",{className:"card-provider-icons","data-testid":"card-provider-icons",children:Z.map(N=>t.jsx(Mn,{provider:N,size:"sm"},N))}),e.assignedAgentId&&t.jsxs("span",{className:`card-agent-badge${oe?" card-agent-badge--loading":""}`,title:`Assigned to ${$??e.assignedAgentId}`,children:[t.jsx(an,{size:11}),t.jsx("span",{className:"card-agent-badge-text",children:Rj($??e.assignedAgentId,15)})]})]}),t.jsx(co,{slotId:"task-card-badge",projectId:n})]})}const $d=10,Kj=300,Dd=140;function Ld(e,n){return e?e.length>n?e.slice(0,n)+"…":e:""}const qr=a.memo(Gj,Wj);qr.displayName="TaskCard";function Jj({label:e,activeTasks:n,queuedTasks:s,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g}){return t.jsxs("div",{className:"worktree-group",children:[t.jsxs("div",{className:"worktree-group-header",children:[t.jsx("span",{className:"worktree-icon",children:e==="Up Next"||e==="Unassigned"?t.jsx(ig,{size:14}):t.jsx(Os,{size:14})}),t.jsx("span",{className:"worktree-label",children:e})]}),n.map(p=>t.jsx(qr,{task:p,projectId:i,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id)),s.map(p=>t.jsx(qr,{task:p,projectId:i,queued:!0,onOpenDetail:r,addToast:o,globalPaused:l,onUpdateTask:c,onOpenDetailWithTab:u,taskStuckTimeoutMs:d,onOpenMission:m,lastFetchTimeMs:h,workflowStepNameLookup:g},p.id))]})}const Ih=a.memo(Jj);Ih.displayName="WorktreeGroup";function zd(e){return e.toLowerCase().replace(/[-_./]/g,"")}function Yj(e,n){let s=0;for(let i=0;i<n.length&&s<e.length;i++)e[s]===n[i]&&s++;return s===e.length}function Qj(e,n,s){const i=e.length,r=n.length;if(i===0)return!0;if(r===0)return!1;let o=new Array(r+1).fill(0),l=new Array(r+1).fill(0);for(let c=1;c<=i;c++){const u=new Array(r+1);u[0]=c;for(let d=1;d<=r;d++){const m=e[c-1]===n[d-1]?0:1;u[d]=Math.min(l[d]+1,u[d-1]+1,l[d-1]+m),c>=2&&d>=2&&e[c-1]===n[d-2]&&e[c-2]===n[d-1]&&(u[d]=Math.min(u[d],o[d-2]+1))}o=l,l=u}for(let c=0;c<=r;c++)if(l[c]<=s)return!0;return!1}function Xj(e,n){const s=zd(e),i=zd(n);if(s.length===0||i.includes(s))return!0;const r=i.split(/\s+/).filter(Boolean);for(const o of r)if(s.length>=3&&Yj(s,o)||s.length>=4&&Qj(s,o,1))return!0;return!1}function Zj(e,n){const s=n.toLowerCase().trim().split(/\s+/).filter(Boolean);return s.length===0?e:e.filter(i=>{const r=`${i.provider} ${i.id} ${i.name}`;return s.every(o=>Xj(o,r))})}function wn({models:e,value:n,onChange:s,placeholder:i="Select a model…",disabled:r=!1,id:o,label:l,favoriteProviders:c=[],onToggleFavorite:u,favoriteModels:d=[],onToggleModelFavorite:m,noChangeValue:h,noChangeLabel:g="No change"}){const[p,f]=a.useState(!1),[b,v]=a.useState(""),[x,k]=a.useState(0),[M,y]=a.useState(null),[R,j]=a.useState(null),C=a.useRef(null),S=a.useRef(null),P=a.useRef(null),T=a.useRef(null),_=a.useRef(null),L=a.useMemo(()=>Zj(e,b),[e,b]),G=a.useMemo(()=>L.reduce((Q,de)=>((Q[de.provider]??=[]).push(de),Q),{}),[L]),$=a.useMemo(()=>{const Q=[];for(const de of d){const Te=de.indexOf("/");if(Te===-1)continue;const fe=de.slice(0,Te),Se=de.slice(Te+1),te=L.find(we=>we.provider===fe&&we.id===Se);te&&Q.push({model:te,fullId:de})}return Q},[d,L]),I=a.useMemo(()=>{const Q=Object.entries(G),de=new Set(c);return Q.sort(([Te],[fe])=>{const Se=de.has(Te),te=de.has(fe);if(Se&&!te)return-1;if(!Se&&te)return 1;if(Se&&te){const we=c.indexOf(Te),Pe=c.indexOf(fe);if(we!==Pe)return we-Pe}return Te.localeCompare(fe)})},[G,c]),w=typeof h=="string"&&h.length>0,q=a.useMemo(()=>{if(!n||w&&n===h)return null;const Q=n.indexOf("/");return Q===-1?null:n.slice(0,Q)},[w,h,n]),W=a.useMemo(()=>{const Q=[];return w&&Q.push({type:"no-change",value:h,label:g}),Q.push({type:"default",value:"",label:"Use default"}),Q},[w,g,h]),B=a.useMemo(()=>{const Q=[...W];for(const{model:de,fullId:Te}of $)Q.push({type:"favorite",value:Te,label:de.name,provider:de.provider});return I.forEach(([de,Te])=>{Q.push({type:"provider",value:`__group_${de}`,label:de,provider:de}),Te.forEach(fe=>{Q.push({type:"model",value:`${fe.provider}/${fe.id}`,label:fe.name,provider:fe.provider})})}),Q},[$,I,W]),A=a.useMemo(()=>{if(w&&n===h)return g;if(!n)return"Use default";const Q=n.indexOf("/");if(Q===-1)return n;const de=n.slice(0,Q),Te=n.slice(Q+1);return e.find(Se=>Se.provider===de&&Se.id===Te)?.name||n},[w,g,h,n,e]),z=a.useMemo(()=>B.findIndex(Q=>Q.value===n),[B,n]),X=a.useCallback(()=>{const Q=window.visualViewport;return Q&&Q.height>0&&Q.width>0?{width:Q.width,height:Q.height,offsetTop:Q.offsetTop,offsetLeft:Q.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),E=a.useCallback(()=>{const{height:Q}=X(),de=typeof window.matchMedia=="function",Te=de?window.matchMedia("(max-width: 640px)").matches:!1,fe=de?window.matchMedia("(max-width: 768px)").matches:!1;return Q<=0?320:Te?Math.min(Q*.6,360):fe?Math.min(Q*.7,420):320},[X]),U=a.useCallback(()=>{const Q=S.current;if(!Q)return;const de=Q.getBoundingClientRect(),{width:Te,height:fe,offsetTop:Se,offsetLeft:te}=X(),we=16,Pe=16,We=4,Ke=E(),Ne=de.bottom-Se,_e=de.top-Se,Oe=de.left-te,ye=fe-Ne,De=_e,se=Math.max(ye-Pe-We,160),J=Math.max(De-Pe-We,160),me=ye<Ke&&De>ye,ee=Math.max(Math.min(me?J:se,Ke),160),he=Math.min(de.width,Te-we*2),le=Math.min(Math.max(Oe,we),Te-we-he)+te,Ie=me?Math.max(Pe+Se,_e-ee-We+Se):Math.min(Ne+We+Se,fe+Se-Pe-ee);y({top:Ie,left:le,width:he,maxHeight:ee})},[X,E]);a.useEffect(()=>{j(document.body)},[]),a.useEffect(()=>{if(p){const Q=B.findIndex((de,Te)=>Te>=(z>=0?z:0)&&de.type!=="provider");k(Q>=0?Q:0)}},[p,B,z]),a.useEffect(()=>{if(!p)return;U();const Q=requestAnimationFrame(()=>T.current?.focus());return()=>cancelAnimationFrame(Q)},[p,U]),a.useEffect(()=>{if(!p)return;const Q=()=>U();window.addEventListener("resize",Q),window.addEventListener("scroll",Q,!0);const de=window.visualViewport;return de&&(de.addEventListener("resize",Q),de.addEventListener("scroll",Q)),()=>{window.removeEventListener("resize",Q),window.removeEventListener("scroll",Q,!0),de&&(de.removeEventListener("resize",Q),de.removeEventListener("scroll",Q))}},[p,U]),a.useEffect(()=>{if(!p)return;const Q=de=>{const Te=de.target,fe=C.current?.contains(Te),Se=P.current?.contains(Te);!fe&&!Se&&(f(!1),v(""))};return document.addEventListener("mousedown",Q),()=>document.removeEventListener("mousedown",Q)},[p]);const pe=a.useCallback(Q=>{switch(Q.key){case"ArrowDown":if(Q.preventDefault(),!p)f(!0);else{let de=x;for(let Te=1;Te<=B.length;Te++){const fe=(x+Te)%B.length;if(B[fe]?.type!=="provider"){de=fe;break}}k(de)}break;case"ArrowUp":if(Q.preventDefault(),p){let de=x;for(let Te=1;Te<=B.length;Te++){const fe=(x-Te+B.length)%B.length;if(B[fe]?.type!=="provider"){de=fe;break}}k(de)}break;case"Enter":if(Q.preventDefault(),p){const de=B[x];de&&de.type!=="provider"&&de.type!=="favorite"&&(s(de.value),f(!1),v(""))}else f(!0);break;case"Escape":Q.preventDefault(),f(!1),v("");break;case"Tab":p&&(f(!1),v(""));break}},[p,x,B,s]),ie=a.useCallback(Q=>{s(Q),f(!1),v("")},[s]),re=a.useCallback(()=>{v(""),T.current?.focus()},[]),F=a.useCallback(()=>{r||f(Q=>!Q)},[r]);a.useEffect(()=>{if(p&&_.current){const Q=_.current.querySelector(`[data-index="${x}"]`);Q&&typeof Q.scrollIntoView=="function"&&Q.scrollIntoView({block:"nearest"})}},[x,p]);const ce=b.length>0,ae=p&&M?t.jsxs("div",{ref:P,className:"model-combobox-dropdown model-combobox-dropdown--portal",role:"listbox","data-testid":"model-combobox-portal",onKeyDown:pe,style:{top:`${M.top}px`,left:`${M.left}px`,width:`${M.width}px`,maxHeight:`${M.maxHeight}px`},children:[t.jsxs("div",{className:"model-combobox-search-wrapper",children:[t.jsx("input",{ref:T,type:"text",className:"model-combobox-search",placeholder:"Filter models…",value:b,onChange:Q=>v(Q.target.value),onClick:Q=>Q.stopPropagation()}),ce&&t.jsx("button",{type:"button",className:"model-combobox-clear",onClick:re,"aria-label":"Clear filter",children:"×"})]}),t.jsxs("div",{className:"model-combobox-results-count",children:[L.length," model",L.length!==1?"s":""]}),t.jsxs("div",{ref:_,className:"model-combobox-list",children:[W.map((Q,de)=>t.jsx("div",{"data-index":de,className:`model-combobox-option ${x===de?"model-combobox-option--highlighted":""} ${n===Q.value?"model-combobox-option--selected":""}`,onClick:()=>ie(Q.value),onMouseEnter:()=>k(de),role:"option","aria-selected":n===Q.value,children:t.jsx("span",{className:"model-combobox-option-text model-combobox-option-text--default",children:Q.label})},`${Q.type}-${Q.value}`)),$.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"model-combobox-divider"}),$.map(({model:Q,fullId:de},Te)=>{const fe=Te+W.length,Se=x===fe,te=n===de;return t.jsxs("div",{"data-index":fe,className:`model-combobox-option model-combobox-option--favorite ${Se?"model-combobox-option--highlighted":""} ${te?"model-combobox-option--selected":""}`,onClick:()=>ie(de),onMouseEnter:()=>k(fe),role:"option","aria-selected":te,children:[t.jsxs("span",{className:"model-combobox-option-main",children:[t.jsx("span",{className:"model-combobox-option-icon",children:t.jsx(Mn,{provider:Q.provider,size:"sm"})}),t.jsx("span",{className:"model-combobox-option-text",children:Q.name})]}),t.jsx("span",{className:"model-combobox-option-id",children:Q.id}),m&&t.jsx("button",{type:"button",className:"model-combobox-option-favorite model-combobox-option-favorite--active",onClick:we=>{we.stopPropagation(),m(de)},title:"Remove from favorites","aria-label":`Remove ${Q.name} from favorites`,children:"★"})]},de)}),t.jsx("div",{className:"model-combobox-divider"})]}),I.map(([Q,de])=>{const Te=B.findIndex(te=>te.value===`__group_${Q}`),fe=c.includes(Q),Se=de.filter(te=>{const we=`${te.provider}/${te.id}`;return!d.includes(we)});return Se.length===0?null:t.jsxs("div",{className:"model-combobox-group",children:[t.jsxs("div",{className:"model-combobox-optgroup","data-index":Te,children:[t.jsx(Mn,{provider:Q,size:"sm"}),t.jsx("span",{className:"model-combobox-optgroup-text",children:Q}),u&&t.jsx("button",{type:"button",className:`model-combobox-optgroup-favorite ${fe?"model-combobox-optgroup-favorite--active":""}`,onClick:te=>{te.stopPropagation(),u(Q)},title:fe?"Remove from favorites":"Add to favorites","aria-label":fe?`Remove ${Q} from favorites`:`Add ${Q} to favorites`,children:"★"})]}),Se.map(te=>{const we=`${te.provider}/${te.id}`,Pe=B.findIndex(_e=>_e.value===we),We=x===Pe,Ke=n===we,Ne=d.includes(we);return t.jsxs("div",{"data-index":Pe,className:`model-combobox-option ${We?"model-combobox-option--highlighted":""} ${Ke?"model-combobox-option--selected":""}`,onClick:()=>ie(we),onMouseEnter:()=>k(Pe),role:"option","aria-selected":Ke,children:[t.jsx("span",{className:"model-combobox-option-text",children:te.name}),t.jsx("span",{className:"model-combobox-option-id",children:te.id}),m&&t.jsx("button",{type:"button",className:`model-combobox-option-favorite ${Ne?"model-combobox-option-favorite--active":""}`,onClick:_e=>{_e.stopPropagation(),m(we)},title:Ne?"Remove from favorites":"Add to favorites","aria-label":Ne?`Remove ${te.name} from favorites`:`Add ${te.name} to favorites`,children:Ne?"★":"☆"})]},we)})]},Q)}),L.length===0&&ce&&t.jsxs("div",{className:"model-combobox-no-results",children:["No models match '",b,"'"]})]})]}):null;return t.jsxs(t.Fragment,{children:[t.jsx("div",{ref:C,className:"model-combobox",onKeyDown:pe,children:t.jsxs("button",{ref:S,type:"button",id:o,className:"model-combobox-trigger",onClick:F,disabled:r,"aria-haspopup":"listbox","aria-expanded":p,"aria-label":l,children:[q&&t.jsx("span",{className:"model-combobox-trigger-icon",children:t.jsx(Mn,{provider:q,size:"sm"})}),t.jsx("span",{className:"model-combobox-trigger-text",children:A||i}),t.jsx("span",{className:"model-combobox-trigger-arrow",children:"▼"})]})}),R&&ae?Ta.createPortal(ae,R):null]})}function hc(e,n){return typeof n!="string"||n.length===0?e:`kb:${n}:${e}`}function Nn(e,n){return typeof window>"u"?null:window.localStorage.getItem(hc(e,n))}function ts(e,n,s){typeof window>"u"||window.localStorage.setItem(hc(e,s),n)}function Ha(e,n){typeof window>"u"||window.localStorage.removeItem(hc(e,n))}const fa="kb-quick-entry-text",ew=["image/png","image/jpeg","image/gif","image/webp"];function $o(e,n){return e&&n?`${e}/${n}`:""}function Do(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Ph({onCreate:e,addToast:n,tasks:s=[],availableModels:i,onPlanningMode:r,onSubtaskBreakdown:o,projectId:l,autoExpand:c=!0,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h}){const[g,p]=a.useState(()=>typeof window<"u"&&Nn(fa,l)||""),[f,b]=a.useState(!1),[v,x]=a.useState(!1),[k,M]=a.useState(!1),y=a.useRef(null),R=a.useRef(null),j=a.useRef(!1),C=a.useRef(l),[S,P]=a.useState([]),T=a.useRef([]),[_,L]=a.useState([]),[G,$]=a.useState(!1),[I,w]=a.useState(""),[q,W]=a.useState(null),[B,A]=a.useState([]),[z,X]=a.useState(void 0),[E,U]=a.useState(!1),[pe,ie]=a.useState(!1),[re,F]=a.useState(!1),[ce,ae]=a.useState(null),[Q,de]=a.useState(void 0),[Te,fe]=a.useState(void 0),[Se,te]=a.useState(void 0),[we,Pe]=a.useState(void 0),[We,Ke]=a.useState(void 0),[Ne,_e]=a.useState(void 0),Oe=a.useRef(null),ye=a.useRef(null),De=a.useRef(null),se=a.useRef(null),[J,me]=a.useState(null),[ee,he]=a.useState(null),le=a.useRef(null),Ie=a.useRef(null),[Ze,at]=a.useState(null),[oe]=a.useState(()=>typeof document<"u"?document.body:null),[Z,ue]=a.useState(!1),[Ce,$e]=a.useState(null),[ve,Ge]=a.useState(i??[]),[je,Ue]=a.useState([]),[He,ge]=a.useState([]),[Fe,be]=a.useState(null),[Je,st]=a.useState(void 0),[dt,Tt]=a.useState(!1),[$t,Dt]=a.useState(!1),[Bt,qt]=a.useState(!1),Lt=a.useRef(null),Ct=a.useRef(null),[xt,Et]=a.useState(null),Le=u??je,gt=d??He,ut=!e;a.useEffect(()=>{if(i)Ge(i),ue(!1),$e(null);else{let ne=!1;return ue(!0),$e(null),is().then(Ee=>{ne||(Ge(Ee.models),u||Ue(Ee.favoriteProviders),d||ge(Ee.favoriteModels))}).catch(Ee=>{ne||$e(xe(Ee)||"Failed to load models")}).finally(()=>{ne||ue(!1)}),ro(l).then(Ee=>{ne||be(Ee)}).catch(()=>{}),()=>{ne=!0}}},[i,u,d,l]);const Me=$o(Q,Te),Qe=$o(Se,we),rt=$o(We,Ne),N=!!(Q&&Te),H=!!(Se&&we),Ae=!!(We&&Ne),ot=Number(N)+Number(H)+Number(Ae),kt=Je?Fe?.modelPresets?.find(ne=>ne.id===Je)?.name??"Models":ot>0?`${ot} model${ot===1?"":"s"}`:"Models",Ot=a.useCallback((ne,Ee)=>{if(!ne||!Ee)return"Using default";const nt=ve.find(ft=>ft.provider===ne&&ft.id===Ee);return nt?`${nt.provider}/${nt.id}`:`${ne}/${Ee}`},[ve]);a.useEffect(()=>{p(Nn(fa,l)||"")},[l]),a.useEffect(()=>{typeof window<"u"&&ts(fa,g,l)},[g,l]),a.useEffect(()=>{C.current!==l&&(C.current=l,A([]),X(void 0),W(null),U(!1),me(null))},[l]),a.useEffect(()=>{typeof window<"u"&&localStorage.removeItem("kb-quick-entry-expanded")},[]),a.useEffect(()=>{T.current=S},[S]),a.useEffect(()=>()=>{T.current.forEach(ne=>URL.revokeObjectURL(ne.previewUrl))},[]);const sn=a.useCallback(()=>{const ne=y.current;if(!ne)return;ne.style.height="auto";const Ee=Math.min(ne.scrollHeight,200);ne.style.height=`${Ee}px`},[]);a.useEffect(()=>{v&&sn()},[g,v,sn]),a.useEffect(()=>{if(!f&&g===""&&y.current){const ne=setTimeout(()=>{y.current?.focus()},0);return()=>clearTimeout(ne)}},[f,g]),a.useEffect(()=>{G||w("")},[G]),a.useEffect(()=>{if(!$t)return;const ne=Ee=>{const nt=Ee.target,ft=Lt.current?.contains(nt),bt=Ct.current?.contains(nt);!ft&&!bt&&Dt(!1)};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[$t]),a.useEffect(()=>{if(!re)return;const ne=Ee=>{const nt=Ee.target,ft=Oe.current?.contains(nt),bt=ye.current?.contains(nt),on=nt instanceof Element&&nt.closest?.(".model-combobox-dropdown--portal")!=null;!ft&&!bt&&!on&&(F(!1),ae(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[re]),a.useEffect(()=>{if(!E)return;const ne=Ee=>{const nt=Ee.target;De.current?.contains(nt)||se.current?.contains(nt)||(U(!1),me(null))};return document.addEventListener("mousedown",ne),()=>document.removeEventListener("mousedown",ne)},[E]);const Rt=a.useCallback(()=>{S.forEach(ne=>URL.revokeObjectURL(ne.previewUrl)),P([]),R.current&&(R.current.value=""),p(""),L([]),W(null),U(!1),me(null),de(void 0),fe(void 0),te(void 0),Pe(void 0),Ke(void 0),_e(void 0),st(void 0),Tt(!1),$(!1),F(!1),he(null),ae(null),Dt(!1),qt(!1),x(!1),M(!1),j.current=!0,y.current&&(y.current.style.height="auto"),typeof window<"u"&&Ha(fa,l)},[S,l]),zn=a.useCallback(ne=>{if(!ne||ne.length===0)return;const Ee=[];for(let nt=0;nt<ne.length;nt++){const ft=ne[nt];ew.includes(ft.type)&&Ee.push({file:ft,previewUrl:URL.createObjectURL(ft)})}Ee.length>0&&P(nt=>[...nt,...Ee])},[]),Wn=a.useCallback(ne=>{f||zn(ne.clipboardData?.files)},[zn,f]),ms=a.useCallback(ne=>{P(Ee=>{const nt=Ee[ne];return nt&&URL.revokeObjectURL(nt.previewUrl),Ee.filter((ft,bt)=>bt!==ne)})},[]),pn=a.useCallback(async()=>{const ne=g.trim();if(!(!ne||f||!e)){b(!0);try{const Ee=await e({description:ne,column:"triage",dependencies:_.length?_:void 0,...q?{assignedAgentId:q}:{},modelPresetId:Je,modelProvider:N?Q:void 0,modelId:N?Te:void 0,validatorModelProvider:H?Se:void 0,validatorModelId:H?we:void 0,planningModelProvider:Ae?We:void 0,planningModelId:Ae?Ne:void 0,...dt?{executionMode:"fast"}:{}});if(Ee&&S.length>0){const nt=[];for(const ft of S)try{await Ua(Ee.id,ft.file,l)}catch{nt.push(ft.file.name)}nt.length>0&&n(`Failed to upload: ${nt.join(", ")}`,"error")}Rt()}catch(Ee){n(xe(Ee)||"Failed to create task","error")}finally{b(!1)}}},[g,f,e,_,q,N,Q,Te,H,Se,we,Ae,We,Ne,S,l,n,Rt,dt]),Fn=a.useCallback(ne=>{if(ne.key==="Enter"){if(ne.shiftKey&&v)return;ne.preventDefault(),pn()}else if(ne.key==="Escape"){if(ne.preventDefault(),ce){ae(null);return}if(re){F(!1),he(null);return}if(G){$(!1);return}if($t){Dt(!1);return}if(E){U(!1),me(null);return}g.trim()&&(p(""),y.current&&(y.current.style.height="auto"),typeof window<"u"&&Ha(fa,l)),x(!1),M(!1),y.current?.blur()}},[pn,g,v,G,E,re,ce,$t,l,M]),Sn=a.useCallback(()=>{j.current&&(j.current=!1)},[]),fn=a.useCallback(()=>{c&&x(!0)},[c]),Gn=a.useCallback(ne=>{L(Ee=>Ee.includes(ne)?Ee.filter(nt=>nt!==ne):[...Ee,ne])},[]),dn=a.useCallback(()=>{const ne=window.visualViewport;return ne&&ne.width>0&&ne.height>0?{width:ne.width,height:ne.height,offsetTop:ne.offsetTop,offsetLeft:ne.offsetLeft}:{width:window.innerWidth,height:window.innerHeight,offsetTop:0,offsetLeft:0}},[]),Mt=a.useCallback(()=>{const ne=Oe.current;if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:nt,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Xt=16,cn=16,Gt=4,bn=nt<=768,Cn=Math.min(bn?ft*.6:ft*.5,360),gs=bn?Math.min(nt-Xt*2,360):Math.max(Ee.width,240),Un=Math.min(gs,Math.max(nt-Xt*2,200)),Jn=Ee.top-bt,Bn=Ee.bottom-bt,Yn=Ee.left-on,un=ft-Bn,Qn=Jn,Es=Math.max(un-cn-Gt,160),Is=Math.max(Qn-cn-Gt,160),rs=un<Cn&&Qn>un,An=Math.max(Math.min(rs?Is:Es,Cn),160),bs=Math.min(Math.max(Yn,Xt),nt-Xt-Un)+on,Tn=rs?Math.max(cn+bt,Jn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);he({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]),yn=a.useCallback(()=>{const ne=Lt.current?.querySelector(".refine-button");if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:nt,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Xt=8,cn=12,Gt=4,bn=Math.min(200,Math.max(ft-cn*2,160)),Cn=Math.min(200,nt-Xt*2),gs=Ee.top-bt,Un=Ee.bottom-bt,Jn=Ee.left-on,Bn=ft-Un,Yn=gs,un=Bn<bn&&Yn>Bn,Qn=Math.min(Math.max(Jn,Xt),nt-Xt-Cn)+on,Es=un?Math.max(cn+bt,gs-bn-Gt+bt):Math.min(Un+Gt+bt,ft+bt-cn-bn);Et({top:Es,left:Qn})},[dn]),Kn=a.useCallback(()=>{const ne=le.current;if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:nt,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Xt=16,cn=16,Gt=4,bn=nt<=768,Cn=Math.min(bn?ft*.6:ft*.5,320),gs=bn?Math.min(nt-Xt*2,360):Math.max(Ee.width,280),Un=Math.min(gs,Math.max(nt-Xt*2,240)),Jn=Ee.top-bt,Bn=Ee.bottom-bt,Yn=Ee.left-on,un=ft-Bn,Qn=Jn,Es=Math.max(un-cn-Gt,200),Is=Math.max(Qn-cn-Gt,200),rs=un<Cn&&Qn>un,An=Math.max(Math.min(rs?Is:Es,Cn),200),bs=Math.min(Math.max(Yn,Xt),nt-Xt-Un)+on,Tn=rs?Math.max(cn+bt,Jn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);at({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]),kn=a.useCallback(()=>{const ne=De.current?.querySelector("button");if(!ne)return;const Ee=ne.getBoundingClientRect(),{width:nt,height:ft,offsetTop:bt,offsetLeft:on}=dn(),Xt=16,cn=16,Gt=4,bn=nt<=768,Cn=Math.min(bn?ft*.6:ft*.5,320),gs=bn?Math.min(nt-Xt*2,280):Math.max(Ee.width,240),Un=Math.min(gs,Math.max(nt-Xt*2,200)),Jn=Ee.top-bt,Bn=Ee.bottom-bt,Yn=Ee.left-on,un=ft-Bn,Qn=Jn,Es=Math.max(un-cn-Gt,160),Is=Math.max(Qn-cn-Gt,160),rs=un<Cn&&Qn>un,An=Math.max(Math.min(rs?Is:Es,Cn),160),bs=Math.min(Math.max(Yn,Xt),nt-Xt-Un)+on,Tn=rs?Math.max(cn+bt,Jn-An-Gt+bt):Math.min(Bn+Gt+bt,ft+bt-cn-An);me({top:Tn,left:bs,width:Un,maxHeight:An})},[dn]);a.useEffect(()=>{if(!re)return;const ne=()=>Mt();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[re,Mt]),a.useEffect(()=>{if(!$t)return;const ne=()=>yn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[$t,yn]),a.useEffect(()=>{if(!G)return;const ne=()=>Kn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[G,Kn]),a.useEffect(()=>{if(!E)return;const ne=()=>kn();window.addEventListener("resize",ne),window.addEventListener("scroll",ne,!0);const Ee=window.visualViewport;return Ee&&(Ee.addEventListener("resize",ne),Ee.addEventListener("scroll",ne)),()=>{window.removeEventListener("resize",ne),window.removeEventListener("scroll",ne,!0),Ee&&(Ee.removeEventListener("resize",ne),Ee.removeEventListener("scroll",ne))}},[E,kn]);const _n=a.useCallback(ne=>{const Ee=Do(ne);Ke(Ee.provider),_e(Ee.modelId)},[]),hs=a.useCallback(ne=>{const Ee=Do(ne);de(Ee.provider),fe(Ee.modelId)},[]),ps=a.useCallback(ne=>{const Ee=Do(ne);te(Ee.provider),Pe(Ee.modelId)},[]),On=a.useCallback(async ne=>{if(m){m(ne);return}const Ee=je,ft=Ee.includes(ne)?Ee.filter(bt=>bt!==ne):[ne,...Ee];Ue(ft);try{await nn({favoriteProviders:ft,favoriteModels:He})}catch{Ue(Ee)}},[je,He,m]),K=a.useCallback(async ne=>{if(h){h(ne);return}const Ee=He,ft=Ee.includes(ne)?Ee.filter(bt=>bt!==ne):[ne,...Ee];ge(ft);try{await nn({favoriteProviders:je,favoriteModels:ft})}catch{ge(Ee)}},[He,je,h]),ze=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}r?.(ne),Rt()},[g,r,n,Rt]),tt=a.useCallback(()=>{const ne=g.trim();if(!ne){n("Enter a description first","error");return}o?.(ne),Rt()},[g,o,n,Rt]),et=a.useCallback(()=>{pn()},[pn]),mt=a.useCallback(async ne=>{const Ee=g.trim();if(!(!Ee||Bt)){Dt(!1),qt(!0);try{const nt=await bh(Ee,ne,l);p(nt),n("Description refined with AI","success"),y.current&&(y.current.style.height="auto",y.current.style.height=`${Math.min(y.current.scrollHeight,200)}px`)}catch(nt){const ft=xh(nt);n(ft,"error")}finally{qt(!1)}}},[g,Bt,n,l]),jt=(ne,Ee)=>ne.length>Ee?ne.slice(0,Ee)+"…":ne,_t=a.useCallback(async()=>{if(i){Ge(i),$e(null),ue(!1);return}ue(!0),$e(null);try{const ne=await is();Ge(ne.models),u||Ue(ne.favoriteProviders),d||ge(ne.favoriteModels)}catch(ne){$e(xe(ne)||"Failed to load models")}finally{ue(!1)}},[i,u,d]),gn=a.useCallback(async()=>{if(B.length>0&&z===l){U(!0),kn();return}ie(!0);try{const ne=await oa(void 0,l);A(ne),X(l),U(!0),kn()}catch(ne){const Ee=xe(ne);n(Ee?`Failed to load agents: ${Ee}`:"Failed to load agents","error"),U(!1)}finally{ie(!1)}},[B.length,z,l,n,kn]),Qt=(q?B.find(ne=>ne.id===q):void 0)?.name??q,vt=k,ct=a.useCallback(()=>{M(ne=>{const Ee=!ne;return x(Ee),Ee})},[]);return t.jsxs("div",{className:`quick-entry-box ${k?"quick-entry-box--expanded":"quick-entry-box--collapsed"}`,"data-testid":"quick-entry-box",children:[t.jsx("div",{className:"description-with-refine",children:t.jsxs("div",{className:"quick-entry-main-row",children:[t.jsx("div",{className:"quick-entry-textarea-wrap",children:t.jsx("textarea",{ref:y,className:`quick-entry-input ${v?"quick-entry-input--expanded":""}`,placeholder:f?"Creating...":"Add a task...",value:g,onChange:ne=>p(ne.target.value),onKeyDown:Fn,onPaste:Wn,onFocus:fn,onBlur:Sn,disabled:f||ut,"data-testid":"quick-entry-input",rows:2,"aria-controls":"quick-entry-controls","aria-expanded":k})}),t.jsx("button",{type:"button",className:"btn btn-sm quick-entry-toggle",onClick:ct,"aria-expanded":k,"aria-controls":"quick-entry-controls","data-testid":"quick-entry-toggle",title:k?"Collapse":"Expand",children:k?t.jsx(Ys,{size:14}):t.jsx(zt,{size:14})})]})}),t.jsxs("div",{id:"quick-entry-controls",className:"quick-entry-controls",hidden:!vt,"aria-hidden":!vt,children:[vt&&!f&&t.jsxs("div",{className:"quick-entry-actions","data-testid":"quick-entry-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:ze,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"plan-button",title:"Open planning mode with current description",children:[t.jsx(Us,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Plan"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:tt,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim(),"data-testid":"subtask-button",title:"Break down into AI-generated subtasks",children:[t.jsx(no,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Subtask"]}),t.jsxs("div",{className:"refine-trigger-wrap",ref:Lt,children:[t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${Bt?"refine-button--loading":""}`,onClick:()=>{Dt(ne=>{const Ee=!ne;return Ee?yn():Et(null),Ee})},disabled:!g.trim()||Bt,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle"}}),Bt?"Refining...":"Refine"]}),$t&&oe&&xt&&Ta.createPortal(t.jsxs("div",{ref:Ct,className:"refine-menu refine-menu--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${xt.top}px`,left:`${xt.left}px`},children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>mt("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]}),oe)]}),t.jsx("div",{className:"dep-trigger-wrap",children:t.jsxs("button",{ref:le,type:"button",className:"btn btn-sm dep-trigger","data-testid":"quick-entry-deps",onClick:()=>{$(ne=>{const Ee=!ne;return Ee?(F(!1),he(null),ae(null),U(!1),Kn()):at(null),Ee})},children:[t.jsx(Wi,{size:12,style:{verticalAlign:"middle"}}),_.length>0?`${_.length} deps`:"Deps"]})}),G&&oe&&Ze&&(()=>{const ne=I.toLowerCase(),Ee=(ne?s.filter(nt=>nt.id.toLowerCase().includes(ne)||nt.title&&nt.title.toLowerCase().includes(ne)||nt.description&&nt.description.toLowerCase().includes(ne)):[...s]).sort((nt,ft)=>{const bt=ft.createdAt.localeCompare(nt.createdAt);if(bt!==0)return bt;const on=parseInt(nt.id.slice(nt.id.lastIndexOf("-")+1),10)||0;return(parseInt(ft.id.slice(ft.id.lastIndexOf("-")+1),10)||0)-on});return Ta.createPortal(t.jsxs("div",{ref:Ie,className:"dep-dropdown dep-dropdown--portal",onMouseDown:nt=>nt.preventDefault(),style:{position:"fixed",top:`${Ze.top}px`,left:`${Ze.left}px`,width:`${Ze.width}px`,maxHeight:Ze.maxHeight?`${Ze.maxHeight}px`:void 0,overflowY:Ze.maxHeight?"auto":void 0},children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:I,onChange:nt=>w(nt.target.value),onClick:nt=>nt.stopPropagation()}),Ee.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No existing tasks"}):Ee.map(nt=>t.jsxs("div",{className:`dep-dropdown-item${_.includes(nt.id)?" selected":""}`,onMouseDown:ft=>ft.preventDefault(),onClick:()=>Gn(nt.id),children:[t.jsx("span",{className:"dep-dropdown-id",children:nt.id}),t.jsx("span",{className:"dep-dropdown-title",children:jt(nt.title||nt.description||nt.id,60)})]},nt.id))]}),oe)})(),t.jsxs("button",{type:"button",className:"btn btn-sm","data-testid":"quick-entry-attach",onClick:()=>R.current?.click(),children:[t.jsx(xb,{size:12,style:{verticalAlign:"middle"}}),S.length>0?`Attach (${S.length})`:"Attach"]}),t.jsxs("button",{ref:Oe,type:"button",className:"btn btn-sm","data-testid":"quick-entry-models",onClick:()=>{$(!1),U(!1),ae(null),F(!0),Mt()},children:[t.jsx(Pr,{size:12,style:{verticalAlign:"middle"}}),kt]}),t.jsx("div",{className:"agent-trigger-wrap",ref:De,children:t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{E?(U(!1),me(null)):gn()},"data-testid":"quick-entry-agent-button",children:[t.jsx(an,{size:12,style:{verticalAlign:"middle"}}),Qt?` ${Qt}`:" Agent"]})}),E&&oe&&J&&Ta.createPortal(t.jsxs("div",{ref:se,className:"dep-dropdown agent-picker-dropdown agent-picker-dropdown--portal",onMouseDown:ne=>ne.preventDefault(),style:{position:"fixed",top:`${J.top}px`,left:`${J.left}px`,width:`${J.width}px`,maxHeight:J.maxHeight?`${J.maxHeight}px`:void 0,overflowY:J.maxHeight?"auto":void 0},children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),pe&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!pe&&B.filter(ne=>ne.state!=="terminated").map(ne=>t.jsxs("div",{className:`dep-dropdown-item${q===ne.id?" selected":""}`,onMouseDown:Ee=>Ee.preventDefault(),onClick:()=>{W(ne.id===q?null:ne.id),U(!1),me(null)},children:[t.jsx(an,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ne.role}),t.jsx("span",{className:"dep-dropdown-title",children:ne.name})]},ne.id)),!pe&&B.filter(ne=>ne.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),q&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ne=>ne.preventDefault(),onClick:()=>{W(null),U(!1),me(null)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]}),oe),t.jsx("button",{type:"button",className:`btn btn-sm ${dt?"btn-primary":""}`,onClick:()=>Tt(ne=>!ne),onMouseDown:ne=>ne.preventDefault(),"aria-pressed":dt,"data-testid":"quick-entry-fast-toggle",title:"Toggle fast execution mode",children:"Fast"}),t.jsxs("button",{type:"button",className:"btn btn-task-create btn-sm",onClick:et,onMouseDown:ne=>ne.preventDefault(),disabled:!g.trim()||f,"data-testid":"quick-entry-save",title:"Create task",children:[t.jsx(lh,{size:12,style:{verticalAlign:"middle",marginRight:4}}),"Save"]})]}),S.length>0&&t.jsx("div",{className:"inline-create-previews",children:S.map((ne,Ee)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:ne.previewUrl,alt:ne.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>ms(Ee),disabled:f,title:"Remove image","data-testid":`quick-entry-preview-remove-${Ee}`,children:"×"})]},ne.previewUrl))}),re&&oe&&ee&&Ta.createPortal(t.jsx("div",{ref:ye,className:"model-nested-menu model-nested-menu--portal",onMouseDown:ne=>ne.preventDefault(),"data-testid":"model-nested-menu",style:{position:"fixed",top:`${ee.top}px`,left:`${ee.left}px`,width:`${ee.width}px`,maxHeight:ee.maxHeight?`${ee.maxHeight}px`:void 0,overflowY:ee.maxHeight?"auto":void 0},children:ce===null?t.jsxs("div",{className:"model-menu-items",children:[t.jsxs("button",{type:"button",className:`model-menu-item ${Ae?"model-menu-item--active":""}`,onClick:()=>ae("plan"),"data-testid":"model-menu-plan",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Us,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Plan"]}),t.jsx("span",{className:"model-menu-item-value",children:Ae?Ot(We,Ne):"Using default"}),t.jsx(en,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${N?"model-menu-item--active":""}`,onClick:()=>ae("executor"),"data-testid":"model-menu-executor",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Executor"]}),t.jsx("span",{className:"model-menu-item-value",children:N?Ot(Q,Te):"Using default"}),t.jsx(en,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]}),t.jsxs("button",{type:"button",className:`model-menu-item ${H?"model-menu-item--active":""}`,onClick:()=>ae("validator"),"data-testid":"model-menu-validator",children:[t.jsxs("span",{className:"model-menu-item-label",children:[t.jsx(Pr,{size:12,style:{verticalAlign:"middle",marginRight:6}}),"Validator"]}),t.jsx("span",{className:"model-menu-item-value",children:H?Ot(Se,we):"Using default"}),t.jsx(en,{size:12,style:{marginLeft:"auto",color:"var(--text-dim)"}})]})]}):t.jsxs("div",{className:"model-submenu",children:[t.jsxs("button",{type:"button",className:"model-submenu-back",onClick:()=>ae(null),"data-testid":"model-submenu-back",children:[t.jsx(zt,{size:12,style:{transform:"rotate(90deg)",marginRight:4}}),"Back"]}),t.jsxs("div",{className:"model-submenu-header",children:[ce==="plan"&&"Plan Model",ce==="executor"&&"Executor Model",ce==="validator"&&"Validator Model"]}),t.jsx(wn,{models:ve,value:ce==="plan"?rt:ce==="executor"?Me:Qe,onChange:ce==="plan"?_n:ce==="executor"?hs:ps,placeholder:"Using default",disabled:Z,id:`model-${ce}-select`,label:`${ce} model`,favoriteProviders:Le,onToggleFavorite:On,favoriteModels:gt,onToggleModelFavorite:K}),Ce&&t.jsxs("div",{className:"model-submenu-error",children:[t.jsx("span",{children:Ce}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:_t,children:"Retry"})]})]})}),oe)]}),t.jsx("input",{ref:R,type:"file",accept:"image/*",multiple:!0,style:{display:"none"},onChange:ne=>{zn(ne.target.files),ne.currentTarget.value=""},"data-testid":"quick-entry-file-input"}),t.jsx("div",{className:"quick-entry-hint",children:"Enter to create · Esc to cancel"})]})}function tw(e){const n=e.replace(/\/+$/,"").split("/");return n[n.length-1]||e}function nw(e){const n=new Map(e.map(l=>[l.id,l])),s=[],i=new Set,r=new Set;function o(l){if(i.has(l)||r.has(l))return;r.add(l);const c=n.get(l);if(c)for(const u of c.dependencies||[])n.has(u)&&o(u);r.delete(l),i.add(l),s.push(l)}for(const l of e)o(l.id);return s}function sw(e,n,s){const i=e.filter(f=>f.worktree),r=e.filter(f=>!f.worktree),o=new Map;for(const f of i){const b=f.worktree,v=o.get(b)||[];v.push(f),o.set(b,v)}const l=new Map(n.map(f=>[f.id,f])),u=n.filter(f=>f.column==="todo").filter(f=>!f.paused&&(f.dependencies||[]).every(b=>{const v=l.get(b);return v&&(v.column==="done"||v.column==="in-review"||v.column==="archived")})),m=nw(u).map(f=>l.get(f)).filter(f=>f!==void 0&&u.includes(f)),h=[],g=Array.from(o.keys());for(const f of g)h.push({label:tw(f),activeTasks:o.get(f),queuedTasks:[]});r.length>0&&h.push({label:"Unassigned",activeTasks:r,queuedTasks:[]});const p=m.slice(0,s);return p.length>0&&h.push({label:"Up Next",activeTasks:[],queuedTasks:p}),h}const Fd=100,Lo=50,Od=25;function iw({column:e,tasks:n,projectId:s,maxConcurrent:i,onMoveTask:r,onPauseTask:o,onOpenDetail:l,addToast:c,onQuickCreate:u,onNewTask:d,autoMerge:m,onToggleAutoMerge:h,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,onArchiveAllDone:x,collapsed:k,onToggleCollapse:M,allTasks:y,availableModels:R,onPlanningMode:j,onSubtaskBreakdown:C,onOpenDetailWithTab:S,favoriteProviders:P,favoriteModels:T,onToggleFavorite:_,onToggleModelFavorite:L,isSearchActive:G,taskStuckTimeoutMs:$,onOpenMission:I,lastFetchTimeMs:w,workflowStepNameLookup:q}){const[W,B]=a.useState(!1),[A,z]=a.useState(Lo),[X,E]=a.useState(!1),[U,pe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),ae=a.useRef(null),Q=sj(n.length);a.useEffect(()=>{if(!X)return;function he(Ie){ae.current?.contains(Ie.target)||E(!1)}function le(Ie){Ie.key==="Escape"&&E(!1)}return document.addEventListener("mousedown",he),document.addEventListener("keydown",le),()=>{document.removeEventListener("mousedown",he),document.removeEventListener("keydown",le)}},[X]);const de=e==="archived",Te=de&&k,fe=!de&&!G&&e!=="in-progress"&&n.length>Fd;a.useEffect(()=>{z(he=>e==="in-progress"||de||n.length<=Fd?Lo:Math.min(Math.max(he,Lo),n.length))},[e,de,n.length]);const Se=a.useCallback(he=>{de||(he.preventDefault(),he.dataTransfer.dropEffect="move",B(!0))},[de]),te=a.useCallback(he=>{he.currentTarget.contains(he.relatedTarget)||B(!1)},[]),we=a.useCallback(async he=>{he.preventDefault(),B(!1);const le=he.dataTransfer.getData("text/plain");if(!le)return;const Ie=n.find(Ze=>Ze.id===le);if(!(Ie&&Ie.column===e))try{await r(le,e)}catch(Ze){c(xe(Ze),"error")}},[e,r,c,n]),Pe=a.useMemo(()=>e!=="in-progress"?[]:sw(n,n,i),[e,n,i]),We=a.useMemo(()=>fe?n.slice(0,A):n,[fe,n,A]),Ke=Math.max(0,n.length-We.length),Ne=a.useCallback(()=>{z(he=>Math.min(he+Od,n.length))},[n.length]),_e=a.useCallback(async()=>{if(E(!1),!(n.length===0||!window.confirm(`Move all ${n.length} todo task${n.length===1?"":"s"} back to triage to be respecified?`))){pe(!0);try{const le=await Promise.allSettled(n.map(at=>r(at.id,"triage"))),Ie=le.filter(at=>at.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Moved ${Ze} task${Ze===1?"":"s"} to triage for respec`,"success"):c(`Moved ${Ze} of ${le.length} tasks; ${Ie} failed`,"error")}finally{pe(!1)}}},[n,r,c]),Oe=a.useMemo(()=>n.filter(he=>!he.paused),[n]),ye=Oe.length,De=e==="todo"||e==="in-progress"||e==="in-review",se=U||ie||F,J=a.useCallback(async()=>{if(!(!o||(E(!1),ye===0)||!window.confirm(`Stop all ${ye} ${Pn[e].toLowerCase()} task${ye===1?"":"s"}?`))){re(!0);try{const le=await Promise.allSettled(Oe.map(at=>o(at.id))),Ie=le.filter(at=>at.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Stopped ${Ze} task${Ze===1?"":"s"}`,"success"):c(`Stopped ${Ze} of ${le.length} tasks; ${Ie} failed`,"error")}finally{re(!1)}}},[o,ye,e,Oe,c]),me=a.useCallback(async()=>{if(E(!1),!(n.length===0||!window.confirm(`Move all ${n.length} ${Pn[e].toLowerCase()} task${n.length===1?"":"s"} to Todo?`))){ce(!0);try{const le=await Promise.allSettled(n.map(at=>r(at.id,"todo"))),Ie=le.filter(at=>at.status==="rejected").length,Ze=le.length-Ie;Ie===0?c(`Moved ${Ze} task${Ze===1?"":"s"} to Todo`,"success"):c(`Moved ${Ze} of ${le.length} tasks to Todo; ${Ie} failed`,"error")}finally{ce(!1)}}},[n,e,r,c]),ee=a.useCallback(async()=>{if(!(!x||n.length===0||!window.confirm(`Archive all ${n.length} done tasks?`)))try{const le=await x();c(`Archived ${le.length} tasks`,"success")}catch(le){c(xe(le)||"Failed to archive tasks","error")}},[x,n.length,c]);return t.jsxs("div",{className:`column${W?" drag-over":""}${de?" column-archived":""}${Te?" column-collapsed":""}`,"data-column":e,onDragOver:Se,onDragLeave:te,onDrop:we,children:[t.jsxs("div",{className:"column-header",children:[t.jsx("div",{className:`column-dot dot-${e}`}),t.jsx("h2",{children:Pn[e]}),t.jsx("span",{className:`column-count${Q?" count-flash":""}`,children:n.length}),e==="in-review"&&h&&t.jsxs("label",{className:"auto-merge-toggle",title:m?"Auto-merge enabled":"Auto-merge disabled",children:[t.jsx("input",{type:"checkbox",checked:!!m,onChange:h}),t.jsx("span",{className:"toggle-slider"}),t.jsx("span",{className:"toggle-label",children:"Auto-merge"})]}),d&&t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:d,children:"+ New Task"}),e==="done"&&x&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:ee,disabled:n.length===0,title:"Archive all done tasks","aria-label":"Archive all done tasks",children:t.jsx(Zr,{size:16})}),de&&M&&t.jsx("button",{className:"btn btn-icon btn-sm",onClick:M,title:k?"Expand archived tasks":"Collapse archived tasks","aria-label":k?"Expand archived tasks":"Collapse archived tasks",children:k?t.jsx(zt,{size:16}):t.jsx(Ys,{size:16})}),De&&t.jsxs("div",{className:"column-menu",ref:ae,children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>E(he=>!he),"aria-haspopup":"menu","aria-expanded":X,"aria-label":`${Pn[e]} column actions`,title:"Column actions",disabled:se,children:t.jsx(fg,{size:16})}),X&&t.jsxs("div",{className:"column-menu-popover",role:"menu",children:[e==="todo"&&t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void _e(),disabled:n.length===0||U,children:["Respecify All",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Triage"]})]}),(e==="in-progress"||e==="in-review")&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void J(),disabled:ye===0||ie||!o,children:["Stop All",t.jsx("span",{className:"column-menu-item-hint",children:n.length===0?"No tasks in this column":ye===0?"All tasks are already paused":`Pause ${ye} active task${ye===1?"":"s"}`})]}),t.jsxs("button",{type:"button",role:"menuitem",className:"column-menu-item",onClick:()=>void me(),disabled:n.length===0||F,children:["Move All to Todo",t.jsxs("span",{className:"column-menu-item-hint",children:["Move ",n.length," task",n.length===1?"":"s"," to Todo"]})]})]})]})]})]}),!Te&&t.jsx("p",{className:"column-desc",children:tj[e]}),!Te&&t.jsxs("div",{className:"column-body",children:[e==="triage"&&u&&t.jsx(Ph,{onCreate:u,addToast:c,tasks:y??[],availableModels:R,onPlanningMode:j,onSubtaskBreakdown:C,projectId:s,autoExpand:!1,favoriteProviders:P,favoriteModels:T,onToggleFavorite:_,onToggleModelFavorite:L}),e==="in-progress"?Pe.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):Pe.map(he=>t.jsx(Ih,{label:he.label,activeTasks:he.activeTasks,queuedTasks:he.queuedTasks,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onOpenDetailWithTab:S,taskStuckTimeoutMs:$,onOpenMission:I,lastFetchTimeMs:w,workflowStepNameLookup:q},he.label)):n.length===0?t.jsx("div",{className:"empty-column",children:"No tasks"}):t.jsxs(t.Fragment,{children:[We.map(he=>t.jsx(qr,{task:he,projectId:s,onOpenDetail:l,addToast:c,globalPaused:g,onUpdateTask:p,onArchiveTask:f,onUnarchiveTask:b,onDeleteTask:v,onOpenDetailWithTab:S,taskStuckTimeoutMs:$,onOpenMission:I,onMoveTask:r,lastFetchTimeMs:w,workflowStepNameLookup:q},he.id)),fe&&Ke>0&&t.jsxs("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Ne,children:["Load ",Math.min(Od,Ke)," more (",Ke," remaining)"]})]}),t.jsx(co,{slotId:"board-column-footer",projectId:s})]})]})}const $h=a.memo(iw);$h.displayName="Column";function aw(e){return[...e].sort((n,s)=>n.columnMovedAt&&s.columnMovedAt?s.columnMovedAt.localeCompare(n.columnMovedAt):n.columnMovedAt&&!s.columnMovedAt?-1:!n.columnMovedAt&&s.columnMovedAt?1:n.createdAt.localeCompare(s.createdAt))}function rw(e,n){return e.length!==n.length?!1:e.every((s,i)=>s===n[i])}const Ud=new Map;function ow(e,n){if(e.size!==n.size)return!1;for(const[s,i]of e)if(n.get(s)!==i)return!1;return!0}function lw({tasks:e,projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,onQuickCreate:c,onNewTask:u,autoMerge:d,onToggleAutoMerge:m,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,onArchiveAllDone:v,onLoadArchivedTasks:x,searchQuery:k="",availableModels:M,onPlanningMode:y,onSubtaskBreakdown:R,onOpenDetailWithTab:j,favoriteProviders:C,favoriteModels:S,onToggleFavorite:P,onToggleModelFavorite:T,taskStuckTimeoutMs:_,onOpenMission:L,lastFetchTimeMs:G}){const[$,I]=a.useState(!0),w=a.useRef(!1),{fetchBatch:q}=vj(n),W=a.useRef(null),[B,A]=a.useState(Ud),z=k.trim()!=="",X=a.useRef({triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]}),E=a.useCallback(()=>{I(ie=>{const re=!ie;return!re&&!w.current&&x&&(w.current=!0,x()),re})},[x]),U=a.useMemo(()=>{const ie=Object.fromEntries(ki.map(ce=>[ce,[]]));for(const ce of e)ie[ce.column].push(ce);const re=X.current,F={};for(const ce of ki){const ae=aw(ie[ce]);F[ce]=rw(re[ce],ae)?re[ce]:ae}return X.current=F,F},[e]);a.useEffect(()=>{let ie=!1;return oo(n).then(re=>{if(ie)return;const F=new Map(re.map(ce=>[ce.id,ce.name]));A(ce=>ow(ce,F)?ce:F)}).catch(()=>{ie||A(re=>re.size===0?re:Ud)}),()=>{ie=!0}},[n]);const pe=a.useMemo(()=>e.filter(ie=>ie.prInfo||ie.issueInfo).map(ie=>ie.id),[e]);return a.useEffect(()=>{if(pe.length!==0)return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{const ie=[];for(let re=0;re<pe.length;re+=50)ie.push(pe.slice(re,re+50));ie.forEach(re=>{q(re)})},500),()=>{W.current&&clearTimeout(W.current)}},[pe,q]),t.jsx(t.Fragment,{children:t.jsx("main",{className:"board",id:"board",children:ki.map(ie=>t.jsx($h,{column:ie,tasks:U[ie],projectId:n,maxConcurrent:s,onMoveTask:i,onPauseTask:r,onOpenDetail:o,addToast:l,globalPaused:h,onUpdateTask:g,onArchiveTask:p,onUnarchiveTask:f,onDeleteTask:b,allTasks:e,availableModels:M,onOpenDetailWithTab:j,favoriteProviders:C,favoriteModels:S,onToggleFavorite:P,onToggleModelFavorite:T,isSearchActive:z,taskStuckTimeoutMs:_,onOpenMission:L,lastFetchTimeMs:G,workflowStepNameLookup:B,...ie==="triage"?{onQuickCreate:c,onNewTask:u,onPlanningMode:y,onSubtaskBreakdown:R}:{},...ie==="in-review"?{autoMerge:d,onToggleAutoMerge:m}:{},...ie==="done"?{onArchiveAllDone:v}:{},...ie==="archived"?{collapsed:$,onToggleCollapse:E}:{}},ie))})})}const ga={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},Bd=new Set(["planning","researching","executing","finalizing","merging","specifying"]),Bl=["id","title","status","column","dependencies","progress"];function Hd(e){try{const n=Nn("kb-dashboard-list-columns",e);if(n){const i=JSON.parse(n).filter(r=>Bl.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set(Bl)}function qd(e){try{const n=Nn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function Vd(e){try{const n=Nn("kb-dashboard-list-collapsed",e);if(n){const i=JSON.parse(n).filter(r=>ki.includes(r));if(i.length>0)return new Set(i)}}catch{}return new Set}function Wd(e){try{const n=Nn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function cw(e){return e.status==="executing"||e.column==="in-progress"}function Gd(e){const n=Rh(e);return n.total===0||!cw(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function dw({tasks:e,onMoveTask:n,onOpenDetail:s,addToast:i,globalPaused:r,onNewTask:o,onQuickCreate:l,availableModels:c,favoriteProviders:u=[],favoriteModels:d=[],onToggleFavorite:m,onToggleModelFavorite:h,onPlanningMode:g,onSubtaskBreakdown:p,onTasksUpdated:f,projectId:b,projectName:v,taskStuckTimeoutMs:x,searchQuery:k="",lastFetchTimeMs:M}){const[y,R]=a.useState("id"),[j,C]=a.useState("desc"),[S,P]=a.useState(null),[T,_]=a.useState(null),[L,G]=a.useState(null),I=tr()==="mobile",[w,q]=a.useState(()=>Hd(b)),[W,B]=a.useState(()=>qd(b)),[A,z]=a.useState(()=>Vd(b));a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-list-columns",JSON.stringify([...w]),b)},[b,w]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-hide-done",W.toString(),b)},[W,b]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-list-collapsed",JSON.stringify([...A]),b)},[A,b]);const[X,E]=a.useState(!1),U=a.useRef(null),[pe,ie]=a.useState(()=>Wd(b));a.useEffect(()=>{q(Hd(b)),B(qd(b)),z(Vd(b)),ie(Wd(b))},[b]),a.useEffect(()=>{typeof window<"u"&&ts("kb-dashboard-selected-tasks",JSON.stringify([...pe]),b)},[b,pe]);const re=a.useCallback(Z=>{ie(ue=>{const Ce=new Set(ue);return Ce.has(Z)?Ce.delete(Z):Ce.add(Z),Ce})},[]),F=a.useCallback(()=>{ie(new Set)},[]),ce=a.useCallback(Z=>{q(ue=>{const Ce=new Set(ue);return Ce.has(Z)?Ce.size>1&&Ce.delete(Z):Ce.add(Z),Ce})},[]);a.useEffect(()=>{if(!X)return;const Z=Ce=>{U.current&&!U.current.contains(Ce.target)&&E(!1)},ue=Ce=>{Ce.key==="Escape"&&E(!1)};return document.addEventListener("mousedown",Z),document.addEventListener("keydown",ue),()=>{document.removeEventListener("mousedown",Z),document.removeEventListener("keydown",ue)}},[X]);const ae={id:"ID",title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Q=a.useCallback(Z=>{y===Z?C(ue=>ue==="asc"?"desc":"asc"):(R(Z),C("asc"))},[y]),de=a.useCallback(Z=>{G(ue=>ue===Z?null:Z)},[]),Te=a.useCallback(Z=>{z(ue=>{const Ce=new Set(ue);return Ce.has(Z)?Ce.delete(Z):Ce.add(Z),Ce})},[]),fe=a.useCallback(()=>{G(null)},[]),Se=a.useMemo(()=>{let Z=k?e.filter(ve=>ve.id.toLowerCase().includes(k.toLowerCase())||ve.title&&ve.title.toLowerCase().includes(k.toLowerCase())||ve.description.toLowerCase().includes(k.toLowerCase())):[...e];W&&!L&&(Z=Z.filter(ve=>ve.column!=="done"&&ve.column!=="archived"));const Ce=[...L?Z.filter(ve=>ve.column===L):Z].sort((ve,Ge)=>{let je=0;switch(y){case"id":je=ve.id.localeCompare(Ge.id);break;case"title":je=(ve.title||ve.description).localeCompare(Ge.title||Ge.description);break;case"status":je=(ve.status||"").localeCompare(Ge.status||"");break;case"column":je=ve.column.localeCompare(Ge.column);break}return j==="asc"?je:-je}),$e={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};return Ce.forEach(ve=>$e[ve.column].push(ve)),$e},[e,k,y,j,W,L]),te=a.useMemo(()=>Object.values(Se).reduce((Z,ue)=>Z+ue.length,0),[Se]),we=a.useMemo(()=>e.filter(Z=>Z.column==="done"||Z.column==="archived").length,[e]),Pe=a.useMemo(()=>W?we:0,[W,we]),We=a.useCallback(()=>{const Z=Object.values(Se).flat().filter(ue=>ue.column!=="archived").map(ue=>ue.id);ie(ue=>{if(Z.every($e=>ue.has($e))){const $e=new Set(ue);return Z.forEach(ve=>$e.delete(ve)),$e}else return new Set([...ue,...Z])})},[Se]),Ke=a.useMemo(()=>{const Z=Object.values(Se).flat().filter(ue=>ue.column!=="archived");return Z.length===0?!1:Z.every(ue=>pe.has(ue.id))},[Se,pe]),Ne=a.useMemo(()=>{const Z=Object.values(Se).flat().filter(Ce=>Ce.column!=="archived");if(Z.length===0)return!1;const ue=Z.filter(Ce=>pe.has(Ce.id)).length;return ue>0&&ue<Z.length},[Se,pe]),[_e,Oe]=a.useState("__no_change__"),[ye,De]=a.useState("__no_change__"),[se,J]=a.useState(!1),me=a.useCallback(async()=>{if(pe.size===0)return;const Z=Array.from(pe).filter(Ce=>{const $e=e.find(ve=>ve.id===Ce);return $e&&$e.column!=="archived"});if(Z.length===0){i("No valid tasks to update (archived tasks cannot be modified)","error");return}const ue={taskIds:Z};if(_e!=="__no_change__")if(_e==="")ue.modelProvider=null,ue.modelId=null;else{const Ce=_e.indexOf("/");Ce!==-1&&(ue.modelProvider=_e.slice(0,Ce),ue.modelId=_e.slice(Ce+1))}if(ye!=="__no_change__")if(ye==="")ue.validatorModelProvider=null,ue.validatorModelId=null;else{const Ce=ye.indexOf("/");Ce!==-1&&(ue.validatorModelProvider=ye.slice(0,Ce),ue.validatorModelId=ye.slice(Ce+1))}if(Object.keys(ue).length===1){i("No changes to apply","info");return}J(!0);try{const Ce=await yx(ue.taskIds,ue.modelProvider,ue.modelId,ue.validatorModelProvider,ue.validatorModelId,void 0,void 0,b);f&&Ce.updated.length>0&&f(Ce.updated),i(`Updated ${Ce.count} task${Ce.count===1?"":"s"}`,"success"),F(),Oe("__no_change__"),De("__no_change__")}catch(Ce){i(xe(Ce)||"Failed to update models","error")}finally{J(!1)}},[pe,e,_e,ye,b,i,F,f]),ee=a.useCallback(Z=>{s(Z)},[s]),he=a.useCallback((Z,ue)=>{if(ue.paused){Z.preventDefault();return}Z.dataTransfer.setData("text/plain",ue.id),Z.dataTransfer.effectAllowed="move",P(ue.id)},[]),le=a.useCallback(()=>{P(null),_(null)},[]),Ie=a.useCallback((Z,ue)=>{Z.preventDefault(),Z.dataTransfer.dropEffect="move",_(ue)},[]),Ze=a.useCallback(()=>{_(null)},[]),at=a.useCallback(async(Z,ue)=>{Z.preventDefault(),_(null);const Ce=Z.dataTransfer.getData("text/plain");if(Ce){if(ue==="archived"){i("Tasks can only be archived via the archive button","error");return}try{await n(Ce,ue)}catch($e){i(xe($e),"error")}}},[n,i]),oe=Z=>y!==Z?t.jsx(Qm,{size:14,className:"sort-icon"}):j==="asc"?t.jsx(yi,{size:14,className:"sort-icon active"}):t.jsx(Wa,{size:14,className:"sort-icon active"});return t.jsxs("div",{className:"list-view",children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsxs("div",{className:"list-column-toggle",ref:U,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>E(Z=>!Z),"aria-expanded":X,"aria-haspopup":"menu",children:[t.jsx(lg,{size:14}),"Columns"]}),X&&t.jsx("div",{className:"list-column-dropdown",role:"menu",children:Bl.map(Z=>{const ue=w.has(Z),Ce=ue&&w.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${Ce?" disabled":""}`,role:"menuitem",title:Ce?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:ue,onChange:()=>ce(Z),disabled:Ce}),t.jsx("span",{children:ae[Z]})]},Z)})})]}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>B(Z=>!Z),"aria-pressed":W,title:W?"Show done tasks":"Hide done tasks",children:[W?t.jsx(Vi,{size:14}):t.jsx($r,{size:14}),W?"Show Done":"Hide Done"]}),t.jsxs("div",{className:"list-stats",children:[L?`${te} of ${e.length} tasks in ${Pn[L]}`:`${te} of ${e.length} tasks`,Pe>0&&!L&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",Pe," hidden)"]}),L&&t.jsx("button",{className:"btn btn-sm",onClick:fe,"aria-label":"Clear column filter",style:{marginLeft:"8px"},children:"Clear"})]}),pe.size>0&&t.jsxs("div",{className:"list-selection-stats",children:[t.jsxs("span",{className:"selection-count",children:[pe.size," selected"]}),t.jsx("button",{className:"btn btn-sm btn-link",onClick:F,children:"Clear"})]}),pe.size>0&&c&&c.length>0&&t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(wn,{models:c,value:_e,onChange:Oe,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(wn,{models:c,value:ye,onChange:De,label:"Validator Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:u,onToggleFavorite:m,favoriteModels:d,onToggleModelFavorite:h})}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:me,disabled:se||_e==="__no_change__"&&ye==="__no_change__",children:se?"Applying...":"Apply"})]}),o?t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:o,children:"+ New Task"}):null]}),t.jsx("div",{className:"list-drop-zones",children:ki.map(Z=>{const ue=e.filter(Ge=>Ge.column===Z).length,Ce=Z==="done"||Z==="archived",$e=W&&Ce?0:ue,ve=W&&Ce&&ue>0;return t.jsxs("div",{className:`list-drop-zone${T===Z?" drag-over":""}${L===Z?" active":""}`,onClick:()=>de(Z),onDragOver:Ge=>Ie(Ge,Z),onDragLeave:Ze,onDrop:Ge=>at(Ge,Z),"data-column":Z,children:[t.jsx("span",{className:"drop-zone-dot",style:{background:ga[Z]}}),t.jsx("span",{className:"drop-zone-label",children:Pn[Z]}),t.jsx("span",{className:"drop-zone-count",children:ve?`${$e} of ${ue}`:ue})]},Z)})}),t.jsxs("div",{className:"list-table-container",children:[t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Ph,{onCreate:l??(async()=>i("Task creation not available","error")),addToast:i,tasks:e,availableModels:c,onPlanningMode:g,onSubtaskBreakdown:p,projectId:b,autoExpand:!1,favoriteProviders:u,favoriteModels:d,onToggleFavorite:m,onToggleModelFavorite:h})}),te===0?t.jsx("div",{className:"list-empty",children:k?"No tasks match your filter":"No tasks yet"}):I?t.jsx("div",{className:"list-cards",children:ki.map(Z=>{if(L&&Z!==L||W&&(Z==="done"||Z==="archived")&&!L)return null;const ue=Se[Z],Ce=ue.length===0;if(k&&Ce)return null;const $e=A.has(Z);return t.jsxs(a.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${$e?" list-section-header--collapsed":""}`,onClick:()=>Te(Z),"aria-expanded":!$e,role:"button",tabIndex:0,onKeyDown:ve=>{(ve.key==="Enter"||ve.key===" ")&&(ve.preventDefault(),Te(Z))},children:[t.jsx(en,{size:14,className:`list-section-chevron${$e?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Pn[Z]}),t.jsx("span",{className:"list-section-count",children:ue.length})]}),!$e&&t.jsx(t.Fragment,{children:Ce?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):ue.map(ve=>{const Ge=ve.status==="failed",je=ve.paused===!0,Ue=Hr(ve,x,M),He=!r&&!Ge&&!je&&!Ue&&(ve.column==="in-progress"||Bd.has(ve.status)),ge=typeof ve.status=="string"&&ve.status.trim().length>0,Fe=!!(ve.dependencies&&ve.dependencies.length>0),be=Gd(ve),Je=be.hasProgress,st=pe.size>0;return t.jsxs("div",{className:`list-card${He?" agent-active":""}${st?" list-card--selectable":""}`,onClick:()=>ee(ve),"data-id":ve.id,children:[st&&t.jsx("label",{className:"list-card-checkbox",onClick:dt=>dt.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:pe.has(ve.id),onChange:dt=>{dt.stopPropagation(),re(ve.id)},onClick:dt=>dt.stopPropagation(),disabled:ve.column==="archived","aria-label":`Select ${ve.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:ve.id}),ve.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-card-spacer"}),Ue?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ge?t.jsx("span",{className:`list-status-badge list-status-badge--${ve.column}${Ge?" failed":""}${He?" pulsing":""}`,children:ve.status}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:ve.title||ve.description})}),(Fe||Je)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Fe&&t.jsxs("span",{className:"list-dep-badge",title:ve.dependencies.join(", "),children:[t.jsx(Wi,{size:12})," ",ve.dependencies.length]}),Je&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${be.percent}%`,backgroundColor:ga[ve.column]}})}),t.jsx("span",{className:"list-progress-label",children:be.label})]})]})]},ve.id)})})]},Z)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:Ke,ref:Z=>{Z&&(Z.indeterminate=Ne)},onChange:We,"aria-label":"Select all visible tasks"})}),w.has("id")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("id"),children:["ID ",oe("id")]}),w.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("title"),children:["Title ",oe("title")]}),w.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("status"),children:["Status ",oe("status")]}),w.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Q("column"),children:["Column ",oe("column")]}),w.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),w.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ki.map(Z=>{if(L&&Z!==L||W&&(Z==="done"||Z==="archived")&&!L)return null;const ue=Se[Z],Ce=ue.length===0;if(k&&Ce)return null;const $e=A.has(Z);return t.jsxs(a.Fragment,{children:[t.jsx("tr",{className:`list-section-header${$e?" list-section-header--collapsed":""}`,onClick:()=>Te(Z),"aria-expanded":!$e,children:t.jsxs("th",{colSpan:w.size+1,className:"list-section-cell",children:[t.jsx(en,{size:14,className:`list-section-chevron${$e?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${Z}`}),t.jsx("span",{className:"list-section-title",children:Pn[Z]}),t.jsx("span",{className:"list-section-count",children:ue.length})]})}),!$e&&t.jsx(t.Fragment,{children:Ce?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:w.size+1,className:"list-empty-cell",children:"No tasks"})}):ue.map(ve=>{const Ge=ve.status==="failed",je=ve.paused===!0,Ue=Hr(ve,x,M),He=!r&&!Ge&&!je&&!Ue&&(ve.column==="in-progress"||Bd.has(ve.status)),ge=S===ve.id;return t.jsxs("tr",{className:`list-row${Ge?" failed":""}${je?" paused":""}${Ue?" stuck":""}${He?" agent-active":""}${ge?" dragging":""}`,onClick:()=>ee(ve),draggable:!je,onDragStart:Fe=>he(Fe,ve),onDragEnd:le,"data-id":ve.id,children:[t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:pe.has(ve.id),onChange:Fe=>{Fe.stopPropagation(),re(ve.id)},onClick:Fe=>Fe.stopPropagation(),disabled:ve.column==="archived","aria-label":`Select ${ve.id}`})}),w.has("id")&&t.jsx("td",{className:"list-cell list-cell-id",children:ve.id}),w.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[ve.executionMode==="fast"&&t.jsx("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",children:"Fast"}),t.jsx("span",{className:"list-title-text",children:ve.title||ve.description})]})}),w.has("status")&&t.jsx("td",{className:"list-cell",children:Ue?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):ve.status?t.jsx("span",{className:`list-status-badge list-status-badge--${ve.column}${Ge?" failed":""}${He?" pulsing":""}`,children:ve.status}):t.jsx("span",{className:"list-status-badge",children:"-"})}),w.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${ga[ve.column]}20`,color:ga[ve.column]},children:Pn[ve.column]})}),w.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:ve.dependencies&&ve.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:ve.dependencies.join(", "),children:[t.jsx(Wi,{size:12})," ",ve.dependencies.length]}):"-"}),w.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Fe=Gd(ve);return Fe.hasProgress?t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${Fe.percent}%`,backgroundColor:ga[ve.column]}})}),t.jsx("span",{className:"list-progress-label",children:Fe.label})]}):"-"})()})]},ve.id)})})]},Z)})})]})]})]})}const uw={active:{label:"Active",color:"var(--success)",icon:rn},paused:{label:"Paused",color:"var(--warning)",icon:Fs},errored:{label:"Error",color:"var(--color-error)",icon:ss},initializing:{label:"Initializing",color:"var(--info)",icon:it}};function mw(e){if(!e)return"Never";const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(i/36e5),l=Math.floor(i/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function hw(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),i=e.slice(-Math.floor(n/2)+2);return`${s}...${i}`}function pw(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,i=n.health;if(!s&&!i)return!0;if(!s||!i||s.activeTaskCount!==i.activeTaskCount||s.inFlightAgentCount!==i.inFlightAgentCount||s.totalTasksCompleted!==i.totalTasksCompleted||s.totalTasksFailed!==i.totalTasksFailed||s.status!==i.status)return!1;const r=e.node,o=n.node;return!r&&!o?e.nodeNameFallback===n.nodeNameFallback:!r||!o?!1:r.id===o.id&&r.name===o.name&&r.status===o.status&&r.type===o.type}function fw({project:e,health:n,onSelect:s,onPause:i,onResume:r,onRemove:o,node:l,nodeNameFallback:c,isLoading:u=!1}){const[d,m]=a.useState(!1),h=uw[e.status],g=h.icon,p=a.useCallback(()=>{s(e)},[s,e]),f=a.useCallback(y=>{y.stopPropagation(),i(e)},[i,e]),b=a.useCallback(y=>{y.stopPropagation(),r(e)},[r,e]),v=a.useCallback(y=>{if(y.stopPropagation(),!d){m(!0);return}o(e),m(!1)},[d,o,e]),x=e.status==="paused",k=e.status==="errored",M=e.status==="initializing";return t.jsxs("div",{className:`project-card ${u?"project-card-loading":""} ${k?"project-card-errored":""}`,onClick:p,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:y=>{(y.key==="Enter"||y.key===" ")&&(y.preventDefault(),p())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(jn,{size:20})}),t.jsxs("div",{className:"project-card-title-section",children:[t.jsx("h3",{className:"project-card-name",title:e.name,children:e.name}),(l||c)&&t.jsxs("span",{className:"node-badge",title:`Assigned node: ${l?.name??c}`,children:["on: ",l?.name??c]}),t.jsx("span",{className:"project-card-path",title:e.path,children:hw(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:h.color,borderColor:h.color},children:[t.jsx(g,{size:12,className:M?"animate-spin":""}),t.jsx("span",{children:h.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:mw(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[x?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:b,disabled:u,title:"Resume project","aria-label":"Resume project",children:[t.jsx(rn,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:f,disabled:u||M,title:M?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Fs,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:p,disabled:u,title:"Open project","aria-label":"Open project",children:[t.jsx(Ga,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:v,disabled:u,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(Ht,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const gw=a.memo(fw,pw);function bw(){return t.jsxs("div",{className:"project-overview project-overview--loading",children:[t.jsx("div",{className:"project-overview__header-skeleton",children:t.jsxs("div",{className:"project-overview__stats-row",children:[t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(jn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(Ss,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(tn,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]}),t.jsxs("div",{className:"project-overview__stat-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon",children:t.jsx(ss,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),t.jsxs("div",{className:"project-overview__filters-skeleton",children:[t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"}),t.jsx("div",{className:"project-skeleton project-skeleton--tab"})]}),t.jsx("div",{className:"project-grid project-grid--skeleton",children:Array.from({length:6}).map((e,n)=>t.jsxs("div",{className:"project-card project-card--skeleton",children:[t.jsxs("div",{className:"project-card-skeleton__header",children:[t.jsx("div",{className:"project-skeleton project-skeleton--icon-circle"}),t.jsxs("div",{className:"project-skeleton__text-group",children:[t.jsx("div",{className:"project-skeleton project-skeleton--title"}),t.jsx("div",{className:"project-skeleton project-skeleton--path"})]}),t.jsx("div",{className:"project-skeleton project-skeleton--badge"})]}),t.jsxs("div",{className:"project-card-skeleton__health",children:[t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"}),t.jsx("div",{className:"project-skeleton project-skeleton--metric"})]}),t.jsxs("div",{className:"project-card-skeleton__footer",children:[t.jsx("div",{className:"project-skeleton project-skeleton--activity"}),t.jsx("div",{className:"project-skeleton project-skeleton--actions"})]})]},n))})]})}const xw=1e4,Kd=5;function vw(e){const[n,s]=a.useState({}),[i,r]=a.useState(!0),[o,l]=a.useState(null),c=a.useRef(null),u=a.useRef(null),d=a.useRef(!1),m=a.useCallback(async()=>{if(e.length===0){s({}),d.current||(d.current=!0),r(!1);return}u.current&&u.current.abort(),u.current=new AbortController,!d.current&&r(!0),l(null);try{const p={};for(let f=0;f<e.length;f+=Kd){const b=e.slice(f,f+Kd),v=await Promise.allSettled(b.map(async x=>{try{return await gd(x)}catch{return null}}));if(b.forEach((x,k)=>{const M=v[k];p[x]=M.status==="fulfilled"?M.value:null}),u.current?.signal.aborted)return}s(p),d.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),d.current=!0}finally{r(!1)}},[e]),h=a.useCallback(async g=>{try{const p=await gd(g);s(f=>({...f,[g]:p}))}catch(p){console.error(`Failed to fetch health for project ${g}:`,p)}},[]);return a.useEffect(()=>(d.current=!1,m(),()=>{u.current&&u.current.abort()}),[m]),a.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},xw),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:i,error:o,refresh:m,refreshProject:h}}function yw({projects:e,loading:n=!1,onSelectProject:s,onAddProject:i,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[u,d]=a.useState("all"),[m,h]=a.useState(null),[g,p]=a.useState("activity"),[f,b]=a.useState("desc");a.useEffect(()=>{if(typeof window>"u")return;const G=localStorage.getItem("kb-dashboard-recent-projects");if(G)try{const $=JSON.parse(G);x($)}catch{}},[]);const[v,x]=a.useState([]),k=a.useMemo(()=>e.map(G=>G.id),[e]),{healthMap:M,loading:y}=vw(k),R=a.useMemo(()=>e.map(G=>({project:G,health:M[G.id]||null})),[e,M]),j=a.useMemo(()=>{let G=[...R];return u!=="all"&&(G=G.filter(({project:$})=>$.status===u)),m!==null&&(G=G.filter(({project:$})=>$.nodeId===m)),G},[R,u,m]),C=a.useMemo(()=>{const G=[...j];return G.sort(($,I)=>{let w=0;switch(g){case"name":w=$.project.name.localeCompare(I.project.name);break;case"activity":{const q=$.project.lastActivityAt||$.health?.lastActivityAt||$.project.updatedAt,W=I.project.lastActivityAt||I.health?.lastActivityAt||I.project.updatedAt;w=new Date(W).getTime()-new Date(q).getTime();break}case"status":{const q={errored:0,initializing:1,paused:2,active:3};w=q[$.project.status]-q[I.project.status];break}}return f==="asc"?w:-w}),G},[j,g,f]),S=a.useMemo(()=>{const G=e.length,$=e.filter(z=>z.status==="active").length,I=e.filter(z=>z.status==="errored").length,w=new Set;e.forEach(z=>{z.nodeId&&w.add(z.nodeId)});const q=w.size||(G>0?1:0);let W=0,B=0,A=0;return Object.values(M).forEach(z=>{z&&(W+=z.activeTaskCount,B+=z.totalTasksCompleted,A+=z.inFlightAgentCount)}),{totalProjects:G,activeProjects:$,erroredProjects:I,totalNodes:q,totalActiveTasks:W,totalCompletedTasks:B,totalInFlightAgents:A}},[e,M]),P=a.useMemo(()=>({all:e.length,active:e.filter(G=>G.status==="active").length,paused:e.filter(G=>G.status==="paused").length,errored:e.filter(G=>G.status==="errored").length}),[e]),T=a.useMemo(()=>{const G=new Map;return e.forEach($=>{const I=$.nodeId,w=G.get(I);if(w)w.count++;else{const W=c.find(B=>B.id===I)?.name??$._sourceNodeName??"Local";G.set(I,{name:W,count:1})}}),Array.from(G.entries()).map(([$,{name:I,count:w}])=>({nodeId:$??null,name:I,count:w}))},[e,c]),_=a.useCallback(G=>{const $=[G.id,...v.filter(I=>I!==G.id)].slice(0,3);x($),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify($)),s(G)},[s,v]);return n||y&&e.length>0&&Object.keys(M).length===0?t.jsx(bw,{}):e.length===0?t.jsx("div",{className:"project-overview project-overview--empty",children:t.jsxs("div",{className:"project-empty-state",children:[t.jsx("div",{className:"project-empty-state__icon",children:t.jsx(Ra,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:i,children:[t.jsx(Vt,{size:16}),"Add Your First Project"]})]})}):t.jsxs("div",{className:"project-overview",children:[t.jsxs("div",{className:"project-overview__header",children:[t.jsxs("h2",{className:"project-overview__title",children:[t.jsx(Ci,{size:20}),"Projects"]}),t.jsxs("div",{className:"project-overview__stats",children:[t.jsxs("div",{className:"project-stat",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(jn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Ss,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(tn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),S.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(ss,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),S.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Lr,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:S.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:i,children:[t.jsx(Vt,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${u==="all"?"active":""}`,onClick:()=>d("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:P.all})]}),t.jsxs("button",{className:`project-filter-tab ${u==="active"?"active":""}`,onClick:()=>d("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:P.active})]}),t.jsxs("button",{className:`project-filter-tab ${u==="paused"?"active":""}`,onClick:()=>d("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:P.paused})]}),t.jsxs("button",{className:`project-filter-tab ${u==="errored"?"active":""} ${P.errored>0?"has-errors":""}`,onClick:()=>d("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:P.errored})]})]}),T.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(Lr,{size:14}),t.jsxs("select",{value:m??"",onChange:G=>{h(G.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),T.map(({nodeId:G,name:$,count:I})=>t.jsxs("option",{value:G??"",children:[$," (",I,")"]},G??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(Dr,{size:14}),t.jsxs("select",{value:`${g}-${f}`,onChange:G=>{const[$,I]=G.target.value.split("-");p($),b(I)},className:"project-sort-select","aria-label":"Sort projects",children:[t.jsx("option",{value:"activity-desc",children:"Last Activity (Newest)"}),t.jsx("option",{value:"activity-asc",children:"Last Activity (Oldest)"}),t.jsx("option",{value:"name-asc",children:"Name (A-Z)"}),t.jsx("option",{value:"name-desc",children:"Name (Z-A)"}),t.jsx("option",{value:"status-asc",children:"Status (Error → Active)"}),t.jsx("option",{value:"status-desc",children:"Status (Active → Error)"})]}),t.jsx(Qm,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:C.map(({project:G,health:$})=>{const I=c.find(q=>q.id===G.nodeId),w=I?void 0:G._sourceNodeName;return t.jsx(gw,{project:G,health:$,node:I,nodeNameFallback:w,onSelect:_,onPause:r,onResume:o,onRemove:l},G.id)})}),C.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(Dr,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>d("all"),children:"Show All Projects"})]})]})}const kw=45e3,jw=3e3,ww=2e3,Nw=1500,Jd="fusion:sse-client-id";let Di=null;const ci=new Map;function Yd(){const e=typeof globalThis<"u"?globalThis.crypto:void 0;return e&&typeof e.randomUUID=="function"?e.randomUUID():`${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`}function Dh(){if(!(typeof window>"u")){if(Di)return Di;try{const e=window.sessionStorage.getItem(Jd);if(e)return Di=e,e;const n=Yd();return window.sessionStorage.setItem(Jd,n),Di=n,n}catch{return Di=Yd(),Di}}}function Lh(e){if(!(typeof window>"u"))try{return{parsed:new URL(e,window.location.origin),preserveRelativePath:e.startsWith("/")}}catch{return}}function zh(e){return e.origin===window.location.origin&&e.pathname==="/api/events"}function Sw(e){const n=Dh();if(!n)return e;const s=Lh(e);return!s||!zh(s.parsed)?e:(s.parsed.searchParams.set("clientId",n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function pc(e,n){const s=Dh();if(!s)return;const i=Lh(e);if(!i||!zh(i.parsed))return;const r=new URL(`/api/events/${n}`,window.location.origin);r.searchParams.set("clientId",s);const o=i.parsed.searchParams.get("projectId");return o&&r.searchParams.set("projectId",o),Hs(`${r.pathname}${r.search}${r.hash}`)}function Cw(e){if(typeof window>"u")return;const n=pc(e.url,"disconnect");if(!n)return;const s=window.navigator?.sendBeacon?.bind(window.navigator);s&&s(n)||typeof window.fetch=="function"&&window.fetch(n,{method:"POST",keepalive:!0}).catch(()=>{})}function uo(e){e.keepaliveTimer&&(clearInterval(e.keepaliveTimer),e.keepaliveTimer=null)}function Qd(e){if(typeof window>"u"||typeof window.fetch!="function")return;const n=pc(e.url,"keepalive");if(!n)return;const s=typeof AbortController<"u"?new AbortController:null,i=s?window.setTimeout(()=>s.abort(),Nw):null;window.fetch(n,{method:"POST",cache:"no-store",signal:s?.signal}).catch(()=>{}).finally(()=>{i!==null&&window.clearTimeout(i)})}function Ew(e){uo(e),pc(e.url,"keepalive")&&(Qd(e),e.keepaliveTimer=window.setInterval(()=>{Qd(e)},ww))}if(typeof window<"u"){const e=()=>{for(const s of Array.from(ci.values()))if(!s.closed){if(uo(s),Cw(s),s.es){try{s.es.close()}catch{}s.es=null}s.closed=!0}},n=s=>{if(s.persisted)for(const i of Array.from(ci.values()))i.subscribers.size!==0&&(i.closed=!1,fc(i))};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e),window.addEventListener("pageshow",n)}function Ia(e){e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),e.heartbeatTimer=setTimeout(()=>{Fh(e)},kw)}function Fh(e){if(e.heartbeatTimer&&(clearTimeout(e.heartbeatTimer),e.heartbeatTimer=null),e.es&&(e.es.close(),e.es=null),uo(e),e.nativeListeners.clear(),e.closed||e.subscribers.size===0||e.reconnectTimer)return;const n=ci.get(e.url);if(!(!n||n!==e)){for(const s of e.subscribers)s.onReconnect?.();e.reconnectTimer=setTimeout(()=>{if(e.reconnectTimer=null,e.closed)return;const s=ci.get(e.url);s&&s===e&&e.subscribers.size>0&&fc(e)},jw)}}function fc(e){if(e.es||e.closed)return;e.reconnectTimer&&(clearTimeout(e.reconnectTimer),e.reconnectTimer=null);const n=new EventSource(Hs(Sw(e.url)));e.es=n,Ew(e),n.addEventListener("open",()=>{Ia(e);const s=e.hasOpenedOnce;e.hasOpenedOnce=!0;for(const i of e.subscribers)i.onOpen?.(),s&&i.onReconnect?.()}),n.addEventListener("error",s=>{for(const i of e.subscribers)i.onError?.(s);Fh(e)}),n.addEventListener("message",()=>Ia(e)),n.addEventListener("heartbeat",()=>Ia(e)),Oh(e),Ia(e)}function Oh(e){if(!e.es)return;const n=new Set;for(const s of e.subscribers)for(const i of s.events.keys())n.add(i);for(const s of n){if(e.nativeListeners.has(s))continue;const i=r=>{Ia(e);const o=r;for(const l of e.subscribers){const c=l.events.get(s);if(c)for(const u of c)u(o)}};e.nativeListeners.set(s,i),e.es.addEventListener(s,i)}}function Mw(e){e.closed=!0,e.heartbeatTimer&&clearTimeout(e.heartbeatTimer),uo(e),e.reconnectTimer&&clearTimeout(e.reconnectTimer),e.es&&e.es.close(),e.es=null,e.nativeListeners.clear(),ci.delete(e.url)}function qs(e,n={}){let s=ci.get(e);s||(s={url:e,es:null,subscribers:new Set,nativeListeners:new Map,heartbeatTimer:null,keepaliveTimer:null,reconnectTimer:null,hasOpenedOnce:!1,closed:!1},ci.set(e,s));const i={events:new Map,onOpen:n.onOpen,onReconnect:n.onReconnect,onError:n.onError};if(n.events)for(const[o,l]of Object.entries(n.events)){let c=i.events.get(o);c||(c=new Set,i.events.set(o,c)),c.add(l)}s.subscribers.add(i),fc(s),Oh(s);let r=!0;return()=>{if(!r)return;r=!1;const o=ci.get(e);o&&(o.subscribers.delete(i),o.subscribers.size===0&&Mw(o))}}const gc="kb-planning-last-description",bc="kb-subtask-last-description",xc="kb-mission-last-goal";function _w(e,n){ts(gc,e,n)}function Aw(e){return Nn(gc,e)||""}function Li(e){Ha(gc,e)}function Tw(e,n){ts(bc,e,n)}function Rw(e){return Nn(bc,e)||""}function zo(e){Ha(bc,e)}function Iw(e,n){ts(xc,e,n)}function Pw(e){return Nn(xc,e)||""}function ai(e){Ha(xc,e)}function $w(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const i=s;if(n.id in i)return i[n.id]}return s}function Dw(e,n){switch(e.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?e.options?.find(i=>i.id===n)?.label??n:n==null?"":String(n);case"multi_select":return Array.isArray(n)?n.map(s=>typeof s!="string"?String(s):e.options?.find(r=>r.id===s)?.label??s).join(", "):n==null?"":String(n);case"confirm":return n===!0?"Yes":n===!1?"No":n==null?"":String(n);default:return n==null?"":JSON.stringify(n)}}function Lw(e){let n=0;const s=[];for(const i of e){if(i.question){n+=1,s.push({...i,questionNumber:n});continue}i.thinkingOutput&&s.push({...i,questionNumber:null})}return s}function Cs({entries:e,defaultShowThinking:n=!1}){const[s,i]=a.useState({}),r=Lw(e);return r.length===0?null:t.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((o,l)=>{const c=!!o.question,u=!!o.thinkingOutput,d=s[l]??n,m=c?$w(o):void 0,h=o.question&&m!==void 0?Dw(o.question,m):"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"})]}),u&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{i(g=>({...g,[l]:!d}))},"aria-expanded":d,children:[t.jsx("span",{"aria-hidden":"true",children:d?"▾":"▸"}),d?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),d&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const Xd="fusion-tab-id";function zw(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function _i(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(Xd);if(e)return e;const n=zw();return window.sessionStorage.setItem(Xd,n),n}function mo(e){const n=a.useMemo(()=>_i(),[]),[s,i]=a.useState(!1),[r,o]=a.useState(null),[l,c]=a.useState(!1);a.useEffect(()=>{if(!e){i(!1),o(null),c(!1);return}let d=!0;return c(!0),Promise.resolve(Sk(e,n)).then(m=>{if(d){if(m.acquired){i(!1),o(null);return}i(!0),o(m.currentHolder)}}).catch(()=>{d&&(i(!1),o(null))}).finally(()=>{d&&c(!1)}),()=>{d=!1;try{const m=Ck(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),a.useEffect(()=>{if(!e||typeof window>"u")return;const d=()=>{if(typeof navigator.sendBeacon!="function")return;const m=Hs(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",d),()=>{window.removeEventListener("beforeunload",d)}},[e,n]),a.useEffect(()=>!e||typeof EventSource>"u"?void 0:qs("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const g=h.lockedByTab??null;o(g),i(!!(g&&g!==n))}catch{}}}}),[e,n]);const u=a.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(Ek(e,n)),i(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:u,isLoading:l}}const Fw="fusion:ai-session-sync",Zd="fusion:ai-session-sync",Ow=3e4,Uw=6e4;function $s(){return Date.now()}function Bw(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function eu(e){if(!e||typeof e!="object")return null;const n=e;return typeof n.type!="string"||typeof n.timestamp!="number"||!Number.isFinite(n.timestamp)?null:e}class Hw{tabId;listeners=new Set;sessionStates=new Map;ownershipBySession=new Map;heartbeatByTab=new Map;ownedSessions=new Map;snapshot;channel=null;usingStorageFallback=!1;cleanupStorageListener=null;cleanupBeforeUnload=null;heartbeatInterval=null;staleSweepInterval=null;constructor(){this.tabId=Bw(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.isBrowser()&&(this.initializeTransport(),this.startHeartbeat(),this.startStaleSweep(),this.setupBeforeUnloadCleanup())}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}requestSync(){this.publish({type:"sync:request",tabId:this.tabId,timestamp:$s()})}broadcastUpdate(n){const s=n.timestamp??$s();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",i=n.timestamp??$s();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},i),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:i})}broadcastLock(n,s){const i=$s();this.applyTabOwnership(n,s,i),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:i})}broadcastUnlock(n,s){const i=$s();this.releaseTabOwnership(n,s,i),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:i})}broadcastHeartbeat(n){const s=$s();this.updateHeartbeat(n,s),this.publish({type:"tab:heartbeat",tabId:n,timestamp:s})}destroy(){this.cleanupStorageListener?.(),this.cleanupStorageListener=null,this.cleanupBeforeUnload?.(),this.cleanupBeforeUnload=null,this.channel&&(this.channel.close(),this.channel=null),this.heartbeatInterval&&(clearInterval(this.heartbeatInterval),this.heartbeatInterval=null),this.staleSweepInterval&&(clearInterval(this.staleSweepInterval),this.staleSweepInterval=null)}reset(){this.sessionStates.clear(),this.ownershipBySession.clear(),this.heartbeatByTab.clear(),this.ownedSessions.clear(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.emit()}isBrowser(){return typeof window<"u"}initializeTransport(){if(typeof BroadcastChannel<"u")try{this.channel=new BroadcastChannel(Fw),this.channel.onmessage=s=>{const i=eu(s.data);i&&this.handleIncomingMessage(i)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==Zd||!s.newValue))try{const i=JSON.parse(s.newValue),r=eu(i.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=$s();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},Ow)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,i]of this.ownedSessions.entries()){const r=$s();this.publish({type:"tab:inactive",tabId:i,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const i={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(Zd,JSON.stringify(i))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),i=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:i,heartbeats:r,timestamp:$s()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,i=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),i&&this.emit()}applyTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(o&&i<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:i}),this.updateHeartbeat(s,i,!1);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:i}),r&&this.emit()}releaseTabOwnership(n,s,i,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||i<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&i>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:i}),r&&this.emit()}updateHeartbeat(n,s,i=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),i&&this.emit())}emit(){const n=$s(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const i=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>Uw;i.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:i};for(const r of this.listeners)r()}}const Ds=new Hw;function la(){const e=a.useSyncExternalStore(c=>Ds.subscribe(c),()=>Ds.getSnapshot(),()=>Ds.getSnapshot());a.useEffect(()=>{Ds.requestSync()},[]);const n=a.useCallback(c=>{Ds.broadcastUpdate(c)},[]),s=a.useCallback(c=>{Ds.broadcastCompleted(c)},[]),i=a.useCallback((c,u)=>{Ds.broadcastLock(c,u)},[]),r=a.useCallback((c,u)=>{Ds.broadcastUnlock(c,u)},[]),o=a.useCallback(c=>{Ds.broadcastHeartbeat(c)},[]),l=a.useCallback(()=>{Ds.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:i,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function qw(e,n){return e&&n?`${e}/${n}`:""}function Vw(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return n===-1?{provider:void 0,modelId:void 0}:{provider:e.slice(0,n),modelId:e.slice(n+1)}}const Ww=["Build a real-time collaborative document editor","Create a customer onboarding flow with email verification","Add a reporting dashboard with charts and CSV export","Implement a plugin system with marketplace"];function Gw({isOpen:e,onClose:n,onMissionCreated:s,projectId:i,initialGoal:r,resumeSessionId:o}){const[l,c]=a.useState(""),[u,d]=a.useState({type:"initial"}),[m,h]=a.useState(null),[g,p]=a.useState([]),[f,b]=a.useState([]),[v,x]=a.useState(null),[k,M]=a.useState(!1),y=a.useRef(!1),[R,j]=a.useState(""),[C,S]=a.useState(!0),[P,T]=a.useState(!1),[_,L]=a.useState(!1),[G,$]=a.useState(!1),I=a.useRef(null),w=a.useRef(null),q=a.useRef(null),W=a.useRef(null),[B,A]=a.useState(o??null),z=a.useMemo(()=>_i(),[]),{isLockedByOther:X,takeControl:E,isLoading:U}=mo(e?B:null),{activeTabMap:pe,broadcastUpdate:ie,broadcastCompleted:re,broadcastLock:F,broadcastUnlock:ce,broadcastHeartbeat:ae}=la(),[Q,de]=a.useState(void 0),[Te,fe]=a.useState(void 0),[Se,te]=a.useState([]),[we,Pe]=a.useState(!0),[We,Ke]=a.useState(null),[Ne,_e]=a.useState([]),[Oe,ye]=a.useState([]),De=qw(Q,Te);a.useEffect(()=>{(async()=>{try{Pe(!0);const Ue=await is();te(Ue.models),_e(Ue.favoriteProviders),ye(Ue.favoriteModels)}catch(Ue){Ke(xe(Ue)||"Failed to load models")}finally{Pe(!1)}})()},[]);const se=a.useCallback(je=>{_e(Ue=>{const He=Ue,Fe=He.includes(je)?He.filter(be=>be!==je):[je,...He];return nn({favoriteProviders:Fe,favoriteModels:Oe}).catch(()=>{_e(He)}),Fe})},[Oe]),J=a.useCallback(je=>{ye(Ue=>{const He=Ue,Fe=He.includes(je)?He.filter(be=>be!==je):[je,...He];return nn({favoriteProviders:Ne,favoriteModels:Fe}).catch(()=>{ye(He)}),Fe})},[Ne]),me=a.useCallback((je,Ue)=>{if(!je||!Ue)return"Using default";const He=Se.find(ge=>ge.provider===je&&ge.id===Ue);return He?`${He.provider}/${He.id}`:`${je}/${Ue}`},[Se]),ee=a.useCallback(je=>{w.current?.close();const Ue=hk(je,i,{onThinking:He=>{j(ge=>ge+He),ie({sessionId:je,status:"generating",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onQuestion:He=>{T(!1),L(!1),ai(i),d({type:"question",sessionId:je,question:He}),j(""),M(!0),ie({sessionId:je,status:"awaiting_input",needsInput:!0,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onSummary:He=>{T(!1),L(!1),ai(i),d({type:"summary",sessionId:je,summary:He}),x(He),j(""),M(!0),ie({sessionId:je,status:"complete",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null})},onError:He=>{const ge=He||"Session failed while contacting the AI.";T(!1),L(!1),h(null),d({type:"error",sessionId:je,errorMessage:ge}),j(""),M(!0),q.current=je,ie({sessionId:je,status:"error",needsInput:!1,owningTabId:z,type:"mission_interview",title:l.trim()||"Mission interview",projectId:i??null}),re({sessionId:je,status:"error"})},onComplete:()=>{T(!1),L(!1),q.current=null,re({sessionId:je,status:"complete"})},onConnectionStateChange:He=>{T(He==="reconnecting")}});w.current=Ue},[re,ie,l,i,z]),he=a.useCallback(async je=>{const Ue=je??l;if(Ue.trim()){h(null),j(""),p([]),b([]),T(!1),d({type:"loading"});try{const{sessionId:He}=await ck(Ue.trim(),i,Q&&Te?{modelProvider:Q,modelId:Te}:void 0);q.current=He,A(He),ai(i),ee(He),p([])}catch(He){T(!1),h(xe(He)||"Failed to start interview session"),d({type:"initial"}),q.current=null,A(null)}}},[ee,l,Q,Te,i]);a.useEffect(()=>{e&&u.type==="initial"&&I.current?.focus()},[e,u.type]),a.useEffect(()=>{if(e&&r&&!y.current&&u.type==="initial"){c(r);const je=setTimeout(()=>{y.current=!0,he(r)},0);return()=>clearTimeout(je)}else if(e&&!r&&!y.current&&u.type==="initial"){const je=Pw(i);je&&c(je)}},[e,r,u.type,he]),a.useEffect(()=>{e||(y.current=!1,T(!1),L(!1),A(null))},[e]),a.useEffect(()=>{if(!e||!o||u.type!=="initial")return;let je=!1;return Js(o).then(Ue=>{if(je||!Ue)return;const He=Yi(Ue.conversationHistory);if(b(He),A(Ue.id),p(He.map(ge=>ge.response).filter(ge=>!!(ge&&typeof ge=="object"&&!Array.isArray(ge)))),Ue.status==="awaiting_input"&&Ue.currentQuestion)try{ai(i);const ge=JSON.parse(Ue.currentQuestion);q.current=Ue.id,M(!0),d({type:"question",sessionId:Ue.id,question:ge})}catch{h("Failed to restore session question.")}else if(Ue.status==="complete"&&Ue.result)try{ai(i);const ge=JSON.parse(Ue.result);q.current=Ue.id,M(!0),x(ge),d({type:"summary",sessionId:Ue.id,summary:ge})}catch{h("Failed to restore session result.")}else Ue.status==="generating"?(q.current=Ue.id,M(!0),Ue.thinkingOutput&&j(Ue.thinkingOutput),d({type:"loading"}),ee(Ue.id)):Ue.status==="error"&&(q.current=Ue.id,M(!0),h(null),d({type:"error",sessionId:Ue.id,errorMessage:Ue.error??"The session encountered an error."}))}).catch(()=>{je||h("Failed to resume session.")}),()=>{je=!0}},[ee,e,o,u.type,i]),a.useEffect(()=>{if(!e){W.current&&(ce(W.current,z),W.current=null);return}if(B&&W.current!==B){W.current&&ce(W.current,z),F(B,z),W.current=B;return}!B&&W.current&&(ce(W.current,z),W.current=null)},[F,ce,e,B,z]),a.useEffect(()=>{if(!e||!B||W.current!==B)return;ae(z);const je=setInterval(()=>{ae(z)},3e4);return()=>{clearInterval(je)}},[ae,e,B,z]),a.useEffect(()=>()=>{w.current?.close(),w.current=null,W.current&&(ce(W.current,z),W.current=null)},[ce,z]),a.useEffect(()=>{if(!e)return;const je=Ue=>{(u.type==="question"||u.type==="summary")&&(Ue.preventDefault(),Ue.returnValue=""),w.current?.close()};return window.addEventListener("beforeunload",je),()=>window.removeEventListener("beforeunload",je)},[e,u]);const le=a.useCallback(()=>{w.current?.close(),w.current=null,n()},[n]),Ie=a.useCallback(async()=>{if(l&&Iw(l,i),!(k&&!confirm("Are you sure you want to close? Your interview progress will be lost."))){if(w.current?.close(),w.current=null,u.type==="question"||u.type==="summary"||u.type==="error")try{await Nh(u.sessionId,i,z)}catch{}c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),j(""),T(!1),L(!1),M(!1),$(!1),de(void 0),fe(void 0),q.current=null,A(null),n()}},[l,k,u,n,i,z]);a.useEffect(()=>{if(!e)return;const je=Ue=>{Ue.key==="Escape"&&(k?confirm("Are you sure you want to close? Your interview progress will be lost.")&&Ie():Ie())};return document.addEventListener("keydown",je),()=>document.removeEventListener("keydown",je)},[e,k,Ie]);const Ze=a.useCallback(async je=>{if(u.type!=="question")return;const{sessionId:Ue}=u;h(null),p(He=>[...He,je]),b(He=>[...He,{question:u.question,response:je}]),d({type:"loading"}),j("");try{ee(Ue),await dk(Ue,je,i,z),M(!0)}catch(He){w.current?.close(),w.current=null,h(xe(He)||"Failed to submit response"),d({type:"question",sessionId:Ue,question:u.question})}},[u,i,z,ee]),at=a.useCallback(async()=>{if(u.type!=="error")return;const je=u.sessionId;h(null),L(!0),j(""),d({type:"loading"}),ee(je);try{q.current=je,A(je),await uk(je,i,z)}catch(Ue){let He=Ue;if((xe(Ue)||"").includes("not in an error state"))try{const Fe=await Js(je);if(!Fe)throw new Error("Failed to refresh interview session.");const be=Yi(Fe.conversationHistory);if(b(be),p(be.map(Je=>Je.response).filter(Je=>!!(Je&&typeof Je=="object"&&!Array.isArray(Je)))),q.current=Fe.id,A(Fe.id),M(!0),Fe.status==="generating")j(Fe.thinkingOutput??""),d({type:"loading"}),w.current?.isConnected()||ee(Fe.id);else if(Fe.status==="awaiting_input"){if(!Fe.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");ai(i);const Je=JSON.parse(Fe.currentQuestion);d({type:"question",sessionId:Fe.id,question:Je}),w.current?.isConnected()||ee(Fe.id)}else if(Fe.status==="complete"){if(!Fe.result)throw new Error("Interview session is complete but has no result.");ai(i);const Je=JSON.parse(Fe.result);x(Je),d({type:"summary",sessionId:Fe.id,summary:Je})}else Fe.status==="error"&&d({type:"error",sessionId:Fe.id,errorMessage:Fe.error??"Retry failed. Please try again."});T(!1);return}catch(Fe){He=Fe}w.current?.close(),w.current=null,d({type:"error",sessionId:je,errorMessage:xe(He)||"Retry failed. Please try again."}),T(!1)}finally{L(!1)}},[ee,i,z,u]),oe=a.useCallback(async()=>{if(u.type==="summary"){h(null),$(!0);try{const je=await mk(u.sessionId,v||void 0,i);s(je),ai(i),w.current?.close(),w.current=null,c(""),d({type:"initial"}),h(null),p([]),b([]),x(null),j(""),T(!1),L(!1),M(!1),$(!1),q.current=null,A(null),n()}catch(je){h(xe(je)||"Failed to create mission"),$(!1)}}},[u,v,s,n,i]),Z=()=>u.type==="question"?Math.min(g.length+1,6):6,ue=u.type==="loading"||u.type==="question"||u.type==="summary"||u.type==="error",Ce=B?pe.get(B):null,$e=Ce&&Ce.tabId!==z,ve=!!($e&&!Ce.stale),Ge=X&&(!$e||Ce.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:je=>je.target===je.currentTarget&&Ie(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(ns,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[ue&&t.jsx("button",{className:"modal-send-to-background",onClick:le,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ie,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),P&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ve&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),u.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(Dn,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your vision into a structured mission"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build. The AI will interview you to understand scope, constraints, and requirements, then produce a structured plan with milestones, slices, and features."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"mission-goal",children:"What do you want to build?"}),t.jsx("textarea",{ref:I,id:"mission-goal",rows:4,className:"planning-textarea",placeholder:"e.g., Build a real-time collaborative document editor with presence, comments, and version history...",value:l,onChange:je=>c(je.target.value),onKeyDown:je=>{je.key==="Enter"&&!je.shiftKey&&l.trim()&&(je.preventDefault(),he())}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:Ww.map((je,Ue)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(je),children:je.length>45?je.slice(0,45)+"...":je},Ue))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",we&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(wn,{id:"mission-interview-modal-model",label:"Planning Model",value:De,onChange:je=>{const{provider:Ue,modelId:He}=Vw(je);de(Ue),fe(He)},models:Se,disabled:we,favoriteProviders:Ne,onToggleFavorite:se,favoriteModels:Oe,onToggleModelFavorite:J}),We&&t.jsxs("div",{className:"form-hint form-hint-error",children:[We," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{Pe(!0);const je=await is();te(je.models),_e(je.favoriteProviders),ye(je.favoriteModels),Ke(null)}catch(je){Ke(xe(je)||"Failed to load models")}finally{Pe(!1)}})()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${Q&&Te?"model-badge-custom":"model-badge-default"}`,children:me(Q,Te)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>he(),disabled:!l.trim(),children:[t.jsx(ns,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),u.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:R?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>S(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&R&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:R})})]})]}),u.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:f}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:u.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void at(),disabled:_,children:[_?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),t.jsx("span",{className:"icon-ml-6",children:_?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ie,disabled:_,children:"Cancel"})]})]})]})}),u.type==="question"&&t.jsx(Kw,{question:u.question,progress:Z(),historyEntries:f,onSubmit:Ze}),u.type==="summary"&&v&&t.jsx(Jw,{summary:v,historyEntries:f,onSummaryChange:x,onApprove:oe,onStartOver:()=>{d({type:"initial"}),M(!1),x(null),p([]),b([]),A(null),w.current?.close(),w.current=null},isCreating:G}),X&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(so,{size:16}),t.jsx("span",{children:Ge?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Ge&&t.jsx("button",{type:"button",onClick:()=>{E()},disabled:U,className:"btn btn-primary session-lock-take-control",children:U?"Taking control...":"Take Control"})]})})]})]})}):null}function Kw({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Pt,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(Ga,{size:16,className:"icon-ml-4"})]})})]})}function Jw({summary:e,historyEntries:n,onSummaryChange:s,onApprove:i,onStartOver:r,isCreating:o}){const[l,c]=a.useState(()=>new Set(e.milestones.map((y,R)=>R))),[u,d]=a.useState(()=>{const y=new Set;return e.milestones.forEach((R,j)=>{R.slices.forEach((C,S)=>y.add(`${j}-${S}`))}),y}),m=y=>{c(R=>{const j=new Set(R);return j.has(y)?j.delete(y):j.add(y),j})},h=y=>{d(R=>{const j=new Set(R);return j.has(y)?j.delete(y):j.add(y),j})},g=(y,R)=>{const j=[...e.milestones];j[y]={...j[y],...R},s({...e,milestones:j})},p=(y,R,j)=>{const C=[...e.milestones],S=[...C[y].slices];S[R]={...S[R],...j},C[y]={...C[y],slices:S},s({...e,milestones:C})},f=(y,R,j,C)=>{const S=[...e.milestones],P=[...S[y].slices],T=[...P[R].features];T[j]={...T[j],...C},P[R]={...P[R],features:T},S[y]={...S[y],slices:P},s({...e,milestones:S})},b=y=>{const R=e.milestones.filter((j,C)=>C!==y);s({...e,milestones:R})},v=(y,R)=>{const j=[...e.milestones];j[y]={...j[y],slices:j[y].slices.filter((C,S)=>S!==R)},s({...e,milestones:j})},x=(y,R,j)=>{const C=[...e.milestones],S=[...C[y].slices];S[R]={...S[R],features:S[R].features.filter((P,T)=>T!==j)},C[y]={...C[y],slices:S},s({...e,milestones:C})},k=(y,R)=>{const j=[...e.milestones],C=[...j[y].slices];C[R]={...C[R],features:[...C[R].features,{title:"New feature",description:""}]},j[y]={...j[y],slices:C},s({...e,milestones:j})},M=e.milestones.reduce((y,R)=>y+R.slices.reduce((j,C)=>j+C.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(tn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",M," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:y=>s({...e,missionTitle:y.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:y=>s({...e,missionDescription:y.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((y,R)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(R),children:[l.has(R)?t.jsx(zt,{size:16,className:"icon-text-secondary"}):t.jsx(en,{size:16,className:"icon-text-secondary"}),t.jsx(Si,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:y.title,onChange:j=>g(R,{title:j.target.value}),onClick:j=>j.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:j=>{j.stopPropagation(),b(R)},title:"Remove milestone",children:t.jsx(Ht,{size:14,className:"icon-text-secondary"})})]}),l.has(R)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:y.description||"",onChange:j=>g(R,{description:j.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:y.verification||"",onChange:j=>g(R,{verification:j.target.value})})]}),y.slices.map((j,C)=>{const S=`${R}-${C}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(S),children:[u.has(S)?t.jsx(zt,{size:14,className:"icon-text-secondary"}):t.jsx(en,{size:14,className:"icon-text-secondary"}),t.jsx(Il,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:j.title,onChange:P=>p(R,C,{title:P.target.value}),onClick:P=>P.stopPropagation()}),y.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:P=>{P.stopPropagation(),v(R,C)},title:"Remove slice",children:t.jsx(Ht,{size:12,className:"icon-text-secondary"})})]}),u.has(S)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:j.verification||"",onChange:P=>p(R,C,{verification:P.target.value})})]}),j.features.map((P,T)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(Ml,{size:12,className:"icon-feature"}),t.jsxs("div",{className:"roadmap-feature-content",children:[t.jsx("input",{type:"text",className:"form-input roadmap-input-feature",value:P.title,onChange:_=>f(R,C,T,{title:_.target.value})}),P.description&&t.jsx("p",{className:"roadmap-feature-text",children:P.description}),P.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",P.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>x(R,C,T),title:"Remove feature",children:t.jsx(Ht,{size:12,className:"icon-text-secondary"})})]},T)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>k(R,C),children:[t.jsx(Vt,{size:12}),"Add Feature"]})]})]},C)})]})]},R))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(ia,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:i,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}function Yw({isOpen:e,onClose:n,onApplied:s,targetType:i,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:u}){const[d,m]=a.useState({type:"initial"}),[h,g]=a.useState(null),[p,f]=a.useState([]),[b,v]=a.useState([]),[x,k]=a.useState(null),[M,y]=a.useState(""),[R,j]=a.useState(!0),[C,S]=a.useState(!1),[P,T]=a.useState(!1),_=a.useRef(null),L=a.useRef(null),G=a.useRef(null),$=a.useRef(null),[I,w]=a.useState(null),q=a.useMemo(()=>_i(),[]);mo(e?I:null);const{activeTabMap:W,broadcastUpdate:B,broadcastCompleted:A,broadcastLock:z,broadcastUnlock:X,broadcastHeartbeat:E}=la(),U=i==="milestone"?pk:vk,pe=i==="milestone"?fk:yk,ie=i==="milestone"?gk:kk,re=i==="milestone"?bk:jk,F=i==="milestone"?xk:wk,ce=i==="milestone"?"Milestone":"Slice",ae=i==="milestone"?"milestone_interview":"slice_interview",Q=a.useCallback(ye=>{L.current?.close();const De=ie(ye,c,{onThinking:se=>{y(J=>J+se),B({sessionId:ye,status:"generating",needsInput:!1,owningTabId:q,type:ae,title:o,projectId:c??null})},onQuestion:se=>{S(!1),de(),m({type:"question",sessionId:ye,question:se}),y(""),B({sessionId:ye,status:"awaiting_input",needsInput:!0,owningTabId:q,type:ae,title:o,projectId:c??null})},onSummary:se=>{S(!1),de(),m({type:"summary",sessionId:ye,summary:se}),k(se),y(""),B({sessionId:ye,status:"complete",needsInput:!1,owningTabId:q,type:ae,title:o,projectId:c??null})},onError:se=>{const J=se||"Session failed while contacting the AI.";S(!1),g(null),m({type:"error",sessionId:ye,errorMessage:J}),y(""),G.current=ye,B({sessionId:ye,status:"error",needsInput:!1,owningTabId:q,type:ae,title:o,projectId:c??null}),A({sessionId:ye,status:"error"})},onComplete:()=>{S(!1),G.current=null,A({sessionId:ye,status:"complete"})},onConnectionStateChange:se=>{S(se==="reconnecting")}});L.current=De},[A,B,ie,ae,c,q,o]),de=()=>{k(null),f([]),v([]),y("")},Te=a.useCallback(async()=>{g(null),de(),S(!1),m({type:"loading"});try{const{sessionId:ye}=await U(r,c);G.current=ye,w(ye),Q(ye)}catch(ye){S(!1),g(xe(ye)||`Failed to start ${ce.toLowerCase()} interview`),m({type:"initial"}),G.current=null,w(null)}},[Q,c,U,r,ce]),fe=a.useCallback(async()=>{g(null),T(!0);try{await F(r,c),s(),m({type:"applied"})}catch(ye){g(xe(ye)||`Failed to skip ${ce.toLowerCase()} interview`),T(!1)}},[s,c,F,r,ce]);a.useEffect(()=>{e&&d.type==="initial"&&_.current?.focus()},[e,d.type]),a.useEffect(()=>{if(!e||!u||d.type!=="initial")return;let ye=!1;return Js(u).then(De=>{if(ye||!De)return;const se=Yi(De.conversationHistory);if(v(se),w(De.id),f(se.map(J=>J.response).filter(J=>!!(J&&typeof J=="object"&&!Array.isArray(J)))),De.status==="awaiting_input"&&De.currentQuestion)try{const J=JSON.parse(De.currentQuestion);G.current=De.id,m({type:"question",sessionId:De.id,question:J})}catch{g("Failed to restore session question.")}else if(De.status==="complete"&&De.result)try{const J=JSON.parse(De.result);G.current=De.id,k(J),m({type:"summary",sessionId:De.id,summary:J})}catch{g("Failed to restore session result.")}else De.status==="generating"?(G.current=De.id,De.thinkingOutput&&y(De.thinkingOutput),m({type:"loading"}),Q(De.id)):De.status==="error"&&(G.current=De.id,g(null),m({type:"error",sessionId:De.id,errorMessage:De.error??"The session encountered an error."}))}).catch(()=>{ye||g("Failed to resume session.")}),()=>{ye=!0}},[Q,e,u,d.type]),a.useEffect(()=>{e||(S(!1),w(null))},[e]),a.useEffect(()=>{if(!(!e||!I)){if($.current!==I){$.current&&X($.current,q),z(I,q),$.current=I;return}!I&&$.current&&(X($.current,q),$.current=null)}},[z,X,e,I,q]),a.useEffect(()=>{if(!e||!I||$.current!==I)return;E(q);const ye=setInterval(()=>{E(q)},3e4);return()=>{clearInterval(ye)}},[E,e,I,q]),a.useEffect(()=>()=>{L.current?.close(),L.current=null,$.current&&(X($.current,q),$.current=null)},[X,q]);const Se=a.useCallback(()=>{L.current?.close(),L.current=null,n()},[n]),te=a.useCallback(async()=>{L.current?.close(),L.current=null,de(),m({type:"initial"}),g(null),G.current=null,w(null),n()},[n]),we=a.useCallback(async ye=>{if(d.type!=="question")return;const{sessionId:De}=d;g(null),f(se=>[...se,ye]),v(se=>[...se,{question:d.question,response:ye}]),m({type:"loading"}),y("");try{Q(De),await pe(De,ye,c,q)}catch(se){L.current?.close(),L.current=null,g(xe(se)||"Failed to submit response"),m({type:"question",sessionId:De,question:d.question})}},[Q,c,pe,q,d]),Pe=a.useCallback(async()=>{if(d.type==="summary"){g(null),T(!0);try{await re(d.sessionId,x||void 0,c),s(),m({type:"applied"})}catch(ye){g(xe(ye)||"Failed to apply interview results"),T(!1)}}},[re,x,s,c,d]),We=()=>d.type==="question"?Math.min(p.length+1,6):6,Ke=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ne=I?W.get(I):null,Oe=!!(Ne&&Ne.tabId!==q&&!Ne.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:ye=>ye.target===ye.currentTarget&&te(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(Dn,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",ce,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[Ke&&t.jsx("button",{className:"modal-send-to-background",onClick:Se,title:"Send to background","aria-label":"Send to background",children:t.jsx(aa,{size:16})}),t.jsx("button",{className:"modal-close",onClick:te,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[h&&t.jsx("div",{className:"form-error planning-error",children:h}),C&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),Oe&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-intro",children:[t.jsx(Dn,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",ce," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",i,"'s scope, acceptance criteria, and verification methods. Each ",i," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void Te(),children:[t.jsx(Dn,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void fe(),disabled:P,children:[P?t.jsx(it,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:te,children:"Cancel"})]})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(it,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:M?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>j(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),R&&M&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:M})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:te,children:"Cancel"})})]})]})}),d.type==="question"&&t.jsx(Qw,{question:d.question,progress:We(),historyEntries:b,onSubmit:we}),d.type==="summary"&&x&&t.jsx(Xw,{summary:x,historyEntries:b,onSummaryChange:k,onApply:Pe,onCancel:te,isApplying:P}),d.type==="applied"&&t.jsxs("div",{className:"planning-summary planning-applied",children:[t.jsx("div",{className:"planning-view-scroll",children:t.jsxs("div",{className:"planning-applied-content",children:[t.jsx(tn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[ce," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",i,"'s scope and verification have been ",d.type==="applied"?"applied":"updated","."]})]})}),t.jsx("div",{className:"planning-view-footer",children:t.jsx("button",{className:"btn btn-primary",onClick:s,children:"Done"})})]})]})]})}):null}function Qw({question:e,progress:n,historyEntries:s,onSubmit:i}){const[r,o]=a.useState({}),[l,c]=a.useState(""),u=a.useCallback(()=>{e.type==="text"?i({[e.id]:l}):e.type==="confirm"?i({[e.id]:r[e.id]===!0}):i(r)},[e,r,l,i]);a.useEffect(()=>{o({}),c("")},[e.id]);const d=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(m=>t.jsx("div",{className:`planning-progress-step ${m<=n?"active":""}`},m))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:m=>c(m.target.value),onKeyDown:m=>{m.key==="Enter"&&!m.shiftKey&&l.trim()&&(m.preventDefault(),u())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(m=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:m.id,checked:r[e.id]===m.id,onChange:()=>o({[e.id]:m.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(m=>{const h=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:m.id,checked:h.includes(m.id),onChange:g=>{const p=g.target.checked?[...h,m.id]:h.filter(f=>f!==m.id);o({[e.id]:p})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:m.label}),m.description&&t.jsx("span",{className:"planning-option-desc",children:m.description})]})]},m.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(tn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(Pt,{size:18}),"No"]})]})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:u,disabled:!d(),children:["Continue",t.jsx(Ga,{size:16,className:"icon-ml-4"})]})})]})}function Xw({summary:e,historyEntries:n,onSummaryChange:s,onApply:i,onCancel:r,isApplying:o}){const[l,c]=a.useState(e),[u,d]=a.useState(!0),m=(h,g)=>{const p={...l,[h]:g};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(Cs,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>d(!u),"aria-expanded":u,children:[u?t.jsx(zt,{size:16}):t.jsx(en,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),u&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:i,disabled:o,children:[o?t.jsx(it,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const ba={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"},archived:{bg:"var(--mission-archived-bg)",text:"var(--mission-archived-text)"}},tu={planning:{bg:"var(--mission-planning-bg)",text:"var(--mission-planning-text)"},active:{bg:"var(--mission-active-bg)",text:"var(--mission-active-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"},complete:{bg:"var(--mission-complete-bg)",text:"var(--mission-complete-text)"}},nu={pending:{bg:"var(--slice-pending-bg)",text:"var(--slice-pending-text)"},active:{bg:"var(--slice-active-bg)",text:"var(--slice-active-text)"},complete:{bg:"var(--slice-complete-bg)",text:"var(--slice-complete-text)"}},fr={defined:{bg:"var(--feature-defined-bg)",text:"var(--feature-defined-text)"},triaged:{bg:"var(--feature-triaged-bg)",text:"var(--feature-triaged-text)"},"in-progress":{bg:"var(--feature-in-progress-bg)",text:"var(--feature-in-progress-text)"},done:{bg:"var(--feature-done-bg)",text:"var(--feature-done-text)"}},gr={inactive:{bg:"var(--autopilot-inactive-bg)",text:"var(--autopilot-inactive-text)"},watching:{bg:"var(--autopilot-watching-bg)",text:"var(--autopilot-watching-text)"},activating:{bg:"var(--autopilot-activating-bg)",text:"var(--autopilot-activating-text)"},completing:{bg:"var(--autopilot-completing-bg)",text:"var(--autopilot-completing-text)"}},br={pending:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},passed:{bg:"var(--assertion-passed-bg)",text:"var(--assertion-passed-text)"},failed:{bg:"var(--assertion-failed-bg)",text:"var(--assertion-failed-text)"},blocked:{bg:"var(--assertion-blocked-bg)",text:"var(--assertion-blocked-text)"}},su={not_started:{bg:"var(--assertion-pending-bg)",text:"var(--assertion-pending-text)"},needs_coverage:{bg:"var(--loop-needs-fix-bg)",text:"var(--loop-needs-fix-text)"},ready:{bg:"var(--loop-validating-bg)",text:"var(--loop-validating-text)"},passed:{bg:"var(--loop-passed-bg)",text:"var(--loop-passed-text)"},failed:{bg:"var(--loop-blocked-bg)",text:"var(--loop-blocked-text)"},blocked:{bg:"var(--loop-blocked-bg)",text:"var(--loop-blocked-text)"}},Zw=3;function eN(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function iu({state:e}){const n=e==="planned"?"mission-plan-state-indicator--planned":e==="needs_update"?"mission-plan-state-indicator--needs-update":"mission-plan-state-indicator--not-started",s=e==="planned"?"Planned":e==="needs_update"?"Needs update":"Not planned";return t.jsx("span",{className:`mission-plan-state-indicator ${n}`,title:s,"aria-label":s})}function au(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Fo={title:"",description:"",status:"planning",autopilotEnabled:!1},Oo={title:"",description:"",status:"planning",dependencies:[]},Uo={title:"",description:"",status:"pending"},Bo={title:"",description:"",acceptanceCriteria:"",status:"defined"},tN=3600*1e3;function Vr(e){if(!e)return"—";const n=new Date(e).getTime();if(Number.isNaN(n))return"—";const s=Date.now()-n;if(s<0)return"just now";const i=Math.floor(s/(60*1e3));if(i<1)return"just now";if(i<60)return`${i}m ago`;const r=Math.floor(i/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function nN(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=tN,s=e.totalTasks>0&&e.tasksFailed>e.totalTasks*.3;return n||s?"error":e.tasksFailed>0?"warning":e.tasksFailed===0&&e.tasksInFlight<=e.totalTasks?"healthy":"warning"}function sN(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.missionId=="string"&&typeof n.tasksCompleted=="number"&&typeof n.tasksFailed=="number"&&typeof n.tasksInFlight=="number"&&typeof n.totalTasks=="number"&&typeof n.estimatedCompletionPercent=="number"}function iN(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.id=="string"&&typeof n.missionId=="string"&&typeof n.eventType=="string"&&typeof n.description=="string"&&typeof n.timestamp=="string"}function Ho(e){if(!e||typeof e!="object")return!1;const n=e;return typeof n.rollup?.milestoneId=="string"&&typeof n.rollup?.state=="string"&&Array.isArray(n.validationTelemetry?.validationRounds)&&typeof n.validationTelemetry?.totalRuns=="number"&&n.validationContract!==void 0&&Array.isArray(n.fixFeatures)}const Uh=["feature_triaged","feature_completed"],Bh=["slice_activated","slice_completed","milestone_completed"],Hh=["mission_started","mission_paused","mission_resumed","mission_completed"],qh=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function ru(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Hh.includes(e);case"tasks":return Uh.includes(e);case"slices":return Bh.includes(e);case"autopilot":return qh.includes(e);default:return!0}}function aN(e){return e==="error"||e==="warning"?"mission-event__type--error":Hh.includes(e)?"mission-event__type--state":Uh.includes(e)?"mission-event__type--task":Bh.includes(e)?"mission-event__type--slice":qh.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function rN(e){return e.replace(/_/g," ")}function oN(e,n){return n?e==="watching"?`Watching since ${Vr(n)}`:`Last activation ${Vr(n)}`:null}function lN({isOpen:e,isInline:n=!1,onClose:s,addToast:i,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:u,milestoneSliceResumeSessionId:d,onMilestoneSliceResumeFetchError:m}){const h=n||e,[g,p]=a.useState([]),[f,b]=a.useState(null),[v,x]=a.useState(!0),[k,M]=a.useState(!1),[y,R]=a.useState(!1),[j,C]=a.useState(null),[S,P]=a.useState(Fo),[T,_]=a.useState(!1),[L,G]=a.useState(new Set),[$,I]=a.useState(new Set),[w,q]=a.useState(null),[W,B]=a.useState(Oo),[A,z]=a.useState(!1),[X,E]=a.useState(null),[U,pe]=a.useState(Uo),[ie,re]=a.useState(!1),[F,ce]=a.useState(null),[ae,Q]=a.useState(null),[de,Te]=a.useState(Bo),[fe,Se]=a.useState(!1),[te,we]=a.useState(null),[Pe,We]=a.useState(null),[Ke,Ne]=a.useState(""),[_e,Oe]=a.useState(!1),[ye,De]=a.useState([]),[se,J]=a.useState(void 0),me=se??c,[ee,he]=a.useState(null),[le,Ie]=a.useState(null),[Ze,at]=a.useState(null);a.useEffect(()=>{h&&me&&Oe(!0)},[h,me]),a.useEffect(()=>{if(!h||me)return;let O=!1;return Sh(r).then(ke=>{if(O)return;const Re=ke.filter(ht=>ht.type==="mission_interview"&&(ht.status==="awaiting_input"||ht.status==="error"));De(Re)}).catch(ke=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",ke)}),()=>{O=!0}},[h,r,me]),a.useEffect(()=>{if(!h||!d)return;let O=!1;return Js(d).then(ke=>{if(!(O||!ke))try{const Re=JSON.parse(ke.inputPayload||"{}");Re.targetId&&Re.targetType&&he({type:Re.targetType,id:Re.targetId,title:Re.targetTitle||ke.title,resumeSessionId:d})}catch{he({type:"milestone",id:"",title:ke.title,resumeSessionId:d})}}).catch(ke=>{O||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",ke),m?.())}),()=>{O=!0}},[h,d,m]);const[oe,Z]=a.useState(null),[ue,Ce]=a.useState(new Map),[$e,ve]=a.useState(null),[Ge,je]=a.useState({title:"",assertion:"",status:"pending"}),[Ue,He]=a.useState(!1),[ge,Fe]=a.useState(null),[be,Je]=a.useState(new Map),[st,dt]=a.useState(new Set),[Tt,$t]=a.useState(new Set),[Dt,Bt]=a.useState(null),[qt,Lt]=a.useState(new Map),[Ct,xt]=a.useState(null),[Et,Le]=a.useState(null),[gt,ut]=a.useState(!0),[Me,Qe]=a.useState(new Set),[rt,N]=a.useState(new Map),[H,Ae]=a.useState(null),[ot,kt]=a.useState(new Map),[Ot,sn]=a.useState(null),[Rt,zn]=a.useState(new Map),[Wn,ms]=a.useState(new Map),[pn,Fn]=a.useState("structure"),[Sn,fn]=a.useState([]),Gn=a.useRef([]),dn=a.useRef([]),Mt=a.useRef(null),yn=a.useRef(null),Kn=a.useRef("structure"),kn=a.useRef("all"),[_n,hs]=a.useState(!1),[ps,On]=a.useState(0),[K,ze]=a.useState("all"),[tt,et]=a.useState(new Set),mt=a.useRef(null),jt=a.useRef(null);dn.current=g,Mt.current=f,yn.current=Ct,Kn.current=pn,kn.current=K;const _t=a.useCallback((O="auto")=>{const ke=jt.current;if(ke&&typeof ke.scrollIntoView=="function"){ke.scrollIntoView({block:"end",behavior:O});return}const Re=mt.current;Re&&(Re.scrollTop=Re.scrollHeight)},[]),gn=a.useCallback(()=>{const O=mt.current;return O?O.scrollHeight-O.scrollTop-O.clientHeight<=100:!0},[]),fs=a.useCallback(async O=>{if(O.length===0){ms(new Map);return}const ke=await Dy(r);ms(Re=>{const ht=new Map(Re);for(const[Kt,Nt]of Object.entries(ke))sN(Nt)&&ht.set(Kt,Nt);return ht})},[r]),Qt=a.useCallback(async()=>{try{x(!0);const O=await Ty(r);p(O),fs(O)}catch(O){i(xe(O)||"Failed to load missions","error")}finally{x(!1)}},[i,r,fs]),vt=a.useCallback(async O=>{try{M(!0);const ke=await wh(O,r);if(b(ke),ke.milestones.length>0){const Re=ke.milestones[0].id;xt(Re),ut(!0),G(new Set([Re])),Ro(Re,r).then(ht=>{Ce(Kt=>{const Nt=new Map(Kt);return Nt.set(Re,ht),Nt})}).catch(()=>{}),Io(Re,r).then(ht=>{Lt(Kt=>{const Nt=new Map(Kt);return Nt.set(Re,ht),Nt})}).catch(()=>{}),ke.milestones[0].slices.length>0&&I(new Set([ke.milestones[0].slices[0].id]))}else xt(null),Le(null)}catch(ke){i(xe(ke)||"Failed to load mission details","error")}finally{M(!1)}},[i,r]);a.useEffect(()=>{if(!h||!Ct){Le(null);return}let O=!1;return Le(null),xd(Ct,r).then(ke=>{if(!O){if(!Ho(ke)){Le(null);return}Le(ke),Lt(Re=>{const ht=new Map(Re);return ht.set(Ct,ke.rollup),ht})}}).catch(()=>{O||Le(null)}),()=>{O=!0}},[h,Ct,r]),a.useEffect(()=>{ut(!0)},[Ct]);const ct=a.useCallback(O=>{!O||O!==yn.current||xd(O,r).then(ke=>{yn.current!==O||!Ho(ke)||(Le(ke),Lt(Re=>{const ht=new Map(Re);return ht.set(O,ke.rollup),ht}))}).catch(()=>{})},[r]),ne=a.useCallback(async(O,ke)=>{const Re=ke?.append??!1,ht=Re?Gn.current.length:0;Re||(hs(!0),et(new Set));try{const Kt=await $y(O,{limit:50,offset:ht,eventType:void 0},r),Nt=Kt.events.filter(Ut=>ru(Ut.eventType,K));fn(Ut=>{if(!Re)return Nt;const Be=new Set(Ut.map(pt=>pt.id)),qe=[...Ut];for(const pt of Nt)Be.has(pt.id)||qe.push(pt);return qe}),On(Kt.total),Re||requestAnimationFrame(()=>{_t("auto")})}catch(Kt){i(xe(Kt)||"Failed to load mission activity","error")}finally{Re||hs(!1)}},[i,K,r,_t]);a.useEffect(()=>{Gn.current=Sn},[Sn]),a.useEffect(()=>{h&&(Qt(),b(null),xt(null),Le(null),fn([]),On(0),Fn("structure"),ze("all"),et(new Set))},[h,Qt]);const Ee=a.useRef(null);a.useEffect(()=>{h&&u&&Ee.current!==u&&g.length>0&&(Ee.current=u,vt(u))},[h,u,g,vt]),a.useEffect(()=>{h||(Ee.current=null)},[h]),a.useEffect(()=>{!h||!f||pn!=="activity"||ne(f.id)},[pn,h,ne,f,K]),a.useEffect(()=>{if(!h||typeof EventSource>"u")return;const O=new URLSearchParams;r&&O.set("projectId",r);const ke=`/api/events${O.size>0?`?${O.toString()}`:""}`,Re=()=>{fs(dn.current)},ht=En=>{Re();const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At?.id&&p(pi=>pi.map(ys=>ys.id===At.id?{...ys,...At}:ys))}catch{}Mt.current&&vt(Mt.current.id)},Kt=En=>{Re(),Mt.current&&vt(Mt.current.id)},Nt=()=>{Re(),Mt.current&&vt(Mt.current.id)},Ut=En=>{Re(),Mt.current&&vt(Mt.current.id)},Be=En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At&&At.featureId&&(Ws(At.featureId),ni(At.featureId),At.milestoneId&&ct(At.milestoneId))}catch{}},qe=En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At&&At.featureId&&(Ws(At.featureId),ni(At.featureId),At.milestoneId&&ct(At.milestoneId),Mt.current&&vt(Mt.current.id))}catch{}},pt=En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At&&At.milestoneId&&(Y(At.milestoneId),ct(At.milestoneId))}catch{}},Jt=En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);At&&At.milestoneId&&(ti(At.milestoneId),Y(At.milestoneId),ct(At.milestoneId))}catch{}};return qs(ke,{events:{"mission:updated":ht,"slice:updated":Kt,"feature:updated":Nt,"milestone:updated":Ut,"mission:event":En=>{Re();const ln=Mt.current;if(!ln||Kn.current!=="activity")return;const At=gn(),pi=En;if(pi.data)try{const ys=JSON.parse(pi.data);if(!iN(ys)||ys.missionId!==ln.id||!ru(ys.eventType,kn.current))return;fn(Gs=>{const Eo=Gs.filter(Mo=>Mo.id!==ys.id);return[ys,...Eo].slice(0,100)}),On(Gs=>Gs+1),At&&requestAnimationFrame(()=>{const Gs=mt.current;Gs&&(Gs.scrollTop=0)})}catch{}},"validator-run:started":Be,"validator-run:completed":qe,"milestone:validation:updated":pt,"assertion:created":Jt,"assertion:updated":Jt,"assertion:deleted":Jt,"assertion:linked":Jt,"assertion:unlinked":Jt,"fix-feature:created":En=>{const ln=En;if(ln.data)try{const At=JSON.parse(ln.data);if(At&&At.sourceFeatureId){Ws(At.sourceFeatureId);const pi=At?.feature?.sliceId,ys=Mt.current;if(pi&&ys){const Gs=ys.milestones.find(Eo=>Eo.slices.some(Mo=>Mo.id===pi));Gs&&ct(Gs.id)}Mt.current&&vt(Mt.current.id)}}catch{}}}})},[h,gn,vt,fs,r,ct]);const nt=a.useCallback(()=>{R(!0),C(null),P(Fo)},[]),ft=a.useCallback(O=>{C(O.id),R(!1),P({title:O.title,description:O.description||"",status:O.status,autopilotEnabled:O.autopilotEnabled??!1})},[]),bt=a.useCallback(()=>{C(null),R(!1),P(Fo)},[]),on=a.useCallback(async()=>{if(!S.title.trim()){i("Mission title is required","error");return}try{if(_(!0),y)await Ry({title:S.title.trim(),description:S.description.trim()||void 0,autopilotEnabled:S.autopilotEnabled},r),i("Mission created","success");else if(j){const O={title:S.title.trim(),description:S.description.trim()||void 0,status:S.status,autopilotEnabled:S.autopilotEnabled};S.autopilotEnabled&&(O.autoAdvance=!0),await Iy(j,O,r),i("Mission updated","success"),f?.id===j&&await vt(j)}await Qt(),bt()}catch(O){i(xe(O)||"Failed to save mission","error")}finally{_(!1)}},[S,y,j,i,Qt,vt,f,bt,r]),Xt=a.useCallback(async O=>{try{await Py(O,r),i("Mission deleted","success"),f?.id===O&&b(null),await Qt(),Z(null)}catch(ke){i(xe(ke)||"Failed to delete mission","error")}},[i,Qt,f,r]),cn=a.useCallback(()=>{z(!0),q(null),B(Oo)},[]),Gt=a.useCallback(O=>{q(O.id),z(!1),B({title:O.title,description:O.description||"",status:O.status,dependencies:O.dependencies})},[]),bn=a.useCallback(()=>{q(null),z(!1),B(Oo)},[]),Cn=a.useCallback(async()=>{if(!W.title.trim()){i("Milestone title is required","error");return}try{_(!0),A&&f?(await Ly(f.id,{title:W.title.trim(),description:W.description.trim()||void 0,dependencies:W.dependencies},r),i("Milestone created","success")):w&&(await zy(w,{title:W.title.trim(),description:W.description.trim()||void 0,status:W.status,dependencies:W.dependencies},r),i("Milestone updated","success")),await vt(f.id),bn()}catch(O){i(xe(O)||"Failed to save milestone","error")}finally{_(!1)}},[W,A,w,f,i,vt,bn,S.title,r]),gs=a.useCallback(async O=>{try{await Fy(O,r),i("Milestone deleted","success"),await vt(f.id),Z(null)}catch(ke){i(xe(ke)||"Failed to delete milestone","error")}},[i,vt,f,r]),Un=a.useCallback(O=>{xt(O),ut(!0),G(ke=>{const Re=new Set(ke);return!Re.has(O)?(Re.add(O),Ro(O,r).then(Kt=>{Ce(Nt=>{const Ut=new Map(Nt);return Ut.set(O,Kt),Ut})}).catch(()=>{}),Io(O,r).then(Kt=>{Lt(Nt=>{const Ut=new Map(Nt);return Ut.set(O,Kt),Ut})}).catch(()=>{})):Re.delete(O),Re})},[r]),Jn=a.useCallback(O=>{ce(O),re(!0),E(null),pe(Uo)},[]),Bn=a.useCallback(O=>{E(O.id),re(!1),pe({title:O.title,description:O.description||"",status:O.status})},[]),Yn=a.useCallback(()=>{E(null),re(!1),ce(null),pe(Uo)},[]),un=a.useCallback(async()=>{if(!U.title.trim()){i("Slice title is required","error");return}try{_(!0),ie&&F?(await Oy(F,{title:U.title.trim(),description:U.description.trim()||void 0},r),i("Slice created","success")):X&&(await Uy(X,{title:U.title.trim(),description:U.description.trim()||void 0,status:U.status},r),i("Slice updated","success")),await vt(f.id),Yn()}catch(O){i(xe(O)||"Failed to save slice","error")}finally{_(!1)}},[U,ie,X,F,f,i,vt,Yn,r]),Qn=a.useCallback(async O=>{try{await By(O,r),i("Slice deleted","success"),await vt(f.id),Z(null)}catch(ke){i(xe(ke)||"Failed to delete slice","error")}},[i,vt,f,r]),Es=a.useCallback(async O=>{try{await Hy(O,r),i("Slice activated","success"),await vt(f.id)}catch(ke){i(xe(ke)||"Failed to activate slice","error")}},[i,vt,f,r]),Is=a.useCallback(O=>{I(ke=>{const Re=new Set(ke);return Re.has(O)?Re.delete(O):Re.add(O),Re})},[]),rs=a.useCallback(O=>{we(O),Se(!0),Q(null),Te(Bo)},[]),An=a.useCallback(O=>{Q(O.id),Se(!1),Te({title:O.title,description:O.description||"",acceptanceCriteria:O.acceptanceCriteria||"",status:O.status})},[]),bs=a.useCallback(()=>{Q(null),Se(!1),we(null),Te(Bo)},[]),Tn=a.useCallback(async()=>{if(!de.title.trim()){i("Feature title is required","error");return}try{_(!0),fe&&te?(await qy(te,{title:de.title.trim(),description:de.description.trim()||void 0,acceptanceCriteria:de.acceptanceCriteria.trim()||void 0},r),i("Feature created","success")):ae&&(await Vy(ae,{title:de.title.trim(),description:de.description.trim()||void 0,acceptanceCriteria:de.acceptanceCriteria.trim()||void 0,status:de.status},r),i("Feature updated","success")),await vt(f.id),bs()}catch(O){i(xe(O)||"Failed to save feature","error")}finally{_(!1)}},[de,fe,ae,te,f,i,vt,bs,r]),ua=a.useCallback(async O=>{try{await Wy(O,r),i("Feature deleted","success"),await vt(f.id),Z(null)}catch(ke){i(xe(ke)||"Failed to delete feature","error")}},[i,vt,f,r]),xo=a.useCallback(async()=>{if(!Pe||!Ke.trim()){i("Task ID is required","error");return}try{await Gy(Pe,Ke.trim(),r),i("Feature linked to task","success"),await vt(f.id),We(null),Ne("")}catch(O){i(xe(O)||"Failed to link feature to task","error")}},[Pe,Ke,i,vt,f,r]),vo=a.useCallback(async O=>{try{await Ky(O,r),i("Feature unlinked from task","success"),await vt(f.id)}catch(ke){i(xe(ke)||"Failed to unlink feature","error")}},[i,vt,f,r]),mi=a.useCallback(async O=>{try{_(!0),await Jy(O,void 0,void 0,r),i("Feature triaged — task created","success"),await vt(f.id)}catch(ke){i(xe(ke)||"Failed to triage feature","error")}finally{_(!1)}},[i,vt,f,r]),ar=a.useCallback(async O=>{at(O);try{const ke=await Nk(O,r);Ie({featureId:O,enrichedDescription:ke.description})}catch{await mi(O)}finally{at(null)}},[mi,r]),rr=a.useCallback(async()=>{le&&(Ie(null),await mi(le.featureId))},[mi,le]),ei=a.useCallback(()=>{Ie(null)},[]),yo=a.useCallback(async O=>{try{_(!0);const ke=await Yy(O,r);i(`Triaged ${ke.count} feature${ke.count!==1?"s":""}`,"success"),await vt(f.id)}catch(ke){i(xe(ke)||"Failed to triage slice features","error")}finally{_(!1)}},[i,vt,f,r]),ti=a.useCallback(async O=>{try{const ke=await Ro(O,r);Ce(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),Y=a.useCallback(async O=>{try{const ke=await Io(O,r);Lt(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),Ye=a.useCallback(async O=>{if(!Ge.title.trim()||!Ge.assertion.trim()){i("Title and assertion text are required","error");return}try{_(!0),await Qy(O,{title:Ge.title.trim(),assertion:Ge.assertion.trim(),status:Ge.status},r),i("Assertion created","success"),await ti(O),await Y(O),He(!1),je({title:"",assertion:"",status:"pending"})}catch(ke){i(xe(ke)||"Failed to create assertion","error")}finally{_(!1)}},[Ge,i,ti,Y,r]),lt=a.useCallback(O=>{ve(O.id),je({title:O.title,assertion:O.assertion,status:O.status})},[]),wt=a.useCallback(()=>{ve(null),He(!1),je({title:"",assertion:"",status:"pending"})},[]),Ms=a.useCallback(async(O,ke)=>{if(!Ge.title.trim()||!Ge.assertion.trim()){i("Title and assertion text are required","error");return}try{_(!0),await Xy(O,{title:Ge.title.trim(),assertion:Ge.assertion.trim(),status:Ge.status},r),i("Assertion updated","success"),await ti(ke),await Y(ke),wt()}catch(Re){i(xe(Re)||"Failed to update assertion","error")}finally{_(!1)}},[Ge,i,ti,Y,wt,r]),Rn=a.useCallback(async O=>{try{const ke=await tk(O,r);Je(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),or=a.useCallback(async O=>{const ke=ge!==O;Fe(Re=>Re===O?null:O),ke&&await Rn(O)},[ge,Rn]),ma=a.useCallback(O=>{Fe(O),Rn(O),requestAnimationFrame(()=>{const ke=document.querySelector(`[data-mission-assertion-id="${O}"]`);ke instanceof HTMLElement&&typeof ke.scrollIntoView=="function"&&ke.scrollIntoView({behavior:"smooth",block:"center"})})},[Rn]),ko=a.useCallback(async(O,ke)=>{try{dt(Re=>new Set(Re).add(ke)),await Zy(O,ke,r),i("Feature linked to assertion","success"),await Rn(ke),Bt(null)}catch(Re){i(xe(Re)||"Failed to link feature","error")}finally{dt(Re=>{const ht=new Set(Re);return ht.delete(ke),ht})}},[i,Rn,r]),jo=a.useCallback(async(O,ke)=>{const Re=`${O}-${ke}`;try{$t(ht=>new Set(ht).add(Re)),await ek(O,ke,r),i("Feature unlinked from assertion","success"),await Rn(ke)}catch(ht){i(xe(ht)||"Failed to unlink feature","error")}finally{$t(ht=>{const Kt=new Set(ht);return Kt.delete(Re),Kt})}},[i,Rn,r]),wo=a.useCallback(async O=>{try{Qe(Re=>new Set(Re).add(O)),await nk(O,r),i("Validation triggered","success");const ke=await vd(O,r);N(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch(ke){i(xe(ke)||"Failed to trigger validation","error")}finally{Qe(ke=>{const Re=new Set(ke);return Re.delete(O),Re})}},[i,r]),Ws=a.useCallback(async O=>{try{const ke=await vd(O,r);N(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),ni=a.useCallback(async O=>{try{const ke=await sk(O,{limit:10},r);kt(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),si=a.useCallback(O=>{const ke=Mt.current;if(ke){for(const Re of ke.milestones)for(const ht of Re.slices)if(ht.features.find(Nt=>Nt.id===O)){G(Nt=>{const Ut=new Set(Nt);return Ut.add(Re.id),Ut}),I(Nt=>{const Ut=new Set(Nt);return Ut.add(ht.id),Ut}),Ae(O),xt(Re.id),Ws(O),ni(O),requestAnimationFrame(()=>{const Nt=document.querySelector(`[data-mission-feature-id="${O}"]`);Nt instanceof HTMLElement&&typeof Nt.scrollIntoView=="function"&&Nt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[Ws,ni]),Ti=a.useCallback(async O=>{try{const ke=await ik(O,r);zn(Re=>{const ht=new Map(Re);return ht.set(O,ke),ht})}catch{}},[r]),Ri=a.useCallback(async O=>{H===O?Ae(null):(Ae(O),await Ws(O),await ni(O))},[H,Ws,ni]),ha=a.useCallback(async O=>{Ot===O?sn(null):(sn(O),await Ti(O))},[Ot,Ti]),No=a.useCallback(async O=>{try{await ak(O,r),i("Mission resumed","success"),await vt(O),Qt()}catch(ke){i(xe(ke)||"Failed to resume mission","error")}},[i,vt,Qt,r]),So=a.useCallback(async O=>{try{const Re=(await rk(O,r)).pausedTaskIds?.length??0;i(`Mission stopped (${Re} task${Re!==1?"s":""} paused)`,"success"),await vt(O),Qt()}catch(ke){i(xe(ke)||"Failed to stop mission","error")}},[i,vt,Qt,r]),xs=a.useCallback(async O=>{try{await ok(O,r),i("Mission started — first slice activated","success"),await vt(O),Qt()}catch(ke){i(xe(ke)||"Failed to start mission","error")}},[i,vt,Qt,r]),ii=a.useCallback(async(O,ke)=>{try{await lk(O,{enabled:ke},r),i(ke?"Autopilot enabled":"Autopilot disabled","success"),await vt(O),Qt()}catch(Re){i(xe(Re)||"Failed to update autopilot","error")}},[i,vt,Qt,r]),_s=a.useCallback(O=>{Fn("structure"),xt(null),Le(null),fn([]),On(0),ze("all"),et(new Set),vt(O.id)},[vt]),Ps=a.useCallback(()=>{b(null),xt(null),Le(null),Fn("structure"),fn([]),On(0),ze("all"),et(new Set),Qt()},[Qt]),lr=Sn.length<ps,Ii=f?.autopilotState??"inactive",zc=Ii==="watching"||Ii==="activating",Fc=oN(Ii,f?.lastAutopilotActivityAt),cr=a.useMemo(()=>!Et||!Ct||!Ho(Et)?null:Et.rollup.milestoneId===Ct?Et:null,[Ct,Et]),kf=a.useMemo(()=>{const O=new Map;for(const ke of cr?.validationTelemetry.validationRounds??[]){const Re=O.get(ke.featureId);(!Re||ke.startedAt>Re.startedAt)&&O.set(ke.featureId,ke)}return O},[cr]),jf=a.useCallback(()=>{!f||_n||!lr||ne(f.id,{append:!0})},[_n,lr,ne,f]),wf=a.useCallback(O=>{et(ke=>{const Re=new Set(ke);return Re.has(O)?Re.delete(O):Re.add(O),Re})},[]),Co=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),on())},[on]),Oc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Cn())},[Cn]),Uc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),un())},[un]),Bc=a.useCallback(O=>{O.key==="Enter"&&!O.shiftKey&&(O.preventDefault(),Tn())},[Tn]),Nf=a.useRef(null);if(a.useEffect(()=>{if(!h)return;const O=ke=>{ke.key==="Escape"&&s()};return document.addEventListener("keydown",O),()=>document.removeEventListener("keydown",O)},[h,s]),!h)return null;const Hc=t.jsxs("div",{ref:Nf,className:`mission-manager${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[f?t.jsx("button",{className:"mission-manager__back-btn",onClick:Ps,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(rc,{size:18})}):null,t.jsx(ns,{size:18,className:"mission-manager__header-icon"}),t.jsx("h2",{className:"mission-manager__title",children:f?f.title:"Missions"})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(Pt,{size:18})})]}),t.jsx("div",{className:"mission-manager__body",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(it,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):k?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(it,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):f?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[zc&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:f.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(ba[f.status]||ba.planning).bg,color:(ba[f.status]||ba.planning).text},children:f.status})]}),f.description&&t.jsx("p",{className:"mission-detail__description",children:f.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[f.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:f.autopilotEnabled??!1,onChange:O=>ii(f.id,O.target.checked),"aria-label":"Autopilot"}),t.jsx("span",{className:"mission-toggle__track","aria-hidden":"true",children:t.jsx("span",{className:"mission-toggle__thumb"})}),t.jsxs("span",{className:"mission-toggle__label",children:[t.jsx(vn,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(gr[Ii]||gr.inactive).bg,color:(gr[Ii]||gr.inactive).text},"data-testid":"autopilot-state-badge",children:[zc&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ii]})]}),Fc&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:Fc})]}),t.jsxs("div",{className:"mission-detail__actions",children:[f.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>So(f.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx(ls,{size:14})}),f.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>No(f.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(rn,{size:14})}),f.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xs(f.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ft(f),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"mission",id:f.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Ht,{size:14})})]})]}),j===f.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:O=>P({...S,title:O.target.value}),onKeyDown:Co,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:O=>P({...S,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:O=>P({...S,status:O.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:S.autopilotEnabled,onChange:O=>P({...S,autopilotEnabled:O.target.checked})}),t.jsx(vn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:on,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${pn==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Fn("structure"),role:"tab","aria-selected":pn==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${pn==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>Fn("activity"),role:"tab","aria-selected":pn==="activity","data-testid":"mission-tab-activity",children:["Activity (",ps,")"]})]}),pn==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[f.milestones.map(O=>{const ke=cr?.rollup.milestoneId===O.id?cr:null,Re=ke?.rollup??qt.get(O.id),ht=ke?.validationTelemetry.validationRounds??[],Kt=ke?.fixFeatures??[],Nt=su[Re?.state??"not_started"]??su.not_started,Ut=Re&&(Re.state==="blocked"||Re.state==="failed")?ke?.validationTelemetry.validationRounds.find(Be=>Be.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>Un(O.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:L.has(O.id)?t.jsx(zt,{size:16}):t.jsx(en,{size:16})}),t.jsx(Si,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:O.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:tu[O.status].bg,color:tu[O.status].text},children:O.status}),t.jsxs("span",{className:"mission-milestone__count",children:[O.slices.length," slices"]}),t.jsx(iu,{state:eN(O.interviewState)}),Re&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Nt.bg,color:Nt.text},title:"Validation state",children:au(Re.state)}),Re.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Re.passedAssertions??0} of ${Re.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Re.passedAssertions??0)/Re.totalAssertions*100}%`,backgroundColor:(Re.passedAssertions??0)===Re.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),O.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>he({type:"milestone",id:O.id,title:O.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(Ni,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Be=>Be.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Jn(O.id),title:"Add slice",children:t.jsx(Vt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Gt(O),title:"Edit milestone",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"milestone",id:O.id}),title:"Delete milestone",children:t.jsx(Ht,{size:14})})]})]}),L.has(O.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(A||w===O.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:W.title,onChange:Be=>B({...W,title:Be.target.value}),onKeyDown:Oc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:W.description,onChange:Be=>B({...W,description:Be.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),w?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bn,children:"Cancel"})]})]}),ke&&t.jsxs("div",{className:"mission-validation-telemetry",children:[t.jsxs("div",{className:"mission-validation-telemetry__header",children:[t.jsx("span",{className:"mission-validation-telemetry__title",children:"Validation Telemetry"}),t.jsxs("span",{className:"mission-validation-telemetry__meta",children:[ke.validationTelemetry.totalRuns," rounds",ke.validationTelemetry.lastValidatorStatus?` · Last ${ke.validationTelemetry.lastValidatorStatus}`:""]})]}),Ut&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Ut]}),ht.length>0&&t.jsxs("div",{className:"mission-validation-rounds",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm mission-validation-rounds__toggle",onClick:()=>ut(Be=>!Be),title:gt?"Hide validation rounds":"Show validation rounds",children:[gt?t.jsx(zt,{size:12}):t.jsx(en,{size:12}),"Validation rounds (",ht.length,")"]}),gt&&t.jsx("div",{className:"mission-validation-rounds__list",children:ht.map(Be=>t.jsxs("div",{className:"mission-validation-round",children:[t.jsxs("div",{className:"mission-validation-round__header",children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-validation-round__status mission-validation-round__status--${Be.validatorStatus}`,children:Be.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Be.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Be.implementationAttempt," · validator #",Be.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Be.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Be.failedAssertionIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ma(qe),title:`Jump to assertion ${qe}`,children:qe},`${Be.roundId}-${qe}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Generated fix features:"}),Be.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Be.generatedFixFeatureIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>si(qe),title:`Jump to fix feature ${qe}`,children:qe},`${Be.roundId}-${qe}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Be.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Be.blockedReason})]},Be.roundId))})]}),Kt.length>0&&t.jsxs("div",{className:"mission-fix-features",children:[t.jsx("div",{className:"mission-fix-features__title",children:"Generated Fix Features"}),t.jsx("div",{className:"mission-fix-features__list",children:Kt.map(Be=>t.jsxs("div",{className:"mission-fix-feature",children:[t.jsxs("div",{className:"mission-fix-feature__header",children:[t.jsx("button",{className:"mission-fix-feature__title",onClick:()=>si(Be.id),title:`Jump to feature ${Be.id}`,children:Be.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:fr[Be.status].bg,color:fr[Be.status].text},children:Be.status}),Be.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Be.loopState}`,children:Be.loopState})]}),t.jsxs("div",{className:"mission-fix-feature__meta",children:[t.jsx("span",{children:"Source:"}),t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>si(Be.sourceFeatureId),title:`Jump to source feature ${Be.sourceFeatureId}`,children:Be.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Be.runId})]}),Be.failedAssertionIds.length>0&&t.jsxs("div",{className:"mission-fix-feature__assertions",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),t.jsx("div",{className:"mission-validation-round__chip-list",children:Be.failedAssertionIds.map(qe=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>ma(qe),title:`Jump to assertion ${qe}`,children:qe},`${Be.id}-${qe}`))})]})]},Be.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[O.slices.map(Be=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>Is(Be.id),children:[t.jsx("button",{className:"mission-slice__expand",children:$.has(Be.id)?t.jsx(zt,{size:16}):t.jsx(en,{size:16})}),t.jsx(Il,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Be.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:nu[Be.status].bg,color:nu[Be.status].text},children:Be.status}),t.jsxs("span",{className:"mission-slice__count",children:[Be.features?.length||0," features"]}),t.jsx(iu,{state:Be.planState??"not_started"}),Be.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>he({type:"slice",id:Be.id,title:Be.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(Ni,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:qe=>qe.stopPropagation(),children:[Be.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Es(Be.id),title:"Activate slice",children:t.jsx(rn,{size:14})}),Be.status==="active"&&Be.features?.some(qe=>qe.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>yo(Be.id),title:"Triage all features",disabled:T,children:T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(vn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>rs(Be.id),title:"Add feature",children:t.jsx(Vt,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Bn(Be),title:"Edit slice",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"slice",id:Be.id}),title:"Delete slice",children:t.jsx(Ht,{size:14})})]})]}),$.has(Be.id)&&t.jsxs("div",{className:"mission-slice__body",children:[ie&&F===O.id&&!X&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:U.title,onChange:qe=>pe({...U,title:qe.target.value}),onKeyDown:Uc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:qe=>pe({...U,description:qe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:un,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),X===Be.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:U.title,onChange:qe=>pe({...U,title:qe.target.value}),onKeyDown:Uc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:U.description,onChange:qe=>pe({...U,description:qe.target.value}),rows:2}),t.jsxs("select",{value:U.status,onChange:qe=>pe({...U,status:qe.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"complete",children:"Complete"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:un,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Yn,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Be.features?.map(qe=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":qe.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Ri(qe.id),title:H===qe.id?"Collapse details":"Expand to show run history",children:H===qe.id?t.jsx(zt,{size:14}):t.jsx(en,{size:14})}),t.jsx(Ml,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:qe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:fr[qe.status].bg,color:fr[qe.status].text},children:qe.status}),qe.loopState&&qe.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${qe.loopState}`,title:`Loop state: ${qe.loopState}`,children:[qe.loopState==="implementing"&&"⏳",qe.loopState==="validating"&&"🔄",qe.loopState==="needs_fix"&&"🔧",qe.loopState==="passed"&&"✅",qe.loopState==="blocked"&&"🚫"]}),qe.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>si(qe.generatedFromFeatureId),title:`Generated from feature: ${qe.generatedFromFeatureId}`,children:"🔗 Fix"}),(qe.loopState==="validating"||qe.loopState==="needs_fix")&&(()=>{const pt=rt.get(qe.id),Jt=kf.get(qe.id),vs=pt?.implementationAttemptCount??Jt?.implementationAttempt??qe.implementationAttemptCount??0,hi=pt?.retryBudgetRemaining??Math.max(0,Zw-vs);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",vs," · ",hi," ",hi===1?"retry":"retries"," left"]})})(),qe.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>wo(qe.id),title:"Validate feature",disabled:Me.has(qe.id),children:Me.has(qe.id)?t.jsx(it,{size:14,className:"spinner"}):t.jsx(Dn,{size:14})}),qe.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(qe.taskId),title:"Click to view task",children:qe.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[qe.status==="defined"&&!qe.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>ar(qe.id),title:"Triage — create task",disabled:T||Ze===qe.id,children:Ze===qe.id?t.jsx(it,{size:14,className:"spinner"}):t.jsx(vn,{size:14})}),qe.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>vo(qe.id),title:"Unlink task",children:t.jsx(Yc,{size:14})}):qe.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>We(qe.id),title:"Link to task",children:t.jsx(Wi,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>An(qe),title:"Edit feature",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"feature",id:qe.id}),title:"Delete feature",children:t.jsx(Ht,{size:14})})]})]}),qe.description&&t.jsx("p",{className:"mission-feature__description",children:qe.description}),qe.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",qe.acceptanceCriteria]}),le?.featureId===qe.id&&t.jsxs("div",{className:"mission-triage-preview",children:[t.jsx("div",{className:"mission-triage-preview__header",children:"Enriched Description Preview"}),t.jsx("div",{className:"mission-triage-preview__content",children:le.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:rr,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:ei,disabled:T,children:"Cancel"})]})]}),ae===qe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:pt=>Te({...de,title:pt.target.value}),onKeyDown:Bc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:pt=>Te({...de,description:pt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:pt=>Te({...de,acceptanceCriteria:pt.target.value}),rows:2}),t.jsxs("select",{value:de.status,onChange:pt=>Te({...de,status:pt.target.value}),children:[t.jsx("option",{value:"defined",children:"Defined"}),t.jsx("option",{value:"triaged",children:"Triaged"}),t.jsx("option",{value:"in-progress",children:"In Progress"}),t.jsx("option",{value:"done",children:"Done"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Tn,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),H===qe.id&&t.jsxs("div",{className:"mission-feature__run-history",children:[t.jsx("div",{className:"mission-feature__run-history-header",children:t.jsx("span",{className:"mission-feature__run-history-title",children:"Validation Runs"})}),(ot.get(qe.id)??[]).map(pt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>ha(pt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${pt.status}`,title:pt.status,children:pt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(pt.startedAt).toLocaleString()}),pt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(pt.completedAt).getTime()-new Date(pt.startedAt).getTime())/1e3),"s"]}),pt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:pt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:Ot===pt.id?"Hide details":"Show details",children:Ot===pt.id?t.jsx(zt,{size:12}):t.jsx(en,{size:12})})]}),Ot===pt.id&&Rt.get(pt.id)&&t.jsxs("div",{className:"mission-run__details",children:[pt.summary&&t.jsx("p",{className:"mission-run__summary",children:pt.summary}),pt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",pt.blockedReason]}),Rt.get(pt.id)?.failures&&Rt.get(pt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),Rt.get(pt.id).failures.map(Jt=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Jt.message}),Jt.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Jt.expected]}),Jt.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Jt.actual]})]},Jt.id))]}),(!Rt.get(pt.id)?.failures||Rt.get(pt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},pt.id)),(!ot.get(qe.id)||ot.get(qe.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},qe.id)),fe&&te===Be.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:de.title,onChange:qe=>Te({...de,title:qe.target.value}),onKeyDown:Bc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:de.description,onChange:qe=>Te({...de,description:qe.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:de.acceptanceCriteria,onChange:qe=>Te({...de,acceptanceCriteria:qe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Tn,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bs,children:"Cancel"})]})]}),!fe&&(!Be.features||Be.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(Ml,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Be.id)),O.slices.length===0&&!ie&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Il,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Re&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Nt.bg,color:Nt.text},children:au(Re.state)}),Re&&Re.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Re.passedAssertions??0} of ${Re.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Re.passedAssertions??0)/Re.totalAssertions*100}%`,backgroundColor:(Re.passedAssertions??0)===Re.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{He(!0),ve(null),je({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx(Vt,{size:14})})]}),Ue&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Ge.title,onChange:Be=>je({...Ge,title:Be.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:Ge.assertion,onChange:Be=>je({...Ge,assertion:Be.target.value}),rows:2}),t.jsxs("select",{value:Ge.status,onChange:Be=>je({...Ge,status:Be.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Ye(O.id),disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:wt,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(ue.get(O.id))?ue.get(O.id):[]).map(Be=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Be.id,children:[t.jsx("div",{className:"mission-assertion__header",children:$e===Be.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:Ge.title,onChange:qe=>je({...Ge,title:qe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:Ge.assertion,onChange:qe=>je({...Ge,assertion:qe.target.value}),rows:2}),t.jsxs("select",{value:Ge.status,onChange:qe=>je({...Ge,status:qe.target.value}),children:[t.jsx("option",{value:"pending",children:"Pending"}),t.jsx("option",{value:"passed",children:"Passed"}),t.jsx("option",{value:"failed",children:"Failed"}),t.jsx("option",{value:"blocked",children:"Blocked"})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:()=>Ms(Be.id,O.id),disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:wt,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(br[Be.status]??br.pending).bg,color:(br[Be.status]??br.pending).text},children:Be.status}),t.jsx("span",{className:"mission-assertion__title",children:Be.title}),(()=>{const pt=be.get(Be.id)?.length??0;return pt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${pt} linked feature${pt!==1?"s":""}`,children:["(",pt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>or(Be.id),title:"Toggle details",children:ge===Be.id?t.jsx(zt,{size:14}):t.jsx(en,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>lt(Be),title:"Edit assertion",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"assertion",id:Be.id}),title:"Delete assertion",children:t.jsx(Ht,{size:14})})]})}),ge===Be.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Be.assertion}),t.jsxs("div",{className:"mission-assertion__linked-features",children:[t.jsxs("div",{className:"mission-assertion__linked-features-header",children:[t.jsx("span",{className:"mission-assertion__linked-features-label",children:"Linked Features"}),t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:async()=>{ge!==Be.id&&await or(Be.id),Bt(Dt===Be.id?null:Be.id)},title:"Link a feature",children:[t.jsx(Wi,{size:12}),"Link Feature"]})]}),Dt===Be.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const qe=new Set((be.get(Be.id)??[]).map(Jt=>Jt.id)),pt=[];return f?.milestones.forEach(Jt=>Jt.slices.forEach(vs=>pt.push(...vs.features.filter(hi=>!qe.has(hi.id))))),pt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):pt.map(Jt=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>ko(Jt.id,Be.id),disabled:st.has(Be.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Jt.title}),st.has(Be.id)&&t.jsx(it,{size:12,className:"spinner"})]},Jt.id))})()})}),(()=>{const qe=be.get(Be.id)??[];return qe.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):qe.map(pt=>{const Jt=`${pt.id}-${Be.id}`,vs=Tt.has(Jt);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:pt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>jo(pt.id,Be.id),disabled:vs,title:"Unlink feature",children:vs?t.jsx(it,{size:12,className:"spinner"}):t.jsx(Yc,{size:12})})]},pt.id)})})()]})]})]},Be.id)),(!ue.get(O.id)||ue.get(O.id)?.length===0)&&!Ue&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},O.id)}),f&&!A&&w===null&&t.jsxs("button",{className:"mission-add-btn",onClick:cn,children:[t.jsx(Vt,{size:16}),"Add Milestone"]}),A&&w===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:W.title,onChange:O=>B({...W,title:O.target.value}),onKeyDown:Oc,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:W.description,onChange:O=>B({...W,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Cn,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bn,children:"Cancel"})]})]}),f.milestones.length===0&&!A&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Si,{size:24}),t.jsx("span",{children:"No milestones yet. Add one to get started."})]})]}):t.jsxs("div",{className:"mission-detail__activity","data-testid":"mission-activity-tab",children:[t.jsxs("div",{className:"mission-detail__activity-controls",children:[t.jsxs("label",{className:"mission-detail__activity-filter",children:[t.jsx("span",{children:"Filter"}),t.jsxs("select",{value:K,onChange:O=>ze(O.target.value),"data-testid":"mission-activity-filter",children:[t.jsx("option",{value:"all",children:"All events"}),t.jsx("option",{value:"errors",children:"Errors & warnings"}),t.jsx("option",{value:"state_changes",children:"State changes"}),t.jsx("option",{value:"tasks",children:"Task events"}),t.jsx("option",{value:"slices",children:"Slice & milestone events"}),t.jsx("option",{value:"autopilot",children:"Autopilot events"})]})]}),t.jsxs("span",{className:"mission-detail__activity-count",children:[Sn.length," of ",ps]})]}),!_n&&lr&&t.jsx("div",{className:"mission-detail__activity-load-more mission-detail__activity-load-more--top",children:t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:jf,"data-testid":"mission-activity-load-more",children:"Load more"})}),_n?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(it,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):Sn.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Ss,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:mt,className:"mission-events","data-testid":"mission-activity-events",children:[Sn.map(O=>{const ke=!!(O.metadata&&Object.keys(O.metadata).length>0),Re=tt.has(O.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${aN(O.eventType)}`,children:rN(O.eventType)}),t.jsx("span",{className:"mission-event__time",children:Vr(O.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:O.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(O.timestamp).toLocaleString()}),ke&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>wf(O.id),"data-testid":`mission-event-metadata-${O.id}`,children:[Re?"Hide":"Show"," metadata"]}),Re&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(O.metadata,null,2)})]})]},O.id)}),t.jsx("div",{ref:jt})]})]})]}):t.jsxs("div",{className:"mission-list",children:[y&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:O=>P({...S,title:O.target.value}),onKeyDown:Co,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:O=>P({...S,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:on,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),g.map(O=>{const ke=O,Re=f,ht=Re&&Re.id===ke.id,Kt=ba[ke.status]||{bg:"",text:""},Nt=ke.summary,Ut=Wn.get(ke.id),Be=nN(Ut),qe=!!(Nt&&(Nt.totalMilestones>0||Nt.totalFeatures>0)),pt=Ut?.totalTasks??0,Jt=Ut?.tasksCompleted??0,vs=Ut?.tasksFailed??0,hi=Ut?.estimatedCompletionPercent??Nt?.progressPercent??0,En=qe||pt>0||vs>0||!!Ut?.lastActivityAt,ln=ke.status==="active"&&(Ut?.currentMilestoneId||Ut?.currentSliceId)?"Current milestone/slice in progress":null;return t.jsxs("div",{className:`mission-list__item ${ht?"mission-list__item--selected":""}`,onClick:()=>_s(O),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ns,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:ke.title}),O.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(vn,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${Be}`,"data-testid":`mission-health-badge-${ke.id}`,"aria-label":`Mission health: ${Be}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Kt.bg,color:Kt.text},children:ke.status})]}),ke.description&&t.jsx("p",{className:"mission-list__item-description",children:ke.description}),ln&&t.jsxs("p",{className:"mission-list__item-active-slice",children:["Active: ",ln]}),En&&t.jsxs("div",{className:"mission-list__item-summary",children:[qe&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Nt.completedMilestones,"/",Nt.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Nt.completedFeatures,"/",Nt.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${ke.id}`,children:[Jt,"/",pt," tasks"]}),vs>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:At=>{At.stopPropagation(),_s(O)},"data-testid":`mission-failed-${ke.id}`,title:"View mission failures",children:[vs," failed"]}),t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${ke.id}`,children:["Activity ",Vr(Ut?.lastActivityAt)]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${Be}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${hi}%`}})})]})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:At=>At.stopPropagation(),children:[ke.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>So(ke.id),title:"Stop mission",children:t.jsx(ls,{size:14})}),ke.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>No(ke.id),title:"Resume mission",children:t.jsx(rn,{size:14})}),ke.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>xs(ke.id),title:"Start mission",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ft(O),title:"Edit mission",children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Z({type:"mission",id:ke.id}),title:"Delete mission",children:t.jsx(Ht,{size:14})})]})]},ke.id)}),j&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:S.title,onChange:O=>P({...S,title:O.target.value}),onKeyDown:Co,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:S.description,onChange:O=>P({...S,description:O.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:S.status,onChange:O=>P({...S,status:O.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:S.autopilotEnabled,onChange:O=>P({...S,autopilotEnabled:O.target.checked})}),t.jsx(vn,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:on,disabled:T,children:[T?t.jsx(it,{size:14,className:"spinner"}):t.jsx(xn,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:bt,children:"Cancel"})]})]}),g.length===0&&!y&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large",children:[t.jsx(ns,{size:32}),t.jsx("span",{children:"No missions yet. Create one to start planning."})]}),!y&&t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:"8px"},children:[ye.length>0&&t.jsxs("div",{className:"mission-resume-prompt",children:[t.jsx(ss,{size:16}),t.jsx("span",{children:ye.length===1?`Resume "${ye[0].title}"?`:`${ye.length} interview sessions pending`}),t.jsx("div",{style:{display:"flex",gap:"4px",marginLeft:"auto"},children:ye.map(O=>t.jsxs("button",{className:"mission-add-btn",onClick:()=>{J(O.id),Oe(!0),De([])},children:[O.status==="error"?t.jsx(hn,{size:14}):t.jsx(Dn,{size:14}),O.status==="error"?"Retry":"Resume"]},O.id))})]}),t.jsxs("div",{style:{display:"flex",gap:"8px"},children:[t.jsxs("button",{className:"mission-add-btn",onClick:()=>Oe(!0),children:[t.jsx(Dn,{size:16}),"Plan with AI"]}),t.jsxs("button",{className:"mission-add-btn",onClick:nt,children:[t.jsx(Vt,{size:16}),"New Mission"]})]})]})]})}),oe&&t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsxs("p",{children:["Delete this ",oe.type,"? This cannot be undone."]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--danger",onClick:async()=>{oe.type==="mission"?await Xt(oe.id):oe.type==="milestone"?await gs(oe.id):oe.type==="slice"?await Qn(oe.id):oe.type==="feature"&&await ua(oe.id)},children:"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Z(null),children:"Cancel"})]})]})}),Pe&&t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--link",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:"Link feature to task:"}),t.jsx("input",{type:"text",placeholder:"Task ID (e.g., FN-001)",value:Ke,onChange:O=>Ne(O.target.value),autoFocus:!0}),l.length>0&&t.jsxs("div",{className:"mission-task-suggestions",children:[t.jsx("small",{children:"Or select:"}),t.jsx("div",{className:"mission-task-suggestions__list",children:l.slice(0,5).map(O=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Ne(O.id),children:[O.id,": ",O.title||"Untitled"]},O.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:xo,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{We(null),Ne("")},children:"Cancel"})]})]})})]}),qc=t.jsx(Gw,{isOpen:_e,onClose:()=>Oe(!1),onMissionCreated:()=>{Qt(),i("Mission created from AI interview","success")},projectId:r,resumeSessionId:me}),Vc=ee?t.jsx(Yw,{isOpen:!0,onClose:()=>he(null),onApplied:()=>{he(null),f&&vt(f.id)},targetType:ee.type,targetId:ee.id,targetTitle:ee.title,missionContext:f?.title,projectId:r,resumeSessionId:ee.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[Hc,qc,Vc]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:O=>O.target===O.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:Hc}),qc,Vc]})}const xr=2e3;function ou({recipient:e,replyContext:n,agents:s=[],projectId:i,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[u,d]=a.useState(e?.id??""),[m,h]=a.useState(e?.type??"agent"),[g,p]=a.useState(""),[f,b]=a.useState(!1),[v,x]=a.useState(null),k=u.trim()!==""&&g.trim().length>0&&g.length<=xr,M=a.useCallback(async()=>{if(!(!k||f)){b(!0),x(null);try{const R=m==="agent"?"user-to-agent":"system";await Rk({toId:u.trim(),toType:m,content:g.trim(),type:R,...n?{metadata:{replyTo:{messageId:n.messageId}}}:{}},i),r()}catch(R){const j=xe(R)||"Failed to send message";x(j),l?.(j,"error")}finally{b(!1)}}},[k,f,u,m,g,n,i,r,l]),y=a.useCallback(R=>{d(R),h("agent")},[]);return t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(Pt,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:u,onChange:R=>y(R.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(R=>t.jsx("option",{value:R.id,children:R.name||R.id},R.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(an,{size:14}),e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",className:"message-composer-textarea",placeholder:"Type your message…",value:g,onChange:R=>p(R.target.value),maxLength:xr,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:g.length>xr?"over-limit":"",children:[g.length,"/",xr]})})]}),v&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(ss,{size:14}),t.jsx("span",{children:v})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:M,disabled:!k||f,"data-testid":"message-composer-send",children:f?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(vi,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}function zi(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 cN(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const i=s?.get(e)?.trim();return i?i===e?`Agent: ${e}`:`Agent: ${i} (${e})`:`Agent: ${e}`}return"System"}function dN(e){switch(e){case"agent-to-agent":return"Agent ↔ Agent";case"agent-to-user":return"Agent → You";case"user-to-agent":return"You → Agent";case"system":return"System"}}function lu(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function uN(e){const n=new Map;for(const s of e){const i=`${s.fromType}:${s.fromId}`,r=n.get(i);r?(r.messages.push(s),new Date(s.createdAt)>new Date(r.latestMessage.createdAt)&&(r.latestMessage=s),s.read||r.unreadCount++):n.set(i,{key:i,fromId:s.fromId,fromType:s.fromType,latestMessage:s,messages:[s],unreadCount:s.read?0:1})}return Array.from(n.values()).sort((s,i)=>new Date(i.latestMessage.createdAt).getTime()-new Date(s.latestMessage.createdAt).getTime())}function mN({projectId:e,addToast:n,onUnreadCountChange:s}){const[i,r]=a.useState("inbox"),[o,l]=a.useState(null),[c,u]=a.useState(null),[d,m]=a.useState(0),[h,g]=a.useState(!1),[p,f]=a.useState(null),[b,v]=a.useState([]),[x,k]=a.useState(!1),[M,y]=a.useState(null),[R,j]=a.useState(null),[C,S]=a.useState(null),[P,T]=a.useState("inbox"),[_,L]=a.useState(null),[G,$]=a.useState([]),I=a.useMemo(()=>new Map(G.map(te=>[te.id,te.name??""])),[G]),w=a.useCallback((te,we)=>cN(te,we,I),[I]),W=tr()==="mobile",B=!W,A=a.useCallback(async()=>{g(!0);try{const te=await Ak({limit:50},e);l(te),m(te.unreadCount),s?.(te.unreadCount)}catch{}finally{g(!1)}},[e,s]),z=a.useCallback(async()=>{g(!0);try{const te=await Tk({limit:50},e);u(te)}catch{}finally{g(!1)}},[e]),X=a.useCallback(async te=>{g(!0);try{const we=await Lk(te,e);L(we)}catch{}finally{g(!1)}},[e]),E=a.useCallback(async()=>{try{const te=await oa(void 0,e);$(te)}catch{}},[e]),U=a.useCallback(async()=>{try{const te=await Ch(e);m(te.unreadCount),s?.(te.unreadCount)}catch{}},[e,s]);a.useEffect(()=>{i==="inbox"?A():i==="outbox"?z():i==="agents"&&E()},[i,A,z,E]),a.useEffect(()=>{C&&X(C)},[C,X]),a.useEffect(()=>{U()},[U]),a.useEffect(()=>{E()},[E]),a.useEffect(()=>{if(typeof EventSource>"u")return;const te=e?`?projectId=${encodeURIComponent(e)}`:"",we=()=>{U(),i==="inbox"?A():i==="outbox"&&z(),C&&X(C)};return qs(`/api/events${te}`,{events:{"message:sent":we,"message:received":we,"message:read":we,"message:deleted":we}})},[e,i,C,U,A,z,X]);const pe=a.useCallback(async te=>{if(f(te),!te.read)try{const we=await Ik(te.id,e);we&&l(We=>We&&{...We,messages:We.messages.map(Ke=>Ke.id===we.id?we:Ke),unreadCount:Math.max(0,We.unreadCount-1)});const Pe=Math.max(0,d-1);m(Pe),s?.(Pe)}catch{}try{const we=await Dk(te.fromId,te.fromType,e);v(we)}catch{v([te])}},[e,d,s]),ie=a.useCallback(()=>{f(null),v([])},[]),re=a.useCallback(async()=>{try{const te=await Pk(e);m(0),s?.(0),l(we=>we&&{...we,messages:we.messages.map(Pe=>({...Pe,read:!0})),unreadCount:0}),n?.(`Marked ${te.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),F=a.useCallback(async te=>{try{await $k(te,e),f(null),v([]),i==="inbox"?A():i==="outbox"?z():C&&X(C),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,i,C,A,z,X,n]),ce=a.useCallback(te=>{y({id:te.fromId,type:te.fromType}),j({messageId:te.id,preview:lu(te.content,120)}),k(!0)},[]),ae=a.useCallback(()=>{k(!1),y(null),j(null),n?.("Message sent","success"),i==="outbox"?z():i==="agents"&&C&&X(C),U()},[i,z,C,X,n,U]),Q=a.useCallback(()=>{y(i==="agents"&&C?{id:C,type:"agent"}:null),j(null),k(!0)},[i,C]),de=a.useCallback(()=>{k(!1),y(null),j(null)},[]),Te=()=>!p||x?null:t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[W&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:ie,"data-testid":"mailbox-back-to-list",children:"← Back"}),t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:dN(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:zi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ce(p),"data-testid":"mailbox-reply",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>F(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Ht,{size:14}),t.jsx("span",{children:"Delete"})]})]})]}),t.jsxs("div",{className:"mailbox-message-participants",children:[t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"From:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.fromType==="agent"?t.jsx(an,{size:14}):t.jsx(Pi,{size:14}),w(p.fromId,p.fromType)]})]}),t.jsxs("div",{className:"mailbox-participant",children:[t.jsx("span",{className:"mailbox-participant-label",children:"To:"}),t.jsxs("span",{className:"mailbox-participant-value",children:[p.toType==="agent"?t.jsx(an,{size:14}):t.jsx(Pi,{size:14}),w(p.toId,p.toType)]})]})]}),b.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),b.map(te=>{const we=te.metadata?.replyTo?.messageId,Pe=we?b.find(We=>We.id===we):void 0;return t.jsxs("div",{className:`mailbox-conversation-msg ${te.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:zi(te.createdAt)})]}),we&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":`mailbox-reply-context-${te.id}`,children:["↪ Replying to ",Pe?lu(Pe.content,60):`message ${we}`]}),t.jsx("div",{className:"mailbox-conversation-msg-body",children:te.content})]},te.id)})]}),b.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx("div",{className:"mailbox-message-body","data-testid":"mailbox-message-body",children:p.content})]})]}),fe=()=>t.jsxs(t.Fragment,{children:[i==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(qo,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(Ra,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o&&o.messages.length>0&&t.jsx("div",{className:"mailbox-conversations","data-testid":"mailbox-conversations",children:uN(o.messages).map(te=>t.jsxs("div",{className:`mailbox-conversation-group ${te.unreadCount>0?"unread":""}`,onClick:()=>pe(te.latestMessage),"data-testid":`mailbox-conversation-${te.key}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.fromType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:zi(te.latestMessage.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.latestMessage.content.slice(0,80),te.latestMessage.content.length>80?"…":""]})]}),te.unreadCount>0&&t.jsx("div",{className:"mailbox-group-unread-badge","data-testid":`mailbox-unread-badge-${te.key}`,children:te.unreadCount>9?"9+":te.unreadCount})]},te.key))})]}),i==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(qo,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(vi,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(te=>t.jsxs("div",{className:"mailbox-item",onClick:()=>pe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.toType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",w(te.toId,te.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:zi(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id))]}),i==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:G.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(an,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:C??"",onChange:te=>{S(te.target.value||null),T("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:"",children:"Select an agent…"}),G.map(te=>t.jsx("option",{value:te.id,children:te.name||te.id},te.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:Q,"data-testid":"mailbox-compose-btn",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Compose"})]})]}),C&&t.jsxs("div",{className:"mailbox-agent-subtabs","data-testid":"mailbox-agent-subtabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${P==="inbox"?"active":""}`,onClick:()=>T("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(Ra,{size:12}),t.jsx("span",{children:"Inbox"}),_&&_.unreadCount>0&&t.jsx("span",{className:"mailbox-tab-badge",children:_.unreadCount})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${P==="outbox"?"active":""}`,onClick:()=>T("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(vi,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[!C&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(an,{size:32}),t.jsx("p",{children:"Select an agent to view their mailbox"})]}),C&&h&&!_&&t.jsx(qo,{}),C&&_&&P==="inbox"&&_.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Ra,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),C&&_&&P==="outbox"&&_.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(vi,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),C&&_&&P==="inbox"&&_.inbox.map(te=>t.jsxs("div",{className:`mailbox-item ${te.read?"":"unread"}`,onClick:()=>pe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.fromType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsx("span",{className:"mailbox-item-from",children:w(te.fromId,te.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:zi(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id)),C&&_&&P==="outbox"&&_.outbox.map(te=>t.jsxs("div",{className:"mailbox-item",onClick:()=>pe(te),"data-testid":`mailbox-item-${te.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:te.toType==="agent"?t.jsx(an,{size:16}):t.jsx(Pi,{size:16})}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-to",children:["To: ",w(te.toId,te.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:zi(te.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[te.content.slice(0,80),te.content.length>80?"…":""]})]})]},te.id))]})]})})]}),Se=()=>x?t.jsx(ou,{recipient:M,replyContext:R,agents:G,projectId:e,onSend:ae,onCancel:de,addToast:n}):p?Te():t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(Gi,{size:24}),t.jsx("p",{children:"Select a conversation to read messages"})]});return t.jsxs("div",{className:"mailbox-view","data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(Gi,{size:18}),t.jsx("span",{children:"Mailbox"}),d>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:d})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:Q,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(li,{size:14}),t.jsx("span",{children:"Compose"})]}),i==="inbox"&&d>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:re,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Wf,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{i==="inbox"?A():i==="outbox"?z():C&&X(C)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="inbox"?"active":""}`,onClick:()=>{r("inbox"),f(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(Ra,{size:14}),t.jsx("span",{children:"Inbox"}),d>0&&t.jsx("span",{className:"mailbox-tab-badge",children:d})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="outbox"?"active":""}`,onClick:()=>{r("outbox"),f(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(vi,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${i==="agents"?"active":""}`,onClick:()=>{r("agents"),f(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(an,{size:14}),t.jsx("span",{children:"Agents"})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:B?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",children:fe()}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Se()})]}):t.jsxs(t.Fragment,{children:[Te(),x&&t.jsx(ou,{recipient:M,replyContext:R,agents:G,projectId:e,onSend:ae,onCancel:de,addToast:n}),!p&&!x&&fe()]})})]})}function qo(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}function hN(e,n){const s={};return(e[e.length-1]===""?[...e,""]:e).join((s.padRight?" ":"")+","+(s.padLeft===!1?"":" ")).trim()}const pN=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,fN=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,gN={};function cu(e,n){return(gN.jsx?fN:pN).test(e)}const bN=/[ \t\n\f\r]/g;function xN(e){return typeof e=="object"?e.type==="text"?du(e.value):!1:du(e)}function du(e){return e.replace(bN,"")===""}class nr{constructor(n,s,i){this.normal=s,this.property=n,i&&(this.space=i)}}nr.prototype.normal={};nr.prototype.property={};nr.prototype.space=void 0;function Vh(e,n){const s={},i={};for(const r of e)Object.assign(s,r.property),Object.assign(i,r.normal);return new nr(s,i,n)}function Hl(e){return e.toLowerCase()}class as{constructor(n,s){this.attribute=s,this.property=n}}as.prototype.attribute="";as.prototype.booleanish=!1;as.prototype.boolean=!1;as.prototype.commaOrSpaceSeparated=!1;as.prototype.commaSeparated=!1;as.prototype.defined=!1;as.prototype.mustUseProperty=!1;as.prototype.number=!1;as.prototype.overloadedBoolean=!1;as.prototype.property="";as.prototype.spaceSeparated=!1;as.prototype.space=void 0;let vN=0;const St=Ai(),mn=Ai(),ql=Ai(),Xe=Ai(),Yt=Ai(),qi=Ai(),os=Ai();function Ai(){return 2**++vN}const Vl=Object.freeze(Object.defineProperty({__proto__:null,boolean:St,booleanish:mn,commaOrSpaceSeparated:os,commaSeparated:qi,number:Xe,overloadedBoolean:ql,spaceSeparated:Yt},Symbol.toStringTag,{value:"Module"})),Vo=Object.keys(Vl);class vc extends as{constructor(n,s,i,r){let o=-1;if(super(n,s),uu(this,"space",r),typeof i=="number")for(;++o<Vo.length;){const l=Vo[o];uu(this,Vo[o],(i&Vl[l])===Vl[l])}}}vc.prototype.defined=!0;function uu(e,n,s){s&&(e[n]=s)}function ca(e){const n={},s={};for(const[i,r]of Object.entries(e.properties)){const o=new vc(i,e.transform(e.attributes||{},i),r,e.space);e.mustUseProperty&&e.mustUseProperty.includes(i)&&(o.mustUseProperty=!0),n[i]=o,s[Hl(i)]=i,s[Hl(o.attribute)]=i}return new nr(n,s,e.space)}const Wh=ca({properties:{ariaActiveDescendant:null,ariaAtomic:mn,ariaAutoComplete:null,ariaBusy:mn,ariaChecked:mn,ariaColCount:Xe,ariaColIndex:Xe,ariaColSpan:Xe,ariaControls:Yt,ariaCurrent:null,ariaDescribedBy:Yt,ariaDetails:null,ariaDisabled:mn,ariaDropEffect:Yt,ariaErrorMessage:null,ariaExpanded:mn,ariaFlowTo:Yt,ariaGrabbed:mn,ariaHasPopup:null,ariaHidden:mn,ariaInvalid:null,ariaKeyShortcuts:null,ariaLabel:null,ariaLabelledBy:Yt,ariaLevel:Xe,ariaLive:null,ariaModal:mn,ariaMultiLine:mn,ariaMultiSelectable:mn,ariaOrientation:null,ariaOwns:Yt,ariaPlaceholder:null,ariaPosInSet:Xe,ariaPressed:mn,ariaReadOnly:mn,ariaRelevant:null,ariaRequired:mn,ariaRoleDescription:Yt,ariaRowCount:Xe,ariaRowIndex:Xe,ariaRowSpan:Xe,ariaSelected:mn,ariaSetSize:Xe,ariaSort:null,ariaValueMax:Xe,ariaValueMin:Xe,ariaValueNow:Xe,ariaValueText:null,role:null},transform(e,n){return n==="role"?n:"aria-"+n.slice(4).toLowerCase()}});function Gh(e,n){return n in e?e[n]:n}function Kh(e,n){return Gh(e,n.toLowerCase())}const yN=ca({attributes:{acceptcharset:"accept-charset",classname:"class",htmlfor:"for",httpequiv:"http-equiv"},mustUseProperty:["checked","multiple","muted","selected"],properties:{abbr:null,accept:qi,acceptCharset:Yt,accessKey:Yt,action:null,allow:null,allowFullScreen:St,allowPaymentRequest:St,allowUserMedia:St,alt:null,as:null,async:St,autoCapitalize:null,autoComplete:Yt,autoFocus:St,autoPlay:St,blocking:Yt,capture:null,charSet:null,checked:St,cite:null,className:Yt,cols:Xe,colSpan:null,content:null,contentEditable:mn,controls:St,controlsList:Yt,coords:Xe|qi,crossOrigin:null,data:null,dateTime:null,decoding:null,default:St,defer:St,dir:null,dirName:null,disabled:St,download:ql,draggable:mn,encType:null,enterKeyHint:null,fetchPriority:null,form:null,formAction:null,formEncType:null,formMethod:null,formNoValidate:St,formTarget:null,headers:Yt,height:Xe,hidden:ql,high:Xe,href:null,hrefLang:null,htmlFor:Yt,httpEquiv:Yt,id:null,imageSizes:null,imageSrcSet:null,inert:St,inputMode:null,integrity:null,is:null,isMap:St,itemId:null,itemProp:Yt,itemRef:Yt,itemScope:St,itemType:Yt,kind:null,label:null,lang:null,language:null,list:null,loading:null,loop:St,low:Xe,manifest:null,max:null,maxLength:Xe,media:null,method:null,min:null,minLength:Xe,multiple:St,muted:St,name:null,nonce:null,noModule:St,noValidate:St,onAbort:null,onAfterPrint:null,onAuxClick:null,onBeforeMatch:null,onBeforePrint:null,onBeforeToggle:null,onBeforeUnload:null,onBlur:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onContextLost:null,onContextMenu:null,onContextRestored:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnded:null,onError:null,onFocus:null,onFormData:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLanguageChange:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadEnd:null,onLoadStart:null,onMessage:null,onMessageError:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRejectionHandled:null,onReset:null,onResize:null,onScroll:null,onScrollEnd:null,onSecurityPolicyViolation:null,onSeeked:null,onSeeking:null,onSelect:null,onSlotChange:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnhandledRejection:null,onUnload:null,onVolumeChange:null,onWaiting:null,onWheel:null,open:St,optimum:Xe,pattern:null,ping:Yt,placeholder:null,playsInline:St,popover:null,popoverTarget:null,popoverTargetAction:null,poster:null,preload:null,readOnly:St,referrerPolicy:null,rel:Yt,required:St,reversed:St,rows:Xe,rowSpan:Xe,sandbox:Yt,scope:null,scoped:St,seamless:St,selected:St,shadowRootClonable:St,shadowRootDelegatesFocus:St,shadowRootMode:null,shape:null,size:Xe,sizes:null,slot:null,span:Xe,spellCheck:mn,src:null,srcDoc:null,srcLang:null,srcSet:null,start:Xe,step:null,style:null,tabIndex:Xe,target:null,title:null,translate:null,type:null,typeMustMatch:St,useMap:null,value:mn,width:Xe,wrap:null,writingSuggestions:null,align:null,aLink:null,archive:Yt,axis:null,background:null,bgColor:null,border:Xe,borderColor:null,bottomMargin:Xe,cellPadding:null,cellSpacing:null,char:null,charOff:null,classId:null,clear:null,code:null,codeBase:null,codeType:null,color:null,compact:St,declare:St,event:null,face:null,frame:null,frameBorder:null,hSpace:Xe,leftMargin:Xe,link:null,longDesc:null,lowSrc:null,marginHeight:Xe,marginWidth:Xe,noResize:St,noHref:St,noShade:St,noWrap:St,object:null,profile:null,prompt:null,rev:null,rightMargin:Xe,rules:null,scheme:null,scrolling:mn,standby:null,summary:null,text:null,topMargin:Xe,valueType:null,version:null,vAlign:null,vLink:null,vSpace:Xe,allowTransparency:null,autoCorrect:null,autoSave:null,disablePictureInPicture:St,disableRemotePlayback:St,prefix:null,property:null,results:Xe,security:null,unselectable:null},space:"html",transform:Kh}),kN=ca({attributes:{accentHeight:"accent-height",alignmentBaseline:"alignment-baseline",arabicForm:"arabic-form",baselineShift:"baseline-shift",capHeight:"cap-height",className:"class",clipPath:"clip-path",clipRule:"clip-rule",colorInterpolation:"color-interpolation",colorInterpolationFilters:"color-interpolation-filters",colorProfile:"color-profile",colorRendering:"color-rendering",crossOrigin:"crossorigin",dataType:"datatype",dominantBaseline:"dominant-baseline",enableBackground:"enable-background",fillOpacity:"fill-opacity",fillRule:"fill-rule",floodColor:"flood-color",floodOpacity:"flood-opacity",fontFamily:"font-family",fontSize:"font-size",fontSizeAdjust:"font-size-adjust",fontStretch:"font-stretch",fontStyle:"font-style",fontVariant:"font-variant",fontWeight:"font-weight",glyphName:"glyph-name",glyphOrientationHorizontal:"glyph-orientation-horizontal",glyphOrientationVertical:"glyph-orientation-vertical",hrefLang:"hreflang",horizAdvX:"horiz-adv-x",horizOriginX:"horiz-origin-x",horizOriginY:"horiz-origin-y",imageRendering:"image-rendering",letterSpacing:"letter-spacing",lightingColor:"lighting-color",markerEnd:"marker-end",markerMid:"marker-mid",markerStart:"marker-start",navDown:"nav-down",navDownLeft:"nav-down-left",navDownRight:"nav-down-right",navLeft:"nav-left",navNext:"nav-next",navPrev:"nav-prev",navRight:"nav-right",navUp:"nav-up",navUpLeft:"nav-up-left",navUpRight:"nav-up-right",onAbort:"onabort",onActivate:"onactivate",onAfterPrint:"onafterprint",onBeforePrint:"onbeforeprint",onBegin:"onbegin",onCancel:"oncancel",onCanPlay:"oncanplay",onCanPlayThrough:"oncanplaythrough",onChange:"onchange",onClick:"onclick",onClose:"onclose",onCopy:"oncopy",onCueChange:"oncuechange",onCut:"oncut",onDblClick:"ondblclick",onDrag:"ondrag",onDragEnd:"ondragend",onDragEnter:"ondragenter",onDragExit:"ondragexit",onDragLeave:"ondragleave",onDragOver:"ondragover",onDragStart:"ondragstart",onDrop:"ondrop",onDurationChange:"ondurationchange",onEmptied:"onemptied",onEnd:"onend",onEnded:"onended",onError:"onerror",onFocus:"onfocus",onFocusIn:"onfocusin",onFocusOut:"onfocusout",onHashChange:"onhashchange",onInput:"oninput",onInvalid:"oninvalid",onKeyDown:"onkeydown",onKeyPress:"onkeypress",onKeyUp:"onkeyup",onLoad:"onload",onLoadedData:"onloadeddata",onLoadedMetadata:"onloadedmetadata",onLoadStart:"onloadstart",onMessage:"onmessage",onMouseDown:"onmousedown",onMouseEnter:"onmouseenter",onMouseLeave:"onmouseleave",onMouseMove:"onmousemove",onMouseOut:"onmouseout",onMouseOver:"onmouseover",onMouseUp:"onmouseup",onMouseWheel:"onmousewheel",onOffline:"onoffline",onOnline:"ononline",onPageHide:"onpagehide",onPageShow:"onpageshow",onPaste:"onpaste",onPause:"onpause",onPlay:"onplay",onPlaying:"onplaying",onPopState:"onpopstate",onProgress:"onprogress",onRateChange:"onratechange",onRepeat:"onrepeat",onReset:"onreset",onResize:"onresize",onScroll:"onscroll",onSeeked:"onseeked",onSeeking:"onseeking",onSelect:"onselect",onShow:"onshow",onStalled:"onstalled",onStorage:"onstorage",onSubmit:"onsubmit",onSuspend:"onsuspend",onTimeUpdate:"ontimeupdate",onToggle:"ontoggle",onUnload:"onunload",onVolumeChange:"onvolumechange",onWaiting:"onwaiting",onZoom:"onzoom",overlinePosition:"overline-position",overlineThickness:"overline-thickness",paintOrder:"paint-order",panose1:"panose-1",pointerEvents:"pointer-events",referrerPolicy:"referrerpolicy",renderingIntent:"rendering-intent",shapeRendering:"shape-rendering",stopColor:"stop-color",stopOpacity:"stop-opacity",strikethroughPosition:"strikethrough-position",strikethroughThickness:"strikethrough-thickness",strokeDashArray:"stroke-dasharray",strokeDashOffset:"stroke-dashoffset",strokeLineCap:"stroke-linecap",strokeLineJoin:"stroke-linejoin",strokeMiterLimit:"stroke-miterlimit",strokeOpacity:"stroke-opacity",strokeWidth:"stroke-width",tabIndex:"tabindex",textAnchor:"text-anchor",textDecoration:"text-decoration",textRendering:"text-rendering",transformOrigin:"transform-origin",typeOf:"typeof",underlinePosition:"underline-position",underlineThickness:"underline-thickness",unicodeBidi:"unicode-bidi",unicodeRange:"unicode-range",unitsPerEm:"units-per-em",vAlphabetic:"v-alphabetic",vHanging:"v-hanging",vIdeographic:"v-ideographic",vMathematical:"v-mathematical",vectorEffect:"vector-effect",vertAdvY:"vert-adv-y",vertOriginX:"vert-origin-x",vertOriginY:"vert-origin-y",wordSpacing:"word-spacing",writingMode:"writing-mode",xHeight:"x-height",playbackOrder:"playbackorder",timelineBegin:"timelinebegin"},properties:{about:os,accentHeight:Xe,accumulate:null,additive:null,alignmentBaseline:null,alphabetic:Xe,amplitude:Xe,arabicForm:null,ascent:Xe,attributeName:null,attributeType:null,azimuth:Xe,bandwidth:null,baselineShift:null,baseFrequency:null,baseProfile:null,bbox:null,begin:null,bias:Xe,by:null,calcMode:null,capHeight:Xe,className:Yt,clip:null,clipPath:null,clipPathUnits:null,clipRule:null,color:null,colorInterpolation:null,colorInterpolationFilters:null,colorProfile:null,colorRendering:null,content:null,contentScriptType:null,contentStyleType:null,crossOrigin:null,cursor:null,cx:null,cy:null,d:null,dataType:null,defaultAction:null,descent:Xe,diffuseConstant:Xe,direction:null,display:null,dur:null,divisor:Xe,dominantBaseline:null,download:St,dx:null,dy:null,edgeMode:null,editable:null,elevation:Xe,enableBackground:null,end:null,event:null,exponent:Xe,externalResourcesRequired:null,fill:null,fillOpacity:Xe,fillRule:null,filter:null,filterRes:null,filterUnits:null,floodColor:null,floodOpacity:null,focusable:null,focusHighlight:null,fontFamily:null,fontSize:null,fontSizeAdjust:null,fontStretch:null,fontStyle:null,fontVariant:null,fontWeight:null,format:null,fr:null,from:null,fx:null,fy:null,g1:qi,g2:qi,glyphName:qi,glyphOrientationHorizontal:null,glyphOrientationVertical:null,glyphRef:null,gradientTransform:null,gradientUnits:null,handler:null,hanging:Xe,hatchContentUnits:null,hatchUnits:null,height:null,href:null,hrefLang:null,horizAdvX:Xe,horizOriginX:Xe,horizOriginY:Xe,id:null,ideographic:Xe,imageRendering:null,initialVisibility:null,in:null,in2:null,intercept:Xe,k:Xe,k1:Xe,k2:Xe,k3:Xe,k4:Xe,kernelMatrix:os,kernelUnitLength:null,keyPoints:null,keySplines:null,keyTimes:null,kerning:null,lang:null,lengthAdjust:null,letterSpacing:null,lightingColor:null,limitingConeAngle:Xe,local:null,markerEnd:null,markerMid:null,markerStart:null,markerHeight:null,markerUnits:null,markerWidth:null,mask:null,maskContentUnits:null,maskUnits:null,mathematical:null,max:null,media:null,mediaCharacterEncoding:null,mediaContentEncodings:null,mediaSize:Xe,mediaTime:null,method:null,min:null,mode:null,name:null,navDown:null,navDownLeft:null,navDownRight:null,navLeft:null,navNext:null,navPrev:null,navRight:null,navUp:null,navUpLeft:null,navUpRight:null,numOctaves:null,observer:null,offset:null,onAbort:null,onActivate:null,onAfterPrint:null,onBeforePrint:null,onBegin:null,onCancel:null,onCanPlay:null,onCanPlayThrough:null,onChange:null,onClick:null,onClose:null,onCopy:null,onCueChange:null,onCut:null,onDblClick:null,onDrag:null,onDragEnd:null,onDragEnter:null,onDragExit:null,onDragLeave:null,onDragOver:null,onDragStart:null,onDrop:null,onDurationChange:null,onEmptied:null,onEnd:null,onEnded:null,onError:null,onFocus:null,onFocusIn:null,onFocusOut:null,onHashChange:null,onInput:null,onInvalid:null,onKeyDown:null,onKeyPress:null,onKeyUp:null,onLoad:null,onLoadedData:null,onLoadedMetadata:null,onLoadStart:null,onMessage:null,onMouseDown:null,onMouseEnter:null,onMouseLeave:null,onMouseMove:null,onMouseOut:null,onMouseOver:null,onMouseUp:null,onMouseWheel:null,onOffline:null,onOnline:null,onPageHide:null,onPageShow:null,onPaste:null,onPause:null,onPlay:null,onPlaying:null,onPopState:null,onProgress:null,onRateChange:null,onRepeat:null,onReset:null,onResize:null,onScroll:null,onSeeked:null,onSeeking:null,onSelect:null,onShow:null,onStalled:null,onStorage:null,onSubmit:null,onSuspend:null,onTimeUpdate:null,onToggle:null,onUnload:null,onVolumeChange:null,onWaiting:null,onZoom:null,opacity:null,operator:null,order:null,orient:null,orientation:null,origin:null,overflow:null,overlay:null,overlinePosition:Xe,overlineThickness:Xe,paintOrder:null,panose1:null,path:null,pathLength:Xe,patternContentUnits:null,patternTransform:null,patternUnits:null,phase:null,ping:Yt,pitch:null,playbackOrder:null,pointerEvents:null,points:null,pointsAtX:Xe,pointsAtY:Xe,pointsAtZ:Xe,preserveAlpha:null,preserveAspectRatio:null,primitiveUnits:null,propagate:null,property:os,r:null,radius:null,referrerPolicy:null,refX:null,refY:null,rel:os,rev:os,renderingIntent:null,repeatCount:null,repeatDur:null,requiredExtensions:os,requiredFeatures:os,requiredFonts:os,requiredFormats:os,resource:null,restart:null,result:null,rotate:null,rx:null,ry:null,scale:null,seed:null,shapeRendering:null,side:null,slope:null,snapshotTime:null,specularConstant:Xe,specularExponent:Xe,spreadMethod:null,spacing:null,startOffset:null,stdDeviation:null,stemh:null,stemv:null,stitchTiles:null,stopColor:null,stopOpacity:null,strikethroughPosition:Xe,strikethroughThickness:Xe,string:null,stroke:null,strokeDashArray:os,strokeDashOffset:null,strokeLineCap:null,strokeLineJoin:null,strokeMiterLimit:Xe,strokeOpacity:Xe,strokeWidth:null,style:null,surfaceScale:Xe,syncBehavior:null,syncBehaviorDefault:null,syncMaster:null,syncTolerance:null,syncToleranceDefault:null,systemLanguage:os,tabIndex:Xe,tableValues:null,target:null,targetX:Xe,targetY:Xe,textAnchor:null,textDecoration:null,textRendering:null,textLength:null,timelineBegin:null,title:null,transformBehavior:null,type:null,typeOf:os,to:null,transform:null,transformOrigin:null,u1:null,u2:null,underlinePosition:Xe,underlineThickness:Xe,unicode:null,unicodeBidi:null,unicodeRange:null,unitsPerEm:Xe,values:null,vAlphabetic:Xe,vMathematical:Xe,vectorEffect:null,vHanging:Xe,vIdeographic:Xe,version:null,vertAdvY:Xe,vertOriginX:Xe,vertOriginY:Xe,viewBox:null,viewTarget:null,visibility:null,width:null,widths:null,wordSpacing:null,writingMode:null,x:null,x1:null,x2:null,xChannelSelector:null,xHeight:Xe,y:null,y1:null,y2:null,yChannelSelector:null,z:null,zoomAndPan:null},space:"svg",transform:Gh}),Jh=ca({properties:{xLinkActuate:null,xLinkArcRole:null,xLinkHref:null,xLinkRole:null,xLinkShow:null,xLinkTitle:null,xLinkType:null},space:"xlink",transform(e,n){return"xlink:"+n.slice(5).toLowerCase()}}),Yh=ca({attributes:{xmlnsxlink:"xmlns:xlink"},properties:{xmlnsXLink:null,xmlns:null},space:"xmlns",transform:Kh}),Qh=ca({properties:{xmlBase:null,xmlLang:null,xmlSpace:null},space:"xml",transform(e,n){return"xml:"+n.slice(3).toLowerCase()}}),jN={classId:"classID",dataType:"datatype",itemId:"itemID",strokeDashArray:"strokeDasharray",strokeDashOffset:"strokeDashoffset",strokeLineCap:"strokeLinecap",strokeLineJoin:"strokeLinejoin",strokeMiterLimit:"strokeMiterlimit",typeOf:"typeof",xLinkActuate:"xlinkActuate",xLinkArcRole:"xlinkArcrole",xLinkHref:"xlinkHref",xLinkRole:"xlinkRole",xLinkShow:"xlinkShow",xLinkTitle:"xlinkTitle",xLinkType:"xlinkType",xmlnsXLink:"xmlnsXlink"},wN=/[A-Z]/g,mu=/-[a-z]/g,NN=/^data[-\w.:]+$/i;function SN(e,n){const s=Hl(n);let i=n,r=as;if(s in e.normal)return e.property[e.normal[s]];if(s.length>4&&s.slice(0,4)==="data"&&NN.test(n)){if(n.charAt(4)==="-"){const o=n.slice(5).replace(mu,EN);i="data"+o.charAt(0).toUpperCase()+o.slice(1)}else{const o=n.slice(4);if(!mu.test(o)){let l=o.replace(wN,CN);l.charAt(0)!=="-"&&(l="-"+l),n="data"+l}}r=vc}return new r(i,n)}function CN(e){return"-"+e.toLowerCase()}function EN(e){return e.charAt(1).toUpperCase()}const MN=Vh([Wh,yN,Jh,Yh,Qh],"html"),yc=Vh([Wh,kN,Jh,Yh,Qh],"svg");function _N(e){return e.join(" ").trim()}var Fi={},Wo,hu;function AN(){if(hu)return Wo;hu=1;var e=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,n=/\n/g,s=/^\s*/,i=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,r=/^:\s*/,o=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,l=/^[;\s]*/,c=/^\s+|\s+$/g,u=`
|
|
578
578
|
`,d="/",m="*",h="",g="comment",p="declaration";function f(v,x){if(typeof v!="string")throw new TypeError("First argument must be a string");if(!v)return[];x=x||{};var k=1,M=1;function y($){var I=$.match(n);I&&(k+=I.length);var w=$.lastIndexOf(u);M=~w?$.length-w:M+$.length}function R(){var $={line:k,column:M};return function(I){return I.position=new j($),P(),I}}function j($){this.start=$,this.end={line:k,column:M},this.source=x.source}j.prototype.content=v;function C($){var I=new Error(x.source+":"+k+":"+M+": "+$);if(I.reason=$,I.filename=x.source,I.line=k,I.column=M,I.source=v,!x.silent)throw I}function S($){var I=$.exec(v);if(I){var w=I[0];return y(w),v=v.slice(w.length),I}}function P(){S(s)}function T($){var I;for($=$||[];I=_();)I!==!1&&$.push(I);return $}function _(){var $=R();if(!(d!=v.charAt(0)||m!=v.charAt(1))){for(var I=2;h!=v.charAt(I)&&(m!=v.charAt(I)||d!=v.charAt(I+1));)++I;if(I+=2,h===v.charAt(I-1))return C("End of comment missing");var w=v.slice(2,I-2);return M+=2,y(w),v=v.slice(I),M+=2,$({type:g,comment:w})}}function L(){var $=R(),I=S(i);if(I){if(_(),!S(r))return C("property missing ':'");var w=S(o),q=$({type:p,property:b(I[0].replace(e,h)),value:w?b(w[0].replace(e,h)):h});return S(l),q}}function G(){var $=[];T($);for(var I;I=L();)I!==!1&&($.push(I),T($));return $}return P(),G()}function b(v){return v?v.replace(c,h):h}return Wo=f,Wo}var pu;function TN(){if(pu)return Fi;pu=1;var e=Fi&&Fi.__importDefault||function(i){return i&&i.__esModule?i:{default:i}};Object.defineProperty(Fi,"__esModule",{value:!0}),Fi.default=s;const n=e(AN());function s(i,r){let o=null;if(!i||typeof i!="string")return o;const l=(0,n.default)(i),c=typeof r=="function";return l.forEach(u=>{if(u.type!=="declaration")return;const{property:d,value:m}=u;c?r(d,m,u):m&&(o=o||{},o[d]=m)}),o}return Fi}var xa={},fu;function RN(){if(fu)return xa;fu=1,Object.defineProperty(xa,"__esModule",{value:!0}),xa.camelCase=void 0;var e=/^--[a-zA-Z0-9_-]+$/,n=/-([a-z])/g,s=/^[^-]+$/,i=/^-(webkit|moz|ms|o|khtml)-/,r=/^-(ms)-/,o=function(d){return!d||s.test(d)||e.test(d)},l=function(d,m){return m.toUpperCase()},c=function(d,m){return"".concat(m,"-")},u=function(d,m){return m===void 0&&(m={}),o(d)?d:(d=d.toLowerCase(),m.reactCompat?d=d.replace(r,c):d=d.replace(i,c),d.replace(n,l))};return xa.camelCase=u,xa}var va,gu;function IN(){if(gu)return va;gu=1;var e=va&&va.__importDefault||function(r){return r&&r.__esModule?r:{default:r}},n=e(TN()),s=RN();function i(r,o){var l={};return!r||typeof r!="string"||(0,n.default)(r,function(c,u){c&&u&&(l[(0,s.camelCase)(c,o)]=u)}),l}return i.default=i,va=i,va}var PN=IN();const $N=Km(PN),Xh=Zh("end"),kc=Zh("start");function Zh(e){return n;function n(s){const i=s&&s.position&&s.position[e]||{};if(typeof i.line=="number"&&i.line>0&&typeof i.column=="number"&&i.column>0)return{line:i.line,column:i.column,offset:typeof i.offset=="number"&&i.offset>-1?i.offset:void 0}}}function DN(e){const n=kc(e),s=Xh(e);if(n&&s)return{start:n,end:s}}function $a(e){return!e||typeof e!="object"?"":"position"in e||"type"in e?bu(e.position):"start"in e||"end"in e?bu(e):"line"in e||"column"in e?Wl(e):""}function Wl(e){return xu(e&&e.line)+":"+xu(e&&e.column)}function bu(e){return Wl(e&&e.start)+"-"+Wl(e&&e.end)}function xu(e){return e&&typeof e=="number"?e:1}class Ln extends Error{constructor(n,s,i){super(),typeof s=="string"&&(i=s,s=void 0);let r="",o={},l=!1;if(s&&("line"in s&&"column"in s?o={place:s}:"start"in s&&"end"in s?o={place:s}:"type"in s?o={ancestors:[s],place:s.position}:o={...s}),typeof n=="string"?r=n:!o.cause&&n&&(l=!0,r=n.message,o.cause=n),!o.ruleId&&!o.source&&typeof i=="string"){const u=i.indexOf(":");u===-1?o.ruleId=i:(o.source=i.slice(0,u),o.ruleId=i.slice(u+1))}if(!o.place&&o.ancestors&&o.ancestors){const u=o.ancestors[o.ancestors.length-1];u&&(o.place=u.position)}const c=o.place&&"start"in o.place?o.place.start:o.place;this.ancestors=o.ancestors||void 0,this.cause=o.cause||void 0,this.column=c?c.column:void 0,this.fatal=void 0,this.file="",this.message=r,this.line=c?c.line:void 0,this.name=$a(o.place)||"1:1",this.place=o.place||void 0,this.reason=this.message,this.ruleId=o.ruleId||void 0,this.source=o.source||void 0,this.stack=l&&o.cause&&typeof o.cause.stack=="string"?o.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}Ln.prototype.file="";Ln.prototype.name="";Ln.prototype.reason="";Ln.prototype.message="";Ln.prototype.stack="";Ln.prototype.column=void 0;Ln.prototype.line=void 0;Ln.prototype.ancestors=void 0;Ln.prototype.cause=void 0;Ln.prototype.fatal=void 0;Ln.prototype.place=void 0;Ln.prototype.ruleId=void 0;Ln.prototype.source=void 0;const jc={}.hasOwnProperty,LN=new Map,zN=/[A-Z]/g,FN=new Set(["table","tbody","thead","tfoot","tr"]),ON=new Set(["td","th"]),ep="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function UN(e,n){if(!n||n.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const s=n.filePath||void 0;let i;if(n.development){if(typeof n.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");i=JN(s,n.jsxDEV)}else{if(typeof n.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof n.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");i=KN(s,n.jsx,n.jsxs)}const r={Fragment:n.Fragment,ancestors:[],components:n.components||{},create:i,elementAttributeNameCase:n.elementAttributeNameCase||"react",evaluater:n.createEvaluater?n.createEvaluater():void 0,filePath:s,ignoreInvalidStyle:n.ignoreInvalidStyle||!1,passKeys:n.passKeys!==!1,passNode:n.passNode||!1,schema:n.space==="svg"?yc:MN,stylePropertyNameCase:n.stylePropertyNameCase||"dom",tableCellAlignToStyle:n.tableCellAlignToStyle!==!1},o=tp(r,e,void 0);return o&&typeof o!="string"?o:r.create(e,r.Fragment,{children:o||void 0},void 0)}function tp(e,n,s){if(n.type==="element")return BN(e,n,s);if(n.type==="mdxFlowExpression"||n.type==="mdxTextExpression")return HN(e,n);if(n.type==="mdxJsxFlowElement"||n.type==="mdxJsxTextElement")return VN(e,n,s);if(n.type==="mdxjsEsm")return qN(e,n);if(n.type==="root")return WN(e,n,s);if(n.type==="text")return GN(e,n)}function BN(e,n,s){const i=e.schema;let r=i;n.tagName.toLowerCase()==="svg"&&i.space==="html"&&(r=yc,e.schema=r),e.ancestors.push(n);const o=sp(e,n.tagName,!1),l=YN(e,n);let c=Nc(e,n);return FN.has(n.tagName)&&(c=c.filter(function(u){return typeof u=="string"?!xN(u):!0})),np(e,l,o,n),wc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function HN(e,n){if(n.data&&n.data.estree&&e.evaluater){const i=n.data.estree.body[0];return i.type,e.evaluater.evaluateExpression(i.expression)}qa(e,n.position)}function qN(e,n){if(n.data&&n.data.estree&&e.evaluater)return e.evaluater.evaluateProgram(n.data.estree);qa(e,n.position)}function VN(e,n,s){const i=e.schema;let r=i;n.name==="svg"&&i.space==="html"&&(r=yc,e.schema=r),e.ancestors.push(n);const o=n.name===null?e.Fragment:sp(e,n.name,!0),l=QN(e,n),c=Nc(e,n);return np(e,l,o,n),wc(l,c),e.ancestors.pop(),e.schema=i,e.create(n,o,l,s)}function WN(e,n,s){const i={};return wc(i,Nc(e,n)),e.create(n,e.Fragment,i,s)}function GN(e,n){return n.value}function np(e,n,s,i){typeof s!="string"&&s!==e.Fragment&&e.passNode&&(n.node=i)}function wc(e,n){if(n.length>0){const s=n.length>1?n:n[0];s&&(e.children=s)}}function KN(e,n,s){return i;function i(r,o,l,c){const d=Array.isArray(l.children)?s:n;return c?d(o,l,c):d(o,l)}}function JN(e,n){return s;function s(i,r,o,l){const c=Array.isArray(o.children),u=kc(i);return n(r,o,l,c,{columnNumber:u?u.column-1:void 0,fileName:e,lineNumber:u?u.line:void 0},void 0)}}function YN(e,n){const s={};let i,r;for(r in n.properties)if(r!=="children"&&jc.call(n.properties,r)){const o=XN(e,r,n.properties[r]);if(o){const[l,c]=o;e.tableCellAlignToStyle&&l==="align"&&typeof c=="string"&&ON.has(n.tagName)?i=c:s[l]=c}}if(i){const o=s.style||(s.style={});o[e.stylePropertyNameCase==="css"?"text-align":"textAlign"]=i}return s}function QN(e,n){const s={};for(const i of n.attributes)if(i.type==="mdxJsxExpressionAttribute")if(i.data&&i.data.estree&&e.evaluater){const o=i.data.estree.body[0];o.type;const l=o.expression;l.type;const c=l.properties[0];c.type,Object.assign(s,e.evaluater.evaluateExpression(c.argument))}else qa(e,n.position);else{const r=i.name;let o;if(i.value&&typeof i.value=="object")if(i.value.data&&i.value.data.estree&&e.evaluater){const c=i.value.data.estree.body[0];c.type,o=e.evaluater.evaluateExpression(c.expression)}else qa(e,n.position);else o=i.value===null?!0:i.value;s[r]=o}return s}function Nc(e,n){const s=[];let i=-1;const r=e.passKeys?new Map:LN;for(;++i<n.children.length;){const o=n.children[i];let l;if(e.passKeys){const u=o.type==="element"?o.tagName:o.type==="mdxJsxFlowElement"||o.type==="mdxJsxTextElement"?o.name:void 0;if(u){const d=r.get(u)||0;l=u+"-"+d,r.set(u,d+1)}}const c=tp(e,o,l);c!==void 0&&s.push(c)}return s}function XN(e,n,s){const i=SN(e.schema,n);if(!(s==null||typeof s=="number"&&Number.isNaN(s))){if(Array.isArray(s)&&(s=i.commaSeparated?hN(s):_N(s)),i.property==="style"){let r=typeof s=="object"?s:ZN(e,String(s));return e.stylePropertyNameCase==="css"&&(r=e1(r)),["style",r]}return[e.elementAttributeNameCase==="react"&&i.space?jN[i.property]||i.property:i.attribute,s]}}function ZN(e,n){try{return $N(n,{reactCompat:!0})}catch(s){if(e.ignoreInvalidStyle)return{};const i=s,r=new Ln("Cannot parse `style` attribute",{ancestors:e.ancestors,cause:i,ruleId:"style",source:"hast-util-to-jsx-runtime"});throw r.file=e.filePath||void 0,r.url=ep+"#cannot-parse-style-attribute",r}}function sp(e,n,s){let i;if(!s)i={type:"Literal",value:n};else if(n.includes(".")){const r=n.split(".");let o=-1,l;for(;++o<r.length;){const c=cu(r[o])?{type:"Identifier",name:r[o]}:{type:"Literal",value:r[o]};l=l?{type:"MemberExpression",object:l,property:c,computed:!!(o&&c.type==="Literal"),optional:!1}:c}i=l}else i=cu(n)&&!/^[a-z]/.test(n)?{type:"Identifier",name:n}:{type:"Literal",value:n};if(i.type==="Literal"){const r=i.value;return jc.call(e.components,r)?e.components[r]:r}if(e.evaluater)return e.evaluater.evaluateExpression(i);qa(e)}function qa(e,n){const s=new Ln("Cannot handle MDX estrees without `createEvaluater`",{ancestors:e.ancestors,place:n,ruleId:"mdx-estree",source:"hast-util-to-jsx-runtime"});throw s.file=e.filePath||void 0,s.url=ep+"#cannot-handle-mdx-estrees-without-createevaluater",s}function e1(e){const n={};let s;for(s in e)jc.call(e,s)&&(n[t1(s)]=e[s]);return n}function t1(e){let n=e.replace(zN,n1);return n.slice(0,3)==="ms-"&&(n="-"+n),n}function n1(e){return"-"+e.toLowerCase()}const Go={action:["form"],cite:["blockquote","del","ins","q"],data:["object"],formAction:["button","input"],href:["a","area","base","link"],icon:["menuitem"],itemId:null,manifest:["html"],ping:["a","area"],poster:["video"],src:["audio","embed","iframe","img","input","script","source","track","video"]},s1={};function Sc(e,n){const s=s1,i=typeof s.includeImageAlt=="boolean"?s.includeImageAlt:!0,r=typeof s.includeHtml=="boolean"?s.includeHtml:!0;return ip(e,i,r)}function ip(e,n,s){if(i1(e)){if("value"in e)return e.type==="html"&&!s?"":e.value;if(n&&"alt"in e&&e.alt)return e.alt;if("children"in e)return vu(e.children,n,s)}return Array.isArray(e)?vu(e,n,s):""}function vu(e,n,s){const i=[];let r=-1;for(;++r<e.length;)i[r]=ip(e[r],n,s);return i.join("")}function i1(e){return!!(e&&typeof e=="object")}const yu=document.createElement("i");function Cc(e){const n="&"+e+";";yu.innerHTML=n;const s=yu.textContent;return s.charCodeAt(s.length-1)===59&&e!=="semi"||s===n?!1:s}function ds(e,n,s,i){const r=e.length;let o=0,l;if(n<0?n=-n>r?0:r+n:n=n>r?r:n,s=s>0?s:0,i.length<1e4)l=Array.from(i),l.unshift(n,s),e.splice(...l);else for(s&&e.splice(n,s);o<i.length;)l=i.slice(o,o+1e4),l.unshift(n,0),e.splice(...l),o+=1e4,n+=1e4}function ws(e,n){return e.length>0?(ds(e,e.length,0,n),e):n}const ku={}.hasOwnProperty;function ap(e){const n={};let s=-1;for(;++s<e.length;)a1(n,e[s]);return n}function a1(e,n){let s;for(s in n){const r=(ku.call(e,s)?e[s]:void 0)||(e[s]={}),o=n[s];let l;if(o)for(l in o){ku.call(r,l)||(r[l]=[]);const c=o[l];r1(r[l],Array.isArray(c)?c:c?[c]:[])}}}function r1(e,n){let s=-1;const i=[];for(;++s<n.length;)(n[s].add==="after"?e:i).push(n[s]);ds(e,0,0,i)}function rp(e,n){const s=Number.parseInt(e,n);return s<9||s===11||s>13&&s<32||s>126&&s<160||s>55295&&s<57344||s>64975&&s<65008||(s&65535)===65535||(s&65535)===65534||s>1114111?"�":String.fromCodePoint(s)}function Rs(e){return e.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const qn=ui(/[A-Za-z]/),$n=ui(/[\dA-Za-z]/),o1=ui(/[#-'*+\--9=?A-Z^-~]/);function Wr(e){return e!==null&&(e<32||e===127)}const Gl=ui(/\d/),l1=ui(/[\dA-Fa-f]/),c1=ui(/[!-/:-@[-`{-~]/);function yt(e){return e!==null&&e<-2}function Wt(e){return e!==null&&(e<0||e===32)}function It(e){return e===-2||e===-1||e===32}const ho=ui(/\p{P}|\p{S}/u),Ei=ui(/\s/);function ui(e){return n;function n(s){return s!==null&&s>-1&&e.test(String.fromCharCode(s))}}function da(e){const n=[];let s=-1,i=0,r=0;for(;++s<e.length;){const o=e.charCodeAt(s);let l="";if(o===37&&$n(e.charCodeAt(s+1))&&$n(e.charCodeAt(s+2)))r=2;else if(o<128)/[!#$&-;=?-Z_a-z~]/.test(String.fromCharCode(o))||(l=String.fromCharCode(o));else if(o>55295&&o<57344){const c=e.charCodeAt(s+1);o<56320&&c>56319&&c<57344?(l=String.fromCharCode(o,c),r=1):l="�"}else l=String.fromCharCode(o);l&&(n.push(e.slice(i,s),encodeURIComponent(l)),i=s+r+1,l=""),r&&(s+=r,r=0)}return n.join("")+e.slice(i)}function Ft(e,n,s,i){const r=i?i-1:Number.POSITIVE_INFINITY;let o=0;return l;function l(u){return It(u)?(e.enter(s),c(u)):n(u)}function c(u){return It(u)&&o++<r?(e.consume(u),c):(e.exit(s),n(u))}}const d1={tokenize:u1};function u1(e){const n=e.attempt(this.parser.constructs.contentInitial,i,r);let s;return n;function i(c){if(c===null){e.consume(c);return}return e.enter("lineEnding"),e.consume(c),e.exit("lineEnding"),Ft(e,n,"linePrefix")}function r(c){return e.enter("paragraph"),o(c)}function o(c){const u=e.enter("chunkText",{contentType:"text",previous:s});return s&&(s.next=u),s=u,l(c)}function l(c){if(c===null){e.exit("chunkText"),e.exit("paragraph"),e.consume(c);return}return yt(c)?(e.consume(c),e.exit("chunkText"),o):(e.consume(c),l)}}const m1={tokenize:h1},ju={tokenize:p1};function h1(e){const n=this,s=[];let i=0,r,o,l;return c;function c(M){if(i<s.length){const y=s[i];return n.containerState=y[1],e.attempt(y[0].continuation,u,d)(M)}return d(M)}function u(M){if(i++,n.containerState._closeFlow){n.containerState._closeFlow=void 0,r&&k();const y=n.events.length;let R=y,j;for(;R--;)if(n.events[R][0]==="exit"&&n.events[R][1].type==="chunkFlow"){j=n.events[R][1].end;break}x(i);let C=y;for(;C<n.events.length;)n.events[C][1].end={...j},C++;return ds(n.events,R+1,0,n.events.slice(y)),n.events.length=C,d(M)}return c(M)}function d(M){if(i===s.length){if(!r)return g(M);if(r.currentConstruct&&r.currentConstruct.concrete)return f(M);n.interrupt=!!(r.currentConstruct&&!r._gfmTableDynamicInterruptHack)}return n.containerState={},e.check(ju,m,h)(M)}function m(M){return r&&k(),x(i),g(M)}function h(M){return n.parser.lazy[n.now().line]=i!==s.length,l=n.now().offset,f(M)}function g(M){return n.containerState={},e.attempt(ju,p,f)(M)}function p(M){return i++,s.push([n.currentConstruct,n.containerState]),g(M)}function f(M){if(M===null){r&&k(),x(0),e.consume(M);return}return r=r||n.parser.flow(n.now()),e.enter("chunkFlow",{_tokenizer:r,contentType:"flow",previous:o}),b(M)}function b(M){if(M===null){v(e.exit("chunkFlow"),!0),x(0),e.consume(M);return}return yt(M)?(e.consume(M),v(e.exit("chunkFlow")),i=0,n.interrupt=void 0,c):(e.consume(M),b)}function v(M,y){const R=n.sliceStream(M);if(y&&R.push(null),M.previous=o,o&&(o.next=M),o=M,r.defineSkip(M.start),r.write(R),n.parser.lazy[M.start.line]){let j=r.events.length;for(;j--;)if(r.events[j][1].start.offset<l&&(!r.events[j][1].end||r.events[j][1].end.offset>l))return;const C=n.events.length;let S=C,P,T;for(;S--;)if(n.events[S][0]==="exit"&&n.events[S][1].type==="chunkFlow"){if(P){T=n.events[S][1].end;break}P=!0}for(x(i),j=C;j<n.events.length;)n.events[j][1].end={...T},j++;ds(n.events,S+1,0,n.events.slice(C)),n.events.length=j}}function x(M){let y=s.length;for(;y-- >M;){const R=s[y];n.containerState=R[1],R[0].exit.call(n,e)}s.length=M}function k(){r.write([null]),o=void 0,r=void 0,n.containerState._closeFlow=void 0}}function p1(e,n,s){return Ft(e,e.attempt(this.parser.constructs.document,n,s),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Qi(e){if(e===null||Wt(e)||Ei(e))return 1;if(ho(e))return 2}function po(e,n,s){const i=[];let r=-1;for(;++r<e.length;){const o=e[r].resolveAll;o&&!i.includes(o)&&(n=o(n,s),i.push(o))}return n}const Kl={name:"attention",resolveAll:f1,tokenize:g1};function f1(e,n){let s=-1,i,r,o,l,c,u,d,m;for(;++s<e.length;)if(e[s][0]==="enter"&&e[s][1].type==="attentionSequence"&&e[s][1]._close){for(i=s;i--;)if(e[i][0]==="exit"&&e[i][1].type==="attentionSequence"&&e[i][1]._open&&n.sliceSerialize(e[i][1]).charCodeAt(0)===n.sliceSerialize(e[s][1]).charCodeAt(0)){if((e[i][1]._close||e[s][1]._open)&&(e[s][1].end.offset-e[s][1].start.offset)%3&&!((e[i][1].end.offset-e[i][1].start.offset+e[s][1].end.offset-e[s][1].start.offset)%3))continue;u=e[i][1].end.offset-e[i][1].start.offset>1&&e[s][1].end.offset-e[s][1].start.offset>1?2:1;const h={...e[i][1].end},g={...e[s][1].start};wu(h,-u),wu(g,u),l={type:u>1?"strongSequence":"emphasisSequence",start:h,end:{...e[i][1].end}},c={type:u>1?"strongSequence":"emphasisSequence",start:{...e[s][1].start},end:g},o={type:u>1?"strongText":"emphasisText",start:{...e[i][1].end},end:{...e[s][1].start}},r={type:u>1?"strong":"emphasis",start:{...l.start},end:{...c.end}},e[i][1].end={...l.start},e[s][1].start={...c.end},d=[],e[i][1].end.offset-e[i][1].start.offset&&(d=ws(d,[["enter",e[i][1],n],["exit",e[i][1],n]])),d=ws(d,[["enter",r,n],["enter",l,n],["exit",l,n],["enter",o,n]]),d=ws(d,po(n.parser.constructs.insideSpan.null,e.slice(i+1,s),n)),d=ws(d,[["exit",o,n],["enter",c,n],["exit",c,n],["exit",r,n]]),e[s][1].end.offset-e[s][1].start.offset?(m=2,d=ws(d,[["enter",e[s][1],n],["exit",e[s][1],n]])):m=0,ds(e,i-1,s-i+3,d),s=i+d.length-m-2;break}}for(s=-1;++s<e.length;)e[s][1].type==="attentionSequence"&&(e[s][1].type="data");return e}function g1(e,n){const s=this.parser.constructs.attentionMarkers.null,i=this.previous,r=Qi(i);let o;return l;function l(u){return o=u,e.enter("attentionSequence"),c(u)}function c(u){if(u===o)return e.consume(u),c;const d=e.exit("attentionSequence"),m=Qi(u),h=!m||m===2&&r||s.includes(u),g=!r||r===2&&m||s.includes(i);return d._open=!!(o===42?h:h&&(r||!g)),d._close=!!(o===42?g:g&&(m||!h)),n(u)}}function wu(e,n){e.column+=n,e.offset+=n,e._bufferIndex+=n}const b1={name:"autolink",tokenize:x1};function x1(e,n,s){let i=0;return r;function r(p){return e.enter("autolink"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.enter("autolinkProtocol"),o}function o(p){return qn(p)?(e.consume(p),l):p===64?s(p):d(p)}function l(p){return p===43||p===45||p===46||$n(p)?(i=1,c(p)):d(p)}function c(p){return p===58?(e.consume(p),i=0,u):(p===43||p===45||p===46||$n(p))&&i++<32?(e.consume(p),c):(i=0,d(p))}function u(p){return p===62?(e.exit("autolinkProtocol"),e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):p===null||p===32||p===60||Wr(p)?s(p):(e.consume(p),u)}function d(p){return p===64?(e.consume(p),m):o1(p)?(e.consume(p),d):s(p)}function m(p){return $n(p)?h(p):s(p)}function h(p){return p===46?(e.consume(p),i=0,m):p===62?(e.exit("autolinkProtocol").type="autolinkEmail",e.enter("autolinkMarker"),e.consume(p),e.exit("autolinkMarker"),e.exit("autolink"),n):g(p)}function g(p){if((p===45||$n(p))&&i++<63){const f=p===45?g:h;return e.consume(p),f}return s(p)}}const sr={partial:!0,tokenize:v1};function v1(e,n,s){return i;function i(o){return It(o)?Ft(e,r,"linePrefix")(o):r(o)}function r(o){return o===null||yt(o)?n(o):s(o)}}const op={continuation:{tokenize:k1},exit:j1,name:"blockQuote",tokenize:y1};function y1(e,n,s){const i=this;return r;function r(l){if(l===62){const c=i.containerState;return c.open||(e.enter("blockQuote",{_container:!0}),c.open=!0),e.enter("blockQuotePrefix"),e.enter("blockQuoteMarker"),e.consume(l),e.exit("blockQuoteMarker"),o}return s(l)}function o(l){return It(l)?(e.enter("blockQuotePrefixWhitespace"),e.consume(l),e.exit("blockQuotePrefixWhitespace"),e.exit("blockQuotePrefix"),n):(e.exit("blockQuotePrefix"),n(l))}}function k1(e,n,s){const i=this;return r;function r(l){return It(l)?Ft(e,o,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(l):o(l)}function o(l){return e.attempt(op,n,s)(l)}}function j1(e){e.exit("blockQuote")}const lp={name:"characterEscape",tokenize:w1};function w1(e,n,s){return i;function i(o){return e.enter("characterEscape"),e.enter("escapeMarker"),e.consume(o),e.exit("escapeMarker"),r}function r(o){return c1(o)?(e.enter("characterEscapeValue"),e.consume(o),e.exit("characterEscapeValue"),e.exit("characterEscape"),n):s(o)}}const cp={name:"characterReference",tokenize:N1};function N1(e,n,s){const i=this;let r=0,o,l;return c;function c(h){return e.enter("characterReference"),e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),u}function u(h){return h===35?(e.enter("characterReferenceMarkerNumeric"),e.consume(h),e.exit("characterReferenceMarkerNumeric"),d):(e.enter("characterReferenceValue"),o=31,l=$n,m(h))}function d(h){return h===88||h===120?(e.enter("characterReferenceMarkerHexadecimal"),e.consume(h),e.exit("characterReferenceMarkerHexadecimal"),e.enter("characterReferenceValue"),o=6,l=l1,m):(e.enter("characterReferenceValue"),o=7,l=Gl,m(h))}function m(h){if(h===59&&r){const g=e.exit("characterReferenceValue");return l===$n&&!Cc(i.sliceSerialize(g))?s(h):(e.enter("characterReferenceMarker"),e.consume(h),e.exit("characterReferenceMarker"),e.exit("characterReference"),n)}return l(h)&&r++<o?(e.consume(h),m):s(h)}}const Nu={partial:!0,tokenize:C1},Su={concrete:!0,name:"codeFenced",tokenize:S1};function S1(e,n,s){const i=this,r={partial:!0,tokenize:R};let o=0,l=0,c;return u;function u(j){return d(j)}function d(j){const C=i.events[i.events.length-1];return o=C&&C[1].type==="linePrefix"?C[2].sliceSerialize(C[1],!0).length:0,c=j,e.enter("codeFenced"),e.enter("codeFencedFence"),e.enter("codeFencedFenceSequence"),m(j)}function m(j){return j===c?(l++,e.consume(j),m):l<3?s(j):(e.exit("codeFencedFenceSequence"),It(j)?Ft(e,h,"whitespace")(j):h(j))}function h(j){return j===null||yt(j)?(e.exit("codeFencedFence"),i.interrupt?n(j):e.check(Nu,b,y)(j)):(e.enter("codeFencedFenceInfo"),e.enter("chunkString",{contentType:"string"}),g(j))}function g(j){return j===null||yt(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),h(j)):It(j)?(e.exit("chunkString"),e.exit("codeFencedFenceInfo"),Ft(e,p,"whitespace")(j)):j===96&&j===c?s(j):(e.consume(j),g)}function p(j){return j===null||yt(j)?h(j):(e.enter("codeFencedFenceMeta"),e.enter("chunkString",{contentType:"string"}),f(j))}function f(j){return j===null||yt(j)?(e.exit("chunkString"),e.exit("codeFencedFenceMeta"),h(j)):j===96&&j===c?s(j):(e.consume(j),f)}function b(j){return e.attempt(r,y,v)(j)}function v(j){return e.enter("lineEnding"),e.consume(j),e.exit("lineEnding"),x}function x(j){return o>0&&It(j)?Ft(e,k,"linePrefix",o+1)(j):k(j)}function k(j){return j===null||yt(j)?e.check(Nu,b,y)(j):(e.enter("codeFlowValue"),M(j))}function M(j){return j===null||yt(j)?(e.exit("codeFlowValue"),k(j)):(e.consume(j),M)}function y(j){return e.exit("codeFenced"),n(j)}function R(j,C,S){let P=0;return T;function T(I){return j.enter("lineEnding"),j.consume(I),j.exit("lineEnding"),_}function _(I){return j.enter("codeFencedFence"),It(I)?Ft(j,L,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(I):L(I)}function L(I){return I===c?(j.enter("codeFencedFenceSequence"),G(I)):S(I)}function G(I){return I===c?(P++,j.consume(I),G):P>=l?(j.exit("codeFencedFenceSequence"),It(I)?Ft(j,$,"whitespace")(I):$(I)):S(I)}function $(I){return I===null||yt(I)?(j.exit("codeFencedFence"),C(I)):S(I)}}}function C1(e,n,s){const i=this;return r;function r(l){return l===null?s(l):(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}const Ko={name:"codeIndented",tokenize:M1},E1={partial:!0,tokenize:_1};function M1(e,n,s){const i=this;return r;function r(d){return e.enter("codeIndented"),Ft(e,o,"linePrefix",5)(d)}function o(d){const m=i.events[i.events.length-1];return m&&m[1].type==="linePrefix"&&m[2].sliceSerialize(m[1],!0).length>=4?l(d):s(d)}function l(d){return d===null?u(d):yt(d)?e.attempt(E1,l,u)(d):(e.enter("codeFlowValue"),c(d))}function c(d){return d===null||yt(d)?(e.exit("codeFlowValue"),l(d)):(e.consume(d),c)}function u(d){return e.exit("codeIndented"),n(d)}}function _1(e,n,s){const i=this;return r;function r(l){return i.parser.lazy[i.now().line]?s(l):yt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),r):Ft(e,o,"linePrefix",5)(l)}function o(l){const c=i.events[i.events.length-1];return c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):yt(l)?r(l):s(l)}}const A1={name:"codeText",previous:R1,resolve:T1,tokenize:I1};function T1(e){let n=e.length-4,s=3,i,r;if((e[s][1].type==="lineEnding"||e[s][1].type==="space")&&(e[n][1].type==="lineEnding"||e[n][1].type==="space")){for(i=s;++i<n;)if(e[i][1].type==="codeTextData"){e[s][1].type="codeTextPadding",e[n][1].type="codeTextPadding",s+=2,n-=2;break}}for(i=s-1,n++;++i<=n;)r===void 0?i!==n&&e[i][1].type!=="lineEnding"&&(r=i):(i===n||e[i][1].type==="lineEnding")&&(e[r][1].type="codeTextData",i!==r+2&&(e[r][1].end=e[i-1][1].end,e.splice(r+2,i-r-2),n-=i-r-2,i=r+2),r=void 0);return e}function R1(e){return e!==96||this.events[this.events.length-1][1].type==="characterEscape"}function I1(e,n,s){let i=0,r,o;return l;function l(h){return e.enter("codeText"),e.enter("codeTextSequence"),c(h)}function c(h){return h===96?(e.consume(h),i++,c):(e.exit("codeTextSequence"),u(h))}function u(h){return h===null?s(h):h===32?(e.enter("space"),e.consume(h),e.exit("space"),u):h===96?(o=e.enter("codeTextSequence"),r=0,m(h)):yt(h)?(e.enter("lineEnding"),e.consume(h),e.exit("lineEnding"),u):(e.enter("codeTextData"),d(h))}function d(h){return h===null||h===32||h===96||yt(h)?(e.exit("codeTextData"),u(h)):(e.consume(h),d)}function m(h){return h===96?(e.consume(h),r++,m):r===i?(e.exit("codeTextSequence"),e.exit("codeText"),n(h)):(o.type="codeTextData",d(h))}}class P1{constructor(n){this.left=n?[...n]:[],this.right=[]}get(n){if(n<0||n>=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+n+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return n<this.left.length?this.left[n]:this.right[this.right.length-n+this.left.length-1]}get length(){return this.left.length+this.right.length}shift(){return this.setCursor(0),this.right.pop()}slice(n,s){const i=s??Number.POSITIVE_INFINITY;return i<this.left.length?this.left.slice(n,i):n>this.left.length?this.right.slice(this.right.length-i+this.left.length,this.right.length-n+this.left.length).reverse():this.left.slice(n).concat(this.right.slice(this.right.length-i+this.left.length).reverse())}splice(n,s,i){const r=s||0;this.setCursor(Math.trunc(n));const o=this.right.splice(this.right.length-r,Number.POSITIVE_INFINITY);return i&&ya(this.left,i),o.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(n){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(n)}pushMany(n){this.setCursor(Number.POSITIVE_INFINITY),ya(this.left,n)}unshift(n){this.setCursor(0),this.right.push(n)}unshiftMany(n){this.setCursor(0),ya(this.right,n.reverse())}setCursor(n){if(!(n===this.left.length||n>this.left.length&&this.right.length===0||n<0&&this.left.length===0))if(n<this.left.length){const s=this.left.splice(n,Number.POSITIVE_INFINITY);ya(this.right,s.reverse())}else{const s=this.right.splice(this.left.length+this.right.length-n,Number.POSITIVE_INFINITY);ya(this.left,s.reverse())}}}function ya(e,n){let s=0;if(n.length<1e4)e.push(...n);else for(;s<n.length;)e.push(...n.slice(s,s+1e4)),s+=1e4}function dp(e){const n={};let s=-1,i,r,o,l,c,u,d;const m=new P1(e);for(;++s<m.length;){for(;s in n;)s=n[s];if(i=m.get(s),s&&i[1].type==="chunkFlow"&&m.get(s-1)[1].type==="listItemPrefix"&&(u=i[1]._tokenizer.events,o=0,o<u.length&&u[o][1].type==="lineEndingBlank"&&(o+=2),o<u.length&&u[o][1].type==="content"))for(;++o<u.length&&u[o][1].type!=="content";)u[o][1].type==="chunkText"&&(u[o][1]._isInFirstContentOfListItem=!0,o++);if(i[0]==="enter")i[1].contentType&&(Object.assign(n,$1(m,s)),s=n[s],d=!0);else if(i[1]._container){for(o=s,r=void 0;o--;)if(l=m.get(o),l[1].type==="lineEnding"||l[1].type==="lineEndingBlank")l[0]==="enter"&&(r&&(m.get(r)[1].type="lineEndingBlank"),l[1].type="lineEnding",r=o);else if(!(l[1].type==="linePrefix"||l[1].type==="listItemIndent"))break;r&&(i[1].end={...m.get(r)[1].start},c=m.slice(r,s),c.unshift(i),m.splice(r,s-r+1,c))}}return ds(e,0,Number.POSITIVE_INFINITY,m.slice(0)),!d}function $1(e,n){const s=e.get(n)[1],i=e.get(n)[2];let r=n-1;const o=[];let l=s._tokenizer;l||(l=i.parser[s.contentType](s.start),s._contentTypeTextTrailing&&(l._contentTypeTextTrailing=!0));const c=l.events,u=[],d={};let m,h,g=-1,p=s,f=0,b=0;const v=[b];for(;p;){for(;e.get(++r)[1]!==p;);o.push(r),p._tokenizer||(m=i.sliceStream(p),p.next||m.push(null),h&&l.defineSkip(p.start),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=!0),l.write(m),p._isInFirstContentOfListItem&&(l._gfmTasklistFirstContentOfListItem=void 0)),h=p,p=p.next}for(p=s;++g<c.length;)c[g][0]==="exit"&&c[g-1][0]==="enter"&&c[g][1].type===c[g-1][1].type&&c[g][1].start.line!==c[g][1].end.line&&(b=g+1,v.push(b),p._tokenizer=void 0,p.previous=void 0,p=p.next);for(l.events=[],p?(p._tokenizer=void 0,p.previous=void 0):v.pop(),g=v.length;g--;){const x=c.slice(v[g],v[g+1]),k=o.pop();u.push([k,k+x.length-1]),e.splice(k,2,x)}for(u.reverse(),g=-1;++g<u.length;)d[f+u[g][0]]=f+u[g][1],f+=u[g][1]-u[g][0]-1;return d}const D1={resolve:z1,tokenize:F1},L1={partial:!0,tokenize:O1};function z1(e){return dp(e),e}function F1(e,n){let s;return i;function i(c){return e.enter("content"),s=e.enter("chunkContent",{contentType:"content"}),r(c)}function r(c){return c===null?o(c):yt(c)?e.check(L1,l,o)(c):(e.consume(c),r)}function o(c){return e.exit("chunkContent"),e.exit("content"),n(c)}function l(c){return e.consume(c),e.exit("chunkContent"),s.next=e.enter("chunkContent",{contentType:"content",previous:s}),s=s.next,r}}function O1(e,n,s){const i=this;return r;function r(l){return e.exit("chunkContent"),e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),Ft(e,o,"linePrefix")}function o(l){if(l===null||yt(l))return s(l);const c=i.events[i.events.length-1];return!i.parser.constructs.disable.null.includes("codeIndented")&&c&&c[1].type==="linePrefix"&&c[2].sliceSerialize(c[1],!0).length>=4?n(l):e.interrupt(i.parser.constructs.flow,s,n)(l)}}function up(e,n,s,i,r,o,l,c,u){const d=u||Number.POSITIVE_INFINITY;let m=0;return h;function h(x){return x===60?(e.enter(i),e.enter(r),e.enter(o),e.consume(x),e.exit(o),g):x===null||x===32||x===41||Wr(x)?s(x):(e.enter(i),e.enter(l),e.enter(c),e.enter("chunkString",{contentType:"string"}),b(x))}function g(x){return x===62?(e.enter(o),e.consume(x),e.exit(o),e.exit(r),e.exit(i),n):(e.enter(c),e.enter("chunkString",{contentType:"string"}),p(x))}function p(x){return x===62?(e.exit("chunkString"),e.exit(c),g(x)):x===null||x===60||yt(x)?s(x):(e.consume(x),x===92?f:p)}function f(x){return x===60||x===62||x===92?(e.consume(x),p):p(x)}function b(x){return!m&&(x===null||x===41||Wt(x))?(e.exit("chunkString"),e.exit(c),e.exit(l),e.exit(i),n(x)):m<d&&x===40?(e.consume(x),m++,b):x===41?(e.consume(x),m--,b):x===null||x===32||x===40||Wr(x)?s(x):(e.consume(x),x===92?v:b)}function v(x){return x===40||x===41||x===92?(e.consume(x),b):b(x)}}function mp(e,n,s,i,r,o){const l=this;let c=0,u;return d;function d(p){return e.enter(i),e.enter(r),e.consume(p),e.exit(r),e.enter(o),m}function m(p){return c>999||p===null||p===91||p===93&&!u||p===94&&!c&&"_hiddenFootnoteSupport"in l.parser.constructs?s(p):p===93?(e.exit(o),e.enter(r),e.consume(p),e.exit(r),e.exit(i),n):yt(p)?(e.enter("lineEnding"),e.consume(p),e.exit("lineEnding"),m):(e.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||yt(p)||c++>999?(e.exit("chunkString"),m(p)):(e.consume(p),u||(u=!It(p)),p===92?g:h)}function g(p){return p===91||p===92||p===93?(e.consume(p),c++,h):h(p)}}function hp(e,n,s,i,r,o){let l;return c;function c(g){return g===34||g===39||g===40?(e.enter(i),e.enter(r),e.consume(g),e.exit(r),l=g===40?41:g,u):s(g)}function u(g){return g===l?(e.enter(r),e.consume(g),e.exit(r),e.exit(i),n):(e.enter(o),d(g))}function d(g){return g===l?(e.exit(o),u(l)):g===null?s(g):yt(g)?(e.enter("lineEnding"),e.consume(g),e.exit("lineEnding"),Ft(e,d,"linePrefix")):(e.enter("chunkString",{contentType:"string"}),m(g))}function m(g){return g===l||g===null||yt(g)?(e.exit("chunkString"),d(g)):(e.consume(g),g===92?h:m)}function h(g){return g===l||g===92?(e.consume(g),m):m(g)}}function Da(e,n){let s;return i;function i(r){return yt(r)?(e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),s=!0,i):It(r)?Ft(e,i,s?"linePrefix":"lineSuffix")(r):n(r)}}const U1={name:"definition",tokenize:H1},B1={partial:!0,tokenize:q1};function H1(e,n,s){const i=this;let r;return o;function o(p){return e.enter("definition"),l(p)}function l(p){return mp.call(i,e,c,s,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function c(p){return r=Rs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)),p===58?(e.enter("definitionMarker"),e.consume(p),e.exit("definitionMarker"),u):s(p)}function u(p){return Wt(p)?Da(e,d)(p):d(p)}function d(p){return up(e,m,s,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function m(p){return e.attempt(B1,h,h)(p)}function h(p){return It(p)?Ft(e,g,"whitespace")(p):g(p)}function g(p){return p===null||yt(p)?(e.exit("definition"),i.parser.defined.push(r),n(p)):s(p)}}function q1(e,n,s){return i;function i(c){return Wt(c)?Da(e,r)(c):s(c)}function r(c){return hp(e,o,s,"definitionTitle","definitionTitleMarker","definitionTitleString")(c)}function o(c){return It(c)?Ft(e,l,"whitespace")(c):l(c)}function l(c){return c===null||yt(c)?n(c):s(c)}}const V1={name:"hardBreakEscape",tokenize:W1};function W1(e,n,s){return i;function i(o){return e.enter("hardBreakEscape"),e.consume(o),r}function r(o){return yt(o)?(e.exit("hardBreakEscape"),n(o)):s(o)}}const G1={name:"headingAtx",resolve:K1,tokenize:J1};function K1(e,n){let s=e.length-2,i=3,r,o;return e[i][1].type==="whitespace"&&(i+=2),s-2>i&&e[s][1].type==="whitespace"&&(s-=2),e[s][1].type==="atxHeadingSequence"&&(i===s-1||s-4>i&&e[s-2][1].type==="whitespace")&&(s-=i+1===s?2:4),s>i&&(r={type:"atxHeadingText",start:e[i][1].start,end:e[s][1].end},o={type:"chunkText",start:e[i][1].start,end:e[s][1].end,contentType:"text"},ds(e,i,s-i+1,[["enter",r,n],["enter",o,n],["exit",o,n],["exit",r,n]])),e}function J1(e,n,s){let i=0;return r;function r(m){return e.enter("atxHeading"),o(m)}function o(m){return e.enter("atxHeadingSequence"),l(m)}function l(m){return m===35&&i++<6?(e.consume(m),l):m===null||Wt(m)?(e.exit("atxHeadingSequence"),c(m)):s(m)}function c(m){return m===35?(e.enter("atxHeadingSequence"),u(m)):m===null||yt(m)?(e.exit("atxHeading"),n(m)):It(m)?Ft(e,c,"whitespace")(m):(e.enter("atxHeadingText"),d(m))}function u(m){return m===35?(e.consume(m),u):(e.exit("atxHeadingSequence"),c(m))}function d(m){return m===null||m===35||Wt(m)?(e.exit("atxHeadingText"),c(m)):(e.consume(m),d)}}const Y1=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Cu=["pre","script","style","textarea"],Q1={concrete:!0,name:"htmlFlow",resolveTo:e0,tokenize:t0},X1={partial:!0,tokenize:s0},Z1={partial:!0,tokenize:n0};function e0(e){let n=e.length;for(;n--&&!(e[n][0]==="enter"&&e[n][1].type==="htmlFlow"););return n>1&&e[n-2][1].type==="linePrefix"&&(e[n][1].start=e[n-2][1].start,e[n+1][1].start=e[n-2][1].start,e.splice(n-2,2)),e}function t0(e,n,s){const i=this;let r,o,l,c,u;return d;function d(E){return m(E)}function m(E){return e.enter("htmlFlow"),e.enter("htmlFlowData"),e.consume(E),h}function h(E){return E===33?(e.consume(E),g):E===47?(e.consume(E),o=!0,b):E===63?(e.consume(E),r=3,i.interrupt?n:A):qn(E)?(e.consume(E),l=String.fromCharCode(E),v):s(E)}function g(E){return E===45?(e.consume(E),r=2,p):E===91?(e.consume(E),r=5,c=0,f):qn(E)?(e.consume(E),r=4,i.interrupt?n:A):s(E)}function p(E){return E===45?(e.consume(E),i.interrupt?n:A):s(E)}function f(E){const U="CDATA[";return E===U.charCodeAt(c++)?(e.consume(E),c===U.length?i.interrupt?n:L:f):s(E)}function b(E){return qn(E)?(e.consume(E),l=String.fromCharCode(E),v):s(E)}function v(E){if(E===null||E===47||E===62||Wt(E)){const U=E===47,pe=l.toLowerCase();return!U&&!o&&Cu.includes(pe)?(r=1,i.interrupt?n(E):L(E)):Y1.includes(l.toLowerCase())?(r=6,U?(e.consume(E),x):i.interrupt?n(E):L(E)):(r=7,i.interrupt&&!i.parser.lazy[i.now().line]?s(E):o?k(E):M(E))}return E===45||$n(E)?(e.consume(E),l+=String.fromCharCode(E),v):s(E)}function x(E){return E===62?(e.consume(E),i.interrupt?n:L):s(E)}function k(E){return It(E)?(e.consume(E),k):T(E)}function M(E){return E===47?(e.consume(E),T):E===58||E===95||qn(E)?(e.consume(E),y):It(E)?(e.consume(E),M):T(E)}function y(E){return E===45||E===46||E===58||E===95||$n(E)?(e.consume(E),y):R(E)}function R(E){return E===61?(e.consume(E),j):It(E)?(e.consume(E),R):M(E)}function j(E){return E===null||E===60||E===61||E===62||E===96?s(E):E===34||E===39?(e.consume(E),u=E,C):It(E)?(e.consume(E),j):S(E)}function C(E){return E===u?(e.consume(E),u=null,P):E===null||yt(E)?s(E):(e.consume(E),C)}function S(E){return E===null||E===34||E===39||E===47||E===60||E===61||E===62||E===96||Wt(E)?R(E):(e.consume(E),S)}function P(E){return E===47||E===62||It(E)?M(E):s(E)}function T(E){return E===62?(e.consume(E),_):s(E)}function _(E){return E===null||yt(E)?L(E):It(E)?(e.consume(E),_):s(E)}function L(E){return E===45&&r===2?(e.consume(E),w):E===60&&r===1?(e.consume(E),q):E===62&&r===4?(e.consume(E),z):E===63&&r===3?(e.consume(E),A):E===93&&r===5?(e.consume(E),B):yt(E)&&(r===6||r===7)?(e.exit("htmlFlowData"),e.check(X1,X,G)(E)):E===null||yt(E)?(e.exit("htmlFlowData"),G(E)):(e.consume(E),L)}function G(E){return e.check(Z1,$,X)(E)}function $(E){return e.enter("lineEnding"),e.consume(E),e.exit("lineEnding"),I}function I(E){return E===null||yt(E)?G(E):(e.enter("htmlFlowData"),L(E))}function w(E){return E===45?(e.consume(E),A):L(E)}function q(E){return E===47?(e.consume(E),l="",W):L(E)}function W(E){if(E===62){const U=l.toLowerCase();return Cu.includes(U)?(e.consume(E),z):L(E)}return qn(E)&&l.length<8?(e.consume(E),l+=String.fromCharCode(E),W):L(E)}function B(E){return E===93?(e.consume(E),A):L(E)}function A(E){return E===62?(e.consume(E),z):E===45&&r===2?(e.consume(E),A):L(E)}function z(E){return E===null||yt(E)?(e.exit("htmlFlowData"),X(E)):(e.consume(E),z)}function X(E){return e.exit("htmlFlow"),n(E)}}function n0(e,n,s){const i=this;return r;function r(l){return yt(l)?(e.enter("lineEnding"),e.consume(l),e.exit("lineEnding"),o):s(l)}function o(l){return i.parser.lazy[i.now().line]?s(l):n(l)}}function s0(e,n,s){return i;function i(r){return e.enter("lineEnding"),e.consume(r),e.exit("lineEnding"),e.attempt(sr,n,s)}}const i0={name:"htmlText",tokenize:a0};function a0(e,n,s){const i=this;let r,o,l;return c;function c(A){return e.enter("htmlText"),e.enter("htmlTextData"),e.consume(A),u}function u(A){return A===33?(e.consume(A),d):A===47?(e.consume(A),R):A===63?(e.consume(A),M):qn(A)?(e.consume(A),S):s(A)}function d(A){return A===45?(e.consume(A),m):A===91?(e.consume(A),o=0,f):qn(A)?(e.consume(A),k):s(A)}function m(A){return A===45?(e.consume(A),p):s(A)}function h(A){return A===null?s(A):A===45?(e.consume(A),g):yt(A)?(l=h,q(A)):(e.consume(A),h)}function g(A){return A===45?(e.consume(A),p):h(A)}function p(A){return A===62?w(A):A===45?g(A):h(A)}function f(A){const z="CDATA[";return A===z.charCodeAt(o++)?(e.consume(A),o===z.length?b:f):s(A)}function b(A){return A===null?s(A):A===93?(e.consume(A),v):yt(A)?(l=b,q(A)):(e.consume(A),b)}function v(A){return A===93?(e.consume(A),x):b(A)}function x(A){return A===62?w(A):A===93?(e.consume(A),x):b(A)}function k(A){return A===null||A===62?w(A):yt(A)?(l=k,q(A)):(e.consume(A),k)}function M(A){return A===null?s(A):A===63?(e.consume(A),y):yt(A)?(l=M,q(A)):(e.consume(A),M)}function y(A){return A===62?w(A):M(A)}function R(A){return qn(A)?(e.consume(A),j):s(A)}function j(A){return A===45||$n(A)?(e.consume(A),j):C(A)}function C(A){return yt(A)?(l=C,q(A)):It(A)?(e.consume(A),C):w(A)}function S(A){return A===45||$n(A)?(e.consume(A),S):A===47||A===62||Wt(A)?P(A):s(A)}function P(A){return A===47?(e.consume(A),w):A===58||A===95||qn(A)?(e.consume(A),T):yt(A)?(l=P,q(A)):It(A)?(e.consume(A),P):w(A)}function T(A){return A===45||A===46||A===58||A===95||$n(A)?(e.consume(A),T):_(A)}function _(A){return A===61?(e.consume(A),L):yt(A)?(l=_,q(A)):It(A)?(e.consume(A),_):P(A)}function L(A){return A===null||A===60||A===61||A===62||A===96?s(A):A===34||A===39?(e.consume(A),r=A,G):yt(A)?(l=L,q(A)):It(A)?(e.consume(A),L):(e.consume(A),$)}function G(A){return A===r?(e.consume(A),r=void 0,I):A===null?s(A):yt(A)?(l=G,q(A)):(e.consume(A),G)}function $(A){return A===null||A===34||A===39||A===60||A===61||A===96?s(A):A===47||A===62||Wt(A)?P(A):(e.consume(A),$)}function I(A){return A===47||A===62||Wt(A)?P(A):s(A)}function w(A){return A===62?(e.consume(A),e.exit("htmlTextData"),e.exit("htmlText"),n):s(A)}function q(A){return e.exit("htmlTextData"),e.enter("lineEnding"),e.consume(A),e.exit("lineEnding"),W}function W(A){return It(A)?Ft(e,B,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(A):B(A)}function B(A){return e.enter("htmlTextData"),l(A)}}const Ec={name:"labelEnd",resolveAll:c0,resolveTo:d0,tokenize:u0},r0={tokenize:m0},o0={tokenize:h0},l0={tokenize:p0};function c0(e){let n=-1;const s=[];for(;++n<e.length;){const i=e[n][1];if(s.push(e[n]),i.type==="labelImage"||i.type==="labelLink"||i.type==="labelEnd"){const r=i.type==="labelImage"?4:2;i.type="data",n+=r}}return e.length!==s.length&&ds(e,0,e.length,s),e}function d0(e,n){let s=e.length,i=0,r,o,l,c;for(;s--;)if(r=e[s][1],o){if(r.type==="link"||r.type==="labelLink"&&r._inactive)break;e[s][0]==="enter"&&r.type==="labelLink"&&(r._inactive=!0)}else if(l){if(e[s][0]==="enter"&&(r.type==="labelImage"||r.type==="labelLink")&&!r._balanced&&(o=s,r.type!=="labelLink")){i=2;break}}else r.type==="labelEnd"&&(l=s);const u={type:e[o][1].type==="labelLink"?"link":"image",start:{...e[o][1].start},end:{...e[e.length-1][1].end}},d={type:"label",start:{...e[o][1].start},end:{...e[l][1].end}},m={type:"labelText",start:{...e[o+i+2][1].end},end:{...e[l-2][1].start}};return c=[["enter",u,n],["enter",d,n]],c=ws(c,e.slice(o+1,o+i+3)),c=ws(c,[["enter",m,n]]),c=ws(c,po(n.parser.constructs.insideSpan.null,e.slice(o+i+4,l-3),n)),c=ws(c,[["exit",m,n],e[l-2],e[l-1],["exit",d,n]]),c=ws(c,e.slice(l+1)),c=ws(c,[["exit",u,n]]),ds(e,o,e.length,c),e}function u0(e,n,s){const i=this;let r=i.events.length,o,l;for(;r--;)if((i.events[r][1].type==="labelImage"||i.events[r][1].type==="labelLink")&&!i.events[r][1]._balanced){o=i.events[r][1];break}return c;function c(g){return o?o._inactive?h(g):(l=i.parser.defined.includes(Rs(i.sliceSerialize({start:o.end,end:i.now()}))),e.enter("labelEnd"),e.enter("labelMarker"),e.consume(g),e.exit("labelMarker"),e.exit("labelEnd"),u):s(g)}function u(g){return g===40?e.attempt(r0,m,l?m:h)(g):g===91?e.attempt(o0,m,l?d:h)(g):l?m(g):h(g)}function d(g){return e.attempt(l0,m,h)(g)}function m(g){return n(g)}function h(g){return o._balanced=!0,s(g)}}function m0(e,n,s){return i;function i(h){return e.enter("resource"),e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),r}function r(h){return Wt(h)?Da(e,o)(h):o(h)}function o(h){return h===41?m(h):up(e,l,c,"resourceDestination","resourceDestinationLiteral","resourceDestinationLiteralMarker","resourceDestinationRaw","resourceDestinationString",32)(h)}function l(h){return Wt(h)?Da(e,u)(h):m(h)}function c(h){return s(h)}function u(h){return h===34||h===39||h===40?hp(e,d,s,"resourceTitle","resourceTitleMarker","resourceTitleString")(h):m(h)}function d(h){return Wt(h)?Da(e,m)(h):m(h)}function m(h){return h===41?(e.enter("resourceMarker"),e.consume(h),e.exit("resourceMarker"),e.exit("resource"),n):s(h)}}function h0(e,n,s){const i=this;return r;function r(c){return mp.call(i,e,o,l,"reference","referenceMarker","referenceString")(c)}function o(c){return i.parser.defined.includes(Rs(i.sliceSerialize(i.events[i.events.length-1][1]).slice(1,-1)))?n(c):s(c)}function l(c){return s(c)}}function p0(e,n,s){return i;function i(o){return e.enter("reference"),e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),r}function r(o){return o===93?(e.enter("referenceMarker"),e.consume(o),e.exit("referenceMarker"),e.exit("reference"),n):s(o)}}const f0={name:"labelStartImage",resolveAll:Ec.resolveAll,tokenize:g0};function g0(e,n,s){const i=this;return r;function r(c){return e.enter("labelImage"),e.enter("labelImageMarker"),e.consume(c),e.exit("labelImageMarker"),o}function o(c){return c===91?(e.enter("labelMarker"),e.consume(c),e.exit("labelMarker"),e.exit("labelImage"),l):s(c)}function l(c){return c===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(c):n(c)}}const b0={name:"labelStartLink",resolveAll:Ec.resolveAll,tokenize:x0};function x0(e,n,s){const i=this;return r;function r(l){return e.enter("labelLink"),e.enter("labelMarker"),e.consume(l),e.exit("labelMarker"),e.exit("labelLink"),o}function o(l){return l===94&&"_hiddenFootnoteSupport"in i.parser.constructs?s(l):n(l)}}const Jo={name:"lineEnding",tokenize:v0};function v0(e,n){return s;function s(i){return e.enter("lineEnding"),e.consume(i),e.exit("lineEnding"),Ft(e,n,"linePrefix")}}const Rr={name:"thematicBreak",tokenize:y0};function y0(e,n,s){let i=0,r;return o;function o(d){return e.enter("thematicBreak"),l(d)}function l(d){return r=d,c(d)}function c(d){return d===r?(e.enter("thematicBreakSequence"),u(d)):i>=3&&(d===null||yt(d))?(e.exit("thematicBreak"),n(d)):s(d)}function u(d){return d===r?(e.consume(d),i++,u):(e.exit("thematicBreakSequence"),It(d)?Ft(e,c,"whitespace")(d):c(d))}}const Zn={continuation:{tokenize:N0},exit:C0,name:"list",tokenize:w0},k0={partial:!0,tokenize:E0},j0={partial:!0,tokenize:S0};function w0(e,n,s){const i=this,r=i.events[i.events.length-1];let o=r&&r[1].type==="linePrefix"?r[2].sliceSerialize(r[1],!0).length:0,l=0;return c;function c(p){const f=i.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(f==="listUnordered"?!i.containerState.marker||p===i.containerState.marker:Gl(p)){if(i.containerState.type||(i.containerState.type=f,e.enter(f,{_container:!0})),f==="listUnordered")return e.enter("listItemPrefix"),p===42||p===45?e.check(Rr,s,d)(p):d(p);if(!i.interrupt||p===49)return e.enter("listItemPrefix"),e.enter("listItemValue"),u(p)}return s(p)}function u(p){return Gl(p)&&++l<10?(e.consume(p),u):(!i.interrupt||l<2)&&(i.containerState.marker?p===i.containerState.marker:p===41||p===46)?(e.exit("listItemValue"),d(p)):s(p)}function d(p){return e.enter("listItemMarker"),e.consume(p),e.exit("listItemMarker"),i.containerState.marker=i.containerState.marker||p,e.check(sr,i.interrupt?s:m,e.attempt(k0,g,h))}function m(p){return i.containerState.initialBlankLine=!0,o++,g(p)}function h(p){return It(p)?(e.enter("listItemPrefixWhitespace"),e.consume(p),e.exit("listItemPrefixWhitespace"),g):s(p)}function g(p){return i.containerState.size=o+i.sliceSerialize(e.exit("listItemPrefix"),!0).length,n(p)}}function N0(e,n,s){const i=this;return i.containerState._closeFlow=void 0,e.check(sr,r,o);function r(c){return i.containerState.furtherBlankLines=i.containerState.furtherBlankLines||i.containerState.initialBlankLine,Ft(e,n,"listItemIndent",i.containerState.size+1)(c)}function o(c){return i.containerState.furtherBlankLines||!It(c)?(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,l(c)):(i.containerState.furtherBlankLines=void 0,i.containerState.initialBlankLine=void 0,e.attempt(j0,n,l)(c))}function l(c){return i.containerState._closeFlow=!0,i.interrupt=void 0,Ft(e,e.attempt(Zn,n,s),"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(c)}}function S0(e,n,s){const i=this;return Ft(e,r,"listItemIndent",i.containerState.size+1);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===i.containerState.size?n(o):s(o)}}function C0(e){e.exit(this.containerState.type)}function E0(e,n,s){const i=this;return Ft(e,r,"listItemPrefixWhitespace",i.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function r(o){const l=i.events[i.events.length-1];return!It(o)&&l&&l[1].type==="listItemPrefixWhitespace"?n(o):s(o)}}const Eu={name:"setextUnderline",resolveTo:M0,tokenize:_0};function M0(e,n){let s=e.length,i,r,o;for(;s--;)if(e[s][0]==="enter"){if(e[s][1].type==="content"){i=s;break}e[s][1].type==="paragraph"&&(r=s)}else e[s][1].type==="content"&&e.splice(s,1),!o&&e[s][1].type==="definition"&&(o=s);const l={type:"setextHeading",start:{...e[i][1].start},end:{...e[e.length-1][1].end}};return e[r][1].type="setextHeadingText",o?(e.splice(r,0,["enter",l,n]),e.splice(o+1,0,["exit",e[i][1],n]),e[i][1].end={...e[o][1].end}):e[i][1]=l,e.push(["exit",l,n]),e}function _0(e,n,s){const i=this;let r;return o;function o(d){let m=i.events.length,h;for(;m--;)if(i.events[m][1].type!=="lineEnding"&&i.events[m][1].type!=="linePrefix"&&i.events[m][1].type!=="content"){h=i.events[m][1].type==="paragraph";break}return!i.parser.lazy[i.now().line]&&(i.interrupt||h)?(e.enter("setextHeadingLine"),r=d,l(d)):s(d)}function l(d){return e.enter("setextHeadingLineSequence"),c(d)}function c(d){return d===r?(e.consume(d),c):(e.exit("setextHeadingLineSequence"),It(d)?Ft(e,u,"lineSuffix")(d):u(d))}function u(d){return d===null||yt(d)?(e.exit("setextHeadingLine"),n(d)):s(d)}}const A0={tokenize:T0};function T0(e){const n=this,s=e.attempt(sr,i,e.attempt(this.parser.constructs.flowInitial,r,Ft(e,e.attempt(this.parser.constructs.flow,r,e.attempt(D1,r)),"linePrefix")));return s;function i(o){if(o===null){e.consume(o);return}return e.enter("lineEndingBlank"),e.consume(o),e.exit("lineEndingBlank"),n.currentConstruct=void 0,s}function r(o){if(o===null){e.consume(o);return}return e.enter("lineEnding"),e.consume(o),e.exit("lineEnding"),n.currentConstruct=void 0,s}}const R0={resolveAll:fp()},I0=pp("string"),P0=pp("text");function pp(e){return{resolveAll:fp(e==="text"?$0:void 0),tokenize:n};function n(s){const i=this,r=this.parser.constructs[e],o=s.attempt(r,l,c);return l;function l(m){return d(m)?o(m):c(m)}function c(m){if(m===null){s.consume(m);return}return s.enter("data"),s.consume(m),u}function u(m){return d(m)?(s.exit("data"),o(m)):(s.consume(m),u)}function d(m){if(m===null)return!0;const h=r[m];let g=-1;if(h)for(;++g<h.length;){const p=h[g];if(!p.previous||p.previous.call(i,i.previous))return!0}return!1}}}function fp(e){return n;function n(s,i){let r=-1,o;for(;++r<=s.length;)o===void 0?s[r]&&s[r][1].type==="data"&&(o=r,r++):(!s[r]||s[r][1].type!=="data")&&(r!==o+2&&(s[o][1].end=s[r-1][1].end,s.splice(o+2,r-o-2),r=o+2),o=void 0);return e?e(s,i):s}}function $0(e,n){let s=0;for(;++s<=e.length;)if((s===e.length||e[s][1].type==="lineEnding")&&e[s-1][1].type==="data"){const i=e[s-1][1],r=n.sliceStream(i);let o=r.length,l=-1,c=0,u;for(;o--;){const d=r[o];if(typeof d=="string"){for(l=d.length;d.charCodeAt(l-1)===32;)c++,l--;if(l)break;l=-1}else if(d===-2)u=!0,c++;else if(d!==-1){o++;break}}if(n._contentTypeTextTrailing&&s===e.length&&(c=0),c){const d={type:s===e.length||u||c<2?"lineSuffix":"hardBreakTrailing",start:{_bufferIndex:o?l:i.start._bufferIndex+l,_index:i.start._index+o,line:i.end.line,column:i.end.column-c,offset:i.end.offset-c},end:{...i.end}};i.end={...d.start},i.start.offset===i.end.offset?Object.assign(i,d):(e.splice(s,0,["enter",d,n],["exit",d,n]),s+=2)}s++}return e}const D0={42:Zn,43:Zn,45:Zn,48:Zn,49:Zn,50:Zn,51:Zn,52:Zn,53:Zn,54:Zn,55:Zn,56:Zn,57:Zn,62:op},L0={91:U1},z0={[-2]:Ko,[-1]:Ko,32:Ko},F0={35:G1,42:Rr,45:[Eu,Rr],60:Q1,61:Eu,95:Rr,96:Su,126:Su},O0={38:cp,92:lp},U0={[-5]:Jo,[-4]:Jo,[-3]:Jo,33:f0,38:cp,42:Kl,60:[b1,i0],91:b0,92:[V1,lp],93:Ec,95:Kl,96:A1},B0={null:[Kl,R0]},H0={null:[42,95]},q0={null:[]},V0=Object.freeze(Object.defineProperty({__proto__:null,attentionMarkers:H0,contentInitial:L0,disable:q0,document:D0,flow:F0,flowInitial:z0,insideSpan:B0,string:O0,text:U0},Symbol.toStringTag,{value:"Module"}));function W0(e,n,s){let i={_bufferIndex:-1,_index:0,line:s&&s.line||1,column:s&&s.column||1,offset:s&&s.offset||0};const r={},o=[];let l=[],c=[];const u={attempt:C(R),check:C(j),consume:k,enter:M,exit:y,interrupt:C(j,{interrupt:!0})},d={code:null,containerState:{},defineSkip:b,events:[],now:f,parser:e,previous:null,sliceSerialize:g,sliceStream:p,write:h};let m=n.tokenize.call(d,u);return n.resolveAll&&o.push(n),d;function h(_){return l=ws(l,_),v(),l[l.length-1]!==null?[]:(S(n,0),d.events=po(o,d.events,d),d.events)}function g(_,L){return K0(p(_),L)}function p(_){return G0(l,_)}function f(){const{_bufferIndex:_,_index:L,line:G,column:$,offset:I}=i;return{_bufferIndex:_,_index:L,line:G,column:$,offset:I}}function b(_){r[_.line]=_.column,T()}function v(){let _;for(;i._index<l.length;){const L=l[i._index];if(typeof L=="string")for(_=i._index,i._bufferIndex<0&&(i._bufferIndex=0);i._index===_&&i._bufferIndex<L.length;)x(L.charCodeAt(i._bufferIndex));else x(L)}}function x(_){m=m(_)}function k(_){yt(_)?(i.line++,i.column=1,i.offset+=_===-3?2:1,T()):_!==-1&&(i.column++,i.offset++),i._bufferIndex<0?i._index++:(i._bufferIndex++,i._bufferIndex===l[i._index].length&&(i._bufferIndex=-1,i._index++)),d.previous=_}function M(_,L){const G=L||{};return G.type=_,G.start=f(),d.events.push(["enter",G,d]),c.push(G),G}function y(_){const L=c.pop();return L.end=f(),d.events.push(["exit",L,d]),L}function R(_,L){S(_,L.from)}function j(_,L){L.restore()}function C(_,L){return G;function G($,I,w){let q,W,B,A;return Array.isArray($)?X($):"tokenize"in $?X([$]):z($);function z(ie){return re;function re(F){const ce=F!==null&&ie[F],ae=F!==null&&ie.null,Q=[...Array.isArray(ce)?ce:ce?[ce]:[],...Array.isArray(ae)?ae:ae?[ae]:[]];return X(Q)(F)}}function X(ie){return q=ie,W=0,ie.length===0?w:E(ie[W])}function E(ie){return re;function re(F){return A=P(),B=ie,ie.partial||(d.currentConstruct=ie),ie.name&&d.parser.constructs.disable.null.includes(ie.name)?pe():ie.tokenize.call(L?Object.assign(Object.create(d),L):d,u,U,pe)(F)}}function U(ie){return _(B,A),I}function pe(ie){return A.restore(),++W<q.length?E(q[W]):w}}}function S(_,L){_.resolveAll&&!o.includes(_)&&o.push(_),_.resolve&&ds(d.events,L,d.events.length-L,_.resolve(d.events.slice(L),d)),_.resolveTo&&(d.events=_.resolveTo(d.events,d))}function P(){const _=f(),L=d.previous,G=d.currentConstruct,$=d.events.length,I=Array.from(c);return{from:$,restore:w};function w(){i=_,d.previous=L,d.currentConstruct=G,d.events.length=$,c=I,T()}}function T(){i.line in r&&i.column<2&&(i.column=r[i.line],i.offset+=r[i.line]-1)}}function G0(e,n){const s=n.start._index,i=n.start._bufferIndex,r=n.end._index,o=n.end._bufferIndex;let l;if(s===r)l=[e[s].slice(i,o)];else{if(l=e.slice(s,r),i>-1){const c=l[0];typeof c=="string"?l[0]=c.slice(i):l.shift()}o>0&&l.push(e[r].slice(0,o))}return l}function K0(e,n){let s=-1;const i=[];let r;for(;++s<e.length;){const o=e[s];let l;if(typeof o=="string")l=o;else switch(o){case-5:{l="\r";break}case-4:{l=`
|
|
@@ -602,7 +602,7 @@ Delete anyway by removing these dependency references first?`)&&d(e.id,{removeDe
|
|
|
602
602
|
`))+1))}const l="#".repeat(r),c=s.enter("headingAtx"),u=s.enter("phrasing");o.move(l+" ");let d=s.containerPhrasing(e,{before:"# ",after:`
|
|
603
603
|
`,...o.current()});return/^[\t ]/.test(d)&&(d=Va(d.charCodeAt(0))+d.slice(1)),d=d?l+" "+d:l,s.options.closeAtx&&(d+=" "+l),u(),c(),d}Tp.peek=N2;function Tp(e){return e.value||""}function N2(){return"<"}Rp.peek=S2;function Rp(e,n,s,i){const r=Pc(s),o=r==='"'?"Quote":"Apostrophe",l=s.enter("image");let c=s.enter("label");const u=s.createTracker(i);let d=u.move("![");return d+=u.move(s.safe(e.alt,{before:d,after:"]",...u.current()})),d+=u.move("]("),c(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(c=s.enter("destinationLiteral"),d+=u.move("<"),d+=u.move(s.safe(e.url,{before:d,after:">",...u.current()})),d+=u.move(">")):(c=s.enter("destinationRaw"),d+=u.move(s.safe(e.url,{before:d,after:e.title?" ":")",...u.current()}))),c(),e.title&&(c=s.enter(`title${o}`),d+=u.move(" "+r),d+=u.move(s.safe(e.title,{before:d,after:r,...u.current()})),d+=u.move(r),c()),d+=u.move(")"),l(),d}function S2(){return"!"}Ip.peek=C2;function Ip(e,n,s,i){const r=e.referenceType,o=s.enter("imageReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("![");const d=s.safe(e.alt,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function C2(){return"!"}Pp.peek=E2;function Pp(e,n,s){let i=e.value||"",r="`",o=-1;for(;new RegExp("(^|[^`])"+r+"([^`]|$)").test(i);)r+="`";for(/[^ \r\n]/.test(i)&&(/^[ \r\n]/.test(i)&&/[ \r\n]$/.test(i)||/^`|`$/.test(i))&&(i=" "+i+" ");++o<s.unsafe.length;){const l=s.unsafe[o],c=s.compilePattern(l);let u;if(l.atBreak)for(;u=c.exec(i);){let d=u.index;i.charCodeAt(d)===10&&i.charCodeAt(d-1)===13&&d--,i=i.slice(0,d)+" "+i.slice(u.index+1)}}return r+i+r}function E2(){return"`"}function $p(e,n){const s=Sc(e);return!!(!n.options.resourceLink&&e.url&&!e.title&&e.children&&e.children.length===1&&e.children[0].type==="text"&&(s===e.url||"mailto:"+s===e.url)&&/^[a-z][a-z+.-]+:/i.test(e.url)&&!/[\0- <>\u007F]/.test(e.url))}Dp.peek=M2;function Dp(e,n,s,i){const r=Pc(s),o=r==='"'?"Quote":"Apostrophe",l=s.createTracker(i);let c,u;if($p(e,s)){const m=s.stack;s.stack=[],c=s.enter("autolink");let h=l.move("<");return h+=l.move(s.containerPhrasing(e,{before:h,after:">",...l.current()})),h+=l.move(">"),c(),s.stack=m,h}c=s.enter("link"),u=s.enter("label");let d=l.move("[");return d+=l.move(s.containerPhrasing(e,{before:d,after:"](",...l.current()})),d+=l.move("]("),u(),!e.url&&e.title||/[\0- \u007F]/.test(e.url)?(u=s.enter("destinationLiteral"),d+=l.move("<"),d+=l.move(s.safe(e.url,{before:d,after:">",...l.current()})),d+=l.move(">")):(u=s.enter("destinationRaw"),d+=l.move(s.safe(e.url,{before:d,after:e.title?" ":")",...l.current()}))),u(),e.title&&(u=s.enter(`title${o}`),d+=l.move(" "+r),d+=l.move(s.safe(e.title,{before:d,after:r,...l.current()})),d+=l.move(r),u()),d+=l.move(")"),c(),d}function M2(e,n,s){return $p(e,s)?"<":"["}Lp.peek=_2;function Lp(e,n,s,i){const r=e.referenceType,o=s.enter("linkReference");let l=s.enter("label");const c=s.createTracker(i);let u=c.move("[");const d=s.containerPhrasing(e,{before:u,after:"]",...c.current()});u+=c.move(d+"]["),l();const m=s.stack;s.stack=[],l=s.enter("reference");const h=s.safe(s.associationId(e),{before:u,after:"]",...c.current()});return l(),s.stack=m,o(),r==="full"||!d||d!==h?u+=c.move(h+"]"):r==="shortcut"?u=u.slice(0,-1):u+=c.move("]"),u}function _2(){return"["}function $c(e){const n=e.options.bullet||"*";if(n!=="*"&&n!=="+"&&n!=="-")throw new Error("Cannot serialize items with `"+n+"` for `options.bullet`, expected `*`, `+`, or `-`");return n}function A2(e){const n=$c(e),s=e.options.bulletOther;if(!s)return n==="*"?"-":"*";if(s!=="*"&&s!=="+"&&s!=="-")throw new Error("Cannot serialize items with `"+s+"` for `options.bulletOther`, expected `*`, `+`, or `-`");if(s===n)throw new Error("Expected `bullet` (`"+n+"`) and `bulletOther` (`"+s+"`) to be different");return s}function T2(e){const n=e.options.bulletOrdered||".";if(n!=="."&&n!==")")throw new Error("Cannot serialize items with `"+n+"` for `options.bulletOrdered`, expected `.` or `)`");return n}function zp(e){const n=e.options.rule||"*";if(n!=="*"&&n!=="-"&&n!=="_")throw new Error("Cannot serialize rules with `"+n+"` for `options.rule`, expected `*`, `-`, or `_`");return n}function R2(e,n,s,i){const r=s.enter("list"),o=s.bulletCurrent;let l=e.ordered?T2(s):$c(s);const c=e.ordered?l==="."?")":".":A2(s);let u=n&&s.bulletLastUsed?l===s.bulletLastUsed:!1;if(!e.ordered){const m=e.children?e.children[0]:void 0;if((l==="*"||l==="-")&&m&&(!m.children||!m.children[0])&&s.stack[s.stack.length-1]==="list"&&s.stack[s.stack.length-2]==="listItem"&&s.stack[s.stack.length-3]==="list"&&s.stack[s.stack.length-4]==="listItem"&&s.indexStack[s.indexStack.length-1]===0&&s.indexStack[s.indexStack.length-2]===0&&s.indexStack[s.indexStack.length-3]===0&&(u=!0),zp(s)===l&&m){let h=-1;for(;++h<e.children.length;){const g=e.children[h];if(g&&g.type==="listItem"&&g.children&&g.children[0]&&g.children[0].type==="thematicBreak"){u=!0;break}}}}u&&(l=c),s.bulletCurrent=l;const d=s.containerFlow(e,i);return s.bulletLastUsed=l,s.bulletCurrent=o,r(),d}function I2(e){const n=e.options.listItemIndent||"one";if(n!=="tab"&&n!=="one"&&n!=="mixed")throw new Error("Cannot serialize items with `"+n+"` for `options.listItemIndent`, expected `tab`, `one`, or `mixed`");return n}function P2(e,n,s,i){const r=I2(s);let o=s.bulletCurrent||$c(s);n&&n.type==="list"&&n.ordered&&(o=(typeof n.start=="number"&&n.start>-1?n.start:1)+(s.options.incrementListMarker===!1?0:n.children.indexOf(e))+o);let l=o.length+1;(r==="tab"||r==="mixed"&&(n&&n.type==="list"&&n.spread||e.spread))&&(l=Math.ceil(l/4)*4);const c=s.createTracker(i);c.move(o+" ".repeat(l-o.length)),c.shift(l);const u=s.enter("listItem"),d=s.indentLines(s.containerFlow(e,c.current()),m);return u(),d;function m(h,g,p){return g?(p?"":" ".repeat(l))+h:(p?o:o+" ".repeat(l-o.length))+h}}function $2(e,n,s,i){const r=s.enter("paragraph"),o=s.enter("phrasing"),l=s.containerPhrasing(e,i);return o(),r(),l}const D2=go(["break","delete","emphasis","footnote","footnoteReference","image","imageReference","inlineCode","inlineMath","link","linkReference","mdxJsxTextElement","mdxTextExpression","strong","text","textDirective"]);function L2(e,n,s,i){return(e.children.some(function(l){return D2(l)})?s.containerPhrasing:s.containerFlow).call(s,e,i)}function z2(e){const n=e.options.strong||"*";if(n!=="*"&&n!=="_")throw new Error("Cannot serialize strong with `"+n+"` for `options.strong`, expected `*`, or `_`");return n}Fp.peek=F2;function Fp(e,n,s,i){const r=z2(s),o=s.enter("strong"),l=s.createTracker(i),c=l.move(r+r);let u=l.move(s.containerPhrasing(e,{after:r,before:c,...l.current()}));const d=u.charCodeAt(0),m=Jr(i.before.charCodeAt(i.before.length-1),d,r);m.inside&&(u=Va(d)+u.slice(1));const h=u.charCodeAt(u.length-1),g=Jr(i.after.charCodeAt(0),h,r);g.inside&&(u=u.slice(0,-1)+Va(h));const p=l.move(r+r);return o(),s.attentionEncodeSurroundingInfo={after:g.outside,before:m.outside},c+u+p}function F2(e,n,s){return s.options.strong||"*"}function O2(e,n,s,i){return s.safe(e.value,i)}function U2(e){const n=e.options.ruleRepetition||3;if(n<3)throw new Error("Cannot serialize rules with repetition `"+n+"` for `options.ruleRepetition`, expected `3` or more");return n}function B2(e,n,s){const i=(zp(s)+(s.options.ruleSpaces?" ":"")).repeat(U2(s));return s.options.ruleSpaces?i.slice(0,-1):i}const Op={blockquote:u2,break:Ku,code:b2,definition:v2,emphasis:Ap,hardBreak:Ku,heading:w2,html:Tp,image:Rp,imageReference:Ip,inlineCode:Pp,link:Dp,linkReference:Lp,list:R2,listItem:P2,paragraph:$2,root:L2,strong:Fp,text:O2,thematicBreak:B2};function H2(){return{enter:{table:q2,tableData:Ju,tableHeader:Ju,tableRow:W2},exit:{codeText:G2,table:V2,tableData:ol,tableHeader:ol,tableRow:ol}}}function q2(e){const n=e._align;this.enter({type:"table",align:n.map(function(s){return s==="none"?null:s}),children:[]},e),this.data.inTable=!0}function V2(e){this.exit(e),this.data.inTable=void 0}function W2(e){this.enter({type:"tableRow",children:[]},e)}function ol(e){this.exit(e)}function Ju(e){this.enter({type:"tableCell",children:[]},e)}function G2(e){let n=this.resume();this.data.inTable&&(n=n.replace(/\\([\\|])/g,K2));const s=this.stack[this.stack.length-1];s.type,s.value=n,this.exit(e)}function K2(e,n){return n==="|"?n:e}function J2(e){const n=e||{},s=n.tableCellPadding,i=n.tablePipeAlign,r=n.stringLength,o=s?" ":"|";return{unsafe:[{character:"\r",inConstruct:"tableCell"},{character:`
|
|
604
604
|
`,inConstruct:"tableCell"},{atBreak:!0,character:"|",after:"[ :-]"},{character:"|",inConstruct:"tableCell"},{atBreak:!0,character:":",after:"-"},{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{inlineCode:g,table:l,tableCell:u,tableRow:c}};function l(p,f,b,v){return d(m(p,b,v),p.align)}function c(p,f,b,v){const x=h(p,b,v),k=d([x]);return k.slice(0,k.indexOf(`
|
|
605
|
-
`))}function u(p,f,b,v){const x=b.enter("tableCell"),k=b.enter("phrasing"),M=b.containerPhrasing(p,{...v,before:o,after:o});return k(),x(),M}function d(p,f){return c2(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,b){const v=p.children;let x=-1;const k=[],M=f.enter("table");for(;++x<v.length;)k[x]=h(v[x],f,b);return M(),k}function h(p,f,b){const v=p.children;let x=-1;const k=[],M=f.enter("tableRow");for(;++x<v.length;)k[x]=u(v[x],p,f,b);return M(),k}function g(p,f,b){let v=Op.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function Y2(){return{exit:{taskListCheckValueChecked:Yu,taskListCheckValueUnchecked:Yu,paragraph:X2}}}function Q2(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Z2}}}function Yu(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function X2(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const s=this.stack[this.stack.length-1];s.type;const i=s.children[0];if(i&&i.type==="text"){const r=n.children;let o=-1,l;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){l=c;break}}l===s&&(i.value=i.value.slice(1),i.value.length===0?s.children.shift():s.position&&i.position&&typeof i.position.start.offset=="number"&&(i.position.start.column++,i.position.start.offset++,s.position.start=Object.assign({},i.position.start)))}}this.exit(e)}function Z2(e,n,s,i){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(i);o&&c.move(l);let u=Op.listItem(e,n,s,{...i,...c.current()});return o&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,d)),u;function d(m){return m+l}}function eE(){return[RC(),ZC(),s2(),H2(),Y2()]}function tE(e){return{extensions:[IC(),e2(e),i2(),J2(e),Q2()]}}const nE={tokenize:lE,partial:!0},Up={tokenize:cE,partial:!0},Bp={tokenize:dE,partial:!0},Hp={tokenize:uE,partial:!0},sE={tokenize:mE,partial:!0},qp={name:"wwwAutolink",tokenize:rE,previous:Wp},Vp={name:"protocolAutolink",tokenize:oE,previous:Gp},Zs={name:"emailAutolink",tokenize:aE,previous:Kp},Vs={};function iE(){return{text:Vs}}let bi=48;for(;bi<123;)Vs[bi]=Zs,bi++,bi===58?bi=65:bi===91&&(bi=97);Vs[43]=Zs;Vs[45]=Zs;Vs[46]=Zs;Vs[95]=Zs;Vs[72]=[Zs,Vp];Vs[104]=[Zs,Vp];Vs[87]=[Zs,qp];Vs[119]=[Zs,qp];function aE(e,n,s){const i=this;let r,o;return l;function l(h){return!Zl(h)||!Kp.call(i,i.previous)||Dc(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Zl(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(sE,m,d)(h):h===45||h===95||$n(h)?(o=!0,e.consume(h),u):m(h)}function d(h){return e.consume(h),r=!0,u}function m(h){return o&&r&&qn(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function rE(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Wp.call(i,i.previous)||Dc(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(nE,e.attempt(Up,e.attempt(Bp,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function oE(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Gp.call(i,i.previous)&&!Dc(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(qn(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||Wr(h)||Wt(h)||Ei(h)||ho(h)?s(h):e.attempt(Up,e.attempt(Bp,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function lE(e,n,s){let i=0;return r;function r(l){return(l===87||l===119)&&i<3?(i++,e.consume(l),r):l===46&&i===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function cE(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Hp,u,c)(d):d===null||Wt(d)||Ei(d)||d!==45&&ho(d)?u(d):(o=!0,e.consume(d),l)}function c(d){return d===95?i=!0:(r=i,i=void 0),e.consume(d),l}function u(d){return r||i||!o?s(d):n(d)}}function dE(e,n){let s=0,i=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&i<s?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(Hp,n,o)(l):l===null||Wt(l)||Ei(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function uE(e,n,s){return i;function i(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||Wt(c)||Ei(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Wt(c)||Ei(c)?n(c):i(c)}function o(c){return qn(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):qn(c)?(e.consume(c),l):s(c)}}function mE(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return $n(o)?s(o):n(o)}}function Wp(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Wt(e)}function Gp(e){return!qn(e)}function Kp(e){return!(e===47||Zl(e))}function Zl(e){return e===43||e===45||e===46||e===95||$n(e)}function Dc(e){let n=e.length,s=!1;for(;n--;){const i=e[n][1];if((i.type==="labelLink"||i.type==="labelImage")&&!i._balanced){s=!0;break}if(i._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const hE={tokenize:kE,partial:!0};function pE(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:xE,continuation:{tokenize:vE},exit:yE}},text:{91:{name:"gfmFootnoteCall",tokenize:bE},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:fE,resolveTo:gE}}}}function fE(e,n,s){const i=this;let r=i.events.length;const o=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l;for(;r--;){const u=i.events[r][1];if(u.type==="labelImage"){l=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return c;function c(u){if(!l||!l._balanced)return s(u);const d=Rs(i.sliceSerialize({start:l.end,end:i.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?s(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),n(u))}}function gE(e,n){let s=e.length;for(;s--;)if(e[s][1].type==="labelImage"&&e[s][0]==="enter"){e[s][1];break}e[s+1][1].type="data",e[s+3][1].type="gfmFootnoteCallLabelMarker";const i={type:"gfmFootnoteCall",start:Object.assign({},e[s+3][1].start),end:Object.assign({},e[e.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},e[s+3][1].end),end:Object.assign({},e[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[s+1],e[s+2],["enter",i,n],e[s+3],e[s+4],["enter",r,n],["exit",r,n],["enter",o,n],["enter",l,n],["exit",l,n],["exit",o,n],e[e.length-2],e[e.length-1],["exit",i,n]];return e.splice(s,e.length-s+1,...c),e}function bE(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),u}function u(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(h){if(o>999||h===93&&!l||h===null||h===91||Wt(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Rs(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Wt(h)||(l=!0),o++,e.consume(h),h===92?m:d}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,d):d(h)}}function xE(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(f)}function m(f){if(l>999||f===93&&!c||f===null||f===91||Wt(f))return s(f);if(f===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=Rs(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return Wt(f)||(c=!0),l++,e.consume(f),f===92?h:m}function h(f){return f===91||f===92||f===93?(e.consume(f),l++,m):m(f)}function g(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),r.includes(o)||r.push(o),Ft(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function vE(e,n,s){return e.check(sr,n,e.attempt(hE,n,s))}function yE(e){e.exit("gfmFootnoteDefinition")}function kE(e,n,s){const i=this;return Ft(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function jE(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},g=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&ds(g,g.length,0,po(p,l.slice(d+1,u),c)),ds(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),ds(l,d-1,u-d+3,g),u=d+g.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return g;function g(f){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(f):(l.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const b=Qi(d);if(f===126)return h>1?u(f):(l.consume(f),h++,p);if(h<2&&!s)return u(f);const v=l.exit("strikethroughSequenceTemporary"),x=Qi(f);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(f)}}}class wE{constructor(){this.map=[]}add(n,s,i){NE(this,n,s,i)}consume(n){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let s=this.map.length;const i=[];for(;s>0;)s-=1,i.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];i.push(n.slice()),n.length=0;let r=i.pop();for(;r;){for(const o of r)n.push(o);r=i.pop()}this.map.length=0}}function NE(e,n,s,i){let r=0;if(!(s===0&&i.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...i);return}r+=1}e.map.push([n,s,i])}}function SE(e,n){let s=!1;const i=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&i.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=i.length-1;i[o]=i[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return i}function CE(){return{flow:{null:{name:"table",tokenize:EE,resolveAll:ME}}}}function EE(e,n,s){const i=this;let r=0,o=0,l;return c;function c(T){let _=i.events.length-1;for(;_>-1;){const $=i.events[_][1].type;if($==="lineEnding"||$==="linePrefix")_--;else break}const L=_>-1?i.events[_][1].type:null,G=L==="tableHead"||L==="tableRow"?j:u;return G===j&&i.parser.lazy[i.now().line]?s(T):G(T)}function u(T){return e.enter("tableHead"),e.enter("tableRow"),d(T)}function d(T){return T===124||(l=!0,o+=1),m(T)}function m(T){return T===null?s(T):yt(T)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),p):s(T):It(T)?Ft(e,m,"whitespace")(T):(o+=1,l&&(l=!1,r+=1),T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(T)))}function h(T){return T===null||T===124||Wt(T)?(e.exit("data"),m(T)):(e.consume(T),T===92?g:h)}function g(T){return T===92||T===124?(e.consume(T),h):h(T)}function p(T){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(T):(e.enter("tableDelimiterRow"),l=!1,It(T)?Ft(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):f(T))}function f(T){return T===45||T===58?v(T):T===124?(l=!0,e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),b):R(T)}function b(T){return It(T)?Ft(e,v,"whitespace")(T):v(T)}function v(T){return T===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),x):T===45?(o+=1,x(T)):T===null||yt(T)?y(T):R(T)}function x(T){return T===45?(e.enter("tableDelimiterFiller"),k(T)):R(T)}function k(T){return T===45?(e.consume(T),k):T===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),M):(e.exit("tableDelimiterFiller"),M(T))}function M(T){return It(T)?Ft(e,y,"whitespace")(T):y(T)}function y(T){return T===124?f(T):T===null||yt(T)?!l||r!==o?R(T):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(T)):R(T)}function R(T){return s(T)}function j(T){return e.enter("tableRow"),C(T)}function C(T){return T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),C):T===null||yt(T)?(e.exit("tableRow"),n(T)):It(T)?Ft(e,C,"whitespace")(T):(e.enter("data"),S(T))}function S(T){return T===null||T===124||Wt(T)?(e.exit("data"),C(T)):(e.consume(T),T===92?P:S)}function P(T){return T===92||T===124?(e.consume(T),S):S(T)}}function ME(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const g=new wE;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Qu(g,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",d,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",m,n]])),r=f.type==="tableDelimiterRow"?2:m?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=jr(g,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=jr(g,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):f.type==="tableHead"?(c=!0,u=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=jr(g,n,o,r,s,h)):l[1]!==0&&(h=jr(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Qu(g,n,u,d,m),g.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=SE(n.events,s))}return e}function jr(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Ui(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=Ui(n.events,s[1]);if(o={type:l,start:Object.assign({},u),end:Object.assign({},u)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const d=Ui(n.events,s[2]),m=Ui(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const g=n.events[s[2]],p=n.events[s[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const f=s[2]+1,b=s[3]-s[2]-1;e.add(f,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},Ui(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Qu(e,n,s,i,r){const o=[],l=Ui(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),i.end=Object.assign({},l),o.push(["exit",i,n]),e.add(s+1,0,o)}function Ui(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const _E={name:"tasklistCheck",tokenize:TE};function AE(){return{text:{91:_E}}}function TE(e,n,s){const i=this;return r;function r(u){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?s(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return Wt(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),l):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),l):s(u)}function l(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(u)}function c(u){return yt(u)?n(u):It(u)?e.check({tokenize:RE},n,s)(u):s(u)}}function RE(e,n,s){return Ft(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function IE(e){return ap([iE(),pE(),jE(e),CE(),AE()])}const PE={};function Xs(e){const n=this,s=e||PE,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(IE(s)),o.push(eE()),l.push(tE(s))}const Xu=500,Zu=100;function ll(e){return e.length>Xu?e.slice(-Xu):e}function Jp(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),k=a.useRef(n),M=a.useRef(0);(v.current!==e||x.current!==s||k.current!==n)&&(v.current=e,x.current=s,k.current=n,b.current++,f.current=!0,r([]),l(!1),u(!1),m(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const C=b.current,S=++M.current;f.current=!1;const P=e,T=s;async function _(){if(!P)return;l(!0),g(!1);try{const G=await td(P,T,{limit:Zu});if(f.current||b.current!==C||M.current!==S)return;r(ll(G.entries)),u(G.hasMore),m(G.total)}catch{if(f.current||b.current!==C||M.current!==S)return;r([]),u(!1),m(null)}finally{!f.current&&b.current===C&&M.current===S&&l(!1)}const L=T?`?projectId=${encodeURIComponent(T)}`:"";p.current=qs(`/api/tasks/${P}/logs/stream${L}`,{events:{"agent:log":G=>{if(!(f.current||b.current!==C))try{const $=JSON.parse(G.data);r(I=>ll([...I,$])),m(I=>I!==null?I+1:null)}catch{}}}})}return _(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const R=a.useCallback(async()=>{if(!e||h)return;const C=b.current,S=i.length,P=e;g(!0);try{const T=await td(P,s,{limit:Zu,offset:S});if(f.current||b.current!==C)return;r(_=>{const L=[...T.entries,..._];return ll(L)}),u(T.hasMore),m(T.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),j=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:j,loadMore:R,hasMore:c,total:d,loadingMore:h}}function $E(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}const em={pre:({children:e,...n})=>t.jsx("pre",{...n,style:{overflowX:"auto",maxWidth:"100%",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:e}),table:({children:e,...n})=>t.jsx("table",{...n,style:{display:"block",overflowX:"auto",maxWidth:"100%"},children:e})},DE=50;function Yp(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function LE(e){const n=new Map;return e.map(s=>{const i=Yp(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function zE({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),g=a.useRef(null),[p,f]=a.useState(!0),[b,v]=a.useState(!1),[x,k]=a.useState(!1),M=a.useMemo(()=>LE(e),[e]);a.useLayoutEffect(()=>{const _=d.current;if(!_)return;const L=e.length,G=m.current,$=h.current,I=M[M.length-1]??null,w=g.current!==I;if(L>G){const q=_.scrollTop<=DE;if(w)if(q)_.scrollTop=0;else{const W=_.scrollHeight-$;W>0&&(_.scrollTop+=W)}}m.current=L,h.current=_.scrollHeight,g.current=I},[e,M]);const y=a.useCallback(_=>{_.key==="Escape"&&b&&v(!1)},[b]);if(a.useEffect(()=>{if(b)return document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)}},[b,y]),n&&e.length===0)return t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})});if(e.length===0)return t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})});const R=[...e].reverse(),j=[...M].reverse(),C=s?.provider&&s?.modelId,S=i?.provider&&i?.modelId,P=r?.provider&&r?.modelId,T=a.useMemo(()=>{const _=[];return C&&_.push({role:"Executor",provider:s.provider,modelId:s.modelId}),S&&_.push({role:"Validator",provider:i.provider,modelId:i.modelId}),P&&_.push({role:"Planning",provider:r.provider,modelId:r.modelId}),_},[C,s,S,i,P,r]);return t.jsxs("div",{ref:d,className:`agent-log-viewer agent-log-viewer--streaming${b?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[T.map(_=>t.jsx(Mn,{provider:_.provider,size:"sm"},`${_.role}-${_.provider}-${_.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>k(_=>!_),"aria-label":x?"Collapse model details":"Expand model details","aria-expanded":x,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:x?t.jsx(zt,{size:14}):t.jsx(en,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>f(_=>!_),"aria-label":p?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":p,"data-testid":"agent-log-mode-toggle",title:p?"Show raw text":"Show formatted markdown",children:p?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>v(_=>!_),"aria-label":b?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:b?"Exit full screen":"Expand agent log to full screen",children:b?t.jsx(aa,{size:14}):t.jsx(io,{size:14})})]}),x&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),C?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{provider:s.provider,size:"sm"}),t.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Validator:"}),S?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{provider:i.provider,size:"sm"}),t.jsxs("span",{children:[i.provider,"/",i.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning/Triage:"}),P?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),R.map((_,L)=>{const G=j[L]??`${Yp(_)}|fallback`,$=R[L-1],I=_.type==="tool"||_.type==="tool_result"||_.type==="tool_error",w=_.agent?I||L===0||$&&($.agent!==_.agent||$.type!==_.type):!1,q=w?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:$E(_.timestamp)}):null,W=w?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",_.agent,"]"]}),q]}):null;return _.type==="tool"?t.jsxs("div",{className:"agent-log-tool",children:[W,"⚡ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):_.type==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[W,p?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:em,children:_.text})}):_.text]},G):_.type==="tool_result"?t.jsxs("div",{className:"agent-log-tool-result",children:[W,"✓ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):_.type==="tool_error"?t.jsxs("div",{className:"agent-log-tool-error",children:[W,"✗ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):t.jsxs("div",{className:"agent-log-text",children:[W,p?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:em,children:_.text})}):_.text]},G)}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})})]})}function Xi(e){return e??void 0}function wr(e){return{provider:Xi(e.modelProvider),modelId:Xi(e.modelId)}}function Nr(e){return{provider:Xi(e.validatorModelProvider),modelId:Xi(e.validatorModelId)}}function Sr(e){return{provider:Xi(e.planningModelProvider),modelId:Xi(e.planningModelId)}}function FE(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function OE(e,n){return e.validatorModelProvider&&e.validatorModelId?{provider:e.validatorModelProvider,modelId:e.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function UE(e,n){return e.planningModelProvider&&e.planningModelId?{provider:e.planningModelProvider,modelId:e.planningModelId}:n?.planningProvider&&n.planningModelId?{provider:n.planningProvider,modelId:n.planningModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function cl(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return{provider:e.slice(0,n),modelId:e.slice(n+1)}}function dl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function ul(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function BE(e,n){const i={executor:"Executor",validator:"Validator",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function HE({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(()=>wr(e)),[v,x]=a.useState(()=>wr(e)),[k,M]=a.useState(()=>Nr(e)),[y,R]=a.useState(()=>Nr(e)),[j,C]=a.useState(()=>Sr(e)),[S,P]=a.useState(()=>Sr(e)),[T,_]=a.useState(()=>e.thinkingLevel??null),[L,G]=a.useState(()=>e.thinkingLevel??null),[$,I]=a.useState(null),w=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),is().then(fe=>{o(fe.models),c(fe.favoriteProviders),d(fe.favoriteModels)}).catch(fe=>{p(fe.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const q=a.useCallback(async fe=>{const Se=l,we=Se.includes(fe)?Se.filter(Pe=>Pe!==fe):[fe,...Se];c(we);try{await nn({favoriteProviders:we,favoriteModels:u})}catch{c(Se),n("Failed to update favorites","error")}},[l,u,n]),W=a.useCallback(async fe=>{const Se=u,we=Se.includes(fe)?Se.filter(Pe=>Pe!==fe):[fe,...Se];d(we);try{await nn({favoriteProviders:l,favoriteModels:we})}catch{d(Se),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{w.current=e.id;const fe=wr(e),Se=Nr(e),te=Sr(e);b(fe),x(fe),M(Se),R(Se),C(te),P(te);const we=e.thinkingLevel??null;_(we),G(we),I(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const B=a.useMemo(()=>dl(f),[f]),A=a.useMemo(()=>dl(k),[k]),z=a.useMemo(()=>dl(j),[j]),X=a.useMemo(()=>FE(e,i),[e,i]),E=a.useMemo(()=>OE(e,i),[e,i]),U=a.useMemo(()=>UE(e,i),[e,i]),pe=$!==null,ie=a.useCallback(async(fe,Se)=>{const te=e.id,we=v,Pe=y,We=S;I(fe);try{const Ke=s?fe==="executor"?{modelProvider:Se.provider??null,modelId:Se.modelId??null}:fe==="validator"?{validatorModelProvider:Se.provider??null,validatorModelId:Se.modelId??null}:{planningModelProvider:Se.provider??null,planningModelId:Se.modelId??null}:{modelProvider:(fe==="executor"?Se:v).provider??null,modelId:(fe==="executor"?Se:v).modelId??null,validatorModelProvider:(fe==="validator"?Se:y).provider??null,validatorModelId:(fe==="validator"?Se:y).modelId??null,planningModelProvider:(fe==="planning"?Se:S).provider??null,planningModelId:(fe==="planning"?Se:S).modelId??null},Ne=await Ks(te,Ke);if(w.current!==te)return;const _e=wr(Ne),Oe=Nr(Ne),ye=Sr(Ne);x(_e),b(_e),R(Oe),M(Oe),P(ye),C(ye),s?.(Ne),n(BE(fe,{executor:_e,validator:Oe,planning:ye}[fe]),"success")}catch(Ke){if(w.current!==te)return;fe==="executor"?b(we):fe==="validator"?M(Pe):C(We),n(xe(Ke)||"Failed to save model settings","error")}finally{w.current===te&&I(null)}},[e.id,v,y,S,n,s]),re=a.useCallback(fe=>{const Se=cl(fe);b(Se),!ul(Se,v)&&ie("executor",Se)},[v,ie]),F=a.useCallback(fe=>{const Se=cl(fe);M(Se),!ul(Se,y)&&ie("validator",Se)},[y,ie]),ce=a.useCallback(fe=>{const Se=cl(fe);C(Se),!ul(Se,S)&&ie("planning",Se)},[S,ie]),ae=a.useCallback(async fe=>{const Se=e.id,te=L,we=fe===""?null:fe;_(we),I("thinking");try{const Pe=await Ks(Se,{thinkingLevel:we});if(w.current!==Se)return;const We=Pe.thinkingLevel??null;G(We),_(We),s?.(Pe);const Ke=i?.defaultThinkingLevel??"off";n(We===null?`Thinking level set to default (${Ke})`:`Thinking level set to ${We}`,"success")}catch(Pe){if(w.current!==Se)return;_(te),n(xe(Pe)||"Failed to save thinking level","error")}finally{w.current===Se&&I(null)}},[e.id,L,i,n,s]),Q=!v.provider&&!v.modelId,de=!y.provider&&!y.modelId,Te=!S.provider&&!S.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):g?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",g,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),is().then(fe=>{o(fe.models),c(fe.favoriteProviders),d(fe.favoriteModels)}).catch(fe=>p(fe.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:Q?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",X.provider&&X.modelId?` (${X.provider}/${X.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Mn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(wn,{id:"executorModel",label:"Executor Model",value:B,onChange:re,models:r,disabled:pe,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Validator Model"}),t.jsx("div",{className:"model-selector-current",children:de?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",E.provider&&E.modelId?` (${E.provider}/${E.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[y.provider&&t.jsx(Mn,{provider:y.provider,size:"sm"}),y.provider,"/",y.modelId]})}),t.jsx(wn,{id:"validatorModel",label:"Validator Model",value:A,onChange:F,models:r,disabled:pe,placeholder:"Select validator model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),t.jsx("small",{children:"The AI model used to review code and plans for this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planningModel",children:"Planning Model"}),t.jsx("div",{className:"model-selector-current",children:Te?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",U.provider&&U.modelId?` (${U.provider}/${U.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[S.provider&&t.jsx(Mn,{provider:S.provider,size:"sm"}),S.provider,"/",S.modelId]})}),t.jsx(wn,{id:"planningModel",label:"Planning Model",value:z,onChange:ce,models:r,disabled:pe,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:L===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:L})}),t.jsxs("select",{id:"thinkingLevel",value:T??"",onChange:fe=>ae(fe.target.value),disabled:pe,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",i?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:Q&&de&&Te&&L===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const qE={open:t.jsx(eo,{size:16}),closed:t.jsx(Ka,{size:16}),merged:t.jsx(sh,{size:16})};function VE({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[b,v]=a.useState(!1),[x,k]=a.useState(!1),[M,y]=a.useState(null),R=a.useCallback(async()=>{if(h.trim()){v(!0);try{const P=await rv(e,{title:h.trim(),body:p.trim()||void 0},n);l(P),m(!1),g(""),f(""),u(`Created PR #${P.number}`,"success")}catch(P){u(xe(P)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),j=a.useCallback(async()=>{if(s){k(!0);try{const P=await ov(e,n);y(P),c(P.prInfo),u("PR status refreshed","success")}catch(P){u(xe(P)||"Failed to refresh PR","error")}finally{k(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):d?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:P=>g(P.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:P=>f(P.target.value),disabled:b,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:R,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m(!0),disabled:!o,title:o?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(Vt,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),!o&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const C=qE[s.status]??t.jsx(eo,{size:16}),S=M?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:C}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:j,disabled:x,title:"Refresh PR status",children:t.jsx(hn,{size:14,style:{verticalAlign:"middle",opacity:x?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:S.length>0?`Waiting for: ${S.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(li,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(xg,{size:14}),"View on GitHub"]})]})]})]})}const tm=2e3;function WE(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function GE(e){return e==="agent"||e==="system"}function KE({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),b=a.useMemo(()=>[...e.comments||[]].sort((C,S)=>new Date(S.createdAt).getTime()-new Date(C.createdAt).getTime()),[e.comments]),v=o.length>tm;async function x(){const C=o.trim();if(C){g(!0);try{const S=await Fx(e.id,C,r);l(""),n?.(S),s("Comment added","success")}catch(S){s(xe(S)||"Failed to add comment","error")}finally{g(!1)}}}async function k(C){const S=d.trim();if(S){g(!0);try{const P=await Px(e.id,C,S,r);u(null),m(""),n?.(P),s("Comment updated","success")}catch(P){s(xe(P)||"Failed to update comment","error")}finally{g(!1)}}}async function M(C){f(C);try{const S=await $x(e.id,C,r);n?.(S),s("Comment deleted","success")}catch(S){s(xe(S)||"Failed to delete comment","error")}finally{f(null)}}function y(C){C.key==="Enter"&&(C.ctrlKey||C.metaKey)&&(C.preventDefault(),x())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),b.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:b.map(C=>{const S=C.author===i,P=c===C.id,T=GE(C.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[T?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:C.author}),t.jsx("span",{className:"detail-log-timestamp",children:WE(C)})]}),S&&!P?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(C.id),m(C.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void M(C.id),disabled:p===C.id,children:p===C.id?"Deleting…":"Delete"})]}):null]}),P?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:_=>m(_.target.value),rows:3,className:"spec-editor-feedback"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void k(C.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:C.text})]},C.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:C=>l(C.target.value),onKeyDown:y,rows:3,placeholder:"Add a comment",className:"spec-editor-feedback"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",tm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function JE(e){return e?e.slice(0,7):"Unknown"}function YE({task:e}){if(e.column!=="done"||!e.mergeDetails)return null;const n=e.mergeDetails;return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Merge Details"}),t.jsxs("div",{className:"pr-card merge-details-card",children:[t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Status"}),t.jsx("span",{className:"detail-log-outcome",children:n.mergeConfirmed===!1?"Recorded without local merge confirmation":"Merged successfully"})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Commit"}),t.jsx("span",{className:"detail-log-outcome",children:JE(n.commitSha)})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Files changed"}),t.jsx("span",{className:"detail-log-outcome",children:n.filesChanged??0})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Insertions / Deletions"}),t.jsxs("span",{className:"detail-log-outcome",children:["+",n.insertions??0," / -",n.deletions??0]})]})}),n.mergedAt?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Merged at"}),t.jsx("span",{className:"detail-log-outcome",children:new Date(n.mergedAt).toLocaleString()})]})}):null,n.prNumber?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"PR"}),t.jsxs("span",{className:"detail-log-outcome",children:["#",n.prNumber]})]})}):null,n.mergeCommitMessage?t.jsxs("div",{className:"detail-log-entry",children:[t.jsx("div",{className:"detail-log-header",children:t.jsx("span",{className:"detail-log-action",children:"Message"})}),t.jsx("div",{className:"detail-log-outcome",children:n.mergeCommitMessage})]}):null]})]})}function Qp(e){return e.split(`
|
|
605
|
+
`))}function u(p,f,b,v){const x=b.enter("tableCell"),k=b.enter("phrasing"),M=b.containerPhrasing(p,{...v,before:o,after:o});return k(),x(),M}function d(p,f){return c2(p,{align:f,alignDelimiters:i,padding:s,stringLength:r})}function m(p,f,b){const v=p.children;let x=-1;const k=[],M=f.enter("table");for(;++x<v.length;)k[x]=h(v[x],f,b);return M(),k}function h(p,f,b){const v=p.children;let x=-1;const k=[],M=f.enter("tableRow");for(;++x<v.length;)k[x]=u(v[x],p,f,b);return M(),k}function g(p,f,b){let v=Op.inlineCode(p,f,b);return b.stack.includes("tableCell")&&(v=v.replace(/\|/g,"\\$&")),v}}function Y2(){return{exit:{taskListCheckValueChecked:Yu,taskListCheckValueUnchecked:Yu,paragraph:X2}}}function Q2(){return{unsafe:[{atBreak:!0,character:"-",after:"[:|-]"}],handlers:{listItem:Z2}}}function Yu(e){const n=this.stack[this.stack.length-2];n.type,n.checked=e.type==="taskListCheckValueChecked"}function X2(e){const n=this.stack[this.stack.length-2];if(n&&n.type==="listItem"&&typeof n.checked=="boolean"){const s=this.stack[this.stack.length-1];s.type;const i=s.children[0];if(i&&i.type==="text"){const r=n.children;let o=-1,l;for(;++o<r.length;){const c=r[o];if(c.type==="paragraph"){l=c;break}}l===s&&(i.value=i.value.slice(1),i.value.length===0?s.children.shift():s.position&&i.position&&typeof i.position.start.offset=="number"&&(i.position.start.column++,i.position.start.offset++,s.position.start=Object.assign({},i.position.start)))}}this.exit(e)}function Z2(e,n,s,i){const r=e.children[0],o=typeof e.checked=="boolean"&&r&&r.type==="paragraph",l="["+(e.checked?"x":" ")+"] ",c=s.createTracker(i);o&&c.move(l);let u=Op.listItem(e,n,s,{...i,...c.current()});return o&&(u=u.replace(/^(?:[*+-]|\d+\.)([\r\n]| {1,3})/,d)),u;function d(m){return m+l}}function eE(){return[RC(),ZC(),s2(),H2(),Y2()]}function tE(e){return{extensions:[IC(),e2(e),i2(),J2(e),Q2()]}}const nE={tokenize:lE,partial:!0},Up={tokenize:cE,partial:!0},Bp={tokenize:dE,partial:!0},Hp={tokenize:uE,partial:!0},sE={tokenize:mE,partial:!0},qp={name:"wwwAutolink",tokenize:rE,previous:Wp},Vp={name:"protocolAutolink",tokenize:oE,previous:Gp},Zs={name:"emailAutolink",tokenize:aE,previous:Kp},Vs={};function iE(){return{text:Vs}}let bi=48;for(;bi<123;)Vs[bi]=Zs,bi++,bi===58?bi=65:bi===91&&(bi=97);Vs[43]=Zs;Vs[45]=Zs;Vs[46]=Zs;Vs[95]=Zs;Vs[72]=[Zs,Vp];Vs[104]=[Zs,Vp];Vs[87]=[Zs,qp];Vs[119]=[Zs,qp];function aE(e,n,s){const i=this;let r,o;return l;function l(h){return!Zl(h)||!Kp.call(i,i.previous)||Dc(i.events)?s(h):(e.enter("literalAutolink"),e.enter("literalAutolinkEmail"),c(h))}function c(h){return Zl(h)?(e.consume(h),c):h===64?(e.consume(h),u):s(h)}function u(h){return h===46?e.check(sE,m,d)(h):h===45||h===95||$n(h)?(o=!0,e.consume(h),u):m(h)}function d(h){return e.consume(h),r=!0,u}function m(h){return o&&r&&qn(i.previous)?(e.exit("literalAutolinkEmail"),e.exit("literalAutolink"),n(h)):s(h)}}function rE(e,n,s){const i=this;return r;function r(l){return l!==87&&l!==119||!Wp.call(i,i.previous)||Dc(i.events)?s(l):(e.enter("literalAutolink"),e.enter("literalAutolinkWww"),e.check(nE,e.attempt(Up,e.attempt(Bp,o),s),s)(l))}function o(l){return e.exit("literalAutolinkWww"),e.exit("literalAutolink"),n(l)}}function oE(e,n,s){const i=this;let r="",o=!1;return l;function l(h){return(h===72||h===104)&&Gp.call(i,i.previous)&&!Dc(i.events)?(e.enter("literalAutolink"),e.enter("literalAutolinkHttp"),r+=String.fromCodePoint(h),e.consume(h),c):s(h)}function c(h){if(qn(h)&&r.length<5)return r+=String.fromCodePoint(h),e.consume(h),c;if(h===58){const g=r.toLowerCase();if(g==="http"||g==="https")return e.consume(h),u}return s(h)}function u(h){return h===47?(e.consume(h),o?d:(o=!0,u)):s(h)}function d(h){return h===null||Wr(h)||Wt(h)||Ei(h)||ho(h)?s(h):e.attempt(Up,e.attempt(Bp,m),s)(h)}function m(h){return e.exit("literalAutolinkHttp"),e.exit("literalAutolink"),n(h)}}function lE(e,n,s){let i=0;return r;function r(l){return(l===87||l===119)&&i<3?(i++,e.consume(l),r):l===46&&i===3?(e.consume(l),o):s(l)}function o(l){return l===null?s(l):n(l)}}function cE(e,n,s){let i,r,o;return l;function l(d){return d===46||d===95?e.check(Hp,u,c)(d):d===null||Wt(d)||Ei(d)||d!==45&&ho(d)?u(d):(o=!0,e.consume(d),l)}function c(d){return d===95?i=!0:(r=i,i=void 0),e.consume(d),l}function u(d){return r||i||!o?s(d):n(d)}}function dE(e,n){let s=0,i=0;return r;function r(l){return l===40?(s++,e.consume(l),r):l===41&&i<s?o(l):l===33||l===34||l===38||l===39||l===41||l===42||l===44||l===46||l===58||l===59||l===60||l===63||l===93||l===95||l===126?e.check(Hp,n,o)(l):l===null||Wt(l)||Ei(l)?n(l):(e.consume(l),r)}function o(l){return l===41&&i++,e.consume(l),r}}function uE(e,n,s){return i;function i(c){return c===33||c===34||c===39||c===41||c===42||c===44||c===46||c===58||c===59||c===63||c===95||c===126?(e.consume(c),i):c===38?(e.consume(c),o):c===93?(e.consume(c),r):c===60||c===null||Wt(c)||Ei(c)?n(c):s(c)}function r(c){return c===null||c===40||c===91||Wt(c)||Ei(c)?n(c):i(c)}function o(c){return qn(c)?l(c):s(c)}function l(c){return c===59?(e.consume(c),i):qn(c)?(e.consume(c),l):s(c)}}function mE(e,n,s){return i;function i(o){return e.consume(o),r}function r(o){return $n(o)?s(o):n(o)}}function Wp(e){return e===null||e===40||e===42||e===95||e===91||e===93||e===126||Wt(e)}function Gp(e){return!qn(e)}function Kp(e){return!(e===47||Zl(e))}function Zl(e){return e===43||e===45||e===46||e===95||$n(e)}function Dc(e){let n=e.length,s=!1;for(;n--;){const i=e[n][1];if((i.type==="labelLink"||i.type==="labelImage")&&!i._balanced){s=!0;break}if(i._gfmAutolinkLiteralWalkedInto){s=!1;break}}return e.length>0&&!s&&(e[e.length-1][1]._gfmAutolinkLiteralWalkedInto=!0),s}const hE={tokenize:kE,partial:!0};function pE(){return{document:{91:{name:"gfmFootnoteDefinition",tokenize:xE,continuation:{tokenize:vE},exit:yE}},text:{91:{name:"gfmFootnoteCall",tokenize:bE},93:{name:"gfmPotentialFootnoteCall",add:"after",tokenize:fE,resolveTo:gE}}}}function fE(e,n,s){const i=this;let r=i.events.length;const o=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let l;for(;r--;){const u=i.events[r][1];if(u.type==="labelImage"){l=u;break}if(u.type==="gfmFootnoteCall"||u.type==="labelLink"||u.type==="label"||u.type==="image"||u.type==="link")break}return c;function c(u){if(!l||!l._balanced)return s(u);const d=Rs(i.sliceSerialize({start:l.end,end:i.now()}));return d.codePointAt(0)!==94||!o.includes(d.slice(1))?s(u):(e.enter("gfmFootnoteCallLabelMarker"),e.consume(u),e.exit("gfmFootnoteCallLabelMarker"),n(u))}}function gE(e,n){let s=e.length;for(;s--;)if(e[s][1].type==="labelImage"&&e[s][0]==="enter"){e[s][1];break}e[s+1][1].type="data",e[s+3][1].type="gfmFootnoteCallLabelMarker";const i={type:"gfmFootnoteCall",start:Object.assign({},e[s+3][1].start),end:Object.assign({},e[e.length-1][1].end)},r={type:"gfmFootnoteCallMarker",start:Object.assign({},e[s+3][1].end),end:Object.assign({},e[s+3][1].end)};r.end.column++,r.end.offset++,r.end._bufferIndex++;const o={type:"gfmFootnoteCallString",start:Object.assign({},r.end),end:Object.assign({},e[e.length-1][1].start)},l={type:"chunkString",contentType:"string",start:Object.assign({},o.start),end:Object.assign({},o.end)},c=[e[s+1],e[s+2],["enter",i,n],e[s+3],e[s+4],["enter",r,n],["exit",r,n],["enter",o,n],["enter",l,n],["exit",l,n],["exit",o,n],e[e.length-2],e[e.length-1],["exit",i,n]];return e.splice(s,e.length-s+1,...c),e}function bE(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o=0,l;return c;function c(h){return e.enter("gfmFootnoteCall"),e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),u}function u(h){return h!==94?s(h):(e.enter("gfmFootnoteCallMarker"),e.consume(h),e.exit("gfmFootnoteCallMarker"),e.enter("gfmFootnoteCallString"),e.enter("chunkString").contentType="string",d)}function d(h){if(o>999||h===93&&!l||h===null||h===91||Wt(h))return s(h);if(h===93){e.exit("chunkString");const g=e.exit("gfmFootnoteCallString");return r.includes(Rs(i.sliceSerialize(g)))?(e.enter("gfmFootnoteCallLabelMarker"),e.consume(h),e.exit("gfmFootnoteCallLabelMarker"),e.exit("gfmFootnoteCall"),n):s(h)}return Wt(h)||(l=!0),o++,e.consume(h),h===92?m:d}function m(h){return h===91||h===92||h===93?(e.consume(h),o++,d):d(h)}}function xE(e,n,s){const i=this,r=i.parser.gfmFootnotes||(i.parser.gfmFootnotes=[]);let o,l=0,c;return u;function u(f){return e.enter("gfmFootnoteDefinition")._container=!0,e.enter("gfmFootnoteDefinitionLabel"),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),d}function d(f){return f===94?(e.enter("gfmFootnoteDefinitionMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionMarker"),e.enter("gfmFootnoteDefinitionLabelString"),e.enter("chunkString").contentType="string",m):s(f)}function m(f){if(l>999||f===93&&!c||f===null||f===91||Wt(f))return s(f);if(f===93){e.exit("chunkString");const b=e.exit("gfmFootnoteDefinitionLabelString");return o=Rs(i.sliceSerialize(b)),e.enter("gfmFootnoteDefinitionLabelMarker"),e.consume(f),e.exit("gfmFootnoteDefinitionLabelMarker"),e.exit("gfmFootnoteDefinitionLabel"),g}return Wt(f)||(c=!0),l++,e.consume(f),f===92?h:m}function h(f){return f===91||f===92||f===93?(e.consume(f),l++,m):m(f)}function g(f){return f===58?(e.enter("definitionMarker"),e.consume(f),e.exit("definitionMarker"),r.includes(o)||r.push(o),Ft(e,p,"gfmFootnoteDefinitionWhitespace")):s(f)}function p(f){return n(f)}}function vE(e,n,s){return e.check(sr,n,e.attempt(hE,n,s))}function yE(e){e.exit("gfmFootnoteDefinition")}function kE(e,n,s){const i=this;return Ft(e,r,"gfmFootnoteDefinitionIndent",5);function r(o){const l=i.events[i.events.length-1];return l&&l[1].type==="gfmFootnoteDefinitionIndent"&&l[2].sliceSerialize(l[1],!0).length===4?n(o):s(o)}}function jE(e){let s=(e||{}).singleTilde;const i={name:"strikethrough",tokenize:o,resolveAll:r};return s==null&&(s=!0),{text:{126:i},insideSpan:{null:[i]},attentionMarkers:{null:[126]}};function r(l,c){let u=-1;for(;++u<l.length;)if(l[u][0]==="enter"&&l[u][1].type==="strikethroughSequenceTemporary"&&l[u][1]._close){let d=u;for(;d--;)if(l[d][0]==="exit"&&l[d][1].type==="strikethroughSequenceTemporary"&&l[d][1]._open&&l[u][1].end.offset-l[u][1].start.offset===l[d][1].end.offset-l[d][1].start.offset){l[u][1].type="strikethroughSequence",l[d][1].type="strikethroughSequence";const m={type:"strikethrough",start:Object.assign({},l[d][1].start),end:Object.assign({},l[u][1].end)},h={type:"strikethroughText",start:Object.assign({},l[d][1].end),end:Object.assign({},l[u][1].start)},g=[["enter",m,c],["enter",l[d][1],c],["exit",l[d][1],c],["enter",h,c]],p=c.parser.constructs.insideSpan.null;p&&ds(g,g.length,0,po(p,l.slice(d+1,u),c)),ds(g,g.length,0,[["exit",h,c],["enter",l[u][1],c],["exit",l[u][1],c],["exit",m,c]]),ds(l,d-1,u-d+3,g),u=d+g.length-2;break}}for(u=-1;++u<l.length;)l[u][1].type==="strikethroughSequenceTemporary"&&(l[u][1].type="data");return l}function o(l,c,u){const d=this.previous,m=this.events;let h=0;return g;function g(f){return d===126&&m[m.length-1][1].type!=="characterEscape"?u(f):(l.enter("strikethroughSequenceTemporary"),p(f))}function p(f){const b=Qi(d);if(f===126)return h>1?u(f):(l.consume(f),h++,p);if(h<2&&!s)return u(f);const v=l.exit("strikethroughSequenceTemporary"),x=Qi(f);return v._open=!x||x===2&&!!b,v._close=!b||b===2&&!!x,c(f)}}}class wE{constructor(){this.map=[]}add(n,s,i){NE(this,n,s,i)}consume(n){if(this.map.sort(function(o,l){return o[0]-l[0]}),this.map.length===0)return;let s=this.map.length;const i=[];for(;s>0;)s-=1,i.push(n.slice(this.map[s][0]+this.map[s][1]),this.map[s][2]),n.length=this.map[s][0];i.push(n.slice()),n.length=0;let r=i.pop();for(;r;){for(const o of r)n.push(o);r=i.pop()}this.map.length=0}}function NE(e,n,s,i){let r=0;if(!(s===0&&i.length===0)){for(;r<e.map.length;){if(e.map[r][0]===n){e.map[r][1]+=s,e.map[r][2].push(...i);return}r+=1}e.map.push([n,s,i])}}function SE(e,n){let s=!1;const i=[];for(;n<e.length;){const r=e[n];if(s){if(r[0]==="enter")r[1].type==="tableContent"&&i.push(e[n+1][1].type==="tableDelimiterMarker"?"left":"none");else if(r[1].type==="tableContent"){if(e[n-1][1].type==="tableDelimiterMarker"){const o=i.length-1;i[o]=i[o]==="left"?"center":"right"}}else if(r[1].type==="tableDelimiterRow")break}else r[0]==="enter"&&r[1].type==="tableDelimiterRow"&&(s=!0);n+=1}return i}function CE(){return{flow:{null:{name:"table",tokenize:EE,resolveAll:ME}}}}function EE(e,n,s){const i=this;let r=0,o=0,l;return c;function c(T){let _=i.events.length-1;for(;_>-1;){const $=i.events[_][1].type;if($==="lineEnding"||$==="linePrefix")_--;else break}const L=_>-1?i.events[_][1].type:null,G=L==="tableHead"||L==="tableRow"?j:u;return G===j&&i.parser.lazy[i.now().line]?s(T):G(T)}function u(T){return e.enter("tableHead"),e.enter("tableRow"),d(T)}function d(T){return T===124||(l=!0,o+=1),m(T)}function m(T){return T===null?s(T):yt(T)?o>1?(o=0,i.interrupt=!0,e.exit("tableRow"),e.enter("lineEnding"),e.consume(T),e.exit("lineEnding"),p):s(T):It(T)?Ft(e,m,"whitespace")(T):(o+=1,l&&(l=!1,r+=1),T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),l=!0,m):(e.enter("data"),h(T)))}function h(T){return T===null||T===124||Wt(T)?(e.exit("data"),m(T)):(e.consume(T),T===92?g:h)}function g(T){return T===92||T===124?(e.consume(T),h):h(T)}function p(T){return i.interrupt=!1,i.parser.lazy[i.now().line]?s(T):(e.enter("tableDelimiterRow"),l=!1,It(T)?Ft(e,f,"linePrefix",i.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(T):f(T))}function f(T){return T===45||T===58?v(T):T===124?(l=!0,e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),b):R(T)}function b(T){return It(T)?Ft(e,v,"whitespace")(T):v(T)}function v(T){return T===58?(o+=1,l=!0,e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),x):T===45?(o+=1,x(T)):T===null||yt(T)?y(T):R(T)}function x(T){return T===45?(e.enter("tableDelimiterFiller"),k(T)):R(T)}function k(T){return T===45?(e.consume(T),k):T===58?(l=!0,e.exit("tableDelimiterFiller"),e.enter("tableDelimiterMarker"),e.consume(T),e.exit("tableDelimiterMarker"),M):(e.exit("tableDelimiterFiller"),M(T))}function M(T){return It(T)?Ft(e,y,"whitespace")(T):y(T)}function y(T){return T===124?f(T):T===null||yt(T)?!l||r!==o?R(T):(e.exit("tableDelimiterRow"),e.exit("tableHead"),n(T)):R(T)}function R(T){return s(T)}function j(T){return e.enter("tableRow"),C(T)}function C(T){return T===124?(e.enter("tableCellDivider"),e.consume(T),e.exit("tableCellDivider"),C):T===null||yt(T)?(e.exit("tableRow"),n(T)):It(T)?Ft(e,C,"whitespace")(T):(e.enter("data"),S(T))}function S(T){return T===null||T===124||Wt(T)?(e.exit("data"),C(T)):(e.consume(T),T===92?P:S)}function P(T){return T===92||T===124?(e.consume(T),S):S(T)}}function ME(e,n){let s=-1,i=!0,r=0,o=[0,0,0,0],l=[0,0,0,0],c=!1,u=0,d,m,h;const g=new wE;for(;++s<e.length;){const p=e[s],f=p[1];p[0]==="enter"?f.type==="tableHead"?(c=!1,u!==0&&(Qu(g,n,u,d,m),m=void 0,u=0),d={type:"table",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",d,n]])):f.type==="tableRow"||f.type==="tableDelimiterRow"?(i=!0,h=void 0,o=[0,0,0,0],l=[0,s+1,0,0],c&&(c=!1,m={type:"tableBody",start:Object.assign({},f.start),end:Object.assign({},f.end)},g.add(s,0,[["enter",m,n]])),r=f.type==="tableDelimiterRow"?2:m?3:1):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")?(i=!1,l[2]===0&&(o[1]!==0&&(l[0]=l[1],h=jr(g,n,o,r,void 0,h),o=[0,0,0,0]),l[2]=s)):f.type==="tableCellDivider"&&(i?i=!1:(o[1]!==0&&(l[0]=l[1],h=jr(g,n,o,r,void 0,h)),o=l,l=[o[1],s,0,0])):f.type==="tableHead"?(c=!0,u=s):f.type==="tableRow"||f.type==="tableDelimiterRow"?(u=s,o[1]!==0?(l[0]=l[1],h=jr(g,n,o,r,s,h)):l[1]!==0&&(h=jr(g,n,l,r,s,h)),r=0):r&&(f.type==="data"||f.type==="tableDelimiterMarker"||f.type==="tableDelimiterFiller")&&(l[3]=s)}for(u!==0&&Qu(g,n,u,d,m),g.consume(n.events),s=-1;++s<n.events.length;){const p=n.events[s];p[0]==="enter"&&p[1].type==="table"&&(p[1]._align=SE(n.events,s))}return e}function jr(e,n,s,i,r,o){const l=i===1?"tableHeader":i===2?"tableDelimiter":"tableData",c="tableContent";s[0]!==0&&(o.end=Object.assign({},Ui(n.events,s[0])),e.add(s[0],0,[["exit",o,n]]));const u=Ui(n.events,s[1]);if(o={type:l,start:Object.assign({},u),end:Object.assign({},u)},e.add(s[1],0,[["enter",o,n]]),s[2]!==0){const d=Ui(n.events,s[2]),m=Ui(n.events,s[3]),h={type:c,start:Object.assign({},d),end:Object.assign({},m)};if(e.add(s[2],0,[["enter",h,n]]),i!==2){const g=n.events[s[2]],p=n.events[s[3]];if(g[1].end=Object.assign({},p[1].end),g[1].type="chunkText",g[1].contentType="text",s[3]>s[2]+1){const f=s[2]+1,b=s[3]-s[2]-1;e.add(f,b,[])}}e.add(s[3]+1,0,[["exit",h,n]])}return r!==void 0&&(o.end=Object.assign({},Ui(n.events,r)),e.add(r,0,[["exit",o,n]]),o=void 0),o}function Qu(e,n,s,i,r){const o=[],l=Ui(n.events,s);r&&(r.end=Object.assign({},l),o.push(["exit",r,n])),i.end=Object.assign({},l),o.push(["exit",i,n]),e.add(s+1,0,o)}function Ui(e,n){const s=e[n],i=s[0]==="enter"?"start":"end";return s[1][i]}const _E={name:"tasklistCheck",tokenize:TE};function AE(){return{text:{91:_E}}}function TE(e,n,s){const i=this;return r;function r(u){return i.previous!==null||!i._gfmTasklistFirstContentOfListItem?s(u):(e.enter("taskListCheck"),e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),o)}function o(u){return Wt(u)?(e.enter("taskListCheckValueUnchecked"),e.consume(u),e.exit("taskListCheckValueUnchecked"),l):u===88||u===120?(e.enter("taskListCheckValueChecked"),e.consume(u),e.exit("taskListCheckValueChecked"),l):s(u)}function l(u){return u===93?(e.enter("taskListCheckMarker"),e.consume(u),e.exit("taskListCheckMarker"),e.exit("taskListCheck"),c):s(u)}function c(u){return yt(u)?n(u):It(u)?e.check({tokenize:RE},n,s)(u):s(u)}}function RE(e,n,s){return Ft(e,i,"whitespace");function i(r){return r===null?s(r):n(r)}}function IE(e){return ap([iE(),pE(),jE(e),CE(),AE()])}const PE={};function Xs(e){const n=this,s=e||PE,i=n.data(),r=i.micromarkExtensions||(i.micromarkExtensions=[]),o=i.fromMarkdownExtensions||(i.fromMarkdownExtensions=[]),l=i.toMarkdownExtensions||(i.toMarkdownExtensions=[]);r.push(IE(s)),o.push(eE()),l.push(tE(s))}const Xu=500,Zu=100;function ll(e){return e.length>Xu?e.slice(-Xu):e}function Jp(e,n,s){const[i,r]=a.useState([]),[o,l]=a.useState(!1),[c,u]=a.useState(!1),[d,m]=a.useState(null),[h,g]=a.useState(!1),p=a.useRef(null),f=a.useRef(!1),b=a.useRef(0),v=a.useRef(e),x=a.useRef(s),k=a.useRef(n),M=a.useRef(0);(v.current!==e||x.current!==s||k.current!==n)&&(v.current=e,x.current=s,k.current=n,b.current++,f.current=!0,r([]),l(!1),u(!1),m(null),g(!1),p.current&&(p.current(),p.current=null)),a.useEffect(()=>{if(!e||!n){p.current&&(p.current(),p.current=null);return}const C=b.current,S=++M.current;f.current=!1;const P=e,T=s;async function _(){if(!P)return;l(!0),g(!1);try{const G=await td(P,T,{limit:Zu});if(f.current||b.current!==C||M.current!==S)return;r(ll(G.entries)),u(G.hasMore),m(G.total)}catch{if(f.current||b.current!==C||M.current!==S)return;r([]),u(!1),m(null)}finally{!f.current&&b.current===C&&M.current===S&&l(!1)}const L=T?`?projectId=${encodeURIComponent(T)}`:"";p.current=qs(`/api/tasks/${P}/logs/stream${L}`,{events:{"agent:log":G=>{if(!(f.current||b.current!==C))try{const $=JSON.parse(G.data);r(I=>ll([...I,$])),m(I=>I!==null?I+1:null)}catch{}}}})}return _(),()=>{f.current=!0,p.current&&(p.current(),p.current=null)}},[e,n,s]);const R=a.useCallback(async()=>{if(!e||h)return;const C=b.current,S=i.length,P=e;g(!0);try{const T=await td(P,s,{limit:Zu,offset:S});if(f.current||b.current!==C)return;r(_=>{const L=[...T.entries,..._];return ll(L)}),u(T.hasMore),m(T.total)}catch{}finally{g(!1)}},[e,s,i.length,h]),j=a.useCallback(()=>r([]),[]);return{entries:i,loading:o,clear:j,loadMore:R,hasMore:c,total:d,loadingMore:h}}function $E(e){const n=new Date(e),i=new Date().getTime()-n.getTime(),r=Math.floor(i/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}const em={pre:({children:e,...n})=>t.jsx("pre",{...n,style:{overflowX:"auto",maxWidth:"100%",whiteSpace:"pre-wrap",wordBreak:"break-word"},children:e}),table:({children:e,...n})=>t.jsx("table",{...n,style:{display:"block",overflowX:"auto",maxWidth:"100%"},children:e})},DE=50;function Yp(e){return[e.taskId,e.timestamp,e.agent??"",e.type,e.text,e.detail??""].join("|")}function LE(e){const n=new Map;return e.map(s=>{const i=Yp(s),r=n.get(i)??0;return n.set(i,r+1),`${i}|${r}`})}function zE({entries:e,loading:n,executorModel:s,validatorModel:i,planningModel:r,hasMore:o=!1,onLoadMore:l,loadingMore:c=!1,totalCount:u=null}){const d=a.useRef(null),m=a.useRef(0),h=a.useRef(0),g=a.useRef(null),[p,f]=a.useState(!0),[b,v]=a.useState(!1),[x,k]=a.useState(!1),M=a.useMemo(()=>LE(e),[e]);a.useLayoutEffect(()=>{const _=d.current;if(!_)return;const L=e.length,G=m.current,$=h.current,I=M[M.length-1]??null,w=g.current!==I;if(L>G){const q=_.scrollTop<=DE;if(w)if(q)_.scrollTop=0;else{const W=_.scrollHeight-$;W>0&&(_.scrollTop+=W)}}m.current=L,h.current=_.scrollHeight,g.current=I},[e,M]);const y=a.useCallback(_=>{_.key==="Escape"&&b&&v(!1)},[b]);a.useEffect(()=>{if(b)return document.addEventListener("keydown",y),()=>{document.removeEventListener("keydown",y)}},[b,y]);const R=s?.provider&&s?.modelId,j=i?.provider&&i?.modelId,C=r?.provider&&r?.modelId,S=a.useMemo(()=>{const _=[];return R&&_.push({role:"Executor",provider:s.provider,modelId:s.modelId}),j&&_.push({role:"Validator",provider:i.provider,modelId:i.modelId}),C&&_.push({role:"Planning",provider:r.provider,modelId:r.modelId}),_},[R,s,j,i,C,r]);if(n&&e.length===0)return t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-loading",children:"Loading agent logs…"})});if(e.length===0)return t.jsx("div",{className:"agent-log-viewer","data-testid":"agent-log-viewer",children:t.jsx("div",{className:"agent-log-empty",children:"No agent output yet."})});const P=[...e].reverse(),T=[...M].reverse();return t.jsxs("div",{ref:d,className:`agent-log-viewer agent-log-viewer--streaming${b?" agent-log-viewer--fullscreen":""}`,"data-testid":"agent-log-viewer",children:[t.jsxs("div",{className:"agent-log-model-header","data-testid":"agent-log-model-header",children:[t.jsxs("div",{className:"agent-log-model-icons",children:[S.map(_=>t.jsx(Mn,{provider:_.provider,size:"sm"},`${_.role}-${_.provider}-${_.modelId??"default"}`)),t.jsx("button",{className:"agent-log-model-expand-btn",onClick:()=>k(_=>!_),"aria-label":x?"Collapse model details":"Expand model details","aria-expanded":x,"aria-controls":"agent-log-model-details","data-testid":"agent-log-model-expand",children:x?t.jsx(zt,{size:14}):t.jsx(en,{size:14})})]}),t.jsxs("div",{className:"agent-log-model-header-toggle",children:[t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>f(_=>!_),"aria-label":p?"Switch to plain text mode":"Switch to markdown mode","aria-pressed":p,"data-testid":"agent-log-mode-toggle",title:p?"Show raw text":"Show formatted markdown",children:p?"Markdown":"Plain"}),t.jsx("button",{className:"agent-log-mode-toggle",onClick:()=>v(_=>!_),"aria-label":b?"Exit full screen":"Expand agent log to full screen","data-testid":"agent-log-fullscreen-toggle",title:b?"Exit full screen":"Expand agent log to full screen",children:b?t.jsx(aa,{size:14}):t.jsx(io,{size:14})})]}),x&&t.jsxs("div",{id:"agent-log-model-details",className:"agent-log-model-details",children:[t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Executor:"}),R?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{provider:s.provider,size:"sm"}),t.jsxs("span",{children:[s.provider,"/",s.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Validator:"}),j?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{provider:i.provider,size:"sm"}),t.jsxs("span",{children:[i.provider,"/",i.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]}),t.jsxs("div",{className:"agent-log-model-group",children:[t.jsx("span",{className:"agent-log-model-label",children:"Planning/Triage:"}),C?t.jsxs("span",{className:"agent-log-model-value",children:[t.jsx(Mn,{provider:r.provider,size:"sm"}),t.jsxs("span",{children:[r.provider,"/",r.modelId]})]}):t.jsx("span",{className:"model-badge-default",children:"Using default"})]})]})]}),u!==null&&t.jsxs("div",{className:"agent-log-summary","data-testid":"agent-log-summary",children:["Showing ",e.length," of ",u," entries"]}),P.map((_,L)=>{const G=T[L]??`${Yp(_)}|fallback`,$=P[L-1],I=_.type==="tool"||_.type==="tool_result"||_.type==="tool_error",w=_.agent?I||L===0||$&&($.agent!==_.agent||$.type!==_.type):!1,q=w?t.jsx("span",{className:"agent-log-timestamp","data-testid":"agent-log-timestamp",children:$E(_.timestamp)}):null,W=w?t.jsxs("span",{className:"agent-log-badge-row",children:[t.jsxs("span",{className:"agent-log-agent-badge",children:["[",_.agent,"]"]}),q]}):null;return _.type==="tool"?t.jsxs("div",{className:"agent-log-tool",children:[W,"⚡ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):_.type==="thinking"?t.jsxs("div",{className:"agent-log-thinking",children:[W,p?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:em,children:_.text})}):_.text]},G):_.type==="tool_result"?t.jsxs("div",{className:"agent-log-tool-result",children:[W,"✓ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):_.type==="tool_error"?t.jsxs("div",{className:"agent-log-tool-error",children:[W,"✗ ",_.text,_.detail&&t.jsxs("span",{className:"agent-log-tool-detail",children:["— ",_.detail]})]},G):t.jsxs("div",{className:"agent-log-text",children:[W,p?t.jsx("div",{className:"markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],components:em,children:_.text})}):_.text]},G)}),o&&l&&t.jsx("div",{className:"agent-log-load-more","data-testid":"agent-log-load-more",children:t.jsx("button",{className:"agent-log-mode-toggle",onClick:l,disabled:c,"data-testid":"agent-log-load-more-button",children:c?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:14,className:"animate-spin"}),"Loading…"]}):"Load More"})})]})}function Xi(e){return e??void 0}function wr(e){return{provider:Xi(e.modelProvider),modelId:Xi(e.modelId)}}function Nr(e){return{provider:Xi(e.validatorModelProvider),modelId:Xi(e.validatorModelId)}}function Sr(e){return{provider:Xi(e.planningModelProvider),modelId:Xi(e.planningModelId)}}function FE(e,n){return e.modelProvider&&e.modelId?{provider:e.modelProvider,modelId:e.modelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function OE(e,n){return e.validatorModelProvider&&e.validatorModelId?{provider:e.validatorModelProvider,modelId:e.validatorModelId}:n?.validatorProvider&&n.validatorModelId?{provider:n.validatorProvider,modelId:n.validatorModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function UE(e,n){return e.planningModelProvider&&e.planningModelId?{provider:e.planningModelProvider,modelId:e.planningModelId}:n?.planningProvider&&n.planningModelId?{provider:n.planningProvider,modelId:n.planningModelId}:n?.defaultProvider&&n.defaultModelId?{provider:n.defaultProvider,modelId:n.defaultModelId}:{}}function cl(e){if(!e)return{provider:void 0,modelId:void 0};const n=e.indexOf("/");return{provider:e.slice(0,n),modelId:e.slice(n+1)}}function dl(e){return e.provider&&e.modelId?`${e.provider}/${e.modelId}`:""}function ul(e,n){return e.provider===n.provider&&e.modelId===n.modelId}function BE(e,n){const i={executor:"Executor",validator:"Validator",planning:"Planning"}[e]||e;return!n.provider||!n.modelId?`${i} model set to default`:`${i} model set to ${n.provider}/${n.modelId}`}function HE({task:e,addToast:n,onTaskUpdated:s,settings:i}){const[r,o]=a.useState([]),[l,c]=a.useState([]),[u,d]=a.useState([]),[m,h]=a.useState(!1),[g,p]=a.useState(null),[f,b]=a.useState(()=>wr(e)),[v,x]=a.useState(()=>wr(e)),[k,M]=a.useState(()=>Nr(e)),[y,R]=a.useState(()=>Nr(e)),[j,C]=a.useState(()=>Sr(e)),[S,P]=a.useState(()=>Sr(e)),[T,_]=a.useState(()=>e.thinkingLevel??null),[L,G]=a.useState(()=>e.thinkingLevel??null),[$,I]=a.useState(null),w=a.useRef(e.id);a.useEffect(()=>{h(!0),p(null),is().then(fe=>{o(fe.models),c(fe.favoriteProviders),d(fe.favoriteModels)}).catch(fe=>{p(fe.message||"Failed to load models")}).finally(()=>{h(!1)})},[]);const q=a.useCallback(async fe=>{const Se=l,we=Se.includes(fe)?Se.filter(Pe=>Pe!==fe):[fe,...Se];c(we);try{await nn({favoriteProviders:we,favoriteModels:u})}catch{c(Se),n("Failed to update favorites","error")}},[l,u,n]),W=a.useCallback(async fe=>{const Se=u,we=Se.includes(fe)?Se.filter(Pe=>Pe!==fe):[fe,...Se];d(we);try{await nn({favoriteProviders:l,favoriteModels:we})}catch{d(Se),n("Failed to update model favorites","error")}},[u,l,n]);a.useEffect(()=>{w.current=e.id;const fe=wr(e),Se=Nr(e),te=Sr(e);b(fe),x(fe),M(Se),R(Se),C(te),P(te);const we=e.thinkingLevel??null;_(we),G(we),I(null)},[e.id,e.modelProvider,e.modelId,e.validatorModelProvider,e.validatorModelId,e.planningModelProvider,e.planningModelId,e.thinkingLevel]);const B=a.useMemo(()=>dl(f),[f]),A=a.useMemo(()=>dl(k),[k]),z=a.useMemo(()=>dl(j),[j]),X=a.useMemo(()=>FE(e,i),[e,i]),E=a.useMemo(()=>OE(e,i),[e,i]),U=a.useMemo(()=>UE(e,i),[e,i]),pe=$!==null,ie=a.useCallback(async(fe,Se)=>{const te=e.id,we=v,Pe=y,We=S;I(fe);try{const Ke=s?fe==="executor"?{modelProvider:Se.provider??null,modelId:Se.modelId??null}:fe==="validator"?{validatorModelProvider:Se.provider??null,validatorModelId:Se.modelId??null}:{planningModelProvider:Se.provider??null,planningModelId:Se.modelId??null}:{modelProvider:(fe==="executor"?Se:v).provider??null,modelId:(fe==="executor"?Se:v).modelId??null,validatorModelProvider:(fe==="validator"?Se:y).provider??null,validatorModelId:(fe==="validator"?Se:y).modelId??null,planningModelProvider:(fe==="planning"?Se:S).provider??null,planningModelId:(fe==="planning"?Se:S).modelId??null},Ne=await Ks(te,Ke);if(w.current!==te)return;const _e=wr(Ne),Oe=Nr(Ne),ye=Sr(Ne);x(_e),b(_e),R(Oe),M(Oe),P(ye),C(ye),s?.(Ne),n(BE(fe,{executor:_e,validator:Oe,planning:ye}[fe]),"success")}catch(Ke){if(w.current!==te)return;fe==="executor"?b(we):fe==="validator"?M(Pe):C(We),n(xe(Ke)||"Failed to save model settings","error")}finally{w.current===te&&I(null)}},[e.id,v,y,S,n,s]),re=a.useCallback(fe=>{const Se=cl(fe);b(Se),!ul(Se,v)&&ie("executor",Se)},[v,ie]),F=a.useCallback(fe=>{const Se=cl(fe);M(Se),!ul(Se,y)&&ie("validator",Se)},[y,ie]),ce=a.useCallback(fe=>{const Se=cl(fe);C(Se),!ul(Se,S)&&ie("planning",Se)},[S,ie]),ae=a.useCallback(async fe=>{const Se=e.id,te=L,we=fe===""?null:fe;_(we),I("thinking");try{const Pe=await Ks(Se,{thinkingLevel:we});if(w.current!==Se)return;const We=Pe.thinkingLevel??null;G(We),_(We),s?.(Pe);const Ke=i?.defaultThinkingLevel??"off";n(We===null?`Thinking level set to default (${Ke})`:`Thinking level set to ${We}`,"success")}catch(Pe){if(w.current!==Se)return;_(te),n(xe(Pe)||"Failed to save thinking level","error")}finally{w.current===Se&&I(null)}},[e.id,L,i,n,s]),Q=!v.provider&&!v.modelId,de=!y.provider&&!y.modelId,Te=!S.provider&&!S.modelId;return t.jsxs("div",{className:"model-selector-tab",children:[t.jsx("h4",{children:"Model Configuration"}),t.jsx("p",{className:"model-selector-intro",children:"Override the AI models used for this task. When not specified, project or global defaults are used."}),m?t.jsx("div",{className:"model-selector-loading",children:"Loading available models…"}):g?t.jsxs("div",{className:"model-selector-error",children:["Error loading models: ",g,t.jsx("button",{className:"btn btn-sm",onClick:()=>{h(!0),p(null),is().then(fe=>{o(fe.models),c(fe.favoriteProviders),d(fe.favoriteModels)}).catch(fe=>p(fe.message)).finally(()=>h(!1))},style:{marginLeft:"8px"},children:"Retry"})]}):r.length===0?t.jsx("div",{className:"model-selector-empty",children:"No models available. Configure authentication in Settings to enable model selection."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"executorModel",children:"Executor Model"}),t.jsx("div",{className:"model-selector-current",children:Q?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",X.provider&&X.modelId?` (${X.provider}/${X.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[v.provider&&t.jsx(Mn,{provider:v.provider,size:"sm"}),v.provider,"/",v.modelId]})}),t.jsx(wn,{id:"executorModel",label:"Executor Model",value:B,onChange:re,models:r,disabled:pe,placeholder:"Select executor model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),t.jsx("small",{children:"The AI model used to implement this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"validatorModel",children:"Validator Model"}),t.jsx("div",{className:"model-selector-current",children:de?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",E.provider&&E.modelId?` (${E.provider}/${E.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[y.provider&&t.jsx(Mn,{provider:y.provider,size:"sm"}),y.provider,"/",y.modelId]})}),t.jsx(wn,{id:"validatorModel",label:"Validator Model",value:A,onChange:F,models:r,disabled:pe,placeholder:"Select validator model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),t.jsx("small",{children:"The AI model used to review code and plans for this task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planningModel",children:"Planning Model"}),t.jsx("div",{className:"model-selector-current",children:Te?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default",U.provider&&U.modelId?` (${U.provider}/${U.modelId})`:""]}):t.jsxs("span",{className:"model-badge model-badge-custom",children:[S.provider&&t.jsx(Mn,{provider:S.provider,size:"sm"}),S.provider,"/",S.modelId]})}),t.jsx(wn,{id:"planningModel",label:"Planning Model",value:z,onChange:ce,models:r,disabled:pe,placeholder:"Select planning model…",favoriteProviders:l,onToggleFavorite:q,favoriteModels:u,onToggleModelFavorite:W}),t.jsx("small",{children:"The AI model used for task specification (triage phase)."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"thinkingLevel",children:"Thinking Level"}),t.jsx("div",{className:"model-selector-current",children:L===null?t.jsxs("span",{className:"model-badge model-badge-default",children:["Using default (",i?.defaultThinkingLevel??"off",")"]}):t.jsx("span",{className:"model-badge model-badge-custom",children:L})}),t.jsxs("select",{id:"thinkingLevel",value:T??"",onChange:fe=>ae(fe.target.value),disabled:pe,className:"thinking-level-select",children:[t.jsxs("option",{value:"",children:["Default (",i?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]}),t.jsx("small",{children:"Controls the reasoning effort for the AI agent. Higher levels use more tokens."})]}),t.jsx("div",{className:"model-selector-status",children:Q&&de&&Te&&L===null?"Using project or global default models.":"Model settings are up to date."})]})]})}const qE={open:t.jsx(eo,{size:16}),closed:t.jsx(Ka,{size:16}),merged:t.jsx(sh,{size:16})};function VE({taskId:e,projectId:n,prInfo:s,automationStatus:i,autoMerge:r=!1,prAuthAvailable:o,onPrCreated:l,onPrUpdated:c,addToast:u}){const[d,m]=a.useState(!1),[h,g]=a.useState(""),[p,f]=a.useState(""),[b,v]=a.useState(!1),[x,k]=a.useState(!1),[M,y]=a.useState(null),R=a.useCallback(async()=>{if(h.trim()){v(!0);try{const P=await rv(e,{title:h.trim(),body:p.trim()||void 0},n);l(P),m(!1),g(""),f(""),u(`Created PR #${P.number}`,"success")}catch(P){u(xe(P)||"Failed to create PR","error")}finally{v(!1)}}},[e,h,p,n,l,u]),j=a.useCallback(async()=>{if(s){k(!0);try{const P=await ov(e,n);y(P),c(P.prInfo),u("PR status refreshed","success")}catch(P){u(xe(P)||"Failed to refresh PR","error")}finally{k(!1)}}},[e,s,n,c,u]);if(!s)return i==="creating-pr"?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"fn is creating a pull request automatically for this task."})]}):r?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsx("div",{className:"pr-hint pr-hint--muted",children:"Auto-merge will handle this task automatically."})]}):d?t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Create Pull Request"]}),t.jsxs("div",{className:"pr-form",children:[t.jsx("input",{type:"text",placeholder:"PR title",value:h,onChange:P=>g(P.target.value),disabled:b,className:"pr-input"}),t.jsx("textarea",{placeholder:"PR description (optional)",value:p,onChange:P=>f(P.target.value),disabled:b,className:"pr-textarea",rows:3}),t.jsxs("div",{className:"pr-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>m(!1),disabled:b,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:R,disabled:!h.trim()||b,children:b?"Creating…":"Create PR"})]})]})]}):t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>m(!0),disabled:!o,title:o?"Create a PR for this task":"PR auth unavailable — run 'gh auth login'",children:[t.jsx(Vt,{size:14,className:"pr-section-icon--sm"}),"Create PR"]}),!o&&t.jsxs("div",{className:"pr-hint pr-hint--subtle",children:["Run ",t.jsx("code",{children:"gh auth login"})," to enable PR creation."]})]});const C=qE[s.status]??t.jsx(eo,{size:16}),S=M?.blockingReasons??[];return t.jsxs("div",{className:"pr-section",children:[t.jsxs("h4",{children:[t.jsx(es,{size:16,className:"pr-section-icon"}),"Pull Request"]}),t.jsxs("div",{className:`pr-card pr-card--status-${s.status}`,children:[t.jsxs("div",{className:"pr-header",children:[t.jsx("span",{className:"pr-status-icon",children:C}),t.jsx("span",{className:`pr-status-badge pr-status-badge--${s.status}`,children:s.status}),t.jsxs("span",{className:"pr-number",children:["#",s.number]}),t.jsx("div",{className:"pr-spacer"}),t.jsx("button",{className:"btn btn-sm pr-refresh-btn",onClick:j,disabled:x,title:"Refresh PR status",children:t.jsx(hn,{size:14,style:{verticalAlign:"middle",opacity:x?.5:1}})})]}),t.jsx("div",{className:"pr-title",children:s.title}),t.jsxs("div",{className:"pr-meta",children:[t.jsx("span",{children:s.headBranch}),t.jsx("span",{className:"pr-meta-arrow",children:"→"}),t.jsx("span",{children:s.baseBranch})]}),i==="merging-pr"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"fn is merging this pull request automatically."}),i==="awaiting-pr-checks"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:S.length>0?`Waiting for: ${S.join("; ")}`:"Waiting for required checks or review feedback before auto-merge."}),s.status==="merged"&&t.jsx("div",{className:"pr-hint pr-hint--info",children:"This PR is merged. fn will finish local cleanup and move the task to Done."}),t.jsxs("div",{className:"pr-footer",children:[s.commentCount>0&&t.jsxs("span",{className:"pr-comments",children:[t.jsx(li,{size:14}),s.commentCount]}),t.jsxs("a",{href:s.url,target:"_blank",rel:"noopener noreferrer",className:"pr-link",children:[t.jsx(xg,{size:14}),"View on GitHub"]})]})]})]})}const tm=2e3;function WE(e){const n=e.updatedAt||e.createdAt,s=new Date(n).toLocaleString();return e.updatedAt?`${s} (edited)`:s}function GE(e){return e==="agent"||e==="system"}function KE({task:e,onTaskUpdated:n,addToast:s,currentAuthor:i="user",projectId:r}){const[o,l]=a.useState(""),[c,u]=a.useState(null),[d,m]=a.useState(""),[h,g]=a.useState(!1),[p,f]=a.useState(null),b=a.useMemo(()=>[...e.comments||[]].sort((C,S)=>new Date(S.createdAt).getTime()-new Date(C.createdAt).getTime()),[e.comments]),v=o.length>tm;async function x(){const C=o.trim();if(C){g(!0);try{const S=await Fx(e.id,C,r);l(""),n?.(S),s("Comment added","success")}catch(S){s(xe(S)||"Failed to add comment","error")}finally{g(!1)}}}async function k(C){const S=d.trim();if(S){g(!0);try{const P=await Px(e.id,C,S,r);u(null),m(""),n?.(P),s("Comment updated","success")}catch(P){s(xe(P)||"Failed to update comment","error")}finally{g(!1)}}}async function M(C){f(C);try{const S=await $x(e.id,C,r);n?.(S),s("Comment deleted","success")}catch(S){s(xe(S)||"Failed to delete comment","error")}finally{f(null)}}function y(C){C.key==="Enter"&&(C.ctrlKey||C.metaKey)&&(C.preventDefault(),x())}return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Comments"}),b.length===0?t.jsx("div",{className:"detail-log-empty",children:"No comments yet."}):t.jsx("div",{className:"detail-activity-list",children:b.map(C=>{const S=C.author===i,P=c===C.id,T=GE(C.author);return t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header comments-header-row",children:[t.jsxs("div",{className:"comments-author-row",children:[T?t.jsx("span",{className:"ai-guidance-badge","data-testid":"ai-guidance-badge",children:"AI Guidance"}):t.jsx("strong",{children:C.author}),t.jsx("span",{className:"detail-log-timestamp",children:WE(C)})]}),S&&!P?t.jsxs("div",{className:"comments-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(C.id),m(C.text)},children:"Edit"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void M(C.id),disabled:p===C.id,children:p===C.id?"Deleting…":"Delete"})]}):null]}),P?t.jsxs("div",{className:"comments-edit-form",children:[t.jsx("textarea",{value:d,onChange:_=>m(_.target.value),rows:3,className:"spec-editor-feedback"}),t.jsxs("div",{className:"comments-edit-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{u(null),m("")},disabled:h,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void k(C.id),disabled:h||!d.trim(),children:"Save"})]})]}):t.jsx("div",{className:"detail-log-outcome comments-outcome-text",children:C.text})]},C.id)})}),t.jsxs("div",{className:"comments-compose-form",children:[t.jsx("textarea",{value:o,onChange:C=>l(C.target.value),onKeyDown:y,rows:3,placeholder:"Add a comment",className:"spec-editor-feedback"}),t.jsxs("div",{className:"comments-footer-row",children:[t.jsxs("span",{className:`comments-char-count${v?" comments-char-count--over":""}`,children:[o.length," / ",tm]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void x(),disabled:h||!o.trim()||v,children:h?"Posting…":"Add Comment"})]})]})]})}function JE(e){return e?e.slice(0,7):"Unknown"}function YE({task:e}){if(e.column!=="done"||!e.mergeDetails)return null;const n=e.mergeDetails;return t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Merge Details"}),t.jsxs("div",{className:"pr-card merge-details-card",children:[t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Status"}),t.jsx("span",{className:"detail-log-outcome",children:n.mergeConfirmed===!1?"Recorded without local merge confirmation":"Merged successfully"})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Commit"}),t.jsx("span",{className:"detail-log-outcome",children:JE(n.commitSha)})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Files changed"}),t.jsx("span",{className:"detail-log-outcome",children:n.filesChanged??0})]})}),t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Insertions / Deletions"}),t.jsxs("span",{className:"detail-log-outcome",children:["+",n.insertions??0," / -",n.deletions??0]})]})}),n.mergedAt?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"Merged at"}),t.jsx("span",{className:"detail-log-outcome",children:new Date(n.mergedAt).toLocaleString()})]})}):null,n.prNumber?t.jsx("div",{className:"detail-log-entry",children:t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-action",children:"PR"}),t.jsxs("span",{className:"detail-log-outcome",children:["#",n.prNumber]})]})}):null,n.mergeCommitMessage?t.jsxs("div",{className:"detail-log-entry",children:[t.jsx("div",{className:"detail-log-header",children:t.jsx("span",{className:"detail-log-action",children:"Message"})}),t.jsx("div",{className:"detail-log-outcome",children:n.mergeCommitMessage})]}):null]})]})}function Qp(e){return e.split(`
|
|
606
606
|
`).map((s,i)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
|
|
607
607
|
`},i):t.jsx(Jm.Fragment,{children:`${s}
|
|
608
608
|
`},i)})}function nm(e,n=60){if(!e||e.length<=n)return e;if(n<4)return e.slice(0,n);const s="...",i=e.lastIndexOf("/");if(i===-1){const m=Math.max(1,n-s.length);return e.slice(0,m)+s}const r=[];for(let m=1;m<e.length;m++)e[m]==="/"&&r.push(m);const o=n-s.length;let l=null,c=-1;for(let m=r.length-1;m>=0;m--){const h=r[m],g=e.slice(h);if(g.length>o)continue;const p=o-g.length;for(let f=0;f<r.length;f++){const b=r[f],v=e.slice(0,b);v.length<=p&&v.length+s.length+g.length<=n&&v.length+g.length>c&&(c=v.length+g.length,l=v+s+g)}}if(l)return l;const u=e.slice(i);if(s.length+u.length<=n)return s+u;const d=n-s.length;return s+e.slice(e.length-d)}function QE(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function XE({isOpen:e,taskId:n,files:s,stats:i,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[u,d]=a.useState(null),[m,h]=a.useState(!0);a.useEffect(()=>{s.length>0&&u===null&&d(0)},[s,u]);const g=a.useCallback(()=>{d(v=>v!==null&&v>0?v-1:v)},[]),p=a.useCallback(()=>{d(v=>v!==null&&v<s.length-1?v+1:v)},[]);if(a.useEffect(()=>{if(!e)return;const v=x=>{if(x.key==="Escape"){l();return}x.key==="ArrowUp"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),g()),x.key==="ArrowDown"&&(x.metaKey||x.ctrlKey)&&(x.preventDefault(),p())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[e,l,g,p]),!e)return null;const f=u!==null?s[u]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",onClick:l,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",onClick:v=>v.stopPropagation(),children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Ts,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",i.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",i.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:u===null||u<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(rc,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:u!==null?`${u+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:p,disabled:u===null||u>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(en,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(v=>!v),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(zr,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(hn,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"changes-diff-body",children:[t.jsxs("div",{className:"changes-diff-sidebar",children:[b&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(za,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((v,x)=>t.jsxs("button",{className:`changes-diff-file-item ${u===x?"selected":""}`,onClick:()=>d(x),title:v.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${v.status}`,children:QE(v.status)}),t.jsx("span",{className:"changes-diff-file-path",children:v.path}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",v.additions," -",v.deletions]})]},v.path))})]}),t.jsx("div",{className:"changes-diff-content",children:f?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:f.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",f.additions," -",f.deletions]})]}),f.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Qp(f.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(Ts,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function sm(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function ZE({taskId:e,worktree:n,projectId:s,column:i,mergeDetails:r,modifiedFiles:o}){const[l,c]=a.useState([]),[u,d]=a.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=a.useState(!0),[g,p]=a.useState(null),[f,b]=a.useState(new Set),[v,x]=a.useState(null),[k,M]=a.useState(!0),[y,R]=a.useState(!1),j=i==="done",C=j&&!!r?.commitSha,S=i==="in-progress"||i==="in-review"||C,P=a.useCallback(async()=>{if(!S){h(!1);return}try{h(!0),p(null);const $=await jh(e,void 0,s),I=$.files.map(w=>({path:w.path,status:w.status,additions:w.additions,deletions:w.deletions,patch:w.patch}));c(I),d($.stats),I.length>0&&(b(new Set([I[0].path])),x(0))}catch($){p(xe($)||"Failed to load diff")}finally{h(!1)}},[e,s,S]);a.useEffect(()=>{P()},[P]);const T=$=>{b(I=>{const w=new Set(I);if(w.has($))w.delete($);else{w.add($);const q=l.findIndex(W=>W.path===$);q!==-1&&x(q)}return w})},_=$=>{if($<0||$>=l.length)return;const I=l[$].path;b(new Set([I])),x($)},L=v!==null&&v>0,G=v!==null&&v<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(g)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(ss,{size:16}),t.jsxs("span",{children:["Error loading changes: ",g]})]})});if(!j&&!n)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(j&&!C){const $=r?.filesChanged,I=r?.insertions,w=r?.deletions,q=$!=null||I!=null||w!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:q?`Merge summary: ${$??0} file${($??0)===1?"":"s"} changed, +${I??0} additions, -${w??0} deletions.`:"No merge commit was recorded for this task."})]})})}return l.length===0?j&&o&&o.length>0?t.jsxs("div",{className:"detail-section task-changes-tab",children:[j&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(za,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsxs("p",{children:[o.length," file",o.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:o.map($=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:sm("unknown")}),t.jsx("span",{className:"changes-file-path",title:$,children:nm($)})]})},$))})]}):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Ts,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:j?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[j&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(za,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"changes-header",children:[t.jsxs("div",{className:"task-changes-header-title",children:[t.jsxs("h4",{children:[t.jsx(Ts,{size:16}),"Files Changed (",u.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",u.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",u.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>L&&_(v-1),disabled:!L,title:"Previous file","aria-label":"Previous file",children:t.jsx(rc,{size:14})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:v!==null?`${v+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>G&&_(v+1),disabled:!G,title:"Next file","aria-label":"Next file",children:t.jsx(en,{size:14})})]}),t.jsx("button",{className:`btn btn-sm ${k?"btn-primary":""}`,onClick:()=>M($=>!$),title:k?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(zr,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:P,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>R(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(io,{size:14})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map($=>{const I=f.has($.path);return t.jsxs("div",{className:`changes-file-item ${I?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>T($.path),children:[t.jsx("span",{className:"changes-file-toggle",children:I?t.jsx(zt,{size:14}):t.jsx(en,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${$.status}`,title:$.status,children:sm($.status)}),t.jsx("span",{className:"changes-file-path",title:$.path,children:nm($.path)}),t.jsxs("span",{className:"changes-file-stat",title:`+${$.additions} -${$.deletions}`,children:["+",$.additions," -",$.deletions]})]}),I&&$.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${k?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:Qp($.patch)})})})]},$.path)})}),t.jsx(XE,{isOpen:y,taskId:e,files:l,stats:u,mergeDetails:r,column:i,onClose:()=>R(!1),onRefresh:P})]})}function im(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function eM(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function lP(e,n){const s=eM(e),i=new Set(n.map(c=>c.id));if(!i.has(s))return s;const r=30;let o=s,l=1;for(;i.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}const am=["image/png","image/jpeg","image/gif","image/webp"];function tM(e,n,s){const i=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${i}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function Xp({mode:e,description:n,onDescriptionChange:s,title:i,onTitleChange:r,dependencies:o,onDependenciesChange:l,priority:c,onPriorityChange:u,executorModel:d,onExecutorModelChange:m,validatorModel:h,onValidatorModelChange:g,planningModel:p,onPlanningModelChange:f,thinkingLevel:b,onThinkingLevelChange:v,presetMode:x,onPresetModeChange:k,selectedPresetId:M,onSelectedPresetIdChange:y,selectedWorkflowSteps:R,onWorkflowStepsChange:j,onDefaultOnApplied:C,pendingImages:S,onImagesChange:P,tasks:T,projectId:_,disabled:L=!1,addToast:G,isActive:$=!0,onAutoSaveDescription:I,onPlanningMode:w,onSubtaskBreakdown:q,onClose:W,renderBelowPrimary:B,renderBelowModelConfiguration:A,hideDependencies:z,autoExpandMoreOptionsOnSelection:X=!0,reviewLevel:E,onReviewLevelChange:U,executionMode:pe,onExecutionModeChange:ie}){const re=(z?!1:o.length>0)||S.length>0||R.length>0||x!=="default"||(c??cs)!==cs||d!==""||h!==""||(p||"")!==""||(b||"")!==""||E!==void 0||pe==="fast",[F,ce]=a.useState(!1),[ae,Q]=a.useState(X?re:!1),[de,Te]=a.useState(""),[fe,Se]=a.useState([]),[te,we]=a.useState([]),[Pe,We]=a.useState([]),[Ke,Ne]=a.useState(!1),[_e,Oe]=a.useState(null),[ye,De]=a.useState([]),[se,J]=a.useState("idle"),[me,ee]=a.useState(!1),[he,le]=a.useState(!1),[Ie,Ze]=a.useState(!1),at=a.useRef(null),oe=a.useRef(null),Z=a.useRef(null),ue=a.useRef(null),Ce=a.useRef(null),$e=a.useRef(null),ve=a.useRef(null),Ge=a.useRef(!1),je=a.useRef(re),Ue=a.useRef(n.trim()),He=a.useRef(n.trim());a.useEffect(()=>{$&&(Ne(!0),is().then(N=>{Se(N.models),we(N.favoriteProviders),We(N.favoriteModels)}).catch(()=>{}).finally(()=>Ne(!1)),ro(_).then(N=>Oe(N)).catch(()=>Oe(null)),oo(_).then(N=>De(N.filter(H=>H.enabled))).catch(()=>De([])))},[$,_]);const ge=_e?.modelPresets||[],Fe=ge.find(N=>N.id===M),be=(z?!1:o.length>0)||S.length>0||R.length>0||x!=="default"||(c??cs)!==cs||d!==""||h!==""||(p||"")!==""||(b||"")!==""||E!==void 0||pe==="fast";a.useEffect(()=>{if(e!=="create"||!$||!_e?.autoSelectModelPreset)return;const N=(_e.defaultPresetBySize,void 0);if(N){const H=im(N);y(N.id),k("preset"),m(H.executorValue),g(H.validatorValue)}},[$,_e,ge,e]);const Je=a.useRef(!1);a.useEffect(()=>{if(e!=="create"||!$||Je.current||ye.length===0)return;const N=ye.filter(Ae=>Ae.defaultOn);if(N.length===0)return;Je.current=!0;const H=N.map(Ae=>Ae.id);j(H),C?.(H)},[e,$,ye]),a.useEffect(()=>{$||(Je.current=!1)},[$]),a.useEffect(()=>{if(!X){je.current=be;return}be&&!je.current&&Q(!0),je.current=be},[be,X]),a.useEffect(()=>{ae||(ce(!1),Te(""))},[ae]),a.useEffect(()=>{e!=="edit"||!$||ue.current&&(ue.current.focus(),ue.current.select())},[e,$]),a.useEffect(()=>{if(!F)return;const N=H=>{oe.current&&!oe.current.contains(H.target)&&ce(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[F]),a.useEffect(()=>{(e!=="edit"||L)&&Ze(!1)},[e,L]),a.useEffect(()=>{if(e!=="edit"){J("idle");return}const N=n.trim();Ue.current=N,He.current=N,J("idle")},[e]),a.useEffect(()=>{if(e!=="edit"||!I||!$)return;const N=n.trim(),H=Ue.current;if(N===H||N===He.current){$e.current&&(clearTimeout($e.current),$e.current=null),Ge.current||J("idle");return}return $e.current&&clearTimeout($e.current),$e.current=setTimeout(async()=>{if(!Ge.current){Ge.current=!0,J("saving");try{await I(N),He.current=N,J("saved"),ve.current&&clearTimeout(ve.current),ve.current=setTimeout(()=>{J("idle"),ve.current=null},2e3)}catch{J("idle")}finally{Ge.current=!1,$e.current=null}}},1500),()=>{$e.current&&(clearTimeout($e.current),$e.current=null)}},[e,n,I,$]),a.useEffect(()=>()=>{$e.current&&clearTimeout($e.current),ve.current&&clearTimeout(ve.current)},[]),a.useEffect(()=>{if(!me)return;const N=H=>{at.current&&!at.current.contains(H.target)&&ee(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[me]);const st=a.useCallback(N=>{const H=N.clipboardData?.items;if(H)for(let Ae=0;Ae<H.length;Ae++){const ot=H[Ae];if(ot.type.startsWith("image/")){const kt=ot.getAsFile();if(kt&&am.includes(kt.type)){N.preventDefault(),P([...S,{file:kt,previewUrl:URL.createObjectURL(kt)}]);return}}}},[S,P]),dt=a.useCallback(N=>{N.preventDefault();const H=N.dataTransfer.files;for(let Ae=0;Ae<H.length;Ae++){const ot=H[Ae];if(am.includes(ot.type)){P([...S,{file:ot,previewUrl:URL.createObjectURL(ot)}]);return}}},[S,P]),Tt=a.useCallback(N=>{const H=S[N];H&&URL.revokeObjectURL(H.previewUrl),P(S.filter((Ae,ot)=>ot!==N))},[S,P]),$t=a.useCallback(N=>{l(o.includes(N)?o.filter(H=>H!==N):[...o,N])},[o,l]),Dt=(N,H)=>N.length>H?N.slice(0,H)+"…":N,Bt=a.useCallback(N=>{s(N.target.value);const H=N.target;H.style.height="auto",H.style.height=H.scrollHeight+"px"},[s]),qt=a.useCallback(()=>{Ze(N=>!N)},[]),Lt=a.useCallback(N=>{!Ie||N.key!=="Escape"||(N.preventDefault(),N.stopPropagation(),Ze(!1))},[Ie]),Ct=a.useCallback(async N=>{const H=n.trim();if(!(!H||he)){le(!0);try{const Ae=await bh(H,N,_);s(Ae),ee(!1),G("Description refined with AI","success"),Z.current&&(Z.current.style.height="auto",Z.current.style.height=Z.current.scrollHeight+"px")}catch(Ae){const ot=xh(Ae);G(ot,"error")}finally{le(!1)}}},[n,he,G,s,_]),xt=a.useCallback(async N=>{const H=te,ot=H.includes(N)?H.filter(kt=>kt!==N):[N,...H];we(ot);try{await nn({favoriteProviders:ot,favoriteModels:Pe})}catch{we(H)}},[te,Pe]),Et=a.useCallback(async N=>{const H=Pe,ot=H.includes(N)?H.filter(kt=>kt!==N):[N,...H];We(ot);try{await nn({favoriteProviders:te,favoriteModels:ot})}catch{We(H)}},[Pe,te]),Le=a.useCallback(N=>{if(N<=0)return;const H=[...R];[H[N-1],H[N]]=[H[N],H[N-1]],j(H)},[R,j]),gt=a.useCallback(N=>{if(N>=R.length-1)return;const H=[...R];[H[N],H[N+1]]=[H[N+1],H[N]],j(H)},[R,j]),ut=a.useCallback(N=>{j(R.filter(H=>H!==N))},[R,j]),Me=new Map;for(const N of ye)Me.set(N.id,{name:N.name,description:N.description});const Qe=T.filter(N=>!o.includes(N.id)).sort((N,H)=>{const Ae=H.createdAt.localeCompare(N.createdAt);if(Ae!==0)return Ae;const ot=parseInt(N.id.slice(N.id.lastIndexOf("-")+1),10)||0;return(parseInt(H.id.slice(H.id.lastIndexOf("-")+1),10)||0)-ot}),rt=de?Qe.filter(N=>N.id.toLowerCase().includes(de.toLowerCase())||N.title&&N.title.toLowerCase().includes(de.toLowerCase())||N.description&&N.description.toLowerCase().includes(de.toLowerCase())):Qe;return t.jsxs("div",{className:"task-form",onDrop:dt,onDragOver:N=>N.preventDefault(),onPaste:st,children:[t.jsxs("div",{className:"task-form-primary-section",children:[e==="edit"&&r&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-form-title",children:"Title"}),t.jsx("input",{ref:ue,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:i||"",onChange:N=>r(N.target.value),disabled:L})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:"task-form-description",className:"description-label-row",children:[t.jsx("span",{children:"Description"}),t.jsx("span",{className:`description-auto-save-status${se==="idle"?"":" is-visible"}`,"aria-live":"polite",children:se==="saving"?"Saving...":se==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${Ie?" description--fullscreen":""}`,ref:at,onKeyDown:Lt,children:[Ie&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:qt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(aa,{size:14})})]}),t.jsx("textarea",{ref:Z,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Bt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:L||he}),(()=>{const N=!!n.trim()&&!L;return t.jsxs(t.Fragment,{children:[!Ie&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${N?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:qt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(io,{size:14})}),N&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${he?"refine-button--loading":""}`,onClick:()=>ee(H=>!H),disabled:he,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(Dn,{size:12,style:{verticalAlign:"middle"}}),he?"Refining...":"Refine"]})]})})(),me&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:N=>N.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ct("clarify"),"data-testid":"refine-clarify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Clarify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Make the description clearer and more specific"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ct("add-details"),"data-testid":"refine-add-details",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Add details"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Add implementation details and context"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ct("expand"),"data-testid":"refine-expand",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Expand"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Expand into a more comprehensive description"})]}),t.jsxs("div",{className:"refine-menu-item",onClick:()=>Ct("simplify"),"data-testid":"refine-simplify",children:[t.jsx("div",{className:"refine-menu-item-title",children:"Simplify"}),t.jsx("div",{className:"refine-menu-item-desc",children:"Simplify and make more concise"})]})]})]})]}),e==="create"&&(w||q)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[w&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const N=n.trim();if(!N){G("Enter a description first","error");return}W?.(),w(N)},disabled:L||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),q&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const N=n.trim();if(!N){G("Enter a description first","error");return}W?.(),q(N)},disabled:L||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),B,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>Q(N=>!N),"aria-expanded":ae,"aria-controls":"task-form-more-options",disabled:L,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),ae?t.jsx(Ys,{size:14}):t.jsx(zt,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${ae?"":" collapsed"}`,"aria-hidden":!ae,hidden:!ae,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),S.length>0&&t.jsx("div",{className:"inline-create-previews",children:S.map((N,H)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:N.previewUrl,alt:N.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>Tt(H),disabled:L,title:"Remove image",children:"×"})]},N.previewUrl))}),t.jsx("input",{ref:Ce,type:"file",accept:"image/*",onChange:N=>{const H=N.target.files?.[0];H&&(P([...S,{file:H,previewUrl:URL.createObjectURL(H)}]),N.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Ce.current?.click(),disabled:L,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),!z&&t.jsx(t.Fragment,{children:t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"dep-trigger-wrap",ref:oe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ce(N=>!N),disabled:L,children:o.length>0?`${o.length} selected`:"Add dependencies"}),F&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:de,onChange:N=>Te(N.target.value),onClick:N=>N.stopPropagation()}),rt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):rt.map(N=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(N.id)?" selected":""}`,onClick:()=>$t(N.id),onMouseDown:H=>H.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:N.id}),t.jsx("span",{className:"dep-dropdown-title",children:Dt(N.title||N.description||N.id,30)})]},N.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(N=>t.jsxs("span",{className:"dep-chip",children:[N,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>$t(N),disabled:L,children:"×"})]},N))})]})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),u&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:c??cs,onChange:N=>u(N.target.value),disabled:L,children:uc.map(N=>t.jsx("option",{value:N,children:N[0].toUpperCase()+N.slice(1)},N))})]}),ie&&pe!==void 0&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-execution-mode",className:"model-select-label",children:"Execution mode"}),t.jsxs("select",{id:"task-execution-mode","data-testid":"task-form-execution-mode-select",value:pe,onChange:N=>ie(N.target.value),disabled:L,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ke?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):fe.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:x==="preset"?M:x,onChange:N=>{const H=N.target.value;if(H==="default"){k("default"),y(""),m(""),g("");return}if(H==="custom"){k("custom"),y("");return}const Ae=ge.find(kt=>kt.id===H),ot=im(Ae);k("preset"),y(H),m(ot.executorValue),g(ot.validatorValue)},disabled:L,children:[t.jsx("option",{value:"default",children:"Use default"}),ge.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,ge.map(N=>t.jsx("option",{value:N.id,children:N.name},N.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),x==="preset"&&Fe?t.jsxs("small",{children:["Using preset: ",Fe.name]}):null,x==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>k("custom"),disabled:L,children:"Override"}):null,t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"executor-model",className:"model-select-label",children:"Executor"}),t.jsx(wn,{id:"executor-model",label:"Executor Model",value:d,onChange:N=>{k("custom"),y(""),m(N)},models:fe,disabled:L||x==="preset",favoriteProviders:te,onToggleFavorite:xt,favoriteModels:Pe,onToggleModelFavorite:Et})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Validator"}),t.jsx(wn,{id:"validator-model",label:"Validator Model",value:h,onChange:N=>{k("custom"),y(""),g(N)},models:fe,disabled:L||x==="preset",favoriteProviders:te,onToggleFavorite:xt,favoriteModels:Pe,onToggleModelFavorite:Et})]}),f&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(wn,{id:"planning-model",label:"Planning Model",value:p||"",onChange:N=>{k("custom"),y(""),f(N)},models:fe,disabled:L||x==="preset",favoriteProviders:te,onToggleFavorite:xt,favoriteModels:Pe,onToggleModelFavorite:Et})]}),v&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:b||"",onChange:N=>v(N.target.value),disabled:L||x==="preset",children:[t.jsxs("option",{value:"",children:["Default (",_e?.defaultThinkingLevel??"off",")"]}),t.jsx("option",{value:"off",children:"Off"}),t.jsx("option",{value:"minimal",children:"Minimal"}),t.jsx("option",{value:"low",children:"Low"}),t.jsx("option",{value:"medium",children:"Medium"}),t.jsx("option",{value:"high",children:"High"})]})]}),U&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"review-level",className:"model-select-label",children:"Review"}),t.jsxs("select",{id:"review-level",value:E??"",onChange:N=>U(N.target.value===""?0:parseInt(N.target.value,10)),disabled:L,children:[t.jsx("option",{value:"",children:"Default (None)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),A,t.jsxs("div",{className:"form-group","data-testid":"workflow-steps-section",children:[t.jsx("label",{children:"Workflow Steps"}),t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:ye.length>0&&ye.map(N=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${N.id}`,children:[t.jsx("input",{type:"checkbox",checked:R.includes(N.id),onChange:H=>{j(H.target.checked?[...R,N.id]:R.filter(Ae=>Ae!==N.id))},disabled:L}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[N.name,tM(N.phase||"pre-merge",N.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:N.description})]})]},N.id))})]}),R.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),R.map((N,H)=>{const Ae=Me.get(N);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${N}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:H+1}),t.jsx("span",{className:"workflow-step-order-name",children:Ae?.name||N}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Le(H),disabled:L||H===0,"data-testid":`workflow-step-move-up-${N}`,title:"Move up",children:t.jsx(Ys,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>gt(H),disabled:L||H===R.length-1,"data-testid":`workflow-step-move-down-${N}`,title:"Move down",children:t.jsx(zt,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>ut(N),disabled:L,"data-testid":`workflow-step-remove-${N}`,title:"Remove",children:t.jsx(Pt,{size:14})})]})]},N)})]})]})]})]})}const rm={pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:e}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function nM(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function sM(e,n){if(!e||!n)return null;const s=new Date(e).getTime(),r=new Date(n).getTime()-s;if(r<1e3)return`${r}ms`;const o=Math.round(r/1e3);if(o<60)return`${o}s`;const l=Math.floor(o/60),c=o%60;return`${l}m ${c}s`}function iM(e){return e?new Date(e).toLocaleString():null}function aM(e){const n=e.split(`
|
|
@@ -613,4 +613,4 @@ Delete anyway by removing these dependency references first?`))return;try{await
|
|
|
613
613
|
\x1B[33m[Process exited with code ${J}]\x1B[0m\r
|
|
614
614
|
`))});return()=>{Oe(),ye(),De(),se()}},[u,$?.sessionId,$?.id,$,U,re,ae,F,ce,A]),a.useEffect(()=>{U==="connected"&&s&&j.current!==s&&$&&(j.current=s,setTimeout(()=>{pe(s+`
|
|
615
615
|
`)},500))},[U,s,pe,$,g]),a.useEffect(()=>{if(!e)return;const Ne=_e=>{if(!(!_e.ctrlKey&&!_e.metaKey)){if(_e.code==="Equal"||_e.code==="NumpadAdd"){if(_e.preventDefault(),y.current){const Oe=y.current.options.fontSize||14;y.current.options.fontSize=Math.min(Oe+1,32),R.current?.fit()}return}if(_e.code==="Minus"||_e.code==="NumpadSubtract"){if(_e.preventDefault(),y.current){const Oe=y.current.options.fontSize||14;y.current.options.fontSize=Math.max(Oe-1,8),R.current?.fit()}return}if(_e.code==="Digit0"||_e.code==="Numpad0"){_e.preventDefault(),y.current&&(y.current.options.fontSize=14,R.current?.fit());return}}};return window.addEventListener("keydown",Ne),()=>window.removeEventListener("keydown",Ne)},[e]),a.useEffect(()=>{if(!e)return;const Ne=_e=>{_e.key==="Escape"&&n()};return document.addEventListener("keydown",Ne),()=>document.removeEventListener("keydown",Ne)},[e,n]),a.useEffect(()=>{U==="connected"&&y.current&&setTimeout(()=>{if(!y.current||!k.current)return;const Ne=k.current.querySelector(".xterm-helper-textarea");Ne&&Ne.focus();try{k.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[U]);const Te=a.useCallback(()=>{if(!k.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;y.current?.focus();const _e=k.current.querySelector(".xterm-helper-textarea");if(!_e)return;_e.autocapitalize="off",_e.autocomplete="off",_e.autocorrect="off",_e.spellcheck=!1,_e.setAttribute("inputmode","text");try{_e.focus({preventScroll:!0})}catch{_e.focus()}const Oe=_e.value.length;_e.setSelectionRange(Oe,Oe)},[]);a.useEffect(()=>de(()=>{y.current?.clear(),c(null),j.current=!1,y.current&&(y.current.dispose(),y.current=null),R.current=null,C.current=!1,d(!1),h(null),E().catch(_e=>{console.error("Failed to replace invalid terminal session:",_e)})}),[de,E]);const fe=a.useCallback(Ne=>{Ne.target===Ne.currentTarget&&n()},[n]),Se=a.useCallback(()=>{y.current?.clear()},[]),te=a.useCallback(async()=>{y.current?.clear(),c(null),j.current=!1;try{await z()}catch(Ne){o(xe(Ne)||"Failed to restart terminal session")}},[z]),we=a.useCallback(()=>{y.current&&(y.current.dispose(),y.current=null),R.current=null,C.current=!1,h(null),d(!1)},[]),Pe=a.useCallback(()=>{window.location.reload()},[]);if(!e)return null;const We=()=>{switch(U){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}},Ke=!I||!$&&!w||!u&&!m;return t.jsx("div",{className:"modal-overlay open",onClick:fe,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:f>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:M,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:[G.map(Ne=>t.jsxs("div",{className:`terminal-tab ${Ne.isActive?"terminal-tab--active":""}`,onClick:()=>B(Ne.id),title:Ne.title,role:"tab","aria-selected":Ne.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Ne.title}),G.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:_e=>{_e.stopPropagation(),W(Ne.id)},title:"Close tab",children:"×"})]},Ne.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:q,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(Bs,{size:16}),We()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[U==="disconnected"&&$&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:Q,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(hn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:te,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(hn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Se,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Ht,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(Pt,{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:[Ke&&!w&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),w&&!$&&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: ",w]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:X,"data-testid":"terminal-retry-btn",children:[t.jsx(hn,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(hn,{size:14}),"Refresh page"]})]})]})}),m&&$&&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:we,"data-testid":"terminal-reinit-btn",children:[t.jsx(hn,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Pe,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(hn,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:k,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:Te,onTouchStart:Te},$?.sessionId)]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${U}`,children:[U==="connected"&&"Connected",U==="connecting"&&"Connecting...",U==="reconnecting"&&"Reconnecting...",U==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • Ctrl+L clear • Esc close"})]})]})})}const Na={name:"",command:""};function gm(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function e_(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function t_({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(Na),[b,v]=a.useState(!1),[x,k]=a.useState(null),[M,y]=a.useState(null),R=a.useCallback(async()=>{try{u(!0);const I=await Xa(i);l(I)}catch(I){s(xe(I)||"Failed to load scripts","error")}finally{u(!1)}},[s,i]);a.useEffect(()=>{e&&R()},[e,R]);const j=a.useCallback(()=>{m(!0),g(null),f(Na),y(null)},[]),C=a.useCallback((I,w)=>{g(I),m(!1),f({name:I,command:w}),y(null)},[]),S=a.useCallback(()=>{g(null),m(!1),f(Na),y(null)},[]),P=a.useCallback(I=>{f(w=>({...w,name:I})),I&&!gm(I)?y("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):y(null)},[]),T=a.useCallback(async()=>{const I=p.name.trim(),w=p.command.trim();if(!I){s("Script name is required","error");return}if(!gm(I)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!w){s("Script command is required","error");return}v(!0);try{await cy(I,w,i),s(h?"Script updated":"Script created","success"),g(null),m(!1),f(Na),y(null),await R()}catch(q){const W=xe(q);W?.includes("already exists")?s("A script with this name already exists","error"):s(W||"Failed to save script","error")}finally{v(!1)}},[p,h,s,R,i]),_=a.useCallback(async I=>{try{await dy(I,i),s("Script deleted","success"),k(null),h===I&&(g(null),f(Na)),await R()}catch(w){s(xe(w)||"Failed to delete script","error")}},[h,s,R,i]),L=a.useCallback((I,w)=>{r&&r(I,w)},[r]);if(!e)return null;const G=d||h!==null,$=Object.entries(o).map(([I,w])=>({name:I,command:w}));return t.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",onClick:I=>I.stopPropagation(),role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(Bs,{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(it,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):G?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=>P(I.target.value),placeholder:"e.g., build, test, lint",disabled:b||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:M?"var(--color-error)":void 0}}),M&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:M}),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(w=>({...w,command:I.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:b,"data-testid":"script-command-input",style:{width:"100%",resize:"vertical",fontFamily:"monospace"}})]}),t.jsxs("div",{className:"scripts-modal-form-actions",style:{display:"flex",gap:"8px",justifyContent:"flex-end"},children:[t.jsx("button",{className:"btn btn-secondary",onClick:S,disabled:b,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:T,disabled:b||!!M,"data-testid":"script-save-btn",children:b?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:$.length===0?"No scripts defined":`${$.length} script${$.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:j,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx(Vt,{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(Bs,{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:e_(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:()=>L(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(rn,{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(Vt,{size:14,style:{transform:"rotate(45deg)"}})}),x===I.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>_(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(Ht,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>k(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${I.name}`,children:t.jsx(Pt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>k(I.name),title:"Delete","aria-label":`Delete ${I.name}`,"data-testid":`delete-script-${I.name}`,children:t.jsx(Ht,{size:14})})]})]})},I.name))})]})})]})})}function n_(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(b=>b+1)},[]),f=a.useCallback(b=>{l(b),m(null)},[]);return a.useEffect(()=>{l("."),m(null),r([])},[e]),a.useEffect(()=>{if(!n||!e)return;let b=!1;async function v(){u(!0),m(null);try{const x=await Ev(e,o==="."?void 0:o,s);b||r(x.entries)}catch(x){b||(m(xe(x)||"Failed to load files"),r([]))}finally{b||u(!1)}}return v(),()=>{b=!0}},[e,o,n,h,s]),{entries:i,currentPath:o,setPath:f,loading:c,error:d,refresh:p}}function s_(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,b]=a.useState(null),v=a.useCallback(M=>{o(M),b(null)},[]);a.useEffect(()=>{if(!e||!n){o(""),c(""),d(null),b(null);return}let M=!1;async function y(){h(!0),b(null);try{const R=await Mv(e,n,i);M||(o(R.content),c(R.content),d(R.mtime))}catch(R){M||(b(xe(R)||"Failed to load file"),o(""),c(""),d(null))}finally{M||h(!1)}}return y(),()=>{M=!0}},[e,n,s,i]);const x=r!==l,k=a.useCallback(async()=>{if(!(!e||!n||!x)){p(!0),b(null);try{const M=await _v(e,n,r,i);c(r),d(M.mtime)}catch(M){throw b(xe(M)||"Failed to save file"),M}finally{p(!1)}}},[e,n,r,x,i]);return{content:r,setContent:v,originalContent:l,loading:m,saving:g,error:f,save:k,hasChanges:x,mtime:u}}const i_=1e4;function a_(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function r_(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function o_(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 Cv(e);if(d)return;s(a_(g.project)),r(g.tasks.map(r_)),u(null)}catch(g){d||u(xe(g)||"Failed to load workspaces")}finally{d||l(!1)}}m();const h=window.setInterval(()=>{m()},i_);return()=>{d=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:i,loading:o,error:c}}function l_(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function c_(e){return e?new Date(e).toLocaleDateString():""}function bm(e,n){return e==="."?n:`${e}/${n}`}const Sa={visible:!1,x:0,y:0,entry:null,entryFullPath:""},xl={type:null,entry:null,entryFullPath:""},d_=200,u_=500,xm=10;function m_({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,b=g?.offsetLeft??0,v=g?.offsetTop??0,x=8;let k=e-b,M=n-v;k+h.width>p-x&&(k=p-x-h.width),M+h.height>f-x&&(M=f-x-h.height),k<x&&(k=x),M<x&&(M=x),c({x:k+b,y:M+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:wi,disabled:!1},{id:"move",label:"Move",icon:fb,disabled:!1},{id:"rename",label:"Rename",icon:Hn,disabled:!1},...u?[{id:"download-zip",label:"Download as ZIP",icon:Zr,disabled:!1}]:[{id:"download",label:"Download",icon:hg,disabled:!1}],{id:"divider",label:"",icon:wi,disabled:!0},{id:"delete",label:"Delete",icon:Ht,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 h_({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 p_({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(Sa),[g,p]=a.useState(xl),[f,b]=a.useState(!1),[v,x]=a.useState(null),[k,M]=a.useState(!1),[y,R]=a.useState(null),j=a.useRef(null),C=a.useRef(null),S=a.useRef(null),P=a.useRef(!1),T=a.useCallback(()=>{j.current!==null&&(window.clearTimeout(j.current),j.current=null),C.current!==null&&(window.clearTimeout(C.current),C.current=null)},[]),_=a.useCallback(()=>{T(),S.current=null,M(!1),R(null)},[T]);a.useEffect(()=>()=>{T()},[T]);const L=a.useCallback((z,X,E,U)=>{h({visible:!0,x:z,y:X,entry:E,entryFullPath:U})},[]),G=a.useCallback((z,X,E)=>{if(z.touches.length!==1)return;const U=z.touches[0];U&&(_(),S.current={x:U.clientX,y:U.clientY},C.current=window.setTimeout(()=>{M(!0),R(E)},d_),j.current=window.setTimeout(()=>{const pe=S.current;pe&&(P.current=!0,M(!1),R(null),T(),L(pe.x,pe.y,X,E))},u_))},[_,T,L]),$=a.useCallback(z=>{const X=S.current,E=z.touches[0];!X||!E||(Math.abs(E.clientX-X.x)>xm||Math.abs(E.clientY-X.y)>xm)&&_()},[_]),I=a.useCallback(()=>{_()},[_]);a.useEffect(()=>{if(!m.visible)return;const z=document.querySelector(".file-browser-list"),X=()=>{P.current=!1,_(),h(Sa)};return z?.addEventListener("scroll",X),()=>z?.removeEventListener("scroll",X)},[_,m.visible]),a.useEffect(()=>{if(!m.visible)return;const z=X=>{X.key==="Escape"&&(P.current=!1,h(Sa))};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[m.visible]);const w=a.useCallback((z,X)=>{z.preventDefault(),z.stopPropagation(),_(),P.current=!1,L(z.clientX,z.clientY,X,bm(n,X.name))},[_,n,L]),q=a.useCallback(z=>{if(!m.entry)return;P.current=!1;const X=m.entry,E=m.entryFullPath;if(h(Sa),z==="download"){if(!c)return;const U=fh(c,E,d);window.open(Hs(U),"_blank");return}if(z==="download-zip"){if(!c)return;const U=$v(c,E,d);window.open(Hs(U),"_blank");return}p({type:z,entry:X,entryFullPath:E}),x(null)},[m,c,d]),W=a.useCallback(async z=>{if(!(!g.type||!g.entry||!c)){b(!0),x(null);try{switch(g.type){case"copy":await Tv(c,g.entryFullPath,z,d);break;case"move":await Rv(c,g.entryFullPath,z,d);break;case"rename":await Pv(c,g.entryFullPath,z,d);break;case"delete":await Iv(c,g.entryFullPath,d);break}p(xl),u?.()}catch(X){x(xe(X)||"Operation failed")}finally{b(!1)}}},[g,c,u,d]),B=a.useCallback(()=>{p(xl),x(null)},[]),A=a.useCallback((z,X)=>{if(P.current){P.current=!1;return}m.visible||(z.type==="directory"?i(X):s(X))},[m.visible,i,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(it,{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 z=n.split("/").filter(Boolean);z.pop(),i(z.length===0?".":z.join("/"))},children:[t.jsx(en,{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(z=>{const X=bm(n,z.name),E=k&&y===X;return t.jsxs("div",{className:`file-node file-node--${z.type} ${E?"file-node--long-pressing":""}`,onClick:()=>A(z,X),onContextMenu:U=>w(U,z),onTouchStart:U=>G(U,z,X),onTouchMove:$,onTouchEnd:I,onTouchCancel:I,children:[t.jsx("div",{className:"file-node-icon",children:z.type==="directory"?t.jsx(jn,{size:16}):t.jsx(nh,{size:16})}),t.jsx("div",{className:"file-node-name",children:z.name}),z.type==="file"&&z.size!==void 0&&t.jsx("div",{className:"file-node-size",children:l_(z.size)}),z.mtime&&t.jsx("div",{className:"file-node-time",children:c_(z.mtime)})]},z.name)})}),m.visible&&m.entry&&t.jsx(m_,{x:m.x,y:m.y,entry:m.entry,onAction:q,onClose:()=>{P.current=!1,h(Sa)}}),g.type&&g.entry&&t.jsx(h_,{type:g.type,entry:g.entry,entryFullPath:g.entryFullPath,onConfirm:W,onCancel:B,loading:f,error:v})]})}function f_(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function g_({content:e,onChange:n,readOnly:s,filePath:i}){const[r,o]=a.useState(!1),[l,c]=a.useState(!0),u=f_(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(th,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${d?"btn-primary":""}`,onClick:h,disabled:d,"aria-label":"Preview mode",children:[t.jsx(Vi,{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(zr,{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(zr,{size:14})})]}),d?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(Qs,{remarkPlugins:[Xs],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 b_(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function x_({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(Kc,{size:14}):t.jsx(Al,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(zt,{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(Kc,{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(Al,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:b_(c.title)})]},c.id))]})]})]})}const v_=768,ef=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),y_=new Set([...ef,".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 vm(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return y_.has(n)}function k_(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return ef.has(n)}function j_({initialWorkspace:e="project",onClose:n,onWorkspaceChange:s,projectId:i}){const{projectName:r,workspaces:o}=o_(i),[l,c]=a.useState(e),[u,d]=a.useState(null),[m,h]=a.useState(!1),[g,p]=a.useState("list"),{entries:f,currentPath:b,setPath:v,loading:x,error:k,refresh:M}=n_(l,!0,i),{content:y,setContent:R,originalContent:j,loading:C,saving:S,error:P,save:T,hasChanges:_,mtime:L}=s_(l,u,!0,i);a.useEffect(()=>{c(e)},[e]),a.useEffect(()=>{const z=()=>{h(window.innerWidth<=v_)};return z(),window.addEventListener("resize",z),()=>window.removeEventListener("resize",z)},[]),a.useEffect(()=>{u||p("list")},[u]),a.useEffect(()=>{const z=X=>{X.key==="Escape"&&n(),(X.metaKey||X.ctrlKey)&&X.key==="s"&&(X.preventDefault(),_&&!S&&T())};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[n,_,S,T]);const G=a.useCallback(z=>{d(z),m&&p("editor")},[m]),$=a.useCallback(()=>{p("list")},[]),I=a.useCallback(()=>{R(j)},[j,R]),w=a.useCallback(z=>{c(z),d(null),p("list"),s?.(z)},[s]),W=`Files — ${a.useMemo(()=>l==="project"?"Project":o.find(z=>z.id===l)?.id??l,[l,o])}`,B=a.useMemo(()=>!u||!k_(u)?null:fh(l,u,i),[u,l,i]),A=z=>{const X=new Blob([z]).size;return X<1024?`${X} B`:`${(X/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",onClick:n,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",onClick:z=>z.stopPropagation(),children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(jn,{size:18}),t.jsx("span",{children:W}),u&&t.jsx("span",{className:"file-browser-header-path",children:u})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(x_,{currentWorkspace:l,projectName:r,workspaces:o,onSelect:w}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${m?"mobile":""} ${g==="list"?"active":""}`,children:t.jsx(p_,{entries:f,currentPath:b,onSelectFile:G,onNavigate:v,loading:x,error:k,onRetry:M,workspace:l,onRefresh:M,projectId:i})}),t.jsx("div",{className:`file-browser-content ${m?"mobile":""} ${g==="editor"?"active":""}`,children:u?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[m&&g==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:$,"aria-label":"Back to file list",children:[t.jsx(ia,{size:16}),t.jsx("span",{children:"Back"})]}),u,vm(u)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Rg,{size:12}),"Binary file — read only"]}),L&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(L).toLocaleString()]}),C&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!B&&_&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:I,disabled:S,children:[t.jsx(Eb,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void T(),disabled:S,children:[t.jsx(lh,{size:14}),S?"Saving...":"Save"]})]})})]}),P&&!B&&t.jsx("div",{className:"file-browser-error-banner",children:P}),B?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:B,alt:u??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(g_,{content:y,onChange:R,filePath:u,readOnly:vm(u)})}),!B&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:A(y)}),_&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(jn,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}function w_(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 Hx();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:xe(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 N_(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 S_(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const tf="kb-usage-hidden-windows";function ym(e){const n=Nn(tf,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 C_(e,n){ts(tf,JSON.stringify(e),n)}function nf(e,n,s){return s[e]?.includes(n)??!1}function E_({window:e,viewMode:n,isHidden:s,onToggleHidden:i}){const r=S_(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,u=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let d=e.resetText;if(!d&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const x=Math.floor(v/36e5),k=Math.floor(x/24),M=x%24;k>0&&M>0?d=`resets in ${k}d ${M}h`:k>0?d=`resets in ${k}d`:x>0?d=`resets in ${x}h`:d=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let g=0;h&&(g=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",f=m?.status==="behind",b=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:i,"aria-label":`${s?"Show":"Hide"} ${e.label}`,"data-testid":"usage-window-hide-btn",children:s?t.jsx($r,{size:14}):t.jsx(Vi,{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:N_(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(lc,{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(Bb,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),b&&t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function M_(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")?"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 __({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:i,onShowAllHidden:r}){const o=s[e.name]?.length??0,l=()=>{switch(e.status){case"ok":return t.jsx("span",{className:"usage-status-badge usage-status-badge--connected",children:"Connected"});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(Mn,{provider:M_(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name})]}),t.jsxs("div",{className:"usage-provider-actions",children:[l(),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,")"]})]})]}),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=nf(e.name,c.label,s);return t.jsx(E_,{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 A_(){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 T_({isOpen:e,onClose:n,projectId:s}){const{providers:i,loading:r,error:o,lastUpdated:l,refresh:c}=w_({autoRefresh:e}),[u,d]=a.useState(!1),[m,h]=a.useState("used"),[g,p]=a.useState(()=>ym(s)),f=a.useRef(null),b=a.useRef(e),v=a.useRef(!1);a.useEffect(()=>{e||(v.current=!1)},[e]),a.useEffect(()=>{i.length>0&&(v.current=!0)},[i.length]),a.useEffect(()=>{!b.current&&e&&(!l||Date.now()-l.getTime()>5e3)&&c(),b.current=e},[e,l,c]),a.useEffect(()=>{const j=Nn("kb-usage-view-mode",s);if(j==="used"||j==="remaining"){h(j);return}h("used")},[s]);const x=a.useCallback(j=>{h(j),ts("kb-usage-view-mode",j,s)},[s]);a.useEffect(()=>{p(ym(s))},[s]),a.useEffect(()=>{C_(g,s)},[g,s]);const k=a.useCallback((j,C)=>{p(S=>{if(nf(j,C,S)){const P=(S[j]??[]).filter(T=>T!==C);if(P.length===0){const{[j]:T,..._}=S;return _}return{...S,[j]:P}}return{...S,[j]:[...S[j]??[],C]}})},[]),M=a.useCallback(j=>{p(C=>{if(!C[j])return C;const{[j]:S,...P}=C;return P})},[]),y=a.useCallback(async()=>{d(!0),await c(),d(!1)},[c]);a.useEffect(()=>{if(!e)return;const j=C=>{C.key==="Escape"&&n()};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[e,n]);const R=a.useCallback(j=>{j.target===j.currentTarget&&n()},[n]);return e?t.jsx("div",{className:"modal-overlay open",onClick:R,"data-testid":"usage-modal-overlay",children:t.jsxs("div",{className:"modal usage-modal","data-testid":"usage-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Ss,{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 ${m==="used"?"active":""}`,onClick:()=>x("used"),"aria-pressed":m==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${m==="remaining"?"active":""}`,onClick:()=>x("remaining"),"aria-pressed":m==="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(Pt,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:f,children:(r||!v.current&&!o)&&i.length===0?t.jsx(A_,{}):o&&i.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:o}),t.jsx("button",{className:"btn btn-sm",onClick:y,children:"Retry"})]}):i.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:i.map(j=>t.jsx(__,{provider:j,viewMode:m,hiddenWindows:g,onToggleWindow:k,onShowAllHidden:M},j.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:l&&t.jsxs("span",{children:["Last updated: ",l.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:y,disabled:r||u,"data-testid":"usage-refresh-btn",children:[t.jsx(hn,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]})}):null}function sf(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 Yr(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 R_={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},af={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},I_={cron:Xm,webhook:ch,api:Zm,manual:vn},P_={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},$_={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function D_({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(tn,{size:12}):t.jsx(Ka,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:sf(n)})]})}function L_({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"} ${Yr(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(tn,{size:12}):t.jsx(Ka,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:Yr(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:af[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:sf(r)}),s?t.jsx(Ys,{size:12}):t.jsx(zt,{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 z_({routine:e,onEdit:n,onDelete:s,onRun:i,onToggle:r,running:o}){const[l,c]=a.useState(!1),u=a.useCallback(()=>{window.confirm(`Delete routine "${e.name}"? This cannot be undone.`)&&s(e)},[e,s]),d=R_[e.trigger.type],m=I_[e.trigger.type],h=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"}`,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:d,color:d},children:[t.jsx(m,{size:10}),af[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(jn,{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:t.jsx(rn,{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(Fs,{size:14}):t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Hn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:u,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Ht,{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(Si,{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"&&h&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ji,{size:12}),t.jsx("code",{className:"routine-cron",children:h})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:P_[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:$_[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:Yr(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:Yr(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(D_,{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})]})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>c(g=>!g),"aria-expanded":l,children:[l?t.jsx(Ys,{size:12}):t.jsx(zt,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),l&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,p)=>t.jsx(L_,{result:g,index:p},`${g.startedAt}-${p}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function F_({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(Bs,{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(sb,{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(Dn,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function vl(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function O_(e){return e==="command"?{id:vl(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:vl(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:vl(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function U_({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??""),[b,v]=a.useState(e.taskTitle??""),[x,k]=a.useState(e.taskDescription??""),[M,y]=a.useState(e.taskColumn??"triage"),[R,j]=a.useState(e.timeoutMs),[C,S]=a.useState(e.continueOnFailure??!1),[P,T]=a.useState({}),[_,L]=a.useState([]),[G,$]=a.useState(!1),[I,w]=a.useState(null);a.useEffect(()=>{let z=!1;return $(!0),w(null),is().then(X=>{z||L(X.models)}).catch(X=>{z||w(X instanceof Error?X.message:"Failed to load models")}).finally(()=>{z||$(!1)}),()=>{z=!0}},[]);const q=a.useCallback(()=>{const z={};return i.trim()||(z.name="Step name is required"),o==="command"&&!c.trim()&&(z.command="Command is required"),o==="ai-prompt"&&!d.trim()&&(z.prompt="Prompt is required"),o==="create-task"&&!x.trim()&&(z.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(z.modelProvider="Both model provider and model ID must be set together"),R!==void 0&&R<1e3&&(z.timeoutMs="Timeout must be at least 1 second (1000ms)"),T(z),Object.keys(z).length===0},[i,o,c,d,x,h,p,R]),W=h&&p?`${h}/${p}`:"",B=a.useCallback(z=>{if(!z)g(""),f("");else{const X=z.indexOf("/");X!==-1&&(g(z.slice(0,X)),f(z.slice(X+1)))}},[]),A=a.useCallback(()=>{if(!q())return;const z={...e,name:i.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?d.trim():void 0,taskTitle:o==="create-task"&&b.trim()?b.trim():void 0,taskDescription:o==="create-task"&&x.trim()?x.trim():void 0,taskColumn:o==="create-task"?M: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:C};o!=="ai-prompt"&&delete z.prompt,o!=="create-task"&&(delete z.taskTitle,delete z.taskDescription,delete z.taskColumn),n(z)},[q,n,e,i,o,c,d,b,x,M,h,p,R,C]);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:z=>r(z.target.value),"aria-invalid":!!P.name}),P.name&&t.jsx("small",{className:"field-error",children:P.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:z=>l(z.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:z=>u(z.target.value),rows:2,"aria-invalid":!!P.command}),P.command&&t.jsx("small",{className:"field-error",children:P.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:z=>m(z.target.value),rows:3,"aria-invalid":!!P.prompt}),P.prompt&&t.jsx("small",{className:"field-error",children:P.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(wn,{id:`step-model-${e.id}`,label:"Model",models:_,value:W,onChange:B,placeholder:"Use default",disabled:G}),I&&t.jsx("small",{className:"field-error",children:I}),t.jsx("small",{children:"AI model for this step. Uses default if not selected."})]})]}),o==="create-task"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-title-${e.id}`,children:"Task Title (optional)"}),t.jsx("input",{id:`step-task-title-${e.id}`,type:"text",placeholder:"e.g. Review weekly dependencies",value:b,onChange:z=>v(z.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:x,onChange:z=>k(z.target.value),rows:4,"aria-invalid":!!P.taskDescription}),P.taskDescription&&t.jsx("small",{className:"field-error",children:P.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:M,onChange:z=>y(z.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(wn,{id:`step-task-model-${e.id}`,label:"Model",models:_,value:W,onChange:B,placeholder:"Use default",disabled:G}),I&&t.jsx("small",{className:"field-error",children:I}),P.modelProvider&&t.jsx("small",{className:"field-error",children:P.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:z=>j(z.target.value?Number(z.target.value):void 0),"aria-invalid":!!P.timeoutMs}),P.timeoutMs&&t.jsx("small",{className:"field-error",children:P.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:C,onChange:z=>S(z.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:A,children:"Save Step"})]})]})}function B_({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=O_(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(U_,{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(oc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(F_,{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(Ys,{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(zt,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(d.id),title:"Edit","aria-label":`Edit ${d.name}`,children:t.jsx(Hn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(d.id),title:"Delete","aria-label":`Delete ${d.name}`,children:t.jsx(Ht,{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(Vt,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx(Vt,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx(Vt,{size:14}),"Add Create Task Step"]})]})]})}const rf={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},H_={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function q_(e){const n=e.trim();for(const[s,i]of Object.entries(rf))if(i===n)return s;return"custom"}function V_(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function W_(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 G_(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 K_=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],J_=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function km(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function jm({routine:e,onSubmit:n,onCancel:s,scope:i,projectId:r,onScopeChange:o}){const l=!!e,c=e?G_(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,b]=a.useState(c.cronExpression),[v,x]=a.useState(()=>c.triggerType!=="cron"?"custom":q_(c.cronExpression)),[k,M]=a.useState(c.webhookPath),[y,R]=a.useState(c.webhookSecret),[j,C]=a.useState(c.endpoint),[S,P]=a.useState(e?.executionPolicy??"queue"),[T,_]=a.useState(e?.catchUpPolicy??"run_one"),[L,G]=a.useState(e?.enabled??!0),$=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,I=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[w,q]=a.useState(e?.steps&&e.steps.length>0&&!$&&!I?"advanced":"simple"),[W,B]=a.useState(()=>$?"ai-prompt":I?"create-task":"command"),[A,z]=a.useState(e?.command??""),[X,E]=a.useState(e?.steps??[]),[U,pe]=a.useState(!1),[ie,re]=a.useState(e?.timeoutMs??3e5),[F,ce]=a.useState($?e.steps?.[0]?.prompt??"":""),[ae,Q]=a.useState(I?e.steps?.[0]?.taskTitle??"":""),[de,Te]=a.useState(I?e.steps?.[0]?.taskDescription??"":""),[fe,Se]=a.useState(I?e.steps?.[0]?.taskColumn??"triage":"triage"),[te,we]=a.useState($||I?e.steps?.[0]?.modelProvider??"":""),[Pe,We]=a.useState($||I?e.steps?.[0]?.modelId??"":""),[Ke,Ne]=a.useState([]),[_e,Oe]=a.useState(!1),[ye,De]=a.useState(null),[se,J]=a.useState(i??"global"),[me,ee]=a.useState({}),[he,le]=a.useState(!1),Ie=a.useRef(!0);a.useEffect(()=>()=>{Ie.current=!1},[]),a.useEffect(()=>{i&&J(i)},[i]),a.useEffect(()=>{let be=!1;return Oe(!0),De(null),is().then(Je=>{be||Ne(Je.models)}).catch(Je=>{be||De(Je instanceof Error?Je.message:"Failed to load models")}).finally(()=>{be||Oe(!1)}),()=>{be=!0}},[]);const Ze=te&&Pe?`${te}/${Pe}`:"",at=a.useCallback(be=>{if(!be){we(""),We("");return}const Je=be.indexOf("/");Je!==-1&&(we(be.slice(0,Je)),We(be.slice(Je+1)))},[]),oe=a.useCallback(()=>{const be={};if(u.trim()||(be.name="Name is required"),se==="project"&&!r&&(be.scope="Project-specific entries require an active project."),g==="cron"&&v==="custom"&&(f.trim()?V_(f)||(be.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):be.cronExpression="Cron expression is required"),g==="webhook"&&!k.trim()&&(be.webhookPath="Webhook path is required"),g==="api"&&!j.trim()&&(be.endpoint="API endpoint is required"),w==="simple")W==="command"&&!A.trim()&&(be.command="Command is required"),W==="ai-prompt"&&!F.trim()&&(be.prompt="Prompt is required"),W==="create-task"&&!de.trim()&&(be.taskDescription="Task description is required"),(te.trim()&&!Pe.trim()||!te.trim()&&Pe.trim())&&(be.model="Both model provider and model ID must be set, or both must be empty");else{X.length===0&&(be.steps="At least one step is required"),U&&(be.stepsEditing="Please save or cancel all step edits before saving the routine");const Je=[];X.forEach((st,dt)=>{st.name?.trim()||Je.push(`Step ${dt+1}: Name is required`),st.type==="command"&&!st.command?.trim()&&Je.push(`Step ${dt+1}: Command is required`),st.type==="ai-prompt"&&!st.prompt?.trim()&&Je.push(`Step ${dt+1}: Prompt is required`),st.type==="create-task"&&!st.taskDescription?.trim()&&Je.push(`Step ${dt+1}: Task description is required`)}),Je.length>0&&(be.steps=Je.join("; "))}return ie<1e3&&(be.timeoutMs="Timeout must be at least 1 second (1000ms)"),ee(be),Object.keys(be).length===0},[u,g,f,v,k,j,se,r,w,W,A,F,de,te,Pe,X,U,ie]),Z=a.useCallback(async be=>{if(be.preventDefault(),!!oe()){le(!0);try{let Je=e?.scope??se??(r?"project":"global");Je==="project"&&!r&&(Je="global");const st=W_(g,f,k,y,j);let dt,Tt;w==="simple"?W==="command"?dt=A.trim()||void 0:W==="ai-prompt"?Tt=[{id:km(),type:"ai-prompt",name:u.trim(),prompt:F.trim(),modelProvider:te.trim()||void 0,modelId:Pe.trim()||void 0}]:Tt=[{id:km(),type:"create-task",name:u.trim(),taskTitle:ae.trim()||void 0,taskDescription:de.trim(),taskColumn:fe,modelProvider:te.trim()||void 0,modelId:Pe.trim()||void 0}]:Tt=X;const $t={name:u.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:st,command:dt,steps:Tt,timeoutMs:ie,executionPolicy:S,catchUpPolicy:T,enabled:L,scope:Je};await n($t)}finally{Ie.current&&le(!1)}}},[oe,n,u,m,g,f,k,y,j,w,W,A,F,te,Pe,ae,de,fe,X,ie,S,T,L,se,r,e?.scope,e?.agentId]),ue="routine-name-error",Ce="routine-cron-error",$e="routine-webhook-error",ve="routine-endpoint-error",Ge="routine-command-error",je="routine-prompt-error",Ue="routine-task-description-error",He="routine-model-error",ge="routine-timeout-error",Fe=a.useCallback(be=>{x(be),be!=="custom"&&b(rf[be])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:Z,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:be=>d(be.target.value),"aria-invalid":!!me.name,"aria-describedby":me.name?ue:void 0}),me.name&&t.jsx("small",{id:ue,className:"field-error",children:me.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:be=>h(be.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:()=>{J("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:()=>{J("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(jn,{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."}),me.scope&&t.jsx("small",{className:"field-error",children:me.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(Xm,{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(ch,{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(Zm,{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(vn,{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:be=>Fe(be.target.value),children:Object.entries(H_).map(([be,Je])=>t.jsx("option",{value:be,children:Je},be))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:f,onChange:be=>b(be.target.value),disabled:v!=="custom","aria-invalid":!!me.cronExpression,"aria-describedby":me.cronExpression?Ce:void 0}),me.cronExpression?t.jsx("small",{id:Ce,className:"field-error",children:me.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:k,onChange:be=>M(be.target.value),"aria-invalid":!!me.webhookPath,"aria-describedby":me.webhookPath?$e:void 0}),me.webhookPath?t.jsx("small",{id:$e,className:"field-error",children:me.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:y,onChange:be=>R(be.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:j,onChange:be=>C(be.target.value),"aria-invalid":!!me.endpoint,"aria-describedby":me.endpoint?ve:void 0}),me.endpoint?t.jsx("small",{id:ve,className:"field-error",children:me.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${w==="simple"?" active":""}`,onClick:()=>q("simple"),role:"radio","aria-checked":w==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${w==="advanced"?" active":""}`,onClick:()=>q("advanced"),role:"radio","aria-checked":w==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:w==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),w==="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${W==="command"?" active":""}`,onClick:()=>B("command"),role:"radio","aria-checked":W==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${W==="ai-prompt"?" active":""}`,onClick:()=>B("ai-prompt"),role:"radio","aria-checked":W==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${W==="create-task"?" active":""}`,onClick:()=>B("create-task"),role:"radio","aria-checked":W==="create-task",children:"Create Task"})]})]}),W==="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:A,onChange:be=>z(be.target.value),"aria-invalid":!!me.command,"aria-describedby":me.command?Ge:void 0}),me.command?t.jsx("small",{id:Ge,className:"field-error",children:me.command}):t.jsx("small",{children:"Shell command to execute."})]}):W==="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:F,onChange:be=>ce(be.target.value),rows:3,"aria-invalid":!!me.prompt,"aria-describedby":me.prompt?je:void 0}),me.prompt?t.jsx("small",{id:je,className:"field-error",children:me.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(wn,{id:"routine-model",label:"Model",models:Ke,value:Ze,onChange:at,placeholder:"Use default",disabled:_e}),ye&&t.jsx("small",{className:"field-error",children:ye}),me.model&&t.jsx("small",{id:He,className:"field-error",children:me.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:ae,onChange:be=>Q(be.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:de,onChange:be=>Te(be.target.value),rows:4,"aria-invalid":!!me.taskDescription,"aria-describedby":me.taskDescription?Ue:void 0}),me.taskDescription?t.jsx("small",{id:Ue,className:"field-error",children:me.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:fe,onChange:be=>Se(be.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(wn,{id:"routine-task-model",label:"Executor Model",models:Ke,value:Ze,onChange:at,placeholder:"Use default",disabled:_e}),ye&&t.jsx("small",{className:"field-error",children:ye}),me.model&&t.jsx("small",{id:He,className:"field-error",children:me.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(B_,{steps:X,onChange:E,onEditingChange:pe}),me.steps&&t.jsx("small",{className:"field-error",children:me.steps}),me.stepsEditing&&t.jsx("small",{className:"field-error",children:me.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:ie,onChange:be=>re(Number(be.target.value)),"aria-invalid":!!me.timeoutMs,"aria-describedby":me.timeoutMs?ge:void 0}),me.timeoutMs?t.jsx("small",{id:ge,className:"field-error",children:me.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:S,onChange:be=>P(be.target.value),children:K_.map(be=>t.jsx("option",{value:be.value,children:be.label},be.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:T,onChange:be=>_(be.target.value),children:J_.map(be=>t.jsx("option",{value:be.value,children:be.label},be.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:L,onChange:be=>G(be.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:he,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:he,children:he?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const Y_=3e4;function Q_({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=a.useMemo(()=>({scope:i,projectId:i==="project"?s:void 0}),[i,s]),f=a.useCallback(async()=>{try{const _=await Zv(p);l(_)}catch(_){n(xe(_)||"Failed to load routines","error")}},[n,p]);a.useEffect(()=>{f()},[f]),a.useEffect(()=>{const _=setInterval(()=>{f()},Y_);return()=>clearInterval(_)},[f]),a.useEffect(()=>{const _=L=>{L.key==="Escape"&&(c!=="list"?(u("list"),m(void 0)):e())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,c]);const b=a.useCallback(_=>{_.target===_.currentTarget&&e()},[e]),v=a.useCallback(async _=>{try{await ey(_,p),n("Routine created","success"),u("list"),await f()}catch(L){n(xe(L)||"Failed to create routine","error")}},[n,f,p]),x=a.useCallback(_=>{m(_),u("edit")},[]),k=a.useCallback(async _=>{if(d)try{await cd(d.id,_,p),n("Routine updated","success"),u("list"),m(void 0),await f()}catch(L){n(xe(L)||"Failed to update routine","error")}},[d,n,f,p]),M=a.useCallback(async _=>{try{await ty(_.id,p),n(`Deleted "${_.name}"`,"success"),await f()}catch(L){n(xe(L)||"Failed to delete routine","error")}},[n,f,p]),y=a.useCallback(async _=>{g(_.id);try{const{result:L}=await ny(_.id,p);L.success?n(`"${_.name}" completed successfully`,"success"):n(`"${_.name}" failed: ${L.error||"Unknown error"}`,"error"),await f()}catch(L){n(xe(L)||"Failed to run routine","error")}finally{g(null)}},[n,f,p]),R=a.useCallback(async _=>{try{await cd(_.id,{enabled:!_.enabled},p),n(`"${_.name}" ${_.enabled?"disabled":"enabled"}`,"success"),await f()}catch(L){n(xe(L)||"Failed to toggle routine","error")}},[n,f,p]),j=a.useCallback(()=>{u("list"),m(void 0)},[]),C=a.useCallback(_=>{r(_),u("list"),m(void 0)},[]),S=()=>c==="create"?t.jsx(jm,{onSubmit:v,onCancel:j,scope:i,projectId:s}):c==="edit"&&d?t.jsx(jm,{routine:d,onSubmit:k,onCancel:j,scope:i,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(vn,{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(Vt,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(_=>t.jsx(z_,{routine:_,onEdit:x,onDelete:M,onRun:y,onToggle:R,running:h===_.id},_.id))}),P=()=>S(),T=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",onClick:b,children:t.jsxs("div",{className:"modal modal-lg",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header scheduling-modal-header",children:[t.jsxs("div",{className:"scheduling-header-main-row",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(vn,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsxs("div",{className:"modal-header-actions",children:[T&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>u("create"),"aria-label":"Create new automation",children:[t.jsx(Vt,{size:14}),"New Automation"]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(Pt,{size:20})})]})]}),t.jsx("div",{className:"scheduling-header-scope-row",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:()=>C("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:()=>C("project"),"aria-pressed":i==="project",title:"Project-scoped automations",children:[t.jsx(jn,{size:14}),"Project"]})]})})]}),t.jsxs("div",{className:"scheduling-summary","aria-live":"polite",children:[t.jsx(vn,{size:14}),t.jsxs("span",{children:[o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"detail-tabs",role:"tablist",children:t.jsxs("button",{className:"detail-tab detail-tab-active",role:"tab",id:"tab-routines","aria-selected":"true","aria-controls":"scheduled-tasks-content",onClick:()=>{u("list"),m(void 0)},children:[t.jsx(vn,{size:14})," Routines"]})}),t.jsx("div",{className:"schedule-modal-content",role:"tabpanel",id:"scheduled-tasks-content",children:P()})]})})}const X_=3e4,ec=new Map,yl=new Map;function wm(e){return e??"default"}function Nm(e){const n=ec.get(e);return n?Date.now()>=n.expiresAt?(ec.delete(e),null):n:null}function Z_(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 eA(e){const n=yl.get(e);if(n)return n;const s=Ba().then(({providers:i,ghCli:r})=>{const l={...Z_(i,r),ghCli:r,expiresAt:Date.now()+X_};return ec.set(e,l),l}).finally(()=>{yl.delete(e)});return yl.set(e,s),s}function of(e){const n=wm(e),s=Nm(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=wm(e),p=Nm(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 eA(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 lf({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(Pt,{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 tA({isOpen:e,onClose:n,projectId:s,tasks:i,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const[u,d]=a.useState(""),[m,h]=a.useState([]),[g,p]=a.useState([]),[f,b]=a.useState(!1),[v,x]=a.useState(""),[k,M]=a.useState(""),[y,R]=a.useState(""),[j,C]=a.useState(""),[S,P]=a.useState(""),[T,_]=a.useState("default"),[L,G]=a.useState(!1),[$,I]=a.useState([]),[w,q]=a.useState(!1),[W,B]=a.useState(void 0),[A,z]=a.useState(cs),[X,E]=a.useState(null),[U,pe]=a.useState([]),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),ae=a.useRef(null),[Q,de]=a.useState(!1),[Te,fe]=a.useState(""),Se=a.useRef(null),{hasAiProvider:te,hasGithub:we,loading:Pe}=of(s),We=a.useCallback(le=>{q(!0),I(le)},[]),Ke=a.useCallback(()=>{q(!1)},[]),Ne=a.useCallback(async()=>{if(U.length>0){re(!0);return}ce(!0);try{const le=await oa(void 0,s);pe(le),re(!0)}catch(le){const Ie=xe(le);o(Ie?`Failed to load agents: ${Ie}`:"Failed to load agents","error"),re(!1)}finally{ce(!1)}},[U.length,s,o]);a.useEffect(()=>{if(!ie)return;const le=Ie=>{ae.current&&!ae.current.contains(Ie.target)&&re(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[ie]),a.useEffect(()=>{if(!Q)return;const le=Ie=>{Se.current&&!Se.current.contains(Ie.target)&&(de(!1),fe(""))};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[Q]);const _e=i.filter(le=>!m.includes(le.id)).sort((le,Ie)=>{const Ze=Ie.createdAt.localeCompare(le.createdAt);if(Ze!==0)return Ze;const at=parseInt(le.id.slice(le.id.lastIndexOf("-")+1),10)||0;return(parseInt(Ie.id.slice(Ie.id.lastIndexOf("-")+1),10)||0)-at}),Oe=Te?_e.filter(le=>le.id.toLowerCase().includes(Te.toLowerCase())||le.title&&le.title.toLowerCase().includes(Te.toLowerCase())||le.description&&le.description.toLowerCase().includes(Te.toLowerCase())):_e,ye=(le,Ie)=>le.length>Ie?le.slice(0,Ie)+"…":le;a.useEffect(()=>{const le=u.trim()!==""||m.length>0||g.length>0||v!==""||k!==""||y!==""||j!==""||$.length>0||X!==null||W!==void 0||A!==cs;G(le)},[u,m,g,v,k,y,j,$,X,W,A]);const De=a.useCallback(()=>{L&&!confirm("You have unsaved changes. Discard them?")||(g.forEach(le=>URL.revokeObjectURL(le.previewUrl)),p([]),d(""),h([]),x(""),M(""),R(""),C(""),P(""),_("default"),I([]),q(!1),E(null),re(!1),B(void 0),z(cs),G(!1),n())},[L,n,g]),se=a.useCallback(async()=>{const le=u.trim();if(!(!le||f)){b(!0);try{const Ie=v.indexOf("/"),Ze=k.indexOf("/"),at=y.indexOf("/"),oe=await r({title:void 0,description:le,column:"triage",dependencies:m.length?m:void 0,enabledWorkflowSteps:w?$.length>0?$:[]:void 0,...X?{assignedAgentId:X}:{},modelPresetId:T==="preset"&&S||void 0,modelProvider:v&&Ie!==-1?v.slice(0,Ie):void 0,modelId:v&&Ie!==-1?v.slice(Ie+1):void 0,validatorModelProvider:k&&Ze!==-1?k.slice(0,Ze):void 0,validatorModelId:k&&Ze!==-1?k.slice(Ze+1):void 0,planningModelProvider:y&&at!==-1?y.slice(0,at):void 0,planningModelId:y&&at!==-1?y.slice(at+1):void 0,thinkingLevel:j!==""?j:void 0,reviewLevel:W,priority:A});if(g.length>0){const Z=[];for(const ue of g)try{await Ua(oe.id,ue.file,s)}catch{Z.push(ue.file.name)}Z.length>0&&o(`Failed to upload: ${Z.join(", ")}`,"error")}g.forEach(Z=>URL.revokeObjectURL(Z.previewUrl)),p([]),d(""),h([]),x(""),M(""),R(""),C(""),P(""),_("default"),I([]),q(!1),E(null),re(!1),B(void 0),z(cs),o(`Created ${oe.id}`,"success"),n()}catch(Ie){o(xe(Ie)||"Failed to create task","error")}finally{b(!1)}}},[u,m,g,v,k,y,j,f,r,o,n,s,T,S,$,w,X,W,A]),J=a.useCallback(le=>{le.key==="Escape"&&(le.preventDefault(),De())},[De]),ee=(X?U.find(le=>le.id===X):void 0)?.name??X,he=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:Se,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>de(le=>!le),disabled:f,"data-testid":"dep-trigger",children:m.length>0?`${m.length} selected`:"Add dependencies"}),Q&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Te,onChange:le=>fe(le.target.value),onClick:le=>le.stopPropagation()}),Oe.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Oe.map(le=>t.jsxs("div",{className:`dep-dropdown-item${m.includes(le.id)?" selected":""}`,onClick:()=>{h(m.includes(le.id)?m.filter(Ie=>Ie!==le.id):[...m,le.id]),de(!1),fe("")},onMouseDown:Ie=>Ie.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:le.id}),t.jsx("span",{className:"dep-dropdown-title",children:ye(le.title||le.description||le.id,30)})]},le.id))]})]}),m.length>0&&t.jsx("div",{className:"selected-deps",children:m.map(le=>t.jsxs("span",{className:"dep-chip",children:[le,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>h(m.filter(Ie=>Ie!==le)),disabled:f,children:"×"})]},le))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:ae,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{ie?re(!1):Ne()},disabled:f,"data-testid":"new-task-agent-button",children:[t.jsx(an,{size:12,style:{verticalAlign:"middle"}}),ee?` ${ee}`:" Assign agent"]}),ie&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:le=>le.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),F&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!F&&U.filter(le=>le.state!=="terminated").map(le=>t.jsxs("div",{className:`dep-dropdown-item${X===le.id?" selected":""}`,onMouseDown:Ie=>Ie.preventDefault(),onClick:()=>{E(le.id===X?null:le.id),re(!1)},"data-testid":`agent-option-${le.id}`,children:[t.jsx(an,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:le.role}),t.jsx("span",{className:"dep-dropdown-title",children:le.name})]},le.id)),!F&&U.filter(le=>le.state!=="terminated").length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),X&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:le=>le.preventDefault(),onClick:()=>{E(null),re(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:De,onKeyDown:J,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:le=>le.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:De,disabled:f,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!Pe&&t.jsx(lf,{hasAiProvider:te,hasGithub:we}),t.jsx(Xp,{mode:"create",description:u,onDescriptionChange:d,dependencies:m,onDependenciesChange:h,executorModel:v,onExecutorModelChange:x,validatorModel:k,onValidatorModelChange:M,presetMode:T,onPresetModeChange:_,selectedPresetId:S,onSelectedPresetIdChange:P,selectedWorkflowSteps:$,onWorkflowStepsChange:We,onDefaultOnApplied:Ke,pendingImages:g,onImagesChange:p,tasks:i,projectId:s,disabled:f,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:De,planningModel:y,onPlanningModelChange:R,thinkingLevel:j,onThinkingLevelChange:C,reviewLevel:W,onReviewLevelChange:B,priority:A,onPriorityChange:z,renderBelowPrimary:he,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:De,disabled:f,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:se,disabled:!u.trim()||f,children:f?"Creating...":"Create Task"})]})]})}):null}const nA=5e3;function sA(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),b=a.useRef(void 0),v=a.useCallback(async()=>{try{d(!0),h(null);let M;o?M=await bd({limit:i,projectId:n,type:s}):M=(await dd({limit:i,type:s,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(M),p(M.length===i),M.length>0&&(b.current=M[M.length-1].timestamp)}catch(M){h(M instanceof Error?M.message:"Failed to load activity log")}finally{d(!1)}},[i,n,s,o]),x=a.useCallback(async()=>{if(b.current)try{d(!0);let M;o?M=await bd({limit:i,projectId:n,type:s,since:b.current}):M=(await dd({limit:i,type:s,since:b.current,projectId:n})).map(R=>({...R,projectId:n??"",projectName:""})),c(y=>[...y,...M]),p(M.length===i),M.length>0&&(b.current=M[M.length-1].timestamp)}catch(M){h(M instanceof Error?M.message:"Failed to load more entries")}finally{d(!1)}},[i,n,s,o]),k=a.useCallback(()=>{c([]),p(!1),b.current=void 0},[]);return a.useEffect(()=>{v()},[v]),a.useEffect(()=>{if(r)return f.current=setInterval(()=>{v()},nA),()=>{f.current&&(clearInterval(f.current),f.current=null)}},[r,v]),{entries:l,loading:u,error:m,refresh:v,clear:k,hasMore:g,loadMore:x}}const kl={"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"},iA={"task:created":t.jsx(Vt,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Ga,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(hn,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(Pt,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(tn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Ka,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Oa,{size:14,className:"activity-icon settings"})};function aA(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 rA({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,b=m==="all"?void 0:m,v=!c&&o.length>0,{entries:x,loading:k,error:M,refresh:y,hasMore:R}=sA({projectId:b,type:f,limit:100,autoRefresh:e,useCentralFeed:v}),j=x.map(_=>({id:_.id,timestamp:_.timestamp,type:_.type,taskId:_.taskId,taskTitle:_.taskTitle,details:_.details,metadata:_.metadata,projectId:_.projectId,projectName:_.projectName})),C=async()=>{try{await sy(),y(),p(!1)}catch{p(!1)}},S=_=>{i&&i(_)},P=_=>{h(_),l?.(_==="all"?void 0:_)};a.useEffect(()=>{if(!e)return;const _=L=>{L.key==="Escape"&&(g?p(!1):n())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n,g]);const T=u!=="all"||m!=="all";return e?t.jsx("div",{className:"modal-overlay open",onClick:_=>{_.target===_.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(Fa,{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(jn,{size:14}),t.jsxs("select",{value:m,onChange:_=>P(_.target.value),className:"activity-log-filter-select","data-testid":"activity-project-filter",children:[t.jsx("option",{value:"all",children:"All Projects"}),o.map(_=>t.jsx("option",{value:_.id,children:_.name},_.id))]})]}),t.jsxs("div",{className:"activity-log-filter",children:[t.jsx(Dr,{size:14}),t.jsxs("select",{value:u,onChange:_=>d(_.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(kl).map(([_,L])=>t.jsx("option",{value:_,children:L},_))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>y(),title:"Refresh","data-testid":"activity-refresh",children:k?t.jsx(it,{size:14,className:"spin"}):t.jsx(hn,{size:14})}),j.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Ht,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),T&&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(_=>_.id===m)?.name||m]}),u!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",kl[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:[M&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(ss,{size:16}),t.jsx("span",{children:M})]}),j.length===0&&!k&&!M&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Fa,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:T?"No activity matches the current filters":"No activity recorded yet"}),T&&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:j.map(_=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:iA[_.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:kl[_.type]}),t.jsx("span",{className:"activity-log-entry-time",children:aA(_.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[_.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>S(_.taskId),"data-testid":"activity-task-link",children:_.taskId}),_.taskTitle&&t.jsx("span",{className:"activity-log-task-title",children:_.taskTitle}),t.jsx("span",{className:"activity-log-entry-text",children:_.details})]}),_.metadata&&Object.keys(_.metadata).length>0&&t.jsxs("div",{className:"activity-log-entry-metadata",children:[typeof _.metadata.from=="string"&&typeof _.metadata.to=="string"&&t.jsxs("span",{className:"activity-log-metadata-item",children:[_.metadata.from," → ",_.metadata.to]}),typeof _.metadata.merged=="boolean"&&t.jsx("span",{className:`activity-log-metadata-item ${_.metadata.merged?"success":"error"}`,children:_.metadata.merged?"Merged":"Not merged"})]})]})]},_.id))}),R&&!k&&t.jsx("button",{className:"activity-log-load-more",onClick:y,"data-testid":"activity-load-more",children:"Load More"}),k&&j.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(it,{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:C,children:"Clear Log"})]})]})})]})}):null}const Ca=[{id:"status",label:"Status",icon:oh},{id:"changes",label:"Changes",icon:eh},{id:"commits",label:"Commits",icon:za},{id:"branches",label:"Branches",icon:Os},{id:"worktrees",label:"Worktrees",icon:Wg},{id:"stashes",label:"Stashes",icon:Zr},{id:"remotes",label:"Remotes",icon:sh}];function Sm({status:e}){switch(e){case"added":case"untracked":return t.jsx(Eg,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(th,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(Ng,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(Ni,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(_g,{size:14,className:"gm-file-icon"})}}function Cm({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 oA(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 Zi(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 lA({isOpen:e,onClose:n,tasks:s,addToast:i,projectId:r}){const[o,l]=a.useState("status"),[c,u]=a.useState(!1),[d,m]=a.useState(null),h=a.useRef(null),g=oA(i),[p,f]=a.useState(null),[b,v]=a.useState([]),[x,k]=a.useState(new Set),[M,y]=a.useState(""),[R,j]=a.useState(!1),[C,S]=a.useState(null),[P,T]=a.useState(!1),[_,L]=a.useState(null),[G,$]=a.useState(null),I=a.useRef(0),[w,q]=a.useState([]),[W,B]=a.useState(null),[A,z]=a.useState(null),[X,E]=a.useState(!1),[U,pe]=a.useState(20),[ie,re]=a.useState(""),[F,ce]=a.useState([]),[ae,Q]=a.useState(""),[de,Te]=a.useState(""),[fe,Se]=a.useState(""),[te,we]=a.useState(null),[Pe,We]=a.useState([]),[Ke,Ne]=a.useState(!1),[_e,Oe]=a.useState(null),[ye,De]=a.useState(null),[se,J]=a.useState(!1),[me,ee]=a.useState([]),[he,le]=a.useState([]),[Ie,Ze]=a.useState(""),[at,oe]=a.useState(null),[Z,ue]=a.useState(null),[Ce,$e]=a.useState(null),ve=a.useCallback(async()=>{if(e){u(!0),m(null);try{switch(o){case"status":{const N=await As(r);f(N);break}case"changes":{const[N,H]=await Promise.all([As(r),$i(r)]);f(N),v(H),k(new Set),$(null),S(null),L(null);break}case"commits":{const N=await dv(U,r);q(N);break}case"branches":{const[N,H]=await Promise.all([pa(r),As(r)]);ce(N),f(H);break}case"worktrees":{const N=await pv(r);ee(N);break}case"stashes":{const N=await mr(r);le(N);break}case"remotes":{const N=await As(r);f(N);break}}}catch(N){m(xe(N)||"Failed to fetch git data"),i(xe(N)||"Failed to fetch git data","error")}finally{u(!1)}}},[o,e,U,i,r]);a.useEffect(()=>{e&&ve()},[ve,e]),a.useEffect(()=>{if(!e)return;const N=H=>{if(H.key==="Escape"){n();return}if((H.key==="ArrowUp"||H.key==="ArrowDown")&&H.altKey){H.preventDefault();const Ae=Ca.findIndex(ot=>ot.id===o);H.key==="ArrowUp"&&Ae>0?l(Ca[Ae-1].id):H.key==="ArrowDown"&&Ae<Ca.length-1&&l(Ca[Ae+1].id)}};return document.addEventListener("keydown",N),()=>document.removeEventListener("keydown",N)},[e,n,o]);const Ge=a.useCallback(async N=>{try{await ad(N,r),i(`Staged ${N.length} file(s)`,"success");const H=await $i(r);v(H),k(new Set),$(null),S(null),L(null)}catch(H){i(xe(H)||"Failed to stage files","error")}},[i,r]),je=a.useCallback(async N=>{try{await Nv(N,r),i(`Unstaged ${N.length} file(s)`,"success");const H=await $i(r);v(H),k(new Set),$(null),S(null),L(null)}catch(H){i(xe(H)||"Failed to unstage files","error")}},[i,r]),Ue=a.useCallback(async N=>{if(confirm(`Discard changes to ${N.length} file(s)? This cannot be undone.`))try{await Sv(N,r),i(`Discarded changes to ${N.length} file(s)`,"success");const[H,Ae]=await Promise.all([$i(r),As(r)]);v(H),f(Ae),k(new Set),$(null),S(null),L(null)}catch(H){i(xe(H)||"Failed to discard changes","error")}},[i,r]),He=a.useCallback(async N=>{if(N.preventDefault(),!!M.trim()){j(!0);try{const H=await rd(M.trim(),r);i(`Committed: ${H.hash}`,"success"),y("");const[Ae,ot]=await Promise.all([$i(r),As(r)]);v(Ae),f(ot),$(null),S(null),L(null)}catch(H){i(xe(H)||"Failed to commit","error")}finally{j(!1)}}},[M,i,r]),ge=a.useCallback(async()=>{if(M.trim()){j(!0);try{const N=b.filter(kt=>!kt.staged).map(kt=>kt.file);N.length>0&&await ad(N,r);const H=await rd(M.trim(),r);i(`Committed: ${H.hash}`,"success"),y("");const[Ae,ot]=await Promise.all([$i(r),As(r)]);v(Ae),f(ot),$(null),S(null),L(null)}catch(N){i(xe(N)||"Failed to commit","error")}finally{j(!1)}}},[M,b,i,r]),Fe=a.useCallback(async(N,H)=>{$({file:N,staged:H}),T(!0),L(null);const Ae=I.current+1;I.current=Ae;try{const ot=await wv(N,H,r);if(I.current!==Ae)return;S(ot)}catch(ot){if(I.current!==Ae)return;const kt=xe(ot)||"Failed to load file diff";S(null),L(kt),i(kt,"error")}finally{I.current===Ae&&T(!1)}},[i,r]),be=a.useCallback(N=>{k(H=>{const Ae=new Set(H);return Ae.has(N)?Ae.delete(N):Ae.add(N),Ae})},[]),Je=a.useCallback(async N=>{if(W===N){B(null),z(null);return}B(N),E(!0);try{const H=await Ur(N,r);z(H)}catch(H){i(xe(H)||"Failed to load diff","error"),z(null)}finally{E(!1)}},[W,i,r]),st=a.useCallback(()=>{pe(N=>Math.min(N+20,100))},[]),dt=a.useMemo(()=>{if(!ie.trim())return w;const N=ie.toLowerCase();return w.filter(H=>H.message.toLowerCase().includes(N)||H.author.toLowerCase().includes(N)||H.shortHash.toLowerCase().includes(N))},[w,ie]),Tt=a.useCallback(async N=>{if(N.preventDefault(),!!ae.trim()){u(!0);try{await fv(ae.trim(),de.trim()||void 0,r),i(`Created branch ${ae}`,"success"),Q(""),Te("");const H=await pa(r);ce(H)}catch(H){i(xe(H)||"Failed to create branch","error")}finally{u(!1)}}},[ae,de,i,r]),$t=a.useCallback(async N=>{u(!0);try{await gv(N,r),i(`Switched to ${N}`,"success");const[H,Ae]=await Promise.all([As(r),pa(r)]);f(H),ce(Ae)}catch(H){i(xe(H)||"Failed to checkout branch","error")}finally{u(!1)}},[i,r]),Dt=a.useCallback(async N=>{if(confirm(`Delete branch "${N}"?`)){u(!0);try{await id(N,void 0,r),i(`Deleted branch ${N}`,"success");const H=await pa(r);ce(H)}catch(H){if(xe(H).includes("not fully merged")){if(confirm("Branch has unmerged commits. Force delete?"))try{await id(N,!0,r),i(`Force deleted branch ${N}`,"success");const Ae=await pa(r);ce(Ae)}catch(Ae){i(xe(Ae)||"Failed to delete branch","error")}}else i(xe(H)||"Failed to delete branch","error")}finally{u(!1)}}},[i,r]),Bt=a.useMemo(()=>{if(!fe.trim())return F;const N=fe.toLowerCase();return F.filter(H=>H.name.toLowerCase().includes(N))},[F,fe]),qt=a.useCallback(async N=>{if(te===N){we(null),We([]),Oe(null),De(null);return}we(N),We([]),Oe(null),De(null),Ne(!0);try{const H=await hv(N,10,r);We(H)}catch{We([])}finally{Ne(!1)}},[te,r]),Lt=a.useCallback(async N=>{if(_e===N){Oe(null),De(null);return}Oe(N),De(null),J(!0);try{const H=await Ur(N,r);De(H)}catch{De(null)}finally{J(!1)}},[_e,r]),Ct=a.useCallback(()=>{we(null),We([]),Oe(null),De(null)},[]),xt=a.useCallback(async N=>{N.preventDefault(),oe("create");try{await yv(Ie.trim()||void 0,r),i("Changes stashed","success"),Ze("");const H=await mr(r);le(H)}catch(H){i(xe(H)||"Failed to stash changes","error")}finally{oe(null)}},[Ie,i,r]),Et=a.useCallback(async(N,H=!1)=>{oe(`apply-${N}`);try{await kv(N,H,r),i(H?"Stash popped":"Stash applied","success");const Ae=await mr(r);le(Ae)}catch(Ae){i(xe(Ae)||"Failed to apply stash","error")}finally{oe(null)}},[i,r]),Le=a.useCallback(async N=>{if(confirm(`Drop stash@{${N}}? This cannot be undone.`)){oe(`drop-${N}`);try{await jv(N,r),i("Stash dropped","success");const H=await mr(r);le(H)}catch(H){i(xe(H)||"Failed to drop stash","error")}finally{oe(null)}}},[i,r]),gt=a.useCallback(async()=>{ue("fetch");try{const N=await bv(void 0,r);$e(N),i(N.message||"Fetch completed",N.fetched?"success":"info");const H=await As(r);f(H)}catch(N){i(xe(N)||"Fetch failed","error")}finally{ue(null)}},[i,r]),ut=a.useCallback(async()=>{ue("pull");try{const N=await xv(r);$e(N),N.conflict?i("Merge conflict detected. Resolve manually.","error"):i(N.message||"Pull completed","success");const H=await As(r);f(H)}catch(N){i(xe(N)||"Pull failed","error")}finally{ue(null)}},[i,r]),Me=a.useCallback(async()=>{ue("push");try{const N=await vv(r);$e(N),i(N.message||"Push completed","success");const H=await As(r);f(H)}catch(N){i(xe(N)||"Push failed","error")}finally{ue(null)}},[i,r]),Qe=a.useMemo(()=>b.filter(N=>N.staged),[b]),rt=a.useMemo(()=>b.filter(N=>!N.staged),[b]);return e?t.jsx("div",{className:"modal-overlay open",onClick:N=>N.target===N.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(Al,{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:ve,disabled:c,title:"Refresh",children:t.jsx(hn,{size:14,className:c?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(Pt,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:Ca.map(N=>{const H=N.icon;return t.jsxs("button",{role:"tab","aria-selected":o===N.id,className:`gm-nav-item${o===N.id?" active":""}`,onClick:()=>l(N.id),children:[t.jsx(H,{size:16}),t.jsx("span",{className:"gm-nav-label",children:N.label})]},N.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[c&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),d&&!c&&t.jsxs("div",{className:"gm-error",children:[t.jsx(ss,{size:18}),t.jsx("span",{children:d}),t.jsx("button",{className:"btn btn-sm",onClick:ve,children:"Retry"})]}),o==="status"&&!c&&p&&t.jsx(cA,{status:p,copyToClipboard:g}),o==="changes"&&!c&&t.jsx(dA,{status:p,stagedFiles:Qe,unstagedFiles:rt,selectedFiles:x,toggleFileSelection:be,onStageFiles:Ge,onUnstageFiles:je,onDiscardChanges:Ue,onSelectDiffFile:Fe,selectedDiffTarget:G,changeDiff:C,loadingChangeDiff:P,changeDiffError:_,commitMessage:M,setCommitMessage:y,onCommit:He,onStageAllAndCommit:ge,committing:R}),o==="commits"&&!c&&t.jsx(uA,{commits:dt,commitSearch:ie,setCommitSearch:re,selectedCommit:W,commitDiff:A,loadingDiff:X,onCommitClick:Je,onLoadMore:st,canLoadMore:w.length>=U&&U<100,copyToClipboard:g}),o==="branches"&&!c&&t.jsx(mA,{branches:Bt,branchSearch:fe,setBranchSearch:Se,newBranchName:ae,setNewBranchName:Q,branchBase:de,setBranchBase:Te,onCreateBranch:Tt,onCheckoutBranch:$t,onDeleteBranch:Dt,loading:c,allBranches:F,selectedBranch:te,branchCommits:Pe,loadingBranchCommits:Ke,expandedBranchCommit:_e,branchCommitDiff:ye,loadingBranchCommitDiff:se,onSelectBranch:qt,onBranchCommitClick:Lt,onCloseBranchDetails:Ct}),o==="worktrees"&&!c&&t.jsx(hA,{worktrees:me}),o==="stashes"&&!c&&t.jsx(pA,{stashes:he,stashMessage:Ie,setStashMessage:Ze,onCreateStash:xt,onApplyStash:Et,onDropStash:Le,stashLoading:at}),o==="remotes"&&!c&&t.jsx(fA,{status:p,remoteLoading:Z,lastRemoteResult:Ce,onFetch:gt,onPull:ut,onPush:Me,addToast:i,projectId:r,copyToClipboard:g})]})]})]})}):null}function cA({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(Os,{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(wi,{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(ss,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(tn,{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(yi,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Wa,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(tn,{size:12}),"Up to date"]})]})]})]})]})}function dA({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:b,onStageAllAndCommit:v,committing:x}){const k=s.filter(y=>i.has(`unstaged:${y.file}`)),M=n.filter(y=>i.has(`staged:${y.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(Os,{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:[k.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(k.map(y=>y.file)),title:"Stage selected",children:[t.jsx(Vt,{size:12})," Stage (",k.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(k.map(y=>y.file)),title:"Discard selected",children:t.jsx(Ka,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(y=>y.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(y=>{const R=d?.file===y.file&&d.staged===!1;return t.jsxs("div",{className:`gm-file-item${R?" active":""}`,onClick:()=>u(y.file,!1),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),u(y.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:j=>j.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`unstaged:${y.file}`),onChange:()=>r(`unstaged:${y.file}`)})}),t.jsx(Sm,{status:y.status}),t.jsx("span",{className:"gm-file-name",title:y.file,children:y.file}),t.jsx(Cm,{status:y.status}),t.jsx("button",{className:"gm-icon-btn",onClick:j=>{j.stopPropagation(),o([y.file])},title:"Stage file",children:t.jsx(Vt,{size:12})})]},`unstaged:${y.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:[M.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(M.map(y=>y.file)),title:"Unstage selected",children:["Unstage (",M.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(y=>y.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(y=>{const R=d?.file===y.file&&d.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${R?" active":""}`,onClick:()=>u(y.file,!0),role:"button",tabIndex:0,onKeyDown:j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),u(y.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:j=>j.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:i.has(`staged:${y.file}`),onChange:()=>r(`staged:${y.file}`)})}),t.jsx(Sm,{status:y.status}),t.jsx("span",{className:"gm-file-name",title:y.file,children:y.file}),t.jsx(Cm,{status:y.status}),t.jsx("button",{className:"gm-icon-btn",onClick:j=>{j.stopPropagation(),l([y.file])},title:"Unstage file",children:t.jsx(Pt,{size:12})})]},`staged:${y.file}`)})})]}),(d||h||m||g)&&t.jsxs("div",{className:"gm-diff-section",children:[d&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(eh,{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(it,{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:b,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:y=>f(y.target.value),rows:3,disabled:x}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:x||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[x?t.jsx(it,{size:14,className:"spin"}):t.jsx(vi,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:x||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function uA({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(Bi,{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:Zi(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(wi,{size:12})})}),i===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{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 mA({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:b,branchCommitDiff:v,loadingBranchCommitDiff:x,onSelectBranch:k,onBranchCommitClick:M,onCloseBranchDetails:y}){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(Bi,{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(Vt,{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:()=>k(R.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[R.isCurrent&&t.jsx(xn,{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:Zi(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:j=>{j.stopPropagation(),u(R.name)},disabled:m,title:"Checkout",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:j=>{j.stopPropagation(),d(R.name)},disabled:m,title:"Delete",children:t.jsx(Ht,{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(za,{size:14}),"Commits on ",R.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:y,title:"Close","data-testid":"close-branch-details",children:t.jsx(Pt,{size:14})})]}),f?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(it,{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(j=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>M(j.hash),"data-testid":`branch-commit-${j.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:j.shortHash}),t.jsx("span",{className:"gm-commit-message",title:j.message,children:j.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:j.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(j.date)}),j.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),b===j.hash&&t.jsx("div",{className:"gm-commit-diff",children:x?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{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"})})]},j.hash))})]})]},R.name))})]})}function hA({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(Os,{size:12}),n.branch]}),n.taskId&&t.jsx("span",{className:"gm-worktree-task",children:n.taskId})]})]})},n.path))})]})}function pA({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(it,{size:14,className:"spin"}):t.jsx(Zr,{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(Os,{size:12}),c.branch]}),t.jsx("span",{children:Zi(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(it,{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(it,{size:14,className:"spin"}):t.jsx(Ht,{size:14})})]})]},c.index))})]})}function fA({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:i,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:u}){const d=J=>{try{return new URL(J).hostname}catch{return J.replace(/^git@/,"").split(":")[0]||J}},[m,h]=a.useState([]),[g,p]=a.useState(!1),[f,b]=a.useState(null),[v,x]=a.useState(""),[k,M]=a.useState(""),[y,R]=a.useState(null),[j,C]=a.useState(""),[S,P]=a.useState(""),[T,_]=a.useState(!1),[L,G]=a.useState([]),[$,I]=a.useState(!1),[w,q]=a.useState(null),[W,B]=a.useState([]),[A,z]=a.useState(!1),[X,E]=a.useState(null),U=m.find(J=>J.name===w),[pe,ie]=a.useState(null),[re,F]=a.useState(null),[ce,ae]=a.useState(!1),[Q,de]=a.useState(null),[Te,fe]=a.useState(null),[Se,te]=a.useState(!1);a.useEffect(()=>{we()},[]),a.useEffect(()=>{e&&e.ahead>0?Pe():e&&e.ahead===0&&G([])},[e?.ahead]),a.useEffect(()=>{m.length>0&&!w&&q(m[0].name)},[m]),a.useEffect(()=>{w?We(w):(B([]),E(null))},[w]),a.useEffect(()=>{w&&!m.find(J=>J.name===w)&&q(m.length>0?m[0].name:null)},[m,w]);const we=async()=>{p(!0);try{const J=await tv(c);h(J)}catch(J){l(xe(J)||"Failed to load remotes","error")}finally{p(!1)}},Pe=async()=>{I(!0);try{const J=await uv(c);G(J)}catch{G([])}finally{I(!1)}},We=async J=>{z(!0),E(null);try{const me=await mv(J,void 0,10,c);B(me)}catch(me){E(xe(me)||"Failed to load remote commits"),B([])}finally{z(!1)}},Ke=async J=>{if(J.preventDefault(),!(!v.trim()||!k.trim())){b("add");try{await nv(v.trim(),k.trim(),c),l(`Remote '${v}' added successfully`,"success"),x(""),M(""),_(!1),await we()}catch(me){l(xe(me)||"Failed to add remote","error")}finally{b(null)}}},Ne=async J=>{if(confirm(`Are you sure you want to remove remote '${J}'?`)){b(`remove-${J}`);try{await sv(J,c),l(`Remote '${J}' removed`,"success"),await we()}catch(me){l(xe(me)||"Failed to remove remote","error")}finally{b(null)}}},_e=async J=>{if(S.trim()){b(`rename-${J}`);try{await iv(J,S.trim(),c),l(`Remote renamed to '${S.trim()}'`,"success"),R(null),P(""),await we()}catch(me){l(xe(me)||"Failed to rename remote","error")}finally{b(null)}}},Oe=async J=>{if(j.trim()){b(`url-${J}`);try{await av(J,j.trim(),c),l("Remote URL updated","success"),R(null),C(""),await we()}catch(me){l(xe(me)||"Failed to update remote URL","error")}finally{b(null)}}},ye=a.useCallback(async(J,me)=>{if(me==="ahead"){if(pe===J){ie(null),F(null);return}ie(J),F(null),ae(!0);try{const ee=await Ur(J);F(ee)}catch{F(null)}finally{ae(!1)}}else{if(Q===J){de(null),fe(null);return}de(J),fe(null),te(!0);try{const ee=await Ur(J);fe(ee)}catch{fe(null)}finally{te(!1)}}},[pe,Q]),De=J=>{R(`url-${J.name}`),C(J.pushUrl||J.fetchUrl)},se=J=>{R(`name-${J.name}`),P(J.name)};return t.jsx("div",{className:"gm-panel gm-remotes-panel","data-testid":"remotes-panel",children:t.jsxs("div",{className:"gm-remotes-layout",children:[t.jsxs("div",{className:"gm-remote-selector","data-testid":"remote-selector",children:[t.jsxs("div",{className:"gm-remote-selector-header",children:[t.jsx("span",{className:"gm-remote-selector-title",children:"Remotes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>_(!T),disabled:f!==null,title:T?"Cancel":"Add Remote",children:T?t.jsx(Pt,{size:14}):t.jsx(Vt,{size:14})})]}),T&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Ke,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:J=>x(J.target.value),disabled:f==="add",className:"gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:k,onChange:J=>M(J.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()||!k.trim()||f==="add",children:[f==="add"?t.jsx(it,{size:12,className:"spin"}):t.jsx(Vt,{size:12}),"Add"]})]}),g?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(J=>t.jsxs("div",{className:`gm-remote-selector-item${w===J.name?" selected":""}`,onClick:()=>q(J.name),role:"button",tabIndex:0,children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[J.name,J.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",children:d(J.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:me=>{me.stopPropagation(),Ne(J.name)},disabled:f!==null,title:"Remove remote",children:t.jsx(Ht,{size:14})})]},J.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[w&&U?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:w}),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(yi,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx(Wa,{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(it,{size:14,className:"spin"}):t.jsx(hn,{size:14}),"Fetch"]}),t.jsxs("button",{className:"btn btn-primary",onClick:r,disabled:n!==null||g,children:[n==="pull"?t.jsx(it,{size:14,className:"spin"}):t.jsx(es,{size:14}),"Pull"]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||g,children:[n==="push"?t.jsx(it,{size:14,className:"spin"}):t.jsx(yi,{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:"}),y===`url-${w}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:j,onChange:J=>C(J.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Oe(w),disabled:f===`url-${w}`,children:f===`url-${w}`?t.jsx(it,{size:12,className:"spin"}):t.jsx(xn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),C("")},title:"Cancel",children:t.jsx(Pt,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:U.fetchUrl,children:U.fetchUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(U.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(wi,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>De(U),disabled:f!==null,title:"Edit remote URL",children:t.jsx(Hn,{size:14})})]})]}),U.pushUrl&&U.pushUrl!==U.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:U.pushUrl,children:U.pushUrl}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>u(U.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(wi,{size:14})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:y===`name-${w}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:S,onChange:J=>P(J.target.value),className:"gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>_e(w),disabled:f===`rename-${w}`,children:f===`rename-${w}`?t.jsx(it,{size:12,className:"spin"}):t.jsx(xn,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(null),P("")},title:"Cancel",children:t.jsx(Pt,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>se(U),disabled:f!==null,title:"Edit remote name",children:t.jsx(Hn,{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(yi,{size:14}),"Commits to Push (",e.ahead,")"]})}),$?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:14,className:"spin"}),"Loading..."]}):L.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:L.map(J=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ye(J.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:J.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:J.message,children:J.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:J.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(J.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:pe===J.hash?t.jsx(zt,{size:14}):t.jsx(en,{size:14})})]}),pe===J.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:ce?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading diff..."]}):re?t.jsxs(t.Fragment,{children:[J.message&&t.jsx("div",{className:"gm-commit-message-full",children:J.message}),re.stat&&t.jsx("pre",{className:"gm-diff-stat",children:re.stat}),t.jsx("pre",{className:"gm-diff-patch",children:re.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},J.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(oh,{size:14}),"Recent commits on ",w]})}),A?t.jsxs("div",{className:"gm-loading",children:[t.jsx(it,{size:14,className:"spin"}),"Loading commits..."]}):X?t.jsxs("div",{className:"gm-error",children:[t.jsx(ss,{size:14}),X]}):W.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",w,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:W.map(J=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ye(J.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:J.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:J.message,children:J.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:J.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Zi(J.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:Q===J.hash?t.jsx(zt,{size:14}):t.jsx(en,{size:14})})]}),Q===J.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:Se?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(it,{size:16,className:"spin"}),"Loading diff..."]}):Te?t.jsxs(t.Fragment,{children:[J.message&&t.jsx("div",{className:"gm-commit-message-full",children:J.message}),Te.stat&&t.jsx("pre",{className:"gm-diff-stat",children:Te.stat}),t.jsx("pre",{className:"gm-diff-patch",children:Te.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},J.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 Ea={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function gA(e,n){return e&&n?`${e}/${n}`:""}function bA(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 xA(e){switch(e){case"file-text":return Ni;case"check-circle":return tn;case"shield":return Pb;case"zap":return vn;case"eye":return Vi;case"globe":return to;case"layout-grid":return Ci;default:return tn}}function vA(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 yA({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,b]=a.useState(null),[v,x]=a.useState(!1),[k,M]=a.useState(Ea),[y,R]=a.useState(!1),[j,C]=a.useState(!1),[S,P]=a.useState(null),[T,_]=a.useState(null),[L,G]=a.useState({}),[$,I]=a.useState([]),w=a.useCallback(async()=>{try{d(!0);const F=await oo(i);o(F)}catch(F){s(xe(F)||"Failed to load workflow steps","error")}finally{d(!1)}},[s,i]),q=a.useCallback(async()=>{try{const F=await Xa(i);G(F||{})}catch{}},[i]),W=a.useCallback(async()=>{try{const F=await is();I(F.models||[])}catch{}},[]),B=a.useCallback(async()=>{try{h(!0);const F=await oy();c(F.templates)}catch(F){s(xe(F)||"Failed to load templates","error")}finally{h(!1)}},[s]);a.useEffect(()=>{e&&(w(),B(),q(),W())},[e,w,B,q,W]);const A=a.useCallback(()=>{x(!0),b(null),M(Ea)},[]),z=a.useCallback(F=>{b(F.id),x(!1),M({name:F.name,description:F.description,mode:F.mode||"prompt",phase:F.phase||"pre-merge",prompt:F.prompt,scriptName:F.scriptName||"",enabled:F.enabled,defaultOn:F.defaultOn||!1,modelProvider:F.modelProvider||"",modelId:F.modelId||""})},[]),X=a.useCallback(()=>{b(null),x(!1),M(Ea)},[]),E=a.useCallback(async()=>{if(!k.name.trim()||!k.description.trim()){s("Name and description are required","error");return}R(!0);try{const F=k.mode==="prompt"&&k.modelProvider&&k.modelId?{modelProvider:k.modelProvider,modelId:k.modelId}:k.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(v){const ce={name:k.name.trim(),description:k.description.trim(),mode:k.mode,phase:k.phase,prompt:k.mode==="prompt"&&k.prompt.trim()||void 0,scriptName:k.mode==="script"?k.scriptName.trim():void 0,enabled:k.enabled,defaultOn:k.defaultOn||void 0,...F};await ud(ce,i),s("Workflow step created","success")}else f&&(await iy(f,{name:k.name.trim(),description:k.description.trim(),mode:k.mode,phase:k.phase,prompt:k.mode==="prompt"?k.prompt:"",scriptName:k.mode==="script"?k.scriptName.trim():void 0,enabled:k.enabled,defaultOn:k.defaultOn,...F},i),s("Workflow step updated","success"));x(!1),b(null),M(Ea),await w()}catch(F){s(xe(F)||"Failed to save workflow step","error")}finally{R(!1)}},[k,v,f,s,w]),U=a.useCallback(async F=>{try{await ay(F,i),s("Workflow step deleted","success"),P(null),f===F&&(b(null),M(Ea)),await w()}catch(ce){s(xe(ce)||"Failed to delete workflow step","error")}},[f,s,w]),pe=a.useCallback(async()=>{if(!(!f&&!v)&&k.mode==="prompt"){if(v){if(!k.name.trim()||!k.description.trim()){s("Name and description are required before refining","error");return}R(!0);try{const F=k.modelProvider&&k.modelId?{modelProvider:k.modelProvider,modelId:k.modelId}:{},ce={name:k.name.trim(),description:k.description.trim(),mode:"prompt",prompt:k.prompt.trim()||void 0,enabled:k.enabled,defaultOn:k.defaultOn||void 0,...F},ae=await ud(ce,i);x(!1),b(ae.id),C(!0);const Q=await md(ae.id,i);M(de=>({...de,prompt:Q.prompt})),s("Prompt refined with AI","success"),await w()}catch(F){s(xe(F)||"Failed to refine prompt","error")}finally{R(!1),C(!1)}return}if(f){C(!0);try{const F=await md(f,i);M(ce=>({...ce,prompt:F.prompt})),s("Prompt refined with AI","success"),await w()}catch(F){s(xe(F)||"Failed to refine prompt","error")}finally{C(!1)}}}},[f,v,k,s,w]),ie=a.useCallback(async F=>{_(F.id);try{await ly(F.id,i),s(`Added ${F.name} workflow step`,"success"),await w(),p("my-steps")}catch(ce){const ae=xe(ce);ae?.includes("already exists")?s(`A workflow step named '${F.name}' already exists`,"error"):s(ae||"Failed to add workflow step from template","error")}finally{_(null)}},[s,w]);if(!e)return null;const re=v||f!==null;return t.jsx("div",{className:"modal-overlay open",onClick:n,"data-testid":"workflow-step-manager",children:t.jsxs("div",{className:"modal workflow-step-manager-modal",onClick:F=>F.stopPropagation(),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:[!re&&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(Of,{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(Ci,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!re&&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(F=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${F.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:F.name}),t.jsx("span",{className:`wfm-badge ${F.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:F.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(F.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(F.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(F.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(F.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),F.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:F.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>z(F),title:"Edit","aria-label":`Edit ${F.name}`,children:t.jsx(Hn,{size:14})}),S===F.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>U(F.id),title:"Confirm delete","aria-label":`Confirm delete ${F.name}`,children:t.jsx(xn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>P(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(Pt,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>P(F.id),title:"Delete","aria-label":`Delete ${F.name}`,children:t.jsx(Ht,{size:14})})]})]})},F.id))})]}),g==="templates"&&!re&&t.jsx(t.Fragment,{children:m?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(it,{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(F=>{const ce=xA(F.icon),ae=vA(F.category),Q=T===F.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${F.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(ce,{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:F.name}),t.jsx("span",{className:ae,children:F.category})]}),t.jsx("div",{className:"wfm-template-desc",children:F.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>ie(F),disabled:Q,"data-testid":`add-template-${F.id}`,children:Q?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Vt,{size:12}),"Add"]})})]})]})},F.id)})})}),re&&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:k.name,onChange:F=>M(ce=>({...ce,name:F.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:k.description,onChange:F=>M(ce=>({...ce,description:F.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 ${k.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(li,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${k.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(Bs,{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 ${k.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${k.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>M(F=>({...F,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:k.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),k.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:pe,disabled:!k.description.trim()||j,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[j?t.jsx(it,{size:12,className:"spin"}):t.jsx(Dn,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:k.prompt,onChange:F=>M(ce=>({...ce,prompt:F.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),k.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"}),k.modelProvider&&k.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>M(F=>({...F,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(Pt,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:k.modelProvider&&k.modelId?`Using ${k.modelProvider}/${k.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(wn,{models:$,value:gA(k.modelProvider,k.modelId),onChange:F=>{const ce=bA(F);M(ae=>({...ae,modelProvider:ce.provider,modelId:ce.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),k.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(L).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:k.scriptName,onChange:F=>M(ce=>({...ce,scriptName:F.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(L).map(([F,ce])=>t.jsxs("option",{value:F,children:[F," (",ce,")"]},F))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:k.enabled,onChange:F=>M(ce=>({...ce,enabled:F.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:k.defaultOn,onChange:F=>M(ce=>({...ce,defaultOn:F.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:X,disabled:y,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:E,disabled:y||!k.name.trim()||!k.description.trim()||k.mode==="script"&&!k.scriptName.trim(),"data-testid":"save-workflow-step",children:y?"Saving...":v?"Create":"Save"})]})]})]})]})}),!re&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:A,"data-testid":"add-workflow-step",children:[t.jsx(Vt,{size:14}),"Add Workflow Step"]})})]})})}const kA=36e5,jA=3e5,jl=[{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 wA(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 NA(e){return typeof e!="number"||!Number.isFinite(e)?kA:Math.max(jA,Math.round(e))}function cP(e){if(jl.some(s=>s.value===e))return[...jl];const n={value:e,label:`${wA(e)} (custom)`};return[...jl,n].sort((s,i)=>s.value-i.value)}const SA=4,CA=5*6e4;function EA(e){const n=NA(e?.heartbeatIntervalMs);return Math.max(n*SA,CA)}function MA(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 _A(e){const{state:n,lastHeartbeatAt:s,lastError:i,pauseReason:r,runtimeConfig:o}=e,l=MA(e);if(n==="terminated")return{label:"Terminated",icon:t.jsx(ls,{size:14}),color:"var(--state-error-text)",stateDerived:!0};if(n==="error")return{label:i??"Error",icon:t.jsx(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!i};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Fs,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Ss,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(an,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const c=new Date(s).getTime(),u=Date.now()-c,d=EA(o);return u>d?{label:"Unresponsive",icon:t.jsx(Ss,{size:14}),color:"var(--state-error-text)",stateDerived:!1}:{label:"Healthy",icon:t.jsx(Kg,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}const Ma=[{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 AA({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,b]=a.useState("all"),[v,x]=a.useState(()=>{if(typeof window>"u")return"list";const w=Nn("fn-agent-view",i);return w==="board"||w==="list"?w:"list"});a.useEffect(()=>{const w=Nn("fn-agent-view",i);if(w==="board"||w==="list"){x(w);return}x("list")},[i]),a.useEffect(()=>{ts("fn-agent-view",v,i)},[i,v]);const[k,M]=a.useState(null),y=a.useRef(null),R=a.useMemo(()=>f==="all"?r.filter(w=>w.state!=="terminated"):r,[r,f]),j=a.useCallback(async()=>{c(!0);try{const q=await oa(f!=="all"?{state:f}:void 0,i);o(q)}catch(w){s(`Failed to load agents: ${xe(w)}`,"error")}finally{c(!1)}},[f,s,i]);a.useEffect(()=>{e&&j()},[e,j]),a.useEffect(()=>{if(!e)return;const w=setInterval(()=>{j()},3e4);return()=>{clearInterval(w)}},[e,j]);const C=async()=>{if(m.trim())try{await by({name:m.trim(),role:g},i),s(`Agent "${m}" created`,"success"),h(""),d(!1),j()}catch(w){s(`Failed to create agent: ${xe(w)}`,"error")}},S=async(w,q)=>{try{await vy(w,q,i),s(`Agent state updated to ${q}`,"success"),j()}catch(W){s(`Failed to update state: ${xe(W)}`,"error")}},P=async(w,q)=>{if(confirm(`Delete agent "${q}"? This cannot be undone.`))try{await yy(w,i),s(`Agent "${q}" deleted`,"success"),j()}catch(W){s(`Failed to delete agent: ${xe(W)}`,"error")}},T=async(w,q)=>{const W=r.find(B=>B.id===w);if(W){if(W.role===q){M(null);return}try{await xy(w,{role:q},i),s(`Agent role updated to ${Ma.find(B=>B.value===q)?.label??q}`,"success"),M(null),j()}catch(B){s(`Failed to update role: ${xe(B)}`,"error")}}},_=(w,q)=>{w.key==="Escape"&&M(null)},L=w=>Ma.find(q=>q.value===w)?.label??w,G=w=>Ma.find(q=>q.value===w)?.icon??"◆",$=w=>_A(w),I=w=>w.color==="var(--state-active-text)"?"active":w.color==="var(--state-paused-text)"?"paused":w.color==="var(--state-error-text)"?"error":"muted";return e?t.jsx("div",{className:"modal-overlay open",onClick:w=>w.target===w.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(an,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>x("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(Ci,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>x("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(Tl,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void j(),title:"Refresh",disabled:l,children:t.jsx(hn,{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(Dr,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:w=>b(w.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--primary",onClick:()=>d(!u),children:[t.jsx(Vt,{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:w=>h(w.target.value),onKeyDown:w=>w.key==="Enter"&&C(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:g,onChange:w=>p(w.target.value),children:Ma.map(w=>t.jsxs("option",{value:w.value,children:[w.icon," ",w.label]},w.value))}),t.jsx("button",{className:"btn btn--primary",onClick:()=>void C(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:R.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(an,{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"?R.map(w=>{const q=$(w),W=I(q);return t.jsxs("div",{className:"agent-board-card","data-state":w.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:G(w.role)}),t.jsx("span",{className:"agent-board-badge","data-state":w.state,children:w.state}),t.jsx("span",{className:"agent-board-health","data-health":W,title:q.label,children:q.icon})]}),t.jsx("div",{className:"agent-board-name",title:w.name,children:w.name}),t.jsx("div",{className:"agent-board-id",children:w.id}),t.jsxs("div",{className:"agent-board-actions",children:[w.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Activate",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:t.jsx(Ht,{size:14})})]}),w.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"paused"),title:"Pause",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),w.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Resume",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),w.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"paused"),title:"Pause",children:t.jsx(Fs,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),w.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Retry",children:t.jsx(rn,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:t.jsx(ls,{size:14})})]}),w.state==="terminated"&&t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:t.jsx(Ht,{size:14})})]})]},w.id)}):R.map(w=>{const q=$(w),W=I(q);return t.jsxs("div",{className:"agent-card","data-state":w.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[k===w.id?t.jsx("select",{ref:y,className:"select agent-role-select",value:w.role,onChange:B=>void T(w.id,B.target.value),onKeyDown:B=>_(B,w.id),onBlur:()=>M(null),autoFocus:!0,children:Ma.map(B=>t.jsxs("option",{value:B.value,children:[B.icon," ",B.label]},B.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>M(w.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:B=>{(B.key==="Enter"||B.key===" ")&&M(w.id)},children:G(w.role)}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:w.name}),t.jsx("span",{className:"agent-id text-secondary",children:w.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":w.state,children:w.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":W,title:q.label,children:[q.icon,!q.stateDerived&&` ${q.label}`]}),t.jsx("span",{className:"badge text-secondary",children:L(w.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[w.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:w.taskId})]}),w.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date(w.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[w.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Activate",children:[t.jsx(rn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:[t.jsx(Ht,{size:14})," Delete"]})]}),w.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"paused"),title:"Pause",children:[t.jsx(Fs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),w.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Resume",children:[t.jsx(rn,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),w.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"paused"),title:"Pause",children:[t.jsx(Fs,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),w.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void S(w.id,"active"),title:"Retry",children:[t.jsx(rn,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void S(w.id,"terminated"),title:"Stop",children:[t.jsx(ls,{size:14})," Stop"]})]}),w.state==="terminated"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm btn--primary",onClick:()=>void S(w.id,"active"),title:"Start",children:[t.jsx(rn,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void P(w.id,w.name),title:"Delete",children:[t.jsx(Ht,{size:14})," Delete"]})]})]})]},w.id)})})]})]})}):null}function TA({authenticated:e,onToggled:n,compact:s=!1}){const[i,r]=a.useState(null),[o,l]=a.useState(null),[c,u]=a.useState(null),d=a.useRef(!0);a.useEffect(()=>(d.current=!0,()=>{d.current=!1}),[]);const m=a.useCallback(async()=>{try{const x=await qx();return d.current&&r(x),x}catch(x){return d.current&&u({kind:"error",message:x instanceof Error?x.message:String(x)}),null}},[]);a.useEffect(()=>{m()},[m]);const h=a.useCallback(async()=>{l("testing"),u(null),await m(),d.current&&l(null)},[m]),g=a.useCallback(async x=>{l(x?"enabling":"disabling"),u(null);try{const k=await Vx(x);d.current&&u({kind:k.enabled?"enabled":"disabled",restartRequired:k.restartRequired}),n?.(k.enabled),await m()}catch(k){d.current&&u({kind:"error",message:k instanceof Error?k.message:String(k)})}finally{d.current&&l(null)}},[n,m]),p=i?.binary.available??!1,f=i?.enabled??e,b=t.jsxs("span",{className:"onboarding-provider-card__description",children:["Route AI calls through your locally-installed ",t.jsx("code",{children:"claude"})," CLI. Uses your existing Claude subscription / quota instead of an API key."]}),v=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(it,{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(Mn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(RA,{status:i,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[b,t.jsx(Em,{status:i,authenticated:e}),c&&t.jsx(Mm,{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(Mn,{provider:"claude-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Anthropic — via Claude CLI"}),b,t.jsx(Em,{status:i,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(Mm,{action:c})]})}function RA({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 Em({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(it,{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 Mm({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 IA(e){return e.match(/\bcode\s+([A-Z0-9]+(?:-[A-Z0-9]+)+)\b/i)?.[1]??null}function _m({instructions:e,"data-testid":n}){const[s,i]=a.useState(!1),r=IA(e),o=a.useCallback(async()=>{const l=r??e;try{await navigator.clipboard.writeText(l),i(!0),setTimeout(()=>i(!1),2e3)}catch{}},[r,e]);return t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((l,c,u)=>t.jsxs("span",{children:[l,c<u.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:o,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(xn,{size:12}):t.jsx(wi,{size:12})})]})]},c))}):e})}const Mi="fusion_model_onboarding_state",ea=[],ta=[],Qr=!1,Xr=!1,na={},PA=void 0,oi=["ai-setup","github","project-setup","first-task"],$A={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function us(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Mi);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?DA(n):null}catch{return null}}function DA(e){const n=e.postOnboardingDismissedAt??PA;return{...e,completedSteps:e.completedSteps??ea,skippedSteps:e.skippedSteps??ta,dismissed:e.dismissed??Qr,completed:e.completed??Xr,stepData:e.stepData??na,...n?{postOnboardingDismissedAt:n}:{}}}function Ar(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:ea,skippedSteps:ta,dismissed:Qr,completed:Xr,stepData:na};try{localStorage.setItem(Mi,JSON.stringify(s))}catch{}return}try{const s=us(),i=new Date().toISOString(),r=n.completed??Xr;let o=n.dismissed??Qr;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??ea,c=n.skippedSteps??s?.skippedSteps??ta,u={...s?.stepData??na};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(Mi,JSON.stringify(d))}catch{}}}function LA(e){if(!(typeof window>"u"))try{const n=us(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:ea,skippedSteps:[e],dismissed:Qr,completed:Xr,stepData:na};localStorage.setItem(Mi,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(Mi,JSON.stringify(r))}catch{}}function Am(){if(!(typeof window>"u"))try{const e=us(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:ea,skippedSteps:ta,dismissed:!1,completed:!0,stepData:na};localStorage.setItem(Mi,JSON.stringify(s))}catch{}}function sa(){const e=us();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function zA(){if(!(typeof window>"u"))try{const e=us(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:ea,skippedSteps:ta,dismissed:!1,completed:!1,stepData:na,postOnboardingDismissedAt:n};localStorage.setItem(Mi,JSON.stringify(s))}catch{}}function cf(){const e=us();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function FA(){const e=us();return!e||sa()?!1:e.currentStep!=="complete"}function OA(){const e=us();if(!e||sa()||e.currentStep==="complete")return null;const n=e.currentStep,s=$A[n]??HA(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function UA(){const e=us();return e?e.skippedSteps:ta}function BA(e){const n=us();return!n||!n.stepData?null:n.stepData[e]??null}function HA(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const df="fusion_onboarding_events",Tm="fusion_onboarding_session_id",qA=200,VA=50;function js(e,n={}){if(!(typeof window>"u"))try{const s=GA(),i=YA(n.step),r={type:e,timestamp:new Date().toISOString(),...i?{step:i}:{},metadata:n,sessionId:WA()},o=JA([...s,r]);KA(o)}catch{}}function WA(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(Tm);if(e)return e;const n=Rm();return sessionStorage.setItem(Tm,n),n}catch{return Rm()}}function Rm(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function GA(){try{const e=localStorage.getItem(df);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(QA):[]}catch{return[]}}function KA(e){try{localStorage.setItem(df,JSON.stringify(e))}catch{}}function JA(e){const n=[...e];for(;n.length>qA;)n.splice(0,VA);return n}function YA(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function QA(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 XA={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"}}},uf={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:"..."}},ZA={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},Im={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 tc(e){if(Im[e])return Im[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 wl=["anthropic","openai","google","gemini","ollama"],eT=["anthropic","claude-cli","openai-codex","gemini","minimax","kimi","zai"],tT={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"},nT={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function nc(e){return tT[e]??e}function Pm(e){const n=nc(e),s=eT.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function $m(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=Pm(e.id),i=Pm(n.id);if(s!==i)return s-i;const r=nc(e.id),o=nc(n.id);if(r!==o)return r.localeCompare(o);const l=nT[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 sT(e,n){const s=n.trim();if(!s)return"API key is required";const i=uf[e]??ZA;return i.pattern.test(s)?null:`${tc(e)} keys should follow this format: ${i.hint} (e.g. ${i.example})`}const mf={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"},iT={description:"AI provider — connect to start using AI models",apiKeyInfo:mf};function sc(e){return XA[e]??iT}function aT(e){return sc(e.id).apiKeyInfo??mf}function zs({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(en,{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 rT({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 oT({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=uf[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(zs,{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:b=>c(e.id,b.target.value),onKeyDown:b=>{b.key==="Enter"&&u(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>u(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:i?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(zs,{summary:"Advanced setup details",children:f})]})}const lT=150;function cT({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:i,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const u=us(),d=u?.currentStep,m=d==="complete"?"ai-setup":oi.includes(d)?d:"ai-setup",h=u?.completedSteps??[],g=u?.skippedSteps??UA(),[p,f]=a.useState(!0),[b,v]=a.useState(m),[x,k]=a.useState(h),[M,y]=a.useState(g),[R,j]=a.useState(!1),[C,S]=a.useState(""),[P,T]=a.useState(!1),[_,L]=a.useState(null),[G,$]=a.useState(null),[I,w]=a.useState([]),[q,W]=a.useState(void 0),[B,A]=a.useState(!0),[z,X]=a.useState(null),[E,U]=a.useState({}),[pe,ie]=a.useState([]),[re,F]=a.useState(""),[ce,ae]=a.useState(!1),[Q,de]=a.useState({}),[Te,fe]=a.useState({}),[Se,te]=a.useState({}),we=a.useRef({}),Pe=a.useRef(null),We=a.useRef(null),[Ke,Ne]=a.useState({}),[_e,Oe]=a.useState(()=>us()?.stepData?.github?.skipped===!0),ye=a.useRef(0),De=a.useRef(l),se=a.useRef(!1),J=u?.currentStep,me=!!u&&u.currentStep!=="complete",[ee,he]=a.useState(()=>us()?.stepData?.["ai-setup"]?.skippedProviders??{}),le=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],Ie=le.findIndex(K=>K.key===b),Ze=b==="complete"?le.length:Ie;a.useEffect(()=>{b!=="complete"&&Ar(b,{completedSteps:x,skippedSteps:M})},[b,x,M]),a.useEffect(()=>{se.current||(se.current=!0,js("onboarding:wizard-opened",{source:me?"resume":"initial",resumedFromStep:J}))},[me,J]),a.useEffect(()=>{const K=De.current!=null,ze=l!=null;!K&&ze&&j(!0),ze||j(!1),De.current=l},[l]);const at=a.useRef(m);a.useEffect(()=>{if(at.current==="ai-setup"&&b!=="ai-setup"&&!I.some(ze=>ze.id!=="github"&&ze.authenticated)){const ze={};for(const tt of I)tt.id!=="github"&&!tt.authenticated&&!ee[tt.id]&&(ze[tt.id]=!0);if(Object.keys(ze).length>0){const tt={...ee,...ze};he(tt),Ar(b,{stepData:{"ai-setup":{skippedProviders:tt}}})}}at.current=b},[b,I,ee]);const oe=a.useCallback(async()=>{try{const{providers:K,ghCli:ze}=await Ba();w(K),W(ze),U(tt=>{const et={};for(const[mt,jt]of Object.entries(tt)){const _t=K.find(gn=>gn.id===mt);_t&&!_t.authenticated&&(et[mt]=jt)}return Object.keys(et).length===Object.keys(tt).length?tt:et}),he(tt=>{const et={...tt};for(const mt of K)mt.authenticated&&et[mt.id]&&delete et[mt.id];return Object.keys(et).length===Object.keys(tt).length?tt:et})}catch{}},[]),Z=a.useRef(!1);a.useEffect(()=>{Z.current&&oe(),Z.current=b!=="ai-setup"},[b,oe]);const ue=I.find(K=>K.id==="github"),Ce=!!ue,$e=ue?.authenticated??!1,ve=q?.authenticated??!1,Ge=$e||ve,je=!$e&&ve,Ue=a.useCallback(K=>{if(K.authenticated)return"connected";const ze=Ke?.[K.id];return ze==="timeout"||ze==="failed"?"retry":ee[K.id]?"skipped":"not-connected"},[Ke,ee]);function He({status:K}){const ze={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:tt,className:et}=ze[K];return t.jsx("span",{"data-testid":"provider-status-badge",className:et,"data-status":K,children:tt})}const ge=a.useCallback(()=>{if(Ge)return"connected";const K=Ke.github;return K==="pending"?"pending":K==="failed"||K==="timeout"?"failed":_e?"skipped":"not-connected"},[Ge,Ke,_e]);function Fe({status:K}){const ze={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:tt,className:et}=ze[K];return t.jsx("span",{"data-testid":"github-status-badge",className:et,"data-status":K,children:tt})}const be=a.useCallback(async()=>{try{const K=await is();ie(K.models)}catch{}},[]),Je=a.useCallback(async()=>{try{const K=await ra();if(K.defaultProvider&&K.defaultModelId){const ze=`${K.defaultProvider}/${K.defaultModelId}`;F(ze)}}catch{}},[]);a.useEffect(()=>{Promise.all([oe(),be(),Je()]).finally(()=>A(!1))},[oe,be,Je]),a.useEffect(()=>{const K=BA("ai-setup");if(K?.loginOutcomes){const ze=K.loginOutcomes,tt={};for(const[et,mt]of Object.entries(ze))mt!=="pending"&&(tt[et]=mt);Object.keys(tt).length>0&&Ne(tt)}},[]);const st=a.useCallback((K,ze)=>{Ar(b,{completedSteps:x,stepData:{"ai-setup":{loginOutcomes:{[K]:ze}}}})},[b,x]);a.useEffect(()=>{const K=Object.entries(Ke).filter(([ze,tt])=>tt!=="pending");for(const[ze,tt]of K)st(ze,tt)},[Ke,st]),a.useEffect(()=>()=>{We.current&&clearInterval(We.current),Object.values(we.current).forEach(clearTimeout),we.current={}},[]);const dt=a.useCallback(K=>{Oe(K),Ar(b,{completedSteps:x,stepData:{github:{skipped:K}}})},[b,x]),Tt=a.useCallback(K=>K==="complete"?-1:oi.indexOf(K),[]),$t=a.useCallback(()=>{k(ze=>[...new Set([...ze,b])]),y(ze=>ze.filter(tt=>tt!==b)),js("onboarding:step-completed",{step:b}),b==="github"&&!$e&&dt(!1);const K=Tt(b);K>=0&&K<oi.length-1&&v(oi[K+1])},[b,$e,dt,Tt]),Dt=a.useCallback(()=>{y(ze=>[...new Set([...ze,b])]),LA(b),js("onboarding:step-skipped",{step:b}),b==="github"&&!$e&&dt(!0);const K=Tt(b);K>=0&&K<oi.length-1&&v(oi[K+1])},[b,$e,dt,Tt]),Bt=a.useCallback(()=>{const K=b;k(tt=>tt.filter(et=>et!==K)),y(tt=>tt.filter(et=>et!==K)),K==="github"&&!$e&&dt(!1);const ze=Tt(b);ze>0&&v(oi[ze-1])},[b,$e,dt,Tt]),qt=a.useCallback(()=>{Dt()},[Dt]),Lt=a.useCallback(async K=>{Ne(ze=>{const tt=ze[K];if(tt&&tt!=="pending"){const{[K]:et,...mt}=ze;return mt}return ze}),U(ze=>{if(!(K in ze))return ze;const tt={...ze};return delete tt[K],tt}),Ne(ze=>({...ze,[K]:"pending"})),X(K),ye.current=0;try{const{url:ze,instructions:tt}=await Wx(K);tt?.trim()&&U(et=>({...et,[K]:tt})),window.open(Hs(ze),"_blank"),We.current=setInterval(async()=>{if(ye.current++,ye.current>=lT){We.current&&(clearInterval(We.current),We.current=null),X(null),Ne(et=>({...et,[K]:"timeout"})),U(et=>{if(!(K in et))return et;const mt={...et};return delete mt[K],mt}),n("Login timed out. Please try again.","warning");return}try{const{providers:et,ghCli:mt}=await Ba();w(et),W(mt),et.find(_t=>_t.id===K)?.authenticated&&(We.current&&(clearInterval(We.current),We.current=null),X(null),Ne(_t=>({..._t,[K]:"success"})),U(_t=>{if(!(K in _t))return _t;const gn={..._t};return delete gn[K],gn}),K==="github"&&dt(!1),n("Login successful","success"))}catch{}},2e3)}catch(ze){ze instanceof Error&&ze.message.includes("already in progress")||ze&&typeof ze=="object"&&"status"in ze&&ze.status===409?(n("Login already in progress. Please wait or cancel the current attempt.","warning"),Ne(et=>({...et,[K]:"failed"}))):(n(ze instanceof Error?ze.message:"Login failed","error"),Ne(et=>({...et,[K]:"failed"}))),X(null),U(et=>{if(!(K in et))return et;const mt={...et};return delete mt[K],mt})}},[n,dt]),Ct=a.useCallback(K=>{We.current&&(clearInterval(We.current),We.current=null),X(null),ye.current=0,Ne(ze=>({...ze,[K]:"cancelled"})),U(ze=>{if(!(K in ze))return ze;const tt={...ze};return delete tt[K],tt})},[]),xt=a.useCallback((K,ze)=>{de(et=>({...et,[K]:ze}));const tt=we.current[K];tt&&(clearTimeout(tt),delete we.current[K]),fe(et=>{if(!et[K])return et;const mt={...et};return delete mt[K],mt}),te(et=>{if(!et[K])return et;const mt={...et};return delete mt[K],mt})},[]),Et=a.useCallback(()=>{const K=Pe.current;if(!K)return;const ze=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof K.scrollTo=="function"){K.scrollTo({top:0,behavior:ze?"auto":"smooth"});return}}catch{}K.scrollTop=0},[]),Le=a.useCallback(async(K,ze)=>{const tt=(ze??Q[K]??"").trim(),et=sT(K,tt);if(et){fe(jt=>({...jt,[K]:et}));return}const mt=we.current[K];mt&&(clearTimeout(mt),delete we.current[K]),X(K),fe(jt=>{const _t={...jt};return delete _t[K],_t}),te(jt=>{if(!jt[K])return jt;const _t={...jt};return delete _t[K],_t});try{await Kx(K,tt),await oe(),Et(),de(jt=>{const _t={...jt};return delete _t[K],_t}),fe(jt=>{if(!jt[K])return jt;const _t={...jt};return delete _t[K],_t}),te(jt=>({...jt,[K]:"✓ Key saved"})),we.current[K]=setTimeout(()=>{te(jt=>{if(!jt[K])return jt;const _t={...jt};return delete _t[K],_t}),delete we.current[K]},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";fe(gn=>({...gn,[K]:_t})),te(gn=>{if(!gn[K])return gn;const fs={...gn};return delete fs[K],fs}),n(_t,"error")}finally{X(null)}},[Q,n,oe,Et]),gt=a.useCallback(async K=>{X(K);try{await Jx(K),await oe(),n("API key removed","success")}catch(ze){n(ze instanceof Error?ze.message:"Failed to clear API key","error")}finally{X(null)}},[n,oe]),ut=a.useCallback(async K=>{X(K);try{await Gx(K),await oe(),n("Logged out","success")}catch(ze){n(ze instanceof Error?ze.message:"Logout failed","error")}finally{X(null)}},[n,oe]),Me=a.useCallback(K=>{F(K)},[]),Qe=a.useCallback(async()=>{try{const K={modelOnboardingComplete:!0};if(re){const ze=re.indexOf("/"),tt=ze!==-1?re.slice(0,ze):void 0,et=ze!==-1?re.slice(ze+1):re,mt=pe.find(jt=>jt.id===et);mt?(K.defaultProvider=mt.provider,K.defaultModelId=mt.id):tt&&et&&(K.defaultProvider=tt,K.defaultModelId=et)}await nn(K),Am()}catch{}},[re,pe,nn,Am]),rt=a.useCallback(async()=>{const K=[...new Set([...x,"first-task"])];ae(!0);try{await Qe(),js("onboarding:completed",{completedSteps:K,skippedSteps:M}),k(K),y(ze=>ze.filter(tt=>tt!=="first-task")),v("complete")}finally{ae(!1)}},[Qe,x,M]),N=a.useCallback(async()=>{if(!s)return;const K=C.trim();if(!K){L("Please enter a task description.");return}L(null),T(!0);let ze=!1;try{const tt=await mh({description:K},s);$(tt),j(!0),js("onboarding:first-task-created",{taskId:tt?.id}),n("Task created","success"),ze=!0}catch(tt){const et=tt instanceof Error?tt.message:"Something went wrong creating your task. Please try again.";L(et),n(et,"error")}finally{T(!1)}ze&&Qe()},[s,C,n,Qe]),H=a.useCallback(async()=>{ae(!0);try{await Qe()}finally{ae(!1)}js("onboarding:open-new-task",{}),r?.()},[Qe,r]),Ae=a.useCallback(async()=>{if(Ge){ae(!0);try{await Qe()}finally{ae(!1)}f(!1),e(),js("onboarding:open-github-import",{}),o?.()}},[Qe,Ge,e,o]),ot=a.useCallback(async()=>{js("onboarding:dismissed",{currentStep:b,completedSteps:x,skippedSteps:M}),ae(!0);try{await nn({modelOnboardingComplete:!0})}catch{}f(!1),e()},[b,x,M,e]),kt=a.useCallback(()=>{js("onboarding:finished",{}),f(!1),e()},[e]),Ot=a.useCallback(()=>{const K=l??G;K&&(Qe(),c?.(K),e())},[l,G,Qe,c,e]),sn=a.useCallback(()=>{Qe(),e()},[Qe,e]);if(!p)return null;const Rt=ge(),zn=I.filter(K=>K.id!=="github"),Wn=[...zn].sort($m),ms=Wn.some(K=>!K.type||K.type==="oauth"),pn=Wn.some(K=>K.type==="api_key"),Fn=zn.filter(K=>K.authenticated),Sn=Fn.length>0,fn=!!s,Gn=b==="github"&&!Sn,dn=(()=>{if(!re)return"";const K=re.indexOf("/"),ze=K===-1?void 0:re.slice(0,K),tt=K===-1?re:re.slice(K+1),et=pe.find(mt=>mt.id===tt&&(!ze||mt.provider===ze));return et?.name?et.name:ze?`${tc(ze)} ${tt}`:re})(),Mt=[];if(fn?Mt.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):Mt.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),Sn){const K=tc(Fn[0]?.id??"");Mt.push({label:"AI Provider",status:"connected",detail:`${K} connected — AI agents can work on tasks`})}else zn.length>0&&zn.some(K=>ee[K.id])?Mt.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):Mt.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});Ge?Mt.push({label:"GitHub",status:"connected",detail:je?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Ce||_e?Mt.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):Mt.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),dn&&Mt.push({label:"Default Model",status:"connected",detail:dn});const yn=l??G,Kn=yn?.description?.split(`
|
|
616
|
-
`)[0]?.trim()||yn?.title||"",kn=new Set(wl),_n=Wn.filter(K=>kn.has(K.id)).sort((K,ze)=>{const tt=wl.indexOf(K.id),et=wl.indexOf(ze.id);return tt!==et?tt-et:$m(K,ze)}),hs=Wn.filter(K=>K.authenticated&&!kn.has(K.id)),ps=Wn.filter(K=>!K.authenticated&&!kn.has(K.id)),On=K=>{if(K.id==="claude-cli"&&K.type==="cli")return t.jsx(TA,{authenticated:K.authenticated,onToggled:()=>{oe()}},K.id);if(K.type==="api_key"){const ze=sc(K.id),tt=aT(K);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Mn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(ah,{size:14,className:"onboarding-provider-key-icon"}),K.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:ze.description}),t.jsx(He,{status:Ue(K)}),K.authenticated&&K.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",K.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(oT,{provider:K,apiKeyInfo:tt,inputValue:Q[K.id]??"",isSaving:z===K.id,error:Te[K.id],success:Se[K.id],isConnected:K.authenticated,onInputChange:xt,onSave:Le,onClear:gt})})]},K.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Mn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:K.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:sc(K.id).description}),t.jsx(He,{status:Ue(K)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:z===K.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:K.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct(K.id),children:"Cancel"})]}):K.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ut(K.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Lt(K.id),children:"Login"})}),z===K.id&&E[K.id]&&t.jsx(_m,{instructions:E[K.id],"data-testid":`onboarding-login-instructions-${K.id}`}),Ke[K.id]==="timeout"&&z!==K.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ke[K.id]==="failed"&&z!==K.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},K.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",children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(vn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(es,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Jc,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Jc,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:ot,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Pt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:le.map((K,ze)=>{const tt=Ze>ze,et=x.includes(K.key)&&tt,mt=M.includes(K.key)&&!x.includes(K.key)&&tt,jt=et||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[ze>0&&t.jsx("div",{className:`model-onboarding-step-connector ${ze<=Ze?"done":""}`}),jt?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===K.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,onClick:()=>v(K.key),"aria-label":`Go back to ${K.label}`,title:`Review ${K.label}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(tn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ze+1}),t.jsx("span",{className:"step-label",children:K.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===K.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(tn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ze+1}),t.jsx("span",{className:"step-label",children:K.label})]})]},K.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Pe,children:[b==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!B&&I.length>0&&(()=>{const K=I.filter(jt=>jt.id!=="github"&&jt.authenticated).length,ze=I.filter(jt=>jt.id!=="github").length,tt=Object.keys(ee).filter(jt=>!I.find(_t=>_t.id===jt)?.authenticated).length;if(ze===0)return null;let et="onboarding-provider-summary",mt="";return K>0?(et+=" onboarding-provider-summary--connected",mt=`✓ ${K} of ${ze} provider${ze!==1?"s":""} connected`):tt>0?(et+=" onboarding-provider-summary--skipped",mt=`${tt} provider${tt!==1?"s":""} skipped`):(et+=" onboarding-provider-summary--none",mt="No providers connected yet"),t.jsx("div",{className:et,"data-testid":"provider-summary",children:mt})})(),t.jsx(zs,{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."})}),I.length>0&&!I.some(K=>K.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),B?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(it,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):I.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"}),_n.length>0?t.jsx("div",{className:"model-onboarding-providers",children:_n.map(K=>On(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),hs.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:hs.map(K=>On(K))})]}),t.jsx(zs,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:ps.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ps.map(K=>On(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),ms&&t.jsx(zs,{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."})}),pn&&t.jsx(zs,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]}),t.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(zs,{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."})}),pe.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(wn,{models:pe,value:re,onChange:Me,placeholder:"Select a default model…",label:"Default model"})}),re&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",pe.find(K=>K.id===re)?.name??re]})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[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."}),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"})]})}),Gn&&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(zs,{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."})}),Ce?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(es,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Fe,{status:Rt})})]}),$e&&(z==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ut("github"),children:"Disconnect"}))]}),(Rt==="not-connected"||Rt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[z==="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:()=>Ct("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Lt("github"),children:[t.jsx(es,{size:16}),"Connect"]}),z==="github"&&E.github&&t.jsx(_m,{instructions:E.github,"data-testid":"onboarding-login-instructions-github"})]}),Rt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:je?"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."}),Rt==="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:()=>Lt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:qt,children:"Skip for now"})]})]}),Rt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Rt==="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:()=>Lt("github"),children:"Connect anyway"})})]}),Rt==="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(es,{size:48,className:"optional-icon"}),je?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth integration in Settings → Authentication 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.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:"Continue without GitHub →"})]})]}),b==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),fn?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(zs,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),R&&yn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(tn,{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:yn.id}),Kn&&t.jsx("p",{className:"onboarding-task-created__description",children:Kn}),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:Ot,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:sn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[fn?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:C,onChange:K=>{S(K.target.value),L(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:N,disabled:P,"data-testid":"onboarding-first-task-submit",children:P?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),_&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:_}),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(rT,{items:Mt}),fn&&t.jsxs(t.Fragment,{children:[t.jsx(zs,{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:H,disabled:ce,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Vt,{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${Ge?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Ae,disabled:ce||!Ge,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(es,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!Ge&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(tn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:ot,disabled:ce,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Dt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Dt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,disabled:!fn,children:"Next →"})]}),b==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:rt,disabled:ce,children:ce?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:kt,children:[t.jsx(tn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function hf({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 dT=a.lazy(()=>Zt(()=>import("./SetupWizardModal-BLiljNn7.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),uT=a.lazy(()=>Zt(()=>import("./SettingsModal-CyCC7MzL.js"),__vite__mapDeps([11,1,12,13,14,0,2,15])).then(e=>({default:e.SettingsModal})));function mT(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Zt(()=>import("./SettingsModal-CyCC7MzL.js"),__vite__mapDeps([11,1,12,13,14,0,2,15]))},{timeout:1500})}function hT({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[b,v]=a.useState(null),x=p??c.closeSettings,k=a.useCallback(()=>{c.openNewTask()},[c]),M=a.useCallback(()=>{c.openGitHubImport()},[c]),y=a.useCallback(j=>{v(null),c.closeModelOnboarding(),c.openDetailTask(j)},[c]),R=a.useCallback(async j=>{const C=await d.handleModalCreate(j);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{mT()},[]),t.jsxs(t.Fragment,{children:[c.detailTask&&t.jsx(fi,{children:t.jsx(CM,{task:c.detailTask,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(fi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(uT,{onClose:x,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(MM,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(fi,{children:t.jsx(RM,{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(fi,{children:t.jsx(zM,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(ZM,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(t_,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(j_,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(T_,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e}),c.schedulesOpen&&t.jsx(Q_,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(fi,{children:t.jsx(tA,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:R,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(rA,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:j=>{const C=n.find(S=>S.id===j);C&&c.openDetailTask(C)}}),t.jsx(fi,{children:t.jsx(lA,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(fi,{children:t.jsx(yA,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(AA,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(dT,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(cT,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:k,onOpenGitHubImport:M,firstCreatedTask:b,onViewTask:y}),t.jsx(hf,{toasts:o,onRemove:l})]})}function pT({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 ic=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function fT(e,n){if(n==="ready")return"done";const s=ic.findIndex(r=>r.id===n),i=ic.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function gT({stage:e}){return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":"Loading Fusion dashboard","data-stage":e,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:ic.map(n=>{const s=fT(n.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${s}`,"data-testid":`dashboard-loader-step-${n.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:s==="done"?"✓":s==="active"?t.jsx(it,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:n.label})]},n.id)})})]})})}const bT=5e3;function xT(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function vT(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++,Hr(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 yT(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 Ey(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()},bT),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=vT(e,s,i),f=xT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const kT={planning:Us,subtask:Si,mission_interview:ns,milestone_interview:ns,slice_interview:ns},jT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function wT({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const[o,l]=a.useState(!1),[c,u]=a.useState(new Set),d=a.useRef(null),m=a.useRef(new Map),h=a.useRef(null),{activeTabMap:g}=la(),p=a.useMemo(()=>_i(),[]);if(a.useEffect(()=>{if(!o)return;const v=x=>{d.current&&!d.current.contains(x.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[o]),a.useEffect(()=>{const v=new Set,x=new Map;for(const k of e){const M=g.get(k.id),y=[k.status,k.updatedAt,M?.tabId??k.lockedByTab??"",M?.stale?"stale":"fresh"].join("|"),R=m.current.get(k.id);R&&R!==y&&v.add(k.id),x.set(k.id,y)}if(m.current=x,v.size!==0)return u(v),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{u(new Set),h.current=null},500),()=>{h.current&&(clearTimeout(h.current),h.current=null)}},[g,e]),e.length===0)return null;const f=e.length,b=s>0;return t.jsxs("div",{ref:d,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${b?" background-tasks-indicator__pill--attention":""}`,onClick:()=>l(v=>!v),title:`${f} background AI task${f!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(it,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Gc,{size:12}),t.jsxs("span",{children:["AI ",f]})]}),o&&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(v=>{const x=kT[v.type],k=v.status==="generating",M=v.status==="awaiting_input",y=v.status==="error",R=g.get(v.id),j=R?.tabId??v.lockedByTab??null,C=!!(j&&j!==p&&!R?.stale),S=c.has(v.id);return t.jsxs("div",{className:`background-tasks-indicator__item${S?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:S?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:S?"translateY(-1px)":void 0},onClick:()=>{C&&!window.confirm("This session is active in another tab. Open anyway?")||(i(v),l(!1))},children:[y?t.jsx(ss,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(x,{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:v.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[y?"Failed":jT[v.type],k&&" — generating...",M&&!C&&" — needs input",M&&C&&" — active in another tab"]})]}),k&&t.jsx(it,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),M&&!C&&t.jsx(Gc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),M&&C&&t.jsx(so,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:P=>{P.stopPropagation(),r(v.id)},title:"Dismiss",children:t.jsx(Pt,{size:12})})]},v.id)})})]})]})}function NT(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 ST(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:rn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Fs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:vn}}}function CT({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}=yT(e,n,s,u),[f,b]=a.useState(!1),v=a.useMemo(()=>ST(h.executorState),[h.executorState]),x=a.useMemo(()=>NT(h.lastActivityAt),[h.lastActivityAt]),k=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(lc,{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(wT,{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:()=>b(M=>!M),"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(jn,{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(ji,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(k,{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 ET={planning:Us,subtask:Si,mission_interview:ns,milestone_interview:ns,slice_interview:ns},MT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},xi=new Set;function _T({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(xi.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let b=!1;for(const v of xi){const x=f.get(v);x&&x.status!=="awaiting_input"&&x.status!=="error"&&(xi.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!xi.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=>{xi.add(f),l()},g=f=>{xi.delete(f.id),l(),n(f)},p=()=>{for(const f of c)xi.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(ss,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Pt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const b=ET[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(ss,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":MT[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(Pt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function AT({onResume:e}){const n=OA();if(!n)return null;const s=n.completedSteps.length,i=oi.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(Dn,{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:()=>{js("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(rn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function TT({onOpenSettings:e,onOpenModelOnboarding:n}){const s=sa(),i=cf(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let x=!1;return(async()=>{try{o(!0),c(!1);const[M,y]=await Promise.all([Ba(),ra()]);if(x)return;const R=M.providers??[],j=R.find(_=>_.id==="github"),S=!R.some(_=>_.id!=="github"&&_.authenticated),P=!y.defaultProvider&&!y.defaultModelId,T=j?!j.authenticated:!1;h({needsAiProvider:S,needsDefaultModel:P,needsGitHub:T})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const g=a.useCallback(()=>{zA(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),b=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const x=[];return m.needsAiProvider&&x.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:vn}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:ah}),m.needsGitHub&&x.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:es}),x},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,b,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(Us,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const k=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(ss,{size:14,"aria-hidden":!0}),t.jsx(k,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Pt,{size:16,"aria-hidden":!0})})]})}function RT({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 Nl(e){return e>99?"99+":String(e)}function IT({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:o,onOpenMailbox:l,mailboxUnreadCount:c=0,onOpenGitManager:u,onOpenWorkflowSteps:d,onOpenSchedules:m,onOpenScripts:h,onToggleTerminal:g,onOpenFiles:p,onOpenGitHubImport:f,onOpenPlanning:b,onResumePlanning:v,activePlanningSessionCount:x=0,onOpenUsage:k,onRunScript:M,projectId:y,onViewAllProjects:R,showSkillsTab:j,experimentalFeatures:C}){const S=tr(),[P,T]=a.useState(!1),[_,L]=a.useState(!1),[G,$]=a.useState({}),[I,w]=a.useState(!1),q=a.useMemo(()=>Object.entries(G).sort(([re],[F])=>re.localeCompare(F)),[G]);a.useEffect(()=>{if(!_)return;let re=!1;return w(!0),Xa(y).then(F=>{re||$(F)}).catch(()=>{re||$({})}).finally(()=>{re||w(!1)}),()=>{re=!0}},[_,y]);const W=a.useCallback(()=>T(!1),[]),B=a.useCallback(re=>{W(),re?.()},[W]);if(a.useEffect(()=>{if(!P)return;const re=F=>{F.key==="Escape"&&T(!1)};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[P]),S!=="mobile"||i)return null;const A=x>0&&v?v:b,z=!!C?.roadmap,X=!!j,E=z&&(!X||e==="roadmaps"),U=X&&(!z||e!=="roadmaps"),pe=X&&!U,ie=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="roadmaps"&&!E||e==="skills"&&!U;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(Ci,{}),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(an,{}),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(ns,{}),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(li,{}),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(Gi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Nl(c)})]}),U&&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(vn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),E&&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(Rl,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ie?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>T(re=>!re),children:[t.jsx(_l,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:W}),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:()=>B(l),children:[t.jsx(Gi,{}),t.jsx("span",{children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Nl(c)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>B(o),children:[t.jsx(Ss,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>B(u),children:[t.jsx(Os,{}),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:()=>B(g),children:[t.jsx(Bs,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>L(re=>!re),"aria-expanded":_,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(en,{size:14,className:`mobile-more-chevron${_?" mobile-more-chevron--open":""}`})})]}),_&&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(it,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):q.length>0?t.jsxs(t.Fragment,{children:[q.map(([re,F])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${re}`,onClick:()=>{M&&M(re,F),W(),L(!1)},children:[t.jsx(rn,{size:14}),t.jsx("span",{children:re})]},re)),h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{W(),L(!1),h()},children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{W(),L(!1),h()},children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>B(p),children:[t.jsx(jn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>B(A),children:[t.jsx(Us,{}),t.jsx("span",{children:"Planning"}),x>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Nl(x)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>B(d),children:[t.jsx(Pl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>B(m),children:[t.jsx(ji,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>B(f),children:[t.jsx(RT,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>B(k),children:[t.jsx(Ss,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>B(R),children:[t.jsx(ih,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>B(()=>n("documents")),children:[t.jsx(Ni,{}),t.jsx("span",{children:"Documents"})]}),pe&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>B(()=>n("skills")),children:[t.jsx(vn,{}),t.jsx("span",{children:"Skills"})]}),z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>B(()=>n("roadmaps")),children:[t.jsx(Rl,{}),t.jsx("span",{children:"Roadmaps"})]}),C?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>B(()=>n("insights")),children:[t.jsx(Dn,{}),t.jsx("span",{children:"Insights"})]}),C?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>B(()=>n("memory")),children:[t.jsx(Pr,{}),t.jsx("span",{children:"Memory"})]}),C?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{B(()=>n("dev-server"))},children:[t.jsx(rh,{size:14}),t.jsx("span",{children:"Dev Server"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>B(r),children:[t.jsx(Oa,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function PT({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(an,{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 Lc="__fn_agent__";function pf(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Dm(e,n,s){const i=typeof e=="string"?e.trim():"",r=pf(n,s),o=i||(r.modelProvider&&r.modelId?Lc:"");return o?{agentId:o,...r}:null}function Sl(e,n,s){const i=pf(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function $T(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 Lm(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:$T(e.metadata),createdAt:e.createdAt}}function DT(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,b]=a.useState(""),[v,x]=a.useState([]),[k,M]=a.useState(""),y=a.useRef(null),R=a.useRef(!1),j=a.useRef(""),C=a.useRef(""),S=a.useRef(null);a.useEffect(()=>{j.current=k},[k]);const P=a.useCallback(async B=>{const A={agentId:B.agentId};return B.modelProvider&&B.modelId&&(A.modelProvider=B.modelProvider,A.modelId=B.modelId),(await Ok(A,e)).session},[e]),T=a.useCallback(async(B,A,z)=>{const X=Dm(B,A,z);if(!X)return;const E=Sl(X.agentId,X.modelProvider,X.modelId);o(!0);try{const{session:U}=await Fk({agentId:X.agentId,modelProvider:X.modelProvider,modelId:X.modelId},e);if(U)i(U),C.current=E;else{const pe=await P(X);i(pe),C.current=E}}catch(U){console.error("[useQuickChat] Failed to initialize session:",U),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,P]),_=a.useCallback(async()=>{if(s){d(!0);try{const B=await yd(s.id,{limit:50},e);c(B.messages.map(Lm))}catch(B){console.error("[useQuickChat] Failed to load messages:",B)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?_():c([])},[s,_]);const L=a.useCallback(async()=>{if(s){d(!0);try{const B=await yd(s.id,{limit:50},e);c(B.messages.map(Lm))}catch(B){console.error("[useQuickChat] Failed to reload messages:",B)}finally{d(!1)}}},[s,e]),G=a.useCallback(async(B,A,z)=>{const X=Dm(B,A,z);if(!X)return;const E=Sl(X.agentId,X.modelProvider,X.modelId);if(S.current=X,y.current&&(y.current.close(),y.current=null),p(""),b(""),x([]),h(!1),E===C.current&&s){await L();return}c([]),C.current=E,await T(X.agentId,X.modelProvider,X.modelId)},[T,L,s]),$=a.useCallback(async(B,A)=>{await G(Lc,B,A)},[G]),I=a.useCallback(async()=>{const B=S.current;if(!B)return;const A=Sl(B.agentId,B.modelProvider,B.modelId);y.current&&(y.current.close(),y.current=null),p(""),b(""),x([]),h(!1),c([]),o(!0);try{const z=await P(B);i(z),C.current=A}catch(z){console.error("[useQuickChat] Failed to start a fresh session:",z),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,P]),w=a.useCallback(()=>{s&&(R.current=!0,y.current?.close(),y.current=null,Uk(s.id,e).catch(()=>{}),h(!1),p(""),b(""),x([]))},[s,e]),q=a.useCallback(()=>{j.current="",M("")},[]),W=a.useCallback(B=>{if(!s||!B.trim())return;if(m){j.current=B,M(B);return}R.current=!1,y.current&&(y.current.close(),y.current=null);const z={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:B,createdAt:new Date().toISOString()};c(ie=>[...ie,z]),p(""),b(""),x([]),h(!0);let X="",E="",U=[];const pe={onThinking:ie=>{E+=ie,b(E)},onText:ie=>{X+=ie,p(X)},onToolStart:ie=>{U=[...U,{toolName:ie.toolName,args:ie.args,isError:!1,status:"running"}],x(U)},onToolEnd:ie=>{const re=[...U];for(let F=re.length-1;F>=0;F--){const ce=re[F];if(ce?.toolName===ie.toolName&&ce.status==="running"){re[F]={...ce,status:"completed",isError:ie.isError,result:ie.result},U=re,x(re);return}}U=[...re,{toolName:ie.toolName,isError:ie.isError,result:ie.result,status:"completed"}],x(U)},onDone:ie=>{const re={id:ie.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:X,thinkingOutput:E||void 0,toolCalls:U.length>0?U:void 0,createdAt:new Date().toISOString()};c(ce=>[...ce,re]),p(""),b(""),x([]),h(!1),y.current=null;const F=j.current.trim();F&&(j.current="",M(""),W(F))},onError:ie=>{if(p(""),b(""),x([]),h(!1),y.current=null,console.error("[useQuickChat] Stream error:",ie),n?.("Failed to get response","error"),!R.current){const re=j.current.trim();re&&(j.current="",M(""),W(re))}L()}};y.current=Bk(s.id,B,pe,e)},[s,m,e,n,L]);return a.useEffect(()=>()=>{y.current&&(y.current.close(),y.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:k,sendMessage:W,stopStreaming:w,clearPendingMessage:q,switchSession:G,startModelChat:$,startFreshSession:I,loadMessages:_,reloadMessages:L}),[s,r,l,u,m,g,f,v,k,W,w,q,G,$,I,_,L])}function LT(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,b=n?.showSystemAgents??!1,v=await oa({...f,...g,includeEphemeral:g?.includeEphemeral??b},e),x=Array.from(new Map(v.map(k=>[k.id,k])).values());i(x)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await ky(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 qs(`/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||!nj(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function zT({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(nh,{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 FT=200;function OT(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),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=a.useCallback((j,C)=>{if(C<0||C>j.length){r(!1);return}const S=P=>/[a-zA-Z0-9/_.-]/.test(P);for(let P=C-1;P>=0;P--){if(j[P]==="#")if(P===0){const T=j.slice(P+1,C);u(P),l(T),f(0),r(!0);return}else{const T=j[P-1];if(/[\s,.;:!?'"()[\]{}]/.test(T)){const _=j.slice(P+1,C);u(P),l(_),f(0),r(!0);return}r(!1);return}if(!S(j[P])){r(!1);return}}r(!1)},[]),k=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),M=a.useCallback(async j=>{if(!j.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const C=await Av(j,s,n);m(C.files),f(0)}catch(C){C.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{M(o)},FT),()=>{b.current&&clearTimeout(b.current)}},[o,i,M]);const y=a.useCallback((j,C)=>{if(!i||c<0)return C;const S=C.slice(0,c),P=C.slice(c+1),T=P.match(/[\s]|$/),_=T?T.index:P.length,L=P.slice(_);return`${S}#${j.path}${L}`},[i,c]),R=a.useCallback((j,C)=>{if(!i||d.length===0)return!1;switch(j.key){case"ArrowDown":return j.preventDefault(),f(S=>Math.min(S+1,d.length-1)),!0;case"ArrowUp":return j.preventDefault(),f(S=>Math.max(S-1,0)),!0;case"Enter":case"Tab":return d[p]?(j.preventDefault(),!0):!1;case"Escape":return j.preventDefault(),k(),!0;default:return!1}},[i,d,p,k]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:x,selectFile:y,dismissMention:k,handleKeyDown:R}}const UT={display:"inline-flex",alignItems:"center",maxWidth:"180px",padding:"var(--space-xs) var(--space-sm)",borderRadius:"var(--radius-pill)",border:"1px solid color-mix(in srgb, var(--todo) 35%, var(--border))",background:"color-mix(in srgb, var(--todo) 14%, transparent)",color:"var(--text)",fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},BT={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function HT(e){return`${e.name?.trim()||e.id} (${e.role})`}function qT(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 VT(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 Ir(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function WT(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}=${Ir(r,50)}`}).join(", ")}function GT(e){if(e===void 0)return null;if(typeof e=="string")return Ir(e,200);try{return Ir(JSON.stringify(e),200)}catch{return Ir(String(e),200)}}function zm(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(Jb,{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=WT(s.args),c=GT(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 KT={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 JT(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}}function YT(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,k=window.innerWidth<=768?44:0,M=window.innerWidth>768?s():0,y=window.innerWidth-v-x,R=window.innerHeight-v-x-k-M;return{x:Math.max(x,Math.min(y,b.x)),y:Math.max(x,Math.min(R,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),g=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),u.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!u.current||!l)return;const v=b.clientX-u.current.pointerX,x=b.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(d.current=!0),d.current){const k=u.current.x-v,M=u.current.y-x,y=m({x:k,y:M});o(y)}},[l,m]),f=a.useCallback(b=>{if(!u.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function QT({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=LT(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?Me=>{r?.(typeof Me=="function"?Me(p):Me)}:h,[b,v]=a.useState("agent"),[x,k]=a.useState(""),[M,y]=a.useState([]),[R,j]=a.useState(!1),[C,S]=a.useState(""),[P,T]=a.useState(""),[_,L]=a.useState(""),[G,$]=a.useState(!1),[I,w]=a.useState(0),[q,W]=a.useState(-1),[B,A]=a.useState(()=>new Set),[,z]=a.useState(!1),[X,E]=a.useState({top:0,left:0}),U=OT({projectId:e}),pe=a.useCallback(Me=>{if(!Me||!U.mentionActive)return;const Qe=Me.getBoundingClientRect();E({top:Qe.top-260,left:Qe.left+8})},[U.mentionActive]),ie=a.useRef(!1),re=a.useRef(!1),F=a.useRef(""),ce=a.useRef(0),ae=a.useRef(null),{position:Q,isDragging:de,handlePointerDown:Te,handlePointerMove:fe,handlePointerUp:Se}=YT(e,ie),{activeSession:te,messages:we,isStreaming:Pe,streamingText:We,streamingThinking:Ke,streamingToolCalls:Ne,sessionsLoading:_e,messagesLoading:Oe,sendMessage:ye,stopStreaming:De,pendingMessage:se,clearPendingMessage:J,switchSession:me,startModelChat:ee,startFreshSession:he}=DT(e,n),le=a.useRef(null),Ie=a.useRef(null),Ze=a.useRef(null),at=a.useRef(null),oe=a.useMemo(()=>qT(C),[C]),Z=a.useMemo(()=>M.find(Me=>`${Me.provider}/${Me.id}`===C)??null,[M,C]),ue=a.useMemo(()=>VT(Z,oe),[Z,oe]),Ce=a.useMemo(()=>b==="model"?oe?`${Lc}::${oe.modelProvider}/${oe.modelId}`:"":x?`${x}::`:"",[b,oe,x]),$e=b==="agent"?!!x:!!oe;a.useEffect(()=>{if(d.length===0){k(""),v("model");return}d.some(Qe=>Qe.id===x)||k(d[0]?.id??"")},[d,x]),a.useEffect(()=>{!p||re.current||(re.current=!0,j(!0),is().then(Me=>{const Qe=Me.models??[];if(y(Qe),d.length===0&&Qe.length>0&&!C){const rt=Qe[0];rt&&S(`${rt.provider}/${rt.id}`)}}).catch(Me=>{console.error("[QuickChatFAB] Failed to load models:",Me),y([])}).finally(()=>{j(!1)}))},[p,d.length,C]),a.useEffect(()=>{if(!p){F.current="";return}if(!Ce){F.current="";return}if(Ce!==F.current){if(F.current=Ce,b==="model"&&oe){ee(oe.modelProvider,oe.modelId);return}b==="agent"&&x&&me(x)}},[p,b,oe,x,Ce,ee,me]),a.useEffect(()=>{p||($(!1),L(""),W(-1))},[p]);const ve=a.useCallback(Me=>{k(Me)},[]),Ge=a.useCallback(Me=>{S(Me)},[]),je=a.useCallback(()=>{!$e||_e||he()},[$e,_e,he]),Ue=a.useMemo(()=>d.find(Me=>Me.id===x)??null,[d,x]),He=a.useMemo(()=>{const Me=_.trim().toLowerCase();return Me?d.filter(Qe=>Qe.name.toLowerCase().includes(Me)):d},[d,_]),ge=a.useMemo(()=>{const Me=new Map;for(const Qe of d)Me.set(Qe.name.toLowerCase(),Qe);return Me},[d]);a.useEffect(()=>{w(0)},[_,G]),a.useEffect(()=>()=>{ae.current!==null&&(window.clearTimeout(ae.current),ae.current=null)},[]),a.useEffect(()=>{if(!p)return;const Me=rt=>{const N=rt.target;le.current?.contains(N)||Ie.current?.contains(N)||N.closest(".model-combobox-dropdown--portal")||f(!1)},Qe=rt=>{rt.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",Me),document.addEventListener("keydown",Qe),()=>{document.removeEventListener("mousedown",Me),document.removeEventListener("keydown",Qe)}},[p,f]),a.useEffect(()=>{if(!p)return;const Me=Ze.current;Me&&(Me.scrollTop=Me.scrollHeight)},[we,We,Ke,p]);const Fe=a.useMemo(()=>b==="agent"?Ue?`Message ${Ue.name||Ue.id}`:"Select an agent to start chatting":ue?`Message ${ue}`:"Select a model to start chatting",[b,Ue,ue]),be=!$e||!te||_e,Je=se.length>50?`${se.slice(0,50)}…`:se,st=a.useCallback(()=>{const Me=P.trim();!Me||be||(T(""),$(!1),L(""),W(-1),ye(Me))},[ye,be,P]),dt=a.useCallback((Me,Qe)=>{const rt=JT(Me,Qe);if(rt){$(!0),L(rt.filter),W(rt.start);return}$(!1),L(""),W(-1)},[]),Tt=a.useCallback(Me=>{const Qe=at.current;if(!Qe||q<0)return;const rt=Qe.selectionStart??ce.current,N=Qe.selectionEnd??rt,H=Math.max(rt,N),Ae=Math.min(q,H),kt=`${`@${Me.name.replace(/\s+/g,"_")}`} `,Ot=P.slice(0,Ae)+kt+P.slice(H),sn=Ae+kt.length;T(Ot),$(!1),L(""),w(0),W(-1),window.requestAnimationFrame(()=>{at.current&&(at.current.focus(),at.current.setSelectionRange(sn,sn))})},[q,P]),$t=a.useCallback(Me=>{const Qe=Me.target.value,rt=Me.target.selectionStart??Qe.length;ce.current=rt,T(Qe),dt(Qe,rt),U.detectMention(Qe,rt),z(U.mentionActive),U.mentionActive&&pe(Me.target)},[dt,U,pe]),Dt=a.useCallback(()=>{ae.current!==null&&window.clearTimeout(ae.current),ae.current=window.setTimeout(()=>{$(!1),L(""),W(-1),z(!1),U.dismissMention(),ae.current=null},120)},[U]),Bt=a.useCallback(()=>{ae.current!==null&&(window.clearTimeout(ae.current),ae.current=null)},[]),qt=a.useCallback(Me=>{const Qe=Me.currentTarget,rt=Qe.selectionStart??Qe.value.length;ce.current=rt,dt(Qe.value,rt),U.detectMention(Qe.value,rt),z(U.mentionActive),U.mentionActive&&pe(Qe)},[dt,U,pe]),Lt=a.useCallback(Me=>{Me.key!=="Escape"&&qt(Me)},[qt]),Ct=a.useCallback(Me=>{const Qe=/@([\w-]+)/g,rt=[];let N=0,H=Qe.exec(Me);for(;H;){const[Ae,ot=""]=H,kt=H.index;kt>N&&rt.push(Me.slice(N,kt));const Ot=ot.replace(/_/g," ").toLowerCase(),sn=ge.get(Ot);sn?rt.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",sn.name.replace(/\s+/g,"_")]},`${sn.id}-${kt}`)):rt.push(Ae),N=kt+Ae.length,H=Qe.exec(Me)}return N<Me.length&&rt.push(Me.slice(N)),rt.length===0?Me:rt},[ge]),xt=a.useCallback(Me=>{A(Qe=>{const rt=new Set(Qe);return rt.has(Me)?rt.delete(Me):rt.add(Me),rt})},[]),Et=a.useCallback((Me,Qe=!1)=>Qe?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Me}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Qs,{remarkPlugins:[Xs],components:KT,children:Me})}),[]),Le=a.useCallback(Me=>{if(ce.current=Me.currentTarget.selectionStart??ce.current,U.mentionActive&&U.files.length>0){if(U.handleKeyDown(Me,P),Me.key==="Enter"||Me.key==="Tab"){const Qe=U.files[U.selectedIndex];if(Qe){const rt=U.selectFile(Qe,P);T(rt),U.dismissMention(),z(!1)}}return}if(G&&Me.key==="ArrowDown"){Me.preventDefault(),He.length>0&&w(Qe=>(Qe+1)%He.length);return}if(G&&Me.key==="ArrowUp"){Me.preventDefault(),He.length>0&&w(Qe=>Qe===0?He.length-1:Qe-1);return}if(G&&Me.key==="Enter"){Me.preventDefault();const Qe=He[I]??He[0];Qe&&Tt(Qe);return}if(G&&Me.key==="Escape"){Me.preventDefault(),Me.stopPropagation(),$(!1),L(""),W(-1);return}Me.key!=="Enter"||Me.shiftKey||(Me.preventDefault(),st())},[G,He,I,Tt,st,U,P]),gt=a.useCallback(()=>{if(ie.current){ie.current=!1;return}f(Me=>!Me)},[f]),ut=Q.y+60;return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Ie,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":de?"true":"false",style:{right:Q.x,bottom:Q.y},onPointerDown:Te,onPointerMove:fe,onPointerUp:Se,onClick:gt,children:t.jsx(li,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:le,"data-testid":"quick-chat-panel",style:{right:Q.x,bottom:ut},children:[t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{style:BT,children:[t.jsx("h3",{children:"Quick Chat"}),ue&&t.jsx("span",{style:UT,"data-testid":"quick-chat-model-tag",title:ue,children:ue})]}),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:je,disabled:!$e||_e,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(Pt,{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${b==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{v("agent"),S("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{v("model"),k("")},children:"Model"})]}),b==="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:x,onChange:Me=>ve(Me.target.value),"data-testid":"quick-chat-agent-select",children:d.map(Me=>t.jsx("option",{value:Me.id,children:HT(Me)},Me.id))})]}),b==="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(wn,{id:"quick-chat-model-override",models:M,value:C,onChange:Ge,label:"Select model override",placeholder:R?"Loading models…":"Select a model",disabled:R||M.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Ze,"data-testid":"quick-chat-messages",children:_e||Oe?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):we.length===0&&!We&&!Ke&&!Pe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[we.map(Me=>{const Qe=Me.role==="user",rt=!Qe&&B.has(Me.id);return t.jsxs("div",{className:`quick-chat-panel-message ${Qe?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${Me.id}`,children:[Qe?t.jsx("p",{children:Ct(Me.content)}):t.jsxs(t.Fragment,{children:[Et(Me.content,rt),t.jsx("button",{type:"button",className:`btn btn-icon quick-chat-message-render-toggle${rt?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":rt?"Show rendered markdown":"Show plain text",onClick:()=>xt(Me.id),children:rt?t.jsx($r,{size:12}):t.jsx(Vi,{size:12})})]}),zm(Me.toolCalls,!0)]},Me.id)}),Pe&&t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[We?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Et(We,B.has("__streaming__"))}),t.jsx("button",{type:"button",className:`btn btn-icon quick-chat-message-render-toggle${B.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":B.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>xt("__streaming__"),children:B.has("__streaming__")?t.jsx($r,{size:12}):t.jsx(Vi,{size:12})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Ke?"Thinking…":"Connecting…"}),zm(Ne,!0),Ke&&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:Ke})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:at,type:"text",value:P,onChange:$t,onKeyDown:Le,onKeyUp:Lt,onClick:qt,onBlur:Dt,onFocus:Bt,placeholder:Fe,disabled:be,"data-testid":"quick-chat-input"}),t.jsx(PT,{agents:d,filter:_,highlightedIndex:I,visible:G,onSelect:Tt,position:"above"}),t.jsx(zT,{visible:U.mentionActive&&!G,position:X,files:U.files,selectedIndex:U.selectedIndex,onSelect:Me=>{const Qe=U.selectFile(Me,P);T(Qe),U.dismissMention(),z(!1),at.current?.focus()},loading:U.loading}),se&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Je}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:J,children:"×"})]})]}),Pe?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:De,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ls,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void st(),disabled:be||P.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(vi,{size:16})})]})]})]})}function _a(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Fm(e){return e.status==="generating"||e.status==="awaiting_input"}function Aa(e){return e==="complete"||e==="error"}function XT(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=la(),d=a.useCallback(()=>{Sh(e).then(p=>{const f=p.filter(v=>{const x=_a(v.updatedAt),k=r.current.get(v.id);return k===void 0?!0:x<=k?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of f)b.set(v.id,_a(v.updatedAt));i.current=b,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 b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,k=i.current.get(v.sessionId)??0;if(x<k)continue;const M=r.current.get(v.sessionId);if(M!==void 0&&x<=M)continue;if(M!==void 0&&x>M&&!Aa(v.status)&&r.current.delete(v.sessionId),Aa(v.status)){b.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,x);continue}const y=b.get(v.sessionId),R=v.type??y?.type,j=v.title??y?.title;if(!y&&(!R||!j))continue;const C={id:v.sessionId,type:R??"planning",status:v.status,title:j??"AI Session",projectId:v.projectId??y?.projectId??e??null,lockedByTab:v.owningTabId??y?.lockedByTab??null,updatedAt:v.updatedAt??y?.updatedAt??new Date(x).toISOString()},S=b.get(v.sessionId);(!S||S.status!==C.status||S.title!==C.title||S.type!==C.type||S.projectId!==C.projectId||S.lockedByTab!==C.lockedByTab||S.updatedAt!==C.updatedAt)&&(b.set(v.sessionId,C),i.current.set(v.sessionId,x),f=!0)}return f?[...b.values()].sort((v,x)=>_a(x.updatedAt)-_a(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const x=JSON.parse(v.data),k=_a(x.updatedAt)||Date.now();s(M=>{const y=i.current.get(x.id)??0;if(k<y)return M;const R=r.current.get(x.id);if(R!==void 0&&k<=R)return M;if(R!==void 0&&k>R&&!Aa(x.status)&&r.current.delete(x.id),i.current.set(x.id,k),Aa(x.status))return M.filter(C=>C.id!==x.id);const j=M.findIndex(C=>C.id===x.id);if(j>=0){const C=[...M];return C[j]=x,C}return Fm(x)?[x,...M]:M}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:k}),Aa(x.status)&&c({sessionId:x.id,status:x.status,timestamp:k})}catch{}},b=v=>{try{const x=JSON.parse(v.data);s(k=>k.filter(M=>M.id!==x)),i.current.delete(x),r.current.delete(x)}catch{}};return qs(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":b}})},[c,l,e]);const m=a.useCallback(async p=>{const b=n.find(y=>y.id===p)?.type,v=_i();let x=!1,k=!1;if(b==="planning")try{await gh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${p}: locked by another tab`))}else if(b==="subtask")try{await vh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${p}: locked by another tab`))}else if(b==="mission_interview")try{await Nh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${p}: locked by another tab`))}if(k)return;x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const M=Date.now();r.current.set(p,M),i.current.set(p,Math.max(i.current.get(p)??0,M)),c({sessionId:p,status:"complete",timestamp:M});try{await Mk(p)}catch{}s(y=>y.filter(R=>R.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Fm(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 In(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 Om(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function ZT(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),b=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,k=a.useCallback(async I=>{const w=++m.current,q=n,W=I?.searchQueryOverride??s,B=I?.includeArchivedOverride??u.current;try{const A=await vx(void 0,void 0,q,W,B);if(m.current!==w||n!==q)return;o(A.map(In)),f.current=Date.now()}catch{if(m.current!==w||n!==q)return;if(I?.clearOnError){o([]);return}o(A=>A)}},[n,s]);p.current=k;const M=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const I=setTimeout(()=>{k({searchQueryOverride:s})},300);return()=>clearTimeout(I)},[s]),a.useEffect(()=>{k({clearOnError:!0});const I=()=>{if(document.visibilityState!=="visible")return;const w=Date.now();w-h.current<x||(h.current=w,k())};return document.addEventListener("visibilitychange",I),()=>{document.removeEventListener("visibilitychange",I)}},[k]),a.useEffect(()=>{if(i===!1)return;const I=b.current,w=n?`?projectId=${encodeURIComponent(n)}`:"",q=()=>b.current!==I;let W=!0;const B=pe=>{if(q())return;const ie=In(JSON.parse(pe.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(re=>re.some(F=>F.id===ie.id)?re:[...re,ie])},A=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ie,to:re}=JSON.parse(pe.data),F=In(ie);o(ce=>ce.map(ae=>ae.id===F.id?{...F,column:re}:ae)),f.current=Date.now()},z=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ie=In(JSON.parse(pe.data));o(re=>re.map(F=>{if(F.id!==ie.id||Om(ie.updatedAt,F.updatedAt)<0)return F;if(F.column===ie.column)return ie;const ae=Om(F.columnMovedAt,ie.columnMovedAt);return F.columnMovedAt&&!ie.columnMovedAt?{...ie,column:F.column,columnMovedAt:F.columnMovedAt}:ae>0?{...ie,column:F.column,columnMovedAt:F.columnMovedAt}:ie})),f.current=Date.now()},X=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ie=In(JSON.parse(pe.data));o(re=>re.filter(F=>F.id!==ie.id))},E=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ie}=JSON.parse(pe.data),re=In(ie);o(F=>F.map(ce=>ce.id===re.id?{...re,column:"done"}:ce))},U=qs(`/api/events${w}`,{events:{"task:created":B,"task:moved":A,"task:updated":z,"task:deleted":X,"task:merged":E},onReconnect:()=>{W&&(q()||p.current())}});return()=>{W=!1,U()}},[n,i]);const y=a.useCallback(async I=>{const w=In(await mh(I,n));return o(q=>q.some(W=>W.id===w.id)?q:[...q,w]),w},[n]),R=a.useCallback(async(I,w)=>In(await kx(I,w,n)),[n]),j=a.useCallback(async I=>In(await hh(I,n)),[n]),C=a.useCallback(async I=>In(await jx(I,n)),[n]),S=a.useCallback(async I=>wx(I,n),[n]),P=a.useCallback(async I=>In(await Nx(I,n)),[n]),T=a.useCallback(async I=>{const w=In(await Sx(I,n));return o(q=>q.some(W=>W.id===w.id)?q:[...q,w]),w},[n]),_=a.useCallback(async(I,w)=>{const q=d.current.find(B=>B.id===I),W=q?{...q,...w,updatedAt:new Date().toISOString()}:void 0;W&&o(B=>B.map(A=>A.id===I?W:A));try{const B=In(await Ks(I,w,n));return o(A=>A.map(z=>z.id===I?B:z)),B}catch(B){throw q&&o(A=>A.map(z=>z.id===I?q:z)),B}},[n]),L=a.useCallback(async I=>{const w=In(await Ex(I,n));return o(q=>q.map(W=>W.id===I?w:W)),w},[n]),G=a.useCallback(async I=>{const w=In(await Mx(I,n));return o(q=>q.map(W=>W.id===I?w:W)),w},[n]),$=a.useCallback(async()=>{const w=(await _x(n)).map(In);return o(q=>q.map(W=>w.find(A=>A.id===W.id)||W)),w},[n]);return{tasks:r,createTask:y,moveTask:R,pauseTask:j,deleteTask:C,mergeTask:S,retryTask:P,duplicateTask:T,updateTask:_,archiveTask:L,unarchiveTask:G,archiveAllDone:$,loadArchivedTasks:M,includeArchived:l,lastFetchTimeMs:f.current}}const eR=5e3,tR=1e3;function nR(){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 pd();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 b=performance.now();try{const v=await pd(),k=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${k}`),Pa("[useProjects]",k),g||(n(v),o(null))}catch(v){const k=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${k}`),Pa("[useProjects]",k),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<tR||(c.current=b,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},eR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Cy(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await Ay(g,p);return n(b=>b.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await kh(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 sR=1e4,iR=1e3;function aR(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const p=await fd();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const v=await fd();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<iR||(c.current=v,u())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},sR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await jy(p);return n(b=>[...b,f]),f},[]),m=a.useCallback(async(p,f)=>{const b=await wy(p,f);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await Ny(p),n(f=>f.filter(b=>b.id!==p))},[]),g=a.useCallback(async p=>{const f=await Sy(p);n(b=>b.map(v=>v.id===p?{...v,status:f.status,updatedAt:f.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:g}}const rR="kb-dashboard-current-project";function oR(e){return e??"local"}function lR(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=oR(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await ra();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(k=>k.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(rR);if(x){const k=JSON.parse(x);k?.id&&e.some(y=>y.id===k.id)&&(r(k),c.current=!0,d.current={...d.current,[m]:k.id},await nn({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(b=>b.id===i.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,nn({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,nn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,nn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const ff=a.createContext(null);function cR({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()},[]),Jm.createElement(ff.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function dR(){const e=a.useContext(ff);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const gf="kb-dashboard-theme-mode",bf="kb-dashboard-color-theme",xf=[...ej],ac="theme-data",Cl="theme-data.css";function uR(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Cl}`:e.replace(/\/[^/]+$/,`/${Cl}`):`/${Cl}`}const Ns=typeof window<"u",mR=Ns?a.useLayoutEffect:a.useEffect;function vf(e){return e==="dark"||e==="light"||e==="system"}function Um(){if(!Ns)return"dark";try{const e=localStorage.getItem(gf);if(vf(e))return e}catch{}return"dark"}function Bm(){if(!Ns)return"default";try{const e=localStorage.getItem(bf);if(e&&xf.includes(e))return e}catch{}return"default"}function Hm(e){if(Ns)try{localStorage.setItem(gf,e)}catch{}}function qm(e){if(Ns)try{localStorage.setItem(bf,e)}catch{}}function hR(e,n){return e==="system"?n?"dark":"light":e}function pR(e,n,s){if(!Ns)return;const i=hR(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Vm(){if(!Ns)return;const e=uR(),n=document.getElementById(ac);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=ac,document.head.appendChild(s)}function Wm(){if(!Ns)return;const e=document.getElementById(ac);e&&e.remove()}function fR(){const[e,n]=a.useState(()=>Um()),[s,i]=a.useState(()=>Bm()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ns?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(!Ns||!r)return;let f=!1;return ra().then(b=>{f||(vf(b.themeMode)&&!m.current&&(u.current!==b.themeMode&&(u.current=b.themeMode,n(b.themeMode)),Um()!==b.themeMode&&Hm(b.themeMode)),b.colorTheme&&xf.includes(b.colorTheme)&&!h.current&&(d.current!==b.colorTheme&&(d.current=b.colorTheme,i(b.colorTheme)),Bm()!==b.colorTheme&&qm(b.colorTheme)))}).catch(b=>{console.warn("[useTheme] Failed to hydrate theme from global settings",b)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Ns)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),b=v=>{c(v.matches)};return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),mR(()=>{pR(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ns||r||(s!=="default"?Vm():Wm())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Hm(f),nn({themeMode:f}).catch(b=>{console.warn("[useTheme] Failed to persist themeMode to global settings",b)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),qm(f),f!=="default"?Vm():Wm(),nn({colorTheme:f}).catch(b=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",b)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function gR(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,b]=a.useState(void 0),[v,x]=a.useState(null),[k,M]=a.useState("definition"),[y,R]=a.useState(!1),[j,C]=a.useState(void 0),[S,P]=a.useState(!1),[T,_]=a.useState(!1),[L,G]=a.useState(!1),[$,I]=a.useState(!1),[w,q]=a.useState(void 0),[W,B]=a.useState(!1),[A,z]=a.useState("project"),[X,E]=a.useState(!1),[U,pe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),[ae,Q]=a.useState(!1),[de,Te]=a.useState(!1),[fe,Se]=a.useState(!1),te=!!(v||y||s||r||m||$||W||X||U||ie||ae||F||L||S||T||de||fe),we=a.useCallback(()=>i(!0),[]),Pe=a.useCallback(()=>i(!1),[]),We=a.useCallback(()=>o(!0),[]),Ke=a.useCallback(ut=>{c(ut),o(!0)},[]),Ne=a.useCallback(()=>{const ut=n[0];ut&&(d(ut.id),o(!0))},[n]),_e=a.useCallback(ut=>{d(ut),o(!0)},[]),Oe=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),ye=a.useCallback(ut=>{p(ut),h(!0)},[]),De=a.useCallback(ut=>{b(ut),h(!0)},[]),se=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),J=a.useCallback((ut,Me="definition")=>{x(ut),M(Me)},[]),me=a.useCallback(ut=>{x(ut),M("changes")},[]),ee=a.useCallback(ut=>{x(Me=>Me&&{...Me,...ut})},[]),he=a.useCallback(()=>{x(null)},[]),le=a.useCallback(ut=>{C(ut),R(!0)},[]),Ie=a.useCallback(()=>{R(!1),C(void 0)},[]),Ze=a.useCallback(()=>P(!0),[]),at=a.useCallback(()=>P(!1),[]),oe=a.useCallback(()=>_(!0),[]),Z=a.useCallback(()=>_(!1),[]),ue=a.useCallback(()=>G(!0),[]),Ce=a.useCallback(()=>G(!1),[]),$e=a.useCallback(()=>{I(ut=>!ut)},[]),ve=a.useCallback(()=>{I(!1),q(void 0)},[]),Ge=a.useCallback(()=>B(!0),[]),je=a.useCallback(()=>B(!1),[]),Ue=a.useCallback(ut=>{z(ut)},[]),He=a.useCallback(()=>E(!0),[]),ge=a.useCallback(()=>E(!1),[]),Fe=a.useCallback(()=>pe(!0),[]),be=a.useCallback(()=>pe(!1),[]),Je=a.useCallback(()=>re(!0),[]),st=a.useCallback(()=>re(!1),[]),dt=a.useCallback(()=>ce(!0),[]),Tt=a.useCallback(()=>ce(!1),[]),$t=a.useCallback(()=>Q(!0),[]),Dt=a.useCallback(()=>Q(!1),[]),Bt=a.useCallback(async(ut,Me)=>{Q(!1),q(Me),I(!0)},[]),qt=a.useCallback(()=>Te(!0),[]),Lt=a.useCallback(()=>Te(!1),[]),Ct=a.useCallback(()=>Se(!0),[]),xt=a.useCallback(()=>Se(!1),[]),Et=a.useCallback((ut,Me)=>{Me(`Created ${ut.id} from planning mode`,"success"),o(!1),c(null)},[]),Le=a.useCallback((ut,Me)=>{const Qe=ut.map(rt=>rt.id).join(", ");Me(`Created ${Qe} from planning mode`,"success"),o(!1),c(null)},[]),gt=a.useCallback((ut,Me)=>{const Qe=ut.map(rt=>rt.id).join(", ");Me(`Created ${Qe} 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:k,settingsOpen:y,settingsInitialSection:j,schedulesOpen:S,githubImportOpen:T,usageOpen:L,terminalOpen:$,terminalInitialCommand:w,filesOpen:W,fileBrowserWorkspace:A,activityLogOpen:X,gitManagerOpen:U,workflowStepsOpen:ie,agentsOpen:F,scriptsOpen:ae,setupWizardOpen:de,modelOnboardingOpen:fe,anyModalOpen:te,openNewTask:we,closeNewTask:Pe,openPlanning:We,openPlanningWithInitialPlan:Ke,resumePlanning:Ne,openPlanningWithSession:_e,closePlanning:Oe,openSubtaskBreakdown:ye,openSubtaskWithSession:De,closeSubtask:se,openDetailTask:J,openDetailWithChangesTab:me,updateDetailTask:ee,closeDetailTask:he,openSettings:le,closeSettings:Ie,openSchedules:Ze,closeSchedules:at,openGitHubImport:oe,closeGitHubImport:Z,openUsage:ue,closeUsage:Ce,toggleTerminal:$e,closeTerminal:ve,openFiles:Ge,closeFiles:je,setFileWorkspace:Ue,openActivityLog:He,closeActivityLog:ge,openGitManager:Fe,closeGitManager:be,openWorkflowSteps:Je,closeWorkflowSteps:st,openAgents:dt,closeAgents:Tt,openScripts:$t,closeScripts:Dt,runScript:Bt,openSetupWizard:qt,closeSetupWizard:Lt,openModelOnboarding:Ct,closeModelOnboarding:xt,onPlanningTaskCreated:Et,onPlanningTasksCreated:Le,onSubtaskTasksCreated:gt}}function bR(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),[b,v]=a.useState(!1),[x,k]=a.useState({}),[M,y]=a.useState(!1),[R,j]=a.useState(!1),[C,S]=a.useState(!1),[P,T]=a.useState(!1),_=a.useCallback(async()=>{const[w,q]=await Promise.allSettled([Rx(e),ro(e)]);if(w.status==="fulfilled"&&(s(w.value.maxConcurrent),r(w.value.rootDir)),q.status==="fulfilled"){const W=q.value;l(!!W.autoMerge),u(!!W.globalPause),m(!!W.enginePaused),v(!!W.prAuthAvailable),g(W.taskStuckTimeoutMs),f(W.showQuickChatFAB===!0),k(W.experimentalFeatures??{});const B=W.experimentalFeatures??{};y(B.insights===!0),j(B.roadmap===!0),S(B.memoryView===!0),T(B.devServerView===!0||B.devServer===!0)}},[e]);a.useEffect(()=>{_()},[_]);const L=a.useCallback(async()=>{const w=!o;l(w);try{await dr({autoMerge:w},e)}catch{l(!w)}},[o,e]),G=a.useCallback(async()=>{const w=!c;u(w);try{await dr({globalPause:w,globalPauseReason:w?"manual":void 0},e)}catch{u(!w)}},[c,e]),$=a.useCallback(async()=>{const w=!d;m(w);try{await dr({enginePaused:w},e)}catch{m(!w)}},[d,e]),I=a.useCallback(async()=>{const w=!p;f(w);try{await dr({showQuickChatFAB:w},e)}catch{f(!w)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,experimentalFeatures:x,insightsEnabled:M,roadmapEnabled:R,memoryEnabled:C,devServerEnabled:P,toggleAutoMerge:L,toggleGlobalPause:G,toggleEnginePause:$,toggleShowQuickChatFAB:I,refresh:_}}function xR(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(x=>x.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,Or(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 vR(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{is().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 nn({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 nn({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 yR({projectId:e,openModelOnboarding:n,openSettings:s}){const i=a.useRef(!1);a.useEffect(()=>{if(i.current)return;i.current=!0;let r=!1,o=!1;Ba().then(({providers:l})=>{const c=l.some(d=>d.authenticated);if(l.length>0&&!c||l.length>0&&c)return ra().then(d=>{const m=!!(d.defaultProvider&&d.defaultModelId);(d.modelOnboardingComplete===!1||d.modelOnboardingComplete===void 0)&&(!c||!m)&&!sa()?r=!0:!c&&!sa()&&(o=!0)})}).then(()=>{r?(js("onboarding:auto-triggered",{trigger:"first-run"}),n()):o&&(js("onboarding:auto-triggered",{trigger:"missing-provider"}),s("authentication"))}).catch(()=>{})},[e,n,s])}const kR=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function Gm(e){return e!==null&&kR.includes(e)}function jR(e){return e==="devserver"?"dev-server":e}function wR(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[g,p]=a.useState(()=>{const x=Nn("kb-dashboard-task-view");return Gm(x)?x:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Nn("kb-dashboard-task-view",r?.id);if(Gm(x)){const k=!f.current&&x==="devserver";p(k?"devserver":jR(x))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{ts("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 x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,c]);const b=a.useCallback(x=>{p(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],k=x.indexOf(u),M=x[(k+1)%x.length];d(M)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function NR(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(S=>{n(S),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),x=a.useCallback(S=>{h(),n(S),i("project"),u(`Project ${S.name} registered successfully`,"success"),o()},[h,n,i,u,o]),k=a.useCallback(()=>{g()},[g]),M=a.useCallback(async S=>{try{await My(S.id),u(`Project ${S.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${S.name}`,"error")}},[u,o]),y=a.useCallback(async S=>{try{await _y(S.id),u(`Project ${S.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${S.name}`,"error")}},[u,o]),R=a.useCallback(async S=>{try{await kh(S.id),u(`Project ${S.name} removed`,"success"),r?.id===S.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${S.name}`,"error")}},[r,s,i,u,o]),j=a.useCallback(async S=>{try{await l(S)}catch{u("Failed to update favorites","error")}},[l,u]),C=a.useCallback(async S=>{try{await c(S)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:k,handlePauseProject:M,handleResumeProject:y,handleRemoveProject:R,handleToggleFavorite:j,handleToggleModelFavorite:C}}function SR(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 CR(e){return lo("/health",{nodeId:e})}async function ER(e){return lo("/projects",{nodeId:e})}async function MR(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),lo(`/tasks?${i.toString()}`,{nodeId:e})}async function _R(e,n){return lo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function dP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function uP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function mP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function hP(e){return D(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function AR(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),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const x=new AbortController;f.current=x,h(!0),p(null);try{const k=[CR(e),ER(e)];s&&(k.push(MR(e,s,i)),k.push(_R(e,s)));const M=await Promise.allSettled(k);if(x.signal.aborted)return;const y=M[0],R=M[1];if(y.status==="rejected"){p(`Failed to fetch node health: ${y.reason}`),h(!1);return}if(d(y.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&M[2]){const j=M[2];if(j.status==="rejected"){p(`Failed to fetch tasks: ${j.reason}`),h(!1);return}j.status==="fulfilled"&&c(j.value)}h(!1)}catch(k){x.signal.aborted||(p(k instanceof Error?k.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{f.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function TR(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 qs(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 RR="fusion-dashboard-current-node",yf=a.createContext(null);function IR({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 ra();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(RR);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(l.current=b.id,await nn({dashboardCurrentNodeId:b.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,nn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,nn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,nn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(yf.Provider,{value:d,children:e})}function PR(){const e=a.useContext(yf);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function $R({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&&(lx(l),window.location.reload())},[n]),o=a.useCallback(()=>{cx(),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 DR=a.lazy(()=>Zt(()=>import("./AgentsView-DegK8aw-.js").then(e=>e.A),__vite__mapDeps([16,1,17,8,18])).then(e=>({default:e.AgentsView}))),LR=a.lazy(()=>Zt(()=>import("./DocumentsView-CsQxuyz3.js"),__vite__mapDeps([19,1,0,2,20])).then(e=>({default:e.DocumentsView}))),zR=a.lazy(()=>Zt(()=>import("./InsightsView-Bzs7A2jv.js"),__vite__mapDeps([21,1,14,0,2,22])).then(e=>({default:e.InsightsView}))),FR=a.lazy(()=>Zt(()=>import("./NodesView-BpiqRlvc.js"),__vite__mapDeps([23,1,17,0,2,24])).then(e=>({default:e.NodesView}))),OR=a.lazy(()=>Zt(()=>import("./ChatView-CYpEShLS.js"),__vite__mapDeps([25,1,0,2])).then(e=>({default:e.ChatView}))),UR=a.lazy(()=>Zt(()=>import("./RoadmapsView-CYPLTTB0.js"),__vite__mapDeps([26,1,0,2,27])).then(e=>({default:e.RoadmapsView}))),BR=a.lazy(()=>Zt(()=>import("./SkillsView-Dlpw5LKI.js"),__vite__mapDeps([28,1,0,2,29])).then(e=>({default:e.SkillsView}))),HR=a.lazy(()=>Zt(()=>import("./MemoryView-Cl5ASqjW.js"),__vite__mapDeps([30,1,12,13,0,2,31])).then(e=>({default:e.MemoryView}))),qR=a.lazy(()=>Zt(()=>import("./DevServerView-DfCTA9fx.js"),__vite__mapDeps([32,1,0,2,33])).then(e=>({default:e.DevServerView})));function VR(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Zt(()=>import("./AgentsView-DegK8aw-.js").then(n=>n.A),__vite__mapDeps([16,1,17,8,18])),Zt(()=>import("./DocumentsView-CsQxuyz3.js"),__vite__mapDeps([19,1,0,2,20])),Zt(()=>import("./InsightsView-Bzs7A2jv.js"),__vite__mapDeps([21,1,14,0,2,22])),Zt(()=>import("./NodesView-BpiqRlvc.js"),__vite__mapDeps([23,1,17,0,2,24])),Zt(()=>import("./ChatView-CYpEShLS.js"),__vite__mapDeps([25,1,0,2])),Zt(()=>import("./RoadmapsView-CYPLTTB0.js"),__vite__mapDeps([26,1,0,2,27])),Zt(()=>import("./SkillsView-Dlpw5LKI.js"),__vite__mapDeps([28,1,0,2,29])),Zt(()=>import("./MemoryView-Cl5ASqjW.js"),__vite__mapDeps([30,1,12,13,0,2,31])),Zt(()=>import("./DevServerView-DfCTA9fx.js"),__vite__mapDeps([32,1,0,2,33]))})}const El="kb-setup-warning-dismissed";function WR(){const{toasts:e,addToast:n,removeToast:s}=dR(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{VR()},[]);const{projects:r,loading:o,error:l,refresh:c}=nR(),{nodes:u}=aR(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=PR(),{currentProject:f,setCurrentProject:b,clearCurrentProject:v,loading:x}=lR(r,{nodeId:m}),{hasAiProvider:k,hasGithub:M,loading:y,hasWarnings:R}=of(f?.id);a.useEffect(()=>{if(m&&!d&&u.length>0){const ct=u.find(ne=>ne.id===m);if(ct){g(ct);return}}m&&u.length>0&&(u.some(ne=>ne.id===m)||p())},[m,d,u,g,p]);const[j,C]=a.useState(""),S=AR(m,{projectId:f?.id,searchQuery:j||void 0});TR(m);const P=h&&S.projects.length>0?S.projects:r,{themeMode:T,colorTheme:_,setThemeMode:L,setColorTheme:G}=fR(),{sessions:$,generating:I,needsInput:w,planningSessions:q,dismissSession:W}=XT(f?.id),B=$.filter(ct=>ct.status==="awaiting_input"||ct.status==="error"),A=gR({projectId:f?.id,planningSessions:q}),{viewMode:z,setViewMode:X,taskView:E,handleChangeTaskView:U}=wR({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:f,projectsLength:r.length,setupWizardOpen:A.setupWizardOpen,openSetupWizard:A.openSetupWizard,themeMode:T,setThemeMode:L}),pe=a.useCallback(ct=>{ct==="missions"&&(ue(void 0),$e(void 0),Ge(void 0)),U(ct)},[U]),ie=E==="board"||E==="list",{tasks:re,createTask:F,moveTask:ce,pauseTask:ae,deleteTask:Q,mergeTask:de,retryTask:Te,updateTask:fe,duplicateTask:Se,archiveTask:te,unarchiveTask:we,archiveAllDone:Pe,loadArchivedTasks:We,lastFetchTimeMs:Ke}=ZT({...f?{projectId:f.id}:{},searchQuery:j||void 0,sseEnabled:ie}),[Ne,_e]=a.useState(!1),Oe=a.useRef(performance.now()),ye=a.useRef(!1),De=a.useRef(!1),se=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!ye.current){ye.current=!0;const ct=`projects loaded at ${Math.round(performance.now()-Oe.current)}ms from mount`;console.log(`[App] ${ct}`),Pa("[App]",ct)}if(!x&&!De.current){De.current=!0;const ct=`current-project resolved at ${Math.round(performance.now()-Oe.current)}ms from mount`;console.log(`[App] ${ct}`),Pa("[App]",ct)}},[o,x]),a.useEffect(()=>{if(Ne||o||x)return;const ct=performance.now(),ne=window.setTimeout(()=>{const Ee=`dashboard ready at ${Math.round(performance.now()-Oe.current)}ms from mount (settle delay=${Math.round(performance.now()-ct)}ms)`;console.log(`[App] ${Ee}`),Pa("[App]",Ee),_e(!0)},200);return()=>{window.clearTimeout(ne)}},[Ne,o,x]);const me=tr()==="mobile",[ee,he]=a.useState(0),le=a.useCallback(()=>{Ch(f?.id).then(ct=>{he(ct.unreadCount)}).catch(ct=>{console.warn("[App] Failed to fetch mailbox unread count:",ct)})},[f?.id]);a.useEffect(()=>{le();const ct=new URLSearchParams;f?.id&&ct.set("projectId",f.id);const ne=ct.size>0?`?${ct.toString()}`:"";return qs(`/api/events${ne}`,{events:{"message:sent":le,"message:received":le,"message:read":le,"message:deleted":le}})},[f?.id,le]);const[Ie,Ze]=a.useState(!1),[at,oe]=a.useState(!1),[Z,ue]=a.useState(void 0),[Ce,$e]=a.useState(void 0),[ve,Ge]=a.useState(void 0),[je,Ue]=a.useState(!1),[He,ge]=a.useState(!1),[Fe,be]=a.useState(()=>Nn(El,f?.id)==="true");a.useEffect(()=>{be(Nn(El,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const ct=()=>{ge(!0)};return window.addEventListener(Dl,ct),()=>{window.removeEventListener(Dl,ct)}},[]);const Je=a.useCallback(()=>{ts(El,"true",f?.id),be(!0)},[f?.id]),{maxConcurrent:st,autoMerge:dt,globalPaused:Tt,enginePaused:$t,taskStuckTimeoutMs:Dt,showQuickChatFAB:Bt,prAuthAvailable:qt,experimentalFeatures:Lt,insightsEnabled:Ct,roadmapEnabled:xt,memoryEnabled:Et,devServerEnabled:Le,toggleAutoMerge:gt,toggleGlobalPause:ut,toggleEnginePause:Me,refresh:Qe}=bR(f?.id),rt=Lt.skillsView===!0,N=Lt.nodesView===!0,H=!0;a.useEffect(()=>{Object.keys(Lt).length!==0&&(E==="insights"&&!Ct&&U("board"),E==="roadmaps"&&!xt&&U("board"),E==="memory"&&!Et&&U("board"),(E==="devserver"||E==="dev-server")&&!Le&&U("board"))},[E,Ct,xt,Lt,U,H,Et,Le]),a.useEffect(()=>{Ie&&!N&&Ze(!1)},[Ie,N]);const{availableModels:Ae,favoriteProviders:ot,favoriteModels:kt,toggleFavoriteProvider:Ot,toggleFavoriteModel:sn}=vR();yR({projectId:f?.id,openModelOnboarding:A.openModelOnboarding,openSettings:A.openSettings});const{handleSelectProject:Rt,handleViewAllProjects:zn,handleOpenSettings:Wn,handleAddProject:ms,handleSetupComplete:pn,handleModelOnboardingComplete:Fn,handlePauseProject:Sn,handleResumeProject:fn,handleRemoveProject:Gn,handleToggleFavorite:dn,handleToggleModelFavorite:Mt}=NR({setCurrentProject:b,clearCurrentProject:v,setViewMode:X,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Ot,toggleFavoriteModel:sn,addToast:n,openSettings:A.openSettings,openSetupWizard:A.openSetupWizard,closeSetupWizard:A.closeSetupWizard,closeModelOnboarding:A.closeModelOnboarding}),{handleDetailClose:yn}=xR({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:b,addToast:n,openTaskDetail:A.openDetailTask,closeTaskDetail:A.closeDetailTask}),{handleBoardQuickCreate:Kn,handleModalCreate:kn,handlePlanningTaskCreated:_n,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:On}=SR({createTask:F,onPlanningTaskCreated:A.onPlanningTaskCreated,onPlanningTasksCreated:A.onPlanningTasksCreated,onSubtaskTasksCreated:A.onSubtaskTasksCreated,addToast:n}),K=a.useCallback((ct,ne)=>{if(ne==="changes"){A.openDetailWithChangesTab(ct);return}A.openDetailTask(ct,ne)},[A]),ze=a.useCallback(()=>{N&&Ze(ct=>!ct)},[N]),tt=a.useCallback(()=>{A.setFileWorkspace("project"),A.openFiles()},[A]),et=a.useCallback(async()=>{oe(!0);try{await c()}finally{oe(!1)}},[c]),mt=a.useCallback(ct=>{$e(ct),ue(void 0),U("missions")},[U]),jt=a.useCallback(ct=>{ct.type==="planning"?A.openPlanningWithSession(ct.id):ct.type==="subtask"?A.openSubtaskWithSession(ct.id):ct.type==="mission_interview"?($e(void 0),ue(ct.id),Ge(void 0),U("missions")):(ct.type==="milestone_interview"||ct.type==="slice_interview")&&(ue(void 0),$e(void 0),Ge(ct.id),U("missions"))},[U,A]),_t=a.useCallback(()=>{for(const ct of B)W(ct.id)},[W,B]),gn=!o&&!x&&r.length===0&&!f&&!!l,fs=()=>gn?t.jsx(pT,{errorMessage:l??"Failed to fetch projects",isRetrying:at,onRetry:et}):Ie?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(FR,{addToast:n,onClose:()=>Ze(!1)})})})}):z==="overview"?t.jsx(Xn,{children:t.jsx(yw,{projects:r,loading:o,onSelectProject:Rt,onAddProject:ms,onPauseProject:Sn,onResumeProject:fn,onRemoveProject:Gn,nodes:u})}):E==="skills"?rt?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(BR,{addToast:n,projectId:f?.id,onClose:()=>U("board")})})}):(U("board"),null):E==="chat"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(OR,{addToast:n,projectId:f?.id})})}):E==="mailbox"?t.jsx(Xn,{children:t.jsx(mN,{projectId:f?.id,addToast:n,onUnreadCountChange:he})}):E==="roadmaps"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(UR,{addToast:n,projectId:f?.id})})}):E==="missions"?t.jsx(Xn,{children:t.jsx(lN,{isInline:!0,isOpen:!0,onClose:()=>{$e(void 0),ue(void 0),Ge(void 0),U("board")},addToast:n,projectId:f?.id,onSelectTask:ct=>{const ne=re.find(Ee=>Ee.id===ct);ne&&A.openDetailTask(ne)},availableTasks:re.map(ct=>({id:ct.id,title:ct.title})),resumeSessionId:Z,targetMissionId:Ce,milestoneSliceResumeSessionId:ve,onMilestoneSliceResumeFetchError:()=>Ge(void 0)})}):E==="agents"&&H?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(DR,{addToast:n,projectId:f?.id})})}):E==="documents"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(LR,{projectId:f?.id,addToast:n,onOpenDetail:A.openDetailTask})})}):E==="insights"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(zR,{projectId:f?.id,addToast:n,onClose:()=>U("board")})})}):E==="memory"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(HR,{addToast:n,projectId:f?.id})})}):E==="devserver"||E==="dev-server"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(qR,{addToast:n,projectId:f?.id})})}):E==="board"?t.jsx(Xn,{children:t.jsx(lw,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f?.id,maxConcurrent:st,onMoveTask:ce,onPauseTask:ae,onOpenDetail:A.openDetailTask,addToast:n,onQuickCreate:Kn,onNewTask:A.openNewTask,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,autoMerge:dt,onToggleAutoMerge:gt,globalPaused:Tt,onUpdateTask:fe,onArchiveTask:te,onUnarchiveTask:we,onDeleteTask:Q,onArchiveAllDone:Pe,onLoadArchivedTasks:We,searchQuery:j,availableModels:Ae,onOpenDetailWithTab:K,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt,taskStuckTimeoutMs:Dt,onOpenMission:mt,lastFetchTimeMs:Ke})}):t.jsx(Xn,{children:t.jsx(dw,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f?.id,onMoveTask:ce,onOpenDetail:A.openDetailTask,addToast:n,globalPaused:Tt,onNewTask:A.openNewTask,onQuickCreate:Kn,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,availableModels:Ae,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt,taskStuckTimeoutMs:Dt,searchQuery:j,lastFetchTimeMs:Ke})});if(!Ne)return t.jsxs(t.Fragment,{children:[t.jsx(gT,{stage:se}),t.jsx(hf,{toasts:e,onRemove:s})]});const Qt=!A.modelOnboardingOpen&&FA(),vt=!A.modelOnboardingOpen&&!Qt&&sa()&&!cf();return t.jsxs(t.Fragment,{children:[t.jsx(Jk,{isElectron:i,onOpenSettings:Wn,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:q.length,onOpenUsage:A.openUsage,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>pe("mailbox"),mailboxUnreadCount:ee,onOpenSchedules:A.openSchedules,onOpenGitManager:A.openGitManager,onOpenNodes:ze,showNodesButton:N,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenScripts:A.openScripts,onRunScript:A.runScript,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,filesOpen:A.filesOpen,globalPaused:Tt,enginePaused:$t,onToggleGlobalPause:ut,onToggleEnginePause:Me,view:E,onChangeView:z==="project"&&f?pe:void 0,showSkillsTab:rt,showAgentsTab:H,searchQuery:j,onSearchChange:C,projects:P,currentProject:f,onSelectProject:Rt,onViewAllProjects:zn,projectId:f?.id,mobileNavEnabled:me,availableNodes:u,currentNode:d,onSelectNode:ct=>{ct===null?p():g(ct)},isRemote:h,experimentalFeatures:{insights:Ct,roadmap:xt,memoryView:Et,devServer:Le,devServerView:Le}}),z==="project"&&f&&!Ie&&E!=="missions"&&!A.isPlanningOpen&&t.jsx(_T,{sessions:B,onResumeSession:jt,onDismissSession:W,onDismissAll:_t}),z==="project"&&f&&Qt&&t.jsx(AT,{onResume:A.openModelOnboarding}),z==="project"&&f&&vt&&t.jsx(TT,{onOpenModelOnboarding:A.openModelOnboarding,onOpenSettings:ct=>A.openSettings(ct)}),z==="project"&&f&&!y&&R&&!Fe&&t.jsx(lf,{hasAiProvider:k,hasGithub:M,onDismiss:Je}),t.jsx("div",{className:`project-content${z==="project"&&f?" project-content--with-footer":""}${me?" project-content--with-mobile-nav":""}`,children:fs()}),z==="project"&&f&&!Ie&&t.jsx(CT,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f.id,taskStuckTimeoutMs:Dt,backgroundSessions:$,backgroundGenerating:I,backgroundNeedsInput:w,onOpenBackgroundSession:jt,onDismissBackgroundSession:W,lastFetchTimeMs:Ke,currentProjectPath:f.path,onOpenProjectDirectory:tt}),t.jsx(IT,{view:E,onChangeView:z==="project"&&f?pe:()=>{},footerVisible:z==="project"&&!!f,modalOpen:A.anyModalOpen,onOpenSettings:Wn,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>pe("mailbox"),mailboxUnreadCount:ee,onOpenGitManager:A.openGitManager,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenSchedules:A.openSchedules,onOpenScripts:A.openScripts,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:q.length,onOpenUsage:A.openUsage,onViewAllProjects:zn,onRunScript:A.runScript,projectId:f?.id,showSkillsTab:rt,experimentalFeatures:{insights:Ct,roadmap:xt,memoryView:Et,devServer:Le,devServerView:Le}}),z==="project"&&f&&E!=="chat"&&E!=="mailbox"&&E!=="insights"&&E!=="devserver"&&E!=="dev-server"&&t.jsx(QT,{projectId:f.id,addToast:n,showFAB:Bt,open:je,onOpenChange:Ue,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt}),t.jsx(hT,{projectId:f?.id,tasks:re,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:A,projectActions:{handleAddProject:ms,handleSetupComplete:pn,handleModelOnboardingComplete:Fn},taskHandlers:{handleModalCreate:kn,handlePlanningTaskCreated:_n,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:On},taskOperations:{moveTask:ce,deleteTask:Q,mergeTask:de,retryTask:Te,duplicateTask:Se},deepLink:{handleDetailClose:yn},settings:{prAuthAvailable:qt,themeMode:T,colorTheme:_,setThemeMode:L,setColorTheme:G},onSettingsClose:()=>{A.closeSettings(),Qe()},onReopenOnboarding:()=>{A.closeSettings(),A.openModelOnboarding()}}),t.jsx($R,{open:He})]})}function GR(){return t.jsx(cR,{children:t.jsx(IR,{children:t.jsx(WR,{})})})}gx();tx();Sf.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(nx,{children:t.jsx(GR,{})})}));"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{A4 as $,Ss as A,an as B,tn as C,en as D,rn as E,Ni as F,to as G,jl as H,Ht as I,Fs as J,zt as K,it as L,_A as M,xy as N,jA as O,Mn as P,wA as Q,hn as R,Bi as S,lc as T,vy as U,yy as V,Y4 as W,Pt as X,_4 as Y,vn as Z,Zt as _,ts as a,MI as a$,Or as a0,Mv as a1,$r as a2,Vi as a3,ia as a4,Qs as a5,Xs as a6,Ys as a7,eP as a8,sP as a9,XI as aA,ZI as aB,Uk as aC,Bk as aD,OT as aE,tr as aF,rc as aG,PT as aH,zT as aI,ls as aJ,vi as aK,li as aL,Jb as aM,hI as aN,fI as aO,pI as aP,gI as aQ,bI as aR,xI as aS,vI as aT,yI as aU,kI as aV,jI as aW,wI as aX,NI as aY,SI as aZ,CI as a_,nP as aa,tP as ab,iP as ac,Dn as ad,ss as ae,Bb as af,Us as ag,xg as ah,Zr as ai,ji as aj,mP as ak,dP as al,uP as am,hP as an,Lr as ao,Pb as ap,Oa as aq,hg as ar,Hn as as,lh as at,aR as au,nR as av,QI as aw,yd as ax,Ha as ay,Ok as az,aI as b,cI as b$,_I as b0,EI as b1,xn as b2,oc as b3,wi as b4,JI as b5,KI as b6,YI as b7,d4 as b8,c4 as b9,Wv as bA,T4 as bB,aa as bC,io as bD,rh as bE,Ki as bF,Cy as bG,lx as bH,cx as bI,Of as bJ,n_ as bK,k4 as bL,uI as bM,YR as bN,Ba as bO,rI as bP,QR as bQ,ZR as bR,tv as bS,Wx as bT,Hs as bU,Gx as bV,Kx as bW,Jx as bX,N4 as bY,oI as bZ,lI as b_,l4 as ba,u4 as bb,v4 as bc,y4 as bd,g4 as be,h4 as bf,p4 as bg,f4 as bh,m4 as bi,o4 as bj,b4 as bk,g_ as bl,P4 as bm,I4 as bn,O4 as bo,R4 as bp,$4 as bq,D4 as br,L4 as bs,z4 as bt,Yv as bu,F4 as bv,dc as bw,Gv as bx,Kv as by,Jv as bz,Ve as c,w4 as c$,aP as c0,rP as c1,mI as c2,XR as c3,jn as c4,p_ as c5,TA as c6,_m as c7,co as c8,e4 as c9,eI as cA,th as cB,V4 as cC,q4 as cD,kA as cE,Q4 as cF,Ka as cG,zE as cH,B4 as cI,U4 as cJ,_v as cK,H4 as cL,W4 as cM,zI as cN,FI as cO,Eb as cP,Il as cQ,VI as cR,WI as cS,BI as cT,UI as cU,HI as cV,OI as cW,qI as cX,dI as cY,S4 as cZ,j4 as c_,t4 as ca,n4 as cb,s4 as cc,i4 as cd,a4 as ce,r4 as cf,im as cg,oP as ch,lP as ci,x4 as cj,AI as ck,RI as cl,$I as cm,II as cn,TI as co,PI as cp,DI as cq,yh as cr,td as cs,Kg as ct,LI as cu,X4 as cv,G4 as cw,J4 as cx,K4 as cy,tI as cz,sI as d,E4 as d0,M4 as d1,C4 as d2,iI as e,GI as f,Nn as g,is as h,oa as i,wn as j,by as k,nI as l,LT as m,ro as n,dr as o,xe as p,nj as q,Z4 as r,qs as s,Tl as t,nn as u,Os as v,Vt as w,Dr as x,NA as y,cP as z};
|
|
616
|
+
`)[0]?.trim()||yn?.title||"",kn=new Set(wl),_n=Wn.filter(K=>kn.has(K.id)).sort((K,ze)=>{const tt=wl.indexOf(K.id),et=wl.indexOf(ze.id);return tt!==et?tt-et:$m(K,ze)}),hs=Wn.filter(K=>K.authenticated&&!kn.has(K.id)),ps=Wn.filter(K=>!K.authenticated&&!kn.has(K.id)),On=K=>{if(K.id==="claude-cli"&&K.type==="cli")return t.jsx(TA,{authenticated:K.authenticated,onToggled:()=>{oe()}},K.id);if(K.type==="api_key"){const ze=sc(K.id),tt=aT(K);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Mn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(ah,{size:14,className:"onboarding-provider-key-icon"}),K.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:ze.description}),t.jsx(He,{status:Ue(K)}),K.authenticated&&K.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",K.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(oT,{provider:K,apiKeyInfo:tt,inputValue:Q[K.id]??"",isSaving:z===K.id,error:Te[K.id],success:Se[K.id],isConnected:K.authenticated,onInputChange:xt,onSave:Le,onClear:gt})})]},K.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${K.id}`,className:`onboarding-provider-card${K.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${K.id}`,"aria-hidden":"true",children:t.jsx(Mn,{provider:K.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:K.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:sc(K.id).description}),t.jsx(He,{status:Ue(K)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:z===K.id?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:K.authenticated?"Logging out…":"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>Ct(K.id),children:"Cancel"})]}):K.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>ut(K.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>Lt(K.id),children:"Login"})}),z===K.id&&E[K.id]&&t.jsx(_m,{instructions:E[K.id],"data-testid":`onboarding-login-instructions-${K.id}`}),Ke[K.id]==="timeout"&&z!==K.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ke[K.id]==="failed"&&z!==K.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},K.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",children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(vn,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(es,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Jc,{size:24})," Set Up Your Project"]}),b==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Jc,{size:24})," Create Your First Task"]}),b==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(tn,{size:24})," All Set!"]})]}),b!=="complete"&&t.jsx("button",{className:"modal-close",onClick:ot,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(Pt,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:le.map((K,ze)=>{const tt=Ze>ze,et=x.includes(K.key)&&tt,mt=M.includes(K.key)&&!x.includes(K.key)&&tt,jt=et||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[ze>0&&t.jsx("div",{className:`model-onboarding-step-connector ${ze<=Ze?"done":""}`}),jt?t.jsxs("button",{className:`model-onboarding-step-indicator ${b===K.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,onClick:()=>v(K.key),"aria-label":`Go back to ${K.label}`,title:`Review ${K.label}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(tn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ze+1}),t.jsx("span",{className:"step-label",children:K.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${b===K.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(tn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):ze+1}),t.jsx("span",{className:"step-label",children:K.label})]})]},K.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Pe,children:[b==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),!B&&I.length>0&&(()=>{const K=I.filter(jt=>jt.id!=="github"&&jt.authenticated).length,ze=I.filter(jt=>jt.id!=="github").length,tt=Object.keys(ee).filter(jt=>!I.find(_t=>_t.id===jt)?.authenticated).length;if(ze===0)return null;let et="onboarding-provider-summary",mt="";return K>0?(et+=" onboarding-provider-summary--connected",mt=`✓ ${K} of ${ze} provider${ze!==1?"s":""} connected`):tt>0?(et+=" onboarding-provider-summary--skipped",mt=`${tt} provider${tt!==1?"s":""} skipped`):(et+=" onboarding-provider-summary--none",mt="No providers connected yet"),t.jsx("div",{className:et,"data-testid":"provider-summary",children:mt})})(),t.jsx(zs,{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."})}),I.length>0&&!I.some(K=>K.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),B?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(it,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):I.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"}),_n.length>0?t.jsx("div",{className:"model-onboarding-providers",children:_n.map(K=>On(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),hs.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:hs.map(K=>On(K))})]}),t.jsx(zs,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsx("div",{"data-testid":"onboarding-advanced-provider-settings",children:ps.length>0?t.jsx("div",{className:"model-onboarding-providers",children:ps.map(K=>On(K))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."})})}),ms&&t.jsx(zs,{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."})}),pn&&t.jsx(zs,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})})]}),t.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(zs,{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."})}),pe.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(wn,{models:pe,value:re,onChange:Me,placeholder:"Select a default model…",label:"Default model"})}),re&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",pe.find(K=>K.id===re)?.name??re]})})]})]}),b==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[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."}),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"})]})}),Gn&&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(zs,{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."})}),Ce?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"onboarding-provider-row",children:[t.jsxs("div",{className:"onboarding-provider-info",children:[t.jsxs("strong",{children:[t.jsx(es,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Fe,{status:Rt})})]}),$e&&(z==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>ut("github"),children:"Disconnect"}))]}),(Rt==="not-connected"||Rt==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[z==="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:()=>Ct("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>Lt("github"),children:[t.jsx(es,{size:16}),"Connect"]}),z==="github"&&E.github&&t.jsx(_m,{instructions:E.github,"data-testid":"onboarding-login-instructions-github"})]}),Rt==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:je?"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."}),Rt==="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:()=>Lt("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:qt,children:"Skip for now"})]})]}),Rt==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),Rt==="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:()=>Lt("github"),children:"Connect anyway"})})]}),Rt==="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(es,{size:48,className:"optional-icon"}),je?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth integration in Settings → Authentication 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.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>v("project-setup"),children:"Continue without GitHub →"})]})]}),b==="project-setup"&&t.jsxs("div",{className:"model-onboarding-project-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Choose your first project before creating or importing tasks. You can register an existing local directory or clone a GitHub repository URL through the setup wizard."}),fn?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(zs,{summary:"What does project setup do?",children:t.jsx("p",{className:"onboarding-helper-text",children:"Project setup registers a workspace so Fusion knows where to read files, run commands, and track task changes."})})]}),b==="first-task"&&t.jsxs("div",{className:"model-onboarding-first-task",children:[t.jsx("p",{className:"model-onboarding-description",children:"Create your first task to start the board and launch AI execution."}),R&&yn?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(tn,{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:yn.id}),Kn&&t.jsx("p",{className:"onboarding-task-created__description",children:Kn}),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:Ot,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:sn,children:"Go to Dashboard"})]})]}):t.jsxs(t.Fragment,{children:[fn?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:C,onChange:K=>{S(K.target.value),L(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:N,disabled:P,"data-testid":"onboarding-first-task-submit",children:P?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),_&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:_}),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(rT,{items:Mt}),fn&&t.jsxs(t.Fragment,{children:[t.jsx(zs,{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:H,disabled:ce,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(Vt,{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${Ge?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Ae,disabled:ce||!Ge,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(es,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Import from GitHub"}),t.jsx("span",{children:"Turn GitHub issues into tasks you can track here"}),!Ge&&t.jsx("small",{className:"onboarding-cta-note",children:"Requires GitHub connection"})]})]})]}),t.jsxs("p",{className:"onboarding-skip-note",children:["You can create tasks anytime from the board, or use"," ",t.jsx("code",{children:"fn task create"})," in the terminal."]})]})]})]}),b==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(tn,{size:48,className:"success-icon"}),t.jsx("p",{children:"Setup complete! Head to the board to create your first task, or explore the dashboard to see what's available."})]})]}),t.jsxs("div",{className:"model-onboarding-footer",children:[b==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:ot,disabled:ce,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Dt,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,children:"Next →"})]}),b==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Dt,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,children:"Next →"})]}),b==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:$t,disabled:!fn,children:"Next →"})]}),b==="first-task"&&!R&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Bt,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:rt,disabled:ce,children:ce?t.jsxs(t.Fragment,{children:[t.jsx(it,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),b==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:kt,children:[t.jsx(tn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function hf({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 dT=a.lazy(()=>Zt(()=>import("./SetupWizardModal-D1bmCQrf.js"),__vite__mapDeps([6,1,7,8,9,0,2,10])).then(e=>({default:e.SetupWizardModal}))),uT=a.lazy(()=>Zt(()=>import("./SettingsModal-Bs_lNs5B.js"),__vite__mapDeps([11,1,12,13,14,0,2,15])).then(e=>({default:e.SettingsModal})));function mT(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{Zt(()=>import("./SettingsModal-Bs_lNs5B.js"),__vite__mapDeps([11,1,12,13,14,0,2,15]))},{timeout:1500})}function hT({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[b,v]=a.useState(null),x=p??c.closeSettings,k=a.useCallback(()=>{c.openNewTask()},[c]),M=a.useCallback(()=>{c.openGitHubImport()},[c]),y=a.useCallback(j=>{v(null),c.closeModelOnboarding(),c.openDetailTask(j)},[c]),R=a.useCallback(async j=>{const C=await d.handleModalCreate(j);return c.modelOnboardingOpen&&v(C),C},[d.handleModalCreate,c.modelOnboardingOpen]);return a.useEffect(()=>{!c.modelOnboardingOpen&&b&&v(null)},[c.modelOnboardingOpen,b]),a.useEffect(()=>{mT()},[]),t.jsxs(t.Fragment,{children:[c.detailTask&&t.jsx(fi,{children:t.jsx(CM,{task:c.detailTask,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(fi,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(uT,{onClose:x,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:g.themeMode,colorTheme:g.colorTheme,onThemeModeChange:g.setThemeMode,onColorThemeChange:g.setColorTheme,onReopenOnboarding:f})})}),t.jsx(MM,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:d.handleGitHubImport,tasks:n,projectId:e}),t.jsx(fi,{children:t.jsx(RM,{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(fi,{children:t.jsx(zM,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:d.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(ZM,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(t_,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(j_,{initialWorkspace:c.fileBrowserWorkspace,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),t.jsx(T_,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e}),c.schedulesOpen&&t.jsx(Q_,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(fi,{children:t.jsx(tA,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:R,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(rA,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:i,onOpenTaskDetail:j=>{const C=n.find(S=>S.id===j);C&&c.openDetailTask(C)}}),t.jsx(fi,{children:t.jsx(lA,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(fi,{children:t.jsx(yA,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(AA,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(a.Suspense,{fallback:null,children:t.jsx(dT,{onProjectRegistered:u.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(cT,{onComplete:u.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:u.handleAddProject,onOpenNewTask:k,onOpenGitHubImport:M,firstCreatedTask:b,onViewTask:y}),t.jsx(hf,{toasts:o,onRemove:l})]})}function pT({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 ic=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function fT(e,n){if(n==="ready")return"done";const s=ic.findIndex(r=>r.id===n),i=ic.findIndex(r=>r.id===e);return i<s?"done":i===s?"active":"pending"}function gT({stage:e}){return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":"Loading Fusion dashboard","data-stage":e,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:ic.map(n=>{const s=fT(n.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${s}`,"data-testid":`dashboard-loader-step-${n.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:s==="done"?"✓":s==="active"?t.jsx(it,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:n.label})]},n.id)})})]})})}const bT=5e3;function xT(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function vT(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++,Hr(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 yT(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 Ey(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()},bT),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[g]);const p=vT(e,s,i),f=xT(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:f,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:u,refresh:g}}const kT={planning:Us,subtask:Si,mission_interview:ns,milestone_interview:ns,slice_interview:ns},jT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function wT({sessions:e,generating:n,needsInput:s,onOpenSession:i,onDismissSession:r}){const[o,l]=a.useState(!1),[c,u]=a.useState(new Set),d=a.useRef(null),m=a.useRef(new Map),h=a.useRef(null),{activeTabMap:g}=la(),p=a.useMemo(()=>_i(),[]);if(a.useEffect(()=>{if(!o)return;const v=x=>{d.current&&!d.current.contains(x.target)&&l(!1)};return document.addEventListener("mousedown",v),()=>document.removeEventListener("mousedown",v)},[o]),a.useEffect(()=>{const v=new Set,x=new Map;for(const k of e){const M=g.get(k.id),y=[k.status,k.updatedAt,M?.tabId??k.lockedByTab??"",M?.stale?"stale":"fresh"].join("|"),R=m.current.get(k.id);R&&R!==y&&v.add(k.id),x.set(k.id,y)}if(m.current=x,v.size!==0)return u(v),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>{u(new Set),h.current=null},500),()=>{h.current&&(clearTimeout(h.current),h.current=null)}},[g,e]),e.length===0)return null;const f=e.length,b=s>0;return t.jsxs("div",{ref:d,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${b?" background-tasks-indicator__pill--attention":""}`,onClick:()=>l(v=>!v),title:`${f} background AI task${f!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(it,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(Gc,{size:12}),t.jsxs("span",{children:["AI ",f]})]}),o&&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(v=>{const x=kT[v.type],k=v.status==="generating",M=v.status==="awaiting_input",y=v.status==="error",R=g.get(v.id),j=R?.tabId??v.lockedByTab??null,C=!!(j&&j!==p&&!R?.stale),S=c.has(v.id);return t.jsxs("div",{className:`background-tasks-indicator__item${S?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:S?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:S?"translateY(-1px)":void 0},onClick:()=>{C&&!window.confirm("This session is active in another tab. Open anyway?")||(i(v),l(!1))},children:[y?t.jsx(ss,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(x,{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:v.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[y?"Failed":jT[v.type],k&&" — generating...",M&&!C&&" — needs input",M&&C&&" — active in another tab"]})]}),k&&t.jsx(it,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),M&&!C&&t.jsx(Gc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),M&&C&&t.jsx(so,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:P=>{P.stopPropagation(),r(v.id)},title:"Dismiss",children:t.jsx(Pt,{size:12})})]},v.id)})})]})]})}function NT(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 ST(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:rn};case"paused":return{label:"Paused",color:"var(--triage)",icon:Fs};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:vn}}}function CT({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}=yT(e,n,s,u),[f,b]=a.useState(!1),v=a.useMemo(()=>ST(h.executorState),[h.executorState]),x=a.useMemo(()=>NT(h.lastActivityAt),[h.lastActivityAt]),k=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(lc,{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(wT,{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:()=>b(M=>!M),"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(jn,{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(ji,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:x})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(k,{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 ET={planning:Us,subtask:Si,mission_interview:ns,milestone_interview:ns,slice_interview:ns},MT={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},xi=new Set;function _T({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:i}){const[r,o]=a.useState(0),l=()=>o(f=>f+1);a.useEffect(()=>{if(xi.size===0)return;const f=new Map(e.map(v=>[v.id,v]));let b=!1;for(const v of xi){const x=f.get(v);x&&x.status!=="awaiting_input"&&x.status!=="error"&&(xi.delete(v),b=!0)}b&&l()},[e]);const c=a.useMemo(()=>e.filter(f=>(f.status==="awaiting_input"||f.status==="error")&&!xi.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=>{xi.add(f),l()},g=f=>{xi.delete(f.id),l(),n(f)},p=()=>{for(const f of c)xi.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(ss,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(Pt,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(f=>{const b=ET[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(ss,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(b,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:f.title,children:f.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":MT[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(Pt,{size:14,"aria-hidden":"true"})})]})]},f.id)})})]})}function AT({onResume:e}){const n=OA();if(!n)return null;const s=n.completedSteps.length,i=oi.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(Dn,{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:()=>{js("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(rn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function TT({onOpenSettings:e,onOpenModelOnboarding:n}){const s=sa(),i=cf(),[r,o]=a.useState(!0),[l,c]=a.useState(!1),[u,d]=a.useState(!1),[m,h]=a.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});a.useEffect(()=>{if(!s||i){o(!1);return}let x=!1;return(async()=>{try{o(!0),c(!1);const[M,y]=await Promise.all([Ba(),ra()]);if(x)return;const R=M.providers??[],j=R.find(_=>_.id==="github"),S=!R.some(_=>_.id!=="github"&&_.authenticated),P=!y.defaultProvider&&!y.defaultModelId,T=j?!j.authenticated:!1;h({needsAiProvider:S,needsDefaultModel:P,needsGitHub:T})}catch{x||c(!0)}finally{x||o(!1)}})(),()=>{x=!0}},[s,i]);const g=a.useCallback(()=>{zA(),d(!0)},[]),p=a.useCallback(()=>{n()},[n]),f=a.useCallback(()=>{e("global-models")},[e]),b=a.useCallback(()=>{e("authentication")},[e]),v=a.useMemo(()=>{const x=[];return m.needsAiProvider&&x.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:vn}),m.needsDefaultModel&&x.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:f,icon:ah}),m.needsGitHub&&x.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:b,icon:es}),x},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,b,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(Us,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(x=>{const k=x.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsxs("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:[t.jsx(ss,{size:14,"aria-hidden":!0}),t.jsx(k,{size:14,"aria-hidden":!0})]}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:x.title}),t.jsx("span",{children:x.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:x.onAction,children:x.actionLabel})]},x.id)})})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:g,"aria-label":"Dismiss recommendations",children:t.jsx(Pt,{size:16,"aria-hidden":!0})})]})}function RT({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 Nl(e){return e>99?"99+":String(e)}function IT({view:e,onChangeView:n,footerVisible:s,modalOpen:i=!1,onOpenSettings:r,onOpenActivityLog:o,onOpenMailbox:l,mailboxUnreadCount:c=0,onOpenGitManager:u,onOpenWorkflowSteps:d,onOpenSchedules:m,onOpenScripts:h,onToggleTerminal:g,onOpenFiles:p,onOpenGitHubImport:f,onOpenPlanning:b,onResumePlanning:v,activePlanningSessionCount:x=0,onOpenUsage:k,onRunScript:M,projectId:y,onViewAllProjects:R,showSkillsTab:j,experimentalFeatures:C}){const S=tr(),[P,T]=a.useState(!1),[_,L]=a.useState(!1),[G,$]=a.useState({}),[I,w]=a.useState(!1),q=a.useMemo(()=>Object.entries(G).sort(([re],[F])=>re.localeCompare(F)),[G]);a.useEffect(()=>{if(!_)return;let re=!1;return w(!0),Xa(y).then(F=>{re||$(F)}).catch(()=>{re||$({})}).finally(()=>{re||w(!1)}),()=>{re=!0}},[_,y]);const W=a.useCallback(()=>T(!1),[]),B=a.useCallback(re=>{W(),re?.()},[W]);if(a.useEffect(()=>{if(!P)return;const re=F=>{F.key==="Escape"&&T(!1)};return document.addEventListener("keydown",re),()=>document.removeEventListener("keydown",re)},[P]),S!=="mobile"||i)return null;const A=x>0&&v?v:b,z=!!C?.roadmap,X=!!j,E=z&&(!X||e==="roadmaps"),U=X&&(!z||e!=="roadmaps"),pe=X&&!U,ie=e==="documents"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||e==="roadmaps"&&!E||e==="skills"&&!U;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(Ci,{}),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(an,{}),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(ns,{}),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(li,{}),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(Gi,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:Nl(c)})]}),U&&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(vn,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),E&&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(Rl,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Roadmaps"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ie?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>T(re=>!re),children:[t.jsx(_l,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),P&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:W}),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:()=>B(l),children:[t.jsx(Gi,{}),t.jsx("span",{children:"Mailbox"}),c>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:Nl(c)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>B(o),children:[t.jsx(Ss,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>B(u),children:[t.jsx(Os,{}),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:()=>B(g),children:[t.jsx(Bs,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>L(re=>!re),"aria-expanded":_,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(en,{size:14,className:`mobile-more-chevron${_?" mobile-more-chevron--open":""}`})})]}),_&&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(it,{size:14,className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):q.length>0?t.jsxs(t.Fragment,{children:[q.map(([re,F])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${re}`,onClick:()=>{M&&M(re,F),W(),L(!1)},children:[t.jsx(rn,{size:14}),t.jsx("span",{children:re})]},re)),h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{W(),L(!1),h()},children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"Manage Scripts…"})]})]}):h&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{W(),L(!1),h()},children:[t.jsx(Ts,{size:14}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>B(p),children:[t.jsx(jn,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>B(A),children:[t.jsx(Us,{}),t.jsx("span",{children:"Planning"}),x>0&&t.jsx("span",{className:"mobile-more-item-badge",children:Nl(x)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>B(d),children:[t.jsx(Pl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>B(m),children:[t.jsx(ji,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>B(f),children:[t.jsx(RT,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>B(k),children:[t.jsx(Ss,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>B(R),children:[t.jsx(ih,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>B(()=>n("documents")),children:[t.jsx(Ni,{}),t.jsx("span",{children:"Documents"})]}),pe&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>B(()=>n("skills")),children:[t.jsx(vn,{}),t.jsx("span",{children:"Skills"})]}),z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-roadmaps",onClick:()=>B(()=>n("roadmaps")),children:[t.jsx(Rl,{}),t.jsx("span",{children:"Roadmaps"})]}),C?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>B(()=>n("insights")),children:[t.jsx(Dn,{}),t.jsx("span",{children:"Insights"})]}),C?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>B(()=>n("memory")),children:[t.jsx(Pr,{}),t.jsx("span",{children:"Memory"})]}),C?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{B(()=>n("dev-server"))},children:[t.jsx(rh,{size:14}),t.jsx("span",{children:"Dev Server"})]}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>B(r),children:[t.jsx(Oa,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function PT({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(an,{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 Lc="__fn_agent__";function pf(e,n){const s=typeof e=="string"?e.trim():"",i=typeof n=="string"?n.trim():"";return!s||!i?{}:{modelProvider:s,modelId:i}}function Dm(e,n,s){const i=typeof e=="string"?e.trim():"",r=pf(n,s),o=i||(r.modelProvider&&r.modelId?Lc:"");return o?{agentId:o,...r}:null}function Sl(e,n,s){const i=pf(n,s),r=i.modelProvider??"",o=i.modelId??"";return`${e}::${r}/${o}`}function $T(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 Lm(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:$T(e.metadata),createdAt:e.createdAt}}function DT(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,b]=a.useState(""),[v,x]=a.useState([]),[k,M]=a.useState(""),y=a.useRef(null),R=a.useRef(!1),j=a.useRef(""),C=a.useRef(""),S=a.useRef(null);a.useEffect(()=>{j.current=k},[k]);const P=a.useCallback(async B=>{const A={agentId:B.agentId};return B.modelProvider&&B.modelId&&(A.modelProvider=B.modelProvider,A.modelId=B.modelId),(await Ok(A,e)).session},[e]),T=a.useCallback(async(B,A,z)=>{const X=Dm(B,A,z);if(!X)return;const E=Sl(X.agentId,X.modelProvider,X.modelId);o(!0);try{const{session:U}=await Fk({agentId:X.agentId,modelProvider:X.modelProvider,modelId:X.modelId},e);if(U)i(U),C.current=E;else{const pe=await P(X);i(pe),C.current=E}}catch(U){console.error("[useQuickChat] Failed to initialize session:",U),n?.("Failed to initialize chat","error")}finally{o(!1)}},[e,n,P]),_=a.useCallback(async()=>{if(s){d(!0);try{const B=await yd(s.id,{limit:50},e);c(B.messages.map(Lm))}catch(B){console.error("[useQuickChat] Failed to load messages:",B)}finally{d(!1)}}},[s,e]);a.useEffect(()=>{s?_():c([])},[s,_]);const L=a.useCallback(async()=>{if(s){d(!0);try{const B=await yd(s.id,{limit:50},e);c(B.messages.map(Lm))}catch(B){console.error("[useQuickChat] Failed to reload messages:",B)}finally{d(!1)}}},[s,e]),G=a.useCallback(async(B,A,z)=>{const X=Dm(B,A,z);if(!X)return;const E=Sl(X.agentId,X.modelProvider,X.modelId);if(S.current=X,y.current&&(y.current.close(),y.current=null),p(""),b(""),x([]),h(!1),E===C.current&&s){await L();return}c([]),C.current=E,await T(X.agentId,X.modelProvider,X.modelId)},[T,L,s]),$=a.useCallback(async(B,A)=>{await G(Lc,B,A)},[G]),I=a.useCallback(async()=>{const B=S.current;if(!B)return;const A=Sl(B.agentId,B.modelProvider,B.modelId);y.current&&(y.current.close(),y.current=null),p(""),b(""),x([]),h(!1),c([]),o(!0);try{const z=await P(B);i(z),C.current=A}catch(z){console.error("[useQuickChat] Failed to start a fresh session:",z),n?.("Failed to start a new chat","error")}finally{o(!1)}},[n,P]),w=a.useCallback(()=>{s&&(R.current=!0,y.current?.close(),y.current=null,Uk(s.id,e).catch(()=>{}),h(!1),p(""),b(""),x([]))},[s,e]),q=a.useCallback(()=>{j.current="",M("")},[]),W=a.useCallback(B=>{if(!s||!B.trim())return;if(m){j.current=B,M(B);return}R.current=!1,y.current&&(y.current.close(),y.current=null);const z={id:`temp-${Date.now()}`,sessionId:s.id,role:"user",content:B,createdAt:new Date().toISOString()};c(ie=>[...ie,z]),p(""),b(""),x([]),h(!0);let X="",E="",U=[];const pe={onThinking:ie=>{E+=ie,b(E)},onText:ie=>{X+=ie,p(X)},onToolStart:ie=>{U=[...U,{toolName:ie.toolName,args:ie.args,isError:!1,status:"running"}],x(U)},onToolEnd:ie=>{const re=[...U];for(let F=re.length-1;F>=0;F--){const ce=re[F];if(ce?.toolName===ie.toolName&&ce.status==="running"){re[F]={...ce,status:"completed",isError:ie.isError,result:ie.result},U=re,x(re);return}}U=[...re,{toolName:ie.toolName,isError:ie.isError,result:ie.result,status:"completed"}],x(U)},onDone:ie=>{const re={id:ie.messageId||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:X,thinkingOutput:E||void 0,toolCalls:U.length>0?U:void 0,createdAt:new Date().toISOString()};c(ce=>[...ce,re]),p(""),b(""),x([]),h(!1),y.current=null;const F=j.current.trim();F&&(j.current="",M(""),W(F))},onError:ie=>{if(p(""),b(""),x([]),h(!1),y.current=null,console.error("[useQuickChat] Stream error:",ie),n?.("Failed to get response","error"),!R.current){const re=j.current.trim();re&&(j.current="",M(""),W(re))}L()}};y.current=Bk(s.id,B,pe,e)},[s,m,e,n,L]);return a.useEffect(()=>()=>{y.current&&(y.current.close(),y.current=null)},[]),a.useMemo(()=>({activeSession:s,sessionsLoading:r,messages:l,messagesLoading:u,isStreaming:m,streamingText:g,streamingThinking:f,streamingToolCalls:v,pendingMessage:k,sendMessage:W,stopStreaming:w,clearPendingMessage:q,switchSession:G,startModelChat:$,startFreshSession:I,loadMessages:_,reloadMessages:L}),[s,r,l,u,m,g,f,v,k,W,w,q,G,$,I,_,L])}function LT(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,b=n?.showSystemAgents??!1,v=await oa({...f,...g,includeEphemeral:g?.includeEphemeral??b},e),x=Array.from(new Map(v.map(k=>[k.id,k])).values());i(x)}catch(p){console.error("Failed to load agents:",p)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),d=a.useCallback(async()=>{try{const g=await ky(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 qs(`/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||!nj(g));return{agents:s,activeAgents:h,stats:r,isLoading:l,loadAgents:u,loadStats:d}}function zT({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(nh,{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 FT=200;function OT(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),b=a.useRef(null),v=a.useRef(null);a.useEffect(()=>()=>{b.current&&clearTimeout(b.current),v.current?.abort()},[]);const x=a.useCallback((j,C)=>{if(C<0||C>j.length){r(!1);return}const S=P=>/[a-zA-Z0-9/_.-]/.test(P);for(let P=C-1;P>=0;P--){if(j[P]==="#")if(P===0){const T=j.slice(P+1,C);u(P),l(T),f(0),r(!0);return}else{const T=j[P-1];if(/[\s,.;:!?'"()[\]{}]/.test(T)){const _=j.slice(P+1,C);u(P),l(_),f(0),r(!0);return}r(!1);return}if(!S(j[P])){r(!1);return}}r(!1)},[]),k=a.useCallback(()=>{r(!1),l(""),u(-1),m([]),f(0),g(!1)},[]),M=a.useCallback(async j=>{if(!j.trim()){m([]),g(!1);return}v.current?.abort(),v.current=new AbortController;try{g(!0);const C=await Av(j,s,n);m(C.files),f(0)}catch(C){C.name!=="AbortError"&&m([])}finally{g(!1)}},[s,n]);a.useEffect(()=>{if(i)return b.current&&clearTimeout(b.current),b.current=setTimeout(()=>{M(o)},FT),()=>{b.current&&clearTimeout(b.current)}},[o,i,M]);const y=a.useCallback((j,C)=>{if(!i||c<0)return C;const S=C.slice(0,c),P=C.slice(c+1),T=P.match(/[\s]|$/),_=T?T.index:P.length,L=P.slice(_);return`${S}#${j.path}${L}`},[i,c]),R=a.useCallback((j,C)=>{if(!i||d.length===0)return!1;switch(j.key){case"ArrowDown":return j.preventDefault(),f(S=>Math.min(S+1,d.length-1)),!0;case"ArrowUp":return j.preventDefault(),f(S=>Math.max(S-1,0)),!0;case"Enter":case"Tab":return d[p]?(j.preventDefault(),!0):!1;case"Escape":return j.preventDefault(),k(),!0;default:return!1}},[i,d,p,k]);return{mentionActive:i,files:d,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:f,detectMention:x,selectFile:y,dismissMention:k,handleKeyDown:R}}const UT={display:"inline-flex",alignItems:"center",maxWidth:"180px",padding:"var(--space-xs) var(--space-sm)",borderRadius:"var(--radius-pill)",border:"1px solid color-mix(in srgb, var(--todo) 35%, var(--border))",background:"color-mix(in srgb, var(--todo) 14%, transparent)",color:"var(--text)",fontSize:"11px",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},BT={display:"flex",alignItems:"center",gap:"var(--space-sm)",minWidth:0};function HT(e){return`${e.name?.trim()||e.id} (${e.role})`}function qT(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 VT(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 Ir(e,n){return e.length>n?`${e.slice(0,n)}…`:e}function WT(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}=${Ir(r,50)}`}).join(", ")}function GT(e){if(e===void 0)return null;if(typeof e=="string")return Ir(e,200);try{return Ir(JSON.stringify(e),200)}catch{return Ir(String(e),200)}}function zm(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(Jb,{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=WT(s.args),c=GT(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 KT={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 JT(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}}function YT(e,n){const s=a.useCallback(()=>{if(typeof window>"u")return 0;const b=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return b&&parseFloat(b)||0},[]),i=a.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=a.useState(()=>{if(typeof window>"u")return i();const b=`fusion-quick-chat-position-${e||"default"}`;try{const v=localStorage.getItem(b);if(v){const x=JSON.parse(v);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return i()}),[l,c]=a.useState(!1),u=a.useRef(null),d=n??a.useRef(!1),m=a.useCallback(b=>{if(typeof window>"u")return b;const v=48,x=window.innerWidth<=768?4:8,k=window.innerWidth<=768?44:0,M=window.innerWidth>768?s():0,y=window.innerWidth-v-x,R=window.innerHeight-v-x-k-M;return{x:Math.max(x,Math.min(y,b.x)),y:Math.max(x,Math.min(R,b.y))}},[s]),h=a.useCallback(b=>{if(typeof window>"u")return;const v=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(v,JSON.stringify(b))}catch{}},[e]),g=a.useCallback(b=>{if(b.button!==0&&b.pointerType==="mouse")return;const x=b.target.closest(".quick-chat-fab");x&&(b.preventDefault(),typeof x.setPointerCapture=="function"&&x.setPointerCapture(b.pointerId),u.current={x:r.x,y:r.y,pointerX:b.clientX,pointerY:b.clientY},d.current=!1,c(!0),document.body.style.userSelect="none")},[r]),p=a.useCallback(b=>{if(!u.current||!l)return;const v=b.clientX-u.current.pointerX,x=b.clientY-u.current.pointerY;if((Math.abs(v)>=5||Math.abs(x)>=5)&&(d.current=!0),d.current){const k=u.current.x-v,M=u.current.y-x,y=m({x:k,y:M});o(y)}},[l,m]),f=a.useCallback(b=>{if(!u.current)return;const v=b.target.closest(".quick-chat-fab");if(v&&typeof v.releasePointerCapture=="function"&&v.releasePointerCapture(b.pointerId),c(!1),document.body.style.userSelect="",!d.current){u.current=null;return}h(r),u.current=null,d.current=!1},[r,h]);return{position:r,isDragging:l,handlePointerDown:g,handlePointerMove:p,handlePointerUp:f}}function QT({projectId:e,addToast:n,showFAB:s=!0,open:i,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:u}){const{agents:d}=LT(e),[m,h]=a.useState(!1),g=i!==void 0,p=g?i:m,f=g?Me=>{r?.(typeof Me=="function"?Me(p):Me)}:h,[b,v]=a.useState("agent"),[x,k]=a.useState(""),[M,y]=a.useState([]),[R,j]=a.useState(!1),[C,S]=a.useState(""),[P,T]=a.useState(""),[_,L]=a.useState(""),[G,$]=a.useState(!1),[I,w]=a.useState(0),[q,W]=a.useState(-1),[B,A]=a.useState(()=>new Set),[,z]=a.useState(!1),[X,E]=a.useState({top:0,left:0}),U=OT({projectId:e}),pe=a.useCallback(Me=>{if(!Me||!U.mentionActive)return;const Qe=Me.getBoundingClientRect();E({top:Qe.top-260,left:Qe.left+8})},[U.mentionActive]),ie=a.useRef(!1),re=a.useRef(!1),F=a.useRef(""),ce=a.useRef(0),ae=a.useRef(null),{position:Q,isDragging:de,handlePointerDown:Te,handlePointerMove:fe,handlePointerUp:Se}=YT(e,ie),{activeSession:te,messages:we,isStreaming:Pe,streamingText:We,streamingThinking:Ke,streamingToolCalls:Ne,sessionsLoading:_e,messagesLoading:Oe,sendMessage:ye,stopStreaming:De,pendingMessage:se,clearPendingMessage:J,switchSession:me,startModelChat:ee,startFreshSession:he}=DT(e,n),le=a.useRef(null),Ie=a.useRef(null),Ze=a.useRef(null),at=a.useRef(null),oe=a.useMemo(()=>qT(C),[C]),Z=a.useMemo(()=>M.find(Me=>`${Me.provider}/${Me.id}`===C)??null,[M,C]),ue=a.useMemo(()=>VT(Z,oe),[Z,oe]),Ce=a.useMemo(()=>b==="model"?oe?`${Lc}::${oe.modelProvider}/${oe.modelId}`:"":x?`${x}::`:"",[b,oe,x]),$e=b==="agent"?!!x:!!oe;a.useEffect(()=>{if(d.length===0){k(""),v("model");return}d.some(Qe=>Qe.id===x)||k(d[0]?.id??"")},[d,x]),a.useEffect(()=>{!p||re.current||(re.current=!0,j(!0),is().then(Me=>{const Qe=Me.models??[];if(y(Qe),d.length===0&&Qe.length>0&&!C){const rt=Qe[0];rt&&S(`${rt.provider}/${rt.id}`)}}).catch(Me=>{console.error("[QuickChatFAB] Failed to load models:",Me),y([])}).finally(()=>{j(!1)}))},[p,d.length,C]),a.useEffect(()=>{if(!p){F.current="";return}if(!Ce){F.current="";return}if(Ce!==F.current){if(F.current=Ce,b==="model"&&oe){ee(oe.modelProvider,oe.modelId);return}b==="agent"&&x&&me(x)}},[p,b,oe,x,Ce,ee,me]),a.useEffect(()=>{p||($(!1),L(""),W(-1))},[p]);const ve=a.useCallback(Me=>{k(Me)},[]),Ge=a.useCallback(Me=>{S(Me)},[]),je=a.useCallback(()=>{!$e||_e||he()},[$e,_e,he]),Ue=a.useMemo(()=>d.find(Me=>Me.id===x)??null,[d,x]),He=a.useMemo(()=>{const Me=_.trim().toLowerCase();return Me?d.filter(Qe=>Qe.name.toLowerCase().includes(Me)):d},[d,_]),ge=a.useMemo(()=>{const Me=new Map;for(const Qe of d)Me.set(Qe.name.toLowerCase(),Qe);return Me},[d]);a.useEffect(()=>{w(0)},[_,G]),a.useEffect(()=>()=>{ae.current!==null&&(window.clearTimeout(ae.current),ae.current=null)},[]),a.useEffect(()=>{if(!p)return;const Me=rt=>{const N=rt.target;le.current?.contains(N)||Ie.current?.contains(N)||N.closest(".model-combobox-dropdown--portal")||f(!1)},Qe=rt=>{rt.key==="Escape"&&f(!1)};return document.addEventListener("mousedown",Me),document.addEventListener("keydown",Qe),()=>{document.removeEventListener("mousedown",Me),document.removeEventListener("keydown",Qe)}},[p,f]),a.useEffect(()=>{if(!p)return;const Me=Ze.current;Me&&(Me.scrollTop=Me.scrollHeight)},[we,We,Ke,p]);const Fe=a.useMemo(()=>b==="agent"?Ue?`Message ${Ue.name||Ue.id}`:"Select an agent to start chatting":ue?`Message ${ue}`:"Select a model to start chatting",[b,Ue,ue]),be=!$e||!te||_e,Je=se.length>50?`${se.slice(0,50)}…`:se,st=a.useCallback(()=>{const Me=P.trim();!Me||be||(T(""),$(!1),L(""),W(-1),ye(Me))},[ye,be,P]),dt=a.useCallback((Me,Qe)=>{const rt=JT(Me,Qe);if(rt){$(!0),L(rt.filter),W(rt.start);return}$(!1),L(""),W(-1)},[]),Tt=a.useCallback(Me=>{const Qe=at.current;if(!Qe||q<0)return;const rt=Qe.selectionStart??ce.current,N=Qe.selectionEnd??rt,H=Math.max(rt,N),Ae=Math.min(q,H),kt=`${`@${Me.name.replace(/\s+/g,"_")}`} `,Ot=P.slice(0,Ae)+kt+P.slice(H),sn=Ae+kt.length;T(Ot),$(!1),L(""),w(0),W(-1),window.requestAnimationFrame(()=>{at.current&&(at.current.focus(),at.current.setSelectionRange(sn,sn))})},[q,P]),$t=a.useCallback(Me=>{const Qe=Me.target.value,rt=Me.target.selectionStart??Qe.length;ce.current=rt,T(Qe),dt(Qe,rt),U.detectMention(Qe,rt),z(U.mentionActive),U.mentionActive&&pe(Me.target)},[dt,U,pe]),Dt=a.useCallback(()=>{ae.current!==null&&window.clearTimeout(ae.current),ae.current=window.setTimeout(()=>{$(!1),L(""),W(-1),z(!1),U.dismissMention(),ae.current=null},120)},[U]),Bt=a.useCallback(()=>{ae.current!==null&&(window.clearTimeout(ae.current),ae.current=null)},[]),qt=a.useCallback(Me=>{const Qe=Me.currentTarget,rt=Qe.selectionStart??Qe.value.length;ce.current=rt,dt(Qe.value,rt),U.detectMention(Qe.value,rt),z(U.mentionActive),U.mentionActive&&pe(Qe)},[dt,U,pe]),Lt=a.useCallback(Me=>{Me.key!=="Escape"&&qt(Me)},[qt]),Ct=a.useCallback(Me=>{const Qe=/@([\w-]+)/g,rt=[];let N=0,H=Qe.exec(Me);for(;H;){const[Ae,ot=""]=H,kt=H.index;kt>N&&rt.push(Me.slice(N,kt));const Ot=ot.replace(/_/g," ").toLowerCase(),sn=ge.get(Ot);sn?rt.push(t.jsxs("span",{className:"chat-mention-chip",children:["@",sn.name.replace(/\s+/g,"_")]},`${sn.id}-${kt}`)):rt.push(Ae),N=kt+Ae.length,H=Qe.exec(Me)}return N<Me.length&&rt.push(Me.slice(N)),rt.length===0?Me:rt},[ge]),xt=a.useCallback(Me=>{A(Qe=>{const rt=new Set(Qe);return rt.has(Me)?rt.delete(Me):rt.add(Me),rt})},[]),Et=a.useCallback((Me,Qe=!1)=>Qe?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:Me}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(Qs,{remarkPlugins:[Xs],components:KT,children:Me})}),[]),Le=a.useCallback(Me=>{if(ce.current=Me.currentTarget.selectionStart??ce.current,U.mentionActive&&U.files.length>0){if(U.handleKeyDown(Me,P),Me.key==="Enter"||Me.key==="Tab"){const Qe=U.files[U.selectedIndex];if(Qe){const rt=U.selectFile(Qe,P);T(rt),U.dismissMention(),z(!1)}}return}if(G&&Me.key==="ArrowDown"){Me.preventDefault(),He.length>0&&w(Qe=>(Qe+1)%He.length);return}if(G&&Me.key==="ArrowUp"){Me.preventDefault(),He.length>0&&w(Qe=>Qe===0?He.length-1:Qe-1);return}if(G&&Me.key==="Enter"){Me.preventDefault();const Qe=He[I]??He[0];Qe&&Tt(Qe);return}if(G&&Me.key==="Escape"){Me.preventDefault(),Me.stopPropagation(),$(!1),L(""),W(-1);return}Me.key!=="Enter"||Me.shiftKey||(Me.preventDefault(),st())},[G,He,I,Tt,st,U,P]),gt=a.useCallback(()=>{if(ie.current){ie.current=!1;return}f(Me=>!Me)},[f]),ut=Q.y+60;return t.jsxs(t.Fragment,{children:[s&&t.jsx("button",{ref:Ie,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":de?"true":"false",style:{right:Q.x,bottom:Q.y},onPointerDown:Te,onPointerMove:fe,onPointerUp:Se,onClick:gt,children:t.jsx(li,{size:24})}),p&&t.jsxs("div",{className:"quick-chat-panel",ref:le,"data-testid":"quick-chat-panel",style:{right:Q.x,bottom:ut},children:[t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{style:BT,children:[t.jsx("h3",{children:"Quick Chat"}),ue&&t.jsx("span",{style:UT,"data-testid":"quick-chat-model-tag",title:ue,children:ue})]}),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:je,disabled:!$e||_e,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(Pt,{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${b==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-agent",onClick:()=>{v("agent"),S("")},children:"Agent"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${b==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-mode-model",onClick:()=>{v("model"),k("")},children:"Model"})]}),b==="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:x,onChange:Me=>ve(Me.target.value),"data-testid":"quick-chat-agent-select",children:d.map(Me=>t.jsx("option",{value:Me.id,children:HT(Me)},Me.id))})]}),b==="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(wn,{id:"quick-chat-model-override",models:M,value:C,onChange:Ge,label:"Select model override",placeholder:R?"Loading models…":"Select a model",disabled:R||M.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:u})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:Ze,"data-testid":"quick-chat-messages",children:_e||Oe?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):we.length===0&&!We&&!Ke&&!Pe?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[we.map(Me=>{const Qe=Me.role==="user",rt=!Qe&&B.has(Me.id);return t.jsxs("div",{className:`quick-chat-panel-message ${Qe?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${Me.id}`,children:[Qe?t.jsx("p",{children:Ct(Me.content)}):t.jsxs(t.Fragment,{children:[Et(Me.content,rt),t.jsx("button",{type:"button",className:`btn btn-icon quick-chat-message-render-toggle${rt?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":rt?"Show rendered markdown":"Show plain text",onClick:()=>xt(Me.id),children:rt?t.jsx($r,{size:12}):t.jsx(Vi,{size:12})})]}),zm(Me.toolCalls,!0)]},Me.id)}),Pe&&t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[We?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Et(We,B.has("__streaming__"))}),t.jsx("button",{type:"button",className:`btn btn-icon quick-chat-message-render-toggle${B.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":B.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>xt("__streaming__"),children:B.has("__streaming__")?t.jsx($r,{size:12}):t.jsx(Vi,{size:12})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:Ke?"Thinking…":"Connecting…"}),zm(Ne,!0),Ke&&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:Ke})]})]})]})}),t.jsxs("div",{className:"quick-chat-panel-input",children:[t.jsxs("div",{className:"quick-chat-input-wrapper",children:[t.jsx("input",{ref:at,type:"text",value:P,onChange:$t,onKeyDown:Le,onKeyUp:Lt,onClick:qt,onBlur:Dt,onFocus:Bt,placeholder:Fe,disabled:be,"data-testid":"quick-chat-input"}),t.jsx(PT,{agents:d,filter:_,highlightedIndex:I,visible:G,onSelect:Tt,position:"above"}),t.jsx(zT,{visible:U.mentionActive&&!G,position:X,files:U.files,selectedIndex:U.selectedIndex,onSelect:Me=>{const Qe=U.selectFile(Me,P);T(Qe),U.dismissMention(),z(!1),at.current?.focus()},loading:U.loading}),se&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Je}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:J,children:"×"})]})]}),Pe?t.jsx("button",{type:"button",className:"chat-input-stop",onClick:De,"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx(ls,{size:14})}):t.jsx("button",{type:"button",onClick:()=>void st(),disabled:be||P.trim().length===0,"data-testid":"quick-chat-send",children:t.jsx(vi,{size:16})})]})]})]})}function _a(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Fm(e){return e.status==="generating"||e.status==="awaiting_input"}function Aa(e){return e==="complete"||e==="error"}function XT(e){const[n,s]=a.useState([]),i=a.useRef(new Map),r=a.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:u}=la(),d=a.useCallback(()=>{Sh(e).then(p=>{const f=p.filter(v=>{const x=_a(v.updatedAt),k=r.current.get(v.id);return k===void 0?!0:x<=k?!1:(r.current.delete(v.id),!0)}),b=new Map;for(const v of f)b.set(v.id,_a(v.updatedAt));i.current=b,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 b=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const x=v.lastEventTimestamp,k=i.current.get(v.sessionId)??0;if(x<k)continue;const M=r.current.get(v.sessionId);if(M!==void 0&&x<=M)continue;if(M!==void 0&&x>M&&!Aa(v.status)&&r.current.delete(v.sessionId),Aa(v.status)){b.delete(v.sessionId)&&(f=!0),i.current.set(v.sessionId,x);continue}const y=b.get(v.sessionId),R=v.type??y?.type,j=v.title??y?.title;if(!y&&(!R||!j))continue;const C={id:v.sessionId,type:R??"planning",status:v.status,title:j??"AI Session",projectId:v.projectId??y?.projectId??e??null,lockedByTab:v.owningTabId??y?.lockedByTab??null,updatedAt:v.updatedAt??y?.updatedAt??new Date(x).toISOString()},S=b.get(v.sessionId);(!S||S.status!==C.status||S.title!==C.title||S.type!==C.type||S.projectId!==C.projectId||S.lockedByTab!==C.lockedByTab||S.updatedAt!==C.updatedAt)&&(b.set(v.sessionId,C),i.current.set(v.sessionId,x),f=!0)}return f?[...b.values()].sort((v,x)=>_a(x.updatedAt)-_a(v.updatedAt)):p})},[e,o]),a.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",f=v=>{try{const x=JSON.parse(v.data),k=_a(x.updatedAt)||Date.now();s(M=>{const y=i.current.get(x.id)??0;if(k<y)return M;const R=r.current.get(x.id);if(R!==void 0&&k<=R)return M;if(R!==void 0&&k>R&&!Aa(x.status)&&r.current.delete(x.id),i.current.set(x.id,k),Aa(x.status))return M.filter(C=>C.id!==x.id);const j=M.findIndex(C=>C.id===x.id);if(j>=0){const C=[...M];return C[j]=x,C}return Fm(x)?[x,...M]:M}),l({sessionId:x.id,status:x.status,needsInput:x.status==="awaiting_input",type:x.type,title:x.title,projectId:x.projectId,owningTabId:x.lockedByTab,updatedAt:x.updatedAt,timestamp:k}),Aa(x.status)&&c({sessionId:x.id,status:x.status,timestamp:k})}catch{}},b=v=>{try{const x=JSON.parse(v.data);s(k=>k.filter(M=>M.id!==x)),i.current.delete(x),r.current.delete(x)}catch{}};return qs(`/api/events${p}`,{events:{"ai_session:updated":f,"ai_session:deleted":b}})},[c,l,e]);const m=a.useCallback(async p=>{const b=n.find(y=>y.id===p)?.type,v=_i();let x=!1,k=!1;if(b==="planning")try{await gh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss planning session ${p}: locked by another tab`))}else if(b==="subtask")try{await vh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss subtask session ${p}: locked by another tab`))}else if(b==="mission_interview")try{await Nh(p,e,v)}catch(y){x=!0,y instanceof Error&&y.message.includes("locked")&&(k=!0,console.warn(`[useBackgroundSessions] Cannot dismiss mission interview session ${p}: locked by another tab`))}if(k)return;x&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const M=Date.now();r.current.set(p,M),i.current.set(p,Math.max(i.current.get(p)??0,M)),c({sessionId:p,status:"complete",timestamp:M});try{await Mk(p)}catch{}s(y=>y.filter(R=>R.id!==p))},[c,e,n]),h=a.useMemo(()=>n.filter(p=>Fm(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 In(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 Om(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function ZT(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),b=a.useRef(0),v=a.useRef(n);d.current=r,g.current=s,v.current!==n&&(v.current=n,b.current++);const x=1e3,k=a.useCallback(async I=>{const w=++m.current,q=n,W=I?.searchQueryOverride??s,B=I?.includeArchivedOverride??u.current;try{const A=await vx(void 0,void 0,q,W,B);if(m.current!==w||n!==q)return;o(A.map(In)),f.current=Date.now()}catch{if(m.current!==w||n!==q)return;if(I?.clearOnError){o([]);return}o(A=>A)}},[n,s]);p.current=k;const M=a.useCallback(async()=>{u.current||(c(!0),u.current=!0,await p.current({includeArchivedOverride:!0}))},[]);a.useEffect(()=>{if(s===void 0)return;const I=setTimeout(()=>{k({searchQueryOverride:s})},300);return()=>clearTimeout(I)},[s]),a.useEffect(()=>{k({clearOnError:!0});const I=()=>{if(document.visibilityState!=="visible")return;const w=Date.now();w-h.current<x||(h.current=w,k())};return document.addEventListener("visibilitychange",I),()=>{document.removeEventListener("visibilitychange",I)}},[k]),a.useEffect(()=>{if(i===!1)return;const I=b.current,w=n?`?projectId=${encodeURIComponent(n)}`:"",q=()=>b.current!==I;let W=!0;const B=pe=>{if(q())return;const ie=In(JSON.parse(pe.data));if(g.current){p.current({searchQueryOverride:g.current});return}o(re=>re.some(F=>F.id===ie.id)?re:[...re,ie])},A=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ie,to:re}=JSON.parse(pe.data),F=In(ie);o(ce=>ce.map(ae=>ae.id===F.id?{...F,column:re}:ae)),f.current=Date.now()},z=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ie=In(JSON.parse(pe.data));o(re=>re.map(F=>{if(F.id!==ie.id||Om(ie.updatedAt,F.updatedAt)<0)return F;if(F.column===ie.column)return ie;const ae=Om(F.columnMovedAt,ie.columnMovedAt);return F.columnMovedAt&&!ie.columnMovedAt?{...ie,column:F.column,columnMovedAt:F.columnMovedAt}:ae>0?{...ie,column:F.column,columnMovedAt:F.columnMovedAt}:ie})),f.current=Date.now()},X=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const ie=In(JSON.parse(pe.data));o(re=>re.filter(F=>F.id!==ie.id))},E=pe=>{if(q())return;if(g.current){p.current({searchQueryOverride:g.current});return}const{task:ie}=JSON.parse(pe.data),re=In(ie);o(F=>F.map(ce=>ce.id===re.id?{...re,column:"done"}:ce))},U=qs(`/api/events${w}`,{events:{"task:created":B,"task:moved":A,"task:updated":z,"task:deleted":X,"task:merged":E},onReconnect:()=>{W&&(q()||p.current())}});return()=>{W=!1,U()}},[n,i]);const y=a.useCallback(async I=>{const w=In(await mh(I,n));return o(q=>q.some(W=>W.id===w.id)?q:[...q,w]),w},[n]),R=a.useCallback(async(I,w)=>In(await kx(I,w,n)),[n]),j=a.useCallback(async I=>In(await hh(I,n)),[n]),C=a.useCallback(async I=>In(await jx(I,n)),[n]),S=a.useCallback(async I=>wx(I,n),[n]),P=a.useCallback(async I=>In(await Nx(I,n)),[n]),T=a.useCallback(async I=>{const w=In(await Sx(I,n));return o(q=>q.some(W=>W.id===w.id)?q:[...q,w]),w},[n]),_=a.useCallback(async(I,w)=>{const q=d.current.find(B=>B.id===I),W=q?{...q,...w,updatedAt:new Date().toISOString()}:void 0;W&&o(B=>B.map(A=>A.id===I?W:A));try{const B=In(await Ks(I,w,n));return o(A=>A.map(z=>z.id===I?B:z)),B}catch(B){throw q&&o(A=>A.map(z=>z.id===I?q:z)),B}},[n]),L=a.useCallback(async I=>{const w=In(await Ex(I,n));return o(q=>q.map(W=>W.id===I?w:W)),w},[n]),G=a.useCallback(async I=>{const w=In(await Mx(I,n));return o(q=>q.map(W=>W.id===I?w:W)),w},[n]),$=a.useCallback(async()=>{const w=(await _x(n)).map(In);return o(q=>q.map(W=>w.find(A=>A.id===W.id)||W)),w},[n]);return{tasks:r,createTask:y,moveTask:R,pauseTask:j,deleteTask:C,mergeTask:S,retryTask:P,duplicateTask:T,updateTask:_,archiveTask:L,unarchiveTask:G,archiveAllDone:$,loadArchivedTasks:M,includeArchived:l,lastFetchTimeMs:f.current}}const eR=5e3,tR=1e3;function nR(){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 pd();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 b=performance.now();try{const v=await pd(),k=`initial fetchProjectsAcrossNodes took ${Math.round(performance.now()-b)}ms (${v.length} projects)`;console.log(`[useProjects] ${k}`),Pa("[useProjects]",k),g||(n(v),o(null))}catch(v){const k=`initial fetch failed after ${Math.round(performance.now()-b)}ms: ${v instanceof Error?v.message:String(v)}`;console.warn(`[useProjects] ${k}`),Pa("[useProjects]",k),g||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{g||i(!1)}}p();const f=()=>{if(document.visibilityState!=="visible")return;const b=Date.now();b-c.current<tR||(c.current=b,u())};return document.addEventListener("visibilitychange",f),()=>{g=!0,document.removeEventListener("visibilitychange",f)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},eR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async g=>{const p=await Cy(g);return n(f=>[...f,p]),p},[]),m=a.useCallback(async(g,p)=>{const f=await Ay(g,p);return n(b=>b.map(v=>v.id===g?f:v)),f},[]),h=a.useCallback(async g=>{await kh(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 sR=1e4,iR=1e3;function aR(){const[e,n]=a.useState([]),[s,i]=a.useState(!0),[r,o]=a.useState(null),l=a.useRef(null),c=a.useRef(0),u=a.useCallback(async()=>{try{o(null);const p=await fd();n(p)}catch(p){o(p instanceof Error?p.message:"Failed to fetch nodes")}},[]);a.useEffect(()=>{let p=!1;async function f(){i(!0);try{const v=await fd();p||(n(v),o(null))}catch(v){p||o(v instanceof Error?v.message:"Failed to fetch nodes")}finally{p||i(!1)}}f();const b=()=>{if(document.visibilityState!=="visible")return;const v=Date.now();v-c.current<iR||(c.current=v,u())};return document.addEventListener("visibilitychange",b),()=>{p=!0,document.removeEventListener("visibilitychange",b)}},[u]),a.useEffect(()=>{if(!s)return l.current=setInterval(()=>{u()},sR),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,u]);const d=a.useCallback(async p=>{const f=await jy(p);return n(b=>[...b,f]),f},[]),m=a.useCallback(async(p,f)=>{const b=await wy(p,f);return n(v=>v.map(x=>x.id===p?b:x)),b},[]),h=a.useCallback(async p=>{await Ny(p),n(f=>f.filter(b=>b.id!==p))},[]),g=a.useCallback(async p=>{const f=await Sy(p);n(b=>b.map(v=>v.id===p?{...v,status:f.status,updatedAt:f.checkedAt}:v))},[]);return{nodes:e,loading:s,error:r,refresh:u,register:d,update:m,unregister:h,healthCheck:g}}const rR="kb-dashboard-current-project";function oR(e){return e??"local"}function lR(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=oR(s);a.useEffect(()=>{let p=!1;async function f(){try{const b=await ra();if(p)return;d.current=b.dashboardCurrentProjectIdByNode??{};const v=d.current[m];if(v){const x=e.find(k=>k.id===v);x&&(r(x),c.current=!0)}if(!v)try{const x=localStorage.getItem(rR);if(x){const k=JSON.parse(x);k?.id&&e.some(y=>y.id===k.id)&&(r(k),c.current=!0,d.current={...d.current,[m]:k.id},await nn({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(b=>b.id===i.id)&&e.length>0){const b=e.find(v=>v.status==="active");r(b||e[0]||null);return}const f={...d.current,[m]:i.id};d.current=f,nn({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,nn({dashboardCurrentProjectIdByNode:f}).catch(()=>{})}},[m]),g=a.useCallback(()=>{u.current=!0,r(null);const p={...d.current};delete p[m],d.current=p,nn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:i,setCurrentProject:h,clearCurrentProject:g,loading:o}}const ff=a.createContext(null);function cR({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()},[]),Jm.createElement(ff.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function dR(){const e=a.useContext(ff);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const gf="kb-dashboard-theme-mode",bf="kb-dashboard-color-theme",xf=[...ej],ac="theme-data",Cl="theme-data.css";function uR(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.endsWith("/")?e.slice(0,-1)+`/${Cl}`:e.replace(/\/[^/]+$/,`/${Cl}`):`/${Cl}`}const Ns=typeof window<"u",mR=Ns?a.useLayoutEffect:a.useEffect;function vf(e){return e==="dark"||e==="light"||e==="system"}function Um(){if(!Ns)return"dark";try{const e=localStorage.getItem(gf);if(vf(e))return e}catch{}return"dark"}function Bm(){if(!Ns)return"default";try{const e=localStorage.getItem(bf);if(e&&xf.includes(e))return e}catch{}return"default"}function Hm(e){if(Ns)try{localStorage.setItem(gf,e)}catch{}}function qm(e){if(Ns)try{localStorage.setItem(bf,e)}catch{}}function hR(e,n){return e==="system"?n?"dark":"light":e}function pR(e,n,s){if(!Ns)return;const i=hR(e,s);document.documentElement.setAttribute("data-theme",i),document.documentElement.setAttribute("data-color-theme",n)}function Vm(){if(!Ns)return;const e=uR(),n=document.getElementById(ac);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=ac,document.head.appendChild(s)}function Wm(){if(!Ns)return;const e=document.getElementById(ac);e&&e.remove()}function fR(){const[e,n]=a.useState(()=>Um()),[s,i]=a.useState(()=>Bm()),[r,o]=a.useState(!0),[l,c]=a.useState(()=>Ns?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(!Ns||!r)return;let f=!1;return ra().then(b=>{f||(vf(b.themeMode)&&!m.current&&(u.current!==b.themeMode&&(u.current=b.themeMode,n(b.themeMode)),Um()!==b.themeMode&&Hm(b.themeMode)),b.colorTheme&&xf.includes(b.colorTheme)&&!h.current&&(d.current!==b.colorTheme&&(d.current=b.colorTheme,i(b.colorTheme)),Bm()!==b.colorTheme&&qm(b.colorTheme)))}).catch(b=>{console.warn("[useTheme] Failed to hydrate theme from global settings",b)}).finally(()=>{f||o(!1)}),()=>{f=!0}},[r]),a.useEffect(()=>{if(!Ns)return;const f=window.matchMedia("(prefers-color-scheme: dark)"),b=v=>{c(v.matches)};return f.addEventListener("change",b),()=>f.removeEventListener("change",b)},[]),mR(()=>{pR(e,s,l)},[e,s,l]),a.useEffect(()=>{!Ns||r||(s!=="default"?Vm():Wm())},[s,r]);const g=a.useCallback(f=>{m.current=!0,u.current=f,n(f),Hm(f),nn({themeMode:f}).catch(b=>{console.warn("[useTheme] Failed to persist themeMode to global settings",b)})},[]),p=a.useCallback(f=>{h.current=!0,d.current=f,i(f),qm(f),f!=="default"?Vm():Wm(),nn({colorTheme:f}).catch(b=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",b)})},[]);return{themeMode:e,colorTheme:s,setThemeMode:g,setColorTheme:p,isSystemDark:l}}function gR(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,b]=a.useState(void 0),[v,x]=a.useState(null),[k,M]=a.useState("definition"),[y,R]=a.useState(!1),[j,C]=a.useState(void 0),[S,P]=a.useState(!1),[T,_]=a.useState(!1),[L,G]=a.useState(!1),[$,I]=a.useState(!1),[w,q]=a.useState(void 0),[W,B]=a.useState(!1),[A,z]=a.useState("project"),[X,E]=a.useState(!1),[U,pe]=a.useState(!1),[ie,re]=a.useState(!1),[F,ce]=a.useState(!1),[ae,Q]=a.useState(!1),[de,Te]=a.useState(!1),[fe,Se]=a.useState(!1),te=!!(v||y||s||r||m||$||W||X||U||ie||ae||F||L||S||T||de||fe),we=a.useCallback(()=>i(!0),[]),Pe=a.useCallback(()=>i(!1),[]),We=a.useCallback(()=>o(!0),[]),Ke=a.useCallback(ut=>{c(ut),o(!0)},[]),Ne=a.useCallback(()=>{const ut=n[0];ut&&(d(ut.id),o(!0))},[n]),_e=a.useCallback(ut=>{d(ut),o(!0)},[]),Oe=a.useCallback(()=>{o(!1),c(null),d(void 0)},[]),ye=a.useCallback(ut=>{p(ut),h(!0)},[]),De=a.useCallback(ut=>{b(ut),h(!0)},[]),se=a.useCallback(()=>{h(!1),p(null),b(void 0)},[]),J=a.useCallback((ut,Me="definition")=>{x(ut),M(Me)},[]),me=a.useCallback(ut=>{x(ut),M("changes")},[]),ee=a.useCallback(ut=>{x(Me=>Me&&{...Me,...ut})},[]),he=a.useCallback(()=>{x(null)},[]),le=a.useCallback(ut=>{C(ut),R(!0)},[]),Ie=a.useCallback(()=>{R(!1),C(void 0)},[]),Ze=a.useCallback(()=>P(!0),[]),at=a.useCallback(()=>P(!1),[]),oe=a.useCallback(()=>_(!0),[]),Z=a.useCallback(()=>_(!1),[]),ue=a.useCallback(()=>G(!0),[]),Ce=a.useCallback(()=>G(!1),[]),$e=a.useCallback(()=>{I(ut=>!ut)},[]),ve=a.useCallback(()=>{I(!1),q(void 0)},[]),Ge=a.useCallback(()=>B(!0),[]),je=a.useCallback(()=>B(!1),[]),Ue=a.useCallback(ut=>{z(ut)},[]),He=a.useCallback(()=>E(!0),[]),ge=a.useCallback(()=>E(!1),[]),Fe=a.useCallback(()=>pe(!0),[]),be=a.useCallback(()=>pe(!1),[]),Je=a.useCallback(()=>re(!0),[]),st=a.useCallback(()=>re(!1),[]),dt=a.useCallback(()=>ce(!0),[]),Tt=a.useCallback(()=>ce(!1),[]),$t=a.useCallback(()=>Q(!0),[]),Dt=a.useCallback(()=>Q(!1),[]),Bt=a.useCallback(async(ut,Me)=>{Q(!1),q(Me),I(!0)},[]),qt=a.useCallback(()=>Te(!0),[]),Lt=a.useCallback(()=>Te(!1),[]),Ct=a.useCallback(()=>Se(!0),[]),xt=a.useCallback(()=>Se(!1),[]),Et=a.useCallback((ut,Me)=>{Me(`Created ${ut.id} from planning mode`,"success"),o(!1),c(null)},[]),Le=a.useCallback((ut,Me)=>{const Qe=ut.map(rt=>rt.id).join(", ");Me(`Created ${Qe} from planning mode`,"success"),o(!1),c(null)},[]),gt=a.useCallback((ut,Me)=>{const Qe=ut.map(rt=>rt.id).join(", ");Me(`Created ${Qe} 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:k,settingsOpen:y,settingsInitialSection:j,schedulesOpen:S,githubImportOpen:T,usageOpen:L,terminalOpen:$,terminalInitialCommand:w,filesOpen:W,fileBrowserWorkspace:A,activityLogOpen:X,gitManagerOpen:U,workflowStepsOpen:ie,agentsOpen:F,scriptsOpen:ae,setupWizardOpen:de,modelOnboardingOpen:fe,anyModalOpen:te,openNewTask:we,closeNewTask:Pe,openPlanning:We,openPlanningWithInitialPlan:Ke,resumePlanning:Ne,openPlanningWithSession:_e,closePlanning:Oe,openSubtaskBreakdown:ye,openSubtaskWithSession:De,closeSubtask:se,openDetailTask:J,openDetailWithChangesTab:me,updateDetailTask:ee,closeDetailTask:he,openSettings:le,closeSettings:Ie,openSchedules:Ze,closeSchedules:at,openGitHubImport:oe,closeGitHubImport:Z,openUsage:ue,closeUsage:Ce,toggleTerminal:$e,closeTerminal:ve,openFiles:Ge,closeFiles:je,setFileWorkspace:Ue,openActivityLog:He,closeActivityLog:ge,openGitManager:Fe,closeGitManager:be,openWorkflowSteps:Je,closeWorkflowSteps:st,openAgents:dt,closeAgents:Tt,openScripts:$t,closeScripts:Dt,runScript:Bt,openSetupWizard:qt,closeSetupWizard:Lt,openModelOnboarding:Ct,closeModelOnboarding:xt,onPlanningTaskCreated:Et,onPlanningTasksCreated:Le,onSubtaskTasksCreated:gt}}function bR(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),[b,v]=a.useState(!1),[x,k]=a.useState({}),[M,y]=a.useState(!1),[R,j]=a.useState(!1),[C,S]=a.useState(!1),[P,T]=a.useState(!1),_=a.useCallback(async()=>{const[w,q]=await Promise.allSettled([Rx(e),ro(e)]);if(w.status==="fulfilled"&&(s(w.value.maxConcurrent),r(w.value.rootDir)),q.status==="fulfilled"){const W=q.value;l(!!W.autoMerge),u(!!W.globalPause),m(!!W.enginePaused),v(!!W.prAuthAvailable),g(W.taskStuckTimeoutMs),f(W.showQuickChatFAB===!0),k(W.experimentalFeatures??{});const B=W.experimentalFeatures??{};y(B.insights===!0),j(B.roadmap===!0),S(B.memoryView===!0),T(B.devServerView===!0||B.devServer===!0)}},[e]);a.useEffect(()=>{_()},[_]);const L=a.useCallback(async()=>{const w=!o;l(w);try{await dr({autoMerge:w},e)}catch{l(!w)}},[o,e]),G=a.useCallback(async()=>{const w=!c;u(w);try{await dr({globalPause:w,globalPauseReason:w?"manual":void 0},e)}catch{u(!w)}},[c,e]),$=a.useCallback(async()=>{const w=!d;m(w);try{await dr({enginePaused:w},e)}catch{m(!w)}},[d,e]),I=a.useCallback(async()=>{const w=!p;f(w);try{await dr({showQuickChatFAB:w},e)}catch{f(!w)}},[p,e]);return{maxConcurrent:n,rootDir:i,autoMerge:o,globalPaused:c,enginePaused:d,taskStuckTimeoutMs:h,showQuickChatFAB:p,prAuthAvailable:b,experimentalFeatures:x,insightsEnabled:M,roadmapEnabled:R,memoryEnabled:C,devServerEnabled:P,toggleAutoMerge:L,toggleGlobalPause:G,toggleEnginePause:$,toggleShowQuickChatFAB:I,refresh:_}}function xR(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(x=>x.id===p);if(!v){l(`Project '${p}' not found`,"error");return}r?.id!==v.id&&o(v)}if(d.current)return;d.current=!0,Or(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 vR(){const[e,n]=a.useState([]),[s,i]=a.useState([]),[r,o]=a.useState([]),l=a.useRef(s),c=a.useRef(r);a.useEffect(()=>{is().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 nn({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 nn({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 yR({projectId:e,openModelOnboarding:n,openSettings:s}){const i=a.useRef(!1);a.useEffect(()=>{if(i.current)return;i.current=!0;let r=!1,o=!1;Ba().then(({providers:l})=>{const c=l.some(d=>d.authenticated);if(l.length>0&&!c||l.length>0&&c)return ra().then(d=>{const m=!!(d.defaultProvider&&d.defaultModelId);(d.modelOnboardingComplete===!1||d.modelOnboardingComplete===void 0)&&(!c||!m)&&!sa()?r=!0:!c&&!sa()&&(o=!0)})}).then(()=>{r?(js("onboarding:auto-triggered",{trigger:"first-run"}),n()):o&&(js("onboarding:auto-triggered",{trigger:"missing-provider"}),s("authentication"))}).catch(()=>{})},[e,n,s])}const kR=["board","list","agents","missions","chat","documents","roadmaps","skills","mailbox","insights","memory","devserver","dev-server"];function Gm(e){return e!==null&&kR.includes(e)}function jR(e){return e==="devserver"?"dev-server":e}function wR(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:i,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:u,setThemeMode:d}=e,[m,h]=a.useState(()=>{if(typeof window<"u"){const x=window.localStorage.getItem("kb-dashboard-view-mode");if(x==="overview"||x==="project")return x}return"overview"}),[g,p]=a.useState(()=>{const x=Nn("kb-dashboard-task-view");return Gm(x)?x:"board"}),f=a.useRef(!1);a.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),a.useEffect(()=>{const x=Nn("kb-dashboard-task-view",r?.id);if(Gm(x)){const k=!f.current&&x==="devserver";p(k?"devserver":jR(x))}else p("board");r?.id&&(f.current=!0)},[r?.id]),a.useEffect(()=>{ts("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 x=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(x)},[n,s,o,i,r,l,c]);const b=a.useCallback(x=>{p(x)},[]),v=a.useCallback(()=>{const x=["dark","light","system"],k=x.indexOf(u),M=x[(k+1)%x.length];d(M)},[u,d]);return{viewMode:m,setViewMode:h,taskView:g,setTaskView:p,handleChangeTaskView:b,handleToggleTheme:v}}function NR(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(S=>{n(S),i("project")},[n,i]),f=a.useCallback(()=>{s(),i("overview")},[s,i]),b=a.useCallback(()=>{d()},[d]),v=a.useCallback(()=>{m()},[m]),x=a.useCallback(S=>{h(),n(S),i("project"),u(`Project ${S.name} registered successfully`,"success"),o()},[h,n,i,u,o]),k=a.useCallback(()=>{g()},[g]),M=a.useCallback(async S=>{try{await My(S.id),u(`Project ${S.name} paused`,"success"),await o()}catch{u(`Failed to pause project ${S.name}`,"error")}},[u,o]),y=a.useCallback(async S=>{try{await _y(S.id),u(`Project ${S.name} resumed`,"success"),await o()}catch{u(`Failed to resume project ${S.name}`,"error")}},[u,o]),R=a.useCallback(async S=>{try{await kh(S.id),u(`Project ${S.name} removed`,"success"),r?.id===S.id&&(s(),i("overview")),await o()}catch{u(`Failed to remove project ${S.name}`,"error")}},[r,s,i,u,o]),j=a.useCallback(async S=>{try{await l(S)}catch{u("Failed to update favorites","error")}},[l,u]),C=a.useCallback(async S=>{try{await c(S)}catch{u("Failed to update model favorites","error")}},[c,u]);return{handleSelectProject:p,handleViewAllProjects:f,handleOpenSettings:b,handleAddProject:v,handleSetupComplete:x,handleModelOnboardingComplete:k,handlePauseProject:M,handleResumeProject:y,handleRemoveProject:R,handleToggleFavorite:j,handleToggleModelFavorite:C}}function SR(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 CR(e){return lo("/health",{nodeId:e})}async function ER(e){return lo("/projects",{nodeId:e})}async function MR(e,n,s){const i=new URLSearchParams({projectId:n});return s&&s.trim()&&i.set("q",s.trim()),lo(`/tasks?${i.toString()}`,{nodeId:e})}async function _R(e,n){return lo(`/project-health?projectId=${encodeURIComponent(n)}`,{nodeId:e})}async function dP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/push`,{method:"POST",body:JSON.stringify({})})}async function uP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/pull`,{method:"POST",body:JSON.stringify({conflictResolution:"last-write-wins"})})}async function mP(e){return D(`/nodes/${encodeURIComponent(e)}/settings/sync-status`)}async function hP(e){return D(`/nodes/${encodeURIComponent(e)}/auth/sync`,{method:"POST",body:JSON.stringify({})})}function AR(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),b=a.useCallback(async()=>{if(!e){o([]),c([]),d(null),h(!1),p(null);return}f.current?.abort();const x=new AbortController;f.current=x,h(!0),p(null);try{const k=[CR(e),ER(e)];s&&(k.push(MR(e,s,i)),k.push(_R(e,s)));const M=await Promise.allSettled(k);if(x.signal.aborted)return;const y=M[0],R=M[1];if(y.status==="rejected"){p(`Failed to fetch node health: ${y.reason}`),h(!1);return}if(d(y.value),R.status==="rejected"){p(`Failed to fetch projects: ${R.reason}`),h(!1);return}if(o(R.value),s&&M[2]){const j=M[2];if(j.status==="rejected"){p(`Failed to fetch tasks: ${j.reason}`),h(!1);return}j.status==="fulfilled"&&c(j.value)}h(!1)}catch(k){x.signal.aborted||(p(k instanceof Error?k.message:"Unknown error"),h(!1))}},[e,s,i]);a.useEffect(()=>(b(),()=>{f.current?.abort()}),[b]);const v=a.useCallback(()=>{b()},[b]);return{projects:r,tasks:l,health:u,loading:m,error:g,refresh:v}}function TR(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 qs(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 RR="fusion-dashboard-current-node",yf=a.createContext(null);function IR({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 ra();if(m)return;l.current=g.dashboardCurrentNodeId;const p=g.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const f=localStorage.getItem(RR);if(f){const b=JSON.parse(f);b?.id&&b?.type==="remote"&&(l.current=b.id,await nn({dashboardCurrentNodeId:b.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),a.useEffect(()=>{if(!i)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,nn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,nn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,i]);const c=a.useCallback(m=>{s(m)},[]),u=a.useCallback(()=>{s(null),l.current=void 0,nn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),d={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:u};return t.jsx(yf.Provider,{value:d,children:e})}function PR(){const e=a.useContext(yf);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}function $R({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&&(lx(l),window.location.reload())},[n]),o=a.useCallback(()=>{cx(),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 DR=a.lazy(()=>Zt(()=>import("./AgentsView-DpEpW88a.js").then(e=>e.A),__vite__mapDeps([16,1,17,8,18])).then(e=>({default:e.AgentsView}))),LR=a.lazy(()=>Zt(()=>import("./DocumentsView-Dx0M1YHw.js"),__vite__mapDeps([19,1,0,2,20])).then(e=>({default:e.DocumentsView}))),zR=a.lazy(()=>Zt(()=>import("./InsightsView-BtXdAo7D.js"),__vite__mapDeps([21,1,14,0,2,22])).then(e=>({default:e.InsightsView}))),FR=a.lazy(()=>Zt(()=>import("./NodesView-B_ZwUORz.js"),__vite__mapDeps([23,1,17,0,2,24])).then(e=>({default:e.NodesView}))),OR=a.lazy(()=>Zt(()=>import("./ChatView-BUt3C4cf.js"),__vite__mapDeps([25,1,0,2])).then(e=>({default:e.ChatView}))),UR=a.lazy(()=>Zt(()=>import("./RoadmapsView-DbUzBLeF.js"),__vite__mapDeps([26,1,0,2,27])).then(e=>({default:e.RoadmapsView}))),BR=a.lazy(()=>Zt(()=>import("./SkillsView-Dzzpd5Md.js"),__vite__mapDeps([28,1,0,2,29])).then(e=>({default:e.SkillsView}))),HR=a.lazy(()=>Zt(()=>import("./MemoryView-kKPuqmwf.js"),__vite__mapDeps([30,1,12,13,0,2,31])).then(e=>({default:e.MemoryView}))),qR=a.lazy(()=>Zt(()=>import("./DevServerView-BOyWtQJM.js"),__vite__mapDeps([32,1,0,2,33])).then(e=>({default:e.DevServerView})));function VR(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{Zt(()=>import("./AgentsView-DpEpW88a.js").then(n=>n.A),__vite__mapDeps([16,1,17,8,18])),Zt(()=>import("./DocumentsView-Dx0M1YHw.js"),__vite__mapDeps([19,1,0,2,20])),Zt(()=>import("./InsightsView-BtXdAo7D.js"),__vite__mapDeps([21,1,14,0,2,22])),Zt(()=>import("./NodesView-B_ZwUORz.js"),__vite__mapDeps([23,1,17,0,2,24])),Zt(()=>import("./ChatView-BUt3C4cf.js"),__vite__mapDeps([25,1,0,2])),Zt(()=>import("./RoadmapsView-DbUzBLeF.js"),__vite__mapDeps([26,1,0,2,27])),Zt(()=>import("./SkillsView-Dzzpd5Md.js"),__vite__mapDeps([28,1,0,2,29])),Zt(()=>import("./MemoryView-kKPuqmwf.js"),__vite__mapDeps([30,1,12,13,0,2,31])),Zt(()=>import("./DevServerView-BOyWtQJM.js"),__vite__mapDeps([32,1,0,2,33]))})}const El="kb-setup-warning-dismissed";function WR(){const{toasts:e,addToast:n,removeToast:s}=dR(),i=typeof window<"u"&&!!window.electronAPI;a.useEffect(()=>{VR()},[]);const{projects:r,loading:o,error:l,refresh:c}=nR(),{nodes:u}=aR(),{currentNode:d,currentNodeId:m,isRemote:h,setCurrentNode:g,clearCurrentNode:p}=PR(),{currentProject:f,setCurrentProject:b,clearCurrentProject:v,loading:x}=lR(r,{nodeId:m}),{hasAiProvider:k,hasGithub:M,loading:y,hasWarnings:R}=of(f?.id);a.useEffect(()=>{if(m&&!d&&u.length>0){const ct=u.find(ne=>ne.id===m);if(ct){g(ct);return}}m&&u.length>0&&(u.some(ne=>ne.id===m)||p())},[m,d,u,g,p]);const[j,C]=a.useState(""),S=AR(m,{projectId:f?.id,searchQuery:j||void 0});TR(m);const P=h&&S.projects.length>0?S.projects:r,{themeMode:T,colorTheme:_,setThemeMode:L,setColorTheme:G}=fR(),{sessions:$,generating:I,needsInput:w,planningSessions:q,dismissSession:W}=XT(f?.id),B=$.filter(ct=>ct.status==="awaiting_input"||ct.status==="error"),A=gR({projectId:f?.id,planningSessions:q}),{viewMode:z,setViewMode:X,taskView:E,handleChangeTaskView:U}=wR({projectsLoading:o,projectsError:l,currentProjectLoading:x,currentProject:f,projectsLength:r.length,setupWizardOpen:A.setupWizardOpen,openSetupWizard:A.openSetupWizard,themeMode:T,setThemeMode:L}),pe=a.useCallback(ct=>{ct==="missions"&&(ue(void 0),$e(void 0),Ge(void 0)),U(ct)},[U]),ie=E==="board"||E==="list",{tasks:re,createTask:F,moveTask:ce,pauseTask:ae,deleteTask:Q,mergeTask:de,retryTask:Te,updateTask:fe,duplicateTask:Se,archiveTask:te,unarchiveTask:we,archiveAllDone:Pe,loadArchivedTasks:We,lastFetchTimeMs:Ke}=ZT({...f?{projectId:f.id}:{},searchQuery:j||void 0,sseEnabled:ie}),[Ne,_e]=a.useState(!1),Oe=a.useRef(performance.now()),ye=a.useRef(!1),De=a.useRef(!1),se=a.useMemo(()=>o?"projects":x?"project":"tasks",[o,x]);a.useEffect(()=>{if(!o&&!ye.current){ye.current=!0;const ct=`projects loaded at ${Math.round(performance.now()-Oe.current)}ms from mount`;console.log(`[App] ${ct}`),Pa("[App]",ct)}if(!x&&!De.current){De.current=!0;const ct=`current-project resolved at ${Math.round(performance.now()-Oe.current)}ms from mount`;console.log(`[App] ${ct}`),Pa("[App]",ct)}},[o,x]),a.useEffect(()=>{if(Ne||o||x)return;const ct=performance.now(),ne=window.setTimeout(()=>{const Ee=`dashboard ready at ${Math.round(performance.now()-Oe.current)}ms from mount (settle delay=${Math.round(performance.now()-ct)}ms)`;console.log(`[App] ${Ee}`),Pa("[App]",Ee),_e(!0)},200);return()=>{window.clearTimeout(ne)}},[Ne,o,x]);const me=tr()==="mobile",[ee,he]=a.useState(0),le=a.useCallback(()=>{Ch(f?.id).then(ct=>{he(ct.unreadCount)}).catch(ct=>{console.warn("[App] Failed to fetch mailbox unread count:",ct)})},[f?.id]);a.useEffect(()=>{le();const ct=new URLSearchParams;f?.id&&ct.set("projectId",f.id);const ne=ct.size>0?`?${ct.toString()}`:"";return qs(`/api/events${ne}`,{events:{"message:sent":le,"message:received":le,"message:read":le,"message:deleted":le}})},[f?.id,le]);const[Ie,Ze]=a.useState(!1),[at,oe]=a.useState(!1),[Z,ue]=a.useState(void 0),[Ce,$e]=a.useState(void 0),[ve,Ge]=a.useState(void 0),[je,Ue]=a.useState(!1),[He,ge]=a.useState(!1),[Fe,be]=a.useState(()=>Nn(El,f?.id)==="true");a.useEffect(()=>{be(Nn(El,f?.id)==="true")},[f?.id]),a.useEffect(()=>{const ct=()=>{ge(!0)};return window.addEventListener(Dl,ct),()=>{window.removeEventListener(Dl,ct)}},[]);const Je=a.useCallback(()=>{ts(El,"true",f?.id),be(!0)},[f?.id]),{maxConcurrent:st,autoMerge:dt,globalPaused:Tt,enginePaused:$t,taskStuckTimeoutMs:Dt,showQuickChatFAB:Bt,prAuthAvailable:qt,experimentalFeatures:Lt,insightsEnabled:Ct,roadmapEnabled:xt,memoryEnabled:Et,devServerEnabled:Le,toggleAutoMerge:gt,toggleGlobalPause:ut,toggleEnginePause:Me,refresh:Qe}=bR(f?.id),rt=Lt.skillsView===!0,N=Lt.nodesView===!0,H=!0;a.useEffect(()=>{Object.keys(Lt).length!==0&&(E==="insights"&&!Ct&&U("board"),E==="roadmaps"&&!xt&&U("board"),E==="memory"&&!Et&&U("board"),(E==="devserver"||E==="dev-server")&&!Le&&U("board"))},[E,Ct,xt,Lt,U,H,Et,Le]),a.useEffect(()=>{Ie&&!N&&Ze(!1)},[Ie,N]);const{availableModels:Ae,favoriteProviders:ot,favoriteModels:kt,toggleFavoriteProvider:Ot,toggleFavoriteModel:sn}=vR();yR({projectId:f?.id,openModelOnboarding:A.openModelOnboarding,openSettings:A.openSettings});const{handleSelectProject:Rt,handleViewAllProjects:zn,handleOpenSettings:Wn,handleAddProject:ms,handleSetupComplete:pn,handleModelOnboardingComplete:Fn,handlePauseProject:Sn,handleResumeProject:fn,handleRemoveProject:Gn,handleToggleFavorite:dn,handleToggleModelFavorite:Mt}=NR({setCurrentProject:b,clearCurrentProject:v,setViewMode:X,currentProject:f,refreshProjects:c,toggleFavoriteProvider:Ot,toggleFavoriteModel:sn,addToast:n,openSettings:A.openSettings,openSetupWizard:A.openSetupWizard,closeSetupWizard:A.closeSetupWizard,closeModelOnboarding:A.closeModelOnboarding}),{handleDetailClose:yn}=xR({projectId:f?.id,projects:r,projectsLoading:o,currentProject:f,setCurrentProject:b,addToast:n,openTaskDetail:A.openDetailTask,closeTaskDetail:A.closeDetailTask}),{handleBoardQuickCreate:Kn,handleModalCreate:kn,handlePlanningTaskCreated:_n,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:On}=SR({createTask:F,onPlanningTaskCreated:A.onPlanningTaskCreated,onPlanningTasksCreated:A.onPlanningTasksCreated,onSubtaskTasksCreated:A.onSubtaskTasksCreated,addToast:n}),K=a.useCallback((ct,ne)=>{if(ne==="changes"){A.openDetailWithChangesTab(ct);return}A.openDetailTask(ct,ne)},[A]),ze=a.useCallback(()=>{N&&Ze(ct=>!ct)},[N]),tt=a.useCallback(()=>{A.setFileWorkspace("project"),A.openFiles()},[A]),et=a.useCallback(async()=>{oe(!0);try{await c()}finally{oe(!1)}},[c]),mt=a.useCallback(ct=>{$e(ct),ue(void 0),U("missions")},[U]),jt=a.useCallback(ct=>{ct.type==="planning"?A.openPlanningWithSession(ct.id):ct.type==="subtask"?A.openSubtaskWithSession(ct.id):ct.type==="mission_interview"?($e(void 0),ue(ct.id),Ge(void 0),U("missions")):(ct.type==="milestone_interview"||ct.type==="slice_interview")&&(ue(void 0),$e(void 0),Ge(ct.id),U("missions"))},[U,A]),_t=a.useCallback(()=>{for(const ct of B)W(ct.id)},[W,B]),gn=!o&&!x&&r.length===0&&!f&&!!l,fs=()=>gn?t.jsx(pT,{errorMessage:l??"Failed to fetch projects",isRetrying:at,onRetry:et}):Ie?t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(FR,{addToast:n,onClose:()=>Ze(!1)})})})}):z==="overview"?t.jsx(Xn,{children:t.jsx(yw,{projects:r,loading:o,onSelectProject:Rt,onAddProject:ms,onPauseProject:Sn,onResumeProject:fn,onRemoveProject:Gn,nodes:u})}):E==="skills"?rt?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(BR,{addToast:n,projectId:f?.id,onClose:()=>U("board")})})}):(U("board"),null):E==="chat"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(OR,{addToast:n,projectId:f?.id})})}):E==="mailbox"?t.jsx(Xn,{children:t.jsx(mN,{projectId:f?.id,addToast:n,onUnreadCountChange:he})}):E==="roadmaps"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(UR,{addToast:n,projectId:f?.id})})}):E==="missions"?t.jsx(Xn,{children:t.jsx(lN,{isInline:!0,isOpen:!0,onClose:()=>{$e(void 0),ue(void 0),Ge(void 0),U("board")},addToast:n,projectId:f?.id,onSelectTask:ct=>{const ne=re.find(Ee=>Ee.id===ct);ne&&A.openDetailTask(ne)},availableTasks:re.map(ct=>({id:ct.id,title:ct.title})),resumeSessionId:Z,targetMissionId:Ce,milestoneSliceResumeSessionId:ve,onMilestoneSliceResumeFetchError:()=>Ge(void 0)})}):E==="agents"&&H?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(DR,{addToast:n,projectId:f?.id})})}):E==="documents"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(LR,{projectId:f?.id,addToast:n,onOpenDetail:A.openDetailTask})})}):E==="insights"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(zR,{projectId:f?.id,addToast:n,onClose:()=>U("board")})})}):E==="memory"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(HR,{addToast:n,projectId:f?.id})})}):E==="devserver"||E==="dev-server"?t.jsx(Xn,{children:t.jsx(a.Suspense,{fallback:null,children:t.jsx(qR,{addToast:n,projectId:f?.id})})}):E==="board"?t.jsx(Xn,{children:t.jsx(lw,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f?.id,maxConcurrent:st,onMoveTask:ce,onPauseTask:ae,onOpenDetail:A.openDetailTask,addToast:n,onQuickCreate:Kn,onNewTask:A.openNewTask,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,autoMerge:dt,onToggleAutoMerge:gt,globalPaused:Tt,onUpdateTask:fe,onArchiveTask:te,onUnarchiveTask:we,onDeleteTask:Q,onArchiveAllDone:Pe,onLoadArchivedTasks:We,searchQuery:j,availableModels:Ae,onOpenDetailWithTab:K,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt,taskStuckTimeoutMs:Dt,onOpenMission:mt,lastFetchTimeMs:Ke})}):t.jsx(Xn,{children:t.jsx(dw,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f?.id,onMoveTask:ce,onOpenDetail:A.openDetailTask,addToast:n,globalPaused:Tt,onNewTask:A.openNewTask,onQuickCreate:Kn,onPlanningMode:A.openPlanningWithInitialPlan,onSubtaskBreakdown:A.openSubtaskBreakdown,availableModels:Ae,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt,taskStuckTimeoutMs:Dt,searchQuery:j,lastFetchTimeMs:Ke})});if(!Ne)return t.jsxs(t.Fragment,{children:[t.jsx(gT,{stage:se}),t.jsx(hf,{toasts:e,onRemove:s})]});const Qt=!A.modelOnboardingOpen&&FA(),vt=!A.modelOnboardingOpen&&!Qt&&sa()&&!cf();return t.jsxs(t.Fragment,{children:[t.jsx(Jk,{isElectron:i,onOpenSettings:Wn,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:q.length,onOpenUsage:A.openUsage,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>pe("mailbox"),mailboxUnreadCount:ee,onOpenSchedules:A.openSchedules,onOpenGitManager:A.openGitManager,onOpenNodes:ze,showNodesButton:N,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenScripts:A.openScripts,onRunScript:A.runScript,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,filesOpen:A.filesOpen,globalPaused:Tt,enginePaused:$t,onToggleGlobalPause:ut,onToggleEnginePause:Me,view:E,onChangeView:z==="project"&&f?pe:void 0,showSkillsTab:rt,showAgentsTab:H,searchQuery:j,onSearchChange:C,projects:P,currentProject:f,onSelectProject:Rt,onViewAllProjects:zn,projectId:f?.id,mobileNavEnabled:me,availableNodes:u,currentNode:d,onSelectNode:ct=>{ct===null?p():g(ct)},isRemote:h,experimentalFeatures:{insights:Ct,roadmap:xt,memoryView:Et,devServer:Le,devServerView:Le}}),z==="project"&&f&&!Ie&&E!=="missions"&&!A.isPlanningOpen&&t.jsx(_T,{sessions:B,onResumeSession:jt,onDismissSession:W,onDismissAll:_t}),z==="project"&&f&&Qt&&t.jsx(AT,{onResume:A.openModelOnboarding}),z==="project"&&f&&vt&&t.jsx(TT,{onOpenModelOnboarding:A.openModelOnboarding,onOpenSettings:ct=>A.openSettings(ct)}),z==="project"&&f&&!y&&R&&!Fe&&t.jsx(lf,{hasAiProvider:k,hasGithub:M,onDismiss:Je}),t.jsx("div",{className:`project-content${z==="project"&&f?" project-content--with-footer":""}${me?" project-content--with-mobile-nav":""}`,children:fs()}),z==="project"&&f&&!Ie&&t.jsx(CT,{tasks:h&&S.tasks.length>0?S.tasks:re,projectId:f.id,taskStuckTimeoutMs:Dt,backgroundSessions:$,backgroundGenerating:I,backgroundNeedsInput:w,onOpenBackgroundSession:jt,onDismissBackgroundSession:W,lastFetchTimeMs:Ke,currentProjectPath:f.path,onOpenProjectDirectory:tt}),t.jsx(IT,{view:E,onChangeView:z==="project"&&f?pe:()=>{},footerVisible:z==="project"&&!!f,modalOpen:A.anyModalOpen,onOpenSettings:Wn,onOpenActivityLog:A.openActivityLog,onOpenMailbox:()=>pe("mailbox"),mailboxUnreadCount:ee,onOpenGitManager:A.openGitManager,onOpenWorkflowSteps:A.openWorkflowSteps,onOpenSchedules:A.openSchedules,onOpenScripts:A.openScripts,onToggleTerminal:A.toggleTerminal,onOpenFiles:A.openFiles,onOpenGitHubImport:A.openGitHubImport,onOpenPlanning:A.openPlanning,onResumePlanning:A.resumePlanning,activePlanningSessionCount:q.length,onOpenUsage:A.openUsage,onViewAllProjects:zn,onRunScript:A.runScript,projectId:f?.id,showSkillsTab:rt,experimentalFeatures:{insights:Ct,roadmap:xt,memoryView:Et,devServer:Le,devServerView:Le}}),z==="project"&&f&&E!=="chat"&&E!=="mailbox"&&E!=="insights"&&E!=="devserver"&&E!=="dev-server"&&t.jsx(QT,{projectId:f.id,addToast:n,showFAB:Bt,open:je,onOpenChange:Ue,favoriteProviders:ot,favoriteModels:kt,onToggleFavorite:dn,onToggleModelFavorite:Mt}),t.jsx(hT,{projectId:f?.id,tasks:re,projects:r,currentProject:f,addToast:n,toasts:e,removeToast:s,modalManager:A,projectActions:{handleAddProject:ms,handleSetupComplete:pn,handleModelOnboardingComplete:Fn},taskHandlers:{handleModalCreate:kn,handlePlanningTaskCreated:_n,handlePlanningTasksCreated:hs,handleSubtaskTasksCreated:ps,handleGitHubImport:On},taskOperations:{moveTask:ce,deleteTask:Q,mergeTask:de,retryTask:Te,duplicateTask:Se},deepLink:{handleDetailClose:yn},settings:{prAuthAvailable:qt,themeMode:T,colorTheme:_,setThemeMode:L,setColorTheme:G},onSettingsClose:()=>{A.closeSettings(),Qe()},onReopenOnboarding:()=>{A.closeSettings(),A.openModelOnboarding()}}),t.jsx($R,{open:He})]})}function GR(){return t.jsx(cR,{children:t.jsx(IR,{children:t.jsx(WR,{})})})}gx();tx();Sf.createRoot(document.getElementById("root")).render(t.jsx(a.StrictMode,{children:t.jsx(nx,{children:t.jsx(GR,{})})}));"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{A4 as $,Ss as A,an as B,tn as C,en as D,rn as E,Ni as F,to as G,jl as H,Ht as I,Fs as J,zt as K,it as L,_A as M,xy as N,jA as O,Mn as P,wA as Q,hn as R,Bi as S,lc as T,vy as U,yy as V,Y4 as W,Pt as X,_4 as Y,vn as Z,Zt as _,ts as a,MI as a$,Or as a0,Mv as a1,$r as a2,Vi as a3,ia as a4,Qs as a5,Xs as a6,Ys as a7,eP as a8,sP as a9,XI as aA,ZI as aB,Uk as aC,Bk as aD,OT as aE,tr as aF,rc as aG,PT as aH,zT as aI,ls as aJ,vi as aK,li as aL,Jb as aM,hI as aN,fI as aO,pI as aP,gI as aQ,bI as aR,xI as aS,vI as aT,yI as aU,kI as aV,jI as aW,wI as aX,NI as aY,SI as aZ,CI as a_,nP as aa,tP as ab,iP as ac,Dn as ad,ss as ae,Bb as af,Us as ag,xg as ah,Zr as ai,ji as aj,mP as ak,dP as al,uP as am,hP as an,Lr as ao,Pb as ap,Oa as aq,hg as ar,Hn as as,lh as at,aR as au,nR as av,QI as aw,yd as ax,Ha as ay,Ok as az,aI as b,cI as b$,_I as b0,EI as b1,xn as b2,oc as b3,wi as b4,JI as b5,KI as b6,YI as b7,d4 as b8,c4 as b9,Wv as bA,T4 as bB,aa as bC,io as bD,rh as bE,Ki as bF,Cy as bG,lx as bH,cx as bI,Of as bJ,n_ as bK,k4 as bL,uI as bM,YR as bN,Ba as bO,rI as bP,QR as bQ,ZR as bR,tv as bS,Wx as bT,Hs as bU,Gx as bV,Kx as bW,Jx as bX,N4 as bY,oI as bZ,lI as b_,l4 as ba,u4 as bb,v4 as bc,y4 as bd,g4 as be,h4 as bf,p4 as bg,f4 as bh,m4 as bi,o4 as bj,b4 as bk,g_ as bl,P4 as bm,I4 as bn,O4 as bo,R4 as bp,$4 as bq,D4 as br,L4 as bs,z4 as bt,Yv as bu,F4 as bv,dc as bw,Gv as bx,Kv as by,Jv as bz,Ve as c,w4 as c$,aP as c0,rP as c1,mI as c2,XR as c3,jn as c4,p_ as c5,TA as c6,_m as c7,co as c8,e4 as c9,eI as cA,th as cB,V4 as cC,q4 as cD,kA as cE,Q4 as cF,Ka as cG,zE as cH,B4 as cI,U4 as cJ,_v as cK,H4 as cL,W4 as cM,zI as cN,FI as cO,Eb as cP,Il as cQ,VI as cR,WI as cS,BI as cT,UI as cU,HI as cV,OI as cW,qI as cX,dI as cY,S4 as cZ,j4 as c_,t4 as ca,n4 as cb,s4 as cc,i4 as cd,a4 as ce,r4 as cf,im as cg,oP as ch,lP as ci,x4 as cj,AI as ck,RI as cl,$I as cm,II as cn,TI as co,PI as cp,DI as cq,yh as cr,td as cs,Kg as ct,LI as cu,X4 as cv,G4 as cw,J4 as cx,K4 as cy,tI as cz,sI as d,E4 as d0,M4 as d1,C4 as d2,iI as e,GI as f,Nn as g,is as h,oa as i,wn as j,by as k,nI as l,LT as m,ro as n,dr as o,xe as p,nj as q,Z4 as r,qs as s,Tl as t,nn as u,Os as v,Vt as w,Dr as x,NA as y,cP as z};
|