@runfusion/fusion 0.28.0 → 0.28.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.
Files changed (43) hide show
  1. package/dist/bin.js +0 -27
  2. package/dist/client/assets/{AgentDetailView-V32TpEe1.js → AgentDetailView-DG01uRND.js} +1 -1
  3. package/dist/client/assets/{AgentsView-CxITZE-U.js → AgentsView-B6IKroR1.js} +3 -3
  4. package/dist/client/assets/{ChatView-7WPHyB_7.js → ChatView-DKstOyUm.js} +1 -1
  5. package/dist/client/assets/{DevServerView-Diw4hjw0.js → DevServerView-DQQcGd2N.js} +1 -1
  6. package/dist/client/assets/{DirectoryPicker-CWSApoLU.js → DirectoryPicker-BfShQutV.js} +1 -1
  7. package/dist/client/assets/{DocumentsView-1kr0dhsV.js → DocumentsView-C4Ky-ZkQ.js} +1 -1
  8. package/dist/client/assets/{EvalsView-cDfXYiK6.js → EvalsView-B-z_KLLW.js} +1 -1
  9. package/dist/client/assets/{ExperimentalAgentOnboardingModal-lNSf6UtY.js → ExperimentalAgentOnboardingModal-CtR7eRBv.js} +1 -1
  10. package/dist/client/assets/{InsightsView-D2AjxOnu.js → InsightsView-BGbXkJpz.js} +1 -1
  11. package/dist/client/assets/{MemoryView-Dq4yjIPI.js → MemoryView-CRbaCcG_.js} +1 -1
  12. package/dist/client/assets/{NodesView-Cpmkze7n.js → NodesView-Hjxwv7rE.js} +1 -1
  13. package/dist/client/assets/{PiExtensionsManager-oi9FHT0y.js → PiExtensionsManager-ckNj1Wvv.js} +1 -1
  14. package/dist/client/assets/{PluginManager-o12KG4e8.js → PluginManager-CpY9rYNq.js} +1 -1
  15. package/dist/client/assets/{ResearchView-C9bjVB7-.js → ResearchView-BMxwiVk9.js} +1 -1
  16. package/dist/client/assets/{SettingsModal-Cu93Jjho.js → SettingsModal-3Jxv4PMI.js} +3 -3
  17. package/dist/client/assets/{SettingsModal-CT01a5Rh.js → SettingsModal-Bqfq-gnu.js} +1 -1
  18. package/dist/client/assets/{SetupWizardModal-Agi3XNtZ.js → SetupWizardModal-SVUr5Mpm.js} +1 -1
  19. package/dist/client/assets/{SkillsView-DmZfbGLs.js → SkillsView-COs7muvr.js} +1 -1
  20. package/dist/client/assets/{StashRecoveryView-BwKJQaUW.js → StashRecoveryView-BhB_6Fvq.js} +1 -1
  21. package/dist/client/assets/{TodoView-uJRg4Cnl.js → TodoView-CDtkPdrq.js} +1 -1
  22. package/dist/client/assets/{dashboard-view-C7Snlgow.js → dashboard-view-Czurx3BJ.js} +1 -1
  23. package/dist/client/assets/{folder-open-DU-Ec_iC.js → folder-open-D8Qfxakh.js} +1 -1
  24. package/dist/client/assets/{index-DiewofJh.js → index-u6AOHWO5.js} +5 -5
  25. package/dist/client/assets/{star-Qi0GspVN.js → star-BkCn1oUu.js} +1 -1
  26. package/dist/client/assets/{upload-Dx_l9Vbu.js → upload-BHiYszS2.js} +1 -1
  27. package/dist/client/assets/{users-3Qw_TMah.js → users-Ch_Fnf5M.js} +1 -1
  28. package/dist/client/index.html +1 -1
  29. package/dist/client/version.json +1 -1
  30. package/dist/droid-cli/package.json +1 -1
  31. package/dist/extension.js +0 -27
  32. package/dist/pi-claude-cli/package.json +1 -1
  33. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  34. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  35. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  36. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  37. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  38. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  39. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  40. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  41. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  42. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  43. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-V32TpEe1.js","assets/vendor-react-K0fH_qHe.js","assets/star-Qi0GspVN.js","assets/ExperimentalAgentOnboardingModal-lNSf6UtY.js","assets/ExperimentalAgentOnboardingModal-B-APN_lM.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-DSpIqBOs.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-uJRg4Cnl.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-Agi3XNtZ.js","assets/DirectoryPicker-CWSApoLU.js","assets/folder-open-DU-Ec_iC.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-Cu93Jjho.js","assets/SettingsModal-CT01a5Rh.js","assets/SettingsModal-Ci0_sqbU.css","assets/users-3Qw_TMah.js","assets/SettingsModal-DWKgRxBA.css","assets/dashboard-view-C7Snlgow.js","assets/createLucideIcon-BazL2hk5.js","assets/dashboard-view-DqWnXEbq.css","assets/dashboard-view-BWGH_fAq.js","assets/dashboard-view-DdGlfuu-.css","assets/AgentsView-CxITZE-U.js","assets/upload-Dx_l9Vbu.js","assets/AgentsView-B3ADnF0D.css","assets/DocumentsView-1kr0dhsV.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-D2AjxOnu.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-C9bjVB7-.js","assets/ResearchView-C7uXon3o.css","assets/EvalsView-cDfXYiK6.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-Cpmkze7n.js","assets/NodesView-DT4pXowv.css","assets/ChatView-7WPHyB_7.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-DmZfbGLs.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-Dq4yjIPI.js","assets/MemoryView-zaXewZzi.css","assets/DevServerView-Diw4hjw0.js","assets/DevServerView-DlZpuAnj.css","assets/StashRecoveryView-BwKJQaUW.js","assets/StashRecoveryView-B_8WIQEo.css"])))=>i.map(i=>d[i]);
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-DG01uRND.js","assets/vendor-react-K0fH_qHe.js","assets/star-BkCn1oUu.js","assets/ExperimentalAgentOnboardingModal-CtR7eRBv.js","assets/ExperimentalAgentOnboardingModal-B-APN_lM.css","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/AgentDetailView-DSpIqBOs.css","assets/addon-fit-C7jRorKK.js","assets/addon-web-links-CkJwd4cQ.js","assets/addon-webgl-BjvOw43o.js","assets/TodoView-CDtkPdrq.js","assets/TodoView-Cx9cVhq7.css","assets/SetupWizardModal-SVUr5Mpm.js","assets/DirectoryPicker-BfShQutV.js","assets/folder-open-D8Qfxakh.js","assets/DirectoryPicker-DzKVmxOf.css","assets/projectDetection-G3XuxD2X.js","assets/SetupWizardModal-CGYGKurR.css","assets/SettingsModal-3Jxv4PMI.js","assets/SettingsModal-Bqfq-gnu.js","assets/SettingsModal-Ci0_sqbU.css","assets/users-Ch_Fnf5M.js","assets/SettingsModal-DWKgRxBA.css","assets/dashboard-view-Czurx3BJ.js","assets/createLucideIcon-BazL2hk5.js","assets/dashboard-view-DqWnXEbq.css","assets/dashboard-view-BWGH_fAq.js","assets/dashboard-view-DdGlfuu-.css","assets/AgentsView-B6IKroR1.js","assets/upload-BHiYszS2.js","assets/AgentsView-B3ADnF0D.css","assets/DocumentsView-C4Ky-ZkQ.js","assets/DocumentsView-gv4zG3aT.css","assets/InsightsView-BGbXkJpz.js","assets/InsightsView-B0J4mhzV.css","assets/ResearchView-BMxwiVk9.js","assets/ResearchView-C7uXon3o.css","assets/EvalsView-B-z_KLLW.js","assets/EvalsView-CUNJ1TLc.css","assets/NodesView-Hjxwv7rE.js","assets/NodesView-DT4pXowv.css","assets/ChatView-DKstOyUm.js","assets/ChatView-DwJAd5G1.css","assets/SkillsView-COs7muvr.js","assets/SkillsView-Cytf009Z.css","assets/MemoryView-CRbaCcG_.js","assets/MemoryView-zaXewZzi.css","assets/DevServerView-DQQcGd2N.js","assets/DevServerView-DlZpuAnj.css","assets/StashRecoveryView-BhB_6Fvq.js","assets/StashRecoveryView-B_8WIQEo.css"])))=>i.map(i=>d[i]);
2
2
  import{r as i,j as t,R as ga,a as $a,g as Kg,c as vy}from"./vendor-react-K0fH_qHe.js";import"./vendor-xterm-DzcZoU0P.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))a(r);new MutationObserver(r=>{for(const o of r)if(o.type==="childList")for(const l of o.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&a(l)}).observe(document,{childList:!0,subtree:!0});function s(r){const o={};return r.integrity&&(o.integrity=r.integrity),r.referrerPolicy&&(o.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?o.credentials="include":r.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function a(r){if(r.ep)return;r.ep=!0;const o=s(r);fetch(r.href,o)}})();/**
3
3
  * @license lucide-react v1.7.0 - ISC
4
4
  *
@@ -639,7 +639,7 @@ import{r as i,j as t,R as ga,a as $a,g as Kg,c as vy}from"./vendor-react-K0fH_qH
639
639
  *
640
640
  * This source code is licensed under the ISC license.
641
641
  * See the LICENSE file in the root directory of this source tree.
642
- */const mj=[["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"}]],ls=it("zap",mj),ou="fusion:version-reload",lu="fusion:version-update";let Uu=!0;function zc(e){Uu=e}function hj(){try{if(sessionStorage.getItem(lu))return sessionStorage.removeItem(lu),!0}catch{}return!1}function Hu(e){if(sessionStorage.getItem(ou)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(ou,"1"),!Uu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function pj(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError|Unable to preload (?:CSS|module) for/i.test(n)}function fj(e){return pj(e)?(Hu(`chunk load error: ${e?.message??e}`),!0):!1}async function gj(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}async function bj(){try{const e=new AbortController,n=setTimeout(()=>e.abort(),3e3),s=await fetch("/api/settings",{headers:{Accept:"application/json"},signal:e.signal});clearTimeout(n),s.ok&&(await s.json()).autoReloadOnVersionChange===!1&&(Uu=!1)}catch{}}const xj=6e4;let Fm=0,Bc=!1;async function Uc(){if(!(Bc||document.visibilityState!=="visible")&&!(Date.now()-Fm<xj)){Fm=Date.now(),Bc=!0;try{const e=await gj();if(e&&e!=="1d87d7711-c6fabaa4"){try{sessionStorage.setItem(lu,"1")}catch{}Hu(`build version changed: 1d87d7711-c6fabaa4 -> ${e}`)}}finally{Bc=!1}}}function vj(){bj(),window.setTimeout(()=>sessionStorage.removeItem(ou),5e3),document.addEventListener("visibilitychange",()=>{Uc()}),window.addEventListener("focus",()=>{Uc()}),window.setTimeout(()=>void Uc(),2e3)}class Vo extends i.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!fj(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",a=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(zr,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:a}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Is({children:e,onError:n}){return t.jsx(Vo,{level:"page",onError:n,children:e})}function Ia({children:e,onError:n}){return t.jsx(Vo,{level:"modal",onError:n,children:e})}function yj({children:e,onError:n}){return t.jsx(Vo,{level:"root",onError:n,children:e})}const wj="modulepreload",kj=function(e){return"/"+e},zm={},En=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=c?.nonce||c?.getAttribute("nonce");r=l(s.map(u=>{if(u=kj(u),u in zm)return;zm[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":wj,m||(f.as="script"),f.crossOrigin="",f.href=u,d&&f.setAttribute("nonce",d),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},qu="fn.authToken",Bm="token",jj="fn_token";let vr,Um=!1,Gl=!1;const cu="fn:auth-token-recovery-required";function Nj(){try{const e=window.localStorage.getItem(qu);return e&&e.length>0?e:void 0}catch{return}}function cb(e){try{window.localStorage.setItem(qu,e)}catch{}}function Sj(){if(!(Um||typeof window>"u")){Um=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Bm);if(!n)return;cb(n),e.searchParams.delete(Bm);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Er(){if(vr!==void 0)return vr;const e=Sj();if(e)return vr=e,e;const n=Nj();if(n)return vr=n,n}function Cj(e){vr=e,Gl=!1,cb(e)}function Ej(){vr=void 0,Gl=!1;try{window.localStorage.removeItem(qu)}catch{}}function Hm(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function _j(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Mj(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!_j(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Hm(e.protocol)===Hm(n.protocol);return s&&a&&r}function Aj(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 Fi(e){const n=Er();if(!n||typeof window>"u")return e;const s=Aj(e);return!s||!Mj(s.parsed)?e:(s.parsed.searchParams.set(jj,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function _i(e){const n=Er();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Rj(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Ij(){typeof window>"u"||Gl||(Gl=!0,window.dispatchEvent(new CustomEvent(cu)))}async function Tj(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const a=await n.json();Rj(a)&&Ij()}catch{}}function Pj(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Er();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=Er(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const d=new URL(o,window.location.origin);return d.origin!==window.location.origin?!1:d.pathname.startsWith("/api/")||d.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,a);const c=new Headers(a?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...a,headers:c}).then(d=>(Tj(d),d))}}class Kl extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function $j(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Ms(e){return`/api${e}`}async function I(e,n={}){const s=Ms(e),a=Er(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),_i(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),d=l.includes("application/json");if(l.includes("text/html")||$j(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!d){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new Kl(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function Dj(){return I("/health")}function Lj(){return I("/health/refresh",{method:"POST"})}function _6(){return I("/updates/check")}function Oj(e,n,s,a,r){const o=new URLSearchParams;e!==void 0&&o.set("limit",String(e)),n!==void 0&&o.set("offset",String(n)),s&&o.set("projectId",s),a&&o.set("q",a),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return I(`/tasks${l}`)}async function Ba(e,n){const a=Ms(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:_i({"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 db(e,n,s){const{title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:w,planningModelId:v,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:j,priority:C,source:x,nodeId:N,branch:R,baseBranch:F,githubTracking:E}=e;return Jo(V("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:w,planningModelId:v,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:j,priority:C,source:x,nodeId:N,branch:R,baseBranch:F,githubTracking:E})})}function Us(e,n,s){return I(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Fj(e,n,s,a,r,o,l,c,d){return I(V("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function zj(e,n,s,a){return I(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Bj(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return I(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Uj(e,n){return I(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Hj(e,n){return I(V(`/tasks/${e}/retry`,n),{method:"POST"})}function qj(e,n){return I(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Vj(e,n){return I(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function ub(e,n){return I(V(`/tasks/${e}/pause`,n),{method:"POST"})}function Wj(e,n){return I(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Gj(e,n){return I(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Kj(e,n){return I(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Jj(e){return I(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Yj(e,n){return I(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Qj(e,n){return I(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Xj(e){return I(V("/config",e))}function kc(e){return I(V("/settings",e))}function sl(e,n){return I(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Zj(e){return I(V("/update-check",e))}function M6(e){return I(V("/remote/settings",e))}function A6(e,n){return I(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function R6(e){return I(V("/remote/status",e))}function I6(e){return I(V("/remote/install-cloudflared",e),{method:"POST"})}function T6(e){return I(V("/remote/tunnel/start",e),{method:"POST"})}function P6(e){return I(V("/remote/tunnel/stop",e),{method:"POST"})}function $6(e){return I(V("/remote/tunnel/kill-external",e),{method:"POST"})}function D6(e){return I(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function L6(e,n){return I(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function mb(e,n,s){const a=new URLSearchParams;e&&a.set("format",e),a.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&a.set("ttlMs",String(s));const r=a.toString();return r?`?${r}`:""}function O6(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=mb(null,s,a);return I(V(`/remote/url${r}`,n))}function F6(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=mb(e,a,r);return I(V(`/remote/qr${o}`,s))}function z6(e){return I(V("/memory",e))}function B6(e,n){return I(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function U6(e){return I(V("/memory/files",e))}function H6(e,n){const s=`path=${encodeURIComponent(e)}`;return I(V(`/memory/file?${s}`,n))}function q6(e,n,s){return I(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function V6(e,n){let s,a=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:a=r}return I(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function W6(e){return I(V("/memory/dream",e),{method:"POST"})}function G6(e){return I(V("/memory/insights",e))}function K6(e,n){return I(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function J6(e){return I(V("/memory/extract",e),{method:"POST"})}function Y6(e){return I(V("/memory/audit",e))}function Q6(e){return I(V("/memory/stats",e))}function X6(e){return I(V("/memory/backend",e))}function Z6(e){return I(V("/memory/install-qmd",e),{method:"POST"})}function e3(e,n){return I(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function na(){return I("/settings/global")}function Bn(e){return I("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function t3(e){return I(V("/settings/scopes",e))}function n3(e){return I(V("/settings/pi-extensions",e))}function s3(e,n){return I(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function i3(e,n,s){return I(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function a3(){return I("/pi-settings")}async function r3(e){return I("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function o3(e){return I("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function l3(e){return I(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function jc(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ms(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:_i(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function eN(e,n,s){return I(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function qm(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Ms(o),{headers:_i()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),d=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,u=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:d,hasMore:u}}function tN(e,n,s,a){return I(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function nN(e,n,s){return I(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function sN(e,n){return I(V(`/tasks/${e}/documents`,n))}function iN(e,n,s){return I(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function c3(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const a=s.toString(),r=`/documents${a?`?${a}`:""}`;return I(V(r,n))}function d3(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return I(V(r,e))}function Vm(e,n,s,a,r){return I(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function aN(e,n,s){return I(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function rN(e,n,s){return I(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function oN(e,n,s){return I(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function lN(e,n){return I(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function cN(e,n,s){return I(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ws(){return I("/models")}function dN(){return I("/usage")}function uN(){return I("/providers/claude-cli/status")}function mN(){return I("/system/fn-binary/status")}function hN(){return I("/system/fn-binary/install",{method:"POST"})}function pN(){return I("/providers/droid-cli/status")}function fN(){return I("/providers/cursor-cli/status")}function gN(){return I("/providers/llama-cpp/status")}async function u3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/hermes/status${n}`)}async function m3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await I(`/providers/hermes/profiles${n}`)).profiles??[]}async function h3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/openclaw/status${n}`)}async function p3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),I(`/providers/paperclip/status?${n.toString()}`)}async function f3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function g3(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function b3(e){return I("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function x3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function v3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await I(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function y3(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await I(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function w3(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function bN(e){return I("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function xN(e){return I("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function vN(e){return I("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function yN(e){return I("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function wN(){const n=(await I("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function kN(e){return I("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function k3(e,n){const s=n,a={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function j3(e){return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function jN(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return kN({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function Po(){return I("/auth/status")}function NN(e){return I("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function SN(e,n){return I("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function CN(e){return I("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function EN(e){return I("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function _N(e,n){return I("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function MN(e){return I("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function AN(e,n,s,a){return I("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function RN(e,n,s,a){return I(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function IN(e,n,s){return I("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function TN(e,n,s,a){return I(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function PN(e){return I(V("/git/remotes",e))}function $N(e){return I(V("/git/remotes/detailed",e))}function DN(e,n,s){return I(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function LN(e,n){return I(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ON(e,n,s){return I(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function FN(e,n,s){return I(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function zN(e,n,s){return I(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function BN(e,n){return I(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function UN(e,n){return(await I(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function il(e,n,s,a){return I(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Wm(e,n){return I(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function HN(e){return I(V("/terminal/sessions",e))}function ji(e){return I(V("/git/status",e))}function qN(e,n){const s=e?`?limit=${e}`:"";return I(V(`/git/commits${s}`,n))}function Jl(e,n){return I(V(`/git/commits/${e}/diff`,n))}function VN(e){return I(V("/git/commits/ahead",e))}function WN(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return I(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function Xr(e){return I(V("/git/branches",e))}function GN(e,n,s){const a=`?limit=${n}`;return I(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function KN(e){return I(V("/git/worktrees",e))}function JN(e,n,s){return I(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function YN(e,n){return I(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Gm(e,n,s){const a=n?"?force=true":"";return I(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function QN(e,n){return I(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function XN(e,n){const s=typeof e=="string"?void 0:e;return I(V("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function ZN(e){return I(V("/git/push",e),{method:"POST"})}function al(e){return I(V("/git/stashes",e))}function eS(e,n){return I(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function tS(e,n,s){return I(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function nS(e,n){return I(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function sS(e,n){return I(V(`/git/stashes/${e}/diff`,n))}function iS(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),I(V(`/git/diff/file?${a.toString()}`,s))}function cr(e){return I(V("/git/changes",e))}function Km(e,n){return I(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function aS(e,n){return I(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Jm(e,n){return I(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function rS(e,n){return I(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function oS(e){return I(V("/workspaces",e))}function lS(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),I(`/files?${a.toString()}`)}function cS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function dS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function uS(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),I(`/files/search?${a.toString()}`)}function mS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function hS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function pS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),I(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function fS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function hb(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function gS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function bS(e,n,s){return I(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function xS(e,n,s,a,r){return I(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function Ym(e,n,s,a){return I(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function vS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function yS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function wS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function pb(e,n,s){return I(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function N3(e,n,s,a){return I(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function S3(e,n,s){return I(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function C3(e,n){return I(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function kS(e,n,s){return I(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function jS(e,n,s){return I(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function NS(e,n,s){return I(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const du=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(du))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function SS(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Br(e,n,s={}){const a=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,d=null,u=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const w=Number.parseInt(g,10);return Number.isFinite(w)?d!==null&&w<=d?!1:(d=w,!0):!0},h=()=>{if(o)return;const p=SS(e,d),g=new EventSource(Fi(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=w=>{const v=w;m(v)&&n.onMessage?.(v)};for(const[w,v]of Object.entries(n.events??{}))g.addEventListener(w,b=>{const y=b;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){u||(u=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=a){s.onFatalError?.("Connection lost");return}u=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),du.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return du.add(f),f}function Qm(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,a=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:a,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${a} (${l})`}}function _r(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",a=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:a,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:a,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function CS(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 ES(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>CS(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function _S(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,a=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((u,m)=>({id:m+1,text:u,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(u=>u.id>r).slice(0,s),totalLines:o};const c=Math.max(o-a,0),d=Math.max(c-s,0);return{lines:l.slice(d,c),totalLines:o}}function Xm(e){return Array.isArray(e)?e.map(Qm):(e.candidates??[]).map(Qm)}async function MS(e){try{const n=await I(V("/dev-server/candidates",e));return Xm(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await I(V("/dev-server/detect",e));return Xm(s)}throw n}}function Vu(e){return I(V("/dev-server/status",e)).then(_r)}async function E3(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const a=s.size>0?`?${s.toString()}`:"";try{const r=await I(V(`/dev-server/logs/history${a}`,n));return ES(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Vu(n);return _S(o.logs,e)}throw r}}function AS(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return I(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(_r)}function RS(e){return I(V("/dev-server/stop",e),{method:"POST"}).then(_r)}function IS(e){return I(V("/dev-server/restart",e),{method:"POST"}).then(_r)}async function TS(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await I(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return _r(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await I(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return _r(r)}throw a}}function _3(e){return Ms(V("/dev-server/logs/stream",e))}async function M3(e){try{return(await I(V("/devserver",e))).sessions??[]}catch{try{const n=await Vu(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function A3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Vu(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function R3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await AS({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function I3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await RS(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function T3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await IS(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function P3(e,n,s){try{const a=await I(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await TS({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function $3(e){try{return(await I(V("/devserver/detect",e))).candidates??[]}catch{try{return(await MS(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function D3(e,n){return Ms(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Wo(e,n,s=25e3){const a=setInterval(()=>{_0(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function PS(e,n){return Ms(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function $S(e,n){return Ms(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function L3(e,n,s,a){const r=$S(e,n),o=Br(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function DS(e,n,s,a){const r=PS(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Go(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const a=s.toString();return a?`${e}?${a}`:e}function LS(e){return I(Go("/routines",e))}function OS(e,n){return I(Go("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Zm(e,n,s){return I(Go(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function FS(e,n){await I(Go(`/routines/${e}`,n),{method:"DELETE"})}function zS(e,n){return I(Go(`/routines/${e}/trigger`,n),{method:"POST"})}function eh(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity${s}`)}function BS(e){const n=V("/activity",e);return I(n,{method:"DELETE"})}function Ko(e){return I(V("/workflow-steps",e))}function th(e,n){return I(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function US(e,n,s){return I(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function HS(e,n){return I(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function nh(e,n){return I(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function qS(e,n){return I(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function VS(){return I("/workflow-step-templates")}function WS(){return I("/plugin-workflow-step-templates")}function GS(e,n){return I(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function $o(e){return I(V("/scripts",e))}function KS(e,n,s){return I(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function JS(e,n){return I(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function fb(e,n,s){return(await I(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const rl={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 gb(e){if(!(e instanceof Error))return rl.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?rl.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?rl.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:rl.NETWORK}function YS(e,n){return I(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function QS(e,n,s){return I(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function XS(e,n){return Ms(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function ZS(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Br(XS(e,n),{onOpen:()=>{l(),r=Wo(e,n)},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},subtasks:d=>{try{s.onSubtasks?.(JSON.parse(d.data))}catch(u){console.error("[subtasks] Failed to parse subtasks event:",u)}},error:d=>{try{const u=JSON.parse(d.data),m=typeof u=="string"&&u.length>0?u:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{l(),s.onError?.(d)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function e1(e,n,s,a,r){return I(V("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,...r?.branch!==void 0?{branch:r.branch}:{},...r?.baseBranch!==void 0?{baseBranch:r.baseBranch}:{},...r?.branchSelection?{branchSelection:r.branchSelection}:{},...r?.branchAssignment?{branchAssignment:r.branchAssignment}:{},subtasks:n.map(o=>({tempId:o.id,title:o.title,description:o.description,size:o.suggestedSize,dependsOn:o.dependsOn}))})})}function bb(e,n,s){return I(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 t1(e,n,s){if(!n||n===s)return e;const a="/api",r=e.startsWith(a)?e.slice(a.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function Jo(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=t1(e,s,a);return I(o,r)}function Ur(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/agents${a}`)}function uu(e,n){return I(V(`/agents/${encodeURIComponent(e)}`,n))}function n1(e,n){return I(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function s1(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function O3(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ms(V(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:_i(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function F3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function z3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function B3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function U3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function H3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function q3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function V3(e,n,s){const a=`path=${encodeURIComponent(n)}`;return I(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function W3(e,n,s,a){return I(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function i1(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function a1(e,n){return I(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function G3(e,n,s){const a=new URLSearchParams;n!==void 0&&a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/runs${r}`)}function K3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function J3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function Y3(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return I(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function Q3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function r1(e){return I(V("/agents/stats",e))}function X3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function Z3(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return I(`/agents/org-tree${a?`?${a}`:""}`)}function e5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function sh(e,n,s){return I(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function xb(e){return{reviewState:{source:e.mode,summary:e.summary??void 0,items:e.items.map(n=>({id:n.itemId,body:n.body,author:{login:n.author},createdAt:n.createdAt??new Date(0).toISOString(),updatedAt:n.updatedAt??void 0,path:n.filePath,threadId:n.threadId,htmlUrl:n.url,state:n.reviewState??void 0,isResolved:n.isResolved})),addressing:[],lastRefreshedAt:e.fetchedAt??void 0,refreshStatus:"ready",refreshSource:"initial-load"},automationStatus:null}}async function o1(e,n){const s=await I(V(`/tasks/${encodeURIComponent(e)}/review`,n));return xb(s)}async function l1(e,n){const s=await I(V(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return xb(s)}function c1(e,n,s){return I(V(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function t5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function n5(){return I("/agents/companies")}function s5(e,n){return I(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function i5(e,n){return I(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function a5(e,n){return I(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function r5(e){return I(V("/backups",e))}function o5(e){return I(V("/backups",e),{method:"POST"})}function l5(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return I(a)}function c5(e,n,s){return I(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function d1(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function ih(){return I("/projects/across-nodes")}function Yl(){return I("/nodes")}function d5(){return I("/docker/nodes")}function u5(e){return I(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function m5(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return I(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function h5(e){return I("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function u1(e){return I("/nodes",{method:"POST",body:JSON.stringify(e)})}function m1(e){return I("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function h1(e,n){return I(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function p1(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config`)}function f1(e,n){return I(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function g1(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function ah(e){return I(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function b1(e){const n=await I(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}async function p5(){return I("/mesh/state")}function f5(e,n,s,a){const r=s&&s!==a?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=Er();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return I(d)}function x1(e){return I("/projects",{method:"POST",body:JSON.stringify(e)})}function vb(e){return I(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function v1(e,n,s){return I(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function rh(e){return I(`/projects/${encodeURIComponent(e)}/health`)}function y1(e){return I(V("/executor/stats",e))}function w1(e){return I(V("/system-stats",e))}function k1(e){return I(V("/kill-vitest",e),{method:"POST"})}function oh(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity-feed${s}`)}function j1(e){return I(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function N1(e){return I(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function g5(){return I("/global-concurrency")}function b5(e){return I("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function S1(e,n){return I(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function yb(e,n,s){const a=new URLSearchParams;n&&a.set("worktree",n),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function C1(e,n){return I(V(`/tasks/${encodeURIComponent(e)}/commit-associations`,n))}function E1(e){return I(V("/missions",e))}function _1(e,n){return I(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function wb(e,n){return I(V(`/missions/${encodeURIComponent(e)}`,n))}function M1(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function A1(e,n){return I(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function R1(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function I1(e){return I(V("/missions/health",e))}function T1(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function P1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $1(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function D1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function L1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function O1(e,n){return I(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function F1(e,n){return I(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function z1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function B1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function U1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function H1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function q1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function V1(e,n,s,a,r){return I(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function W1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify({})})}function Hc(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function G1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function K1(e,n,s){return I(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function J1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function Y1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Q1(e,n){return I(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function qc(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function lh(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function X1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function ch(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function Z1(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function e0(e,n){return I(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function t0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function n0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function s0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function i0(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function a0(e,n,s){return I(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function r0(e,n,s,a){return I(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function o0(e,n,s){return I(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function kb(e,n,s){return I(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}async function l0(e){const n=e?`?${new URLSearchParams({projectId:e}).toString()}`:"";return(await I(`/missions/interview/drafts${n}`)).drafts??[]}function c0(e,n,s){return I(V(`/missions/interview/drafts/${encodeURIComponent(e)}/discard`,n),{method:"POST",body:JSON.stringify({tabId:s})})}function d0(e,n,s,a){return I(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function u0(e,n,s,a){const r=Ms(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Yo(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Qo(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function m0(e,n){return I(Yo(e,"/start",n),{method:"POST"})}function h0(e,n,s,a){return I(Yo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function p0(e,n,s,a){const r=Ms(Yo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function f0(e,n,s){return I(Yo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function g0(e,n){return I(Yo(e,"/skip",n),{method:"POST"})}function b0(e,n){return I(Qo(e,"/start",n),{method:"POST"})}function x0(e,n,s,a){return I(Qo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function v0(e,n,s,a){const r=Ms(Qo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function y0(e,n,s){return I(Qo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function w0(e,n){return I(Qo(e,"/skip",n),{method:"POST"})}async function k0(e,n){try{return await I(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function x5(e){return I(V("/todos",e))}function v5(e,n){const s={title:e};return I(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function y5(e,n,s){const a={title:n};return I(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function w5(e,n){return I(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function k5(e,n,s){const a={text:n};return I(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function j5(e,n,s){const a=n;return I(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function N5(e,n){return I(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function S5(e,n,s){return I(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Mr(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Wu(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const a=s.toString(),r=await fetch(Ms(`/ai-sessions${a?`?${a}`:""}`),{headers:_i()});return r.ok?(await r.json()).sessions??[]:[]}async function j0(e){return I(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function N0(e){return I(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Di(e){const n=await fetch(Ms(`/ai-sessions/${encodeURIComponent(e)}`),{headers:_i()});return n.ok?n.json():null}async function S0(e,n){const s=await I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function C0(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function E0(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function jb(e){await fetch(Ms(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:_i()})}function _0(e,n){return I(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function M0(e,n,s){return I(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function A0(e,n){return I(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function R0(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/messages/inbox${a}`)}function I0(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/messages/outbox${a}`)}function Nb(e){return I(V("/messages/unread-count",e))}function T0(e,n){return I(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function P0(e,n){return I(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function $0(e){return I(V("/messages/read-all",e),{method:"POST"})}function D0(e,n){return I(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function L0(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return I(V(a,s))}function O0(e,n){return I(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function F0(e){return I(V("/agents/mailbox/all",e))}function ol(e,n){const s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/approvals${a}`)}function dh(e,n){return I(V(`/approvals/${encodeURIComponent(e)}`,n))}function z0(e,n,s){return I(V(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function C5(e,n,s){const a=new URLSearchParams;a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function E5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function _5(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/performance${r}`)}function M5(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.category&&a.set("category",n.category),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function A5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function R5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function I5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function T5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function P5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function $5(e){return I(V("/plugins",e))}async function D5(e,n){return I(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function L5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function O5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function F5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function z5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function B5(e,n,s){return I(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function U5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function H5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function q5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function V5(e,n,s){return I(V(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function W5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function B0(e){return I(V("/plugins/ui-slots",e))}async function U0(e){return I(V("/plugins/dashboard-views",e))}async function G5(e){return I(V("/plugins/runtimes",e))}async function H0(e){return(await I(V("/skills/discovered",e))).skills}async function K5(e,n,s){return I(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function J5(e,n,s){const a=new URLSearchParams;e&&a.set("q",e),a.set("limit",String(n));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/skills/catalog${r}`,s))}async function Y5(e,n){return(await I(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function uh(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return I(`/chat/sessions${a?`?${a}`:""}`)}async function q0(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const a=e.modelProvider?.trim(),r=e.modelId?.trim();if(a&&!r||!a&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),a&&r&&(o.set("modelProvider",a),o.set("modelId",r)),{session:(await I(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function V0(e,n){return I(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function W0(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function Q5(e,n,s){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function X5(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Zr(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return I(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Z5(e={},n){const s=new URLSearchParams;n&&s.set("projectId",n),e.status&&s.set("status",e.status),e.agentId&&s.set("agentId",e.agentId);const a=s.toString();return I(`/chat/rooms${a?`?${a}`:""}`)}function e8(e,n){const s={...e,...n?{projectId:n}:{}};return I(V("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function t8(e,n){return I(V(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function n8(e,n){return I(V(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function s8(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return I(V(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function i8(e,n,s){return I(V(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function G0(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function K0(e){if(!e||typeof e!="object")return null;const n=e,s=typeof n.summary=="string"?n.summary.trim():"";if(!s)return null;const a=(()=>{const r=n.reference;if(!r||typeof r!="object")return;const o=r,l=typeof o.kind=="string"?o.kind.trim():"",c=typeof o.id=="string"?o.id.trim():"";if(!(!l||!c))return{kind:l,id:c,...typeof o.label=="string"&&o.label.trim()?{label:o.label.trim()}:{}}})();return{summary:s,...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...a?{reference:a}:{}}}function Sb(e){try{const n=JSON.parse(e),s=K0(n);return s||(n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:e||"Stream error")}catch{return e||"Stream error"}}function J0(e,n,s,a,r,o){const l=Ms(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1,m=!1;const h=Math.max(1e3,6e4);let f=null;const p=()=>{f&&(clearTimeout(f),f=null)},g=()=>{m||(m=!0,p())},w=(v,b)=>{if(v)switch(g(),v){case"thinking":try{s.onThinking?.(JSON.parse(b))}catch{s.onThinking?.(b)}break;case"text":try{s.onText?.(JSON.parse(b))}catch{s.onText?.(b)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(b))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(b))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(b))}catch{}break;case"done":u=!0;try{const y=JSON.parse(b);s.onDone?.({messageId:typeof y.messageId=="string"?y.messageId:"",...y.message&&typeof y.message=="object"?{message:y.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0,s.onError?.(Sb(b));break}};return(async()=>{try{const v=Array.isArray(a)&&a.length>0,b=v?(()=>{const E=new FormData;return E.append("content",n),a.forEach(_=>E.append("attachments",_)),E})():JSON.stringify({content:n}),y=await fetch(l,{method:"POST",headers:v?_i():_i({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!y.ok){const E=await y.text();let _=`Request failed: ${y.status}`;try{_=JSON.parse(E).error||_}catch{}s.onError?.(_);return}if(!y.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),f=setTimeout(()=>{u||d||m||(u=!0,s.onError?.("Timed out waiting for first response event"),c.abort())},h);const S=y.body.getReader(),j=new TextDecoder;let C="",x="",N=[];const R=(E,_=!1)=>{C+=E;const K=C.split(`
642
+ */const mj=[["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"}]],ls=it("zap",mj),ou="fusion:version-reload",lu="fusion:version-update";let Uu=!0;function zc(e){Uu=e}function hj(){try{if(sessionStorage.getItem(lu))return sessionStorage.removeItem(lu),!0}catch{}return!1}function Hu(e){if(sessionStorage.getItem(ou)){console.warn("[versionCheck] reload already attempted, suppressing",e);return}if(sessionStorage.setItem(ou,"1"),!Uu){console.info("[versionCheck] auto-reload disabled by setting, skipping reload:",e);return}console.info("[versionCheck] reloading:",e),window.location.reload()}function pj(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return/Failed to fetch dynamically imported module|error loading dynamically imported module|Importing a module script failed|is not a valid JavaScript MIME type|ChunkLoadError|Unable to preload (?:CSS|module) for/i.test(n)}function fj(e){return pj(e)?(Hu(`chunk load error: ${e?.message??e}`),!0):!1}async function gj(){try{const e=await fetch("/version.json",{cache:"no-store",headers:{Accept:"application/json"}});if(!e.ok||!(e.headers.get("content-type")??"").includes("application/json"))return null;const s=await e.json();return typeof s.version=="string"?s.version:null}catch{return null}}async function bj(){try{const e=new AbortController,n=setTimeout(()=>e.abort(),3e3),s=await fetch("/api/settings",{headers:{Accept:"application/json"},signal:e.signal});clearTimeout(n),s.ok&&(await s.json()).autoReloadOnVersionChange===!1&&(Uu=!1)}catch{}}const xj=6e4;let Fm=0,Bc=!1;async function Uc(){if(!(Bc||document.visibilityState!=="visible")&&!(Date.now()-Fm<xj)){Fm=Date.now(),Bc=!0;try{const e=await gj();if(e&&e!=="681770fc1-ac2f0f6c"){try{sessionStorage.setItem(lu,"1")}catch{}Hu(`build version changed: 681770fc1-ac2f0f6c -> ${e}`)}}finally{Bc=!1}}}function vj(){bj(),window.setTimeout(()=>sessionStorage.removeItem(ou),5e3),document.addEventListener("visibilitychange",()=>{Uc()}),window.addEventListener("focus",()=>{Uc()}),window.setTimeout(()=>void Uc(),2e3)}class Vo extends i.Component{constructor(n){super(n),this.state={hasError:!1,error:null}}static getDerivedStateFromError(n){return{hasError:!0,error:n}}componentDidCatch(n,s){console.error("[ErrorBoundary]",n,s),!fj(n)&&this.props.onError?.(n,s)}resetErrorBoundary=()=>{this.setState({hasError:!1,error:null})};render(){if(!this.state.hasError)return this.props.children;if(this.props.fallback)return this.props.fallback;const n=this.props.level??"page",a=n==="modal"?"This section encountered an error":"Something went wrong";return t.jsxs("div",{className:`error-boundary error-boundary--${n}`,children:[t.jsx("div",{className:"error-boundary__icon",children:t.jsx(zr,{size:40})}),t.jsx("div",{className:"error-boundary__title",children:a}),this.state.error&&t.jsx("pre",{className:"error-boundary__message",children:this.state.error.message}),t.jsxs("div",{className:"error-boundary__actions",children:[t.jsx("button",{className:"btn btn-primary",onClick:this.resetErrorBoundary,children:"Retry"}),t.jsx("button",{className:"btn",onClick:()=>window.location.reload(),children:"Reload page"})]})]})}}function Is({children:e,onError:n}){return t.jsx(Vo,{level:"page",onError:n,children:e})}function Ia({children:e,onError:n}){return t.jsx(Vo,{level:"modal",onError:n,children:e})}function yj({children:e,onError:n}){return t.jsx(Vo,{level:"root",onError:n,children:e})}const wj="modulepreload",kj=function(e){return"/"+e},zm={},En=function(n,s,a){let r=Promise.resolve();if(s&&s.length>0){let l=function(u){return Promise.all(u.map(m=>Promise.resolve(m).then(h=>({status:"fulfilled",value:h}),h=>({status:"rejected",reason:h}))))};document.getElementsByTagName("link");const c=document.querySelector("meta[property=csp-nonce]"),d=c?.nonce||c?.getAttribute("nonce");r=l(s.map(u=>{if(u=kj(u),u in zm)return;zm[u]=!0;const m=u.endsWith(".css"),h=m?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${u}"]${h}`))return;const f=document.createElement("link");if(f.rel=m?"stylesheet":wj,m||(f.as="script"),f.crossOrigin="",f.href=u,d&&f.setAttribute("nonce",d),document.head.appendChild(f),m)return new Promise((p,g)=>{f.addEventListener("load",p),f.addEventListener("error",()=>g(new Error(`Unable to preload CSS for ${u}`)))})}))}function o(l){const c=new Event("vite:preloadError",{cancelable:!0});if(c.payload=l,window.dispatchEvent(c),!c.defaultPrevented)throw l}return r.then(l=>{for(const c of l||[])c.status==="rejected"&&o(c.reason);return n().catch(o)})},qu="fn.authToken",Bm="token",jj="fn_token";let vr,Um=!1,Gl=!1;const cu="fn:auth-token-recovery-required";function Nj(){try{const e=window.localStorage.getItem(qu);return e&&e.length>0?e:void 0}catch{return}}function cb(e){try{window.localStorage.setItem(qu,e)}catch{}}function Sj(){if(!(Um||typeof window>"u")){Um=!0;try{const e=new URL(window.location.href),n=e.searchParams.get(Bm);if(!n)return;cb(n),e.searchParams.delete(Bm);const s=e.pathname+(e.search?e.search:"")+e.hash;return window.history.replaceState(window.history.state,"",s),n}catch{return}}}function Er(){if(vr!==void 0)return vr;const e=Sj();if(e)return vr=e,e;const n=Nj();if(n)return vr=n,n}function Cj(e){vr=e,Gl=!1,cb(e)}function Ej(){vr=void 0,Gl=!1;try{window.localStorage.removeItem(qu)}catch{}}function Hm(e){return e==="ws:"?"http:":e==="wss:"?"https:":e}function _j(e){return e==="http:"||e==="https:"||e==="ws:"||e==="wss:"}function Mj(e){if(typeof window>"u")return!1;const n=new URL(window.location.origin);if(!_j(e.protocol))return!1;const s=e.hostname===n.hostname,a=e.port===n.port,r=Hm(e.protocol)===Hm(n.protocol);return s&&a&&r}function Aj(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 Fi(e){const n=Er();if(!n||typeof window>"u")return e;const s=Aj(e);return!s||!Mj(s.parsed)?e:(s.parsed.searchParams.set(jj,n),s.preserveRelativePath?`${s.parsed.pathname}${s.parsed.search}${s.parsed.hash}`:s.parsed.toString())}function _i(e){const n=Er();if(!n)return e;const s=new Headers(e??{});return s.has("Authorization")||s.set("Authorization",`Bearer ${n}`),s}function Rj(e){if(!e||typeof e!="object")return!1;const n=e;return n.error==="Unauthorized"&&n.message==="Valid bearer token required"}function Ij(){typeof window>"u"||Gl||(Gl=!0,window.dispatchEvent(new CustomEvent(cu)))}async function Tj(e){if(e.status===401)try{const n=e.clone();if(!(n.headers.get("content-type")??"").toLowerCase().includes("application/json"))return;const a=await n.json();Rj(a)&&Ij()}catch{}}function Pj(){if(typeof window>"u"||window.__fnAuthFetchInstalled)return;window.__fnAuthFetchInstalled=!0,Er();const e=window.fetch.bind(window);window.fetch=function(s,a){const r=Er(),o=typeof s=="string"?s:s instanceof URL?s.toString():s.url;if(!(()=>{try{const d=new URL(o,window.location.origin);return d.origin!==window.location.origin?!1:d.pathname.startsWith("/api/")||d.pathname==="/api"}catch{return o.startsWith("/api/")||o==="/api"}})())return e(s,a);const c=new Headers(a?.headers??(s instanceof Request?s.headers:void 0));return r&&!c.has("Authorization")&&c.set("Authorization",`Bearer ${r}`),e(s,{...a,headers:c}).then(d=>(Tj(d),d))}}class Kl extends Error{status;details;constructor(n,s,a){super(n),this.name="ApiRequestError",this.status=s,this.details=a}}function $j(e){const n=e.trim();return n.startsWith("<!DOCTYPE")||n.startsWith("<html")||n.startsWith("<HTML")}function Ms(e){return`/api${e}`}async function I(e,n={}){const s=Ms(e),a=Er(),r=(()=>{if(a){const f=new Headers(n.headers??{});return f.has("Content-Type")||f.set("Content-Type","application/json"),_i(f)}if(!n.headers)return{"Content-Type":"application/json"};const h=new Headers(n.headers);return h.has("Content-Type")||h.set("Content-Type","application/json"),Object.fromEntries(h.entries())})(),o=await fetch(s,{...n,headers:r});if(o.status===204){if(!o.ok)throw new Error(`Request failed for ${s}: ${o.status} ${o.statusText}`);return}const l=o.headers.get("content-type")??"",c=await o.text(),d=l.includes("application/json");if(l.includes("text/html")||$j(c))throw new Error(`API returned HTML instead of JSON for ${s}. The endpoint may not be properly configured. (${o.status} ${o.statusText})`);if(!d){const h=c.length>160?`${c.slice(0,160)}...`:c;throw new Error(`API returned ${l||"an unknown content type"} instead of JSON for ${s}. (${o.status} ${o.statusText})${h?` Response: ${h}`:""}`)}let m;try{m=c?JSON.parse(c):null}catch{throw new Error(`API returned invalid JSON for ${s}. (${o.status} ${o.statusText})`)}if(!o.ok){const h=m;throw new Kl(h?.error||`Request failed for ${s}: ${o.status} ${o.statusText}`,o.status,h?.details)}return m}function Dj(){return I("/health")}function Lj(){return I("/health/refresh",{method:"POST"})}function _6(){return I("/updates/check")}function Oj(e,n,s,a,r){const o=new URLSearchParams;e!==void 0&&o.set("limit",String(e)),n!==void 0&&o.set("offset",String(n)),s&&o.set("projectId",s),a&&o.set("q",a),r&&o.set("includeArchived","1");const l=o.size>0?`?${o.toString()}`:"";return I(`/tasks${l}`)}async function Ba(e,n){const a=Ms(V(`/tasks/${e}`,n));for(let r=1;r<=2;r++){const o=await fetch(a,{headers:_i({"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 db(e,n,s){const{title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:w,planningModelId:v,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:j,priority:C,source:x,nodeId:N,branch:R,baseBranch:F,githubTracking:E}=e;return Jo(V("/tasks",n),{method:"POST",nodeId:s?.transportNodeId,localNodeId:s?.localNodeId,body:JSON.stringify({title:a,description:r,column:o,dependencies:l,breakIntoSubtasks:c,enabledWorkflowSteps:d,assignedAgentId:u,modelPresetId:m,modelProvider:h,modelId:f,validatorModelProvider:p,validatorModelId:g,planningModelProvider:w,planningModelId:v,thinkingLevel:b,summarize:y,reviewLevel:S,executionMode:j,priority:C,source:x,nodeId:N,branch:R,baseBranch:F,githubTracking:E})})}function Us(e,n,s){return I(V(`/tasks/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function Fj(e,n,s,a,r,o,l,c,d){return I(V("/tasks/batch-update-models",d),{method:"POST",body:JSON.stringify({taskIds:e,modelProvider:n,modelId:s,validatorModelProvider:a,validatorModelId:r,planningModelProvider:o,planningModelId:l,nodeId:c})})}function zj(e,n,s,a){return I(V(`/tasks/${e}/move`,s),{method:"POST",body:JSON.stringify({column:n,...typeof a=="object"&&a?.preserveProgress?{preserveProgress:!0}:{}})})}function Bj(e,n,s){const a=new URLSearchParams;s?.removeDependencyReferences&&a.set("removeDependencyReferences","true");const r=a.size>0?`?${a.toString()}`:"";return I(V(`/tasks/${e}${r}`,n),{method:"DELETE"})}function Uj(e,n){return I(V(`/tasks/${e}/merge`,n),{method:"POST"})}function Hj(e,n){return I(V(`/tasks/${e}/retry`,n),{method:"POST"})}function qj(e,n){return I(V(`/tasks/${e}/reset`,n),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({confirm:!0})})}function Vj(e,n){return I(V(`/tasks/${e}/duplicate`,n),{method:"POST"})}function ub(e,n){return I(V(`/tasks/${e}/pause`,n),{method:"POST"})}function Wj(e,n){return I(V(`/tasks/${e}/unpause`,n),{method:"POST"})}function Gj(e,n){return I(V(`/tasks/${e}/archive`,n),{method:"POST"})}function Kj(e,n){return I(V(`/tasks/${e}/unarchive`,n),{method:"POST"})}function Jj(e){return I(V("/tasks/archive-all-done",e),{method:"POST"}).then(n=>n.archived)}function Yj(e,n){return I(V(`/tasks/${e}/approve-plan`,n),{method:"POST"})}function Qj(e,n){return I(V(`/tasks/${e}/reject-plan`,n),{method:"POST"})}function Xj(e){return I(V("/config",e))}function kc(e){return I(V("/settings",e))}function sl(e,n){return I(V("/settings",n),{method:"PUT",body:JSON.stringify(e)})}function Zj(e){return I(V("/update-check",e))}function M6(e){return I(V("/remote/settings",e))}function A6(e,n){return I(V("/remote/settings",n),{method:"PUT",body:JSON.stringify(e)})}function R6(e){return I(V("/remote/status",e))}function I6(e){return I(V("/remote/install-cloudflared",e),{method:"POST"})}function T6(e){return I(V("/remote/tunnel/start",e),{method:"POST"})}function P6(e){return I(V("/remote/tunnel/stop",e),{method:"POST"})}function $6(e){return I(V("/remote/tunnel/kill-external",e),{method:"POST"})}function D6(e){return I(V("/remote/token/persistent/regenerate",e),{method:"POST"})}function L6(e,n){return I(V("/remote/token/short-lived/generate",n),{method:"POST",body:JSON.stringify({ttlMs:e})})}function mb(e,n,s){const a=new URLSearchParams;e&&a.set("format",e),a.set("tokenType",n),n==="short-lived"&&typeof s=="number"&&Number.isFinite(s)&&a.set("ttlMs",String(s));const r=a.toString();return r?`?${r}`:""}function O6(e={}){const{projectId:n,tokenType:s="persistent",ttlMs:a}=e,r=mb(null,s,a);return I(V(`/remote/url${r}`,n))}function F6(e="text",n={}){const{projectId:s,tokenType:a="persistent",ttlMs:r}=n,o=mb(e,a,r);return I(V(`/remote/qr${o}`,s))}function z6(e){return I(V("/memory",e))}function B6(e,n){return I(V("/memory",n),{method:"PUT",body:JSON.stringify({content:e})})}function U6(e){return I(V("/memory/files",e))}function H6(e,n){const s=`path=${encodeURIComponent(e)}`;return I(V(`/memory/file?${s}`,n))}function q6(e,n,s){return I(V("/memory/file",s),{method:"PUT",body:JSON.stringify({path:e,content:n})})}function V6(e,n){let s,a=n;if(n!==void 0)s=e;else if(typeof e=="string"&&e.trim().length>0){const r=e.trim();r.includes("/")||r.endsWith(".md")||r.startsWith(".")?s=r:a=r}return I(V("/memory/compact",a),{method:"POST",body:JSON.stringify(s?{path:s}:{})})}function W6(e){return I(V("/memory/dream",e),{method:"POST"})}function G6(e){return I(V("/memory/insights",e))}function K6(e,n){return I(V("/memory/insights",n),{method:"PUT",body:JSON.stringify({content:e})})}function J6(e){return I(V("/memory/extract",e),{method:"POST"})}function Y6(e){return I(V("/memory/audit",e))}function Q6(e){return I(V("/memory/stats",e))}function X6(e){return I(V("/memory/backend",e))}function Z6(e){return I(V("/memory/install-qmd",e),{method:"POST"})}function e3(e,n){return I(V("/memory/test",n),{method:"POST",body:JSON.stringify({query:e})})}function na(){return I("/settings/global")}function Bn(e){return I("/settings/global",{method:"PUT",body:JSON.stringify(e)})}function t3(e){return I(V("/settings/scopes",e))}function n3(e){return I(V("/settings/pi-extensions",e))}function s3(e,n){return I(V("/settings/pi-extensions",n),{method:"PUT",body:JSON.stringify({disabledIds:e})})}function i3(e,n,s){return I(V("/settings/test-notification",s),{method:"POST",body:JSON.stringify({providerId:e,...n??{}})})}function a3(){return I("/pi-settings")}async function r3(e){return I("/pi-settings",{method:"PUT",body:JSON.stringify(e)})}async function o3(e){return I("/pi-settings/packages",{method:"POST",body:JSON.stringify({source:e})})}async function l3(e){return I(V("/pi-settings/reinstall-fusion",e),{method:"POST"})}async function jc(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ms(V(`/tasks/${e}/attachments`,s)),{method:"POST",headers:_i(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Upload failed");return o}async function eN(e,n,s){return I(V(`/tasks/${e}/attachments/${n}`,s),{method:"DELETE"})}async function qm(e,n,s){const a=new URLSearchParams;s?.limit!==void 0&&a.set("limit",String(s.limit)),s?.offset!==void 0&&a.set("offset",String(s.offset));const r=a.toString()?`?${a.toString()}`:"",o=V(`/tasks/${e}/logs${r}`,n),l=await fetch(Ms(o),{headers:_i()});if(!l.ok){const m=await l.json().catch(()=>({error:"Failed to fetch agent logs"}));throw new Error(m.error||`HTTP ${l.status}`)}const c=await l.json(),d=l.headers.has("X-Total-Count")?parseInt(l.headers.get("X-Total-Count"),10):c.length,u=l.headers.has("X-Has-More")?l.headers.get("X-Has-More")==="true":!1;return{entries:c,total:d,hasMore:u}}function tN(e,n,s,a){return I(V(`/tasks/${e}/comments/${n}`,a),{method:"PATCH",body:JSON.stringify({text:s})})}function nN(e,n,s){return I(V(`/tasks/${e}/comments/${n}`,s),{method:"DELETE"})}function sN(e,n){return I(V(`/tasks/${e}/documents`,n))}function iN(e,n,s){return I(V(`/tasks/${e}/documents/${n}/revisions`,s))}async function c3(e,n){const s=new URLSearchParams;e?.q&&s.set("q",e.q),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset));const a=s.toString(),r=`/documents${a?`?${a}`:""}`;return I(V(r,n))}function d3(e,n){const s=new URLSearchParams;n?.showHidden&&s.set("showHidden","1");const a=s.toString(),r=`/files/markdown-list${a?`?${a}`:""}`;return I(V(r,e))}function Vm(e,n,s,a,r){return I(V(`/tasks/${e}/documents/${n}`,r),{method:"PUT",body:JSON.stringify({content:s,author:a?.author,metadata:a?.metadata})})}function aN(e,n,s){return I(V(`/tasks/${e}/documents/${n}`,s),{method:"DELETE"})}function rN(e,n,s){return I(V(`/tasks/${e}/steer`,s),{method:"POST",body:JSON.stringify({text:n})})}function oN(e,n,s){return I(V(`/tasks/${e}/spec/revise`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function lN(e,n){return I(V(`/tasks/${e}/spec/rebuild`,n),{method:"POST"})}function cN(e,n,s){return I(V(`/tasks/${e}/refine`,s),{method:"POST",body:JSON.stringify({feedback:n})})}function Ws(){return I("/models")}function dN(){return I("/usage")}function uN(){return I("/providers/claude-cli/status")}function mN(){return I("/system/fn-binary/status")}function hN(){return I("/system/fn-binary/install",{method:"POST"})}function pN(){return I("/providers/droid-cli/status")}function fN(){return I("/providers/cursor-cli/status")}function gN(){return I("/providers/llama-cpp/status")}async function u3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/hermes/status${n}`)}async function m3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return(await I(`/providers/hermes/profiles${n}`)).profiles??[]}async function h3(e){const n=e?.binaryPath?`?binaryPath=${encodeURIComponent(e.binaryPath)}`:"";return I(`/providers/openclaw/status${n}`)}async function p3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),I(`/providers/paperclip/status?${n.toString()}`)}async function f3(e){const n=new URLSearchParams({apiUrl:e.apiUrl});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/companies?${n.toString()}`)).companies??[]}async function g3(e){const n=new URLSearchParams({apiUrl:e.apiUrl,companyId:e.companyId});return e.apiKey&&n.set("apiKey",e.apiKey),(await I(`/providers/paperclip/agents?${n.toString()}`)).agents??[]}async function b3(e){return I("/providers/paperclip/cli-mint-key",{method:"POST",body:JSON.stringify(e)})}async function x3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-status${s?`?${s}`:""}`)}async function v3(e){const n=new URLSearchParams;e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return(await I(`/providers/paperclip/cli-companies${s?`?${s}`:""}`)).companies??[]}async function y3(e){const n=new URLSearchParams({companyId:e.companyId});return e.cliBinaryPath&&n.set("cliBinaryPath",e.cliBinaryPath),e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath),(await I(`/providers/paperclip/cli-agents?${n.toString()}`)).agents??[]}async function w3(e={}){const n=new URLSearchParams;e.cliConfigPath&&n.set("cliConfigPath",e.cliConfigPath);const s=n.toString();return I(`/providers/paperclip/cli-discovery${s?`?${s}`:""}`)}function bN(e){return I("/auth/claude-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function xN(e){return I("/auth/droid-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function vN(e){return I("/auth/cursor-cli",{method:"POST",body:JSON.stringify({enabled:e})})}function yN(e){return I("/auth/llama-cpp",{method:"POST",body:JSON.stringify({enabled:e})})}async function wN(){const n=(await I("/custom-providers")).map(s=>({id:s.id,name:s.name,baseUrl:s.baseUrl,api:s.apiType==="anthropic-compatible"?"anthropic-messages":"openai-completions",apiKey:s.apiKey,models:(s.models??[]).map(a=>({id:a.id,name:a.name}))}));return Object.assign(n,{providers:n})}function kN(e){return I("/custom-providers",{method:"POST",body:JSON.stringify(e)})}function k3(e,n){const s=n,a={...typeof s.name=="string"?{name:s.name}:{},...typeof s.baseUrl=="string"?{baseUrl:s.baseUrl}:{},...typeof s.apiKey=="string"?{apiKey:s.apiKey}:{},...Array.isArray(s.models)?{models:s.models.map(r=>({id:r.id,name:r.name??r.id}))}:{},...s.api?{apiType:s.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible"}:{},..."apiType"in n?{apiType:n.apiType}:{}};return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"PUT",body:JSON.stringify(a)})}function j3(e){return I(`/custom-providers/${encodeURIComponent(e)}`,{method:"DELETE"})}function jN(e){const n=e.api==="anthropic-messages"?"anthropic-compatible":"openai-compatible";return kN({name:e.name?.trim()||e.id,apiType:n,baseUrl:e.baseUrl,apiKey:e.apiKey,models:e.models?.map(s=>({id:s.id,name:s.name??s.id}))})}function Po(){return I("/auth/status")}function NN(e){return I("/auth/login",{method:"POST",body:JSON.stringify({provider:e,origin:window.location.origin})})}function SN(e,n){return I("/auth/manual-code",{method:"POST",body:JSON.stringify({provider:e,code:n})})}function CN(e){return I("/auth/logout",{method:"POST",body:JSON.stringify({provider:e})})}function EN(e){return I("/auth/cancel",{method:"POST",body:JSON.stringify({provider:e})})}function _N(e,n){return I("/auth/api-key",{method:"POST",body:JSON.stringify({provider:e,apiKey:n})})}function MN(e){return I("/auth/api-key",{method:"DELETE",body:JSON.stringify({provider:e})})}function AN(e,n,s,a){return I("/github/issues/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s,labels:a})})}function RN(e,n,s,a){return I(V("/github/issues/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,issueNumber:s})})}function IN(e,n,s){return I("/github/pulls/fetch",{method:"POST",body:JSON.stringify({owner:e,repo:n,limit:s})})}function TN(e,n,s,a){return I(V("/github/pulls/import",a),{method:"POST",body:JSON.stringify({owner:e,repo:n,prNumber:s})})}function PN(e){return I(V("/git/remotes",e))}function $N(e){return I(V("/git/remotes/detailed",e))}function DN(e,n,s){return I(V("/git/remotes",s),{method:"POST",body:JSON.stringify({name:e,url:n})})}function LN(e,n){return I(V(`/git/remotes/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function ON(e,n,s){return I(V(`/git/remotes/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify({newName:n})})}function FN(e,n,s){return I(V(`/git/remotes/${encodeURIComponent(e)}/url`,s),{method:"PUT",body:JSON.stringify({url:n})})}function zN(e,n,s){return I(V(`/tasks/${e}/pr/create`,s),{method:"POST",body:JSON.stringify(n)})}function BN(e,n){return I(V(`/tasks/${e}/pr/refresh`,n),{method:"POST"})}async function UN(e,n){return(await I(V("/github/batch/status",n),{method:"POST",body:JSON.stringify({taskIds:e})})).results}function il(e,n,s,a){return I(V("/terminal/sessions",a),{method:"POST",body:JSON.stringify({cwd:e,cols:n,rows:s})})}function Wm(e,n){return I(V(`/terminal/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function HN(e){return I(V("/terminal/sessions",e))}function ji(e){return I(V("/git/status",e))}function qN(e,n){const s=e?`?limit=${e}`:"";return I(V(`/git/commits${s}`,n))}function Jl(e,n){return I(V(`/git/commits/${e}/diff`,n))}function VN(e){return I(V("/git/commits/ahead",e))}function WN(e,n,s,a){const r=new URLSearchParams;r.set("limit",String(s));const o=r.size>0?`?${r.toString()}`:"";return I(V(`/git/remotes/${encodeURIComponent(e)}/commits${o}`,a))}function Xr(e){return I(V("/git/branches",e))}function GN(e,n,s){const a=`?limit=${n}`;return I(V(`/git/branches/${encodeURIComponent(e)}/commits${a}`,s))}function KN(e){return I(V("/git/worktrees",e))}function JN(e,n,s){return I(V("/git/branches",s),{method:"POST",body:JSON.stringify({name:e,base:n})})}function YN(e,n){return I(V(`/git/branches/${encodeURIComponent(e)}/checkout`,n),{method:"POST"})}function Gm(e,n,s){const a=n?"?force=true":"";return I(V(`/git/branches/${encodeURIComponent(e)}${a}`,s),{method:"DELETE"})}function QN(e,n){return I(V("/git/fetch",n),{method:"POST",body:JSON.stringify({remote:e})})}function XN(e,n){const s=typeof e=="string"?void 0:e;return I(V("/git/pull",typeof e=="string"?e:n),{method:"POST",body:JSON.stringify({rebase:s?.rebase??!1})})}function ZN(e){return I(V("/git/push",e),{method:"POST"})}function al(e){return I(V("/git/stashes",e))}function eS(e,n){return I(V("/git/stashes",n),{method:"POST",body:JSON.stringify({message:e})})}function tS(e,n,s){return I(V(`/git/stashes/${e}/apply`,s),{method:"POST",body:JSON.stringify({drop:n})})}function nS(e,n){return I(V(`/git/stashes/${e}`,n),{method:"DELETE"})}function sS(e,n){return I(V(`/git/stashes/${e}/diff`,n))}function iS(e,n,s){const a=new URLSearchParams;return a.set("path",e),a.set("staged",String(n)),I(V(`/git/diff/file?${a.toString()}`,s))}function cr(e){return I(V("/git/changes",e))}function Km(e,n){return I(V("/git/stage",n),{method:"POST",body:JSON.stringify({files:e})})}function aS(e,n){return I(V("/git/unstage",n),{method:"POST",body:JSON.stringify({files:e})})}function Jm(e,n){return I(V("/git/commit",n),{method:"POST",body:JSON.stringify({message:e})})}function rS(e,n){return I(V("/git/discard",n),{method:"POST",body:JSON.stringify({files:e})})}function oS(e){return I(V("/workspaces",e))}function lS(e,n,s){const a=new URLSearchParams({workspace:e});return n&&a.set("path",n),s&&a.set("projectId",s),I(`/files?${a.toString()}`)}function cS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),I(`/files/${encodeURIComponent(n)}?${a.toString()}`)}function dS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}?${r.toString()}`,{method:"POST",body:JSON.stringify({content:s})})}function uS(e,n,s){const a=new URLSearchParams({q:e});return n&&a.set("workspace",n),s&&a.set("projectId",s),I(`/files/search?${a.toString()}`)}function mS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/copy?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function hS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/move?${r.toString()}`,{method:"POST",body:JSON.stringify({destination:s})})}function pS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),I(`/files/${encodeURIComponent(n)}/delete?${a.toString()}`,{method:"POST"})}function fS(e,n,s,a){const r=new URLSearchParams({workspace:e});return a&&r.set("projectId",a),I(`/files/${encodeURIComponent(n)}/rename?${r.toString()}`,{method:"POST",body:JSON.stringify({newName:s})})}function hb(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download?${a.toString()}`}function gS(e,n,s){const a=new URLSearchParams({workspace:e});return s&&a.set("projectId",s),`/api/files/${encodeURIComponent(n)}/download-zip?${a.toString()}`}function bS(e,n,s){return I(V("/planning/create-draft",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId})})}function xS(e,n,s,a,r){return I(V("/planning/start-streaming",n),{method:"POST",body:JSON.stringify({initialPlan:e,planningModelProvider:s?.planningModelProvider,planningModelId:s?.planningModelId,planningDepth:a?.planningDepth,customQuestionCount:a?.customQuestionCount,...r?{existingSessionId:r}:{}})})}function Ym(e,n,s,a){return I(V("/planning/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function vS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/back`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function yS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function wS(e,n,s){return I(V(`/planning/${encodeURIComponent(e)}/stop`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function pb(e,n,s){return I(V("/planning/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}function N3(e,n,s,a){return I(V("/agents/onboarding/start-streaming",s),{method:"POST",body:JSON.stringify({intent:e,context:n,mode:n.mode,existingAgentConfig:n.existingAgentConfig,planningModelProvider:a?.planningModelProvider,planningModelId:a?.planningModelId})})}function S3(e,n,s){return I(V("/agents/onboarding/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n})})}function C3(e,n){return I(V("/agents/onboarding/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function kS(e,n,s){return I(V("/planning/create-task",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function jS(e,n,s){return I(V("/planning/start-breakdown",s),{method:"POST",body:JSON.stringify(n?{sessionId:e,summary:n}:{sessionId:e})})}function NS(e,n,s){return I(V("/planning/create-tasks",s),{method:"POST",body:JSON.stringify({planningSessionId:e,subtasks:n})})}const du=new Set;if(typeof window<"u"){const e=()=>{for(const n of Array.from(du))try{n.close()}catch{}};window.addEventListener("pagehide",e),window.addEventListener("beforeunload",e)}function SS(e,n){if(n===null||n<=0)return e;const s=e.includes("?")?"&":"?";return`${e}${s}lastEventId=${encodeURIComponent(String(n))}`}function Br(e,n,s={}){const a=s.maxReconnectAttempts??10;let r=null,o=!1,l=0,c=null,d=null,u=!1;const m=p=>{const g=p.lastEventId;if(!g)return!0;const w=Number.parseInt(g,10);return Number.isFinite(w)?d!==null&&w<=d?!1:(d=w,!0):!0},h=()=>{if(o)return;const p=SS(e,d),g=new EventSource(Fi(p));r=g,g.onopen=()=>{l=0,u=!1,s.onConnectionStateChange?.("connected"),n.onOpen?.()},g.onmessage=w=>{const v=w;m(v)&&n.onMessage?.(v)};for(const[w,v]of Object.entries(n.events??{}))g.addEventListener(w,b=>{const y=b;m(y)&&v(y)});g.onerror=()=>{if(o||r!==g)return;if(g.readyState===EventSource.CONNECTING){u||(u=!0,s.onConnectionStateChange?.("reconnecting"));return}if(g.close(),l>=a){s.onFatalError?.("Connection lost");return}u=!0,s.onConnectionStateChange?.("reconnecting"),l+=1;const v=Math.min(1e3*2**(l-1),3e4);c=setTimeout(()=>{c=null,h()},v)}};h();const f={close:()=>{o=!0,c&&(clearTimeout(c),c=null),r?.close(),du.delete(f)},isConnected:()=>!o&&r?.readyState===EventSource.OPEN};return du.add(f),f}function Qm(e){const n=typeof e.source=="string"&&e.source.trim().length>0?e.source.trim():"root",s=n==="root"?".":n,a=e.name,r=typeof e.packagePath=="string"&&e.packagePath.trim().length>0?e.packagePath.trim():s,o=typeof e.confidence=="number"?e.confidence:1,l=n==="root"?"root":n,c=typeof e.packageName=="string"&&e.packageName.trim().length>0?e.packageName.trim():"project";return{name:e.name,command:e.command,scriptName:a,packagePath:r,confidence:o,cwd:s,source:n,workspaceName:typeof e.packageName=="string"?e.packageName:void 0,label:`${c} · ${a} (${l})`}}function _r(e){const n=e.status,s=n==="starting"||n==="running"||n==="failed"||n==="stopped"?n:"stopped",a=typeof e.previewUrl=="string"?e.previewUrl:e.detectedUrl,r=typeof e.manualPreviewUrl=="string"?e.manualPreviewUrl:e.manualUrl;return{id:typeof e.id=="string"?e.id:"",name:typeof e.name=="string"&&e.name.length>0?e.name:"default",status:s,command:typeof e.command=="string"?e.command:"",scriptName:typeof e.scriptId=="string"?e.scriptId:"",cwd:typeof e.cwd=="string"?e.cwd:"",pid:e.pid,startedAt:e.startedAt,previewUrl:a,detectedUrl:typeof e.detectedUrl=="string"?e.detectedUrl:a,detectedPort:e.detectedPort,manualPreviewUrl:r,manualUrl:typeof e.manualUrl=="string"?e.manualUrl:r,logs:Array.isArray(e.logHistory)?e.logHistory:[],exitCode:e.exitCode}}function CS(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 ES(e){const s=(Array.isArray(e.lines)?e.lines:[]).map((a,r)=>CS(a,r+1));return{lines:s,totalLines:typeof e.totalLines=="number"&&Number.isFinite(e.totalLines)?e.totalLines:s.length}}function _S(e,n){const s=typeof n.maxLines=="number"&&Number.isFinite(n.maxLines)?Math.max(1,Math.floor(n.maxLines)):100,a=typeof n.offset=="number"&&Number.isFinite(n.offset)?Math.max(0,Math.floor(n.offset)):0,r=typeof n.lastEventId=="number"&&Number.isFinite(n.lastEventId)?Math.max(0,Math.floor(n.lastEventId)):null,o=e.length,l=e.map((u,m)=>({id:m+1,text:u,stream:"stdout",timestamp:""}));if(r!==null)return{lines:l.filter(u=>u.id>r).slice(0,s),totalLines:o};const c=Math.max(o-a,0),d=Math.max(c-s,0);return{lines:l.slice(d,c),totalLines:o}}function Xm(e){return Array.isArray(e)?e.map(Qm):(e.candidates??[]).map(Qm)}async function MS(e){try{const n=await I(V("/dev-server/candidates",e));return Xm(n)}catch(n){if(n instanceof Error&&/\/dev-server\/candidates/.test(n.message)){const s=await I(V("/dev-server/detect",e));return Xm(s)}throw n}}function Vu(e){return I(V("/dev-server/status",e)).then(_r)}async function E3(e={},n){const s=new URLSearchParams;typeof e.maxLines=="number"&&Number.isFinite(e.maxLines)&&s.set("maxLines",String(Math.max(1,Math.floor(e.maxLines)))),typeof e.offset=="number"&&Number.isFinite(e.offset)&&s.set("offset",String(Math.max(0,Math.floor(e.offset)))),typeof e.lastEventId=="number"&&Number.isFinite(e.lastEventId)&&s.set("lastEventId",String(Math.max(0,Math.floor(e.lastEventId))));const a=s.size>0?`?${s.toString()}`:"";try{const r=await I(V(`/dev-server/logs/history${a}`,n));return ES(r)}catch(r){if(r instanceof Error&&/\/dev-server\/logs\/history/.test(r.message)){const o=await Vu(n);return _S(o.logs,e)}throw r}}function AS(e,n){const s=e.cwd??e.packagePath??".",a=e.scriptName;return I(V("/dev-server/start",n),{method:"POST",body:JSON.stringify({command:e.command,scriptName:a,scriptId:a,cwd:s,packagePath:e.packagePath})}).then(_r)}function RS(e){return I(V("/dev-server/stop",e),{method:"POST"}).then(_r)}function IS(e){return I(V("/dev-server/restart",e),{method:"POST"}).then(_r)}async function TS(e,n){const s=typeof e=="string"?{url:e}:e;try{const a=await I(V("/dev-server/preview-url",n),{method:"POST",body:JSON.stringify(s)});return _r(a)}catch(a){if(a instanceof Error&&/\/dev-server\/preview-url/.test(a.message)){const r=await I(V("/dev-server/preview-url",n),{method:"PUT",body:JSON.stringify(s)});return _r(r)}throw a}}function _3(e){return Ms(V("/dev-server/logs/stream",e))}async function M3(e){try{return(await I(V("/devserver",e))).sessions??[]}catch{try{const n=await Vu(e);return[{config:{id:n.id??"default",name:n.name??"Dev Server",command:n.command??"",cwd:n.cwd??"."},status:n.status,runtime:n.pid?{pid:n.pid,startedAt:n.startedAt??new Date().toISOString(),exitCode:n.exitCode??void 0,previewUrl:n.previewUrl}:void 0,previewUrl:n.previewUrl??n.detectedUrl??void 0,logHistory:(n.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}]}catch{return[]}}}async function A3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}`,n))}catch{try{const s=await Vu(n);return!e||e==="default"||e===s.id?{config:{id:s.id??"default",name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}:null}catch{return null}}}async function R3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/start`,n),{method:"POST"})}catch{const s=await AS({command:""},n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function I3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}catch{const s=await RS(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function T3(e,n){try{return await I(V(`/devserver/${encodeURIComponent(e)}/restart`,n),{method:"POST"})}catch{const s=await IS(n);return{config:{id:s.id??e,name:s.name??"Dev Server",command:s.command??"",cwd:s.cwd??"."},status:s.status,runtime:s.pid?{pid:s.pid,startedAt:s.startedAt??new Date().toISOString(),exitCode:s.exitCode??void 0,previewUrl:s.previewUrl}:void 0,previewUrl:s.previewUrl??s.detectedUrl??void 0,logHistory:(s.logs??[]).map(a=>({timestamp:new Date().toISOString(),stream:a.startsWith("[stderr]")?"stderr":"stdout",text:a.replace(/^\[stderr\]\s*/,"")}))}}}async function P3(e,n,s){try{const a=await I(V(`/devserver/${encodeURIComponent(e)}/preview`,s),{method:"POST",body:JSON.stringify({url:n})});return{url:a.url??null,source:a.source??null}}catch{const a=await TS({url:n},s);return{url:a.previewUrl??a.manualUrl??null,source:"manual"}}}async function $3(e){try{return(await I(V("/devserver/detect",e))).candidates??[]}catch{try{return(await MS(e)).map(s=>({name:s.name,command:s.command,cwd:s.cwd,scriptName:s.scriptName,packagePath:s.packagePath}))}catch{return[]}}}function D3(e,n){return Ms(V(`/devserver/${encodeURIComponent(e)}/logs/stream`,n))}function Wo(e,n,s=25e3){const a=setInterval(()=>{_0(e,n).catch(()=>{})},s);return{stop:()=>{clearInterval(a)}}}function PS(e,n){return Ms(V(`/planning/${encodeURIComponent(e)}/stream`,n))}function $S(e,n){return Ms(V(`/agents/onboarding/${encodeURIComponent(e)}/stream`,n))}function L3(e,n,s,a){const r=$S(e,n),o=Br(r,{events:{thinking:l=>{try{s.onThinking?.(JSON.parse(l.data))}catch{s.onThinking?.(l.data)}},question:l=>{try{s.onQuestion?.(JSON.parse(l.data))}catch{}},summary:l=>{try{s.onSummary?.(JSON.parse(l.data))}catch{}},error:l=>{try{const c=JSON.parse(l.data);s.onError?.(c.message||c)}catch{s.onError?.(l.data||"Stream error")}},complete:()=>{s.onComplete?.()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:l=>s.onError?.(l)});return{close:o.close,isConnected:o.isConnected}}function DS(e,n,s,a){const r=PS(e,n);let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[planning] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Go(e,n){const s=new URLSearchParams;n?.scope&&s.set("scope",n.scope),n?.projectId&&s.set("projectId",n.projectId);const a=s.toString();return a?`${e}?${a}`:e}function LS(e){return I(Go("/routines",e))}function OS(e,n){return I(Go("/routines",n),{method:"POST",body:JSON.stringify(e)})}function Zm(e,n,s){return I(Go(`/routines/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function FS(e,n){await I(Go(`/routines/${e}`,n),{method:"DELETE"})}function zS(e,n){return I(Go(`/routines/${e}/trigger`,n),{method:"POST"})}function eh(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since!==void 0&&n.set("since",e.since),e?.type!==void 0&&n.set("type",e.type),e?.projectId&&n.set("projectId",e.projectId);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity${s}`)}function BS(e){const n=V("/activity",e);return I(n,{method:"DELETE"})}function Ko(e){return I(V("/workflow-steps",e))}function th(e,n){return I(V("/workflow-steps",n),{method:"POST",body:JSON.stringify(e)})}function US(e,n,s){return I(V(`/workflow-steps/${e}`,s),{method:"PATCH",body:JSON.stringify(n)})}function HS(e,n){return I(V(`/workflow-steps/${e}`,n),{method:"DELETE"})}function nh(e,n){return I(V(`/workflow-steps/${e}/refine`,n),{method:"POST"})}function qS(e,n){return I(V(`/tasks/${encodeURIComponent(e)}/workflow-results`,n))}function VS(){return I("/workflow-step-templates")}function WS(){return I("/plugin-workflow-step-templates")}function GS(e,n){return I(V(`/workflow-step-templates/${encodeURIComponent(e)}/create`,n),{method:"POST"})}function $o(e){return I(V("/scripts",e))}function KS(e,n,s){return I(V("/scripts",s),{method:"POST",body:JSON.stringify({name:e,command:n})})}function JS(e,n){return I(V(`/scripts/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function fb(e,n,s){return(await I(V("/ai/refine-text",s),{method:"POST",body:JSON.stringify({text:e,type:n})})).refined}const rl={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 gb(e){if(!(e instanceof Error))return rl.NETWORK;const n=e.message.toLowerCase();return n.includes("rate limit")||n.includes("429")?rl.RATE_LIMIT:n.includes("invalid")&&n.includes("type")?rl.INVALID_TYPE:n.startsWith("text must")||n.includes("text is required")||n.includes("type is required")?e.message:rl.NETWORK}function YS(e,n){return I(V("/subtasks/start-streaming",n),{method:"POST",body:JSON.stringify({description:e})})}function QS(e,n,s){return I(V(`/subtasks/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function XS(e,n){return Ms(V(`/subtasks/${encodeURIComponent(e)}/stream`,n))}function ZS(e,n,s,a){let r=null,o=null;const l=()=>{r?.stop(),r=null},c=Br(XS(e,n),{onOpen:()=>{l(),r=Wo(e,n)},events:{thinking:d=>{try{s.onThinking?.(JSON.parse(d.data))}catch{s.onThinking?.(d.data)}},subtasks:d=>{try{s.onSubtasks?.(JSON.parse(d.data))}catch(u){console.error("[subtasks] Failed to parse subtasks event:",u)}},error:d=>{try{const u=JSON.parse(d.data),m=typeof u=="string"&&u.length>0?u:null;s.onError?.(m||"Stream error")}catch{s.onError?.("Stream error")}o?.close()},complete:()=>{s.onComplete?.(),o?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:d=>{l(),s.onError?.(d)}});return o={close:()=>{l(),c.close()},isConnected:c.isConnected},o}function e1(e,n,s,a,r){return I(V("/subtasks/create-tasks",a),{method:"POST",body:JSON.stringify({sessionId:e,parentTaskId:s,...r?.branch!==void 0?{branch:r.branch}:{},...r?.baseBranch!==void 0?{baseBranch:r.baseBranch}:{},...r?.branchSelection?{branchSelection:r.branchSelection}:{},...r?.branchAssignment?{branchAssignment:r.branchAssignment}:{},subtasks:n.map(o=>({tempId:o.id,title:o.title,description:o.description,size:o.suggestedSize,dependsOn:o.dependsOn}))})})}function bb(e,n,s){return I(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 t1(e,n,s){if(!n||n===s)return e;const a="/api",r=e.startsWith(a)?e.slice(a.length):e;return`/proxy/${encodeURIComponent(n)}${r}`}function Jo(e,n){const{nodeId:s,localNodeId:a,...r}=n??{},o=t1(e,s,a);return I(o,r)}function Ur(e,n){const s=new URLSearchParams;e?.state&&s.set("state",e.state),e?.role&&s.set("role",e.role),e?.includeEphemeral===!0&&s.set("includeEphemeral","true"),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/agents${a}`)}function uu(e,n){return I(V(`/agents/${encodeURIComponent(e)}`,n))}function n1(e,n){return I(V("/agents",n),{method:"POST",body:JSON.stringify(e)})}function s1(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function O3(e,n,s){const a=new FormData;a.append("file",n);const r=await fetch(Ms(V(`/agents/${encodeURIComponent(e)}/avatar`,s)),{method:"POST",headers:_i(),body:a}),o=await r.json();if(!r.ok)throw new Error(o.error||"Avatar upload failed");return o}function F3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/avatar`,n),{method:"DELETE"})}function z3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/upgrade-heartbeat-procedure`,n),{method:"POST"})}function B3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/instructions`,s),{method:"PATCH",body:JSON.stringify(n)})}function U3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/soul`,s),{method:"PATCH",body:JSON.stringify({soul:n})})}function H3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/memory`,s),{method:"PATCH",body:JSON.stringify({memory:n})})}function q3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/memory/files`,n))}function V3(e,n,s){const a=`path=${encodeURIComponent(n)}`;return I(V(`/agents/${encodeURIComponent(e)}/memory/file?${a}`,s))}function W3(e,n,s,a){return I(V(`/agents/${encodeURIComponent(e)}/memory/file`,a),{method:"PUT",body:JSON.stringify({path:n,content:s})})}function i1(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/state`,s),{method:"POST",body:JSON.stringify({state:n})})}function a1(e,n){return I(V(`/agents/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function G3(e,n,s){const a=new URLSearchParams;n!==void 0&&a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/runs${r}`)}function K3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}`,s))}function J3(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/runs/${encodeURIComponent(n)}/logs`,s))}function Y3(e,n,s){const a=s?.source??"manual",r=s?.triggerDetail??"Agent activated via dashboard";return I(V(`/agents/${encodeURIComponent(e)}/runs`,n),{method:"POST",body:JSON.stringify({source:a,triggerDetail:r})})}function Q3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/runs/stop`,n),{method:"POST"})}function r1(e){return I(V("/agents/stats",e))}function X3(e,n){return I(V(`/agents/${encodeURIComponent(e)}/chain-of-command`,n))}function Z3(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeEphemeral&&s.set("includeEphemeral","true");const a=s.toString();return I(`/agents/org-tree${a?`?${a}`:""}`)}function e5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/children`,n)).catch(s=>{if(s.message.includes("not found"))return[];throw s})}function sh(e,n,s){return I(V(`/tasks/${encodeURIComponent(e)}/assign`,s),{method:"PATCH",body:JSON.stringify({agentId:n})})}function xb(e){return{reviewState:{source:e.mode,summary:e.summary??void 0,items:e.items.map(n=>({id:n.itemId,body:n.body,author:{login:n.author},createdAt:n.createdAt??new Date(0).toISOString(),updatedAt:n.updatedAt??void 0,path:n.filePath,threadId:n.threadId,htmlUrl:n.url,state:n.reviewState??void 0,isResolved:n.isResolved})),addressing:[],lastRefreshedAt:e.fetchedAt??void 0,refreshStatus:"ready",refreshSource:"initial-load"},automationStatus:null}}async function o1(e,n){const s=await I(V(`/tasks/${encodeURIComponent(e)}/review`,n));return xb(s)}async function l1(e,n){const s=await I(V(`/tasks/${encodeURIComponent(e)}/review/refresh`,n),{method:"POST"});return xb(s)}function c1(e,n,s){return I(V(`/tasks/${encodeURIComponent(e)}/review/address`,s),{method:"POST",body:JSON.stringify({selectedItems:n,tab:"review"})})}function t5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/tasks`,n))}function n5(){return I("/agents/companies")}function s5(e,n){return I(V("/agents/generate/start",n),{method:"POST",body:JSON.stringify({role:e})})}function i5(e,n){return I(V("/agents/generate/spec",n),{method:"POST",body:JSON.stringify({sessionId:e})})}function a5(e,n){return I(V(`/agents/generate/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function r5(e){return I(V("/backups",e))}function o5(e){return I(V("/backups",e),{method:"POST"})}function l5(e,n){const s=V("/settings/export",n),a=`${s}${s.includes("?")?"&":"?"}scope=${encodeURIComponent(e)}`;return I(a)}function c5(e,n,s){return I(V("/settings/import",s),{method:"POST",body:JSON.stringify({data:e,scope:n?.scope??"both",merge:n?.merge??!0})})}function d1(e){return Array.isArray(e.nodeMappings)||Array.isArray(e.projectNodeMappings)||Array.isArray(e.pathMappings)}function ih(){return I("/projects/across-nodes")}function Yl(){return I("/nodes")}function d5(){return I("/docker/nodes")}function u5(e){return I(`/docker/nodes/${encodeURIComponent(e)}/container-status`)}function m5(e,n){const s=new URLSearchParams;typeof n?.tail=="number"&&s.set("tail",String(n.tail));const a=s.size>0?`?${s.toString()}`:"";return I(`/docker/nodes/${encodeURIComponent(e)}/logs${a}`)}function h5(e){return I("/docker-nodes",{method:"POST",body:JSON.stringify(e)})}function u1(e){return I("/nodes",{method:"POST",body:JSON.stringify(e)})}function m1(e){return I("/nodes/discover-projects",{method:"POST",body:JSON.stringify(e)})}function h1(e,n){return I(`/nodes/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function p1(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config`)}function f1(e,n){return I(`/nodes/${encodeURIComponent(e)}/docker-config`,{method:"PATCH",body:JSON.stringify(n)})}function g1(e){return I(`/nodes/${encodeURIComponent(e)}/docker-config/diff`)}function ah(e){return I(`/nodes/${encodeURIComponent(e)}`,{method:"DELETE"})}async function b1(e){const n=await I(`/nodes/${encodeURIComponent(e)}/health-check`,{method:"POST"});return{nodeId:n.nodeId??e,status:n.status,responseTimeMs:n.responseTimeMs,error:n.error,checkedAt:n.checkedAt??new Date().toISOString()}}async function p5(){return I("/mesh/state")}function f5(e,n,s,a){const r=s&&s!==a?s:void 0,o=new URLSearchParams;e&&o.set("path",e),n&&o.set("showHidden","true"),r&&o.set("nodeId",r);const l=Er();l&&o.set("fn_token",l);const c=o.toString(),d=`/browse-directory${c?`?${c}`:""}`;return I(d)}function x1(e){return I("/projects",{method:"POST",body:JSON.stringify(e)})}function vb(e){return I(`/projects/${encodeURIComponent(e)}`,{method:"DELETE"})}function v1(e,n,s){return I(`/projects/${encodeURIComponent(e)}/path-mappings/${encodeURIComponent(n)}`,{method:"PUT",body:JSON.stringify({path:s})})}function rh(e){return I(`/projects/${encodeURIComponent(e)}/health`)}function y1(e){return I(V("/executor/stats",e))}function w1(e){return I(V("/system-stats",e))}function k1(e){return I(V("/kill-vitest",e),{method:"POST"})}function oh(e){const n=new URLSearchParams;e?.limit!==void 0&&n.set("limit",String(e.limit)),e?.since&&n.set("since",e.since),e?.projectId&&n.set("projectId",e.projectId),e?.type&&n.set("type",e.type);const s=n.size>0?`?${n.toString()}`:"";return I(`/activity-feed${s}`)}function j1(e){return I(`/projects/${encodeURIComponent(e)}/pause`,{method:"POST"})}function N1(e){return I(`/projects/${encodeURIComponent(e)}/resume`,{method:"POST"})}function g5(){return I("/global-concurrency")}function b5(e){return I("/global-concurrency",{method:"PUT",body:JSON.stringify(e)})}function S1(e,n){return I(`/projects/${encodeURIComponent(e)}`,{method:"PATCH",body:JSON.stringify(n)})}function yb(e,n,s){const a=new URLSearchParams;n&&a.set("worktree",n),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/tasks/${encodeURIComponent(e)}/diff${r}`)}function C1(e,n){return I(V(`/tasks/${encodeURIComponent(e)}/commit-associations`,n))}function E1(e){return I(V("/missions",e))}function _1(e,n){return I(V("/missions",n),{method:"POST",body:JSON.stringify(e)})}function wb(e,n){return I(V(`/missions/${encodeURIComponent(e)}`,n))}function M1(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function A1(e,n){return I(V(`/missions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function R1(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/missions/${encodeURIComponent(e)}/events${r}`,s))}function I1(e){return I(V("/missions/health",e))}function T1(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}/milestones`,s),{method:"POST",body:JSON.stringify(n)})}function P1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function $1(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function D1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}/slices`,s),{method:"POST",body:JSON.stringify(n)})}function L1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function O1(e,n){return I(V(`/missions/slices/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function F1(e,n){return I(V(`/missions/slices/${encodeURIComponent(e)}/activate`,n),{method:"POST"})}function z1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}/features`,s),{method:"POST",body:JSON.stringify(n)})}function B1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function U1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function H1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/link-task`,s),{method:"POST",body:JSON.stringify({taskId:n})})}function q1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/unlink-task`,n),{method:"POST"})}function V1(e,n,s,a,r){return I(V(`/missions/features/${encodeURIComponent(e)}/triage`,a),{method:"POST",body:JSON.stringify({taskTitle:n,taskDescription:s,...r})})}function W1(e,n,s){return I(V(`/missions/slices/${encodeURIComponent(e)}/triage-all`,n),{method:"POST",body:JSON.stringify({})})}function Hc(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,n))}function G1(e,n,s){return I(V(`/missions/milestones/${encodeURIComponent(e)}/assertions`,s),{method:"POST",body:JSON.stringify(n)})}function K1(e,n,s){return I(V(`/missions/assertions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function J1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/link`,s),{method:"POST"})}function Y1(e,n,s){return I(V(`/missions/features/${encodeURIComponent(e)}/assertions/${encodeURIComponent(n)}/unlink`,s),{method:"POST"})}function Q1(e,n){return I(V(`/missions/assertions/${encodeURIComponent(e)}/features`,n))}function qc(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/validation`,n))}function lh(e,n){return I(V(`/missions/milestones/${encodeURIComponent(e)}/validation-telemetry`,n))}function X1(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/validate`,n),{method:"POST"})}function ch(e,n){return I(V(`/missions/features/${encodeURIComponent(e)}/validation-loop`,n))}function Z1(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/missions/features/${encodeURIComponent(e)}/validation-runs${r}`,s)).then(o=>o.runs)}function e0(e,n){return I(V(`/missions/validation-runs/${encodeURIComponent(e)}`,n))}function t0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/resume`,n),{method:"POST"})}function n0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/stop`,n),{method:"POST"})}function s0(e,n){return I(V(`/missions/${encodeURIComponent(e)}/start`,n),{method:"POST"})}function i0(e,n,s){return I(V(`/missions/${encodeURIComponent(e)}/autopilot`,s),{method:"PATCH",body:JSON.stringify(n)})}function a0(e,n,s){return I(V("/missions/interview/start",n),{method:"POST",body:JSON.stringify({missionTitle:e,modelProvider:s?.modelProvider,modelId:s?.modelId})})}function r0(e,n,s,a){return I(V("/missions/interview/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function o0(e,n,s){return I(V(`/missions/interview/${encodeURIComponent(e)}/retry`,n),{method:"POST",...s?{body:JSON.stringify({tabId:s})}:{}})}function kb(e,n,s){return I(V("/missions/interview/cancel",n),{method:"POST",body:JSON.stringify({sessionId:e,tabId:s})})}async function l0(e){const n=e?`?${new URLSearchParams({projectId:e}).toString()}`:"";return(await I(`/missions/interview/drafts${n}`)).drafts??[]}function c0(e,n,s){return I(V(`/missions/interview/drafts/${encodeURIComponent(e)}/discard`,n),{method:"POST",body:JSON.stringify({tabId:s})})}function d0(e,n,s,a){return I(V("/missions/interview/create-mission",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function u0(e,n,s,a){const r=Ms(V(`/missions/interview/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[mission-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function Yo(e,n,s){return V(`/missions/milestones/${encodeURIComponent(e)}/interview${n}`,s)}function Qo(e,n,s){return V(`/missions/slices/${encodeURIComponent(e)}/interview${n}`,s)}function m0(e,n){return I(Yo(e,"/start",n),{method:"POST"})}function h0(e,n,s,a){return I(Yo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function p0(e,n,s,a){const r=Ms(Yo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[milestone-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function f0(e,n,s){return I(Yo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function g0(e,n){return I(Yo(e,"/skip",n),{method:"POST"})}function b0(e,n){return I(Qo(e,"/start",n),{method:"POST"})}function x0(e,n,s,a){return I(Qo(e,"/respond",s),{method:"POST",body:JSON.stringify({sessionId:e,responses:n,tabId:a})})}function v0(e,n,s,a){const r=Ms(Qo(e,`/${encodeURIComponent(e)}/stream`,n));let o=null,l=null;const c=()=>{o?.stop(),o=null},d=Br(r,{onOpen:()=>{c(),o=Wo(e,n)},onMessage:u=>{u.data.startsWith(":")},events:{thinking:u=>{try{s.onThinking?.(JSON.parse(u.data))}catch{s.onThinking?.(u.data)}},question:u=>{try{s.onQuestion?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse question event:",m)}},summary:u=>{try{s.onSummary?.(JSON.parse(u.data))}catch(m){console.error("[slice-interview] Failed to parse summary event:",m)}},error:u=>{try{const m=JSON.parse(u.data);s.onError?.(m.message||m)}catch{s.onError?.(u.data||"Stream error")}l?.close()},complete:()=>{s.onComplete?.(),l?.close()}}},{maxReconnectAttempts:a?.maxReconnectAttempts,onConnectionStateChange:s.onConnectionStateChange,onFatalError:u=>{c(),s.onError?.(u)}});return l={close:()=>{c(),d.close()},isConnected:d.isConnected},l}function y0(e,n,s){return I(Qo(e,"/apply",s),{method:"POST",body:JSON.stringify({sessionId:e,summary:n})})}function w0(e,n){return I(Qo(e,"/skip",n),{method:"POST"})}async function k0(e,n){try{return await I(V(`/missions/features/${encodeURIComponent(e)}/preview-description`,n),{method:"POST"})}catch{throw new Error("Preview endpoint not available")}}function x5(e){return I(V("/todos",e))}function v5(e,n){const s={title:e};return I(V("/todos",n),{method:"POST",body:JSON.stringify(s)})}function y5(e,n,s){const a={title:n};return I(V(`/todos/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function w5(e,n){return I(V(`/todos/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function k5(e,n,s){const a={text:n};return I(V(`/todos/${encodeURIComponent(e)}/items`,s),{method:"POST",body:JSON.stringify(a)})}function j5(e,n,s){const a=n;return I(V(`/todos/items/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(a)})}function N5(e,n){return I(V(`/todos/items/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function S5(e,n,s){return I(V(`/todos/${encodeURIComponent(e)}/items/reorder`,s),{method:"POST",body:JSON.stringify({itemIds:n})})}function Mr(e){if(!e)return[];try{const n=JSON.parse(e);return Array.isArray(n)?n:[]}catch{return[]}}async function Wu(e,n){const s=new URLSearchParams;e&&s.set("projectId",e),n?.includeCompleted&&s.set("includeCompleted","1"),n?.includeArchived&&s.set("includeArchived","1");const a=s.toString(),r=await fetch(Ms(`/ai-sessions${a?`?${a}`:""}`),{headers:_i()});return r.ok?(await r.json()).sessions??[]:[]}async function j0(e){return I(`/ai-sessions/${encodeURIComponent(e)}/archive`,{method:"POST"})}async function N0(e){return I(`/ai-sessions/${encodeURIComponent(e)}/unarchive`,{method:"POST"})}async function Di(e){const n=await fetch(Ms(`/ai-sessions/${encodeURIComponent(e)}`),{headers:_i()});return n.ok?n.json():null}async function S0(e,n){const s=await I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"POST",body:JSON.stringify({tabId:n})});return{acquired:s.acquired,currentHolder:s.currentHolder??null}}function C0(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock`,{method:"DELETE",body:JSON.stringify({tabId:n})})}function E0(e,n){return I(`/ai-sessions/${encodeURIComponent(e)}/lock/force`,{method:"POST",body:JSON.stringify({tabId:n})})}async function jb(e){await fetch(Ms(`/ai-sessions/${encodeURIComponent(e)}`),{method:"DELETE",headers:_i()})}function _0(e,n){return I(V(`/ai-sessions/${encodeURIComponent(e)}/ping`,n),{method:"POST"})}function M0(e,n,s){return I(V(`/ai-sessions/${encodeURIComponent(e)}/draft`,s),{method:"PATCH",body:JSON.stringify(n)})}function A0(e,n){return I(V(`/planning/${encodeURIComponent(e)}/summarize-draft-title`,n),{method:"POST"})}function R0(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.unreadOnly&&s.set("unreadOnly","true"),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/messages/inbox${a}`)}function I0(e,n){const s=new URLSearchParams;s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),e?.type&&s.set("type",e.type),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/messages/outbox${a}`)}function Nb(e){return I(V("/messages/unread-count",e))}function T0(e,n){return I(V("/messages",n),{method:"POST",body:JSON.stringify(e)})}function P0(e,n){return I(V(`/messages/${encodeURIComponent(e)}/read`,n),{method:"POST"})}function $0(e){return I(V("/messages/read-all",e),{method:"POST"})}function D0(e,n){return I(V(`/messages/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function L0(e,n,s){const a=`/messages/conversation/${encodeURIComponent(n)}/${encodeURIComponent(e)}`;return I(V(a,s))}function O0(e,n){return I(V(`/agents/${encodeURIComponent(e)}/mailbox`,n))}function F0(e){return I(V("/agents/mailbox/all",e))}function ol(e,n){const s=new URLSearchParams;e?.status&&s.set("status",e.status),e?.limit!==void 0&&s.set("limit",String(e.limit)),e?.offset!==void 0&&s.set("offset",String(e.offset)),n&&s.set("projectId",n);const a=s.size>0?`?${s.toString()}`:"";return I(`/approvals${a}`)}function dh(e,n){return I(V(`/approvals/${encodeURIComponent(e)}`,n))}function z0(e,n,s){return I(V(`/approvals/${encodeURIComponent(e)}/decision`,s),{method:"POST",body:JSON.stringify(n)})}function C5(e,n,s){const a=new URLSearchParams;a.set("limit",String(n)),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/reflections${r}`)}function E5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/reflections`,n),{method:"POST"})}function _5(e,n,s){const a=new URLSearchParams;s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/performance${r}`)}function M5(e,n,s){const a=new URLSearchParams;a.set("limit",String(n.limit)),n?.category&&a.set("category",n.category),s&&a.set("projectId",s);const r=a.size>0?`?${a.toString()}`:"";return I(`/agents/${encodeURIComponent(e)}/ratings${r}`)}function A5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/ratings`,s),{method:"POST",body:JSON.stringify(n)})}function R5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/ratings/summary`,n))}function I5(e,n,s){return I(V(`/agents/${encodeURIComponent(e)}/ratings/${encodeURIComponent(n)}`,s),{method:"DELETE"})}function T5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/budget`,n))}function P5(e,n){return I(V(`/agents/${encodeURIComponent(e)}/budget/reset`,n),{method:"POST"})}async function $5(e){return I(V("/plugins",e))}async function D5(e,n){return I(V("/plugins",n),{method:"POST",body:JSON.stringify({mode:"install",...e})})}async function L5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/enable`,n),{method:"POST"})}async function O5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/disable`,n),{method:"POST"})}async function F5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}`,n),{method:"DELETE"})}async function z5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/settings`,n))}async function B5(e,n,s){return I(V(`/plugins/${encodeURIComponent(e)}/settings`,s),{method:"PUT",body:JSON.stringify({settings:n})})}async function U5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/setup-status`,n))}async function H5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/setup/install`,n),{method:"POST"})}async function q5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/reload`,n),{method:"POST"})}async function V5(e,n,s){return I(V(`/plugins/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}async function W5(e,n){return I(V(`/plugins/${encodeURIComponent(e)}/rescan`,n),{method:"POST"})}async function B0(e){return I(V("/plugins/ui-slots",e))}async function U0(e){return I(V("/plugins/dashboard-views",e))}async function G5(e){return I(V("/plugins/runtimes",e))}async function H0(e){return(await I(V("/skills/discovered",e))).skills}async function K5(e,n,s){return I(V("/skills/execution",s),{method:"PATCH",body:JSON.stringify({skillId:e,enabled:n})})}async function J5(e,n,s){const a=new URLSearchParams;e&&a.set("q",e),a.set("limit",String(n));const r=a.size>0?`?${a.toString()}`:"";return I(V(`/skills/catalog${r}`,s))}async function Y5(e,n){return(await I(V(`/skills/${encodeURIComponent(e)}/content`,n))).content}function uh(e,n){const s=new URLSearchParams;e&&s.set("projectId",e);const a=s.toString();return I(`/chat/sessions${a?`?${a}`:""}`)}async function q0(e,n){const s=e.agentId.trim();if(!s)throw new Error("agentId is required");const a=e.modelProvider?.trim(),r=e.modelId?.trim();if(a&&!r||!a&&r)throw new Error("Both modelProvider and modelId must be provided together, or neither should be provided");const o=new URLSearchParams;return o.set("lookup","resume"),o.set("agentId",s),n&&o.set("projectId",n),a&&r&&(o.set("modelProvider",a),o.set("modelId",r)),{session:(await I(`/chat/sessions?${o.toString()}`)).sessions[0]??null}}function V0(e,n){return I(V("/chat/sessions",n),{method:"POST",body:JSON.stringify(e)})}function W0(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,n))}function Q5(e,n,s){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,s),{method:"PATCH",body:JSON.stringify(n)})}function X5(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function Zr(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return I(V(`/chat/sessions/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function Z5(e={},n){const s=new URLSearchParams;n&&s.set("projectId",n),e.status&&s.set("status",e.status),e.agentId&&s.set("agentId",e.agentId);const a=s.toString();return I(`/chat/rooms${a?`?${a}`:""}`)}function e8(e,n){const s={...e,...n?{projectId:n}:{}};return I(V("/chat/rooms",n),{method:"POST",body:JSON.stringify(s)})}function t8(e,n){return I(V(`/chat/rooms/${encodeURIComponent(e)}`,n),{method:"DELETE"})}function n8(e,n){return I(V(`/chat/rooms/${encodeURIComponent(e)}/members`,n))}function s8(e,n,s){const a=new URLSearchParams;n?.limit!==void 0&&a.set("limit",String(n.limit)),n?.offset!==void 0&&a.set("offset",String(n.offset)),n?.before&&a.set("before",n.before);const r=a.toString();return I(V(`/chat/rooms/${encodeURIComponent(e)}/messages${r?`?${r}`:""}`,s))}function i8(e,n,s){return I(V(`/chat/rooms/${encodeURIComponent(e)}/messages`,s),{method:"POST",body:JSON.stringify(n)})}function G0(e,n){return I(V(`/chat/sessions/${encodeURIComponent(e)}/cancel`,n),{method:"POST"})}function K0(e){if(!e||typeof e!="object")return null;const n=e,s=typeof n.summary=="string"?n.summary.trim():"";if(!s)return null;const a=(()=>{const r=n.reference;if(!r||typeof r!="object")return;const o=r,l=typeof o.kind=="string"?o.kind.trim():"",c=typeof o.id=="string"?o.id.trim():"";if(!(!l||!c))return{kind:l,id:c,...typeof o.label=="string"&&o.label.trim()?{label:o.label.trim()}:{}}})();return{summary:s,...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...a?{reference:a}:{}}}function Sb(e){try{const n=JSON.parse(e),s=K0(n);return s||(n&&typeof n=="object"&&typeof n.message=="string"?n.message:typeof n=="string"?n:e||"Stream error")}catch{return e||"Stream error"}}function J0(e,n,s,a,r,o){const l=Ms(V(`/chat/sessions/${encodeURIComponent(e)}/messages`,r)),c=new AbortController;let d=!1,u=!1,m=!1;const h=Math.max(1e3,6e4);let f=null;const p=()=>{f&&(clearTimeout(f),f=null)},g=()=>{m||(m=!0,p())},w=(v,b)=>{if(v)switch(g(),v){case"thinking":try{s.onThinking?.(JSON.parse(b))}catch{s.onThinking?.(b)}break;case"text":try{s.onText?.(JSON.parse(b))}catch{s.onText?.(b)}break;case"tool_start":try{s.onToolStart?.(JSON.parse(b))}catch{}break;case"tool_end":try{s.onToolEnd?.(JSON.parse(b))}catch{}break;case"fallback":try{s.onFallback?.(JSON.parse(b))}catch{}break;case"done":u=!0;try{const y=JSON.parse(b);s.onDone?.({messageId:typeof y.messageId=="string"?y.messageId:"",...y.message&&typeof y.message=="object"?{message:y.message}:{}})}catch{s.onDone?.({messageId:""})}break;case"error":u=!0,s.onError?.(Sb(b));break}};return(async()=>{try{const v=Array.isArray(a)&&a.length>0,b=v?(()=>{const E=new FormData;return E.append("content",n),a.forEach(_=>E.append("attachments",_)),E})():JSON.stringify({content:n}),y=await fetch(l,{method:"POST",headers:v?_i():_i({"Content-Type":"application/json"}),body:b,signal:c.signal});if(!y.ok){const E=await y.text();let _=`Request failed: ${y.status}`;try{_=JSON.parse(E).error||_}catch{}s.onError?.(_);return}if(!y.body){s.onError?.("No response body");return}s.onConnectionStateChange?.("connected"),f=setTimeout(()=>{u||d||m||(u=!0,s.onError?.("Timed out waiting for first response event"),c.abort())},h);const S=y.body.getReader(),j=new TextDecoder;let C="",x="",N=[];const R=(E,_=!1)=>{C+=E;const K=C.split(`
643
643
  `);C=K.pop()||"",_&&C.length>0&&(K.push(C),C="");for(const U of K){const A=U.endsWith("\r")?U.slice(0,-1):U;if(A.startsWith("event:"))x=A.slice(6).trim();else if(A.startsWith("data:")){const T=A.slice(5);N.push(T.startsWith(" ")?T.slice(1):T)}else if(A===""){const T=N.join(`
644
644
  `);w(x,T),x="",N=[]}}if(_&&x&&N.length>0){const U=N.join(`
645
645
  `);w(x,U),x="",N=[]}};for(;;){const{done:E,value:_}=await S.read();if(E){R(j.decode(),!0);break}R(j.decode(_,{stream:!0}))}const F=C.length>0||x.length>0||N.length>0;!u&&!d&&!F&&s.onError?.("Connection closed unexpectedly"),p()}catch(v){if(v instanceof DOMException&&v.name==="AbortError"){!d&&!u&&s.onError?.("Connection aborted"),p();return}if(d){p();return}p(),s.onError?.(v instanceof Error?v.message:"Connection error")}})(),{close:()=>{d=!0,p(),c.abort()},isConnected:()=>!d}}function Y0(e,n,s,a){const r=Ms(V(`/chat/sessions/${encodeURIComponent(e)}/stream`,s)),o=new AbortController;let l=!1,c=!1;const d=(u,m)=>{if(u)switch(u){case"thinking":try{n.onThinking?.(JSON.parse(m))}catch{n.onThinking?.(m)}break;case"text":try{n.onText?.(JSON.parse(m))}catch{n.onText?.(m)}break;case"tool_start":try{n.onToolStart?.(JSON.parse(m))}catch{}break;case"tool_end":try{n.onToolEnd?.(JSON.parse(m))}catch{}break;case"fallback":try{n.onFallback?.(JSON.parse(m))}catch{}break;case"done":c=!0;try{const h=JSON.parse(m);n.onDone?.({messageId:typeof h.messageId=="string"?h.messageId:"",...h.message&&typeof h.message=="object"?{message:h.message}:{}})}catch{n.onDone?.({messageId:""})}break;case"error":c=!0,n.onError?.(Sb(m));break}};return(async()=>{try{const u=new Headers(_i());typeof a?.lastEventId=="number"&&u.set("Last-Event-ID",String(a.lastEventId));const m=await fetch(r,{method:"GET",headers:u,signal:o.signal});if(!m.ok){const y=await m.text();let S=`Request failed: ${m.status}`;try{S=JSON.parse(y).error||S}catch{}n.onError?.(S);return}if(!m.body){n.onError?.("No response body");return}n.onConnectionStateChange?.("connected");const h=m.body.getReader(),f=new TextDecoder;let p="",g="",w=[];const v=(y,S=!1)=>{p+=y;const j=p.split(`
@@ -681,12 +681,12 @@ Delete anyway by removing these dependency references first?`,danger:!0}))return
681
681
  `).map((s,a)=>{let r="";return s.startsWith("+")&&!s.startsWith("+++")?r="diff-add":s.startsWith("-")&&!s.startsWith("---")?r="diff-del":s.startsWith("@@")&&(r="diff-hunk"),r?t.jsx("span",{className:r,children:`${s}
682
682
  `},a):t.jsx(ga.Fragment,{children:`${s}
683
683
  `},a)})}function gP(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function bP({isOpen:e,taskId:n,files:s,stats:a,mergeDetails:r,column:o,onClose:l,onRefresh:c}){const[d,u]=i.useState(null),[m,h]=i.useState(!0),f=i.useRef(null);zi(f,e,"fusion:changes-diff-modal-size");const p=sa(l);i.useEffect(()=>{s.length>0&&d===null&&u(0)},[s,d]);const g=i.useCallback(()=>{u(y=>y!==null&&y>0?y-1:y)},[]),w=i.useCallback(()=>{u(y=>y!==null&&y<s.length-1?y+1:y)},[]);if(i.useEffect(()=>{if(!e)return;const y=S=>{if(S.key==="Escape"){l();return}S.key==="ArrowUp"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),g()),S.key==="ArrowDown"&&(S.metaKey||S.ctrlKey)&&(S.preventDefault(),w())};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[e,l,g,w]),!e)return null;const v=d!==null?s[d]:null,b=o==="done";return t.jsx("div",{className:"modal-overlay open",...p,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal changes-diff-modal",ref:f,children:[t.jsxs("div",{className:"modal-header changes-diff-modal-header",children:[t.jsxs("div",{className:"changes-diff-header-title",children:[t.jsx(Si,{size:18}),t.jsxs("span",{children:["Changes — ",n]}),t.jsxs("span",{className:"changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",a.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",a.deletions]})]})]}),t.jsxs("div",{className:"changes-diff-header-actions",children:[s.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:g,disabled:d===null||d<=0,title:"Previous file (Ctrl+↑)","aria-label":"Previous file",children:t.jsx(pc,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:d!==null?`${d+1}/${s.length}`:`—/${s.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:w,disabled:d===null||d>=s.length-1,title:"Next file (Ctrl+↓)","aria-label":"Next file",children:t.jsx(qn,{})})]}),t.jsx("button",{className:`btn btn-sm ${m?"btn-primary":""}`,onClick:()=>h(y=>!y),title:m?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Vl,{size:14})}),c&&t.jsxs("button",{className:"btn btn-sm",onClick:c,children:[t.jsx(ps,{size:14}),"Refresh"]}),t.jsx("button",{className:"modal-close",onClick:l,"aria-label":"Close",children:t.jsx(mn,{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(Nr,{size:14}),t.jsx("code",{children:r.commitSha.slice(0,7)})]}),r.mergeCommitMessage&&t.jsx("div",{className:"commit-diff-message",children:r.mergeCommitMessage}),r.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(r.mergedAt).toLocaleString()]})]}),t.jsx("div",{className:"changes-diff-file-list",children:s.map((y,S)=>t.jsxs("button",{className:`changes-diff-file-item ${d===S?"selected":""}`,onClick:()=>u(S),title:y.path,children:[t.jsx("span",{className:`changes-file-status changes-file-status--${y.status}`,children:gP(y.status)}),t.jsx("span",{className:"changes-diff-file-path",title:y.path,children:t.jsx("bdo",{dir:"ltr",children:y.path})}),t.jsxs("span",{className:"changes-diff-file-stat",children:["+",y.additions," -",y.deletions]})]},y.path))})]}),t.jsx("div",{className:"changes-diff-content",children:v?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"changes-diff-file-header-bar",children:[t.jsx("span",{className:"changes-diff-file-header-name",children:v.path}),t.jsxs("span",{className:"changes-diff-file-header-stats",children:["+",v.additions," -",v.deletions]})]}),v.patch?t.jsx("div",{className:"changes-diff-viewer",children:t.jsx("pre",{className:`changes-diff-patch ${m?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:hv(v.patch)})})}):t.jsx("div",{className:"changes-diff-empty",children:"No diff available for this file."})]}):t.jsxs("div",{className:"changes-diff-empty",children:[t.jsx(Si,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to view its diff"})]})})]})]})})}function pv(e){switch(e){case"added":return"A";case"deleted":return"D";case"modified":return"M";default:return"?"}}function Sd(e,n,s){return t.jsxs("div",{className:"detail-section task-changes-tab",children:[n&&s&&t.jsxs("div",{className:"commit-diff-meta",children:[s.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Nr,{size:14}),t.jsx("code",{children:s.commitSha.slice(0,7)})]}),s.mergedAt&&t.jsxs("div",{className:"commit-diff-timestamp",children:["Merged ",new Date(s.mergedAt).toLocaleString()]})]}),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Si,{size:24}),t.jsxs("p",{children:[e.length," file",e.length===1?"":"s"," modified during execution."]}),t.jsx("span",{className:"task-changes-state-hint",children:n?"The recorded merge commit has no diff (likely collapsed into a squash on main). Showing file paths only — patches unavailable.":"The live worktree diff is empty. Showing the last file paths captured during execution — patches unavailable."})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:e.map(a=>t.jsx("div",{className:"changes-file-item",children:t.jsxs("div",{className:"changes-file-header changes-file-header--static",children:[t.jsx("span",{className:"changes-file-status changes-file-status--unknown",title:"status unknown",children:pv("unknown")}),t.jsx("span",{className:"changes-file-path",title:a,children:t.jsx("bdo",{dir:"ltr",children:a})})]})},a))})]})}function xP({taskId:e,worktree:n,projectId:s,column:a,mergeDetails:r,modifiedFiles:o}){const[l,c]=i.useState([]),[d,u]=i.useState({filesChanged:0,additions:0,deletions:0}),[m,h]=i.useState(!0),[f,p]=i.useState(null),[g,w]=i.useState([]),[v,b]=i.useState(null),[y,S]=i.useState(new Set),[j,C]=i.useState(null),[x,N]=i.useState(!0),[R,F]=i.useState(!1),E=a==="done",_=E&&!!r?.commitSha,K=a==="in-progress"||a==="in-review"||_,U=i.useCallback(async()=>{if(!K&&!E){h(!1);return}try{h(!0),p(null);const O=await C1(e,s);if(b(O.lineageId),w(O.associations),!K){c([]),u({filesChanged:0,additions:0,deletions:0});return}const M=await yb(e,void 0,s),D=M.files.map($=>({path:$.path,status:$.status,additions:$.additions,deletions:$.deletions,patch:$.patch}));c(D),u(M.stats),D.length>0&&(S(new Set([D[0].path])),C(0))}catch(O){p(Se(O)||"Failed to load task changes")}finally{h(!1)}},[e,s,K,E]);i.useEffect(()=>{U()},[U]);const A=O=>{S(M=>{const D=new Set(M);if(D.has(O))D.delete(O);else{D.add(O);const $=l.findIndex(k=>k.path===O);$!==-1&&C($)}return D})},T=O=>{if(O<0||O>=l.length)return;const M=l[O].path;S(new Set([M])),C(O)},H=j!==null&&j>0,Q=j!==null&&j<l.length-1;if(m)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--loading",children:[t.jsx("div",{className:"loading-spinner"}),t.jsx("span",{children:"Loading changes..."})]})});if(f)return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--error",children:[t.jsx(Vs,{size:16}),t.jsxs("span",{children:["Error loading changes: ",f]})]})});if(!E&&!n)return o&&o.length>0?Sd(o,!1):t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Si,{size:24}),t.jsx("p",{children:"No worktree available for this task."}),t.jsx("span",{className:"task-changes-state-hint",children:"Changes will be shown once the task is in progress."})]})});if(E&&!_){if(o&&o.length>0)return Sd(o,!0,r);const O=r?.filesChanged,M=r?.insertions,D=r?.deletions,$=O!=null||M!=null||D!=null;return t.jsx("div",{className:"detail-section",children:t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Si,{size:24}),t.jsx("p",{children:"Detailed file changes unavailable."}),t.jsx("span",{className:"task-changes-state-hint",children:$?`Merge summary: ${O??0} file${(O??0)===1?"":"s"} changed, +${M??0} additions, -${D??0} deletions.`:"No merge commit was recorded for this task."})]})})}const se=()=>t.jsxs("section",{className:"task-lineage-associations","aria-label":"Task commit associations",children:[t.jsxs("div",{className:"task-lineage-associations-header",children:[t.jsxs("h4",{children:[t.jsx(Nr,{size:16}),"Lineage commit associations"]}),v&&t.jsx("code",{className:"task-lineage-id",children:v})]}),g.length===0?t.jsx("p",{className:"task-lineage-associations-empty",children:"No associated commits recorded yet."}):t.jsx("div",{className:"task-lineage-associations-list",children:g.map(O=>{const M=O.matchedBy.replace(/-/g," ");return t.jsxs("article",{className:`task-lineage-association task-lineage-association--${O.confidence}`,children:[t.jsxs("div",{className:"task-lineage-association-main",children:[t.jsx("code",{className:"task-lineage-sha",children:O.commitSha.slice(0,7)}),t.jsx("span",{className:"task-lineage-subject",children:O.commitSubject})]}),t.jsxs("div",{className:"task-lineage-association-meta",children:[t.jsx("span",{children:new Date(O.authoredAt).toLocaleString()}),t.jsxs("span",{children:["Confidence: ",O.confidence]}),t.jsxs("span",{children:["Match: ",M]}),t.jsxs("span",{children:["Task snapshot: ",O.taskIdSnapshot]})]}),O.note&&t.jsx("p",{className:"task-lineage-note",children:O.note})]},`${O.commitSha}-${O.matchedBy}`)})})]});return l.length===0?o&&o.length>0?Sd(o,E,r):t.jsxs("div",{className:"detail-section task-changes-tab",children:[se(),t.jsxs("div",{className:"task-changes-state task-changes-state--empty",children:[t.jsx(Si,{size:24}),t.jsx("p",{children:"No files modified."}),t.jsx("span",{className:"task-changes-state-hint",children:E?"No file changes were recorded in the merge commit.":"The agent did not modify any files during execution."})]})]}):t.jsxs("div",{className:"detail-section task-changes-tab",children:[se(),E&&r&&t.jsxs("div",{className:"commit-diff-meta",children:[r.commitSha&&t.jsxs("div",{className:"commit-diff-sha",children:[t.jsx(Nr,{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(Si,{size:16}),"Files Changed (",d.filesChanged,")"]}),t.jsxs("span",{className:"task-changes-stats changes-stat-summary",children:[t.jsxs("span",{className:"diff-add",children:["+",d.additions]})," ",t.jsxs("span",{className:"diff-del",children:["-",d.deletions]})]})]}),t.jsxs("div",{className:"changes-header-actions-wrapper",children:[t.jsxs("div",{className:"changes-header-actions",children:[l.length>0&&t.jsxs("div",{className:"changes-nav",children:[t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>H&&T(j-1),disabled:!H,title:"Previous file","aria-label":"Previous file",children:t.jsx(pc,{})}),t.jsx("span",{className:"changes-nav-indicator","aria-live":"polite",children:j!==null?`${j+1}/${l.length}`:`—/${l.length}`}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>Q&&T(j+1),disabled:!Q,title:"Next file","aria-label":"Next file",children:t.jsx(qn,{})})]}),t.jsx("button",{className:`btn btn-sm ${x?"btn-primary":""}`,onClick:()=>N(O=>!O),title:x?"Disable word wrap":"Enable word wrap","aria-label":"Toggle word wrap",children:t.jsx(Vl,{size:14})})]}),t.jsxs("div",{className:"changes-header-actions-secondary",children:[t.jsx("button",{className:"btn btn-sm",onClick:U,disabled:m,children:"Refresh"}),t.jsx("button",{className:"btn btn-sm btn-icon",onClick:()=>F(!0),title:"Expand to full-screen diff view","aria-label":"Expand diff view",children:t.jsx(wc,{})})]})]})]}),t.jsx("div",{className:"changes-file-list task-changes-file-list--compact",children:l.map(O=>{const M=y.has(O.path);return t.jsxs("div",{className:`changes-file-item ${M?"expanded":""}`,children:[t.jsxs("button",{className:"changes-file-header",onClick:()=>A(O.path),children:[t.jsx("span",{className:"changes-file-toggle",children:M?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})}),t.jsx("span",{className:`changes-file-status changes-file-status--${O.status}`,title:O.status,children:pv(O.status)}),t.jsx("span",{className:"changes-file-path",title:O.path,children:t.jsx("bdo",{dir:"ltr",children:O.path})}),t.jsxs("span",{className:"changes-file-stat",title:`+${O.additions} -${O.deletions}`,children:["+",O.additions," -",O.deletions]})]}),M&&O.patch&&t.jsx("div",{className:"changes-file-content",children:t.jsx("pre",{className:`changes-diff-patch ${x?"changes-diff-patch--wrap":"changes-diff-patch--nowrap"}`,children:t.jsx("code",{children:hv(O.patch)})})})]},O.path)})}),t.jsx(bP,{isOpen:R,taskId:e,files:l,stats:d,mergeDetails:r,column:a,onClose:()=>F(!1),onRefresh:U})]})}function Xp(e){return{executorValue:e?.executorProvider&&e?.executorModelId?`${e.executorProvider}/${e.executorModelId}`:"",validatorValue:e?.validatorProvider&&e?.validatorModelId?`${e.validatorProvider}/${e.validatorModelId}`:""}}function vP(e){return e.trim().toLowerCase().replace(/[^a-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^[-_]+|[-_]+$/g,"").slice(0,32)||"preset"}function T8(e,n){const s=vP(e),a=new Set(n.map(c=>c.id));if(!a.has(s))return s;const r=30;let o=s,l=1;for(;a.has(o)&&l<100;){const c=`-${l}`;o=`${s.slice(0,r-c.length)}${c}`,l++}return o}function Zp(e){const n=e?.trim()??"";return Sc.test(n)?n:""}function fv(e,n){const s=Zp(e?.githubTrackingDefaultRepo);return s||Zp(n?.githubTrackingDefaultRepo)}function yP(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}const ef=["image/png","image/jpeg","image/gif","image/webp"];function wP(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function gv({mode:e,description:n,onDescriptionChange:s,title:a,onTitleChange:r,dependencies:o,onDependenciesChange:l,branch:c,onBranchChange:d,baseBranch:u,onBaseBranchChange:m,nodeId:h,onNodeIdChange:f,nodeOptions:p,nodeOverrideDisabled:g=!1,nodeOverrideDisabledReason:w,priority:v,onPriorityChange:b,executorModel:y,onExecutorModelChange:S,validatorModel:j,onValidatorModelChange:C,planningModel:x,onPlanningModelChange:N,thinkingLevel:R,onThinkingLevelChange:F,presetMode:E,onPresetModeChange:_,selectedPresetId:K,onSelectedPresetIdChange:U,selectedWorkflowSteps:A,onWorkflowStepsChange:T,onDefaultOnApplied:H,pendingImages:Q,onImagesChange:se,tasks:O,projectId:M,disabled:D=!1,addToast:$,isActive:k=!0,onAutoSaveDescription:X,onPlanningMode:le,onSubtaskBreakdown:ke,onClose:He,renderBelowPrimary:ye,renderBelowModelConfiguration:je,hideDependencies:ne,autoExpandMoreOptionsOnSelection:fe=!0,reviewLevel:Z,onReviewLevelChange:re,executionMode:q,onExecutionModeChange:L,githubTrackingEnabled:xe,onGithubTrackingEnabledChange:he,githubRepoOverride:B,onGithubRepoOverrideChange:pe}){const ze=(ne?!1:o.length>0)||Q.length>0||A.length>0||E!=="default"||(v??Ps)!==Ps||y!==""||j!==""||(x||"")!==""||(R||"")!==""||Z!==void 0||q==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||xe===!0||(B||"")!=="",[ae,Ve]=i.useState(!1),[Te,rt]=i.useState(fe?ze:!1),[Be,ce]=i.useState(""),[Re,Le]=i.useState([]),[ct,Ue]=i.useState([]),[ue,oe]=i.useState([]),[Ee,ft]=i.useState(!1),[ht,tt]=i.useState(null),[xt,Me]=i.useState(null),[Ye,dt]=i.useState([]),[wt,St]=i.useState("idle"),[Fe,J]=i.useState(!1),[me,Ze]=i.useState(!1),[be,gt]=i.useState(!1),$t=i.useRef(null),Ie=i.useRef(null),ge=i.useRef(null),st=i.useRef(null),yt=i.useRef(null),pt=i.useRef(null),vt=i.useRef(null),Ut=i.useRef(!1),Dt=i.useRef(ze),nn=i.useRef(n.trim()),on=i.useRef(n.trim());i.useEffect(()=>{k&&(ft(!0),Ws().then(W=>{Le(W.models),Ue(W.favoriteProviders),oe(W.favoriteModels)}).catch(()=>{}).finally(()=>ft(!1)),kc(M).then(W=>tt(W)).catch(()=>tt(null)),Ko(M).then(W=>dt(W.filter(Y=>Y.enabled))).catch(()=>dt([])),na().then(W=>Me(W)).catch(()=>Me(null)))},[k,M]);const sn=ht?.modelPresets||[],ln=sn.find(W=>W.id===K),xn=fv(ht,xt),qt=(B||"").trim(),Qt=qt.length>0&&!Sc.test(qt),hn=(ne?!1:o.length>0)||Q.length>0||A.length>0||E!=="default"||(v??Ps)!==Ps||y!==""||j!==""||(x||"")!==""||(R||"")!==""||Z!==void 0||q==="fast"||(c||"")!==""||(u||"")!==""||(h||"")!==""||xe===!0||(B||"")!=="";i.useEffect(()=>{if(e!=="create"||!k||!ht?.autoSelectModelPreset)return;const W=(ht.defaultPresetBySize,void 0);if(W){const Y=Xp(W);U(W.id),_("preset"),S(Y.executorValue),C(Y.validatorValue)}},[k,ht,sn,e]);const Zt=i.useRef(!1),ve=i.useRef(!1);i.useEffect(()=>{if(e!=="create"||!k||Zt.current||Ye.length===0)return;const W=Ye.filter(_e=>_e.defaultOn);if(W.length===0)return;Zt.current=!0;const Y=W.map(_e=>_e.id);T(Y),H?.(Y)},[e,k,Ye]),i.useEffect(()=>{k||(Zt.current=!1)},[k]),i.useEffect(()=>{e!=="create"||!k||he&&(ve.current||ht&&(he(ht.githubTrackingEnabledByDefault??!1),ve.current=!0))},[e,k,ht,he]),i.useEffect(()=>{k||(ve.current=!1)},[k]),i.useEffect(()=>{if(!fe){Dt.current=hn;return}hn&&!Dt.current&&rt(!0),Dt.current=hn},[hn,fe]),i.useEffect(()=>{Te||(Ve(!1),ce(""))},[Te]),i.useEffect(()=>{e!=="edit"||!k||st.current&&(st.current.focus(),st.current.select())},[e,k]),i.useEffect(()=>{if(!ae)return;const W=Y=>{Ie.current&&!Ie.current.contains(Y.target)&&Ve(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[ae]),i.useEffect(()=>{(e!=="edit"||D)&&gt(!1)},[e,D]),i.useEffect(()=>{if(e!=="edit"){St("idle");return}const W=n.trim();nn.current=W,on.current=W,St("idle")},[e]),i.useEffect(()=>{if(e!=="edit"||!X||!k)return;const W=n.trim(),Y=nn.current;if(W===Y||W===on.current){pt.current&&(clearTimeout(pt.current),pt.current=null),Ut.current||St("idle");return}return pt.current&&clearTimeout(pt.current),pt.current=setTimeout(async()=>{if(!Ut.current){Ut.current=!0,St("saving");try{await X(W),on.current=W,St("saved"),vt.current&&clearTimeout(vt.current),vt.current=setTimeout(()=>{St("idle"),vt.current=null},2e3)}catch{St("idle")}finally{Ut.current=!1,pt.current=null}}},1500),()=>{pt.current&&(clearTimeout(pt.current),pt.current=null)}},[e,n,X,k]),i.useEffect(()=>()=>{pt.current&&clearTimeout(pt.current),vt.current&&clearTimeout(vt.current)},[]),i.useEffect(()=>{if(!Fe)return;const W=Y=>{$t.current&&!$t.current.contains(Y.target)&&J(!1)};return document.addEventListener("mousedown",W),()=>document.removeEventListener("mousedown",W)},[Fe]);const Pe=i.useCallback(W=>{const Y=W.clipboardData?.items;if(Y)for(let _e=0;_e<Y.length;_e++){const ut=Y[_e];if(ut.type.startsWith("image/")){const At=ut.getAsFile();if(At&&ef.includes(At.type)){W.preventDefault(),se([...Q,{file:At,previewUrl:URL.createObjectURL(At)}]);return}}}},[Q,se]),Ke=i.useCallback(W=>{W.preventDefault();const Y=W.dataTransfer.files;for(let _e=0;_e<Y.length;_e++){const ut=Y[_e];if(ef.includes(ut.type)){se([...Q,{file:ut,previewUrl:URL.createObjectURL(ut)}]);return}}},[Q,se]),at=i.useCallback(W=>{const Y=Q[W];Y&&URL.revokeObjectURL(Y.previewUrl),se(Q.filter((_e,ut)=>ut!==W))},[Q,se]),We=i.useCallback(W=>{l(o.includes(W)?o.filter(Y=>Y!==W):[...o,W])},[o,l]),It=(W,Y)=>W.length>Y?W.slice(0,Y)+"…":W,Lt=i.useCallback(W=>{s(W.target.value);const Y=W.target;Y.style.height="auto",Y.style.height=Y.scrollHeight+"px"},[s]),Bt=i.useCallback(()=>{gt(W=>!W)},[]),Gt=i.useCallback(W=>{!be||W.key!=="Escape"||(W.preventDefault(),W.stopPropagation(),gt(!1))},[be]),bt=i.useCallback(async W=>{const Y=n.trim();if(!(!Y||me)){Ze(!0);try{const _e=await fb(Y,W,M);s(_e),J(!1),$("Description refined with AI","success"),ge.current&&(ge.current.style.height="auto",ge.current.style.height=ge.current.scrollHeight+"px")}catch(_e){const ut=gb(_e);$(ut,"error")}finally{Ze(!1)}}},[n,me,$,s,M]),Ot=i.useCallback(async W=>{const Y=ct,ut=Y.includes(W)?Y.filter(At=>At!==W):[W,...Y];Ue(ut);try{await Bn({favoriteProviders:ut,favoriteModels:ue})}catch{Ue(Y)}},[ct,ue]),en=i.useCallback(async W=>{const Y=ue,ut=Y.includes(W)?Y.filter(At=>At!==W):[W,...Y];oe(ut);try{await Bn({favoriteProviders:ct,favoriteModels:ut})}catch{oe(Y)}},[ue,ct]),Kt=i.useCallback(W=>{if(W<=0)return;const Y=[...A];[Y[W-1],Y[W]]=[Y[W],Y[W-1]],T(Y)},[A,T]),Sn=i.useCallback(W=>{if(W>=A.length-1)return;const Y=[...A];[Y[W],Y[W+1]]=[Y[W+1],Y[W]],T(Y)},[A,T]),dn=i.useCallback(W=>{T(A.filter(Y=>Y!==W))},[A,T]),Jt=new Map;for(const W of Ye)Jt.set(W.id,{name:W.name,description:W.description});const tn=O.filter(W=>!o.includes(W.id)).sort((W,Y)=>{const _e=Y.createdAt.localeCompare(W.createdAt);if(_e!==0)return _e;const ut=parseInt(W.id.slice(W.id.lastIndexOf("-")+1),10)||0;return(parseInt(Y.id.slice(Y.id.lastIndexOf("-")+1),10)||0)-ut}),Ne=Be?tn.filter(W=>W.id.toLowerCase().includes(Be.toLowerCase())||W.title&&W.title.toLowerCase().includes(Be.toLowerCase())||W.description&&W.description.toLowerCase().includes(Be.toLowerCase())):tn;return t.jsxs("div",{className:"task-form",onDrop:Ke,onDragOver:W=>W.preventDefault(),onPaste:Pe,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:st,autoFocus:!0,id:"task-form-title",type:"text",className:"modal-edit-input",placeholder:"Task title",value:a||"",onChange:W=>r(W.target.value),disabled:D})]}),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${wt==="idle"?"":" is-visible"}`,"aria-live":"polite",children:wt==="saving"?"Saving...":wt==="saved"?"Saved":""})]}),t.jsxs("div",{className:`description-with-refine${be?" description--fullscreen":""}`,ref:$t,onKeyDown:Gt,children:[be&&t.jsxs("div",{className:"description-fullscreen-header",children:[t.jsx("span",{children:"Editing Description"}),t.jsx("button",{type:"button",className:"btn btn-sm description-expand-btn",onClick:Bt,"aria-label":"Collapse description",title:"Collapse description",children:t.jsx(qo,{size:14})})]}),t.jsx("textarea",{ref:ge,autoFocus:e==="create",id:"task-form-description",value:n,onChange:Lt,placeholder:"What needs to be done?",rows:e==="edit"?8:5,disabled:D||me}),(()=>{const W=!!n.trim()&&!D;return t.jsxs(t.Fragment,{children:[!be&&t.jsx("button",{type:"button",className:`btn btn-sm description-expand-btn${W?" description-expand-btn--offset":" description-expand-btn--flush"}`,onClick:Bt,"aria-label":"Expand description",title:"Expand description",children:t.jsx(wc,{size:14})}),W&&t.jsxs("button",{type:"button",className:`btn btn-sm refine-button ${me?"refine-button--loading":""}`,onClick:()=>J(Y=>!Y),disabled:me,"data-testid":"refine-button",title:"Refine description with AI",children:[t.jsx(ms,{size:12,style:{verticalAlign:"middle"}}),me?"Refining...":"Refine"]})]})})(),Fe&&t.jsxs("div",{className:"refine-menu refine-menu--modal",onMouseDown:W=>W.preventDefault(),children:[t.jsxs("div",{className:"refine-menu-item",onClick:()=>bt("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:()=>bt("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:()=>bt("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:()=>bt("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"&&(le||ke)&&t.jsxs("div",{className:"task-form-description-actions","data-testid":"task-form-description-actions",children:[le&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const W=n.trim();if(!W){$("Enter a description first","error");return}He?.(),le(W)},disabled:D||!n.trim(),"data-testid":"task-form-plan-button",children:"Plan"}),ke&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{const W=n.trim();if(!W){$("Enter a description first","error");return}He?.(),ke(W)},disabled:D||!n.trim(),"data-testid":"task-form-subtask-button",children:"Subtask"})]})]}),ye,t.jsxs("button",{type:"button",className:"task-form-more-options-toggle",onClick:()=>rt(W=>!W),"aria-expanded":Te,"aria-controls":"task-form-more-options",disabled:D,"data-testid":"task-form-more-options-toggle",children:[t.jsx("span",{children:"More options"}),Te?t.jsx(Li,{size:14}):t.jsx(gn,{size:14})]}),t.jsxs("div",{id:"task-form-more-options",className:`task-form-more-options${Te?"":" collapsed"}`,"aria-hidden":!Te,hidden:!Te,"data-testid":"task-form-more-options",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Attachments"}),Q.length>0&&t.jsx("div",{className:"inline-create-previews",children:Q.map((W,Y)=>t.jsxs("div",{className:"inline-create-preview",children:[t.jsx("img",{src:W.previewUrl,alt:W.file.name}),t.jsx("button",{type:"button",className:"inline-create-preview-remove",onClick:()=>at(Y),disabled:D,title:"Remove image",children:"×"})]},W.previewUrl))}),t.jsx("input",{ref:yt,type:"file",accept:"image/*",onChange:W=>{const Y=W.target.files?.[0];Y&&(se([...Q,{file:Y,previewUrl:URL.createObjectURL(Y)}]),W.target.value="")},style:{display:"none"}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>yt.current?.click(),disabled:D,children:"Attach Screenshot"}),t.jsx("small",{children:"You can also paste images or drag & drop"})]}),f&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"task-node-select",children:"Execution Node Override"}),t.jsxs("select",{id:"task-node-select",className:"select",value:h??"",onChange:W=>f(W.target.value||void 0),disabled:D||g,children:[t.jsx("option",{value:"",children:"Use project default / local"}),(p??[]).map(W=>t.jsxs("option",{value:W.id,children:[W.name," (",yP(W.status),")"]},W.id))]}),(()=>{const W=(p??[]).find(Y=>Y.id===h);return W?t.jsx("div",{className:"task-form-node-status",children:t.jsx(Ua,{status:W.status,showLabel:!0})}):null})(),t.jsx("small",{children:w??"Task override takes priority over project default node routing."})]}),!ne&&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:Ie,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>Ve(W=>!W),disabled:D,children:o.length>0?`${o.length} selected`:"Add dependencies"}),ae&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Be,onChange:W=>ce(W.target.value),onClick:W=>W.stopPropagation()}),Ne.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):Ne.map(W=>t.jsxs("div",{className:`dep-dropdown-item${o.includes(W.id)?" selected":""}`,onClick:()=>We(W.id),onMouseDown:Y=>Y.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:W.id}),t.jsx("span",{className:"dep-dropdown-title",children:It(W.title||W.description||W.id,30)})]},W.id))]})]}),o.length>0&&t.jsx("div",{className:"selected-deps",children:o.map(W=>t.jsxs("span",{className:"dep-chip",children:[W,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>We(W),disabled:D,children:"×"})]},W))})]})}),(d||m)&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch Settings"}),d&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-working-branch",className:"model-select-label",children:"Working branch"}),t.jsx("input",{id:"task-working-branch",className:"input",value:c||"",onChange:W=>d(W.target.value),placeholder:"e.g. feature/my-task",disabled:D})]}),m&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-base-branch",className:"model-select-label",children:"Merge target / base branch"}),t.jsx("input",{id:"task-base-branch",className:"input",value:u||"",onChange:W=>m(W.target.value),placeholder:"e.g. main",disabled:D})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Model Configuration"}),b&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"task-priority",className:"model-select-label",children:"Priority"}),t.jsx("select",{id:"task-priority","data-testid":"task-priority-select",value:v??Ps,onChange:W=>b(W.target.value),disabled:D,children:wa.map(W=>t.jsx("option",{value:W,children:W[0].toUpperCase()+W.slice(1)},W))})]}),L&&q!==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:q,onChange:W=>L(W.target.value),disabled:D,children:[t.jsx("option",{value:"standard",children:"Standard"}),t.jsx("option",{value:"fast",children:"Fast"})]})]}),Ee?t.jsx("div",{className:"model-selector-loading",children:"Loading models…"}):Re.length===0?t.jsx("small",{children:"No models available. Configure authentication in Settings."}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"model-preset",className:"model-select-label",children:"Preset"}),t.jsxs("select",{id:"model-preset",value:E==="preset"?K:E,onChange:W=>{const Y=W.target.value;if(Y==="default"){_("default"),U(""),S(""),C("");return}if(Y==="custom"){_("custom"),U("");return}const _e=sn.find(At=>At.id===Y),ut=Xp(_e);_("preset"),U(Y),S(ut.executorValue),C(ut.validatorValue)},disabled:D,children:[t.jsx("option",{value:"default",children:"Use default"}),sn.length>0?t.jsx("option",{disabled:!0,children:"──────────"}):null,sn.map(W=>t.jsx("option",{value:W.id,children:W.name},W.id)),t.jsx("option",{value:"custom",children:"Custom"})]})]}),E==="preset"&&ln?t.jsxs("small",{children:["Using preset: ",ln.name]}):null,E==="preset"?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>_("custom"),disabled:D,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(_s,{id:"executor-model",label:"Executor Model",value:y,onChange:W=>{_("custom"),U(""),S(W)},models:Re,disabled:D||E==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:ue,onToggleModelFavorite:en})]}),t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"validator-model",className:"model-select-label",children:"Reviewer"}),t.jsx(_s,{id:"validator-model",label:"Reviewer Model",value:j,onChange:W=>{_("custom"),U(""),C(W)},models:Re,disabled:D||E==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:ue,onToggleModelFavorite:en})]}),N&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"planning-model",className:"model-select-label",children:"Planning"}),t.jsx(_s,{id:"planning-model",label:"Planning Model",value:x||"",onChange:W=>{_("custom"),U(""),N(W)},models:Re,disabled:D||E==="preset",favoriteProviders:ct,onToggleFavorite:Ot,favoriteModels:ue,onToggleModelFavorite:en})]}),F&&t.jsxs("div",{className:"model-select-row",children:[t.jsx("label",{htmlFor:"thinking-level",className:"model-select-label",children:"Thinking"}),t.jsxs("select",{id:"thinking-level",value:R||"",onChange:W=>F(W.target.value),disabled:D||E==="preset",children:[t.jsxs("option",{value:"",children:["Default (",ht?.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"})]})]}),re&&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:Z??"",onChange:W=>re(W.target.value===""?void 0:parseInt(W.target.value,10)),disabled:D,children:[t.jsx("option",{value:"",children:"Default (Auto — triage decides)"}),t.jsx("option",{value:"0",children:"0 — None"}),t.jsx("option",{value:"1",children:"1 — Plan Only"}),t.jsx("option",{value:"2",children:"2 — Plan and Code"}),t.jsx("option",{value:"3",children:"3 — Full"})]})]})]})]}),je,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(W=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${W.id}`,children:[t.jsx("input",{type:"checkbox",checked:A.includes(W.id),onChange:Y=>{T(Y.target.checked?[...A,W.id]:A.filter(_e=>_e!==W.id))},disabled:D}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[W.name,wP(W.phase||"pre-merge",W.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:W.description})]})]},W.id))})]}),A.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),A.map((W,Y)=>{const _e=Jt.get(W);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${W}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:Y+1}),t.jsx("span",{className:"workflow-step-order-name",children:_e?.name||W}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Kt(Y),disabled:D||Y===0,"data-testid":`workflow-step-move-up-${W}`,title:"Move up",children:t.jsx(Li,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Sn(Y),disabled:D||Y===A.length-1,"data-testid":`workflow-step-move-down-${W}`,title:"Move down",children:t.jsx(gn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>dn(W),disabled:D,"data-testid":`workflow-step-remove-${W}`,title:"Remove",children:t.jsx(mn,{})})]})]},W)})]})]}),(he||pe)&&t.jsxs("div",{className:"form-group","data-testid":"task-form-github-tracking",children:[t.jsx("label",{children:"GitHub Tracking"}),he&&t.jsxs("label",{className:"checkbox-label",htmlFor:"task-github-tracking-enabled",children:[t.jsx("input",{id:"task-github-tracking-enabled",type:"checkbox",checked:xe===!0,onChange:W=>{ve.current=!0,he(W.target.checked)},disabled:D}),"Enable GitHub issue tracking for this task"]}),pe&&t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"task-github-repo-override",className:"model-select-label",children:"Repository (owner/repo)"}),t.jsx("input",{id:"task-github-repo-override",className:"input",value:B||"",onChange:W=>pe(W.target.value),placeholder:xn||"owner/repo",disabled:D}),Qt?t.jsx("div",{className:"form-error",children:"Repository must be in owner/repo format."}):null]})]})]})]})}const tf={p:({children:e,...n})=>t.jsx("p",{...n,children:Ys(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ys(e)}),code:({children:e,...n})=>t.jsx("code",{...n,children:Ys(e)}),pre:({children:e,className:n,...s})=>t.jsx("pre",{...s,className:["workflow-markdown-pre",n].filter(Boolean).join(" "),children:Ys(e)}),table:({children:e,className:n,...s})=>t.jsx("table",{...s,className:["workflow-markdown-table",n].filter(Boolean).join(" "),children:e})};function kP(e){switch(e){case"passed":return"Passed";case"failed":return"Failed";case"skipped":return"Skipped";case"pending":return"Running…";default:return e}}function jP(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 NP(e){return e?new Date(e).toLocaleString():null}function SP(e){const n=e.split(`
684
- `);return n.length<=1?e:`${n.length} lines`}function xl(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function CP({entries:e,startedAt:n,stepId:s}){const a=i.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return i.useEffect(()=>{const l=a.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),o.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:a,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:Cs(l.text)},c):t.jsx("span",{className:"workflow-live-log-text",children:Cs(l.text)},c))})}function EP({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[m,h]=i.useState({}),[f,p]=i.useState(null),[g,w]=i.useState([]),[v,b]=i.useState(!1),y=n.some(k=>k.status==="pending"),{entries:S}=lv(e,!!l&&y,o);i.useEffect(()=>{let k=!1;return Ko(o).then(X=>{k||w(X.filter(le=>le.enabled))}).catch(()=>{k||w([])}),()=>{k=!0}},[o]);const j=a??[],C=i.useMemo(()=>g.map(k=>({id:k.id,name:k.name,description:k.description,phase:k.phase||"pre-merge"})),[g]),x=i.useMemo(()=>new Map(C.map(k=>[k.id,k])),[C]),N=k=>{u(X=>({...X,[k]:!X[k]}))},R=k=>{h(X=>{const le=X[k]??"markdown";return{...X,[k]:le==="markdown"?"plain":"markdown"}})},F=k=>{p(k)},E=()=>{p(null)};i.useEffect(()=>{if(!f)return;const k=X=>{X.key==="Escape"&&E()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[f]);const _=i.useCallback((k,X)=>{if(c){if(X){if(j.includes(k)){c(j);return}c([...j,k]);return}c(j.filter(le=>le!==k))}},[c,j]),K=i.useCallback(k=>{if(!c||k<=0)return;const X=[...j];[X[k-1],X[k]]=[X[k],X[k-1]],c(X)},[c,j]),U=i.useCallback(k=>{if(!c||k>=j.length-1)return;const X=[...j];[X[k],X[k+1]]=[X[k+1],X[k]],c(X)},[c,j]),A=i.useCallback(k=>{c&&c(j.filter(X=>X!==k))},[c,j]),T=n.length>0,H=j.length>0;i.useEffect(()=>{r||b(!1)},[r]);const Q=i.useMemo(()=>j.map(k=>{const X=x.get(k);return{id:k,name:X?.name||k,description:X?.description||"Step definition not found.",phase:X?.phase||"pre-merge"}}),[j,x]),se=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:C.map(k=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${k.id}`,children:[t.jsx("input",{type:"checkbox",checked:j.includes(k.id),onChange:X=>_(k.id,X.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,xl(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),j.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),j.map((k,X)=>{const le=x.get(k);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${k}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:X+1}),t.jsx("span",{className:"workflow-step-order-name",children:le?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>K(X),disabled:X===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(Li,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(X),disabled:X===j.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(gn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(k),"data-testid":`workflow-step-remove-${k}`,title:"Remove",children:t.jsx(mn,{})})]})]},k)})]})]}),O=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!T)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const k=n.filter(ye=>ye.status==="passed").length,X=n.filter(ye=>ye.status==="failed").length,le=n.filter(ye=>ye.status==="skipped").length,ke=n.filter(ye=>ye.status==="pending").length,He=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&He.push(`${k} passed`),X>0&&He.push(`${X} failed`),le>0&&He.push(`${le} skipped`),ke>0&&He.push(`${ke} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:He.join(" · ")}),n.map((ye,je)=>{const ne=ye.phase||"pre-merge",fe=d[ye.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ye.status}`,"data-testid":`workflow-result-item-${ye.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ye.workflowStepName,xl(ne,ye.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ye.status}`,"data-testid":`workflow-result-badge-${ye.workflowStepId}`,children:kP(ye.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ye.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",NP(ye.startedAt)]}),ye.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:jP(ye.startedAt,ye.completedAt)})]}),ye.status==="pending"&&ye.startedAt?t.jsx(CP,{entries:S,startedAt:ye.startedAt,stepId:ye.workflowStepId}):ye.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>N(ye.workflowStepId),"data-testid":`workflow-result-toggle-${ye.workflowStepId}`,children:fe?"Hide output":"Show output"}),!fe&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ye.workflowStepId}`,children:SP(ye.output)}),fe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(ye.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ye.workflowStepId}`,title:(m[ye.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ye.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>F(ye.workflowStepId),"data-testid":`workflow-result-expand-${ye.workflowStepId}`,title:"Expand output",children:t.jsx(wc,{size:12})})]})]}),fe&&t.jsx("div",{className:`workflow-result-output${(m[ye.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ye.workflowStepId}`,children:(m[ye.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:tf,children:ye.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Cs(ye.output)})})]}):null]},`${ye.workflowStepId}-${je}`)})]})},M=r?t.jsx("button",{type:"button",className:"btn btn-sm workflow-results-edit-toggle",onClick:()=>b(k=>!k),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(ks,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Hs,{size:14}),"Edit"]})}):null,D=!s&&!T&&H,$=r&&T;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[D?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[Q.length," step",Q.length===1?"":"s"]})]}),M]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Q.map(k=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${k.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[t.jsx("span",{className:"workflow-configured-name-text",children:k.name}),xl(k.phase,k.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:k.description})]},k.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),se()]}):t.jsxs(t.Fragment,{children:[$&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),M]}),O(),se()]}),f&&(()=>{const k=n.find(ke=>ke.workflowStepId===f);if(!k)return null;const X=m[k.workflowStepId]??"markdown",le=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ke=>{ke.target===ke.currentTarget&&E()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:k.workflowStepName}),xl(le,k.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:X==="markdown"?"Switch to plain text":"Switch to markdown",children:X==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(mn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${X==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:X==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:tf,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Cs(k.output)})})})]})})})()]})}function _P(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const MP=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function AP(e){return e!==void 0&&e!=="online"}function RP({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,h]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),Yl().then(E=>{o(E)}).catch(E=>{u(Se(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const w=i.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),v=i.useMemo(()=>[...r].sort((E,_)=>E.name.localeCompare(_.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",j=y?w.get(y):void 0,C=j?`${j.name} (${j.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",x=e.column==="in-progress"||MP.has(e.status),N=x||f||l,R=i.useCallback(async E=>{if(E===m)return;const _=e.id,K=m;h(E),p(!0);try{const U=await Us(_,{nodeId:E||null});if(g.current!==_)return;h(U.nodeId??""),a?.(U),s(E?"Node override updated":"Node override cleared","success")}catch(U){if(g.current!==_)return;h(K),s(Se(U)||"Failed to update node override","error")}finally{g.current===_&&p(!1)}},[s,a,m,e.id]),F=i.useCallback(()=>{R("")},[R]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(Ua,{status:j.status,compact:!0}):null,C,AP(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:_P(b?.unavailableNodePolicy)})]})]}),x&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),x?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:N,onChange:E=>{R(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(E=>t.jsxs("option",{value:E.id,title:`Status: ${E.status}`,children:[E.name," (",E.type,") — ",E.status]},E.id))]}),d?t.jsx("div",{className:"routing-tab__error",children:d}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",w.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:x||f,onClick:F,children:"Clear override"})]}):null]})]})}const IP=/^[a-zA-Z0-9_-]{1,64}$/,TP=200;function nf(e){return e?new Date(e).toLocaleString():""}function PP(e,n=TP){return e.length<=n?e:e.substring(0,n)+"…"}function $P({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(""),[p,g]=i.useState(null),[w,v]=i.useState(""),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,x]=i.useState(!1),[N,R]=i.useState(!1),[F,E]=i.useState(""),[_,K]=i.useState(""),[U,A]=i.useState(!1),[T,H]=i.useState(null),[Q,se]=i.useState(null),[O,M]=i.useState(!1),D=i.useCallback(async()=>{try{const ne=await sN(e,a);l(ne)}catch(ne){n(Se(ne)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{D()},[D]);async function $(ne){u===ne.key?(m(null),f(""),g(null),v(""),y(null),j([]),M(!1)):(m(ne.key),f(ne.content),g(null),v(""),y(null),j([]),M(!1))}async function k(ne){if(b===ne)y(null),j([]);else{y(ne),x(!0);try{const fe=await iN(e,ne,a);j(fe)}catch(fe){n(Se(fe)||"Failed to load revisions","error")}finally{x(!1)}}}function X(){u&&(g(u),v(h))}function le(){g(null),v("")}async function ke(){if(!(!p||!w.trim())){A(!0);try{await Vm(e,p,w,{},a),g(null),v(""),await D();const ne=o.find(fe=>fe.key===p);ne&&f(ne.content),n("Document saved","success")}catch(ne){n(Se(ne)||"Failed to save document","error")}finally{A(!1)}}}async function He(){const ne=F.trim(),fe=_.trim();if(!ne){n("Document key is required","error");return}if(!IP.test(ne)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!fe){n("Content is required","error");return}A(!0);try{await Vm(e,ne,fe,{},a),R(!1),E(""),K(""),await D(),n("Document created","success")}catch(Z){n(Se(Z)||"Failed to create document","error")}finally{A(!1)}}async function ye(ne){H(ne);try{await aN(e,ne,a),se(null),H(null),u===ne&&(m(null),f("")),b===ne&&(y(null),j([])),await D(),n("Document deleted","success")}catch(fe){n(Se(fe)||"Failed to delete document","error")}finally{H(null)}}function je(ne){f(ne.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),N&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:F,onChange:ne=>E(ne.target.value),placeholder:"e.g., plan, notes, research",disabled:U}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:_,onChange:ne=>K(ne.target.value),rows:6,placeholder:"Enter document content…",disabled:U})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(!1),E(""),K("")},disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void He(),disabled:U||!F.trim()||!_.trim(),children:U?"Creating…":"Create"})]})]}),o.length===0&&!N?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(ne=>t.jsxs("div",{className:"task-document-card",children:[t.jsxs("div",{className:"task-document-card-header",children:[t.jsxs("div",{className:"task-document-card-title",children:[t.jsx(xa,{size:14}),t.jsx("span",{className:"task-document-key",children:ne.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",ne.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:ne.author}),t.jsx("span",{className:"task-document-timestamp",children:nf(ne.updatedAt||ne.createdAt)})]})]}),u===ne.key&&p!==ne.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>M(fe=>!fe),"aria-label":O?"Switch to plain text":"Switch to markdown","aria-pressed":O,title:O?"Switch to plain text":"Switch to markdown",children:O?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:O?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===ne.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),C?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(fe=>fe.revision<ne.revision).sort((fe,Z)=>Z.revision-fe.revision).map(fe=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>je(fe),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",fe.revision]}),t.jsx("span",{className:"revision-author",children:fe.author}),t.jsx("span",{className:"revision-timestamp",children:nf(fe.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:PP(fe.content,100)})]},fe.id))})]})]}),p===ne.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:w,onChange:fe=>v(fe.target.value),rows:10,disabled:U}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:le,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ke(),disabled:U||!w.trim(),children:U?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(ne),children:u===ne.key?t.jsxs(t.Fragment,{children:[t.jsx(Li,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(gn,{size:14})," Expand"]})}),u===ne.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(ne.key),children:[t.jsx(Oa,{size:14})," History"]}),r&&p!==ne.key&&t.jsx("button",{className:"btn btn-sm",onClick:X,children:"Edit"}),r&&(Q===ne.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void ye(ne.key),disabled:T===ne.key,children:T===ne.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>se(null),disabled:T===ne.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>se(ne.key),children:t.jsx(Tn,{size:14})}))]})]})]},ne.key))}),r&&!N&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>R(!0),children:[t.jsx($n,{size:14})," New Document"]})]})}function vl(e){return e.toLocaleString()}function Cd(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function oo(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),a=Math.round(n%60);return`${s}m ${a}s`}function DP(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const d=new Date(o.completedAt).getTime();if(Number.isNaN(d)||d<l)return null;c=d}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),a=Wb(e,n)??0,r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:a,longestStep:r}}function LP({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=qb(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,w)=>g+(w.durationMs??0),0),c=Vb(s?.log)??0,d=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(l,c),u=o.reduce((g,w)=>!g||(w.durationMs??0)>(g.durationMs??0)?w:g,void 0),m=DP(s?.workflowStepResults??[]),f=Gb(s?.executionStartedAt,s?.executionCompletedAt,a)??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:d+m.totalDurationMs),p=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:r.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:oo(d)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:m.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:oo(m.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:oo(f)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:u?.durationMs?`${u.summary} (${oo(u.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:m.longestStep?`${m.longestStep.name} (${oo(m.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:p>0?`${Math.min((s?.currentStep??0)+1,p)} / ${p}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${Cd(s.nextRecoveryAt)}`:"No scheduled recovery"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Self-heal counters"}),t.jsx("dd",{children:`stuck kills: ${s?.stuckKillCount??0}, post-review fixes: ${s?.postReviewFixCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime links"}),t.jsx("dd",{children:[s?.assignedAgentId?`agent ${s.assignedAgentId}`:null,s?.checkedOutBy?`checkout ${s.checkedOutBy}`:null,s?.blockedBy?`blocked by ${s.blockedBy}`:null,s?.sessionFile?"has session":null].filter(Boolean).join(", ")||"No runtime links"})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Token Usage"}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),t.jsx("span",{className:"task-token-stats-panel__value",children:vl(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),t.jsx("span",{className:"task-token-stats-panel__value",children:vl(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),t.jsx("span",{className:"task-token-stats-panel__value",children:vl(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),t.jsx("span",{className:"task-token-stats-panel__value",children:vl(e.totalTokens)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"First used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:Cd(e.firstUsedAt)})})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Last used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.lastUsedAt,children:Cd(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const km=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),sf={p:({children:e,...n})=>t.jsx("p",{...n,children:Ys(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ys(e)}),code:({children:e,...n})=>{const s=typeof e=="string"?e:ga.Children.toArray(e).join(""),a=Cs(s);return a.length===1&&typeof a[0]=="string"?t.jsx("code",{...n,children:e}):t.jsx("code",{...n,children:a})}};function OP(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const a=s.text.match(/^Executor using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function FP(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const a=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function bv(e){const n=e?.runtimeConfig??void 0,s=typeof n?.model=="string"?n.model.trim():"";if(s){const o=s.indexOf("/");if(o>0&&o<s.length-1)return{provider:s.slice(0,o),modelId:s.slice(o+1)}}const a=typeof n?.modelProvider=="string"?n.modelProvider.trim():"",r=typeof n?.modelId=="string"?n.modelId.trim():"";return{provider:a||void 0,modelId:r||void 0}}function zP(e,n,s,a){const r=OP(n);if(r)return r;if(km.has(e.status??"")||e.column==="in-progress"){const o=bv(s);if(o.provider&&o.modelId)return o}return Tb(e,a)}function BP(e,n,s,a){const r=FP(n);if(r)return r;if(km.has(e.status??"")||e.column==="in-progress"){const o=bv(s);if(o.provider&&o.modelId)return o}return Pb(e,a)}function UP(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const a=s.text.match(/^Triage using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function HP(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=UP(n);return a||$b(e,s)}function qP(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--in-progress)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function Ed(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function VP(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function _d(e,n){return e.length>n?e.slice(0,n)+"…":e}function af(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Md(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Ad(e){return e.trim()}function WP(e){const n=e.trim();return n.length>0?n:void 0}function Ki(e){return typeof e=="string"&&wa.includes(e)?e:Ps}function Ji(e){return e==="fast"?"fast":"standard"}function GP(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function KP(e){const n=e?.findingLabel;if(typeof n=="string"&&n.length>0)return n;const s=e?.runId;return typeof s=="string"&&s.length>0?s:void 0}const JP=i.lazy(()=>En(()=>import("./AgentDetailView-V32TpEe1.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function YP(e,n={}){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??"agent",sourceAgentId:e.sourceAgentId};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":return{label:"GitHub Import",contextInfo:GP(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:KP(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const Rd=200,QP=new Set(["triage","todo"]),XP=new Set(["triage","todo","in-progress","in-review"]);function xv({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:m,addToast:h,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:w=!1,onRequestClose:v}){const[b,y]=i.useState(p),[S,j]=i.useState(()=>"prompt"in e?e:null),[C,x]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){j(e),x(!1);return}let ee=!1;return x(!0),j(null),Ba(e.id,n).then(De=>{ee||(j(De),x(!1))}).catch(()=>{ee||x(!1)}),()=>{ee=!0}},[e.id,n]);const N=S?{...S,...e,prompt:S.prompt,log:S.log,githubTracking:e.githubTracking??S.githubTracking}:{...e,prompt:""},R=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[F,E]=i.useState(null),[_,K]=i.useState(null),U=YP(N,{sourceAgentName:F?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{Q(!1)},[e.id]);const[A,T]=i.useState("activity"),[H,Q]=i.useState(!1),[se,O]=i.useState(e.attachments||[]),[M,D]=i.useState(!1),[$,k]=i.useState(e.dependencies||[]),[X,le]=i.useState(!1),[ke,He]=i.useState(""),[ye,je]=i.useState(null),[ne,fe]=i.useState([]),[Z,re]=i.useState(!1),[q,L]=i.useState(!1),[xe,he]=i.useState(!1),[B,pe]=i.useState(!1),[ze,ae]=i.useState(!1),[Ve,Te]=i.useState(N.prompt||""),[rt,Be]=i.useState(""),[ce,Re]=i.useState(!1),[Le,ct]=i.useState(""),[Ue,ue]=i.useState(!1),[oe,Ee]=i.useState(!1),[ft,ht]=i.useState(e.title||""),[tt,xt]=i.useState(e.description||""),[Me,Ye]=i.useState(e.dependencies||[]),[dt,wt]=i.useState(e.branch??""),[St,Fe]=i.useState(e.baseBranch??""),[J,me]=i.useState(""),[Ze,be]=i.useState(""),[gt,$t]=i.useState(""),[Ie,ge]=i.useState(""),[st,yt]=i.useState("default"),[pt,vt]=i.useState(void 0),[Ut,Dt]=i.useState(Ps),[nn,on]=i.useState(e.nodeId),[sn,ln]=i.useState(Ji(e.executionMode)),[xn,qt]=i.useState(""),[Qt,hn]=i.useState(e.enabledWorkflowSteps||[]),[Zt,ve]=i.useState(e.sourceIssue?.provider??""),[Pe,Ke]=i.useState(e.sourceIssue?.repository??""),[at,We]=i.useState(e.sourceIssue?.externalIssueId??""),[It,Lt]=i.useState(e.sourceIssue?.url??""),[Bt,Gt]=i.useState([]),[bt,Ot]=i.useState(!1),[en,Kt]=i.useState(Ki(e.priority)),[Sn,dn]=i.useState(!1),[Jt,tn]=i.useState(Ji(e.executionMode)),[Ne,W]=i.useState(!1),Y=i.useRef(!1),[_e,ut]=i.useState(!1),[At,zt]=i.useState(!1),[yn,Zn]=i.useState(!1),[vn,Dn]=i.useState(!1),[de,nt]=i.useState(e.githubTracking?.repoOverride??""),[ot,_t]=i.useState(null),[G,Oe]=i.useState(null),[Mt,Xt]=i.useState(!1),_n=i.useRef(null),Pn=i.useRef(null),kn=i.useRef(null),{getSlotsForId:Vn}=Eb(n),vs=Vn("task-detail-tab").map((ee,De)=>({entry:ee,tabId:`plugin-${ee.pluginId}-${De}`})),As=typeof b=="string"&&b.startsWith("plugin-")?vs.find(ee=>ee.tabId===b)??null:null;i.useEffect(()=>(Y.current=!0,()=>{Y.current=!1}),[]);const[bn,Ht]=i.useState(void 0),[On,Fn]=i.useState(null),[as,Wn]=i.useState([]),[Rs,In]=i.useState(!1),[rs,Ns]=i.useState(e.enabledWorkflowSteps||[]),ys=e.column==="in-progress"||km.has(e.status);i.useEffect(()=>{ht(e.title||""),xt(e.description||""),wt(e.branch??""),Fe(e.baseBranch??""),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),ln(Ji(e.executionMode)),Zn(!1),Dn(!1),nt(N.githubTracking?.repoOverride??""),_t(null),Oe(null),Ee(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,N.githubTracking]),i.useEffect(()=>{Ns(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Kt(Ki(e.priority))},[e.id,e.priority]),i.useEffect(()=>{tn(Ji(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{ot!==null&&N.githubTracking?.enabled===!0===ot&&_t(null)},[ot,N.githubTracking?.enabled]),i.useEffect(()=>{let ee=!1;return kc(n).then(De=>{ee||Ht(De)}).catch(()=>{}),na().then(De=>{ee||Fn(De)}).catch(()=>{ee||Fn(null)}),()=>{ee=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let ee=!1;return In(!0),qS(e.id,n).then(De=>{ee||Wn(De)}).catch(De=>{ee||h(`Failed to load workflow results: ${Se(De)}`,"error")}).finally(()=>{ee||In(!1)}),()=>{ee=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const ee=n?`?projectId=${encodeURIComponent(n)}`:"",De=Ct=>{try{const Wt=JSON.parse(Ct.data);Wt.id===e.id&&Array.isArray(Wt.workflowStepResults)&&Wn(Wt.workflowStepResults)}catch{}};return yi(`/api/events${ee}`,{events:{"task:updated":De}})},[b,e.id,n]),i.useEffect(()=>{X||He("")},[X]),i.useEffect(()=>{if(!e.assignedAgentId){je(null);return}const ee=ne.find(Ct=>Ct.id===e.assignedAgentId);if(ee){je(ee);return}let De=!1;return uu(e.assignedAgentId,n).then(Ct=>{De||je(Ct)}).catch(()=>{De||je(null)}),()=>{De=!0}},[e.assignedAgentId,n,ne]),i.useEffect(()=>{if(!e.sourceAgentId){E(null);return}const ee=ne.find(Ct=>Ct.id===e.sourceAgentId);if(ee){E(ee);return}let De=!1;return Promise.resolve(uu(e.sourceAgentId,n)).then(Ct=>{De||E(Ct??null)}).catch(()=>{De||E(null)}),()=>{De=!0}},[e.sourceAgentId,n,ne]),i.useEffect(()=>{re(!1)},[e.id]),i.useEffect(()=>{if(!(_e||At))return;const De=Ct=>{const Wt=Ct.target,ns=_n.current?.contains(Wt),Gi=kn.current?.contains(Wt);!ns&&_e&&ut(!1),!Gi&&At&&zt(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[_e,At]),i.useEffect(()=>{if(!(_e||At))return;const De=Ct=>{Ct.key==="Escape"&&(Ct.stopPropagation(),_e&&ut(!1),At&&zt(!1))};return document.addEventListener("keydown",De),()=>document.removeEventListener("keydown",De)},[_e,At]),i.useEffect(()=>{ae(!1),Te(N.prompt||""),Be("")},[e.id,N.prompt]);const cs=QP.has(e.column)&&!bt,ss=XP.has(e.column)&&!bt,te=ot??N.githubTracking?.enabled===!0,we=N.githubTracking?.issue,P=ss&&!we&&(!te||Mt&&N.githubTracking?.enabled!==!0),Ce=ss||te||!!we,qe=we?"Linked":te?"Enabled":"Disabled",et=fv(bn??null,On),mt=de.trim(),Nt=i.useCallback(async()=>{if(!ss||Mt)return;const ee=!te;_t(ee),Xt(!0);try{const De=await Us(e.id,{githubTracking:{enabled:ee}},n);m?.(De)}catch(De){_t(N.githubTracking?.enabled===!0),h(`Failed to update ${e.id}: ${Se(De)}`,"error")}finally{Y.current&&Xt(!1)}},[h,ss,te,Mt,m,n,N.githubTracking?.enabled,e.id]),Pt=i.useCallback(async()=>{if(!(!ss||Mt)){if(mt.length>0&&!Sc.test(mt)){Oe("Repository override must be in owner/repo format");return}Oe(null),Xt(!0);try{const ee=await Us(e.id,{githubTracking:{repoOverride:mt.length>0?mt:null}},n);m?.(ee)}catch(ee){h(`Failed to update ${e.id}: ${Se(ee)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,ss,mt,Mt,m,n,e.id]),an=i.useCallback(async()=>{if(!(!te||we||Mt)){Xt(!0);try{const ee=await Us(e.id,{githubTracking:{enabled:!0}},n);m?.(ee),h("Requested GitHub tracking issue creation","info")}catch(ee){h(`Failed to update ${e.id}: ${Se(ee)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,we,te,Mt,m,n,e.id]),Cn=i.useCallback(()=>{if(!cs)return;Ee(!0),ht(e.title||""),xt(e.description||""),Ye(e.dependencies||[]),wt(e.branch??""),Fe(e.baseBranch??"");const ee=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",De=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",Ct=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";me(ee),be(De),$t(Ct),ge(e.thinkingLevel??""),on(e.nodeId),yt(ee||De||Ct?"custom":"default"),qt(""),hn(e.enabledWorkflowSteps||[]),ln(Ji(e.executionMode)),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),Gt([]),vt(e.reviewLevel),Dt(Ki(e.priority))},[cs,e]),ie=i.useCallback(()=>{Ee(!1),ht(e.title||""),xt(e.description||""),Ye(e.dependencies||[]),wt(e.branch??""),Fe(e.baseBranch??""),on(e.nodeId),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),Dt(Ki(e.priority)),ln(Ji(e.executionMode)),Bt.forEach(ee=>URL.revokeObjectURL(ee.previewUrl)),Gt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Bt]),[$e,Qe]=i.useState("idle"),Ft=i.useRef(null),cn=i.useRef(0),pn=i.useCallback(ee=>{const De={},Ct=ft.trim(),Wt=tt.trim();Ct&&Ct!==(e.title??"")&&(De.title=Ct),ee&&Wt&&Wt!==(e.description??"")&&(De.description=Wt),af(Me,e.dependencies??[])||(De.dependencies=Me),af(Qt,e.enabledWorkflowSteps??[])||(De.enabledWorkflowSteps=Qt);const ns=dt.trim()||null,Gi=e.branch??null;ns!==Gi&&(De.branch=ns);const Em=St.trim()||null,hy=e.baseBranch??null;Em!==hy&&(De.baseBranch=Em);const _m=Md(J),py=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";J!==py&&(De.modelProvider=_m?.provider??null,De.modelId=_m?.modelId??null);const Mm=Md(Ze),fy=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Ze!==fy&&(De.validatorModelProvider=Mm?.provider??null,De.validatorModelId=Mm?.modelId??null);const Am=Md(gt),gy=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";gt!==gy&&(De.planningModelProvider=Am?.provider??null,De.planningModelId=Am?.modelId??null);const by=e.thinkingLevel??"";Ie!==by&&(De.thinkingLevel=Ie!==""?Ie:null),(e.nodeId??void 0)!==nn&&(De.nodeId=nn??null),pt!==e.reviewLevel&&(De.reviewLevel=pt),Ut!==Ki(e.priority)&&(De.priority=Ut),sn!==Ji(e.executionMode)&&(De.executionMode=sn==="fast"?"fast":null);const $c=Ad(Zt),Dc=Ad(Pe),nl=Ad(at),Lc=WP(It);if($c.length===0&&Dc.length===0&&nl.length===0&&!Lc)e.sourceIssue&&(De.sourceIssue=null);else{if(!$c||!Dc||!nl)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const xy=Number.parseInt(nl,10),Oc=e.sourceIssue?.issueNumber??xy;if(!Number.isFinite(Oc)||Oc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const or={provider:$c,repository:Dc,externalIssueId:nl,issueNumber:Oc,...Lc?{url:Lc}:{}},lr=e.sourceIssue;(!lr||lr.provider!==or.provider||lr.repository!==or.repository||lr.externalIssueId!==or.externalIssueId||lr.issueNumber!==or.issueNumber||(lr.url??void 0)!==or.url)&&(De.sourceIssue=or)}return{updates:De,error:null}},[St,dt,Me,tt,sn,J,nn,gt,Ut,pt,Qt,at,Zt,Pe,It,Ie,ft,Ze,e]),jn=i.useCallback(async ee=>{const{updates:De,error:Ct}=pn(ee);if(!De)return Qe("error"),Ct&&h(`Failed to update ${e.id}: ${Ct}`,"error"),!1;if(Object.keys(De).length===0)return!0;const Wt=++cn.current;Ot(!0),Qe("saving");try{const ns=await Us(e.id,De,n);return Wt!==cn.current?void 0:(m?.(ns),Qe("saved"),!0)}catch(ns){return Wt===cn.current&&(Qe("error"),h(`Failed to update ${e.id}: ${Se(ns)}`,"error")),!1}finally{Y.current&&Wt===cn.current&&Ot(!1)}},[h,pn,m,n,e.id]),Un=i.useCallback(async ee=>{await jn(!0)},[jn]),gs=i.useCallback(async()=>{await jn(!0)&&(h(`Updated ${e.id}`,"success"),Y.current&&Ee(!1))},[h,jn,e.id]);i.useEffect(()=>{if(oe)return Ft.current&&clearTimeout(Ft.current),Ft.current=setTimeout(()=>{jn(!1)},700),()=>{Ft.current&&(clearTimeout(Ft.current),Ft.current=null)}},[oe,ft,Me,dt,St,J,Ze,gt,Ie,nn,pt,Ut,sn,Qt,Zt,Pe,at,It,jn]);const bs=i.useCallback(async ee=>{const De=Ki(ee),Ct=Ki(e.priority);if(De===Ct){Kt(Ct);return}const Wt=en;Kt(De),dn(!0);try{const ns=await Us(e.id,{priority:De},n);Kt(Ki(ns.priority)),m?.(ns),h(`Priority updated to ${Ki(ns.priority)}`,"success")}catch(ns){Kt(Wt),h(`Failed to update ${e.id}: ${Se(ns)}`,"error")}finally{Y.current&&dn(!1)}},[e.id,e.priority,n,en,m,h]),is=i.useCallback(async()=>{const De=Ji(e.executionMode)==="fast"?"standard":"fast",Ct=Jt;tn(De),W(!0);try{const Wt=await Us(e.id,{executionMode:De==="fast"?"fast":null},n),ns=Ji(Wt.executionMode);tn(ns),m?.(Wt),h(`Execution mode updated to ${ns}`,"success")}catch(Wt){tn(Ct),h(`Failed to update ${e.id}: ${Se(Wt)}`,"error")}finally{Y.current&&W(!1)}},[e.id,e.executionMode,n,Jt,m,h]),ds=i.useCallback(ee=>{oe&&(ee.key==="Escape"?(ee.preventDefault(),ie()):ee.key==="Enter"&&(ee.ctrlKey||ee.metaKey)&&(ee.preventDefault(),gs()))},[oe,ie,gs]);i.useEffect(()=>{if(oe)return document.addEventListener("keydown",ds),()=>document.removeEventListener("keydown",ds)},[oe,ds]);const xs=i.useRef(null),{nodes:ra}=Cc(),{confirm:Jn}=li(),Ui=i.useCallback(async()=>{if(!(!cs||!we||Mt||!await Jn({title:"Unlink GitHub issue?",message:"This stops Fusion from syncing with the linked GitHub issue. The issue itself will not be modified.",confirmLabel:"Unlink",danger:!0}))){Xt(!0);try{const De=await Us(e.id,{githubTracking:{issue:null}},n);m?.(De),h("GitHub issue unlinked","success")}catch(De){h(`Failed to update ${e.id}: ${Se(De)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,cs,Jn,we,Mt,m,n,e.id]),{entries:Hi,loading:Zs,loadMore:ja,hasMore:Na,total:Ya,loadingMore:Qa}=lv(e.id,b==="logs"&&A==="agent-log",n),Mn=i.useCallback(()=>{v?.()},[v]);i.useEffect(()=>{if(w)return;const ee=De=>{De.key==="Escape"&&!oe&&Mn()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[w,Mn,oe]);const ci=i.useCallback(async ee=>{try{const De=e.steps.some(ns=>ns.status!=="pending"),Ct=(ee==="todo"||ee==="triage")&&De;let Wt;if(Ct){if(await Jn({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Wt={preserveProgress:!0};else if(!await Jn({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(e.id,ee,Wt),Mn(),h(`Moved to ${hs[ee]}`,"success")}catch(De){h(Se(De),"error")}},[e.id,e.steps,r,Mn,h,Jn]),wi=i.useCallback(async()=>{if(await Jn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),Mn(),h(`Deleted ${e.id}`,"info")}catch(De){const Ct=Zu(De);if(!Ct||Ct.dependentIds.length===0){h(Se(De),"error");return}const Wt=Ct.dependentIds.join(", ");if(!await Jn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Wt}.
684
+ `);return n.length<=1?e:`${n.length} lines`}function xl(e,n,s){const a=e==="post-merge"?"phase-badge--post-merge":"phase-badge--pre-merge";return t.jsx("span",{className:`phase-badge ${a}`,"data-testid":`${s}-${n}`,children:e==="post-merge"?"Post-merge":"Pre-merge"})}function CP({entries:e,startedAt:n,stepId:s}){const a=i.useRef(null),r=new Date(n).getTime(),o=e.filter(l=>new Date(l.timestamp).getTime()>=r);return i.useEffect(()=>{const l=a.current;l&&(l.scrollTop=l.scrollHeight)},[o.length]),o.length===0?t.jsx("div",{className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:t.jsx("div",{className:"workflow-live-log-empty",children:"Waiting for agent output…"})}):t.jsx("div",{ref:a,className:"workflow-live-log","data-testid":`workflow-live-log-${s}`,children:o.map((l,c)=>l.type==="tool"?t.jsxs("div",{className:"workflow-live-log-tool",children:["⚡ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="tool_result"?t.jsxs("div",{className:"workflow-live-log-tool-result",children:["✓ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="tool_error"?t.jsxs("div",{className:"workflow-live-log-tool-error",children:["✗ ",Cs(l.text),l.detail&&t.jsxs("span",{className:"workflow-live-log-detail",children:[" — ",Cs(l.detail)]})]},c):l.type==="thinking"?t.jsx("div",{className:"workflow-live-log-thinking",children:Cs(l.text)},c):t.jsx("span",{className:"workflow-live-log-text",children:Cs(l.text)},c))})}function EP({taskId:e,results:n,loading:s,enabledWorkflowSteps:a,canEdit:r,projectId:o,isTaskInProgress:l,onWorkflowStepsChange:c}){const[d,u]=i.useState({}),[m,h]=i.useState({}),[f,p]=i.useState(null),[g,w]=i.useState([]),[v,b]=i.useState(!1),y=n.some(k=>k.status==="pending"),{entries:S}=lv(e,!!l&&y,o);i.useEffect(()=>{let k=!1;return Ko(o).then(X=>{k||w(X.filter(le=>le.enabled))}).catch(()=>{k||w([])}),()=>{k=!0}},[o]);const j=a??[],C=i.useMemo(()=>g.map(k=>({id:k.id,name:k.name,description:k.description,phase:k.phase||"pre-merge"})),[g]),x=i.useMemo(()=>new Map(C.map(k=>[k.id,k])),[C]),N=k=>{u(X=>({...X,[k]:!X[k]}))},R=k=>{h(X=>{const le=X[k]??"markdown";return{...X,[k]:le==="markdown"?"plain":"markdown"}})},F=k=>{p(k)},E=()=>{p(null)};i.useEffect(()=>{if(!f)return;const k=X=>{X.key==="Escape"&&E()};return document.addEventListener("keydown",k),()=>{document.removeEventListener("keydown",k)}},[f]);const _=i.useCallback((k,X)=>{if(c){if(X){if(j.includes(k)){c(j);return}c([...j,k]);return}c(j.filter(le=>le!==k))}},[c,j]),K=i.useCallback(k=>{if(!c||k<=0)return;const X=[...j];[X[k-1],X[k]]=[X[k],X[k-1]],c(X)},[c,j]),U=i.useCallback(k=>{if(!c||k>=j.length-1)return;const X=[...j];[X[k],X[k+1]]=[X[k+1],X[k]],c(X)},[c,j]),A=i.useCallback(k=>{c&&c(j.filter(X=>X!==k))},[c,j]),T=n.length>0,H=j.length>0;i.useEffect(()=>{r||b(!1)},[r]);const Q=i.useMemo(()=>j.map(k=>{const X=x.get(k);return{id:k,name:X?.name||k,description:X?.description||"Step definition not found.",phase:X?.phase||"pre-merge"}}),[j,x]),se=()=>!r||!v||s?null:t.jsxs("div",{className:"workflow-results-editor","data-testid":"workflow-steps-editor",children:[t.jsxs("div",{className:"workflow-steps-section",children:[t.jsx("small",{className:"workflow-steps-description",children:"Select steps to run after task implementation completes"}),t.jsx("div",{className:"workflow-steps-list",children:C.map(k=>t.jsxs("label",{className:"checkbox-label workflow-step-item","data-testid":`workflow-step-checkbox-${k.id}`,children:[t.jsx("input",{type:"checkbox",checked:j.includes(k.id),onChange:X=>_(k.id,X.target.checked)}),t.jsxs("div",{children:[t.jsxs("span",{className:"workflow-step-name",children:[k.name,xl(k.phase,k.id,"workflow-step-phase")]}),t.jsx("div",{className:"workflow-step-description",children:k.description})]})]},k.id))})]}),j.length>1&&t.jsxs("div",{className:"workflow-step-order","data-testid":"workflow-step-order",children:[t.jsx("small",{className:"workflow-step-order-label",children:"Execution order:"}),j.map((k,X)=>{const le=x.get(k);return t.jsxs("div",{className:"workflow-step-order-item","data-testid":`workflow-step-order-item-${k}`,children:[t.jsx("span",{className:"workflow-step-order-number",children:X+1}),t.jsx("span",{className:"workflow-step-order-name",children:le?.name||k}),t.jsxs("div",{className:"workflow-step-order-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>K(X),disabled:X===0,"data-testid":`workflow-step-move-up-${k}`,title:"Move up",children:t.jsx(Li,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>U(X),disabled:X===j.length-1,"data-testid":`workflow-step-move-down-${k}`,title:"Move down",children:t.jsx(gn,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>A(k),"data-testid":`workflow-step-remove-${k}`,title:"Remove",children:t.jsx(mn,{})})]})]},k)})]})]}),O=()=>{if(s)return t.jsxs("div",{className:"workflow-results-loading","data-testid":"workflow-results-loading",children:[t.jsx("div",{className:"workflow-results-spinner"}),t.jsx("span",{children:"Loading workflow results…"})]});if(!T)return t.jsxs("div",{className:"workflow-results-empty","data-testid":"workflow-results-empty",children:[t.jsx("p",{children:"No workflow steps configured for this task."}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."})]});const k=n.filter(ye=>ye.status==="passed").length,X=n.filter(ye=>ye.status==="failed").length,le=n.filter(ye=>ye.status==="skipped").length,ke=n.filter(ye=>ye.status==="pending").length,He=[`${n.length} step${n.length!==1?"s":""}`];return k>0&&He.push(`${k} passed`),X>0&&He.push(`${X} failed`),le>0&&He.push(`${le} skipped`),ke>0&&He.push(`${ke} running`),t.jsxs("div",{className:"workflow-results-list","data-testid":"workflow-results-list",children:[t.jsx("div",{className:"workflow-results-summary-bar","data-testid":"workflow-results-summary",children:He.join(" · ")}),n.map((ye,je)=>{const ne=ye.phase||"pre-merge",fe=d[ye.workflowStepId]??!1;return t.jsxs("div",{className:`workflow-result-item workflow-result-item--${ye.status}`,"data-testid":`workflow-result-item-${ye.workflowStepId}`,children:[t.jsxs("div",{className:"workflow-result-header",children:[t.jsxs("div",{className:"workflow-result-name",children:[ye.workflowStepName,xl(ne,ye.workflowStepId,"workflow-result-phase")]}),t.jsx("span",{className:`workflow-result-badge workflow-result-badge--${ye.status}`,"data-testid":`workflow-result-badge-${ye.workflowStepId}`,children:kP(ye.status)})]}),t.jsxs("div",{className:"workflow-result-meta",children:[ye.startedAt&&t.jsxs("span",{className:"workflow-result-timestamp",children:["Started: ",NP(ye.startedAt)]}),ye.completedAt&&t.jsx("span",{className:"workflow-result-duration",children:jP(ye.startedAt,ye.completedAt)})]}),ye.status==="pending"&&ye.startedAt?t.jsx(CP,{entries:S,startedAt:ye.startedAt,stepId:ye.workflowStepId}):ye.output?t.jsxs("div",{className:"workflow-result-output-section",children:[t.jsxs("div",{className:"workflow-result-output-header",children:[t.jsx("span",{className:"workflow-result-output-label",children:"Output:"}),t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-toggle",onClick:()=>N(ye.workflowStepId),"data-testid":`workflow-result-toggle-${ye.workflowStepId}`,children:fe?"Hide output":"Show output"}),!fe&&t.jsx("span",{className:"workflow-result-output-preview","data-testid":`workflow-result-preview-${ye.workflowStepId}`,children:SP(ye.output)}),fe&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(ye.workflowStepId),"data-testid":`workflow-result-mode-toggle-${ye.workflowStepId}`,title:(m[ye.workflowStepId]??"markdown")==="markdown"?"Switch to plain text":"Switch to markdown",children:(m[ye.workflowStepId]??"markdown")==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-result-expand-toggle",onClick:()=>F(ye.workflowStepId),"data-testid":`workflow-result-expand-${ye.workflowStepId}`,title:"Expand output",children:t.jsx(wc,{size:12})})]})]}),fe&&t.jsx("div",{className:`workflow-result-output${(m[ye.workflowStepId]??"markdown")==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":`workflow-result-output-${ye.workflowStepId}`,children:(m[ye.workflowStepId]??"markdown")==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:tf,children:ye.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Cs(ye.output)})})]}):null]},`${ye.workflowStepId}-${je}`)})]})},M=r?t.jsx("button",{type:"button",className:"btn btn-sm workflow-results-edit-toggle",onClick:()=>b(k=>!k),"data-testid":"workflow-steps-edit-toggle","aria-label":v?"Done editing workflow steps":"Edit workflow steps",title:v?"Done":"Edit",children:v?t.jsxs(t.Fragment,{children:[t.jsx(ks,{size:14}),"Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Hs,{size:14}),"Edit"]})}):null,D=!s&&!T&&H,$=r&&T;return t.jsxs("div",{className:"workflow-results-tab","data-task-id":e,children:[D?t.jsxs("div",{className:"workflow-configured-steps","data-testid":"workflow-configured-steps",children:[t.jsxs("div",{className:"workflow-configured-header","data-testid":"workflow-configured-header",children:[t.jsxs("div",{className:"workflow-configured-title-row",children:[t.jsx("h4",{children:"Configured Workflow Steps"}),t.jsxs("span",{className:"workflow-configured-count","data-testid":"workflow-configured-count",children:[Q.length," step",Q.length===1?"":"s"]})]}),M]}),t.jsx("div",{className:"workflow-configured-list","data-testid":"workflow-configured-list",children:Q.map(k=>t.jsxs("div",{className:"workflow-configured-item","data-testid":`workflow-configured-step-${k.id}`,children:[t.jsxs("div",{className:"workflow-configured-name",children:[t.jsx("span",{className:"workflow-configured-name-text",children:k.name}),xl(k.phase,k.id,"workflow-configured-phase")]}),t.jsx("p",{className:"workflow-configured-description",children:k.description})]},k.id))}),t.jsx("p",{className:"workflow-results-empty-hint",children:"Pre-merge steps run after implementation, before merge. Post-merge steps run after merge succeeds."}),se()]}):t.jsxs(t.Fragment,{children:[$&&t.jsxs("div",{className:"workflow-results-edit-header","data-testid":"workflow-results-edit-header",children:[t.jsx("h4",{children:"Workflow Steps"}),M]}),O(),se()]}),f&&(()=>{const k=n.find(ke=>ke.workflowStepId===f);if(!k)return null;const X=m[k.workflowStepId]??"markdown",le=k.phase||"pre-merge";return t.jsx("div",{className:"workflow-output-modal-overlay",onClick:ke=>{ke.target===ke.currentTarget&&E()},"data-testid":"workflow-output-modal",children:t.jsxs("div",{className:"workflow-output-modal",role:"dialog","aria-modal":"true",children:[t.jsxs("div",{className:"workflow-output-modal-header",children:[t.jsxs("div",{className:"workflow-output-modal-title",children:[t.jsx("span",{className:"workflow-output-modal-name",children:k.workflowStepName}),xl(le,k.workflowStepId,"workflow-output-modal-phase")]}),t.jsxs("div",{className:"workflow-output-modal-controls",children:[t.jsx("button",{type:"button",className:"btn btn-sm workflow-result-mode-toggle",onClick:()=>R(k.workflowStepId),"data-testid":"workflow-output-modal-mode-toggle",title:X==="markdown"?"Switch to plain text":"Switch to markdown",children:X==="markdown"?"Markdown":"Plain"}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm workflow-output-modal-close",onClick:E,"data-testid":"workflow-output-modal-close","aria-label":"Close",children:t.jsx(mn,{size:16})})]})]}),t.jsx("div",{className:"workflow-output-modal-body",children:t.jsx("div",{className:`workflow-result-output workflow-result-output--expanded${X==="markdown"?" workflow-result-output--markdown":""}`,"data-testid":"workflow-output-modal-content",children:X==="markdown"?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:tf,children:k.output})}):t.jsx("pre",{className:"workflow-result-output-text",children:Cs(k.output)})})})]})})})()]})}function _P(e){return e==="block"?"Block execution":e==="fallback-local"?"Fall back to local":"Not configured"}const MP=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function AP(e){return e!==void 0&&e!=="online"}function RP({task:e,settings:n,addToast:s,onTaskUpdated:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(null),[m,h]=i.useState(e.nodeId??""),[f,p]=i.useState(!1),g=i.useRef(e.id);i.useEffect(()=>{g.current=e.id,h(e.nodeId??""),p(!1)},[e.id,e.nodeId]),i.useEffect(()=>{c(!0),u(null),Yl().then(E=>{o(E)}).catch(E=>{u(Se(E)||"Failed to load nodes")}).finally(()=>{c(!1)})},[]);const w=i.useMemo(()=>new Map(r.map(E=>[E.id,E])),[r]),v=i.useMemo(()=>[...r].sort((E,_)=>E.name.localeCompare(_.name)),[r]),b=n,y=e.nodeId??b?.defaultNodeId??null,S=e.nodeId?"Per-task override":b?.defaultNodeId?"Project default":"No routing",j=y?w.get(y):void 0,C=j?`${j.name} (${j.type})`:y?`${y} (node unavailable or unknown)`:"Local (no routing configured)",x=e.column==="in-progress"||MP.has(e.status),N=x||f||l,R=i.useCallback(async E=>{if(E===m)return;const _=e.id,K=m;h(E),p(!0);try{const U=await Us(_,{nodeId:E||null});if(g.current!==_)return;h(U.nodeId??""),a?.(U),s(E?"Node override updated":"Node override cleared","success")}catch(U){if(g.current!==_)return;h(K),s(Se(U)||"Failed to update node override","error")}finally{g.current===_&&p(!1)}},[s,a,m,e.id]),F=i.useCallback(()=>{R("")},[R]);return t.jsxs("div",{className:"routing-tab",children:[t.jsx("h4",{children:"Task Routing"}),t.jsx("p",{className:"routing-tab__intro",children:"View the effective execution node and control per-task node override."}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Routing Summary"}),t.jsxs("div",{className:"routing-summary-grid",role:"list",children:[t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Effective node"}),t.jsxs("span",{className:"routing-summary-value",children:[j?t.jsx(Ua,{status:j.status,compact:!0}):null,C,AP(j?.status)?t.jsx("span",{className:"routing-summary-warning",children:"Unhealthy"}):null]})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Routing source"}),t.jsx("span",{className:"routing-summary-value",children:S})]}),t.jsxs("div",{className:"routing-summary-row",role:"listitem",children:[t.jsx("span",{className:"routing-summary-label",children:"Unavailable-node policy"}),t.jsx("span",{className:"routing-summary-value",children:_P(b?.unavailableNodePolicy)})]})]}),x&&y?t.jsx("div",{className:"routing-tab__info-banner",children:"Routing is locked while this task is active. Node override cannot be changed until the task is no longer active."}):null]}),t.jsxs("section",{className:"routing-tab__section",children:[t.jsx("h5",{children:"Node Override"}),x?t.jsx("div",{className:"routing-tab__warning-banner",children:"Node override cannot be changed while the task is active."}):null,t.jsx("label",{className:"routing-tab__selector-label",htmlFor:`routing-node-${e.id}`,children:"Select execution node"}),t.jsxs("select",{id:`routing-node-${e.id}`,className:"select routing-tab__selector",value:m,disabled:N,onChange:E=>{R(E.target.value)},children:[t.jsx("option",{value:"",children:"Use project default"}),v.map(E=>t.jsxs("option",{value:E.id,title:`Status: ${E.status}`,children:[E.name," (",E.type,") — ",E.status]},E.id))]}),d?t.jsx("div",{className:"routing-tab__error",children:d}):null,e.nodeId?t.jsxs("div",{className:"routing-tab__override-row",children:[t.jsxs("span",{className:"routing-tab__override-text",children:["Override set to: ",w.get(e.nodeId)?.name??e.nodeId]}),t.jsx("button",{type:"button",className:"btn btn-sm",disabled:x||f,onClick:F,children:"Clear override"})]}):null]})]})}const IP=/^[a-zA-Z0-9_-]{1,64}$/,TP=200;function nf(e){return e?new Date(e).toLocaleString():""}function PP(e,n=TP){return e.length<=n?e:e.substring(0,n)+"…"}function $P({taskId:e,addToast:n,onTaskUpdated:s,projectId:a,canEdit:r=!1}){const[o,l]=i.useState([]),[c,d]=i.useState(!0),[u,m]=i.useState(null),[h,f]=i.useState(""),[p,g]=i.useState(null),[w,v]=i.useState(""),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,x]=i.useState(!1),[N,R]=i.useState(!1),[F,E]=i.useState(""),[_,K]=i.useState(""),[U,A]=i.useState(!1),[T,H]=i.useState(null),[Q,se]=i.useState(null),[O,M]=i.useState(!1),D=i.useCallback(async()=>{try{const ne=await sN(e,a);l(ne)}catch(ne){n(Se(ne)||"Failed to load documents","error")}finally{d(!1)}},[e,a,n]);i.useEffect(()=>{D()},[D]);async function $(ne){u===ne.key?(m(null),f(""),g(null),v(""),y(null),j([]),M(!1)):(m(ne.key),f(ne.content),g(null),v(""),y(null),j([]),M(!1))}async function k(ne){if(b===ne)y(null),j([]);else{y(ne),x(!0);try{const fe=await iN(e,ne,a);j(fe)}catch(fe){n(Se(fe)||"Failed to load revisions","error")}finally{x(!1)}}}function X(){u&&(g(u),v(h))}function le(){g(null),v("")}async function ke(){if(!(!p||!w.trim())){A(!0);try{await Vm(e,p,w,{},a),g(null),v(""),await D();const ne=o.find(fe=>fe.key===p);ne&&f(ne.content),n("Document saved","success")}catch(ne){n(Se(ne)||"Failed to save document","error")}finally{A(!1)}}}async function He(){const ne=F.trim(),fe=_.trim();if(!ne){n("Document key is required","error");return}if(!IP.test(ne)){n("Invalid key format. Use 1-64 alphanumeric characters, hyphens, or underscores.","error");return}if(!fe){n("Content is required","error");return}A(!0);try{await Vm(e,ne,fe,{},a),R(!1),E(""),K(""),await D(),n("Document created","success")}catch(Z){n(Se(Z)||"Failed to create document","error")}finally{A(!1)}}async function ye(ne){H(ne);try{await aN(e,ne,a),se(null),H(null),u===ne&&(m(null),f("")),b===ne&&(y(null),j([])),await D(),n("Document deleted","success")}catch(fe){n(Se(fe)||"Failed to delete document","error")}finally{H(null)}}function je(ne){f(ne.content),g(null),v("")}return c?t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),t.jsx("div",{className:"detail-log-empty",children:"Loading documents…"})]}):t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Documents"}),N&&t.jsxs("div",{className:"task-document-create-form",children:[t.jsx("h5",{children:"New Document"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-key",children:"Key"}),t.jsx("input",{id:"doc-key",type:"text",className:"task-document-key-input",value:F,onChange:ne=>E(ne.target.value),placeholder:"e.g., plan, notes, research",disabled:U}),t.jsx("span",{className:"form-hint",children:"Alphanumeric, hyphens, underscores (1-64 chars)"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"doc-content",children:"Content"}),t.jsx("textarea",{id:"doc-content",value:_,onChange:ne=>K(ne.target.value),rows:6,placeholder:"Enter document content…",disabled:U})]}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>{R(!1),E(""),K("")},disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void He(),disabled:U||!F.trim()||!_.trim(),children:U?"Creating…":"Create"})]})]}),o.length===0&&!N?t.jsx("div",{className:"detail-log-empty",children:"No documents yet."}):t.jsx("div",{className:"task-documents-list",children:o.map(ne=>t.jsxs("div",{className:"task-document-card",children:[t.jsxs("div",{className:"task-document-card-header",children:[t.jsxs("div",{className:"task-document-card-title",children:[t.jsx(xa,{size:14}),t.jsx("span",{className:"task-document-key",children:ne.key}),t.jsxs("span",{className:"task-document-revision-badge",children:["v",ne.revision]})]}),t.jsxs("div",{className:"task-document-meta",children:[t.jsx("span",{className:"task-document-author",children:ne.author}),t.jsx("span",{className:"task-document-timestamp",children:nf(ne.updatedAt||ne.createdAt)})]})]}),u===ne.key&&p!==ne.key&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"task-document-content-header",children:t.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>M(fe=>!fe),"aria-label":O?"Switch to plain text":"Switch to markdown","aria-pressed":O,title:O?"Switch to plain text":"Switch to markdown",children:O?"Markdown":"Plain"})}),t.jsx("div",{className:"task-document-content",children:O?t.jsx("div",{className:"task-document-content-markdown",children:t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],children:h})})}):t.jsx("pre",{className:"task-document-content-text",children:h})}),b===ne.key&&t.jsxs("div",{className:"task-document-revisions",children:[t.jsx("h5",{children:"Revision History"}),C?t.jsx("div",{className:"detail-log-empty",children:"Loading…"}):S.length<=1?t.jsx("div",{className:"detail-log-empty",children:"No previous revisions."}):t.jsx("div",{className:"task-document-revision-list",children:S.filter(fe=>fe.revision<ne.revision).sort((fe,Z)=>Z.revision-fe.revision).map(fe=>t.jsxs("div",{className:"task-document-revision-item",onClick:()=>je(fe),children:[t.jsxs("div",{className:"revision-header",children:[t.jsxs("span",{className:"revision-badge",children:["v",fe.revision]}),t.jsx("span",{className:"revision-author",children:fe.author}),t.jsx("span",{className:"revision-timestamp",children:nf(fe.createdAt)})]}),t.jsx("div",{className:"revision-preview",children:PP(fe.content,100)})]},fe.id))})]})]}),p===ne.key&&t.jsxs("div",{className:"task-document-edit-form",children:[t.jsx("textarea",{value:w,onChange:fe=>v(fe.target.value),rows:10,disabled:U}),t.jsxs("div",{className:"form-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:le,disabled:U,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void ke(),disabled:U||!w.trim(),children:U?"Saving…":"Save"})]})]}),t.jsxs("div",{className:"task-document-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>void $(ne),children:u===ne.key?t.jsxs(t.Fragment,{children:[t.jsx(Li,{size:14})," Collapse"]}):t.jsxs(t.Fragment,{children:[t.jsx(gn,{size:14})," Expand"]})}),u===ne.key&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>void k(ne.key),children:[t.jsx(Oa,{size:14})," History"]}),r&&p!==ne.key&&t.jsx("button",{className:"btn btn-sm",onClick:X,children:"Edit"}),r&&(Q===ne.key?t.jsxs("div",{className:"confirm-delete-actions",children:[t.jsx("span",{children:"Delete?"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>void ye(ne.key),disabled:T===ne.key,children:T===ne.key?"…":"Yes"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>se(null),disabled:T===ne.key,children:"No"})]}):t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>se(ne.key),children:t.jsx(Tn,{size:14})}))]})]})]},ne.key))}),r&&!N&&t.jsxs("button",{className:"btn btn-sm task-document-new-btn",onClick:()=>R(!0),children:[t.jsx($n,{size:14})," New Document"]})]})}function vl(e){return e.toLocaleString()}function Cd(e){const n=new Date(e);return Number.isNaN(n.getTime())?e:n.toLocaleString()}function oo(e){if(e<1e3)return`${Math.round(e)} ms`;const n=e/1e3;if(n<60)return`${n.toFixed(1)} s`;const s=Math.floor(n/60),a=Math.round(n%60);return`${s}m ${a}s`}function DP(e){const n=Date.now(),s=e.map(o=>{if(!o.startedAt)return null;const l=new Date(o.startedAt).getTime();if(Number.isNaN(l))return null;let c;if(o.completedAt){const d=new Date(o.completedAt).getTime();if(Number.isNaN(d)||d<l)return null;c=d}else c=Math.max(l,n);return{name:o.workflowStepName||o.workflowStepId,durationMs:c-l}}).filter(o=>o!==null),a=Wb(e,n)??0,r=s.reduce((o,l)=>!o||l.durationMs>o.durationMs?l:o,void 0);return{timedStepCount:s.length,totalDurationMs:a,longestStep:r}}function LP({tokenUsage:e,loading:n,task:s}){const a=Date.now(),r=qb(s?.log??[]),o=r.filter(g=>typeof g.durationMs=="number"),l=o.reduce((g,w)=>g+(w.durationMs??0),0),c=Vb(s?.log)??0,d=typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:Math.max(l,c),u=o.reduce((g,w)=>!g||(w.durationMs??0)>(g.durationMs??0)?w:g,void 0),m=DP(s?.workflowStepResults??[]),f=Gb(s?.executionStartedAt,s?.executionCompletedAt,a)??(typeof s?.timedExecutionMs=="number"?s.timedExecutionMs:d+m.totalDurationMs),p=s?.steps?.length??0;return t.jsxs("section",{className:"task-token-stats-panel","aria-label":"Task execution statistics",children:[t.jsx("h4",{children:"Execution & Token Stats"}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Timing"}),t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Execution timing metrics",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timing events"}),t.jsx("span",{className:"task-token-stats-panel__value",children:r.length.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Timed duration"}),t.jsx("span",{className:"task-token-stats-panel__value",children:oo(d)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow timed steps"}),t.jsx("span",{className:"task-token-stats-panel__value",children:m.timedStepCount.toLocaleString()})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Workflow runtime"}),t.jsx("span",{className:"task-token-stats-panel__value",children:oo(m.totalDurationMs)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total execution time"}),t.jsx("span",{className:"task-token-stats-panel__value",children:oo(f)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest timing event"}),t.jsx("dd",{children:u?.durationMs?`${u.summary} (${oo(u.durationMs)})`:"No timed events recorded yet."})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Longest workflow step"}),t.jsx("dd",{children:m.longestStep?`${m.longestStep.name} (${oo(m.longestStep.durationMs)})`:"No completed workflow step timings yet."})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Execution Details"}),t.jsxs("dl",{className:"task-token-stats-panel__details",children:[t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Execution mode"}),t.jsx("dd",{children:s?.executionMode==="fast"?"Fast":"Standard"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime status"}),t.jsx("dd",{children:s?.status??"Not set"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Paused"}),t.jsx("dd",{children:s?.paused?"Yes":"No"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Step progress"}),t.jsx("dd",{children:p>0?`${Math.min((s?.currentStep??0)+1,p)} / ${p}`:"No steps"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Retries (recovery / workflow / merge / task_done)"}),t.jsx("dd",{children:`${s?.recoveryRetryCount??0} / ${s?.workflowStepRetries??0} / ${s?.mergeRetries??0} / ${s?.taskDoneRetryCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Recovery state"}),t.jsx("dd",{children:s?.nextRecoveryAt?`Next recovery at ${Cd(s.nextRecoveryAt)}`:"No scheduled recovery"})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Self-heal counters"}),t.jsx("dd",{children:`stuck kills: ${s?.stuckKillCount??0}, post-review fixes: ${s?.postReviewFixCount??0}`})]}),t.jsxs("div",{className:"task-token-stats-panel__detail-row",children:[t.jsx("dt",{children:"Runtime links"}),t.jsx("dd",{children:[s?.assignedAgentId?`agent ${s.assignedAgentId}`:null,s?.checkedOutBy?`checkout ${s.checkedOutBy}`:null,s?.blockedBy?`blocked by ${s.blockedBy}`:null,s?.sessionFile?"has session":null].filter(Boolean).join(", ")||"No runtime links"})]})]})]}),t.jsxs("div",{className:"task-token-stats-panel__section",children:[t.jsx("h5",{children:"Token Usage"}),!e&&n?t.jsx("div",{className:"task-token-stats-panel__loading",role:"status","aria-live":"polite",children:"Loading token statistics…"}):e?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"task-token-stats-panel__grid",role:"list","aria-label":"Task token totals",children:[t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Input"}),t.jsx("span",{className:"task-token-stats-panel__value",children:vl(e.inputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Output"}),t.jsx("span",{className:"task-token-stats-panel__value",children:vl(e.outputTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Cached"}),t.jsx("span",{className:"task-token-stats-panel__value",children:vl(e.cachedTokens)})]}),t.jsxs("div",{className:"task-token-stats-panel__metric",role:"listitem",children:[t.jsx("span",{className:"task-token-stats-panel__label",children:"Total"}),t.jsx("span",{className:"task-token-stats-panel__value",children:vl(e.totalTokens)})]})]}),t.jsxs("dl",{className:"task-token-stats-panel__timestamps",children:[t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"First used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.firstUsedAt,children:Cd(e.firstUsedAt)})})]}),t.jsxs("div",{className:"task-token-stats-panel__timestamp-row",children:[t.jsx("dt",{children:"Last used"}),t.jsx("dd",{children:t.jsx("time",{dateTime:e.lastUsedAt,children:Cd(e.lastUsedAt)})})]})]})]}):t.jsx("div",{className:"task-token-stats-panel__empty",role:"status",children:"No token usage recorded for this task yet."})]})]})}const km=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]),sf={p:({children:e,...n})=>t.jsx("p",{...n,children:Ys(e)}),li:({children:e,...n})=>t.jsx("li",{...n,children:Ys(e)}),code:({children:e,...n})=>{const s=typeof e=="string"?e:ga.Children.toArray(e).join(""),a=Cs(s);return a.length===1&&typeof a[0]=="string"?t.jsx("code",{...n,children:e}):t.jsx("code",{...n,children:a})}};function OP(e){let n=null;for(const s of e){if(s.agent!=="executor"||s.type!=="text")continue;const a=s.text.match(/^Executor using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function FP(e){let n=null;for(const s of e){if(s.agent!=="reviewer"||s.type!=="text")continue;const a=s.text.match(/^Reviewer using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function bv(e){const n=e?.runtimeConfig??void 0,s=typeof n?.model=="string"?n.model.trim():"";if(s){const o=s.indexOf("/");if(o>0&&o<s.length-1)return{provider:s.slice(0,o),modelId:s.slice(o+1)}}const a=typeof n?.modelProvider=="string"?n.modelProvider.trim():"",r=typeof n?.modelId=="string"?n.modelId.trim():"";return{provider:a||void 0,modelId:r||void 0}}function zP(e,n,s,a){const r=OP(n);if(r)return r;if(km.has(e.status??"")||e.column==="in-progress"){const o=bv(s);if(o.provider&&o.modelId)return o}return Tb(e,a)}function BP(e,n,s,a){const r=FP(n);if(r)return r;if(km.has(e.status??"")||e.column==="in-progress"){const o=bv(s);if(o.provider&&o.modelId)return o}return Pb(e,a)}function UP(e){let n=null;for(const s of e){if(s.agent!=="triage"||s.type!=="text")continue;const a=s.text.match(/^Triage using model: (.+?)\/(.+)$/);a&&(n={provider:a[1],modelId:a[2]})}return n}function HP(e,n,s){if(e.planningModelProvider&&e.planningModelId)return{provider:e.planningModelProvider,modelId:e.planningModelId};const a=UP(n);return a||$b(e,s)}function qP(e){switch(e){case"done":return"var(--color-success)";case"in-progress":return"var(--in-progress)";case"skipped":return"var(--text-dim)";case"pending":default:return"var(--border)"}}function Ed(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(r/60),l=Math.floor(o/24);return r<1?"just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function VP(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function _d(e,n){return e.length>n?e.slice(0,n)+"…":e}function af(e=[],n=[]){return e.length===n.length&&e.every((s,a)=>s===n[a])}function Md(e){const n=e.indexOf("/");return!e||n===-1?null:{provider:e.slice(0,n),modelId:e.slice(n+1)}}function Ad(e){return e.trim()}function WP(e){const n=e.trim();return n.length>0?n:void 0}function Ki(e){return typeof e=="string"&&wa.includes(e)?e:Ps}function Ji(e){return e==="fast"?"fast":"standard"}function GP(e){const n=e?.issueUrl;return typeof n=="string"&&n.length>0?n:void 0}function KP(e){const n=e?.findingLabel;if(typeof n=="string"&&n.length>0)return n;const s=e?.runId;return typeof s=="string"&&s.length>0?s:void 0}const JP=i.lazy(()=>En(()=>import("./AgentDetailView-DG01uRND.js"),__vite__mapDeps([0,1,2,3,4,5,6,7])).then(e=>({default:e.AgentDetailView})));function YP(e,n={}){switch(e.sourceType){case"dashboard_ui":return{label:"Dashboard"};case"quick_chat":return{label:"Quick Chat"};case"chat_session":return{label:"Chat Session"};case"agent_heartbeat":return{label:n.sourceAgentName??e.sourceAgentId??"agent",sourceAgentId:e.sourceAgentId};case"automation":return{label:"Automation"};case"cron":return{label:"Scheduled Task"};case"workflow_step":return{label:"Workflow Step"};case"github_import":return{label:"GitHub Import",contextInfo:GP(e.sourceMetadata)};case"research":return{label:"Research",contextInfo:KP(e.sourceMetadata)};case"task_refine":return{label:"Refinement",parentTaskId:e.sourceParentTaskId};case"task_duplicate":return{label:"Duplicate",parentTaskId:e.sourceParentTaskId};case"cli":return{label:"CLI"};case"api":return{label:"API"};case"recovery":return{label:"Recovery"};case"unknown":default:return null}}const Rd=200,QP=new Set(["triage","todo"]),XP=new Set(["triage","todo","in-progress","in-review"]);function xv({task:e,projectId:n,tasks:s=[],onOpenDetail:a,onMoveTask:r,onDeleteTask:o,onMergeTask:l,onRetryTask:c,onResetTask:d,onDuplicateTask:u,onTaskUpdated:m,addToast:h,prAuthAvailable:f,initialTab:p="definition",mobileHeaderMode:g="close",embedded:w=!1,onRequestClose:v}){const[b,y]=i.useState(p),[S,j]=i.useState(()=>"prompt"in e?e:null),[C,x]=i.useState(()=>!("prompt"in e));i.useEffect(()=>{if("prompt"in e){j(e),x(!1);return}let ee=!1;return x(!0),j(null),Ba(e.id,n).then(De=>{ee||(j(De),x(!1))}).catch(()=>{ee||x(!1)}),()=>{ee=!0}},[e.id,n]);const N=S?{...S,...e,prompt:S.prompt,log:S.log,githubTracking:e.githubTracking??S.githubTracking}:{...e,prompt:""},R=e.status==="failed"||e.status==="stuck-killed"||e.status==="planning"||e.status==="needs-replan"||(e.stuckKillCount??0)>0||(e.recoveryRetryCount??0)>0||!!e.nextRecoveryAt,[F,E]=i.useState(null),[_,K]=i.useState(null),U=YP(N,{sourceAgentName:F?.name});i.useEffect(()=>{y(p)},[p]),i.useEffect(()=>{Q(!1)},[e.id]);const[A,T]=i.useState("activity"),[H,Q]=i.useState(!1),[se,O]=i.useState(e.attachments||[]),[M,D]=i.useState(!1),[$,k]=i.useState(e.dependencies||[]),[X,le]=i.useState(!1),[ke,He]=i.useState(""),[ye,je]=i.useState(null),[ne,fe]=i.useState([]),[Z,re]=i.useState(!1),[q,L]=i.useState(!1),[xe,he]=i.useState(!1),[B,pe]=i.useState(!1),[ze,ae]=i.useState(!1),[Ve,Te]=i.useState(N.prompt||""),[rt,Be]=i.useState(""),[ce,Re]=i.useState(!1),[Le,ct]=i.useState(""),[Ue,ue]=i.useState(!1),[oe,Ee]=i.useState(!1),[ft,ht]=i.useState(e.title||""),[tt,xt]=i.useState(e.description||""),[Me,Ye]=i.useState(e.dependencies||[]),[dt,wt]=i.useState(e.branch??""),[St,Fe]=i.useState(e.baseBranch??""),[J,me]=i.useState(""),[Ze,be]=i.useState(""),[gt,$t]=i.useState(""),[Ie,ge]=i.useState(""),[st,yt]=i.useState("default"),[pt,vt]=i.useState(void 0),[Ut,Dt]=i.useState(Ps),[nn,on]=i.useState(e.nodeId),[sn,ln]=i.useState(Ji(e.executionMode)),[xn,qt]=i.useState(""),[Qt,hn]=i.useState(e.enabledWorkflowSteps||[]),[Zt,ve]=i.useState(e.sourceIssue?.provider??""),[Pe,Ke]=i.useState(e.sourceIssue?.repository??""),[at,We]=i.useState(e.sourceIssue?.externalIssueId??""),[It,Lt]=i.useState(e.sourceIssue?.url??""),[Bt,Gt]=i.useState([]),[bt,Ot]=i.useState(!1),[en,Kt]=i.useState(Ki(e.priority)),[Sn,dn]=i.useState(!1),[Jt,tn]=i.useState(Ji(e.executionMode)),[Ne,W]=i.useState(!1),Y=i.useRef(!1),[_e,ut]=i.useState(!1),[At,zt]=i.useState(!1),[yn,Zn]=i.useState(!1),[vn,Dn]=i.useState(!1),[de,nt]=i.useState(e.githubTracking?.repoOverride??""),[ot,_t]=i.useState(null),[G,Oe]=i.useState(null),[Mt,Xt]=i.useState(!1),_n=i.useRef(null),Pn=i.useRef(null),kn=i.useRef(null),{getSlotsForId:Vn}=Eb(n),vs=Vn("task-detail-tab").map((ee,De)=>({entry:ee,tabId:`plugin-${ee.pluginId}-${De}`})),As=typeof b=="string"&&b.startsWith("plugin-")?vs.find(ee=>ee.tabId===b)??null:null;i.useEffect(()=>(Y.current=!0,()=>{Y.current=!1}),[]);const[bn,Ht]=i.useState(void 0),[On,Fn]=i.useState(null),[as,Wn]=i.useState([]),[Rs,In]=i.useState(!1),[rs,Ns]=i.useState(e.enabledWorkflowSteps||[]),ys=e.column==="in-progress"||km.has(e.status);i.useEffect(()=>{ht(e.title||""),xt(e.description||""),wt(e.branch??""),Fe(e.baseBranch??""),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),ln(Ji(e.executionMode)),Zn(!1),Dn(!1),nt(N.githubTracking?.repoOverride??""),_t(null),Oe(null),Ee(!1)},[e.id,e.title,e.description,e.branch,e.baseBranch,e.sourceIssue,e.executionMode,N.githubTracking]),i.useEffect(()=>{Ns(e.enabledWorkflowSteps||[])},[e.id,e.enabledWorkflowSteps]),i.useEffect(()=>{Kt(Ki(e.priority))},[e.id,e.priority]),i.useEffect(()=>{tn(Ji(e.executionMode))},[e.id,e.executionMode]),i.useEffect(()=>{ot!==null&&N.githubTracking?.enabled===!0===ot&&_t(null)},[ot,N.githubTracking?.enabled]),i.useEffect(()=>{let ee=!1;return kc(n).then(De=>{ee||Ht(De)}).catch(()=>{}),na().then(De=>{ee||Fn(De)}).catch(()=>{ee||Fn(null)}),()=>{ee=!0}},[n]),i.useEffect(()=>{if(b!=="workflow")return;let ee=!1;return In(!0),qS(e.id,n).then(De=>{ee||Wn(De)}).catch(De=>{ee||h(`Failed to load workflow results: ${Se(De)}`,"error")}).finally(()=>{ee||In(!1)}),()=>{ee=!0}},[b,e.id,n,h]),i.useEffect(()=>{if(b!=="workflow")return;const ee=n?`?projectId=${encodeURIComponent(n)}`:"",De=Ct=>{try{const Wt=JSON.parse(Ct.data);Wt.id===e.id&&Array.isArray(Wt.workflowStepResults)&&Wn(Wt.workflowStepResults)}catch{}};return yi(`/api/events${ee}`,{events:{"task:updated":De}})},[b,e.id,n]),i.useEffect(()=>{X||He("")},[X]),i.useEffect(()=>{if(!e.assignedAgentId){je(null);return}const ee=ne.find(Ct=>Ct.id===e.assignedAgentId);if(ee){je(ee);return}let De=!1;return uu(e.assignedAgentId,n).then(Ct=>{De||je(Ct)}).catch(()=>{De||je(null)}),()=>{De=!0}},[e.assignedAgentId,n,ne]),i.useEffect(()=>{if(!e.sourceAgentId){E(null);return}const ee=ne.find(Ct=>Ct.id===e.sourceAgentId);if(ee){E(ee);return}let De=!1;return Promise.resolve(uu(e.sourceAgentId,n)).then(Ct=>{De||E(Ct??null)}).catch(()=>{De||E(null)}),()=>{De=!0}},[e.sourceAgentId,n,ne]),i.useEffect(()=>{re(!1)},[e.id]),i.useEffect(()=>{if(!(_e||At))return;const De=Ct=>{const Wt=Ct.target,ns=_n.current?.contains(Wt),Gi=kn.current?.contains(Wt);!ns&&_e&&ut(!1),!Gi&&At&&zt(!1)};return document.addEventListener("mousedown",De),()=>document.removeEventListener("mousedown",De)},[_e,At]),i.useEffect(()=>{if(!(_e||At))return;const De=Ct=>{Ct.key==="Escape"&&(Ct.stopPropagation(),_e&&ut(!1),At&&zt(!1))};return document.addEventListener("keydown",De),()=>document.removeEventListener("keydown",De)},[_e,At]),i.useEffect(()=>{ae(!1),Te(N.prompt||""),Be("")},[e.id,N.prompt]);const cs=QP.has(e.column)&&!bt,ss=XP.has(e.column)&&!bt,te=ot??N.githubTracking?.enabled===!0,we=N.githubTracking?.issue,P=ss&&!we&&(!te||Mt&&N.githubTracking?.enabled!==!0),Ce=ss||te||!!we,qe=we?"Linked":te?"Enabled":"Disabled",et=fv(bn??null,On),mt=de.trim(),Nt=i.useCallback(async()=>{if(!ss||Mt)return;const ee=!te;_t(ee),Xt(!0);try{const De=await Us(e.id,{githubTracking:{enabled:ee}},n);m?.(De)}catch(De){_t(N.githubTracking?.enabled===!0),h(`Failed to update ${e.id}: ${Se(De)}`,"error")}finally{Y.current&&Xt(!1)}},[h,ss,te,Mt,m,n,N.githubTracking?.enabled,e.id]),Pt=i.useCallback(async()=>{if(!(!ss||Mt)){if(mt.length>0&&!Sc.test(mt)){Oe("Repository override must be in owner/repo format");return}Oe(null),Xt(!0);try{const ee=await Us(e.id,{githubTracking:{repoOverride:mt.length>0?mt:null}},n);m?.(ee)}catch(ee){h(`Failed to update ${e.id}: ${Se(ee)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,ss,mt,Mt,m,n,e.id]),an=i.useCallback(async()=>{if(!(!te||we||Mt)){Xt(!0);try{const ee=await Us(e.id,{githubTracking:{enabled:!0}},n);m?.(ee),h("Requested GitHub tracking issue creation","info")}catch(ee){h(`Failed to update ${e.id}: ${Se(ee)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,we,te,Mt,m,n,e.id]),Cn=i.useCallback(()=>{if(!cs)return;Ee(!0),ht(e.title||""),xt(e.description||""),Ye(e.dependencies||[]),wt(e.branch??""),Fe(e.baseBranch??"");const ee=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"",De=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"",Ct=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";me(ee),be(De),$t(Ct),ge(e.thinkingLevel??""),on(e.nodeId),yt(ee||De||Ct?"custom":"default"),qt(""),hn(e.enabledWorkflowSteps||[]),ln(Ji(e.executionMode)),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),Gt([]),vt(e.reviewLevel),Dt(Ki(e.priority))},[cs,e]),ie=i.useCallback(()=>{Ee(!1),ht(e.title||""),xt(e.description||""),Ye(e.dependencies||[]),wt(e.branch??""),Fe(e.baseBranch??""),on(e.nodeId),ve(e.sourceIssue?.provider??""),Ke(e.sourceIssue?.repository??""),We(e.sourceIssue?.externalIssueId??""),Lt(e.sourceIssue?.url??""),Dt(Ki(e.priority)),ln(Ji(e.executionMode)),Bt.forEach(ee=>URL.revokeObjectURL(ee.previewUrl)),Gt([])},[e.title,e.description,e.dependencies,e.nodeId,e.priority,e.executionMode,Bt]),[$e,Qe]=i.useState("idle"),Ft=i.useRef(null),cn=i.useRef(0),pn=i.useCallback(ee=>{const De={},Ct=ft.trim(),Wt=tt.trim();Ct&&Ct!==(e.title??"")&&(De.title=Ct),ee&&Wt&&Wt!==(e.description??"")&&(De.description=Wt),af(Me,e.dependencies??[])||(De.dependencies=Me),af(Qt,e.enabledWorkflowSteps??[])||(De.enabledWorkflowSteps=Qt);const ns=dt.trim()||null,Gi=e.branch??null;ns!==Gi&&(De.branch=ns);const Em=St.trim()||null,hy=e.baseBranch??null;Em!==hy&&(De.baseBranch=Em);const _m=Md(J),py=e.modelProvider&&e.modelId?`${e.modelProvider}/${e.modelId}`:"";J!==py&&(De.modelProvider=_m?.provider??null,De.modelId=_m?.modelId??null);const Mm=Md(Ze),fy=e.validatorModelProvider&&e.validatorModelId?`${e.validatorModelProvider}/${e.validatorModelId}`:"";Ze!==fy&&(De.validatorModelProvider=Mm?.provider??null,De.validatorModelId=Mm?.modelId??null);const Am=Md(gt),gy=e.planningModelProvider&&e.planningModelId?`${e.planningModelProvider}/${e.planningModelId}`:"";gt!==gy&&(De.planningModelProvider=Am?.provider??null,De.planningModelId=Am?.modelId??null);const by=e.thinkingLevel??"";Ie!==by&&(De.thinkingLevel=Ie!==""?Ie:null),(e.nodeId??void 0)!==nn&&(De.nodeId=nn??null),pt!==e.reviewLevel&&(De.reviewLevel=pt),Ut!==Ki(e.priority)&&(De.priority=Ut),sn!==Ji(e.executionMode)&&(De.executionMode=sn==="fast"?"fast":null);const $c=Ad(Zt),Dc=Ad(Pe),nl=Ad(at),Lc=WP(It);if($c.length===0&&Dc.length===0&&nl.length===0&&!Lc)e.sourceIssue&&(De.sourceIssue=null);else{if(!$c||!Dc||!nl)return{updates:null,error:"Source issue provider, repository, and issue identifier are required"};const xy=Number.parseInt(nl,10),Oc=e.sourceIssue?.issueNumber??xy;if(!Number.isFinite(Oc)||Oc<=0)return{updates:null,error:"Source issue identifier must be numeric for new metadata"};const or={provider:$c,repository:Dc,externalIssueId:nl,issueNumber:Oc,...Lc?{url:Lc}:{}},lr=e.sourceIssue;(!lr||lr.provider!==or.provider||lr.repository!==or.repository||lr.externalIssueId!==or.externalIssueId||lr.issueNumber!==or.issueNumber||(lr.url??void 0)!==or.url)&&(De.sourceIssue=or)}return{updates:De,error:null}},[St,dt,Me,tt,sn,J,nn,gt,Ut,pt,Qt,at,Zt,Pe,It,Ie,ft,Ze,e]),jn=i.useCallback(async ee=>{const{updates:De,error:Ct}=pn(ee);if(!De)return Qe("error"),Ct&&h(`Failed to update ${e.id}: ${Ct}`,"error"),!1;if(Object.keys(De).length===0)return!0;const Wt=++cn.current;Ot(!0),Qe("saving");try{const ns=await Us(e.id,De,n);return Wt!==cn.current?void 0:(m?.(ns),Qe("saved"),!0)}catch(ns){return Wt===cn.current&&(Qe("error"),h(`Failed to update ${e.id}: ${Se(ns)}`,"error")),!1}finally{Y.current&&Wt===cn.current&&Ot(!1)}},[h,pn,m,n,e.id]),Un=i.useCallback(async ee=>{await jn(!0)},[jn]),gs=i.useCallback(async()=>{await jn(!0)&&(h(`Updated ${e.id}`,"success"),Y.current&&Ee(!1))},[h,jn,e.id]);i.useEffect(()=>{if(oe)return Ft.current&&clearTimeout(Ft.current),Ft.current=setTimeout(()=>{jn(!1)},700),()=>{Ft.current&&(clearTimeout(Ft.current),Ft.current=null)}},[oe,ft,Me,dt,St,J,Ze,gt,Ie,nn,pt,Ut,sn,Qt,Zt,Pe,at,It,jn]);const bs=i.useCallback(async ee=>{const De=Ki(ee),Ct=Ki(e.priority);if(De===Ct){Kt(Ct);return}const Wt=en;Kt(De),dn(!0);try{const ns=await Us(e.id,{priority:De},n);Kt(Ki(ns.priority)),m?.(ns),h(`Priority updated to ${Ki(ns.priority)}`,"success")}catch(ns){Kt(Wt),h(`Failed to update ${e.id}: ${Se(ns)}`,"error")}finally{Y.current&&dn(!1)}},[e.id,e.priority,n,en,m,h]),is=i.useCallback(async()=>{const De=Ji(e.executionMode)==="fast"?"standard":"fast",Ct=Jt;tn(De),W(!0);try{const Wt=await Us(e.id,{executionMode:De==="fast"?"fast":null},n),ns=Ji(Wt.executionMode);tn(ns),m?.(Wt),h(`Execution mode updated to ${ns}`,"success")}catch(Wt){tn(Ct),h(`Failed to update ${e.id}: ${Se(Wt)}`,"error")}finally{Y.current&&W(!1)}},[e.id,e.executionMode,n,Jt,m,h]),ds=i.useCallback(ee=>{oe&&(ee.key==="Escape"?(ee.preventDefault(),ie()):ee.key==="Enter"&&(ee.ctrlKey||ee.metaKey)&&(ee.preventDefault(),gs()))},[oe,ie,gs]);i.useEffect(()=>{if(oe)return document.addEventListener("keydown",ds),()=>document.removeEventListener("keydown",ds)},[oe,ds]);const xs=i.useRef(null),{nodes:ra}=Cc(),{confirm:Jn}=li(),Ui=i.useCallback(async()=>{if(!(!cs||!we||Mt||!await Jn({title:"Unlink GitHub issue?",message:"This stops Fusion from syncing with the linked GitHub issue. The issue itself will not be modified.",confirmLabel:"Unlink",danger:!0}))){Xt(!0);try{const De=await Us(e.id,{githubTracking:{issue:null}},n);m?.(De),h("GitHub issue unlinked","success")}catch(De){h(`Failed to update ${e.id}: ${Se(De)}`,"error")}finally{Y.current&&Xt(!1)}}},[h,cs,Jn,we,Mt,m,n,e.id]),{entries:Hi,loading:Zs,loadMore:ja,hasMore:Na,total:Ya,loadingMore:Qa}=lv(e.id,b==="logs"&&A==="agent-log",n),Mn=i.useCallback(()=>{v?.()},[v]);i.useEffect(()=>{if(w)return;const ee=De=>{De.key==="Escape"&&!oe&&Mn()};return document.addEventListener("keydown",ee),()=>document.removeEventListener("keydown",ee)},[w,Mn,oe]);const ci=i.useCallback(async ee=>{try{const De=e.steps.some(ns=>ns.status!=="pending"),Ct=(ee==="todo"||ee==="triage")&&De;let Wt;if(Ct){if(await Jn({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Wt={preserveProgress:!0};else if(!await Jn({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await r(e.id,ee,Wt),Mn(),h(`Moved to ${hs[ee]}`,"success")}catch(De){h(Se(De),"error")}},[e.id,e.steps,r,Mn,h,Jn]),wi=i.useCallback(async()=>{if(await Jn({title:"Delete Task",message:`Delete ${e.id}?`,danger:!0}))try{await o(e.id),Mn(),h(`Deleted ${e.id}`,"info")}catch(De){const Ct=Zu(De);if(!Ct||Ct.dependentIds.length===0){h(Se(De),"error");return}const Wt=Ct.dependentIds.join(", ");if(!await Jn({title:"Force Delete Task",message:`${e.id} is a dependency of ${Wt}.
685
685
 
686
686
  Delete anyway by removing these dependency references first?`,danger:!0}))return;try{await o(e.id,{removeDependencyReferences:!0}),Mn(),h(`Deleted ${e.id} after removing dependency references`,"info")}catch(Gi){h(Se(Gi),"error")}}},[e.id,o,Mn,h,Jn]),Ai=i.useCallback(async()=>{await Jn({title:"Merge Task",message:`Merge ${e.id} into the current branch?`})&&(Mn(),h(`Merging ${e.id}...`,"info"),l(e.id).then(De=>{const Ct=De.merged?`Merged ${e.id} (branch: ${De.branch})`:`Closed ${e.id} (${De.error||"no branch to merge"})`;h(Ct,"success")}).catch(De=>{h(Se(De),"error")}))},[e.id,l,Mn,h,Jn]),Sa=i.useCallback(()=>{c&&(Mn(),c(e.id).then(()=>{h(`Retried ${e.id}`,"success")}).catch(ee=>{h(Se(ee),"error")}))},[e.id,c,Mn,h]),Xa=i.useCallback(()=>{d&&window.confirm(`This will erase all progress for ${e.id} and start the task from scratch. Continue?`)&&(Mn(),d(e.id).then(()=>{h(`Reset ${e.id} — fresh run will be allocated`,"success")}).catch(ee=>{h(Se(ee),"error")}))},[e.id,d,Mn,h]),Za=i.useCallback(async()=>{if(!(!u||!await Jn({title:"Duplicate Task",message:`Duplicate ${e.id}? This will create a new task in Triage with the same description and prompt.`})))try{const De=await u(e.id);Mn(),h(`Duplicated ${e.id} → ${De.id}`,"success")}catch(De){h(Se(De),"error")}},[e.id,u,Mn,h,Jn]),Ca=i.useCallback(async()=>{try{e.paused?(await Wj(e.id,n),h(`Unpaused ${e.id}`,"success")):(await ub(e.id,n),h(`Paused ${e.id}`,"success")),Mn()}catch(ee){h(Se(ee),"error")}},[e.id,e.paused,Mn,h]),Ea=i.useCallback(async()=>{try{await Yj(e.id,n),h(`Plan approved — ${e.id} moved to Todo`,"success"),Mn()}catch(ee){h(Se(ee),"error")}},[e.id,Mn,h]),_a=i.useCallback(async()=>{if(await Jn({title:"Reject Plan",message:"Reject this plan? The specification will be discarded and regenerated.",danger:!0}))try{await Qj(e.id,n),h(`Plan rejected — ${e.id} returned to Planning for replanning`,"info"),Mn()}catch(De){h(Se(De),"error")}},[e.id,Mn,h,Jn]),er=i.useCallback(async()=>{if(await Jn({title:"Rebuild Plan",message:"Rebuild the plan for this task? The task will move to planning for replanning."}))try{await lN(e.id,n),Mn(),h(`Replanning ${e.id}...`,"info")}catch(De){h(Se(De),"error")}},[e.id,n,Mn,h,Jn]),Ma=i.useCallback(()=>{Re(!0),ct("")},[]),di=i.useCallback(()=>{ut(!1),zt(!1)},[]),ki=i.useCallback(ee=>{di(),ci(ee)},[di]),Ds=i.useCallback(ee=>{di(),ee()},[di]),tr=i.useCallback(()=>{di(),Ai()},[di,Ai]),qi=i.useCallback(()=>{Re(!1),ct(""),ue(!1)},[]),nr=i.useCallback(async()=>{if(!Le.trim()){h("Please enter feedback describing what needs refinement","error");return}if(Le.length>2e3){h("Feedback must be 2000 characters or less","error");return}ue(!0);try{const ee=await cN(e.id,Le.trim(),n);h(`Refinement task created: ${ee.id}`,"success"),Mn()}catch(ee){h(Se(ee),"error")}finally{ue(!1)}},[e.id,Le,h,Mn]),ei=i.useCallback(async ee=>{D(!0);try{const De=await jc(e.id,ee,n);O(Ct=>[...Ct,De]),h("Screenshot attached","success")}catch(De){h(Se(De),"error")}finally{D(!1)}},[e.id,h]),Gr=i.useCallback(async ee=>{const De=ee.target.files?.[0];De&&(await ei(De),xs.current&&(xs.current.value=""))},[ei]);i.useEffect(()=>{const ee=De=>{const Ct=De.clipboardData?.items;if(Ct)for(let Wt=0;Wt<Ct.length;Wt++){const ns=Ct[Wt];if(ns.type.startsWith("image/")){const Gi=ns.getAsFile();if(Gi){De.preventDefault(),ei(Gi);return}}}};return document.addEventListener("paste",ee),()=>document.removeEventListener("paste",ee)},[ei]);const Kr=i.useCallback(ee=>{ee.preventDefault()},[]),Jr=i.useCallback(ee=>{ee.preventDefault();const De=ee.dataTransfer.files;for(let Ct=0;Ct<De.length;Ct++){const Wt=De[Ct];if(Wt.type.startsWith("image/")){ei(Wt);return}}},[ei]),oa=i.useCallback(async ee=>{try{await eN(e.id,ee,n),O(De=>De.filter(Ct=>Ct.filename!==ee)),h("Attachment deleted","info")}catch(De){h(Se(De),"error")}},[e.id,h]),Vi=i.useCallback(async ee=>{const De=rs;Ns(ee);try{const Ct=await Us(e.id,{enabledWorkflowSteps:ee},n);h("Workflow steps updated","success"),m?.(Ct)}catch(Ct){Ns(De),h(`Failed to update workflow steps: ${Se(Ct)}`,"error")}},[e.id,n,rs,m,h]),sr=i.useCallback(async()=>{L(!0);try{const ee=await Ur(void 0,n);fe(ee),re(!0)}catch(ee){h(`Failed to load agents: ${Se(ee)}`,"error"),re(!1)}finally{L(!1)}},[n,h]),ir=i.useCallback(async ee=>{try{const De=await sh(e.id,ee,n),Ct=ne.find(Wt=>Wt.id===ee)??null;je(Ct||(Wt=>Wt?.id===ee?Wt:null)),re(!1),m?.(De),h("Assigned agent updated","success")}catch(De){h(`Failed to assign agent: ${Se(De)}`,"error")}},[e.id,n,ne,m,h]),Yr=i.useCallback(async()=>{try{const ee=await sh(e.id,null,n);je(null),re(!1),m?.(ee),h("Agent unassigned","success")}catch(ee){h(`Failed to unassign agent: ${Se(ee)}`,"error")}},[e.id,n,m,h]),ar=i.useCallback(async ee=>{const De=[...$,ee];k(De);try{await Us(e.id,{dependencies:De},n)}catch(Ct){k($),h(Se(Ct),"error")}},[e.id,$,h]),Aa=i.useCallback(async(ee,De)=>{ee.stopPropagation();const Ct=$.filter(Wt=>Wt!==De);k(Ct);try{await Us(e.id,{dependencies:Ct},n)}catch(Wt){k($),h(Se(Wt),"error")}},[e.id,$,h]),Wi=i.useCallback(async ee=>{try{const De=await Ba(ee,n);a(De)}catch{h(`Failed to load dependency ${ee}`,"error")}},[a,h]),Je=i.useCallback(async ee=>{he(!0);try{await Us(N.id,{prompt:ee},n),h("Spec updated","success"),S&&(S.prompt=ee)}catch(De){throw h(Se(De),"error"),De}finally{he(!1)}},[N,S,h]),Rt=i.useCallback(async ee=>{pe(!0);try{await oN(e.id,ee,n),h("AI revision requested. Task moved to planning.","success"),Mn()}catch(De){const Ct=Se(De);Ct.includes("done")||Ct.includes("archived")?h("Cannot request revision: Task must be in 'triage', 'todo', 'in-progress', or 'in-review' column.","error"):h(Ct,"error")}finally{pe(!1)}},[e.id,h,Mn]),rn=i.useCallback(()=>{ae(!0),Te(N.prompt||""),Be("")},[N.prompt]),es=i.useCallback(()=>{ae(!1),Te(N.prompt||""),Be("")},[N.prompt]),Hn=i.useCallback(async()=>{if(Ve===(N.prompt||"")){es();return}ae(!1);try{await Je(Ve)}catch(ee){throw ae(!0),ee}},[Ve,N.prompt,Je,es]),Bs=i.useCallback(async()=>{rt.trim()&&await Rt(rt.trim())},[rt,Rt]),rr=i.useCallback(ee=>{ee.key==="Escape"?(ee.preventDefault(),es()):ee.key==="Enter"&&(ee.ctrlKey||ee.metaKey)&&(ee.preventDefault(),Hn())},[es,Hn]),Qr=s.filter(ee=>ee.id!==e.id&&!$.includes(ee.id)).sort((ee,De)=>{const Ct=De.createdAt.localeCompare(ee.createdAt);if(Ct!==0)return Ct;const Wt=parseInt(ee.id.slice(ee.id.lastIndexOf("-")+1),10)||0;return(parseInt(De.id.slice(De.id.lastIndexOf("-")+1),10)||0)-Wt}),z=i.useMemo(()=>tm(s),[s]).get(e.id),Ae=i.useMemo(()=>{if(!z)return[];const ee=new Set(z.staleBlockedByDependentIds);return z.dependentIds.map(De=>{const Ct=s.find(Wt=>Wt.id===De);return{id:De,label:Ct?.title||Ct?.description||De,stale:ee.has(De)}})},[z,s]),Ge=ye?.name??e.assignedAgentId??null,kt=i.useMemo(()=>{const ee=[];return N.modelProvider&&ee.push(N.modelProvider),N.validatorModelProvider&&!ee.includes(N.validatorModelProvider)&&ee.push(N.validatorModelProvider),N.planningModelProvider&&!ee.includes(N.planningModelProvider)&&ee.push(N.planningModelProvider),ee},[N.modelProvider,N.validatorModelProvider,N.planningModelProvider]),An=mu[e.column]||[],Vt=["todo","in-progress"],Nn=e.column==="in-review"?Vt:An,Xe=Nn[0],lt=Nn.slice(1),Tt=lt.length>0,Ln=i.useCallback(()=>{ut(!1),Pn.current?.focus()},[]),ti=i.useCallback(ee=>{if(!Tt){Xe&&ki(Xe);return}const De=ee.currentTarget.querySelector(".detail-move-btn__arrow");if(!!(ee.target instanceof Element&&ee.target.closest(".detail-move-btn__arrow")||De&&ee.clientX>0&&ee.clientX>=De.getBoundingClientRect().left)){ut(Wt=>!Wt),zt(!1);return}Xe&&ki(Xe)},[Tt,Xe,ki]),ui=i.useCallback(ee=>{!Tt||!(ee.key==="ArrowDown"||ee.altKey&&ee.key==="ArrowDown")||(ee.preventDefault(),ut(!0),zt(!1))},[Tt]),us=i.useCallback(ee=>{ee.key==="Escape"&&(ee.preventDefault(),ee.stopPropagation(),Ln())},[Ln]);i.useEffect(()=>{if(!_e)return;_n.current?.querySelector(".detail-move-menu-item")?.focus()},[_e]);const ts={"creating-pr":"Creating PR…","awaiting-pr-checks":"Awaiting PR checks","merging-pr":"Merging PR…","merging-fix":"Merging fixes…"},un=e.status?ts[e.status]:void 0,ni=bn?.mergeStrategy??"direct",Gs=bn?.autoMerge??!1,mi=ni==="pull-request"&&!Gs;let la="Merge & Close";return mi&&!un&&(e.prInfo?e.prInfo.status==="open"?la="Check PR Status":e.prInfo.status==="merged"&&(la="Finish & Close"):la="Start PR Review"),t.jsxs("div",{className:w?"task-detail-content task-detail-content--embedded":"task-detail-content",onDragOver:Kr,onDrop:Jr,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx("span",{className:"detail-id",children:e.id}),t.jsx("span",{className:`detail-column-badge badge-${e.column}`,children:hs[e.column]})]}),t.jsxs("div",{className:"modal-header-actions",children:[!oe&&cs&&t.jsx("button",{className:"modal-edit-btn",onClick:Cn,title:"Edit task","aria-label":"Edit task",children:t.jsx(Hs,{size:14})}),!w&&g==="back"&&t.jsxs("button",{className:"modal-close task-detail-mobile-back",onClick:Mn,"aria-label":"Back to task list",type:"button",children:[t.jsx(Ga,{"aria-hidden":"true"}),t.jsx("span",{children:"Back"})]}),!w&&g!=="back"&&t.jsx("button",{className:"modal-close",onClick:Mn,"aria-label":"Close",type:"button",children:"×"})]})]}),t.jsxs("div",{className:`detail-body${b==="logs"&&A==="agent-log"&&!oe?" detail-body--agent-log":""}`,children:[oe?t.jsx("div",{className:"modal-edit-form",children:t.jsx(gv,{mode:"edit",title:ft,onTitleChange:ht,description:tt,onDescriptionChange:xt,dependencies:Me,onDependenciesChange:Ye,branch:dt,onBranchChange:wt,baseBranch:St,onBaseBranchChange:Fe,executorModel:J,onExecutorModelChange:me,validatorModel:Ze,onValidatorModelChange:be,planningModel:gt,onPlanningModelChange:$t,thinkingLevel:Ie,onThinkingLevelChange:ge,presetMode:st,onPresetModeChange:yt,selectedPresetId:xn,onSelectedPresetIdChange:qt,selectedWorkflowSteps:Qt,onWorkflowStepsChange:hn,pendingImages:Bt,onImagesChange:Gt,tasks:s.filter(ee=>ee.id!==e.id),projectId:n,disabled:bt,addToast:h,isActive:oe,onAutoSaveDescription:Un,reviewLevel:pt,onReviewLevelChange:vt,priority:Ut,onPriorityChange:Dt,nodeId:nn,onNodeIdChange:on,nodeOptions:ra,nodeOverrideDisabled:ys,nodeOverrideDisabledReason:ys?"Execution node override is locked while a task is active/in progress.":void 0,executionMode:sn,onExecutionModeChange:ln,renderBelowModelConfiguration:t.jsxs("div",{className:"form-group detail-source-edit-group",children:[t.jsx("label",{children:"Source Issue"}),t.jsxs("div",{className:"detail-source-edit-grid",children:[t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Provider (e.g. github)",value:Zt,onChange:ee=>ve(ee.target.value),disabled:bt,"data-testid":"task-source-provider-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Repository (e.g. owner/repo)",value:Pe,onChange:ee=>Ke(ee.target.value),disabled:bt,"data-testid":"task-source-repository-input"}),t.jsx("input",{type:"text",className:"modal-edit-input",placeholder:"Issue identifier",value:at,onChange:ee=>We(ee.target.value),disabled:bt,"data-testid":"task-source-external-id-input"}),t.jsx("input",{type:"url",className:"modal-edit-input",placeholder:"Issue URL",value:It,onChange:ee=>Lt(ee.target.value),disabled:bt,"data-testid":"task-source-url-input"})]}),t.jsx("small",{children:"Leave all fields empty to clear source issue metadata."})]})})}):t.jsxs(t.Fragment,{children:[(()=>{const ee=e.title||e.description||e.id,De=!H&&ee.length>Rd;return t.jsxs(t.Fragment,{children:[t.jsx("h2",{className:"detail-title",children:De?ee.slice(0,Rd)+"…":ee}),ee.length>Rd&&t.jsx("button",{className:"detail-description-toggle",onClick:()=>Q(!H),children:H?"Show less":"Show more"})]})})(),t.jsxs("div",{className:"detail-meta",children:[t.jsxs("div",{className:"detail-meta-inline-controls","data-testid":"detail-meta-inline-controls",children:[t.jsxs("label",{className:`card-priority-badge card-priority-badge--${en} detail-priority-chip ${Sn?"detail-priority-chip--saving":""}`,children:[t.jsx("span",{children:"Priority:"}),t.jsx("select",{className:"detail-priority-select",value:en,onChange:ee=>{bs(ee.target.value)},disabled:Sn,"aria-label":"Task priority",children:wa.map(ee=>t.jsx("option",{value:ee,children:ee},ee))})]}),t.jsxs("button",{type:"button",className:`btn btn-sm detail-execution-mode-toggle ${Jt==="fast"?"detail-execution-mode-toggle--fast":""} ${Ne?"detail-execution-mode-toggle--saving":""}`,onClick:()=>{is()},disabled:Ne,"aria-label":`Execution mode: ${Jt}`,"aria-pressed":Jt==="fast",children:[t.jsx(ls,{"aria-hidden":"true"}),t.jsx("span",{children:Jt==="fast"?"Fast":"Standard"})]})]}),U&&t.jsxs("div",{className:"detail-provenance",children:[t.jsx(Os,{"aria-hidden":"true"}),t.jsxs("span",{children:[N.sourceType==="agent_heartbeat"?t.jsxs(t.Fragment,{children:["Created by"," ",U.sourceAgentId?t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>K(U.sourceAgentId),children:U.label}):U.label]}):t.jsxs(t.Fragment,{children:["Created via ",U.label]}),U.parentTaskId&&t.jsxs(t.Fragment,{children:[" ","of"," ",t.jsx("button",{type:"button",className:"detail-provenance-link",onClick:()=>Wi(U.parentTaskId),children:U.parentTaskId})]}),U.contextInfo?` (${U.contextInfo})`:""]})]}),(e.prInfo?.number||e.mergeDetails?.prNumber)&&t.jsxs("div",{className:"detail-provenance detail-pr-link-row",children:[t.jsx(Os,{"aria-hidden":"true"}),t.jsxs("span",{children:["PR"," ",e.prInfo?.url?t.jsxs("a",{className:"detail-provenance-link",href:e.prInfo.url,target:"_blank",rel:"noopener noreferrer",children:["#",e.prInfo.number]}):t.jsxs("span",{children:["#",e.prInfo?.number??e.mergeDetails?.prNumber]})]})]}),t.jsxs("div",{className:"detail-timestamps","aria-label":"Task timestamps",children:[t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Created"})," ",t.jsx("time",{dateTime:e.createdAt,title:new Date(e.createdAt).toLocaleString(),children:Ed(e.createdAt)})]}),t.jsx("span",{className:"detail-timestamp-separator","aria-hidden":"true",children:"·"}),t.jsxs("span",{className:"detail-timestamp-item",children:[t.jsx("span",{className:"detail-timestamp-label",children:"Updated"})," ",t.jsx("time",{dateTime:e.updatedAt,title:new Date(e.updatedAt).toLocaleString(),children:Ed(e.updatedAt)})]})]})]})]}),e.status==="failed"&&e.error&&t.jsxs("div",{className:"detail-error-alert",children:[t.jsx("span",{className:"detail-error-icon",children:"⚠"}),t.jsxs("div",{className:"detail-error-content",children:[t.jsx("div",{className:"detail-error-title",children:"Task Failed"}),t.jsx("div",{className:"detail-error-message",children:e.error})]})]}),!oe&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"detail-tabs",children:[t.jsx("button",{className:`detail-tab${b==="definition"?" detail-tab-active":""}`,onClick:()=>y("definition"),children:"Definition"}),t.jsx("button",{className:`detail-tab${b==="logs"?" detail-tab-active":""}`,onClick:()=>y("logs"),children:"Logs"}),(e.column==="in-progress"||e.column==="in-review"||e.column==="done")&&t.jsx("button",{className:`detail-tab${b==="changes"?" detail-tab-active":""}`,onClick:()=>y("changes"),children:"Changes"}),t.jsx("button",{className:`detail-tab${b==="review"?" detail-tab-active":""}`,onClick:()=>y("review"),children:"Review"}),t.jsx("button",{className:`detail-tab${b==="comments"?" detail-tab-active":""}`,onClick:()=>y("comments"),children:"Comments"}),t.jsx("button",{className:`detail-tab${b==="documents"?" detail-tab-active":""}`,onClick:()=>y("documents"),children:"Documents"}),t.jsx("button",{className:`detail-tab${b==="model"?" detail-tab-active":""}`,onClick:()=>y("model"),children:"Model"}),t.jsx("button",{className:`detail-tab${b==="workflow"?" detail-tab-active":""}`,onClick:()=>y("workflow"),children:"Workflow"}),t.jsx("button",{className:`detail-tab${b==="stats"?" detail-tab-active":""}`,onClick:()=>y("stats"),children:"Stats"}),t.jsx("button",{className:`detail-tab${b==="routing"?" detail-tab-active":""}`,onClick:()=>y("routing"),children:"Routing"}),vs.map(({entry:ee,tabId:De})=>t.jsx("button",{className:`detail-tab${b===De?" detail-tab-active":""}`,onClick:()=>y(De),children:ee.slot.label},`plugin-tab-${ee.pluginId}-${De}`))]}),b==="workflow"?t.jsx("div",{className:"detail-section",children:t.jsx(EP,{taskId:e.id,results:as,loading:Rs,enabledWorkflowSteps:rs,canEdit:cs,projectId:n,isTaskInProgress:e.column==="in-progress"&&e.status!=="paused",onWorkflowStepsChange:Vi})}):b==="model"?t.jsx("div",{className:"detail-section",children:t.jsx(tP,{task:e,addToast:h,onTaskUpdated:m,settings:bn})}):b==="logs"?t.jsxs("div",{className:`detail-section${A==="agent-log"?" detail-section--agent-log":""}`,children:[t.jsxs("div",{className:"log-subview-toggle",children:[t.jsx("button",{className:`log-subview-btn${A==="activity"?" log-subview-btn-active":""}`,onClick:()=>T("activity"),children:"Activity"}),t.jsx("button",{className:`log-subview-btn${A==="agent-log"?" log-subview-btn-active":""}`,onClick:()=>T("agent-log"),children:"Agent Log"})]}),A==="agent-log"?t.jsx(YT,{entries:Hi,loading:Zs,executorModel:zP(e,Hi,ye,bn),validatorModel:BP(e,Hi,ye,bn),planningModel:HP(e,Hi,bn),hasMore:Na,onLoadMore:ja,loadingMore:Qa,totalCount:Ya}):t.jsxs("div",{className:"detail-activity",children:[t.jsx("h4",{children:"Activity"}),N.activityLogTruncatedCount?t.jsxs("div",{className:"detail-log-truncated",children:["Showing the most recent ",N.log.length," activity entries."]}):null,N.log&&N.log.length>0?t.jsx("div",{className:"detail-activity-list",children:[...N.log].reverse().map((ee,De)=>t.jsxs("div",{className:"detail-log-entry",children:[t.jsxs("div",{className:"detail-log-header",children:[t.jsx("span",{className:"detail-log-timestamp",children:Ed(ee.timestamp)}),t.jsx("span",{className:"detail-log-action",children:ee.action})]}),ee.outcome&&t.jsx("div",{className:"detail-log-outcome",children:ee.outcome})]},De))}):t.jsx("div",{className:"detail-log-empty",children:"(no activity)"})]})]}):b==="changes"?t.jsx(xP,{taskId:e.id,worktree:e.worktree,projectId:n,column:e.column,mergeDetails:e.mergeDetails,modifiedFiles:e.modifiedFiles}):b==="review"?t.jsx(hP,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="comments"?t.jsx(rP,{task:e,addToast:h,projectId:n,onTaskUpdated:m}):b==="documents"?t.jsx($P,{taskId:e.id,addToast:h,projectId:n,onTaskUpdated:m,canEdit:cs}):As?t.jsx("div",{className:"detail-section",children:t.jsx(pa,{slotId:"task-detail-tab",projectId:n,pluginIds:[As.entry.pluginId]})}):b==="stats"?t.jsx("div",{className:"detail-section",children:t.jsx(LP,{tokenUsage:N.tokenUsage,loading:C,task:N})}):b==="routing"?t.jsx("div",{className:"detail-section",children:t.jsx(RP,{task:e,settings:bn,addToast:h,onTaskUpdated:m})}):t.jsxs(t.Fragment,{children:[e.column==="done"&&e.summary&&t.jsxs("div",{className:"detail-section detail-summary",children:[t.jsx("h4",{children:"Summary"}),t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:sf,children:e.summary})})]}),t.jsx(fP,{task:e}),e.sourceIssue&&t.jsxs("div",{className:"detail-section detail-source-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"Source issue"}),e.sourceIssue.provider.toLowerCase()==="github"&&t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub source issue",children:[t.jsx(Os,{"aria-hidden":"true"}),t.jsx("span",{children:"GitHub"})]}),e.sourceIssue.url?t.jsx("a",{className:"detail-source-link detail-source-link--summary detail-source-number",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:`(#${e.sourceIssue.issueNumber})`}):t.jsx("span",{className:"detail-source-number",children:`(#${e.sourceIssue.issueNumber})`})]}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":yn,"aria-label":yn?"Collapse source issue details":"Expand source issue details",onClick:()=>Zn(ee=>!ee),children:t.jsx(qn,{size:16,className:yn?"detail-source-chevron--expanded":void 0})})]}),yn&&t.jsxs("dl",{className:"detail-source-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Provider"}),t.jsx("dd",{children:e.sourceIssue.provider})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Repository"}),t.jsx("dd",{children:e.sourceIssue.repository})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"Issue Identifier"}),t.jsx("dd",{children:e.sourceIssue.externalIssueId})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"URL"}),t.jsx("dd",{children:e.sourceIssue.url?t.jsx("a",{className:"detail-source-link",href:e.sourceIssue.url,target:"_blank",rel:"noopener noreferrer",children:e.sourceIssue.url}):t.jsx("span",{className:"detail-source-empty",children:"(none)"})})]})]})]}),Ce&&t.jsxs("div",{className:"detail-section detail-github-tracking-section",children:[t.jsxs("div",{className:"detail-source-header",children:[t.jsxs("div",{className:"detail-source-summary",children:[t.jsx("span",{className:"detail-source-label",children:"GitHub tracking"}),t.jsxs("span",{className:"detail-source-provider-badge","aria-label":"GitHub tracking status",children:[t.jsx(Os,{"aria-hidden":"true"}),t.jsx("span",{children:qe})]}),!we&&t.jsx("span",{className:"detail-source-empty",children:te?"Issue not yet created":"Tracking is currently disabled"})]}),P&&t.jsx("button",{type:"button",className:"btn btn-sm btn-primary detail-github-tracking-enable","aria-label":"Enable GitHub tracking",onClick:()=>void Nt(),disabled:Mt,children:Mt?"Saving…":"Enable"}),t.jsx("button",{type:"button",className:"detail-source-toggle","aria-expanded":vn,"aria-label":vn?"Collapse GitHub tracking details":"Expand GitHub tracking details",onClick:()=>Dn(ee=>!ee),children:t.jsx(qn,{size:16,className:vn?"detail-source-chevron--expanded":void 0})})]}),vn&&t.jsxs("div",{className:"detail-github-tracking-content",children:[we&&t.jsxs("dl",{className:"detail-source-grid detail-github-tracking-grid",children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Issue"}),t.jsx("dd",{children:we.url?t.jsx("a",{className:"detail-source-link",href:we.url,target:"_blank",rel:"noopener noreferrer",children:`${we.owner}/${we.repo}#${we.number}`}):t.jsx("span",{children:`${we.owner}/${we.repo}#${we.number}`})})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"State"}),t.jsx("dd",{children:t.jsx("span",{className:`detail-github-issue-state ${e.issueInfo?.state==="closed"?"detail-github-issue-state--closed":"detail-github-issue-state--open"}`,children:e.issueInfo?.state??"open"})})]})]}),t.jsxs("div",{className:"detail-github-tracking-controls",children:[!we&&te&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void an(),disabled:Mt,children:"Create tracking issue"}),ss&&t.jsxs(t.Fragment,{children:[t.jsxs("label",{className:"checkbox-label",htmlFor:"detail-github-tracking-toggle",children:[t.jsx("input",{id:"detail-github-tracking-toggle",type:"checkbox",checked:te,disabled:Mt,onChange:()=>void Nt()}),"Enable GitHub tracking"]}),t.jsxs("div",{className:"detail-github-tracking-repo-row",children:[t.jsx("input",{className:"input",value:de,onChange:ee=>{nt(ee.target.value),Oe(null)},placeholder:et||"owner/repo"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void Pt(),disabled:Mt,children:"Save"})]}),G&&t.jsx("small",{className:"detail-github-tracking-error",children:G}),we&&t.jsx("button",{className:"btn btn-sm touch-target",onClick:()=>void Ui(),disabled:Mt,children:"Unlink GitHub issue"})]})]})]})]}),t.jsx("div",{className:"detail-section detail-agent-section",children:t.jsxs("div",{className:"detail-meta-row",children:[t.jsxs("div",{className:"detail-meta-left",children:[kt.length>0&&t.jsx("span",{className:"detail-provider-icons","data-testid":"detail-provider-icons",children:kt.map(ee=>t.jsx(zn,{provider:ee,size:"sm"},ee))}),t.jsxs("span",{className:"detail-meta-label",children:[t.jsx(Qn,{size:14,className:"detail-meta-label-icon"}),"Agent"]})]}),t.jsxs("div",{className:"detail-agent-actions",children:[Ge?t.jsxs("span",{className:"detail-agent-chip",children:[t.jsx(Qn,{size:14}),Ge,t.jsx("button",{className:"detail-agent-clear",onClick:()=>void Yr(),title:"Unassign agent",children:t.jsx(mn,{size:12})})]}):t.jsx("button",{className:"btn btn-sm",onClick:()=>{Z?re(!1):sr()},children:"Assign Agent"}),Z&&t.jsxs("div",{className:"agent-picker-dropdown",children:[q&&t.jsx("div",{className:"agent-picker-loading",children:"Loading agents..."}),!q&&ne.map(ee=>t.jsxs("button",{className:`agent-picker-item${e.assignedAgentId===ee.id?" selected":""}`,onClick:()=>void ir(ee.id),children:[t.jsx(Qn,{size:14}),t.jsx("span",{className:"agent-picker-name",children:ee.name}),t.jsx("span",{className:"agent-picker-role",children:ee.role})]},ee.id)),!q&&ne.length===0&&t.jsx("div",{className:"agent-picker-empty",children:"No agents available"})]})]})]})}),t.jsxs("div",{className:"detail-section detail-step-progress",children:[t.jsx("h4",{children:"Progress"}),N.steps&&N.steps.length>0?t.jsxs("div",{className:"step-progress-wrapper",children:[t.jsx("div",{className:"step-progress-bar",children:N.steps.map((ee,De)=>t.jsx("div",{className:`step-progress-segment step-progress-segment--${ee.status}`,"data-tooltip":`${ee.name} (${ee.status})`,style:{backgroundColor:qP(ee.status)}},De))}),t.jsxs("span",{className:"step-progress-label",children:[N.steps.filter(ee=>ee.status==="done").length,"/",N.steps.length," step",N.steps.length===1?"":"s"]})]}):t.jsx("div",{className:"step-progress-empty",children:"(no steps defined)"})]}),t.jsxs("div",{className:"detail-section",children:[!ze&&t.jsx("div",{className:"detail-spec-edit-trigger",children:t.jsx("button",{className:"btn btn-sm",onClick:rn,children:"Edit"})}),ze?t.jsxs("div",{className:"spec-editor-edit-mode",children:[t.jsx("textarea",{className:"spec-editor-textarea",value:Ve,onChange:ee=>Te(ee.target.value),onKeyDown:rr,disabled:xe,placeholder:"Enter task specification in Markdown...",rows:12}),t.jsxs("div",{className:"spec-editor-actions-row",children:[t.jsx("button",{className:"btn btn-sm",onClick:es,disabled:xe,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Hn(),disabled:Ve===(N.prompt||"")||xe,children:xe?"Saving…":"Save"})]}),t.jsxs("div",{className:"spec-editor-hint",children:[t.jsx("kbd",{children:"Ctrl"}),"+",t.jsx("kbd",{children:"Enter"})," to save · ",t.jsx("kbd",{children:"Escape"})," to cancel"]}),t.jsxs("div",{className:"spec-editor-revision",children:[t.jsx("h4",{children:"Ask AI to Revise"}),t.jsx("p",{className:"spec-editor-revision-help",children:"Provide feedback for the AI to improve this specification. The task will move to planning for replanning."}),t.jsx("textarea",{className:"spec-editor-feedback",value:rt,onChange:ee=>Be(ee.target.value),placeholder:"e.g., 'Add more details about error handling', 'Split this into smaller steps', 'Include tests for the API endpoints'...",disabled:B,rows:4,maxLength:2e3}),t.jsxs("div",{className:"spec-editor-revision-actions",children:[t.jsxs("span",{className:"spec-editor-char-count",children:[rt.length,"/2000"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void Bs(),disabled:!rt.trim()||B,children:B?"Requesting…":"Request AI Revision"})]})]})]}):C?t.jsx("div",{className:"spec-loading",children:"Loading specification…"}):N.prompt?t.jsx("div",{className:"markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],components:sf,children:N.prompt.replace(/^#\s+[^\n]*\n+/,"")})}):t.jsx("div",{className:"detail-prompt",children:"(no prompt)"})]}),t.jsxs("div",{className:"detail-section",children:[t.jsx("h4",{children:"Attachments"}),se.length>0?t.jsx("div",{className:"detail-attachments-grid",children:se.map(ee=>{const De=Fi(`/api/tasks/${e.id}/attachments/${ee.filename}`);return t.jsxs("div",{className:"detail-attachment-card",children:[t.jsx("a",{className:"detail-attachment-link",href:De,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{src:De,alt:ee.originalName,className:"detail-attachment-image"})}),t.jsxs("div",{className:"detail-attachment-meta",children:[ee.originalName," (",VP(ee.size),")"]}),t.jsx("button",{className:"detail-attachment-delete",onClick:()=>oa(ee.filename),title:"Delete attachment",children:"×"})]},ee.filename)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no attachments)"}),t.jsx("input",{className:"detail-hidden-file-input",ref:xs,type:"file",accept:"image/*",onChange:Gr}),t.jsx("button",{className:"btn btn-sm",onClick:()=>xs.current?.click(),disabled:M,children:M?"Uploading…":"Attach Screenshot"})]}),t.jsxs("div",{className:"detail-deps",children:[t.jsx("h4",{children:"Dependencies"}),$.length>0?t.jsx("ul",{className:"detail-dep-list",children:$.map(ee=>{const De=s.find(Wt=>Wt.id===ee),Ct=De?.title||De?.description||ee;return t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Wi(ee),onKeyDown:Wt=>{(Wt.key==="Enter"||Wt.key===" ")&&(Wt.preventDefault(),Wi(ee))},role:"link",tabIndex:0,title:`Click to view ${ee}`,children:[t.jsx("span",{className:"detail-dep-id",children:ee}),t.jsx("span",{className:"detail-dep-label",children:_d(Ct,40)})]}),t.jsx("button",{className:"dep-remove-btn",onClick:Wt=>Aa(Wt,ee),title:`Remove dependency ${ee}`,children:"×"})]},ee)})}):t.jsx("div",{className:"detail-empty-inline",children:"(no dependencies)"}),t.jsxs("div",{className:"dep-trigger-wrap",children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{X&&He(""),le(ee=>!ee)},children:"Add Dependency"}),X&&(()=>{const ee=ke.toLowerCase(),De=ee?Qr.filter(Ct=>Ct.id.toLowerCase().includes(ee)||Ct.title&&Ct.title.toLowerCase().includes(ee)||Ct.description&&Ct.description.toLowerCase().includes(ee)):Qr;return t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:ke,onChange:Ct=>He(Ct.target.value),onClick:Ct=>Ct.stopPropagation()}),De.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):De.map(Ct=>t.jsxs("div",{className:"dep-dropdown-item",onClick:()=>{ar(Ct.id),le(!1)},children:[t.jsx("span",{className:"dep-dropdown-id",children:Ct.id}),t.jsx("span",{className:"dep-dropdown-title",children:_d(Ct.title||Ct.description||Ct.id,30)})]},Ct.id))]})})()]})]}),t.jsxs("div",{className:"detail-deps detail-blocking",children:[t.jsx("h4",{children:"Blocking"}),Ae.length>0?t.jsx("ul",{className:"detail-dep-list",children:Ae.map(ee=>t.jsxs("li",{className:"detail-dep-item",children:[t.jsxs("span",{className:"detail-dep-link",onClick:()=>Wi(ee.id),onKeyDown:De=>{(De.key==="Enter"||De.key===" ")&&(De.preventDefault(),Wi(ee.id))},role:"link",tabIndex:0,title:`Click to view ${ee.id}`,children:[t.jsx("span",{className:"detail-dep-id",children:ee.id}),t.jsx("span",{className:"detail-dep-label",children:_d(ee.label,40)})]}),ee.stale&&t.jsx("span",{className:"detail-blocking-item--stale",title:"Stale blockedBy edge: self-healing clearStaleBlockedBy should clear this automatically",children:"(stale)"})]},ee.id))}):t.jsx("div",{className:"detail-empty-inline",children:"(no downstream tasks blocked)"})]}),e.column==="in-review"&&t.jsx("div",{className:"detail-section detail-pr-section",children:t.jsx(sP,{taskId:e.id,projectId:n,prInfo:e.prInfo,automationStatus:e.status??null,autoMerge:bn?.autoMerge??!1,isManualPrFlow:mi,prAuthAvailable:f??!1,onPrCreated:ee=>{e.prInfo=ee},onPrUpdated:ee=>{e.prInfo=ee},addToast:h})})]})]})]}),t.jsx("div",{className:"modal-actions",children:oe?t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"modal-edit-hint",children:$e==="saving"?"Autosaving…":$e==="saved"?"Saved":$e==="error"?"Save failed":"Changes autosave as you edit"}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("button",{className:"btn btn-sm",onClick:ie,disabled:bt,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void gs(),disabled:bt,children:bt?"Saving…":"Save"})]}):t.jsxs(t.Fragment,{children:[e.column==="triage"&&e.status==="awaiting-approval"&&N.prompt&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ea,children:"Approve Plan"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:_a,children:"Reject Plan"})]}),e.column==="triage"&&e.status!=="awaiting-approval"&&!R&&t.jsx("button",{className:"btn btn-sm btn-danger",onClick:wi,"aria-label":"Delete task",title:"Delete task",children:"Delete"}),(e.column!=="triage"||e.status==="awaiting-approval"||R||e.paused)&&t.jsxs("div",{className:"detail-actions-dropdown",ref:kn,children:[t.jsxs("button",{className:"btn btn-sm",onClick:()=>{zt(ee=>!ee),ut(!1)},"aria-haspopup":"menu","aria-expanded":At,children:["Actions",t.jsx(gn,{size:12})]}),At&&t.jsxs("div",{className:"detail-actions-menu",role:"menu",children:[t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>Ds(wi),children:"Delete"}),u&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(Za),children:"Duplicate"}),(e.column==="done"||e.column==="in-review")&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(Ma),children:"Refine"}),t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(er),children:"Respecify"}),R&&c&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(Sa),children:"Retry"}),d&&e.column!=="done"&&e.column!=="archived"&&t.jsx("button",{className:"detail-actions-menu-item detail-actions-menu-item-danger",role:"menuitem",onClick:()=>Ds(Xa),children:"Reset"}),e.column!=="done"&&!e.assignedAgentId&&t.jsx("button",{className:"detail-actions-menu-item",role:"menuitem",onClick:()=>Ds(Ca),children:e.paused?"Unpause":"Pause"}),e.column!=="done"&&e.paused&&e.pausedByAgentId&&t.jsx("span",{className:"detail-actions-menu-item detail-actions-menu-note",role:"note",children:"Paused by agent"})]})]}),t.jsx("div",{className:"modal-actions-spacer"}),t.jsx("div",{className:"detail-move-dropdown",ref:_n,children:e.column==="in-review"?t.jsxs("div",{className:"detail-move-actions-in-review",children:[t.jsxs("div",{children:[t.jsxs("button",{ref:Pn,className:"btn btn-primary btn-sm detail-move-btn",onClick:ti,onKeyDown:ui,disabled:!Xe,"aria-label":Xe?`Move to ${hs[Xe]}`:void 0,"aria-haspopup":Tt?"menu":void 0,"aria-expanded":Tt?_e:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Xe?hs[Xe]:""]}),Tt&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(gn,{size:12})})]}),_e&&Tt&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:us,children:lt.map(ee=>t.jsx("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ki(ee),onKeyDown:us,children:ee==="in-progress"?"Back to In Progress":`Move to ${hs[ee]}`},ee))})]}),un?t.jsx("button",{className:"btn btn-primary btn-sm",disabled:!0,children:un}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:tr,children:la})]}):t.jsxs("div",{children:[t.jsxs("button",{ref:Pn,className:"btn btn-primary btn-sm detail-move-btn",onClick:ti,onKeyDown:ui,disabled:!Xe,"aria-label":Xe?`Move to ${hs[Xe]}`:void 0,"aria-haspopup":Tt?"menu":void 0,"aria-expanded":Tt?_e:void 0,children:[t.jsxs("span",{className:"detail-move-btn__label",children:["Move to ",Xe?hs[Xe]:""]}),Tt&&t.jsx("span",{className:"detail-move-btn__arrow","aria-hidden":"true",children:t.jsx(gn,{size:12})})]}),_e&&Tt&&t.jsx("div",{className:"detail-move-menu",role:"menu",onKeyDown:us,children:lt.map(ee=>t.jsxs("button",{className:"detail-move-menu-item",role:"menuitem",onClick:()=>ki(ee),onKeyDown:us,children:["Move to ",hs[ee]]},ee))})]})})]})}),ce&&t.jsx("div",{className:"modal-overlay open detail-refine-overlay",onClick:qi,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal detail-refine-modal",onClick:ee=>ee.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{className:"detail-refine-title",children:"Refine"}),t.jsx("button",{className:"modal-close",onClick:qi,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"detail-body",children:[t.jsx("p",{className:"detail-refine-help",children:"Describe what needs to be refined or improved..."}),t.jsx("textarea",{className:"detail-refine-textarea",value:Le,onChange:ee=>ct(ee.target.value),placeholder:"Enter your feedback here...",rows:6,maxLength:2e3,autoFocus:!0}),t.jsxs("div",{className:"detail-refine-input-group",children:[t.jsxs("div",{className:"detail-refine-char-count",children:[Le.length,"/2000 characters"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:nr,disabled:!Le.trim()||Ue,children:Ue?"Creating...":"Create Refinement Task"})]})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{className:"btn btn-sm",onClick:qi,disabled:Ue,children:"Cancel"})})]})}),_&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(JP,{agentId:_,projectId:n,onClose:()=>K(null),addToast:h})})]})}function ZP({onClose:e,...n}){const s=i.useRef(null);zi(s,!0,"task-detail-modal-size"),Mi(!0);const a=sa(e);return t.jsx("div",{className:"modal-overlay open",...a,role:"dialog","aria-modal":"true",children:t.jsx("div",{className:"modal modal-lg task-detail-modal",ref:s,children:t.jsx(xv,{...n,onRequestClose:e})})})}const yl={triage:"var(--triage)",todo:"var(--todo)","in-progress":"var(--in-progress)","in-review":"var(--in-review)",done:"var(--done)",archived:"var(--text-secondary)"},rf=new Set(["planning","researching","executing","finalizing","merging","merging-fix"]);function of(e){return e==="merging-fix"?"Merging fixes…":e}const vv=["title","status","column","dependencies","progress"],e$=["title","status","column"];function t$(e){return e==="online"?"Online":e==="connecting"?"Connecting":e==="error"?"Error":"Offline"}function n$(e){return e==="online"?"●":e==="connecting"?"◐":e==="error"?"✕":"○"}function lf(e){try{const n=Gn("kb-dashboard-list-columns",e);if(n){const a=JSON.parse(n).filter(r=>vv.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set(e$)}function cf(e){try{const n=Gn("kb-dashboard-hide-done",e);if(n!==null)return n==="true"}catch{}return!1}function df(e){try{const n=Gn("kb-dashboard-list-collapsed",e);if(n){const a=JSON.parse(n).filter(r=>ha.includes(r));if(a.length>0)return new Set(a)}}catch{}return new Set}function uf(e){try{const n=Gn("kb-dashboard-selected-tasks",e);if(n){const s=JSON.parse(n);return new Set(s)}}catch{}return new Set}function mf(e){try{const n=Gn("kb-dashboard-list-selected-task",e);if(typeof n=="string"&&n.trim().length>0)return n}catch{}return null}function hf(e){try{const s=Gn("kb-dashboard-list-sidebar-width",e);if(!s)return 400;const a=Number(s);if(Number.isFinite(a)&&a>0)return a}catch{}return 400}const ac=280,_u=.65,wl=16;function Mu(e){return Math.max(ac,e*_u)}function kl(e,n){const s=Mu(n);return Math.min(Math.max(e,ac),s)}function s$(e){return e.status==="executing"||e.column==="in-progress"}function pf(e){const n=Hb(e);return n.total===0||!s$(e)?{label:"-",percent:0,hasProgress:!1}:{label:`${n.completed}/${n.total}`,percent:n.completed/n.total*100,hasProgress:!0}}function i$({tasks:e,onMoveTask:n,onRetryTask:s,onDeleteTask:a,onMergeTask:r,onResetTask:o,onDuplicateTask:l,onOpenDetail:c,addToast:d,globalPaused:u,onNewTask:m,onQuickCreate:h,availableModels:f,favoriteProviders:p=[],favoriteModels:g=[],onToggleFavorite:w,onToggleModelFavorite:v,onPlanningMode:b,onSubtaskBreakdown:y,onTasksUpdated:S,projectId:j,projectName:C,taskStuckTimeoutMs:x,searchQuery:N="",lastFetchTimeMs:R,prAuthAvailable:F}){const[E,_]=i.useState(null),[K,U]=i.useState("asc"),[A,T]=i.useState(null),[H,Q]=i.useState(null),[se,O]=i.useState(null),D=oi()==="mobile",{confirm:$}=li(),[k,X]=i.useState(()=>lf(j)),[le,ke]=i.useState(()=>cf(j)),[He,ye]=i.useState(()=>df(j));i.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-list-columns",JSON.stringify([...k]),j)},[j,k]),i.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-hide-done",le.toString(),j)},[le,j]),i.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-list-collapsed",JSON.stringify([...He]),j)},[He,j]);const[je,ne]=i.useState(!1),[fe,Z]=i.useState(!1),[re,q]=i.useState(()=>uf(j)),[L,xe]=i.useState(()=>mf(j)),[he,B]=i.useState(null),[pe,ze]=i.useState(()=>hf(j)),ae=i.useRef(null),Ve=i.useRef(null);i.useEffect(()=>{X(lf(j)),ke(cf(j)),ye(df(j)),q(uf(j));const ve=mf(j);xe(ve),B(ve?e.find(Pe=>Pe.id===ve)??null:null),ze(hf(j))},[j,e]),i.useEffect(()=>{typeof window<"u"&&fs("kb-dashboard-selected-tasks",JSON.stringify([...re]),j)},[j,re]),i.useEffect(()=>{if(!(typeof window>"u")){if(L){fs("kb-dashboard-list-selected-task",L,j);return}Ar("kb-dashboard-list-selected-task",j)}},[j,L]),i.useEffect(()=>{if(!L){B(null);return}const ve=e.find(Pe=>Pe.id===L);ve&&B(Pe=>!Pe||Pe.id!==L?ve:{...Pe,...ve})},[L,e]),i.useEffect(()=>{if(D||typeof ResizeObserver>"u")return;const ve=ae.current;if(!ve)return;const Pe=()=>{const at=kl(pe,ve.clientWidth);at!==pe&&ze(at)};Pe();const Ke=new ResizeObserver(Pe);return Ke.observe(ve),()=>Ke.disconnect()},[D,pe]),i.useEffect(()=>{if(D||typeof ResizeObserver>"u")return;const ve=Ve.current,Pe=ae.current;if(!ve||!Pe)return;let Ke=null,at=ve.offsetWidth;const We=new ResizeObserver(()=>{const It=kl(ve.offsetWidth,Pe.clientWidth);It!==at&&(at=It,Ke&&clearTimeout(Ke),Ke=setTimeout(()=>{try{fs("kb-dashboard-list-sidebar-width",String(It),j)}catch{}},200))});return We.observe(ve),()=>{We.disconnect(),Ke&&clearTimeout(Ke)}},[D,j]);const Te=i.useCallback(()=>{Z(ve=>(ve&&q(new Set),!ve))},[]),rt=i.useCallback(ve=>{q(Pe=>{const Ke=new Set(Pe);return Ke.has(ve)?Ke.delete(ve):Ke.add(ve),Ke})},[]),Be=i.useCallback(()=>{q(new Set)},[]),ce=i.useCallback(ve=>{X(Pe=>{const Ke=new Set(Pe);return Ke.has(ve)?Ke.size>1&&Ke.delete(ve):Ke.add(ve),Ke})},[]),Re={title:"Title",status:"Status",column:"Column",dependencies:"Dependencies",progress:"Progress"},Le=i.useCallback(ve=>{if(E===ve){U(Pe=>Pe==="asc"?"desc":"asc");return}_(ve),U("asc")},[E]),ct=i.useCallback(ve=>{O(Pe=>Pe===ve?null:ve)},[]),Ue=i.useCallback(ve=>{ye(Pe=>{const Ke=new Set(Pe);return Ke.has(ve)?Ke.delete(ve):Ke.add(ve),Ke})},[]),ue=i.useCallback(()=>{O(null)},[]),oe=i.useMemo(()=>{let ve=N?e.filter(at=>at.id.toLowerCase().includes(N.toLowerCase())||at.title&&at.title.toLowerCase().includes(N.toLowerCase())||at.description.toLowerCase().includes(N.toLowerCase())):[...e];le&&!se&&(ve=ve.filter(at=>at.column!=="done"&&at.column!=="archived"));const Pe=se?ve.filter(at=>at.column===se):ve,Ke={triage:[],todo:[],"in-progress":[],"in-review":[],done:[],archived:[]};Pe.forEach(at=>{const We=Qu(at.column)?at.column:Xl;Ke[We].push(at)});for(const at of ha){if(!E){Ke[at]=Ob(Ke[at],at);continue}Ke[at]=[...Ke[at]].sort((We,It)=>{let Lt=0;switch(E){case"title":Lt=(We.title||We.description).localeCompare(It.title||It.description);break;case"status":Lt=(We.status||"").localeCompare(It.status||"");break;case"column":Lt=We.column.localeCompare(It.column);break}return K==="asc"?Lt:-Lt})}return Ke},[e,N,E,K,le,se]),Ee=i.useMemo(()=>Object.values(oe).reduce((ve,Pe)=>ve+Pe.length,0),[oe]),ft=i.useMemo(()=>e.filter(ve=>ve.column==="done"||ve.column==="archived").length,[e]),ht=i.useMemo(()=>le?ft:0,[le,ft]),tt=i.useCallback(()=>{const ve=Object.values(oe).flat().filter(Pe=>Pe.column!=="archived").map(Pe=>Pe.id);q(Pe=>{if(ve.every(at=>Pe.has(at))){const at=new Set(Pe);return ve.forEach(We=>at.delete(We)),at}else return new Set([...Pe,...ve])})},[oe]),xt=i.useMemo(()=>{const ve=Object.values(oe).flat().filter(Pe=>Pe.column!=="archived");return ve.length===0?!1:ve.every(Pe=>re.has(Pe.id))},[oe,re]),Me=i.useMemo(()=>{const ve=Object.values(oe).flat().filter(Ke=>Ke.column!=="archived");if(ve.length===0)return!1;const Pe=ve.filter(Ke=>re.has(Ke.id)).length;return Pe>0&&Pe<ve.length},[oe,re]),[Ye,dt]=i.useState("__no_change__"),[wt,St]=i.useState("__no_change__"),[Fe,J]=i.useState("__no_change__"),[me,Ze]=i.useState([]),[be,gt]=i.useState(!1),$t=i.useMemo(()=>Fe&&Fe!=="__no_change__"?me.find(ve=>ve.id===Fe):void 0,[me,Fe]),[Ie,ge]=i.useState(!1);i.useEffect(()=>{if(re.size===0)return;let ve=!1;return(async()=>{gt(!0);try{const Ke=await Yl();ve||Ze(Ke)}catch(Ke){console.error("Failed to fetch nodes for bulk edit",Ke),ve||Ze([])}finally{ve||gt(!1)}})(),()=>{ve=!0}},[re.size]);const st=i.useCallback(async()=>{if(re.size===0)return;const ve=Array.from(re).map(Bt=>e.find(Gt=>Gt.id===Bt)).filter(Bt=>!!Bt),Pe=ve.filter(Bt=>Bt.column==="archived"),Ke=ve.filter(Bt=>Bt.column!=="archived");if(Ke.length===0){d("No selected tasks can be deleted (archived tasks are excluded)","error");return}if(!await $({title:"Delete Selected Tasks",message:`Delete ${Ke.length} selected task${Ke.length===1?"":"s"}?`,confirmLabel:"Delete",cancelLabel:"Cancel",danger:!0}))return;ge(!0);const We=[],It=[],Lt=Pe.map(Bt=>Bt.id);try{for(const Bt of Ke)try{await a(Bt.id),We.push(Bt.id)}catch(Gt){const bt=Zu(Gt);if(!bt){It.push(Bt.id);continue}if(!await $({title:"Force Delete Task",message:`Task ${Bt.id} has dependents: ${bt.dependentIds.join(", ")}. Remove dependency references and force delete?`,confirmLabel:"Force Delete",cancelLabel:"Skip",danger:!0})){It.push(Bt.id);continue}try{await a(Bt.id,{removeDependencyReferences:!0}),We.push(Bt.id)}catch{It.push(Bt.id)}}}finally{ge(!1)}We.length>0&&q(Bt=>{const Gt=new Set(Bt);for(const bt of We)Gt.delete(bt);return Gt}),d(`Deleted ${We.length} task${We.length===1?"":"s"} · ${Lt.length} archived skipped · ${It.length} failed`,It.length>0?"error":"success")},[d,$,a,re,e]),yt=i.useCallback(async()=>{if(re.size===0)return;const ve=Array.from(re).filter(Ke=>{const at=e.find(We=>We.id===Ke);return at&&at.column!=="archived"});if(ve.length===0){d("No valid tasks to update (archived tasks cannot be modified)","error");return}const Pe={taskIds:ve};if(Ye!=="__no_change__")if(Ye==="")Pe.modelProvider=null,Pe.modelId=null;else{const Ke=Ye.indexOf("/");Ke!==-1&&(Pe.modelProvider=Ye.slice(0,Ke),Pe.modelId=Ye.slice(Ke+1))}if(wt!=="__no_change__")if(wt==="")Pe.validatorModelProvider=null,Pe.validatorModelId=null;else{const Ke=wt.indexOf("/");Ke!==-1&&(Pe.validatorModelProvider=wt.slice(0,Ke),Pe.validatorModelId=wt.slice(Ke+1))}if(Fe!=="__no_change__"&&(Fe===""?Pe.nodeId=null:Pe.nodeId=Fe),Object.keys(Pe).length===1){d("No changes to apply","info");return}ge(!0);try{const Ke=await Fj(Pe.taskIds,Pe.modelProvider,Pe.modelId,Pe.validatorModelProvider,Pe.validatorModelId,void 0,void 0,Pe.nodeId,j);S&&S(Ke.updated),d(`Updated ${ve.length} task${ve.length===1?"":"s"}`,"success"),Be(),dt("__no_change__"),St("__no_change__"),J("__no_change__")}catch(Ke){d(Se(Ke)||"Failed to update models","error")}finally{ge(!1)}},[re,e,Ye,wt,Fe,j,d,Be,S]),pt=i.useCallback(ve=>{if(D){c(ve,{origin:"list-mobile"});return}xe(ve.id),B(ve)},[D,c]),vt=i.useRef(null),Ut=i.useRef(null);i.useEffect(()=>()=>{vt.current&&clearTimeout(vt.current)},[]);const Dt=i.useCallback(ve=>{if(xe(ve.id),B(ve),"prompt"in ve){Ut.current=null,vt.current&&(clearTimeout(vt.current),vt.current=null);return}Ut.current=ve.id,vt.current&&clearTimeout(vt.current),vt.current=setTimeout(()=>{vt.current=null,Ut.current===ve.id&&Ba(ve.id,j).then(Ke=>{Ut.current===Ke.id&&B(at=>!at||at.id!==Ke.id?at:{...at,...Ke})}).catch(()=>{})},200)},[j]),nn=i.useCallback((ve,Pe)=>{if(Pe.paused){ve.preventDefault();return}ve.dataTransfer.setData("text/plain",Pe.id),ve.dataTransfer.effectAllowed="move",T(Pe.id)},[]),on=i.useCallback(()=>{T(null),Q(null)},[]),sn=i.useCallback(ve=>{if(D)return;ve.preventDefault();const Pe=ae.current;if(!Pe)return;const Ke=Pe.getBoundingClientRect(),at=It=>{const Lt=It.clientX-Ke.left;ze(kl(Lt,Ke.width))},We=()=>{window.removeEventListener("mousemove",at),window.removeEventListener("mouseup",We)};window.addEventListener("mousemove",at),window.addEventListener("mouseup",We)},[D]),ln=i.useCallback(ve=>{if(D)return;const Pe=ae.current?.clientWidth??0,Ke=pe/_u+wl,at=Math.max(Pe,Ke),We=Mu(at);if(ve.key==="ArrowLeft"||ve.key==="ArrowRight"){ve.preventDefault();const It=ve.key==="ArrowLeft"?-wl:wl;ze(Lt=>kl(Lt+It,at));return}if(ve.key==="Home"){ve.preventDefault(),ze(ac);return}ve.key==="End"&&(ve.preventDefault(),ze(We))},[D,pe]),xn=i.useCallback((ve,Pe)=>{ve.preventDefault(),ve.dataTransfer.dropEffect="move",Q(Pe)},[]),qt=i.useCallback(()=>{Q(null)},[]),Qt=i.useCallback(async(ve,Pe)=>{ve.preventDefault(),Q(null);const Ke=ve.dataTransfer.getData("text/plain");if(Ke){if(Pe==="archived"){d("Tasks can only be archived via the archive button","error");return}try{const We=e.find(Bt=>Bt.id===Ke)?.steps.some(Bt=>Bt.status!=="pending")??!1,It=(Pe==="todo"||Pe==="triage")&&We;let Lt;if(It){if(await $({title:"Preserve Progress?",message:"This task has completed steps. Keep progress before moving?",confirmLabel:"Keep Progress",cancelLabel:"Reset Progress"}))Lt={preserveProgress:!0};else if(!await $({title:"Reset Progress?",message:"Reset all step progress before moving this task?",confirmLabel:"Reset Progress",cancelLabel:"Cancel Move",danger:!0}))return}await n(Ke,Pe,Lt)}catch(at){d(Se(at),"error")}}},[n,d,e,$]),hn=ve=>!E||E!==ve?t.jsx(Yg,{size:14,className:"sort-icon"}):K==="asc"?t.jsx(La,{size:14,className:"sort-icon active"}):t.jsx(Bo,{size:14,className:"sort-icon active"}),Zt=ve=>t.jsxs("div",{id:ve,className:"list-view-options-panel",children:[t.jsx("div",{className:"list-view-options-columns",children:vv.map(Pe=>{const Ke=k.has(Pe),at=Ke&&k.size===1;return t.jsxs("label",{className:`list-column-dropdown-item${at?" disabled":""}`,title:at?"At least one column must be visible":"",children:[t.jsx("input",{type:"checkbox",checked:Ke,onChange:()=>ce(Pe),disabled:at}),t.jsx("span",{children:Re[Pe]})]},Pe)})}),t.jsxs("button",{className:"btn btn-sm list-hide-done-toggle",onClick:()=>ke(Pe=>!Pe),"aria-pressed":le,title:le?"Show done tasks":"Hide done tasks",children:[le?t.jsx(Fr,{size:14}):t.jsx(zu,{size:14}),le?"Show Done":"Hide Done"]}),t.jsx("div",{className:"list-drop-zones list-drop-zones--sidebar",children:ha.map(Pe=>{const Ke=e.filter(Lt=>Lt.column===Pe).length,at=Pe==="done"||Pe==="archived",We=le&&at?0:Ke,It=le&&at&&Ke>0;return t.jsxs("div",{className:`list-drop-zone${H===Pe?" drag-over":""}${se===Pe?" active":""}`,onClick:()=>ct(Pe),onDragOver:Lt=>xn(Lt,Pe),onDragLeave:qt,onDrop:Lt=>Qt(Lt,Pe),"data-column":Pe,children:[t.jsx("span",{className:`list-section-dot dot-${Pe}`}),t.jsx("span",{className:"drop-zone-label",children:hs[Pe]}),t.jsx("span",{className:"drop-zone-count",children:It?`${We} of ${Ke}`:Ke})]},Pe)})})]});return t.jsxs("div",{className:"list-view",children:[D&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"list-toolbar",children:[t.jsx("button",{className:"btn btn-sm",onClick:Te,"aria-pressed":fe,children:fe?"Done Editing":"Bulk Edit"}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>ne(ve=>!ve),"aria-expanded":je,"aria-controls":"list-view-options-panel-mobile",children:[t.jsx(Tm,{size:14}),"View options"]}),m?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:m,children:"+ New Task"}):null,t.jsx("div",{className:"list-stats",children:se?`${Ee} of ${e.length} tasks in ${hs[se]}`:`${Ee} of ${e.length} tasks`})]}),je?t.jsx("div",{className:"list-toolbar-mobile-options",children:Zt("list-view-options-panel-mobile")}):null]}),t.jsx("div",{className:"list-table-container",children:t.jsxs("div",{className:D?"":"list-split-layout","data-testid":D?void 0:"list-split-layout",ref:ae,children:[t.jsxs("div",{className:D?"":"list-split-sidebar","data-testid":D?void 0:"list-split-sidebar",ref:Ve,style:D?void 0:{width:`${pe}px`},children:[!D&&t.jsxs("aside",{className:"list-sidebar-controls","aria-label":"List controls",children:[t.jsxs("div",{className:"list-sidebar-controls__header",children:[t.jsxs("p",{className:"list-stats",children:[se?`${Ee} of ${e.length} tasks in ${hs[se]}`:`${Ee} of ${e.length} tasks`,ht>0&&!se&&t.jsxs("span",{className:"list-stats-hidden",children:[" (",ht," hidden)"]})]}),t.jsxs("div",{className:"list-sidebar-controls__actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:Te,"aria-pressed":fe,children:fe?"Done Editing":"Bulk Edit"}),m?t.jsx("button",{className:"btn btn-task-create btn-sm list-new-task-action",onClick:m,children:"+ New Task"}):null]}),t.jsxs("div",{className:"list-sidebar-summary-chips",children:[se?t.jsx("button",{className:"btn btn-sm",onClick:ue,"aria-label":"Clear column filter",children:`Filter: ${hs[se]}`}):null,le?t.jsx("span",{className:"list-sidebar-chip",children:"Done hidden"}):null,fe?t.jsx("span",{className:"list-sidebar-chip",children:"Bulk edit"}):null,fe&&re.size>0?t.jsx("button",{className:"btn btn-sm",onClick:Be,children:`${re.size} selected`}):null]})]}),t.jsxs("button",{className:"btn btn-sm list-view-options-toggle",onClick:()=>ne(ve=>!ve),"aria-expanded":je,"aria-controls":"list-view-options-panel",children:[t.jsx(Tm,{size:14}),"View options"]}),je&&Zt("list-view-options-panel"),fe&&re.size>0?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"bulk-edit-toolbar",children:t.jsxs("button",{className:"btn btn-danger btn-sm",onClick:st,disabled:Ie,children:[t.jsx(Tn,{size:14}),"Delete selected"]})}),f&&f.length>0?t.jsxs("div",{className:"bulk-edit-toolbar",children:[t.jsx("span",{className:"bulk-edit-label",children:"Bulk Edit Models & Node:"}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(_s,{models:f,value:Ye,onChange:dt,label:"Executor Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:w,favoriteModels:g,onToggleModelFavorite:v})}),t.jsx("div",{className:"bulk-edit-dropdown",children:t.jsx(_s,{models:f,value:wt,onChange:St,label:"Reviewer Model",noChangeValue:"__no_change__",noChangeLabel:"No change",favoriteProviders:p,onToggleFavorite:w,favoriteModels:g,onToggleModelFavorite:v})}),t.jsxs("div",{className:"bulk-edit-dropdown bulk-edit-node-wrap",children:[t.jsxs("select",{className:"select bulk-node-select",value:Fe,onChange:ve=>J(ve.target.value),"aria-label":"Node Override",disabled:be,children:[t.jsx("option",{value:"__no_change__",children:"No change"}),t.jsx("option",{value:"",children:"Use project default"}),me.map(ve=>t.jsx("option",{value:ve.id,children:`${n$(ve.status)} ${ve.name||ve.id} (${t$(ve.status)})`},ve.id))]}),$t?t.jsx(Ua,{status:$t.status,showLabel:!0}):null]}),t.jsx("button",{className:"btn btn-primary btn-sm bulk-edit-apply-btn",onClick:yt,disabled:Ie||Ye==="__no_change__"&&wt==="__no_change__"&&Fe==="__no_change__",children:Ie?"Applying...":"Apply"})]}):null]}):null]}),t.jsx("div",{className:"list-quick-entry-above-table",children:t.jsx(Qb,{onCreate:h??(async()=>d("Task creation not available","error")),addToast:d,tasks:e,availableModels:f,onPlanningMode:b,onSubtaskBreakdown:y,projectId:j,autoExpand:!1,favoriteProviders:p,favoriteModels:g,onToggleFavorite:w,onToggleModelFavorite:v})}),Ee===0?t.jsx("div",{className:"list-empty",children:N?"No tasks match your filter":"No tasks yet"}):D?t.jsx("div",{className:"list-cards",children:ha.map(ve=>{if(se&&ve!==se||le&&(ve==="done"||ve==="archived")&&!se)return null;const Pe=oe[ve],Ke=Pe.length===0;if(N&&Ke)return null;const at=He.has(ve);return t.jsxs(i.Fragment,{children:[t.jsxs("div",{className:`list-card-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>Ue(ve),"aria-expanded":!at,role:"button",tabIndex:0,onKeyDown:We=>{(We.key==="Enter"||We.key===" ")&&(We.preventDefault(),Ue(ve))},children:[t.jsx(qn,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ve}`}),t.jsx("span",{className:"list-section-title",children:hs[ve]}),t.jsx("span",{className:"list-section-count",children:Pe.length})]}),!at&&t.jsx(t.Fragment,{children:Ke?t.jsx("div",{className:"list-empty-cell list-card-empty",children:"No tasks"}):Pe.map(We=>{const It=We.status==="failed",Lt=We.paused===!0,Bt=ec(We,x,R),Gt=!u&&!It&&!Lt&&!Bt&&(We.column==="in-progress"||rf.has(We.status)),bt=typeof We.status=="string"&&We.status.trim().length>0,Ot=!!(We.dependencies&&We.dependencies.length>0),en=pf(We),Kt=en.hasProgress,Sn=fe;return t.jsxs("div",{className:`list-card${Gt?" agent-active":""}${Sn?" list-card--selectable":""}`,onClick:()=>pt(We),"data-id":We.id,children:[Sn&&t.jsx("label",{className:"list-card-checkbox",onClick:dn=>dn.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:re.has(We.id),onChange:dn=>{dn.stopPropagation(),rt(We.id)},onClick:dn=>dn.stopPropagation(),disabled:We.column==="archived","aria-label":`Select ${We.id}`})}),t.jsxs("div",{className:"list-card-row",children:[t.jsx("span",{className:"list-card-id",children:We.id}),We.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(ls,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-card-spacer"}),Lt&&We.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Bt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):bt?t.jsx("span",{className:`list-status-badge list-status-badge--${We.column}${It?" failed":""}${Gt?" pulsing":""}`,children:of(We.status??"")}):null]}),t.jsx("div",{className:"list-card-row",children:t.jsx("div",{className:"list-card-title",children:We.title||We.description})}),(Ot||Kt)&&t.jsxs("div",{className:"list-card-row list-card-meta",children:[Ot&&t.jsxs("span",{className:"list-dep-badge",title:We.dependencies.join(", "),children:[t.jsx(Sr,{size:12})," ",We.dependencies.length]}),Kt&&t.jsxs("div",{className:"list-progress",children:[t.jsx("div",{className:"list-progress-bar",children:t.jsx("div",{className:"list-progress-fill",style:{width:`${en.percent}%`,backgroundColor:yl[We.column]}})}),t.jsx("span",{className:"list-progress-label",children:en.label})]})]})]},We.id)})})]},ve)})}):t.jsxs("table",{className:"list-table",children:[t.jsx("thead",{children:t.jsxs("tr",{children:[fe&&t.jsx("th",{className:"list-header-cell list-header-checkbox",children:t.jsx("input",{type:"checkbox",checked:xt,ref:ve=>{ve&&(ve.indeterminate=Me)},onChange:tt,"aria-label":"Select all visible tasks"})}),k.has("title")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Le("title"),children:["Title ",hn("title")]}),k.has("status")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Le("status"),children:["Status ",hn("status")]}),k.has("column")&&t.jsxs("th",{className:"list-header-cell",onClick:()=>Le("column"),children:["Column ",hn("column")]}),k.has("dependencies")&&t.jsx("th",{className:"list-header-cell",children:"Dependencies"}),k.has("progress")&&t.jsx("th",{className:"list-header-cell",children:"Progress"})]})}),t.jsx("tbody",{children:ha.map(ve=>{if(se&&ve!==se||le&&(ve==="done"||ve==="archived")&&!se)return null;const Pe=oe[ve],Ke=Pe.length===0;if(N&&Ke)return null;const at=He.has(ve);return t.jsxs(i.Fragment,{children:[t.jsx("tr",{className:`list-section-header${at?" list-section-header--collapsed":""}`,onClick:()=>Ue(ve),"aria-expanded":!at,children:t.jsxs("th",{colSpan:k.size+(fe?1:0),className:"list-section-cell",children:[t.jsx(qn,{size:14,className:`list-section-chevron${at?"":" list-section-chevron--expanded"}`}),t.jsx("span",{className:`list-section-dot dot-${ve}`}),t.jsx("span",{className:"list-section-title",children:hs[ve]}),t.jsx("span",{className:"list-section-count",children:Pe.length})]})}),!at&&t.jsx(t.Fragment,{children:Ke?t.jsx("tr",{className:"list-section-empty",children:t.jsx("td",{colSpan:k.size+(fe?1:0),className:"list-empty-cell",children:"No tasks"})}):Pe.map(We=>{const It=We.status==="failed",Lt=We.paused===!0,Bt=ec(We,x,R),Gt=!u&&!It&&!Lt&&!Bt&&(We.column==="in-progress"||rf.has(We.status)),bt=A===We.id;return t.jsxs("tr",{className:`list-row${It?" failed":""}${Lt?" paused":""}${Bt?" stuck":""}${Gt?" agent-active":""}${bt?" dragging":""}${L===We.id?" list-row--selected":""}`,onClick:()=>pt(We),draggable:!Lt,onDragStart:Ot=>nn(Ot,We),onDragEnd:on,"data-id":We.id,children:[fe&&t.jsx("td",{className:"list-cell list-cell-checkbox",children:t.jsx("input",{type:"checkbox",checked:re.has(We.id),onChange:Ot=>{Ot.stopPropagation(),rt(We.id)},onClick:Ot=>Ot.stopPropagation(),disabled:We.column==="archived","aria-label":`Select ${We.id}`})}),k.has("title")&&t.jsx("td",{className:"list-cell list-cell-title",children:t.jsxs("div",{className:"list-title-content",children:[t.jsx("span",{className:"list-title-id",children:We.id}),t.jsxs("div",{className:"list-title-row",children:[We.executionMode==="fast"&&t.jsxs("span",{className:"list-execution-mode-badge list-execution-mode-badge--fast",title:"Fast mode","aria-label":"Fast mode",children:[t.jsx(ls,{"aria-hidden":"true"}),t.jsx("span",{className:"visually-hidden",children:"Fast mode"})]}),t.jsx("span",{className:"list-title-text",children:We.title||We.description})]})]})}),k.has("status")&&t.jsx("td",{className:"list-cell",children:Lt&&We.pausedByAgentId?t.jsx("span",{className:"list-status-badge paused",children:"paused by agent"}):Bt?t.jsx("span",{className:"list-status-badge stuck",children:"Stuck"}):We.status?t.jsx("span",{className:`list-status-badge list-status-badge--${We.column}${It?" failed":""}${Gt?" pulsing":""}`,children:of(We.status??"")}):t.jsx("span",{className:"list-status-badge",children:"-"})}),k.has("column")&&t.jsx("td",{className:"list-cell",children:t.jsx("span",{className:"list-column-badge",style:{background:`${yl[We.column]}20`,color:yl[We.column]},children:hs[We.column]})}),k.has("dependencies")&&t.jsx("td",{className:"list-cell list-cell-deps",children:We.dependencies&&We.dependencies.length>0?t.jsxs("span",{className:"list-dep-badge",title:We.dependencies.join(", "),children:[t.jsx(Sr,{size:12})," ",We.dependencies.length]}):"-"}),k.has("progress")&&t.jsx("td",{className:"list-cell list-cell-progress",children:(()=>{const Ot=pf(We);return Ot.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:`${Ot.percent}%`,backgroundColor:yl[We.column]}})}),t.jsx("span",{className:"list-progress-label",children:Ot.label})]}):"-"})()})]},We.id)})})]},ve)})})]})]}),!D&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"list-split-resize-handle","data-testid":"list-split-resize-handle",onMouseDown:sn,onKeyDown:ln,role:"separator",tabIndex:0,"aria-orientation":"vertical","aria-label":"Resize task list sidebar","aria-valuemin":ac,"aria-valuemax":Math.round(Mu(ae.current?.clientWidth??pe/_u+wl)),"aria-valuenow":Math.round(pe)}),t.jsx("div",{className:"list-split-detail","data-testid":"list-split-detail",children:he?t.jsx("div",{className:"list-split-detail-content","data-testid":"list-split-detail-content",children:t.jsx(xv,{task:he,projectId:j,tasks:e,embedded:!0,onOpenDetail:Dt,onMoveTask:n,onDeleteTask:a,onMergeTask:r,onRetryTask:s,onResetTask:o,onDuplicateTask:l,onTaskUpdated:ve=>{B(Pe=>!Pe||Pe.id!==ve.id?Pe:{...Pe,...ve})},addToast:d,prAuthAvailable:F})}):t.jsx("div",{className:"list-split-detail-empty",children:t.jsx("p",{children:"Select a task to view details"})})})]})]})})]})}const a$={active:{label:"Active",color:"var(--color-success)",icon:os},paused:{label:"Paused",color:"var(--color-warning)",icon:Ci},errored:{label:"Error",color:"var(--color-error)",icon:Vs},initializing:{label:"Initializing",color:"var(--color-warning)",icon:jt}};function r$(e){if(!e)return"Never";const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString()}function ff(e,n=40){if(e.length<=n)return e;const s=e.slice(0,Math.floor(n/2)-2),a=e.slice(-Math.floor(n/2)+2);return`${s}...${a}`}function o$(e,n){if(e.project.id!==n.project.id||e.project.status!==n.project.status||e.project.name!==n.project.name||e.project.path!==n.project.path||e.project.lastActivityAt!==n.project.lastActivityAt||e.isLoading!==n.isLoading)return!1;const s=e.health,a=n.health;if(!s&&!a)return!0;if(!s||!a||s.activeTaskCount!==a.activeTaskCount||s.inFlightAgentCount!==a.inFlightAgentCount||s.totalTasksCompleted!==a.totalTasksCompleted||s.totalTasksFailed!==a.totalTasksFailed||s.status!==a.status)return!1;const r=e.availabilityMappings??[],o=n.availabilityMappings??[];return r.length!==o.length?!1:r.every((l,c)=>{const d=o[c];return!!d&&l.nodeId===d.nodeId&&l.path===d.path&&l.displayName===d.displayName&&l.available===d.available})}function l$({project:e,health:n,onSelect:s,onPause:a,onResume:r,onRemove:o,availabilityMappings:l=[],isLoading:c=!1}){const[d,u]=i.useState(!1),m=a$[e.status],h=m.icon,f=i.useCallback(()=>{s(e)},[s,e]),p=i.useCallback(S=>{S.stopPropagation(),a(e)},[a,e]),g=i.useCallback(S=>{S.stopPropagation(),r(e)},[r,e]),w=i.useCallback(S=>{if(S.stopPropagation(),!d){u(!0);return}o(e),u(!1)},[d,o,e]),v=e.status==="paused",b=e.status==="errored",y=e.status==="initializing";return t.jsxs("div",{className:`project-card ${c?"project-card-loading":""} ${b?"project-card-errored":""}`,onClick:f,"data-project-id":e.id,role:"button",tabIndex:0,onKeyDown:S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),f())},children:[t.jsxs("div",{className:"project-card-header",children:[t.jsx("div",{className:"project-card-icon",children:t.jsx(js,{size:20})}),t.jsxs("div",{className:"project-card-title-section",children:[t.jsx("h3",{className:"project-card-name",title:e.name,children:e.name}),l.length>0&&t.jsxs("div",{className:"project-card-availability","aria-label":"Project node availability",children:[l.slice(0,3).map(S=>t.jsxs("div",{className:"project-card-availability__row",title:`${S.displayName} → ${S.path}`,children:[t.jsx("span",{className:"project-card-availability__node",children:S.displayName}),t.jsx("span",{className:"project-card-availability__arrow",children:"→"}),t.jsx("code",{className:"project-card-availability__path",children:ff(S.path,28)})]},`${S.nodeId}-${S.path}`)),l.length>3&&t.jsxs("span",{className:"project-card-availability__more",children:["+",l.length-3," more"]})]}),t.jsx("span",{className:"project-card-path",title:e.path,children:ff(e.path)})]}),t.jsxs("div",{className:"project-card-status-badge",style:{color:m.color,borderColor:m.color},children:[t.jsx(h,{size:12,className:y?"animate-spin":""}),t.jsx("span",{children:m.label})]})]}),t.jsxs("div",{className:"project-card-health",children:[n&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.activeTaskCount}),t.jsx("span",{className:"project-card-metric-label",children:"Active Tasks"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.inFlightAgentCount}),t.jsx("span",{className:"project-card-metric-label",children:"Agents"})]}),t.jsxs("div",{className:"project-card-metric",children:[t.jsx("span",{className:"project-card-metric-value",children:n.totalTasksCompleted}),t.jsx("span",{className:"project-card-metric-label",children:"Completed"})]})]}),!n&&t.jsx("div",{className:"project-card-metric project-card-metric-empty",children:t.jsx("span",{className:"project-card-metric-label",children:"No health data available"})})]}),t.jsxs("div",{className:"project-card-footer",children:[t.jsxs("div",{className:"project-card-activity",children:[t.jsx("span",{className:"project-card-activity-label",children:"Last activity:"}),t.jsx("span",{className:"project-card-activity-time",children:r$(e.lastActivityAt||n?.lastActivityAt)})]}),t.jsxs("div",{className:"project-card-actions",children:[v?t.jsxs("button",{className:"project-card-action project-card-action-resume",onClick:g,disabled:c,title:"Resume project","aria-label":"Resume project",children:[t.jsx(os,{size:14}),t.jsx("span",{children:"Resume"})]}):t.jsxs("button",{className:"project-card-action project-card-action-pause",onClick:p,disabled:c||y,title:y?"Cannot pause while initializing":"Pause project","aria-label":"Pause project",children:[t.jsx(Ci,{size:14}),t.jsx("span",{children:"Pause"})]}),t.jsxs("button",{className:"project-card-action project-card-action-open",onClick:f,disabled:c,title:"Open project","aria-label":"Open project",children:[t.jsx(Uo,{size:14}),t.jsx("span",{children:"Open"})]}),t.jsxs("button",{className:`project-card-action project-card-action-remove ${d?"is-armed":""}`,onClick:w,disabled:c,title:d?"Confirm remove":"Remove project","aria-label":d?"Confirm remove project":"Remove project",children:[t.jsx(Tn,{size:14}),t.jsx("span",{children:d?"Confirm":""})]})]})]})]})}const c$=i.memo(l$,o$);function gf(e){return typeof e=="string"&&e.trim().length>0}function ko(e){return(e.nodeMappings??[]).filter(s=>gf(s.nodeId)&&gf(s.path)).map(s=>({nodeId:s.nodeId,nodeName:s.nodeName,path:s.path,available:s.available!==!1}))}function d$(e,n){return ko(e).filter(s=>s.nodeId===n.id&&s.available)}function u$(e,n){return d$(e,n).length>0}function m$(e,n){return e.filter(s=>u$(s,n))}function P8(e,n){return m$(e,n).length}function bf(e,n,s,a){const r=s.find(o=>o.id===e);return r?.name?r.name:n?.nodeName?n.nodeName:a._sourceNodeName?a._sourceNodeName:e}function h$(){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(js,{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(Js,{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(Xn,{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(Vs,{size:20,className:"project-skeleton-icon"})}),t.jsx("div",{className:"project-skeleton project-skeleton--value"}),t.jsx("div",{className:"project-skeleton project-skeleton--label"})]})]})}),t.jsxs("div",{className:"project-overview__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 p$=1e4,xf=5;function f$(e){const[n,s]=i.useState({}),[a,r]=i.useState(!0),[o,l]=i.useState(null),c=i.useRef(null),d=i.useRef(null),u=i.useRef(!1),m=i.useCallback(async()=>{if(e.length===0){s({}),u.current||(u.current=!0),r(!1);return}d.current&&d.current.abort(),d.current=new AbortController,!u.current&&r(!0),l(null);try{const p={};for(let g=0;g<e.length;g+=xf){const w=e.slice(g,g+xf),v=await Promise.allSettled(w.map(async b=>{try{return await rh(b)}catch{return null}}));if(w.forEach((b,y)=>{const S=v[y];p[b]=S.status==="fulfilled"?S.value:null}),d.current?.signal.aborted)return}s(p),u.current=!0}catch(p){if(p instanceof Error&&p.name==="AbortError")return;l(p instanceof Error?p.message:"Failed to fetch health data"),u.current=!0}finally{r(!1)}},[e]),h=i.useCallback(async f=>{try{const p=await rh(f);s(g=>({...g,[f]:p}))}catch(p){console.error(`Failed to fetch health for project ${f}:`,p)}},[]);return i.useEffect(()=>(u.current=!1,m(),()=>{d.current&&d.current.abort()}),[m]),i.useEffect(()=>{if(e.length!==0)return c.current&&clearInterval(c.current),c.current=setInterval(()=>{m()},p$),()=>{c.current&&(clearInterval(c.current),c.current=null)}},[m,e.length]),{healthMap:n,loading:a,error:o,refresh:m,refreshProject:h}}function g$({projects:e,loading:n=!1,onSelectProject:s,onAddProject:a,onPauseProject:r,onResumeProject:o,onRemoveProject:l,nodes:c=[]}){const[d,u]=i.useState("all"),[m,h]=i.useState(null),[f,p]=i.useState("activity"),[g,w]=i.useState("desc");i.useEffect(()=>{if(typeof window>"u")return;const U=localStorage.getItem("kb-dashboard-recent-projects");if(U)try{const A=JSON.parse(U);b(A)}catch{}},[]);const[v,b]=i.useState([]),y=i.useMemo(()=>e.map(U=>U.id),[e]),{healthMap:S,loading:j}=f$(y),C=i.useMemo(()=>e.map(U=>({project:U,health:S[U.id]||null})),[e,S]),x=i.useMemo(()=>{let U=[...C];return d!=="all"&&(U=U.filter(({project:A})=>A.status===d)),m!==null&&(U=U.filter(({project:A})=>ko(A).some(T=>T.available&&T.nodeId===m))),U},[C,d,m]),N=i.useMemo(()=>{const U=[...x];return U.sort((A,T)=>{let H=0;switch(f){case"name":H=A.project.name.localeCompare(T.project.name);break;case"activity":{const Q=A.project.lastActivityAt||A.health?.lastActivityAt||A.project.updatedAt,se=T.project.lastActivityAt||T.health?.lastActivityAt||T.project.updatedAt;H=new Date(se).getTime()-new Date(Q).getTime();break}case"status":{const Q={errored:0,initializing:1,paused:2,active:3};H=Q[A.project.status]-Q[T.project.status];break}}return g==="asc"?H:-H}),U},[x,f,g]),R=i.useMemo(()=>{const U=e.length,A=e.filter(D=>D.status==="active").length,T=e.filter(D=>D.status==="errored").length,H=new Set;e.forEach(D=>{ko(D).forEach($=>{$.available&&H.add($.nodeId)})});const Q=H.size;let se=0,O=0,M=0;return Object.values(S).forEach(D=>{D&&(se+=D.activeTaskCount,O+=D.totalTasksCompleted,M+=D.inFlightAgentCount)}),{totalProjects:U,activeProjects:A,erroredProjects:T,totalNodes:Q,totalActiveTasks:se,totalCompletedTasks:O,totalInFlightAgents:M}},[e,S]),F=i.useMemo(()=>({all:e.length,active:e.filter(U=>U.status==="active").length,paused:e.filter(U=>U.status==="paused").length,errored:e.filter(U=>U.status==="errored").length}),[e]),E=i.useMemo(()=>{const U=new Map;return e.forEach(A=>{ko(A).filter(T=>T.available).forEach(T=>{const H=T.nodeId,Q=U.get(H),se=bf(H,T,c,A);Q?Q.count+=1:U.set(H,{name:se,count:1})})}),Array.from(U.entries()).map(([A,{name:T,count:H}])=>({nodeId:A,name:T,count:H}))},[e,c]),_=i.useCallback(U=>{const A=[U.id,...v.filter(T=>T!==U.id)].slice(0,3);b(A),typeof window<"u"&&localStorage.setItem("kb-dashboard-recent-projects",JSON.stringify(A)),s(U)},[s,v]);return n||j&&e.length>0&&Object.keys(S).length===0?t.jsx(h$,{}):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(ma,{size:48})}),t.jsx("h2",{className:"project-empty-state__title",children:"No Projects Found"}),t.jsx("p",{className:"project-empty-state__description",children:"Get started by adding your first project. Projects allow you to organize and track tasks across multiple repositories."}),t.jsxs("button",{className:"btn btn-primary project-empty-state__cta",onClick:a,children:[t.jsx($n,{size:16}),"Add Your First Project"]})]})}):t.jsxs("div",{className:"project-overview",children:[t.jsxs("div",{className:"project-overview__header",children:[t.jsxs("h2",{className:"project-overview__title",children:[t.jsx(va,{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(js,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalProjects}),t.jsx("span",{className:"project-stat__label",children:"Total"})]})]}),t.jsxs("div",{className:"project-stat project-stat--active",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Js,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalActiveTasks}),t.jsx("span",{className:"project-stat__label",children:"Active Tasks"})]})]}),t.jsxs("div",{className:"project-stat project-stat--completed",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Xn,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalCompletedTasks}),t.jsx("span",{className:"project-stat__label",children:"Completed"})]})]}),R.erroredProjects>0&&t.jsxs("div",{className:"project-stat project-stat--error",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(Vs,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.erroredProjects}),t.jsx("span",{className:"project-stat__label",children:"Errored"})]})]}),R.totalNodes>1&&t.jsxs("div",{className:"project-stat project-stat--nodes",children:[t.jsx("div",{className:"project-stat__icon",children:t.jsx(To,{size:16})}),t.jsxs("div",{className:"project-stat__content",children:[t.jsx("span",{className:"project-stat__value",children:R.totalNodes}),t.jsx("span",{className:"project-stat__label",children:"Nodes"})]})]})]}),t.jsxs("button",{className:"btn btn-primary project-overview__add-btn",onClick:a,children:[t.jsx($n,{size:16}),"Add Project"]})]}),t.jsxs("div",{className:"project-overview__filters",children:[t.jsxs("div",{className:"project-filter-tabs",children:[t.jsxs("button",{className:`project-filter-tab ${d==="all"?"active":""}`,onClick:()=>u("all"),children:["All",t.jsx("span",{className:"project-filter-count",children:F.all})]}),t.jsxs("button",{className:`project-filter-tab ${d==="active"?"active":""}`,onClick:()=>u("active"),children:["Active",t.jsx("span",{className:"project-filter-count",children:F.active})]}),t.jsxs("button",{className:`project-filter-tab ${d==="paused"?"active":""}`,onClick:()=>u("paused"),children:["Paused",t.jsx("span",{className:"project-filter-count",children:F.paused})]}),t.jsxs("button",{className:`project-filter-tab ${d==="errored"?"active":""} ${F.errored>0?"has-errors":""}`,onClick:()=>u("errored"),children:["Errored",t.jsx("span",{className:"project-filter-count",children:F.errored})]})]}),E.length>1&&t.jsxs("div",{className:"project-node-filter",children:[t.jsx(To,{size:14}),t.jsxs("select",{value:m??"",onChange:U=>{h(U.target.value||null)},className:"project-node-filter-select","aria-label":"Filter by node",children:[t.jsx("option",{value:"",children:"All Nodes"}),E.map(({nodeId:U,name:A,count:T})=>t.jsxs("option",{value:U??"",children:[A," (",T,")"]},U??"local"))]})]}),t.jsxs("div",{className:"project-sort",children:[t.jsx(ql,{size:14}),t.jsxs("select",{value:`${f}-${g}`,onChange:U=>{const[A,T]=U.target.value.split("-");p(A),w(T)},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(Yg,{size:14})]})]}),t.jsx("div",{className:"project-grid",children:N.map(({project:U,health:A})=>{const T=ko(U).filter(H=>H.available).map(H=>({...H,displayName:bf(H.nodeId,H,c,U)}));return t.jsx(c$,{project:U,health:A,availabilityMappings:T,onSelect:_,onPause:r,onResume:o,onRemove:l},U.id)})}),N.length===0&&t.jsxs("div",{className:"project-overview__no-results",children:[t.jsx(ql,{size:32}),t.jsx("p",{children:"No projects match the current filter"}),t.jsx("button",{className:"btn btn-secondary",onClick:()=>u("all"),children:"Show All Projects"})]})]})}const yv=i.createContext(null);function b$({value:e,children:n}){return i.createElement(yv.Provider,{value:e},n)}function wv(){const e=i.useContext(yv);if(!e)throw new Error("useNavigationHistoryContext must be used within a NavigationHistoryProvider");return e}function x$(e){const{enabled:n}=e,s=i.useRef([]),a=i.useRef(!1),r=i.useRef(n);r.current=n;const o=i.useCallback(c=>{if(!r.current||a.current)return;const d=s.current[s.current.length-1];if(d){const h=d.type==="modal"?d.close:d.revert,f=c.type==="modal"?c.close:c.revert;if(h===f)return}s.current.push(c);const u=s.current.length,m=typeof window<"u"&&window.history.state?window.history.state:{};window.history.pushState({...m,navIndex:u},"")},[]),l=i.useCallback(c=>{if(!r.current||s.current.length===0)return;s.current[s.current.length-1]=c;const d=s.current.length,u=typeof window<"u"&&window.history.state?window.history.state:{};window.history.replaceState({...u,navIndex:d},"")},[]);return i.useEffect(()=>{if(typeof window>"u")return;const c=d=>{if(!r.current)return;const u=d.state?.navIndex??0,m=s.current.length;if(u>=m)return;const h=m-u;if(!(h<=0)){a.current=!0;try{for(let f=0;f<h;f++){const p=s.current.pop();p&&(p.type==="modal"?p.close():p.revert())}}finally{a.current=!1}}};return window.addEventListener("popstate",c),()=>{window.removeEventListener("popstate",c)}},[]),{pushNav:o,replaceCurrent:l}}const jm="kb-planning-last-description",Nm="kb-subtask-last-description",Sm="kb-mission-last-goal";function v$(e,n){fs(jm,e,n)}function y$(e){return Gn(jm,e)||""}function hr(e){Ar(jm,e)}function w$(e,n){fs(Nm,e,n)}function k$(e){return Gn(Nm,e)||""}function Id(e){Ar(Nm,e)}function j$(e,n){fs(Sm,e,n)}function N$(e){return Gn(Sm,e)||""}function da(e){Ar(Sm,e)}function S$(e){const{question:n,response:s}=e;if(!n)return s;if(s&&typeof s=="object"&&!Array.isArray(s)){const a=s;if(n.id in a)return a[n.id]}return s}function C$(e,n){switch(e.type){case"text":return typeof n=="string"?n:n==null?"":String(n);case"single_select":return typeof n=="string"?e.options?.find(a=>a.id===n)?.label??n:n==null?"":String(n);case"multi_select":return Array.isArray(n)?n.map(s=>typeof s!="string"?String(s):e.options?.find(r=>r.id===s)?.label??s).join(", "):n==null?"":String(n);case"confirm":return n===!0?"Yes":n===!1?"No":n==null?"":String(n);default:return n==null?"":JSON.stringify(n)}}function E$(e){let n=0;const s=[];for(const a of e){if(a.question){n+=1,s.push({...a,questionNumber:n});continue}a.thinkingOutput&&s.push({...a,questionNumber:null})}return s}function bi({entries:e,defaultShowThinking:n=!1}){const[s,a]=i.useState({}),r=E$(e);return r.length===0?null:t.jsx("div",{className:"conversation-history","data-testid":"conversation-history",children:r.map((o,l)=>{const c=!!o.question,d=!!o.thinkingOutput,u=s[l]??n,m=c?S$(o):void 0,h=o.question&&m!==void 0?C$(o.question,m):"",f=o.response&&typeof o.response=="object"&&!Array.isArray(o.response)?o.response:void 0,p=typeof f?._comment=="string"?f._comment.trim():"";return t.jsxs("div",{className:"conversation-entry",children:[c?t.jsxs("div",{className:"conversation-entry-question",children:[t.jsxs("span",{className:"conversation-entry-question-label",children:["Q",o.questionNumber]}),t.jsx("p",{children:o.question?.question})]}):t.jsx("div",{className:"conversation-entry-question",children:t.jsx("span",{className:"conversation-entry-question-label",children:"AI Reasoning"})}),c&&t.jsxs("div",{className:"conversation-entry-response",children:[t.jsx("strong",{children:"Your response"}),t.jsx("p",{children:h||"—"}),p&&t.jsxs("p",{className:"conversation-comment",children:["💬 ",p]})]}),d&&t.jsxs("div",{className:"conversation-entry-thinking",children:[t.jsxs("button",{type:"button",className:"conversation-thinking-toggle",onClick:()=>{a(g=>({...g,[l]:!u}))},"aria-expanded":u,children:[t.jsx("span",{"aria-hidden":"true",children:u?"▾":"▸"}),u?`Hide ${c?"AI thinking":"AI reasoning"}`:`Show ${c?"AI thinking":"AI reasoning"}`]}),u&&t.jsx("pre",{children:o.thinkingOutput})]})]},`${o.question?.id??"thinking"}-${l}`)})})}const vf="fusion-tab-id";function _$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Ja(){if(typeof window>"u")return"server-tab";const e=window.sessionStorage.getItem(vf);if(e)return e;const n=_$();return window.sessionStorage.setItem(vf,n),n}function Tc(e){const n=i.useMemo(()=>Ja(),[]),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(!1);i.useEffect(()=>{if(!e){a(!1),o(null),c(!1);return}let u=!0;return c(!0),Promise.resolve(S0(e,n)).then(m=>{if(u){if(m.acquired){a(!1),o(null);return}a(!0),o(m.currentHolder)}}).catch(()=>{u&&(a(!1),o(null))}).finally(()=>{u&&c(!1)}),()=>{u=!1;try{const m=C0(e,n);m&&typeof m.catch=="function"&&m.catch(()=>{})}catch{}}},[e,n]),i.useEffect(()=>{if(!e||typeof window>"u")return;const u=()=>{if(typeof navigator.sendBeacon!="function")return;const m=Fi(`/api/ai-sessions/${encodeURIComponent(e)}/lock/beacon?tabId=${encodeURIComponent(n)}`);navigator.sendBeacon(m)};return window.addEventListener("beforeunload",u),()=>{window.removeEventListener("beforeunload",u)}},[e,n]),i.useEffect(()=>!e||typeof EventSource>"u"?void 0:yi("/api/events",{events:{"ai_session:updated":m=>{try{const h=JSON.parse(m.data);if(h.id!==e)return;const f=h.lockedByTab??null;o(f),a(!!(f&&f!==n))}catch{}}}}),[e,n]);const d=i.useCallback(async()=>{if(e){c(!0);try{await Promise.resolve(E0(e,n)),a(!1),o(null)}finally{c(!1)}}},[e,n]);return{isLockedByOther:s,currentHolder:r,takeControl:d,isLoading:l}}const M$="fusion:ai-session-sync",yf="fusion:ai-session-sync",A$=3e4,R$=6e4;function Ii(){return Date.now()}function I$(){const e=globalThis.crypto;return e&&typeof e.randomUUID=="function"?e.randomUUID():`tab-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function wf(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 T${tabId;listeners=new Set;sessionStates=new Map;ownershipBySession=new Map;heartbeatByTab=new Map;ownedSessions=new Map;snapshot;channel=null;usingStorageFallback=!1;cleanupStorageListener=null;cleanupBeforeUnload=null;heartbeatInterval=null;staleSweepInterval=null;constructor(){this.tabId=I$(),this.snapshot={tabId:this.tabId,sessions:new Map,activeTabMap:new Map},this.isBrowser()&&(this.initializeTransport(),this.startHeartbeat(),this.startStaleSweep(),this.setupBeforeUnloadCleanup())}subscribe(n){return this.listeners.add(n),()=>{this.listeners.delete(n)}}getSnapshot(){return this.snapshot}requestSync(){this.publish({type:"sync:request",tabId:this.tabId,timestamp:Ii()})}broadcastUpdate(n){const s=n.timestamp??Ii();this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",owningTabId:n.owningTabId,type:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},s),this.publish({type:"session:updated",sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,sessionType:n.type,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt,timestamp:s})}broadcastCompleted(n){const s=n.status??"complete",a=n.timestamp??Ii();this.applySessionUpdate({sessionId:n.sessionId,status:s,needsInput:!1,owningTabId:null},a),this.ownershipBySession.delete(n.sessionId),this.ownedSessions.delete(n.sessionId),this.emit(),this.publish({type:"session:completed",sessionId:n.sessionId,status:s,timestamp:a})}broadcastLock(n,s){const a=Ii();this.applyTabOwnership(n,s,a),this.ownedSessions.set(n,s),this.publish({type:"tab:active",tabId:s,sessionId:n,timestamp:a})}broadcastUnlock(n,s){const a=Ii();this.releaseTabOwnership(n,s,a),this.ownedSessions.delete(n),this.publish({type:"tab:inactive",tabId:s,sessionId:n,timestamp:a})}broadcastHeartbeat(n){const s=Ii();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(M$),this.channel.onmessage=s=>{const a=wf(s.data);a&&this.handleIncomingMessage(a)},this.usingStorageFallback=!1;return}catch{}this.usingStorageFallback=!0;const n=s=>{if(!(s.key!==yf||!s.newValue))try{const a=JSON.parse(s.newValue),r=wf(a.message);r&&this.handleIncomingMessage(r)}catch{}};window.addEventListener("storage",n),this.cleanupStorageListener=()=>{window.removeEventListener("storage",n)}}startHeartbeat(){this.heartbeatInterval=setInterval(()=>{const n=Ii();this.updateHeartbeat(this.tabId,n),this.publish({type:"tab:heartbeat",tabId:this.tabId,timestamp:n})},A$)}startStaleSweep(){this.staleSweepInterval=setInterval(()=>{this.emit()},1e4)}setupBeforeUnloadCleanup(){const n=()=>{for(const[s,a]of this.ownedSessions.entries()){const r=Ii();this.publish({type:"tab:inactive",tabId:a,sessionId:s,timestamp:r})}};window.addEventListener("beforeunload",n),this.cleanupBeforeUnload=()=>{window.removeEventListener("beforeunload",n)}}publish(n){const s={...n,senderTabId:this.tabId};if(this.channel){this.channel.postMessage(s);return}if(this.usingStorageFallback)try{const a={id:`${s.type}-${s.timestamp}-${Math.random().toString(36).slice(2,8)}`,message:s};window.localStorage.setItem(yf,JSON.stringify(a))}catch{}}handleIncomingMessage(n){switch(n.type){case"session:updated":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status,needsInput:n.needsInput,owningTabId:n.owningTabId,type:n.sessionType,title:n.title,projectId:n.projectId,updatedAt:n.updatedAt},n.timestamp);return}case"session:completed":{this.applySessionUpdate({sessionId:n.sessionId,status:n.status??"complete",needsInput:!1,owningTabId:null},n.timestamp),this.ownershipBySession.delete(n.sessionId),this.emit();return}case"tab:active":{this.applyTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:inactive":{this.releaseTabOwnership(n.sessionId,n.tabId,n.timestamp);return}case"tab:heartbeat":{this.updateHeartbeat(n.tabId,n.timestamp);return}case"sync:request":{if(n.tabId===this.tabId)return;const s=[...this.sessionStates.values()].map(o=>{const l=this.ownershipBySession.get(o.sessionId);return{...o,owningTabId:l?.tabId??o.owningTabId??null}}),a=[...this.ownershipBySession.entries()].map(([o,l])=>({sessionId:o,tabId:l.tabId,timestamp:l.timestamp})),r=[...this.heartbeatByTab.entries()].map(([o,l])=>({tabId:o,timestamp:l}));this.publish({type:"sync:response",tabId:n.tabId,sessions:s,locks:a,heartbeats:r,timestamp:Ii()});return}case"sync:response":{if(n.tabId!==this.tabId)return;for(const s of n.sessions)this.applySessionUpdate({sessionId:s.sessionId,status:s.status,needsInput:s.needsInput,owningTabId:s.owningTabId,type:s.type,title:s.title,projectId:s.projectId,updatedAt:s.updatedAt},s.lastEventTimestamp,!1);for(const s of n.locks??[])this.applyTabOwnership(s.sessionId,s.tabId,s.timestamp,!1);for(const s of n.heartbeats??[])this.updateHeartbeat(s.tabId,s.timestamp,!1);this.emit();return}default:return}}applySessionUpdate(n,s,a=!0){const r=this.sessionStates.get(n.sessionId);if(r&&s<r.lastEventTimestamp)return;const o=this.ownershipBySession.get(n.sessionId),l={sessionId:n.sessionId,status:n.status,needsInput:n.needsInput??n.status==="awaiting_input",lastEventTimestamp:s,owningTabId:n.owningTabId??o?.tabId??r?.owningTabId??null,type:n.type??r?.type,title:n.title??r?.title,projectId:n.projectId??r?.projectId,updatedAt:n.updatedAt??new Date(s).toISOString()};this.sessionStates.set(n.sessionId,l),n.owningTabId!==void 0&&(n.owningTabId?this.applyTabOwnership(n.sessionId,n.owningTabId,s,!1):this.ownershipBySession.delete(n.sessionId)),a&&this.emit()}applyTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(o&&a<o.timestamp)return;this.ownershipBySession.set(n,{tabId:s,timestamp:a}),this.updateHeartbeat(s,a,!1);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:s,lastEventTimestamp:a}),r&&this.emit()}releaseTabOwnership(n,s,a,r=!0){const o=this.ownershipBySession.get(n);if(!o||o.tabId!==s||a<o.timestamp)return;this.ownershipBySession.delete(n);const l=this.sessionStates.get(n);l&&a>=l.lastEventTimestamp&&this.sessionStates.set(n,{...l,owningTabId:null,lastEventTimestamp:a}),r&&this.emit()}updateHeartbeat(n,s,a=!0){const r=this.heartbeatByTab.get(n);r!==void 0&&s<r||(this.heartbeatByTab.set(n,s),a&&this.emit())}emit(){const n=Ii(),s=new Map;for(const[r,o]of this.sessionStates.entries()){const l=this.ownershipBySession.get(r);s.set(r,{...o,owningTabId:l?.tabId??o.owningTabId??null})}const a=new Map;for(const[r,o]of this.ownershipBySession.entries()){const l=this.heartbeatByTab.get(o.tabId)??o.timestamp,c=n-l>R$;a.set(r,{sessionId:r,tabId:o.tabId,lastHeartbeatTimestamp:l,lastLockTimestamp:o.timestamp,stale:c})}this.snapshot={tabId:this.tabId,sessions:s,activeTabMap:a};for(const r of this.listeners)r()}}const Ti=new T$;function Wr(){const e=i.useSyncExternalStore(c=>Ti.subscribe(c),()=>Ti.getSnapshot(),()=>Ti.getSnapshot());i.useEffect(()=>{Ti.requestSync()},[]);const n=i.useCallback(c=>{Ti.broadcastUpdate(c)},[]),s=i.useCallback(c=>{Ti.broadcastCompleted(c)},[]),a=i.useCallback((c,d)=>{Ti.broadcastLock(c,d)},[]),r=i.useCallback((c,d)=>{Ti.broadcastUnlock(c,d)},[]),o=i.useCallback(c=>{Ti.broadcastHeartbeat(c)},[]),l=i.useCallback(()=>{Ti.requestSync()},[]);return{tabId:e.tabId,sessions:e.sessions,activeTabMap:e.activeTabMap,broadcastUpdate:n,broadcastCompleted:s,broadcastLock:a,broadcastUnlock:r,broadcastHeartbeat:o,requestSync:l}}function P$(e,n){return e&&n?`${e}/${n}`:""}function $$(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 D$=["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 L$({isOpen:e,onClose:n,onMissionCreated:s,projectId:a,initialGoal:r,resumeSessionId:o}){Mi(e);const[l,c]=i.useState(""),[d,u]=i.useState({type:"initial"}),[m,h]=i.useState(null),[f,p]=i.useState([]),[g,w]=i.useState([]),[v,b]=i.useState(null),[y,S]=i.useState(!1),j=i.useRef(!1),[C,x]=i.useState(""),[N,R]=i.useState(!0),[F,E]=i.useState(!1),[_,K]=i.useState(!1),[U,A]=i.useState(!1),T=i.useRef(null),H=i.useRef(null),Q=i.useRef(null),se=i.useRef(null),[O,M]=i.useState(o??null),D=i.useMemo(()=>Ja(),[]),{isLockedByOther:$,takeControl:k,isLoading:X}=Tc(e?O:null),{activeTabMap:le,broadcastUpdate:ke,broadcastCompleted:He,broadcastLock:ye,broadcastUnlock:je,broadcastHeartbeat:ne}=Wr(),{confirm:fe}=li(),[Z,re]=i.useState(void 0),[q,L]=i.useState(void 0),[xe,he]=i.useState([]),[B,pe]=i.useState(!0),[ze,ae]=i.useState(null),[Ve,Te]=i.useState([]),[rt,Be]=i.useState([]),ce=P$(Z,q);i.useEffect(()=>{(async()=>{try{pe(!0);const J=await Ws();he(J.models),Te(J.favoriteProviders),Be(J.favoriteModels)}catch(J){ae(Se(J)||"Failed to load models")}finally{pe(!1)}})()},[]);const Re=i.useCallback(Fe=>{Te(J=>{const me=J,be=me.includes(Fe)?me.filter(gt=>gt!==Fe):[Fe,...me];return Bn({favoriteProviders:be,favoriteModels:rt}).catch(()=>{Te(me)}),be})},[rt]),Le=i.useCallback(Fe=>{Be(J=>{const me=J,be=me.includes(Fe)?me.filter(gt=>gt!==Fe):[Fe,...me];return Bn({favoriteProviders:Ve,favoriteModels:be}).catch(()=>{Be(me)}),be})},[Ve]),ct=i.useCallback((Fe,J)=>{if(!Fe||!J)return"Using default";const me=xe.find(Ze=>Ze.provider===Fe&&Ze.id===J);return me?`${me.provider}/${me.id}`:`${Fe}/${J}`},[xe]),Ue=i.useCallback(Fe=>{H.current?.close();const J=u0(Fe,a,{onThinking:me=>{x(Ze=>Ze+me),ke({sessionId:Fe,status:"generating",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onQuestion:me=>{E(!1),K(!1),da(a),u({type:"question",sessionId:Fe,question:me}),x(""),S(!0),ke({sessionId:Fe,status:"awaiting_input",needsInput:!0,owningTabId:D,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onSummary:me=>{E(!1),K(!1),da(a),u({type:"summary",sessionId:Fe,summary:me}),b(me),x(""),S(!0),ke({sessionId:Fe,status:"complete",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||void 0,projectId:a??null})},onError:me=>{const Ze=me||"Session failed while contacting the AI.";E(!1),K(!1),h(null),u({type:"error",sessionId:Fe,errorMessage:Ze}),x(""),S(!0),Q.current=Fe,ke({sessionId:Fe,status:"error",needsInput:!1,owningTabId:D,type:"mission_interview",title:l.trim()||void 0,projectId:a??null}),He({sessionId:Fe,status:"error"})},onComplete:()=>{E(!1),K(!1),Q.current=null,He({sessionId:Fe,status:"complete"})},onConnectionStateChange:me=>{E(me==="reconnecting")}});H.current=J},[He,ke,l,a,D]),ue=i.useCallback(async Fe=>{const J=Fe??l;if(J.trim()){h(null),x(""),p([]),w([]),E(!1),u({type:"loading"});try{const{sessionId:me}=await a0(J.trim(),a,Z&&q?{modelProvider:Z,modelId:q}:void 0);Q.current=me,M(me),da(a),Ue(me),p([])}catch(me){E(!1),h(Se(me)||"Failed to start interview session"),u({type:"initial"}),Q.current=null,M(null)}}},[Ue,l,Z,q,a]);i.useEffect(()=>{e&&d.type==="initial"&&T.current?.focus()},[e,d.type]),i.useEffect(()=>{if(e&&!r&&!o&&!j.current&&d.type==="initial"){const Fe=N$(a);Fe&&c(Fe)}},[e]),i.useEffect(()=>{if(e&&r&&!j.current&&d.type==="initial"){c(r);const Fe=setTimeout(()=>{j.current=!0,ue(r)},0);return()=>clearTimeout(Fe)}},[e,r,d.type,ue]),i.useEffect(()=>{e||(j.current=!1,E(!1),K(!1),M(null))},[e]),i.useEffect(()=>{if(!e||!o||d.type!=="initial")return;let Fe=!1;return Di(o).then(J=>{if(Fe||!J)return;const me=Mr(J.conversationHistory);if(w(me),M(J.id),p(me.map(Ze=>Ze.response).filter(Ze=>!!(Ze&&typeof Ze=="object"&&!Array.isArray(Ze)))),J.status==="awaiting_input"&&J.currentQuestion)try{da(a);const Ze=JSON.parse(J.currentQuestion);Q.current=J.id,S(!0),u({type:"question",sessionId:J.id,question:Ze})}catch{h("Failed to restore session question.")}else if(J.status==="complete"&&J.result)try{da(a);const Ze=JSON.parse(J.result);Q.current=J.id,S(!0),b(Ze),u({type:"summary",sessionId:J.id,summary:Ze})}catch{h("Failed to restore session result.")}else J.status==="generating"?(Q.current=J.id,S(!0),J.thinkingOutput&&x(J.thinkingOutput),u({type:"loading"}),Ue(J.id)):J.status==="error"&&(Q.current=J.id,S(!0),h(null),u({type:"error",sessionId:J.id,errorMessage:J.error??"The session encountered an error."}))}).catch(()=>{Fe||h("Failed to resume session.")}),()=>{Fe=!0}},[Ue,e,o,d.type,a]),i.useEffect(()=>{if(!e){se.current&&(je(se.current,D),se.current=null);return}if(O&&se.current!==O){se.current&&je(se.current,D),ye(O,D),se.current=O;return}!O&&se.current&&(je(se.current,D),se.current=null)},[ye,je,e,O,D]),i.useEffect(()=>{if(!e||!O||se.current!==O)return;ne(D);const Fe=setInterval(()=>{ne(D)},3e4);return()=>{clearInterval(Fe)}},[ne,e,O,D]),i.useEffect(()=>()=>{H.current?.close(),H.current=null,se.current&&(je(se.current,D),se.current=null)},[je,D]),i.useEffect(()=>{if(!e)return;const Fe=J=>{(d.type==="question"||d.type==="summary")&&(J.preventDefault(),J.returnValue=""),H.current?.close()};return window.addEventListener("beforeunload",Fe),()=>window.removeEventListener("beforeunload",Fe)},[e,d]);const oe=i.useCallback(()=>{H.current?.close(),H.current=null,n()},[n]),Ee=i.useCallback(async()=>{if(l&&j$(l,a),!(y&&!await fe({title:"Close Interview",message:"Are you sure you want to close? Your interview progress will be lost.",danger:!0}))){if(H.current?.close(),H.current=null,d.type==="question"||d.type==="summary"||d.type==="error")try{await kb(d.sessionId,a,D)}catch{}c(""),u({type:"initial"}),h(null),p([]),w([]),b(null),x(""),E(!1),K(!1),S(!1),A(!1),re(void 0),L(void 0),Q.current=null,M(null),n()}},[l,y,d,n,a,D,fe]);i.useEffect(()=>{if(!e)return;const Fe=J=>{J.key==="Escape"&&Ee()};return document.addEventListener("keydown",Fe),()=>document.removeEventListener("keydown",Fe)},[e,Ee]);const ft=i.useCallback(async Fe=>{if(d.type!=="question")return;const{sessionId:J}=d;h(null),p(me=>[...me,Fe]),w(me=>[...me,{question:d.question,response:Fe}]),u({type:"loading"}),x("");try{Ue(J),await r0(J,Fe,a,D),S(!0)}catch(me){H.current?.close(),H.current=null,h(Se(me)||"Failed to submit response"),u({type:"question",sessionId:J,question:d.question})}},[d,a,D,Ue]),ht=i.useCallback(async()=>{if(d.type!=="error")return;const Fe=d.sessionId;h(null),K(!0),x(""),u({type:"loading"}),Ue(Fe);try{Q.current=Fe,M(Fe),await o0(Fe,a,D)}catch(J){let me=J;if((Se(J)||"").includes("not in an error state"))try{const be=await Di(Fe);if(!be)throw new Error("Failed to refresh interview session.");const gt=Mr(be.conversationHistory);if(w(gt),p(gt.map($t=>$t.response).filter($t=>!!($t&&typeof $t=="object"&&!Array.isArray($t)))),Q.current=be.id,M(be.id),S(!0),be.status==="generating")x(be.thinkingOutput??""),u({type:"loading"}),H.current?.isConnected()||Ue(be.id);else if(be.status==="awaiting_input"){if(!be.currentQuestion)throw new Error("Interview session is awaiting input but has no current question.");da(a);const $t=JSON.parse(be.currentQuestion);u({type:"question",sessionId:be.id,question:$t}),H.current?.isConnected()||Ue(be.id)}else if(be.status==="complete"){if(!be.result)throw new Error("Interview session is complete but has no result.");da(a);const $t=JSON.parse(be.result);b($t),u({type:"summary",sessionId:be.id,summary:$t})}else be.status==="error"&&u({type:"error",sessionId:be.id,errorMessage:be.error??"Retry failed. Please try again."});E(!1);return}catch(be){me=be}H.current?.close(),H.current=null,u({type:"error",sessionId:Fe,errorMessage:Se(me)||"Retry failed. Please try again."}),E(!1)}finally{K(!1)}},[Ue,a,D,d]),tt=i.useCallback(async()=>{if(d.type==="summary"){h(null),A(!0);try{const Fe=await d0(d.sessionId,v||void 0,a);s(Fe),da(a),H.current?.close(),H.current=null,c(""),u({type:"initial"}),h(null),p([]),w([]),b(null),x(""),E(!1),K(!1),S(!1),A(!1),Q.current=null,M(null),n()}catch(Fe){h(Se(Fe)||"Failed to create mission"),A(!1)}}},[d,v,s,n,a]),xt=()=>d.type==="question"?Math.min(f.length+1,6):6,Me=d.type==="loading"||d.type==="question"||d.type==="summary"||d.type==="error",Ye=O?le.get(O):null,dt=Ye&&Ye.tabId!==D,wt=!!(dt&&!Ye.stale),St=$&&(!dt||Ye.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Fe=>Fe.target===Fe.currentTarget&&Ee(),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(Es,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Plan Mission with AI"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Me&&t.jsx("button",{className:"modal-send-to-background",onClick:oe,title:"Send to background","aria-label":"Send to background",children:t.jsx(qo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ee,"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[m&&t.jsx("div",{className:"form-error planning-error",children:m}),F&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),wt&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),d.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(ms,{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:T,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:Fe=>c(Fe.target.value),onKeyDown:Fe=>{Fe.key==="Enter"&&!Fe.shiftKey&&l.trim()&&(Fe.preventDefault(),ue())}})]}),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:D$.map((Fe,J)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>c(Fe),children:Fe.length>45?Fe.slice(0,45)+"...":Fe},J))})]}),t.jsxs("div",{className:"planning-model-select-group",children:[t.jsxs("label",{htmlFor:"mission-interview-modal-model",className:"form-label",children:["Planning Model",B&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx(_s,{id:"mission-interview-modal-model",label:"Planning Model",value:ce,onChange:Fe=>{const{provider:J,modelId:me}=$$(Fe);re(J),L(me)},models:xe,disabled:B,favoriteProviders:Ve,onToggleFavorite:Re,favoriteModels:rt,onToggleModelFavorite:Le}),ze&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ze," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{(async()=>{try{pe(!0);const Fe=await Ws();he(Fe.models),Te(Fe.favoriteProviders),Be(Fe.favoriteModels),ae(null)}catch(Fe){ae(Se(Fe)||"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 ${Z&&q?"model-badge-custom":"model-badge-default"}`,children:ct(Z,q)})})]})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>ue(),disabled:!l.trim(),children:[t.jsx(Es,{size:16,className:"icon-mr-8"}),"Start Interview"]})})]}),d.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:C?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>R(!N),type:"button",children:N?"Hide thinking":"Show thinking"}),N&&C&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:C})})]})]}),d.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[g.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:g}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:d.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void ht(),disabled:_,children:[_?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),t.jsx("span",{className:"icon-ml-6",children:_?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Ee,disabled:_,children:"Cancel"})]})]})]})}),d.type==="question"&&t.jsx(O$,{question:d.question,progress:xt(),historyEntries:g,onSubmit:ft}),d.type==="summary"&&v&&t.jsx(F$,{summary:v,historyEntries:g,onSummaryChange:b,onApprove:tt,onStartOver:()=>{u({type:"initial"}),S(!1),b(null),p([]),w([]),M(null),H.current?.close(),H.current=null},isCreating:U}),$&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(yc,{size:16}),t.jsx("span",{children:St?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),St&&t.jsx("button",{type:"button",onClick:()=>{k()},disabled:X,className:"btn btn-primary session-lock-take-control",children:X?"Taking control...":"Take Control"})]})})]})]})}):null}function O$({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const w=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:w})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Xn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(mn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx(Uo,{size:16,className:"icon-ml-4"})]})})]})}function F$({summary:e,historyEntries:n,onSummaryChange:s,onApprove:a,onStartOver:r,isCreating:o}){const[l,c]=i.useState(()=>new Set(e.milestones.map((j,C)=>C))),[d,u]=i.useState(()=>{const j=new Set;return e.milestones.forEach((C,x)=>{C.slices.forEach((N,R)=>j.add(`${x}-${R}`))}),j}),m=j=>{c(C=>{const x=new Set(C);return x.has(j)?x.delete(j):x.add(j),x})},h=j=>{u(C=>{const x=new Set(C);return x.has(j)?x.delete(j):x.add(j),x})},f=(j,C)=>{const x=[...e.milestones];x[j]={...x[j],...C},s({...e,milestones:x})},p=(j,C,x)=>{const N=[...e.milestones],R=[...N[j].slices];R[C]={...R[C],...x},N[j]={...N[j],slices:R},s({...e,milestones:N})},g=(j,C,x,N)=>{const R=[...e.milestones],F=[...R[j].slices],E=[...F[C].features];E[x]={...E[x],...N},F[C]={...F[C],features:E},R[j]={...R[j],slices:F},s({...e,milestones:R})},w=j=>{const C=e.milestones.filter((x,N)=>N!==j);s({...e,milestones:C})},v=(j,C)=>{const x=[...e.milestones];x[j]={...x[j],slices:x[j].slices.filter((N,R)=>R!==C)},s({...e,milestones:x})},b=(j,C,x)=>{const N=[...e.milestones],R=[...N[j].slices];R[C]={...R[C],features:R[C].features.filter((F,E)=>E!==x)},N[j]={...N[j],slices:R},s({...e,milestones:N})},y=(j,C)=>{const x=[...e.milestones],N=[...x[j].slices];N[C]={...N[C],features:[...N[C].features,{title:"New feature",description:""}]},x[j]={...x[j],slices:N},s({...e,milestones:x})},S=e.milestones.reduce((j,C)=>j+C.slices.reduce((x,N)=>x+N.features.length,0),0);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Xn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Mission Plan Ready"}),t.jsxs("p",{className:"text-muted",children:[e.milestones.length," milestones, ",S," features. Review and edit before approving."]})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Title"}),t.jsx("input",{type:"text",className:"form-input",value:e.missionTitle||"",onChange:j=>s({...e,missionTitle:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Mission Description"}),t.jsx("textarea",{className:"planning-textarea",rows:3,value:e.missionDescription||"",onChange:j=>s({...e,missionDescription:j.target.value})})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Roadmap"}),t.jsx("div",{className:"roadmap-list",children:e.milestones.map((j,C)=>t.jsxs("div",{className:"roadmap-card",children:[t.jsxs("div",{className:"roadmap-card-header",onClick:()=>m(C),children:[l.has(C)?t.jsx(gn,{size:16,className:"icon-text-secondary"}):t.jsx(qn,{size:16,className:"icon-text-secondary"}),t.jsx(Fa,{size:16,className:"icon-milestone"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-title",value:j.title,onChange:x=>f(C,{title:x.target.value}),onClick:x=>x.stopPropagation()}),e.milestones.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:x=>{x.stopPropagation(),w(C)},title:"Remove milestone",children:t.jsx(Tn,{size:14,className:"icon-text-secondary"})})]}),l.has(C)&&t.jsxs("div",{className:"roadmap-card-body",children:[t.jsx("textarea",{className:"planning-textarea roadmap-textarea-md",rows:2,placeholder:"Milestone description...",value:j.description||"",onChange:x=>f(C,{description:x.target.value})}),t.jsxs("div",{className:"roadmap-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Verification Criteria"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-sm",rows:2,placeholder:"How to confirm this milestone is complete...",value:j.verification||"",onChange:x=>f(C,{verification:x.target.value})})]}),j.slices.map((x,N)=>{const R=`${C}-${N}`;return t.jsxs("div",{className:"roadmap-slice-card",children:[t.jsxs("div",{className:"roadmap-slice-header",onClick:()=>h(R),children:[d.has(R)?t.jsx(gn,{size:14,className:"icon-text-secondary"}):t.jsx(qn,{size:14,className:"icon-text-secondary"}),t.jsx(ru,{size:14,className:"icon-slice"}),t.jsx("input",{type:"text",className:"form-input roadmap-input-subtitle",value:x.title,onChange:F=>p(C,N,{title:F.target.value}),onClick:F=>F.stopPropagation()}),j.slices.length>1&&t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:F=>{F.stopPropagation(),v(C,N)},title:"Remove slice",children:t.jsx(Tn,{size:12,className:"icon-text-secondary"})})]}),d.has(R)&&t.jsxs("div",{className:"roadmap-slice-body",children:[t.jsxs("div",{className:"roadmap-slice-field-group",children:[t.jsx("label",{className:"roadmap-field-label",children:"Slice Verification"}),t.jsx("textarea",{className:"planning-textarea roadmap-textarea-xs",rows:1,placeholder:"How to confirm this slice is done...",value:x.verification||"",onChange:F=>p(C,N,{verification:F.target.value})})]}),x.features.map((F,E)=>t.jsxs("div",{className:"roadmap-feature-row",children:[t.jsx(eu,{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:F.title,onChange:_=>g(C,N,E,{title:_.target.value})}),F.description&&t.jsx("p",{className:"roadmap-feature-text",children:F.description}),F.acceptanceCriteria&&t.jsxs("p",{className:"roadmap-feature-text--italic",children:["AC: ",F.acceptanceCriteria]})]}),t.jsx("button",{className:"btn-icon roadmap-shrink",onClick:()=>b(C,N,E),title:"Remove feature",children:t.jsx(Tn,{size:12,className:"icon-text-secondary"})})]},E)),t.jsxs("button",{className:"btn roadmap-add-feature-btn",onClick:()=>y(C,N),children:[t.jsx($n,{size:12}),"Add Feature"]})]})]},N)})]})]},C))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:o,children:[t.jsx(Ga,{size:16,className:"icon-mr-4"}),"Start Over"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:o||e.milestones.length===0,children:o?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Creating Mission..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:16,className:"icon-mr-8"}),"Approve Plan"]})})]})]})}const z$=30,B$=16,U$=16;function H$(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}let Ul=null;function kv(){return Ul===null&&(Ul=window.visualViewport?.height??window.innerHeight),Ul}function q$(e){const n=kv();e>n&&(Ul=e)}function V$(e){return e?e instanceof HTMLTextAreaElement?!0:e instanceof HTMLInputElement?!new Set(["checkbox","radio","button","submit","reset","file","range","color","hidden"]).has(e.type):e instanceof HTMLElement&&e.isContentEditable:!1}function kf(){if(typeof window>"u"||!window.visualViewport)return{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0};const e=window.visualViewport,n=V$(document.activeElement),s=e.offsetTop;n||q$(e.height);const a=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(a>0&&n)return{overlap:a,open:!0,vvHeight:e.height,vvOffsetTop:s};const r=kv(),o=Math.max(0,r-e.offsetTop-e.height);if(o>=z$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};if(o>=B$&&n)return{overlap:o,open:!0,vvHeight:e.height,vvOffsetTop:s};const l=Math.max(0,r-e.height);return n&&l>=U$?{overlap:0,open:!0,vvHeight:e.height,vvOffsetTop:s}:{overlap:0,open:!1,vvHeight:null,vvOffsetTop:0}}function aa({enabled:e=!0}={}){const[n,s]=i.useState(0),[a,r]=i.useState(null),[o,l]=i.useState(0),[c,d]=i.useState(!1);return i.useEffect(()=>{if(!e||!H$()){s(0),r(null),l(0),d(!1);return}const u=window.visualViewport;if(!u){s(0),r(null),l(0),d(!1);return}const m=()=>{const x=kf();s(x.overlap),r(x.vvHeight),l(x.vvOffsetTop),d(x.open)},h=()=>{const x=kf();s(x.overlap),r(x.vvHeight),d(x.open)},f=[],p=x=>{if(typeof window>"u")return;const N=window.setTimeout(()=>{typeof window>"u"||m()},x);f.push(N)};let g=null,w=0,v=-1,b=0;const y=()=>{g!==null&&typeof window<"u"&&(window.cancelAnimationFrame(g),g=null)},S=()=>{if(typeof window>"u")return;m();const x=window.visualViewport?.offsetTop??0;if(x===v?b+=1:(b=0,v=x),b>=2||performance.now()>w){g=null;return}g=window.requestAnimationFrame(S)},j=()=>{typeof window>"u"||(y(),w=performance.now()+1500,v=-1,b=0,g=window.requestAnimationFrame(S))},C=()=>{m(),p(50),p(200),p(500),p(1e3),p(1500),j()};return C(),u.addEventListener("resize",m),u.addEventListener("scroll",h),document.addEventListener("focusin",C),document.addEventListener("focusout",m),document.addEventListener("visibilitychange",C),window.addEventListener("pageshow",C),()=>{u.removeEventListener("resize",m),u.removeEventListener("scroll",h),document.removeEventListener("focusin",C),document.removeEventListener("focusout",m),document.removeEventListener("visibilitychange",C),window.removeEventListener("pageshow",C);for(const x of f)clearTimeout(x);y(),s(0),r(null),l(0),d(!1)}},[e]),{keyboardOverlap:n,viewportHeight:a,viewportOffsetTop:o,keyboardOpen:c}}function W$({isOpen:e,onClose:n,onApplied:s,targetType:a,targetId:r,targetTitle:o,missionContext:l,projectId:c,resumeSessionId:d}){const u=oi();Mi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=aa({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[w,v]=i.useState({type:"initial"}),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,x]=i.useState([]),[N,R]=i.useState(null),[F,E]=i.useState(""),[_,K]=i.useState(!0),[U,A]=i.useState(!1),[T,H]=i.useState(!1),Q=i.useRef(null),se=i.useRef(null),O=i.useRef(null),M=i.useRef(null),[D,$]=i.useState(null),k=i.useMemo(()=>Ja(),[]);Tc(e?D:null);const{activeTabMap:X,broadcastUpdate:le,broadcastCompleted:ke,broadcastLock:He,broadcastUnlock:ye,broadcastHeartbeat:je}=Wr(),ne=a==="milestone"?m0:b0,fe=a==="milestone"?h0:x0,Z=a==="milestone"?p0:v0,re=a==="milestone"?f0:y0,q=a==="milestone"?g0:w0,L=a==="milestone"?"Milestone":"Slice",xe=a==="milestone"?"milestone_interview":"slice_interview",he=i.useCallback(Ue=>{se.current?.close();const ue=Z(Ue,c,{onThinking:oe=>{E(Ee=>Ee+oe),le({sessionId:Ue,status:"generating",needsInput:!1,owningTabId:k,type:xe,title:o,projectId:c??null})},onQuestion:oe=>{A(!1),B(),v({type:"question",sessionId:Ue,question:oe}),E(""),le({sessionId:Ue,status:"awaiting_input",needsInput:!0,owningTabId:k,type:xe,title:o,projectId:c??null})},onSummary:oe=>{A(!1),B(),v({type:"summary",sessionId:Ue,summary:oe}),R(oe),E(""),le({sessionId:Ue,status:"complete",needsInput:!1,owningTabId:k,type:xe,title:o,projectId:c??null})},onError:oe=>{const Ee=oe||"Session failed while contacting the AI.";A(!1),y(null),v({type:"error",sessionId:Ue,errorMessage:Ee}),E(""),O.current=Ue,le({sessionId:Ue,status:"error",needsInput:!1,owningTabId:k,type:xe,title:o,projectId:c??null}),ke({sessionId:Ue,status:"error"})},onComplete:()=>{A(!1),O.current=null,ke({sessionId:Ue,status:"complete"})},onConnectionStateChange:oe=>{A(oe==="reconnecting")}});se.current=ue},[ke,le,Z,xe,c,k,o]),B=()=>{R(null),j([]),x([]),E("")},pe=i.useCallback(async()=>{y(null),B(),A(!1),v({type:"loading"});try{const{sessionId:Ue}=await ne(r,c);O.current=Ue,$(Ue),he(Ue)}catch(Ue){A(!1),y(Se(Ue)||`Failed to start ${L.toLowerCase()} interview`),v({type:"initial"}),O.current=null,$(null)}},[he,c,ne,r,L]),ze=i.useCallback(async()=>{y(null),H(!0);try{await q(r,c),s(),v({type:"applied"})}catch(Ue){y(Se(Ue)||`Failed to skip ${L.toLowerCase()} interview`),H(!1)}},[s,c,q,r,L]);i.useEffect(()=>{e&&w.type==="initial"&&Q.current?.focus()},[e,w.type]),i.useEffect(()=>{if(!e||!d||w.type!=="initial")return;let Ue=!1;return Di(d).then(ue=>{if(Ue||!ue)return;const oe=Mr(ue.conversationHistory);if(x(oe),$(ue.id),j(oe.map(Ee=>Ee.response).filter(Ee=>!!(Ee&&typeof Ee=="object"&&!Array.isArray(Ee)))),ue.status==="awaiting_input"&&ue.currentQuestion)try{const Ee=JSON.parse(ue.currentQuestion);O.current=ue.id,v({type:"question",sessionId:ue.id,question:Ee})}catch{y("Failed to restore session question.")}else if(ue.status==="complete"&&ue.result)try{const Ee=JSON.parse(ue.result);O.current=ue.id,R(Ee),v({type:"summary",sessionId:ue.id,summary:Ee})}catch{y("Failed to restore session result.")}else ue.status==="generating"?(O.current=ue.id,ue.thinkingOutput&&E(ue.thinkingOutput),v({type:"loading"}),he(ue.id)):ue.status==="error"&&(O.current=ue.id,y(null),v({type:"error",sessionId:ue.id,errorMessage:ue.error??"The session encountered an error."}))}).catch(()=>{Ue||y("Failed to resume session.")}),()=>{Ue=!0}},[he,e,d,w.type]),i.useEffect(()=>{e||(A(!1),$(null))},[e]),i.useEffect(()=>{if(!(!e||!D)){if(M.current!==D){M.current&&ye(M.current,k),He(D,k),M.current=D;return}!D&&M.current&&(ye(M.current,k),M.current=null)}},[He,ye,e,D,k]),i.useEffect(()=>{if(!e||!D||M.current!==D)return;je(k);const Ue=setInterval(()=>{je(k)},3e4);return()=>{clearInterval(Ue)}},[je,e,D,k]),i.useEffect(()=>()=>{se.current?.close(),se.current=null,M.current&&(ye(M.current,k),M.current=null)},[ye,k]);const ae=i.useCallback(()=>{se.current?.close(),se.current=null,n()},[n]),Ve=i.useCallback(async()=>{se.current?.close(),se.current=null,B(),v({type:"initial"}),y(null),O.current=null,$(null),n()},[n]),Te=i.useCallback(async Ue=>{if(w.type!=="question")return;const{sessionId:ue}=w;y(null),j(oe=>[...oe,Ue]),x(oe=>[...oe,{question:w.question,response:Ue}]),v({type:"loading"}),E("");try{he(ue),await fe(ue,Ue,c,k)}catch(oe){se.current?.close(),se.current=null,y(Se(oe)||"Failed to submit response"),v({type:"question",sessionId:ue,question:w.question})}},[he,c,fe,k,w]),rt=i.useCallback(async()=>{if(w.type==="summary"){y(null),H(!0);try{await re(w.sessionId,N||void 0,c),s(),v({type:"applied"})}catch(Ue){y(Se(Ue)||"Failed to apply interview results"),H(!1)}}},[re,N,s,c,w]),Be=()=>w.type==="question"?Math.min(S.length+1,6):6,ce=w.type==="loading"||w.type==="question"||w.type==="summary"||w.type==="error",Re=D?X.get(D):null,ct=!!(Re&&Re.tabId!==k&&!Re.stale);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ue=>Ue.target===Ue.currentTarget&&Ve(),role:"dialog","aria-modal":"true","data-testid":"milestone-slice-interview-modal",children:t.jsxs("div",{className:"modal modal-lg planning-modal",style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(ms,{size:20,className:"icon-triage"}),t.jsxs("h3",{children:["Plan ",L,": ",o]})]}),t.jsxs("div",{className:"modal-header-actions",children:[ce&&t.jsx("button",{className:"modal-send-to-background",onClick:ae,title:"Send to background","aria-label":"Send to background",children:t.jsx(qo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:Ve,"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[b&&t.jsx("div",{className:"form-error planning-error",children:b}),U&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ct&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),w.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(ms,{size:32,className:"icon-triage-lg"}),t.jsxs("h4",{children:["Refine ",L," scope with AI"]}),t.jsxs("p",{className:"text-muted",children:["The AI will interview you to refine the ",a,"'s scope, acceptance criteria, and verification methods. Each ",a," can have its own refined plan or inherit context from the mission level."]}),l&&t.jsxs("div",{className:"planning-context-info",children:[t.jsx("span",{className:"planning-context-label",children:"Mission context:"}),t.jsx("span",{className:"planning-context-text",children:l})]})]})}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>void pe(),children:[t.jsx(ms,{size:16,className:"icon-mr-8"}),"Start Interview"]}),t.jsxs("button",{className:"btn planning-use-context-btn",onClick:()=>void ze(),disabled:T,children:[T?t.jsx(jt,{size:16,className:"spin"}):null,"Use Mission Context"]}),t.jsx("button",{className:"btn",onClick:Ve,children:"Cancel"})]})]}),w.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:F?"AI is thinking...":"Preparing next question..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>K(!_),type:"button",children:_?"Hide thinking":"Show thinking"}),_&&F&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:F})})]})]}),w.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[C.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:C}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:w.errorMessage}),t.jsx("div",{className:"ai-error-actions",children:t.jsx("button",{className:"btn",onClick:Ve,children:"Cancel"})})]})]})}),w.type==="question"&&t.jsx(G$,{question:w.question,progress:Be(),historyEntries:C,onSubmit:Te}),w.type==="summary"&&N&&t.jsx(K$,{summary:N,historyEntries:C,onSummaryChange:R,onApply:rt,onCancel:Ve,isApplying:T}),w.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(Xn,{size:48,className:"icon-success"}),t.jsxs("h4",{children:[L," Updated"]}),t.jsxs("p",{className:"text-muted",children:["The ",a,"'s scope and verification have been ",w.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 G$({question:e,progress:n,historyEntries:s,onSubmit:a}){const[r,o]=i.useState({}),[l,c]=i.useState(""),[d,u]=i.useState(""),m=i.useCallback(()=>{let f;e.type==="text"?f={[e.id]:l}:e.type==="confirm"?f={[e.id]:r[e.id]===!0}:f=r;const p=d.trim();p.length>0&&(f={...f,_comment:p}),a(f)},[d,e,r,l,a]);i.useEffect(()=>{o({}),c(""),u("")},[e.id]);const h=()=>{switch(e.type){case"text":return l.trim().length>0;case"single_select":return r[e.id]!==void 0;case"multi_select":return Array.isArray(r[e.id])&&r[e.id].length>0;case"confirm":return r[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3,4,5,6].map(f=>t.jsx("div",{className:`planning-progress-step ${f<=n?"active":""}`},f))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~6"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:l,onChange:f=>c(f.target.value),onKeyDown:f=>{f.key==="Enter"&&!f.shiftKey&&l.trim()&&(f.preventDefault(),m())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(f=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:f.id,checked:r[e.id]===f.id,onChange:()=>o({[e.id]:f.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(f=>{const p=r[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:f.id,checked:p.includes(f.id),onChange:g=>{const w=g.target.checked?[...p,f.id]:p.filter(v=>v!==f.id);o({[e.id]:w})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:f.label}),f.description&&t.jsx("span",{className:"planning-option-desc",children:f.description})]})]},f.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!0?"selected":""}`,onClick:()=>o({[e.id]:!0}),children:[t.jsx(Xn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${r[e.id]===!1?"selected":""}`,onClick:()=>o({[e.id]:!1}),children:[t.jsx(mn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:d,onChange:f=>u(f.target.value)})]})]})]})]}),t.jsx("div",{className:"planning-actions",children:t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:m,disabled:!h(),children:["Continue",t.jsx(Uo,{size:16,className:"icon-ml-4"})]})})]})}function K$({summary:e,historyEntries:n,onSummaryChange:s,onApply:a,onCancel:r,isApplying:o}){const[l,c]=i.useState(e),[d,u]=i.useState(!0),m=(h,f)=>{const p={...l,[h]:f};c(p),s(p)};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-panel",children:[t.jsx("div",{className:"planning-summary-header",children:t.jsxs("button",{className:"planning-summary-toggle",onClick:()=>u(!d),"aria-expanded":d,children:[d?t.jsx(gn,{size:16}):t.jsx(qn,{size:16}),t.jsx("span",{children:"Refined Scope"})]})}),d&&t.jsxs("div",{className:"planning-summary-content",children:[l.description&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:l.description,onChange:h=>m("description",h.target.value)})]}),l.planningNotes&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Planning Notes"}),t.jsx("textarea",{rows:3,value:l.planningNotes,onChange:h=>m("planningNotes",h.target.value)})]}),l.verification&&t.jsxs("div",{className:"planning-summary-field",children:[t.jsx("label",{children:"Verification Criteria"}),t.jsx("textarea",{rows:2,value:l.verification,onChange:h=>m("verification",h.target.value)})]}),!l.description&&!l.planningNotes&&!l.verification&&t.jsx("p",{className:"text-muted planning-summary-empty",children:"No additional details were generated for this item."})]})]})]}),t.jsxs("div",{className:"planning-view-footer",children:[t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:a,disabled:o,children:[o?t.jsx(jt,{size:16,className:"spin"}):null,"Apply"]}),t.jsx("button",{className:"btn",onClick:r,disabled:o,children:"Cancel"})]})]})}const jf=300,jl=220,Nl=560,Nf="fusion:mission-sidebar-width",lo={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)"}},Sf={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)"}},Cf={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)"}},Sl={defined:{bg:"var(--feature-defined-bg)",text:"var(--feature-defined-text)"},triaged:{bg:"var(--feature-triaged-bg)",text:"var(--feature-triaged-text)"},"in-progress":{bg:"var(--feature-in-progress-bg)",text:"var(--feature-in-progress-text)"},done:{bg:"var(--feature-done-bg)",text:"var(--feature-done-text)"},blocked:{bg:"var(--mission-blocked-bg)",text:"var(--mission-blocked-text)"}},Cl={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)"}},El={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)"}},Ef={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)"}},J$=3,Y$=new Set(["generating","awaiting_input","error"]);function Q$(e){switch(e){case"generating":return"Generating plan";case"awaiting_input":return"Awaiting input";case"error":return"Needs retry";default:return e}}function X$(e){return e==="error"?"Retry interview":"Resume interview"}function Z$(e){return e==="completed"?"planned":e==="needs_update"?"needs_update":"not_started"}function _f({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 Mf(e){return e?e.replace(/_/g," ").replace(/^\w/,n=>n.toUpperCase()):"Not started"}const Af={title:"",description:"",status:"planning",autopilotEnabled:!1},Td={title:"",description:"",status:"planning",dependencies:[]},Pd={title:"",description:"",status:"pending"},$d={title:"",description:"",acceptanceCriteria:"",status:"defined"},e4=3600*1e3;function rc(e){if(!e)return"—";const n=new Date(e).getTime();if(Number.isNaN(n))return"—";const s=Date.now()-n;if(s<0)return"just now";const a=Math.floor(s/(60*1e3));if(a<1)return"just now";if(a<60)return`${a}m ago`;const r=Math.floor(a/60);return r<24?`${r}h ago`:`${Math.floor(r/24)}d ago`}function t4(e){if(!e)return"healthy";const n=typeof e.lastErrorAt=="string"&&Date.now()-new Date(e.lastErrorAt).getTime()<=e4,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 n4(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 s4(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 Dd(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 jv=["feature_triaged","feature_completed"],Nv=["slice_activated","slice_completed","milestone_completed"],Sv=["mission_started","mission_paused","mission_resumed","mission_completed"],Cv=["autopilot_enabled","autopilot_disabled","autopilot_state_changed","autopilot_retry","autopilot_stale"];function Rf(e,n){switch(n){case"errors":return e==="error"||e==="warning";case"state_changes":return Sv.includes(e);case"tasks":return jv.includes(e);case"slices":return Nv.includes(e);case"autopilot":return Cv.includes(e);default:return!0}}function i4(e){return e==="error"||e==="warning"?"mission-event__type--error":Sv.includes(e)?"mission-event__type--state":jv.includes(e)?"mission-event__type--task":Nv.includes(e)?"mission-event__type--slice":Cv.includes(e)?"mission-event__type--autopilot":"mission-event__type--default"}function a4(e){return e.replace(/_/g," ")}function r4(e,n){return n?e==="watching"?`Watching since ${rc(n)}`:`Last activation ${rc(n)}`:null}function o4({isOpen:e,isInline:n=!1,onClose:s,addToast:a,projectId:r,onSelectTask:o,availableTasks:l=[],resumeSessionId:c,targetMissionId:d,milestoneSliceResumeSessionId:u,onMilestoneSliceResumeFetchError:m}){const h=n||e,[f,p]=i.useState([]),[g,w]=i.useState(null),[v,b]=i.useState(!0),[y,S]=i.useState(!1),j=oi()==="mobile",{pushNav:C}=wv(),[x,N]=i.useState(()=>{if(typeof window>"u")return jf;const z=window.localStorage.getItem(Nf),Ae=z?Number(z):NaN;return Number.isFinite(Ae)?Math.max(jl,Math.min(Nl,Ae)):jf}),R=i.useCallback(z=>{try{window.localStorage.setItem(Nf,String(z))}catch{}},[]),F=i.useCallback(z=>{if(j)return;z.preventDefault(),z.stopPropagation();const Ae=z.currentTarget;typeof Ae.setPointerCapture=="function"&&Ae.setPointerCapture(z.pointerId);const Ge=z.clientX,kt=x;let An=kt;document.body.style.userSelect="none";const Vt=Xe=>{const lt=Xe.clientX-Ge,Tt=Math.max(jl,Math.min(Nl,kt+lt));An=Tt,N(Tt)},Nn=Xe=>{typeof Ae.releasePointerCapture=="function"&&Ae.releasePointerCapture(Xe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Vt),document.removeEventListener("pointerup",Nn),R(An)};document.addEventListener("pointermove",Vt),document.addEventListener("pointerup",Nn)},[j,R,x]),E=i.useCallback(z=>{if(j||z.key!=="ArrowLeft"&&z.key!=="ArrowRight")return;z.preventDefault();const Ae=z.shiftKey?50:10,Ge=z.key==="ArrowLeft"?-Ae:Ae,kt=Math.max(jl,Math.min(Nl,x+Ge));N(kt),R(kt)},[j,R,x]),[_,K]=i.useState(!1),[U,A]=i.useState(null),[T,H]=i.useState(Af),[Q,se]=i.useState(!1),[O,M]=i.useState(new Set),[D,$]=i.useState(new Set),[k,X]=i.useState(null),[le,ke]=i.useState(Td),[He,ye]=i.useState(!1),[je,ne]=i.useState(null),[fe,Z]=i.useState(Pd),[re,q]=i.useState(!1),[L,xe]=i.useState(null),[he,B]=i.useState(null),[pe,ze]=i.useState($d),[ae,Ve]=i.useState(!1),[Te,rt]=i.useState(null),[Be,ce]=i.useState(null),[Re,Le]=i.useState(""),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState([]),[Ee,ft]=i.useState([]),[ht,tt]=i.useState(void 0),xt=i.useRef(null),Me=ht??(c&&xt.current===c?void 0:c),[Ye,dt]=i.useState(null),[wt,St]=i.useState(null),[Fe,J]=i.useState(null);i.useEffect(()=>{h&&Me&&Ue(!0)},[h,Me]),i.useEffect(()=>{c&&xt.current!==c&&(xt.current=null)},[c]),i.useEffect(()=>{if(!h)return;let z=!1;return Wu(r).then(Ae=>{if(z)return;const Ge=Ae.filter(kt=>kt.type!=="mission_interview"||!Y$.has(kt.status)?!1:r?kt.projectId===r:kt.projectId==null);oe(Ge)}).catch(Ae=>{console.warn("[MissionManager] Failed to fetch pending interview sessions:",Ae)}),()=>{z=!0}},[h,r,Me]),i.useEffect(()=>{if(!h)return;let z=!1;return l0(r).then(Ae=>{z||ft(Ae)}).catch(Ae=>{console.warn("[MissionManager] Failed to fetch mission interview drafts:",Ae)}),()=>{z=!0}},[h,r,Me]),i.useEffect(()=>{if(!h||!u)return;let z=!1;return Di(u).then(Ae=>{if(!(z||!Ae))try{const Ge=JSON.parse(Ae.inputPayload||"{}");Ge.targetId&&Ge.targetType&&dt({type:Ge.targetType,id:Ge.targetId,title:Ge.targetTitle||Ae.title,resumeSessionId:u})}catch{dt({type:"milestone",id:"",title:Ae.title,resumeSessionId:u})}}).catch(Ae=>{z||(console.warn("[MissionManager] Failed to fetch session for milestone/slice resume:",Ae),m?.())}),()=>{z=!0}},[h,u,m]);const[me,Ze]=i.useState(null),[be,gt]=i.useState(new Map),[$t,Ie]=i.useState(null),[ge,st]=i.useState({title:"",assertion:"",status:"pending"}),[yt,pt]=i.useState(!1),[vt,Ut]=i.useState(null),[Dt,nn]=i.useState(new Map),[on,sn]=i.useState(new Set),[ln,xn]=i.useState(new Set),[qt,Qt]=i.useState(null),[hn,Zt]=i.useState(new Map),[ve,Pe]=i.useState(null),[Ke,at]=i.useState(null),[We,It]=i.useState(!0),[Lt,Bt]=i.useState(new Set),[Gt,bt]=i.useState(new Map),[Ot,en]=i.useState(null),[Kt,Sn]=i.useState(new Map),[dn,Jt]=i.useState(null),[tn,Ne]=i.useState(new Map),[W,Y]=i.useState(new Map),[_e,ut]=i.useState("structure"),[At,zt]=i.useState([]),yn=i.useRef([]),Zn=i.useRef([]),vn=i.useRef(null),Dn=i.useRef(null),de=i.useRef("structure"),nt=i.useRef("all"),[ot,_t]=i.useState(!1),[G,Oe]=i.useState(0),[Mt,Xt]=i.useState("all"),[_n,Pn]=i.useState(new Set),kn=i.useRef(null),Vn=i.useRef(null);Zn.current=f,vn.current=g,Dn.current=ve,de.current=_e,nt.current=Mt;const $s=i.useCallback((z="auto")=>{const Ae=Vn.current;if(Ae&&typeof Ae.scrollIntoView=="function"){Ae.scrollIntoView({block:"end",behavior:z});return}const Ge=kn.current;Ge&&(Ge.scrollTop=Ge.scrollHeight)},[]),vs=i.useCallback(()=>{const z=kn.current;return z?z.scrollHeight-z.scrollTop-z.clientHeight<=100:!0},[]),As=i.useCallback(async z=>{if(z.length===0){Y(new Map);return}const Ae=await I1(r);Y(Ge=>{const kt=new Map(Ge);for(const[An,Vt]of Object.entries(Ae))n4(Vt)&&kt.set(An,Vt);return kt})},[r]),bn=i.useCallback(async()=>{try{b(!0);const z=await E1(r);p(z),As(z)}catch(z){a(Se(z)||"Failed to load missions","error")}finally{b(!1)}},[a,r,As]),Ht=i.useCallback(async z=>{try{S(!0);const Ae=await wb(z,r);if(!Ae||!Array.isArray(Ae.milestones)){S(!1);return}if(w(Ae),Ae.milestones.length>0){const Ge=Ae.milestones[0].id;Pe(Ge),It(!0),M(new Set([Ge])),Hc(Ge,r).then(kt=>{gt(An=>{const Vt=new Map(An);return Vt.set(Ge,kt),Vt})}).catch(()=>{}),qc(Ge,r).then(kt=>{Zt(An=>{const Vt=new Map(An);return Vt.set(Ge,kt),Vt})}).catch(()=>{}),Ae.milestones[0].slices.length>0&&$(new Set([Ae.milestones[0].slices[0].id]))}else Pe(null),at(null)}catch(Ae){a(Se(Ae)||"Failed to load mission details","error")}finally{S(!1)}},[a,r]);i.useEffect(()=>{if(!h||!ve){at(null);return}let z=!1;return at(null),lh(ve,r).then(Ae=>{if(!z){if(!Dd(Ae)){at(null);return}at(Ae),Zt(Ge=>{const kt=new Map(Ge);return kt.set(ve,Ae.rollup),kt})}}).catch(()=>{z||at(null)}),()=>{z=!0}},[h,ve,r]),i.useEffect(()=>{It(!0)},[ve]);const On=i.useCallback(z=>{!z||z!==Dn.current||lh(z,r).then(Ae=>{Dn.current!==z||!Dd(Ae)||(at(Ae),Zt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae.rollup),kt}))}).catch(()=>{})},[r]),Fn=i.useCallback(async(z,Ae)=>{const Ge=Ae?.append??!1,kt=Ge?yn.current.length:0;Ge||(_t(!0),Pn(new Set));try{const An=await R1(z,{limit:50,offset:kt,eventType:void 0},r),Vt=An.events.filter(Nn=>Rf(Nn.eventType,Mt));zt(Nn=>{if(!Ge)return yn.current=Vt,Vt;const Xe=new Set(Nn.map(Tt=>Tt.id)),lt=[...Nn];for(const Tt of Vt)Xe.has(Tt.id)||lt.push(Tt);return yn.current=lt,lt}),Oe(An.total),Ge||requestAnimationFrame(()=>{$s("auto")})}catch(An){a(Se(An)||"Failed to load mission activity","error")}finally{Ge||_t(!1)}},[a,Mt,r,$s]);i.useEffect(()=>{yn.current=At},[At]),i.useEffect(()=>{h&&(bn(),w(null),Pe(null),at(null),zt([]),Oe(0),ut("structure"),Xt("all"),Pn(new Set))},[h,bn]);const as=i.useRef(null);i.useEffect(()=>{h&&d&&as.current!==d&&f.length>0&&(as.current=d,Ht(d))},[h,d,f,Ht]),i.useEffect(()=>{h||(as.current=null)},[h]);const Wn=i.useRef(!1);i.useEffect(()=>{!h||!n||j||v||Wn.current||g||d||f.length!==0&&(Wn.current=!0,Ht(f[0].id))},[h,n,j,v,f,g,d,Ht]),i.useEffect(()=>{h||(Wn.current=!1)},[h]),i.useEffect(()=>{!h||!g||_e!=="activity"||Fn(g.id)},[_e,h,Fn,g,Mt]),i.useEffect(()=>{if(!h||typeof EventSource>"u")return;const z=new URLSearchParams;r&&z.set("projectId",r);const Ae=`/api/events${z.size>0?`?${z.toString()}`:""}`,Ge=()=>{As(Zn.current)},kt=us=>{Ge();const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un?.id&&p(ni=>ni.map(Gs=>Gs.id===un.id?{...Gs,...un}:Gs))}catch{}vn.current&&Ht(vn.current.id)},An=us=>{Ge(),vn.current&&Ht(vn.current.id)},Vt=()=>{Ge(),vn.current&&Ht(vn.current.id)},Nn=us=>{Ge(),vn.current&&Ht(vn.current.id)},Xe=us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un&&un.featureId&&(ci(un.featureId),wi(un.featureId),un.milestoneId&&On(un.milestoneId))}catch{}},lt=us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un&&un.featureId&&(ci(un.featureId),wi(un.featureId),un.milestoneId&&On(un.milestoneId),vn.current&&Ht(vn.current.id))}catch{}},Tt=us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un&&un.milestoneId&&(xs(un.milestoneId),On(un.milestoneId))}catch{}},Ln=us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);un&&un.milestoneId&&(ds(un.milestoneId),xs(un.milestoneId),On(un.milestoneId))}catch{}};return yi(Ae,{events:{"mission:updated":kt,"slice:updated":An,"feature:updated":Vt,"milestone:updated":Nn,"mission:event":us=>{Ge();const ts=vn.current;if(!ts||de.current!=="activity")return;const un=vs(),ni=us;if(ni.data)try{const Gs=JSON.parse(ni.data);if(!s4(Gs)||Gs.missionId!==ts.id||!Rf(Gs.eventType,nt.current))return;zt(mi=>{const la=mi.filter(ee=>ee.id!==Gs.id);return[Gs,...la].slice(0,100)}),Oe(mi=>mi+1),un&&requestAnimationFrame(()=>{const mi=kn.current;mi&&(mi.scrollTop=0)})}catch{}},"validator-run:started":Xe,"validator-run:completed":lt,"milestone:validation:updated":Tt,"assertion:created":Ln,"assertion:updated":Ln,"assertion:deleted":Ln,"assertion:linked":Ln,"assertion:unlinked":Ln,"fix-feature:created":us=>{const ts=us;if(ts.data)try{const un=JSON.parse(ts.data);if(un&&un.sourceFeatureId){ci(un.sourceFeatureId);const ni=un?.feature?.sliceId,Gs=vn.current;if(ni&&Gs){const mi=Gs.milestones.find(la=>la.slices.some(ee=>ee.id===ni));mi&&On(mi.id)}vn.current&&Ht(vn.current.id)}}catch{}}}})},[h,vs,Ht,As,r,On]);const Rs=i.useCallback(z=>{A(z.id),K(!1),H({title:z.title,description:z.description||"",status:z.status,autopilotEnabled:z.autopilotEnabled??!1})},[]),In=i.useCallback(()=>{A(null),K(!1),H(Af)},[]),rs=i.useCallback(async()=>{if(!T.title.trim()){a("Mission title is required","error");return}try{if(se(!0),_)await _1({title:T.title.trim(),description:T.description.trim()||void 0,autopilotEnabled:T.autopilotEnabled},r),a("Mission created","success");else if(U){const z={title:T.title.trim(),description:T.description.trim()||void 0,status:T.status,autopilotEnabled:T.autopilotEnabled};T.autopilotEnabled&&(z.autoAdvance=!0),await M1(U,z,r),a("Mission updated","success"),g?.id===U&&await Ht(U)}await bn(),In()}catch(z){a(Se(z)||"Failed to save mission","error")}finally{se(!1)}},[T,_,U,a,bn,Ht,g,In,r]),Ns=i.useCallback(async z=>{try{await A1(z,r),a("Mission deleted","success"),g?.id===z&&w(null),await bn(),Ze(null)}catch(Ae){a(Se(Ae)||"Failed to delete mission","error")}},[a,bn,g,r]),ys=i.useCallback(()=>{ye(!0),X(null),ke(Td)},[]),cs=i.useCallback(z=>{X(z.id),ye(!1),ke({title:z.title,description:z.description||"",status:z.status,dependencies:z.dependencies})},[]),ss=i.useCallback(()=>{X(null),ye(!1),ke(Td)},[]),te=i.useCallback(async()=>{if(!le.title.trim()){a("Milestone title is required","error");return}try{se(!0),He&&g?(await T1(g.id,{title:le.title.trim(),description:le.description.trim()||void 0,dependencies:le.dependencies},r),a("Milestone created","success")):k&&(await P1(k,{title:le.title.trim(),description:le.description.trim()||void 0,status:le.status,dependencies:le.dependencies},r),a("Milestone updated","success")),await Ht(g.id),ss()}catch(z){a(Se(z)||"Failed to save milestone","error")}finally{se(!1)}},[le,He,k,g,a,Ht,ss,T.title,r]),we=i.useCallback(async z=>{try{await $1(z,r),a("Milestone deleted","success"),await Ht(g.id),Ze(null)}catch(Ae){a(Se(Ae)||"Failed to delete milestone","error")}},[a,Ht,g,r]),P=i.useCallback(z=>{Pe(z),It(!0),M(Ae=>{const Ge=new Set(Ae);return!Ge.has(z)?(Ge.add(z),Hc(z,r).then(An=>{gt(Vt=>{const Nn=new Map(Vt);return Nn.set(z,An),Nn})}).catch(()=>{}),qc(z,r).then(An=>{Zt(Vt=>{const Nn=new Map(Vt);return Nn.set(z,An),Nn})}).catch(()=>{})):Ge.delete(z),Ge})},[r]),Ce=i.useCallback(z=>{xe(z),q(!0),ne(null),Z(Pd)},[]),qe=i.useCallback(z=>{ne(z.id),q(!1),Z({title:z.title,description:z.description||"",status:z.status})},[]),et=i.useCallback(()=>{ne(null),q(!1),xe(null),Z(Pd)},[]),mt=i.useCallback(async()=>{if(!fe.title.trim()){a("Slice title is required","error");return}try{se(!0),re&&L?(await D1(L,{title:fe.title.trim(),description:fe.description.trim()||void 0},r),a("Slice created","success")):je&&(await L1(je,{title:fe.title.trim(),description:fe.description.trim()||void 0,status:fe.status},r),a("Slice updated","success")),await Ht(g.id),et()}catch(z){a(Se(z)||"Failed to save slice","error")}finally{se(!1)}},[fe,re,je,L,g,a,Ht,et,r]),Nt=i.useCallback(async z=>{try{await O1(z,r),a("Slice deleted","success"),await Ht(g.id),Ze(null)}catch(Ae){a(Se(Ae)||"Failed to delete slice","error")}},[a,Ht,g,r]),Pt=i.useCallback(async z=>{try{await F1(z,r),a("Slice activated","success"),await Ht(g.id)}catch(Ae){a(Se(Ae)||"Failed to activate slice","error")}},[a,Ht,g,r]),an=i.useCallback(z=>{$(Ae=>{const Ge=new Set(Ae);return Ge.has(z)?Ge.delete(z):Ge.add(z),Ge})},[]),Cn=i.useCallback(z=>{rt(z),Ve(!0),B(null),ze($d)},[]),ie=i.useCallback(z=>{B(z.id),Ve(!1),ze({title:z.title,description:z.description||"",acceptanceCriteria:z.acceptanceCriteria||"",status:z.status})},[]),$e=i.useCallback(()=>{B(null),Ve(!1),rt(null),ze($d)},[]),Qe=i.useCallback(async()=>{if(!pe.title.trim()){a("Feature title is required","error");return}try{se(!0),ae&&Te?(await z1(Te,{title:pe.title.trim(),description:pe.description.trim()||void 0,acceptanceCriteria:pe.acceptanceCriteria.trim()||void 0},r),a("Feature created","success")):he&&(await B1(he,{title:pe.title.trim(),description:pe.description.trim()||void 0,acceptanceCriteria:pe.acceptanceCriteria.trim()||void 0,status:pe.status},r),a("Feature updated","success")),await Ht(g.id),$e()}catch(z){a(Se(z)||"Failed to save feature","error")}finally{se(!1)}},[pe,ae,he,Te,g,a,Ht,$e,r]),Ft=i.useCallback(async z=>{try{await U1(z,r),a("Feature deleted","success"),await Ht(g.id),Ze(null)}catch(Ae){a(Se(Ae)||"Failed to delete feature","error")}},[a,Ht,g,r]),cn=i.useCallback(async()=>{if(!Be||!Re.trim()){a("Task ID is required","error");return}try{await H1(Be,Re.trim(),r),a("Feature linked to task","success"),await Ht(g.id),ce(null),Le("")}catch(z){a(Se(z)||"Failed to link feature to task","error")}},[Be,Re,a,Ht,g,r]),pn=i.useCallback(async z=>{try{await q1(z,r),a("Feature unlinked from task","success"),await Ht(g.id)}catch(Ae){a(Se(Ae)||"Failed to unlink feature","error")}},[a,Ht,g,r]),jn=i.useCallback(async z=>{try{se(!0),await V1(z,void 0,void 0,r),a("Feature triaged — task created","success"),await Ht(g.id)}catch(Ae){a(Se(Ae)||"Failed to triage feature","error")}finally{se(!1)}},[a,Ht,g,r]),Un=i.useCallback(async z=>{J(z);try{const Ae=await k0(z,r);St({featureId:z,enrichedDescription:Ae.description})}catch{await jn(z)}finally{J(null)}},[jn,r]),gs=i.useCallback(async()=>{wt&&(St(null),await jn(wt.featureId))},[jn,wt]),bs=i.useCallback(()=>{St(null)},[]),is=i.useCallback(async z=>{try{se(!0);const Ae=await W1(z,r);a(`Triaged ${Ae.count} feature${Ae.count!==1?"s":""}`,"success"),await Ht(g.id)}catch(Ae){a(Se(Ae)||"Failed to triage slice features","error")}finally{se(!1)}},[a,Ht,g,r]),ds=i.useCallback(async z=>{try{const Ae=await Hc(z,r);gt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),xs=i.useCallback(async z=>{try{const Ae=await qc(z,r);Zt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),ra=i.useCallback(async z=>{if(!ge.title.trim()||!ge.assertion.trim()){a("Title and assertion text are required","error");return}try{se(!0),await G1(z,{title:ge.title.trim(),assertion:ge.assertion.trim(),status:ge.status},r),a("Assertion created","success"),await ds(z),await xs(z),pt(!1),st({title:"",assertion:"",status:"pending"})}catch(Ae){a(Se(Ae)||"Failed to create assertion","error")}finally{se(!1)}},[ge,a,ds,xs,r]),Jn=i.useCallback(z=>{Ie(z.id),st({title:z.title,assertion:z.assertion,status:z.status})},[]),Ui=i.useCallback(()=>{Ie(null),pt(!1),st({title:"",assertion:"",status:"pending"})},[]),Hi=i.useCallback(async(z,Ae)=>{if(!ge.title.trim()||!ge.assertion.trim()){a("Title and assertion text are required","error");return}try{se(!0),await K1(z,{title:ge.title.trim(),assertion:ge.assertion.trim(),status:ge.status},r),a("Assertion updated","success"),await ds(Ae),await xs(Ae),Ui()}catch(Ge){a(Se(Ge)||"Failed to update assertion","error")}finally{se(!1)}},[ge,a,ds,xs,Ui,r]),Zs=i.useCallback(async z=>{try{const Ae=await Q1(z,r);nn(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),ja=i.useCallback(async z=>{const Ae=vt!==z;Ut(Ge=>Ge===z?null:z),Ae&&await Zs(z)},[vt,Zs]),Na=i.useCallback(z=>{Ut(z),Zs(z),requestAnimationFrame(()=>{const Ae=document.querySelector(`[data-mission-assertion-id="${z}"]`);Ae instanceof HTMLElement&&typeof Ae.scrollIntoView=="function"&&Ae.scrollIntoView({behavior:"smooth",block:"center"})})},[Zs]),Ya=i.useCallback(async(z,Ae)=>{try{sn(Ge=>new Set(Ge).add(Ae)),await J1(z,Ae,r),a("Feature linked to assertion","success"),await Zs(Ae),Qt(null)}catch(Ge){a(Se(Ge)||"Failed to link feature","error")}finally{sn(Ge=>{const kt=new Set(Ge);return kt.delete(Ae),kt})}},[a,Zs,r]),Qa=i.useCallback(async(z,Ae)=>{const Ge=`${z}-${Ae}`;try{xn(kt=>new Set(kt).add(Ge)),await Y1(z,Ae,r),a("Feature unlinked from assertion","success"),await Zs(Ae)}catch(kt){a(Se(kt)||"Failed to unlink feature","error")}finally{xn(kt=>{const An=new Set(kt);return An.delete(Ge),An})}},[a,Zs,r]),Mn=i.useCallback(async z=>{try{Bt(Ge=>new Set(Ge).add(z)),await X1(z,r),a("Validation triggered","success");const Ae=await ch(z,r);bt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch(Ae){a(Se(Ae)||"Failed to trigger validation","error")}finally{Bt(Ae=>{const Ge=new Set(Ae);return Ge.delete(z),Ge})}},[a,r]),ci=i.useCallback(async z=>{try{const Ae=await ch(z,r);bt(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),wi=i.useCallback(async z=>{try{const Ae=await Z1(z,{limit:10},r);Sn(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),Ai=i.useCallback(z=>{const Ae=vn.current;if(Ae){for(const Ge of Ae.milestones)for(const kt of Ge.slices)if(kt.features.find(Vt=>Vt.id===z)){M(Vt=>{const Nn=new Set(Vt);return Nn.add(Ge.id),Nn}),$(Vt=>{const Nn=new Set(Vt);return Nn.add(kt.id),Nn}),en(z),Pe(Ge.id),ci(z),wi(z),requestAnimationFrame(()=>{const Vt=document.querySelector(`[data-mission-feature-id="${z}"]`);Vt instanceof HTMLElement&&typeof Vt.scrollIntoView=="function"&&Vt.scrollIntoView({behavior:"smooth",block:"center"})});return}}},[ci,wi]),Sa=i.useCallback(async z=>{try{const Ae=await e0(z,r);Ne(Ge=>{const kt=new Map(Ge);return kt.set(z,Ae),kt})}catch{}},[r]),Xa=i.useCallback(async z=>{Ot===z?en(null):(en(z),await ci(z),await wi(z))},[Ot,ci,wi]),Za=i.useCallback(async z=>{dn===z?Jt(null):(Jt(z),await Sa(z))},[dn,Sa]),Ca=i.useCallback(async z=>{try{await t0(z,r),a("Mission resumed","success"),await Ht(z),bn()}catch(Ae){a(Se(Ae)||"Failed to resume mission","error")}},[a,Ht,bn,r]),Ea=i.useCallback(async z=>{try{const Ge=(await n0(z,r)).pausedTaskIds?.length??0;a(`Mission stopped (${Ge} task${Ge!==1?"s":""} paused)`,"success"),await Ht(z),bn()}catch(Ae){a(Se(Ae)||"Failed to stop mission","error")}},[a,Ht,bn,r]),_a=i.useCallback(async z=>{try{await s0(z,r),a("Mission started — first slice activated","success"),await Ht(z),bn()}catch(Ae){a(Se(Ae)||"Failed to start mission","error")}},[a,Ht,bn,r]),er=i.useCallback(async(z,Ae)=>{try{await i0(z,{enabled:Ae},r),a(Ae?"Autopilot enabled":"Autopilot disabled","success"),await Ht(z),bn()}catch(Ge){a(Se(Ge)||"Failed to update autopilot","error")}},[a,Ht,bn,r]),Ma=i.useCallback(z=>{ut("structure"),Pe(null),at(null),zt([]),Oe(0),Xt("all"),Pn(new Set),Ht(z.id)},[Ht]),di=i.useCallback(()=>{w(null),Pe(null),at(null),ut("structure"),zt([]),Oe(0),Xt("all"),Pn(new Set),bn()},[bn]),ki=At.length<G,Ds=g?.autopilotState??"inactive",tr=Ds==="watching"||Ds==="activating",qi=r4(Ds,g?.lastAutopilotActivityAt),nr=i.useRef(g?.id??null);i.useEffect(()=>{const z=nr.current,Ae=g?.id??null;nr.current=Ae,!(!h||!j||!Ae||z===Ae)&&C({type:"view",revert:di})},[di,h,j,C,g?.id]);const ei=i.useMemo(()=>!Ke||!ve||!Dd(Ke)?null:Ke.rollup.milestoneId===ve?Ke:null,[ve,Ke]),Gr=i.useMemo(()=>{const z=new Map;for(const Ae of ei?.validationTelemetry.validationRounds??[]){const Ge=z.get(Ae.featureId);(!Ge||Ae.startedAt>Ge.startedAt)&&z.set(Ae.featureId,Ae)}return z},[ei]),Kr=i.useCallback(()=>{!g||ot||!ki||Fn(g.id,{append:!0})},[ot,ki,Fn,g]),Jr=i.useCallback(z=>{Pn(Ae=>{const Ge=new Set(Ae);return Ge.has(z)?Ge.delete(z):Ge.add(z),Ge})},[]),oa=i.useCallback(z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),rs())},[rs]),Vi=i.useCallback(z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),te())},[te]),sr=i.useCallback(z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),mt())},[mt]),ir=i.useCallback(z=>{z.key==="Enter"&&!z.shiftKey&&(z.preventDefault(),Qe())},[Qe]),Yr=i.useRef(null);if(i.useEffect(()=>{if(!h)return;const z=Ae=>{Ae.key==="Escape"&&s()};return document.addEventListener("keydown",z),()=>document.removeEventListener("keydown",z)},[h,s]),!h)return null;const ar=()=>g?t.jsxs("div",{className:"mission-detail",children:[t.jsxs("div",{className:"mission-detail__header",children:[t.jsxs("div",{className:"mission-detail__title-row",children:[t.jsxs("div",{className:"mission-detail__title-text",children:[tr&&t.jsx("span",{className:"mission-detail__autopilot-dot",title:"Autopilot watching"}),t.jsx("h3",{className:"mission-detail__title",children:g.title})]}),t.jsx("span",{className:"mission-status-badge",style:{backgroundColor:(lo[g.status]||lo.planning).bg,color:(lo[g.status]||lo.planning).text},children:g.status})]}),g.description&&t.jsx("p",{className:"mission-detail__description",children:g.description}),t.jsx("div",{className:"mission-detail__meta",children:t.jsxs("span",{className:"mission-detail__meta-info",children:[g.milestones.length," milestones"]})}),t.jsxs("div",{className:"mission-detail__autopilot",children:[t.jsxs("div",{className:"mission-detail__autopilot-toggle",children:[t.jsxs("label",{className:"mission-toggle","data-testid":"mission-autopilot-toggle",children:[t.jsx("input",{type:"checkbox",checked:g.autopilotEnabled??!1,onChange:z=>er(g.id,z.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(ls,{size:14,className:"mission-detail__autopilot-icon"}),"Autopilot"]})]}),t.jsxs("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(Cl[Ds]||Cl.inactive).bg,color:(Cl[Ds]||Cl.inactive).text},"data-testid":"autopilot-state-badge",children:[tr&&t.jsx("span",{className:"mission-detail__autopilot-pulse"}),Ds]})]}),qi&&t.jsx("span",{className:"mission-detail__autopilot-activity mission-relative-time",children:qi})]}),t.jsxs("div",{className:"mission-detail__actions",children:[g.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ea(g.id),title:"Stop mission","aria-label":"Stop mission",children:t.jsx($i,{size:14})}),g.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ca(g.id),title:"Resume mission","aria-label":"Resume mission",children:t.jsx(os,{size:14})}),g.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>_a(g.id),title:"Start mission","aria-label":"Start mission",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Rs(g),title:"Edit mission","aria-label":"Edit mission",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"mission",id:g.id}),title:"Delete mission","aria-label":"Delete mission",children:t.jsx(Tn,{size:14})})]})]}),U===g.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:z=>H({...T,title:z.target.value}),onKeyDown:oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:z=>H({...T,description:z.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:z=>H({...T,status:z.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:T.autopilotEnabled,onChange:z=>H({...T,autopilotEnabled:z.target.checked})}),t.jsx(ls,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:In,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-detail__tabs",role:"tablist","aria-label":"Mission detail tabs",children:[t.jsx("button",{className:`mission-btn ${_e==="structure"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>ut("structure"),role:"tab","aria-selected":_e==="structure","data-testid":"mission-tab-structure",children:"Structure"}),t.jsxs("button",{className:`mission-btn ${_e==="activity"?"mission-btn--primary":"mission-btn--ghost"} mission-btn--sm mission-detail__tab`,onClick:()=>ut("activity"),role:"tab","aria-selected":_e==="activity","data-testid":"mission-tab-activity",children:["Activity (",G,")"]})]}),_e==="structure"?t.jsxs("div",{className:"mission-detail__milestones",children:[g.milestones.map(z=>{const Ae=ei?.rollup.milestoneId===z.id?ei:null,Ge=Ae?.rollup??hn.get(z.id),kt=Ae?.validationTelemetry.validationRounds??[],An=Ae?.fixFeatures??[],Vt=Ef[Ge?.state??"not_started"]??Ef.not_started,Nn=Ge&&(Ge.state==="blocked"||Ge.state==="failed")?Ae?.validationTelemetry.validationRounds.find(Xe=>Xe.blockedReason)?.blockedReason:void 0;return t.jsxs("div",{className:"mission-milestone",children:[t.jsxs("div",{className:"mission-milestone__header",onClick:()=>P(z.id),children:[t.jsx("button",{className:"mission-milestone__expand",children:O.has(z.id)?t.jsx(gn,{size:16}):t.jsx(qn,{size:16})}),t.jsx(Fa,{size:16,className:"mission-milestone__icon"}),t.jsx("span",{className:"mission-milestone__title",children:z.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Sf[z.status].bg,color:Sf[z.status].text},children:z.status}),t.jsxs("span",{className:"mission-milestone__count",children:[z.slices.length," slices"]}),t.jsx(_f,{state:Z$(z.interviewState)}),Ge&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},title:"Validation state",children:Mf(Ge.state)}),Ge.totalAssertions>0&&t.jsx("div",{className:"mission-milestone__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-milestone__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})})]}),z.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>dt({type:"milestone",id:z.id,title:z.title}),title:"Plan milestone","aria-label":"Plan milestone",children:t.jsx(xa,{size:14})}),t.jsxs("div",{className:"mission-milestone__actions",onClick:Xe=>Xe.stopPropagation(),children:[t.jsx("button",{className:"mission-icon-btn",onClick:()=>Ce(z.id),title:"Add slice",children:t.jsx($n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>cs(z),title:"Edit milestone",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"milestone",id:z.id}),title:"Delete milestone",children:t.jsx(Tn,{size:14})})]})]}),O.has(z.id)&&t.jsxs("div",{className:"mission-milestone__body",children:[(He||k===z.id)&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:le.title,onChange:Xe=>ke({...le,title:Xe.target.value}),onKeyDown:Vi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:le.description,onChange:Xe=>ke({...le,description:Xe.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:te,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),k?"Update":"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ss,children:"Cancel"})]})]}),Ae&&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:[Ae.validationTelemetry.totalRuns," rounds",Ae.validationTelemetry.lastValidatorStatus?` · Last ${Ae.validationTelemetry.lastValidatorStatus}`:""]})]}),Nn&&t.jsxs("div",{className:"mission-blocked-reason",children:[t.jsx("strong",{children:"Blocked reason:"})," ",Nn]}),kt.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:()=>It(Xe=>!Xe),title:We?"Hide validation rounds":"Show validation rounds",children:[We?t.jsx(gn,{size:12}):t.jsx(qn,{size:12}),"Validation rounds (",kt.length,")"]}),We&&t.jsx("div",{className:"mission-validation-rounds__list",children:kt.map(Xe=>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--${Xe.validatorStatus}`,children:Xe.validatorStatus}),t.jsx("span",{className:"mission-validation-round__feature",children:Xe.featureTitle}),t.jsxs("span",{className:"mission-validation-round__attempts",children:["impl #",Xe.implementationAttempt," · reviewer #",Xe.validatorAttempt]})]}),t.jsxs("div",{className:"mission-validation-round__links",children:[t.jsx("span",{className:"mission-validation-round__label",children:"Failed assertions:"}),Xe.failedAssertionIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.failedAssertionIds.map(lt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Na(lt),title:`Jump to assertion ${lt}`,children:lt},`${Xe.roundId}-${lt}`))}):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:"}),Xe.generatedFixFeatureIds.length>0?t.jsx("div",{className:"mission-validation-round__chip-list",children:Xe.generatedFixFeatureIds.map(lt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Ai(lt),title:`Jump to fix feature ${lt}`,children:lt},`${Xe.roundId}-${lt}`))}):t.jsx("span",{className:"mission-validation-round__empty",children:"None"})]}),Xe.blockedReason&&t.jsx("div",{className:"mission-validation-round__blocked-reason",children:Xe.blockedReason})]},Xe.roundId))})]}),An.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:An.map(Xe=>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:()=>Ai(Xe.id),title:`Jump to feature ${Xe.id}`,children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Sl[Xe.status].bg,color:Sl[Xe.status].text},children:Xe.status}),Xe.loopState&&t.jsx("span",{className:`mission-loop-state mission-loop-state--${Xe.loopState}`,children:Xe.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:()=>Ai(Xe.sourceFeatureId),title:`Jump to source feature ${Xe.sourceFeatureId}`,children:Xe.sourceFeatureId}),t.jsx("span",{children:"Run:"}),t.jsx("span",{className:"mission-fix-feature__run",children:Xe.runId})]}),Xe.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:Xe.failedAssertionIds.map(lt=>t.jsx("button",{className:"mission-validation-round__link-chip",onClick:()=>Na(lt),title:`Jump to assertion ${lt}`,children:lt},`${Xe.id}-${lt}`))})]})]},Xe.id))})]})]}),t.jsxs("div",{className:"mission-slices",children:[z.slices.map(Xe=>t.jsxs("div",{className:"mission-slice",children:[t.jsxs("div",{className:"mission-slice__header",onClick:()=>an(Xe.id),children:[t.jsx("button",{className:"mission-slice__expand",children:D.has(Xe.id)?t.jsx(gn,{size:16}):t.jsx(qn,{size:16})}),t.jsx(ru,{size:16,className:"mission-slice__icon"}),t.jsx("span",{className:"mission-slice__title",children:Xe.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Cf[Xe.status].bg,color:Cf[Xe.status].text},children:Xe.status}),t.jsxs("span",{className:"mission-slice__count",children:[Xe.features?.length||0," features"]}),t.jsx(_f,{state:Xe.planState??"not_started"}),Xe.status!=="complete"&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>dt({type:"slice",id:Xe.id,title:Xe.title}),title:"Plan slice","aria-label":"Plan slice",children:t.jsx(xa,{size:14})}),t.jsxs("div",{className:"mission-slice__actions",onClick:lt=>lt.stopPropagation(),children:[Xe.status==="pending"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Pt(Xe.id),title:"Activate slice",children:t.jsx(os,{size:14})}),Xe.status==="active"&&Xe.features?.some(lt=>lt.status==="defined")&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>is(Xe.id),title:"Triage all features",disabled:Q,children:Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ls,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Cn(Xe.id),title:"Add feature",children:t.jsx($n,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>qe(Xe),title:"Edit slice",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"slice",id:Xe.id}),title:"Delete slice",children:t.jsx(Tn,{size:14})})]})]}),D.has(Xe.id)&&t.jsxs("div",{className:"mission-slice__body",children:[re&&L===z.id&&!je&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:fe.title,onChange:lt=>Z({...fe,title:lt.target.value}),onKeyDown:sr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:fe.description,onChange:lt=>Z({...fe,description:lt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:mt,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:et,children:"Cancel"})]})]}),je===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Slice title",value:fe.title,onChange:lt=>Z({...fe,title:lt.target.value}),onKeyDown:sr,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:fe.description,onChange:lt=>Z({...fe,description:lt.target.value}),rows:2}),t.jsxs("select",{value:fe.status,onChange:lt=>Z({...fe,status:lt.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:mt,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:et,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-features",children:[Xe.features?.map(lt=>t.jsxs("div",{className:"mission-feature","data-mission-feature-id":lt.id,children:[t.jsxs("div",{className:"mission-feature__header",children:[t.jsx("button",{className:"mission-feature__expand",onClick:()=>Xa(lt.id),title:Ot===lt.id?"Collapse details":"Expand to show run history",children:Ot===lt.id?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})}),t.jsx(eu,{size:14,className:"mission-feature__icon"}),t.jsx("span",{className:"mission-feature__title",children:lt.title}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Sl[lt.status].bg,color:Sl[lt.status].text},children:lt.status}),lt.loopState&&lt.loopState!=="idle"&&t.jsxs("span",{className:`mission-loop-state mission-loop-state--${lt.loopState}`,title:`Loop state: ${lt.loopState}`,children:[lt.loopState==="implementing"&&"⏳",lt.loopState==="validating"&&"🔄",lt.loopState==="needs_fix"&&"🔧",lt.loopState==="passed"&&"✅",lt.loopState==="blocked"&&"🚫"]}),lt.generatedFromFeatureId&&t.jsx("button",{className:"mission-feature__lineage",onClick:()=>Ai(lt.generatedFromFeatureId),title:`Generated from feature: ${lt.generatedFromFeatureId}`,children:"🔗 Fix"}),(lt.loopState==="validating"||lt.loopState==="needs_fix")&&(()=>{const Tt=Gt.get(lt.id),Ln=Gr.get(lt.id),ti=Tt?.implementationAttemptCount??Ln?.implementationAttempt??lt.implementationAttemptCount??0,ui=Tt?.retryBudgetRemaining??Math.max(0,J$-ti);return t.jsxs("span",{className:"mission-feature__retry-budget",title:"Implementation attempts and remaining retry budget",children:["Attempt ",ti," · ",ui," ",ui===1?"retry":"retries"," left"]})})(),lt.loopState==="implementing"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--validate",onClick:()=>Mn(lt.id),title:"Validate feature",disabled:Lt.has(lt.id),children:Lt.has(lt.id)?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ms,{size:14})}),lt.taskId&&t.jsx("span",{className:"mission-feature__task-link",onClick:()=>o?.(lt.taskId),title:"Click to view task",children:lt.taskId}),t.jsxs("div",{className:"mission-feature__actions",children:[lt.status==="defined"&&!lt.taskId&&t.jsx("button",{className:"mission-icon-btn",onClick:()=>Un(lt.id),title:"Triage — create task",disabled:Q||Fe===lt.id,children:Fe===lt.id?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ls,{size:14})}),lt.taskId?t.jsx("button",{className:"mission-icon-btn",onClick:()=>pn(lt.id),title:"Unlink task",children:t.jsx(Lm,{size:14})}):lt.status!=="defined"?t.jsx("button",{className:"mission-icon-btn",onClick:()=>ce(lt.id),title:"Link to task",children:t.jsx(Sr,{size:14})}):null,t.jsx("button",{className:"mission-icon-btn",onClick:()=>ie(lt),title:"Edit feature",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"feature",id:lt.id}),title:"Delete feature",children:t.jsx(Tn,{size:14})})]})]}),lt.description&&t.jsx("p",{className:"mission-feature__description",children:lt.description}),lt.acceptanceCriteria&&t.jsxs("p",{className:"mission-feature__criteria",children:[t.jsx("strong",{children:"Acceptance:"})," ",lt.acceptanceCriteria]}),wt?.featureId===lt.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:wt.enrichedDescription}),t.jsxs("div",{className:"mission-triage-preview__actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:gs,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):null,"Create Task"]}),t.jsx("button",{className:"btn",onClick:bs,disabled:Q,children:"Cancel"})]})]}),he===lt.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:pe.title,onChange:Tt=>ze({...pe,title:Tt.target.value}),onKeyDown:ir,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:pe.description,onChange:Tt=>ze({...pe,description:Tt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:pe.acceptanceCriteria,onChange:Tt=>ze({...pe,acceptanceCriteria:Tt.target.value}),rows:2}),t.jsxs("select",{value:pe.status,onChange:Tt=>ze({...pe,status:Tt.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:Qe,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$e,children:"Cancel"})]})]}),Ot===lt.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"})}),(Kt.get(lt.id)??[]).map(Tt=>t.jsxs("div",{className:"mission-run",children:[t.jsxs("div",{className:"mission-run__header",onClick:()=>Za(Tt.id),children:[t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-run__status mission-run__status--${Tt.status}`,title:Tt.status,children:Tt.status}),t.jsx("span",{className:"mission-run__time",children:new Date(Tt.startedAt).toLocaleString()}),Tt.completedAt&&t.jsxs("span",{className:"mission-run__duration",children:[Math.round((new Date(Tt.completedAt).getTime()-new Date(Tt.startedAt).getTime())/1e3),"s"]}),Tt.triggerType&&t.jsx("span",{className:"mission-run__trigger",children:Tt.triggerType}),t.jsx("button",{className:"mission-icon-btn",title:dn===Tt.id?"Hide details":"Show details",children:dn===Tt.id?t.jsx(gn,{size:12}):t.jsx(qn,{size:12})})]}),dn===Tt.id&&tn.get(Tt.id)&&t.jsxs("div",{className:"mission-run__details",children:[Tt.summary&&t.jsx("p",{className:"mission-run__summary",children:Tt.summary}),Tt.blockedReason&&t.jsxs("p",{className:"mission-run__blocked-reason",children:[t.jsx("strong",{children:"Blocked:"})," ",Tt.blockedReason]}),tn.get(Tt.id)?.failures&&tn.get(Tt.id).failures.length>0&&t.jsxs("div",{className:"mission-run__failures",children:[t.jsx("span",{className:"mission-run__failures-title",children:"Failed Assertions:"}),tn.get(Tt.id).failures.map(Ln=>t.jsxs("div",{className:"mission-run__failure",children:[t.jsx("span",{className:"mission-run__failure-message",children:Ln.message}),Ln.expected&&t.jsxs("span",{className:"mission-run__failure-expected",children:["Expected: ",Ln.expected]}),Ln.actual&&t.jsxs("span",{className:"mission-run__failure-actual",children:["Actual: ",Ln.actual]})]},Ln.id))]}),(!tn.get(Tt.id)?.failures||tn.get(Tt.id).failures.length===0)&&t.jsx("p",{className:"mission-run__no-failures",children:"No assertion failures"})]})]},Tt.id)),(!Kt.get(lt.id)||Kt.get(lt.id).length===0)&&t.jsx("div",{className:"mission-run-history__empty",children:"No validation runs yet."})]})]},lt.id)),ae&&Te===Xe.id&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Feature title",value:pe.title,onChange:lt=>ze({...pe,title:lt.target.value}),onKeyDown:ir,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:pe.description,onChange:lt=>ze({...pe,description:lt.target.value}),rows:2}),t.jsx("textarea",{placeholder:"Acceptance criteria (optional)",value:pe.acceptanceCriteria,onChange:lt=>ze({...pe,acceptanceCriteria:lt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:Qe,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:$e,children:"Cancel"})]})]}),!ae&&(!Xe.features||Xe.features.length===0)&&t.jsxs("div",{className:"mission-manager__empty mission-features__empty",children:[t.jsx(eu,{size:16}),t.jsx("span",{children:"No fix features generated."})]})]})]})]},Xe.id)),z.slices.length===0&&!re&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(ru,{size:16}),t.jsx("span",{children:"No slices yet"})]}),t.jsxs("div",{className:"mission-assertions",children:[t.jsxs("div",{className:"mission-assertions__header",children:[t.jsx("span",{className:"mission-assertions__title",children:"Assertions"}),Ge&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},children:Mf(Ge.state)}),Ge&&Ge.totalAssertions>0&&t.jsx("div",{className:"mission-assertions__coverage-bar",title:`${Ge.passedAssertions??0} of ${Ge.totalAssertions} assertions passing`,children:t.jsx("div",{className:"mission-assertions__coverage-bar-fill",style:{width:`${(Ge.passedAssertions??0)/Ge.totalAssertions*100}%`,backgroundColor:(Ge.passedAssertions??0)===Ge.totalAssertions?"var(--color-success)":"var(--color-warning)"}})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>{pt(!0),Ie(null),st({title:"",assertion:"",status:"pending"})},title:"Add assertion",children:t.jsx($n,{size:14})})]}),yt&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:ge.title,onChange:Xe=>st({...ge,title:Xe.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text (what should be true when complete)",value:ge.assertion,onChange:Xe=>st({...ge,assertion:Xe.target.value}),rows:2}),t.jsxs("select",{value:ge.status,onChange:Xe=>st({...ge,status:Xe.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:()=>ra(z.id),disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ui,children:"Cancel"})]})]}),t.jsxs("div",{className:"mission-assertions__list",children:[(Array.isArray(be.get(z.id))?be.get(z.id):[]).map(Xe=>t.jsxs("div",{className:"mission-assertion","data-mission-assertion-id":Xe.id,children:[t.jsx("div",{className:"mission-assertion__header",children:$t===Xe.id?t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Assertion title",value:ge.title,onChange:lt=>st({...ge,title:lt.target.value}),autoFocus:!0}),t.jsx("textarea",{placeholder:"Assertion text",value:ge.assertion,onChange:lt=>st({...ge,assertion:lt.target.value}),rows:2}),t.jsxs("select",{value:ge.status,onChange:lt=>st({...ge,status:lt.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:()=>Hi(Xe.id,z.id),disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Save"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Ui,children:"Cancel"})]})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:(El[Xe.status]??El.pending).bg,color:(El[Xe.status]??El.pending).text},children:Xe.status}),t.jsx("span",{className:"mission-assertion__title",children:Xe.title}),(()=>{const Tt=Dt.get(Xe.id)?.length??0;return Tt>0?t.jsxs("span",{className:"mission-assertion__linked-count",title:`${Tt} linked feature${Tt!==1?"s":""}`,children:["(",Tt," linked)"]}):null})(),t.jsx("button",{className:"mission-icon-btn",onClick:()=>ja(Xe.id),title:"Toggle details",children:vt===Xe.id?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Jn(Xe),title:"Edit assertion",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"assertion",id:Xe.id}),title:"Delete assertion",children:t.jsx(Tn,{size:14})})]})}),vt===Xe.id&&t.jsxs("div",{className:"mission-assertion__body",children:[t.jsx("p",{className:"mission-assertion__text",children:Xe.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()=>{vt!==Xe.id&&await ja(Xe.id),Qt(qt===Xe.id?null:Xe.id)},title:"Link a feature",children:[t.jsx(Sr,{size:12}),"Link Feature"]})]}),qt===Xe.id&&t.jsx("div",{className:"mission-assertion__feature-picker",children:t.jsx("div",{className:"mission-assertion__feature-picker-dropdown",children:(()=>{const lt=new Set((Dt.get(Xe.id)??[]).map(Ln=>Ln.id)),Tt=[];return g?.milestones.forEach(Ln=>Ln.slices.forEach(ti=>Tt.push(...ti.features.filter(ui=>!lt.has(ui.id))))),Tt.length===0?t.jsx("span",{className:"mission-assertion__feature-picker-empty",children:"All features already linked"}):Tt.map(Ln=>t.jsxs("button",{className:"mission-assertion__feature-picker-item",onClick:()=>Ya(Ln.id,Xe.id),disabled:on.has(Xe.id),children:[t.jsx("span",{className:"mission-assertion__feature-picker-title",children:Ln.title}),on.has(Xe.id)&&t.jsx(jt,{size:12,className:"spinner"})]},Ln.id))})()})}),(()=>{const lt=Dt.get(Xe.id)??[];return lt.length===0?t.jsx("span",{className:"mission-assertion__linked-empty",children:"No features linked yet"}):lt.map(Tt=>{const Ln=`${Tt.id}-${Xe.id}`,ti=ln.has(Ln);return t.jsxs("div",{className:"mission-assertion__linked-feature",children:[t.jsx("span",{className:"mission-assertion__linked-feature-title",children:Tt.title}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Qa(Tt.id,Xe.id),disabled:ti,title:"Unlink feature",children:ti?t.jsx(jt,{size:12,className:"spinner"}):t.jsx(Lm,{size:12})})]},Tt.id)})})()]})]})]},Xe.id)),(!be.get(z.id)||be.get(z.id)?.length===0)&&!yt&&t.jsx("div",{className:"mission-manager__empty mission-assertions__empty",children:t.jsx("span",{children:"No assertions defined. Add one to define completion criteria."})})]})]})]})]})]},z.id)}),g&&!He&&k===null&&t.jsxs("button",{className:"mission-add-btn",onClick:ys,children:[t.jsx($n,{size:16}),"Add Milestone"]}),He&&k===null&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Milestone title",value:le.title,onChange:z=>ke({...le,title:z.target.value}),onKeyDown:Vi,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:le.description,onChange:z=>ke({...le,description:z.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:te,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:ss,children:"Cancel"})]})]}),g.milestones.length===0&&!He&&t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Fa,{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:Mt,onChange:z=>Xt(z.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:[At.length," of ",G]})]}),!ot&&ki&&t.jsx("div",{className:"mission-detail__activity-load-more mission-detail__activity-load-more--top",children:t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:Kr,"data-testid":"mission-activity-load-more",children:"Load more"})}),ot?t.jsxs("div",{className:"mission-manager__loading mission-detail__activity-loading",children:[t.jsx(jt,{size:18,className:"spinner"}),t.jsx("span",{children:"Loading mission activity..."})]}):At.length===0?t.jsxs("div",{className:"mission-manager__empty",children:[t.jsx(Js,{size:18}),t.jsx("span",{children:"No events yet."})]}):t.jsxs("div",{ref:kn,className:"mission-events","data-testid":"mission-activity-events",children:[At.map(z=>{const Ae=!!(z.metadata&&Object.keys(z.metadata).length>0),Ge=_n.has(z.id);return t.jsxs("div",{className:"mission-event",children:[t.jsxs("div",{className:"mission-event__header",children:[t.jsx("span",{className:`mission-event__type ${i4(z.eventType)}`,children:a4(z.eventType)}),t.jsx("span",{className:"mission-event__time",children:rc(z.timestamp)})]}),t.jsx("p",{className:"mission-event__description",children:z.description}),t.jsx("span",{className:"mission-event__timestamp",children:new Date(z.timestamp).toLocaleString()}),Ae&&t.jsxs("div",{className:"mission-event__metadata",children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Jr(z.id),"data-testid":`mission-event-metadata-${z.id}`,children:[Ge?"Hide":"Show"," metadata"]}),Ge&&t.jsx("pre",{className:"mission-event__metadata-content",children:JSON.stringify(z.metadata,null,2)})]})]},z.id)}),t.jsx("div",{ref:Vn})]})]})]}):null,Aa=z=>{tt(z),Ue(!0)},Wi=()=>{xt.current=Me??null,tt(void 0),Ue(!1)},Je=async z=>{try{await c0(z,r),ft(Ae=>Ae.filter(Ge=>Ge.id!==z))}catch(Ae){if(Ae instanceof Kl&&Ae.status===409){a("Draft is open in another tab","error");return}if(Ae instanceof Kl&&Ae.status===404){ft(Ge=>Ge.filter(kt=>kt.id!==z));return}a(Se(Ae)||"Failed to discard draft","error");return}finally{Ze(null)}},Rt=()=>Ee.map(z=>{const Ae=z.status==="error",Ge=z.status==="generating",kt=X$(z.status);return t.jsxs("div",{className:"mission-list__item mission-list__item--interview",onClick:()=>Aa(z.id),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(ms,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:z.title||"Mission interview"})]}),t.jsx("div",{className:"mission-list__item-tags",children:t.jsx("span",{className:`mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--${z.status}`,children:Q$(z.status)})}),t.jsx("p",{className:"mission-list__item-description",children:Ge?"Generating mission hierarchy from interview context.":Ae?"Interview hit an error. Retry from this list item.":"Interview is waiting for your next response."})]}),t.jsxs("div",{className:"mission-list__item-actions mission-list__resume-actions",onClick:An=>An.stopPropagation(),children:[t.jsxs("button",{className:"mission-btn mission-btn--ghost mission-btn--sm",onClick:()=>Aa(z.id),title:kt,"aria-label":kt,children:[Ge?t.jsx(jt,{size:14,className:"spinner"}):Ae?t.jsx(ps,{size:14}):t.jsx(ms,{size:14}),t.jsx("span",{children:Ae?"Retry":"Resume"})]}),t.jsxs("button",{className:"mission-btn mission-btn--danger mission-btn--sm",onClick:()=>Ze({type:"interview_draft",id:z.id}),title:"Discard draft","aria-label":"Discard draft",children:[t.jsx(Tn,{size:14}),t.jsx("span",{children:"Discard"})]})]})]},z.id)}),rn=(z,Ae)=>z.map(Ge=>{const kt=Ge,An=g?.id===kt.id,Vt=lo[kt.status]||{bg:"",text:""},Nn=kt.summary,Xe=W.get(kt.id),lt=t4(Xe),Tt=!!(Nn&&(Nn.totalMilestones>0||Nn.totalFeatures>0)),Ln=Xe?.totalTasks??0,ti=Xe?.tasksCompleted??0,ui=Xe?.tasksFailed??0,us=Xe?.estimatedCompletionPercent??Nn?.progressPercent??0,ts=Tt||Ln>0||ui>0||!!Xe?.lastActivityAt,un=Ae?.interviewStyle===!0;return t.jsxs("div",{className:`mission-list__item ${An?"mission-list__item--selected":""} ${un?"mission-list__item--interview":""}`,onClick:()=>Ma(Ge),children:[t.jsxs("div",{className:"mission-list__item-content",children:[t.jsxs("div",{className:"mission-list__item-header",children:[t.jsx(Es,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{className:"mission-list__item-title",children:kt.title})]}),t.jsxs("div",{className:"mission-list__item-tags",children:[Ge.autopilotEnabled&&t.jsx("span",{title:"Autopilot enabled",children:t.jsx(ls,{size:12,className:"mission-list__item-autopilot-icon"})}),t.jsx("span",{className:`mission-health-badge mission-health-badge--${lt}`,"data-testid":`mission-health-badge-${kt.id}`,"aria-label":`Mission health: ${lt}`}),t.jsx("span",{className:"mission-status-badge mission-status-badge--sm",style:{backgroundColor:Vt.bg,color:Vt.text},children:kt.status}),un&&t.jsx("span",{className:"mission-status-badge mission-status-badge--sm mission-interview-status mission-interview-status--awaiting_input",children:"Interview in progress"})]}),un?t.jsx("p",{className:"mission-list__item-description",children:"Mission interview is still in progress. Open this mission to continue planning."}):kt.description?t.jsx("p",{className:"mission-list__item-description",children:kt.description}):null,ts&&t.jsxs("div",{className:"mission-list__item-summary",children:[Tt&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"mission-list__item-stat",children:[Nn.completedMilestones,"/",Nn.totalMilestones," milestones"]}),t.jsxs("span",{className:"mission-list__item-stat",children:[Nn.completedFeatures,"/",Nn.totalFeatures," features"]})]}),t.jsxs("span",{className:"mission-list__item-stat","data-testid":`mission-task-stats-${kt.id}`,children:[ti,"/",Ln," tasks"]}),ui>0&&t.jsxs("button",{className:"mission-list__item-failed",onClick:ni=>{ni.stopPropagation(),Ma(Ge)},"data-testid":`mission-failed-${kt.id}`,title:"View mission failures",children:[ui," failed"]}),t.jsx("div",{className:`mission-list__item-progress mission-list__item-progress--${lt}`,children:t.jsx("div",{className:"mission-list__item-progress-bar",style:{width:`${us}%`}})})]}),ts&&t.jsx("div",{className:"mission-list__item-activity",children:t.jsxs("span",{className:"mission-relative-time","data-testid":`mission-last-activity-${kt.id}`,children:["Activity ",rc(Xe?.lastActivityAt)]})})]}),t.jsxs("div",{className:"mission-list__item-actions",onClick:ni=>ni.stopPropagation(),children:[kt.status==="active"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ea(kt.id),title:"Stop mission",children:t.jsx($i,{size:14})}),kt.status==="blocked"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>Ca(kt.id),title:"Resume mission",children:t.jsx(os,{size:14})}),kt.status==="planning"&&t.jsx("button",{className:"mission-icon-btn mission-icon-btn--success",onClick:()=>_a(kt.id),title:"Start mission",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"mission-icon-btn",onClick:()=>Rs(Ge),title:"Edit mission",children:t.jsx(Hs,{size:14})}),t.jsx("button",{className:"mission-icon-btn mission-icon-btn--danger",onClick:()=>Ze({type:"mission",id:kt.id}),title:"Delete mission",children:t.jsx(Tn,{size:14})})]})]},kt.id)}),es=({hideBottomButtons:z=!1}={})=>{const Ae=f.filter(Vt=>Vt.interviewState==="in_progress"),Ge=f.filter(Vt=>Vt.interviewState!=="in_progress"),kt=j&&f.length>0&&!_,An=!z&&!kt;return t.jsxs("div",{className:"mission-list",children:[_&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Vt=>H({...T,title:Vt.target.value}),onKeyDown:oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Vt=>H({...T,description:Vt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Create"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:In,children:"Cancel"})]})]}),kt&&t.jsx("div",{className:"mission-list__top-action",children:t.jsxs("button",{className:"btn btn-sm btn-task-create mission-list__primary-cta",onClick:()=>Ue(!0),children:[t.jsx(ms,{size:14}),"Plan New Mission"]})}),rn(Ae,{interviewStyle:!0}),rn(Ge),Ee.length>0&&t.jsxs("div",{className:"mission-list__drafts-group",children:[t.jsxs("div",{className:"mission-list__drafts-header",children:[t.jsx(ms,{size:16,className:"mission-list__item-icon"}),t.jsx("span",{children:"Drafts"}),t.jsxs("span",{children:["(",Ee.length,")"]})]}),Rt()]}),U&&t.jsxs("div",{className:"mission-form-card",children:[t.jsx("input",{type:"text",placeholder:"Mission title",value:T.title,onChange:Vt=>H({...T,title:Vt.target.value}),onKeyDown:oa,autoFocus:!0}),t.jsx("textarea",{placeholder:"Description (optional)",value:T.description,onChange:Vt=>H({...T,description:Vt.target.value}),rows:2}),t.jsxs("div",{className:"mission-form-card__row",children:[t.jsxs("select",{value:T.status,onChange:Vt=>H({...T,status:Vt.target.value}),children:[t.jsx("option",{value:"planning",children:"Planning"}),t.jsx("option",{value:"active",children:"Active"}),t.jsx("option",{value:"blocked",children:"Blocked"}),t.jsx("option",{value:"complete",children:"Complete"}),t.jsx("option",{value:"archived",children:"Archived"})]}),t.jsxs("label",{className:"mission-checkbox",children:[t.jsx("input",{type:"checkbox",checked:T.autopilotEnabled,onChange:Vt=>H({...T,autopilotEnabled:Vt.target.checked})}),t.jsx(ls,{size:12})," Autopilot"]})]}),t.jsxs("div",{className:"mission-form-card__actions",children:[t.jsxs("button",{className:"mission-btn mission-btn--primary",onClick:rs,disabled:Q,children:[Q?t.jsx(jt,{size:14,className:"spinner"}):t.jsx(ks,{size:14}),"Update"]}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:In,children:"Cancel"})]})]}),f.length===0&&Ee.length===0&&!_&&t.jsxs("div",{className:"mission-manager__empty mission-manager__empty--large mission-manager__empty--mission",children:[t.jsx(Es,{size:32}),t.jsx("h3",{className:"mission-manager__empty-title",children:"No missions yet"}),t.jsx("p",{className:"mission-manager__empty-body",children:"Missions are large initiatives that bundle milestones, slices, and features into a single plan. Plan a mission to break down a goal end-to-end and let agents work through it autopilot-style."}),t.jsxs("button",{className:"btn btn-sm btn-primary mission-manager__empty-cta",onClick:()=>Ue(!0),children:[t.jsx(ms,{size:14}),"Plan New Mission"]})]}),!_&&t.jsx("div",{className:"mission-list__footer",children:An&&t.jsx("div",{className:"mission-list__footer-actions",children:t.jsxs("button",{className:"mission-add-btn",onClick:()=>Ue(!0),children:[t.jsx(ms,{size:16}),"Plan New Mission"]})})})]})},Hn=()=>{const z=me?.type==="interview_draft";return t.jsx("div",{className:"mission-confirm-panel mission-confirm-panel--danger",children:t.jsxs("div",{className:"mission-confirm-panel__content",children:[t.jsx("p",{children:z?"Discard this interview draft? This removes the saved draft and cannot be undone.":`Delete this ${me?.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()=>{me&&(me.type==="mission"?await Ns(me.id):me.type==="milestone"?await we(me.id):me.type==="slice"?await Nt(me.id):me.type==="feature"?await Ft(me.id):me.type==="interview_draft"&&await Je(me.id))},children:z?"Discard":"Delete"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>Ze(null),children:"Cancel"})]})]})})},Bs=()=>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:Re,onChange:z=>Le(z.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(z=>t.jsxs("button",{className:"mission-task-suggestions__item",onClick:()=>Le(z.id),children:[z.id,": ",z.title||"Untitled"]},z.id))})]}),t.jsxs("div",{className:"mission-confirm-panel__actions",children:[t.jsx("button",{className:"mission-btn mission-btn--primary",onClick:cn,children:"Link"}),t.jsx("button",{className:"mission-btn mission-btn--ghost",onClick:()=>{ce(null),Le("")},children:"Cancel"})]})]})}),rr=t.jsxs("div",{ref:Yr,className:`mission-manager mission-manager--desktop${n?" mission-manager--inline":""}`,role:n?void 0:"dialog","aria-modal":n?void 0:!0,"aria-label":n?void 0:"Mission Manager","data-testid":"mission-manager-dialog",children:[t.jsxs("div",{className:`mission-manager__header${n?" mission-manager__header--inline":""}`,children:[t.jsxs("div",{className:"mission-manager__header-title",children:[g&&t.jsx("button",{className:"mission-manager__back-btn",onClick:di,title:"Back to missions","aria-label":"Back to missions list","data-testid":"mission-back-btn",children:t.jsx(pc,{size:18})}),t.jsx(Es,{size:18,className:"mission-manager__header-icon"}),t.jsxs("h2",{className:"mission-manager__title","data-testid":"mission-header-title",children:[t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--desktop",children:"Missions"}),t.jsx("span",{className:"mission-manager__title-text mission-manager__title-text--mobile",children:g?g.title:"Missions"})]})]}),!n&&t.jsx("button",{className:"modal-close",onClick:s,title:"Close","aria-label":"Close Mission Manager","data-testid":"mission-close-btn",children:t.jsx(mn,{size:18})})]}),j?t.jsxs("div",{className:"mission-manager__body mission-manager__body--stacked",children:[v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ar():es(),me&&Hn(),Be&&Bs()]}):t.jsxs("div",{className:"mission-manager__split",children:[t.jsxs("aside",{className:"mission-manager__sidebar","data-testid":"mission-sidebar","aria-label":"Mission list",style:j?void 0:{width:`${x}px`},children:[t.jsx("div",{className:"mission-manager__sidebar-list",children:v?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading missions..."})]}):es({hideBottomButtons:!0})}),t.jsx("div",{className:"mission-manager__sidebar-footer","data-testid":"mission-sidebar-footer",children:t.jsxs("button",{className:"btn btn-primary mission-manager__sidebar-cta",onClick:()=>Ue(!0),title:"Plan New Mission","aria-label":"Plan New Mission",children:[t.jsx(ms,{size:14}),"Plan New Mission"]})})]}),!j&&t.jsx("div",{className:"mission-manager__sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":jl,"aria-valuemax":Nl,"aria-valuenow":x,"aria-label":"Resize mission sidebar",tabIndex:0,onPointerDown:F,onKeyDown:E}),t.jsxs("div",{className:"mission-manager__detail-pane",children:[y?t.jsxs("div",{className:"mission-manager__loading",children:[t.jsx(jt,{size:24,className:"spinner"}),t.jsx("span",{children:"Loading mission details..."})]}):g?ar():t.jsxs("div",{className:"mission-manager__detail-pane-empty","data-testid":"mission-empty-detail",children:[t.jsx(Es,{size:32}),t.jsx("span",{children:"Select a mission to view details"})]}),me&&Hn(),Be&&Bs()]})]})]}),Qr=t.jsx(L$,{isOpen:ct,onClose:Wi,onMissionCreated:()=>{bn(),a("Mission created from AI interview","success")},projectId:r,resumeSessionId:Me}),Pc=Ye?t.jsx(W$,{isOpen:!0,onClose:()=>dt(null),onApplied:()=>{dt(null),g&&Ht(g.id)},targetType:Ye.type,targetId:Ye.id,targetTitle:Ye.title,missionContext:g?.title,projectId:r,resumeSessionId:Ye.resumeSessionId}):null;return n?t.jsxs(t.Fragment,{children:[rr,Qr,Pc]}):t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mission-manager-overlay open",onClick:z=>z.target===z.currentTarget&&s(),"data-testid":"mission-manager-overlay",role:"dialog","aria-modal":"true",children:rr}),Qr,Pc]})}const l4={pre:({children:e,...n})=>t.jsx("pre",{...n,className:"mailbox-markdown-pre",children:e}),table:({children:e,...n})=>t.jsx("table",{...n,className:"mailbox-markdown-table",children:e}),a:({children:e,...n})=>t.jsx("a",{...n,target:"_blank",rel:"noopener noreferrer",children:e})},If=i.memo(function({content:n,className:s,testId:a}){const r=s?`mailbox-markdown ${s}`:"mailbox-markdown";return t.jsx("div",{className:r,"data-testid":a,children:t.jsx(xi,{remarkPlugins:[vi],components:l4,children:n})})}),_l=2e3;function Tf({recipient:e,replyContext:n,agents:s=[],projectId:a,onSend:r,onCancel:o,addToast:l,isLoadingAgents:c=!1}){const[d,u]=i.useState(e?.id??""),[m,h]=i.useState(e?.type??"agent"),[f,p]=i.useState(""),[g,w]=i.useState(!1),[v,b]=i.useState(!1),[y,S]=i.useState(null),j=i.useRef(null),C=i.useMemo(()=>s.find(U=>U.id===d),[s,d]),x=i.useMemo(()=>e?s.find(U=>U.id===e.id):void 0,[s,e]),N=m==="agent",R=N&&C?.runtimeConfig?.messageResponseMode==="immediate",F=N&&(g||R),E=d.trim()!==""&&f.trim().length>0&&f.length<=_l,_=i.useCallback(async()=>{if(!(!E||v)){b(!0),S(null);try{const U=m==="agent"?"user-to-agent":"system",A=n?{replyTo:{messageId:n.messageId}}:void 0,T=F;await T0({toId:d.trim(),toType:m,content:f.trim(),type:U,...A?{metadata:A}:{},...T?{wakeImmediately:!0}:{}},a),r()}catch(U){const A=Se(U)||"Failed to send message";S(A),l?.(A,"error")}finally{b(!1)}}},[E,v,d,m,f,F,n,a,r,l]),K=i.useCallback(U=>{u(U),h("agent")},[]);return i.useEffect(()=>{n&&j.current?.focus()},[n]),i.useEffect(()=>{if(!n||typeof window>"u"||window.visualViewport==null)return;const U=()=>{j.current?.scrollIntoView({block:"center",behavior:"auto"})};return window.visualViewport.addEventListener("resize",U),()=>{window.visualViewport?.removeEventListener("resize",U)}},[n]),t.jsxs("div",{className:"message-composer","data-testid":"message-composer",children:[t.jsxs("div",{className:"message-composer-header",children:[t.jsx("span",{children:n?"Reply":"New Message"}),t.jsx("button",{className:"btn-icon",onClick:o,"aria-label":"Cancel","data-testid":"message-composer-cancel",children:t.jsx(mn,{size:16})})]}),t.jsxs("div",{className:"message-composer-body",children:[!e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-recipient",children:"To:"}),t.jsxs("select",{id:"message-recipient",className:"message-composer-select",value:d,onChange:U=>K(U.target.value),disabled:c||s.length===0,"data-testid":"message-composer-recipient",children:[t.jsx("option",{value:"",children:c?"Loading agents…":s.length===0?"No agents available":"Select agent…"}),s.map(U=>t.jsx("option",{value:U.id,children:U.name||U.id},U.id))]})]}),e&&t.jsxs("div",{className:"message-composer-field",children:[t.jsx("span",{className:"message-composer-label",children:"To:"}),t.jsxs("span",{className:"message-composer-recipient-fixed",children:[t.jsx(Qn,{size:14}),x?.name||e.id]})]}),n&&t.jsxs("div",{className:"message-composer-field","data-testid":"message-composer-reply-context",children:[t.jsx("span",{className:"message-composer-label",children:"Replying to:"}),t.jsx("span",{className:"message-composer-recipient-fixed",children:n.preview?.trim()?n.preview:`Message ${n.messageId}`})]}),t.jsxs("div",{className:"message-composer-field message-composer-field--content",children:[t.jsx("label",{className:"message-composer-label",htmlFor:"message-content",children:"Message:"}),t.jsx("textarea",{id:"message-content",ref:j,className:"message-composer-textarea",placeholder:"Type your message…",value:f,onChange:U=>p(U.target.value),maxLength:_l,rows:4,"data-testid":"message-composer-content"}),t.jsx("div",{className:"message-composer-charcount","data-testid":"message-composer-charcount",children:t.jsxs("span",{className:f.length>_l?"over-limit":"",children:[f.length,"/",_l]})})]}),N&&t.jsx("div",{className:"message-composer-field message-composer-field--wake",children:t.jsxs("label",{className:"message-composer-wake-label",children:[t.jsx("input",{type:"checkbox",checked:F,disabled:R,onChange:U=>w(U.target.checked),"data-testid":"message-composer-wake"}),t.jsxs("span",{children:["Wake agent immediately",t.jsx("span",{className:"message-composer-wake-hint","data-testid":"message-composer-wake-hint",children:R?"(agent is already set to immediate response mode)":"(one-off override for this message only)"})]})]})}),y&&t.jsxs("div",{className:"message-composer-error","data-testid":"message-composer-error",children:[t.jsx(Vs,{size:14}),t.jsx("span",{children:y})]})]}),t.jsxs("div",{className:"message-composer-footer",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:o,"data-testid":"message-composer-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:_,disabled:!E||v,"data-testid":"message-composer-send",children:v?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"spin"}),t.jsx("span",{children:"Sending…"})]}):t.jsxs(t.Fragment,{children:[t.jsx(Da,{size:14}),t.jsx("span",{children:"Send"})]})})]})]})}const Ts="__all_agents__",oc=280,Au=.65,Ld=16,Pf=320;function Ru(e){return Math.max(oc,e*Au)}function Od(e,n){const s=Ru(n);return Math.min(Math.max(e,oc),s)}function $f(e){try{const n=Gn("kb-dashboard-mailbox-sidebar-width",e);if(!n)return Pf;const s=Number(n);if(Number.isFinite(s)&&s>0)return s}catch{}return Pf}function Yi(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function c4(e,n,s){if(n==="user")return e==="dashboard"?"You":`User: ${e}`;if(n==="agent"){const a=s?.get(e)?.trim();return a?a===e?`Agent: ${e}`:`Agent: ${a} (${e})`:`Agent: ${e}`}return"System"}function d4(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 Df(e,n=80){return e.length<=n?e:`${e.slice(0,n)}…`}function Lf(){if(typeof window>"u")return null;const n=new URLSearchParams(window.location.search).get("mailbox-message");return n||(/^#message-(.+)$/.exec(window.location.hash)?.[1]??null)}function co(e){return`mailbox-list-message-${e}`}function Fd(e){return`mailbox-detail-message-${e}`}function u4(e,n){const s=[...e];s.some(o=>o.id===n.id)||s.push(n);const a=new Set([n.id]);let r=!0;for(;r;){r=!1;for(const o of s){const l=o.metadata?.replyTo?.messageId;a.has(o.id)&&l&&!a.has(l)&&(a.add(l),r=!0),l&&a.has(l)&&!a.has(o.id)&&(a.add(o.id),r=!0)}}return s.filter(o=>a.has(o.id)).sort((o,l)=>new Date(o.createdAt).getTime()-new Date(l.createdAt).getTime())}function m4({projectId:e,addToast:n,onUnreadCountChange:s}){const[a,r]=i.useState("inbox"),[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(0),[h,f]=i.useState(!1),[p,g]=i.useState(null),[w,v]=i.useState([]),[b,y]=i.useState(!1),[S,j]=i.useState(null),[C,x]=i.useState(null),[N,R]=i.useState(Ts),[F,E]=i.useState("inbox"),[_,K]=i.useState(null),[U,A]=i.useState(null),[T,H]=i.useState([]),[Q,se]=i.useState("pending"),[O,M]=i.useState([]),[D,$]=i.useState(0),[k,X]=i.useState(null),[le,ke]=i.useState(""),[He,ye]=i.useState(!1),je=i.useMemo(()=>new Map(T.map(J=>[J.id,J.name??""])),[T]),ne=i.useCallback((J,me)=>c4(J,me,je),[je]),Z=oi()==="mobile",re=!Z,[q,L]=i.useState(()=>$f(e)),xe=i.useRef(null),{keyboardOverlap:he,viewportHeight:B,viewportOffsetTop:pe,keyboardOpen:ze}=aa({enabled:Z}),ae=i.useMemo(()=>{if(ze)return{"--keyboard-overlap":`${he}px`,"--vv-offset-top":`${pe}px`,...B!=null?{"--vv-height":`${B}px`}:{}}},[ze,he,B,pe]);i.useEffect(()=>{L($f(e))},[e]),i.useEffect(()=>{if(!re)return;const J=xe.current?.clientWidth;J&&L(me=>Od(me,J))},[re]),i.useEffect(()=>{if(re)try{fs("kb-dashboard-mailbox-sidebar-width",String(q),e)}catch{}},[re,e,q]);const Ve=i.useCallback(J=>{if(!re)return;J.preventDefault();const me=xe.current;if(!me)return;const Ze=me.getBoundingClientRect(),be=$t=>{const Ie=$t.clientX-Ze.left;L(Od(Ie,Ze.width))},gt=()=>{window.removeEventListener("mousemove",be),window.removeEventListener("mouseup",gt)};window.addEventListener("mousemove",be),window.addEventListener("mouseup",gt)},[re]),Te=i.useCallback(J=>{if(!re)return;const me=xe.current?.clientWidth??0,Ze=q/Au+Ld,be=Math.max(me,Ze),gt=Ru(be);if(J.key==="ArrowLeft"||J.key==="ArrowRight"){J.preventDefault();const $t=J.key==="ArrowLeft"?-Ld:Ld;L(Ie=>Od(Ie+$t,be));return}if(J.key==="Home"){J.preventDefault(),L(oc);return}J.key==="End"&&(J.preventDefault(),L(gt))},[re,q]),rt=i.useCallback(async()=>{f(!0);try{const J=await R0({limit:50},e);l(J),m(J.unreadCount),s?.(J.unreadCount)}catch{}finally{f(!1)}},[e,s]),Be=i.useCallback(async()=>{f(!0);try{const J=await I0({limit:50},e);d(J)}catch{}finally{f(!1)}},[e]),ce=i.useCallback(async J=>{f(!0);try{const me=await O0(J,e);K(me)}catch{}finally{f(!1)}},[e]),Re=i.useCallback(async()=>{f(!0);try{const J=await F0(e);A(J)}catch{}finally{f(!1)}},[e]),Le=i.useCallback(async()=>{try{const J=await Ur(void 0,e);H(J)}catch{}},[e]),ct=i.useCallback(async()=>{try{const J=await Nb(e);m(J.unreadCount),s?.(J.unreadCount)}catch{}},[e,s]),Ue=i.useCallback(async J=>{f(!0);try{const me=await ol({status:J==="pending"?"pending":void 0,limit:100},e);if(J==="pending")M(me.requests);else{const[Ze,be,gt]=await Promise.all([ol({status:"approved",limit:100},e),ol({status:"denied",limit:100},e),ol({status:"completed",limit:100},e)]);M([...Ze.requests,...be.requests,...gt.requests].sort(($t,Ie)=>Ie.updatedAt.localeCompare($t.updatedAt)))}$(me.pendingCount)}catch{}finally{f(!1)}},[e]);i.useEffect(()=>{a==="inbox"?rt():a==="outbox"?Be():a==="agents"?Le():a==="approvals"&&Ue(Q)},[a,rt,Be,Le,Ue,Q]),i.useEffect(()=>{if(N===Ts){Re();return}ce(N)},[N,ce,Re]),i.useEffect(()=>{ct()},[ct]),i.useEffect(()=>{Le()},[Le]),i.useEffect(()=>{if(typeof EventSource>"u")return;const J=e?`?projectId=${encodeURIComponent(e)}`:"",me=()=>{ct(),a==="inbox"?rt():a==="outbox"?Be():a==="approvals"&&Ue(Q),N===Ts?Re():N&&ce(N)};return yi(`/api/events${J}`,{events:{"message:sent":me,"message:received":me,"message:read":me,"message:deleted":me,"approval:requested":me,"approval:updated":me,"approval:decided":me}})},[e,a,N,ct,rt,Be,ce,Re,Ue,Q]);const ue=i.useCallback(async J=>{if(g(J),!J.read&&a==="inbox")try{const me=await P0(J.id,e);me&&l(be=>be&&{...be,messages:be.messages.map(gt=>gt.id===me.id?me:gt),unreadCount:Math.max(0,be.unreadCount-1)});const Ze=Math.max(0,u-1);m(Ze),s?.(Ze)}catch{}try{const me=await L0(J.fromId,J.fromType,e);v(me)}catch{v([J])}},[e,u,s,a]);i.useEffect(()=>{const J=Lf();if(!J)return;const me=[...o?.messages??[],...c?.messages??[],..._?.inbox??[],..._?.outbox??[],...U?.messages??[],...w].find(Ze=>Ze.id===J);me&&ue(me)},[o,c,_,U,w,ue]),i.useEffect(()=>{const J=Lf();if(!J)return;const me=document.getElementById(Fd(J));if(!me)return;me.scrollIntoView({behavior:"smooth",block:"center"}),me.classList.add("mailbox-message-highlight");const Ze=window.setTimeout(()=>{me.classList.remove("mailbox-message-highlight")},2e3);return()=>{window.clearTimeout(Ze)}},[p,w]);const oe=i.useCallback(()=>{g(null),v([])},[]),Ee=i.useCallback(async()=>{try{const J=await $0(e);m(0),s?.(0),l(me=>me&&{...me,messages:me.messages.map(Ze=>({...Ze,read:!0})),unreadCount:0}),n?.(`Marked ${J.markedAsRead} messages as read`,"success")}catch{n?.("Failed to mark messages as read","error")}},[e,n,s]),ft=i.useCallback(async J=>{try{await D0(J,e),g(null),v([]),a==="inbox"?rt():a==="outbox"?Be():N===Ts?Re():N&&ce(N),n?.("Message deleted","success")}catch{n?.("Failed to delete message","error")}},[e,a,N,rt,Be,ce,Re,n]),ht=i.useCallback(J=>{j({id:J.fromId,type:J.fromType}),x({messageId:J.id,preview:Df(J.content,120)}),y(!0)},[]),tt=i.useCallback(()=>{y(!1),j(null),x(null),n?.("Message sent","success"),a==="outbox"?Be():a==="agents"&&N===Ts?Re():a==="agents"&&N&&ce(N),ct()},[a,Be,N,ce,Re,n,ct]),xt=i.useCallback(()=>{j(a==="agents"&&N&&N!==Ts?{id:N,type:"agent"}:null),x(null),y(!0)},[a,N]),Me=i.useCallback(()=>{y(!1),j(null),x(null)},[]),Ye=i.useCallback(async J=>{try{const me=await dh(J.id,e);X(me),ke("")}catch{n?.("Failed to load approval request","error")}},[e,n]),dt=i.useCallback(async J=>{if(!(!k||He)){ye(J);try{await z0(k.id,{decision:J,comment:le||void 0},e),await Ue(Q);const me=await dh(k.id,e);X(me),ke(""),n?.(`Request ${J==="approve"?"approved":"denied"}`,"success")}catch{n?.("Failed to submit decision","error")}finally{ye(!1)}}},[k,He,le,e,Ue,Q,n]),wt=()=>{if(!p||b)return null;const J=u4(w,p);return t.jsxs("div",{className:"mailbox-message-detail","data-testid":"mailbox-message-detail",id:Fd(p.id),children:[t.jsxs("div",{className:"mailbox-message-detail-header",children:[Z&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:oe,"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:d4(p.type)}),t.jsx("span",{className:"mailbox-message-time",children:Yi(p.createdAt)})]}),t.jsxs("div",{className:"mailbox-message-detail-actions",children:[p.fromType==="agent"&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ht(p),"data-testid":"mailbox-reply",children:[t.jsx(Zi,{size:14}),t.jsx("span",{children:"Reply"})]}),t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:()=>ft(p.id),"data-testid":"mailbox-delete",children:[t.jsx(Tn,{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(Qn,{size:14}):t.jsx(Ra,{size:14}),ne(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(Qn,{size:14}):t.jsx(Ra,{size:14}),ne(p.toId,p.toType)]})]})]}),J.length>1&&t.jsxs("div",{className:"mailbox-conversation","data-testid":"mailbox-conversation",children:[t.jsx("div",{className:"mailbox-conversation-label",children:"Conversation"}),J.map(me=>{const Ze=me.metadata?.replyTo?.messageId,be=Ze?J.find(gt=>gt.id===Ze):void 0;return t.jsxs("div",{id:Fd(me.id),className:`mailbox-conversation-msg ${me.id===p.id?"current":""}`,children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:ne(me.fromId,me.fromType)}),t.jsx("span",{className:"mailbox-message-time",children:Yi(me.createdAt)})]}),Ze&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":`mailbox-reply-context-${me.id}`,children:["↪ Replying to ",be?Df(be.content,60):`message ${Ze}`]}),t.jsx(If,{content:me.content,className:"mailbox-conversation-msg-body"})]},me.id)})]}),J.length<=1&&t.jsxs(t.Fragment,{children:[p.metadata?.replyTo?.messageId&&t.jsxs("div",{className:"mailbox-reply-context-static","data-testid":"mailbox-selected-reply-context",children:["↪ Replying to message ",p.metadata.replyTo.messageId]}),t.jsx(If,{content:p.content,className:"mailbox-message-body",testId:"mailbox-message-body"})]})]})},St=()=>t.jsxs(t.Fragment,{children:[a==="inbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-inbox-list",children:[h&&!o&&t.jsx(Ml,{}),o&&o.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-inbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No messages in your inbox"})]}),o?.messages.map(J=>t.jsxs("div",{id:co(J.id),className:`mailbox-item ${J.read?"":"unread"}`,onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.fromType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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:ne(J.fromId,J.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]}),!J.read&&t.jsx("div",{className:"mailbox-item-unread-dot","data-testid":`mailbox-unread-dot-${J.id}`})]},J.id))]}),a==="outbox"&&t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-outbox-list",children:[h&&!c&&t.jsx(Ml,{}),c&&c.messages.length===0&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-outbox-empty",children:[t.jsx(Da,{size:32}),t.jsx("p",{children:"No sent messages"})]}),c?.messages.map(J=>t.jsxs("div",{id:co(J.id),className:"mailbox-item",onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.toType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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: ",ne(J.toId,J.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]})]},J.id))]}),a==="approvals"&&t.jsxs("div",{className:"mailbox-approvals","data-testid":"mailbox-approvals",children:[t.jsxs("div",{className:"mailbox-approval-filters","data-testid":"mailbox-approval-filters",children:[t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Q==="pending"?"active":""}`,onClick:()=>{se("pending"),X(null)},"data-testid":"mailbox-approval-filter-pending",children:"Pending"}),t.jsx("button",{className:`btn btn-sm btn-secondary mailbox-agent-subtab ${Q==="history"?"active":""}`,onClick:()=>{se("history"),X(null)},"data-testid":"mailbox-approval-filter-history",children:"History"})]}),t.jsxs("div",{className:"mailbox-list","data-testid":"mailbox-approval-list",children:[O.length===0&&!h&&t.jsxs("div",{className:"mailbox-empty","data-testid":"mailbox-approval-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:Q==="pending"?"No pending approvals":"No historical approvals"})]}),O.map(J=>t.jsxs("div",{className:"mailbox-item mailbox-approval-item",onClick:()=>void Ye(J),"data-testid":`mailbox-approval-item-${J.id}`,children:[t.jsx("div",{className:`status-dot mailbox-approval-status-dot mailbox-approval-status-dot--${J.status}`}),t.jsxs("div",{className:"mailbox-item-content",children:[t.jsxs("div",{className:"mailbox-item-header",children:[t.jsxs("span",{className:"mailbox-item-from",children:[J.agentId," · ",J.actionCategory]}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsx("div",{className:"mailbox-item-preview",children:J.actionSummary})]}),t.jsx("span",{className:`mailbox-approval-status mailbox-approval-status--${J.status}`,children:J.status})]},J.id))]})]}),a==="agents"&&t.jsx("div",{className:"mailbox-agents","data-testid":"mailbox-agents",children:T.length===0?t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Qn,{size:32}),t.jsx("p",{children:"No agents found"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"mailbox-agents-header",children:[t.jsx("div",{className:"mailbox-agents-dropdown",children:t.jsxs("select",{className:"message-composer-select mailbox-agent-select",value:N,onChange:J=>{R(J.target.value),E("inbox")},"data-testid":"mailbox-agent-select",children:[t.jsx("option",{value:Ts,children:"All agents"}),T.map(J=>t.jsx("option",{value:J.id,children:J.name||J.id},J.id))]})}),t.jsxs("button",{className:"btn btn-sm btn-secondary mailbox-compose-btn",onClick:xt,"data-testid":"mailbox-compose-btn",children:[t.jsx(Zi,{size:14}),t.jsx("span",{children:"Compose"})]})]}),N&&N!==Ts&&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 ${F==="inbox"?"active":""}`,onClick:()=>E("inbox"),"data-testid":"mailbox-agent-subtab-inbox",children:[t.jsx(ma,{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 ${F==="outbox"?"active":""}`,onClick:()=>E("outbox"),"data-testid":"mailbox-agent-subtab-outbox",children:[t.jsx(Da,{size:12}),t.jsx("span",{children:"Outbox"})]})]}),t.jsxs("div",{className:"mailbox-agents-content",children:[N===Ts&&h&&!U&&t.jsx(Ml,{}),N===Ts&&U&&U.messages.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No agent-to-agent messages"})]}),N===Ts&&U&&U.messages.map(J=>t.jsxs("div",{id:co(J.id),className:`mailbox-item ${J.read?"":"unread"}`,onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.fromType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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:ne(J.fromId,J.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-participants","data-testid":`mailbox-item-participants-${J.id}`,children:[t.jsxs("span",{children:["From: ",ne(J.fromId,J.fromType)]}),t.jsxs("span",{children:["To: ",ne(J.toId,J.toType)]})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]})]},J.id)),N&&N!==Ts&&h&&!_&&t.jsx(Ml,{}),N&&N!==Ts&&_&&F==="inbox"&&_.inbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(ma,{size:32}),t.jsx("p",{children:"No received messages for this agent"})]}),N&&N!==Ts&&_&&F==="outbox"&&_.outbox.length===0&&t.jsxs("div",{className:"mailbox-empty",children:[t.jsx(Da,{size:32}),t.jsx("p",{children:"No sent messages for this agent"})]}),N&&N!==Ts&&_&&F==="inbox"&&_.inbox.map(J=>t.jsxs("div",{id:co(J.id),className:`mailbox-item ${J.read?"":"unread"}`,onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.fromType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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:ne(J.fromId,J.fromType)}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]})]},J.id)),N&&N!==Ts&&_&&F==="outbox"&&_.outbox.map(J=>t.jsxs("div",{id:co(J.id),className:"mailbox-item",onClick:()=>ue(J),"data-testid":`mailbox-item-${J.id}`,children:[t.jsx("div",{className:"mailbox-item-avatar",children:J.toType==="agent"?t.jsx(Qn,{size:16}):t.jsx(Ra,{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: ",ne(J.toId,J.toType)]}),t.jsx("span",{className:"mailbox-item-time",children:Yi(J.createdAt)})]}),t.jsxs("div",{className:"mailbox-item-preview",children:[J.content.slice(0,80),J.content.length>80?"…":""]})]})]},J.id))]})]})})]}),Fe=()=>b?t.jsx(Tf,{recipient:S,replyContext:C,agents:T,projectId:e,onSend:tt,onCancel:Me,addToast:n}):p?wt():a==="approvals"&&k?t.jsxs("div",{className:"mailbox-message-detail mailbox-approval-detail","data-testid":"mailbox-approval-detail",children:[Z&&t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>X(null),"data-testid":"mailbox-approval-back-to-list",children:"← Back"}),t.jsx("div",{className:"mailbox-message-detail-header",children:t.jsxs("div",{className:"mailbox-message-detail-meta",children:[t.jsx("span",{className:"mailbox-message-type",children:k.actionCategory}),t.jsx("span",{className:"mailbox-message-time",children:k.status})]})}),t.jsxs("div",{className:"mailbox-message-body",children:[t.jsx("strong",{children:k.actionSummary}),t.jsxs("p",{children:["Requester: ",k.requester.actorName," (",k.agentId,")"]}),k.taskId&&t.jsxs("p",{children:["Task: ",k.taskId]}),t.jsxs("p",{children:["Requested: ",Yi(k.createdAt)]})]}),t.jsx("div",{className:"mailbox-conversation","data-testid":"mailbox-approval-history",children:k.history.map(J=>t.jsxs("div",{className:"mailbox-conversation-msg",children:[t.jsxs("div",{className:"mailbox-conversation-msg-header",children:[t.jsx("span",{children:J.eventType}),t.jsx("span",{children:J.actor.actorName})]}),J.note&&t.jsx("div",{className:"mailbox-item-preview",children:J.note})]},J.id))}),k.status==="pending"&&t.jsxs("div",{className:"mailbox-approval-decision","data-testid":"mailbox-approval-decision",children:[t.jsx("textarea",{className:"message-composer-textarea mailbox-approval-comment",value:le,onChange:J=>ke(J.target.value),placeholder:"Optional comment","data-testid":"mailbox-approval-comment"}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsx("button",{className:"btn btn-sm btn-secondary",onClick:()=>void dt("deny"),disabled:He!==!1,"data-testid":"mailbox-approval-deny",children:"Deny"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void dt("approve"),disabled:He!==!1,"data-testid":"mailbox-approval-approve",children:"Approve"})]})]})]}):t.jsxs("div",{className:"mailbox-split-empty","data-testid":"mailbox-split-empty",children:[t.jsx(za,{size:24}),t.jsx("p",{children:"Select a message to read"})]});return t.jsxs("div",{className:"mailbox-view",style:ae,"data-testid":"mailbox-view",children:[t.jsxs("div",{className:"mailbox-header",children:[t.jsxs("div",{className:"mailbox-title",children:[t.jsx(za,{size:18}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mailbox-unread-badge","data-testid":"mailbox-unread-badge",children:u})]}),t.jsxs("div",{className:"mailbox-header-actions",children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:xt,title:"Compose message","data-testid":"mailbox-header-compose",children:[t.jsx(Zi,{size:14}),t.jsx("span",{children:"Compose"})]}),a==="inbox"&&u>0&&t.jsxs("button",{className:"btn btn-sm btn-secondary",onClick:Ee,title:"Mark all as read","data-testid":"mailbox-mark-all-read",children:[t.jsx(Im,{size:14}),t.jsx("span",{children:"Mark all read"})]}),t.jsx("button",{className:"btn-icon",onClick:()=>{a==="inbox"?rt():a==="outbox"?Be():a==="approvals"?Ue(Q):N===Ts?Re():N&&ce(N)},disabled:h,title:"Refresh","data-testid":"mailbox-refresh",children:h?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14})})]})]}),t.jsxs("div",{className:"mailbox-tabs","data-testid":"mailbox-tabs",children:[t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="inbox"?"active":""}`,onClick:()=>{r("inbox"),g(null)},"data-testid":"mailbox-tab-inbox",children:[t.jsx(ma,{size:14}),t.jsx("span",{children:"Inbox"}),u>0&&t.jsx("span",{className:"mailbox-tab-badge",children:u})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="outbox"?"active":""}`,onClick:()=>{r("outbox"),g(null)},"data-testid":"mailbox-tab-outbox",children:[t.jsx(Da,{size:14}),t.jsx("span",{children:"Outbox"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="agents"?"active":""}`,onClick:()=>{r("agents"),g(null),X(null)},"data-testid":"mailbox-tab-agents",children:[t.jsx(Qn,{size:14}),t.jsx("span",{children:"Agents"})]}),t.jsxs("button",{className:`btn btn-sm btn-secondary mailbox-tab ${a==="approvals"?"active":""}`,onClick:()=>{r("approvals"),g(null),X(null)},"data-testid":"mailbox-tab-approvals",children:[t.jsx(Im,{size:14}),t.jsx("span",{children:"Approvals"}),D>0&&t.jsx("span",{className:"mailbox-tab-badge","data-testid":"mailbox-approvals-pending-badge",children:D})]})]}),t.jsx("div",{className:"mailbox-content","data-testid":"mailbox-content",children:re?t.jsxs("div",{className:"mailbox-split-layout","data-testid":"mailbox-split-layout",ref:xe,children:[t.jsx("div",{className:"mailbox-split-list-pane","data-testid":"mailbox-split-list-pane",style:{width:`${q}px`},children:St()}),t.jsx("div",{className:"mailbox-split-resize-handle","data-testid":"mailbox-split-resize-handle",role:"separator","aria-orientation":"vertical","aria-label":"Resize message list pane",tabIndex:0,"aria-valuemin":oc,"aria-valuemax":Math.round(Ru(xe.current?.clientWidth??q/Au)),"aria-valuenow":Math.round(q),onMouseDown:Ve,onKeyDown:Te}),t.jsx("div",{className:"mailbox-split-detail-pane","data-testid":"mailbox-split-detail-pane",children:Fe()})]}):t.jsxs(t.Fragment,{children:[wt(),a==="approvals"&&k&&Fe(),b&&t.jsx(Tf,{recipient:S,replyContext:C,agents:T,projectId:e,onSend:tt,onCancel:Me,addToast:n}),!p&&!k&&!b&&St()]})})]})}function Ml(){return t.jsx("div",{className:"mailbox-skeleton","data-testid":"mailbox-skeleton",children:Array.from({length:5}).map((e,n)=>t.jsxs("div",{className:"mailbox-skeleton-item",children:[t.jsx("div",{className:"mailbox-skeleton-avatar"}),t.jsxs("div",{className:"mailbox-skeleton-content",children:[t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--short"}),t.jsx("div",{className:"mailbox-skeleton-line mailbox-skeleton-line--long"})]})]},n))})}const h4=640;function p4({isOpen:e,onClose:n,onImport:s,tasks:a,projectId:r}){Mi(e);const[o,l]=i.useState(""),[c,d]=i.useState(""),[u,m]=i.useState(""),[h,f]=i.useState(!1),[p,g]=i.useState("issues"),[w,v]=i.useState([]),[b,y]=i.useState(null),[S,j]=i.useState([]),[C,x]=i.useState(null),[N,R]=i.useState(null),[F,E]=i.useState(!1),[_,K]=i.useState([]),[U,A]=i.useState(!1),[T,H]=i.useState(""),Q=i.useRef(!1),se=i.useRef(null);zi(se,e,"fusion:github-modal-size");const O=sa(n),[M,D]=i.useState(!1),[$,k]=i.useState("list"),X=i.useRef(null),le=new Set;for(const ue of a){const oe=ue.description.match(/Source: (https:\/\/github\.com\/[^/]+\/[^/]+\/issues\/\d+)/);oe&&le.add(oe[1]);const Ee=ue.description.match(/PR: (https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+)/);Ee&&le.add(Ee[1])}i.useEffect(()=>{if(e)return l(""),d(""),m(""),v([]),y(null),j([]),x(null),g("issues"),R(null),E(!1),K([]),A(!0),H(""),X.current=null,Q.current=!0,PN().then(ue=>{if(Q.current)if(K(ue),A(!1),ue.length===1){const oe=ue[0];l(oe.owner),d(oe.repo),H(oe.name)}else ue.length>1&&(l(""),d(""),H(""))}).catch(()=>{Q.current&&A(!1)}),()=>{Q.current=!1}},[e]);const ke=i.useCallback(ue=>{if(H(ue),ue==="")l(""),d("");else{const oe=_.find(Ee=>Ee.name===ue);oe&&(l(oe.owner),d(oe.repo))}},[_]),He=i.useCallback(async()=>{if(!o.trim()||!c.trim()){R("Repository must be selected");return}f(!0),R(null),v([]),y(null);try{const ue=u.split(",").map(Ee=>Ee.trim()).filter(Boolean),oe=await AN(o.trim(),c.trim(),30,ue.length>0?ue:void 0);v(oe),oe.length===0&&R("No open issues found")}catch(ue){R(Se(ue)||"Failed to fetch issues")}finally{f(!1)}},[o,c,u]),ye=i.useCallback(async()=>{if(!o.trim()||!c.trim()){R("Repository must be selected");return}f(!0),R(null),j([]),x(null);try{const ue=await IN(o.trim(),c.trim(),30);j(ue),ue.length===0&&R("No open pull requests found")}catch(ue){R(Se(ue)||"Failed to fetch pull requests")}finally{f(!1)}},[o,c]);i.useEffect(()=>{if(!e||!o.trim()||!c.trim()||h||F)return;const ue={owner:o.trim(),repo:c.trim(),labels:u.trim(),tab:p};X.current?.owner===ue.owner&&X.current?.repo===ue.repo&&X.current?.labels===ue.labels&&X.current?.tab===ue.tab||(X.current=ue,p==="issues"?He():ye())},[o,c,u,p,e,h,F,He,ye]),i.useEffect(()=>{if(!e)return;const ue=oe=>{oe.key==="Escape"&&n()};return document.addEventListener("keydown",ue),()=>document.removeEventListener("keydown",ue)},[e,n]),i.useEffect(()=>{if(!e)return;const ue=()=>{D(window.innerWidth<=h4)};return ue(),window.addEventListener("resize",ue),()=>window.removeEventListener("resize",ue)},[e]);const je=i.useCallback(ue=>{y(ue),M&&k("preview")},[M]),ne=i.useCallback(ue=>{x(ue),M&&k("preview")},[M]),fe=i.useCallback(()=>{k("list")},[]),Z=i.useCallback(async()=>{if(p==="issues"){if(b===null)return;E(!0),R(null);try{const ue=await RN(o.trim(),c.trim(),b,r);s(ue),y(null),M&&$==="preview"&&k("list")}catch(ue){const oe=Se(ue);oe?.includes("already imported")?R(oe):R(oe||"Failed to import issue")}finally{E(!1)}}else{if(C===null)return;E(!0),R(null);try{const ue=await TN(o.trim(),c.trim(),C,r);s(ue),x(null),M&&$==="preview"&&k("list")}catch(ue){const oe=Se(ue);oe?.includes("already imported")?R(oe):R(oe||"Failed to import pull request")}finally{E(!1)}}},[p,b,C,o,c,s,M,$]),re=w.find(ue=>ue.number===b),q=S.find(ue=>ue.number===C);if(!e)return null;const L=_.length>0,xe=_.length===1,he=w.filter(ue=>le.has(ue.html_url)).length,B=S.filter(ue=>le.has(ue.html_url)).length,pe=N==="No open issues found",ze=N==="No open pull requests found",ae=p==="issues"?pe:ze,Ve=!!N&&!pe&&w.length===0&&!h,Te=!!N&&!ze&&S.length===0&&!h,rt=p==="issues"?Ve:Te,Be=h||w.length>0||pe||Ve,ce=h||S.length>0||ze||Te,Re=p==="issues"?Be:ce,Le=!!N&&w.length>0&&!pe,ct=!!N&&S.length>0&&!ze,Ue=p==="issues"?Le:ct;return t.jsx("div",{className:"modal-overlay open",...O,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg github-import-modal",ref:se,children:[t.jsxs("div",{className:"modal-header github-import-modal__header",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"Import from GitHub"}),t.jsx("p",{className:"github-import-modal__subtitle",children:"Choose a detected remote, load open issues or pull requests, and import one into the board."})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close import modal",children:"×"})]}),t.jsxs("div",{className:"modal-body github-import-modal__body",children:[t.jsxs("div",{className:"github-import-tabs",role:"tablist","aria-label":"Import type",children:[t.jsxs("button",{role:"tab","aria-selected":p==="issues","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="issues"?"active":""}`,onClick:()=>{g("issues"),x(null)},disabled:h||F,children:[t.jsx(fc,{size:16}),t.jsx("span",{children:"Issues"})]}),t.jsxs("button",{role:"tab","aria-selected":p==="pulls","aria-controls":"github-import-list-pane",className:`github-import-tab ${p==="pulls"?"active":""}`,onClick:()=>{g("pulls"),y(null)},disabled:h||F,children:[t.jsx(ii,{size:16}),t.jsx("span",{children:"Pull Requests"})]})]}),t.jsxs("div",{className:"github-import-toolbar","data-testid":"github-import-toolbar",role:"toolbar","aria-label":"GitHub import controls",children:[t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--remote",children:U?t.jsxs("div",{className:"github-import-toolbar__loading",role:"status","aria-live":"polite",children:[t.jsx(jt,{size:16,className:"spin"}),t.jsx("span",{children:"Detecting…"})]}):L?xe?t.jsxs("div",{className:"github-import-remote-pill","data-testid":"github-import-single-remote",children:[t.jsx("span",{className:"github-import-remote-pill__name",children:_[0].name}),t.jsxs("span",{className:"github-import-remote-pill__repo",children:[_[0].owner,"/",_[0].repo]})]}):t.jsxs("div",{className:"github-import-remote-select",children:[t.jsx("label",{htmlFor:"gh-remote",className:"visually-hidden",children:"Repository"}),t.jsxs("select",{id:"gh-remote",value:T,onChange:ue=>ke(ue.target.value),disabled:h||F,"aria-label":"Select Git remote",children:[t.jsx("option",{value:"",children:"Select remote…"}),_.map(ue=>t.jsxs("option",{value:ue.name,children:[ue.name," (",ue.owner,"/",ue.repo,")"]},ue.name))]})]}):t.jsx("span",{className:"github-import-toolbar__no-remote",children:"No remotes"})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--filter",children:p==="issues"?t.jsxs(t.Fragment,{children:[t.jsx("label",{htmlFor:"gh-labels",className:"visually-hidden",children:"Filter by labels"}),t.jsx("input",{id:"gh-labels",type:"text",placeholder:"Filter: bug,enhancement…",value:u,onChange:ue=>m(ue.target.value),onKeyDown:ue=>ue.key==="Enter"&&He(),disabled:h||F||!L,"aria-label":"Filter issues by labels"})]}):t.jsxs("span",{className:"github-import-filter-hint",children:["Open pull requests from ",o||"selected remote"]})}),t.jsx("div",{className:"github-import-toolbar__zone github-import-toolbar__zone--action",children:t.jsxs("button",{id:"gh-load",className:"btn btn-primary github-import-load-button",onClick:p==="issues"?He:ye,disabled:h||F||!o.trim()||!c.trim(),"aria-label":h?`Loading ${p}`:`Load ${p} from repository`,title:h?"Loading…":`Load ${p}`,children:[h?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),t.jsx("span",{children:h?"Loading…":"Load"})]})})]}),!U&&!L&&t.jsxs("div",{className:"github-import-state github-import-state--warning",role:"alert",children:[t.jsxs("div",{children:[t.jsx("strong",{children:"No GitHub remotes detected"}),t.jsx("span",{children:"Add a GitHub remote to this repository, then reopen the modal."})]}),t.jsx("code",{className:"github-import-command",children:"git remote add origin https://github.com/owner/repo.git"})]}),Ue&&t.jsx("div",{className:"form-error github-import-banner",role:"alert",children:N}),t.jsxs("div",{className:"github-import-workspace",children:[t.jsxs("section",{className:`github-import-list-pane ${M?"mobile":""} ${$==="list"?"active":""}`,"data-testid":"github-import-list-pane","aria-labelledby":"github-import-results-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[t.jsx("h4",{id:"github-import-results-heading",children:p==="issues"?"Issues":"Pull Requests"}),p==="issues"&&w.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[w.length," issue",w.length===1?"":"s"]}),t.jsxs("span",{children:[he," imported"]})]}),p==="pulls"&&S.length>0&&t.jsxs("div",{className:"github-import-results-meta","aria-live":"polite",children:[t.jsxs("span",{children:[S.length," pull request",S.length===1?"":"s"]}),t.jsxs("span",{children:[B," imported"]})]})]}),t.jsxs("div",{className:"github-import-pane-content",children:[!Re&&t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-results-idle",children:t.jsxs("div",{children:[t.jsx("strong",{children:"Nothing loaded yet"}),t.jsx("span",{children:"Select a repository and click Load to start reviewing import candidates."})]})}),h&&t.jsxs("div",{className:"github-import-state github-import-state--loading",role:"status","aria-live":"polite",children:[t.jsx(jt,{size:16,className:"spin"}),t.jsxs("div",{children:[t.jsxs("strong",{children:["Loading open ",p==="issues"?"issues":"pull requests","…"]}),t.jsx("span",{children:"Fetching the latest list from GitHub."})]})]}),rt&&t.jsx("div",{className:"github-import-state github-import-state--error",role:"alert",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["Could not load ",p==="issues"?"issues":"pull requests"]}),t.jsx("span",{children:N})]})}),ae&&t.jsx("div",{className:"github-import-state github-import-state--empty",role:"status",children:t.jsxs("div",{children:[t.jsxs("strong",{children:["No open ",p==="issues"?"issues":"pull requests"," found"]}),t.jsx("span",{children:p==="issues"?"Try a different label filter or choose another repository.":"Choose another repository."})]})}),p==="issues"&&w.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:w.map(ue=>{const oe=le.has(ue.html_url);return t.jsxs("div",{className:`issue-item ${b===ue.number?"selected":""} ${oe?"imported":""}`,onClick:()=>!oe&&je(ue.number),children:[t.jsx("input",{type:"radio",name:"issue",checked:b===ue.number,onChange:()=>je(ue.number),disabled:oe,"aria-label":`Select issue #${ue.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ue.number]}),t.jsx("span",{className:"issue-title",children:ue.title})]}),ue.labels.length>0&&t.jsx("span",{className:"issue-labels",children:ue.labels.map(Ee=>t.jsx("span",{className:"label-chip",children:Ee.name},Ee.name))})]}),oe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ue.number)})}),p==="pulls"&&S.length>0&&t.jsx("div",{className:"issues-list","aria-live":"polite",children:S.map(ue=>{const oe=le.has(ue.html_url);return t.jsxs("div",{className:`issue-item ${C===ue.number?"selected":""} ${oe?"imported":""}`,onClick:()=>!oe&&ne(ue.number),children:[t.jsx("input",{type:"radio",name:"pull",checked:C===ue.number,onChange:()=>ne(ue.number),disabled:oe,"aria-label":`Select pull request #${ue.number}`}),t.jsxs("div",{className:"issue-main",children:[t.jsxs("div",{className:"issue-heading-row",children:[t.jsxs("span",{className:"issue-number",children:["#",ue.number]}),t.jsx("span",{className:"issue-title",children:ue.title})]}),t.jsxs("span",{className:"pull-branch-info",children:[ue.headBranch," → ",ue.baseBranch]})]}),oe&&t.jsx("span",{className:"imported-badge",children:"Imported"})]},ue.number)})})]})]}),t.jsxs("section",{className:`github-import-preview-pane ${M?"mobile":""} ${$==="preview"?"active":""}`,"data-testid":"github-import-preview-pane","aria-labelledby":"github-import-preview-heading",children:[t.jsxs("div",{className:"github-import-pane-header",children:[M&&t.jsxs("button",{className:"github-import-back-button",onClick:fe,"data-testid":"github-import-back-button","aria-label":`Back to ${p==="issues"?"issues":"pull requests"} list`,children:[t.jsx(Ga,{size:16}),t.jsx("span",{children:"Back"})]}),t.jsx("h4",{id:"github-import-preview-heading",children:"Preview"})]}),t.jsxs("div",{className:"github-import-pane-content",children:[p==="issues"&&re?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Issue #",re.number]}),t.jsx("div",{className:"preview-title",children:re.title}),t.jsx("div",{className:"preview-body",children:re.body?re.body.slice(0,200)+(re.body.length>200?"…":""):"(no description)"})]}):p==="issues"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No issue selected"}),t.jsx("span",{children:"Choose an issue from the list to inspect its title and description."})]})}):null,p==="pulls"&&q?t.jsxs("div",{className:"issue-preview","data-testid":"github-import-preview-card",children:[t.jsxs("div",{className:"preview-meta",children:["Pull Request #",q.number]}),t.jsx("div",{className:"preview-title",children:q.title}),t.jsxs("div",{className:"preview-branch",children:[t.jsx("strong",{children:"Branch:"})," ",q.headBranch," → ",q.baseBranch]}),t.jsx("div",{className:"preview-body",children:q.body?q.body.slice(0,200)+(q.body.length>200?"…":""):"(no description)"})]}):p==="pulls"?t.jsx("div",{className:"github-import-state github-import-state--idle","data-testid":"github-import-preview-empty",children:t.jsxs("div",{children:[t.jsx("strong",{children:"No pull request selected"}),t.jsx("span",{children:"Choose a pull request from the list to inspect its details."})]})}):null]})]})]})]}),t.jsxs("div",{className:"modal-actions github-import-modal__actions",children:[t.jsx("button",{className:"btn",onClick:n,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:Z,disabled:(p==="issues"?b===null:C===null)||F,children:F?t.jsx(jt,{size:14,className:"spin"}):"Import"})]})]})})}function fi({summary:e,children:n,className:s="",onToggle:a,defaultOpen:r=!1}){const[o,l]=i.useState(r);return t.jsxs("div",{className:`onboarding-disclosure ${s}`.trim(),children:[t.jsxs("button",{className:"onboarding-disclosure-trigger",onClick:()=>{const c=!o;l(c),a?.(c)},"aria-expanded":o,type:"button",children:[t.jsx(qn,{size:14,className:"onboarding-disclosure-chevron","aria-hidden":"true"}),t.jsx("span",{children:e})]}),o?t.jsx("div",{className:"onboarding-disclosure-content",children:n}):null]})}const f4=["Build a user authentication system with login and signup","Add dark mode support to the dashboard","Create an API endpoint for exporting tasks as CSV","Refactor the task card component for better performance"];function Va(e){return e&&wa.includes(e)?e:Ps}function zd(e){return{...e,priority:Va(e.priority)}}function g4(e,n){return e.length===n.length&&e.every((s,a)=>s===n[a])}function b4(e,n){const s=new Map(e.map(a=>[a.id,a]));return n.map(a=>{const r=s.get(a.id),o=Va(a.priority),l={id:a.id};return(!r||a.title!==r.title)&&(l.title=a.title),(!r||a.description!==r.description)&&(l.description=a.description),(!r||a.suggestedSize!==r.suggestedSize)&&(l.suggestedSize=a.suggestedSize),(!r||o!==Va(r.priority))&&(l.priority=o),(!r||!g4(a.dependsOn,r.dependsOn))&&(l.dependsOn=a.dependsOn),l})}function x4(e,n){return e&&n?`${e}/${n}`:""}function v4(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 y4({isOpen:e,onClose:n,onTaskCreated:s,onTasksCreated:a,tasks:r,initialPlan:o,projectId:l,resumeSessionId:c}){const[d,u]=i.useState(""),[m,h]=i.useState({type:"initial"}),[f,p]=i.useState(null),[g,w]=i.useState([]),[v,b]=i.useState([]),[y,S]=i.useState(null),j=i.useRef(!1),C=i.useRef(!1),[x,N]=i.useState(""),[R,F]=i.useState(!0),[E,_]=i.useState(!1),[K,U]=i.useState(!1),[A,T]=i.useState(null),[H,Q]=i.useState(0),se=i.useRef(null),O=i.useRef(null),M=i.useRef(null),D=i.useRef(null),$=i.useRef(null),k=i.useRef(null),X=i.useRef(null),[le,ke]=i.useState(c??null),He=i.useMemo(()=>Ja(),[]),{isLockedByOther:ye,takeControl:je,isLoading:ne}=Tc(e?le:null),{activeTabMap:fe,broadcastUpdate:Z,broadcastCompleted:re,broadcastLock:q,broadcastUnlock:L,broadcastHeartbeat:xe}=Wr(),[he,B]=i.useState(void 0),[pe,ze]=i.useState(void 0),[ae,Ve]=i.useState("medium"),[Te,rt]=i.useState(""),[Be,ce]=i.useState([]),[Re,Le]=i.useState(!1),[ct,Ue]=i.useState(null),[ue,oe]=i.useState([]),[Ee,ft]=i.useState([]),[ht,tt]=i.useState({}),xt=i.useRef(null),[Me,Ye]=i.useState([]),[dt,wt]=i.useState(!1),[St,Fe]=i.useState(c??null),[J,me]=i.useState(!!c),[Ze,be]=i.useState(null),[gt,$t]=i.useState(!1),Ie=i.useRef(!1),ge=i.useRef(null),st=i.useRef(""),yt=i.useRef(null),pt=i.useRef(null);zi(O,e,"fusion:planning-modal-size");const vt=oi(),Ut=vt==="mobile",{pushNav:Dt}=wv(),{keyboardOverlap:nn,viewportHeight:on,viewportOffsetTop:sn,keyboardOpen:ln}=aa({enabled:vt==="mobile"});Mi(vt==="mobile"&&e),i.useEffect(()=>{const de=O.current;de&&(ln?(de.style.setProperty("--keyboard-overlap",`${nn}px`),de.style.setProperty("--vv-offset-top",`${sn}px`),on!==null?de.style.setProperty("--vv-height",`${on}px`):de.style.removeProperty("--vv-height")):(de.style.removeProperty("--keyboard-overlap"),de.style.removeProperty("--vv-offset-top"),de.style.removeProperty("--vv-height")))},[ln,nn,sn,on]),i.useEffect(()=>{st.current=x},[x]),i.useEffect(()=>{const de=ge.current;if(!de)return;de.scrollHeight-de.scrollTop-de.clientHeight<32&&(de.scrollTop=de.scrollHeight)},[x]),i.useEffect(()=>{if(m.type!=="loading"){T(null),Q(0);return}const de=Date.now();T(de),Q(0);const nt=setInterval(()=>{Q(Math.max(0,Math.floor((Date.now()-de)/1e3)))},1e3);return()=>clearInterval(nt)},[m.type]),i.useEffect(()=>{if(m.type!=="loading")return;const de=D.current;if(!de)return;let nt=!1;const _t=setInterval(async()=>{try{const G=await Di(de);if(nt||!G||D.current!==de)return;if(G.status==="awaiting_input"&&G.currentQuestion){const Oe=JSON.parse(G.currentQuestion);h({type:"question",session:{sessionId:de,currentQuestion:Oe,summary:null}}),N("")}else if(G.status==="complete"&&G.result){const Oe=zd(JSON.parse(G.result));h({type:"summary",session:{sessionId:de,currentQuestion:null,summary:Oe},summary:Oe}),S(Oe),N("")}}catch{}},8e3);return()=>{nt=!0,clearInterval(_t)}},[m.type]);const xn=i.useCallback(()=>{u(""),h({type:"initial"}),p(null),w([]),b([]),S(null),N(""),_(!1),U(!1),B(void 0),ze(void 0),Ve("medium"),rt(""),D.current=null,ke(null)},[]),qt=x4(he,pe),Qt=i.useCallback((de,nt)=>{if(!de||!nt)return ht.provider&&ht.modelId?`${ht.provider}/${ht.modelId}`:"Using default";const ot=Be.find(_t=>_t.provider===de&&_t.id===nt);return ot?`${ot.provider}/${ot.id}`:`${de}/${nt}`},[Be,ht.modelId,ht.provider]),hn=i.useCallback(async()=>{Le(!0),Ue(null);try{const de=await Ws();ce(de.models),oe(de.favoriteProviders),ft(de.favoriteModels),tt({provider:de.resolvedPlanningProvider,modelId:de.resolvedPlanningModelId})}catch(de){Ue(Se(de)||"Failed to load models")}finally{Le(!1)}},[]),Zt=i.useCallback(de=>{oe(nt=>{const ot=nt,G=ot.includes(de)?ot.filter(Oe=>Oe!==de):[de,...ot];return Bn({favoriteProviders:G,favoriteModels:Ee}).catch(()=>{oe(ot)}),G})},[Ee]),ve=i.useCallback(de=>{ft(nt=>{const ot=nt,G=ot.includes(de)?ot.filter(Oe=>Oe!==de):[de,...ot];return Bn({favoriteProviders:ue,favoriteModels:G}).catch(()=>{ft(ot)}),G})},[ue]),Pe=i.useCallback(de=>{M.current?.close();const nt=()=>D.current!==de,ot=DS(de,l,{onThinking:_t=>{nt()||(N(G=>G+_t),Z({sessionId:de,status:"generating",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null}))},onQuestion:_t=>{if(nt())return;_(!1),U(!1),hr(l);const G=st.current.trim();G&&b(Oe=>Oe[Oe.length-1]?.thinkingOutput===G?Oe:[...Oe,{thinkingOutput:G}]),h({type:"question",session:{sessionId:de,currentQuestion:_t,summary:null}}),N(""),Z({sessionId:de,status:"awaiting_input",needsInput:!0,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null})},onSummary:_t=>{if(nt())return;_(!1),U(!1),hr(l);const G=st.current.trim();G&&b(Oe=>Oe[Oe.length-1]?.thinkingOutput===G?Oe:[...Oe,{thinkingOutput:G}]),h({type:"summary",session:{sessionId:de,currentQuestion:null,summary:_t},summary:_t}),S(_t),N(""),Z({sessionId:de,status:"complete",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null})},onError:_t=>{const G=_t||"Session failed while contacting the AI.";_(!0),(async()=>{try{const Oe=await Di(de);if(Oe&&(Oe.status==="generating"||Oe.status==="awaiting_input")){Pe(de);return}}catch{}_(!1),U(!1),p(null),h(Oe=>Oe.type==="question"||Oe.type==="summary"||Oe.type==="error"?{type:"error",session:Oe.session,errorMessage:G}:{type:"error",session:{sessionId:de,currentQuestion:null,summary:null},errorMessage:G}),N(""),D.current=de,Z({sessionId:de,status:"error",needsInput:!1,owningTabId:He,type:"planning",title:d.trim()||void 0,projectId:l??null}),re({sessionId:de,status:"error"})})()},onComplete:()=>{_(!1),U(!1),D.current=null,re({sessionId:de,status:"complete"})},onConnectionStateChange:_t=>{_(_t==="reconnecting")}});M.current=ot},[re,Z,d,l,He]),Ke=i.useCallback(async de=>{const nt=de??d;if(nt.trim()){p(null),N(""),b([]),w([]),_(!1),h({type:"loading"});try{const ot=he&&pe?{planningModelProvider:he,planningModelId:pe}:void 0,_t=Te.trim()?Number.parseInt(Te,10):void 0,G=$.current,{sessionId:Oe}=await xS(nt.trim(),l,ot,{planningDepth:ae,customQuestionCount:Number.isInteger(_t)?_t:void 0},G??void 0);$.current=null,D.current=Oe,ke(Oe),Fe(Oe),Pe(Oe),w([])}catch(ot){_(!1),p(Se(ot)||"Failed to start planning session"),h({type:"initial"}),D.current=null,ke(null)}}},[Pe,Te,d,ae,pe,he,l]);i.useEffect(()=>{e&&m.type==="initial"&&se.current?.focus()},[e,m.type]),i.useEffect(()=>{e&&hn()},[e,hn]),i.useEffect(()=>{if(e&&o&&!j.current&&m.type==="initial"){u(o);const de=setTimeout(()=>{j.current=!0,Ke(o)},0);return()=>clearTimeout(de)}else if(e&&!o&&!j.current&&!C.current&&m.type==="initial"){C.current=!0;const de=y$(l);de&&u(de)}},[e,o,m.type,Ke,l]);const at=i.useCallback(async de=>{M.current?.close(),M.current=null,p(null),N(""),w([]),b([]),S(null),U(!1),h({type:"loading"});try{const nt=await Di(de);if(!nt){Fe(null),me(!1),h({type:"initial"});return}D.current=de,ke(de);const ot=Mr(nt.conversationHistory);if(b(ot),w(ot.map(_t=>_t.response).filter(_t=>!!(_t&&typeof _t=="object"&&!Array.isArray(_t)))),nt.status==="draft"){let _t="",G,Oe;try{const Mt=nt.inputPayload?JSON.parse(nt.inputPayload):null;Mt&&typeof Mt.initialPlan=="string"&&(_t=Mt.initialPlan),Mt&&typeof Mt.modelProvider=="string"&&typeof Mt.modelId=="string"&&(G=Mt.modelProvider,Oe=Mt.modelId)}catch{}u(_t),B(G),ze(Oe),$.current=de,pt.current=_t?{sessionId:de,initialPlan:_t.trim(),modelProvider:G,modelId:Oe}:null,h({type:"initial"})}else if(nt.status==="awaiting_input"&&nt.currentQuestion){hr(l);const _t=JSON.parse(nt.currentQuestion);if(h({type:"question",session:{sessionId:de,currentQuestion:_t,summary:null}}),nt.thinkingOutput){const G=nt.thinkingOutput.trim();G&&b(Oe=>Oe[Oe.length-1]?.thinkingOutput===G?Oe:[...Oe,{thinkingOutput:G}])}Pe(de)}else if(nt.status==="complete"&&nt.result){hr(l);const _t=zd(JSON.parse(nt.result));h({type:"summary",session:{sessionId:de,currentQuestion:null,summary:_t},summary:_t}),S(_t)}else nt.status==="generating"?(h({type:"loading"}),nt.thinkingOutput&&N(nt.thinkingOutput),Pe(de)):nt.status==="error"&&h({type:"error",session:{sessionId:de,currentQuestion:null,summary:null},errorMessage:nt.error||"Session failed"})}catch{p("Failed to load session"),h({type:"initial"})}},[Pe,l]);i.useEffect(()=>{!e||!c||D.current!==c&&X.current!==c&&(Fe(c),me(!0),at(c))},[e,c]),i.useEffect(()=>{e&&St&&(c&&c===St||at(St))},[e]);const We=i.useCallback(async()=>{wt(!0);try{const nt=(await Wu(l,{includeCompleted:!0,includeArchived:gt})).filter(ot=>ot.type==="planning").sort((ot,_t)=>Date.parse(_t.updatedAt)-Date.parse(ot.updatedAt));Ye(nt)}catch{}finally{wt(!1)}},[l,gt]);i.useEffect(()=>{e&&We()},[e,We]);const It=i.useRef(!1);i.useEffect(()=>{const de=It.current&&!dt;It.current=dt,de&&vt==="mobile"&&(J||c||St||Me.length>0||me(!0))},[vt,J,c,St,dt,Me.length]),i.useEffect(()=>{if(!e)return;const de=l?`?projectId=${encodeURIComponent(l)}`:"",nt=_t=>{try{const G=JSON.parse(_t.data);if(G.type!=="planning")return;Ye(Oe=>{const Mt=Oe.findIndex(_n=>_n.id===G.id);return(Mt>=0?[...Oe.slice(0,Mt),G,...Oe.slice(Mt+1)]:[G,...Oe]).sort((_n,Pn)=>Date.parse(Pn.updatedAt)-Date.parse(_n.updatedAt))})}catch{}},ot=_t=>{try{const G=JSON.parse(_t.data);Ye(Oe=>Oe.filter(Mt=>Mt.id!==G))}catch{}};return yi(`/api/events${de}`,{events:{"ai_session:updated":nt,"ai_session:deleted":ot},onReconnect:()=>{We()}})},[e,l,We]);const Lt=i.useCallback(de=>{if(St===de){me(!0);return}Fe(de),me(!0),at(de)},[at,St]),Bt=i.useCallback(()=>{M.current?.close(),M.current=null,$.current=null,k.current&&(clearTimeout(k.current),k.current=null),c&&(X.current=c),xn(),Fe(null),me(!0)},[xn,c]),Gt=i.useCallback(()=>{me(!1)},[]),bt=i.useRef(!1);i.useEffect(()=>{e||(bt.current=!1)},[e]),i.useEffect(()=>{const de=bt.current;if(Ut){if(!J){bt.current=!1;return}de||Dt({type:"view",revert:Gt}),bt.current=!0}},[Gt,Ut,J,Dt]);const Ot=i.useCallback(async(de,nt)=>{const ot=nt.trim();if(!(!ot||pt.current?.sessionId===de&&pt.current.initialPlan===ot&&pt.current.modelProvider===he&&pt.current.modelId===pe))try{await M0(de,{initialPlan:ot,modelProvider:he&&pe?he:void 0,modelId:he&&pe?pe:void 0},l),pt.current={sessionId:de,initialPlan:ot,modelProvider:he,modelId:pe}}catch{}},[pe,he,l]);i.useEffect(()=>{if(yt.current&&(clearTimeout(yt.current),yt.current=null),!(!e||m.type!=="initial"||!St))return yt.current=setTimeout(()=>{Ot(St,d)},500),()=>{yt.current&&(clearTimeout(yt.current),yt.current=null)}},[d,e,St,Ot,m.type]),i.useEffect(()=>{pt.current=null},[St]),i.useEffect(()=>()=>{yt.current&&(clearTimeout(yt.current),yt.current=null)},[]);const en=i.useCallback(async de=>{const nt=_t=>_t==="generating"||_t==="awaiting_input",ot=Me.find(_t=>_t.id===de);if(ot&&nt(ot.status))try{await pb(de,l,He)}catch{}try{await jb(de)}catch{}re({sessionId:de,status:"complete",timestamp:Date.now()}),Ye(_t=>_t.filter(G=>G.id!==de)),St===de&&(M.current?.close(),M.current=null,xn(),Fe(null),me(!1)),be(null)},[re,Me,l,xn,St,He]),Kt=i.useCallback(async de=>{const ot=Me.find(_t=>_t.id===de)?.archived===!0;try{ot?await N0(de):await j0(de)}catch{return}Ye(_t=>!ot&&!gt?_t.filter(G=>G.id!==de):_t.map(G=>G.id===de?{...G,archived:!ot}:G)),!ot&&St===de&&!gt&&(M.current?.close(),M.current=null,xn(),Fe(null),me(!1))},[Me,xn,St,me,gt]);i.useEffect(()=>{e||(j.current=!1,C.current=!1,_(!1),U(!1),ke(null))},[e]),i.useEffect(()=>{if(!e){xt.current&&(L(xt.current,He),xt.current=null);return}if(le&&xt.current!==le){xt.current&&L(xt.current,He),q(le,He),xt.current=le;return}!le&&xt.current&&(L(xt.current,He),xt.current=null)},[q,L,e,le,He]),i.useEffect(()=>{if(!e||!le||xt.current!==le)return;xe(He);const de=setInterval(()=>{xe(He)},3e4);return()=>{clearInterval(de)}},[xe,e,le,He]),i.useEffect(()=>()=>{k.current&&(clearTimeout(k.current),k.current=null),M.current?.close(),M.current=null,xt.current&&(L(xt.current,He),xt.current=null)},[L,He]),i.useEffect(()=>{if(!e)return;const de=()=>{M.current?.close(),M.current=null};return window.addEventListener("beforeunload",de),()=>window.removeEventListener("beforeunload",de)},[e]);const Sn=i.useCallback((de,nt)=>{yt.current&&(clearTimeout(yt.current),yt.current=null),(async()=>{try{await Ot(de,nt),await A0(de,l)}catch{}})()},[l,Ot]),dn=i.useCallback(()=>{if(vt!=="mobile")return;const de=document.activeElement;de instanceof HTMLElement&&de.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})},[vt]),Jt=i.useCallback(()=>{d&&m.type==="initial"&&v$(d,l);const de=$.current;de&&d.trim()&&Sn(de,d),$.current=null,k.current&&(clearTimeout(k.current),k.current=null),M.current?.close(),M.current=null,_(!1),U(!1),dn(),n()},[Sn,d,n,l,dn,m.type]);i.useEffect(()=>{if(!e)return;const de=nt=>{nt.key==="Escape"&&Jt()};return document.addEventListener("keydown",de),()=>document.removeEventListener("keydown",de)},[e,Jt]);const tn=i.useCallback(async de=>{if(m.type!=="question")return;const{session:nt}=m,ot=nt.sessionId,_t=nt.currentQuestion;if(!_t){p("No active question in session");return}p(null),w(G=>[...G,de]),b(G=>{const Oe=st.current.trim();let Mt=G;return Oe&&Mt[Mt.length-1]?.thinkingOutput!==Oe&&(Mt=[...Mt,{thinkingOutput:Oe}]),[...Mt,{question:_t,response:de}]}),h({type:"loading"}),N("");try{await Ym(ot,de,l,He)}catch(G){p(Se(G)||"Failed to submit response"),h({type:"question",session:nt})}},[l,He,m]),Ne=i.useCallback(async()=>{if(m.type!=="summary")return;const{session:de,summary:nt}=m,ot=de.sessionId;D.current=ot,ke(ot),p(null),U(!1),N(""),h({type:"loading"}),Pe(ot);try{await Ym(ot,{refine:!0},l,He)}catch(_t){M.current?.close(),M.current=null,p(Se(_t)||"Failed to refine plan"),h({type:"summary",session:de,summary:y??nt})}},[Pe,y,l,He,m]),W=i.useCallback(async()=>{const de=D.current;if(de){try{await wS(de,l,He)}catch{}M.current?.close(),M.current=null,_(!1),U(!1),h({type:"error",session:{sessionId:de,currentQuestion:null,summary:null},errorMessage:"Generation stopped by user. You can retry or start a new session."}),N("")}},[l,He]),Y=i.useCallback(async()=>{if(m.type!=="error")return;const de=m.session;p(null),U(!0),N(""),h({type:"loading"}),Pe(de.sessionId);try{D.current=de.sessionId,ke(de.sessionId),await yS(de.sessionId,l,He)}catch(nt){let ot=nt;if((Se(nt)||"").includes("not in an error state"))try{const G=await Di(de.sessionId);if(!G)throw new Error("Failed to refresh planning session.");if(D.current=G.id,ke(G.id),G.status==="generating")N(G.thinkingOutput??""),h({type:"loading"});else if(G.status==="awaiting_input"){if(!G.currentQuestion)throw new Error("Planning session is awaiting input but has no current question.");const Oe=JSON.parse(G.currentQuestion);if(hr(l),h({type:"question",session:{sessionId:G.id,currentQuestion:Oe,summary:null}}),G.thinkingOutput){const Mt=G.thinkingOutput.trim();Mt&&b(Xt=>Xt[Xt.length-1]?.thinkingOutput===Mt?Xt:[...Xt,{thinkingOutput:Mt}])}M.current?.isConnected()||Pe(G.id)}else if(G.status==="complete"){if(!G.result)throw new Error("Planning session is complete but has no result.");const Oe=zd(JSON.parse(G.result));hr(l),h({type:"summary",session:{sessionId:G.id,currentQuestion:null,summary:Oe},summary:Oe}),S(Oe)}else G.status==="error"&&h({type:"error",session:{sessionId:G.id,currentQuestion:null,summary:null},errorMessage:G.error||"Retry failed. Please try again."});_(!1);return}catch(G){ot=G}M.current?.close(),M.current=null,h({type:"error",session:de,errorMessage:Se(ot)||"Retry failed. Please try again."}),_(!1)}finally{U(!1)}},[Pe,l,He,m]),_e=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const de=m.session.sessionId,nt=await kS(de,y??void 0,l);s(nt),Fe(null),Ye(ot=>ot.filter(_t=>_t.id!==de)),re({sessionId:de,status:"complete",timestamp:Date.now()}),Jt()}catch(de){p(Se(de)||"Failed to create task"),h({type:"summary",session:m.session,summary:m.summary})}}},[re,y,m,l,s,Jt]),ut=i.useCallback(async()=>{if(m.type==="summary"){p(null),h({type:"loading"});try{const de=await jS(m.session.sessionId,y??void 0,l),nt=de.subtasks.map(ot=>({...ot,priority:Va(ot.priority),dependsOn:[...ot.dependsOn]}));ke(de.sessionId),h({type:"breakdown",sessionId:de.sessionId,originalSubtasks:nt.map(ot=>({...ot,dependsOn:[...ot.dependsOn]})),subtasks:nt.map(ot=>({...ot,dependsOn:[...ot.dependsOn]})),dirty:!1})}catch(de){p(Se(de)||"Failed to start breakdown"),h({type:"summary",session:m.session,summary:m.summary})}}},[y,m,l]),At=i.useCallback(async()=>{if(m.type==="breakdown"){p(null),h({type:"creating"});try{const de=m.sessionId,nt=await NS(de,b4(m.originalSubtasks,m.subtasks.map(ot=>({...ot,priority:Va(ot.priority)}))),l);a(nt.tasks),Ye(ot=>ot.filter(_t=>_t.id!==de)),re({sessionId:de,status:"complete",timestamp:Date.now()}),u(""),h({type:"initial"}),p(null),w([]),b([]),S(null),N(""),B(void 0),ze(void 0),Ve("medium"),rt(""),D.current=null,ke(null),Fe(null),Jt()}catch(de){p(Se(de)||"Failed to create tasks"),h({type:"breakdown",sessionId:m.sessionId,originalSubtasks:m.originalSubtasks,subtasks:m.subtasks,dirty:m.dirty})}}},[re,Jt,m,a,l]),zt=i.useCallback(async()=>{if(m.type!=="question"||g.length===0)return;const de=m.session.sessionId;p(null),h({type:"loading"});try{const nt=await vS(de,l,He);w(nt.history.map(ot=>ot.response&&typeof ot.response=="object"&&!Array.isArray(ot.response)?ot.response:{[ot.question.id]:ot.response})),b(nt.history.map(ot=>({question:ot.question,response:ot.response&&typeof ot.response=="object"&&!Array.isArray(ot.response)?ot.response:{[ot.question.id]:ot.response},thinkingOutput:ot.thinkingOutput}))),N(""),h({type:"question",session:{...m.session,currentQuestion:nt.currentQuestion,summary:null}})}catch(nt){p(Se(nt)||"Failed to go back to the previous question"),h({type:"question",session:m.session})}},[l,g.length,He,m]),yn=()=>m.type==="question"?Math.min(g.length+1,3):3,Zn=le?fe.get(le):null,vn=Zn&&Zn.tabId!==He,Dn=ye&&(!vn||Zn.stale);return e?t.jsx("div",{className:"modal-overlay open",onMouseDown:de=>{Ie.current=de.target===de.currentTarget},onClick:de=>{de.target===de.currentTarget&&Ie.current&&Jt(),Ie.current=!1},role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",ref:O,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[J&&t.jsx("button",{className:"modal-back planning-mobile-back",onClick:Gt,"aria-label":"Back to sessions",title:"Back to sessions",children:t.jsx(pc,{size:18})}),t.jsx(Oi,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Planning Mode"})]}),t.jsx("div",{className:"modal-header-actions",children:t.jsx("button",{className:"modal-close",onClick:Jt,"aria-label":"Close",children:t.jsx(mn,{size:20})})})]}),t.jsxs("div",{className:`planning-modal-body planning-modal-body--split ${J?"planning-modal-body--show-detail":"planning-modal-body--show-list"}`,children:[t.jsx(S4,{sessions:Me,loading:dt,selectedSessionId:St,pendingDeleteId:Ze,showArchived:gt,onToggleShowArchived:()=>$t(de=>!de),onArchive:de=>void Kt(de),onSelectSession:Lt,onNewSession:Bt,onRequestDelete:be,onConfirmDelete:de=>void en(de),onCancelDelete:()=>be(null)}),t.jsxs("div",{className:"planning-detail",children:[f&&t.jsx("div",{className:"form-error planning-error",children:f}),E&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),m.type==="initial"&&t.jsxs("div",{className:"planning-initial",children:[t.jsxs("div",{className:"planning-view-scroll",children:[t.jsxs("div",{className:"planning-intro",children:[t.jsx(ms,{size:32,className:"icon-triage-lg"}),t.jsx("h4",{children:"Transform your idea into a detailed task"}),t.jsx("p",{className:"text-muted",children:"Describe what you want to build in plain language. The AI will ask clarifying questions and help you structure a well-defined task."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"initial-plan",children:"What do you want to build?"}),t.jsx("textarea",{ref:se,id:"initial-plan",rows:4,className:"planning-textarea",placeholder:"e.g., Build a user authentication system with login, signup, and password reset...",value:d,onChange:de=>{const nt=de.target.value;u(nt),!($.current||nt.trim().length===0)&&(k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{if($.current)return;const ot=nt.trim();if(!ot)return;bS(ot,l,he&&pe?{planningModelProvider:he,planningModelId:pe}:void 0).then(G=>{$.current=G.sessionId,Ye(Oe=>Oe.some(Xt=>Xt.id===G.sessionId)?Oe:[{id:G.sessionId,type:"planning",status:"draft",title:G.title,preview:ot.length>80?`${ot.slice(0,79).trimEnd()}…`:ot,projectId:l??null,lockedByTab:null,updatedAt:new Date().toISOString(),archived:!1},...Oe].sort((Xt,_n)=>Date.parse(_n.updatedAt)-Date.parse(Xt.updatedAt))),Fe(G.sessionId)}).catch(()=>{})},300))},onKeyDown:de=>{de.key==="Enter"&&!de.shiftKey&&d.trim()&&(de.preventDefault(),Ke())},onBlur:()=>{const de=$.current;de&&d.trim()&&Sn(de,d)}})]}),t.jsxs("div",{className:"planning-examples",children:[t.jsx("span",{className:"planning-examples-label",children:"Try an example:"}),t.jsx("div",{className:"planning-example-chips",children:f4.map((de,nt)=>t.jsx("button",{className:"planning-example-chip",onClick:()=>u(de),children:de.length>40?de.slice(0,40)+"...":de},nt))})]}),t.jsx(fi,{summary:"Advanced planning settings",className:"planning-advanced-disclosure",children:t.jsxs("div",{className:"planning-advanced-content",children:[t.jsxs("div",{className:"planning-advanced-section planning-model-select-group",children:[t.jsxs("label",{htmlFor:"planning-modal-model",className:"form-label",children:["Planning Model",Re&&t.jsx("span",{className:"text-muted text-muted-sm",children:"Loading models…"})]}),t.jsx("p",{className:"planning-advanced-blurb",children:"Selects which model runs the planning interview and writes the final draft."}),t.jsx(_s,{id:"planning-modal-model",label:"Planning Model",value:qt,onChange:de=>{const{provider:nt,modelId:ot}=v4(de);B(nt),ze(ot)},models:Be,disabled:Re,favoriteProviders:ue,onToggleFavorite:Zt,favoriteModels:Ee,onToggleModelFavorite:ve}),ct&&t.jsxs("div",{className:"form-hint form-hint-error",children:[ct," ",t.jsx("button",{type:"button",className:"text-link-btn",onClick:()=>{hn()},children:"Retry"})]}),t.jsx("div",{className:"model-selector-current model-selector-current--spaced",children:t.jsx("span",{className:`model-badge ${he&&pe?"model-badge-custom":"model-badge-default"}`,children:Qt(he,pe)})})]}),t.jsxs("div",{className:"planning-advanced-section planning-depth-selector",children:[t.jsx("p",{className:"planning-advanced-blurb",children:"Plan size sets default interview depth. Questions lets you override with an exact count."}),t.jsxs("div",{className:"planning-depth-controls-row",children:[t.jsx("div",{className:"planning-depth-chip-group",role:"group","aria-label":"Planning depth",children:[{value:"small",label:"Small"},{value:"medium",label:"Medium"},{value:"large",label:"Large"}].map(de=>t.jsx("button",{type:"button",className:`planning-depth-chip btn ${ae===de.value?"btn-primary planning-depth-chip-active":""}`,onClick:()=>Ve(de.value),"aria-pressed":ae===de.value,children:de.label},de.value))}),t.jsxs("label",{className:"planning-depth-question-count",htmlFor:"planning-depth-questions",children:[t.jsx("span",{children:"Questions"}),t.jsx("input",{id:"planning-depth-questions",className:"input planning-depth-question-input",type:"number",min:1,max:20,value:Te,onChange:de=>rt(de.target.value),placeholder:"Auto"})]})]})]})]})})]}),t.jsx("div",{className:"planning-view-footer",children:t.jsxs("button",{className:"btn btn-primary planning-start-btn",onClick:()=>Ke(),disabled:!d.trim(),children:[t.jsx(Oi,{size:16,className:"icon-mr-8"}),"Start Planning"]})})]}),m.type==="loading"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:x?"AI is thinking...":"Generating next question..."}),A&&t.jsxs("div",{className:"planning-elapsed",children:["Thinking… (",H,"s)"]}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>F(!R),type:"button",children:R?"Hide thinking":"Show thinking"}),t.jsx("div",{className:"planning-loading-actions",children:t.jsxs("button",{className:"btn planning-stop-btn",type:"button",onClick:()=>void W(),children:[t.jsx(Xy,{size:14}),t.jsx("span",{className:"icon-ml-6",children:"Stop"})]})}),R&&x&&t.jsx("div",{className:"planning-thinking-output",ref:ge,children:t.jsx("pre",{children:x})})]})]}),m.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:v}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:m.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void Y(),disabled:K,children:[K?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),t.jsx("span",{className:"icon-ml-6",children:K?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:Jt,disabled:K,children:"Dismiss"})]})]})]})}),m.type==="creating"&&t.jsxs("div",{className:"planning-loading",children:[t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"Creating tasks..."})]}),m.type==="question"&&m.session.currentQuestion&&t.jsx("div",{className:"planning-question",children:t.jsx(w4,{question:m.session.currentQuestion,progress:yn(),historyEntries:v,onSubmit:tn,onBack:g.length>0?zt:void 0})}),m.type==="summary"&&y&&t.jsx(k4,{summary:y,historyEntries:v,onSummaryChange:S,tasks:r,onCreateTask:_e,onBreakIntoTasks:ut,onRefine:()=>{Ne()},isLoading:!1}),m.type==="breakdown"&&t.jsx(N4,{subtasks:m.subtasks,isLoading:!1,onUpdateSubtasks:de=>h({...m,subtasks:de,dirty:!0}),onCreateTasks:At,onBack:()=>{const nt={sessionId:m.sessionId,currentQuestion:null,summary:y??null};y&&h({type:"summary",session:nt,summary:y})}})]}),ye&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(yc,{size:16}),t.jsx("span",{children:Dn?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),Dn&&t.jsx("button",{type:"button",onClick:()=>{je()},disabled:ne,className:"btn btn-primary session-lock-take-control",children:ne?"Taking control...":"Take Control"})]})})]})]})}):null}function w4({question:e,progress:n,historyEntries:s,onSubmit:a,onBack:r}){const[o,l]=i.useState({}),[c,d]=i.useState(""),[u,m]=i.useState(""),h=i.useCallback(()=>{let p;e.type==="text"?p={[e.id]:c}:e.type==="confirm"?p={[e.id]:o[e.id]===!0}:p=o;const g=u.trim();g.length>0&&(p={...p,_comment:g}),a(p)},[u,e,o,c,a]);i.useEffect(()=>{l({}),d(""),m("")},[e.id]);const f=()=>{switch(e.type){case"text":return c.trim().length>0;case"single_select":return o[e.id]!==void 0;case"multi_select":return Array.isArray(o[e.id])&&o[e.id].length>0;case"confirm":return o[e.id]!==void 0;default:return!0}};return t.jsxs("div",{className:"planning-question-form",children:[t.jsxs("div",{className:"planning-view-scroll planning-question-scroll",children:[s.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:s}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-question-panel",children:[t.jsxs("div",{className:"planning-progress",children:[t.jsx("div",{className:"planning-progress-bar",children:[1,2,3].map(p=>t.jsx("div",{className:`planning-progress-step ${p<=n?"active":""}`},p))}),t.jsxs("span",{className:"planning-progress-text",children:["Question ",n," of ~3"]})]}),t.jsxs("div",{className:"planning-question-content",children:[t.jsx("h4",{className:"planning-question-text",children:e.question}),e.description&&t.jsx("p",{className:"planning-question-desc",children:e.description}),t.jsxs("div",{className:"planning-options",children:[e.type==="text"&&t.jsx("textarea",{className:"planning-textarea",rows:4,placeholder:"Type your answer here...",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>{p.key==="Enter"&&!p.shiftKey&&c.trim()&&(p.preventDefault(),h())}}),e.type==="single_select"&&e.options&&t.jsx("div",{className:"planning-radio-group",role:"radiogroup",children:e.options.map(p=>t.jsxs("label",{className:"planning-option planning-option--radio",children:[t.jsx("input",{type:"radio",name:e.id,value:p.id,checked:o[e.id]===p.id,onChange:()=>l({[e.id]:p.id})}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id))}),e.type==="multi_select"&&e.options&&t.jsx("div",{className:"planning-checkbox-group",children:e.options.map(p=>{const g=o[e.id]||[];return t.jsxs("label",{className:"planning-option planning-option--checkbox",children:[t.jsx("input",{type:"checkbox",value:p.id,checked:g.includes(p.id),onChange:w=>{const v=w.target.checked?[...g,p.id]:g.filter(b=>b!==p.id);l({[e.id]:v})}}),t.jsxs("div",{className:"planning-option-content",children:[t.jsx("span",{className:"planning-option-label",children:p.label}),p.description&&t.jsx("span",{className:"planning-option-desc",children:p.description})]})]},p.id)})}),e.type==="confirm"&&t.jsxs("div",{className:"planning-confirm-group",children:[t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!0?"selected":""}`,onClick:()=>l({[e.id]:!0}),children:[t.jsx(Xn,{size:18}),"Yes"]}),t.jsxs("button",{className:`planning-confirm-btn ${o[e.id]===!1?"selected":""}`,onClick:()=>l({[e.id]:!1}),children:[t.jsx(mn,{size:18}),"No"]})]})]}),e.type!=="text"&&t.jsxs("div",{className:"planning-comment-section",children:[t.jsx("label",{className:"planning-comment-label",htmlFor:`planning-comment-${e.id}`,children:"Additional comments (optional)"}),t.jsx("textarea",{id:`planning-comment-${e.id}`,className:"planning-textarea",rows:2,placeholder:"Add any extra context or direction...",value:u,onChange:p=>m(p.target.value)})]})]})]})]}),t.jsxs("div",{className:"planning-actions",children:[r&&t.jsxs("button",{className:"btn",onClick:r,children:[t.jsx(Ga,{size:16,className:"icon-mr-4"}),"Back"]}),t.jsxs("button",{className:"btn btn-primary planning-actions-primary",onClick:h,disabled:!f(),children:["Continue",t.jsx(Uo,{size:16,className:"icon-ml-4"})]})]})]})}function k4({summary:e,historyEntries:n,onSummaryChange:s,tasks:a,onCreateTask:r,onBreakIntoTasks:o,onRefine:l,isLoading:c}){const[d,u]=i.useState(!1),[m,h]=i.useState(e.suggestedDependencies),f=Va(e.priority),p=g=>{const w=m.includes(g)?m.filter(v=>v!==g):[...m,g];h(w),s({...e,suggestedDependencies:w})};return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[n.length>0&&t.jsxs(fi,{summary:"Show user Q&A",className:"planning-summary-qa-disclosure",children:[t.jsx(bi,{entries:n}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Xn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Planning Complete!"}),t.jsx("p",{className:"text-muted",children:"Review and refine your task before creating it."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{children:["Description",t.jsx("button",{type:"button",className:"planning-expand-btn",onClick:()=>u(!d),children:d?"Collapse":"Expand"})]}),t.jsx("textarea",{className:`planning-textarea ${d?"expanded":""}`,rows:d?10:4,value:e.description,onChange:g=>s({...e,description:g.target.value})})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-size",children:"Suggested Size"}),t.jsxs("select",{id:"planning-summary-size",className:"planning-size-select",value:e.suggestedSize,onChange:g=>s({...e,suggestedSize:g.target.value}),disabled:c,children:[t.jsx("option",{value:"S",children:"S (Small)"}),t.jsx("option",{value:"M",children:"M (Medium)"}),t.jsx("option",{value:"L",children:"L (Large)"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"planning-summary-priority",children:"Priority"}),t.jsx("select",{id:"planning-summary-priority",className:"planning-size-select",value:f,onChange:g=>s({...e,priority:g.target.value}),disabled:c,children:wa.map(g=>t.jsx("option",{value:g,children:g[0].toUpperCase()+g.slice(1)},g))})]})]}),a.length>0&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Suggested Dependencies"}),t.jsx("div",{className:"planning-deps-list",children:a.map(g=>t.jsxs("label",{className:`planning-dep-chip ${m.includes(g.id)?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:m.includes(g.id),onChange:()=>p(g.id)}),t.jsx("span",{className:"planning-dep-id",children:g.id}),t.jsx("span",{className:"planning-dep-title",children:g.title||g.description.slice(0,30)})]},g.id))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Key Deliverables"}),t.jsx("ul",{className:"planning-deliverables",children:e.keyDeliverables.map((g,w)=>t.jsx("li",{children:g},w))})]})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:l,disabled:c,children:[t.jsx(Ga,{size:16,className:"icon-mr-4"}),"Refine Further"]}),t.jsxs("div",{className:"planning-summary-actions-right",children:[t.jsx("button",{className:"btn",onClick:r,disabled:c,children:c?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Creating..."]}):t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:16,className:"icon-mr-8"}),"Create Single Task"]})}),t.jsx("button",{className:"btn btn-primary",onClick:o,disabled:c,title:"Break the plan into multiple tasks with dependencies",children:c?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-8"}),"Breaking down..."]}):t.jsxs(t.Fragment,{children:[t.jsx(vc,{size:16,className:"icon-mr-8"}),"Break into Tasks"]})})]})]})]})}function Of(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function j4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",priority:Ps,dependsOn:[]}}function N4({subtasks:e,isLoading:n,onUpdateSubtasks:s,onCreateTasks:a,onBack:r}){const[o,l]=i.useState(null),[c,d]=i.useState(null),[u,m]=i.useState(null),h=i.useRef([]),f=i.useMemo(()=>e.length===0||e.some(x=>!x.title.trim())?!0:Of(e),[e]),p=i.useCallback((x,N)=>{s(e.map(R=>R.id===x?{...R,...N}:R))},[e,s]),g=i.useCallback(()=>{s([...e,j4(e.length+1)])},[e,s]),w=i.useCallback(x=>{s(e.filter(N=>N.id!==x).map(N=>({...N,dependsOn:N.dependsOn.filter(R=>R!==x)})))},[e,s]),v=i.useCallback((x,N)=>{if(N<0||N>=e.length)return;const R=[...e],[F]=R.splice(x,1);R.splice(N,0,F),s(R)},[e,s]),b=i.useCallback(x=>N=>{l(x),N.dataTransfer.setData("text/plain",x),N.dataTransfer.effectAllowed="move"},[]),y=i.useCallback(()=>{l(null),d(null),m(null)},[]),S=i.useCallback(x=>N=>{if(N.preventDefault(),x===o)return;const R=N.currentTarget.getBoundingClientRect(),F=R.top+R.height/2,E=N.clientY<F?"before":"after";d(x),m(E)},[o]),j=i.useCallback(x=>N=>{N.preventDefault();const R=N.dataTransfer.getData("text/plain");if(!R||R===x){y();return}const F=e.findIndex(A=>A.id===R),E=e.findIndex(A=>A.id===x);if(F===-1||E===-1){y();return}const _=[...e],[K]=_.splice(F,1);let U=E;u==="after"&&F<E&&U--,u==="after"&&U++,_.splice(U,0,K),s(_),y()},[e,u,s,y]),C=i.useCallback(x=>{const N=x.currentTarget.getBoundingClientRect(),R=x.clientX,F=x.clientY;(R<N.left||R>N.right||F<N.top||F>N.bottom)&&(d(null),m(null))},[]);return t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(vc,{size:24,className:"icon-triage"}),t.jsx("h4",{children:"Break into Tasks"}),t.jsx("p",{className:"text-muted",children:"Review and edit the subtasks generated from your plan. Adjust titles, descriptions, sizes, priorities, and dependencies before creating."})]}),t.jsxs("div",{className:"planning-summary-form",children:[e.map((x,N)=>{const R=o===x.id,F=c===x.id,E=["task-detail-section","subtask-item",R?"subtask-item-dragging":"",F?"subtask-item-drop-target":"",F&&u==="before"?"subtask-item-drop-before":"",F&&u==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:E,"data-testid":`subtask-item-${N}`,draggable:!n,onDragStart:b(x.id),onDragEnd:y,onDragOver:S(x.id),onDrop:j(x.id),onDragLeave:C,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(xc,{size:16}),t.jsx("strong",{children:x.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(N,N-1),disabled:n||N===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(La,{size:14})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>v(N,N+1),disabled:n||N===e.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Bo,{size:14})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>w(x.id),disabled:n,children:[t.jsx(Tn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:_=>{h.current[N]=_},value:x.title,onChange:_=>p(x.id,{title:_.target.value}),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),N<e.length-1&&h.current[N+1]?.focus())},disabled:n})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:3,value:x.description,onChange:_=>p(x.id,{description:_.target.value}),disabled:n})]}),t.jsxs("div",{className:"planning-summary-meta-row",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${x.id}-size`,children:"Size"}),t.jsxs("select",{id:`${x.id}-size`,className:"planning-size-select",value:x.suggestedSize,onChange:_=>p(x.id,{suggestedSize:_.target.value}),disabled:n,children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`${x.id}-priority`,children:"Priority"}),t.jsx("select",{id:`${x.id}-priority`,className:"planning-size-select",value:Va(x.priority),onChange:_=>p(x.id,{priority:_.target.value}),disabled:n,children:wa.map(_=>t.jsx("option",{value:_,children:_[0].toUpperCase()+_.slice(1)},_))})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[e.slice(0,N).filter(_=>_.id!==x.id).map(_=>{const K=x.dependsOn.includes(_.id);return t.jsxs("label",{className:`planning-dep-chip ${K?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:K,onChange:()=>{const U=K?x.dependsOn.filter(A=>A!==_.id):[...x.dependsOn,_.id];p(x.id,{dependsOn:U})},disabled:n}),t.jsx("span",{className:"planning-dep-id",children:_.id}),t.jsx("span",{className:"planning-dep-title",children:_.title||"Untitled"})]},_.id)}),N===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),N>0&&e.slice(0,N).filter(_=>_.id!==x.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},x.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:g,disabled:n,children:[t.jsx($n,{size:16,className:"icon-mr-6"})," Add subtask"]}),Of(e)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsxs("button",{className:"btn",onClick:r,disabled:n,children:[t.jsx(Ga,{size:16,className:"icon-mr-4"}),"Back to Summary"]}),t.jsx("button",{className:"btn btn-primary",onClick:a,disabled:n||f,children:n?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]})}function S4({sessions:e,loading:n,selectedSessionId:s,pendingDeleteId:a,showArchived:r,onToggleShowArchived:o,onArchive:l,onSelectSession:c,onNewSession:d,onRequestDelete:u,onConfirmDelete:m,onCancelDelete:h}){return t.jsxs("aside",{className:"planning-sidebar","aria-label":"Planning sessions",children:[t.jsx("div",{className:"planning-sidebar-header",children:t.jsxs("button",{className:`planning-sidebar-new ${s===null?"active":""}`,onClick:d,type:"button",children:[t.jsx(pk,{size:16}),t.jsx("span",{children:"New session"})]})}),t.jsxs("div",{className:"planning-sidebar-list",children:[e.length===0&&!n&&t.jsx("div",{className:"planning-sidebar-empty text-muted",children:"No saved sessions yet. Start one on the right to see it here."}),e.map(f=>{const p=f.id===s,g=a===f.id,w=f.archived===!0,v=f.status==="complete"||f.status==="error";return t.jsxs("div",{className:`planning-sidebar-item ${p?"selected":""} ${g?"pending-delete":""} ${w?"archived":""}`,children:[t.jsxs("button",{type:"button",className:"planning-sidebar-item-button",onClick:()=>c(f.id),children:[t.jsx(C4,{status:f.status}),t.jsxs("span",{className:"planning-sidebar-item-body",children:[t.jsx("span",{className:"planning-sidebar-item-title",children:f.status==="draft"&&(!f.title||f.title==="New planning session")?f.preview??"New planning session":f.title||"Untitled session"}),t.jsxs("span",{className:"planning-sidebar-item-meta",children:[t.jsx(E4,{status:f.status}),t.jsx("span",{"aria-hidden":!0,children:" · "}),t.jsx("span",{children:_4(f.updatedAt)})]})]})]}),g?t.jsxs("div",{className:"planning-sidebar-confirm",children:[t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>m(f.id),children:"Delete"}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:h,children:"Cancel"})]}):t.jsxs("div",{className:"planning-sidebar-item-actions",children:[v&&t.jsx("button",{type:"button",className:"planning-sidebar-item-archive",onClick:b=>{b.stopPropagation(),l(f.id)},"aria-label":w?"Unarchive session":"Archive session",title:w?"Unarchive session":"Archive session",children:w?t.jsx(_y,{size:14}):t.jsx(zo,{size:14})}),t.jsx("button",{type:"button",className:"planning-sidebar-item-delete",onClick:b=>{b.stopPropagation(),u(f.id)},"aria-label":"Delete session",title:"Delete session",children:t.jsx(Tn,{size:14})})]})]},f.id)})]}),t.jsx("div",{className:"planning-sidebar-footer",children:t.jsx("a",{href:"#",className:"planning-sidebar-toggle-archived-link",onClick:f=>{f.preventDefault(),o()},"aria-pressed":r,children:r?"Hide archived":"Show archived"})})]})}function C4({status:e}){switch(e){case"generating":return t.jsx(jt,{size:14,className:"spin planning-sidebar-status-icon planning-sidebar-status-generating"});case"awaiting_input":return t.jsx(tu,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-awaiting"});case"complete":return t.jsx(Xn,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-complete"});case"error":return t.jsx(Vs,{size:14,className:"planning-sidebar-status-icon planning-sidebar-status-error"});default:return t.jsx(ta,{size:14,className:"planning-sidebar-status-icon"})}}function E4({status:e}){switch(e){case"generating":return t.jsx("span",{children:"Generating"});case"awaiting_input":return t.jsx("span",{children:"Needs input"});case"complete":return t.jsx("span",{children:"Complete"});case"error":return t.jsx("span",{children:"Error"});default:return t.jsx("span",{children:e})}}function _4(e){const n=Date.now()-Date.parse(e);if(!Number.isFinite(n)||n<0)return"";const s=Math.floor(n/1e3);if(s<60)return"just now";const a=Math.floor(s/60);if(a<60)return`${a}m ago`;const r=Math.floor(a/60);if(r<24)return`${r}h ago`;const o=Math.floor(r/24);if(o<7)return`${o}d ago`;const l=Math.floor(o/7);return l<4?`${l}w ago`:new Date(e).toLocaleDateString()}function M4(e){return{id:`subtask-${e}`,title:"",description:"",suggestedSize:"M",dependsOn:[]}}function Ff(e){const n=new Map(e.map(o=>[o.id,o.dependsOn])),s=new Set,a=new Set,r=o=>{if(s.has(o))return!0;if(a.has(o))return!1;s.add(o);for(const l of n.get(o)??[])if(n.has(l)&&r(l))return!0;return s.delete(o),a.add(o),!1};return e.some(o=>r(o.id))}function A4({isOpen:e,onClose:n,initialDescription:s,onTasksCreated:a,parentTaskId:r,projectId:o,resumeSessionId:l}){const c=oi();Mi(e);const{keyboardOverlap:d,viewportHeight:u,viewportOffsetTop:m,keyboardOpen:h}=aa({enabled:c==="mobile"}),f=h?{"--keyboard-overlap":`${d}px`,"--vv-offset-top":`${m}px`,...u!==null?{"--vv-height":`${u}px`}:{}}:{},[p,g]=i.useState({type:"initial"}),[w,v]=i.useState([]),[b,y]=i.useState([]),[S,j]=i.useState(""),[C,x]=i.useState(!0),[N,R]=i.useState(!1),[F,E]=i.useState(!1),[_,K]=i.useState(s),[U,A]=i.useState(null),[T,H]=i.useState(!1),[Q,se]=i.useState("project-default"),[O,M]=i.useState(""),[D,$]=i.useState(""),[k,X]=i.useState("shared"),[le,ke]=i.useState(null),[He,ye]=i.useState(null),[je,ne]=i.useState(null),fe=i.useRef(null),Z=i.useRef([]),re=i.useRef(!1),q=i.useRef(null),L=p.type==="generating"||p.type==="editing"||p.type==="creating"||p.type==="error"?p.sessionId:null,xe=i.useMemo(()=>Ja(),[]),{isLockedByOther:he,takeControl:B,isLoading:pe}=Tc(e?L:null),{activeTabMap:ze,broadcastUpdate:ae,broadcastCompleted:Ve,broadcastLock:Te,broadcastUnlock:rt,broadcastHeartbeat:Be}=Wr(),ce=i.useMemo(()=>w.length===0||w.some(Ie=>!Ie.title.trim())||(Q==="existing"||Q==="custom-new")&&!O.trim()?!0:Ff(w),[Q,O,w]),Re=p.type==="generating"||p.type==="editing"||p.type==="error",Le=L?ze.get(L):null,{confirm:ct}=li(),Ue=Le&&Le.tabId!==xe,ue=!!(Ue&&!Le.stale),oe=he&&(!Ue||Le.stale),Ee=i.useCallback(()=>{_&&w$(_,o),fe.current?.close(),fe.current=null,g({type:"initial"}),v([]),y([]),j(""),x(!0),R(!1),E(!1),A(null),H(!1),se("project-default"),M(""),$(""),X("shared"),re.current=!1},[_,o]),ft=i.useCallback(()=>{fe.current?.close(),fe.current=null,n()},[n]),ht=i.useCallback(async()=>{if(!((T||p.type==="editing"||p.type==="creating")&&!await ct({title:"Discard Changes",message:"Close subtask breakdown? Unsaved changes will be lost.",danger:!0}))){if(L)try{await bb(L,o,xe)}catch{}Ee(),n()}},[T,n,Ee,L,xe,p.type,o,ct]),tt=i.useCallback(Ie=>{fe.current?.close(),fe.current=ZS(Ie,o,{onThinking:ge=>{j(st=>st+ge),ae({sessionId:Ie,status:"generating",needsInput:!1,owningTabId:xe,type:"subtask",title:_.trim()||void 0,projectId:o??null})},onSubtasks:ge=>{R(!1),E(!1),Id(o),v(ge),g({type:"editing",sessionId:Ie}),H(!1),ae({sessionId:Ie,status:"awaiting_input",needsInput:!0,owningTabId:xe,type:"subtask",title:_.trim()||void 0,projectId:o??null})},onError:ge=>{const st=ge||"Session failed while contacting the AI.";R(!1),E(!1),A(null),g({type:"error",sessionId:Ie,errorMessage:st}),ae({sessionId:Ie,status:"error",needsInput:!1,owningTabId:xe,type:"subtask",title:_.trim()||void 0,projectId:o??null}),Ve({sessionId:Ie,status:"error"})},onComplete:()=>{Ve({sessionId:Ie,status:"complete"})},onConnectionStateChange:ge=>{R(ge==="reconnecting")}})},[Ve,ae,_,o,xe]),xt=i.useCallback(async()=>{if(_.trim()){A(null),y([]),j(""),R(!1);try{const{sessionId:Ie}=await YS(_.trim(),o);g({type:"generating",sessionId:Ie}),tt(Ie)}catch(Ie){A(Se(Ie)||"Failed to start subtask breakdown"),g({type:"initial"})}}},[tt,_,o]);i.useEffect(()=>{if(!e){Ee();return}if(e&&s&&!re.current)K(s),re.current=!0,xt();else if(e&&!s&&!re.current){const Ie=k$(o);Ie&&K(Ie)}},[e,s,xt,Ee]),i.useEffect(()=>{!e||!l||p.type!=="initial"||(async()=>{try{const Ie=await Di(l);if(!Ie)return;const ge=Mr(Ie.conversationHistory);if(y(ge),Ie.status==="generating"||Ie.status==="awaiting_input")j(Ie.thinkingOutput??""),g({type:"generating",sessionId:l}),tt(l);else if(Ie.status==="complete"&&Ie.result){Id(o);const st=JSON.parse(Ie.result);v(st),g({type:"editing",sessionId:l})}else Ie.status==="error"&&(A(null),g({type:"error",sessionId:l,errorMessage:Ie.error??"Session encountered an error"}))}catch(Ie){A(Se(Ie)||"Failed to resume session")}})()},[tt,e,l,p.type,o]),i.useEffect(()=>{if(!e){q.current&&(rt(q.current,xe),q.current=null);return}if(L&&q.current!==L){q.current&&rt(q.current,xe),Te(L,xe),q.current=L;return}!L&&q.current&&(rt(q.current,xe),q.current=null)},[Te,rt,e,L,xe]),i.useEffect(()=>{if(!e||!L||q.current!==L)return;Be(xe);const Ie=setInterval(()=>{Be(xe)},3e4);return()=>{clearInterval(Ie)}},[Be,e,L,xe]),i.useEffect(()=>()=>{fe.current?.close(),q.current&&(rt(q.current,xe),q.current=null)},[rt,xe]),i.useEffect(()=>{if(!e)return;const Ie=ge=>{ge.key==="Escape"&&(ge.preventDefault(),ht())};return document.addEventListener("keydown",Ie),()=>document.removeEventListener("keydown",Ie)},[e,ht]);const Me=i.useCallback((Ie,ge)=>{v(st=>st.map(yt=>yt.id===Ie?{...yt,...ge}:yt)),H(!0)},[]),Ye=i.useCallback(()=>{v(Ie=>[...Ie,M4(Ie.length+1)]),H(!0)},[]),dt=i.useCallback(Ie=>{v(ge=>ge.filter(st=>st.id!==Ie).map(st=>({...st,dependsOn:st.dependsOn.filter(yt=>yt!==Ie)}))),H(!0)},[]),wt=i.useCallback(Ie=>ge=>{ke(Ie),ge.dataTransfer.setData("text/plain",Ie),ge.dataTransfer.effectAllowed="move"},[]),St=i.useCallback(()=>{ke(null),ye(null),ne(null)},[]),Fe=i.useCallback(Ie=>ge=>{if(ge.preventDefault(),Ie===le)return;const st=ge.currentTarget.getBoundingClientRect(),yt=st.top+st.height/2,pt=ge.clientY<yt?"before":"after";ye(Ie),ne(pt)},[le]),J=i.useCallback(Ie=>ge=>{ge.preventDefault();const st=ge.dataTransfer.getData("text/plain");if(!st||st===Ie){ke(null),ye(null),ne(null);return}v(yt=>{const pt=yt.findIndex(on=>on.id===st),vt=yt.findIndex(on=>on.id===Ie);if(pt===-1||vt===-1)return yt;const Ut=[...yt],[Dt]=Ut.splice(pt,1);let nn=vt;return je==="after"&&pt<vt&&nn--,je==="after"&&nn++,Ut.splice(nn,0,Dt),Ut}),H(!0),ke(null),ye(null),ne(null)},[je]),me=i.useCallback(Ie=>{const ge=Ie.currentTarget.getBoundingClientRect(),st=Ie.clientX,yt=Ie.clientY;(st<ge.left||st>ge.right||yt<ge.top||yt>ge.bottom)&&(ye(null),ne(null))},[]),Ze=i.useCallback((Ie,ge)=>{ge<0||ge>=w.length||(v(st=>{const yt=[...st],[pt]=yt.splice(Ie,1);return yt.splice(ge,0,pt),yt}),H(!0))},[w.length]),be=i.useCallback(Ie=>{Z.current[Ie+1]?.focus()},[]),gt=i.useCallback(async()=>{if(!(!L||ce)){A(null),g({type:"creating",sessionId:L});try{const Ie=await e1(L,w,r,o,{branchSelection:{mode:Q,...Q==="existing"||Q==="custom-new"?{branchName:O}:{},...D.trim()?{baseBranch:D.trim()}:{}},branchAssignment:{mode:k}});a(Ie.tasks),Ee(),n()}catch(Ie){A(Se(Ie)||"Failed to create tasks"),g({type:"editing",sessionId:L})}}},[D,k,Q,O,ce,n,a,r,o,Ee,L,w]),$t=i.useCallback(async()=>{if(p.type!=="error")return;const Ie=p.sessionId;A(null),E(!0),j(""),g({type:"generating",sessionId:Ie}),tt(Ie);try{await QS(Ie,o,xe)}catch(ge){let st=ge;if((Se(ge)||"").includes("not in an error state"))try{const pt=await Di(Ie);if(!pt)throw new Error("Failed to refresh subtask session.");if(y(Mr(pt.conversationHistory)),pt.status==="generating"||pt.status==="awaiting_input")j(pt.thinkingOutput??""),g({type:"generating",sessionId:pt.id}),fe.current?.isConnected()||tt(pt.id);else if(pt.status==="complete"){if(!pt.result)throw new Error("Subtask session is complete but has no result.");Id(o);const vt=JSON.parse(pt.result);v(vt),g({type:"editing",sessionId:pt.id}),H(!1)}else pt.status==="error"&&g({type:"error",sessionId:pt.id,errorMessage:pt.error??"Retry failed. Please try again."});R(!1);return}catch(pt){st=pt}fe.current?.close(),fe.current=null,g({type:"error",sessionId:Ie,errorMessage:Se(st)||"Retry failed. Please try again."}),R(!1)}finally{E(!1)}},[tt,o,xe,p]);return e?t.jsx("div",{className:"modal-overlay open",onClick:Ie=>Ie.target===Ie.currentTarget&&void ht(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg planning-modal",style:f,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(vc,{size:20,className:"icon-triage"}),t.jsx("h3",{children:"Subtask Breakdown"})]}),t.jsxs("div",{className:"modal-header-actions",children:[Re&&t.jsx("button",{className:"modal-send-to-background",onClick:ft,title:"Send to background","aria-label":"Send to background",children:t.jsx(qo,{size:16})}),t.jsx("button",{className:"modal-close",onClick:()=>void ht(),"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"planning-modal-body",children:[U&&t.jsx("div",{className:"form-error planning-error",children:U}),N&&t.jsx("div",{className:"form-hint text-muted",children:"Reconnecting…"}),ue&&t.jsx("div",{className:"form-hint text-muted","data-testid":"session-active-another-tab-banner",children:"Session is active in another tab."}),p.type==="initial"&&t.jsx("div",{className:"planning-initial",children:t.jsxs("div",{className:"planning-view-scroll",children:[t.jsx("p",{className:"text-muted",children:"Preparing to break this task into subtasks."}),t.jsx("pre",{className:"planning-thinking-output",children:_})]})}),p.type==="generating"&&t.jsxs("div",{className:"planning-loading",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsx(jt,{size:40,className:"spin icon-todo"}),t.jsx("p",{children:"AI is generating subtasks..."}),t.jsxs("div",{className:"planning-thinking-container",children:[t.jsx("button",{className:"planning-thinking-toggle",onClick:()=>x(!C),type:"button",children:C?"Hide thinking":"Show thinking"}),C&&S&&t.jsx("div",{className:"planning-thinking-output",children:t.jsx("pre",{children:S})})]})]}),p.type==="error"&&t.jsx("div",{className:"planning-summary",children:t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:b,defaultShowThinking:!0}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"ai-error-panel",role:"alert",children:[t.jsx("div",{className:"ai-error-icon",children:"⚠️"}),t.jsx("div",{className:"ai-error-message",children:p.errorMessage}),t.jsxs("div",{className:"ai-error-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:()=>void $t(),disabled:F,children:[F?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),t.jsx("span",{className:"icon-ml-6",children:F?"Retrying...":"Retry"})]}),t.jsx("button",{className:"btn",onClick:()=>void ht(),disabled:F,children:"Cancel"})]})]})]})}),(p.type==="editing"||p.type==="creating")&&t.jsxs("div",{className:"planning-summary",children:[t.jsxs("div",{className:"planning-view-scroll planning-summary-scroll",children:[b.length>0&&t.jsxs(t.Fragment,{children:[t.jsx(bi,{entries:b}),t.jsx("div",{className:"conversation-separator"})]}),t.jsxs("div",{className:"planning-summary-header",children:[t.jsx(Xn,{size:24,className:"icon-success"}),t.jsx("h4",{children:"Review your subtasks"}),t.jsx("p",{className:"text-muted",children:"Edit titles, descriptions, sizes, and dependencies before creating all tasks at once."})]}),t.jsxs("div",{className:"planning-summary-form",children:[t.jsxs("div",{className:"task-detail-section",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch strategy"}),t.jsxs("select",{value:Q,onChange:Ie=>se(Ie.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"project-default",children:"Use project/default branch"}),t.jsx("option",{value:"auto-new",children:"Create auto-named branch per task"}),t.jsx("option",{value:"existing",children:"Use existing branch"}),t.jsx("option",{value:"custom-new",children:"Create custom new branch"})]})]}),(Q==="existing"||Q==="custom-new")&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Branch name"}),t.jsx("input",{value:O,onChange:Ie=>M(Ie.target.value),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Merge target / base branch (optional)"}),t.jsx("input",{value:D,onChange:Ie=>$(Ie.target.value),disabled:p.type==="creating",placeholder:"main"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Planning branch mode"}),t.jsxs("select",{value:k,onChange:Ie=>X(Ie.target.value),disabled:p.type==="creating",children:[t.jsx("option",{value:"shared",children:"Shared branch for all subtasks"}),t.jsx("option",{value:"per-task-derived",children:"Per-task branch derived from planning branch"})]})]})]}),w.map((Ie,ge)=>{const st=le===Ie.id,yt=He===Ie.id,pt=["task-detail-section","subtask-item",st?"subtask-item-dragging":"",yt?"subtask-item-drop-target":"",yt&&je==="before"?"subtask-item-drop-before":"",yt&&je==="after"?"subtask-item-drop-after":""].filter(Boolean).join(" ");return t.jsxs("div",{className:pt,"data-testid":`subtask-item-${ge}`,draggable:p.type!=="creating",onDragStart:wt(Ie.id),onDragEnd:St,onDragOver:Fe(Ie.id),onDrop:J(Ie.id),onDragLeave:me,children:[t.jsxs("div",{className:"detail-title-row subtask-item-header subtask-item-header--between",children:[t.jsxs("div",{className:"subtask-drag-handle",title:"Drag to reorder",children:[t.jsx(xc,{size:16}),t.jsx("strong",{children:Ie.id})]}),t.jsxs("div",{className:"subtask-item-actions",children:[t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ze(ge,ge-1),disabled:p.type==="creating"||ge===0,title:"Move up","aria-label":"Move subtask up",children:t.jsx(La,{})}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>Ze(ge,ge+1),disabled:p.type==="creating"||ge===w.length-1,title:"Move down","aria-label":"Move subtask down",children:t.jsx(Bo,{})}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>dt(Ie.id),disabled:p.type==="creating",children:[t.jsx(Tn,{size:14})," Remove"]})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Title"}),t.jsx("input",{ref:vt=>{Z.current[ge]=vt},value:Ie.title,onChange:vt=>Me(Ie.id,{title:vt.target.value}),onKeyDown:vt=>{vt.key==="Enter"&&(vt.preventDefault(),be(ge))},disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{rows:8,value:Ie.description,onChange:vt=>Me(Ie.id,{description:vt.target.value}),disabled:p.type==="creating"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Size"}),t.jsxs("select",{className:"planning-size-select",value:Ie.suggestedSize,onChange:vt=>Me(Ie.id,{suggestedSize:vt.target.value}),disabled:p.type==="creating",children:[t.jsx("option",{value:"S",children:"S"}),t.jsx("option",{value:"M",children:"M"}),t.jsx("option",{value:"L",children:"L"})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Dependencies"}),t.jsxs("div",{className:"planning-deps-list",children:[w.slice(0,ge).filter(vt=>vt.id!==Ie.id).map(vt=>{const Ut=Ie.dependsOn.includes(vt.id);return t.jsxs("label",{className:`planning-dep-chip ${Ut?"selected":""}`,children:[t.jsx("input",{type:"checkbox",checked:Ut,onChange:()=>{const Dt=Ut?Ie.dependsOn.filter(nn=>nn!==vt.id):[...Ie.dependsOn,vt.id];Me(Ie.id,{dependsOn:Dt})},disabled:p.type==="creating"}),t.jsx("span",{className:"planning-dep-id",children:vt.id}),t.jsx("span",{className:"planning-dep-title",children:vt.title||"Untitled"})]},vt.id)}),ge===0&&t.jsx("div",{className:"text-muted",children:"First subtask cannot have dependencies."}),ge>0&&w.slice(0,ge).filter(vt=>vt.id!==Ie.id).length===0&&t.jsx("div",{className:"text-muted",children:"No previous subtasks available."})]})]})]},Ie.id)}),t.jsxs("button",{type:"button",className:"btn",onClick:Ye,disabled:p.type==="creating",children:[t.jsx($n,{size:16,className:"icon-mr-6"})," Add subtask"]}),Ff(w)&&t.jsx("div",{className:"form-error planning-error",children:"Dependencies contain a cycle. Remove circular references before creating tasks."})]})]}),t.jsxs("div",{className:"planning-actions planning-summary-actions",children:[t.jsx("button",{className:"btn",onClick:()=>void ht(),disabled:p.type==="creating",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:()=>void gt(),disabled:p.type==="creating"||ce,children:p.type==="creating"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"spin icon-mr-6"}),"Creating..."]}):t.jsx(t.Fragment,{children:"Create Tasks"})})]})]}),he&&t.jsx("div",{className:"session-lock-overlay","data-testid":"session-lock-overlay",children:t.jsxs("div",{className:"session-lock-banner",children:[t.jsx(yc,{size:16}),t.jsx("span",{children:oe?"This session is active in another tab":"This session is active in another tab (live heartbeat)"}),oe&&t.jsx("button",{type:"button",onClick:()=>{B()},disabled:pe,className:"btn btn-primary session-lock-take-control",children:pe?"Taking control...":"Take Control"})]})})]})]})}):null}const R4=5,I4=1e3,T4=45e3;function Al(){return{scrollback:null,connected:null,data:[]}}function P4(e,n){const[s,a]=i.useState("disconnected"),r=i.useRef(0),o=i.useRef(e),l=i.useRef(n),c=o.current!==e||l.current!==n;c&&(o.current=e,l.current=n,r.current++);const d=i.useRef(null),u=i.useRef(0),m=i.useRef(null),h=i.useRef(null),f=i.useRef(!1),p=i.useRef(new Set),g=i.useRef(new Set),w=i.useRef(new Set),v=i.useRef(new Set),b=i.useRef(new Set),y=i.useRef(Al()),S=i.useCallback(A=>{p.current.add(A);const T=y.current;return T.data.length>0&&(T.data.forEach(H=>A(H)),T.data=[]),()=>p.current.delete(A)},[]),j=i.useCallback(A=>(g.current.add(A),()=>g.current.delete(A)),[]),C=i.useCallback(A=>{w.current.add(A);const T=y.current;return T.connected&&(A(T.connected),T.connected=null),()=>w.current.delete(A)},[]),x=i.useCallback(A=>{v.current.add(A);const T=y.current;return T.scrollback&&(A(T.scrollback),T.scrollback=null),()=>v.current.delete(A)},[]),N=i.useCallback(A=>(b.current.add(A),()=>b.current.delete(A)),[]),R=i.useCallback(A=>{const T=d.current;T?.readyState===WebSocket.OPEN&&T.send(JSON.stringify({type:"input",data:A}))},[]),F=i.useCallback((A,T)=>{const H=d.current;H?.readyState===WebSocket.OPEN&&H.send(JSON.stringify({type:"resize",cols:A,rows:T}))},[]),E=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Al()},[]),_=i.useCallback(()=>{m.current&&(clearTimeout(m.current),m.current=null),h.current&&(clearInterval(h.current),h.current=null),d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),y.current=Al()},[]),K=i.useCallback(()=>{if(!e){a("disconnected");return}if(d.current?.readyState===WebSocket.OPEN)return;d.current&&(f.current=!0,d.current.onopen=null,d.current.onmessage=null,d.current.onclose=null,d.current.onerror=null,d.current.close(),d.current=null),f.current=!1,a("connecting");const A=r.current;let H=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/api/terminal/ws?sessionId=${encodeURIComponent(e)}`;n&&(H+=`&projectId=${encodeURIComponent(n)}`);const Q=new WebSocket(Fi(H));d.current=Q,Q.onopen=()=>{if(r.current!==A){Q.close();return}y.current=Al(),a("connected"),u.current=0,h.current&&clearInterval(h.current),h.current=setInterval(()=>{r.current===A&&Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify({type:"ping"}))},T4)},Q.onmessage=se=>{if(r.current===A)try{const O=JSON.parse(se.data),M=y.current;switch(O.type){case"data":O.data&&(p.current.size===0&&M.data.push(O.data),p.current.forEach(D=>D(O.data)));break;case"scrollback":O.data&&(M.scrollback=O.data,v.current.forEach(D=>D(O.data)));break;case"connected":O.shell&&O.cwd&&(M.connected={shell:O.shell,cwd:O.cwd},w.current.forEach(D=>D({shell:O.shell,cwd:O.cwd})));break;case"exit":O.exitCode!==void 0&&g.current.forEach(D=>D(O.exitCode));break;case"ping":Q.readyState===WebSocket.OPEN&&Q.send(JSON.stringify({type:"pong"}));break;case"pong":break}}catch{}},Q.onclose=se=>{if(r.current!==A)return;if(d.current=null,h.current&&(clearInterval(h.current),h.current=null),f.current){a("disconnected");return}if(se.code===4e3||se.code===4004){a("disconnected"),se.code===4004&&b.current.forEach(D=>D());return}if(u.current++,u.current>R4){a("disconnected");return}const O=I4*Math.pow(2,u.current-1);a("reconnecting");const M=r.current;m.current=setTimeout(()=>{r.current===M&&(f.current||K())},Math.min(O,16e3))},Q.onerror=()=>{}},[e,n]),U=i.useCallback(()=>{u.current=0,_(),K()},[_,K]);return i.useEffect(()=>(c&&(E(),u.current=0,a("disconnected")),e?K():a("disconnected"),_),[e,n,c,K,_,E]),{connectionStatus:s,sendInput:R,resize:F,onData:S,onExit:j,onConnect:C,onScrollback:x,reconnect:U,onSessionInvalid:N}}const Ev="kb-terminal-tabs",$4=15e3,D4=15e3;function zf(){return`tab-${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function Bf(e){if(typeof window>"u")return[];try{const n=Gn(Ev,e);if(n)return JSON.parse(n)}catch{}return[]}function Bd(e){const n=e instanceof Error?e.message:typeof e=="string"?e:"";return n.includes("Failed to parse URL")||n.includes("Invalid URL")}function Uf(e,n,s){let a;const r=new Promise((o,l)=>{a=setTimeout(()=>l(new Error(`${s} timed out after ${n}ms`)),n)});return Promise.race([e,r]).finally(()=>clearTimeout(a))}function L4(e){const[n,s]=i.useState(()=>Bf(e)),[a,r]=i.useState(!1),[o,l]=i.useState(!0),[c,d]=i.useState(null),[u,m]=i.useState(0),h=i.useRef(0);i.useEffect(()=>{h.current+=1,s(Bf(e)),r(!1),l(!0),d(null)},[e]),i.useEffect(()=>{try{fs(Ev,JSON.stringify(n),e)}catch{}},[e,n]),i.useEffect(()=>{let C=!1;const x=h.current;return(async()=>{if(!C)try{const R=await Uf(HN(e),$4,"listTerminalSessions");if(C||x!==h.current)return;const F=new Set(R.map(E=>E.id));l(!0),s(E=>{if(C||x!==h.current)return E;const K=E.map(T=>({...T,_verified:F.has(T.sessionId)})).filter(T=>T._verified);if(K.length===0)return[];const U=K.map(({_verified:T,...H})=>H);return U.find(T=>T.isActive)?U:U.map((T,H)=>({...T,isActive:H===0}))}),r(!0)}catch(R){if(C||x!==h.current)return;const F=Bd(R);F||console.warn("Failed to validate terminal sessions with server:",R),l(!F),r(!0)}})(),()=>{C=!0}},[e]),i.useEffect(()=>{if(n.length===0&&a&&o){const C=h.current,x=setTimeout(()=>{Uf(il(void 0,void 0,void 0,e),D4,"createTerminalSession").then(N=>{if(C!==h.current)return;const R={id:zf(),sessionId:N.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};s(F=>F.length>0?F:[...F.map(_=>({..._,isActive:!1})),R]),d(null)}).catch(N=>{if(C!==h.current)return;Bd(N)||console.error(N);const R=N instanceof Error?N.message:typeof N=="string"?N:"Failed to create terminal session";d(R)})},0);return()=>clearTimeout(x)}},[a,o,n.length,u]);const f=i.useCallback(async()=>{const C=await il(void 0,void 0,void 0,e),x={id:zf(),sessionId:C.sessionId,title:`Terminal ${n.length+1}`,isActive:!0,createdAt:Date.now()};return s(N=>[...N.map(F=>({...F,isActive:!1})),x]),x},[n.length]),p=i.useCallback(async()=>f(),[f]),g=i.useCallback(C=>{s(x=>{const N=x.find(_=>_.id===C);if(!N)return x;Wm(N.sessionId,e).catch(_=>{console.warn(`Failed to kill terminal session ${N.sessionId}:`,_)});const R=x.findIndex(_=>_.id===C),F=N.isActive,E=x.filter(_=>_.id!==C);if(E.length===0)return[];if(F){const _=Math.min(R,E.length-1);return E.map((K,U)=>({...K,isActive:U===_}))}return E})},[]),w=i.useCallback(C=>{s(x=>{let N=!1;const R=x.map(F=>F.id===C?(N=!0,{...F,isActive:!0}):{...F,isActive:!1});return N?R:x})},[]),v=i.useCallback((C,x)=>{s(N=>N.map(R=>R.id===C?{...R,title:x}:R))},[]),b=i.useCallback(async()=>{s(N=>{const R=N.find(F=>F.isActive);return R&&Wm(R.sessionId,e).catch(F=>{console.warn(`Failed to kill old session ${R.sessionId}:`,F)}),N});const C=n.find(N=>N.isActive);if(!C)return;const x=await il(void 0,void 0,void 0,e);s(N=>N.map(R=>R.id===C.id?{...R,sessionId:x.sessionId}:R))},[n]),y=i.useCallback(async()=>{const C=n.find(x=>x.isActive);if(C)try{const x=await il(void 0,void 0,void 0,e);s(N=>N.map(R=>R.id===C.id?{...R,sessionId:x.sessionId}:R)),d(null)}catch(x){Bd(x)||console.error(x);const N=x instanceof Error?x.message:typeof x=="string"?x:"Failed to create terminal session";d(N)}},[n]),S=n.find(C=>C.isActive)??null,j=i.useCallback(()=>{d(null),h.current+=1,m(C=>C+1)},[]);return{tabs:n,activeTab:S,isReady:a,bootstrapError:c,createTab:p,closeTab:g,setActiveTab:w,updateTabTitle:v,restartActiveTab:b,retryBootstrap:j,replaceActiveTabSession:y}}const O4=1e4,F4=[500,1500,3e3],_v="kb-terminal-font-size",jo=14,z4=8,B4=32,U4='"Fusion Terminal Nerd Font Symbols", "MesloLGS NF", "MesloLGM Nerd Font", "JetBrainsMono Nerd Font", "FiraCode Nerd Font", "Hack Nerd Font", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace';function H4(e){if(!e)return"";const n=e.slice(0,1).toUpperCase();return n==="["?"\x1B":n>="A"&&n<="Z"?String.fromCharCode(n.charCodeAt(0)-64):e}function q4(e){return`\x1B${e}`}const V4=[{label:"C",key:"c",description:"SigInt"},{label:"D",key:"d",description:"EOF"},{label:"Z",key:"z",description:"Suspend"},{label:"L",key:"l",description:"Clear"},{label:"R",key:"r",description:"Reverse search"},{label:"A",key:"a",description:"Home"},{label:"E",key:"e",description:"End"},{label:"U",key:"u",description:"Kill line"},{label:"K",key:"k",description:"Kill to EOL"},{label:"W",key:"w",description:"Del word"},{label:".",key:".",description:"Last argument"}];function No(e){return Math.min(B4,Math.max(z4,e))}function W4(){if(typeof window>"u")return jo;try{const e=window.localStorage.getItem(_v);if(!e)return jo;const n=Number.parseInt(e,10);return Number.isFinite(n)?No(n):jo}catch{return jo}}function G4(e){const n=typeof e=="string"?e:e instanceof Error?e.message:String(e);return n.includes("MIME type")||n.includes("Failed to fetch dynamically imported module")}function K4(e){return new Promise(n=>setTimeout(n,e))}async function J4(e,n=F4){let s;for(let a=0;a<=n.length;a+=1)try{return await e()}catch(r){if(!G4(r))throw r;s===void 0&&(s=r);const o=n[a];if(o===void 0)throw s??r;const l=r instanceof Error?r.message:String(r);console.warn(`[TerminalModal] Dynamic xterm import failed (attempt ${a+1}/${n.length+1}). Retrying in ${o}ms...`,l),await K4(o)}throw s??new Error("Dynamic import failed")}function Hf(){if(typeof window>"u")return!1;const e="ontouchstart"in window||navigator.maxTouchPoints>0,n=window.innerWidth<=768;return e&&n}function Y4(){if(typeof window>"u"||!window.visualViewport)return 0;const e=window.visualViewport,n=Math.max(0,window.innerHeight-e.offsetTop-e.height);if(n>0)return n;const a=Q4()-e.offsetTop-e.height;return a>=30&&a>80?a:0}let Ud=null;function Q4(){return Ud===null&&(Ud=window.innerHeight),Ud}function X4({isOpen:e,onClose:n,initialCommand:s,projectId:a}){const[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(0),[g,w]=i.useState(0),[v,b]=i.useState(null),[y,S]=i.useState(()=>W4()),[j,C]=i.useState(!1),[x,N]=i.useState(null),R=i.useRef(null),F=i.useRef(null),E=i.useRef(!1);zi(F,e,"fusion:terminal-modal-size");const _=i.useRef(null),K=i.useRef(null),U=i.useRef(!1),A=i.useRef(!1),T=i.useRef(null),H=i.useRef(()=>{}),Q=i.useRef(null),se=i.useRef(0),O=i.useRef(y),M=i.useRef(null),D=i.useRef(a);se.current=g,O.current=y;const $=i.useCallback(Me=>{if(Me&&A.current!==Me)return;const Ye=K.current,dt=_.current,wt=T.current;if(!(!Ye||!dt)&&!(Me&&A.current!==Me))try{Ye.fit(),wt&&wt(dt.cols,dt.rows)}catch{}},[]);i.useEffect(()=>{e&&p(Me=>Me+1)},[e]),i.useEffect(()=>{if(!e||!Hf())return;const Me=window.visualViewport;if(!Me)return;const Ye=()=>{const dt=Y4();w(dt),b(Me.height),dt>0&&F.current?.scrollIntoView&&F.current.scrollIntoView({block:"end",behavior:"smooth"}),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const wt=typeof A.current=="string"?A.current:void 0;M.current=requestAnimationFrame(()=>{M.current=null,$(wt)})};return Ye(),Me.addEventListener("resize",Ye),Me.addEventListener("scroll",Ye),()=>{Me.removeEventListener("resize",Ye),Me.removeEventListener("scroll",Ye),M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),w(0),b(null)}},[$,e]),i.useEffect(()=>{if(!e)return;const Me=F.current;if(!Me||typeof ResizeObserver>"u")return;let Ye=null;const dt=new ResizeObserver(()=>{Ye!==null&&cancelAnimationFrame(Ye),Ye=requestAnimationFrame(()=>{Ye=null;const wt=typeof A.current=="string"?A.current:void 0;$(wt)})});return dt.observe(Me),()=>{dt.disconnect(),Ye!==null&&cancelAnimationFrame(Ye)}},[$,e]);const{tabs:k,activeTab:X,isReady:le,bootstrapError:ke,createTab:He,closeTab:ye,setActiveTab:je,updateTabTitle:ne,restartActiveTab:fe,retryBootstrap:Z,replaceActiveTabSession:re}=L4(a),{connectionStatus:q,sendInput:L,resize:xe,onData:he,onConnect:B,onExit:pe,onScrollback:ze,reconnect:ae,onSessionInvalid:Ve}=P4(X?.sessionId??null,a);T.current=xe,H.current=L,i.useEffect(()=>{if(!(typeof window>"u"))try{window.localStorage.setItem(_v,String(y))}catch{}},[y]);const Te=i.useCallback(()=>{const Me=_.current;if(Me)try{K.current?.fit(),xe(Me.cols,Me.rows)}catch{}},[xe]);i.useEffect(()=>{if(!e||!le)return;const Me=X?.sessionId;if(!Me)return;const Ye=D.current!==a;if(Ye&&(D.current=a),A.current===Me&&_.current&&!Ye)return;_.current&&(A.current!==Me||Ye)&&(_.current.dispose(),_.current=null,K.current=null,A.current=!1,Q.current&&(window.removeEventListener("resize",Q.current),Q.current=null),u(!1),h(null));let dt=!0,wt;return(async()=>{const Fe=J4(()=>Promise.all([En(()=>import("./vendor-xterm-DzcZoU0P.js").then(be=>be.x),__vite__mapDeps([5,1,6])),En(()=>import("./addon-fit-C7jRorKK.js").then(be=>be.a),__vite__mapDeps([8,1])),En(()=>import("./addon-web-links-CkJwd4cQ.js").then(be=>be.a),__vite__mapDeps([9,1]))])),J=new Promise((be,gt)=>{wt=setTimeout(()=>{gt(new Error("xterm initialization timed out"))},O4)});let me,Ze;try{const[{Terminal:be},{FitAddon:gt},{WebLinksAddon:$t}]=await Promise.race([Fe,J]);if(!dt||!R.current||_.current)return;me=new be({cursorBlink:!0,cursorStyle:"block",fontSize:O.current,fontFamily:U4,theme:{background:"#1e1e1e",foreground:"#d4d4d4",cursor:"#d4d4d4",selectionBackground:"#264f78",black:"#1e1e1e",red:"#f48771",green:"#4ec9b0",yellow:"#dcdcaa",blue:"#569cd6",magenta:"#c586c0",cyan:"#9cdcfe",white:"#d4d4d4"},allowProposedApi:!0,scrollback:5e3}),Ze=new gt,me.loadAddon(Ze);const Ie=new $t;if(me.loadAddon(Ie),!Hf())try{const{WebglAddon:yt}=await En(async()=>{const{WebglAddon:vt}=await import("./addon-webgl-BjvOw43o.js").then(Ut=>Ut.a);return{WebglAddon:vt}},__vite__mapDeps([10,1])),pt=new yt;pt.onContextLoss(()=>{pt.dispose()}),me.loadAddon(pt)}catch{}me.open(R.current),wt&&clearTimeout(wt);const ge=R.current?.querySelector(".xterm-helper-textarea");if(ge&&ge.focus(),R.current)try{R.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}setTimeout(()=>{Ze.fit();const yt=R.current?.querySelector(".xterm-helper-textarea");yt&&yt.focus()},50),_.current=me,K.current=Ze,A.current=Me,se.current>0&&(M.current!==null&&(cancelAnimationFrame(M.current),M.current=null),M.current=requestAnimationFrame(()=>{M.current=null,$(Me)})),me.onData(yt=>{A.current===Me&&H.current(yt)});const st=()=>{if(A.current===Me&&K.current&&_.current)try{K.current.fit();const{cols:yt,rows:pt}=_.current;T.current?.(yt,pt)}catch{}};window.addEventListener("resize",st),Q.current&&window.removeEventListener("resize",Q.current),Q.current=st,u(!0),h(null)}catch(be){if(wt&&clearTimeout(wt),!dt)return;const gt=be instanceof Error?be.message:"xterm initialization failed";h(gt)}})(),()=>{dt=!1,wt&&clearTimeout(wt)}},[$,e,le,X?.sessionId,a]),i.useEffect(()=>{e||(_.current&&(_.current.dispose(),_.current=null),K.current=null,A.current=!1,Q.current&&(window.removeEventListener("resize",Q.current),Q.current=null),u(!1),h(null),U.current=!1,o(null),c(null),C(!1),N(null))},[e]),i.useEffect(()=>{if(!d||!_.current||!X)return;const Me=X.sessionId,Ye=J=>{A.current===Me&&_.current?.write(J)},dt=he(J=>{Ye(J)}),wt=ze(J=>{Ye(J)}),St=B(J=>{ne(X.id,Ju(J.shell)||J.shell)}),Fe=pe(J=>{A.current===Me&&(c(J),_.current?.write(`\r
687
687
  \x1B[33m[Process exited with code ${J}]\x1B[0m\r
688
688
  `))});return()=>{dt(),wt(),St(),Fe()}},[d,X?.sessionId,X?.id,X,q,he,ze,B,pe,ne]),i.useEffect(()=>{q==="connected"&&s&&U.current!==s&&X&&(U.current=s,setTimeout(()=>{L(s+`
689
689
  `)},500))},[q,s,L,X,f]),i.useEffect(()=>{if(!d||!_.current)return;_.current.options.fontSize=y,M.current!==null&&(cancelAnimationFrame(M.current),M.current=null);const Me=requestAnimationFrame(()=>{M.current=null,Te()});return M.current=Me,()=>{M.current===Me&&(cancelAnimationFrame(Me),M.current=null)}},[y,d,Te]),i.useEffect(()=>{if(!e)return;const Me=Ye=>{if(!(!Ye.ctrlKey&&!Ye.metaKey)){if(Ye.code==="Equal"||Ye.code==="NumpadAdd"){Ye.preventDefault(),S(dt=>No(dt+1));return}if(Ye.code==="Minus"||Ye.code==="NumpadSubtract"){Ye.preventDefault(),S(dt=>No(dt-1));return}if(Ye.code==="Digit0"||Ye.code==="Numpad0"){Ye.preventDefault(),S(jo);return}}};return window.addEventListener("keydown",Me),()=>window.removeEventListener("keydown",Me)},[e,Te]),i.useEffect(()=>{if(!e)return;const Me=Ye=>{Ye.key==="Escape"&&n()};return document.addEventListener("keydown",Me),()=>document.removeEventListener("keydown",Me)},[e,n]),i.useEffect(()=>{q==="connected"&&_.current&&setTimeout(()=>{if(!_.current||!R.current)return;const Me=R.current.querySelector(".xterm-helper-textarea");Me&&Me.focus();try{R.current.dispatchEvent(new MouseEvent("click",{bubbles:!0,cancelable:!0}))}catch{}},100)},[q]);const rt=i.useCallback(()=>{if(!R.current||typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(hover: none) and (pointer: coarse)")?.matches===!0)return;_.current?.focus();const Ye=R.current.querySelector(".xterm-helper-textarea");if(!Ye)return;Ye.autocapitalize="off",Ye.autocomplete="off",Ye.autocorrect="off",Ye.spellcheck=!1,Ye.setAttribute("inputmode","text");try{Ye.focus({preventScroll:!0})}catch{Ye.focus()}const dt=Ye.value.length;Ye.setSelectionRange(dt,dt)},[]);i.useEffect(()=>Ve(()=>{_.current?.clear(),c(null),U.current=!1,_.current&&(_.current.dispose(),_.current=null),K.current=null,A.current=!1,Q.current&&(window.removeEventListener("resize",Q.current),Q.current=null),u(!1),h(null),re().catch(Ye=>{console.error("Failed to replace invalid terminal session:",Ye)})}),[Ve,re]);const Be=i.useCallback(Me=>{Me.target===Me.currentTarget&&(E.current=!0)},[]),ce=i.useCallback(Me=>{E.current&&Me.target===Me.currentTarget&&n(),E.current=!1},[n]),Re=i.useCallback(()=>{_.current?.clear()},[]),Le=i.useCallback(async()=>{_.current?.clear(),c(null),U.current=!1;try{await fe()}catch(Me){o(Se(Me)||"Failed to restart terminal session")}},[fe]),ct=i.useCallback(()=>{_.current&&(_.current.dispose(),_.current=null),K.current=null,A.current=!1,Q.current&&(window.removeEventListener("resize",Q.current),Q.current=null),h(null),u(!1)},[]),Ue=i.useCallback(()=>{window.location.reload()},[]),ue=i.useCallback(()=>{S(Me=>No(Me+1))},[]),oe=i.useCallback(()=>{S(Me=>No(Me-1))},[]),Ee=i.useCallback(Me=>{N(Ye=>Ye===Me?null:Me)},[]),ft=i.useCallback(Me=>{if(x==="ctrl"){L(H4(Me)),N(null);return}if(x==="alt"){L(q4(Me)),N(null);return}L(Me)},[L,x]),ht=i.useCallback(Me=>{L(Me),N(null)},[L]);if(!e)return null;const tt=()=>{switch(q){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}},xt=!le||!X&&!ke;return t.jsx("div",{className:"modal-overlay open",onMouseDown:Be,onMouseUp:ce,role:"dialog","aria-modal":"true","data-testid":"terminal-modal-overlay",style:g>0?{"--overlay-padding-top":"0px"}:void 0,children:t.jsxs("div",{ref:F,className:"modal terminal-modal","data-testid":"terminal-modal",style:g>0?{"--keyboard-overlap":`${g}px`,"--vv-height":v?`${v}px`:void 0}:void 0,children:[t.jsxs("div",{className:"terminal-header",children:[t.jsxs("div",{className:"terminal-tabs","data-testid":"terminal-tabs",children:[k.map(Me=>t.jsxs("div",{className:`terminal-tab ${Me.isActive?"terminal-tab--active":""}`,onClick:()=>je(Me.id),title:Me.title,role:"tab","aria-selected":Me.isActive,children:[t.jsx("span",{className:"terminal-tab-label",children:Me.title}),k.length>1&&t.jsx("button",{className:"terminal-tab-close",onClick:Ye=>{Ye.stopPropagation(),ye(Me.id)},title:"Close tab",children:"×"})]},Me.id)),t.jsx("button",{className:"terminal-tab terminal-tab--new",onClick:He,title:"New terminal",children:"+"})]}),t.jsxs("div",{className:"terminal-title","data-testid":"terminal-title",children:[t.jsx(ea,{size:16}),tt()]}),t.jsxs("div",{className:"terminal-actions","data-testid":"terminal-actions",children:[q==="disconnected"&&X&&t.jsxs("button",{className:"terminal-reconnect-btn",onClick:ae,title:"Reconnect","data-testid":"terminal-reconnect-btn",children:[t.jsx(ps,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Reconnect"})]}),l!==null&&t.jsxs("button",{className:"terminal-restart-btn",onClick:Le,title:"New Session","data-testid":"terminal-restart-btn",children:[t.jsx(ps,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"New Session"})]}),t.jsxs("button",{className:"terminal-clear-btn",onClick:Re,"data-testid":"terminal-clear-btn",title:"Clear terminal",children:[t.jsx(Tn,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Clear"})]}),t.jsxs("button",{className:"terminal-clear-btn terminal-clear-btn--shortcut",onClick:()=>C(Me=>!Me),"data-testid":"terminal-shortcut-toggle",title:"Shortcuts","aria-pressed":j,children:[t.jsx(Jw,{size:14}),t.jsx("span",{className:"terminal-action-label",children:"Shortcuts"})]}),t.jsx("button",{className:"terminal-close",onClick:n,"data-testid":"terminal-close-btn",title:"Close terminal",children:t.jsx(mn,{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:[xt&&!ke&&t.jsxs("div",{className:"terminal-loading","data-testid":"terminal-loading",children:[t.jsx("div",{className:"terminal-spinner"}),t.jsx("span",{children:"Starting terminal..."})]}),ke&&!X&&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: ",ke]}),t.jsxs("div",{className:"terminal-error-actions",children:[t.jsxs("button",{className:"terminal-retry-btn",onClick:Z,"data-testid":"terminal-retry-btn",children:[t.jsx(ps,{size:14}),"Retry"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ue,"data-testid":"terminal-bootstrap-refresh-btn",children:[t.jsx(ps,{size:14}),"Refresh page"]})]})]})}),m&&X&&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:ct,"data-testid":"terminal-reinit-btn",children:[t.jsx(ps,{size:14}),"Reinitialize"]}),t.jsxs("button",{className:"terminal-retry-btn",onClick:Ue,"data-testid":"terminal-xterm-refresh-btn",children:[t.jsx(ps,{size:14}),"Refresh page"]})]})]})}),t.jsx("div",{ref:R,className:"terminal-xterm","data-testid":"terminal-xterm",onPointerDown:rt,onTouchStart:rt},X?.sessionId)]}),j&&t.jsxs("div",{className:"terminal-shortcut-panel","data-testid":"terminal-shortcut-panel",children:[t.jsxs("div",{className:"terminal-shortcut-modifier-row",children:[t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${x==="ctrl"?"is-active":""}`,"data-testid":"terminal-modifier-ctrl",onClick:()=>Ee("ctrl"),"aria-pressed":x==="ctrl",children:"Ctrl"}),t.jsx("button",{type:"button",className:`terminal-shortcut-btn terminal-shortcut-btn--modifier ${x==="alt"?"is-active":""}`,"data-testid":"terminal-modifier-alt",onClick:()=>Ee("alt"),"aria-pressed":x==="alt",children:"Alt"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ht("\x1B"),children:"ESC"}),t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ht(" "),children:"Tab"})]}),V4.map(Me=>t.jsx("button",{type:"button",className:"terminal-shortcut-btn",onClick:()=>ft(Me.key),title:Me.description,children:Me.label},Me.label))]}),t.jsxs("div",{className:"terminal-status-bar","data-testid":"terminal-status-bar",children:[t.jsxs("span",{className:`terminal-connection-status ${q}`,children:[q==="connected"&&"Connected",q==="connecting"&&"Connecting...",q==="reconnecting"&&"Reconnecting...",q==="disconnected"&&"Disconnected"]}),l!==null&&t.jsxs("span",{className:"terminal-exit-code","data-testid":"terminal-exit-code",children:["Exit: ",l]}),t.jsxs("span",{className:"terminal-font-size-controls",children:[t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:oe,"data-testid":"terminal-font-size-decrease","aria-label":"Decrease terminal font size",children:t.jsx(xk,{size:14})}),t.jsxs("span",{className:"terminal-font-size-value","data-testid":"terminal-font-size-value",children:[y,"px"]}),t.jsx("button",{type:"button",className:"terminal-font-size-btn",onClick:ue,"data-testid":"terminal-font-size-increase","aria-label":"Increase terminal font size",children:t.jsx($n,{size:14})})]}),t.jsx("span",{className:"terminal-shortcuts",children:"Ctrl++/- zoom • ⌨ Shortcuts panel • Esc close"})]})]})})}const uo={name:"",command:""};function qf(e){return/^[a-zA-Z0-9_-]+$/.test(e)}function Z4(e,n=60){return e.length<=n?e:e.slice(0,n-3)+"..."}function eD({isOpen:e,onClose:n,addToast:s,projectId:a,onRunScript:r}){Mi(e);const[o,l]=i.useState({}),[c,d]=i.useState(!0),[u,m]=i.useState(!1),[h,f]=i.useState(null),[p,g]=i.useState(uo),[w,v]=i.useState(!1),[b,y]=i.useState(null),[S,j]=i.useState(null),C=sa(n),x=i.useCallback(async()=>{try{d(!0);const H=await $o(a);l(H)}catch(H){s(Se(H)||"Failed to load scripts","error")}finally{d(!1)}},[s,a]);i.useEffect(()=>{e&&x()},[e,x]);const N=i.useCallback(()=>{m(!0),f(null),g(uo),j(null)},[]),R=i.useCallback((H,Q)=>{f(H),m(!1),g({name:H,command:Q}),j(null)},[]),F=i.useCallback(()=>{f(null),m(!1),g(uo),j(null)},[]),E=i.useCallback(H=>{g(Q=>({...Q,name:H})),H&&!qf(H)?j("Name must contain only letters, numbers, hyphens, and underscores (no spaces)"):j(null)},[]),_=i.useCallback(async()=>{const H=p.name.trim(),Q=p.command.trim();if(!H){s("Script name is required","error");return}if(!qf(H)){s("Script name must contain only letters, numbers, hyphens, and underscores (no spaces)","error");return}if(!Q){s("Script command is required","error");return}v(!0);try{await KS(H,Q,a),s(h?"Script updated":"Script created","success"),f(null),m(!1),g(uo),j(null),await x()}catch(se){const O=Se(se);O?.includes("already exists")?s("A script with this name already exists","error"):s(O||"Failed to save script","error")}finally{v(!1)}},[p,h,s,x,a]),K=i.useCallback(async H=>{try{await JS(H,a),s("Script deleted","success"),y(null),h===H&&(f(null),g(uo)),await x()}catch(Q){s(Se(Q)||"Failed to delete script","error")}},[h,s,x,a]),U=i.useCallback((H,Q)=>{r&&r(H,Q)},[r]);if(!e)return null;const A=u||h!==null,T=Object.entries(o).map(([H,Q])=>({name:H,command:Q}));return t.jsx("div",{className:"modal-overlay open",...C,"data-testid":"scripts-modal",children:t.jsxs("div",{className:"modal scripts-modal",role:"dialog","aria-modal":"true","aria-label":"Scripts",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{children:[t.jsx(ea,{size:18,style:{marginRight:"8px",verticalAlign:"middle"}}),"Scripts"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"modal-body scripts-modal-body",children:c?t.jsxs("div",{style:{textAlign:"center",padding:"32px",color:"var(--text-muted)"},children:[t.jsx(jt,{size:24,className:"spin",style:{margin:"0 auto 8px",display:"block"}}),"Loading scripts..."]}):A?t.jsxs("div",{className:"scripts-modal-form",style:{display:"flex",flexDirection:"column",gap:"16px"},children:[t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-name",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Script Name"}),t.jsx("input",{id:"script-name",type:"text",className:"input",value:p.name,onChange:H=>E(H.target.value),placeholder:"e.g., build, test, lint",disabled:w||h!==null,"data-testid":"script-name-input",style:{width:"100%",borderColor:S?"var(--color-error)":void 0}}),S&&t.jsx("div",{style:{fontSize:"12px",color:"var(--color-error)",marginTop:"4px"},"data-testid":"script-name-error",children:S}),t.jsx("div",{style:{fontSize:"11px",color:"var(--text-muted)",marginTop:"4px"},children:"Letters, numbers, hyphens, and underscores only"})]}),t.jsxs("div",{children:[t.jsx("label",{htmlFor:"script-command",style:{display:"block",marginBottom:"4px",fontSize:"13px",fontWeight:500,color:"var(--text)"},children:"Command"}),t.jsx("textarea",{id:"script-command",className:"input",value:p.command,onChange:H=>g(Q=>({...Q,command:H.target.value})),placeholder:"e.g., npm run build",rows:3,disabled:w,"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:F,disabled:w,"data-testid":"script-cancel-btn",children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:_,disabled:w||!!S,"data-testid":"script-save-btn",children:w?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:14,className:"spin",style:{marginRight:"6px"}}),"Saving..."]}):h?"Update":"Create"})]})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"scripts-modal-list-header",style:{display:"flex",justifyContent:"space-between",alignItems:"center",marginBottom:"16px"},children:[t.jsx("div",{style:{fontSize:"13px",color:"var(--text-muted)"},children:T.length===0?"No scripts defined":`${T.length} script${T.length===1?"":"s"}`}),t.jsxs("button",{className:"btn btn-primary",onClick:N,"data-testid":"add-script-btn",style:{display:"flex",alignItems:"center",gap:"6px"},children:[t.jsx($n,{size:14}),"Add Script"]})]}),T.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(ea,{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:T.map(H=>t.jsx("div",{className:"script-card","data-testid":`script-${H.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:H.name})}),t.jsx("div",{style:{fontSize:"12px",color:"var(--text-muted)",fontFamily:"monospace",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},title:H.command,children:Z4(H.command)})]}),t.jsxs("div",{className:"script-card-actions",style:{display:"flex",gap:"4px",marginLeft:"8px",flexShrink:0},children:[t.jsxs("button",{className:"btn btn-secondary",onClick:()=>U(H.name,H.command),title:"Run script","aria-label":`Run ${H.name}`,"data-testid":`run-script-${H.name}`,style:{display:"flex",alignItems:"center",gap:"4px",padding:"4px 10px",fontSize:"12px"},children:[t.jsx(os,{size:12}),"Run"]}),t.jsx("button",{className:"btn-icon",onClick:()=>R(H.name,H.command),title:"Edit","aria-label":`Edit ${H.name}`,"data-testid":`edit-script-${H.name}`,children:t.jsx($n,{size:14,style:{transform:"rotate(45deg)"}})}),b===H.name?t.jsxs("div",{className:"script-delete-confirm",style:{display:"flex",gap:"4px",alignItems:"center"},children:[t.jsx("button",{className:"btn-icon",onClick:()=>K(H.name),title:"Confirm delete","aria-label":`Confirm delete ${H.name}`,"data-testid":`confirm-delete-script-${H.name}`,style:{color:"var(--color-error)"},children:t.jsx(Tn,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>y(null),title:"Cancel delete","aria-label":"Cancel delete","data-testid":`cancel-delete-script-${H.name}`,children:t.jsx(mn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>y(H.name),title:"Delete","aria-label":`Delete ${H.name}`,"data-testid":`delete-script-${H.name}`,children:t.jsx(Tn,{size:14})})]})]})},H.name))})]})})]})})}function tD(e,n,s){const[a,r]=i.useState([]),[o,l]=i.useState("."),[c,d]=i.useState(!1),[u,m]=i.useState(null),[h,f]=i.useState(0),p=i.useCallback(()=>{f(w=>w+1)},[]),g=i.useCallback(w=>{l(w),m(null)},[]);return i.useEffect(()=>{l("."),m(null),r([])},[e]),i.useEffect(()=>{if(!n||!e)return;let w=!1;async function v(){d(!0),m(null);try{const b=await lS(e,o==="."?void 0:o,s);w||r(b.entries)}catch(b){w||(m(Se(b)||"Failed to load files"),r([]))}finally{w||d(!1)}}return v(),()=>{w=!0}},[e,o,n,h,s]),{entries:a,currentPath:o,setPath:g,loading:c,error:u,refresh:p}}function nD(e,n,s,a){const[r,o]=i.useState(""),[l,c]=i.useState(""),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,w]=i.useState(null),v=i.useCallback(S=>{o(S),w(null)},[]);i.useEffect(()=>{if(!e||!n){o(""),c(""),u(null),w(null);return}let S=!1;async function j(){h(!0),w(null);try{const C=await cS(e,n,a);S||(o(C.content),c(C.content),u(C.mtime))}catch(C){S||(w(Se(C)||"Failed to load file"),o(""),c(""),u(null))}finally{S||h(!1)}}return j(),()=>{S=!0}},[e,n,s,a]);const b=r!==l,y=i.useCallback(async()=>{if(!(!e||!n||!b)){p(!0),w(null);try{const S=await dS(e,n,r,a);c(r),u(S.mtime)}catch(S){throw w(Se(S)||"Failed to save file"),S}finally{p(!1)}}},[e,n,r,b,a]);return{content:r,setContent:v,originalContent:l,loading:m,saving:f,error:g,save:y,hasChanges:b,mtime:d}}const sD=1e4;function iD(e){const s=e.replace(/[\\/]+$/,"").split(/[\\/]/).filter(Boolean);return s[s.length-1]||e||"Project Root"}function aD(e){return{id:e.id,label:e.id,title:e.title,worktree:e.worktree,kind:"task"}}function rD(e){const[n,s]=i.useState("Project Root"),[a,r]=i.useState([]),[o,l]=i.useState(!0),[c,d]=i.useState(null);return i.useEffect(()=>{let u=!1;async function m(){try{const f=await oS(e);if(u)return;s(iD(f.project)),r(f.tasks.map(aD)),d(null)}catch(f){u||d(Se(f)||"Failed to load workspaces")}finally{u||l(!1)}}m();const h=window.setInterval(()=>{m()},sD);return()=>{u=!0,window.clearInterval(h)}},[e]),{projectName:n,workspaces:a,loading:o,error:c}}function oD(e){return e===void 0?"":e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function lD(e){return e?new Date(e).toLocaleDateString():""}function Vf(e,n){return SC(e,n)}const mo={visible:!1,x:0,y:0,entry:null,entryFullPath:""},Hd={type:null,entry:null,entryFullPath:""},cD=200,dD=500,Wf=10;function uD({x:e,y:n,entry:s,onAction:a,onClose:r}){const o=i.useRef(null),[l,c]=i.useState({x:e,y:n});i.useEffect(()=>{const m=o.current;if(!m)return;const h=m.getBoundingClientRect(),f=window.visualViewport,p=f?.width&&f.width>0?f.width:window.innerWidth,g=f?.height&&f.height>0?f.height:window.innerHeight,w=f?.offsetLeft??0,v=f?.offsetTop??0,b=8;let y=e-w,S=n-v;y+h.width>p-b&&(y=p-b-h.width),S+h.height>g-b&&(S=g-b-h.height),y<b&&(y=b),S<b&&(S=b),c({x:y+w,y:S+v})},[e,n]),i.useEffect(()=>{const m=h=>{h.key==="Escape"&&r()};return document.addEventListener("keydown",m),()=>document.removeEventListener("keydown",m)},[r]);const d=s.type==="directory",u=[{id:"copy",label:"Copy",icon:ba,disabled:!1},{id:"move",label:"Move",icon:wk,disabled:!1},{id:"rename",label:"Rename",icon:Hs,disabled:!1},...d?[{id:"download-zip",label:"Download as ZIP",icon:zo,disabled:!1}]:[{id:"download",label:"Download",icon:lw,disabled:!1}],{id:"divider",label:"",icon:ba,disabled:!0},{id:"delete",label:"Delete",icon:Tn,disabled:!1}];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsx("div",{ref:o,className:"file-browser-context-menu",role:"menu","aria-label":"File operations",style:{left:l.x,top:l.y},onClick:m=>m.stopPropagation(),children:u.map(m=>m.id==="divider"?t.jsx("div",{className:"file-browser-context-menu__divider",role:"separator"},"divider"):t.jsxs("button",{role:"menuitem",className:`file-browser-context-menu__item ${m.disabled?"file-browser-context-menu__disabled":""} ${m.id==="delete"?"file-browser-context-menu__item--danger":""}`,disabled:m.disabled,onClick:()=>a(m.id),children:[t.jsx(m.icon,{size:14,className:"file-browser-context-menu__item-icon"}),t.jsx("span",{children:m.label})]},m.id))})})}function mD({type:e,entry:n,entryFullPath:s,onConfirm:a,onCancel:r,loading:o,error:l}){const c=i.useRef(null),d=e==="rename"?n.name:"",[u,m]=i.useState(d);i.useEffect(()=>{setTimeout(()=>c.current?.focus(),50)},[]),i.useEffect(()=>{if(e==="rename"&&c.current){const g=n.name.lastIndexOf(".");g>0?c.current.setSelectionRange(0,g):c.current.select()}},[e,n.name]);const h=g=>{g.key==="Enter"&&u.trim()&&a(u.trim()),g.key==="Escape"&&r()};if(e==="delete")return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsxs("div",{className:"file-browser-dialog-title",children:["Delete ",n.type==="directory"?"Folder":"File"]}),t.jsxs("div",{className:"file-browser-dialog-message",children:["Are you sure you want to delete ",t.jsx("strong",{children:n.name}),"?",n.type==="directory"&&" This will delete all contents recursively."]}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-danger btn-sm",onClick:()=>a(""),disabled:o,children:o?"Deleting...":"Delete"})]})]})});const p={copy:{title:"Copy",placeholder:"Destination path",confirm:"Copy"},move:{title:"Move",placeholder:"Destination path",confirm:"Move"},rename:{title:"Rename",placeholder:"New name",confirm:"Rename"}}[e];return t.jsx("div",{className:"context-menu-overlay",onClick:r,children:t.jsxs("div",{className:"file-browser-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("div",{className:"file-browser-dialog-title",children:p.title}),t.jsx("div",{className:"file-browser-dialog-info",children:e==="rename"?n.name:s}),t.jsx("input",{ref:c,className:"file-browser-dialog-input",type:"text",value:u,onChange:g=>m(g.target.value),placeholder:p.placeholder,onKeyDown:h,disabled:o}),l&&t.jsx("div",{className:"file-browser-dialog-error",children:l}),t.jsxs("div",{className:"file-browser-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:r,disabled:o,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>a(u.trim()),disabled:o||!u.trim(),children:o?`${p.confirm}ing...`:p.confirm})]})]})})}function hD({entries:e,currentPath:n,onSelectFile:s,onNavigate:a,loading:r,error:o,onRetry:l,workspace:c,onRefresh:d,projectId:u}){const[m,h]=i.useState(mo),[f,p]=i.useState(Hd),[g,w]=i.useState(!1),[v,b]=i.useState(null),[y,S]=i.useState(!1),[j,C]=i.useState(null),x=i.useRef(null),N=i.useRef(null),R=i.useRef(null),F=i.useRef(!1),E=i.useCallback(()=>{x.current!==null&&(window.clearTimeout(x.current),x.current=null),N.current!==null&&(window.clearTimeout(N.current),N.current=null)},[]),_=i.useCallback(()=>{E(),R.current=null,S(!1),C(null)},[E]);i.useEffect(()=>()=>{E()},[E]);const K=i.useCallback((D,$,k,X)=>{h({visible:!0,x:D,y:$,entry:k,entryFullPath:X})},[]),U=i.useCallback((D,$,k)=>{if(D.touches.length!==1)return;const X=D.touches[0];X&&(_(),R.current={x:X.clientX,y:X.clientY},N.current=window.setTimeout(()=>{S(!0),C(k)},cD),x.current=window.setTimeout(()=>{const le=R.current;le&&(F.current=!0,S(!1),C(null),E(),K(le.x,le.y,$,k))},dD))},[_,E,K]),A=i.useCallback(D=>{const $=R.current,k=D.touches[0];!$||!k||(Math.abs(k.clientX-$.x)>Wf||Math.abs(k.clientY-$.y)>Wf)&&_()},[_]),T=i.useCallback(()=>{_()},[_]);i.useEffect(()=>{if(!m.visible)return;const D=document.querySelector(".file-browser-list"),$=()=>{F.current=!1,_(),h(mo)};return D?.addEventListener("scroll",$),()=>D?.removeEventListener("scroll",$)},[_,m.visible]),i.useEffect(()=>{if(!m.visible)return;const D=$=>{$.key==="Escape"&&(F.current=!1,h(mo))};return document.addEventListener("keydown",D),()=>document.removeEventListener("keydown",D)},[m.visible]);const H=i.useCallback((D,$)=>{D.preventDefault(),D.stopPropagation(),_(),F.current=!1,K(D.clientX,D.clientY,$,Vf(n,$.name))},[_,n,K]),Q=i.useCallback(D=>{if(!m.entry)return;F.current=!1;const $=m.entry,k=m.entryFullPath;if(h(mo),D==="download"){if(!c)return;const X=hb(c,k,u);window.open(Fi(X),"_blank");return}if(D==="download-zip"){if(!c)return;const X=gS(c,k,u);window.open(Fi(X),"_blank");return}p({type:D,entry:$,entryFullPath:k}),b(null)},[m,c,u]),se=i.useCallback(async D=>{if(!(!f.type||!f.entry||!c)){w(!0),b(null);try{switch(f.type){case"copy":await mS(c,f.entryFullPath,D,u);break;case"move":await hS(c,f.entryFullPath,D,u);break;case"rename":await fS(c,f.entryFullPath,D,u);break;case"delete":await pS(c,f.entryFullPath,u);break}p(Hd),d?.()}catch($){b(Se($)||"Operation failed")}finally{w(!1)}}},[f,c,d,u]),O=i.useCallback(()=>{p(Hd),b(null)},[]),M=i.useCallback((D,$)=>{if(F.current){F.current=!1;return}m.visible||(D.type==="directory"?a($):s($))},[m.visible,a,s]);return r?t.jsxs("div",{className:"file-browser-loading",children:[t.jsx(jt,{className:"spin",size:24}),t.jsx("span",{children:"Loading files..."})]}):o?t.jsxs("div",{className:"file-browser-error",children:[t.jsxs("p",{children:["Error: ",o]}),l&&t.jsx("button",{className:"btn btn-sm",onClick:l,children:"Retry"})]}):t.jsxs("div",{className:"file-browser",children:[t.jsxs("div",{className:"file-browser-header",children:[n!=="."&&t.jsxs("button",{className:"file-browser-up",onClick:()=>{a(CC(n))},children:[t.jsx(qn,{size:16,style:{transform:"rotate(-90deg)"}}),"Up one level"]}),t.jsx("span",{className:"file-browser-path",children:n==="."?"Root":Hr(n)})]}),t.jsx("div",{className:"file-browser-list",children:e.length===0?t.jsx("div",{className:"file-browser-empty",children:"(empty directory)"}):e.map(D=>{const $=Vf(n,D.name),k=y&&j===$;return t.jsxs("div",{className:`file-node file-node--${D.type} ${k?"file-node--long-pressing":""}`,onClick:()=>M(D,$),onContextMenu:X=>H(X,D),onTouchStart:X=>U(X,D,$),onTouchMove:A,onTouchEnd:T,onTouchCancel:T,children:[t.jsx("div",{className:"file-node-icon",children:D.type==="directory"?t.jsx(js,{size:16}):t.jsx(nb,{size:16})}),t.jsx("div",{className:"file-node-name",children:D.name}),D.type==="file"&&D.size!==void 0&&t.jsx("div",{className:"file-node-size",children:oD(D.size)}),D.mtime&&t.jsx("div",{className:"file-node-time",children:lD(D.mtime)})]},D.name)})}),m.visible&&m.entry&&t.jsx(uD,{x:m.x,y:m.y,entry:m.entry,onAction:Q,onClose:()=>{F.current=!1,h(mo)}}),f.type&&f.entry&&t.jsx(mD,{type:f.type,entry:f.entry,entryFullPath:f.entryFullPath,onConfirm:se,onCancel:O,loading:g,error:v})]})}function pD(e){if(!e)return!1;const n=e.toLowerCase();return n.endsWith(".md")||n.endsWith(".markdown")||n.endsWith(".mdx")}function fD({content:e,onChange:n,readOnly:s,filePath:a,showLineNumbers:r=!1,onToggleLineNumbers:o,canToggleLineNumbers:l=!0}){const[c,d]=i.useState(!1),[u,m]=i.useState(!0),h=i.useRef(null),f=pD(a),p=f&&(s?!0:c),g=r&&!s&&!p,w=!!o&&l&&!s&&!p,v=i.useMemo(()=>g?e.split(`
690
- `).length:0,[e,g]),b=i.useCallback(()=>{d(!1)},[]),y=i.useCallback(()=>{d(!0)},[]),S=i.useCallback(()=>{m(C=>!C)},[]),j=i.useCallback(C=>{h.current&&(h.current.scrollTop=C.currentTarget.scrollTop)},[]);return t.jsxs("div",{className:"file-editor-container",children:[f?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 ${p?"":"btn-primary"}`,onClick:b,disabled:!p,"aria-label":"Edit mode",children:[t.jsx(tb,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${p?"btn-primary":""}`,onClick:y,disabled:p,"aria-label":"Preview mode",children:[t.jsx(Fr,{size:14}),"Preview"]})]}),!s&&t.jsxs("div",{className:"file-editor-toolbar-actions",children:[w&&t.jsxs("button",{className:`btn btn-sm file-editor-line-numbers-button ${r?"btn-primary":""}`,onClick:o,"aria-label":"Toggle line numbers","aria-pressed":r,title:"Toggle line numbers",children:[t.jsx($m,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:S,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Vl,{size:14})})]})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsxs("div",{className:"file-editor-toolbar-actions",children:[w&&t.jsxs("button",{className:`btn btn-sm file-editor-line-numbers-button ${r?"btn-primary":""}`,onClick:o,"aria-label":"Toggle line numbers","aria-pressed":r,title:"Toggle line numbers",children:[t.jsx($m,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:S,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Vl,{size:14})})]})]}),p?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],children:e})}):t.jsxs("div",{className:`file-editor-textarea-shell ${g?"file-editor-textarea-shell--line-numbers":""}`,children:[g&&t.jsx("div",{className:"file-editor-line-numbers",ref:h,"aria-hidden":"true",children:Array.from({length:v},(C,x)=>t.jsx("div",{className:"file-editor-line-number",children:x+1},`line-${x+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${u?"file-editor-textarea--wrap":""}`,value:e,onChange:C=>n(C.target.value),onScroll:j,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function gD(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function bD({currentWorkspace:e,projectName:n,workspaces:s,onSelect:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>e==="project"?n||"Project Root":s.find(d=>d.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(Pm,{size:14}):t.jsx(iu,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(gn,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{a("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Pm,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{a(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(iu,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:gD(c.title)})]},c.id))]})]})]})}const xD=768,vD=280,Rl=180,Il=500,Gf="fusion:file-browser-sidebar-width",Kf="kb-files-line-numbers",Mv=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),yD=new Set([...Mv,".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 Tl(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return yD.has(n)}function wD(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Mv.has(n)}function kD(e){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,""),s=n.lastIndexOf("/");return s>0?n.slice(0,s):"."}function jD({initialWorkspace:e="project",initialFile:n=null,onClose:s,onWorkspaceChange:a,projectId:r}){const{projectName:o,workspaces:l}=rD(r),c=i.useRef(null);zi(c,!0,"fusion:files-modal-size");const d=sa(s),[u,m]=i.useState(e),[h,f]=i.useState(null),[p,g]=i.useState(!1),[w,v]=i.useState("list"),[b,y]=i.useState(vD),[S,j]=i.useState(!1),{entries:C,currentPath:x,setPath:N,loading:R,error:F,refresh:E}=tD(u,!0,r),{content:_,setContent:K,originalContent:U,loading:A,saving:T,error:H,save:Q,hasChanges:se,mtime:O}=nD(u,h,!0,r);i.useEffect(()=>{m(e)},[e]),i.useEffect(()=>{const Z=()=>{g(window.innerWidth<=xD)};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),i.useEffect(()=>{h||v("list")},[h]),i.useEffect(()=>{if(!n){f(null);return}f(n),N(kD(n)),p&&v("editor")},[n,p,N]),i.useEffect(()=>{try{const Z=localStorage.getItem(Gf);if(!Z)return;const re=Number.parseInt(Z,10);if(!Number.isNaN(re)){const q=Math.max(Rl,Math.min(Il,re));y(q)}}catch{}},[]),i.useEffect(()=>{const Z=Gn(Kf,r);j(Z==="true")},[r]),i.useEffect(()=>{const Z=re=>{re.key==="Escape"&&s(),(re.metaKey||re.ctrlKey)&&re.key==="s"&&(re.preventDefault(),se&&!T&&Q())};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[s,se,T,Q]);const M=i.useCallback(Z=>{f(Z),p&&v("editor")},[p]),D=i.useCallback(()=>{v("list")},[]),$=i.useCallback(()=>{K(U)},[U,K]),k=i.useCallback(Z=>{m(Z),f(null),v("list"),a?.(Z)},[a]),X=i.useCallback(Z=>{try{localStorage.setItem(Gf,String(Z))}catch{}},[]),le=i.useCallback(Z=>{if(p)return;Z.preventDefault(),Z.stopPropagation();const re=Z.currentTarget;typeof re.setPointerCapture=="function"&&re.setPointerCapture(Z.pointerId);const q=Z.clientX,L=b;let xe=L;document.body.style.userSelect="none";const he=pe=>{const ze=pe.clientX-q,ae=Math.max(Rl,Math.min(Il,L+ze));xe=ae,y(ae)},B=pe=>{typeof re.releasePointerCapture=="function"&&re.releasePointerCapture(pe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",he),document.removeEventListener("pointerup",B),X(xe)};document.addEventListener("pointermove",he),document.addEventListener("pointerup",B)},[p,X,b]),ke=i.useCallback(Z=>{if(p)return;const re=20;if(Z.key!=="ArrowLeft"&&Z.key!=="ArrowRight")return;Z.preventDefault();const q=Z.key==="ArrowLeft"?-re:re,L=Math.max(Rl,Math.min(Il,b+q));y(L),X(L)},[p,X,b]),He=i.useCallback(()=>{j(Z=>{const re=!Z;return fs(Kf,String(re),r),re})},[r]),je=`Files — ${i.useMemo(()=>u==="project"?"Project":l.find(Z=>Z.id===u)?.id??u,[u,l])}`,ne=i.useMemo(()=>!h||!wD(h)?null:hb(u,h,r),[h,u,r]),fe=Z=>{const re=new Blob([Z]).size;return re<1024?`${re} B`:`${(re/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...d,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:c,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(js,{size:18}),t.jsx("span",{children:je}),h&&t.jsx("span",{className:"file-browser-header-path",children:h})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(bD,{currentWorkspace:u,projectName:o,workspaces:l,onSelect:k}),t.jsx("button",{className:"modal-close",onClick:s,"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${p?"mobile":""} ${w==="list"?"active":""}`,style:p?void 0:{width:`${b}px`},children:t.jsx(hD,{entries:C,currentPath:x,onSelectFile:M,onNavigate:N,loading:R,error:F,onRetry:E,workspace:u,onRefresh:E,projectId:r})}),!p&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Rl,"aria-valuemax":Il,"aria-valuenow":b,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:le,onKeyDown:ke}),t.jsx("div",{className:`file-browser-content ${p?"mobile":""} ${w==="editor"?"active":""}`,children:h?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[p&&w==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:D,"aria-label":"Back to file list",children:[t.jsx(Ga,{size:16}),t.jsx("span",{children:"Back"})]}),h,Tl(h)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Cw,{size:12}),"Binary file — read only"]}),O&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(O).toLocaleString()]}),A&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!ne&&se&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:$,disabled:T,children:[t.jsx(Dk,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void Q(),disabled:T,children:[t.jsx(ob,{size:14}),T?"Saving...":"Save"]})]})})]}),H&&!ne&&t.jsx("div",{className:"file-browser-error-banner",children:H}),ne?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:ne,alt:h??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(fD,{content:_,onChange:K,filePath:h,readOnly:Tl(h),showLineNumbers:S&&!Tl(h),onToggleLineNumbers:He,canToggleLineNumbers:!Tl(h)})}),!ne&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:fe(_)}),se&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(js,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const ND=i.lazy(()=>En(()=>import("./TodoView-uJRg4Cnl.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function SD({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=sa(e),l=oi()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=aa({enabled:l});Mi(l);const h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{};return i.useEffect(()=>{const f=p=>{p.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:h,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(tk,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:"Todos"}),t.jsx("p",{children:"Manage reusable todo lists for your project."})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(mn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(ND,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&m})})})]})})}function CD(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[a,r]=i.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await dN();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:Se(m)||"Failed to fetch usage data"}))}},[]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),i.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const d=i.useCallback(()=>c(!0),[c]);return{providers:a.providers,loading:a.loading,error:a.error,lastUpdated:a.lastUpdated,refresh:d}}function ED(e){const n=new Date(e),s=new Date,a=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return a;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${a}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${a}`}function _D(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Av="kb-usage-hidden-windows",Rv="kb-usage-modal-size",Iv="kb-usage-provider-order";function Jf(e){const n=Gn(Rv,e);if(!n)return null;try{const s=JSON.parse(n);if(s&&typeof s.width=="number"&&typeof s.height=="number"&&s.width>0&&s.height>0)return{width:s.width,height:s.height}}catch{}return null}function Yf(e){const n=Gn(Av,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((a,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(a[r]=l)}return a},{})}catch{return{}}}function MD(e,n){fs(Av,JSON.stringify(e),n)}function Qf(e){const n=Gn(Iv,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function Xf(e,n){fs(Iv,JSON.stringify(e),n)}function Tv(e,n,s){return s[e]?.includes(n)??!1}function AD({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=_D(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?u=`resets in ${y}d ${S}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",w=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Fr,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:d}),t.jsxs("span",{className:"usage-window-reset-group",children:[u&&t.jsx("span",{className:"usage-window-reset",children:u}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:ED(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(zr,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(ij,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),w&&t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function RD(e){const n=e.toLowerCase();return n.includes("claude")||n.includes("anthropic")?"anthropic":n.includes("codex")||n.includes("openai")||n.includes("gpt")?"openai":n.includes("gemini")||n.includes("google")||n.includes("antigravity")?"google":n.includes("ollama")?"ollama":n.includes("minimax")?"minimax":n.includes("zai")||n.includes("zhipu")?"zai":n.includes("kimi")||n.includes("moonshot")?"kimi":n.includes("bedrock")||n.includes("amazon")?"bedrock":n.includes("xai")||n.includes("grok")?"xai":n.includes("opencode")?"opencode":n.includes("copilot")||n==="github copilot"?"github-copilot":e}function ID({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:w,onMoveUp:v,onMoveDown:b}){const y=s[e.name]?.length??0,S=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(zn,{provider:RD(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),y>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",y,")"]})]}),t.jsxs("div",{className:"usage-provider-actions",children:[p&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":`Reorder ${e.name}`,children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:v,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(Li,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!w,"aria-label":`Move ${e.name} down`,children:t.jsx(gn,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(xc,{size:16})})]})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((j,C)=>{const x=Tv(e.name,j.label,s);return t.jsx(AD,{window:j,viewMode:n,isHidden:x,onToggleHidden:()=>a(e.name,j.label)},`${e.name}-${j.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function TD(){return t.jsx("div",{className:"usage-skeleton",children:[1,2,3].map(e=>t.jsxs("div",{className:"usage-skeleton-provider",children:[t.jsxs("div",{className:"usage-skeleton-header",children:[t.jsx("div",{className:"usage-skeleton-icon"}),t.jsx("div",{className:"usage-skeleton-name"}),t.jsx("div",{className:"usage-skeleton-badge"})]}),t.jsx("div",{className:"usage-skeleton-bar"}),t.jsx("div",{className:"usage-skeleton-text"})]},e))})}function PD({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=CD({autoRefresh:e}),[u,m]=i.useState(!1),[h,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[w,v]=i.useState("used"),[b,y]=i.useState(()=>Yf(s)),[S,j]=i.useState(()=>Qf(s)),[C,x]=i.useState(null),[N,R]=i.useState(null),[F,E]=i.useState(null),_=i.useRef(null),K=i.useRef(null),U=i.useRef(e),A=i.useRef(!1),[T,H]=i.useState(()=>Jf(s));i.useEffect(()=>{H(Jf(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const B=K.current;if(!B||typeof ResizeObserver>"u")return;let pe=null;const ze=new ResizeObserver(ae=>{const Ve=ae[0];if(!Ve)return;const{width:Te,height:rt}=Ve.contentRect;Te<=0||rt<=0||(pe&&clearTimeout(pe),pe=setTimeout(()=>{fs(Rv,JSON.stringify({width:Math.round(Te),height:Math.round(rt)}),s)},250))});return ze.observe(B),()=>{pe&&clearTimeout(pe),ze.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(A.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(A.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const B=window.matchMedia?.("(pointer: coarse)"),pe=()=>{f(window.innerWidth>=769),g(B?.matches??!1)};return pe(),window.addEventListener("resize",pe),B?.addEventListener?.("change",pe),()=>{window.removeEventListener("resize",pe),B?.removeEventListener?.("change",pe)}},[]),i.useEffect(()=>{!U.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),U.current=e},[e,c,d]),i.useEffect(()=>{const B=Gn("kb-usage-view-mode",s);if(B==="used"||B==="remaining"){v(B);return}v("used")},[s]);const Q=i.useCallback(B=>{v(B),fs("kb-usage-view-mode",B,s)},[s]);i.useEffect(()=>{y(Yf(s)),j(Qf(s))},[s]),i.useEffect(()=>{MD(b,s)},[b,s]);const se=i.useCallback((B,pe)=>{y(ze=>{if(Tv(B,pe,ze)){const ae=(ze[B]??[]).filter(Ve=>Ve!==pe);if(ae.length===0){const{[B]:Ve,...Te}=ze;return Te}return{...ze,[B]:ae}}return{...ze,[B]:[...ze[B]??[],pe]}})},[]),O=i.useCallback(B=>{y(pe=>{if(!pe[B])return pe;const{[B]:ze,...ae}=pe;return ae})},[]),M=i.useCallback(B=>{if(S.length===0)return B;const pe=new Map(B.map(ae=>[ae.name,ae])),ze=[];for(const ae of S){const Ve=pe.get(ae);Ve&&(ze.push(Ve),pe.delete(ae))}return[...ze,...pe.values()]},[S]),D=i.useCallback((B,pe)=>{B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",pe),x(pe)},[]),$=i.useCallback((B,pe)=>{if(!C||C===pe)return;B.preventDefault(),B.dataTransfer.dropEffect="move";const{top:ze,height:ae}=B.currentTarget.getBoundingClientRect(),Ve=ze+ae/2,Te=B.clientY<Ve?"before":"after";R(pe),E(Te)},[C]),k=i.useCallback((B,pe)=>{B.preventDefault();const ze=C??B.dataTransfer.getData("text/plain");if(!ze||ze===pe){R(null),E(null);return}const Ve=M(r).map(Be=>Be.name).filter(Be=>Be!==ze),Te=Ve.indexOf(pe);if(Te<0){R(null),E(null);return}const rt=F==="after"?Te+1:Te;Ve.splice(rt,0,ze),Xf(Ve,s),j(Ve),R(null),E(null)},[C,F,s,r,M]),X=i.useCallback(()=>{x(null),R(null),E(null)},[]),le=i.useCallback((B,pe)=>{const ze=M(r).map(Be=>Be.name),ae=ze.indexOf(B),Ve=ae+pe;if(ae<0||Ve<0||Ve>=ze.length)return;const Te=[...ze],[rt]=Te.splice(ae,1);Te.splice(Ve,0,rt),Xf(Te,s),j(Te)},[s,r,M]),ke=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const B=pe=>{pe.key==="Escape"&&n()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n]);const He=i.useCallback(B=>{B.target===B.currentTarget&&n()},[n]);if(!e)return null;const ye=!!(a&&h),je=8,ne=12,Z=T?.width??420,re=ye?Math.min((a?.bottom??0)+je,window.innerHeight-ne):void 0,q=ye?Math.max(8,(a?.right??0)-Z):void 0,L=h&&T?{width:T.width,height:T.height}:{},xe=M(r),he=t.jsxs("div",{ref:K,className:`usage-modal${ye?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:ye?{position:"fixed",top:re,left:q,...L}:L,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Js,{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 ${w==="used"?"active":""}`,onClick:()=>Q("used"),"aria-pressed":w==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${w==="remaining"?"active":""}`,onClick:()=>Q("remaining"),"aria-pressed":w==="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(mn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:_,children:(o||!A.current&&!l)&&r.length===0?t.jsx(TD,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:ke,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:xe.map((B,pe)=>t.jsx(ID,{provider:B,viewMode:w,hiddenWindows:b,onToggleWindow:se,onShowAllHidden:O,isDragging:C===B.name,isDragOver:N===B.name,dragOverPosition:N===B.name?F:null,onDragStart:ze=>D(ze,B.name),onDragOver:ze=>$(ze,B.name),onDragLeave:()=>{N===B.name&&(R(null),E(null))},onDrop:ze=>k(ze,B.name),onDragEnd:X,isTouchReorderMode:p,canMoveUp:pe>0,canMoveDown:pe<xe.length-1,onMoveUp:()=>le(B.name,-1),onMoveDown:()=>le(B.name,1)},B.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:ke,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(ps,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return ye?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),he]}):t.jsx("div",{className:"modal-overlay open",onClick:He,"data-testid":"usage-modal-overlay",children:he})}function Pv(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),a=n%60;if(s<60)return a>0?`${s}m ${a}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function lc(e){const n=Date.now(),s=new Date(e).getTime(),a=n-s;if(a<0){const r=Math.abs(a);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return a<6e4?"just now":a<36e5?`${Math.floor(a/6e4)}m ago`:a<864e5?`${Math.floor(a/36e5)}h ago`:`${Math.floor(a/864e5)}d ago`}const $D={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},$v={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},DD={cron:Qg,webhook:lb,api:Xg,manual:ls},LD={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},OD={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function FD({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(Xn,{size:12}):t.jsx(Ho,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Pv(n)})]})}function zD({result:e,index:n}){const[s,a]=i.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>a(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${lc(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Xn,{size:12}):t.jsx(Ho,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:lc(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:$v[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Pv(r)}),s?t.jsx(Li,{size:12}):t.jsx(gn,{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 BD({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=li(),m=i.useCallback(async()=>{await u({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,u]),h=$D[e.trigger.type],f=DD[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:h,color:h},children:[t.jsx(f,{size:10}),$v[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(gc,{size:10}):t.jsx(js,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>a(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(jt,{className:"spinner"}):t.jsx(os,{})}),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(Ci,{}):t.jsx(os,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Hs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Tn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Fa,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ta,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:LD[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:OD[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:lc(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:lc(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(FD,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>d(g=>!g),"aria-expanded":c,children:[c?t.jsx(Li,{size:12}):t.jsx(gn,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,w)=>t.jsx(zD,{result:g,index:w},`${g.startedAt}-${w}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function UD({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(ea,{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(ik,{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(ms,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function qd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function HD(e){return e==="command"?{id:qd(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:qd(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:qd(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function qD({step:e,onSave:n,onCancel:s}){const[a,r]=i.useState(e.name),[o,l]=i.useState(e.type),[c,d]=i.useState(e.command??""),[u,m]=i.useState(e.prompt??""),[h,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[w,v]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[S,j]=i.useState(e.taskColumn??"triage"),[C,x]=i.useState(e.timeoutMs),[N,R]=i.useState(e.continueOnFailure??!1),[F,E]=i.useState({}),[_,K]=i.useState([]),[U,A]=i.useState(!1),[T,H]=i.useState(null);i.useEffect(()=>{let D=!1;return A(!0),H(null),Ws().then($=>{D||K($.models)}).catch($=>{D||H($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{D||A(!1)}),()=>{D=!0}},[]);const Q=i.useCallback(()=>{const D={};return a.trim()||(D.name="Step name is required"),o==="command"&&!c.trim()&&(D.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(D.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(D.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(D.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(D.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(D),Object.keys(D).length===0},[a,o,c,u,b,h,p,C]),se=h&&p?`${h}/${p}`:"",O=i.useCallback(D=>{if(!D)f(""),g("");else{const $=D.indexOf("/");$!==-1&&(f(D.slice(0,$)),g(D.slice($+1)))}},[]),M=i.useCallback(()=>{if(!Q())return;const D={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.trim():void 0,taskTitle:o==="create-task"&&w.trim()?w.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:C||void 0,continueOnFailure:N};o!=="ai-prompt"&&delete D.prompt,o!=="create-task"&&(delete D.taskTitle,delete D.taskDescription,delete D.taskColumn),n(D)},[Q,n,e,a,o,c,u,w,b,S,h,p,C,N]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:D=>r(D.target.value),"aria-invalid":!!F.name}),F.name&&t.jsx("small",{className:"field-error",children:F.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:D=>l(D.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:D=>d(D.target.value),rows:2,"aria-invalid":!!F.command}),F.command&&t.jsx("small",{className:"field-error",children:F.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:D=>m(D.target.value),rows:3,"aria-invalid":!!F.prompt}),F.prompt&&t.jsx("small",{className:"field-error",children:F.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(_s,{id:`step-model-${e.id}`,label:"Model",models:_,value:se,onChange:O,placeholder:"Use default",disabled:U}),T&&t.jsx("small",{className:"field-error",children:T}),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:w,onChange:D=>v(D.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:D=>y(D.target.value),rows:4,"aria-invalid":!!F.taskDescription}),F.taskDescription&&t.jsx("small",{className:"field-error",children:F.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:D=>j(D.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(_s,{id:`step-task-model-${e.id}`,label:"Model",models:_,value:se,onChange:O,placeholder:"Use default",disabled:U}),T&&t.jsx("small",{className:"field-error",children:T}),F.modelProvider&&t.jsx("small",{className:"field-error",children:F.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:D=>x(D.target.value?Number(D.target.value):void 0),"aria-invalid":!!F.timeoutMs}),F.timeoutMs&&t.jsx("small",{className:"field-error",children:F.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:N,onChange:D=>R(D.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:M,children:"Save Step"})]})]})}function VD({steps:e,onChange:n,onEditingChange:s}){const[a,r]=i.useState(null);i.useEffect(()=>{s?.(a!==null)},[a,s]);const o=i.useCallback(u=>{const m=HD(u);n([...e,m]),r(m.id)},[e,n]),l=i.useCallback(u=>{n(e.filter(m=>m.id!==u)),a===u&&r(null)},[e,n,a]),c=i.useCallback((u,m)=>{const h=e.findIndex(g=>g.id===u);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),d=i.useCallback(u=>{n(e.map(m=>m.id===u.id?u:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((u,m)=>t.jsx("div",{className:"step-card",children:a===u.id?t.jsx(qD,{step:u,onSave:d,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(xc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(UD,{type:u.type}),t.jsx("span",{className:"step-card-name",children:u.name}),u.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(Li,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(gn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Hs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(Tn,{})})]})]})},u.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx($n,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx($n,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx($n,{size:14}),"Add Create Task Step"]})]})]})}const Dv={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},WD={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function GD(e){const n=e.trim();for(const[s,a]of Object.entries(Dv))if(a===n)return s;return"custom"}function KD(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function JD(e,n,s,a,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:a||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function YD(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 QD=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],XD=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Zf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function eg({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?YD(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,w]=i.useState(c.cronExpression),[v,b]=i.useState(()=>c.triggerType!=="cron"?"custom":GD(c.cronExpression)),[y,S]=i.useState(c.webhookPath),[j,C]=i.useState(c.webhookSecret),[x,N]=i.useState(c.endpoint),[R,F]=i.useState(e?.executionPolicy??"queue"),[E,_]=i.useState(e?.catchUpPolicy??"run_one"),[K,U]=i.useState(e?.enabled??!0),A=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,T=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[H,Q]=i.useState(e?.steps&&e.steps.length>0&&!A&&!T?"advanced":"simple"),[se,O]=i.useState(()=>A?"ai-prompt":T?"create-task":"command"),[M,D]=i.useState(e?.command??""),[$,k]=i.useState(e?.steps??[]),[X,le]=i.useState(!1),[ke,He]=i.useState(e?.timeoutMs??3e5),[ye,je]=i.useState(A?e.steps?.[0]?.prompt??"":""),[ne,fe]=i.useState(T?e.steps?.[0]?.taskTitle??"":""),[Z,re]=i.useState(T?e.steps?.[0]?.taskDescription??"":""),[q,L]=i.useState(T?e.steps?.[0]?.taskColumn??"triage":"triage"),[xe,he]=i.useState(A||T?e.steps?.[0]?.modelProvider??"":""),[B,pe]=i.useState(A||T?e.steps?.[0]?.modelId??"":""),[ze,ae]=i.useState([]),[Ve,Te]=i.useState(!1),[rt,Be]=i.useState(null),[ce,Re]=i.useState(a??"global"),[Le,ct]=i.useState({}),[Ue,ue]=i.useState(!1),oe=i.useRef(!0);i.useEffect(()=>()=>{oe.current=!1},[]),i.useEffect(()=>{a&&Re(a)},[a]),i.useEffect(()=>{let be=!1;return Te(!0),Be(null),Ws().then(gt=>{be||ae(gt.models)}).catch(gt=>{be||Be(gt instanceof Error?gt.message:"Failed to load models")}).finally(()=>{be||Te(!1)}),()=>{be=!0}},[]);const Ee=xe&&B?`${xe}/${B}`:"",ft=i.useCallback(be=>{if(!be){he(""),pe("");return}const gt=be.indexOf("/");gt!==-1&&(he(be.slice(0,gt)),pe(be.slice(gt+1)))},[]),ht=i.useCallback(()=>{const be={};if(d.trim()||(be.name="Name is required"),ce==="project"&&!r&&(be.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?KD(g)||(be.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):be.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(be.webhookPath="Webhook path is required"),f==="api"&&!x.trim()&&(be.endpoint="API endpoint is required"),H==="simple")se==="command"&&!M.trim()&&(be.command="Command is required"),se==="ai-prompt"&&!ye.trim()&&(be.prompt="Prompt is required"),se==="create-task"&&!Z.trim()&&(be.taskDescription="Task description is required"),(xe.trim()&&!B.trim()||!xe.trim()&&B.trim())&&(be.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(be.steps="At least one step is required"),X&&(be.stepsEditing="Please save or cancel all step edits before saving the routine");const gt=[];$.forEach(($t,Ie)=>{$t.name?.trim()||gt.push(`Step ${Ie+1}: Name is required`),$t.type==="command"&&!$t.command?.trim()&&gt.push(`Step ${Ie+1}: Command is required`),$t.type==="ai-prompt"&&!$t.prompt?.trim()&&gt.push(`Step ${Ie+1}: Prompt is required`),$t.type==="create-task"&&!$t.taskDescription?.trim()&&gt.push(`Step ${Ie+1}: Task description is required`)}),gt.length>0&&(be.steps=gt.join("; "))}return ke<1e3&&(be.timeoutMs="Timeout must be at least 1 second (1000ms)"),ct(be),Object.keys(be).length===0},[d,f,g,v,y,x,ce,r,H,se,M,ye,Z,xe,B,$,X,ke]),tt=i.useCallback(async be=>{if(be.preventDefault(),!!ht()){ue(!0);try{let gt=e?.scope??ce??(r?"project":"global");gt==="project"&&!r&&(gt="global");const $t=JD(f,g,y,j,x);let Ie,ge;H==="simple"?se==="command"?Ie=M.trim()||void 0:se==="ai-prompt"?ge=[{id:Zf(),type:"ai-prompt",name:d.trim(),prompt:ye.trim(),modelProvider:xe.trim()||void 0,modelId:B.trim()||void 0}]:ge=[{id:Zf(),type:"create-task",name:d.trim(),taskTitle:ne.trim()||void 0,taskDescription:Z.trim(),taskColumn:q,modelProvider:xe.trim()||void 0,modelId:B.trim()||void 0}]:ge=$;const st={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:$t,command:Ie,steps:ge,timeoutMs:ke,executionPolicy:R,catchUpPolicy:E,enabled:K,scope:gt};await n(st)}finally{oe.current&&ue(!1)}}},[ht,n,d,m,f,g,y,j,x,H,se,M,ye,xe,B,ne,Z,q,$,ke,R,E,K,ce,r,e?.scope,e?.agentId]),xt="routine-name-error",Me="routine-cron-error",Ye="routine-webhook-error",dt="routine-endpoint-error",wt="routine-command-error",St="routine-prompt-error",Fe="routine-task-description-error",J="routine-model-error",me="routine-timeout-error",Ze=i.useCallback(be=>{b(be),be!=="custom"&&w(Dv[be])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:tt,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:d,onChange:be=>u(be.target.value),"aria-invalid":!!Le.name,"aria-describedby":Le.name?xt:void 0}),Le.name&&t.jsx("small",{id:xt,className:"field-error",children:Le.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${ce==="global"?" active":""}`,onClick:()=>{Re("global"),o?.("global")},role:"radio","aria-checked":ce==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(gc,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${ce==="project"?" active":""}`,onClick:()=>{Re("project"),o?.("project")},role:"radio","aria-checked":ce==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(js,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":ce==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Le.scope&&t.jsx("small",{className:"field-error",children:Le.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(Qg,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(lb,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":f==="api",children:[t.jsx(Xg,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":f==="manual",children:[t.jsx(ls,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:be=>Ze(be.target.value),children:Object.entries(WD).map(([be,gt])=>t.jsx("option",{value:be,children:gt},be))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:be=>w(be.target.value),disabled:v!=="custom","aria-invalid":!!Le.cronExpression,"aria-describedby":Le.cronExpression?Me:void 0}),Le.cronExpression?t.jsx("small",{id:Me,className:"field-error",children:Le.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:be=>S(be.target.value),"aria-invalid":!!Le.webhookPath,"aria-describedby":Le.webhookPath?Ye:void 0}),Le.webhookPath?t.jsx("small",{id:Ye,className:"field-error",children:Le.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:j,onChange:be=>C(be.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:x,onChange:be=>N(be.target.value),"aria-invalid":!!Le.endpoint,"aria-describedby":Le.endpoint?dt:void 0}),Le.endpoint?t.jsx("small",{id:dt,className:"field-error",children:Le.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),f==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${H==="simple"?" active":""}`,onClick:()=>Q("simple"),role:"radio","aria-checked":H==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${H==="advanced"?" active":""}`,onClick:()=>Q("advanced"),role:"radio","aria-checked":H==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:H==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),H==="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${se==="command"?" active":""}`,onClick:()=>O("command"),role:"radio","aria-checked":se==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${se==="ai-prompt"?" active":""}`,onClick:()=>O("ai-prompt"),role:"radio","aria-checked":se==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${se==="create-task"?" active":""}`,onClick:()=>O("create-task"),role:"radio","aria-checked":se==="create-task",children:"Create Task"})]})]}),se==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:M,onChange:be=>D(be.target.value),"aria-invalid":!!Le.command,"aria-describedby":Le.command?wt:void 0}),Le.command?t.jsx("small",{id:wt,className:"field-error",children:Le.command}):t.jsx("small",{children:"Shell command to execute."})]}):se==="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:ye,onChange:be=>je(be.target.value),rows:3,"aria-invalid":!!Le.prompt,"aria-describedby":Le.prompt?St:void 0}),Le.prompt?t.jsx("small",{id:St,className:"field-error",children:Le.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(_s,{id:"routine-model",label:"Model",models:ze,value:Ee,onChange:ft,placeholder:"Use default",disabled:Ve}),rt&&t.jsx("small",{className:"field-error",children:rt}),Le.model&&t.jsx("small",{id:J,className:"field-error",children:Le.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:ne,onChange:be=>fe(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:Z,onChange:be=>re(be.target.value),rows:4,"aria-invalid":!!Le.taskDescription,"aria-describedby":Le.taskDescription?Fe:void 0}),Le.taskDescription?t.jsx("small",{id:Fe,className:"field-error",children:Le.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:q,onChange:be=>L(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(_s,{id:"routine-task-model",label:"Executor Model",models:ze,value:Ee,onChange:ft,placeholder:"Use default",disabled:Ve}),rt&&t.jsx("small",{className:"field-error",children:rt}),Le.model&&t.jsx("small",{id:J,className:"field-error",children:Le.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(VD,{steps:$,onChange:k,onEditingChange:le}),Le.steps&&t.jsx("small",{className:"field-error",children:Le.steps}),Le.stepsEditing&&t.jsx("small",{className:"field-error",children:Le.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:ke,onChange:be=>He(Number(be.target.value)),"aria-invalid":!!Le.timeoutMs,"aria-describedby":Le.timeoutMs?me:void 0}),Le.timeoutMs?t.jsx("small",{id:me,className:"field-error",children:Le.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:R,onChange:be=>F(be.target.value),children:QD.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:E,onChange:be=>_(be.target.value),children:XD.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:K,onChange:be=>U(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:Ue,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ue,children:Ue?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const ZD=3e4;function eL({onClose:e,addToast:n,projectId:s}){const[a,r]=i.useState(()=>s?"project":"global"),[o,l]=i.useState([]),[c,d]=i.useState("list"),[u,m]=i.useState(),[h,f]=i.useState(null),[p,g]=i.useState({}),w=i.useRef(null);zi(w,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const A=await LS(v);l(A),g(T=>{const H={...T};for(const Q of A){const se=H[Q.id];if(!se||!Q.lastRunResult)continue;const O=Q.lastRunResult;O.success===se.success&&(O.output||"")===se.output&&(O.error||"")===(se.error||"")&&delete H[Q.id]}return H})}catch(A){n(Se(A)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const A=setInterval(()=>{b()},ZD);return()=>clearInterval(A)},[b]),i.useEffect(()=>{const A=T=>{T.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e,c]);const y=sa(e),S=i.useCallback(async A=>{try{await OS(A,v),n("Routine created","success"),d("list"),await b()}catch(T){n(Se(T)||"Failed to create routine","error")}},[n,b,v]),j=i.useCallback(A=>{m(A),d("edit")},[]),C=i.useCallback(async A=>{if(u)try{await Zm(u.id,A,v),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(T){n(Se(T)||"Failed to update routine","error")}},[u,n,b,v]),x=i.useCallback(async A=>{try{await FS(A.id,v),n(`Deleted "${A.name}"`,"success"),await b()}catch(T){n(Se(T)||"Failed to delete routine","error")}},[n,b,v]),N=i.useCallback(async A=>{f(A.id);try{const{result:T}=await zS(A.id,v);g(H=>({...H,[A.id]:{output:T.output||"",error:T.error,success:T.success}})),T.success?n(`"${A.name}" completed successfully`,"success"):n(`"${A.name}" failed: ${T.error||"Unknown error"}`,"error"),await b()}catch(T){n(Se(T)||"Failed to run routine","error")}finally{f(null)}},[n,b,v]),R=i.useCallback(async A=>{try{await Zm(A.id,{enabled:!A.enabled},v),n(`"${A.name}" ${A.enabled?"disabled":"enabled"}`,"success"),await b()}catch(T){n(Se(T)||"Failed to toggle routine","error")}},[n,b,v]),F=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const E=i.useCallback(A=>{r(A),d("list"),m(void 0),g({})},[]),_=()=>c==="create"?t.jsx(eg,{onSubmit:S,onCancel:F,scope:a,projectId:s}):c==="edit"&&u?t.jsx(eg,{routine:u,onSubmit:C,onCancel:F,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(ls,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),children:[t.jsx($n,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(A=>t.jsx(BD,{routine:A,onEdit:j,onDelete:x,onRun:N,onToggle:R,running:h===A.id,lastRunOutput:p[A.id]??null},A.id))}),K=()=>_(),U=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:w,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(ls,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(mn,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${a==="global"?" active":""}`,onClick:()=>E("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(gc,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>E("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(js,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(ls,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:U&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx($n,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:K()})]})})}const tL=3e4,Iu=new Map,Vd=new Map;function tg(e){return e??"default"}function ng(e){const n=Iu.get(e);return n?Date.now()>=n.expiresAt?(Iu.delete(e),null):n:null}function nL(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),a=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:a}}async function sL(e){const n=Vd.get(e);if(n)return n;const s=Po().then(({providers:a,ghCli:r})=>{const l={...nL(a,r),ghCli:r,expiresAt:Date.now()+tL};return Iu.set(e,l),l}).finally(()=>{Vd.delete(e)});return Vd.set(e,s),s}function Lv(e){const n=tg(e),s=ng(n),[a,r]=i.useState(s?.hasAiProvider??!1),[o,l]=i.useState(s?.hasGithub??!1),[,c]=i.useState(s?.ghCli),[d,u]=i.useState(s==null),m=i.useRef(!!s);return i.useEffect(()=>{let h=!1;const f=tg(e),p=ng(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const v=await sL(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function Ov({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:a}){if(e&&n)return null;const r=a?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:a,children:t.jsx(mn,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function iL({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=li(),u=oi();Mi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=aa({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[w,v]=i.useState(""),[b,y]=i.useState([]),[S,j]=i.useState(""),[C,x]=i.useState(""),[N,R]=i.useState([]),[F,E]=i.useState(!1),[_,K]=i.useState(""),[U,A]=i.useState(""),[T,H]=i.useState(""),[Q,se]=i.useState(""),[O,M]=i.useState(""),[D,$]=i.useState("default"),[k,X]=i.useState(!1),[le,ke]=i.useState([]),[He,ye]=i.useState(!1),[je,ne]=i.useState(void 0),[fe,Z]=i.useState(Ps),[re,q]=i.useState(void 0),[L,xe]=i.useState(!1),[he,B]=i.useState(""),[pe,ze]=i.useState(null),[ae,Ve]=i.useState([]),[Te,rt]=i.useState(!1),[Be,ce]=i.useState(!1),Re=i.useRef(null),[Le,ct]=i.useState(!1),[Ue,ue]=i.useState(""),oe=i.useRef(null),{hasAiProvider:Ee,hasGithub:ft,loading:ht}=Lv(s),{nodes:tt}=Cc(),xt=i.useCallback(ge=>{ye(!0),ke(ge)},[]),Me=i.useCallback(()=>{ye(!1)},[]),Ye=i.useCallback(async()=>{if(ae.length>0){rt(!0);return}ce(!0);try{const ge=await Ur(void 0,s);Ve(ge),rt(!0)}catch(ge){const st=Se(ge);o(st?`Failed to load agents: ${st}`:"Failed to load agents","error"),rt(!1)}finally{ce(!1)}},[ae.length,s,o]);i.useEffect(()=>{if(!Te)return;const ge=st=>{Re.current&&!Re.current.contains(st.target)&&rt(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Te]),i.useEffect(()=>{if(!Le)return;const ge=st=>{oe.current&&!oe.current.contains(st.target)&&(ct(!1),ue(""))};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Le]);const dt=a.filter(ge=>!b.includes(ge.id)).sort((ge,st)=>{const yt=st.createdAt.localeCompare(ge.createdAt);if(yt!==0)return yt;const pt=parseInt(ge.id.slice(ge.id.lastIndexOf("-")+1),10)||0;return(parseInt(st.id.slice(st.id.lastIndexOf("-")+1),10)||0)-pt}),wt=Ue?dt.filter(ge=>ge.id.toLowerCase().includes(Ue.toLowerCase())||ge.title&&ge.title.toLowerCase().includes(Ue.toLowerCase())||ge.description&&ge.description.toLowerCase().includes(Ue.toLowerCase())):dt,St=(ge,st)=>ge.length>st?ge.slice(0,st)+"…":ge,Fe=he.trim(),J=Fe.length>0&&!Sc.test(Fe);i.useEffect(()=>{const ge=w.trim()!==""||b.length>0||N.length>0||_!==""||U!==""||T!==""||Q!==""||le.length>0||pe!==null||je!==void 0||fe!==Ps||re!==void 0||S!==""||C!==""||L||Fe!=="";X(ge)},[w,b,N,_,U,T,Q,le,pe,je,fe,re,S,C,L,Fe]);const me=i.useCallback(async()=>{k&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(N.forEach(ge=>URL.revokeObjectURL(ge.previewUrl)),R([]),v(""),y([]),K(""),A(""),H(""),se(""),M(""),$("default"),ke([]),ye(!1),ze(null),rt(!1),ne(void 0),Z(Ps),q(void 0),j(""),x(""),X(!1),xe(!1),B(""),n())},[k,n,N,d]),Ze=i.useCallback(async()=>{const ge=w.trim();if(!(!ge||F||J)){E(!0);try{const st=_.indexOf("/"),yt=U.indexOf("/"),pt=T.indexOf("/"),vt=await r({title:void 0,description:ge,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:He?le.length>0?le:[]:void 0,...pe?{assignedAgentId:pe}:{},modelPresetId:D==="preset"&&O||void 0,modelProvider:_&&st!==-1?_.slice(0,st):void 0,modelId:_&&st!==-1?_.slice(st+1):void 0,validatorModelProvider:U&&yt!==-1?U.slice(0,yt):void 0,validatorModelId:U&&yt!==-1?U.slice(yt+1):void 0,planningModelProvider:T&&pt!==-1?T.slice(0,pt):void 0,planningModelId:T&&pt!==-1?T.slice(pt+1):void 0,thinkingLevel:Q!==""?Q:void 0,reviewLevel:je,priority:fe,nodeId:re,branch:S.trim()===""?void 0:S.trim(),baseBranch:C.trim()===""?void 0:C.trim(),...L||Fe!==""?{githubTracking:{enabled:L,...Fe!==""?{repoOverride:Fe}:{}}}:{}});if(N.length>0){const Ut=[];for(const Dt of N)try{await jc(vt.id,Dt.file,s)}catch{Ut.push(Dt.file.name)}Ut.length>0&&o(`Failed to upload: ${Ut.join(", ")}`,"error")}N.forEach(Ut=>URL.revokeObjectURL(Ut.previewUrl)),R([]),v(""),y([]),K(""),A(""),H(""),se(""),M(""),$("default"),ke([]),ye(!1),ze(null),rt(!1),ne(void 0),Z(Ps),q(void 0),j(""),x(""),o(`Created ${vt.id}`,"success"),n()}catch(st){o(Se(st)||"Failed to create task","error")}finally{E(!1)}}},[w,b,N,_,U,T,Q,F,r,o,n,s,D,O,le,He,pe,je,fe,re,S,C]),be=i.useCallback(ge=>{ge.key==="Escape"&&(ge.preventDefault(),me())},[me]),$t=(pe?ae.find(ge=>ge.id===pe):void 0)?.name??pe,Ie=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:oe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ct(ge=>!ge),disabled:F,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),Le&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ue,onChange:ge=>ue(ge.target.value),onClick:ge=>ge.stopPropagation()}),wt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):wt.map(ge=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(ge.id)?" selected":""}`,onClick:()=>{y(b.includes(ge.id)?b.filter(st=>st!==ge.id):[...b,ge.id]),ct(!1),ue("")},onMouseDown:st=>st.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ge.id}),t.jsx("span",{className:"dep-dropdown-title",children:St(ge.title||ge.description||ge.id,30)})]},ge.id))]})]}),b.length>0&&t.jsx("div",{className:"selected-deps",children:b.map(ge=>t.jsxs("span",{className:"dep-chip",children:[ge,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>y(b.filter(st=>st!==ge)),disabled:F,children:"×"})]},ge))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:Re,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{Te?rt(!1):Ye()},disabled:F,"data-testid":"new-task-agent-button",children:[t.jsx(Qn,{size:12,style:{verticalAlign:"middle"}}),$t?` ${$t}`:" Assign agent"]}),Te&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ge=>ge.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Be&&ae.map(ge=>t.jsxs("div",{className:`dep-dropdown-item${pe===ge.id?" selected":""}`,onMouseDown:st=>st.preventDefault(),onClick:()=>{ze(ge.id===pe?null:ge.id),rt(!1)},"data-testid":`agent-option-${ge.id}`,children:[t.jsx(Qn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ge.role}),t.jsx("span",{className:"dep-dropdown-title",children:ge.name})]},ge.id)),!Be&&ae.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),pe&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ge=>ge.preventDefault(),onClick:()=>{ze(null),rt(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:me,onKeyDown:be,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ge=>ge.stopPropagation(),style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:me,disabled:F,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!ht&&t.jsx(Ov,{hasAiProvider:Ee,hasGithub:ft}),t.jsx(gv,{mode:"create",description:w,onDescriptionChange:v,dependencies:b,onDependenciesChange:y,executorModel:_,onExecutorModelChange:K,validatorModel:U,onValidatorModelChange:A,presetMode:D,onPresetModeChange:$,selectedPresetId:O,onSelectedPresetIdChange:M,selectedWorkflowSteps:le,onWorkflowStepsChange:xt,onDefaultOnApplied:Me,pendingImages:N,onImagesChange:R,tasks:a,projectId:s,disabled:F,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:me,planningModel:T,onPlanningModelChange:H,thinkingLevel:Q,onThinkingLevelChange:se,reviewLevel:je,onReviewLevelChange:ne,priority:fe,onPriorityChange:Z,branch:S,onBranchChange:j,baseBranch:C,onBaseBranchChange:x,nodeId:re,onNodeIdChange:q,nodeOptions:tt,githubTrackingEnabled:L,onGithubTrackingEnabledChange:xe,githubRepoOverride:he,onGithubRepoOverrideChange:B,renderBelowPrimary:Ie,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:me,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ze,disabled:!w.trim()||F||J,children:F?"Creating...":"Create Task"})]})]})}):null}function Ni(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function sg(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function aL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function rL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function oL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function lL(e,n){if(e===null||!Number.isFinite(e)||e<0)return"normal";const s=n>0?e/n:e;return s>=80?"critical":s>=50?"warning":"normal"}function Pl(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function cL(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function dL({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,m]=i.useState(!0),[h,f]=i.useState(90),[p,g]=i.useState(!1),[w,v]=i.useState(!1),[b,y]=i.useState(null),[S,j]=i.useState(null),[C,x]=i.useState(null),N=i.useCallback(async ne=>{l(!0);try{const fe=await w1(s);r(fe),d(null),x(Date.now()),ne?.preserveKillResult||y(null)}catch(fe){d(fe instanceof Error?fe.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;N();const ne=window.setInterval(()=>{N()},5e3);return()=>{window.clearInterval(ne)}},[e,N]),i.useEffect(()=>{if(!e)return;(async()=>{try{const fe=await na();m(fe.vitestAutoKillEnabled??!0),f(fe.vitestKillThresholdPct??90),j(null)}catch(fe){j(fe instanceof Error?fe.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const ne=fe=>{fe.key==="Escape"&&n()};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[e,n]);const R=i.useMemo(()=>{if(!a)return[];const ne=a.systemStats,fe=Pl(aL(ne.heapUsed,ne.heapLimit)),Z=Pl(rL(ne.rss,ne.systemTotalMem));return[{label:"RSS",value:Ni(ne.rss),detail:sg(ne.rss,ne.systemTotalMem),className:Z},{label:"Heap Used",value:Ni(ne.heapUsed),detail:`of ${Ni(ne.heapTotal)}`,className:fe},{label:"Heap Limit",value:Ni(ne.heapLimit),detail:"V8 limit"},{label:"External",value:Ni(ne.external)},{label:"Array Buffers",value:Ni(ne.arrayBuffers)}]},[a]),F=i.useCallback(async ne=>{m(ne);try{await Bn({vitestAutoKillEnabled:ne}),j(null)}catch(fe){j(fe instanceof Error?fe.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async ne=>{const fe=Math.min(99,Math.max(50,Number.isFinite(ne)?Math.round(ne):90));f(fe);try{await Bn({vitestKillThresholdPct:fe}),j(null)}catch(Z){j(Z instanceof Error?Z.message:"Failed to save vitest settings")}},[]),_=i.useCallback(async()=>{if(!p){if(!w){v(!0);return}g(!0);try{const ne=await k1(s);y(ne),v(!1),await N({preserveKillResult:!0})}catch(ne){d(ne instanceof Error?ne.message:"Failed to kill vitest processes")}finally{g(!1)}}},[w,p,N,s]);if(!e)return null;const K=a?.systemStats,U=o&&!!a,A=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",T=a?.taskStats,H=K?K.systemTotalMem-K.systemFreeMem:0,Q=K?oL(H,K.systemTotalMem):"normal",se=K?Pl(Q):"",O=K&&Number.isFinite(K.systemTotalMem)&&K.systemTotalMem>0?Math.max(0,Math.min(100,H/K.systemTotalMem*100)):0,M=K?`System memory used: ${O.toFixed(1)}% (${Ni(H)} of ${Ni(K.systemTotalMem)})`:"System memory usage unavailable",D=a?.vitestProcessCount,$=lL(K?.cpuPercent??null,K?.cpuCount??0),k=Pl($),X=K?.cpuPercent??null,le=X===null?0:Math.max(0,Math.min(100,X)),ke=X===null?"Sampling…":`${X.toFixed(1)}%`,He=X===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${X.toFixed(1)}%`,ye=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",je=cL(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:ne=>{ne.target===ne.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(Cr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:A})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void N(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(ps,{size:16,className:U?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(mn,{})})]})]}),o&&!a&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!a&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),a&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:R.map(ne=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ne.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ne.className}`.trim(),children:ne.value}),ne.detail?t.jsx("span",{className:"system-stats-modal__detail",children:ne.detail}):null]})]},ne.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--cpu-used",children:[t.jsx("dt",{children:"App CPU"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${k}`.trim(),children:ke}),t.jsx("span",{className:"system-stats-modal__detail",children:X===null?"First sample pending":"process usage"})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${$}`,role:"progressbar","aria-valuenow":Math.round(le),"aria-valuemin":0,"aria-valuemax":100,"aria-label":He,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${$}`,style:{width:`${le}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:K?.loadAvg.map(ne=>ne.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:K?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:K?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:K?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:K?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${se}`.trim(),children:K?Ni(H):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:K?`${sg(H,K.systemTotalMem)} of ${Ni(K.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${Q}`,role:"progressbar","aria-valuenow":Math.round(O),"aria-valuemin":0,"aria-valuemax":100,"aria-label":M,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${Q}`,style:{width:`${O}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:K?Ni(K.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:T?.total??0})]}),Object.entries(T?.byColumn??{}).map(([ne,fe])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ne}),t.jsx("dd",{children:fe})]},ne))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:T?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:T?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:T?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:T?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(Vk,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:D??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void _(),disabled:p||D===0,children:[t.jsx(Jk,{}),t.jsx("span",{children:w?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:u,onChange:ne=>{F(ne.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:ne=>{const fe=Number.parseInt(ne.target.value,10);E(Number.isNaN(fe)?90:fe)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:ne=>{const fe=Number.parseInt(ne.target.value,10);E(Number.isNaN(fe)?90:fe)},onBlur:()=>{E(h)}})]})]}),b&&t.jsxs("p",{className:ye,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",je]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const uL=5e3;function mL(e={}){const{projectId:n,type:s,limit:a=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),w=i.useRef(void 0),v=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await oh({limit:a,projectId:n,type:s}):S=(await eh({limit:a,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(S),p(S.length===a),S.length>0&&(w.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(w.current)try{u(!0);let S;o?S=await oh({limit:a,projectId:n,type:s,since:w.current}):S=(await eh({limit:a,type:s,since:w.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(j=>[...j,...S]),p(S.length===a),S.length>0&&(w.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),w.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},uL),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:m,refresh:v,clear:y,hasMore:f,loadMore:b}}const Wd={"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"},hL={"task:created":t.jsx($n,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Uo,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(ps,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(mn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Xn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Ho,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Co,{size:14,className:"activity-icon settings"})};function pL(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function fL({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[m,h]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{h(r||"all")},[r]);const g=d==="all"?void 0:d,w=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:j,hasMore:C}=mL({projectId:w,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),x=b.map(_=>({id:_.id,timestamp:_.timestamp,type:_.type,taskId:_.taskId,taskTitle:_.taskTitle,details:_.details,metadata:_.metadata,projectId:_.projectId,projectName:_.projectName})),N=async()=>{try{await BS(),j(),p(!1)}catch{p(!1)}},R=_=>{a&&a(_)},F=_=>{h(_),l?.(_==="all"?void 0:_)};i.useEffect(()=>{if(!e)return;const _=K=>{K.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n,f]);const E=d!=="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(Oa,{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(js,{size:14}),t.jsxs("select",{value:m,onChange:_=>F(_.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(ql,{size:14}),t.jsxs("select",{value:d,onChange:_=>u(_.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Wd).map(([_,K])=>t.jsx("option",{value:_,children:K},_))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14})}),x.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Tn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(_=>_.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Wd[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Vs,{size:16}),t.jsx("span",{children:S})]}),x.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Oa,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:x.map(_=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:hL[_.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:Wd[_.type]}),t.jsx("span",{className:"activity-log-entry-time",children:pL(_.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[_.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>R(_.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:Cs(_.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))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),y&&x.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(jt,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:N,children:"Clear Log"})]})]})})]})}):null}const ho=[{id:"status",label:"Status",icon:rb},{id:"changes",label:"Changes",icon:su},{id:"commits",label:"Commits",icon:Nr},{id:"branches",label:"Branches",icon:Os},{id:"worktrees",label:"Worktrees",icon:Uw},{id:"stashes",label:"Stashes",icon:zo},{id:"remotes",label:"Remotes",icon:sb}];function ig({status:e}){switch(e){case"added":case"untracked":return t.jsx(ww,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(tb,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(xw,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(xa,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(jw,{size:14,className:"gm-file-icon"})}}function ag({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 gL(e){return i.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function Tr(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function bL({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=li(),l=oi();Mi(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=aa({enabled:l==="mobile"}),h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{},f=i.useCallback(()=>{if(l==="mobile"){const Y=document.activeElement;Y instanceof HTMLElement&&Y.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[w,v]=i.useState(!1),[b,y]=i.useState(null),S=i.useRef(null);zi(S,e,"fusion:git-modal-size");const j=sa(f),C=gL(a),[x,N]=i.useState(null),[R,F]=i.useState([]),[E,_]=i.useState(new Set),[K,U]=i.useState(""),[A,T]=i.useState(!1),[H,Q]=i.useState(null),[se,O]=i.useState(!1),[M,D]=i.useState(null),[$,k]=i.useState(null),X=i.useRef(0),[le,ke]=i.useState([]),[He,ye]=i.useState(null),[je,ne]=i.useState(null),[fe,Z]=i.useState(!1),[re,q]=i.useState(20),[L,xe]=i.useState(""),[he,B]=i.useState([]),[pe,ze]=i.useState(""),[ae,Ve]=i.useState(""),[Te,rt]=i.useState(""),[Be,ce]=i.useState(null),[Re,Le]=i.useState([]),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState(null),[Ee,ft]=i.useState(null),[ht,tt]=i.useState(!1),[xt,Me]=i.useState([]),[Ye,dt]=i.useState([]),[wt,St]=i.useState(""),[Fe,J]=i.useState(null),[me,Ze]=i.useState(null),[be,gt]=i.useState(null),[$t,Ie]=i.useState(!1),[ge,st]=i.useState(null),yt=i.useRef(0),[pt,vt]=i.useState(null),[Ut,Dt]=i.useState(null),nn=i.useCallback(async()=>{if(e){v(!0),y(null);try{switch(p){case"status":{const Y=await ji(r);N(Y);break}case"changes":{const[Y,_e]=await Promise.all([ji(r),cr(r)]);N(Y),F(_e),_(new Set),k(null),Q(null),D(null);break}case"commits":{const Y=await qN(re,r);ke(Y);break}case"branches":{const[Y,_e]=await Promise.all([Xr(r),ji(r)]);B(Y),N(_e);break}case"worktrees":{const Y=await KN(r);Me(Y);break}case"stashes":{const Y=await al(r);dt(Y),Ze(null),gt(null),st(null),yt.current+=1;break}case"remotes":{const Y=await ji(r);N(Y);break}}}catch(Y){y(Se(Y)||"Failed to fetch git data"),a(Se(Y)||"Failed to fetch git data","error")}finally{v(!1)}}},[p,e,re,a,r]);i.useEffect(()=>{e&&nn()},[nn,e]),i.useEffect(()=>{if(!e)return;const Y=_e=>{if(_e.key==="Escape"){f();return}if((_e.key==="ArrowUp"||_e.key==="ArrowDown")&&_e.altKey){_e.preventDefault();const ut=ho.findIndex(At=>At.id===p);_e.key==="ArrowUp"&&ut>0?g(ho[ut-1].id):_e.key==="ArrowDown"&&ut<ho.length-1&&g(ho[ut+1].id)}};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[e,f,p]);const on=i.useCallback(async Y=>{try{await Km(Y,r),a(`Staged ${Y.length} file(s)`,"success");const _e=await cr(r);F(_e),_(new Set),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to stage files","error")}},[a,r]),sn=i.useCallback(async Y=>{try{await aS(Y,r),a(`Unstaged ${Y.length} file(s)`,"success");const _e=await cr(r);F(_e),_(new Set),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to unstage files","error")}},[a,r]),ln=i.useCallback(async Y=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${Y.length} file(s)? This cannot be undone.`,danger:!0}))try{await rS(Y,r),a(`Discarded changes to ${Y.length} file(s)`,"success");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),_(new Set),k(null),Q(null),D(null)}catch(ut){a(Se(ut)||"Failed to discard changes","error")}},[a,r,o]),xn=i.useCallback(async Y=>{if(Y.preventDefault(),!!K.trim()){T(!0);try{const _e=await Jm(K.trim(),r);a(`Committed: ${_e.hash}`,"success"),U("");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to commit","error")}finally{T(!1)}}},[K,a,r]),qt=i.useCallback(async()=>{if(K.trim()){T(!0);try{const Y=R.filter(zt=>!zt.staged).map(zt=>zt.file);Y.length>0&&await Km(Y,r);const _e=await Jm(K.trim(),r);a(`Committed: ${_e.hash}`,"success"),U("");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),k(null),Q(null),D(null)}catch(Y){a(Se(Y)||"Failed to commit","error")}finally{T(!1)}}},[K,R,a,r]),Qt=i.useCallback(async(Y,_e)=>{k({file:Y,staged:_e}),O(!0),D(null);const ut=X.current+1;X.current=ut;try{const At=await iS(Y,_e,r);if(X.current!==ut)return;Q(At)}catch(At){if(X.current!==ut)return;const zt=Se(At)||"Failed to load file diff";Q(null),D(zt),a(zt,"error")}finally{X.current===ut&&O(!1)}},[a,r]),hn=i.useCallback(Y=>{_(_e=>{const ut=new Set(_e);return ut.has(Y)?ut.delete(Y):ut.add(Y),ut})},[]),Zt=i.useCallback(async Y=>{if(He===Y){ye(null),ne(null);return}ye(Y),Z(!0);try{const _e=await Jl(Y,r);ne(_e)}catch(_e){a(Se(_e)||"Failed to load diff","error"),ne(null)}finally{Z(!1)}},[He,a,r]),ve=i.useCallback(()=>{q(Y=>Math.min(Y+20,100))},[]),Pe=i.useMemo(()=>{if(!L.trim())return le;const Y=L.toLowerCase();return le.filter(_e=>_e.message.toLowerCase().includes(Y)||_e.author.toLowerCase().includes(Y)||_e.shortHash.toLowerCase().includes(Y))},[le,L]),Ke=i.useCallback(async Y=>{if(Y.preventDefault(),!!pe.trim()){v(!0);try{await JN(pe.trim(),ae.trim()||void 0,r),a(`Created branch ${pe}`,"success"),ze(""),Ve("");const _e=await Xr(r);B(_e)}catch(_e){a(Se(_e)||"Failed to create branch","error")}finally{v(!1)}}},[pe,ae,a,r]),at=i.useCallback(async Y=>{v(!0);try{await YN(Y,r),a(`Switched to ${Y}`,"success");const[_e,ut]=await Promise.all([ji(r),Xr(r)]);N(_e),B(ut)}catch(_e){a(Se(_e)||"Failed to checkout branch","error")}finally{v(!1)}},[a,r]),We=i.useCallback(async Y=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${Y}"?`,danger:!0})){v(!0);try{await Gm(Y,void 0,r),a(`Deleted branch ${Y}`,"success");const ut=await Xr(r);B(ut)}catch(ut){if(Se(ut).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Gm(Y,!0,r),a(`Force deleted branch ${Y}`,"success");const zt=await Xr(r);B(zt)}catch(zt){a(Se(zt)||"Failed to delete branch","error")}}else a(Se(ut)||"Failed to delete branch","error")}finally{v(!1)}}},[a,r,o]),It=i.useMemo(()=>{if(!Te.trim())return he;const Y=Te.toLowerCase();return he.filter(_e=>_e.name.toLowerCase().includes(Y))},[he,Te]),Lt=i.useCallback(async Y=>{if(Be===Y){ce(null),Le([]),oe(null),ft(null);return}ce(Y),Le([]),oe(null),ft(null),Ue(!0);try{const _e=await GN(Y,10,r);Le(_e)}catch{Le([])}finally{Ue(!1)}},[Be,r]),Bt=i.useCallback(async Y=>{if(ue===Y){oe(null),ft(null);return}oe(Y),ft(null),tt(!0);try{const _e=await Jl(Y,r);ft(_e)}catch{ft(null)}finally{tt(!1)}},[ue,r]),Gt=i.useCallback(()=>{ce(null),Le([]),oe(null),ft(null)},[]),bt=i.useCallback(()=>{yt.current+=1,Ze(null),gt(null),st(null),Ie(!1)},[]),Ot=i.useCallback(async Y=>{Y.preventDefault(),J("create"),bt();try{await eS(wt.trim()||void 0,r),a("Changes stashed","success"),St("");const _e=await al(r);dt(_e)}catch(_e){a(Se(_e)||"Failed to stash changes","error")}finally{J(null)}},[wt,a,r,bt]),en=i.useCallback(async(Y,_e=!1)=>{J(`apply-${Y}`),bt();try{await tS(Y,_e,r),a(_e?"Stash popped":"Stash applied","success");const ut=await al(r);dt(ut)}catch(ut){a(Se(ut)||"Failed to apply stash","error")}finally{J(null)}},[a,r,bt]),Kt=i.useCallback(async Y=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${Y}}? This cannot be undone.`,danger:!0})){J(`drop-${Y}`),bt();try{await nS(Y,r),a("Stash dropped","success");const ut=await al(r);dt(ut)}catch(ut){a(Se(ut)||"Failed to drop stash","error")}finally{J(null)}}},[a,r,o,bt]),Sn=i.useCallback(async Y=>{if(me===Y){bt();return}const _e=yt.current+1;yt.current=_e,Ze(Y),gt(null),st(null),Ie(!0);try{const ut=await sS(Y,r);if(yt.current!==_e)return;gt(ut)}catch(ut){if(yt.current!==_e)return;gt(null),st(Se(ut)||"Failed to load stash diff")}finally{yt.current===_e&&Ie(!1)}},[me,r,bt]),dn=i.useCallback(async()=>{vt("fetch");try{const Y=await QN(void 0,r);Dt(Y),a(Y.message||"Fetch completed",Y.fetched?"success":"info");const _e=await ji(r);N(_e)}catch(Y){a(Se(Y)||"Fetch failed","error")}finally{vt(null)}},[a,r]),Jt=i.useCallback(async Y=>{vt("pull");try{const _e=await XN(Y,r);if(Dt(_e),_e.conflict)a("Merge conflict detected. Resolve manually.","error");else{const At=Y?.rebase?"Pull --rebase completed":"Pull completed";a(_e.message||At,"success")}const ut=await ji(r);N(ut)}catch(_e){a(Se(_e)||"Pull failed","error")}finally{vt(null)}},[a,r]),tn=i.useCallback(async()=>{vt("push");try{const Y=await ZN(r);Dt(Y),a(Y.message||"Push completed","success");const _e=await ji(r);N(_e)}catch(Y){a(Se(Y)||"Push failed","error")}finally{vt(null)}},[a,r]),Ne=i.useMemo(()=>R.filter(Y=>Y.staged),[R]),W=i.useMemo(()=>R.filter(Y=>!Y.staged),[R]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...j,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:S,style:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(iu,{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:nn,disabled:w,title:"Refresh",children:t.jsx(ps,{size:14,className:w?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(mn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:ho.map(Y=>{const _e=Y.icon;return t.jsxs("button",{role:"tab","aria-selected":p===Y.id,className:`gm-nav-item${p===Y.id?" active":""}`,onClick:()=>g(Y.id),children:[t.jsx(_e,{size:16}),t.jsx("span",{className:"gm-nav-label",children:Y.label})]},Y.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[w&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!w&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Vs,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:nn,children:"Retry"})]}),p==="status"&&!w&&x&&t.jsx(xL,{status:x,copyToClipboard:C}),p==="changes"&&!w&&t.jsx(vL,{status:x,stagedFiles:Ne,unstagedFiles:W,selectedFiles:E,toggleFileSelection:hn,onStageFiles:on,onUnstageFiles:sn,onDiscardChanges:ln,onSelectDiffFile:Qt,selectedDiffTarget:$,changeDiff:H,loadingChangeDiff:se,changeDiffError:M,commitMessage:K,setCommitMessage:U,onCommit:xn,onStageAllAndCommit:qt,committing:A}),p==="commits"&&!w&&t.jsx(yL,{commits:Pe,commitSearch:L,setCommitSearch:xe,selectedCommit:He,commitDiff:je,loadingDiff:fe,onCommitClick:Zt,onLoadMore:ve,canLoadMore:le.length>=re&&re<100,copyToClipboard:C}),p==="branches"&&!w&&t.jsx(wL,{branches:It,branchSearch:Te,setBranchSearch:rt,newBranchName:pe,setNewBranchName:ze,branchBase:ae,setBranchBase:Ve,onCreateBranch:Ke,onCheckoutBranch:at,onDeleteBranch:We,loading:w,allBranches:he,selectedBranch:Be,branchCommits:Re,loadingBranchCommits:ct,expandedBranchCommit:ue,branchCommitDiff:Ee,loadingBranchCommitDiff:ht,onSelectBranch:Lt,onBranchCommitClick:Bt,onCloseBranchDetails:Gt}),p==="worktrees"&&!w&&t.jsx(kL,{worktrees:xt}),p==="stashes"&&!w&&t.jsx(jL,{stashes:Ye,stashMessage:wt,setStashMessage:St,onCreateStash:Ot,onApplyStash:en,onDropStash:Kt,onToggleStashDiff:Sn,stashLoading:Fe,expandedStashIndex:me,stashDiff:be,loadingStashDiff:$t,stashDiffError:ge}),p==="remotes"&&!w&&t.jsx(NL,{status:x,remoteLoading:pt,lastRemoteResult:Ut,onFetch:dn,onPull:Jt,onPush:tn,addToast:a,projectId:r,copyToClipboard:C})]})]})]})}):null}function xL({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(ba,{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(Vs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Xn,{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(La,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Bo,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Xn,{size:12}),"Up to date"]})]})]})]})]})}function vL({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:w,onStageAllAndCommit:v,committing:b}){const y=s.filter(j=>a.has(`unstaged:${j.file}`)),S=n.filter(j=>a.has(`staged:${j.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Os,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(j=>j.file)),title:"Stage selected",children:[t.jsx($n,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(j=>j.file)),title:"Discard selected",children:t.jsx(Ho,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-unstaged","data-testid":"gm-file-list-unstaged",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(j=>{const C=u?.file===j.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>d(j.file,!1),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:x=>x.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(ig,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(ag,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:x=>{x.stopPropagation(),o([j.file])},title:"Stage file",children:t.jsx($n,{size:12})})]},`unstaged:${j.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-staged","data-testid":"gm-file-list-staged",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(j=>{const C=u?.file===j.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>d(j.file,!0),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:x=>x.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(ig,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(ag,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:x=>{x.stopPropagation(),l([j.file])},title:"Unstage file",children:t.jsx(mn,{size:12})})]},`staged:${j.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(su,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(su,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:w,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>g(j.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Da,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function yL({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:a,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:d,copyToClipboard:u}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Xi,{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:Tr(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>u(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(ba,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[m.body&&t.jsx("div",{className:"gm-commit-message-full",children:m.body}),r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function wL({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:w,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:j}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Xi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:C=>s(C.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:C=>r(C.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(C=>t.jsx("option",{value:C.name,children:C.name},C.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx($n,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(C=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${C.isCurrent?" current":""}${f===C.name?" selected":""}`,onClick:()=>y(C.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[C.isCurrent&&t.jsx(ks,{size:14,className:"gm-current-icon"}),C.name]}),C.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",C.remote]}),C.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Tr(C.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!C.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:x=>{x.stopPropagation(),d(C.name)},disabled:m,title:"Checkout",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:x=>{x.stopPropagation(),u(C.name)},disabled:m,title:"Delete",children:t.jsx(Tn,{size:14})})]})})]}),f===C.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(Nr,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:t.jsx(mn,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(x=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(x.hash),"data-testid":`branch-commit-${x.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:x.shortHash}),t.jsx("span",{className:"gm-commit-message",title:x.message,children:x.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:x.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(x.date)}),x.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),w===x.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[(x.body||x.message)&&t.jsx("div",{className:"gm-commit-message-full",children:x.body||x.message}),v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},x.hash))})]})]},C.name))})]})}function kL({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:Ju(n.path)||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 jL({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:c,expandedStashIndex:d,stashDiff:u,loadingStashDiff:m,stashDiffError:h}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:a,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:f=>s(f.target.value),disabled:c!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:c!==null,children:[c==="create"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(zo,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(f=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-header",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${f.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:f.message}),t.jsxs("div",{className:"gm-stash-meta",children:[f.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Os,{size:12}),f.branch]}),t.jsx("span",{children:Tr(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:c!==null,children:d===f.index?"Hide":"View"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:c!==null,title:"Apply stash (keep)",children:c===`apply-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:c!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:c!==null,title:"Drop stash",children:c===`drop-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Tn,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:m?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading stash diff…"]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):u?t.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&t.jsx("pre",{className:"gm-diff-stat",children:u.stat}),t.jsx("pre",{className:"gm-diff-patch",children:u.patch})]}):null})]},f.index))})]})}function NL({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=oe=>{try{return new URL(oe).hostname}catch{return oe.replace(/^git@/,"").split(":")[0]||oe}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,w]=i.useState(null),[v,b]=i.useState(""),[y,S]=i.useState(""),[j,C]=i.useState(null),[x,N]=i.useState(""),[R,F]=i.useState(""),[E,_]=i.useState(!1),[K,U]=i.useState(!1),A=i.useRef(null),[T,H]=i.useState([]),[Q,se]=i.useState(!1),[O,M]=i.useState(null),[D,$]=i.useState([]),[k,X]=i.useState(!1),[le,ke]=i.useState(null),He=i.useRef(0),ye=m.find(oe=>oe.name===O);i.useEffect(()=>{(n!==null||f)&&U(!1)},[n,f]),i.useEffect(()=>{if(!K)return;const oe=ft=>{A.current?.contains(ft.target)||U(!1)},Ee=ft=>{ft.key==="Escape"&&U(!1)};return document.addEventListener("mousedown",oe),document.addEventListener("keydown",Ee),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",Ee)}},[K]);const[je,ne]=i.useState(null),[fe,Z]=i.useState(null),[re,q]=i.useState(!1),[L,xe]=i.useState(null),[he,B]=i.useState(null),[pe,ze]=i.useState(!1);i.useEffect(()=>{ae()},[]),i.useEffect(()=>{e&&e.ahead>0?Ve():e&&e.ahead===0&&H([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!O&&M(m[0].name)},[m]),i.useEffect(()=>{O?Te(O):($([]),ke(null))},[O]),i.useEffect(()=>{!O||!s||Te(O)},[O,s]),i.useEffect(()=>{O&&!m.find(oe=>oe.name===O)&&M(m.length>0?m[0].name:null)},[m,O]);const ae=async()=>{p(!0);try{const oe=await $N(c);h(oe)}catch(oe){l(Se(oe)||"Failed to load remotes","error")}finally{p(!1)}},Ve=async()=>{se(!0);try{const oe=await VN(c);H(oe)}catch{H([])}finally{se(!1)}},Te=async oe=>{const Ee=He.current+1;He.current=Ee,X(!0),ke(null);try{const ft=await WN(oe,void 0,10,c);if(He.current!==Ee)return;$(ft)}catch(ft){if(He.current!==Ee)return;ke(Se(ft)||"Failed to load remote commits"),$([])}finally{He.current===Ee&&X(!1)}},rt=li(),Be=async oe=>{if(oe.preventDefault(),!(!v.trim()||!y.trim())){w("add");try{await DN(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),_(!1),await ae()}catch(Ee){l(Se(Ee)||"Failed to add remote","error")}finally{w(null)}}},ce=async oe=>{if(await rt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${oe}'?`,danger:!0})){w(`remove-${oe}`);try{await LN(oe,c),l(`Remote '${oe}' removed`,"success"),await ae()}catch(ft){l(Se(ft)||"Failed to remove remote","error")}finally{w(null)}}},Re=async oe=>{if(R.trim()){w(`rename-${oe}`);try{await ON(oe,R.trim(),c),l(`Remote renamed to '${R.trim()}'`,"success"),C(null),F(""),await ae()}catch(Ee){l(Se(Ee)||"Failed to rename remote","error")}finally{w(null)}}},Le=async oe=>{if(x.trim()){w(`url-${oe}`);try{await FN(oe,x.trim(),c),l("Remote URL updated","success"),C(null),N(""),await ae()}catch(Ee){l(Se(Ee)||"Failed to update remote URL","error")}finally{w(null)}}},ct=i.useCallback(async(oe,Ee)=>{if(Ee==="ahead"){if(je===oe){ne(null),Z(null);return}ne(oe),Z(null),q(!0);try{const ft=await Jl(oe);Z(ft)}catch{Z(null)}finally{q(!1)}}else{if(L===oe){xe(null),B(null);return}xe(oe),B(null),ze(!0);try{const ft=await Jl(oe);B(ft)}catch{B(null)}finally{ze(!1)}}},[je,L]),Ue=oe=>{C(`url-${oe.name}`),N(oe.pushUrl||oe.fetchUrl)},ue=oe=>{C(`name-${oe.name}`),F(oe.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:()=>_(!E),disabled:g!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(mn,{size:14}):t.jsx($n,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Be,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:oe=>b(oe.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:oe=>S(oe.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(jt,{size:12,className:"spin"}):t.jsx($n,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(oe=>t.jsxs("div",{className:`gm-remote-selector-item${O===oe.name?" selected":""}`,onClick:()=>M(oe.name),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),M(oe.name))},children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[t.jsx("span",{className:"gm-remote-selector-name-text",children:oe.name}),oe.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:oe.fetchUrl,children:u(oe.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:Ee=>{Ee.stopPropagation(),ce(oe.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(Tn,{size:14})})]},oe.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[O&&ye?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:O}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx("span",{className:"status-dot status-dot--online","aria-hidden":"true"}),t.jsx(La,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx("span",{className:"status-dot status-dot--pending","aria-hidden":"true"}),t.jsx(Bo,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:a,disabled:n!==null||f,children:[n==="fetch"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:A,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{U(!1),r({rebase:!1})},disabled:n!==null||f,children:[n==="pull"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ii,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>U(oe=>!oe),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":K,children:t.jsx(gn,{size:14})}),K?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":"Pull options menu",children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!1})},children:"Pull"}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!0})},children:"Pull --rebase"})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(La,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:x,onChange:oe=>N(oe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Le(O),disabled:g===`url-${O}`,children:g===`url-${O}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ks,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),N("")},title:"Cancel",children:t.jsx(mn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:ye.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:ye.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ye.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(ba,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ue(ye),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Hs,{size:14})})]})]})]}),ye.pushUrl&&ye.pushUrl!==ye.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:ye.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:ye.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ye.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(ba,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:R,onChange:oe=>F(oe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Re(O),disabled:g===`rename-${O}`,children:g===`rename-${O}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ks,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),F("")},title:"Cancel",children:t.jsx(mn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ue(ye),disabled:g!==null,title:"Edit remote name",children:t.jsx(Hs,{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(La,{size:14}),"Commits to Push (",e.ahead,")"]})}),Q?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading..."]}):T.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:T.map(oe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ct(oe.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),ct(oe.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:oe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:oe.message,children:oe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:oe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(oe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:je===oe.hash?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})})]}),je===oe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:re?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):fe?t.jsxs(t.Fragment,{children:[(oe.body||oe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:oe.body||oe.message}),fe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:fe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:fe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},oe.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(rb,{size:14}),"Recent commits on ",O]})}),k?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading commits..."]}):le?t.jsxs("div",{className:"gm-error",children:[t.jsx(Vs,{size:14}),le]}):D.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",O,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:D.map(oe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ct(oe.hash,"remote"),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),ct(oe.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:oe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:oe.message,children:oe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:oe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(oe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:L===oe.hash?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})})]}),L===oe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:pe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):he?t.jsxs(t.Fragment,{children:[(oe.body||oe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:oe.body||oe.message}),he.stat&&t.jsx("pre",{className:"gm-diff-stat",children:he.stat}),t.jsx("pre",{className:"gm-diff-patch",children:he.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},oe.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 pr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function SL(e,n){return e&&n?`${e}/${n}`:""}function CL(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 rg(e){switch(e){case"file-text":return xa;case"check-circle":return Xn;case"shield":return Gk;case"zap":return ls;case"eye":return Fr;case"globe":return gc;case"layout-grid":return va;case"puzzle":return Rk;default:return Xn}}function og(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 EL({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState({}),[m,h]=i.useState(!0),[f,p]=i.useState(!0),[g,w]=i.useState("my-steps"),[v,b]=i.useState(null),[y,S]=i.useState(!1),[j,C]=i.useState(!1),[x,N]=i.useState(pr),[R,F]=i.useState(!1),[E,_]=i.useState(!1),[K,U]=i.useState(null),[A,T]=i.useState(null),[H,Q]=i.useState({}),[se,O]=i.useState([]),M=i.useRef(null);zi(M,e,"fusion:workflow-steps-modal-size");const D=i.useCallback(async()=>{try{h(!0);const L=await Ko(a);o(L)}catch(L){s(Se(L)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),$=i.useCallback(async()=>{try{const L=await $o(a);Q(L||{})}catch{}},[a]),k=i.useCallback(async()=>{try{const L=await Ws();O(L.models||[])}catch{}},[]),X=i.useCallback(async()=>{try{p(!0);const[L,xe]=await Promise.all([VS(),WS()]);c(L.templates);const he=Object.fromEntries(xe.templates.map(({pluginId:B,template:pe})=>[pe.id,B]));u(he)}catch(L){s(Se(L)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(D(),X(),$(),k())},[e,D,X,$,k]);const le=i.useCallback(()=>{C(!0),S(!1),b(null),N(pr)},[]),ke=i.useCallback(()=>{C(!1),S(!0),b(null),N(pr)},[]),He=i.useCallback(L=>{b(L.id),S(!1),N({name:L.name,description:L.description,mode:L.mode||"prompt",phase:L.phase||"pre-merge",prompt:L.prompt,scriptName:L.scriptName||"",enabled:L.enabled,defaultOn:L.defaultOn||!1,modelProvider:L.modelProvider||"",modelId:L.modelId||""})},[]),ye=i.useCallback(()=>{b(null),S(!1),C(!1),N(pr)},[]),je=i.useCallback(async()=>{if(!x.name.trim()||!x.description.trim()){s("Name and description are required","error");return}F(!0);try{const L=x.mode==="prompt"&&x.modelProvider&&x.modelId?{modelProvider:x.modelProvider,modelId:x.modelId}:x.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(y){const xe={name:x.name.trim(),description:x.description.trim(),mode:x.mode,phase:x.phase,prompt:x.mode==="prompt"&&x.prompt.trim()||void 0,scriptName:x.mode==="script"?x.scriptName.trim():void 0,enabled:x.enabled,defaultOn:x.defaultOn||void 0,...L};await th(xe,a),s("Workflow step created","success")}else v&&(await US(v,{name:x.name.trim(),description:x.description.trim(),mode:x.mode,phase:x.phase,prompt:x.mode==="prompt"?x.prompt:"",scriptName:x.mode==="script"?x.scriptName.trim():void 0,enabled:x.enabled,defaultOn:x.defaultOn,...L},a),s("Workflow step updated","success"));S(!1),b(null),N(pr),await D()}catch(L){s(Se(L)||"Failed to save workflow step","error")}finally{F(!1)}},[x,y,v,s,D]),ne=i.useCallback(async L=>{try{await HS(L,a),s("Workflow step deleted","success"),U(null),v===L&&(b(null),N(pr)),await D()}catch(xe){s(Se(xe)||"Failed to delete workflow step","error")}},[v,s,D]),fe=i.useCallback(async()=>{if(!(!v&&!y)&&x.mode==="prompt"){if(y){if(!x.name.trim()||!x.description.trim()){s("Name and description are required before refining","error");return}F(!0);try{const L=x.modelProvider&&x.modelId?{modelProvider:x.modelProvider,modelId:x.modelId}:{},xe={name:x.name.trim(),description:x.description.trim(),mode:"prompt",prompt:x.prompt.trim()||void 0,enabled:x.enabled,defaultOn:x.defaultOn||void 0,...L},he=await th(xe,a);S(!1),b(he.id),_(!0);const B=await nh(he.id,a);N(pe=>({...pe,prompt:B.prompt})),s("Prompt refined with AI","success"),await D()}catch(L){s(Se(L)||"Failed to refine prompt","error")}finally{F(!1),_(!1)}return}if(v){_(!0);try{const L=await nh(v,a);N(xe=>({...xe,prompt:L.prompt})),s("Prompt refined with AI","success"),await D()}catch(L){s(Se(L)||"Failed to refine prompt","error")}finally{_(!1)}}}},[v,y,x,s,D]),Z=i.useCallback(async L=>{T(L.id);try{await GS(L.id,a),s(`Added ${L.name} workflow step`,"success"),await D(),w("my-steps"),C(!1)}catch(xe){const he=Se(xe);he?.includes("already exists")?s(`A workflow step named '${L.name}' already exists`,"error"):s(he||"Failed to add workflow step from template","error")}finally{T(null)}},[s,D]),re=sa(n);if(!e)return null;const q=y||v!==null;return t.jsx("div",{className:"modal-overlay open",...re,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:M,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:m?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!q&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>w("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Dy,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>w("templates"),"data-testid":"tab-templates",children:[t.jsx(va,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!q&&!j&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(L=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${L.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:L.name}),t.jsx("span",{className:`wfm-badge ${L.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:L.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(L.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(L.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(L.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(L.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),L.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:L.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>He(L),title:"Edit","aria-label":`Edit ${L.name}`,children:t.jsx(Hs,{size:14})}),K===L.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>ne(L.id),title:"Confirm delete","aria-label":`Confirm delete ${L.name}`,children:t.jsx(ks,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>U(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(mn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>U(L.id),title:"Delete","aria-label":`Delete ${L.name}`,children:t.jsx(Tn,{size:14})})]})]})},L.id))})]}),g==="templates"&&!q&&!j&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(L=>{const xe=rg(L.icon),he=og(L.category),B=A===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(xe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:he,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Z(L),disabled:B,"data-testid":`add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{size:12}),"Add"]})})]})]})},L.id)})})}),j&&!q&&t.jsxs("div",{className:"wfm-create-chooser","data-testid":"workflow-step-create-chooser",children:[t.jsx("h3",{className:"wfm-form-title",children:"How would you like to create this workflow step?"}),t.jsx("p",{className:"wfm-create-chooser-hint",children:"Start from a built-in template or create a fully custom workflow step."}),t.jsxs("button",{className:"btn wfm-create-custom-btn",onClick:ke,"data-testid":"create-custom-step",children:[t.jsx($n,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading built-in templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"create-chooser-no-templates",children:"No built-in templates are available right now. You can still create a custom step."}):t.jsx("div",{className:"wfm-template-list","data-testid":"create-chooser-templates",children:l.map(L=>{const xe=rg(L.icon),he=og(L.category),B=A===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(xe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:he,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Z(L),disabled:B,"data-testid":`chooser-add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{size:12}),"Add template"]})})]})]})},L.id)})})]}),q&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:y?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:x.name,onChange:L=>N(xe=>({...xe,name:L.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:x.description,onChange:L=>N(xe=>({...xe,description:L.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${x.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Zi,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${x.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(ea,{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 ${x.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${x.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:x.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),x.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:fe,disabled:!x.description.trim()||E,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[E?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ms,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:x.prompt,onChange:L=>N(xe=>({...xe,prompt:L.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),x.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"}),x.modelProvider&&x.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>N(L=>({...L,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(mn,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:x.modelProvider&&x.modelId?`Using ${x.modelProvider}/${x.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(_s,{models:se,value:SL(x.modelProvider,x.modelId),onChange:L=>{const xe=CL(L);N(he=>({...he,modelProvider:xe.provider,modelId:xe.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),x.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(H).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:x.scriptName,onChange:L=>N(xe=>({...xe,scriptName:L.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(H).map(([L,xe])=>t.jsxs("option",{value:L,children:[L," (",xe,")"]},L))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:x.enabled,onChange:L=>N(xe=>({...xe,enabled:L.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:x.defaultOn,onChange:L=>N(xe=>({...xe,defaultOn:L.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:ye,disabled:R,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:je,disabled:R||!x.name.trim()||!x.description.trim()||x.mode==="script"&&!x.scriptName.trim(),"data-testid":"save-workflow-step",children:R?"Saving...":y?"Create":"Save"})]})]})]})]})}),!q&&!j&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:le,"data-testid":"add-workflow-step",children:[t.jsx($n,{size:14}),"Add Workflow Step"]})})]})})}const _L=36e5,ML=3e5,Gd=[{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 AL(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 RL(e){return typeof e!="number"||!Number.isFinite(e)?_L:Math.max(ML,Math.round(e))}function $8(e){if(Gd.some(s=>s.value===e))return[...Gd];const n={value:e,label:`${AL(e)} (custom)`};return[...Gd,n].sort((s,a)=>s.value-a.value)}const IL=4,TL=5*6e4;function PL(e){const n=RL(e?.heartbeatIntervalMs);return Math.max(n*IL,TL)}function lg(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),a=n%60;return s>0&&a>0?`${s}h ${a}m`:s>0?`${s}h`:`${a}m`}function $L(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 DL(e){const s=e.metadata?.heartbeatTimerRepair;if(!s||typeof s!="object")return{};const a=s;return{repairedAt:typeof a.repairedAt=="string"?a.repairedAt:void 0,staleAtRepair:typeof a.staleAtRepair=="boolean"?a.staleAtRepair:void 0,staleRepairReason:typeof a.staleRepairReason=="string"?a.staleRepairReason:void 0}}function LL(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=$L(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Ci,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Js,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(Ci,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Qn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=DL(e);if(d.staleAtRepair&&d.repairedAt){const f=Date.parse(d.repairedAt),p=Date.parse(s);if(Number.isFinite(f)&&Number.isFinite(p)&&p<f)return{label:"Unresponsive",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:d.staleRepairReason??"Heartbeat scheduler repaired a missing timer; waiting for recovery heartbeat"}}const u=new Date(s).getTime(),m=Date.now()-u,h=PL(o);if(m>h){const f=`No heartbeat for ${lg(m)} (threshold: ${lg(h)})`;return{label:"Unresponsive",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:f}}return{label:"Healthy",icon:t.jsx(qw,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function cc({agent:e,size:n=36,className:s}){const[a,r]=i.useState(!1);i.useEffect(()=>{r(!1)},[e.imageUrl]);const o=i.useMemo(()=>{if(!e.imageUrl)return;const l=encodeURIComponent(e.updatedAt??""),c=e.imageUrl.includes("?")?"&":"?";return`${e.imageUrl}${c}t=${l}`},[e.imageUrl,e.updatedAt]);return t.jsx("span",{className:`agent-avatar${s?` ${s}`:""}`,style:{width:`${n}px`,height:`${n}px`},"aria-label":`${e.name} avatar`,children:o&&!a?t.jsx("img",{src:o,alt:`${e.name} avatar`,onError:()=>r(!0)}):e.icon?.trim()?t.jsx("span",{className:"agent-avatar-emoji",style:{fontSize:`calc(${n}px * 0.58)`},"aria-hidden":"true",children:e.icon}):t.jsx(Qn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const OL="https://github.com/Runfusion/Fusion/issues/new";function FL(e,n){const s=`[Agent Error] ${n.surface}${n.agentName?` - ${n.agentName}`:""}`,a=["## Agent Error Report","",`- Surface: ${n.surface}`,`- Agent ID: ${n.agentId??"unknown"}`,`- Agent Name: ${n.agentName??"unknown"}`,`- Agent State: ${n.agentState??"unknown"}`,`- Run ID: ${n.runId??"n/a"}`,`- Task ID: ${n.taskId??"n/a"}`,`- Timestamp: ${n.timestamp??new Date().toISOString()}`,"","## Error","```text",e,"```"],r=new URLSearchParams({title:s,body:a.join(`
690
+ `).length:0,[e,g]),b=i.useCallback(()=>{d(!1)},[]),y=i.useCallback(()=>{d(!0)},[]),S=i.useCallback(()=>{m(C=>!C)},[]),j=i.useCallback(C=>{h.current&&(h.current.scrollTop=C.currentTarget.scrollTop)},[]);return t.jsxs("div",{className:"file-editor-container",children:[f?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 ${p?"":"btn-primary"}`,onClick:b,disabled:!p,"aria-label":"Edit mode",children:[t.jsx(tb,{size:14}),"Edit"]}),t.jsxs("button",{className:`btn btn-sm ${p?"btn-primary":""}`,onClick:y,disabled:p,"aria-label":"Preview mode",children:[t.jsx(Fr,{size:14}),"Preview"]})]}),!s&&t.jsxs("div",{className:"file-editor-toolbar-actions",children:[w&&t.jsxs("button",{className:`btn btn-sm file-editor-line-numbers-button ${r?"btn-primary":""}`,onClick:o,"aria-label":"Toggle line numbers","aria-pressed":r,title:"Toggle line numbers",children:[t.jsx($m,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:S,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Vl,{size:14})})]})]}):!s&&t.jsxs("div",{className:"file-editor-toolbar",children:[t.jsx("div",{className:"file-editor-mode-toggle"}),t.jsxs("div",{className:"file-editor-toolbar-actions",children:[w&&t.jsxs("button",{className:`btn btn-sm file-editor-line-numbers-button ${r?"btn-primary":""}`,onClick:o,"aria-label":"Toggle line numbers","aria-pressed":r,title:"Toggle line numbers",children:[t.jsx($m,{size:14}),t.jsx("span",{children:"Line #"})]}),t.jsx("button",{className:`btn btn-sm ${u?"btn-primary":""}`,onClick:S,"aria-label":"Toggle word wrap",title:"Toggle word wrap",children:t.jsx(Vl,{size:14})})]})]}),p?t.jsx("div",{className:"file-editor-preview markdown-body",children:t.jsx(xi,{remarkPlugins:[vi],children:e})}):t.jsxs("div",{className:`file-editor-textarea-shell ${g?"file-editor-textarea-shell--line-numbers":""}`,children:[g&&t.jsx("div",{className:"file-editor-line-numbers",ref:h,"aria-hidden":"true",children:Array.from({length:v},(C,x)=>t.jsx("div",{className:"file-editor-line-number",children:x+1},`line-${x+1}`))}),t.jsx("textarea",{className:`file-editor-textarea ${u?"file-editor-textarea--wrap":""}`,value:e,onChange:C=>n(C.target.value),onScroll:j,readOnly:s,spellCheck:!1,"aria-label":a?`Editor for ${a}`:"File editor"})]})]})}function gD(e,n=44){if(e)return e.length<=n?e:`${e.slice(0,n-1)}…`}function bD({currentWorkspace:e,projectName:n,workspaces:s,onSelect:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>e==="project"?n||"Project Root":s.find(d=>d.id===e)?.label??e,[e,n,s]);return t.jsxs("div",{className:"workspace-selector",children:[t.jsxs("button",{type:"button",className:"workspace-selector-trigger",onClick:()=>o(c=>!c),"aria-haspopup":"listbox","aria-expanded":r,children:[e==="project"?t.jsx(Pm,{size:14}):t.jsx(iu,{size:14}),t.jsx("span",{className:"workspace-selector-trigger-label",children:l}),t.jsx(gn,{size:14,className:`workspace-selector-trigger-icon${r?" open":""}`})]}),r&&t.jsxs("div",{className:"workspace-selector-menu",role:"listbox","aria-label":"Select workspace",children:[t.jsxs("button",{type:"button",className:`workspace-selector-option${e==="project"?" active":""}`,onClick:()=>{a("project"),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(Pm,{size:14}),t.jsx("span",{children:"Project Root"})]}),t.jsx("span",{className:"workspace-selector-option-meta",children:n})]}),s.length>0&&t.jsxs("div",{className:"workspace-selector-group",children:[t.jsx("div",{className:"workspace-selector-group-label",children:"Task Worktrees"}),s.map(c=>t.jsxs("button",{type:"button",className:`workspace-selector-option${e===c.id?" active":""}`,onClick:()=>{a(c.id),o(!1)},children:[t.jsxs("div",{className:"workspace-selector-option-main",children:[t.jsx(iu,{size:14}),t.jsx("span",{children:c.id})]}),c.title&&t.jsx("span",{className:"workspace-selector-option-meta",title:c.title,children:gD(c.title)})]},c.id))]})]})]})}const xD=768,vD=280,Rl=180,Il=500,Gf="fusion:file-browser-sidebar-width",Kf="kb-files-line-numbers",Mv=new Set([".png",".jpg",".jpeg",".gif",".webp",".ico",".bmp",".svgz"]),yD=new Set([...Mv,".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 Tl(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return yD.has(n)}function wD(e){const n=e.slice(e.lastIndexOf(".")).toLowerCase();return Mv.has(n)}function kD(e){const n=e.replace(/\\/g,"/").replace(/^\.\//,"").replace(/\/$/,""),s=n.lastIndexOf("/");return s>0?n.slice(0,s):"."}function jD({initialWorkspace:e="project",initialFile:n=null,onClose:s,onWorkspaceChange:a,projectId:r}){const{projectName:o,workspaces:l}=rD(r),c=i.useRef(null);zi(c,!0,"fusion:files-modal-size");const d=sa(s),[u,m]=i.useState(e),[h,f]=i.useState(null),[p,g]=i.useState(!1),[w,v]=i.useState("list"),[b,y]=i.useState(vD),[S,j]=i.useState(!1),{entries:C,currentPath:x,setPath:N,loading:R,error:F,refresh:E}=tD(u,!0,r),{content:_,setContent:K,originalContent:U,loading:A,saving:T,error:H,save:Q,hasChanges:se,mtime:O}=nD(u,h,!0,r);i.useEffect(()=>{m(e)},[e]),i.useEffect(()=>{const Z=()=>{g(window.innerWidth<=xD)};return Z(),window.addEventListener("resize",Z),()=>window.removeEventListener("resize",Z)},[]),i.useEffect(()=>{h||v("list")},[h]),i.useEffect(()=>{if(!n){f(null);return}f(n),N(kD(n)),p&&v("editor")},[n,p,N]),i.useEffect(()=>{try{const Z=localStorage.getItem(Gf);if(!Z)return;const re=Number.parseInt(Z,10);if(!Number.isNaN(re)){const q=Math.max(Rl,Math.min(Il,re));y(q)}}catch{}},[]),i.useEffect(()=>{const Z=Gn(Kf,r);j(Z==="true")},[r]),i.useEffect(()=>{const Z=re=>{re.key==="Escape"&&s(),(re.metaKey||re.ctrlKey)&&re.key==="s"&&(re.preventDefault(),se&&!T&&Q())};return document.addEventListener("keydown",Z),()=>document.removeEventListener("keydown",Z)},[s,se,T,Q]);const M=i.useCallback(Z=>{f(Z),p&&v("editor")},[p]),D=i.useCallback(()=>{v("list")},[]),$=i.useCallback(()=>{K(U)},[U,K]),k=i.useCallback(Z=>{m(Z),f(null),v("list"),a?.(Z)},[a]),X=i.useCallback(Z=>{try{localStorage.setItem(Gf,String(Z))}catch{}},[]),le=i.useCallback(Z=>{if(p)return;Z.preventDefault(),Z.stopPropagation();const re=Z.currentTarget;typeof re.setPointerCapture=="function"&&re.setPointerCapture(Z.pointerId);const q=Z.clientX,L=b;let xe=L;document.body.style.userSelect="none";const he=pe=>{const ze=pe.clientX-q,ae=Math.max(Rl,Math.min(Il,L+ze));xe=ae,y(ae)},B=pe=>{typeof re.releasePointerCapture=="function"&&re.releasePointerCapture(pe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",he),document.removeEventListener("pointerup",B),X(xe)};document.addEventListener("pointermove",he),document.addEventListener("pointerup",B)},[p,X,b]),ke=i.useCallback(Z=>{if(p)return;const re=20;if(Z.key!=="ArrowLeft"&&Z.key!=="ArrowRight")return;Z.preventDefault();const q=Z.key==="ArrowLeft"?-re:re,L=Math.max(Rl,Math.min(Il,b+q));y(L),X(L)},[p,X,b]),He=i.useCallback(()=>{j(Z=>{const re=!Z;return fs(Kf,String(re),r),re})},[r]),je=`Files — ${i.useMemo(()=>u==="project"?"Project":l.find(Z=>Z.id===u)?.id??u,[u,l])}`,ne=i.useMemo(()=>!h||!wD(h)?null:hb(u,h,r),[h,u,r]),fe=Z=>{const re=new Blob([Z]).size;return re<1024?`${re} B`:`${(re/1024).toFixed(1)} KB`};return t.jsx("div",{className:"modal-overlay open",...d,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal file-browser-modal",ref:c,children:[t.jsxs("div",{className:"modal-header file-browser-modal-header",children:[t.jsxs("div",{className:"file-browser-header-title",children:[t.jsx(js,{size:18}),t.jsx("span",{children:je}),h&&t.jsx("span",{className:"file-browser-header-path",children:h})]}),t.jsxs("div",{className:"file-browser-header-actions",children:[t.jsx(bD,{currentWorkspace:u,projectName:o,workspaces:l,onSelect:k}),t.jsx("button",{className:"modal-close",onClick:s,"aria-label":"Close",children:t.jsx(mn,{size:20})})]})]}),t.jsxs("div",{className:"file-browser-body",children:[t.jsx("div",{className:`file-browser-sidebar ${p?"mobile":""} ${w==="list"?"active":""}`,style:p?void 0:{width:`${b}px`},children:t.jsx(hD,{entries:C,currentPath:x,onSelectFile:M,onNavigate:N,loading:R,error:F,onRetry:E,workspace:u,onRefresh:E,projectId:r})}),!p&&t.jsx("div",{className:"file-browser-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":Rl,"aria-valuemax":Il,"aria-valuenow":b,"aria-label":"Resize sidebar",tabIndex:0,onPointerDown:le,onKeyDown:ke}),t.jsx("div",{className:`file-browser-content ${p?"mobile":""} ${w==="editor"?"active":""}`,children:h?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"file-browser-toolbar",children:[t.jsxs("div",{className:"file-browser-file-info",children:[p&&w==="editor"&&t.jsxs("button",{className:"file-browser-back-button",onClick:D,"aria-label":"Back to file list",children:[t.jsx(Ga,{size:16}),t.jsx("span",{children:"Back"})]}),h,Tl(h)&&t.jsxs("span",{className:"file-browser-binary-indicator",children:[t.jsx(Cw,{size:12}),"Binary file — read only"]}),O&&t.jsxs("span",{className:"file-browser-mtime",children:["Modified: ",new Date(O).toLocaleString()]}),A&&t.jsx("span",{className:"file-browser-loading",children:"Loading..."})]}),t.jsx("div",{className:"file-browser-actions",children:!ne&&se&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm",onClick:$,disabled:T,children:[t.jsx(Dk,{size:14}),"Discard"]}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>void Q(),disabled:T,children:[t.jsx(ob,{size:14}),T?"Saving...":"Save"]})]})})]}),H&&!ne&&t.jsx("div",{className:"file-browser-error-banner",children:H}),ne?t.jsx("div",{className:"file-browser-image-preview",children:t.jsx("img",{src:ne,alt:h??"",className:"file-browser-image"})}):t.jsx("div",{className:"file-editor-wrapper",children:t.jsx(fD,{content:_,onChange:K,filePath:h,readOnly:Tl(h),showLineNumbers:S&&!Tl(h),onToggleLineNumbers:He,canToggleLineNumbers:!Tl(h)})}),!ne&&t.jsxs("div",{className:"file-browser-footer",children:[t.jsx("span",{children:fe(_)}),se&&t.jsx("span",{className:"file-browser-unsaved",children:"Unsaved changes"})]})]}):t.jsxs("div",{className:"file-browser-placeholder",children:[t.jsx(js,{size:48,opacity:.3}),t.jsx("p",{children:"Select a file to edit"})]})})]})]})})}const ND=i.lazy(()=>En(()=>import("./TodoView-CDtkPdrq.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));function SD({onClose:e,projectId:n,addToast:s,onPlanningMode:a}){const r=sa(e),l=oi()==="mobile",{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=aa({enabled:l});Mi(l);const h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{};return i.useEffect(()=>{const f=p=>{p.key==="Escape"&&e()};return document.addEventListener("keydown",f),()=>document.removeEventListener("keydown",f)},[e]),t.jsx("div",{className:"modal-overlay open",...r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal todo-modal",style:h,children:[t.jsxs("div",{className:"modal-header todo-modal-header",children:[t.jsxs("div",{className:"todo-modal-header-title",children:[t.jsx(tk,{size:18}),t.jsxs("div",{children:[t.jsx("h2",{children:"Todos"}),t.jsx("p",{children:"Manage reusable todo lists for your project."})]})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(mn,{size:20})})]}),t.jsx("div",{className:"todo-modal-body",children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(ND,{projectId:n,addToast:s,onPlanningMode:a,onClose:e,mobileKeyboardActive:l&&m})})})]})})}function CD(e={}){const{pollInterval:n=3e4,autoRefresh:s=!0}=e,[a,r]=i.useState({providers:[],loading:!0,error:null,lastUpdated:null}),o=i.useRef(null),l=i.useRef(null),c=i.useCallback(async(u=!1)=>{l.current&&l.current.abort(),l.current=new AbortController,u&&r(m=>({...m,loading:!0,error:null}));try{const{providers:m}=await dN();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:Se(m)||"Failed to fetch usage data"}))}},[]);i.useEffect(()=>{c()},[c]),i.useEffect(()=>{if(s)return o.current=setInterval(()=>{c(!1)},n),()=>{o.current&&(clearInterval(o.current),o.current=null)}},[s,n,c]),i.useEffect(()=>()=>{l.current&&l.current.abort(),o.current&&clearInterval(o.current)},[]);const d=i.useCallback(()=>c(!0),[c]);return{providers:a.providers,loading:a.loading,error:a.error,lastUpdated:a.lastUpdated,refresh:d}}function ED(e){const n=new Date(e),s=new Date,a=n.toLocaleTimeString(void 0,{hour:"numeric",minute:"2-digit",hour12:!0});if(n.toDateString()===s.toDateString())return a;const o=new Date(s.getFullYear(),s.getMonth(),s.getDate()),l=new Date(n.getFullYear(),n.getMonth(),n.getDate()),c=Math.round((l.getTime()-o.getTime())/(1440*60*1e3));return c>=1&&c<=7?`${n.toLocaleDateString(void 0,{weekday:"short"})} ${a}`:`${n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}, ${a}`}function _D(e){return e>90?"usage-progress-fill--high":e>70?"usage-progress-fill--medium":"usage-progress-fill--low"}const Av="kb-usage-hidden-windows",Rv="kb-usage-modal-size",Iv="kb-usage-provider-order";function Jf(e){const n=Gn(Rv,e);if(!n)return null;try{const s=JSON.parse(n);if(s&&typeof s.width=="number"&&typeof s.height=="number"&&s.width>0&&s.height>0)return{width:s.width,height:s.height}}catch{}return null}function Yf(e){const n=Gn(Av,e);if(!n)return{};try{const s=JSON.parse(n);return!s||typeof s!="object"?{}:Object.entries(s).reduce((a,[r,o])=>{if(Array.isArray(o)){const l=o.filter(c=>typeof c=="string");l.length>0&&(a[r]=l)}return a},{})}catch{return{}}}function MD(e,n){fs(Av,JSON.stringify(e),n)}function Qf(e){const n=Gn(Iv,e);if(!n)return[];try{const s=JSON.parse(n);return Array.isArray(s)?s.filter(a=>typeof a=="string"):[]}catch{return[]}}function Xf(e,n){fs(Iv,JSON.stringify(e),n)}function Tv(e,n,s){return s[e]?.includes(n)??!1}function AD({window:e,viewMode:n,isHidden:s,onToggleHidden:a}){const r=_D(e.percentUsed),o=n==="remaining",l=Math.round(o?e.percentLeft:e.percentUsed),c=o?`${Math.round(e.percentLeft)}% remaining`:`${Math.round(e.percentUsed)}% used`,d=o?`${Math.round(e.percentUsed)}% used`:`${Math.round(e.percentLeft)}% left`;let u=e.resetText;if(!u&&e.resetAt){const v=new Date(e.resetAt).getTime()-Date.now();if(v>0){const b=Math.floor(v/36e5),y=Math.floor(b/24),S=b%24;y>0&&S>0?u=`resets in ${y}d ${S}h`:y>0?u=`resets in ${y}d`:b>0?u=`resets in ${b}h`:u=`resets in ${Math.floor(v/6e4)}m`}}const m=e.pace,h=m!==void 0;let f=0;h&&(f=o?100-m.percentElapsed:m.percentElapsed);const p=m?.status==="ahead",g=m?.status==="behind",w=m?.status==="on-track";return t.jsxs("div",{className:`usage-window ${s?"usage-window--hidden":""}`,children:[t.jsxs("div",{className:"usage-window-header",children:[t.jsx("span",{className:"usage-window-label",children:e.label}),t.jsxs("div",{className:"usage-window-header-controls",children:[!s&&t.jsx("span",{className:"usage-window-percentage",children:c}),!s&&t.jsx("button",{className:"btn-icon usage-window-hide-btn",onClick:a,"aria-label":`Hide ${e.label}`,"data-testid":"usage-window-hide-btn",children:t.jsx(Fr,{size:14})})]})]}),t.jsxs("div",{className:"usage-progress-wrapper",children:[t.jsx("div",{className:"usage-progress-bar",children:t.jsx("div",{className:`usage-progress-fill ${r}`,style:{width:`${l}%`},role:"progressbar","aria-valuenow":l,"aria-valuemin":0,"aria-valuemax":100,"aria-label":`${e.label}: ${c}`})}),h&&t.jsx("div",{className:"usage-pace-marker",style:{left:`${f}%`},"aria-hidden":"true","data-testid":"pace-marker"})]}),t.jsxs("div",{className:"usage-window-footer",children:[t.jsx("span",{className:"usage-window-left",children:d}),t.jsxs("span",{className:"usage-window-reset-group",children:[u&&t.jsx("span",{className:"usage-window-reset",children:u}),e.resetAt&&t.jsx("span",{className:"usage-window-reset-at",children:ED(e.resetAt)})]})]}),h&&t.jsxs("div",{className:"usage-pace-row","data-testid":"pace-row",children:[p&&t.jsxs(t.Fragment,{children:[t.jsx(zr,{size:14,className:"pace-icon pace-ahead"}),t.jsx("span",{className:"pace-text pace-ahead",children:m.message})]}),g&&t.jsxs(t.Fragment,{children:[t.jsx(ij,{size:14,className:"pace-icon pace-behind"}),t.jsx("span",{className:"pace-text pace-behind",children:m.message})]}),w&&t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:14,className:"pace-icon pace-ontrack"}),t.jsx("span",{className:"pace-text pace-ontrack",children:m.message})]})]})]})}function RD(e){const n=e.toLowerCase();return n.includes("claude")||n.includes("anthropic")?"anthropic":n.includes("codex")||n.includes("openai")||n.includes("gpt")?"openai":n.includes("gemini")||n.includes("google")||n.includes("antigravity")?"google":n.includes("ollama")?"ollama":n.includes("minimax")?"minimax":n.includes("zai")||n.includes("zhipu")?"zai":n.includes("kimi")||n.includes("moonshot")?"kimi":n.includes("bedrock")||n.includes("amazon")?"bedrock":n.includes("xai")||n.includes("grok")?"xai":n.includes("opencode")?"opencode":n.includes("copilot")||n==="github copilot"?"github-copilot":e}function ID({provider:e,viewMode:n,hiddenWindows:s,onToggleWindow:a,onShowAllHidden:r,isDragging:o,isDragOver:l,dragOverPosition:c,onDragStart:d,onDragOver:u,onDragLeave:m,onDrop:h,onDragEnd:f,isTouchReorderMode:p,canMoveUp:g,canMoveDown:w,onMoveUp:v,onMoveDown:b}){const y=s[e.name]?.length??0,S=()=>{switch(e.status){case"ok":return null;case"error":return t.jsx("span",{className:"usage-status-badge usage-status-badge--error",children:"Error"});case"no-auth":default:return t.jsx("span",{className:"usage-status-badge usage-status-badge--not-configured",children:"Not configured"})}};return t.jsxs("div",{className:`usage-provider${o?" usage-provider--dragging":""}${l&&c==="before"?" usage-provider--drag-over-before":""}${l&&c==="after"?" usage-provider--drag-over-after":""}`,"data-provider":e.name,"data-status":e.status,draggable:!p,onDragStart:p?void 0:d,onDragOver:p?void 0:u,onDragLeave:p?void 0:m,onDrop:p?void 0:h,onDragEnd:p?void 0:f,children:[t.jsxs("div",{className:"usage-provider-header",children:[t.jsxs("div",{className:"usage-provider-info",children:[t.jsx(zn,{provider:RD(e.name),size:"md"}),t.jsx("span",{className:"usage-provider-name",children:e.name}),y>0&&t.jsxs("button",{className:"btn btn-sm usage-show-hidden-btn",onClick:()=>r(e.name),"data-testid":"usage-show-hidden-btn",children:["Show hidden (",y,")"]})]}),t.jsxs("div",{className:"usage-provider-actions",children:[p&&t.jsxs("div",{className:"usage-provider-reorder-controls",role:"group","aria-label":`Reorder ${e.name}`,children:[t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:v,disabled:!g,"aria-label":`Move ${e.name} up`,children:t.jsx(Li,{size:14})}),t.jsx("button",{className:"btn-icon usage-provider-reorder-btn",type:"button",onClick:b,disabled:!w,"aria-label":`Move ${e.name} down`,children:t.jsx(gn,{size:14})})]}),S(),t.jsx("div",{className:"usage-provider-drag-handle","aria-hidden":"true",children:t.jsx(xc,{size:16})})]})]}),e.error&&t.jsx("div",{className:"usage-provider-error",children:e.error}),e.plan&&t.jsx("div",{className:"usage-provider-meta",children:t.jsx("span",{className:"usage-provider-plan",children:e.plan})}),e.windows.length>0?t.jsx("div",{className:"usage-provider-windows",children:e.windows.map((j,C)=>{const x=Tv(e.name,j.label,s);return t.jsx(AD,{window:j,viewMode:n,isHidden:x,onToggleHidden:()=>a(e.name,j.label)},`${e.name}-${j.label}-${C}`)})}):e.status==="ok"?t.jsx("div",{className:"usage-provider-empty",children:"No usage data available"}):null]})}function TD(){return t.jsx("div",{className:"usage-skeleton",children:[1,2,3].map(e=>t.jsxs("div",{className:"usage-skeleton-provider",children:[t.jsxs("div",{className:"usage-skeleton-header",children:[t.jsx("div",{className:"usage-skeleton-icon"}),t.jsx("div",{className:"usage-skeleton-name"}),t.jsx("div",{className:"usage-skeleton-badge"})]}),t.jsx("div",{className:"usage-skeleton-bar"}),t.jsx("div",{className:"usage-skeleton-text"})]},e))})}function PD({isOpen:e,onClose:n,projectId:s,anchorRect:a}){const{providers:r,loading:o,error:l,lastUpdated:c,refresh:d}=CD({autoRefresh:e}),[u,m]=i.useState(!1),[h,f]=i.useState(()=>typeof window<"u"?window.innerWidth>=769:!1),[p,g]=i.useState(()=>typeof window>"u"?!1:window.matchMedia?.("(pointer: coarse)").matches??!1),[w,v]=i.useState("used"),[b,y]=i.useState(()=>Yf(s)),[S,j]=i.useState(()=>Qf(s)),[C,x]=i.useState(null),[N,R]=i.useState(null),[F,E]=i.useState(null),_=i.useRef(null),K=i.useRef(null),U=i.useRef(e),A=i.useRef(!1),[T,H]=i.useState(()=>Jf(s));i.useEffect(()=>{H(Jf(s))},[s]),i.useEffect(()=>{if(!e||!h)return;const B=K.current;if(!B||typeof ResizeObserver>"u")return;let pe=null;const ze=new ResizeObserver(ae=>{const Ve=ae[0];if(!Ve)return;const{width:Te,height:rt}=Ve.contentRect;Te<=0||rt<=0||(pe&&clearTimeout(pe),pe=setTimeout(()=>{fs(Rv,JSON.stringify({width:Math.round(Te),height:Math.round(rt)}),s)},250))});return ze.observe(B),()=>{pe&&clearTimeout(pe),ze.disconnect()}},[e,h,s]),i.useEffect(()=>{e||(A.current=!1)},[e]),i.useEffect(()=>{r.length>0&&(A.current=!0)},[r.length]),i.useEffect(()=>{if(typeof window>"u")return;const B=window.matchMedia?.("(pointer: coarse)"),pe=()=>{f(window.innerWidth>=769),g(B?.matches??!1)};return pe(),window.addEventListener("resize",pe),B?.addEventListener?.("change",pe),()=>{window.removeEventListener("resize",pe),B?.removeEventListener?.("change",pe)}},[]),i.useEffect(()=>{!U.current&&e&&(!c||Date.now()-c.getTime()>5e3)&&d(),U.current=e},[e,c,d]),i.useEffect(()=>{const B=Gn("kb-usage-view-mode",s);if(B==="used"||B==="remaining"){v(B);return}v("used")},[s]);const Q=i.useCallback(B=>{v(B),fs("kb-usage-view-mode",B,s)},[s]);i.useEffect(()=>{y(Yf(s)),j(Qf(s))},[s]),i.useEffect(()=>{MD(b,s)},[b,s]);const se=i.useCallback((B,pe)=>{y(ze=>{if(Tv(B,pe,ze)){const ae=(ze[B]??[]).filter(Ve=>Ve!==pe);if(ae.length===0){const{[B]:Ve,...Te}=ze;return Te}return{...ze,[B]:ae}}return{...ze,[B]:[...ze[B]??[],pe]}})},[]),O=i.useCallback(B=>{y(pe=>{if(!pe[B])return pe;const{[B]:ze,...ae}=pe;return ae})},[]),M=i.useCallback(B=>{if(S.length===0)return B;const pe=new Map(B.map(ae=>[ae.name,ae])),ze=[];for(const ae of S){const Ve=pe.get(ae);Ve&&(ze.push(Ve),pe.delete(ae))}return[...ze,...pe.values()]},[S]),D=i.useCallback((B,pe)=>{B.dataTransfer.effectAllowed="move",B.dataTransfer.setData("text/plain",pe),x(pe)},[]),$=i.useCallback((B,pe)=>{if(!C||C===pe)return;B.preventDefault(),B.dataTransfer.dropEffect="move";const{top:ze,height:ae}=B.currentTarget.getBoundingClientRect(),Ve=ze+ae/2,Te=B.clientY<Ve?"before":"after";R(pe),E(Te)},[C]),k=i.useCallback((B,pe)=>{B.preventDefault();const ze=C??B.dataTransfer.getData("text/plain");if(!ze||ze===pe){R(null),E(null);return}const Ve=M(r).map(Be=>Be.name).filter(Be=>Be!==ze),Te=Ve.indexOf(pe);if(Te<0){R(null),E(null);return}const rt=F==="after"?Te+1:Te;Ve.splice(rt,0,ze),Xf(Ve,s),j(Ve),R(null),E(null)},[C,F,s,r,M]),X=i.useCallback(()=>{x(null),R(null),E(null)},[]),le=i.useCallback((B,pe)=>{const ze=M(r).map(Be=>Be.name),ae=ze.indexOf(B),Ve=ae+pe;if(ae<0||Ve<0||Ve>=ze.length)return;const Te=[...ze],[rt]=Te.splice(ae,1);Te.splice(Ve,0,rt),Xf(Te,s),j(Te)},[s,r,M]),ke=i.useCallback(async()=>{m(!0),await d(),m(!1)},[d]);i.useEffect(()=>{if(!e)return;const B=pe=>{pe.key==="Escape"&&n()};return document.addEventListener("keydown",B),()=>document.removeEventListener("keydown",B)},[e,n]);const He=i.useCallback(B=>{B.target===B.currentTarget&&n()},[n]);if(!e)return null;const ye=!!(a&&h),je=8,ne=12,Z=T?.width??420,re=ye?Math.min((a?.bottom??0)+je,window.innerHeight-ne):void 0,q=ye?Math.max(8,(a?.right??0)-Z):void 0,L=h&&T?{width:T.width,height:T.height}:{},xe=M(r),he=t.jsxs("div",{ref:K,className:`usage-modal${ye?" usage-modal--popover":" modal"}`,"data-testid":"usage-modal",style:ye?{position:"fixed",top:re,left:q,...L}:L,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"usage-header",children:[t.jsx(Js,{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 ${w==="used"?"active":""}`,onClick:()=>Q("used"),"aria-pressed":w==="used","data-testid":"usage-view-toggle-used",children:"Used"}),t.jsx("button",{className:`usage-view-toggle-btn ${w==="remaining"?"active":""}`,onClick:()=>Q("remaining"),"aria-pressed":w==="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(mn,{size:20})})]})]}),t.jsx("div",{className:"usage-content",ref:_,children:(o||!A.current&&!l)&&r.length===0?t.jsx(TD,{}):l&&r.length===0?t.jsxs("div",{className:"usage-error",children:[t.jsx("p",{children:"Failed to load usage data"}),t.jsx("p",{className:"usage-error-message",children:l}),t.jsx("button",{className:"btn btn-sm",onClick:ke,children:"Retry"})]}):r.length===0?t.jsxs("div",{className:"usage-empty",children:[t.jsx("p",{children:"No AI providers configured"}),t.jsx("p",{className:"usage-empty-hint",children:"Configure authentication in Settings to see usage data."})]}):t.jsx("div",{className:"usage-providers",children:xe.map((B,pe)=>t.jsx(ID,{provider:B,viewMode:w,hiddenWindows:b,onToggleWindow:se,onShowAllHidden:O,isDragging:C===B.name,isDragOver:N===B.name,dragOverPosition:N===B.name?F:null,onDragStart:ze=>D(ze,B.name),onDragOver:ze=>$(ze,B.name),onDragLeave:()=>{N===B.name&&(R(null),E(null))},onDrop:ze=>k(ze,B.name),onDragEnd:X,isTouchReorderMode:p,canMoveUp:pe>0,canMoveDown:pe<xe.length-1,onMoveUp:()=>le(B.name,-1),onMoveDown:()=>le(B.name,1)},B.name))})}),t.jsxs("div",{className:"modal-actions usage-actions",children:[t.jsx("div",{className:"modal-actions-left usage-actions-left",children:t.jsx("div",{className:"usage-last-updated",children:c&&t.jsxs("span",{children:["Last updated: ",c.toLocaleTimeString()]})})}),t.jsxs("div",{className:"modal-actions-right usage-actions-right",children:[t.jsxs("button",{className:"btn btn-sm",onClick:ke,disabled:o||u,"data-testid":"usage-refresh-btn",children:[t.jsx(ps,{size:14,className:u?"spin":"",style:{marginRight:6}}),"Refresh"]}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:n,children:"Close"})]})]})]});return ye?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"usage-popover-backdrop",onClick:n,"data-testid":"usage-modal-overlay"}),he]}):t.jsx("div",{className:"modal-overlay open",onClick:He,"data-testid":"usage-modal-overlay",children:he})}function Pv(e){if(e<1e3)return`${e}ms`;const n=Math.floor(e/1e3);if(n<60)return`${n}s`;const s=Math.floor(n/60),a=n%60;if(s<60)return a>0?`${s}m ${a}s`:`${s}m`;const r=Math.floor(s/60),o=s%60;return o>0?`${r}h ${o}m`:`${r}h`}function lc(e){const n=Date.now(),s=new Date(e).getTime(),a=n-s;if(a<0){const r=Math.abs(a);return r<6e4?"in a moment":r<36e5?`in ${Math.floor(r/6e4)}m`:r<864e5?`in ${Math.floor(r/36e5)}h`:`in ${Math.floor(r/864e5)}d`}return a<6e4?"just now":a<36e5?`${Math.floor(a/6e4)}m ago`:a<864e5?`${Math.floor(a/36e5)}h ago`:`${Math.floor(a/864e5)}d ago`}const $D={cron:"var(--color-blue, #3b82f6)",webhook:"var(--color-purple, #a855f7)",api:"var(--color-green, #22c55e)",manual:"var(--color-gray, #6b7280)"},$v={cron:"Cron",webhook:"Webhook",api:"API",manual:"Manual"},DD={cron:Qg,webhook:lb,api:Xg,manual:ls},LD={parallel:"Concurrent",queue:"Queued",reject:"Exclusive"},OD={run:"Catch up",skip:"Skip missed",run_one:"Catch up (latest)"};function FD({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(Xn,{size:12}):t.jsx(Ho,{size:12}),t.jsx("span",{children:e.success?"Success":"Failed"}),n>0&&t.jsx("span",{className:"schedule-run-duration",children:Pv(n)})]})}function zD({result:e,index:n}){const[s,a]=i.useState(!1),r=e.completedAt&&e.startedAt?new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime():0;return t.jsxs("div",{className:"schedule-history-item",children:[t.jsxs("button",{className:"schedule-history-header",onClick:()=>a(!s),"aria-expanded":s,"aria-label":`Run #${n+1}: ${e.success?"succeeded":"failed"} ${lc(e.startedAt)}`,children:[t.jsx("span",{className:`schedule-history-status ${e.success?"success":"failure"}`,children:e.success?t.jsx(Xn,{size:12}):t.jsx(Ho,{size:12})}),t.jsx("span",{className:"schedule-history-time",children:lc(e.startedAt)}),e.triggerType&&t.jsx("span",{className:"routine-history-trigger-type",children:$v[e.triggerType]}),t.jsx("span",{className:"schedule-history-duration",children:Pv(r)}),s?t.jsx(Li,{size:12}):t.jsx(gn,{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 BD({routine:e,onEdit:n,onDelete:s,onRun:a,onToggle:r,running:o,lastRunOutput:l}){const[c,d]=i.useState(!1),{confirm:u}=li(),m=i.useCallback(async()=>{await u({title:"Delete Routine",message:`Delete routine "${e.name}"? This cannot be undone.`,danger:!0})&&s(e)},[e,s,u]),h=$D[e.trigger.type],f=DD[e.trigger.type],p=e.trigger.type==="cron"?("cronExpression"in e.trigger?e.trigger.cronExpression:void 0)||e.cronExpression||"":e.cronExpression||"";return t.jsxs("div",{className:`routine-card${e.enabled?"":" disabled"}${o?" running":""}`,children:[t.jsxs("div",{className:"routine-card-header",children:[t.jsxs("div",{className:"routine-card-info",children:[t.jsxs("div",{className:"routine-card-name-row",children:[t.jsx("span",{className:"routine-card-name",children:e.name}),t.jsxs("span",{className:"routine-trigger-badge",style:{borderColor:h,color:h},children:[t.jsx(f,{size:10}),$v[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(gc,{size:10}):t.jsx(js,{size:10}),e.scope]})]}),e.description&&t.jsx("p",{className:"routine-card-description",children:e.description})]}),t.jsxs("div",{className:"routine-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>a(e),disabled:o,title:o?"Running…":"Run now","aria-label":o?"Running…":`Run ${e.name} now`,children:o?t.jsx(jt,{className:"spinner"}):t.jsx(os,{})}),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(Ci,{}):t.jsx(os,{})}),t.jsx("button",{className:"btn-icon",onClick:()=>n(e),title:"Edit","aria-label":`Edit ${e.name}`,children:t.jsx(Hs,{})}),t.jsx("button",{className:"btn-icon",onClick:m,title:"Delete","aria-label":`Delete ${e.name}`,children:t.jsx(Tn,{})})]})]}),t.jsxs("div",{className:"routine-card-meta",children:[e.steps&&e.steps.length>0?t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(Fa,{size:12}),t.jsxs("span",{className:"routine-policy-badge",children:[e.steps.length," step",e.steps.length===1?"":"s"]})]}):e.command?t.jsx("div",{className:"routine-meta-item routine-meta-command-preview",title:e.command,children:t.jsx("code",{className:"routine-cron",children:e.command})}):null,e.trigger.type==="cron"&&p&&t.jsxs("div",{className:"routine-meta-item",children:[t.jsx(ta,{size:12}),t.jsx("code",{className:"routine-cron",children:p})]}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Execution policy: ${e.executionPolicy}`,children:LD[e.executionPolicy]})}),t.jsx("div",{className:"routine-meta-item",children:t.jsx("span",{className:"routine-policy-badge",title:`Catch-up policy: ${e.catchUpPolicy}`,children:OD[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:lc(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:lc(e.lastRunAt)})]}),e.lastRunResult&&t.jsx(FD,{result:e.lastRunResult}),t.jsxs("div",{className:"routine-meta-item",children:[t.jsx("span",{className:"routine-meta-label",children:"Runs:"}),t.jsx("span",{children:e.runCount})]})]}),l&&t.jsxs("div",{className:`routine-run-output ${l.success?"success":"failure"}`,children:[l.output&&t.jsx("pre",{className:"routine-run-output-text",children:l.output}),l.error&&t.jsx("div",{className:"routine-run-output-error",children:l.error})]}),e.runHistory.length>0&&t.jsxs("div",{className:"routine-card-history",children:[t.jsxs("button",{className:"schedule-history-toggle",onClick:()=>d(g=>!g),"aria-expanded":c,children:[c?t.jsx(Li,{size:12}):t.jsx(gn,{size:12}),t.jsxs("span",{children:["Run History (",e.runHistory.length,")"]})]}),c&&t.jsxs("div",{className:"schedule-history-list",children:[e.runHistory.slice(0,10).map((g,w)=>t.jsx(zD,{result:g,index:w},`${g.startedAt}-${w}`)),e.runHistory.length>10&&t.jsxs("div",{className:"schedule-history-more",children:["…and ",e.runHistory.length-10," more"]})]})]})]})}function UD({type:e,size:n=12}){return e==="command"?t.jsxs("span",{className:"step-type-badge step-type-command",title:"Command step",children:[t.jsx(ea,{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(ik,{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(ms,{size:n}),t.jsx("span",{children:"AI Prompt"})]})}function qd(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function HD(e){return e==="command"?{id:qd(),type:e,name:"New Command Step",command:"",continueOnFailure:!1}:e==="ai-prompt"?{id:qd(),type:e,name:"New AI Prompt Step",prompt:"",continueOnFailure:!1}:{id:qd(),type:e,name:"New Create Task Step",taskDescription:"",taskColumn:"triage",continueOnFailure:!1}}function qD({step:e,onSave:n,onCancel:s}){const[a,r]=i.useState(e.name),[o,l]=i.useState(e.type),[c,d]=i.useState(e.command??""),[u,m]=i.useState(e.prompt??""),[h,f]=i.useState(e.modelProvider??""),[p,g]=i.useState(e.modelId??""),[w,v]=i.useState(e.taskTitle??""),[b,y]=i.useState(e.taskDescription??""),[S,j]=i.useState(e.taskColumn??"triage"),[C,x]=i.useState(e.timeoutMs),[N,R]=i.useState(e.continueOnFailure??!1),[F,E]=i.useState({}),[_,K]=i.useState([]),[U,A]=i.useState(!1),[T,H]=i.useState(null);i.useEffect(()=>{let D=!1;return A(!0),H(null),Ws().then($=>{D||K($.models)}).catch($=>{D||H($ instanceof Error?$.message:"Failed to load models")}).finally(()=>{D||A(!1)}),()=>{D=!0}},[]);const Q=i.useCallback(()=>{const D={};return a.trim()||(D.name="Step name is required"),o==="command"&&!c.trim()&&(D.command="Command is required"),o==="ai-prompt"&&!u.trim()&&(D.prompt="Prompt is required"),o==="create-task"&&!b.trim()&&(D.taskDescription="Task description is required"),(o==="ai-prompt"||o==="create-task")&&(h||p)&&(!h||!p)&&(D.modelProvider="Both model provider and model ID must be set together"),C!==void 0&&C<1e3&&(D.timeoutMs="Timeout must be at least 1 second (1000ms)"),E(D),Object.keys(D).length===0},[a,o,c,u,b,h,p,C]),se=h&&p?`${h}/${p}`:"",O=i.useCallback(D=>{if(!D)f(""),g("");else{const $=D.indexOf("/");$!==-1&&(f(D.slice(0,$)),g(D.slice($+1)))}},[]),M=i.useCallback(()=>{if(!Q())return;const D={...e,name:a.trim(),type:o,command:o==="command"?c.trim():void 0,prompt:o==="ai-prompt"?u.trim():void 0,taskTitle:o==="create-task"&&w.trim()?w.trim():void 0,taskDescription:o==="create-task"&&b.trim()?b.trim():void 0,taskColumn:o==="create-task"?S:void 0,modelProvider:(o==="ai-prompt"||o==="create-task")&&h.trim()?h.trim():void 0,modelId:(o==="ai-prompt"||o==="create-task")&&p.trim()?p.trim():void 0,timeoutMs:C||void 0,continueOnFailure:N};o!=="ai-prompt"&&delete D.prompt,o!=="create-task"&&(delete D.taskTitle,delete D.taskDescription,delete D.taskColumn),n(D)},[Q,n,e,a,o,c,u,w,b,S,h,p,C,N]);return t.jsxs("div",{className:"step-editor",children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-name-${e.id}`,children:"Step Name"}),t.jsx("input",{id:`step-name-${e.id}`,type:"text",placeholder:"e.g. Run tests",value:a,onChange:D=>r(D.target.value),"aria-invalid":!!F.name}),F.name&&t.jsx("small",{className:"field-error",children:F.name})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-type-${e.id}`,children:"Step Type"}),t.jsxs("select",{id:`step-type-${e.id}`,value:o,onChange:D=>l(D.target.value),children:[t.jsx("option",{value:"command",children:"Command"}),t.jsx("option",{value:"ai-prompt",children:"AI Prompt"}),t.jsx("option",{value:"create-task",children:"Create Task"})]})]}),o==="command"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-command-${e.id}`,children:"Command"}),t.jsx("textarea",{id:`step-command-${e.id}`,placeholder:"e.g. npm test",value:c,onChange:D=>d(D.target.value),rows:2,"aria-invalid":!!F.command}),F.command&&t.jsx("small",{className:"field-error",children:F.command})]}),o==="ai-prompt"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-prompt-${e.id}`,children:"Prompt"}),t.jsx("textarea",{id:`step-prompt-${e.id}`,placeholder:"e.g. Summarize the test results and highlight any failures",value:u,onChange:D=>m(D.target.value),rows:3,"aria-invalid":!!F.prompt}),F.prompt&&t.jsx("small",{className:"field-error",children:F.prompt})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-model-${e.id}`,children:"Model (optional)"}),t.jsx(_s,{id:`step-model-${e.id}`,label:"Model",models:_,value:se,onChange:O,placeholder:"Use default",disabled:U}),T&&t.jsx("small",{className:"field-error",children:T}),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:w,onChange:D=>v(D.target.value)}),t.jsx("small",{children:"Leave blank to auto-summarize from description"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-description-${e.id}`,children:"Task Description *"}),t.jsx("textarea",{id:`step-task-description-${e.id}`,placeholder:"e.g. Check all npm dependencies for security vulnerabilities and update outdated packages",value:b,onChange:D=>y(D.target.value),rows:4,"aria-invalid":!!F.taskDescription}),F.taskDescription&&t.jsx("small",{className:"field-error",children:F.taskDescription})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-column-${e.id}`,children:"Target Column"}),t.jsxs("select",{id:`step-task-column-${e.id}`,value:S,onChange:D=>j(D.target.value),children:[t.jsx("option",{value:"triage",children:"Triage"}),t.jsx("option",{value:"todo",children:"To Do"})]}),t.jsx("small",{children:"Column where the new task will be created"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-task-model-${e.id}`,children:"Executor Model (optional)"}),t.jsx(_s,{id:`step-task-model-${e.id}`,label:"Model",models:_,value:se,onChange:O,placeholder:"Use default",disabled:U}),T&&t.jsx("small",{className:"field-error",children:T}),F.modelProvider&&t.jsx("small",{className:"field-error",children:F.modelProvider}),t.jsx("small",{children:"AI model for executing the created task. Uses default if not selected."})]})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:`step-timeout-${e.id}`,children:"Timeout (ms, optional)"}),t.jsx("input",{id:`step-timeout-${e.id}`,type:"number",min:1e3,step:1e3,placeholder:"Override schedule timeout",value:C??"",onChange:D=>x(D.target.value?Number(D.target.value):void 0),"aria-invalid":!!F.timeoutMs}),F.timeoutMs&&t.jsx("small",{className:"field-error",children:F.timeoutMs})]}),t.jsxs("div",{className:"form-group",children:[t.jsxs("label",{htmlFor:`step-continue-${e.id}`,className:"checkbox-label",children:[t.jsx("input",{id:`step-continue-${e.id}`,type:"checkbox",checked:N,onChange:D=>R(D.target.checked)}),"Continue on failure"]}),t.jsx("small",{children:"If checked, the next step will run even if this one fails"})]}),t.jsxs("div",{className:"step-editor-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:M,children:"Save Step"})]})]})}function VD({steps:e,onChange:n,onEditingChange:s}){const[a,r]=i.useState(null);i.useEffect(()=>{s?.(a!==null)},[a,s]);const o=i.useCallback(u=>{const m=HD(u);n([...e,m]),r(m.id)},[e,n]),l=i.useCallback(u=>{n(e.filter(m=>m.id!==u)),a===u&&r(null)},[e,n,a]),c=i.useCallback((u,m)=>{const h=e.findIndex(g=>g.id===u);if(h<0)return;const f=m==="up"?h-1:h+1;if(f<0||f>=e.length)return;const p=[...e];[p[h],p[f]]=[p[f],p[h]],n(p)},[e,n]),d=i.useCallback(u=>{n(e.map(m=>m.id===u.id?u:m)),r(null)},[e,n]);return t.jsxs("div",{className:"steps-editor",children:[t.jsx("div",{className:"steps-editor-header",children:t.jsxs("span",{className:"steps-editor-title",children:["Steps (",e.length,")"]})}),e.length===0&&t.jsx("div",{className:"steps-empty-state",children:t.jsx("p",{children:"No steps added yet. Add a command or AI prompt step to get started."})}),t.jsx("div",{className:"steps-list",children:e.map((u,m)=>t.jsx("div",{className:"step-card",children:a===u.id?t.jsx(qD,{step:u,onSave:d,onCancel:()=>r(null)}):t.jsxs("div",{className:"step-card-row",children:[t.jsx("div",{className:"step-card-drag",children:t.jsx(xc,{size:14})}),t.jsx("span",{className:"step-card-index",children:m+1}),t.jsx(UD,{type:u.type}),t.jsx("span",{className:"step-card-name",children:u.name}),u.continueOnFailure&&t.jsx("span",{className:"step-card-flag",title:"Continues on failure",children:"⚡"}),t.jsxs("div",{className:"step-card-actions",children:[t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"up"),disabled:m===0,title:"Move up","aria-label":`Move ${u.name} up`,children:t.jsx(Li,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>c(u.id,"down"),disabled:m===e.length-1,title:"Move down","aria-label":`Move ${u.name} down`,children:t.jsx(gn,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>r(u.id),title:"Edit","aria-label":`Edit ${u.name}`,children:t.jsx(Hs,{})}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>l(u.id),title:"Delete","aria-label":`Delete ${u.name}`,children:t.jsx(Tn,{})})]})]})},u.id))}),t.jsxs("div",{className:"steps-add-buttons",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("command"),children:[t.jsx($n,{size:14}),"Add Command Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("ai-prompt"),children:[t.jsx($n,{size:14}),"Add AI Prompt Step"]}),t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>o("create-task"),children:[t.jsx($n,{size:14}),"Add Create Task Step"]})]})]})}const Dv={hourly:"0 * * * *",daily:"0 0 * * *",weekly:"0 0 * * 1",monthly:"0 0 1 * *"},WD={hourly:"Every hour",daily:"Every day (midnight)",weekly:"Every week (Monday)",monthly:"Every month (1st)",custom:"Custom cron expression"};function GD(e){const n=e.trim();for(const[s,a]of Object.entries(Dv))if(a===n)return s;return"custom"}function KD(e){const n=e.trim().split(/\s+/);return n.length!==5?!1:n.every(s=>/^[\d*,/-]+$/.test(s))}function JD(e,n,s,a,r){switch(e){case"cron":return{type:"cron",cronExpression:n};case"webhook":return{type:"webhook",webhookPath:s||"/trigger/"+Math.random().toString(36).slice(2,10),secret:a||void 0};case"api":return{type:"api",endpoint:r||"/api/routine/"+Math.random().toString(36).slice(2,10)};case"manual":return{type:"manual"}}}function YD(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 QD=[{value:"parallel",label:"Allow concurrent runs"},{value:"queue",label:"Queue after current (one at a time)"},{value:"reject",label:"Reject new runs while running"}],XD=[{value:"skip",label:"Skip missed runs"},{value:"run_one",label:"Run the most recent missed run"},{value:"run",label:"Run all missed runs"}];function Zf(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`step-${Date.now()}-${Math.random().toString(36).slice(2,11)}`}function eg({routine:e,onSubmit:n,onCancel:s,scope:a,projectId:r,onScopeChange:o}){const l=!!e,c=e?YD(e):{triggerType:"cron",cronExpression:"0 * * * *",webhookPath:"",webhookSecret:"",endpoint:""},[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.description??""),[f,p]=i.useState(c.triggerType),[g,w]=i.useState(c.cronExpression),[v,b]=i.useState(()=>c.triggerType!=="cron"?"custom":GD(c.cronExpression)),[y,S]=i.useState(c.webhookPath),[j,C]=i.useState(c.webhookSecret),[x,N]=i.useState(c.endpoint),[R,F]=i.useState(e?.executionPolicy??"queue"),[E,_]=i.useState(e?.catchUpPolicy??"run_one"),[K,U]=i.useState(e?.enabled??!0),A=e?.steps&&e.steps.length===1&&e.steps[0].type==="ai-prompt"&&!e.command,T=e?.steps&&e.steps.length===1&&e.steps[0].type==="create-task"&&!e.command,[H,Q]=i.useState(e?.steps&&e.steps.length>0&&!A&&!T?"advanced":"simple"),[se,O]=i.useState(()=>A?"ai-prompt":T?"create-task":"command"),[M,D]=i.useState(e?.command??""),[$,k]=i.useState(e?.steps??[]),[X,le]=i.useState(!1),[ke,He]=i.useState(e?.timeoutMs??3e5),[ye,je]=i.useState(A?e.steps?.[0]?.prompt??"":""),[ne,fe]=i.useState(T?e.steps?.[0]?.taskTitle??"":""),[Z,re]=i.useState(T?e.steps?.[0]?.taskDescription??"":""),[q,L]=i.useState(T?e.steps?.[0]?.taskColumn??"triage":"triage"),[xe,he]=i.useState(A||T?e.steps?.[0]?.modelProvider??"":""),[B,pe]=i.useState(A||T?e.steps?.[0]?.modelId??"":""),[ze,ae]=i.useState([]),[Ve,Te]=i.useState(!1),[rt,Be]=i.useState(null),[ce,Re]=i.useState(a??"global"),[Le,ct]=i.useState({}),[Ue,ue]=i.useState(!1),oe=i.useRef(!0);i.useEffect(()=>()=>{oe.current=!1},[]),i.useEffect(()=>{a&&Re(a)},[a]),i.useEffect(()=>{let be=!1;return Te(!0),Be(null),Ws().then(gt=>{be||ae(gt.models)}).catch(gt=>{be||Be(gt instanceof Error?gt.message:"Failed to load models")}).finally(()=>{be||Te(!1)}),()=>{be=!0}},[]);const Ee=xe&&B?`${xe}/${B}`:"",ft=i.useCallback(be=>{if(!be){he(""),pe("");return}const gt=be.indexOf("/");gt!==-1&&(he(be.slice(0,gt)),pe(be.slice(gt+1)))},[]),ht=i.useCallback(()=>{const be={};if(d.trim()||(be.name="Name is required"),ce==="project"&&!r&&(be.scope="Project-specific entries require an active project."),f==="cron"&&v==="custom"&&(g.trim()?KD(g)||(be.cronExpression="Invalid cron format — expected 5 fields (e.g. '0 */6 * * *')"):be.cronExpression="Cron expression is required"),f==="webhook"&&!y.trim()&&(be.webhookPath="Webhook path is required"),f==="api"&&!x.trim()&&(be.endpoint="API endpoint is required"),H==="simple")se==="command"&&!M.trim()&&(be.command="Command is required"),se==="ai-prompt"&&!ye.trim()&&(be.prompt="Prompt is required"),se==="create-task"&&!Z.trim()&&(be.taskDescription="Task description is required"),(xe.trim()&&!B.trim()||!xe.trim()&&B.trim())&&(be.model="Both model provider and model ID must be set, or both must be empty");else{$.length===0&&(be.steps="At least one step is required"),X&&(be.stepsEditing="Please save or cancel all step edits before saving the routine");const gt=[];$.forEach(($t,Ie)=>{$t.name?.trim()||gt.push(`Step ${Ie+1}: Name is required`),$t.type==="command"&&!$t.command?.trim()&&gt.push(`Step ${Ie+1}: Command is required`),$t.type==="ai-prompt"&&!$t.prompt?.trim()&&gt.push(`Step ${Ie+1}: Prompt is required`),$t.type==="create-task"&&!$t.taskDescription?.trim()&&gt.push(`Step ${Ie+1}: Task description is required`)}),gt.length>0&&(be.steps=gt.join("; "))}return ke<1e3&&(be.timeoutMs="Timeout must be at least 1 second (1000ms)"),ct(be),Object.keys(be).length===0},[d,f,g,v,y,x,ce,r,H,se,M,ye,Z,xe,B,$,X,ke]),tt=i.useCallback(async be=>{if(be.preventDefault(),!!ht()){ue(!0);try{let gt=e?.scope??ce??(r?"project":"global");gt==="project"&&!r&&(gt="global");const $t=JD(f,g,y,j,x);let Ie,ge;H==="simple"?se==="command"?Ie=M.trim()||void 0:se==="ai-prompt"?ge=[{id:Zf(),type:"ai-prompt",name:d.trim(),prompt:ye.trim(),modelProvider:xe.trim()||void 0,modelId:B.trim()||void 0}]:ge=[{id:Zf(),type:"create-task",name:d.trim(),taskTitle:ne.trim()||void 0,taskDescription:Z.trim(),taskColumn:q,modelProvider:xe.trim()||void 0,modelId:B.trim()||void 0}]:ge=$;const st={name:d.trim(),agentId:e?.agentId??"",description:m.trim()||void 0,trigger:$t,command:Ie,steps:ge,timeoutMs:ke,executionPolicy:R,catchUpPolicy:E,enabled:K,scope:gt};await n(st)}finally{oe.current&&ue(!1)}}},[ht,n,d,m,f,g,y,j,x,H,se,M,ye,xe,B,ne,Z,q,$,ke,R,E,K,ce,r,e?.scope,e?.agentId]),xt="routine-name-error",Me="routine-cron-error",Ye="routine-webhook-error",dt="routine-endpoint-error",wt="routine-command-error",St="routine-prompt-error",Fe="routine-task-description-error",J="routine-model-error",me="routine-timeout-error",Ze=i.useCallback(be=>{b(be),be!=="custom"&&w(Dv[be])},[]);return t.jsxs("form",{className:"routine-form",onSubmit:tt,noValidate:!0,children:[t.jsx("h4",{className:"settings-section-heading",children:l?"Edit Routine":"New Routine"}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-name",children:"Name"}),t.jsx("input",{id:"routine-name",type:"text",placeholder:"e.g. Daily standup reminder",value:d,onChange:be=>u(be.target.value),"aria-invalid":!!Le.name,"aria-describedby":Le.name?xt:void 0}),Le.name&&t.jsx("small",{id:xt,className:"field-error",children:Le.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${ce==="global"?" active":""}`,onClick:()=>{Re("global"),o?.("global")},role:"radio","aria-checked":ce==="global"?"true":"false",disabled:!!e?.scope,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:"Global scope",children:[t.jsx(gc,{size:12}),"Global"]}),t.jsxs("button",{type:"button",className:`routine-scope-btn${ce==="project"?" active":""}`,onClick:()=>{Re("project"),o?.("project")},role:"radio","aria-checked":ce==="project"?"true":"false",disabled:!!e?.scope||!r,title:e?.scope?`Scope is locked to ${e.scope} for existing routines`:r?"Project scope":"Select a project to enable project scope",children:[t.jsx(js,{size:12}),"Project"]})]}),t.jsx("small",{children:!r&&!e?.scope?"No active project. Routines will be created at global scope.":ce==="project"&&r?"This routine will be scoped to the current project.":"This routine will be created at global scope."}),Le.scope&&t.jsx("small",{className:"field-error",children:Le.scope})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Trigger Type"}),t.jsxs("div",{className:"routine-trigger-type-selector",role:"radiogroup","aria-label":"Trigger type",children:[t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="cron"?" active":""}`,onClick:()=>p("cron"),role:"radio","aria-checked":f==="cron",children:[t.jsx(Qg,{size:14}),"Cron"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="webhook"?" active":""}`,onClick:()=>p("webhook"),role:"radio","aria-checked":f==="webhook",children:[t.jsx(lb,{size:14}),"Webhook"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="api"?" active":""}`,onClick:()=>p("api"),role:"radio","aria-checked":f==="api",children:[t.jsx(Xg,{size:14}),"API"]}),t.jsxs("button",{type:"button",className:`routine-trigger-btn${f==="manual"?" active":""}`,onClick:()=>p("manual"),role:"radio","aria-checked":f==="manual",children:[t.jsx(ls,{size:14}),"Manual"]})]})]}),f==="cron"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-frequency",children:"Frequency"}),t.jsx("select",{id:"routine-frequency",value:v,onChange:be=>Ze(be.target.value),children:Object.entries(WD).map(([be,gt])=>t.jsx("option",{value:be,children:gt},be))}),t.jsx("label",{htmlFor:"routine-cron",children:"Cron Expression"}),t.jsx("input",{id:"routine-cron",type:"text",placeholder:"* * * * *",value:g,onChange:be=>w(be.target.value),disabled:v!=="custom","aria-invalid":!!Le.cronExpression,"aria-describedby":Le.cronExpression?Me:void 0}),Le.cronExpression?t.jsx("small",{id:Me,className:"field-error",children:Le.cronExpression}):t.jsx("small",{children:v==="custom"?t.jsxs(t.Fragment,{children:["min hour day month weekday — ",t.jsx("a",{href:"https://crontab.guru",target:"_blank",rel:"noopener noreferrer",children:"crontab.guru"})]}):`Auto-filled from preset: ${g}`})]}),f==="webhook"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-path",children:"Webhook Path"}),t.jsx("input",{id:"routine-webhook-path",type:"text",placeholder:"/trigger/my-routine",value:y,onChange:be=>S(be.target.value),"aria-invalid":!!Le.webhookPath,"aria-describedby":Le.webhookPath?Ye:void 0}),Le.webhookPath?t.jsx("small",{id:Ye,className:"field-error",children:Le.webhookPath}):t.jsx("small",{children:"URL path for the webhook endpoint"})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-webhook-secret",children:"Webhook Secret (optional)"}),t.jsx("input",{id:"routine-webhook-secret",type:"password",placeholder:"Optional — leave empty for unauthenticated webhooks",value:j,onChange:be=>C(be.target.value)}),t.jsx("small",{children:"HMAC secret for signature verification. Leave empty for unauthenticated webhooks."})]})]}),f==="api"&&t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-endpoint",children:"API Endpoint"}),t.jsx("input",{id:"routine-endpoint",type:"text",placeholder:"/api/routine/my-routine",value:x,onChange:be=>N(be.target.value),"aria-invalid":!!Le.endpoint,"aria-describedby":Le.endpoint?dt:void 0}),Le.endpoint?t.jsx("small",{id:dt,className:"field-error",children:Le.endpoint}):t.jsx("small",{children:"API endpoint path that triggers this routine"})]}),f==="manual"&&t.jsx("div",{className:"form-group",children:t.jsx("small",{className:"routine-trigger-info",children:"This routine will be triggered manually via the dashboard or API."})}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Action Mode"}),t.jsxs("div",{className:"schedule-mode-toggle",role:"radiogroup","aria-label":"Action mode",children:[t.jsx("button",{type:"button",className:`schedule-mode-btn${H==="simple"?" active":""}`,onClick:()=>Q("simple"),role:"radio","aria-checked":H==="simple",children:"Simple"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${H==="advanced"?" active":""}`,onClick:()=>Q("advanced"),role:"radio","aria-checked":H==="advanced",children:"Multi-Step"})]}),t.jsx("small",{children:H==="simple"?"Run one command, prompt, or task creation action":"Run multiple actions sequentially"})]}),H==="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${se==="command"?" active":""}`,onClick:()=>O("command"),role:"radio","aria-checked":se==="command",children:"Command"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${se==="ai-prompt"?" active":""}`,onClick:()=>O("ai-prompt"),role:"radio","aria-checked":se==="ai-prompt",children:"AI Prompt"}),t.jsx("button",{type:"button",className:`schedule-mode-btn${se==="create-task"?" active":""}`,onClick:()=>O("create-task"),role:"radio","aria-checked":se==="create-task",children:"Create Task"})]})]}),se==="command"?t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-command",children:"Command"}),t.jsx("input",{id:"routine-command",type:"text",placeholder:"e.g. npx runfusion.ai backup --create",value:M,onChange:be=>D(be.target.value),"aria-invalid":!!Le.command,"aria-describedby":Le.command?wt:void 0}),Le.command?t.jsx("small",{id:wt,className:"field-error",children:Le.command}):t.jsx("small",{children:"Shell command to execute."})]}):se==="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:ye,onChange:be=>je(be.target.value),rows:3,"aria-invalid":!!Le.prompt,"aria-describedby":Le.prompt?St:void 0}),Le.prompt?t.jsx("small",{id:St,className:"field-error",children:Le.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(_s,{id:"routine-model",label:"Model",models:ze,value:Ee,onChange:ft,placeholder:"Use default",disabled:Ve}),rt&&t.jsx("small",{className:"field-error",children:rt}),Le.model&&t.jsx("small",{id:J,className:"field-error",children:Le.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:ne,onChange:be=>fe(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:Z,onChange:be=>re(be.target.value),rows:4,"aria-invalid":!!Le.taskDescription,"aria-describedby":Le.taskDescription?Fe:void 0}),Le.taskDescription?t.jsx("small",{id:Fe,className:"field-error",children:Le.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:q,onChange:be=>L(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(_s,{id:"routine-task-model",label:"Executor Model",models:ze,value:Ee,onChange:ft,placeholder:"Use default",disabled:Ve}),rt&&t.jsx("small",{className:"field-error",children:rt}),Le.model&&t.jsx("small",{id:J,className:"field-error",children:Le.model})]})]})]}):t.jsxs(t.Fragment,{children:[t.jsx(VD,{steps:$,onChange:k,onEditingChange:le}),Le.steps&&t.jsx("small",{className:"field-error",children:Le.steps}),Le.stepsEditing&&t.jsx("small",{className:"field-error",children:Le.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:ke,onChange:be=>He(Number(be.target.value)),"aria-invalid":!!Le.timeoutMs,"aria-describedby":Le.timeoutMs?me:void 0}),Le.timeoutMs?t.jsx("small",{id:me,className:"field-error",children:Le.timeoutMs}):t.jsx("small",{children:"Maximum execution time in milliseconds."})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"routine-execution-policy",children:"Execution Policy"}),t.jsx("select",{id:"routine-execution-policy",value:R,onChange:be=>F(be.target.value),children:QD.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:E,onChange:be=>_(be.target.value),children:XD.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:K,onChange:be=>U(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:Ue,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:Ue,children:Ue?"Saving…":l?"Save Changes":"Create Routine"})]})]})}const ZD=3e4;function eL({onClose:e,addToast:n,projectId:s}){const[a,r]=i.useState(()=>s?"project":"global"),[o,l]=i.useState([]),[c,d]=i.useState("list"),[u,m]=i.useState(),[h,f]=i.useState(null),[p,g]=i.useState({}),w=i.useRef(null);zi(w,!0,"fusion:automation-modal-size");const v=i.useMemo(()=>({scope:a,projectId:a==="project"?s:void 0}),[a,s]),b=i.useCallback(async()=>{try{const A=await LS(v);l(A),g(T=>{const H={...T};for(const Q of A){const se=H[Q.id];if(!se||!Q.lastRunResult)continue;const O=Q.lastRunResult;O.success===se.success&&(O.output||"")===se.output&&(O.error||"")===(se.error||"")&&delete H[Q.id]}return H})}catch(A){n(Se(A)||"Failed to load routines","error")}},[n,v]);i.useEffect(()=>{b()},[b]),i.useEffect(()=>{const A=setInterval(()=>{b()},ZD);return()=>clearInterval(A)},[b]),i.useEffect(()=>{const A=T=>{T.key==="Escape"&&(c!=="list"?(d("list"),m(void 0)):e())};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[e,c]);const y=sa(e),S=i.useCallback(async A=>{try{await OS(A,v),n("Routine created","success"),d("list"),await b()}catch(T){n(Se(T)||"Failed to create routine","error")}},[n,b,v]),j=i.useCallback(A=>{m(A),d("edit")},[]),C=i.useCallback(async A=>{if(u)try{await Zm(u.id,A,v),n("Routine updated","success"),d("list"),m(void 0),await b()}catch(T){n(Se(T)||"Failed to update routine","error")}},[u,n,b,v]),x=i.useCallback(async A=>{try{await FS(A.id,v),n(`Deleted "${A.name}"`,"success"),await b()}catch(T){n(Se(T)||"Failed to delete routine","error")}},[n,b,v]),N=i.useCallback(async A=>{f(A.id);try{const{result:T}=await zS(A.id,v);g(H=>({...H,[A.id]:{output:T.output||"",error:T.error,success:T.success}})),T.success?n(`"${A.name}" completed successfully`,"success"):n(`"${A.name}" failed: ${T.error||"Unknown error"}`,"error"),await b()}catch(T){n(Se(T)||"Failed to run routine","error")}finally{f(null)}},[n,b,v]),R=i.useCallback(async A=>{try{await Zm(A.id,{enabled:!A.enabled},v),n(`"${A.name}" ${A.enabled?"disabled":"enabled"}`,"success"),await b()}catch(T){n(Se(T)||"Failed to toggle routine","error")}},[n,b,v]),F=i.useCallback(()=>{d("list"),m(void 0)},[]);i.useEffect(()=>{c!=="list"&&g({})},[c]);const E=i.useCallback(A=>{r(A),d("list"),m(void 0),g({})},[]),_=()=>c==="create"?t.jsx(eg,{onSubmit:S,onCancel:F,scope:a,projectId:s}):c==="edit"&&u?t.jsx(eg,{routine:u,onSubmit:C,onCancel:F,scope:a,projectId:s}):o.length===0?t.jsxs("div",{className:"routine-empty-state",children:[t.jsx(ls,{size:48,strokeWidth:1}),t.jsx("h4",{children:"No automations yet"}),t.jsx("p",{children:"Create an automation with a schedule, webhook, API, or manual trigger."}),t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),children:[t.jsx($n,{size:14}),"Create your first automation"]})]}):t.jsx("div",{className:"routine-list",children:o.map(A=>t.jsx(BD,{routine:A,onEdit:j,onDelete:x,onRun:N,onToggle:R,running:h===A.id,lastRunOutput:p[A.id]??null},A.id))}),K=()=>_(),U=c==="list"&&o.length>0;return t.jsx("div",{className:"modal-overlay open",...y,children:t.jsxs("div",{ref:w,className:"modal modal-lg automation-modal",role:"dialog","aria-modal":"true","aria-labelledby":"schedules-modal-title",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("div",{className:"detail-title-row",children:[t.jsx(ls,{size:20,className:"icon-triage"}),t.jsx("h3",{id:"schedules-modal-title",children:"Automations"})]}),t.jsx("button",{className:"modal-close",onClick:e,"aria-label":"Close",children:t.jsx(mn,{size:20})})]}),t.jsxs("div",{className:"scheduling-toolbar","aria-live":"polite",children:[t.jsxs("div",{className:"scheduling-toolbar-left",role:"group","aria-label":"Scheduling scope",children:[t.jsxs("div",{className:"scheduling-scope-selector",children:[t.jsxs("button",{type:"button",className:`scope-btn${a==="global"?" active":""}`,onClick:()=>E("global"),"aria-pressed":a==="global",title:"Global (user-level) automations",children:[t.jsx(gc,{size:14}),"Global"]}),t.jsxs("button",{type:"button",className:`scope-btn${a==="project"?" active":""}`,onClick:()=>E("project"),"aria-pressed":a==="project",title:"Project-scoped automations",children:[t.jsx(js,{size:14}),"Project"]})]}),t.jsxs("span",{className:"scheduling-count",children:[t.jsx(ls,{size:14}),o.length," automation",o.length===1?"":"s"]})]}),t.jsx("div",{className:"scheduling-toolbar-right",children:U&&t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>d("create"),"aria-label":"Create new automation",children:[t.jsx($n,{size:14}),"New Automation"]})})]}),t.jsx("div",{className:"schedule-modal-content",id:"scheduled-tasks-content",children:K()})]})})}const tL=3e4,Iu=new Map,Vd=new Map;function tg(e){return e??"default"}function ng(e){const n=Iu.get(e);return n?Date.now()>=n.expiresAt?(Iu.delete(e),null):n:null}function nL(e,n){const s=e.some(r=>r.id!=="github"&&r.authenticated),a=e.some(r=>r.id==="github"&&r.authenticated)||(n?.authenticated??!1);return{hasAiProvider:s,hasGithub:a}}async function sL(e){const n=Vd.get(e);if(n)return n;const s=Po().then(({providers:a,ghCli:r})=>{const l={...nL(a,r),ghCli:r,expiresAt:Date.now()+tL};return Iu.set(e,l),l}).finally(()=>{Vd.delete(e)});return Vd.set(e,s),s}function Lv(e){const n=tg(e),s=ng(n),[a,r]=i.useState(s?.hasAiProvider??!1),[o,l]=i.useState(s?.hasGithub??!1),[,c]=i.useState(s?.ghCli),[d,u]=i.useState(s==null),m=i.useRef(!!s);return i.useEffect(()=>{let h=!1;const f=tg(e),p=ng(f);if(p)return r(p.hasAiProvider),l(p.hasGithub),c(p.ghCli),u(!1),m.current=!0,()=>{h=!0};m.current=!1;async function g(){!m.current&&u(!0);try{const v=await sL(f);if(h)return;r(v.hasAiProvider),l(v.hasGithub),c(v.ghCli)}catch{}finally{h||(m.current=!0,u(!1))}}return g(),()=>{h=!0}},[e]),i.useMemo(()=>({hasAiProvider:a,hasGithub:o,loading:d,hasWarnings:!a||!o}),[a,o,d])}function Ov({hasAiProvider:e,hasGithub:n,compact:s=!1,onDismiss:a}){if(e&&n)return null;const r=a?t.jsx("button",{type:"button",className:"setup-warning-banner__dismiss touch-target","aria-label":"Dismiss setup warning",onClick:a,children:t.jsx(mn,{size:16,"aria-hidden":"true"})}):null;if(s)return t.jsxs("div",{className:`setup-warning-banner setup-warning-banner--compact${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[t.jsx("p",{className:"setup-warning-banner__compact-text",children:"⚠ Setup incomplete — AI and/or GitHub features will be limited."}),r]});const o=[];return e||o.push({key:"ai",title:"No AI provider connected",description:"AI agents won't be able to work on tasks until you connect a provider. Set one up in Settings → AI Setup."}),n||o.push({key:"github",title:"GitHub not connected",description:"You won't be able to import issues from GitHub, but you can still create tasks manually."}),t.jsxs("div",{className:`setup-warning-banner${a?" setup-warning-banner--dismissible":""}`,role:"status","aria-live":"polite",children:[r,o.map(l=>t.jsxs("div",{className:"setup-warning-banner__item",children:[t.jsx("strong",{className:"setup-warning-banner__title",children:l.title}),t.jsx("p",{className:"setup-warning-banner__description",children:l.description})]},l.key))]})}function iL({isOpen:e,onClose:n,projectId:s,tasks:a,onCreateTask:r,addToast:o,onPlanningMode:l,onSubtaskBreakdown:c}){const{confirm:d}=li(),u=oi();Mi(e);const{keyboardOverlap:m,viewportHeight:h,viewportOffsetTop:f,keyboardOpen:p}=aa({enabled:u==="mobile"}),g=p?{"--keyboard-overlap":`${m}px`,"--vv-offset-top":`${f}px`,...h!==null?{"--vv-height":`${h}px`}:{}}:{},[w,v]=i.useState(""),[b,y]=i.useState([]),[S,j]=i.useState(""),[C,x]=i.useState(""),[N,R]=i.useState([]),[F,E]=i.useState(!1),[_,K]=i.useState(""),[U,A]=i.useState(""),[T,H]=i.useState(""),[Q,se]=i.useState(""),[O,M]=i.useState(""),[D,$]=i.useState("default"),[k,X]=i.useState(!1),[le,ke]=i.useState([]),[He,ye]=i.useState(!1),[je,ne]=i.useState(void 0),[fe,Z]=i.useState(Ps),[re,q]=i.useState(void 0),[L,xe]=i.useState(!1),[he,B]=i.useState(""),[pe,ze]=i.useState(null),[ae,Ve]=i.useState([]),[Te,rt]=i.useState(!1),[Be,ce]=i.useState(!1),Re=i.useRef(null),[Le,ct]=i.useState(!1),[Ue,ue]=i.useState(""),oe=i.useRef(null),{hasAiProvider:Ee,hasGithub:ft,loading:ht}=Lv(s),{nodes:tt}=Cc(),xt=i.useCallback(ge=>{ye(!0),ke(ge)},[]),Me=i.useCallback(()=>{ye(!1)},[]),Ye=i.useCallback(async()=>{if(ae.length>0){rt(!0);return}ce(!0);try{const ge=await Ur(void 0,s);Ve(ge),rt(!0)}catch(ge){const st=Se(ge);o(st?`Failed to load agents: ${st}`:"Failed to load agents","error"),rt(!1)}finally{ce(!1)}},[ae.length,s,o]);i.useEffect(()=>{if(!Te)return;const ge=st=>{Re.current&&!Re.current.contains(st.target)&&rt(!1)};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Te]),i.useEffect(()=>{if(!Le)return;const ge=st=>{oe.current&&!oe.current.contains(st.target)&&(ct(!1),ue(""))};return document.addEventListener("mousedown",ge),()=>document.removeEventListener("mousedown",ge)},[Le]);const dt=a.filter(ge=>!b.includes(ge.id)).sort((ge,st)=>{const yt=st.createdAt.localeCompare(ge.createdAt);if(yt!==0)return yt;const pt=parseInt(ge.id.slice(ge.id.lastIndexOf("-")+1),10)||0;return(parseInt(st.id.slice(st.id.lastIndexOf("-")+1),10)||0)-pt}),wt=Ue?dt.filter(ge=>ge.id.toLowerCase().includes(Ue.toLowerCase())||ge.title&&ge.title.toLowerCase().includes(Ue.toLowerCase())||ge.description&&ge.description.toLowerCase().includes(Ue.toLowerCase())):dt,St=(ge,st)=>ge.length>st?ge.slice(0,st)+"…":ge,Fe=he.trim(),J=Fe.length>0&&!Sc.test(Fe);i.useEffect(()=>{const ge=w.trim()!==""||b.length>0||N.length>0||_!==""||U!==""||T!==""||Q!==""||le.length>0||pe!==null||je!==void 0||fe!==Ps||re!==void 0||S!==""||C!==""||L||Fe!=="";X(ge)},[w,b,N,_,U,T,Q,le,pe,je,fe,re,S,C,L,Fe]);const me=i.useCallback(async()=>{k&&!await d({title:"Discard Changes",message:"You have unsaved changes. Discard them?",danger:!0})||(N.forEach(ge=>URL.revokeObjectURL(ge.previewUrl)),R([]),v(""),y([]),K(""),A(""),H(""),se(""),M(""),$("default"),ke([]),ye(!1),ze(null),rt(!1),ne(void 0),Z(Ps),q(void 0),j(""),x(""),X(!1),xe(!1),B(""),n())},[k,n,N,d]),Ze=i.useCallback(async()=>{const ge=w.trim();if(!(!ge||F||J)){E(!0);try{const st=_.indexOf("/"),yt=U.indexOf("/"),pt=T.indexOf("/"),vt=await r({title:void 0,description:ge,column:"triage",dependencies:b.length?b:void 0,enabledWorkflowSteps:He?le.length>0?le:[]:void 0,...pe?{assignedAgentId:pe}:{},modelPresetId:D==="preset"&&O||void 0,modelProvider:_&&st!==-1?_.slice(0,st):void 0,modelId:_&&st!==-1?_.slice(st+1):void 0,validatorModelProvider:U&&yt!==-1?U.slice(0,yt):void 0,validatorModelId:U&&yt!==-1?U.slice(yt+1):void 0,planningModelProvider:T&&pt!==-1?T.slice(0,pt):void 0,planningModelId:T&&pt!==-1?T.slice(pt+1):void 0,thinkingLevel:Q!==""?Q:void 0,reviewLevel:je,priority:fe,nodeId:re,branch:S.trim()===""?void 0:S.trim(),baseBranch:C.trim()===""?void 0:C.trim(),...L||Fe!==""?{githubTracking:{enabled:L,...Fe!==""?{repoOverride:Fe}:{}}}:{}});if(N.length>0){const Ut=[];for(const Dt of N)try{await jc(vt.id,Dt.file,s)}catch{Ut.push(Dt.file.name)}Ut.length>0&&o(`Failed to upload: ${Ut.join(", ")}`,"error")}N.forEach(Ut=>URL.revokeObjectURL(Ut.previewUrl)),R([]),v(""),y([]),K(""),A(""),H(""),se(""),M(""),$("default"),ke([]),ye(!1),ze(null),rt(!1),ne(void 0),Z(Ps),q(void 0),j(""),x(""),o(`Created ${vt.id}`,"success"),n()}catch(st){o(Se(st)||"Failed to create task","error")}finally{E(!1)}}},[w,b,N,_,U,T,Q,F,r,o,n,s,D,O,le,He,pe,je,fe,re,S,C]),be=i.useCallback(ge=>{ge.key==="Escape"&&(ge.preventDefault(),me())},[me]),$t=(pe?ae.find(ge=>ge.id===pe):void 0)?.name??pe,Ie=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:oe,children:[t.jsx("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>ct(ge=>!ge),disabled:F,"data-testid":"dep-trigger",children:b.length>0?`${b.length} selected`:"Add dependencies"}),Le&&t.jsxs("div",{className:"dep-dropdown",children:[t.jsx("input",{className:"dep-dropdown-search",placeholder:"Search tasks…",autoFocus:!0,value:Ue,onChange:ge=>ue(ge.target.value),onClick:ge=>ge.stopPropagation()}),wt.length===0?t.jsx("div",{className:"dep-dropdown-empty",children:"No available tasks"}):wt.map(ge=>t.jsxs("div",{className:`dep-dropdown-item${b.includes(ge.id)?" selected":""}`,onClick:()=>{y(b.includes(ge.id)?b.filter(st=>st!==ge.id):[...b,ge.id]),ct(!1),ue("")},onMouseDown:st=>st.preventDefault(),children:[t.jsx("span",{className:"dep-dropdown-id",children:ge.id}),t.jsx("span",{className:"dep-dropdown-title",children:St(ge.title||ge.description||ge.id,30)})]},ge.id))]})]}),b.length>0&&t.jsx("div",{className:"selected-deps",children:b.map(ge=>t.jsxs("span",{className:"dep-chip",children:[ge,t.jsx("button",{type:"button",className:"dep-chip-remove",onClick:()=>y(b.filter(st=>st!==ge)),disabled:F,children:"×"})]},ge))})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{children:"Assign Agent"}),t.jsxs("div",{className:"agent-trigger-wrap",ref:Re,children:[t.jsxs("button",{type:"button",className:"btn btn-sm dep-trigger",onClick:()=>{Te?rt(!1):Ye()},disabled:F,"data-testid":"new-task-agent-button",children:[t.jsx(Qn,{size:12,style:{verticalAlign:"middle"}}),$t?` ${$t}`:" Assign agent"]}),Te&&t.jsxs("div",{className:"dep-dropdown agent-picker-dropdown",onMouseDown:ge=>ge.preventDefault(),children:[t.jsx("div",{className:"dep-dropdown-search-header",children:"Select agent"}),Be&&t.jsx("div",{className:"dep-dropdown-empty",children:"Loading agents..."}),!Be&&ae.map(ge=>t.jsxs("div",{className:`dep-dropdown-item${pe===ge.id?" selected":""}`,onMouseDown:st=>st.preventDefault(),onClick:()=>{ze(ge.id===pe?null:ge.id),rt(!1)},"data-testid":`agent-option-${ge.id}`,children:[t.jsx(Qn,{size:12,style:{marginRight:6}}),t.jsx("span",{className:"dep-dropdown-id",children:ge.role}),t.jsx("span",{className:"dep-dropdown-title",children:ge.name})]},ge.id)),!Be&&ae.length===0&&t.jsx("div",{className:"dep-dropdown-empty",children:"No agents available"}),pe&&t.jsx("div",{className:"dep-dropdown-item",onMouseDown:ge=>ge.preventDefault(),onClick:()=>{ze(null),rt(!1)},children:t.jsx("span",{className:"dep-dropdown-title",children:"Clear selection"})})]})]})]})]});return e?t.jsx("div",{className:"modal-overlay open",onClick:me,onKeyDown:be,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal-lg new-task-modal",onClick:ge=>ge.stopPropagation(),style:g,children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"New Task"}),t.jsx("button",{className:"modal-close",onClick:me,disabled:F,"aria-label":"Close",children:"×"})]}),t.jsxs("div",{className:"modal-body",children:[!ht&&t.jsx(Ov,{hasAiProvider:Ee,hasGithub:ft}),t.jsx(gv,{mode:"create",description:w,onDescriptionChange:v,dependencies:b,onDependenciesChange:y,executorModel:_,onExecutorModelChange:K,validatorModel:U,onValidatorModelChange:A,presetMode:D,onPresetModeChange:$,selectedPresetId:O,onSelectedPresetIdChange:M,selectedWorkflowSteps:le,onWorkflowStepsChange:xt,onDefaultOnApplied:Me,pendingImages:N,onImagesChange:R,tasks:a,projectId:s,disabled:F,addToast:o,isActive:e,onPlanningMode:l,onSubtaskBreakdown:c,onClose:me,planningModel:T,onPlanningModelChange:H,thinkingLevel:Q,onThinkingLevelChange:se,reviewLevel:je,onReviewLevelChange:ne,priority:fe,onPriorityChange:Z,branch:S,onBranchChange:j,baseBranch:C,onBaseBranchChange:x,nodeId:re,onNodeIdChange:q,nodeOptions:tt,githubTrackingEnabled:L,onGithubTrackingEnabledChange:xe,githubRepoOverride:he,onGithubRepoOverrideChange:B,renderBelowPrimary:Ie,hideDependencies:!0,autoExpandMoreOptionsOnSelection:!1})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:me,disabled:F,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:Ze,disabled:!w.trim()||F||J,children:F?"Creating...":"Create Task"})]})]})}):null}function Ni(e){if(!Number.isFinite(e)||e<0)return"—";const n=e/(1024*1024);return n<1024?`${n.toFixed(0)} MB`:`${(n/1024).toFixed(2)} GB`}function sg(e,n){return!Number.isFinite(e)||!Number.isFinite(n)||n<=0?"—":`${(e/n*100).toFixed(1)}%`}function aL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.85?"critical":s>=.65?"warning":"normal"}function rL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.5?"critical":s>=.25?"warning":"normal"}function oL(e,n){if(n<=0)return"normal";const s=e/n;return s>=.9?"critical":s>=.75?"warning":"normal"}function lL(e,n){if(e===null||!Number.isFinite(e)||e<0)return"normal";const s=n>0?e/n:e;return s>=80?"critical":s>=50?"warning":"normal"}function Pl(e){return e==="critical"?"system-stats-modal__value--critical":e==="warning"?"system-stats-modal__value--warning":""}function cL(e){if(!e)return"Not yet";const n=new Date(e);return Number.isNaN(n.getTime())?"Not yet":n.toLocaleString()}function dL({isOpen:e,onClose:n,projectId:s}){const[a,r]=i.useState(null),[o,l]=i.useState(!1),[c,d]=i.useState(null),[u,m]=i.useState(!0),[h,f]=i.useState(90),[p,g]=i.useState(!1),[w,v]=i.useState(!1),[b,y]=i.useState(null),[S,j]=i.useState(null),[C,x]=i.useState(null),N=i.useCallback(async ne=>{l(!0);try{const fe=await w1(s);r(fe),d(null),x(Date.now()),ne?.preserveKillResult||y(null)}catch(fe){d(fe instanceof Error?fe.message:"Failed to load system stats")}finally{l(!1)}},[s]);i.useEffect(()=>{if(!e)return;N();const ne=window.setInterval(()=>{N()},5e3);return()=>{window.clearInterval(ne)}},[e,N]),i.useEffect(()=>{if(!e)return;(async()=>{try{const fe=await na();m(fe.vitestAutoKillEnabled??!0),f(fe.vitestKillThresholdPct??90),j(null)}catch(fe){j(fe instanceof Error?fe.message:"Failed to load vitest settings")}})()},[e]),i.useEffect(()=>{if(!e)return;const ne=fe=>{fe.key==="Escape"&&n()};return document.addEventListener("keydown",ne),()=>document.removeEventListener("keydown",ne)},[e,n]);const R=i.useMemo(()=>{if(!a)return[];const ne=a.systemStats,fe=Pl(aL(ne.heapUsed,ne.heapLimit)),Z=Pl(rL(ne.rss,ne.systemTotalMem));return[{label:"RSS",value:Ni(ne.rss),detail:sg(ne.rss,ne.systemTotalMem),className:Z},{label:"Heap Used",value:Ni(ne.heapUsed),detail:`of ${Ni(ne.heapTotal)}`,className:fe},{label:"Heap Limit",value:Ni(ne.heapLimit),detail:"V8 limit"},{label:"External",value:Ni(ne.external)},{label:"Array Buffers",value:Ni(ne.arrayBuffers)}]},[a]),F=i.useCallback(async ne=>{m(ne);try{await Bn({vitestAutoKillEnabled:ne}),j(null)}catch(fe){j(fe instanceof Error?fe.message:"Failed to save vitest settings")}},[]),E=i.useCallback(async ne=>{const fe=Math.min(99,Math.max(50,Number.isFinite(ne)?Math.round(ne):90));f(fe);try{await Bn({vitestKillThresholdPct:fe}),j(null)}catch(Z){j(Z instanceof Error?Z.message:"Failed to save vitest settings")}},[]),_=i.useCallback(async()=>{if(!p){if(!w){v(!0);return}g(!0);try{const ne=await k1(s);y(ne),v(!1),await N({preserveKillResult:!0})}catch(ne){d(ne instanceof Error?ne.message:"Failed to kill vitest processes")}finally{g(!1)}}},[w,p,N,s]);if(!e)return null;const K=a?.systemStats,U=o&&!!a,A=C?`Updated ${new Date(C).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit",second:"2-digit"})}`:"Waiting for first update",T=a?.taskStats,H=K?K.systemTotalMem-K.systemFreeMem:0,Q=K?oL(H,K.systemTotalMem):"normal",se=K?Pl(Q):"",O=K&&Number.isFinite(K.systemTotalMem)&&K.systemTotalMem>0?Math.max(0,Math.min(100,H/K.systemTotalMem*100)):0,M=K?`System memory used: ${O.toFixed(1)}% (${Ni(H)} of ${Ni(K.systemTotalMem)})`:"System memory usage unavailable",D=a?.vitestProcessCount,$=lL(K?.cpuPercent??null,K?.cpuCount??0),k=Pl($),X=K?.cpuPercent??null,le=X===null?0:Math.max(0,Math.min(100,X)),ke=X===null?"Sampling…":`${X.toFixed(1)}%`,He=X===null?"App CPU usage unavailable: waiting for another sample":`App CPU usage: ${X.toFixed(1)}%`,ye=b?b.killed>0?"system-stats-modal__kill-result system-stats-modal__kill-result--success":"system-stats-modal__kill-result system-stats-modal__kill-result--error":"",je=cL(a?.vitestLastAutoKillAt);return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"system-stats-modal-title",onClick:ne=>{ne.target===ne.currentTarget&&n()},"data-testid":"system-stats-modal-overlay",children:t.jsxs("div",{className:"modal modal-lg system-stats-modal","data-testid":"system-stats-modal",children:[t.jsxs("div",{className:"modal-header system-stats-modal__header",children:[t.jsxs("h2",{id:"system-stats-modal-title",className:"system-stats-modal__title",children:[t.jsx(Cr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("div",{className:"system-stats-modal__header-actions",children:[t.jsxs("span",{className:"system-stats-modal__auto-refresh","aria-live":"polite",children:[t.jsx("span",{children:"Auto-refresh · 5s"}),t.jsx("span",{className:"system-stats-modal__auto-refresh-time",children:A})]}),t.jsx("button",{type:"button",className:"btn-icon",onClick:()=>void N(),title:"Refresh","aria-label":"Refresh system stats",children:t.jsx(ps,{size:16,className:U?"system-stats-modal__refresh--spinning":void 0})}),t.jsx("button",{type:"button",className:"modal-close",onClick:n,"aria-label":"Close",children:t.jsx(mn,{})})]})]}),o&&!a&&t.jsx("div",{className:"system-stats-modal__state",children:"Loading system stats…"}),c&&!a&&t.jsx("div",{className:"system-stats-modal__state system-stats-modal__state--error",role:"alert",children:c}),a&&t.jsxs("div",{className:"system-stats-modal__content",children:[t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Process stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Process"}),t.jsx("dl",{className:"system-stats-modal__grid",children:R.map(ne=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ne.label}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${ne.className}`.trim(),children:ne.value}),ne.detail?t.jsx("span",{className:"system-stats-modal__detail",children:ne.detail}):null]})]},ne.label))})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"CPU and load stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"CPU & Load"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--cpu-used",children:[t.jsx("dt",{children:"App CPU"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${k}`.trim(),children:ke}),t.jsx("span",{className:"system-stats-modal__detail",children:X===null?"First sample pending":"process usage"})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${$}`,role:"progressbar","aria-valuenow":Math.round(le),"aria-valuemin":0,"aria-valuemax":100,"aria-label":He,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${$}`,style:{width:`${le}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Load Avg"}),t.jsx("dd",{children:K?.loadAvg.map(ne=>ne.toFixed(2)).join(" ")??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Cores"}),t.jsx("dd",{children:K?.cpuCount??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Platform"}),t.jsx("dd",{children:K?.platform??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Node"}),t.jsx("dd",{children:K?.nodeVersion??"—"})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"PID"}),t.jsx("dd",{children:K?.pid??"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"System memory stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"System"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row system-stats-modal__row--memory-used",children:[t.jsx("dt",{children:"Memory Used"}),t.jsxs("dd",{children:[t.jsx("span",{className:`system-stats-modal__value ${se}`.trim(),children:K?Ni(H):"—"}),t.jsx("span",{className:"system-stats-modal__detail",children:K?`${sg(H,K.systemTotalMem)} of ${Ni(K.systemTotalMem)}`:""})]}),t.jsx("div",{className:"system-stats-modal__memory-progress-wrapper",children:t.jsx("div",{className:`system-stats-modal__memory-progress-track system-stats-modal__memory-progress-track--${Q}`,role:"progressbar","aria-valuenow":Math.round(O),"aria-valuemin":0,"aria-valuemax":100,"aria-label":M,children:t.jsx("div",{className:`system-stats-modal__memory-progress-fill system-stats-modal__memory-progress-fill--${Q}`,style:{width:`${O}%`}})})})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Memory Free"}),t.jsx("dd",{children:K?Ni(K.systemFreeMem):"—"})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Task stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Tasks"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Total"}),t.jsx("dd",{children:T?.total??0})]}),Object.entries(T?.byColumn??{}).map(([ne,fe])=>t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:ne}),t.jsx("dd",{children:fe})]},ne))]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Agent stats",children:[t.jsx("h3",{className:"system-stats-modal__section-title",children:"Agents"}),t.jsxs("dl",{className:"system-stats-modal__grid",children:[t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"idle"}),t.jsx("dd",{children:T?.agents.idle??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"active"}),t.jsx("dd",{children:T?.agents.active??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"running"}),t.jsx("dd",{children:T?.agents.running??0})]}),t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"error"}),t.jsx("dd",{children:T?.agents.error??0})]})]})]}),t.jsxs("section",{className:"system-stats-modal__section","aria-label":"Vitest controls",children:[t.jsxs("h3",{className:"system-stats-modal__section-title system-stats-modal__section-title--with-icon",children:[t.jsx(Vk,{}),t.jsx("span",{children:"Vitest Controls"})]}),t.jsx("dl",{className:"system-stats-modal__grid system-stats-modal__vitest-controls",children:t.jsxs("div",{className:"system-stats-modal__row",children:[t.jsx("dt",{children:"Vitest Processes"}),t.jsx("dd",{children:D??"—"})]})}),t.jsxs("div",{className:"system-stats-modal__vitest-controls",children:[t.jsx("div",{className:"system-stats-modal__kill-row",children:t.jsxs("button",{type:"button",className:"btn btn-danger",onClick:()=>void _(),disabled:p||D===0,children:[t.jsx(Jk,{}),t.jsx("span",{children:w?"Confirm Kill?":"Kill Vitest Processes"})]})}),t.jsxs("label",{className:"system-stats-modal__toggle-row",children:[t.jsx("input",{type:"checkbox",checked:u,onChange:ne=>{F(ne.target.checked)}}),t.jsx("span",{children:"Auto-kill vitest on memory pressure"})]}),t.jsxs("div",{className:"system-stats-modal__threshold-row",children:[t.jsx("label",{htmlFor:"vitest-threshold-number",children:"Kill threshold (%)"}),t.jsxs("div",{className:"system-stats-modal__threshold-controls",children:[t.jsx("input",{id:"vitest-threshold-range",type:"range",min:50,max:99,value:h,"aria-label":"Kill threshold slider (%)",onChange:ne=>{const fe=Number.parseInt(ne.target.value,10);E(Number.isNaN(fe)?90:fe)}}),t.jsx("input",{id:"vitest-threshold-number",type:"number",className:"input",min:50,max:99,value:h,"aria-label":"Kill threshold (%)",onChange:ne=>{const fe=Number.parseInt(ne.target.value,10);E(Number.isNaN(fe)?90:fe)},onBlur:()=>{E(h)}})]})]}),b&&t.jsxs("p",{className:ye,children:["Killed ",b.killed," processes"]}),t.jsxs("p",{className:"system-stats-modal__last-kill",children:["Last auto-kill: ",je]}),S&&t.jsx("p",{className:"system-stats-modal__kill-result system-stats-modal__kill-result--error",children:S})]})]})]}),c&&a&&t.jsxs("div",{className:"system-stats-modal__footer-error",children:["Latest refresh failed: ",c]})]})})}const uL=5e3;function mL(e={}){const{projectId:n,type:s,limit:a=50,autoRefresh:r=!0,useCentralFeed:o=!1}=e,[l,c]=i.useState([]),[d,u]=i.useState(!1),[m,h]=i.useState(null),[f,p]=i.useState(!1),g=i.useRef(null),w=i.useRef(void 0),v=i.useCallback(async()=>{try{u(!0),h(null);let S;o?S=await oh({limit:a,projectId:n,type:s}):S=(await eh({limit:a,type:s,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(S),p(S.length===a),S.length>0&&(w.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load activity log")}finally{u(!1)}},[a,n,s,o]),b=i.useCallback(async()=>{if(w.current)try{u(!0);let S;o?S=await oh({limit:a,projectId:n,type:s,since:w.current}):S=(await eh({limit:a,type:s,since:w.current,projectId:n})).map(C=>({...C,projectId:n??"",projectName:""})),c(j=>[...j,...S]),p(S.length===a),S.length>0&&(w.current=S[S.length-1].timestamp)}catch(S){h(S instanceof Error?S.message:"Failed to load more entries")}finally{u(!1)}},[a,n,s,o]),y=i.useCallback(()=>{c([]),p(!1),w.current=void 0},[]);return i.useEffect(()=>{v()},[v]),i.useEffect(()=>{if(r)return g.current=setInterval(()=>{v()},uL),()=>{g.current&&(clearInterval(g.current),g.current=null)}},[r,v]),{entries:l,loading:d,error:m,refresh:v,clear:y,hasMore:f,loadMore:b}}const Wd={"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"},hL={"task:created":t.jsx($n,{size:14,className:"activity-icon created"}),"task:moved":t.jsx(Uo,{size:14,className:"activity-icon moved"}),"task:updated":t.jsx(ps,{size:14,className:"activity-icon updated"}),"task:deleted":t.jsx(mn,{size:14,className:"activity-icon deleted"}),"task:merged":t.jsx(Xn,{size:14,className:"activity-icon merged"}),"task:failed":t.jsx(Ho,{size:14,className:"activity-icon failed"}),"settings:updated":t.jsx(Co,{size:14,className:"activity-icon settings"})};function pL(e){const n=new Date(e),a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4),o=Math.floor(a/36e5),l=Math.floor(a/864e5);return r<1?"Just now":r<60?`${r}m ago`:o<24?`${o}h ago`:l<7?`${l}d ago`:n.toLocaleDateString(void 0,{month:"short",day:"numeric"})}function fL({isOpen:e,onClose:n,tasks:s,onOpenTaskDetail:a,projectId:r,projects:o=[],onProjectFilterChange:l,currentProject:c}){const[d,u]=i.useState("all"),[m,h]=i.useState(r||"all"),[f,p]=i.useState(!1);i.useEffect(()=>{h(r||"all")},[r]);const g=d==="all"?void 0:d,w=m==="all"?void 0:m,v=!c&&o.length>0,{entries:b,loading:y,error:S,refresh:j,hasMore:C}=mL({projectId:w,type:g,limit:100,autoRefresh:e,useCentralFeed:v}),x=b.map(_=>({id:_.id,timestamp:_.timestamp,type:_.type,taskId:_.taskId,taskTitle:_.taskTitle,details:_.details,metadata:_.metadata,projectId:_.projectId,projectName:_.projectName})),N=async()=>{try{await BS(),j(),p(!1)}catch{p(!1)}},R=_=>{a&&a(_)},F=_=>{h(_),l?.(_==="all"?void 0:_)};i.useEffect(()=>{if(!e)return;const _=K=>{K.key==="Escape"&&(f?p(!1):n())};return document.addEventListener("keydown",_),()=>document.removeEventListener("keydown",_)},[e,n,f]);const E=d!=="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(Oa,{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(js,{size:14}),t.jsxs("select",{value:m,onChange:_=>F(_.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(ql,{size:14}),t.jsxs("select",{value:d,onChange:_=>u(_.target.value),className:"activity-log-filter-select","data-testid":"activity-filter",children:[t.jsx("option",{value:"all",children:"All Events"}),Object.entries(Wd).map(([_,K])=>t.jsx("option",{value:_,children:K},_))]})]}),t.jsx("button",{className:"activity-log-refresh",onClick:()=>j(),title:"Refresh","data-testid":"activity-refresh",children:y?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14})}),x.length>0&&t.jsx("button",{className:"activity-log-clear",onClick:()=>p(!0),title:"Clear Log","data-testid":"activity-clear",children:t.jsx(Tn,{size:14})})]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",title:"Close","data-testid":"activity-close",children:"×"})]}),E&&t.jsxs("div",{className:"activity-log-active-filters",children:[t.jsx("span",{className:"activity-log-filter-label",children:"Active filters:"}),m!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Project: ",o.find(_=>_.id===m)?.name||m]}),d!=="all"&&t.jsxs("span",{className:"activity-log-filter-badge",children:["Type: ",Wd[d]]}),t.jsx("button",{className:"activity-log-clear-filters",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear all"})]}),t.jsxs("div",{className:"activity-log-content","data-testid":"activity-log-content",children:[S&&t.jsxs("div",{className:"activity-log-error","data-testid":"activity-error",children:[t.jsx(Vs,{size:16}),t.jsx("span",{children:S})]}),x.length===0&&!y&&!S&&t.jsxs("div",{className:"activity-log-empty","data-testid":"activity-empty",children:[t.jsx(Oa,{size:48,className:"activity-log-empty-icon"}),t.jsx("p",{children:E?"No activity matches the current filters":"No activity recorded yet"}),E&&t.jsx("button",{className:"btn btn-secondary",onClick:()=>{u("all"),h("all"),l?.(void 0)},children:"Clear Filters"})]}),t.jsx("div",{className:"activity-log-list",children:x.map(_=>t.jsxs("div",{className:"activity-log-entry","data-testid":"activity-entry",children:[t.jsx("div",{className:"activity-log-entry-icon",children:hL[_.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:Wd[_.type]}),t.jsx("span",{className:"activity-log-entry-time",children:pL(_.timestamp)})]}),t.jsxs("div",{className:"activity-log-entry-details",children:[_.taskId&&t.jsx("button",{className:"activity-log-task-link",onClick:()=>R(_.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:Cs(_.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))}),C&&!y&&t.jsx("button",{className:"activity-log-load-more",onClick:j,"data-testid":"activity-load-more",children:"Load More"}),y&&x.length>0&&t.jsx("div",{className:"activity-log-loading",children:t.jsx(jt,{size:20,className:"spin"})})]}),f&&t.jsx("div",{className:"activity-log-confirm-overlay",children:t.jsxs("div",{className:"activity-log-confirm-dialog",children:[t.jsx("h3",{children:"Clear Activity Log?"}),t.jsx("p",{children:"This will permanently delete all activity log entries. This action cannot be undone."}),t.jsxs("div",{className:"activity-log-confirm-actions",children:[t.jsx("button",{className:"activity-log-confirm-cancel",onClick:()=>p(!1),children:"Cancel"}),t.jsx("button",{className:"activity-log-confirm-clear",onClick:N,children:"Clear Log"})]})]})})]})}):null}const ho=[{id:"status",label:"Status",icon:rb},{id:"changes",label:"Changes",icon:su},{id:"commits",label:"Commits",icon:Nr},{id:"branches",label:"Branches",icon:Os},{id:"worktrees",label:"Worktrees",icon:Uw},{id:"stashes",label:"Stashes",icon:zo},{id:"remotes",label:"Remotes",icon:sb}];function ig({status:e}){switch(e){case"added":case"untracked":return t.jsx(ww,{size:14,className:"gm-file-icon gm-file-added"});case"modified":return t.jsx(tb,{size:14,className:"gm-file-icon gm-file-modified"});case"deleted":return t.jsx(xw,{size:14,className:"gm-file-icon gm-file-deleted"});case"renamed":case"copied":return t.jsx(xa,{size:14,className:"gm-file-icon gm-file-renamed"});default:return t.jsx(jw,{size:14,className:"gm-file-icon"})}}function ag({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 gL(e){return i.useCallback(async(n,s)=>{try{await navigator.clipboard.writeText(n),e(`Copied ${s||"to clipboard"}`,"success")}catch{e("Failed to copy","error")}},[e])}function Tr(e){if(!e)return"—";const n=new Date(e);if(isNaN(n.getTime()))return"—";const a=new Date().getTime()-n.getTime(),r=Math.floor(a/6e4);if(r<1)return"just now";if(r<60)return`${r}m ago`;const o=Math.floor(r/60);if(o<24)return`${o}h ago`;const l=Math.floor(o/24);return l<30?`${l}d ago`:n.toLocaleDateString()}function bL({isOpen:e,onClose:n,tasks:s,addToast:a,projectId:r}){const o=li(),l=oi();Mi(e);const{keyboardOverlap:c,viewportHeight:d,viewportOffsetTop:u,keyboardOpen:m}=aa({enabled:l==="mobile"}),h=m?{"--keyboard-overlap":`${c}px`,"--vv-offset-top":`${u}px`,...d!==null?{"--vv-height":`${d}px`}:{}}:{},f=i.useCallback(()=>{if(l==="mobile"){const Y=document.activeElement;Y instanceof HTMLElement&&Y.blur(),window.scrollTo(0,0),requestAnimationFrame(()=>{window.scrollTo(0,0)})}n()},[n,l]),[p,g]=i.useState("status"),[w,v]=i.useState(!1),[b,y]=i.useState(null),S=i.useRef(null);zi(S,e,"fusion:git-modal-size");const j=sa(f),C=gL(a),[x,N]=i.useState(null),[R,F]=i.useState([]),[E,_]=i.useState(new Set),[K,U]=i.useState(""),[A,T]=i.useState(!1),[H,Q]=i.useState(null),[se,O]=i.useState(!1),[M,D]=i.useState(null),[$,k]=i.useState(null),X=i.useRef(0),[le,ke]=i.useState([]),[He,ye]=i.useState(null),[je,ne]=i.useState(null),[fe,Z]=i.useState(!1),[re,q]=i.useState(20),[L,xe]=i.useState(""),[he,B]=i.useState([]),[pe,ze]=i.useState(""),[ae,Ve]=i.useState(""),[Te,rt]=i.useState(""),[Be,ce]=i.useState(null),[Re,Le]=i.useState([]),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState(null),[Ee,ft]=i.useState(null),[ht,tt]=i.useState(!1),[xt,Me]=i.useState([]),[Ye,dt]=i.useState([]),[wt,St]=i.useState(""),[Fe,J]=i.useState(null),[me,Ze]=i.useState(null),[be,gt]=i.useState(null),[$t,Ie]=i.useState(!1),[ge,st]=i.useState(null),yt=i.useRef(0),[pt,vt]=i.useState(null),[Ut,Dt]=i.useState(null),nn=i.useCallback(async()=>{if(e){v(!0),y(null);try{switch(p){case"status":{const Y=await ji(r);N(Y);break}case"changes":{const[Y,_e]=await Promise.all([ji(r),cr(r)]);N(Y),F(_e),_(new Set),k(null),Q(null),D(null);break}case"commits":{const Y=await qN(re,r);ke(Y);break}case"branches":{const[Y,_e]=await Promise.all([Xr(r),ji(r)]);B(Y),N(_e);break}case"worktrees":{const Y=await KN(r);Me(Y);break}case"stashes":{const Y=await al(r);dt(Y),Ze(null),gt(null),st(null),yt.current+=1;break}case"remotes":{const Y=await ji(r);N(Y);break}}}catch(Y){y(Se(Y)||"Failed to fetch git data"),a(Se(Y)||"Failed to fetch git data","error")}finally{v(!1)}}},[p,e,re,a,r]);i.useEffect(()=>{e&&nn()},[nn,e]),i.useEffect(()=>{if(!e)return;const Y=_e=>{if(_e.key==="Escape"){f();return}if((_e.key==="ArrowUp"||_e.key==="ArrowDown")&&_e.altKey){_e.preventDefault();const ut=ho.findIndex(At=>At.id===p);_e.key==="ArrowUp"&&ut>0?g(ho[ut-1].id):_e.key==="ArrowDown"&&ut<ho.length-1&&g(ho[ut+1].id)}};return document.addEventListener("keydown",Y),()=>document.removeEventListener("keydown",Y)},[e,f,p]);const on=i.useCallback(async Y=>{try{await Km(Y,r),a(`Staged ${Y.length} file(s)`,"success");const _e=await cr(r);F(_e),_(new Set),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to stage files","error")}},[a,r]),sn=i.useCallback(async Y=>{try{await aS(Y,r),a(`Unstaged ${Y.length} file(s)`,"success");const _e=await cr(r);F(_e),_(new Set),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to unstage files","error")}},[a,r]),ln=i.useCallback(async Y=>{if(await o.confirm({title:"Discard Changes",message:`Discard changes to ${Y.length} file(s)? This cannot be undone.`,danger:!0}))try{await rS(Y,r),a(`Discarded changes to ${Y.length} file(s)`,"success");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),_(new Set),k(null),Q(null),D(null)}catch(ut){a(Se(ut)||"Failed to discard changes","error")}},[a,r,o]),xn=i.useCallback(async Y=>{if(Y.preventDefault(),!!K.trim()){T(!0);try{const _e=await Jm(K.trim(),r);a(`Committed: ${_e.hash}`,"success"),U("");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),k(null),Q(null),D(null)}catch(_e){a(Se(_e)||"Failed to commit","error")}finally{T(!1)}}},[K,a,r]),qt=i.useCallback(async()=>{if(K.trim()){T(!0);try{const Y=R.filter(zt=>!zt.staged).map(zt=>zt.file);Y.length>0&&await Km(Y,r);const _e=await Jm(K.trim(),r);a(`Committed: ${_e.hash}`,"success"),U("");const[ut,At]=await Promise.all([cr(r),ji(r)]);F(ut),N(At),k(null),Q(null),D(null)}catch(Y){a(Se(Y)||"Failed to commit","error")}finally{T(!1)}}},[K,R,a,r]),Qt=i.useCallback(async(Y,_e)=>{k({file:Y,staged:_e}),O(!0),D(null);const ut=X.current+1;X.current=ut;try{const At=await iS(Y,_e,r);if(X.current!==ut)return;Q(At)}catch(At){if(X.current!==ut)return;const zt=Se(At)||"Failed to load file diff";Q(null),D(zt),a(zt,"error")}finally{X.current===ut&&O(!1)}},[a,r]),hn=i.useCallback(Y=>{_(_e=>{const ut=new Set(_e);return ut.has(Y)?ut.delete(Y):ut.add(Y),ut})},[]),Zt=i.useCallback(async Y=>{if(He===Y){ye(null),ne(null);return}ye(Y),Z(!0);try{const _e=await Jl(Y,r);ne(_e)}catch(_e){a(Se(_e)||"Failed to load diff","error"),ne(null)}finally{Z(!1)}},[He,a,r]),ve=i.useCallback(()=>{q(Y=>Math.min(Y+20,100))},[]),Pe=i.useMemo(()=>{if(!L.trim())return le;const Y=L.toLowerCase();return le.filter(_e=>_e.message.toLowerCase().includes(Y)||_e.author.toLowerCase().includes(Y)||_e.shortHash.toLowerCase().includes(Y))},[le,L]),Ke=i.useCallback(async Y=>{if(Y.preventDefault(),!!pe.trim()){v(!0);try{await JN(pe.trim(),ae.trim()||void 0,r),a(`Created branch ${pe}`,"success"),ze(""),Ve("");const _e=await Xr(r);B(_e)}catch(_e){a(Se(_e)||"Failed to create branch","error")}finally{v(!1)}}},[pe,ae,a,r]),at=i.useCallback(async Y=>{v(!0);try{await YN(Y,r),a(`Switched to ${Y}`,"success");const[_e,ut]=await Promise.all([ji(r),Xr(r)]);N(_e),B(ut)}catch(_e){a(Se(_e)||"Failed to checkout branch","error")}finally{v(!1)}},[a,r]),We=i.useCallback(async Y=>{if(await o.confirm({title:"Delete Branch",message:`Delete branch "${Y}"?`,danger:!0})){v(!0);try{await Gm(Y,void 0,r),a(`Deleted branch ${Y}`,"success");const ut=await Xr(r);B(ut)}catch(ut){if(Se(ut).includes("not fully merged")){if(await o.confirm({title:"Force Delete Branch",message:"Branch has unmerged commits. Force delete?",danger:!0}))try{await Gm(Y,!0,r),a(`Force deleted branch ${Y}`,"success");const zt=await Xr(r);B(zt)}catch(zt){a(Se(zt)||"Failed to delete branch","error")}}else a(Se(ut)||"Failed to delete branch","error")}finally{v(!1)}}},[a,r,o]),It=i.useMemo(()=>{if(!Te.trim())return he;const Y=Te.toLowerCase();return he.filter(_e=>_e.name.toLowerCase().includes(Y))},[he,Te]),Lt=i.useCallback(async Y=>{if(Be===Y){ce(null),Le([]),oe(null),ft(null);return}ce(Y),Le([]),oe(null),ft(null),Ue(!0);try{const _e=await GN(Y,10,r);Le(_e)}catch{Le([])}finally{Ue(!1)}},[Be,r]),Bt=i.useCallback(async Y=>{if(ue===Y){oe(null),ft(null);return}oe(Y),ft(null),tt(!0);try{const _e=await Jl(Y,r);ft(_e)}catch{ft(null)}finally{tt(!1)}},[ue,r]),Gt=i.useCallback(()=>{ce(null),Le([]),oe(null),ft(null)},[]),bt=i.useCallback(()=>{yt.current+=1,Ze(null),gt(null),st(null),Ie(!1)},[]),Ot=i.useCallback(async Y=>{Y.preventDefault(),J("create"),bt();try{await eS(wt.trim()||void 0,r),a("Changes stashed","success"),St("");const _e=await al(r);dt(_e)}catch(_e){a(Se(_e)||"Failed to stash changes","error")}finally{J(null)}},[wt,a,r,bt]),en=i.useCallback(async(Y,_e=!1)=>{J(`apply-${Y}`),bt();try{await tS(Y,_e,r),a(_e?"Stash popped":"Stash applied","success");const ut=await al(r);dt(ut)}catch(ut){a(Se(ut)||"Failed to apply stash","error")}finally{J(null)}},[a,r,bt]),Kt=i.useCallback(async Y=>{if(await o.confirm({title:"Drop Stash",message:`Drop stash@{${Y}}? This cannot be undone.`,danger:!0})){J(`drop-${Y}`),bt();try{await nS(Y,r),a("Stash dropped","success");const ut=await al(r);dt(ut)}catch(ut){a(Se(ut)||"Failed to drop stash","error")}finally{J(null)}}},[a,r,o,bt]),Sn=i.useCallback(async Y=>{if(me===Y){bt();return}const _e=yt.current+1;yt.current=_e,Ze(Y),gt(null),st(null),Ie(!0);try{const ut=await sS(Y,r);if(yt.current!==_e)return;gt(ut)}catch(ut){if(yt.current!==_e)return;gt(null),st(Se(ut)||"Failed to load stash diff")}finally{yt.current===_e&&Ie(!1)}},[me,r,bt]),dn=i.useCallback(async()=>{vt("fetch");try{const Y=await QN(void 0,r);Dt(Y),a(Y.message||"Fetch completed",Y.fetched?"success":"info");const _e=await ji(r);N(_e)}catch(Y){a(Se(Y)||"Fetch failed","error")}finally{vt(null)}},[a,r]),Jt=i.useCallback(async Y=>{vt("pull");try{const _e=await XN(Y,r);if(Dt(_e),_e.conflict)a("Merge conflict detected. Resolve manually.","error");else{const At=Y?.rebase?"Pull --rebase completed":"Pull completed";a(_e.message||At,"success")}const ut=await ji(r);N(ut)}catch(_e){a(Se(_e)||"Pull failed","error")}finally{vt(null)}},[a,r]),tn=i.useCallback(async()=>{vt("push");try{const Y=await ZN(r);Dt(Y),a(Y.message||"Push completed","success");const _e=await ji(r);N(_e)}catch(Y){a(Se(Y)||"Push failed","error")}finally{vt(null)}},[a,r]),Ne=i.useMemo(()=>R.filter(Y=>Y.staged),[R]),W=i.useMemo(()=>R.filter(Y=>!Y.staged),[R]);return e?t.jsx("div",{className:"modal-overlay open git-manager-modal-overlay",...j,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal gm-modal",ref:S,style:h,children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h3",{children:[t.jsx(iu,{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:nn,disabled:w,title:"Refresh",children:t.jsx(ps,{size:14,className:w?"spin":""})}),t.jsx("button",{className:"modal-close",onClick:f,"aria-label":"Close",children:t.jsx(mn,{size:18})})]})]}),t.jsxs("div",{className:"gm-layout",children:[t.jsx("nav",{className:"gm-sidebar",role:"tablist","aria-label":"Git Manager Sections",children:ho.map(Y=>{const _e=Y.icon;return t.jsxs("button",{role:"tab","aria-selected":p===Y.id,className:`gm-nav-item${p===Y.id?" active":""}`,onClick:()=>g(Y.id),children:[t.jsx(_e,{size:16}),t.jsx("span",{className:"gm-nav-label",children:Y.label})]},Y.id)})}),t.jsxs("div",{className:"gm-content",role:"tabpanel",children:[w&&t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:24,className:"spin"}),t.jsx("span",{children:"Loading..."})]}),b&&!w&&t.jsxs("div",{className:"gm-error",children:[t.jsx(Vs,{size:18}),t.jsx("span",{children:b}),t.jsx("button",{className:"btn btn-sm",onClick:nn,children:"Retry"})]}),p==="status"&&!w&&x&&t.jsx(xL,{status:x,copyToClipboard:C}),p==="changes"&&!w&&t.jsx(vL,{status:x,stagedFiles:Ne,unstagedFiles:W,selectedFiles:E,toggleFileSelection:hn,onStageFiles:on,onUnstageFiles:sn,onDiscardChanges:ln,onSelectDiffFile:Qt,selectedDiffTarget:$,changeDiff:H,loadingChangeDiff:se,changeDiffError:M,commitMessage:K,setCommitMessage:U,onCommit:xn,onStageAllAndCommit:qt,committing:A}),p==="commits"&&!w&&t.jsx(yL,{commits:Pe,commitSearch:L,setCommitSearch:xe,selectedCommit:He,commitDiff:je,loadingDiff:fe,onCommitClick:Zt,onLoadMore:ve,canLoadMore:le.length>=re&&re<100,copyToClipboard:C}),p==="branches"&&!w&&t.jsx(wL,{branches:It,branchSearch:Te,setBranchSearch:rt,newBranchName:pe,setNewBranchName:ze,branchBase:ae,setBranchBase:Ve,onCreateBranch:Ke,onCheckoutBranch:at,onDeleteBranch:We,loading:w,allBranches:he,selectedBranch:Be,branchCommits:Re,loadingBranchCommits:ct,expandedBranchCommit:ue,branchCommitDiff:Ee,loadingBranchCommitDiff:ht,onSelectBranch:Lt,onBranchCommitClick:Bt,onCloseBranchDetails:Gt}),p==="worktrees"&&!w&&t.jsx(kL,{worktrees:xt}),p==="stashes"&&!w&&t.jsx(jL,{stashes:Ye,stashMessage:wt,setStashMessage:St,onCreateStash:Ot,onApplyStash:en,onDropStash:Kt,onToggleStashDiff:Sn,stashLoading:Fe,expandedStashIndex:me,stashDiff:be,loadingStashDiff:$t,stashDiffError:ge}),p==="remotes"&&!w&&t.jsx(NL,{status:x,remoteLoading:pt,lastRemoteResult:Ut,onFetch:dn,onPull:Jt,onPush:tn,addToast:a,projectId:r,copyToClipboard:C})]})]})]})}):null}function xL({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(ba,{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(Vs,{size:12}),"Modified"]}):t.jsxs(t.Fragment,{children:[t.jsx(Xn,{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(La,{size:12}),e.ahead]}),e.behind>0&&t.jsxs("span",{className:"gm-behind",title:`${e.behind} commit(s) behind`,children:[t.jsx(Bo,{size:12}),e.behind]}),e.ahead===0&&e.behind===0&&t.jsxs("span",{className:"gm-in-sync",children:[t.jsx(Xn,{size:12}),"Up to date"]})]})]})]})]})}function vL({status:e,stagedFiles:n,unstagedFiles:s,selectedFiles:a,toggleFileSelection:r,onStageFiles:o,onUnstageFiles:l,onDiscardChanges:c,onSelectDiffFile:d,selectedDiffTarget:u,changeDiff:m,loadingChangeDiff:h,changeDiffError:f,commitMessage:p,setCommitMessage:g,onCommit:w,onStageAllAndCommit:v,committing:b}){const y=s.filter(j=>a.has(`unstaged:${j.file}`)),S=n.filter(j=>a.has(`staged:${j.file}`));return t.jsxs("div",{className:"gm-panel","data-testid":"changes-panel",children:[e&&t.jsxs("div",{className:"gm-changes-header",children:[t.jsxs("span",{className:"gm-branch-indicator",children:[t.jsx(Os,{size:14}),e.branch]}),e.isDirty&&t.jsx("span",{className:"gm-dirty-badge",children:"Modified"})]}),t.jsxs("div",{className:"gm-changes-split",children:[t.jsxs("div",{className:"gm-changes-lists",children:[t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Unstaged Changes (",s.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[y.length>0&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn-sm btn-primary",onClick:()=>o(y.map(j=>j.file)),title:"Stage selected",children:[t.jsx($n,{size:12})," Stage (",y.length,")"]}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>c(y.map(j=>j.file)),title:"Discard selected",children:t.jsx(Ho,{size:12})})]}),s.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>o(s.map(j=>j.file)),title:"Stage all",children:"Stage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-unstaged","data-testid":"gm-file-list-unstaged",children:s.length===0?t.jsx("div",{className:"gm-empty",children:"No unstaged changes"}):s.map(j=>{const C=u?.file===j.file&&u.staged===!1;return t.jsxs("div",{className:`gm-file-item${C?" active":""}`,onClick:()=>d(j.file,!1),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(j.file,!1))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:x=>x.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`unstaged:${j.file}`),onChange:()=>r(`unstaged:${j.file}`)})}),t.jsx(ig,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(ag,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:x=>{x.stopPropagation(),o([j.file])},title:"Stage file",children:t.jsx($n,{size:12})})]},`unstaged:${j.file}`)})})]}),t.jsxs("div",{className:"gm-file-section",children:[t.jsxs("div",{className:"gm-file-section-header",children:[t.jsxs("h5",{children:["Staged Changes (",n.length,")"]}),t.jsxs("div",{className:"gm-file-section-actions",children:[S.length>0&&t.jsxs("button",{className:"btn btn-sm",onClick:()=>l(S.map(j=>j.file)),title:"Unstage selected",children:["Unstage (",S.length,")"]}),n.length>0&&t.jsx("button",{className:"btn btn-sm",onClick:()=>l(n.map(j=>j.file)),title:"Unstage all",children:"Unstage All"})]})]}),t.jsx("div",{className:"gm-file-list gm-file-list-staged","data-testid":"gm-file-list-staged",children:n.length===0?t.jsx("div",{className:"gm-empty",children:"No staged changes"}):n.map(j=>{const C=u?.file===j.file&&u.staged===!0;return t.jsxs("div",{className:`gm-file-item staged${C?" active":""}`,onClick:()=>d(j.file,!0),role:"button",tabIndex:0,onKeyDown:x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),d(j.file,!0))},children:[t.jsx("label",{className:"gm-file-checkbox",onClick:x=>x.stopPropagation(),children:t.jsx("input",{type:"checkbox",checked:a.has(`staged:${j.file}`),onChange:()=>r(`staged:${j.file}`)})}),t.jsx(ig,{status:j.status}),t.jsx("span",{className:"gm-file-name",title:j.file,children:t.jsx("bdo",{dir:"ltr",children:j.file})}),t.jsx(ag,{status:j.status}),t.jsx("button",{className:"gm-icon-btn",onClick:x=>{x.stopPropagation(),l([j.file])},title:"Unstage file",children:t.jsx(mn,{size:12})})]},`staged:${j.file}`)})})]})]}),t.jsx("div",{className:"gm-changes-diff",children:u||h||m||f?t.jsxs("div",{className:"gm-diff-section",children:[u&&t.jsxs("div",{className:"gm-diff-target",children:[t.jsx(su,{size:14}),t.jsxs("span",{children:[u.staged?"Staged":"Unstaged"," diff: "]}),t.jsx("code",{children:u.file})]}),h&&t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}),f&&!h&&t.jsx("div",{className:"gm-diff-error",children:f}),m&&!h&&t.jsxs("div",{className:"gm-diff-viewer",children:[m.stat&&t.jsx("pre",{className:"gm-diff-stat",children:m.stat}),t.jsx("pre",{className:"gm-diff-patch",children:m.patch})]})]}):t.jsxs("div",{className:"gm-diff-empty",children:[t.jsx(su,{size:20}),t.jsx("span",{children:"Select a file to view its diff"})]})})]}),t.jsxs("form",{className:"gm-commit-form",onSubmit:w,children:[t.jsx("textarea",{className:"gm-commit-input",placeholder:"Commit message...",value:p,onChange:j=>g(j.target.value),rows:3,disabled:b}),t.jsxs("div",{className:"gm-commit-actions",children:[t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:b||!p.trim()||n.length===0,title:n.length===0?"No staged changes to commit":"Commit staged changes",children:[b?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Da,{size:14}),"Commit"]}),s.length>0&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:v,disabled:b||!p.trim(),title:"Stage all and commit",children:"Stage All & Commit"})]})]})]})}function yL({commits:e,commitSearch:n,setCommitSearch:s,selectedCommit:a,commitDiff:r,loadingDiff:o,onCommitClick:l,onLoadMore:c,canLoadMore:d,copyToClipboard:u}){return t.jsxs("div",{className:"gm-panel","data-testid":"commits-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Commits"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Xi,{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:Tr(m.date)}),m.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),t.jsx("div",{className:"gm-commit-actions-row",children:t.jsx("button",{className:"gm-icon-btn",onClick:()=>u(m.hash,"commit hash"),title:"Copy full hash",children:t.jsx(ba,{size:12})})}),a===m.hash&&t.jsx("div",{className:"gm-commit-diff",children:o?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):r?t.jsxs(t.Fragment,{children:[m.body&&t.jsx("div",{className:"gm-commit-message-full",children:m.body}),r.stat&&t.jsx("pre",{className:"gm-diff-stat",children:r.stat}),t.jsx("pre",{className:"gm-diff-patch",children:r.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]})]},m.hash))}),d&&t.jsx("button",{className:"gm-load-more",onClick:c,children:"Load more commits"})]})}function wL({branches:e,branchSearch:n,setBranchSearch:s,newBranchName:a,setNewBranchName:r,branchBase:o,setBranchBase:l,onCreateBranch:c,onCheckoutBranch:d,onDeleteBranch:u,loading:m,allBranches:h,selectedBranch:f,branchCommits:p,loadingBranchCommits:g,expandedBranchCommit:w,branchCommitDiff:v,loadingBranchCommitDiff:b,onSelectBranch:y,onBranchCommitClick:S,onCloseBranchDetails:j}){return t.jsxs("div",{className:"gm-panel","data-testid":"branches-panel",children:[t.jsxs("div",{className:"gm-panel-header",children:[t.jsx("h4",{children:"Branches"}),t.jsxs("div",{className:"gm-search-box",children:[t.jsx(Xi,{size:14}),t.jsx("input",{type:"text",placeholder:"Filter branches...",value:n,onChange:C=>s(C.target.value)})]})]}),t.jsxs("form",{className:"gm-create-form",onSubmit:c,children:[t.jsx("input",{type:"text",placeholder:"New branch name",value:a,onChange:C=>r(C.target.value),disabled:m}),t.jsxs("select",{value:o,onChange:C=>l(C.target.value),disabled:m,className:"gm-branch-select",children:[t.jsx("option",{value:"",children:"Base: HEAD"}),h.map(C=>t.jsx("option",{value:C.name,children:C.name},C.name))]}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:m||!a.trim(),children:[t.jsx($n,{size:14}),"Create"]})]}),t.jsx("div",{className:"gm-branches-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:n?"No matching branches":"No branches found"}):e.map(C=>t.jsxs("div",{children:[t.jsxs("div",{className:`gm-branch-item${C.isCurrent?" current":""}${f===C.name?" selected":""}`,onClick:()=>y(C.name),children:[t.jsxs("div",{className:"gm-branch-info",children:[t.jsxs("span",{className:"gm-branch-name",children:[C.isCurrent&&t.jsx(ks,{size:14,className:"gm-current-icon"}),C.name]}),C.remote&&t.jsxs("span",{className:"gm-branch-remote",children:["→ ",C.remote]}),C.lastCommitDate&&t.jsx("span",{className:"gm-branch-date",children:Tr(C.lastCommitDate)})]}),t.jsx("div",{className:"gm-branch-actions",children:!C.isCurrent&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:x=>{x.stopPropagation(),d(C.name)},disabled:m,title:"Checkout",children:t.jsx(Os,{size:14})}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:x=>{x.stopPropagation(),u(C.name)},disabled:m,title:"Delete",children:t.jsx(Tn,{size:14})})]})})]}),f===C.name&&t.jsxs("div",{className:"gm-branch-details",children:[t.jsxs("div",{className:"gm-branch-details-header",children:[t.jsxs("span",{className:"gm-branch-details-title",children:[t.jsx(Nr,{size:14}),"Commits on ",C.name]}),t.jsx("button",{className:"gm-icon-btn",onClick:j,title:"Close","data-testid":"close-branch-details",children:t.jsx(mn,{size:14})})]}),g?t.jsxs("div",{className:"gm-branch-details-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading commits..."]}):p.length===0?t.jsx("div",{className:"gm-empty",children:"No commits found"}):t.jsx("div",{className:"gm-branch-commits-list",children:p.map(x=>t.jsxs("div",{className:"gm-branch-commit",children:[t.jsxs("button",{className:"gm-branch-commit-row",onClick:()=>S(x.hash),"data-testid":`branch-commit-${x.shortHash}`,children:[t.jsx("span",{className:"gm-commit-hash",children:x.shortHash}),t.jsx("span",{className:"gm-commit-message",title:x.message,children:x.message}),t.jsxs("div",{className:"gm-commit-meta",children:[t.jsx("span",{children:x.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(x.date)}),x.parents.length>1&&t.jsx("span",{className:"gm-merge-badge",children:"merge"})]})]}),w===x.hash&&t.jsx("div",{className:"gm-commit-diff",children:b?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):v?t.jsxs(t.Fragment,{children:[(x.body||x.message)&&t.jsx("div",{className:"gm-commit-message-full",children:x.body||x.message}),v.stat&&t.jsx("pre",{className:"gm-diff-stat",children:v.stat}),t.jsx("pre",{className:"gm-diff-patch",children:v.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},x.hash))})]})]},C.name))})]})}function kL({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:Ju(n.path)||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 jL({stashes:e,stashMessage:n,setStashMessage:s,onCreateStash:a,onApplyStash:r,onDropStash:o,onToggleStashDiff:l,stashLoading:c,expandedStashIndex:d,stashDiff:u,loadingStashDiff:m,stashDiffError:h}){return t.jsxs("div",{className:"gm-panel","data-testid":"stashes-panel",children:[t.jsx("div",{className:"gm-panel-header",children:t.jsx("h4",{children:"Stashes"})}),t.jsxs("form",{className:"gm-create-form",onSubmit:a,children:[t.jsx("input",{type:"text",placeholder:"Stash message (optional)",value:n,onChange:f=>s(f.target.value),disabled:c!==null}),t.jsxs("button",{type:"submit",className:"btn btn-primary btn-sm",disabled:c!==null,children:[c==="create"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(zo,{size:14}),"Stash"]})]}),t.jsx("div",{className:"gm-stash-list",children:e.length===0?t.jsx("div",{className:"gm-empty",children:"No stashes"}):e.map(f=>t.jsxs("div",{className:"gm-stash-item",children:[t.jsxs("div",{className:"gm-stash-header",children:[t.jsxs("div",{className:"gm-stash-info",children:[t.jsxs("span",{className:"gm-stash-ref",children:["stash@",`{${f.index}}`]}),t.jsx("span",{className:"gm-stash-message",children:f.message}),t.jsxs("div",{className:"gm-stash-meta",children:[f.branch&&t.jsxs("span",{className:"gm-stash-branch",children:[t.jsx(Os,{size:12}),f.branch]}),t.jsx("span",{children:Tr(f.date)})]})]}),t.jsxs("div",{className:"gm-stash-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>l(f.index),disabled:c!==null,children:d===f.index?"Hide":"View"}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>r(f.index,!1),disabled:c!==null,title:"Apply stash (keep)",children:c===`apply-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):"Apply"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>r(f.index,!0),disabled:c!==null,title:"Pop stash (apply and drop)",children:"Pop"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>o(f.index),disabled:c!==null,title:"Drop stash",children:c===`drop-${f.index}`?t.jsx(jt,{size:14,className:"spin"}):t.jsx(Tn,{size:14})})]})]}),d===f.index&&t.jsx("div",{className:"gm-stash-diff",children:m?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading stash diff…"]}):h?t.jsx("div",{className:"gm-diff-error",children:h}):u?t.jsxs("div",{className:"gm-diff-viewer",children:[u.stat&&t.jsx("pre",{className:"gm-diff-stat",children:u.stat}),t.jsx("pre",{className:"gm-diff-patch",children:u.patch})]}):null})]},f.index))})]})}function NL({status:e,remoteLoading:n,lastRemoteResult:s,onFetch:a,onPull:r,onPush:o,addToast:l,projectId:c,copyToClipboard:d}){const u=oe=>{try{return new URL(oe).hostname}catch{return oe.replace(/^git@/,"").split(":")[0]||oe}},[m,h]=i.useState([]),[f,p]=i.useState(!1),[g,w]=i.useState(null),[v,b]=i.useState(""),[y,S]=i.useState(""),[j,C]=i.useState(null),[x,N]=i.useState(""),[R,F]=i.useState(""),[E,_]=i.useState(!1),[K,U]=i.useState(!1),A=i.useRef(null),[T,H]=i.useState([]),[Q,se]=i.useState(!1),[O,M]=i.useState(null),[D,$]=i.useState([]),[k,X]=i.useState(!1),[le,ke]=i.useState(null),He=i.useRef(0),ye=m.find(oe=>oe.name===O);i.useEffect(()=>{(n!==null||f)&&U(!1)},[n,f]),i.useEffect(()=>{if(!K)return;const oe=ft=>{A.current?.contains(ft.target)||U(!1)},Ee=ft=>{ft.key==="Escape"&&U(!1)};return document.addEventListener("mousedown",oe),document.addEventListener("keydown",Ee),()=>{document.removeEventListener("mousedown",oe),document.removeEventListener("keydown",Ee)}},[K]);const[je,ne]=i.useState(null),[fe,Z]=i.useState(null),[re,q]=i.useState(!1),[L,xe]=i.useState(null),[he,B]=i.useState(null),[pe,ze]=i.useState(!1);i.useEffect(()=>{ae()},[]),i.useEffect(()=>{e&&e.ahead>0?Ve():e&&e.ahead===0&&H([])},[e?.ahead]),i.useEffect(()=>{m.length>0&&!O&&M(m[0].name)},[m]),i.useEffect(()=>{O?Te(O):($([]),ke(null))},[O]),i.useEffect(()=>{!O||!s||Te(O)},[O,s]),i.useEffect(()=>{O&&!m.find(oe=>oe.name===O)&&M(m.length>0?m[0].name:null)},[m,O]);const ae=async()=>{p(!0);try{const oe=await $N(c);h(oe)}catch(oe){l(Se(oe)||"Failed to load remotes","error")}finally{p(!1)}},Ve=async()=>{se(!0);try{const oe=await VN(c);H(oe)}catch{H([])}finally{se(!1)}},Te=async oe=>{const Ee=He.current+1;He.current=Ee,X(!0),ke(null);try{const ft=await WN(oe,void 0,10,c);if(He.current!==Ee)return;$(ft)}catch(ft){if(He.current!==Ee)return;ke(Se(ft)||"Failed to load remote commits"),$([])}finally{He.current===Ee&&X(!1)}},rt=li(),Be=async oe=>{if(oe.preventDefault(),!(!v.trim()||!y.trim())){w("add");try{await DN(v.trim(),y.trim(),c),l(`Remote '${v}' added successfully`,"success"),b(""),S(""),_(!1),await ae()}catch(Ee){l(Se(Ee)||"Failed to add remote","error")}finally{w(null)}}},ce=async oe=>{if(await rt.confirm({title:"Remove Remote",message:`Are you sure you want to remove remote '${oe}'?`,danger:!0})){w(`remove-${oe}`);try{await LN(oe,c),l(`Remote '${oe}' removed`,"success"),await ae()}catch(ft){l(Se(ft)||"Failed to remove remote","error")}finally{w(null)}}},Re=async oe=>{if(R.trim()){w(`rename-${oe}`);try{await ON(oe,R.trim(),c),l(`Remote renamed to '${R.trim()}'`,"success"),C(null),F(""),await ae()}catch(Ee){l(Se(Ee)||"Failed to rename remote","error")}finally{w(null)}}},Le=async oe=>{if(x.trim()){w(`url-${oe}`);try{await FN(oe,x.trim(),c),l("Remote URL updated","success"),C(null),N(""),await ae()}catch(Ee){l(Se(Ee)||"Failed to update remote URL","error")}finally{w(null)}}},ct=i.useCallback(async(oe,Ee)=>{if(Ee==="ahead"){if(je===oe){ne(null),Z(null);return}ne(oe),Z(null),q(!0);try{const ft=await Jl(oe);Z(ft)}catch{Z(null)}finally{q(!1)}}else{if(L===oe){xe(null),B(null);return}xe(oe),B(null),ze(!0);try{const ft=await Jl(oe);B(ft)}catch{B(null)}finally{ze(!1)}}},[je,L]),Ue=oe=>{C(`url-${oe.name}`),N(oe.pushUrl||oe.fetchUrl)},ue=oe=>{C(`name-${oe.name}`),F(oe.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:()=>_(!E),disabled:g!==null,title:E?"Cancel":"Add Remote",children:E?t.jsx(mn,{size:14}):t.jsx($n,{size:14})})]}),E&&t.jsxs("form",{className:"gm-remote-form",onSubmit:Be,children:[t.jsx("input",{type:"text",placeholder:"Remote name",value:v,onChange:oe=>b(oe.target.value),disabled:g==="add",className:"input gm-input"}),t.jsx("input",{type:"text",placeholder:"Repository URL",value:y,onChange:oe=>S(oe.target.value),disabled:g==="add",className:"input gm-input gm-input-url"}),t.jsxs("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:!v.trim()||!y.trim()||g==="add",children:[g==="add"?t.jsx(jt,{size:12,className:"spin"}):t.jsx($n,{size:12}),"Add"]})]}),f?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading..."]}):m.length===0?t.jsx("div",{className:"gm-empty",children:"No remotes"}):m.map(oe=>t.jsxs("div",{className:`gm-remote-selector-item${O===oe.name?" selected":""}`,onClick:()=>M(oe.name),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),M(oe.name))},children:[t.jsxs("div",{className:"gm-remote-selector-info",children:[t.jsxs("span",{className:"gm-remote-selector-name",children:[t.jsx("span",{className:"gm-remote-selector-name-text",children:oe.name}),oe.name==="origin"&&t.jsx("span",{className:"gm-remote-default-badge",children:"default"})]}),t.jsx("span",{className:"gm-remote-selector-host",title:oe.fetchUrl,children:u(oe.fetchUrl)})]}),t.jsx("button",{className:"btn btn-icon btn-sm gm-remote-remove-btn",onClick:Ee=>{Ee.stopPropagation(),ce(oe.name)},disabled:g!==null,title:"Remove remote",children:t.jsx(Tn,{size:14})})]},oe.name))]}),t.jsxs("div",{className:"gm-remote-detail","data-testid":"remote-detail-panel",children:[O&&ye?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:O}),e&&(e.ahead>0||e.behind>0)&&t.jsxs("div",{className:"gm-remote-status",children:[e.ahead>0&&t.jsxs("div",{className:"gm-remote-indicator ahead",children:[t.jsx("span",{className:"status-dot status-dot--online","aria-hidden":"true"}),t.jsx(La,{size:14}),e.ahead," to push"]}),e.behind>0&&t.jsxs("div",{className:"gm-remote-indicator behind",children:[t.jsx("span",{className:"status-dot status-dot--pending","aria-hidden":"true"}),t.jsx(Bo,{size:14}),e.behind," to pull"]})]})]}),t.jsxs("div",{className:"gm-remote-actions",children:[t.jsxs("button",{className:"btn btn-primary",onClick:a,disabled:n!==null||f,children:[n==="fetch"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ps,{size:14}),"Fetch"]}),t.jsxs("div",{className:"gm-pull-split",ref:A,children:[t.jsxs("button",{className:"btn btn-primary gm-pull-split-main",onClick:()=>{U(!1),r({rebase:!1})},disabled:n!==null||f,children:[n==="pull"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(ii,{size:14}),"Pull"]}),t.jsx("button",{className:"btn btn-primary btn-icon gm-pull-split-toggle",onClick:()=>U(oe=>!oe),disabled:n!==null||f,"aria-label":"Pull options","aria-haspopup":"menu","aria-expanded":K,children:t.jsx(gn,{size:14})}),K?t.jsxs("div",{className:"gm-pull-menu",role:"menu","aria-label":"Pull options menu",children:[t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!1})},children:"Pull"}),t.jsx("button",{className:"gm-pull-menu-item",role:"menuitem",onClick:()=>{U(!1),r({rebase:!0})},children:"Pull --rebase"})]}):null]}),t.jsxs("button",{className:"btn btn-primary",onClick:o,disabled:n!==null||f,children:[n==="push"?t.jsx(jt,{size:14,className:"spin"}):t.jsx(La,{size:14}),"Push"]})]})]}),t.jsxs("div",{className:"gm-remote-detail-card","data-testid":"remote-detail-card",children:[t.jsxs("div",{className:"gm-remote-detail-urls",children:[t.jsxs("div",{className:"gm-remote-detail-url-row",children:[t.jsx("span",{className:"gm-url-label",children:"Fetch:"}),j===`url-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:x,onChange:oe=>N(oe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Le(O),disabled:g===`url-${O}`,children:g===`url-${O}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ks,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),N("")},title:"Cancel",children:t.jsx(mn,{size:12})})]}):t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"gm-url-value",title:ye.fetchUrl,children:t.jsx("bdo",{dir:"ltr",children:ye.fetchUrl})}),t.jsxs("div",{className:"gm-remote-inline-actions",children:[t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ye.fetchUrl,"fetch URL"),title:"Copy fetch URL",children:t.jsx(ba,{size:14})}),t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>Ue(ye),disabled:g!==null,title:"Edit remote URL",children:t.jsx(Hs,{size:14})})]})]})]}),ye.pushUrl&&ye.pushUrl!==ye.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:ye.pushUrl,children:t.jsx("bdo",{dir:"ltr",children:ye.pushUrl})}),t.jsx("div",{className:"gm-remote-inline-actions",children:t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>d(ye.pushUrl,"push URL"),title:"Copy push URL",children:t.jsx(ba,{size:14})})})]})]}),t.jsx("div",{className:"gm-remote-detail-name-row",children:j===`name-${O}`?t.jsxs("div",{className:"gm-remote-edit",children:[t.jsx("input",{type:"text",value:R,onChange:oe=>F(oe.target.value),className:"input gm-input",autoFocus:!0}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>Re(O),disabled:g===`rename-${O}`,children:g===`rename-${O}`?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ks,{size:12})}),t.jsx("button",{className:"btn btn-sm",onClick:()=>{C(null),F("")},title:"Cancel",children:t.jsx(mn,{size:12})})]}):t.jsx("button",{className:"btn btn-icon btn-sm",onClick:()=>ue(ye),disabled:g!==null,title:"Edit remote name",children:t.jsx(Hs,{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(La,{size:14}),"Commits to Push (",e.ahead,")"]})}),Q?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading..."]}):T.length>0?t.jsx("div",{className:"gm-ahead-commits-list","data-testid":"ahead-commits-list",children:T.map(oe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ct(oe.hash,"ahead"),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),ct(oe.hash,"ahead"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:oe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:oe.message,children:oe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:oe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(oe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:je===oe.hash?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})})]}),je===oe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:re?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):fe?t.jsxs(t.Fragment,{children:[(oe.body||oe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:oe.body||oe.message}),fe.stat&&t.jsx("pre",{className:"gm-diff-stat",children:fe.stat}),t.jsx("pre",{className:"gm-diff-patch",children:fe.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},oe.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(rb,{size:14}),"Recent commits on ",O]})}),k?t.jsxs("div",{className:"gm-loading",children:[t.jsx(jt,{size:14,className:"spin"}),"Loading commits..."]}):le?t.jsxs("div",{className:"gm-error",children:[t.jsx(Vs,{size:14}),le]}):D.length===0?t.jsxs("div",{className:"gm-empty",children:["No commits found on ",O,". Try fetching first."]}):t.jsx("div",{className:"gm-remote-commits-list","data-testid":"remote-commits-list",children:D.map(oe=>t.jsxs("div",{className:"gm-commit-item-compact-wrapper",children:[t.jsxs("div",{className:"gm-commit-item-compact gm-commit-clickable",onClick:()=>ct(oe.hash,"remote"),role:"button",tabIndex:0,onKeyDown:Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),ct(oe.hash,"remote"))},title:"Click to view diff",children:[t.jsx("div",{className:"gm-commit-compact-hash",children:t.jsx("code",{className:"gm-hash",children:oe.shortHash})}),t.jsxs("div",{className:"gm-commit-compact-info",children:[t.jsx("span",{className:"gm-commit-message",title:oe.message,children:oe.message}),t.jsxs("span",{className:"gm-commit-meta",children:[t.jsx("span",{children:oe.author}),t.jsx("span",{children:"•"}),t.jsx("span",{children:Tr(oe.date)})]})]}),t.jsx("span",{className:"gm-commit-expand-icon",children:L===oe.hash?t.jsx(gn,{size:14}):t.jsx(qn,{size:14})})]}),L===oe.hash&&t.jsx("div",{className:"gm-commit-diff gm-commit-diff-compact",children:pe?t.jsxs("div",{className:"gm-diff-loading",children:[t.jsx(jt,{size:16,className:"spin"}),"Loading diff..."]}):he?t.jsxs(t.Fragment,{children:[(oe.body||oe.message)&&t.jsx("div",{className:"gm-commit-message-full",children:oe.body||oe.message}),he.stat&&t.jsx("pre",{className:"gm-diff-stat",children:he.stat}),t.jsx("pre",{className:"gm-diff-patch",children:he.patch})]}):t.jsx("div",{className:"gm-diff-error",children:"Failed to load diff"})})]},oe.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 pr={name:"",description:"",mode:"prompt",phase:"pre-merge",prompt:"",scriptName:"",enabled:!0,defaultOn:!1,modelProvider:"",modelId:""};function SL(e,n){return e&&n?`${e}/${n}`:""}function CL(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 rg(e){switch(e){case"file-text":return xa;case"check-circle":return Xn;case"shield":return Gk;case"zap":return ls;case"eye":return Fr;case"globe":return gc;case"layout-grid":return va;case"puzzle":return Rk;default:return Xn}}function og(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 EL({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState({}),[m,h]=i.useState(!0),[f,p]=i.useState(!0),[g,w]=i.useState("my-steps"),[v,b]=i.useState(null),[y,S]=i.useState(!1),[j,C]=i.useState(!1),[x,N]=i.useState(pr),[R,F]=i.useState(!1),[E,_]=i.useState(!1),[K,U]=i.useState(null),[A,T]=i.useState(null),[H,Q]=i.useState({}),[se,O]=i.useState([]),M=i.useRef(null);zi(M,e,"fusion:workflow-steps-modal-size");const D=i.useCallback(async()=>{try{h(!0);const L=await Ko(a);o(L)}catch(L){s(Se(L)||"Failed to load workflow steps","error")}finally{h(!1)}},[s,a]),$=i.useCallback(async()=>{try{const L=await $o(a);Q(L||{})}catch{}},[a]),k=i.useCallback(async()=>{try{const L=await Ws();O(L.models||[])}catch{}},[]),X=i.useCallback(async()=>{try{p(!0);const[L,xe]=await Promise.all([VS(),WS()]);c(L.templates);const he=Object.fromEntries(xe.templates.map(({pluginId:B,template:pe})=>[pe.id,B]));u(he)}catch(L){s(Se(L)||"Failed to load templates","error")}finally{p(!1)}},[s]);i.useEffect(()=>{e&&(D(),X(),$(),k())},[e,D,X,$,k]);const le=i.useCallback(()=>{C(!0),S(!1),b(null),N(pr)},[]),ke=i.useCallback(()=>{C(!1),S(!0),b(null),N(pr)},[]),He=i.useCallback(L=>{b(L.id),S(!1),N({name:L.name,description:L.description,mode:L.mode||"prompt",phase:L.phase||"pre-merge",prompt:L.prompt,scriptName:L.scriptName||"",enabled:L.enabled,defaultOn:L.defaultOn||!1,modelProvider:L.modelProvider||"",modelId:L.modelId||""})},[]),ye=i.useCallback(()=>{b(null),S(!1),C(!1),N(pr)},[]),je=i.useCallback(async()=>{if(!x.name.trim()||!x.description.trim()){s("Name and description are required","error");return}F(!0);try{const L=x.mode==="prompt"&&x.modelProvider&&x.modelId?{modelProvider:x.modelProvider,modelId:x.modelId}:x.mode==="prompt"?{modelProvider:void 0,modelId:void 0}:{};if(y){const xe={name:x.name.trim(),description:x.description.trim(),mode:x.mode,phase:x.phase,prompt:x.mode==="prompt"&&x.prompt.trim()||void 0,scriptName:x.mode==="script"?x.scriptName.trim():void 0,enabled:x.enabled,defaultOn:x.defaultOn||void 0,...L};await th(xe,a),s("Workflow step created","success")}else v&&(await US(v,{name:x.name.trim(),description:x.description.trim(),mode:x.mode,phase:x.phase,prompt:x.mode==="prompt"?x.prompt:"",scriptName:x.mode==="script"?x.scriptName.trim():void 0,enabled:x.enabled,defaultOn:x.defaultOn,...L},a),s("Workflow step updated","success"));S(!1),b(null),N(pr),await D()}catch(L){s(Se(L)||"Failed to save workflow step","error")}finally{F(!1)}},[x,y,v,s,D]),ne=i.useCallback(async L=>{try{await HS(L,a),s("Workflow step deleted","success"),U(null),v===L&&(b(null),N(pr)),await D()}catch(xe){s(Se(xe)||"Failed to delete workflow step","error")}},[v,s,D]),fe=i.useCallback(async()=>{if(!(!v&&!y)&&x.mode==="prompt"){if(y){if(!x.name.trim()||!x.description.trim()){s("Name and description are required before refining","error");return}F(!0);try{const L=x.modelProvider&&x.modelId?{modelProvider:x.modelProvider,modelId:x.modelId}:{},xe={name:x.name.trim(),description:x.description.trim(),mode:"prompt",prompt:x.prompt.trim()||void 0,enabled:x.enabled,defaultOn:x.defaultOn||void 0,...L},he=await th(xe,a);S(!1),b(he.id),_(!0);const B=await nh(he.id,a);N(pe=>({...pe,prompt:B.prompt})),s("Prompt refined with AI","success"),await D()}catch(L){s(Se(L)||"Failed to refine prompt","error")}finally{F(!1),_(!1)}return}if(v){_(!0);try{const L=await nh(v,a);N(xe=>({...xe,prompt:L.prompt})),s("Prompt refined with AI","success"),await D()}catch(L){s(Se(L)||"Failed to refine prompt","error")}finally{_(!1)}}}},[v,y,x,s,D]),Z=i.useCallback(async L=>{T(L.id);try{await GS(L.id,a),s(`Added ${L.name} workflow step`,"success"),await D(),w("my-steps"),C(!1)}catch(xe){const he=Se(xe);he?.includes("already exists")?s(`A workflow step named '${L.name}' already exists`,"error"):s(he||"Failed to add workflow step from template","error")}finally{T(null)}},[s,D]),re=sa(n);if(!e)return null;const q=y||v!==null;return t.jsx("div",{className:"modal-overlay open",...re,"data-testid":"workflow-step-manager",children:t.jsxs("div",{ref:M,className:"modal workflow-step-manager-modal",role:"dialog","aria-modal":"true","aria-label":"Workflow Steps",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Workflow Steps"}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"wfm-body",children:m?t.jsx("div",{className:"wfm-loading",children:"Loading..."}):t.jsxs(t.Fragment,{children:[!q&&t.jsxs("div",{className:"wfm-tab-row",children:[t.jsxs("button",{className:`btn ${g==="my-steps"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>w("my-steps"),"data-testid":"tab-my-steps",children:[t.jsx(Dy,{size:14}),"My Workflow Steps (",r.length,")"]}),t.jsxs("button",{className:`btn ${g==="templates"?"btn-primary":"btn-secondary"} wfm-tab-btn`,onClick:()=>w("templates"),"data-testid":"tab-templates",children:[t.jsx(va,{size:14}),"Templates (",l.length,")"]})]}),g==="my-steps"&&!q&&!j&&t.jsxs(t.Fragment,{children:[r.length===0&&t.jsx("div",{className:"wfm-empty","data-testid":"empty-state",children:"No workflow steps defined. Create one to get started, or add one from the Templates tab."}),r.length>0&&t.jsx("div",{className:"wfm-step-list",children:r.map(L=>t.jsx("div",{className:"wfm-step-card","data-testid":`workflow-step-${L.id}`,children:t.jsxs("div",{className:"wfm-step-card-top",children:[t.jsxs("div",{className:"wfm-step-card-info",children:[t.jsxs("div",{className:"wfm-step-card-title-row",children:[t.jsx("span",{className:"wfm-step-card-name",children:L.name}),t.jsx("span",{className:`wfm-badge ${L.enabled?"wfm-badge-enabled":"wfm-badge-disabled"}`,children:L.enabled?"Enabled":"Disabled"}),t.jsx("span",{className:`wfm-badge ${(L.mode||"prompt")==="script"?"wfm-badge-script":"wfm-badge-prompt"}`,children:(L.mode||"prompt")==="script"?"Script":"AI Prompt"}),t.jsx("span",{className:`wfm-badge ${(L.phase||"pre-merge")==="post-merge"?"wfm-badge-post-merge":"wfm-badge-pre-merge"}`,children:(L.phase||"pre-merge")==="post-merge"?"Post-merge":"Pre-merge"}),L.defaultOn&&t.jsx("span",{className:"wfm-badge wfm-badge-default-on",children:"Default on"})]}),t.jsx("div",{className:"wfm-step-card-desc",children:L.description})]}),t.jsxs("div",{className:"wfm-step-card-actions",children:[t.jsx("button",{className:"btn-icon",onClick:()=>He(L),title:"Edit","aria-label":`Edit ${L.name}`,children:t.jsx(Hs,{size:14})}),K===L.id?t.jsxs("div",{className:"wfm-delete-confirm",children:[t.jsx("button",{className:"btn-icon wfm-delete-confirm-btn",onClick:()=>ne(L.id),title:"Confirm delete","aria-label":`Confirm delete ${L.name}`,children:t.jsx(ks,{size:14})}),t.jsx("button",{className:"btn-icon",onClick:()=>U(null),title:"Cancel delete","aria-label":"Cancel delete",children:t.jsx(mn,{size:14})})]}):t.jsx("button",{className:"btn-icon",onClick:()=>U(L.id),title:"Delete","aria-label":`Delete ${L.name}`,children:t.jsx(Tn,{size:14})})]})]})},L.id))})]}),g==="templates"&&!q&&!j&&t.jsx(t.Fragment,{children:f?t.jsxs("div",{className:"wfm-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"no-templates-state",children:"No templates available."}):t.jsx("div",{className:"wfm-template-list",children:l.map(L=>{const xe=rg(L.icon),he=og(L.category),B=A===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(xe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:he,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Z(L),disabled:B,"data-testid":`add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{size:12}),"Add"]})})]})]})},L.id)})})}),j&&!q&&t.jsxs("div",{className:"wfm-create-chooser","data-testid":"workflow-step-create-chooser",children:[t.jsx("h3",{className:"wfm-form-title",children:"How would you like to create this workflow step?"}),t.jsx("p",{className:"wfm-create-chooser-hint",children:"Start from a built-in template or create a fully custom workflow step."}),t.jsxs("button",{className:"btn wfm-create-custom-btn",onClick:ke,"data-testid":"create-custom-step",children:[t.jsx($n,{size:14}),"Custom workflow step"]}),f?t.jsxs("div",{className:"wfm-loading","data-testid":"create-chooser-template-loading",children:[t.jsx(jt,{size:24,className:"spin wfm-spinner"}),"Loading built-in templates..."]}):l.length===0?t.jsx("div",{className:"wfm-empty","data-testid":"create-chooser-no-templates",children:"No built-in templates are available right now. You can still create a custom step."}):t.jsx("div",{className:"wfm-template-list","data-testid":"create-chooser-templates",children:l.map(L=>{const xe=rg(L.icon),he=og(L.category),B=A===L.id;return t.jsx("div",{className:"wfm-template-card","data-testid":`chooser-template-${L.id}`,children:t.jsxs("div",{className:"wfm-template-inner",children:[t.jsx("div",{className:"wfm-template-icon",children:t.jsx(xe,{size:20})}),t.jsxs("div",{className:"wfm-template-content",children:[t.jsxs("div",{className:"wfm-template-title-row",children:[t.jsx("span",{className:"wfm-template-name",children:L.name}),t.jsx("span",{className:he,children:L.category}),d[L.id]&&t.jsx("span",{className:"wfm-badge-category wfm-badge-category-plugin",children:d[L.id]})]}),t.jsx("div",{className:"wfm-template-desc",children:L.description}),t.jsx("button",{className:"btn btn-primary wfm-template-add-btn",onClick:()=>Z(L),disabled:B,"data-testid":`chooser-add-template-${L.id}`,children:B?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"spin"}),"Adding..."]}):t.jsxs(t.Fragment,{children:[t.jsx($n,{size:12}),"Add template"]})})]})]})},L.id)})})]}),q&&t.jsxs("div",{className:"wfm-form","data-testid":"workflow-step-form",children:[t.jsx("h3",{className:"wfm-form-title",children:y?"New Workflow Step":"Edit Workflow Step"}),t.jsxs("div",{className:"wfm-form-fields",children:[t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Name"}),t.jsx("input",{type:"text",value:x.name,onChange:L=>N(xe=>({...xe,name:L.target.value})),placeholder:"e.g. Documentation Review","data-testid":"workflow-step-name"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Description"}),t.jsx("textarea",{value:x.description,onChange:L=>N(xe=>({...xe,description:L.target.value})),placeholder:"Brief description of what this step does",rows:2,"data-testid":"workflow-step-description"})]}),t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Execution Mode"}),t.jsxs("div",{className:"wfm-mode-selector","data-testid":"workflow-step-mode-selector",children:[t.jsxs("button",{className:`btn ${x.mode==="prompt"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"prompt",scriptName:""})),"data-testid":"mode-prompt",children:[t.jsx(Zi,{size:14}),"AI Prompt"]}),t.jsxs("button",{className:`btn ${x.mode==="script"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,mode:"script",prompt:"",modelProvider:"",modelId:""})),"data-testid":"mode-script",children:[t.jsx(ea,{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 ${x.phase==="pre-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,phase:"pre-merge"})),"data-testid":"phase-pre-merge",children:"Pre-merge"}),t.jsx("button",{className:`btn ${x.phase==="post-merge"?"btn-primary":"btn-secondary"} wfm-mode-btn`,onClick:()=>N(L=>({...L,phase:"post-merge"})),"data-testid":"phase-post-merge",children:"Post-merge"})]}),t.jsx("div",{className:"wfm-field-hint",children:x.phase==="pre-merge"?"Runs before merge — can block merge on failure":"Runs after merge success — failures are logged but do not block"})]}),x.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:fe,disabled:!x.description.trim()||E,title:"Refine with AI","aria-label":"Refine prompt with AI","data-testid":"refine-btn",children:[E?t.jsx(jt,{size:12,className:"spin"}):t.jsx(ms,{size:12}),t.jsx("span",{children:"Refine with AI"})]})]}),t.jsx("textarea",{value:x.prompt,onChange:L=>N(xe=>({...xe,prompt:L.target.value})),placeholder:"Leave empty to use AI refinement",rows:6,className:"wfm-prompt-textarea","data-testid":"workflow-step-prompt"})]}),x.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"}),x.modelProvider&&x.modelId&&t.jsxs("button",{type:"button",className:"btn-icon wfm-model-clear-btn",onClick:()=>N(L=>({...L,modelProvider:"",modelId:""})),title:"Clear model override (use global default)","data-testid":"clear-model-override",children:[t.jsx(mn,{size:12}),t.jsx("span",{children:"Use default"})]})]}),t.jsx("span",{className:"wfm-model-hint",children:x.modelProvider&&x.modelId?`Using ${x.modelProvider}/${x.modelId}`:"Using global default model"}),t.jsx("div",{"data-testid":"workflow-step-model-select",children:t.jsx(_s,{models:se,value:SL(x.modelProvider,x.modelId),onChange:L=>{const xe=CL(L);N(he=>({...he,modelProvider:xe.provider,modelId:xe.modelId}))},placeholder:"Select a model override…",label:"Model override for this workflow step"})})]}),x.mode==="script"&&t.jsxs("div",{className:"wfm-field",children:[t.jsx("label",{children:"Script"}),Object.keys(H).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:x.scriptName,onChange:L=>N(xe=>({...xe,scriptName:L.target.value})),"data-testid":"workflow-step-script-select",children:[t.jsx("option",{value:"",children:"Select a script…"}),Object.entries(H).map(([L,xe])=>t.jsxs("option",{value:L,children:[L," (",xe,")"]},L))]})]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:x.enabled,onChange:L=>N(xe=>({...xe,enabled:L.target.checked})),"data-testid":"workflow-step-enabled"}),"Enabled (available for selection on new tasks)"]}),t.jsxs("label",{className:"wfm-checkbox-label",children:[t.jsx("input",{type:"checkbox",checked:x.defaultOn,onChange:L=>N(xe=>({...xe,defaultOn:L.target.checked})),"data-testid":"workflow-step-default-on"}),"Default on for new tasks"]}),t.jsxs("div",{className:"wfm-form-actions",children:[t.jsx("button",{className:"btn btn-secondary",onClick:ye,disabled:R,children:"Cancel"}),t.jsx("button",{className:"btn btn-primary",onClick:je,disabled:R||!x.name.trim()||!x.description.trim()||x.mode==="script"&&!x.scriptName.trim(),"data-testid":"save-workflow-step",children:R?"Saving...":y?"Create":"Save"})]})]})]})]})}),!q&&!j&&t.jsx("div",{className:"wfm-footer",children:t.jsxs("button",{className:"btn btn-primary wfm-footer-add-btn",onClick:le,"data-testid":"add-workflow-step",children:[t.jsx($n,{size:14}),"Add Workflow Step"]})})]})})}const _L=36e5,ML=3e5,Gd=[{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 AL(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 RL(e){return typeof e!="number"||!Number.isFinite(e)?_L:Math.max(ML,Math.round(e))}function $8(e){if(Gd.some(s=>s.value===e))return[...Gd];const n={value:e,label:`${AL(e)} (custom)`};return[...Gd,n].sort((s,a)=>s.value-a.value)}const IL=4,TL=5*6e4;function PL(e){const n=RL(e?.heartbeatIntervalMs);return Math.max(n*IL,TL)}function lg(e){const n=Math.floor(e/6e4);if(n<1)return"<1m";const s=Math.floor(n/60),a=n%60;return s>0&&a>0?`${s}h ${a}m`:s>0?`${s}h`:`${a}m`}function $L(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 DL(e){const s=e.metadata?.heartbeatTimerRepair;if(!s||typeof s!="object")return{};const a=s;return{repairedAt:typeof a.repairedAt=="string"?a.repairedAt:void 0,staleAtRepair:typeof a.staleAtRepair=="boolean"?a.staleAtRepair:void 0,staleRepairReason:typeof a.staleRepairReason=="string"?a.staleRepairReason:void 0}}function LL(e){const{state:n,lastHeartbeatAt:s,lastError:a,pauseReason:r,runtimeConfig:o}=e,l=$L(e),c=l||o?.enabled!==!1;if(n==="error")return{label:a??"Error",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!a};if(n==="paused")return{label:r?`Paused: ${r}`:"Paused",icon:t.jsx(Ci,{size:14}),color:"var(--state-paused-text)",stateDerived:!r};if(n==="running"||l&&n==="active")return{label:"Running",icon:t.jsx(Js,{size:14}),color:"var(--state-active-text)",stateDerived:!0};if(!c)return{label:"Heartbeat Disabled",icon:t.jsx(Ci,{size:14}),color:"var(--state-paused-text)",stateDerived:!1};if(!s)return{label:n==="active"?"Starting...":"Idle",icon:t.jsx(Qn,{size:14}),color:"var(--text-secondary)",stateDerived:!1};const d=DL(e);if(d.staleAtRepair&&d.repairedAt){const f=Date.parse(d.repairedAt),p=Date.parse(s);if(Number.isFinite(f)&&Number.isFinite(p)&&p<f)return{label:"Unresponsive",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:d.staleRepairReason??"Heartbeat scheduler repaired a missing timer; waiting for recovery heartbeat"}}const u=new Date(s).getTime(),m=Date.now()-u,h=PL(o);if(m>h){const f=`No heartbeat for ${lg(m)} (threshold: ${lg(h)})`;return{label:"Unresponsive",icon:t.jsx(Js,{size:14}),color:"var(--state-error-text)",stateDerived:!1,reason:f}}return{label:"Healthy",icon:t.jsx(qw,{size:14}),color:"var(--state-active-text)",stateDerived:!1}}function cc({agent:e,size:n=36,className:s}){const[a,r]=i.useState(!1);i.useEffect(()=>{r(!1)},[e.imageUrl]);const o=i.useMemo(()=>{if(!e.imageUrl)return;const l=encodeURIComponent(e.updatedAt??""),c=e.imageUrl.includes("?")?"&":"?";return`${e.imageUrl}${c}t=${l}`},[e.imageUrl,e.updatedAt]);return t.jsx("span",{className:`agent-avatar${s?` ${s}`:""}`,style:{width:`${n}px`,height:`${n}px`},"aria-label":`${e.name} avatar`,children:o&&!a?t.jsx("img",{src:o,alt:`${e.name} avatar`,onError:()=>r(!0)}):e.icon?.trim()?t.jsx("span",{className:"agent-avatar-emoji",style:{fontSize:`calc(${n}px * 0.58)`},"aria-hidden":"true",children:e.icon}):t.jsx(Qn,{size:Math.max(14,Math.round(n*.55)),"aria-hidden":"true"})})}const OL="https://github.com/Runfusion/Fusion/issues/new";function FL(e,n){const s=`[Agent Error] ${n.surface}${n.agentName?` - ${n.agentName}`:""}`,a=["## Agent Error Report","",`- Surface: ${n.surface}`,`- Agent ID: ${n.agentId??"unknown"}`,`- Agent Name: ${n.agentName??"unknown"}`,`- Agent State: ${n.agentState??"unknown"}`,`- Run ID: ${n.runId??"n/a"}`,`- Task ID: ${n.taskId??"n/a"}`,`- Timestamp: ${n.timestamp??new Date().toISOString()}`,"","## Error","```text",e,"```"],r=new URLSearchParams({title:s,body:a.join(`
691
691
  `)});return`${OL}?${r.toString()}`}function zL({open:e,onClose:n,errorText:s,issueContext:a}){const[r,o]=i.useState(!1),l=i.useMemo(()=>FL(s,a),[s,a]);return e?t.jsx("div",{className:"modal-overlay open",onClick:c=>c.target===c.currentTarget&&n(),role:"dialog","aria-modal":"true","aria-label":"Agent error details",children:t.jsxs("div",{className:"modal agent-error-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Vs,{size:16}),"Agent Error Details"]}),t.jsx("button",{className:"modal-close",onClick:n,"aria-label":"Close",children:"×"})]}),t.jsx("div",{className:"agent-error-modal__content",children:t.jsx("pre",{className:"agent-error-modal__error",children:s})}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:()=>{navigator.clipboard.writeText(s).then(()=>{o(!0),setTimeout(()=>o(!1),1500)})},"aria-label":r?"Copied error to clipboard":"Copy error to clipboard",children:[r?t.jsx(ks,{size:14}):t.jsx(ba,{size:14}),r?"Copied":"Copy"]}),t.jsxs("a",{className:"btn btn-sm btn-warning",href:l,target:"_blank",rel:"noreferrer",onClick:c=>{c.preventDefault(),window.open(l,"_blank","noopener,noreferrer")},children:[t.jsx(eb,{size:14}),"Report on GitHub"]})]})]})}):null}function BL({errorText:e,issueContext:n,summaryPrefix:s="Error"}){const[a,r]=i.useState(!1);return t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",className:"agent-error-indicator",onClick:()=>r(!0),"aria-label":"Open error details",children:[t.jsx(Vs,{size:14}),t.jsx("span",{className:"agent-error-indicator__label",children:s})]}),t.jsx(zL,{open:a,onClose:()=>r(!1),errorText:e,issueContext:n})]})}const $l=[{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 UL({isOpen:e,onClose:n,addToast:s,projectId:a}){const[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState(""),[f,p]=i.useState("custom"),[g,w]=i.useState("all"),[v,b]=i.useState(()=>{if(typeof window>"u")return"list";const $=Gn("fn-agent-view",a);return $==="board"||$==="list"?$:"list"});i.useEffect(()=>{const $=Gn("fn-agent-view",a);if($==="board"||$==="list"){b($);return}b("list")},[a]),i.useEffect(()=>{fs("fn-agent-view",v,a)},[a,v]);const[y,S]=i.useState(null),j=i.useRef(null),[C,x]=i.useState(new Set),[N,R]=i.useState(new Map),{confirm:F}=li(),E=i.useMemo(()=>N.size===0?r:r.map($=>{const k=N.get($.id);return k?{...$,state:k}:$}),[r,N]),_=i.useMemo(()=>g!=="all"?E:[...E].sort(($,k)=>{const X=$.state==="paused"?1:0,le=k.state==="paused"?1:0;return X!==le?X-le:(k.updatedAt??"").localeCompare($.updatedAt??"")}),[E,g]),K=i.useCallback(async()=>{c(!0);try{const k=await Ur(g!=="all"?{state:g}:void 0,a);o(k)}catch($){s(`Failed to load agents: ${Se($)}`,"error")}finally{c(!1)}},[g,s,a]);i.useEffect(()=>{e&&K()},[e,K]),i.useEffect(()=>{if(!e)return;const $=setInterval(()=>{K()},3e4);return()=>{clearInterval($)}},[e,K]);const U=async()=>{if(m.trim())try{await n1({name:m.trim(),role:f},a),s(`Agent "${m}" created`,"success"),h(""),u(!1),K()}catch($){s(`Failed to create agent: ${Se($)}`,"error")}},A=async($,k)=>{if(!C.has($)){x(X=>new Set(X).add($)),R(X=>{const le=new Map(X);return le.set($,k),le});try{await i1($,k,a),s(`Agent state updated to ${k}`,"success"),await K(),R(X=>{const le=new Map(X);return le.delete($),le})}catch(X){R(le=>{const ke=new Map(le);return ke.delete($),ke}),s(`Failed to update state: ${Se(X)}`,"error")}finally{x(X=>{const le=new Set(X);return le.delete($),le})}}},T=async($,k)=>{if(await F({title:"Delete Agent",message:`Delete agent "${k}"? This cannot be undone.`,danger:!0}))try{await a1($,a),s(`Agent "${k}" deleted`,"success"),K()}catch(le){s(`Failed to delete agent: ${Se(le)}`,"error")}},H=async($,k)=>{const X=r.find(le=>le.id===$);if(X){if(X.role===k){S(null);return}try{await s1($,{role:k},a),s(`Agent role updated to ${$l.find(le=>le.value===k)?.label??k}`,"success"),S(null),K()}catch(le){s(`Failed to update role: ${Se(le)}`,"error")}}},Q=($,k)=>{$.key==="Escape"&&S(null)},se=$=>$l.find(k=>k.value===$)?.label??$,O=$=>LL($),M=$=>$.color==="var(--state-active-text)"?"active":$.color==="var(--state-paused-text)"?"paused":$.color==="var(--state-error-text)"?"error":"muted",D=($,k)=>$.state==="error"?{title:void 0,label:"Error"}:{title:k.reason??k.label,label:k.stateDerived?null:k.label};return e?t.jsx("div",{className:"modal-overlay open",onClick:$=>$.target===$.currentTarget&&n(),role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"modal modal--wide agent-list-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsxs("h2",{className:"modal-title",children:[t.jsx(Qn,{size:20}),"Agents"]}),t.jsxs("div",{className:"modal-actions",children:[t.jsxs("div",{className:"view-toggle",children:[t.jsx("button",{className:`view-toggle-btn${v==="board"?" active":""}`,onClick:()=>b("board"),title:"Board view","aria-label":"Board view","aria-pressed":v==="board",children:t.jsx(va,{size:16})}),t.jsx("button",{className:`view-toggle-btn${v==="list"?" active":""}`,onClick:()=>b("list"),title:"List view","aria-label":"List view","aria-pressed":v==="list",children:t.jsx(au,{size:16})})]}),t.jsx("button",{className:"btn-icon",onClick:()=>void K(),title:"Refresh",disabled:l,children:t.jsx(ps,{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(ql,{size:14}),t.jsxs("select",{className:"agent-state-filter-select",value:g,onChange:$=>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.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>u(!d),children:[t.jsx($n,{size:16}),d?"Cancel":"New Agent"]})]}),d&&t.jsxs("div",{className:"agent-create-form",children:[t.jsx("input",{type:"text",placeholder:"Agent name...",value:m,onChange:$=>h($.target.value),onKeyDown:$=>$.key==="Enter"&&U(),className:"input",autoFocus:!0}),t.jsx("select",{className:"select",value:f,onChange:$=>p($.target.value),children:$l.map($=>t.jsxs("option",{value:$.value,children:[$.icon," ",$.label]},$.value))}),t.jsx("button",{className:"btn btn-task-create btn-sm",onClick:()=>void U(),children:"Create"})]}),t.jsx("div",{className:v==="board"?"agent-board":"agent-list",children:_.length===0?t.jsxs("div",{className:"agent-empty",children:[t.jsx(Qn,{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"?_.map($=>{const k=O($),X=D($,k),le=M(k);return t.jsxs("div",{className:"agent-board-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-board-header",children:[t.jsx("span",{className:"agent-board-icon",children:t.jsx(cc,{agent:$,size:20})}),t.jsx("span",{className:"agent-board-badge","data-state":$.state,children:$.state}),t.jsx("span",{className:"agent-board-health","data-health":le,title:X.title,children:k.icon})]}),t.jsx("div",{className:"agent-board-name",title:$.name,children:$.name}),t.jsx("div",{className:"agent-board-id",children:$.id}),t.jsxs("div",{className:"agent-board-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Activate",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T($.id,$.name),title:"Delete",children:t.jsx(Tn,{size:14})})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(Ci,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx($i,{size:14})})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Resume",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void T($.id,$.name),title:"Delete",children:t.jsx(Tn,{size:14})})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:t.jsx(Ci,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx($i,{size:14})})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Retry",children:t.jsx(os,{size:14})}),t.jsx("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:t.jsx($i,{size:14})})]})]})]},$.id)}):_.map($=>{const k=O($),X=D($,k),le=M(k);return t.jsxs("div",{className:"agent-card","data-state":$.state,children:[t.jsxs("div",{className:"agent-card-header",children:[t.jsxs("div",{className:"agent-info",children:[y===$.id?t.jsx("select",{ref:j,className:"select agent-role-select",value:$.role,onChange:ke=>void H($.id,ke.target.value),onKeyDown:ke=>Q(ke,$.id),onBlur:()=>S(null),autoFocus:!0,children:$l.map(ke=>t.jsxs("option",{value:ke.value,children:[ke.icon," ",ke.label]},ke.value))}):t.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:()=>S($.id),title:"Click to change role",role:"button",tabIndex:0,onKeyDown:ke=>{(ke.key==="Enter"||ke.key===" ")&&S($.id)},children:t.jsx(cc,{agent:$,size:20})}),t.jsxs("div",{className:"agent-meta",children:[t.jsx("span",{className:"agent-name",children:$.name}),t.jsx("span",{className:"agent-id text-secondary",children:$.id})]})]}),t.jsxs("div",{className:"agent-badges",children:[t.jsx("span",{className:"badge agent-list-state-badge","data-state":$.state,children:$.state}),t.jsxs("span",{className:"badge agent-list-health-badge","data-health":le,title:X.title,children:[k.icon,X.label?` ${X.label}`:""]}),t.jsx("span",{className:"badge text-secondary",children:se($.role)})]})]}),t.jsxs("div",{className:"agent-card-body",children:[$.state==="error"&&$.lastError?t.jsx(BL,{errorText:$.lastError,issueContext:{surface:"AgentListModal list",agentId:$.id,agentName:$.name,agentState:$.state,taskId:$.taskId}}):null,$.taskId&&t.jsxs("div",{className:"agent-task",children:[t.jsx("span",{className:"text-secondary",children:"Working on:"}),t.jsx("span",{className:"badge",children:$.taskId})]}),$.lastHeartbeatAt&&t.jsxs("div",{className:"agent-heartbeat",children:[t.jsx("span",{className:"text-secondary",children:"Last heartbeat:"}),t.jsx("span",{children:new Date($.lastHeartbeatAt).toLocaleString()})]})]}),t.jsxs("div",{className:"agent-card-actions",children:[$.state==="idle"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Activate",children:[t.jsx(os,{size:14})," Start"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T($.id,$.name),title:"Delete",children:[t.jsx(Tn,{size:14})," Delete"]})]}),$.state==="active"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(Ci,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx($i,{size:14})," Stop"]})]}),$.state==="paused"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Resume",children:[t.jsx(os,{size:14})," Resume"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void T($.id,$.name),title:"Delete",children:[t.jsx(Tn,{size:14})," Delete"]})]}),$.state==="running"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Pause",children:[t.jsx(Ci,{size:14})," Pause"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx($i,{size:14})," Stop"]})]}),$.state==="error"&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{className:"btn btn--sm",onClick:()=>void A($.id,"active"),disabled:C.has($.id),title:"Retry",children:[t.jsx(os,{size:14})," Retry"]}),t.jsxs("button",{className:"btn btn--sm btn--danger",onClick:()=>void A($.id,"paused"),disabled:C.has($.id),title:"Stop",children:[t.jsx($i,{size:14})," Stop"]})]})]})]},$.id)})})]})]})}):null}function HL({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),[c,d]=i.useState(null),u=i.useRef(!0);i.useEffect(()=>(u.current=!0,()=>{u.current=!1}),[]);const m=i.useCallback(async()=>{try{const b=await uN();return u.current&&r(b),b}catch(b){return u.current&&d({kind:"error",message:b instanceof Error?b.message:String(b)}),null}},[]);i.useEffect(()=>{m()},[m]);const h=i.useCallback(async()=>{l("testing"),d(null),await m(),u.current&&l(null)},[m]),f=i.useCallback(async b=>{l(b?"enabling":"disabling"),d(null);try{const y=await bN(b);u.current&&d({kind:y.enabled?"enabled":"disabled",restartRequired:y.restartRequired}),n?.(y.enabled),await m()}catch(y){u.current&&d({kind:"error",message:y instanceof Error?y.message:String(y)})}finally{u.current&&l(null)}},[n,m]),p=a?.binary.available??!1,g=a?.enabled??e,w=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(jt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),g?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void f(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void f(!0),disabled:o!==null||!p,title:p?void 0:"`claude` binary not detected on PATH — install Claude CLI first.",children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"claude-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(zn,{provider:"claude-cli",size:"sm"}),t.jsx("strong",{children:"Anthropic — via Claude CLI"}),t.jsx(qL,{status:a,authenticated:e})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:v})]}),t.jsxs("details",{className:"auth-provider-cli-details",children:[t.jsx("summary",{children:"Details"}),t.jsxs("div",{className:"auth-provider-cli-details-body",children:[w,t.jsx(cg,{status:a,authenticated:e}),c&&t.jsx(dg,{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(zn,{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"}),w,t.jsx(cg,{status:a,authenticated:e})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:v}),c&&t.jsx(dg,{action:c})]})}function qL({status:e,authenticated:n}){const s=e?.enabled??n,a=e?.binary.available??!1;return s?t.jsx("span",{className:"auth-status-badge authenticated",children:"✓ Active"}):!a&&e?t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not installed"}):t.jsx("span",{className:"auth-status-badge not-authenticated",children:"✗ Not connected"})}function cg({status:e,authenticated:n}){if(!e)return t.jsxs("small",{className:"settings-muted",children:[t.jsx(jt,{size:10,className:"animate-spin"})," Probing local CLI…"]});const{binary:s,enabled:a,extension:r,ready:o}=e;return s.available?a?r&&r.status!=="ok"?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--warning",children:["⚠ Extension load failed: ",r.reason??r.status]}):o||n?t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--connected",children:["✓ Connected",s.version?` — ${s.version}`:""]}):t.jsx("small",{className:"settings-muted",children:"Enabled. Validating…"}):t.jsxs("small",{className:"settings-muted",children:[t.jsx("code",{children:"claude"})," ",s.version?`(${s.version})`:""," detected",s.binaryPath?` at ${s.binaryPath}`:"",". Click Enable to route AI calls through it."]}):t.jsxs("small",{className:"onboarding-provider-card__status onboarding-provider-card__status--error",children:["✗ ",s.reason??"`claude` not found on PATH"]})}function dg({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 VL({authenticated:e,compact:n=!1,onToggled:s}){const[a,r]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!0);i.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const d=i.useCallback(async()=>{try{const g=await fN();return c.current&&r(g),g}catch{return null}},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async g=>{l(g?"enabling":"disabling");try{const w=await vN(g);s?.(w.enabled),await d()}finally{c.current&&l(null)}},[s,d]),m=a?.enabled??e,h=a?.binary.available??!1,f=t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("testing"),d().finally(()=>{c.current&&l(null)})},disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"})," Testing…"]}):"Test"}),m?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!h,children:o==="enabling"?"Enabling…":"Enable"})]}),p=a?a.binary.available?m?`Connected${a.binary.version?` — ${a.binary.version}`:""}`:"Detected. Click Enable to route calls through Cursor CLI.":a.binary.reason??"`cursor-agent` not found on PATH":"Probing local CLI…";return n?t.jsxs("div",{className:`cursor-cli-provider-card auth-provider-card auth-provider-card--cli${e?" auth-provider-card--authenticated":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(zn,{provider:"cursor-cli",size:"sm"}),t.jsx("strong",{children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:`auth-status-badge ${m?"authenticated":"not-authenticated"}`,children:m?"✓ Active":"✗ Not connected"})]}),t.jsx("div",{className:"auth-provider-cli-actions",children:f})]}),t.jsx("small",{className:"settings-muted",children:p})]}):t.jsxs("div",{className:`cursor-cli-provider-card onboarding-provider-card${e?" onboarding-provider-card--connected":""}`,"data-testid":"cursor-cli-provider-card",children:[t.jsx("div",{className:"onboarding-provider-card__icon",children:t.jsx(zn,{provider:"cursor-cli",size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:"Cursor — via Cursor CLI"}),t.jsx("span",{className:"onboarding-provider-card__description",children:"Route AI calls through your local Cursor agent runtime."}),t.jsx("small",{className:"settings-muted",children:p})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:f})]})}function WL({authenticated:e,onToggled:n,compact:s=!1}){const[a,r]=i.useState(null),[o,l]=i.useState(null),c=i.useRef(!0);i.useEffect(()=>(c.current=!0,()=>{c.current=!1}),[]);const d=i.useCallback(async()=>{const w=await gN();return c.current&&r(w),w},[]);i.useEffect(()=>{d()},[d]);const u=i.useCallback(async w=>{l(w?"enabling":"disabling");try{const v=await yN(w);n?.(v.enabled),await d()}finally{c.current&&l(null)}},[n,d]),m=i.useCallback(async()=>{l("testing");try{await d()}finally{c.current&&l(null)}},[d]),h=a?.enabled??e,f=a?.server.available??!1,p=a?a.server.available?`Server reachable at ${a.server.url}`:`Server unavailable: ${a.server.reason??"not reachable"}`:"Probing llama.cpp server…",g=t.jsxs("div",{className:"auth-provider-cli-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void m(),disabled:o!==null,children:o==="testing"?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:12,className:"animate-spin"}),"Testing…"]}):"Test"}),h?t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void u(!1),disabled:o!==null,children:o==="disabling"?"Disabling…":"Disable"}):t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void u(!0),disabled:o!==null||!f,children:o==="enabling"?"Enabling…":"Enable"})]});return s?t.jsxs("div",{className:`auth-provider-card auth-provider-card--cli llama-cpp-provider-card llama-cpp-provider-card--compact${h?" auth-provider-card--authenticated":""}`,"data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-header",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(zn,{provider:"llama-cpp",size:"sm"}),t.jsx("strong",{children:"llama.cpp — via HTTP server"})]}),g]}),t.jsx("small",{className:`auth-hint llama-cpp-status${a?.ready?" llama-cpp-status--ok":""}`,children:p})]}):t.jsxs("div",{className:"onboarding-provider-card llama-cpp-provider-card llama-cpp-provider-card--full","data-testid":"llama-cpp-provider-card",children:[t.jsxs("div",{className:"auth-provider-info",children:[t.jsx(zn,{provider:"llama-cpp",size:"md"}),t.jsx("strong",{children:"llama.cpp — via HTTP server"})]}),t.jsx("small",{className:`llama-cpp-status${a?.ready?" llama-cpp-status--ok":""}`,children:p}),g]})}function GL(e){const n="([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+|[A-Z0-9]{6,9})",s=new RegExp(`\\b(?:device\\s+code|your\\s+code|code)\\s*(?:is|:)?\\s*${n}\\b`,"i"),a=new RegExp(`\\b(?:enter|use)\\s+${n}\\b`,"i"),r=/\b([A-Z0-9]{2,}(?:-[A-Z0-9]{2,})+)\b/,o=e.match(s);if(o?.[1])return o[1];const l=e.match(a);if(l?.[1])return l[1];const c=e.match(r);return c?.[1]?c[1]:null}function Kd({instructions:e,"data-testid":n}){const[s,a]=i.useState(!1),r=GL(e),o=i.useRef(null),l=i.useCallback(()=>{a(!0),setTimeout(()=>a(!1),2e3)},[]),c=i.useCallback(async()=>{const d=r??e;try{await navigator.clipboard.writeText(d),l()}catch{}},[r,e,l]);return i.useEffect(()=>{const d=o.current===null&&r!==null;if(o.current=r,!d)return;(async()=>{try{await navigator.clipboard.writeText(r),l()}catch{}})()},[r,l]),t.jsx("p",{className:"auth-login-instructions","data-testid":n,children:r?t.jsx(t.Fragment,{children:e.split(r).map((d,u,m)=>t.jsxs("span",{children:[d,u<m.length-1&&t.jsxs("span",{className:"device-code-wrapper",children:[t.jsx("code",{className:"device-code",children:r}),t.jsx("button",{className:"device-code-copy-btn",onClick:c,title:s?"Copied!":"Copy code","aria-label":s?"Copied to clipboard":"Copy device code",type:"button",children:s?t.jsx(ks,{size:12}):t.jsx(ba,{size:12})})]})]},u))}):e})}function KL({value:e,onChange:n,onSubmit:s,prompt:a,placeholder:r,helpText:o,disabled:l=!1,submitLabel:c="Submit code","data-testid":d}){const u=i.useRef(null),m=i.useRef(null),[h,f]=i.useState(!1),p=i.useCallback(()=>{if(typeof window>"u"||typeof window.matchMedia!="function")return!1;const v=window.matchMedia("(max-width: 768px)").matches,b=window.matchMedia("(pointer: coarse)").matches;return v||b},[]),g=i.useCallback(()=>typeof window>"u"||typeof window.matchMedia!="function"||window.matchMedia("(prefers-reduced-motion: reduce)").matches?"auto":"smooth",[]),w=i.useCallback(()=>{if(!p())return;const v=m.current??u.current;if(!v||typeof v.scrollIntoView!="function")return;const b=g();requestAnimationFrame(()=>{v.scrollIntoView({block:"center",behavior:b,inline:"nearest"}),window.setTimeout(()=>{v.scrollIntoView({block:"center",behavior:b,inline:"nearest"})},120)})},[g,p]);return i.useEffect(()=>{if(!h||!p())return;w();const v=window.visualViewport;if(!v)return;const b=()=>{document.activeElement===m.current&&w()};return v.addEventListener("resize",b),v.addEventListener("scroll",b),()=>{v.removeEventListener("resize",b),v.removeEventListener("scroll",b)}},[h,w,p]),t.jsxs("div",{ref:u,className:"oauth-manual-code","data-testid":d,children:[t.jsx("p",{className:"oauth-manual-code__prompt",children:a}),t.jsx("textarea",{ref:m,className:"form-input oauth-manual-code__input",value:e,onChange:v=>n(v.target.value),onFocus:()=>{f(!0),w()},onBlur:()=>f(!1),placeholder:r,rows:3,spellCheck:!1,disabled:l}),t.jsx("div",{className:"oauth-manual-code__actions",children:t.jsx("button",{type:"button",className:"btn btn-sm",onClick:s,disabled:l,children:c})}),o&&t.jsx("p",{className:"oauth-manual-code__help",children:o})]})}const JL=new Set(["anthropic","claude-cli","pi-claude-cli","openai","openai-codex","google","gemini","google-antigravity","antigravity","google-vertex","vertex","google-cloud-code","cloud-code","google-gemini-cli","google-generative-ai","ollama","github","github-copilot","openrouter","minimax","minimax-cn","zai","kimi","moonshot","kimi-coding","bedrock","amazon-bedrock","xai","grok","opencode","opencode-go","qwen","qwen-ai","qwen-coder","alibaba","tongyi","lmstudio","lm-studio","huggingface","hugging-face","hf","mistral","mistral-ai","azure","azure-openai","azure-openai-responses","fireworks","fireworks-ai","fireworksai","cerebras","groq","vercel","vercel-ai-gateway","hermes","hermes-agent","hermesagent","openclaw","open-claw","paperclip","paperclipai","paperclip-ai"]),YL=/^[a-z][a-z0-9-]*$/,ug=["openai-completions","openai-responses","anthropic-messages","google-generative-ai"];function mg(){return{id:"",name:"",reasoning:!1}}function QL({initialConfig:e,onSave:n,onCancel:s,saving:a=!1,error:r}){const o=!!e,[l,c]=i.useState(e?.id??""),[d,u]=i.useState(e?.name??""),[m,h]=i.useState(e?.baseUrl??""),[f,p]=i.useState(e?.api??"openai-completions"),[g,w]=i.useState(e?.apiKey??""),[v,b]=i.useState(e?.models?.length?e.models:[mg()]),[y,S]=i.useState(null),j=v.length>1,C=i.useMemo(()=>y??r??null,[y,r]);function x(E,_){b(K=>K.map((U,A)=>A===E?{...U,..._}:U))}function N(E){b(_=>_.length<=1?_:_.filter((K,U)=>U!==E))}function R(){if(!l.trim())return"Provider ID is required.";if(!YL.test(l.trim()))return"Provider ID must be kebab-case.";if(!o&&JL.has(l.trim()))return"Provider ID conflicts with a built-in provider.";if(!m.trim())return"Base URL is required.";try{const E=new URL(m.trim());if(E.protocol!=="http:"&&E.protocol!=="https:")return"Base URL must use http or https."}catch{return"Base URL must be a valid URL."}return ug.includes(f)?v.length===0?"At least one model is required.":v.some(E=>!E.id?.trim())?"Each model must have a model ID.":null:"API type is required."}async function F(E){E.preventDefault();const _=R();S(_),!_&&await n({id:l.trim(),name:d.trim()||void 0,baseUrl:m.trim(),api:f,apiKey:g.trim()||void 0,models:v.map(K=>({id:K.id.trim(),name:K.name?.trim()||void 0,reasoning:!!K.reasoning,contextWindow:K.contextWindow,maxTokens:K.maxTokens}))})}return t.jsxs("form",{onSubmit:F,className:"custom-provider-form","aria-label":"custom-provider-form",children:[t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-id",children:"Provider ID"}),t.jsx("input",{id:"custom-provider-id",className:"input",value:l,onChange:E=>c(E.target.value),disabled:o||a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-name",children:"Display Name"}),t.jsx("input",{id:"custom-provider-name",className:"input",value:d,onChange:E=>u(E.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-base-url",children:"Base URL"}),t.jsx("input",{id:"custom-provider-base-url",className:"input",value:m,onChange:E=>h(E.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api",children:"API Type"}),t.jsx("select",{id:"custom-provider-api",className:"select",value:f,onChange:E=>p(E.target.value),disabled:a,children:ug.map(E=>t.jsx("option",{value:E,children:E},E))})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{htmlFor:"custom-provider-api-key",children:"API Key"}),t.jsx("input",{id:"custom-provider-api-key",className:"input",placeholder:"sk-..., MY_API_KEY, or !command",value:g,onChange:E=>w(E.target.value),disabled:a})]}),t.jsxs("div",{className:"form-group custom-provider-form__group",children:[t.jsx("label",{children:"Models"}),t.jsx("div",{className:"custom-provider-form__models",children:v.map((E,_)=>t.jsxs("div",{className:"custom-provider-form__model-row",children:[t.jsx("input",{className:"input","aria-label":`Model ID ${_+1}`,placeholder:"Model ID",value:E.id,onChange:K=>x(_,{id:K.target.value}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Model name ${_+1}`,placeholder:"Display name",value:E.name??"",onChange:K=>x(_,{name:K.target.value}),disabled:a}),t.jsxs("label",{className:"checkbox-label custom-provider-form__toggle",children:[t.jsx("input",{type:"checkbox",checked:!!E.reasoning,onChange:K=>x(_,{reasoning:K.target.checked}),disabled:a}),"Reasoning"]}),t.jsx("input",{className:"input","aria-label":`Context window ${_+1}`,placeholder:"Context window",type:"number",value:E.contextWindow??"",onChange:K=>x(_,{contextWindow:K.target.value?Number(K.target.value):void 0}),disabled:a}),t.jsx("input",{className:"input","aria-label":`Max tokens ${_+1}`,placeholder:"Max tokens",type:"number",value:E.maxTokens??"",onChange:K=>x(_,{maxTokens:K.target.value?Number(K.target.value):void 0}),disabled:a}),t.jsx("button",{type:"button",className:"btn btn-icon btn-sm",onClick:()=>N(_),disabled:a||!j,"aria-label":`Remove model ${_+1}`,children:"×"})]},`${_}-model`))}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>b(E=>[...E,mg()]),disabled:a,children:"+ Add model"})]}),C?t.jsx("div",{className:"form-error",children:C}):null,t.jsxs("div",{className:"custom-provider-form__actions",children:[s?t.jsx("button",{type:"button",className:"btn",onClick:s,disabled:a,children:"Cancel"}):null,t.jsx("button",{type:"submit",className:"btn btn-primary",disabled:a,children:a?"Saving...":"Save Provider"})]})]})}const XL=new Set(["google-antigravity","antigravity","google-gemini-cli"]);function ZL(e){return!XL.has(e)}function hg(e){return e.filter(n=>ZL(n.id))}const Fv={host:"web",activeProfileId:null,profiles:[]},zv=i.createContext({shellApi:null,state:Fv,ready:!0,openConnectionManagerSignal:0});function eO({children:e}){const n=i.useMemo(()=>typeof window<"u"?window.fusionShell??null:null,[]),[s,a]=i.useState(Fv),[r,o]=i.useState(!n),[l,c]=i.useState(0);return i.useEffect(()=>{if(!n)return;let d=!1;n.getState().then(h=>{d||(a(h),o(!0))});const u=n.subscribe(h=>{a(h)}),m=()=>{c(h=>h+1)};return window.addEventListener("shell:open-connection-manager",m),()=>{d=!0,u(),window.removeEventListener("shell:open-connection-manager",m)}},[n]),t.jsx(zv.Provider,{value:{shellApi:n,state:s,ready:r,openConnectionManagerSignal:l},children:e})}function tO(){return i.useContext(zv)}const nO={host:"web",activeProfileId:null,profiles:[]};function sO(e){if(!e)return nO;const n=Array.isArray(e.profiles)?e.profiles.filter(a=>!!(a&&a.id&&a.serverUrl)):[],s=e.activeProfileId&&n.some(a=>a.id===e.activeProfileId)?e.activeProfileId:null;return{...e,activeProfileId:s,profiles:n}}function Cm(e){return new Error(`${e} is only available in native shell mode`)}async function iO(e,n){if(!e)throw Cm("Saving connection profiles");return e.saveProfile(n)}async function aO(e,n){if(!e)throw Cm("Deleting connection profiles");await e.deleteProfile(n)}async function rO(e,n){if(!e)throw Cm("Switching connection profiles");return e.setActiveProfile(n)}function Bv(){const e=tO(),n=i.useMemo(()=>sO(e.state),[e.state]),s=i.useCallback(o=>iO(e.shellApi,o),[e.shellApi]),a=i.useCallback(o=>aO(e.shellApi,o),[e.shellApi]),r=i.useCallback(o=>rO(e.shellApi,o),[e.shellApi]);return{...e,state:n,saveProfile:s,removeProfile:a,setActiveProfile:r}}const Wa="fusion_model_onboarding_state",Pr=[],$r=[],dc=!1,uc=!1,Dr={},oO=void 0,ua=["ai-setup","github","project-setup","first-task"],lO={"ai-setup":"AI Setup",github:"GitHub","project-setup":"Project","first-task":"First Task",complete:"Complete"};function ri(){if(typeof window>"u")return null;try{const e=localStorage.getItem(Wa);if(!e)return null;const n=JSON.parse(e);return n&&typeof n=="object"&&"currentStep"in n&&typeof n.currentStep=="string"?cO(n):null}catch{return null}}function cO(e){const n=e.postOnboardingDismissedAt??oO;return{...e,completedSteps:e.completedSteps??Pr,skippedSteps:e.skippedSteps??$r,dismissed:e.dismissed??dc,completed:e.completed??uc,stepData:e.stepData??Dr,...n?{postOnboardingDismissedAt:n}:{}}}function Dl(e,n){if(!(typeof window>"u")){if(!n){const s={currentStep:e,updatedAt:new Date().toISOString(),completedSteps:Pr,skippedSteps:$r,dismissed:dc,completed:uc,stepData:Dr};try{localStorage.setItem(Wa,JSON.stringify(s))}catch{}return}try{const s=ri(),a=new Date().toISOString(),r=n.completed??uc;let o=n.dismissed??dc;r&&(o=!1);const l=n.completedSteps??s?.completedSteps??Pr,c=n.skippedSteps??s?.skippedSteps??$r,d={...s?.stepData??Dr};if(n.stepData)for(const[m,h]of Object.entries(n.stepData))h!==void 0&&(d[m]={...d[m]??{},...h});const u={currentStep:e,updatedAt:a,completedSteps:l,skippedSteps:c,dismissed:o,completed:r,stepData:d};localStorage.setItem(Wa,JSON.stringify(u))}catch{}}}function dO(e){if(!(typeof window>"u"))try{const n=ri(),s=new Date().toISOString();if(!n){const o={currentStep:e,updatedAt:s,completedSteps:Pr,skippedSteps:[e],dismissed:dc,completed:uc,stepData:Dr};localStorage.setItem(Wa,JSON.stringify(o));return}const a=n.skippedSteps.includes(e)?n.skippedSteps:[...n.skippedSteps,e],r={...n,skippedSteps:a,completedSteps:n.completedSteps.filter(o=>o!==e),updatedAt:s};localStorage.setItem(Wa,JSON.stringify(r))}catch{}}function pg(){if(!(typeof window>"u"))try{const e=ri(),n=new Date().toISOString(),s=e?{...e,completedAt:n,completed:!0,dismissed:!1,updatedAt:n}:{currentStep:"complete",updatedAt:n,completedAt:n,completedSteps:Pr,skippedSteps:$r,dismissed:!1,completed:!0,stepData:Dr};localStorage.setItem(Wa,JSON.stringify(s))}catch{}}function Lr(){const e=ri();return e?e.completed===!0?!0:typeof e.completedAt=="string"&&e.completedAt.length>0:!1}function uO(){if(!(typeof window>"u"))try{const e=ri(),n=new Date().toISOString(),s=e?{...e,updatedAt:n,postOnboardingDismissedAt:n}:{currentStep:"complete",updatedAt:n,completedSteps:Pr,skippedSteps:$r,dismissed:!1,completed:!1,stepData:Dr,postOnboardingDismissedAt:n};localStorage.setItem(Wa,JSON.stringify(s))}catch{}}function Uv(){const e=ri();return e?typeof e.postOnboardingDismissedAt=="string"&&e.postOnboardingDismissedAt.length>0:!1}function mO(){const e=ri();return!e||Lr()?!1:e.currentStep!=="complete"}function hO(){const e=ri();if(!e||Lr()||e.currentStep==="complete")return null;const n=e.currentStep,s=lO[n]??gO(e.currentStep);return{currentStep:e.currentStep,label:s,completedSteps:e.completedSteps}}function pO(){const e=ri();return e?e.skippedSteps:$r}function fO(e){const n=ri();return!n||!n.stepData?null:n.stepData[e]??null}function gO(e){return e.replace(/[-_]/g," ").replace(/\b\w/g,n=>n.toUpperCase())}const Hv="fusion_onboarding_events",fg="fusion_onboarding_session_id",bO=200,xO=50;function pi(e,n={}){if(!(typeof window>"u"))try{const s=yO(),a=jO(n.step),r={type:e,timestamp:new Date().toISOString(),...a?{step:a}:{},metadata:n,sessionId:vO()},o=kO([...s,r]);wO(o)}catch{}}function vO(){if(typeof window>"u")return"server-session";try{const e=sessionStorage.getItem(fg);if(e)return e;const n=gg();return sessionStorage.setItem(fg,n),n}catch{return gg()}}function gg(){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?crypto.randomUUID():`onboarding-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,12)}`}function yO(){try{const e=localStorage.getItem(Hv);if(!e)return[];const n=JSON.parse(e);return Array.isArray(n)?n.filter(NO):[]}catch{return[]}}function wO(e){try{localStorage.setItem(Hv,JSON.stringify(e))}catch{}}function kO(e){const n=[...e];for(;n.length>bO;)n.splice(0,xO);return n}function jO(e){if(e==="ai-setup"||e==="github"||e==="first-task"||e==="complete")return e}function NO(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 SO=e=>({id:e.id,name:e.name,baseUrl:e.baseUrl,api:"api"in e?e.api:e.apiType==="anthropic-compatible"?"anthropic-messages":"openai-responses",apiKey:e.apiKey,models:e.models?.map(n=>({id:n.id,name:n.name}))??[]}),CO={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"}}},qv={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:"..."}},EO={pattern:/^.{8,}$/,hint:"At least 8 characters",example:"..."},bg={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"},_O=e=>`After you sign in with ${e}, the browser will try to redirect to a localhost address that this dashboard can't reach. The redirect tab will look like it failed. Before that happens, copy the full URL from the browser address bar — you'll paste it back here to finish login. Continue?`;function Tu(e){if(bg[e])return bg[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 Jd=["anthropic","openai","google","gemini","ollama"],MO=["anthropic","claude-cli","droid-cli","cursor-cli","llama-cpp","openai-codex","gemini","minimax","kimi","zai"],AO={anthropic:"anthropic","claude-cli":"claude-cli","droid-cli":"droid-cli","llama-cpp":"llama-cpp","openai-codex":"openai-codex",google:"gemini",gemini:"gemini",minimax:"minimax",kimi:"kimi",moonshot:"kimi","kimi-coding":"kimi",zai:"zai"},RO={gemini:["google","gemini"],kimi:["kimi","moonshot","kimi-coding"]};function Pu(e){return AO[e]??e}function xg(e){const n=Pu(e),s=MO.indexOf(n);return s===-1?Number.POSITIVE_INFINITY:s}function vg(e,n){if(e.authenticated!==n.authenticated)return e.authenticated?-1:1;const s=xg(e.id),a=xg(n.id);if(s!==a)return s-a;const r=Pu(e.id),o=Pu(n.id);if(r!==o)return r.localeCompare(o);const l=RO[r];if(l){const d=l.indexOf(e.id),u=l.indexOf(n.id);if(d!==u)return(d===-1?Number.POSITIVE_INFINITY:d)-(u===-1?Number.POSITIVE_INFINITY:u)}const c=e.name.localeCompare(n.name);return c!==0?c:e.id.localeCompare(n.id)}function IO(e,n){const s=n.trim();if(!s)return"API key is required";const a=qv[e]??EO;return a.pattern.test(s)?null:`${Tu(e)} keys should follow this format: ${a.hint} (e.g. ${a.example})`}const Vv={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"},TO={description:"AI provider — connect to start using AI models",apiKeyInfo:Vv};function $u(e){return CO[e]??TO}function PO(e){return $u(e.id).apiKeyInfo??Vv}function $O({items:e}){return e.some(s=>s.status!=="connected")?t.jsxs("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:[t.jsx("p",{className:"onboarding-readiness-header",children:"Setup Summary"}),e.map(s=>{const a=s.status==="connected"?"✓":s.status==="missing"?"⚠":"○";return t.jsxs("div",{className:`onboarding-readiness-item onboarding-readiness-item--${s.status}`,"data-status":s.status,children:[t.jsx("span",{className:"onboarding-readiness-icon","aria-hidden":"true",children:a}),t.jsxs("span",{className:"onboarding-readiness-content",children:[t.jsx("span",{className:"onboarding-readiness-label",children:s.label}),s.detail&&t.jsx("span",{className:"onboarding-readiness-detail",children:s.detail})]})]},s.label)})]}):t.jsx("div",{className:"onboarding-readiness-summary","data-testid":"readiness-summary",role:"status",children:t.jsx("p",{className:"onboarding-readiness-all-connected",children:"✓ All integrations connected"})})}function DO({provider:e,apiKeyInfo:n,inputValue:s,isSaving:a,error:r,success:o,isConnected:l,onInputChange:c,onSave:d,onClear:u}){const m=`onboarding-apikey-input-${e.id}`,h=a||!s.trim(),f=qv[e.id],p=`input onboarding-apikey-input${r?" onboarding-apikey-input--error":""}${o?" onboarding-apikey-input--success":""}`,g=t.jsxs(t.Fragment,{children:[f&&t.jsxs("small",{className:"onboarding-apikey-hint",children:["Format: ",f.hint]}),t.jsx("p",{className:"onboarding-apikey-instructions",children:n.setupInstructions}),n.dashboardUrl&&t.jsx("a",{href:n.dashboardUrl,target:"_blank",rel:"noreferrer",className:"onboarding-apikey-dashboard-link",children:"Get your API key →"}),t.jsx("p",{className:"onboarding-apikey-usage",children:n.usageDescription})]});return l?t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsxs("div",{className:"onboarding-apikey-connected-header",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:n.fieldLabel}),t.jsx("span",{className:"auth-status-badge connected",children:"✓ API key saved"})]}),t.jsx("button",{className:"btn btn-sm",onClick:()=>u(e.id),disabled:a,children:a?"Removing…":"Remove Key"}),t.jsx(fi,{summary:"Advanced setup details",children:g}),r&&t.jsx("small",{className:"field-error",children:r})]}):t.jsxs("div",{className:"onboarding-apikey-form","data-testid":`onboarding-apikey-form-${e.id}`,children:[t.jsx("label",{htmlFor:m,className:"onboarding-apikey-field-label",children:n.fieldLabel}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("input",{id:m,type:"password",className:p,placeholder:n.inputPlaceholder??"Enter API key",value:s,onChange:w=>c(e.id,w.target.value),onKeyDown:w=>{w.key==="Enter"&&d(e.id,s)},"data-testid":m}),t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>d(e.id,s),disabled:h,"data-testid":`onboarding-apikey-save-${e.id}`,children:a?"Saving…":"Save"})]}),r&&t.jsx("small",{className:"field-error",children:r}),o&&!r&&t.jsx("small",{className:"onboarding-apikey-success","data-testid":`onboarding-apikey-success-${e.id}`,children:o}),t.jsx(fi,{summary:"Advanced setup details",children:g})]})}const LO=150;function OO({onComplete:e,addToast:n,projectId:s,onOpenSetupWizard:a,onOpenNewTask:r,onOpenGitHubImport:o,firstCreatedTask:l,onViewTask:c}){const{confirm:d}=li(),u=ri(),m=u?.currentStep,h=m==="complete"?"ai-setup":ua.includes(m)?m:"ai-setup",f=u?.completedSteps??[],p=u?.skippedSteps??pO(),[g,w]=i.useState(!0),[v,b]=i.useState(h),[y,S]=i.useState(f),[j,C]=i.useState(p),[x,N]=i.useState(!1),[R,F]=i.useState(""),[E,_]=i.useState(!1),[K,U]=i.useState(null),[A,T]=i.useState(null),[H,Q]=i.useState([]),[se,O]=i.useState(void 0),[M,D]=i.useState(!0),[$,k]=i.useState(null),[X,le]=i.useState({}),[ke,He]=i.useState({}),[ye,je]=i.useState({}),[ne,fe]=i.useState(null),[Z,re]=i.useState([]),[q,L]=i.useState(""),[xe,he]=i.useState(!1),[B,pe]=i.useState({}),[ze,ae]=i.useState({}),[Ve,Te]=i.useState({}),[rt,Be]=i.useState([]),[ce,Re]=i.useState(!1),[Le,ct]=i.useState(!1),[Ue,ue]=i.useState(),[oe,Ee]=i.useState("Remote Server"),[ft,ht]=i.useState(""),[tt,xt]=i.useState(""),[Me,Ye]=i.useState(!1),[dt,wt]=i.useState(null),St=i.useRef({}),Fe=i.useRef(null),J=i.useRef(null),me=i.useRef(null),[Ze,be]=i.useState({}),[gt,$t]=i.useState(()=>ri()?.stepData?.github?.skipped===!0),Ie=i.useRef(0),ge=i.useRef(l),{shellApi:st,state:yt}=Bv(),pt=i.useRef(!1),vt=u?.currentStep,Ut=!!u&&u.currentStep!=="complete";zi(J,g,"fusion:model-onboarding-modal-size"),i.useEffect(()=>{const P=Fe.current;P&&(P.scrollTop=0)},[v]);const[Dt,nn]=i.useState(()=>ri()?.stepData?.["ai-setup"]?.skippedProviders??{}),on=[{key:"ai-setup",label:"AI Setup"},{key:"github",label:"GitHub"},{key:"project-setup",label:"Project"},{key:"first-task",label:"First Task"}],sn=on.findIndex(P=>P.key===v),ln=v==="complete"?on.length:sn;i.useEffect(()=>{v!=="complete"&&Dl(v,{completedSteps:y,skippedSteps:j})},[v,y,j]),i.useEffect(()=>{pt.current||(pt.current=!0,pi("onboarding:wizard-opened",{source:Ut?"resume":"initial",resumedFromStep:vt}))},[Ut,vt]),i.useEffect(()=>{const P=ge.current!=null,Ce=l!=null;!P&&Ce&&N(!0),Ce||N(!1),ge.current=l},[l]);const xn=i.useRef(h);i.useEffect(()=>{if(xn.current==="ai-setup"&&v!=="ai-setup"&&!H.some(Ce=>Ce.id!=="github"&&Ce.authenticated)){const Ce={};for(const qe of H)qe.id!=="github"&&!qe.authenticated&&!Dt[qe.id]&&(Ce[qe.id]=!0);if(Object.keys(Ce).length>0){const qe={...Dt,...Ce};nn(qe),Dl(v,{stepData:{"ai-setup":{skippedProviders:qe}}})}}xn.current=v},[v,H,Dt]);const qt=i.useCallback(async()=>{try{const{providers:P,ghCli:Ce}=await Po(),qe=hg(P);Q(qe),O(Ce),le(et=>{const mt={};for(const[Nt,Pt]of Object.entries(et)){const an=qe.find(Cn=>Cn.id===Nt);an&&!an.authenticated&&an.loginInProgress&&(mt[Nt]=Pt)}return Object.keys(mt).length===Object.keys(et).length?et:mt}),be(et=>{let mt=!1;const Nt={...et};for(const[Pt,an]of Object.entries(et)){if(an!=="pending")continue;qe.find(ie=>ie.id===Pt)?.loginInProgress||(delete Nt[Pt],mt=!0)}return mt?Nt:et}),nn(et=>{const mt={...et};for(const Nt of qe)Nt.authenticated&&mt[Nt.id]&&delete mt[Nt.id];return Object.keys(mt).length===Object.keys(et).length?et:mt})}catch{}},[]),Qt=i.useCallback(async()=>{try{const P=await wN();Be((P.providers??[]).map(SO))}catch{}},[]),hn=i.useCallback(async P=>{ct(!0),ue(void 0);try{await jN(P),await Qt(),await Ws().then(Ce=>re(Ce.models??[])),Re(!1)}catch(Ce){ue(Se(Ce)||"Failed to create custom provider")}finally{ct(!1)}},[Qt]),Zt=i.useRef(!1);i.useEffect(()=>{v==="ai-setup"&&Qt(),Zt.current&&qt(),Zt.current=v!=="ai-setup"},[v,qt,Qt]),i.useEffect(()=>{if(!H.some(qe=>qe.loginInProgress))return;const Ce=setInterval(()=>{qt()},2e3);return()=>clearInterval(Ce)},[H,qt]);const ve=H.find(P=>P.id==="github"),Pe=!!ve,Ke=ve?.authenticated??!1,at=ve?.loginInProgress??!1,We=se?.authenticated??!1,It=Ke||We,Lt=!Ke&&We,Bt=i.useCallback(P=>{if(P.authenticated)return"connected";const Ce=Ze?.[P.id];return Ce==="timeout"||Ce==="failed"?"retry":Dt[P.id]?"skipped":"not-connected"},[Ze,Dt]);function Gt({status:P}){const Ce={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:qe,className:et}=Ce[P];return t.jsx("span",{"data-testid":"provider-status-badge",className:et,"data-status":P,children:qe})}const bt=i.useCallback(()=>{if(It)return"connected";const P=Ze.github;return P==="pending"?"pending":P==="failed"||P==="timeout"?"failed":gt?"skipped":"not-connected"},[It,Ze,gt]);function Ot({status:P}){const Ce={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:qe,className:et}=Ce[P];return t.jsx("span",{"data-testid":"github-status-badge",className:et,"data-status":P,children:qe})}const en=i.useCallback(async()=>{try{const P=await Ws();re(P.models)}catch{}},[]),Kt=i.useCallback(async()=>{try{const P=await na();if(P.defaultProvider&&P.defaultModelId){const Ce=`${P.defaultProvider}/${P.defaultModelId}`;L(Ce)}}catch{}},[]);i.useEffect(()=>{Promise.all([qt(),en(),Kt()]).finally(()=>D(!1))},[qt,en,Kt]),i.useEffect(()=>{const P=fO("ai-setup");if(P?.loginOutcomes){const Ce=P.loginOutcomes,qe={};for(const[et,mt]of Object.entries(Ce))mt!=="pending"&&(qe[et]=mt);Object.keys(qe).length>0&&be(qe)}},[]);const Sn=i.useCallback((P,Ce)=>{Dl(v,{completedSteps:y,stepData:{"ai-setup":{loginOutcomes:{[P]:Ce}}}})},[v,y]);i.useEffect(()=>{const P=Object.entries(Ze).filter(([Ce,qe])=>qe!=="pending");for(const[Ce,qe]of P)Sn(Ce,qe)},[Ze,Sn]),i.useEffect(()=>()=>{me.current&&clearInterval(me.current),Object.values(St.current).forEach(clearTimeout),St.current={}},[]);const dn=i.useCallback(P=>{$t(P),Dl(v,{completedSteps:y,stepData:{github:{skipped:P}}})},[v,y]),Jt=i.useCallback(P=>P==="complete"?-1:ua.indexOf(P),[]),tn=i.useCallback(()=>{S(Ce=>[...new Set([...Ce,v])]),C(Ce=>Ce.filter(qe=>qe!==v)),pi("onboarding:step-completed",{step:v}),v==="github"&&!Ke&&dn(!1);const P=Jt(v);P>=0&&P<ua.length-1&&b(ua[P+1])},[v,Ke,dn,Jt]),Ne=i.useCallback(()=>{C(Ce=>[...new Set([...Ce,v])]),dO(v),pi("onboarding:step-skipped",{step:v}),v==="github"&&!Ke&&dn(!0);const P=Jt(v);P>=0&&P<ua.length-1&&b(ua[P+1])},[v,Ke,dn,Jt]),W=i.useCallback(()=>{const P=v;S(qe=>qe.filter(et=>et!==P)),C(qe=>qe.filter(et=>et!==P)),P==="github"&&!Ke&&dn(!1);const Ce=Jt(v);Ce>0&&b(ua[Ce-1])},[v,Ke,dn,Jt]),Y=i.useCallback(()=>{Ne()},[Ne]),_e=i.useCallback(async P=>{const Ce=H.find(et=>et.id===P);if(Ce?.requiresManualCode===!0&&!await d({title:"Heads up — manual paste-back required",message:_O(Ce.name),confirmLabel:"Continue to login",cancelLabel:"Cancel"}))return;be(et=>{const mt=et[P];if(mt&&mt!=="pending"){const{[P]:Nt,...Pt}=et;return Pt}return et});const qe=()=>{le(et=>{if(!(P in et))return et;const mt={...et};return delete mt[P],mt}),He(et=>{if(!(P in et))return et;const mt={...et};return delete mt[P],mt}),je(et=>{if(!(P in et))return et;const mt={...et};return delete mt[P],mt})};qe(),be(et=>({...et,[P]:"pending"})),k(P),Ie.current=0;try{const{url:et,instructions:mt,manualCode:Nt}=await NN(P);mt?.trim()&&le(Pt=>({...Pt,[P]:mt})),Nt&&He(Pt=>({...Pt,[P]:Nt})),window.open(Fi(et),"_blank"),me.current=setInterval(async()=>{if(Ie.current++,Ie.current>=LO){me.current&&(clearInterval(me.current),me.current=null),k(null),Q(Pt=>Pt.map(an=>an.id===P?{...an,loginInProgress:!1}:an)),be(Pt=>({...Pt,[P]:"timeout"})),qe(),n("Login timed out. Please try again.","warning");return}try{const{providers:Pt,ghCli:an}=await Po(),Cn=hg(Pt);Q(Cn),O(an);const ie=Cn.find($e=>$e.id===P);if(ie?.authenticated){me.current&&(clearInterval(me.current),me.current=null),k(null),be($e=>({...$e,[P]:"success"})),qe(),P==="github"&&dn(!1),n("Login successful","success");return}ie?.loginInProgress||(me.current&&(clearInterval(me.current),me.current=null),k(null),be($e=>({...$e,[P]:"failed"})),qe(),n("Login did not complete. Please try again.","error"))}catch{}},2e3)}catch(et){et instanceof Error&&et.message.includes("already in progress")||et&&typeof et=="object"&&"status"in et&&et.status===409?(n("Login already in progress. Cancel it to retry.","warning"),be(Nt=>({...Nt,[P]:"pending"})),qt()):(n(et instanceof Error?et.message:"Login failed","error"),be(Nt=>({...Nt,[P]:"failed"}))),k(null),qe()}},[n,H,d,qt,dn]),ut=i.useCallback(async P=>{const Ce=ye[P]?.trim();if(!Ce){n("Paste the full redirect URL or authorization code first.","warning");return}fe(P);try{(await SN(P,Ce)).submitted?(je(et=>{if(!(P in et))return et;const mt={...et};return delete mt[P],mt}),n("Authorization code received. Finishing login…","success")):n("That authorization code was already submitted. Waiting for login…","warning")}catch(qe){n(Se(qe)||"Failed to submit authorization code","error")}finally{fe(null)}},[n,ye]),At=i.useCallback(async P=>{me.current&&(clearInterval(me.current),me.current=null),k(P),Ie.current=0,Q(Ce=>Ce.map(qe=>qe.id===P?{...qe,loginInProgress:!1}:qe)),be(Ce=>({...Ce,[P]:"cancelled"}));try{await EN(P),await qt().catch(()=>{}),n("Login cancelled","success")}catch(Ce){n(Se(Ce)||"Failed to cancel login","error")}finally{k(null),le(Ce=>{if(!(P in Ce))return Ce;const qe={...Ce};return delete qe[P],qe}),He(Ce=>{if(!(P in Ce))return Ce;const qe={...Ce};return delete qe[P],qe}),je(Ce=>{if(!(P in Ce))return Ce;const qe={...Ce};return delete qe[P],qe}),fe(Ce=>Ce===P?null:Ce)}},[n,qt]),zt=i.useCallback((P,Ce)=>{pe(et=>({...et,[P]:Ce}));const qe=St.current[P];qe&&(clearTimeout(qe),delete St.current[P]),ae(et=>{if(!et[P])return et;const mt={...et};return delete mt[P],mt}),Te(et=>{if(!et[P])return et;const mt={...et};return delete mt[P],mt})},[]),yn=i.useCallback(()=>{const P=Fe.current;if(!P)return;const Ce=typeof window<"u"&&typeof window.matchMedia=="function"&&window.matchMedia("(prefers-reduced-motion: reduce)").matches;try{if(typeof P.scrollTo=="function"){P.scrollTo({top:0,behavior:Ce?"auto":"smooth"});return}}catch{}P.scrollTop=0},[]),Zn=i.useCallback(async(P,Ce)=>{const qe=(Ce??B[P]??"").trim(),et=IO(P,qe);if(et){ae(Nt=>({...Nt,[P]:et}));return}const mt=St.current[P];mt&&(clearTimeout(mt),delete St.current[P]),k(P),ae(Nt=>{const Pt={...Nt};return delete Pt[P],Pt}),Te(Nt=>{if(!Nt[P])return Nt;const Pt={...Nt};return delete Pt[P],Pt});try{await _N(P,qe),await qt(),yn(),pe(Nt=>{const Pt={...Nt};return delete Pt[P],Pt}),ae(Nt=>{if(!Nt[P])return Nt;const Pt={...Nt};return delete Pt[P],Pt}),Te(Nt=>({...Nt,[P]:"✓ Key saved"})),St.current[P]=setTimeout(()=>{Te(Nt=>{if(!Nt[P])return Nt;const Pt={...Nt};return delete Pt[P],Pt}),delete St.current[P]},3e3),n("API key saved","success")}catch(Nt){const Pt=Nt instanceof TypeError&&Nt.message.includes("Failed to fetch")?"Could not reach the server. Check your connection and try again.":Nt instanceof Error?Nt.message:"Failed to save API key";ae(an=>({...an,[P]:Pt})),Te(an=>{if(!an[P])return an;const Cn={...an};return delete Cn[P],Cn}),n(Pt,"error")}finally{k(null)}},[B,n,qt,yn]),vn=i.useCallback(async P=>{k(P);try{await MN(P),await qt(),n("API key removed","success")}catch(Ce){n(Ce instanceof Error?Ce.message:"Failed to clear API key","error")}finally{k(null)}},[n,qt]),Dn=i.useCallback(async P=>{k(P);try{await CN(P),await qt(),n("Logged out","success")}catch(Ce){n(Ce instanceof Error?Ce.message:"Logout failed","error")}finally{k(null)}},[n,qt]),de=i.useCallback(P=>{L(P)},[]),nt=i.useCallback(async()=>{try{const P={modelOnboardingComplete:!0};if(q){const Ce=q.indexOf("/"),qe=Ce!==-1?q.slice(0,Ce):void 0,et=Ce!==-1?q.slice(Ce+1):q,mt=Z.find(Nt=>Nt.id===et);mt?(P.defaultProvider=mt.provider,P.defaultModelId=mt.id):qe&&et&&(P.defaultProvider=qe,P.defaultModelId=et)}await Bn(P),pg()}catch{}},[q,Z,Bn,pg]),ot=i.useCallback(async()=>{const P=[...new Set([...y,"first-task"])];he(!0);try{await nt(),pi("onboarding:completed",{completedSteps:P,skippedSteps:j}),S(P),C(Ce=>Ce.filter(qe=>qe!=="first-task")),b("complete")}finally{he(!1)}},[nt,y,j]),_t=i.useCallback(async()=>{if(!s)return;const P=R.trim();if(!P){U("Please enter a task description.");return}U(null),_(!0);let Ce=!1;try{const qe=await db({description:P,source:{sourceType:"dashboard_ui"}},s);T(qe),N(!0),pi("onboarding:first-task-created",{taskId:qe?.id}),n("Task created","success"),Ce=!0}catch(qe){const et=qe instanceof Error?qe.message:"Something went wrong creating your task. Please try again.";U(et),n(et,"error")}finally{_(!1)}Ce&&nt()},[s,R,n,nt]),G=i.useCallback(async()=>{he(!0);try{await nt()}finally{he(!1)}pi("onboarding:open-new-task",{}),r?.()},[nt,r]),Oe=i.useCallback(async()=>{if(It){he(!0);try{await nt()}finally{he(!1)}w(!1),e(),pi("onboarding:open-github-import",{}),o?.()}},[nt,It,e,o]),Mt=i.useCallback(async()=>{pi("onboarding:dismissed",{currentStep:v,completedSteps:y,skippedSteps:j}),he(!0);try{await Bn({modelOnboardingComplete:!0})}catch{}w(!1),e()},[v,y,j,e]),Xt=i.useCallback(()=>{pi("onboarding:finished",{}),w(!1),e()},[e]),_n=i.useCallback(()=>{const P=l??A;P&&(nt(),c?.(P),e())},[l,A,nt,c,e]),Pn=i.useCallback(()=>{nt(),e()},[nt,e]),kn=bt(),Vn=H.filter(P=>P.id!=="github"),$s=yt.host!=="web"&&!yt.activeProfileId,vs=[...Vn].sort(vg),As=vs.some(P=>!P.type||P.type==="oauth"),bn=vs.some(P=>P.type==="api_key"),Ht=Vn.filter(P=>P.authenticated),On=Ht.length>0,Fn=!!s,as=v==="github"&&!On,Wn=i.useCallback(async()=>{if(st){wt(null),Ye(!0);try{const P=await st.saveProfile({name:oe,serverUrl:ft,authToken:tt.trim()?tt:null});try{await st.setActiveProfile(P.id)}catch(Ce){wt(Se(Ce)||"Saved profile but failed to activate it");return}ht(""),xt(""),n("Remote server profile saved","success")}catch(P){wt(Se(P)||"Failed to save shell connection")}finally{Ye(!1)}}},[st,oe,ft,tt,n]);if(!g)return null;const Rs=(()=>{if(!q)return"";const P=q.indexOf("/"),Ce=P===-1?void 0:q.slice(0,P),qe=P===-1?q:q.slice(P+1),et=Z.find(mt=>mt.id===qe&&(!Ce||mt.provider===Ce));return et?.name?et.name:Ce?`${Tu(Ce)} ${qe}`:q})(),In=[];if(Fn?In.push({label:"Project",status:"connected",detail:"Project selected — task creation and imports are available"}):In.push({label:"Project",status:"missing",detail:"Register a project to enable task creation and imports"}),On){const P=Tu(Ht[0]?.id??"");In.push({label:"AI Provider",status:"connected",detail:`${P} connected — AI agents can work on tasks`})}else Vn.length>0&&Vn.some(P=>Dt[P.id])?In.push({label:"AI Provider",status:"skipped",detail:"AI agents won't be available until you connect a provider"}):In.push({label:"AI Provider",status:"missing",detail:"Connect a provider in Settings → AI Setup"});It?In.push({label:"GitHub",status:"connected",detail:Lt?"Connected via GitHub CLI — imports and PR tracking are available":"Issues and PRs can be imported"}):!Pe||gt?In.push({label:"GitHub",status:"skipped",detail:"You can connect anytime from Settings"}):In.push({label:"GitHub",status:"missing",detail:"Connect to import issues as tasks"}),Rs&&In.push({label:"Default Model",status:"connected",detail:Rs});const rs=l??A,Ns=rs?.description?.split(`
692
- `)[0]?.trim()||rs?.title||"",ys=new Set(Jd),cs=vs.filter(P=>ys.has(P.id)).sort((P,Ce)=>{const qe=Jd.indexOf(P.id),et=Jd.indexOf(Ce.id);return qe!==et?qe-et:vg(P,Ce)}),ss=vs.filter(P=>P.authenticated&&!ys.has(P.id)),te=vs.filter(P=>!P.authenticated&&!ys.has(P.id)),we=P=>{const Ce=Ze[P.id]==="timeout"||Ze[P.id]==="failed"||Ze[P.id]==="cancelled",qe=P.loginInProgress&&!Ce;if(P.id==="llama-cpp"&&P.type==="cli")return t.jsx(WL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.id==="claude-cli"&&P.type==="cli")return t.jsx(HL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.id==="cursor-cli"&&P.type==="cli")return t.jsx(VL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.type==="api_key"){const et=$u(P.id),mt=PO(P);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${P.id}`,className:`onboarding-provider-card${P.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${P.id}`,"aria-hidden":"true",children:t.jsx(zn,{provider:P.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(ib,{size:14,className:"onboarding-provider-key-icon"}),P.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:et.description}),t.jsx(Gt,{status:Bt(P)}),P.authenticated&&P.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",P.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(DO,{provider:P,apiKeyInfo:mt,inputValue:B[P.id]??"",isSaving:$===P.id,error:ze[P.id],success:Ve[P.id],isConnected:P.authenticated,onInputChange:zt,onSave:Zn,onClear:vn})})]},P.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${P.id}`,className:`onboarding-provider-card${P.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${P.id}`,"aria-hidden":"true",children:t.jsx(zn,{provider:P.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:P.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:$u(P.id).description}),t.jsx(Gt,{status:Bt(P)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:$===P.id?P.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void At(P.id),children:"Cancel"})]}):qe?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void At(P.id),children:"Cancel"})]}):P.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Dn(P.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>_e(P.id),children:"Login"})}),($===P.id||qe)&&X[P.id]&&t.jsx(Kd,{instructions:X[P.id],"data-testid":`onboarding-login-instructions-${P.id}`}),($===P.id||qe)&&ke[P.id]&&t.jsx(KL,{value:ye[P.id]??"",onChange:et=>je(mt=>({...mt,[P.id]:et})),onSubmit:()=>void ut(P.id),prompt:ke[P.id].prompt,placeholder:ke[P.id].placeholder,helpText:ke[P.id].helpText,disabled:ne===P.id,submitLabel:ne===P.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${P.id}`}),Ze[P.id]==="timeout"&&$!==P.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ze[P.id]==="failed"&&$!==P.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},P.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:J,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[v==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(ls,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),v==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),v==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Dm,{size:24})," Set Up Your Project"]}),v==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Dm,{size:24})," Create Your First Task"]}),v==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:24})," All Set!"]})]}),v!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Mt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(mn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:on.map((P,Ce)=>{const qe=ln>Ce,et=y.includes(P.key)&&qe,mt=j.includes(P.key)&&!y.includes(P.key)&&qe,Nt=et||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Ce>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Ce<=ln?"done":""}`}),Nt?t.jsxs("button",{className:`model-onboarding-step-indicator ${v===P.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,onClick:()=>b(P.key),"aria-label":`Go back to ${P.label}`,title:`Review ${P.label}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(Xn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ce+1}),t.jsx("span",{className:"step-label",children:P.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${v===P.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(Xn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ce+1}),t.jsx("span",{className:"step-label",children:P.label})]})]},P.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Fe,children:[v==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),t.jsx("p",{className:"onboarding-helper-text",children:"Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features."}),$s&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connect remote Fusion server"}),t.jsx("p",{className:"onboarding-helper-text",children:"Your native shell needs an active remote profile before dashboard handoff can complete."}),t.jsx("label",{htmlFor:"onboarding-shell-profile-name",className:"onboarding-apikey-field-label",children:"Profile name"}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:oe,onChange:P=>Ee(P.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-server-url",className:"onboarding-apikey-field-label",children:"Server URL"}),t.jsx("input",{id:"onboarding-shell-server-url",className:"input",placeholder:"https://your-fusion-host",value:ft,onChange:P=>ht(P.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-token",className:"onboarding-apikey-field-label",children:"Auth token (optional)"}),t.jsx("input",{id:"onboarding-shell-token",className:"input",type:"password",value:tt,onChange:P=>xt(P.target.value)}),dt&&t.jsx("small",{className:"field-error",children:dt}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void st?.openConnectionManager(),children:"Open manager"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void Wn(),disabled:!ft.trim()||Me,children:Me?"Saving…":"Save remote server"})]})]}),!M&&H.length>0&&(()=>{const P=H.filter(Nt=>Nt.id!=="github"&&Nt.authenticated).length,Ce=H.filter(Nt=>Nt.id!=="github").length,qe=Object.keys(Dt).filter(Nt=>!H.find(Pt=>Pt.id===Nt)?.authenticated).length;if(Ce===0)return null;let et="onboarding-provider-summary",mt="";return P>0?(et+=" onboarding-provider-summary--connected",mt=`✓ ${P} of ${Ce} provider${Ce!==1?"s":""} connected`):qe>0?(et+=" onboarding-provider-summary--skipped",mt=`${qe} provider${qe!==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(pa,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(fi,{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."})}),H.length>0&&!H.some(P=>P.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),M?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(jt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):H.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsx(pa,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{qt()}}}),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"}),cs.length>0?t.jsx("div",{className:"model-onboarding-providers",children:cs.map(P=>we(P))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),ss.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:ss.map(P=>we(P))})]}),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(fi,{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."})}),Z.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(_s,{models:Z,value:q,onChange:de,placeholder:"Select a default model…",label:"Default model"})}),q&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Z.find(P=>P.id===q)?.name??q]})})]}),t.jsx(fi,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[te.length>0?t.jsx("div",{className:"model-onboarding-providers",children:te.map(P=>we(P))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),rt.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:rt.map(P=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(zn,{provider:P.id,size:"sm"}),t.jsx("span",{children:P.name||P.id})]},P.id))}):null,ce?t.jsx(QL,{onSave:hn,onCancel:()=>{Re(!1),ue(void 0)},saving:Le,error:Ue}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Re(!0),children:"Add custom provider"})]})}),As&&t.jsx(fi,{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."})}),bn&&t.jsx(fi,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})}),t.jsx(pa,{slotId:"onboarding-setup-help",projectId:s})]})]}),v==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[It?t.jsx("p",{className:"model-onboarding-description",children:Lt?"GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed.":"GitHub is connected — issue imports and pull request tracking are available. You're all set; no further action needed."}):t.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),!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"})]})}),as&&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(fi,{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."})}),Pe?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(ii,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Ot,{status:kn})})]}),Ke&&($==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Dn("github"),children:"Disconnect"}))]}),(kn==="not-connected"||kn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[$==="github"||at?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void At("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>_e("github"),children:[t.jsx(ii,{size:16}),"Connect"]}),($==="github"||at)&&X.github&&t.jsx(Kd,{instructions:X.github,"data-testid":"onboarding-login-instructions-github"})]}),kn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Lt?"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."}),kn==="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:()=>_e("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Y,children:"Skip for now"})]})]}),kn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),kn==="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:()=>_e("github"),children:"Connect anyway"})})]}),kn==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(zn,{provider:"github",size:"lg"})}),Lt?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>b("project-setup"),children:Lt?"Continue with gh CLI auth →":"Continue without GitHub →"}),Lt&&($==="github"||at?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(jt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>_e("github"),children:[t.jsx(zn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Lt&&($==="github"||at)&&X.github&&t.jsx(Kd,{instructions:X.github,"data-testid":"onboarding-login-instructions-github"})]})]}),v==="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:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(fi,{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."})})]}),v==="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."}),x&&rs?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Xn,{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:rs.id}),Ns&&t.jsx("p",{className:"onboarding-task-created__description",children:Ns}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:_n,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Pn,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:R,onChange:P=>{F(P.target.value),U(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:_t,disabled:E,"data-testid":"onboarding-first-task-submit",children:E?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),K&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:K}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx($O,{items:In}),Fn&&t.jsxs(t.Fragment,{children:[t.jsx(fi,{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:G,disabled:xe,children:[t.jsx("div",{className:"cta-icon",children:t.jsx($n,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Create a New Task"}),t.jsx("span",{children:"Describe what you need built and AI will work on it"})]})]}),t.jsxs("button",{className:`onboarding-cta-card${It?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Oe,disabled:xe||!It,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ii,{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"}),!It&&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."]})]})]})]}),v==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Xn,{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:[v==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Mt,disabled:xe,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ne,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,children:"Next →"})]}),v==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ne,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,children:"Next →"})]}),v==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,disabled:!Fn,children:"Next →"})]}),v==="first-task"&&!x&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:ot,disabled:xe,children:xe?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),v==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Xt,children:[t.jsx(Xn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Wv({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 FO=i.lazy(()=>En(()=>import("./SetupWizardModal-Agi3XNtZ.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),zO=i.lazy(()=>En(()=>import("./SettingsModal-Cu93Jjho.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function BO(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{En(()=>import("./SettingsModal-Cu93Jjho.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function UO({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[w,v]=i.useState(null),b=c.detailTask?(()=>{const N=n.find(R=>R.id===c.detailTask?.id);return N?"prompt"in c.detailTask?{...c.detailTask,...N,prompt:c.detailTask.prompt,log:c.detailTask.log}:N:c.detailTask})():null,y=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),j=i.useCallback(()=>{c.openGitHubImport()},[c]),C=i.useCallback(N=>{v(null),c.closeModelOnboarding(),c.openDetailTask(N)},[c]),x=i.useCallback(async N=>{const R=await u.handleModalCreate(N);return c.modelOnboardingOpen&&v(R),R},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&w&&v(null)},[c.modelOnboardingOpen,w]),i.useEffect(()=>{BO()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ia,{children:t.jsx(ZP,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,mobileHeaderMode:c.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ia,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(zO,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(p4,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ia,{children:t.jsx(y4,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:u.handlePlanningTaskCreated,onTasksCreated:u.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(Ia,{children:t.jsx(A4,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(X4,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(eD,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(jD,{initialWorkspace:c.fileBrowserWorkspace,initialFile:c.fileBrowserInitialFile,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(SD,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(PD,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(dL,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(eL,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ia,{children:t.jsx(iL,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:x,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(fL,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:N=>{const R=n.find(F=>F.id===N);R&&c.openDetailTask(R)}}),t.jsx(Ia,{children:t.jsx(bL,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ia,{children:t.jsx(EL,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(UL,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(FO,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(OO,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:j,firstCreatedTask:w,onViewTask:C}),t.jsx(Wv,{toasts:o,onRemove:l})]})}function HO({errorMessage:e,isRetrying:n,onRetry:s,onManageConnection:a}){return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:"Can't reach the Fusion backend"}),t.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),t.jsxs("p",{className:"settings-muted",children:["Error: ",e]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"}),a&&t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Manage Connection"})]})]})}const Du=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function qO(e,n){if(n==="ready")return"done";const s=Du.findIndex(r=>r.id===n),a=Du.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function VO({stage:e}){const[n]=i.useState(()=>hj());return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":n?"Updating Fusion dashboard":"Loading Fusion dashboard","data-stage":e,"data-version-update":n?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),n?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:"Updating to a new frontend version..."}):t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:Du.map(s=>{const a=qO(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${a}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:a==="done"?"✓":a==="active"?t.jsx(jt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const WO=5e3;function GO(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function KO(e,n,s){let a=0,r=0,o=0,l=0,c=0;for(const d of e){switch(d.column){case"in-progress":a++,ec(d,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}d.blockedBy&&d.blockedBy.length>0&&r++}return{runningTaskCount:a,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function JO(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const v=await y1(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;u(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},WO),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=KO(e,s,a),g=GO(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const YO={planning:Oi,subtask:Fa,mission_interview:Es,milestone_interview:Es,slice_interview:Es},QO={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function XO({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=li(),[l,c]=i.useState(!1),[d,u]=i.useState(new Set),m=i.useRef(null),h=i.useRef(new Map),f=i.useRef(null),{activeTabMap:p}=Wr(),g=i.useMemo(()=>Ja(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const j=p.get(S.id),C=[S.status,S.updatedAt,j?.tabId??S.lockedByTab??"",j?.stale?"stale":"fresh"].join("|"),x=h.current.get(S.id);x&&x!==C&&b.add(S.id),y.set(S.id,C)}if(h.current=y,b.size!==0)return u(b),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{u(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const w=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${w} background AI task${w!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(jt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(tu,{size:12}),t.jsxs("span",{children:["AI ",w]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=YO[b.type],S=b.status==="generating",j=b.status==="awaiting_input",C=b.status==="error",x=p.get(b.id),N=x?.tabId??b.lockedByTab??null,R=!!(N&&N!==g&&!x?.stale),F=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${F?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:F?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:F?"translateY(-1px)":void 0},onClick:async()=>{R&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[C?t.jsx(Vs,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?"Failed":QO[b.type],S&&" — generating...",j&&!R&&" — needs input",j&&R&&" — active in another tab"]})]}),S&&t.jsx(jt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),j&&!R&&t.jsx(tu,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),j&&R&&t.jsx(yc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:E=>{E.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(mn,{size:12})})]},b.id)})})]})]})}function ZO(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),a=n-s,r=Math.floor(a/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function eF(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:os};case"paused":return{label:"Paused",color:"var(--triage)",icon:Ci};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:ls}}}function tF({tasks:e,projectId:n,taskStuckTimeoutMs:s,staleHighFanoutBlockerAgeThresholdMs:a,backgroundSessions:r,backgroundGenerating:o,backgroundNeedsInput:l,onOpenBackgroundSession:c,onDismissBackgroundSession:d,lastFetchTimeMs:u,currentProjectPath:m,onOpenProjectDirectory:h,keyboardOpen:f}){if(f)return null;const{stats:p,loading:g,error:w}=JO(e,n,s,u),[v,b]=i.useState(!1),y=i.useMemo(()=>eF(p.executorState),[p.executorState]),S=i.useMemo(()=>ZO(p.lastActivityAt),[p.lastActivityAt]),j=i.useMemo(()=>{const x=tm(e,{staleHighFanoutAgeThresholdMs:a??Lb});return Array.from(x.values()).map(R=>R.escalation).filter(R=>!!R).sort((R,F)=>F.activeTodoCount!==R.activeTodoCount?F.activeTodoCount-R.activeTodoCount:F.totalActiveCount!==R.totalActiveCount?F.totalActiveCount-R.totalActiveCount:F.blockingAgeMs!==R.blockingAgeMs?F.blockingAgeMs-R.blockingAgeMs:R.blockerId.localeCompare(F.blockerId,"en",{numeric:!0,sensitivity:"base"}))[0]??null},[e,a]),C=y.icon;return w?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(zr,{size:14}),w]})}):g&&p.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${p.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[r&&r.length>0&&c&&d&&t.jsxs(t.Fragment,{children:[t.jsx(XO,{sessions:r,generating:o??0,needsInput:l??0,onOpenSession:c,onDismissSession:d}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:p.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${p.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:p.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:p.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),p.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:p.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${p.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${p.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:p.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:p.inReviewCount})]}),j&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--fanout",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--fanout executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Escalated"}),t.jsxs("span",{className:"executor-status-bar__fanout-summary",title:`Escalated blocker ${j.blockerId}: ${j.activeTodoCount} todo waiting (threshold ${Xu}), ${j.totalActiveCount} active total`,children:[j.blockerId," · ",j.activeTodoCount," todo"]})]})]}),m&&h&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${v?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(x=>!x),"aria-label":v?"Hide project directory":"Show project directory","aria-expanded":v,"data-testid":"executor-project-path-toggle",title:v?"Hide project directory":"Show project directory",children:t.jsx(js,{size:12,"aria-hidden":"true"})}),v&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:h,title:m,"data-testid":"executor-project-path-link",children:m})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(ta,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:S})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(C,{size:12,style:{color:y.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:y.color},children:y.label})]})]})}const nF={planning:Oi,subtask:Fa,mission_interview:Es,milestone_interview:Es,slice_interview:Es},sF={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Gv="fusion:session-banner-dismissed";function So(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function iF(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Gv);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n)){const o=typeof r=="number"?r:So(r);s.set(a,o)}return s}catch{return new Map}}function aF(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Gv,JSON.stringify(n))}catch{}}const Qi=iF();function rF({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{aF(Qi),o(g=>g+1)};i.useEffect(()=>{if(Qi.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let w=!1;for(const[v,b]of Qi){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Qi.delete(v),w=!0;continue}So(y.updatedAt)>b&&(Qi.delete(v),w=!0)}w&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const w=Qi.get(g.id);return w===void 0?!0:So(g.updatedAt)>w}),[e,r]);if(c.length===0)return null;const d=c.filter(g=>g.status==="awaiting_input").length,u=c.filter(g=>g.status==="error").length;let m="";d>0&&u>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input, ${u} failed`:d>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input`:u>0&&(m=`${u} AI session${u===1?"":"s"} failed`);const h=g=>{Qi.set(g.id,Math.max(So(g.updatedAt),Date.now())),l()},f=g=>{Qi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const w of c)Qi.set(w.id,Math.max(So(w.updatedAt),g));l(),a()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(Vs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(mn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const w=nF[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(Vs,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(w,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":sF[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(mn,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Kv="fusion:cli-binary-banner-dismissed";function oF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Kv)==="1"}catch{return!1}}function lF(){if(!(typeof window>"u"))try{window.localStorage.setItem(Kv,"1")}catch{}}function cF({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>oF()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let y=!1;return mN().then(S=>{y||s(S)}).catch(()=>{}),()=>{y=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const y=await hN();s({binary:y.binary,expectedVersion:y.expectedVersion,state:y.state,install:y.install}),y.installResult.success||d(y.installResult.permissionsHint||y.installResult.stderr||`Install failed (exit ${y.installResult.exitCode??"n/a"})`)}catch(y){d(y instanceof Error?y.message:String(y))}finally{l(!1)}},[]),m=i.useCallback(()=>{lF(),r(!0)},[]);if(a||!n||n.state==="installed"||n.state==="skipped")return null;const h=n.state==="version-mismatch",f=n.binary.version,p=n.expectedVersion,g=h?"Update the Fusion CLI":"Install the Fusion CLI",w=h?t.jsxs(t.Fragment,{children:["Your installed ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," but this dashboard expects"," ",t.jsxs("strong",{children:["v",p]}),". Update to stay in sync."]}):t.jsxs(t.Fragment,{children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),v=h?"Update with npm":"Install with npm",b=h?"Updating…":"Installing…";return t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:g}),t.jsx("div",{className:"cli-binary-banner__text",children:w}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?b:v}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(mn,{size:16})})]})}const dF={duplicate_active_id:"Duplicate active task ID",id_in_active_and_archived:"Task ID present in active and archived storage",next_sequence_at_or_below_used:"Allocator next sequence overlaps an existing task ID",committed_reservation_for_existing_id:"Committed reservation still points at an existing task ID",task_row_outside_known_prefix:"Task row uses a prefix outside allocator state"};function uF(e){return e.length<=5?e.join(", "):`${e.slice(0,5).join(", ")} +${e.length-5} more`}function mF({report:e,recommendedAction:n,onRefresh:s}){const[a,r]=i.useState(!1),[o,l]=i.useState(null);if(e.status!=="anomaly")return null;const c=async()=>{r(!0),l(null);try{const d=await Lj();s?.(d.taskIdIntegrity,d.taskIdIntegrity.recommendedAction)}catch(d){l(d instanceof Error?d.message:"Failed to refresh integrity status.")}finally{r(!1)}};return t.jsxs("section",{className:"task-id-integrity-banner",role:"alert","aria-live":"assertive",children:[t.jsxs("div",{className:"task-id-integrity-banner__header",children:[t.jsxs("div",{className:"task-id-integrity-banner__headline-wrap",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx(zr,{"aria-hidden":"true"}),t.jsx("h2",{className:"task-id-integrity-banner__headline",children:"Task ID integrity anomaly detected"})]}),t.jsxs("button",{type:"button",className:"btn btn-sm task-id-integrity-banner__refresh",onClick:()=>{c()},disabled:a,children:[t.jsx(ps,{className:a?"task-id-integrity-banner__refresh-icon task-id-integrity-banner__refresh-icon--spinning":"task-id-integrity-banner__refresh-icon","aria-hidden":"true"}),a?"Re-checking…":"Re-check"]})]}),t.jsx("p",{className:"task-id-integrity-banner__body",children:"Fusion found allocator state that can cause task IDs to be reused or overwrite live task records."}),t.jsx("ul",{className:"task-id-integrity-banner__list",children:e.anomalies.map(d=>t.jsxs("li",{className:"task-id-integrity-banner__item",children:[t.jsx("strong",{className:"task-id-integrity-banner__item-title",children:dF[d.kind]}),t.jsx("span",{className:"task-id-integrity-banner__item-detail",children:d.details}),t.jsx("code",{className:"task-id-integrity-banner__ids",children:uF(d.affectedIds)})]},`${d.kind}:${d.prefix}:${d.affectedIds.join(",")}`))}),t.jsx("p",{className:"task-id-integrity-banner__footer",children:n}),o?t.jsx("p",{className:"task-id-integrity-banner__error",children:o}):null]})}function hF({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"fn update"})," for an installed CLI, or pull this source checkout."," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(mn,{size:16,"aria-hidden":"true"})})]})}function pF({pendingCount:e,onOpenMailbox:n,onDismiss:s}){const a=e===1?"request":"requests";return t.jsx("section",{className:"approval-notification-banner",role:"region","aria-live":"polite","aria-label":"Approval requests",children:t.jsxs("div",{className:"approval-notification-banner__content",children:[t.jsxs("div",{className:"approval-notification-banner__headline",children:[t.jsx("span",{className:"status-dot","aria-hidden":"true"}),t.jsx(zr,{"aria-hidden":"true"}),t.jsxs("span",{children:[e," approval ",a," need your attention"]})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(ma,{"aria-hidden":"true"}),t.jsx("span",{children:"Open Mailbox"})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":"Dismiss approval notification banner",children:t.jsx(mn,{"aria-hidden":"true"})})]})]})})}function fF({onResume:e}){const n=hO();if(!n)return null;const s=n.completedSteps.length,a=ua.length,r=s>0?`${s} of ${a} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(ms,{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:()=>{pi("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(os,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function gF({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Lr(),a=Uv(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,j]=await Promise.all([Po(),na()]);if(b)return;const C=S.providers??[],x=C.find(_=>_.id==="github"),R=!C.some(_=>_.id!=="github"&&_.authenticated),F=!j.defaultProvider&&!j.defaultModelId,E=x?!x.authenticated:!1;h({needsAiProvider:R,needsDefaultModel:F,needsGitHub:E})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{uO(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),w=i.useCallback(()=>{e("authentication")},[e]),v=i.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:ls}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:ib}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:w,icon:ii}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,w,g,p]);return!s||a||d||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Oi,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsx("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:t.jsx(y,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})}),t.jsx(pa,{slotId:"post-onboarding-recommendation",renderPlaceholder:!1,actions:{openSettingsSection:e,openModelOnboarding:n}})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(mn,{size:16,"aria-hidden":!0})})]})}function bF({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 po(e){return e>99?"99+":String(e)}function xF({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,stashOrphanCount:f=0,onOpenGitManager:p,onOpenWorkflowSteps:g,onOpenSchedules:w,onOpenScripts:v,onToggleTerminal:b,onOpenFiles:y,onOpenTodos:S,todosOpen:j=!1,onOpenGitHubImport:C,onOpenPlanning:x,onResumePlanning:N,activePlanningSessionCount:R=0,onOpenUsage:F,onRunScript:E,projectId:_,onViewAllProjects:K,showSkillsTab:U,experimentalFeatures:A,onOpenNodes:T,pluginDashboardViews:H=[],shellConnectionControl:Q}){const se=oi(),[O,M]=i.useState(!1),[D,$]=i.useState(!1),[k,X]=i.useState({}),[le,ke]=i.useState(!1),He=i.useMemo(()=>Object.entries(k).sort(([ae],[Ve])=>ae.localeCompare(Ve)),[k]);i.useEffect(()=>{if(!D)return;let ae=!1;return ke(!0),$o(_).then(Ve=>{ae||X(Ve)}).catch(()=>{ae||X({})}).finally(()=>{ae||ke(!1)}),()=>{ae=!0}},[D,_]);const ye=i.useCallback(()=>M(!1),[]),je=i.useCallback(ae=>{ye(),ae?.()},[ye]);if(i.useEffect(()=>{if(!O)return;const ae=Ve=>{Ve.key==="Escape"&&M(!1)};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[O]),se!=="mobile"||a||r)return null;const ne=R>0&&N?N:x,fe=!!U,Z=!!A?.todoView,re=fe,q=fe&&!re,he=H.filter(ae=>ae.view.placement==="primary").sort((ae,Ve)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(Ve.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),B=new Set(he.map(ae=>`${ae.pluginId}:${ae.view.viewId}`)),pe=H.filter(ae=>!B.has(`${ae.pluginId}:${ae.view.viewId}`)).sort((ae,Ve)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(Ve.view.order??Number.MAX_SAFE_INTEGER)),ze=e==="documents"||!!A?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||j&&Z||e==="skills"&&!re||e==="graph"||e==="stash-recovery"||wr(e)&&!he.some(ae=>Eo(ae.pluginId,ae.view.viewId)===e);return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(va,{}),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(Qn,{}),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(Es,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Zi,{}),h&&e!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(za,{}),m>0&&e!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Pending approvals"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:po(u)})]}),re&&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(ls,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),he.map(ae=>{const Ve=Eo(ae.pluginId,ae.view.viewId),Te=Ql(ae.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===Ve||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${ae.pluginId}-${ae.view.viewId}`,role:"tab","aria-selected":e===Ve||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph",onClick:()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":Ve),children:[t.jsx(Te,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ze?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>M(ae=>!ae),children:[t.jsx(nu,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),O&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:ye}),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"}),Q?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:Q}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>je(d),children:[t.jsx(za,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:po(u)}),m>0&&t.jsx("span",{className:"mobile-more-item-badge",children:po(m)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>je(l),children:[t.jsx(Js,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>je(c),children:[t.jsx(Cr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>je(p),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:()=>je(b),children:[t.jsx(ea,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>$(ae=>!ae),"aria-expanded":D,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(qn,{size:14,className:`mobile-more-chevron${D?" mobile-more-chevron--open":""}`})})]}),D&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:le?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(jt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):He.length>0?t.jsxs(t.Fragment,{children:[He.map(([ae,Ve])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${ae}`,onClick:()=>{E&&E(ae,Ve),ye(),$(!1)},children:[t.jsx(os,{}),t.jsx("span",{children:ae})]},ae)),v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{ye(),$(!1),v()},children:[t.jsx(Si,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{ye(),$(!1),v()},children:[t.jsx(Si,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>je(y),children:[t.jsx(js,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>je(ne),children:[t.jsx(Oi,{}),t.jsx("span",{children:"Planning"}),R>0&&t.jsx("span",{className:"mobile-more-item-badge",children:po(R)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>je(g),children:[t.jsx(Wl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>je(w),children:[t.jsx(ta,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>je(C),children:[t.jsx(bF,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>je(F),children:[t.jsx(Js,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>je(K),children:[t.jsx(bc,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>je(()=>n("documents")),children:[t.jsx(xa,{}),t.jsx("span",{children:"Documents"})]}),A?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>je(()=>n("evals")),children:[t.jsx(Es,{}),t.jsx("span",{children:"Evals"})]}),q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>je(()=>n("skills")),children:[t.jsx(ls,{}),t.jsx("span",{children:"Skills"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>je(()=>n("stash-recovery")),children:[t.jsx(Oa,{}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"mobile-more-item-badge",children:po(f)}):null]}),A?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>je(()=>n("research")),children:[t.jsx(Xi,{}),t.jsx("span",{children:"Research"})]}),A?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>je(()=>n("insights")),children:[t.jsx(ms,{}),t.jsx("span",{children:"Insights"})]}),A?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>je(()=>n("memory")),children:[t.jsx(Io,{}),t.jsx("span",{children:"Memory"})]}),A?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{je(()=>n("dev-server"))},children:[t.jsx(Cr,{}),t.jsx("span",{children:"Dev Server"})]}),A?.nodesView&&T&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>je(T),children:[t.jsx(jk,{}),t.jsx("span",{children:"Nodes"})]}),Z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>je(()=>S?.()),children:[t.jsx(Bu,{}),t.jsx("span",{children:"Todos"})]}),pe.map(ae=>{const Ve=Eo(ae.pluginId,ae.view.viewId),Te=Ql(ae.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${ae.pluginId}-${ae.view.viewId}`,onClick:()=>je(()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":Ve)),children:[t.jsx(Te,{}),t.jsx("span",{children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>je(o),children:[t.jsx(Co,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function yg(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Jv(e,n){const s=n.trim();if(!s)return!0;const a=yg(s);return yg(e).includes(a)||e.toLowerCase().includes(s.toLowerCase())}function vF({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below",roomMemberIds:l,roomName:c}){const d=i.useMemo(()=>e.filter(g=>Jv(g.name,n)),[e,n]),u=!!l,m=u&&n.trim().length>0,h=i.useMemo(()=>u?d.filter(g=>l?.has(g.id)):d,[d,l,u]),f=i.useMemo(()=>u?d.filter(g=>!l?.has(g.id)):[],[d,l,u]),p=m?[...h,...f]:h;return a?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:p.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):t.jsxs(t.Fragment,{children:[u&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:c?`Members of #${c}`:"Room members"}),h.map((g,w)=>t.jsxs("button",{type:"button",className:`agent-mention-item${w===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:v=>v.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":w===s,children:[t.jsx(cc,{agent:g,size:20}),u&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":"Room member"}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)),u&&!m&&f.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:"Type to search other agents"}),u&&m&&f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:"Other agents"}),f.map((g,w)=>{const v=h.length+w;return t.jsxs("button",{type:"button",className:`agent-mention-item${v===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:b=>b.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":v===s,children:[t.jsx(cc,{agent:g,size:20}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)})]})]})}):null}function wg(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:a,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:c,onDone:d,onError:u,onFallbackSession:m}=e;let h="",f="",p=[],g,w=null,v=null;const b=()=>{w=null,a(h)},y=()=>{v=null,r(f)},S=()=>{w!==null&&(cancelAnimationFrame(w),w=null),v!==null&&(cancelAnimationFrame(v),v=null)};return l.current=S,{handlers:{onThinking:C=>{f+=C,v===null&&(v=requestAnimationFrame(y))},onText:C=>{h+=C,w===null&&(w=requestAnimationFrame(b))},onToolStart:C=>{p=[...p,{toolName:C.toolName,args:C.args,isError:!1,status:"running"}],o(p)},onToolEnd:C=>{const x=[...p];for(let N=x.length-1;N>=0;N--){const R=x[N];if(R?.toolName===C.toolName&&R.status==="running"){x[N]={...R,status:"completed",isError:C.isError,result:C.result},p=x,o(x);return}}p=[...x,{toolName:C.toolName,isError:C.isError,result:C.result,status:"completed"}],o(p)},onFallback:C=>{g=C,m?.(C,n),c?.(`Primary model unavailable. Switched to fallback ${C.fallbackModel}.`,"warning")},onDone:C=>{S(),d({messageId:C.messageId,message:C.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:C=>{S(),u(C,s)}},cancelFlushes:S}}const yF=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function wF(e){const n=e.trim().toLowerCase();return n?yF.some(s=>n.includes(s)):!1}function kF(){const e=i.useRef(null),n=i.useRef(null);i.useEffect(()=>{if(typeof document>"u")return;const r=()=>{const o=Date.now();if(document.visibilityState==="hidden"){e.current=o;return}document.visibilityState==="visible"&&(n.current=o)};return r(),document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[]);const s=i.useCallback(()=>typeof document<"u"&&document.visibilityState==="hidden",[]),a=i.useCallback((r=5e3)=>{const o=e.current;if(o===null)return!1;const l=Date.now();if(s())return l-o<=r;const c=n.current;return c===null||c<o?!1:l-c<=r},[s]);return i.useMemo(()=>({isHiddenNow:s,wasRecentlyHidden:a}),[s,a])}const yr="__fn_agent__";function Yv(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Ll(e,n,s){const a=typeof e=="string"?e.trim():"",r=Yv(n,s),o=a||(r.modelProvider&&r.modelId?yr:"");return o?{agentId:o,...r}:null}function Ol(e,n,s){const a=Yv(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function kg(e){const n=typeof e=="string"?e.trim():"",s=n.indexOf("/");return!n||s<=0||s>=n.length-1?{}:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function jF(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(a=>{if(!a||typeof a!="object")return null;const r=a,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(a=>a!==null);return s.length>0?s:void 0}function NF(e){const n=e?.fallback;if(!n||typeof n!="object")return;const s=n,a=typeof s.primaryModel=="string"?s.primaryModel:"",r=typeof s.fallbackModel=="string"?s.fallbackModel:"",o=s.triggerPoint;if(!(!a||!r||o!=="session-creation"&&o!=="prompt-time"))return{primaryModel:a,fallbackModel:r,triggerPoint:o}}function fr(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:jF(e.metadata),fallbackInfo:NF(e.metadata),createdAt:e.createdAt}}function SF(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,w]=i.useState(""),[v,b]=i.useState(""),[y,S]=i.useState([]),[j,C]=i.useState(""),x=i.useRef(null),N=i.useRef(!1),R=i.useRef(null),F=i.useRef(""),E=i.useRef(f);E.current=f;const _=i.useRef(null),K=i.useRef(""),U=i.useRef(null),A=i.useRef(s);A.current=s;const T=i.useRef(0),H=3,Q=i.useRef(!1);i.useEffect(()=>{F.current=j},[j]);const se=i.useCallback(async()=>{c(!0);try{const q=await uh(e);o(q.sessions)}catch(q){console.error("[useQuickChat] Failed to refresh sessions:",q)}finally{c(!1)}},[e]),O=i.useCallback(async q=>{const L={agentId:q.agentId};return q.modelProvider&&q.modelId&&(L.modelProvider=q.modelProvider,L.modelId=q.modelId),(await V0(L,e)).session},[e]),M=i.useCallback((q,L)=>{if(x.current||!q)return!0;N.current=!1,L&&(w(L.streamingText),b(L.streamingThinking),S(L.toolCalls)),p(!0);const{handlers:xe}=wg({sessionId:q,tempUserMessageId:"",setStreamingText:w,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(he,B)=>{const pe=kg(he.fallbackModel);o(ze=>ze.map(ae=>ae.id===B?{...ae,...pe}:ae)),a(ze=>ze&&ze.id===B?{...ze,...pe}:ze)},onDone:()=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,Zr(q,{limit:50},e).then(he=>{u(he.messages.map(fr))}).catch(()=>{})},onError:he=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null;const B=typeof he=="string"&&he.trim()?he:"Failed to get response";n?.(B,"error"),Zr(q,{limit:50},e).then(pe=>{u(pe.messages.map(fr))}).catch(()=>{})}});return x.current=Y0(q,xe,e,{...typeof L?.replayFromEventId=="number"?{lastEventId:L.replayFromEventId}:{}}),!0},[n,e]),D=i.useCallback(async(q,L,xe)=>{const he=Ll(q,L,xe);if(!he)return;const B=Ol(he.agentId,he.modelProvider,he.modelId);c(!0);try{const{session:pe}=await q0({agentId:he.agentId,modelProvider:he.modelProvider,modelId:he.modelId},e);if(pe)a(pe),K.current=B,pe.isGenerating&&M(pe.id,pe.inFlightGeneration);else{const ze=await O(he);a(ze),K.current=B}T.current=0}catch(pe){console.error("[useQuickChat] Failed to initialize session:",pe),T.current+=1,T.current<=H&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[M,e,n,O]),$=i.useCallback(async()=>{if(s){h(!0);try{const q=await Zr(s.id,{limit:50},e);u(q.messages.map(fr))}catch(q){console.error("[useQuickChat] Failed to load messages:",q)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?$():u([])},[s,$]),i.useEffect(()=>{if(!s?.isGenerating||(x.current||M(s.id,s.inFlightGeneration),!E.current||x.current||!s))return;const q=setInterval(async()=>{if(!E.current||x.current||!s){clearInterval(q);return}try{if(!(await W0(s.id,e)).session.isGenerating){clearInterval(q);const xe=await Zr(s.id,{limit:50},e);u(xe.messages.map(fr)),w(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(q)},[s,M,e]);const k=i.useCallback(async()=>{if(s){h(!0);try{const q=await Zr(s.id,{limit:50},e);u(q.messages.map(fr))}catch(q){console.error("[useQuickChat] Failed to reload messages:",q)}finally{h(!1)}}},[s,e]),X=i.useCallback(()=>{R.current?.(),R.current=null,F.current="",C(""),w(""),b(""),S([]),p(!1)},[]),le=i.useCallback(async(q,L,xe)=>{const he=Ll(q,L,xe);if(!he)return;const B=Ol(he.agentId,he.modelProvider,he.modelId);U.current=he;const pe=B===K.current&&A.current;if(pe||(x.current&&(x.current.close(),x.current=null),X()),pe){await k();return}a(null),u([]),K.current=B,await D(he.agentId,he.modelProvider,he.modelId)},[D,k,X]),ke=i.useCallback(async q=>{const L=Ll(q.agentId,q.modelProvider??void 0,q.modelId??void 0);L&&(U.current=L,K.current=Ol(L.agentId,L.modelProvider,L.modelId),x.current&&(x.current.close(),x.current=null),X(),a(q),q.isGenerating&&M(q.id,q.inFlightGeneration))},[M,X]),He=i.useCallback(async(q,L)=>{await le(yr,q,L)},[le]),ye=i.useCallback(async(q,L,xe)=>{const B=Ll(q??"",L,xe)??U.current;if(!B)return;U.current=B;const pe=Ol(B.agentId,B.modelProvider,B.modelId);Q.current=!0,T.current=0,x.current&&(x.current.close(),x.current=null),X(),u([]),a(null),c(!0);try{const ze=await O(B);a(ze),K.current=pe;const ae=await uh(e);o(ae.sessions)}catch(ze){console.error("[useQuickChat] Failed to start a fresh session:",ze),n?.("Failed to start a new chat","error")}finally{Q.current=!1,c(!1)}},[n,O,e,X]),je=i.useCallback(()=>{s&&(N.current=!0,R.current?.(),R.current=null,x.current?.close(),x.current=null,G0(s.id,e).catch(()=>{}),p(!1),w(""),b(""),S([]))},[s,e]),ne=i.useCallback(()=>{F.current="",C("")},[]),fe=i.useRef(()=>Promise.resolve()),Z=kF(),re=i.useCallback((q,L)=>{if(!s||!q.trim()&&(!L||L.length===0))return Promise.resolve();if(E.current)return L&&L.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(F.current=q,C(q),Promise.resolve());const xe=new Promise((he,B)=>{_.current={resolve:he,reject:B},N.current=!1,x.current&&(x.current.close(),x.current=null);const pe=`temp-${Date.now()}`,ze={id:pe,sessionId:s.id,role:"user",content:q,createdAt:new Date().toISOString()};u(Ve=>[...Ve,ze]),w(""),b(""),S([]),p(!0);const{handlers:ae}=wg({sessionId:s.id,tempUserMessageId:pe,setStreamingText:w,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(Ve,Te)=>{const rt=kg(Ve.fallbackModel);o(Be=>Be.map(ce=>ce.id===Te?{...ce,...rt}:ce)),a(Be=>Be&&Be.id===Te?{...Be,...rt}:Be)},onDone:({messageId:Ve,message:Te,accumulated:rt})=>{const Be=Te?fr(Te):{id:Ve||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:rt.text,thinkingOutput:rt.thinking||void 0,toolCalls:rt.toolCalls.length>0?rt.toolCalls:void 0,fallbackInfo:rt.fallbackInfo,createdAt:new Date().toISOString()};u(Re=>[...Re,Be]),w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,_.current?.resolve(),_.current=null;const ce=F.current.trim();ce&&(F.current="",C(""),fe.current(ce))},onError:Ve=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,console.error("[useQuickChat] Stream error:",Ve);const Te=typeof Ve=="string"&&Ve.trim()?Ve:"Failed to get response";if(typeof Ve=="string"&&wF(Ve)&&(Z.isHiddenNow()||Z.wasRecentlyHidden(5e3))?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",Ve),_.current?.resolve()):(n?.(Te,"error"),_.current?.reject(new Error(Te))),_.current=null,!N.current){const Be=F.current.trim();Be&&(F.current="",C(""),fe.current(Be))}k()}});x.current=J0(s.id,q,ae,L,e)});return xe.catch(()=>{}),xe},[s,e,n,k,Z]);return fe.current=re,i.useEffect(()=>()=>{x.current&&(x.current.close(),x.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:j,sendMessage:re,stopStreaming:je,clearPendingMessage:ne,switchSession:le,selectSession:ke,startModelChat:He,startFreshSession:ye,refreshSessions:se,loadMessages:$,reloadMessages:k,skipNextSessionInitRef:Q}),[s,r,l,d,m,f,g,v,y,j,re,je,ne,le,ke,He,ye,se,$,k])}function CF(e,n){const[s,a]=i.useState([]),[r,o]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback(async p=>{c(!0);try{const g=n?.filterState,w=g&&g!=="all"?{state:g}:void 0,v=n?.showSystemAgents??!1,b=await Ur({...w,...p,includeEphemeral:p?.includeEphemeral??v},e),y=Array.from(new Map(b.map(S=>[S.id,S])).values());a(y)}catch(g){console.error("Failed to load agents:",g)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=i.useCallback(async()=>{try{const p=await r1(e);o(p)}catch(p){console.error("Failed to load agent stats:",p)}},[e]);i.useEffect(()=>{d(),u()},[d,u]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=()=>{d(),u()};return yi(`/api/events${p}`,{events:{"agent:created":g,"agent:updated":g,"agent:deleted":g,"agent:stateChanged":g,"approval:requested":g,"approval:updated":g,"approval:decided":g}})},[e,d,u]);const m=i.useCallback(async()=>{await Promise.all([d(),u()])},[d,u]),h=n?.showSystemAgents??!1,f=s.filter(p=>p.state!=="active"&&p.state!=="running"?!1:h||!HC(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function EF({visible:e,position:n,files:s,selectedIndex:a,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const d=NC(l.path),u=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===a?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===a,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(nb,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:u}),d&&t.jsx("span",{className:"file-mention-popup-item-path",children:d})]})]},l.path)})})]}):null}const _F=200;function MF(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,m]=i.useState([]),[h,f]=i.useState(!1),[p,g]=i.useState(0),w=i.useRef(null),v=i.useRef(null);i.useEffect(()=>()=>{w.current&&clearTimeout(w.current),v.current?.abort()},[]);const b=i.useCallback((x,N)=>{if(N<0||N>x.length){r(!1);return}const R=F=>/[a-zA-Z0-9/_.-]/.test(F);for(let F=N-1;F>=0;F--){if(x[F]==="#")if(F===0){const E=x.slice(F+1,N);d(F),l(E),g(0),r(!0);return}else{const E=x[F-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const _=x.slice(F+1,N);d(F),l(_),g(0),r(!0);return}r(!1);return}if(!R(x[F])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async x=>{if(!x.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const N=await uS(x,s,n);m(N.files),g(0)}catch(N){N.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{S(o)},_F),()=>{w.current&&clearTimeout(w.current)}},[o,a,S]);const j=i.useCallback((x,N)=>{if(!a||c<0)return N;const R=N.slice(0,c),F=N.slice(c+1),E=F.match(/[\s]|$/),_=E?E.index:F.length,K=F.slice(_);return`${R}#${x.path}${K}`},[a,c]),C=i.useCallback((x,N)=>{if(!a||u.length===0)return!1;switch(x.key){case"ArrowDown":return x.preventDefault(),g(R=>Math.min(R+1,u.length-1)),!0;case"ArrowUp":return x.preventDefault(),g(R=>Math.max(R-1,0)),!0;case"Enter":case"Tab":return u[p]?(x.preventDefault(),!0):!1;case"Escape":return x.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:j,dismissMention:y,handleKeyDown:C}}function AF(e){return`${e.name?.trim()||e.id} (${e.role})`}function fo(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 RF(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 Hl(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function IF(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,a])=>{const r=typeof a=="string"?a:(()=>{try{return JSON.stringify(a)}catch{return String(a)}})();return`${s}=${Hl(r,50)}`}).join(", ")}function TF(e){if(e===void 0)return null;if(typeof e=="string")return Hl(e,200);try{return Hl(JSON.stringify(e),200)}catch{return Hl(String(e),200)}}function Qv(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",w=f.status==="completed"&&f.isError,v=IF(f.args),b=TF(f.result),y=g?v:b?`result: ${b}`:v?`args: ${v}`:null,S=n?null:y,j=g?"running":w?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${w?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:j})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${w?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:b})]})]})]},`${f.toolName}-${p}`)},a=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:a,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Om,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),d=c.slice(0,5),u=Math.max(0,c.length-d.length),m=u>0?`${d.join(", ")}, +${u} more`:d.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:a,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Om,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((f,p)=>s(f,p))]})})}const Xv={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 jg(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",a=n[2]??"",r=n.index+s.length;return{filter:a,start:r,end:e.length}}function PF(e,n){const s=e.slice(0,n),a=/(^|[\s])@([\w-]*)$/.exec(s);if(!a)return null;const r=a[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Fl={width:320,height:400},$F=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),DF=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function LF(e){return e.type.startsWith("image/")}function OF(e){if($F.has(e.type))return!0;const n=e.name.toLowerCase();return DF.some(s=>n.endsWith(s))}const gr={width:280,height:260},Ls=768,br=8;function FF(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const j=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return j&&parseFloat(j)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const j=`fusion-quick-chat-position-${e||"default"}`;try{const C=localStorage.getItem(j);if(C){const x=JSON.parse(C);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=i.useRef(r),m=i.useRef(null),h=i.useRef(null),f=n??i.useRef(!1);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback(j=>{if(typeof window>"u")return j;const C=48,x=window.innerWidth<=768?4:8,N=window.innerWidth<=768?44:0,R=window.innerWidth>768?s():0,F=window.innerWidth-C-x,E=window.innerHeight-C-x-N-R;return{x:Math.max(x,Math.min(F,j.x)),y:Math.max(x,Math.min(E,j.y))}},[s]),g=i.useCallback(j=>{if(typeof window>"u")return;const C=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(C,JSON.stringify(j))}catch{}},[e]),w=i.useCallback(()=>{if(!d.current)return;const j=h.current,C=m.current;j&&C!==null&&typeof j.releasePointerCapture=="function"&&j.releasePointerCapture(C),d.current=null,m.current=null,h.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y)},[g]),v=i.useCallback(j=>{if(!d.current||m.current!==null&&j.pointerId!==m.current)return;const C=j.clientX-d.current.pointerX,x=j.clientY-d.current.pointerY;if((Math.abs(C)>=5||Math.abs(x)>=5)&&(f.current=!0),!f.current)return;const N=d.current.x-C,R=d.current.y-x,F=p({x:N,y:R});u.current=F,o(F)},[p]),b=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||w()},[w]),y=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||w()},[w]),S=i.useCallback(j=>{if(j.button!==0&&j.pointerType==="mouse")return;const C=j.currentTarget;j.preventDefault(),typeof C.setPointerCapture=="function"&&C.setPointerCapture(j.pointerId);const x=u.current;d.current={x:x.x,y:x.y,pointerX:j.clientX,pointerY:j.clientY},m.current=j.pointerId,h.current=C,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",v,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",y)},[y,v,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y),document.body.style.userSelect=""},[y,v,b]),{position:r,isDragging:l,handlePointerDown:S}}function zF(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Ls,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const w=Math.max(gr.width,window.innerWidth-p-br),v=Math.max(gr.height,window.innerHeight-g-br);return{width:Math.max(gr.width,Math.min(w,f.width)),height:Math.max(gr.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ls)return Fl;try{const f=localStorage.getItem(a);if(!f)return Fl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Fl:{width:p.width,height:p.height}}catch{return Fl}},[a]),[c,d]=i.useState(l),[u,m]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const h=i.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const w={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-w.pointerX,j=y.clientY-w.pointerY;let C=w.width,x=w.height,N=w.anchorRight,R=w.anchorBottom;if(p.includes("w")&&(C=w.width-S),p.includes("e")){const A=S;C=w.width+A,N=w.anchorRight-A}if(p.includes("n")&&(x=w.height-j),p.includes("s")){const A=j;x=w.height+A,R=w.anchorBottom-A}const F=n+N,E=s+R,_=o({width:C,height:x},F,E),K=Math.max(br-n,Math.min(window.innerWidth-n-gr.width-br,N)),U=Math.max(br-s,Math.min(window.innerHeight-s-gr.height-br,R));d(_),m({right:K,bottom:U})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const Ng=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,roomContext:r,onToggleRender:o}){const l=n.role==="user",c=i.useMemo(()=>{if(!l)return null;const u=n.content,m=/@([\w-]+)/g,h=[];let f=0,p=m.exec(u);for(;p;){const[g,w=""]=p,v=p.index;v>f&&h.push(u.slice(f,v));const b=w.replace(/_/g," ").toLowerCase(),y=a.get(b);if(y){const S=!!(r&&!r.memberIds.has(y.id)),j=S?`Not a member of ${r?.roomName}`:void 0;h.push(t.jsxs("span",{className:`chat-mention-chip${S?" chat-mention-chip--non-member":""}`,title:j,"aria-label":j,children:["@",y.name.replace(/\s+/g,"_")]},`${y.id}-${v}`))}else h.push(g);f=v+g.length,p=m.exec(u)}return f<u.length&&h.push(u.slice(f)),h.length===0?u:h},[l,n.content,a,r]),d=i.useMemo(()=>l?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(xi,{remarkPlugins:[vi],components:Xv,children:n.content})}),[l,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${l?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[l?t.jsx("p",{children:c}):t.jsxs(t.Fragment,{children:[d,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>o(n.id),children:s?t.jsx(zu,{size:14}):t.jsx(Fr,{size:14})})]}),Qv(n.toolCalls,!0)]})});function BF({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d,roomContext:u=null}){const{agents:m}=CF(e),[h,f]=i.useState(!1),p=a!==void 0,g=p?a:h,w=p?ie=>{r?.(typeof ie=="function"?ie(g):ie)}:f,{keyboardOpen:v}=aa({enabled:g}),b=oi(),y=b==="mobile",[S,j]=i.useState("agent"),[C,x]=i.useState(""),[N,R]=i.useState(!1),[F,E]=i.useState("model"),[_,K]=i.useState(""),[U,A]=i.useState(""),[T,H]=i.useState([]),[Q,se]=i.useState(!1),[O,M]=i.useState(""),[D,$]=i.useState(""),[k,X]=i.useState(""),[le,ke]=i.useState([]),[He,ye]=i.useState(!1),[je,ne]=i.useState(!1),[fe,Z]=i.useState(""),[re,q]=i.useState(0),[L,xe]=i.useState(""),[he,B]=i.useState(!1),[pe,ze]=i.useState(0),[ae,Ve]=i.useState(-1),[Te,rt]=i.useState(()=>new Set),[Be,ce]=i.useState(!1),[Re,Le]=i.useState([]),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState(!1),[,Ee]=i.useState(!1),[ft,ht]=i.useState({top:0,left:0}),tt=MF({projectId:e}),xt=i.useCallback(ie=>{if(!ie||!tt.mentionActive)return;const $e=ie.getBoundingClientRect();ht({top:$e.top-260,left:$e.left+8})},[tt.mentionActive]),Me=i.useRef(!1),Ye=i.useRef(!1),dt=i.useRef(!1),wt=i.useRef(""),St=i.useRef(!1),Fe=i.useRef(C),J=i.useRef(O),me=i.useRef(0),Ze=i.useRef(null),be=i.useRef(null),gt=i.useRef(0),{position:$t,isDragging:Ie,handlePointerDown:ge}=FF(e,Me),st=$t.y+60,{panelSize:yt,anchorOffset:pt,handleResizeStart:vt}=zF(e,$t.x,st),Ut=typeof window<"u"&&window.innerWidth>Ls,{activeSession:Dt,messages:nn,isStreaming:on,streamingText:sn,streamingThinking:ln,streamingToolCalls:xn,sessions:qt,sessionsLoading:Qt,messagesLoading:hn,sendMessage:Zt,stopStreaming:ve,pendingMessage:Pe,clearPendingMessage:Ke,switchSession:at,selectSession:We,startModelChat:It,startFreshSession:Lt,refreshSessions:Bt,skipNextSessionInitRef:Gt}=SF(e,n),bt=i.useRef(null),Ot=i.useRef(null),en=i.useRef(null),Kt=i.useRef(null),Sn=i.useRef(null),dn=i.useRef([]),Jt=i.useRef(!1),tn=i.useRef(!1),Ne=i.useRef(!1),W=i.useRef(null),Y=i.useRef(!1),_e=i.useRef(!1),ut=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!g||typeof window>"u"||typeof document>"u"||window.innerWidth>Ls)return;const ie=window.scrollY,$e=document.documentElement,Qe=document.body,Ft={htmlOverflow:$e.style.overflow,bodyOverflow:Qe.style.overflow};return window.scrollTo(0,0),$e.style.overflow="hidden",Qe.style.overflow="hidden",()=>{$e.style.overflow=Ft.htmlOverflow,Qe.style.overflow=Ft.bodyOverflow,window.scrollTo(0,ie)}},[g]),i.useLayoutEffect(()=>{if(!g||typeof window>"u"||!window.visualViewport)return;const ie=bt.current;if(!ie)return;const $e=window.visualViewport,Qe=()=>{Y.current||(ie.style.setProperty("--vv-height",`${$e.height}px`),ie.style.setProperty("--vv-offset-top",`${$e.offsetTop||0}px`))};return Qe(),$e.addEventListener("resize",Qe),$e.addEventListener("scroll",Qe),()=>{$e.removeEventListener("resize",Qe),$e.removeEventListener("scroll",Qe)}},[g]);const At=O||D,zt=i.useMemo(()=>fo(At),[At]),yn=i.useMemo(()=>S==="model"&&Dt?.modelProvider&&Dt?.modelId?`${Dt.modelProvider}/${Dt.modelId}`:At,[Dt?.modelId,Dt?.modelProvider,S,At]),Zn=i.useMemo(()=>fo(yn),[yn]),vn=i.useMemo(()=>T.find(ie=>`${ie.provider}/${ie.id}`===yn)??null,[yn,T]),Dn=i.useMemo(()=>RF(vn,Zn),[vn,Zn]),de=i.useMemo(()=>S==="model"?zt?`${yr}::${zt.modelProvider}/${zt.modelId}`:"":C?`${C}::`:"",[S,C,zt]),ot=!(S==="agent"?!!C:!!zt)||!Dt,_t=i.useMemo(()=>!!C&&qt.some(ie=>!ie.modelProvider&&!ie.modelId&&ie.agentId===C),[C,qt]);i.useEffect(()=>{Fe.current=C},[C]),i.useEffect(()=>{J.current=O},[O]),i.useEffect(()=>{if(m.length===0){x(""),j("model");return}if(St.current&&_t)return;m.some($e=>$e.id===C)||x(m[0]?.id??"")},[m,_t,C]),i.useEffect(()=>{!g||Ye.current||(Ye.current=!0,dt.current=!1,se(!0),Ws().then(ie=>{const $e=ie.models??[];if(H($e),J.current||$e.length===0)return;const Qe=ie.defaultProvider,Ft=ie.defaultModelId;if(Qe&&Ft){const pn=`${Qe}/${Ft}`;if($e.some(Un=>`${Un.provider}/${Un.id}`===pn)){$(pn),J.current||M(pn),St.current||j("model");return}}$("");const cn=$e[0];cn&&!J.current&&M(`${cn.provider}/${cn.id}`)}).catch(ie=>{console.error("[QuickChatFAB] Failed to load models:",ie),H([]),$("")}).finally(()=>{dt.current=!0,se(!1)}))},[g,m.length,O]),i.useEffect(()=>{!g||!e||(ye(!0),H0(e).then(ie=>{ke(ie)}).catch(()=>{ke([])}).finally(()=>{ye(!1)}))},[g,e]),i.useEffect(()=>{g&&Bt()},[g,Bt]),i.useEffect(()=>{if(!g||Qt||St.current||qt.length===0)return;const ie=qt[0];ie&&(ie.modelProvider&&ie.modelId?(j("model"),M(`${ie.modelProvider}/${ie.modelId}`)):(j("agent"),x(ie.agentId)),St.current=!0)},[g,qt,Qt]),i.useEffect(()=>{if(!g){wt.current="";return}if(!St.current&&qt.length===0&&Ye.current&&!dt.current)return;if(!de){wt.current="";return}if(Gt.current){wt.current=de;return}const $e=de===wt.current&&!Dt&&!Qt;if(!(de===wt.current&&!$e)){if(wt.current=de,S==="model"&&zt){It(zt.modelProvider,zt.modelId);return}S==="agent"&&C&&at(C)}},[g,S,zt,C,de,Dt,Qt,It,at,Gt]),i.useEffect(()=>{g||(B(!1),xe(""),Ve(-1),ne(!1),Z(""),q(0),dn.current.forEach(ie=>{ie.previewUrl&&URL.revokeObjectURL(ie.previewUrl)}),Le([]))},[g]),i.useEffect(()=>{dn.current=Re},[Re]),i.useEffect(()=>{if(!g){Jt.current=!1;return}typeof window>"u"||(Jt.current=window.innerWidth<=Ls)},[g]),i.useEffect(()=>{if(!g||ot||!Jt.current)return;const ie=Kt.current;if(!ie)return;const $e=document.activeElement,Qe=$e?bt.current?.contains($e):!1,Ft=$e===document.body,cn=$e===W.current;if(!Qe&&!Ft&&!cn){Jt.current=!1;return}if(cn){ie.focus({preventScroll:!0}),Jt.current=!1;return}const pn=requestAnimationFrame(()=>{ie.focus(),Jt.current=!1});return()=>cancelAnimationFrame(pn)},[g,ot]),i.useEffect(()=>()=>{dn.current.forEach(ie=>{ie.previewUrl&&URL.revokeObjectURL(ie.previewUrl)})},[]);const G=i.useCallback(()=>{R(!0),E("model"),K(m[0]?.id??""),A(O||D||"")},[m,D,O]),Oe=i.useMemo(()=>m.find(ie=>ie.id===C)??null,[m,C]),Mt=i.useMemo(()=>{const ie=fe.trim().toLowerCase();return(ie?le.filter(Qe=>Qe.name.toLowerCase().includes(ie)):le).slice(0,10)},[le,fe]),Xt=i.useMemo(()=>{const ie=m.filter(Ft=>Jv(Ft.name,L));if(!u)return ie;const $e=ie.filter(Ft=>u.memberIds.has(Ft.id));if(L.trim().length===0)return $e;const Qe=ie.filter(Ft=>!u.memberIds.has(Ft.id));return[...$e,...Qe]},[m,L,u]),_n=i.useMemo(()=>{const ie=new Map;for(const $e of m)ie.set($e.name.toLowerCase(),$e);return ie},[m]);i.useEffect(()=>{q(0)},[Mt]),i.useEffect(()=>{ze(0)},[L,he]),i.useEffect(()=>()=>{Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null),be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),i.useEffect(()=>{if(!g)return;const ie=Qe=>{const Ft=Qe.target;bt.current?.contains(Ft)||Ot.current?.contains(Ft)||Ft.closest(".model-combobox-dropdown--portal")||w(!1)},$e=Qe=>{Qe.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",ie),document.addEventListener("keydown",$e),()=>{document.removeEventListener("mousedown",ie),document.removeEventListener("keydown",$e)}},[g,w]);const Pn=i.useCallback(()=>{const ie=en.current;if(!ie)return;const Qe=ie.scrollTop+ie.clientHeight>=ie.scrollHeight-50;oe(!Qe),_e.current=!Qe},[]),kn=i.useCallback(ie=>{if(!ie.isConnected)return;let $e=0,Qe=0,Ft=-1;const cn=6,pn=()=>{if(ie.isConnected){if(ie.scrollTop=ie.scrollHeight,ie.scrollHeight===Ft?Qe+=1:(Qe=0,Ft=ie.scrollHeight),$e+=1,$e>=cn||Qe>=2){oe(!1),_e.current=!1;return}window.requestAnimationFrame(pn)}};pn()},[]),Vn=i.useCallback(()=>{const ie=en.current;ie&&kn(ie)},[kn]);i.useLayoutEffect(()=>{const ie=Dt?.id??null,$e=ut.current;if(ut.current={isOpen:g,sessionId:ie},!g||!ie)return;const Qe=!$e.isOpen&&g,Ft=$e.isOpen&&$e.sessionId!==ie;if(!Qe&&!Ft)return;const cn=en.current;cn&&kn(cn)},[g,Dt?.id,kn]),i.useEffect(()=>{if(!y||!g||!Dt)return;const ie=()=>{const Qe=en.current;Qe&&kn(Qe)},$e=()=>{document.visibilityState==="visible"&&ie()};return document.addEventListener("visibilitychange",$e),window.addEventListener("pageshow",ie),()=>{document.removeEventListener("visibilitychange",$e),window.removeEventListener("pageshow",ie)}},[y,g,Dt,kn]),i.useEffect(()=>{g&&(_e.current||Vn())},[nn,sn,ln,on,g,Vn]);const $s=i.useMemo(()=>{const ie=new Map(m.map(Qe=>[Qe.id,Qe.name?.trim()||Qe.id])),$e=new Map(T.map(Qe=>[`${Qe.provider}/${Qe.id}`,Qe.name?.trim()||""]));return qt.map((Qe,Ft)=>{const cn=Qe.title?.trim()||`Session ${Ft+1}`;let pn=null;if(Qe.agentId&&Qe.agentId!==yr)pn=ie.get(Qe.agentId)||Qe.agentId;else if(Qe.modelProvider&&Qe.modelId){const jn=`${Qe.modelProvider}/${Qe.modelId}`,Un=$e.get(jn);pn=Un?`${Un} [${jn}]`:jn}return{id:Qe.id,label:pn?`${cn} — ${pn}`:cn}})},[m,T,qt]),vs=i.useMemo(()=>S==="agent"?Oe?`Message ${Oe.name||Oe.id}`:"Select an agent to start chatting":Dn?`Message ${Dn}`:"Select a model to start chatting",[S,Oe,Dn]),As=i.useCallback(ie=>{const $e=qt.find(Qe=>Qe.id===ie);$e&&(St.current=!0,$e.modelProvider&&$e.modelId?(j("model"),M(`${$e.modelProvider}/${$e.modelId}`)):(j("agent"),x($e.agentId)),We($e))},[We,qt]),bn=i.useCallback(async()=>{if(!Qt){if(St.current=!0,F==="agent"){if(!_)return;j("agent"),x(_),await Lt(_)}else{const ie=fo(U||O||D);if(!ie)return;j("model"),M(`${ie.modelProvider}/${ie.modelId}`),await Lt(yr,ie.modelProvider,ie.modelId)}await Bt(),R(!1),E("model")}},[D,_,F,U,Bt,O,Qt,Lt]),Ht=Pe.length>50?`${Pe.slice(0,50)}…`:Pe,On=i.useCallback(ie=>{if(!ie||ie.length===0)return;const $e=[];for(let Qe=0;Qe<ie.length;Qe+=1){const Ft=ie[Qe];OF(Ft)&&$e.push({file:Ft,previewUrl:LF(Ft)?URL.createObjectURL(Ft):""})}$e.length>0&&Le(Qe=>[...Qe,...$e])},[]),Fn=i.useCallback(ie=>{Le($e=>{const Qe=$e[ie];return Qe?.previewUrl&&URL.revokeObjectURL(Qe.previewUrl),$e.filter((Ft,cn)=>cn!==ie)})},[]),as=i.useCallback(ie=>{On(ie.clipboardData?.files)},[On]),Wn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ls)return;const ie=Kt.current;!ie||ie.disabled||ie.focus({preventScroll:!0})},[]),Rs=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Ls||(Ne.current=!0)},[]),In=i.useCallback(async()=>{const ie=k.trim(),$e=dn.current;if(!(!ie&&$e.length===0)&&!ot){if(X(""),B(!1),xe(""),Ve(-1),ie==="/help"){ce(!0),Wn(),Ne.current=!1;return}if(ie==="/clear"||ie==="/new"){ve(),Ke(),$e.forEach(Qe=>{Qe.previewUrl&&URL.revokeObjectURL(Qe.previewUrl)}),Le(Qe=>Qe.filter(Ft=>!$e.includes(Ft)));try{if(S==="model"){const Qe=fo(At);if(!Qe)return;await Lt(yr,Qe.modelProvider,Qe.modelId)}else C&&await Lt(C)}catch{n("Failed to clear conversation","error")}finally{Wn(),Ne.current=!1}return}try{ce(!1),await Zt(ie,$e.map(Qe=>Qe.file)),$e.forEach(Qe=>{Qe.previewUrl&&URL.revokeObjectURL(Qe.previewUrl)}),Le(Qe=>Qe.filter(Ft=>!$e.includes(Ft)))}catch{}finally{Wn(),Ne.current=!1}}},[n,S,Ke,Wn,ot,k,At,C,Zt,Lt,ve]),rs=i.useCallback(ie=>{ie.preventDefault(),gt.current+=1,Ue(!0)},[]),Ns=i.useCallback(ie=>{ie.preventDefault(),ie.dataTransfer.dropEffect="copy",Ue(!0)},[]),ys=i.useCallback(ie=>{ie.preventDefault(),gt.current=Math.max(0,gt.current-1),gt.current===0&&Ue(!1)},[]),cs=i.useCallback(ie=>{ie.preventDefault(),gt.current=0,Ue(!1),On(ie.dataTransfer?.files)},[On]),ss=i.useCallback((ie,$e)=>{const Qe=PF(ie,$e);if(Qe){B(!0),xe(Qe.filter),Ve(Qe.start);return}B(!1),xe(""),Ve(-1)},[]),te=i.useCallback(ie=>{X($e=>{const Qe=jg($e);if(!Qe)return $e;const Ft=`/skill:${ie.name} `,cn=$e.slice(0,Qe.start)+Ft+$e.slice(Qe.end);return window.requestAnimationFrame(()=>{Kt.current&&Kt.current.focus()}),cn}),ne(!1),Z(""),q(0)},[]),we=i.useCallback(ie=>{const $e=Kt.current;if(!$e||ae<0)return;const Qe=$e.selectionStart??me.current,Ft=$e.selectionEnd??Qe,cn=Math.max(Qe,Ft),pn=Math.min(ae,cn),Un=`${`@${ie.name.replace(/\s+/g,"_")}`} `,gs=k.slice(0,pn)+Un+k.slice(cn),bs=pn+Un.length;X(gs),B(!1),xe(""),ze(0),Ve(-1),window.requestAnimationFrame(()=>{Kt.current&&(Kt.current.focus(),Kt.current.setSelectionRange(bs,bs))})},[ae,k]),P=i.useCallback(ie=>{const $e=ie.target.value,Qe=ie.target.selectionStart??$e.length;me.current=Qe,X($e),Be&&$e.trim().length>0&&ce(!1),ss($e,Qe);const Ft=jg($e);Ft?(ne(!0),Z(Ft.filter)):(ne(!1),Z("")),tt.detectMention($e,Qe),Ee(tt.mentionActive),tt.mentionActive&&xt(ie.target)},[Be,ss,tt,xt]),Ce=i.useCallback(()=>{if(Ne.current){window.requestAnimationFrame(()=>{Wn()});return}typeof window<"u"&&window.innerWidth<=Ls&&bt.current&&(Y.current=!0,bt.current.style.removeProperty("--vv-height"),bt.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Y.current=!1},450)),Ze.current!==null&&window.clearTimeout(Ze.current),Ze.current=window.setTimeout(()=>{B(!1),xe(""),Ve(-1),Ee(!1),tt.dismissMention(),Ze.current=null},120),be.current!==null&&window.clearTimeout(be.current),be.current=window.setTimeout(()=>{ne(!1),be.current=null},120)},[tt,Wn]),qe=i.useCallback(()=>{Y.current=!1,Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null),be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),et=i.useCallback(ie=>{const $e=ie.currentTarget,Qe=$e.selectionStart??$e.value.length;me.current=Qe,ss($e.value,Qe),tt.detectMention($e.value,Qe),Ee(tt.mentionActive),tt.mentionActive&&xt($e)},[ss,tt,xt]),mt=i.useCallback(ie=>{ie.key!=="Escape"&&et(ie)},[et]),Nt=i.useCallback(ie=>{rt($e=>{const Qe=new Set($e);return Qe.has(ie)?Qe.delete(ie):Qe.add(ie),Qe})},[]),Pt=i.useCallback((ie,$e=!1)=>$e?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:ie}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(xi,{remarkPlugins:[vi],components:Xv,children:ie})}),[]),an=i.useCallback(ie=>{if(me.current=ie.currentTarget.selectionStart??me.current,tt.mentionActive&&tt.files.length>0){if(tt.handleKeyDown(ie,k),ie.key==="Enter"||ie.key==="Tab"){const $e=tt.files[tt.selectedIndex];if($e){const Qe=tt.selectFile($e,k);X(Qe),tt.dismissMention(),Ee(!1)}}return}if(he&&ie.key==="ArrowDown"){ie.preventDefault(),Xt.length>0&&ze($e=>($e+1)%Xt.length);return}if(he&&ie.key==="ArrowUp"){ie.preventDefault(),Xt.length>0&&ze($e=>$e===0?Xt.length-1:$e-1);return}if(he&&ie.key==="Enter"){ie.preventDefault();const $e=Xt[pe]??Xt[0];$e&&we($e);return}if(he&&ie.key==="Escape"){ie.preventDefault(),ie.stopPropagation(),B(!1),xe(""),Ve(-1);return}if(je&&Mt.length>0&&ie.key==="ArrowDown"){ie.preventDefault(),q($e=>($e+1)%Mt.length);return}if(je&&Mt.length>0&&ie.key==="ArrowUp"){ie.preventDefault(),q($e=>$e===0?Mt.length-1:$e-1);return}if(je&&(ie.key==="Enter"||ie.key==="Tab")){ie.preventDefault();const $e=Mt[re]??Mt[0];$e&&te($e);return}if(je&&ie.key==="Escape"){ie.preventDefault(),ne(!1),Z("");return}ie.key!=="Enter"||ie.shiftKey||(ie.preventDefault(),In())},[he,Xt,pe,we,In,tt,k,je,Mt,re,te]),Cn=i.useCallback(()=>{if(Me.current){Me.current=!1;return}if(g){w(!1);return}typeof window<"u"&&window.innerWidth<=Ls&&W.current?.focus({preventScroll:!0}),w(!0)},[g,w]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:W,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Ot,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":Ie?"true":"false",style:{right:$t.x,bottom:$t.y},onPointerDown:ge,onClick:Cn,children:t.jsx(Zi,{size:24})}),g&&t.jsxs("div",{className:`quick-chat-panel${y&&v?" quick-chat-panel--keyboard-open":""}`,ref:bt,"data-testid":"quick-chat-panel",style:{...Ut?{right:$t.x+pt.right,bottom:st+pt.bottom,width:yt.width,height:yt.height}:{}},children:[Ut&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:vt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:vt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:vt,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:vt,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:vt,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:vt,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:vt,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:vt,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),S==="model"&&Dn&&(()=>{const ie=vn?.provider??Zn?.modelProvider??"";return b==="mobile"&&Dn.length>12&&ie?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Dn,"aria-label":Dn,children:t.jsx(zn,{provider:ie,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Dn,children:Dn})})()]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:G,disabled:Qt,children:t.jsx($n,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>w(!1),children:t.jsx(mn,{size:16})})]})]}),t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:[t.jsx("label",{htmlFor:"quick-chat-session-select",className:"visually-hidden",children:"Select session"}),t.jsxs("select",{id:"quick-chat-session-select",value:Dt?.id??"",onChange:ie=>As(ie.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Qt?"Loading sessions…":"Select a session"}),$s.map(ie=>t.jsx("option",{value:ie.id,children:ie.label},ie.id))]})]}),N&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${F==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>E("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${F==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>E("agent"),children:"Agent"})]}),F==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:_,onChange:ie=>K(ie.target.value),"data-testid":"quick-chat-new-agent-select",children:m.map(ie=>t.jsx("option",{value:ie.id,children:AF(ie)},ie.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(_s,{id:"quick-chat-new-model-select",models:T,value:U,onChange:A,label:"Select model override",placeholder:Q?"Loading models…":"Select a model",disabled:Q||T.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:d})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{R(!1),E("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void bn(),disabled:Qt||(F==="agent"?!_:!fo(U||O||D)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:en,"data-testid":"quick-chat-messages",onScroll:Pn,children:Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):on?t.jsxs(t.Fragment,{children:[nn.map(ie=>t.jsx(Ng,{message:ie,forcePlain:ie.role!=="user"&&Te.has(ie.id),mentionAgentsByName:_n,roomContext:u,onToggleRender:Nt},ie.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Pt("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")}),t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[sn?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Pt(sn,Te.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Te.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Te.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Nt("__streaming__"),children:Te.has("__streaming__")?t.jsx(zu,{size:14}):t.jsx(Fr,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:ln?"Thinking…":"Connecting…"}),Qv(xn,!0),ln&&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:ln})]})]})]}):hn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):nn.length===0&&!sn&&!ln&&!on&&!Be?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[nn.map(ie=>t.jsx(Ng,{message:ie,forcePlain:ie.role!=="user"&&Te.has(ie.id),mentionAgentsByName:_n,roomContext:u,onToggleRender:Nt},ie.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Pt("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),ue&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:Vn,children:[t.jsx(gn,{size:14}),"Latest"]}),Re.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Re.map((ie,$e)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${$e}`,children:[ie.previewUrl?t.jsx("img",{src:ie.previewUrl,alt:ie.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ie.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${$e}`,"aria-label":`Remove ${ie.file.name}`,onClick:()=>Fn($e),children:"×"})]},`${ie.file.name}-${$e}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${ct?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:rs,onDragOver:Ns,onDragLeave:ys,onDrop:cs,children:[t.jsx("input",{ref:Sn,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:ie=>{On(ie.target.files),ie.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Sn.current?.click(),children:t.jsx(ab,{size:16})}),t.jsx("input",{ref:Kt,type:"text",value:k,onChange:P,onKeyDown:an,onKeyUp:mt,onClick:et,onBlur:Ce,onFocus:qe,onPaste:as,onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||document.activeElement!==ie.currentTarget&&(ie.preventDefault(),ie.currentTarget.focus({preventScroll:!0}))},placeholder:vs,disabled:ot,"data-testid":"quick-chat-input"}),on?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),ie.pointerType&&ie.pointerType!=="mouse"&&(tn.current=!0,ve()))},onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),tn.current=!0,ve())},onMouseDown:ie=>{typeof window>"u"||window.innerWidth>Ls||ie.preventDefault()},onClick:()=>{if(tn.current){tn.current=!1;return}ve()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx($i,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),ie.pointerType&&ie.pointerType!=="mouse"&&(tn.current=!0,Rs(),Wn(),In()))},onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),tn.current=!0,Rs(),Wn(),In())},onMouseDown:ie=>{typeof window>"u"||window.innerWidth>Ls||ie.preventDefault()},onClick:()=>{if(tn.current){tn.current=!1;return}In()},disabled:ot||k.trim().length===0&&Re.length===0,"data-testid":"quick-chat-send",children:t.jsx(Da,{size:16})})]}),t.jsx(vF,{agents:m,filter:L,highlightedIndex:pe,visible:he,onSelect:we,position:"above",roomMemberIds:u?.memberIds,roomName:u?.roomName}),t.jsx(EF,{visible:tt.mentionActive&&!he,position:ft,files:tt.files,selectedIndex:tt.selectedIndex,onSelect:ie=>{const $e=tt.selectFile(ie,k);X($e),tt.dismissMention(),Ee(!1),Kt.current?.focus()},loading:tt.loading}),je&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:He?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):Mt.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:fe?"No skills found":"No skills available"}):Mt.map((ie,$e)=>t.jsxs("button",{type:"button",role:"option","aria-selected":$e===re,className:`chat-skill-menu-item${$e===re?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Qe=>Qe.preventDefault(),onMouseEnter:()=>q($e),onClick:()=>te(ie),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:ie.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:ie.relativePath,children:ie.relativePath})]},ie.id))}),Pe&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Ht}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Ke,children:"×"})]})]})})]})]})}function go(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Sg(e){return e.status==="generating"||e.status==="awaiting_input"}function bo(e){return e==="complete"||e==="error"}function UF(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Wr(),u=i.useCallback(()=>{Wu(e).then(p=>{const g=p.filter(v=>{const b=go(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),w=new Map;for(const v of g)w.set(v.id,go(v.updatedAt));a.current=w,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);i.useEffect(()=>{d(),u()},[u,d]),i.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const w=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=a.current.get(v.sessionId)??0;if(b<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!bo(v.status)&&r.current.delete(v.sessionId),bo(v.status)){w.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,b);continue}const j=w.get(v.sessionId),C=v.type??j?.type,x=v.title??j?.title;if(!j&&(!C||!x))continue;const N={id:v.sessionId,type:C??"planning",status:v.status,title:x??"AI Session",projectId:v.projectId??j?.projectId??e??null,lockedByTab:v.owningTabId??j?.lockedByTab??null,updatedAt:v.updatedAt??j?.updatedAt??new Date(b).toISOString()},R=w.get(v.sessionId);(!R||R.status!==N.status||R.title!==N.title||R.type!==N.type||R.projectId!==N.projectId||R.lockedByTab!==N.lockedByTab||R.updatedAt!==N.updatedAt)&&(w.set(v.sessionId,N),a.current.set(v.sessionId,b),g=!0)}return g?[...w.values()].sort((v,b)=>go(b.updatedAt)-go(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const b=JSON.parse(v.data),y=go(b.updatedAt)||Date.now();s(S=>{const j=a.current.get(b.id)??0;if(y<j)return S;const C=r.current.get(b.id);if(C!==void 0&&y<=C)return S;if(C!==void 0&&y>C&&!bo(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),bo(b.status))return S.filter(N=>N.id!==b.id);const x=S.findIndex(N=>N.id===b.id);if(x>=0){const N=[...S];return N[x]=b,N}return Sg(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),bo(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},w=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(j=>j.id!==b))}catch{}};return yi(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":w},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const w=n.find(S=>S.id===p)?.type,v=Ja();let b=!1;if(w==="planning")try{await pb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(w==="subtask")try{await bb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(w==="mission_interview")try{await kb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await jb(p)}catch{}s(S=>S.filter(j=>j.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>Sg(p)),[n]),f=i.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:m,refresh:u}}const mc="fusion:hide-session-banners",Lu="fusion:session-banner-pref-changed";function HF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(mc)==="1"}catch{return!1}}function qF(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===mc&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Lu,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Lu,s)}}function D8(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(mc,"1"):window.localStorage.removeItem(mc),window.dispatchEvent(new Event(Lu))}catch{}}function VF(){return i.useSyncExternalStore(qF,HF,()=>!1)}function Ss(e){return{...e,column:Db(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Cg(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function WF(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function Yd(e,n){if(Cg(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return WF(e,n);const a=Cg(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:a>=0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function GF(e){const n=e?.projectId,s=e?.searchQuery,a=e?.sseEnabled??!0,[r,o]=i.useState([]),[l,c]=i.useState(!1),d=i.useRef(l);d.current=l;const u=i.useRef(r),m=i.useRef(0),h=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),w=i.useRef(0),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,w.current++);const b=1e3,y=i.useCallback(async se=>{const O=++m.current,M=n,D=se?.searchQueryOverride??f.current,$=se?.includeArchivedOverride??d.current;try{const k=await Oj(void 0,void 0,M,D,$);if(m.current!==O||n!==M)return;o(k.map(Ss)),g.current=Date.now()}catch{if(m.current!==O||n!==M)return;if(se?.clearOnError){o([]);return}o(k=>k)}},[n]);p.current=y;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),j=i.useRef(s);i.useEffect(()=>{if(s===void 0&&j.current===void 0)return;j.current=s;const se=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(se)},[s]),i.useEffect(()=>{y({clearOnError:!0});const se=()=>{if(document.visibilityState!=="visible")return;const O=Date.now();O-h.current<b||(h.current=O,y())};return document.addEventListener("visibilitychange",se),()=>{document.removeEventListener("visibilitychange",se)}},[y]),i.useEffect(()=>{if(a===!1)return;const se=w.current,O=n?`?projectId=${encodeURIComponent(n)}`:"",M=()=>w.current!==se;let D=!0;const $=ye=>{if(M())return;const je=Ss(JSON.parse(ye.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(ne=>{const fe=ne.findIndex(L=>L.id===je.id);if(fe===-1)return[...ne,je];const Z=ne[fe],re=Yd(Z,je);if(re===Z)return ne;const q=[...ne];return q[fe]=re,q}),g.current=Date.now()},k=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:je,to:ne}=JSON.parse(ye.data),fe=Ss(je),Z={...fe,column:Db(ne,fe.column)};o(re=>{const q=re.findIndex(xe=>xe.id===Z.id);if(q===-1)return[...re,Z];const L=[...re];return L[q]=Z,L}),g.current=Date.now()},X=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const je=Ss(JSON.parse(ye.data));o(ne=>{const fe=ne.findIndex(L=>L.id===je.id);if(fe===-1)return[...ne,je];const Z=ne[fe],re=Yd(Z,je);if(re===Z)return ne;const q=[...ne];return q[fe]=re,q}),g.current=Date.now()},le=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const je=Ss(JSON.parse(ye.data));o(ne=>ne.filter(fe=>fe.id!==je.id))},ke=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:je}=JSON.parse(ye.data),fe={...Ss(je),column:"done"};o(Z=>{const re=Z.findIndex(L=>L.id===fe.id);if(re===-1)return[...Z,fe];const q=[...Z];return q[re]=fe,q})},He=yi(`/api/events${O}`,{events:{"task:created":$,"task:moved":k,"task:updated":X,"task:deleted":le,"task:merged":ke},onReconnect:()=>{D&&(M()||p.current())}});return()=>{D=!1,He()}},[n,a]);const C=i.useCallback(async se=>{const O=Ss(await db(se,n));return o(M=>M.some(D=>D.id===O.id)?M:[...M,O]),O},[n]),x=i.useCallback(async(se,O,M)=>Ss(await zj(se,O,n,M)),[n]),N=i.useCallback(async se=>Ss(await ub(se,n)),[n]),R=i.useCallback(async(se,O)=>Ss(await Bj(se,n,O)),[n]),F=i.useCallback(async se=>Uj(se,n),[n]),E=i.useCallback(async se=>Ss(await Hj(se,n)),[n]),_=i.useCallback(async se=>Ss(await qj(se,n)),[n]),K=i.useCallback(async se=>{const O=Ss(await Vj(se,n));return o(M=>M.some(D=>D.id===O.id)?M:[...M,O]),O},[n]),U=i.useCallback(async(se,O)=>{const M=u.current.find($=>$.id===se),D=M?{...M,...O,updatedAt:new Date().toISOString()}:void 0;D&&o($=>$.map(k=>k.id===se?D:k));try{const $=Ss(await Us(se,O,n));return o(k=>k.map(X=>X.id===se?$:X)),$}catch($){throw M&&o(k=>k.map(X=>X.id===se?M:X)),$}},[n]),A=i.useCallback(async se=>{const O=Ss(await Gj(se,n));return o(M=>M.map(D=>D.id===se?O:D)),O},[n]),T=i.useCallback(async se=>{const O=Ss(await Kj(se,n));return o(M=>M.map(D=>D.id===se?O:D)),O},[n]),H=i.useCallback(async()=>{const O=(await Jj(n)).map(Ss);return o(M=>M.map(D=>O.find(k=>k.id===D.id)||D)),O},[n]),Q=i.useCallback(se=>{if(se.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const O=se.map(Ss);o(M=>{let D=M;for(const $ of O){const k=D.findIndex(ke=>ke.id===$.id);if(k===-1){D===M&&(D=[...M]),D.push($);continue}const X=D[k],le=Yd(X,$);le!==X&&(D===M&&(D=[...M]),D[k]=le)}return D}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:x,pauseTask:N,deleteTask:R,mergeTask:F,retryTask:E,resetTask:_,duplicateTask:K,updateTask:U,archiveTask:A,unarchiveTask:T,archiveAllDone:H,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:Q,lastFetchTimeMs:g.current}}const KF=5e3,JF=1e3;function YF(e){const s=(d1(e)?e.nodeMappings??e.projectNodeMappings??e.pathMappings??[]:[]).filter(a=>!!a?.nodeId&&!!a?.path).map(a=>({nodeId:a.nodeId,nodeName:a.nodeName,path:a.path,available:a.available!==!1}));return s.length>0?s:e.nodeId&&e.path?[{nodeId:e.nodeId,nodeName:e._sourceNodeName,path:e.path,available:!0}]:[]}function Eg(e){return e.map(n=>({...n,nodeMappings:YF(n)}))}function QF(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const f=await ih();n(Eg(f))}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const w=performance.now();try{const v=await ih(),b=Eg(v),y=Math.round(performance.now()-w);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${y}ms (${b.length} projects)`),f||(n(b),o(null))}catch(v){const b=Math.round(performance.now()-w);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${v instanceof Error?v.message:String(v)}`),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const w=Date.now();w-c.current<JF||(c.current=w,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},KF),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await x1(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await S1(f,p);return n(w=>w.map(v=>v.id===f?g:v)),g},[]),h=i.useCallback(async f=>{await vb(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h}}const XF="kb-dashboard-current-project";function ZF(e){return e??"local"}function ez(e,n={}){const{nodeId:s=null}=n,[a,r]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useRef(!1),u=i.useRef(null),m=ZF(s);i.useEffect(()=>{let p=!1;async function g(){try{const w=await na();if(p)return;u.current=w.dashboardCurrentProjectIdByNode??{};const v=u.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(XF);if(b){const y=JSON.parse(b);y?.id&&e.some(j=>j.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await Bn({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(w=>w.id===a.id)&&e.length>0){const w=e.find(v=>v.status==="active");r(w||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,Bn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,m]);const h=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[m]:p.id};u.current=g,Bn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Bn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Zv=i.createContext(null);function tz({children:e}){const[n,s]=i.useState([]),a=i.useRef(0),r=i.useRef(new Map),o=i.useCallback(c=>{const d=r.current.get(c);d!==void 0&&(clearTimeout(d),r.current.delete(c)),s(u=>u.filter(m=>m.id!==c))},[]),l=i.useCallback((c,d="info")=>{const u=a.current++;s(h=>[...h,{id:u,message:c,type:d}]);const m=setTimeout(()=>o(u),4e3);r.current.set(u,m)},[o]);return i.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),ga.createElement(Zv.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function nz(){const e=i.useContext(Zv);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const ey="kb-dashboard-theme-mode",ty="kb-dashboard-color-theme",ny="kb-dashboard-font-scale-pct",Ou=100,sz=85,iz=125,sy=[...BC],Fu="theme-data",xo="theme-data.css";function az(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${xo}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${xo}`:e.replace(/\/[^/]+$/,`/${xo}`):`/${xo}`:`/${xo}`}const Qs=typeof window<"u",rz=Qs?i.useLayoutEffect:i.useEffect;function iy(e){return e==="dark"||e==="light"||e==="system"}function _g(){if(!Qs)return"dark";try{const e=localStorage.getItem(ey);if(iy(e))return e}catch{}return"dark"}function Mg(){if(!Qs)return"default";try{const e=localStorage.getItem(ty);if(e&&sy.includes(e))return e}catch{}return"default"}function Ag(e){if(Qs)try{localStorage.setItem(ey,e)}catch{}}function Rg(e){if(Qs)try{localStorage.setItem(ty,e)}catch{}}function Fo(e){return typeof e!="number"||!Number.isFinite(e)?Ou:Math.min(iz,Math.max(sz,Math.round(e)))}function Ig(){if(!Qs)return Ou;try{const e=Number(localStorage.getItem(ny));return Fo(e)}catch{return Ou}}function Tg(e){if(Qs)try{localStorage.setItem(ny,String(Fo(e)))}catch{}}function oz(e,n){return e==="system"?n?"dark":"light":e}function lz(e,n,s,a){if(!Qs)return;const r=oz(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Fo(s)}%`}function Pg(){if(!Qs)return;const e=az(),n=document.getElementById(Fu);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=Fu,document.head.appendChild(s)}function $g(){if(!Qs)return;const e=document.getElementById(Fu);e&&e.remove()}function cz(){const[e,n]=i.useState(()=>_g()),[s,a]=i.useState(()=>Mg()),[r,o]=i.useState(()=>Ig()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Qs?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=i.useRef(e),h=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),w=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Qs||!l)return;let S=!1;return na().then(j=>{if(!S&&(iy(j.themeMode)&&!p.current&&(m.current!==j.themeMode&&(m.current=j.themeMode,n(j.themeMode)),_g()!==j.themeMode&&Ag(j.themeMode)),j.colorTheme&&sy.includes(j.colorTheme)&&!g.current&&(h.current!==j.colorTheme&&(h.current=j.colorTheme,a(j.colorTheme)),Mg()!==j.colorTheme&&Rg(j.colorTheme)),!w.current)){const C=Fo(j.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),Ig()!==C&&Tg(C)}}).catch(j=>{console.warn("[useTheme] Failed to hydrate theme from global settings",j)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Qs)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),j=C=>{u(C.matches)};return S.addEventListener("change",j),()=>S.removeEventListener("change",j)},[]),rz(()=>{lz(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Qs||l||(s!=="default"?Pg():$g())},[s,l]);const v=i.useCallback(S=>{p.current=!0,m.current=S,n(S),Ag(S),Bn({themeMode:S}).catch(j=>{console.warn("[useTheme] Failed to persist themeMode to global settings",j)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),Rg(S),S!=="default"?Pg():$g(),Bn({colorTheme:S}).catch(j=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",j)})},[]),y=i.useCallback(S=>{const j=Fo(S);w.current=!0,f.current=j,o(j),Tg(j),Bn({dashboardFontScalePct:j}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function dz(e){const{planningSessions:n}=e,[s,a]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(void 0),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,w]=i.useState(void 0),[v,b]=i.useState(null),[y,S]=i.useState("definition"),[j,C]=i.useState(null),[x,N]=i.useState(!1),[R,F]=i.useState(void 0),[E,_]=i.useState(!1),[K,U]=i.useState(!1),[A,T]=i.useState(!1),[H,Q]=i.useState(null),[se,O]=i.useState(!1),[M,D]=i.useState(!1),[$,k]=i.useState(void 0),[X,le]=i.useState(!1),[ke,He]=i.useState(!1),[ye,je]=i.useState("project"),[ne,fe]=i.useState(null),[Z,re]=i.useState(!1),[q,L]=i.useState(!1),[xe,he]=i.useState(!1),[B,pe]=i.useState(!1),[ze,ae]=i.useState(!1),[Ve,Te]=i.useState(!1),[rt,Be]=i.useState(!1),ce=!!(v||x||s||r||m||M||X||ke||Z||q||xe||ze||B||A||se||E||K||Ve||rt),Re=i.useCallback(()=>a(!0),[]),Le=i.useCallback(()=>a(!1),[]),ct=i.useCallback(()=>o(!0),[]),Ue=i.useCallback(bt=>{c(bt),o(!0)},[]),ue=i.useCallback(()=>{const bt=n[0];bt&&(u(bt.id),o(!0))},[n]),oe=i.useCallback(bt=>{u(bt),o(!0)},[]),Ee=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),ft=i.useCallback(bt=>{p(bt),h(!0)},[]),ht=i.useCallback(bt=>{w(bt),h(!0)},[]),tt=i.useCallback(()=>{h(!1),p(null),w(void 0)},[]),xt=i.useCallback((bt,Ot="definition",en)=>{b(bt),S(Ot),C(en?.origin??null)},[]),Me=i.useCallback(bt=>{b(bt),S("changes"),C(null)},[]),Ye=i.useCallback(bt=>{b(Ot=>Ot&&{...Ot,...bt})},[]),dt=i.useCallback(()=>{b(null),C(null)},[]),wt=i.useCallback(bt=>{F(bt),N(!0)},[]),St=i.useCallback(()=>{N(!1),F(void 0)},[]),Fe=i.useCallback(()=>_(!0),[]),J=i.useCallback(()=>_(!1),[]),me=i.useCallback(()=>U(!0),[]),Ze=i.useCallback(()=>U(!1),[]),be=i.useCallback(bt=>{Q(bt??null),T(!0)},[]),gt=i.useCallback(()=>{T(!1),Q(null)},[]),$t=i.useCallback(()=>O(!0),[]),Ie=i.useCallback(()=>O(!1),[]),ge=i.useCallback(()=>{D(bt=>!bt)},[]),st=i.useCallback(()=>{D(!1),k(void 0)},[]),yt=i.useCallback((bt,Ot)=>{bt&&je(bt),fe(Ot??null),le(!0)},[]),pt=i.useCallback(()=>{le(!1),fe(null)},[]),vt=i.useCallback(()=>He(!0),[]),Ut=i.useCallback(()=>He(!1),[]),Dt=i.useCallback(bt=>{je(bt)},[]),nn=i.useCallback(()=>re(!0),[]),on=i.useCallback(()=>re(!1),[]),sn=i.useCallback(()=>L(!0),[]),ln=i.useCallback(()=>L(!1),[]),xn=i.useCallback(()=>he(!0),[]),qt=i.useCallback(()=>he(!1),[]),Qt=i.useCallback(()=>pe(!0),[]),hn=i.useCallback(()=>pe(!1),[]),Zt=i.useCallback(()=>ae(!0),[]),ve=i.useCallback(()=>ae(!1),[]),Pe=i.useCallback(async(bt,Ot)=>{ae(!1),k(Ot),D(!0)},[]),Ke=i.useCallback(()=>Te(!0),[]),at=i.useCallback(()=>Te(!1),[]),We=i.useCallback(()=>Be(!0),[]),It=i.useCallback(()=>Be(!1),[]),Lt=i.useCallback((bt,Ot)=>{Ot(`Created ${bt.id} from planning mode`,"success"),o(!1),c(null)},[]),Bt=i.useCallback((bt,Ot)=>{const en=bt.map(Kt=>Kt.id).join(", ");Ot(`Created ${en} from planning mode`,"success"),o(!1),c(null)},[]),Gt=i.useCallback((bt,Ot)=>{const en=bt.map(Kt=>Kt.id).join(", ");Ot(`Created ${en} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,detailTaskOrigin:j,settingsOpen:x,settingsInitialSection:R,schedulesOpen:E,githubImportOpen:K,usageOpen:A,usageAnchorRect:H,systemStatsOpen:se,terminalOpen:M,terminalInitialCommand:$,filesOpen:X,todosOpen:ke,fileBrowserWorkspace:ye,fileBrowserInitialFile:ne,activityLogOpen:Z,gitManagerOpen:q,workflowStepsOpen:xe,agentsOpen:B,scriptsOpen:ze,setupWizardOpen:Ve,modelOnboardingOpen:rt,anyModalOpen:ce,openNewTask:Re,closeNewTask:Le,openPlanning:ct,openPlanningWithInitialPlan:Ue,resumePlanning:ue,openPlanningWithSession:oe,closePlanning:Ee,openSubtaskBreakdown:ft,openSubtaskWithSession:ht,closeSubtask:tt,openDetailTask:xt,openDetailWithChangesTab:Me,updateDetailTask:Ye,closeDetailTask:dt,openSettings:wt,closeSettings:St,openSchedules:Fe,closeSchedules:J,openGitHubImport:me,closeGitHubImport:Ze,openUsage:be,closeUsage:gt,openSystemStats:$t,closeSystemStats:Ie,toggleTerminal:ge,closeTerminal:st,openFiles:yt,closeFiles:pt,openTodos:vt,closeTodos:Ut,setFileWorkspace:Dt,openActivityLog:nn,closeActivityLog:on,openGitManager:sn,closeGitManager:ln,openWorkflowSteps:xn,closeWorkflowSteps:qt,openAgents:Qt,closeAgents:hn,openScripts:Zt,closeScripts:ve,runScript:Pe,openSetupWizard:Ke,closeSetupWizard:at,openModelOnboarding:We,closeModelOnboarding:It,onPlanningTaskCreated:Lt,onPlanningTasksCreated:Bt,onSubtaskTasksCreated:Gt}}function uz(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(7200*1e3),[w,v]=i.useState(!1),[b,y]=i.useState(!1),[S,j]=i.useState(!1),[C,x]=i.useState({}),[N,R]=i.useState(!1),[F,E]=i.useState(!1),[_,K]=i.useState(!1),[U,A]=i.useState(!1),[T,H]=i.useState(!0),Q=i.useCallback(async()=>{const[k,X]=await Promise.allSettled([Xj(e),kc(e)]);if(k.status==="fulfilled"&&(s(k.value.maxConcurrent),r(k.value.rootDir)),X.status==="fulfilled"){const le=X.value;l(!!le.autoMerge),d(!!le.globalPause),m(!!le.enginePaused),y(!!le.prAuthAvailable),f(le.taskStuckTimeoutMs),g(le.staleHighFanoutBlockerAgeThresholdMs??7200*1e3),v(le.showQuickChatFAB===!0),x(le.experimentalFeatures??{});const ke=le.experimentalFeatures??{};R(ke.insights===!0),E(ke.memoryView===!0),K(ke.devServerView===!0||ke.devServer===!0),A(ke.todoView===!0);const He=le.autoReloadOnVersionChange!==!1;H(He),zc(He)}j(!0)},[e]);i.useEffect(()=>{j(!1),x({}),R(!1),E(!1),K(!1),A(!1),Q()},[Q]);const se=i.useCallback(async()=>{const k=!o;l(k);try{await sl({autoMerge:k},e)}catch{l(!k)}},[o,e]),O=i.useCallback(async()=>{const k=!c;d(k);try{await sl({globalPause:k,globalPauseReason:k?"manual":void 0},e)}catch{d(!k)}},[c,e]),M=i.useCallback(async()=>{const k=!u;m(k);try{await sl({enginePaused:k},e)}catch{m(!k)}},[u,e]),D=i.useCallback(async()=>{const k=!w;v(k);try{await sl({showQuickChatFAB:k},e)}catch{v(!k)}},[w,e]),$=i.useCallback(async()=>{const k=!T;H(k),zc(k);try{await Bn({autoReloadOnVersionChange:k})}catch{H(!k),zc(!k)}},[T]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,staleHighFanoutBlockerAgeThresholdMs:p,showQuickChatFAB:w,prAuthAvailable:b,settingsLoaded:S,experimentalFeatures:C,insightsEnabled:N,memoryEnabled:F,devServerEnabled:_,todosEnabled:U,autoReloadOnVersionChange:T,toggleAutoMerge:se,toggleGlobalPause:O,toggleEnginePause:M,toggleShowQuickChatFAB:D,toggleAutoReloadOnVersionChange:$,refresh:Q}}function mz(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(!1),h=i.useRef(null);return i.useEffect(()=>{if(!m.current){const b=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(b){const y=b[1];if(/^[A-Z]+-\d+$/.test(y)){const S=new URLSearchParams(window.location.search);S.set("task",y);const j=S.toString(),C=window.history.state??{};window.history.replaceState(C,"",j?`/?${j}`:"/"),m.current=!0}}}const p=new URLSearchParams(window.location.search),g=p.get("project"),w=p.get("task");if(!w||a)return;if(g){const b=s.find(y=>y.id===g);if(!b){l(`Project '${g}' not found`,"error");return}r?.id!==b.id&&o(b)}if(u.current)return;u.current=!0,Ba(w,g??n).then(b=>{c(b),h.current=w}).catch(()=>{l(`Task ${w} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(h.current){const p=new URLSearchParams(window.location.search);p.delete("task");const g=p.toString(),w=window.history.state??{};window.history.replaceState(w,"",g?`${window.location.pathname}?${g}`:window.location.pathname),h.current=null}d()},[d])}}function hz(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Ws().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,a(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,a(()=>p);try{await Bn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,a(()=>h),g}},[]),u=i.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await Bn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function pz({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:a}){const r=i.useRef(!1),o=i.useRef(n);o.current=n,i.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Po().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return na().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!Lr()?l=!0:!u&&!Lr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(pi("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(pi("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Dg="kb-update-banner-dismissed";function fz(){const[e,n]=i.useState(!0),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1);i.useEffect(()=>{const h=sessionStorage.getItem(Dg)==="true";u(h);let f=!1;return Zj().then(p=>{f||p.disabled||(a(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=i.useCallback(()=>{u(!0),sessionStorage.setItem(Dg,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const gz=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server","stash-recovery"];function bz(e){return e!==null&&gz.includes(e)}function Qd(e){return e!==null&&(bz(e)||wr(e))}const xz=Xo("fusion-plugin-roadmap","roadmaps");function Lg(e){return e==="devserver"?"dev-server":e}function Og(e){return e!=="roadmaps"?"board":Rb("fusion-plugin-roadmap","roadmaps")?xz:"board"}function vz(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:a,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:d,setThemeMode:u}=e,[m,h]=i.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[f,p]=i.useState(()=>{const b=Gn("kb-dashboard-task-view");return b==="roadmaps"?Og(b):Qd(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=Gn("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(Og(b));else if(Qd(b)){const y=!g.current&&b==="devserver";p(y?"devserver":Lg(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{fs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{if(typeof window>"u")return;const b=new URLSearchParams(window.location.search).get("view");b&&Qd(b)&&p(Lg(b))},[]),i.useEffect(()=>{n||a||r&&m==="overview"&&h("project")},[n,a,r,m]),i.useEffect(()=>{if(n||a||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,a,r,l,c]);const w=i.useCallback(b=>{p(b)},[]),v=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),S=b[(y+1)%b.length];u(S)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:w,handleToggleTheme:v}}const Xd=new Map,yz=6e4;function wz(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),[c,d]=i.useState(0),u=i.useRef(!1),m=i.useCallback(()=>{const h=e??"default";Xd.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=Xd.get(h);if(g&&Date.now()<g.expiresAt){if(f)return;s(g.views),r(!1);return}u.current||r(!0),l(null);try{const w=await U0(e);if(f)return;Xd.set(h,{views:w,expiresAt:Date.now()+yz}),s(w)}catch(w){if(f)return;l(w instanceof Error?w.message:"Failed to fetch plugin dashboard views")}finally{f||(r(!1),u.current=!0)}}return p(),()=>{f=!0}},[e,c]),i.useMemo(()=>({views:n,loading:a,error:o,refetch:m}),[n,a,o,m])}function kz({taskView:e,context:n}){return t.jsx(_C,{viewId:e,context:n})}let Fg=!1;function Or(e,n){return function(){return i.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function jz(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",a=(await En(()=>import("./dashboard-view-C7Snlgow.js"),__vite__mapDeps([24,1,25,5,6,26])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}async function Nz(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",a=(await En(()=>import("./dashboard-view-BWGH_fAq.js"),__vite__mapDeps([27,1,25,28])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}async function Sz(){const e="@fusion-plugin-examples/cli-printing-press/dashboard-view",n="CliPrintingPressWizardView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}catch{return{default:Or(e,n)}}}async function Cz(){const e="@fusion-plugin-examples/cli-printing-press/manage-view",n="CliPrintingPressManageView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}catch{return{default:Or(e,n)}}}function ay(){Fg||(Fg=!0,ll("fusion-plugin-dependency-graph","graph",i.lazy(jz)),ll("fusion-plugin-roadmap","roadmaps",i.lazy(Nz)),ll("fusion-plugin-cli-printing-press","wizard",i.lazy(Sz)),ll("fusion-plugin-cli-printing-press","manage",i.lazy(Cz)))}function Ez(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=i.useCallback(R=>{n(R),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),w=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{m()},[m]),b=i.useCallback(R=>{h(),n(R),a("project"),d(`Project ${R.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),S=i.useCallback(async R=>{try{await j1(R.id),d(`Project ${R.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${R.name}`,"error")}},[d,o]),j=i.useCallback(async R=>{try{await N1(R.id),d(`Project ${R.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${R.name}`,"error")}},[d,o]),C=i.useCallback(async R=>{try{await vb(R.id),d(`Project ${R.name} removed`,"success"),r?.id===R.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${R.name}`,"error")}},[r,s,a,d,o]),x=i.useCallback(async R=>{try{await l(R)}catch{d("Failed to update favorites","error")}},[l,d]),N=i.useCallback(async R=>{try{await c(R)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:w,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:j,handleRemoveProject:C,handleToggleFavorite:x,handleToggleModelFavorite:N}}function _z(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:a,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=i.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=i.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=i.useCallback(p=>{s([p]),a(p,l)},[l,s,a]),m=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=i.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=i.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:d,handlePlanningTaskCreated:u,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}function Mz(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),w=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,h(!0),p(null);try{const y=[Q0(e),X0(e)];s&&(y.push(Z0(e,s,a)),y.push(eC(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const j=S[0],C=S[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(u(j.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.value),s&&S[2]){const x=S[2];if(x.status==="rejected"){p(`Failed to fetch tasks: ${x.reason}`),h(!1);return}x.status==="fulfilled"&&c(x.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(w(),()=>{g.current?.abort()}),[w]);const v=i.useCallback(()=>{w()},[w]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:v}}function Az(e){const[n,s]=i.useState(!1),[a,r]=i.useState(null);return i.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return yi(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:a}}const Rz="fusion-dashboard-current-node",ry=i.createContext(null);function Iz({children:e}){const[n,s]=i.useState(null),[a,r]=i.useState(!0),o=i.useRef(!1),l=i.useRef(void 0);i.useEffect(()=>{let m=!1;async function h(){try{const f=await na();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(Rz);if(g){const w=JSON.parse(g);w?.id&&w?.type==="remote"&&(l.current=w.id,await Bn({dashboardCurrentNodeId:w.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,Bn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Bn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Bn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(ry.Provider,{value:u,children:e})}function Tz(){const e=i.useContext(ry);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const Pz=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],$z=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let hc=null,zg=!1;function Dz(e){if(typeof e=="boolean")return e;if(typeof e=="string"){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1}}function Lz(e){if(!(typeof e!="string"||e.trim().length===0))try{const n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString().replace(/\/$/,"")}catch{return}}function oy(e){if(e==="browser"||e==="desktop-shell"||e==="mobile-shell")return e;if(e==="desktop")return"desktop-shell";if(e==="mobile")return"mobile-shell"}function Oz(e){return e==="local"||e==="remote"?e:void 0}function ly(e){const n=Oz(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=Lz(e.serverUrl),r=Dz(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function Fz(e){for(const n of $z){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=oy(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:ly({kind:r,mode:a.mode??a.shellMode,connectionId:a.connectionId??a.profileId,serverUrl:a.serverUrl??a.serverBaseUrl,canOpenConnectionManager:a.canOpenConnectionManager??a.shellCanOpenConnectionManager})}return null}function zz(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=oy(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:ly({kind:a,mode:s.get("mode")??s.get("shellMode"),connectionId:s.get("connectionId")??s.get("profileId"),serverUrl:s.get("serverUrl")??s.get("serverBaseUrl"),canOpenConnectionManager:s.get("canOpenConnectionManager")??s.get("shellCanOpenConnectionManager")}):null}function Bz(e){try{const n=new URL(e.location.href);let s=!1;for(const r of Pz)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const a=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",a)}catch{}}function Uz(e=window){const n=Fz(e);if(n)return n;const s=zz(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function cy(e=window){return!zg&&typeof window<"u"&&(hc=Uz(e),Bz(e),zg=!0),hc??{kind:"browser"}}function Hz(){return hc||(typeof window>"u"?{kind:"browser"}:cy(window))}const qz={kind:"browser"},dy=i.createContext({host:qz,isNativeShell:!1,kind:"browser"});function Vz(e){const n=e.kind!=="browser";return{host:e,isNativeShell:n,kind:e.kind,...n?{mode:e.mode,connectionId:e.connectionId,serverUrl:e.serverUrl,canOpenConnectionManager:e.canOpenConnectionManager}:{}}}function Wz({children:e}){const n=i.useMemo(()=>Vz(Hz()),[]);return t.jsx(dy.Provider,{value:n,children:e})}function Gz(){return i.useContext(dy)}function Kz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function Jz({open:e,shellApi:n,shellState:s,onComplete:a}){const[r,o]=i.useState(s.desktopMode??"remote"),[l,c]=i.useState("Remote Server"),[d,u]=i.useState(""),[m,h]=i.useState(""),[f,p]=i.useState(null),[g,w]=i.useState(!1),[v,b]=i.useState(!1),y=s.host==="desktop-shell";i.useEffect(()=>{y&&o(s.desktopMode??"remote")},[y,s.desktopMode]);const S=i.useMemo(()=>y&&r==="local"?!0:d.trim().length>0,[y,r,d]);return e?t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-onboarding-modal",children:[t.jsx("div",{className:"modal-header",children:t.jsx("h2",{children:"Welcome to Fusion"})}),t.jsxs("div",{className:"native-shell-onboarding-body",children:[t.jsx("p",{children:"Fusion helps you plan, run, and review AI-assisted engineering work."}),y&&t.jsxs("div",{className:"native-shell-onboarding-mode-row",children:[t.jsx("button",{type:"button",className:`btn ${r==="local"?"btn-primary":""}`,onClick:()=>o("local"),children:"Local Fusion"}),t.jsx("button",{type:"button",className:`btn ${r==="remote"?"btn-primary":""}`,onClick:()=>o("remote"),children:"Remote Server"})]}),(!y||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null),w(!0);try{const j=await n.startQrScan();u(j.serverUrl),h(j.authToken??"")}catch(j){p(j.message)}finally{w(!1)}},disabled:g,children:g?"Scanning…":"Scan QR"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:"Profile name"}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:l,onChange:j=>c(j.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:d,onChange:j=>u(j.target.value),placeholder:"https://your-fusion-host"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:m,onChange:j=>h(j.target.value)})]}),f&&t.jsx("p",{className:"form-error",role:"alert",children:f})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",disabled:!S||v,onClick:async()=>{p(null),b(!0);try{if(y&&r==="local"){await n.setDesktopMode("local"),a();return}const j=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(y&&await n.setDesktopMode("remote"),await n.setActiveProfile(j.id),typeof window<"u"&&s.host!=="web"){window.location.href=Kz(j.serverUrl,j.authToken??null);return}a()}catch(j){p(j.message)}finally{b(!1)}},children:v?"Saving…":"Continue"})})]})}):null}function Yz({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(x=>x.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState(null),[c,d]=i.useState({}),[u,m]=i.useState(null),[h,f]=i.useState(null);if(!e)return null;const p=o==="__new__",g=p?null:s.profiles.find(x=>x.id===o)??r,w=c.name??g?.name??"",v=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",y=()=>{l(null),d({}),f(null)},S=async()=>{f(null);try{const x=new URL(v.trim());if(!/^https?:$/.test(x.protocol))throw new Error("Server URL must use http or https");const N=await n.saveProfile({id:p?void 0:o??g?.id,name:w||"Remote Server",serverUrl:v,authToken:b||null});await n.setActiveProfile(N.id),l(N.id),d({})}catch(x){f(x.message)}},j=async()=>{f(null);try{const x=await n.startQrScan();l("__new__"),d({name:"",serverUrl:x.serverUrl,authToken:x.authToken??""})}catch(x){f(x.message)}},C=async()=>{u&&(await n.deleteProfile(u.id),m(null),y())};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":"Connection Manager",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Connection Manager"}),t.jsx("button",{type:"button",className:"modal-close",onClick:a,"aria-label":"Close",children:"×"})]}),s.host==="desktop-shell"&&t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:`btn ${s.desktopMode==="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("local"),children:"Local"}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:"Remote"})]}),t.jsx("div",{className:"native-shell-connection-manager__profiles",children:s.profiles.length===0?t.jsxs("div",{className:"card native-shell-connection-manager__empty-state",children:[t.jsx("p",{className:"settings-muted",children:"No remote servers saved yet."}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add server"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void j(),children:"Scan QR"})]})]}):s.profiles.map(x=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:x.name}),t.jsx("div",{className:"settings-muted",children:x.serverUrl}),x.id===s.activeProfileId&&t.jsx("span",{className:"native-shell-connection-manager__active-pill",children:"Active"})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Edit ${x.name}`,onClick:()=>{l(x.id),d(x)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${x.name}`,onClick:()=>void n.setActiveProfile(x.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${x.name}`,onClick:()=>m(x),children:"Delete"})]})]},x.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add connection"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void j(),children:"Scan QR"})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:"Name"}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:w,onChange:x=>d(N=>({...N,name:x.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-connection-manager-url",className:"input",value:v,onChange:x=>d(N=>({...N,serverUrl:x.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-connection-manager-token",className:"input",type:"password",value:b??"",onChange:x=>d(N=>({...N,authToken:x.target.value}))}),h&&t.jsx("p",{className:"form-error",role:"alert",children:h})]}),u&&t.jsxs("div",{className:"native-shell-connection-manager__delete-confirm",role:"alertdialog","aria-label":"Delete server confirmation",children:[t.jsxs("p",{children:["Delete ",t.jsx("strong",{children:u.name}),"? This removes the saved profile."]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m(null),children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void C(),children:"Delete"})]})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Close"}),t.jsx("button",{type:"button",className:"btn",onClick:y,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void S(),disabled:!v.trim(),children:"Save"})]})]})})}function Qz(e){if(e.hostKind==="desktop-shell"&&e.mode==="local")return{title:"Desktop local mode",actionLabel:"Switch server",dotClassName:"status-dot status-dot--online"};const n=e.profileLabel??e.profileId,s=e.serverOrigin,a=n&&s?`${n} · ${s}`:n??s;return e.mode==="remote"?{title:a??"Connection info unavailable",actionLabel:e.hostKind==="desktop-shell"?"Switch server":"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}:{title:a??"Connection info unavailable",actionLabel:"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}}function Bg({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=Qz(e),a=i.useCallback(async()=>{const r=await e.openConnectionManager();!r.ok&&r.reason==="failed"&&n?.(r.error??"Failed to open connection manager")},[n,e]);return t.jsxs("button",{type:"button",className:"btn shell-connection-status",onClick:()=>void a(),"data-testid":"shell-connection-status-button",children:[t.jsx("span",{className:s.dotClassName,"aria-hidden":"true"}),t.jsx("span",{className:"shell-connection-status__kind",children:e.hostKind==="desktop-shell"?"Desktop":"Mobile"}),t.jsx("span",{className:"shell-connection-status__summary",title:s.title,children:s.title}),t.jsx("span",{className:"shell-connection-status__action",children:s.actionLabel})]})}function Xz(e){if(e)try{return new URL(e).origin}catch{return}}function Zz(e,n){const s=e.profiles.find(a=>a.id===e.activeProfileId)??null;return s||(n.kind==="browser"||!n.connectionId?null:e.profiles.find(a=>a.id===n.connectionId)??null)}async function e6(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function t6(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await e6(a),o=r?Zz(r,e):null,l=e.kind==="browser"?void 0:e.mode??r?.desktopMode,c=o?.id??(e.kind==="browser"?void 0:e.connectionId),d=o?.name,u=Xz(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),m=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",h=e.kind==="mobile-shell"&&typeof a?.openConnectionManager=="function",f=m||h;return{hostKind:e.kind,available:f,...l?{mode:l}:{},...c?{profileId:c}:{},...d?{profileLabel:d}:{},...u?{serverOrigin:u}:{},openConnectionManager:async()=>{try{return m?(await s.openConnectionManager?.(),{ok:!0}):h?(await a.openConnectionManager(),{ok:!0}):{ok:!1,reason:"unsupported"}}catch(p){return{ok:!1,reason:"failed",error:p instanceof Error?p.message:String(p)}}}}}function n6({open:e}){const[n,s]=i.useState(""),a=i.useRef(null);i.useEffect(()=>{e&&a.current?.focus()},[e]);const r=i.useCallback(()=>{const l=n.trim();l&&(Cj(l),window.location.reload())},[n]),o=i.useCallback(()=>{Ej(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:a,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const s6=200,i6=i.lazy(()=>En(()=>import("./AgentsView-CxITZE-U.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])).then(e=>({default:e.AgentsView}))),a6=i.lazy(()=>En(()=>import("./DocumentsView-1kr0dhsV.js"),__vite__mapDeps([32,1,5,6,33])).then(e=>({default:e.DocumentsView}))),r6=i.lazy(()=>En(()=>import("./InsightsView-D2AjxOnu.js"),__vite__mapDeps([34,1,22,5,6,35])).then(e=>({default:e.InsightsView}))),o6=i.lazy(()=>En(()=>import("./ResearchView-C9bjVB7-.js"),__vite__mapDeps([36,1,5,6,37])).then(e=>({default:e.ResearchView}))),l6=i.lazy(()=>En(()=>import("./EvalsView-cDfXYiK6.js"),__vite__mapDeps([38,1,5,6,39])).then(e=>({default:e.EvalsView}))),c6=i.lazy(()=>En(()=>import("./NodesView-Cpmkze7n.js"),__vite__mapDeps([40,1,17,30,5,6,41])).then(e=>({default:e.NodesView}))),d6=i.lazy(()=>En(()=>import("./ChatView-7WPHyB_7.js"),__vite__mapDeps([42,1,5,6,43])).then(e=>({default:e.ChatView}))),u6=i.lazy(()=>En(()=>import("./SkillsView-DmZfbGLs.js"),__vite__mapDeps([44,1,5,6,45])).then(e=>({default:e.SkillsView}))),m6=i.lazy(()=>En(()=>import("./MemoryView-Dq4yjIPI.js"),__vite__mapDeps([46,1,20,21,5,6,47])).then(e=>({default:e.MemoryView}))),h6=i.lazy(()=>En(()=>import("./DevServerView-Diw4hjw0.js"),__vite__mapDeps([48,1,5,6,49])).then(e=>({default:e.DevServerView})));i.lazy(()=>En(()=>import("./TodoView-uJRg4Cnl.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));const p6=i.lazy(()=>En(()=>import("./StashRecoveryView-BwKJQaUW.js"),__vite__mapDeps([50,1,5,6,51])).then(e=>({default:e.StashRecoveryView})));function f6(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{En(()=>import("./AgentsView-CxITZE-U.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])),En(()=>import("./DocumentsView-1kr0dhsV.js"),__vite__mapDeps([32,1,5,6,33])),En(()=>import("./InsightsView-D2AjxOnu.js"),__vite__mapDeps([34,1,22,5,6,35])),En(()=>import("./ResearchView-C9bjVB7-.js"),__vite__mapDeps([36,1,5,6,37])),En(()=>import("./EvalsView-cDfXYiK6.js"),__vite__mapDeps([38,1,5,6,39])),En(()=>import("./NodesView-Cpmkze7n.js"),__vite__mapDeps([40,1,17,30,5,6,41])),En(()=>import("./ChatView-7WPHyB_7.js"),__vite__mapDeps([42,1,5,6,43])),En(()=>import("./SkillsView-DmZfbGLs.js"),__vite__mapDeps([44,1,5,6,45])),En(()=>import("./MemoryView-Dq4yjIPI.js"),__vite__mapDeps([46,1,20,21,5,6,47])),En(()=>import("./DevServerView-Diw4hjw0.js"),__vite__mapDeps([48,1,5,6,49])),En(()=>import("./TodoView-uJRg4Cnl.js"),__vite__mapDeps([11,1,5,6,12])),En(()=>import("./StashRecoveryView-BwKJQaUW.js"),__vite__mapDeps([50,1,5,6,51]))})}ay();const Zd="kb-setup-warning-dismissed",g6="kb-chat-active-session",Ug="kb-dashboard-working-branch-filter",Hg="kb-dashboard-base-branch-filter",qg="__fusion:no-branch__",uy="fusion:approval-banner-dismissed";function b6(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function Vg(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function x6(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(uy);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n))typeof r=="number"&&Number.isFinite(r)&&s.set(a,r);return s}catch{return new Map}}function Wg(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(uy,JSON.stringify(n))}catch{}}function v6(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function y6(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function w6(){const{toasts:e,addToast:n,removeToast:s}=nz(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=Bv(),c=Gz();i.useEffect(()=>{f6()},[]);const{projects:d,loading:u,error:m,refresh:h}=QF(),{nodes:f}=Cc(),{currentNode:p,currentNodeId:g,isRemote:w,setCurrentNode:v,clearCurrentNode:b}=Tz(),{currentProject:y,setCurrentProject:S,clearCurrentProject:j,loading:C}=ez(d,{nodeId:g}),{hasAiProvider:x,hasGithub:N,loading:R,hasWarnings:F}=Lv(y?.id),{updateAvailable:E,latestVersion:_,currentVersion:K,dismissed:U,dismiss:A}=fz();i.useEffect(()=>{if(g&&!p&&f.length>0){const Je=f.find(Rt=>Rt.id===g);if(Je){v(Je);return}}g&&f.length>0&&(f.some(Rt=>Rt.id===g)||b())},[g,p,f,v,b]);const[T,H]=i.useState(""),[Q,se]=i.useState(""),[O,M]=i.useState("");i.useEffect(()=>{se(Gn(Ug,y?.id)??""),M(Gn(Hg,y?.id)??"")},[y?.id]);const D=i.useCallback(Je=>{se(Je),fs(Ug,Je,y?.id)},[y?.id]),$=i.useCallback(Je=>{M(Je),fs(Hg,Je,y?.id)},[y?.id]),k=Mz(g,{projectId:y?.id,searchQuery:T||void 0});Az(g);const X=w&&k.projects.length>0?k.projects:d,{themeMode:le,colorTheme:ke,dashboardFontScalePct:He,setThemeMode:ye,setColorTheme:je,setDashboardFontScalePct:ne}=cz(),{sessions:fe,generating:Z,needsInput:re,planningSessions:q,dismissSession:L}=UF(y?.id),xe=fe.filter(Je=>Je.status==="awaiting_input"||Je.status==="error"),he=VF(),B=dz({projectId:y?.id,planningSessions:q}),ze=oi()==="mobile",{pushNav:ae,replaceCurrent:Ve}=x$({enabled:!0}),{viewMode:Te,setViewMode:rt,taskView:Be,handleChangeTaskView:ce}=vz({projectsLoading:u,projectsError:m,currentProjectLoading:C,currentProject:y,projectsLength:d.length,setupWizardOpen:B.setupWizardOpen,openSetupWizard:B.openSetupWizard,themeMode:le,setThemeMode:ye}),{views:Re}=wz(y?.id),Le=i.useMemo(()=>{const Je=Re.find(Rt=>Rt.pluginId==="fusion-plugin-dependency-graph"&&Rt.view.viewId==="graph");return Je?`plugin:${Je.pluginId}:${Je.view.viewId}`:Rb("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[Re]),ct=i.useCallback(Je=>{Je==="missions"&&(Sn(void 0),Jt(void 0),Ne(void 0));const Rt=Be;ce(Je),Rt!==Je&&ae({type:"view",revert:()=>ce(Rt)})},[ce,Be,ae]),Ue=Be==="board"||Be==="list",{tasks:ue,createTask:oe,moveTask:Ee,pauseTask:ft,deleteTask:ht,mergeTask:tt,retryTask:xt,resetTask:Me,updateTask:Ye,duplicateTask:dt,archiveTask:wt,unarchiveTask:St,archiveAllDone:Fe,loadArchivedTasks:J,ingestCreatedTasks:me,lastFetchTimeMs:Ze}=GF({...y?{projectId:y.id}:{},searchQuery:T||void 0,sseEnabled:Ue}),be=w&&k.tasks.length>0?k.tasks:ue,[gt,$t]=i.useState(!1),[Ie,ge]=i.useState(0),st=i.useRef(performance.now()),yt=i.useRef(!1),pt=i.useRef(!1),vt=i.useMemo(()=>u?"projects":C?"project":"tasks",[u,C]);i.useEffect(()=>{if(!u&&!yt.current){yt.current=!0;const Je=`projects loaded at ${Math.round(performance.now()-st.current)}ms from mount`;console.log(`[App] ${Je}`)}if(!C&&!pt.current){pt.current=!0;const Je=`current-project resolved at ${Math.round(performance.now()-st.current)}ms from mount`;console.log(`[App] ${Je}`)}},[u,C]),i.useEffect(()=>{if(gt||u||C)return;const Je=performance.now(),Rt=window.setTimeout(()=>{const rn=`dashboard ready at ${Math.round(performance.now()-st.current)}ms from mount (settle delay=${Math.round(performance.now()-Je)}ms)`;console.log(`[App] ${rn}`),$t(!0)},s6);return()=>{window.clearTimeout(Rt)}},[gt,u,C]);const{keyboardOpen:Ut}=aa({enabled:ze}),Dt=ze&&Ut&&!B.anyModalOpen;Mi(Dt);const[nn,on]=i.useState(0),[sn,ln]=i.useState(0),[xn,qt]=i.useState(!1),[Qt,hn]=i.useState(0),[Zt,ve]=i.useState(null),Pe=i.useRef(new Map),Ke=i.useRef(new Set),at=i.useRef(x6()),We=i.useCallback(()=>{Nb(y?.id).then(Je=>{on(Je.unreadCount),ln(Je.pendingApprovalCount??0)}).catch(Je=>{console.warn("[App] Failed to fetch mailbox unread count:",Je)})},[y?.id]);i.useEffect(()=>{const Je=new Map,Rt=new Set;for(const rn of ue)Je.set(rn.id,rn.status),rn.status==="awaiting-approval"&&Rt.add(`task:${rn.id}`);Pe.current=Je,Ke.current=Rt},[ue]),i.useEffect(()=>{We();const Je=new URLSearchParams;y?.id&&Je.set("projectId",y.id);const Rt=Je.size>0?`?${Je.toString()}`:"",rn=es=>{const Hn=at.current.get(es.dedupeKey);Hn!==void 0&&es.updatedAtMs<=Hn||ve(es)};return yi(`/api/events${Rt}`,{onReconnect:We,events:{"message:sent":We,"message:received":We,"message:read":We,"message:deleted":We,"approval:requested":es=>{We();try{const Hn=JSON.parse(es.data),Bs=Hn.id?`approval:${Hn.id}`:Hn.taskId?`task:${Hn.taskId}`:void 0;if(!Bs||Ke.current.has(Bs))return;Ke.current.add(Bs),rn({dedupeKey:Bs,updatedAtMs:Vg(Hn.updatedAt??Hn.createdAt)})}catch{}},"approval:updated":We,"approval:decided":We,"task:updated":es=>{try{const Hn=JSON.parse(es.data);if(!Hn?.id)return;const Bs=`task:${Hn.id}`,rr=Pe.current.get(Hn.id);if(Pe.current.set(Hn.id,Hn.status),Hn.status!=="awaiting-approval"){Ke.current.delete(Bs),at.current.delete(Bs),Wg(at.current);return}if(Ke.current.has(Bs))return;b6(Hn.status,rr)&&(Ke.current.add(Bs),rn({dedupeKey:Bs,updatedAtMs:Vg(Hn.updatedAt)}),We())}catch{}}}})},[y?.id,We]),i.useEffect(()=>{Be==="chat"&&qt(!1)},[Be]),i.useEffect(()=>{let Je=!1;const Rt=async()=>{try{const es=await I("/stash-recovery/orphans");Je||hn(es.count??0)}catch{Je||hn(0)}};Rt();const rn=window.setInterval(()=>void Rt(),3e4);return()=>{Je=!0,window.clearInterval(rn)}},[y?.id]),i.useEffect(()=>{const Je=new URLSearchParams;y?.id&&Je.set("projectId",y.id);const Rt=Je.size>0?`?${Je.toString()}`:"";return yi(`/api/events${Rt}`,{events:{"chat:message:added":rn=>{try{const es=JSON.parse(rn.data),Hn=Gn(g6,y?.id);if(!Hn||es.role!=="assistant"||Be==="chat"||es.sessionId!==Hn||es.projectId&&y?.id&&es.projectId!==y.id)return;qt(!0)}catch{}}}})},[y?.id,Be]);const It=i.useMemo(()=>Array.from(new Set(be.map(Je=>Je.branch?.trim()).filter(Je=>!!(Je&&Je.length>0)))).sort((Je,Rt)=>Je.localeCompare(Rt)),[be]),Lt=i.useMemo(()=>Array.from(new Set(be.map(Je=>Je.baseBranch?.trim()).filter(Je=>!!(Je&&Je.length>0)))).sort((Je,Rt)=>Je.localeCompare(Rt)),[be]),Bt=i.useMemo(()=>be.filter(Je=>{const Rt=Je.branch?.trim()??"",rn=Je.baseBranch?.trim()??"";if(Q===qg){if(Rt.length>0)return!1}else if(Q.length>0&&Rt!==Q)return!1;if(O===qg){if(rn.length>0)return!1}else if(O.length>0&&rn!==O)return!1;return!0}),[be,Q,O]),[Gt,bt]=i.useState(!1),[Ot,en]=i.useState(!1),[Kt,Sn]=i.useState(void 0),[dn,Jt]=i.useState(void 0),[tn,Ne]=i.useState(void 0),[W,Y]=i.useState(!1),[_e,ut]=i.useState(!1),[At,zt]=i.useState(null),[yn,Zn]=i.useState(()=>Gn(Zd,y?.id)==="true");i.useEffect(()=>{Zn(Gn(Zd,y?.id)==="true")},[y?.id]),i.useEffect(()=>{let Je=!1;return Dj().then(Rt=>{Je||zt(Rt)}).catch(()=>{Je||zt(null)}),()=>{Je=!0}},[]),i.useEffect(()=>{const Je=()=>{ut(!0)};return window.addEventListener(cu,Je),()=>{window.removeEventListener(cu,Je)}},[]);const vn=i.useCallback(()=>{fs(Zd,"true",y?.id),Zn(!0)},[y?.id]),{maxConcurrent:Dn,autoMerge:de,globalPaused:nt,enginePaused:ot,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,showQuickChatFAB:Oe,prAuthAvailable:Mt,settingsLoaded:Xt,experimentalFeatures:_n,insightsEnabled:Pn,memoryEnabled:kn,devServerEnabled:Vn,todosEnabled:$s,toggleAutoMerge:vs,toggleGlobalPause:As,toggleEnginePause:bn,refresh:Ht}=uz(y?.id),On=_n.skillsView===!0,Fn=_n.nodesView===!0,as=_n.researchView===!0,Wn=_n.evalsView===!0,Rs=_n.agentOnboarding===!0,In=!0,rs=i.useCallback(()=>{B.closeSettings(),ge(Je=>Je+1),Ht()},[B,Ht]);i.useEffect(()=>{if(Xt&&!wr(Be)){if(Be==="graph"&&!Le){ce("board");return}Be==="skills"&&!On&&ce("board"),Be==="insights"&&!Pn&&ce("board"),Be==="memory"&&!kn&&ce("board"),(Be==="devserver"||Be==="dev-server")&&!Vn&&ce("board"),Be==="research"&&!as&&ce("board"),Be==="evals"&&!Wn&&ce("board")}},[Be,Xt,On,Pn,ce,In,kn,Vn,as,Wn,Le]),i.useEffect(()=>{Gt&&!Fn&&bt(!1)},[Gt,Fn]);const{availableModels:Ns,favoriteProviders:ys,favoriteModels:cs,toggleFavoriteProvider:ss,toggleFavoriteModel:te}=hz();pz({projectId:y?.id,setupWizardOpen:B.setupWizardOpen,openModelOnboarding:B.openModelOnboarding,openSettings:B.openSettings});const{handleSelectProject:we,handleViewAllProjects:P,handleAddProject:Ce,handleSetupComplete:qe,handleModelOnboardingComplete:et,handlePauseProject:mt,handleResumeProject:Nt,handleRemoveProject:Pt,handleToggleFavorite:an,handleToggleModelFavorite:Cn}=Ez({setCurrentProject:S,clearCurrentProject:j,setViewMode:rt,currentProject:y,refreshProjects:h,toggleFavoriteProvider:ss,toggleFavoriteModel:te,addToast:n,openSettings:B.openSettings,openSetupWizard:B.openSetupWizard,closeSetupWizard:B.closeSetupWizard,closeModelOnboarding:B.closeModelOnboarding}),{handleDetailClose:ie}=mz({projectId:y?.id,projects:d,projectsLoading:u,currentProject:y,setCurrentProject:S,addToast:n,openTaskDetail:B.openDetailTask,closeTaskDetail:B.closeDetailTask}),$e=i.useCallback(async({insightId:Je,title:Rt,description:rn})=>{await oe({title:Rt,description:rn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Je}}})},[oe]),{handleBoardQuickCreate:Qe,handleModalCreate:Ft,handlePlanningTaskCreated:cn,handlePlanningTasksCreated:pn,handleSubtaskTasksCreated:jn,handleGitHubImport:Un}=_z({createTask:oe,ingestCreatedTasks:me,onPlanningTaskCreated:B.onPlanningTaskCreated,onPlanningTasksCreated:B.onPlanningTasksCreated,onSubtaskTasksCreated:B.onSubtaskTasksCreated,addToast:n}),gs=i.useCallback((Je,Rt)=>{Rt==="changes"?B.openDetailWithChangesTab(Je):B.openDetailTask(Je,Rt),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),bs=i.useCallback(async Je=>{try{const Rt=await Ba(Je,y?.id);B.openDetailTask(Rt,"logs"),ae({type:"modal",close:B.closeDetailTask})}catch(Rt){n(`Failed to open task logs: ${Rt.message}`,"error")}},[B,y?.id,n,ae]),[is,ds]=i.useState([]);i.useEffect(()=>{let Je=!1;return Ko(y?.id).then(Rt=>{Je||ds(Rt)}).catch(()=>{Je||ds([])}),()=>{Je=!0}},[y?.id]);const xs=i.useMemo(()=>new Map(is.map(Je=>[Je.id,Je.name])),[is]);i.useCallback(()=>{Fn&&bt(Je=>!Je)},[Fn]);const ra=i.useCallback(()=>{Fn&&(Gt?bt(!1):(bt(!0),ae({type:"view",revert:()=>bt(!1)})))},[Fn,Gt,ae]),Jn=i.useCallback((Je,Rt,rn)=>{B.openDetailTask(Je,Rt,rn),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),Ui=i.useCallback(Je=>{B.openSettings(Je),ae({type:"modal",close:rs})},[B,ae,rs]),Hi=i.useCallback(()=>{B.openNewTask(),ae({type:"modal",close:B.closeNewTask})},[B,ae]),Zs=i.useCallback(()=>{B.openPlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),ja=i.useCallback(Je=>{B.openPlanningWithInitialPlan(Je),ae({type:"modal",close:B.closePlanning})},[B,ae]),Na=i.useCallback(()=>{B.resumePlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),Ya=i.useCallback(Je=>{B.openSubtaskBreakdown(Je),ae({type:"modal",close:B.closeSubtask})},[B,ae]),Qa=i.useCallback(()=>{B.openGitHubImport(),ae({type:"modal",close:B.closeGitHubImport})},[B,ae]),Mn=i.useCallback(()=>{B.terminalOpen?B.toggleTerminal():(B.toggleTerminal(),ae({type:"modal",close:B.closeTerminal}))},[B,ae]),ci=i.useCallback((Je,Rt)=>{B.openFiles(Je,Rt),ae({type:"modal",close:B.closeFiles})},[B,ae]),wi=i.useCallback((Je,Rt)=>{B.openFiles(Rt?.workspace,Je),ae({type:"modal",close:B.closeFiles})},[B,ae]),Ai=i.useCallback(()=>{B.openTodos(),ae({type:"modal",close:B.closeTodos})},[B,ae]),Sa=i.useCallback(()=>{B.openActivityLog(),ae({type:"modal",close:B.closeActivityLog})},[B,ae]),Xa=i.useCallback(()=>{B.openGitManager(),ae({type:"modal",close:B.closeGitManager})},[B,ae]),Za=i.useCallback(()=>{B.openSystemStats(),ae({type:"modal",close:B.closeSystemStats})},[B,ae]),Ca=i.useCallback(()=>{B.openSchedules(),ae({type:"modal",close:B.closeSchedules})},[B,ae]),Ea=i.useCallback(()=>{B.openScripts(),ae({type:"modal",close:B.closeScripts})},[B,ae]),_a=i.useCallback(()=>{B.openWorkflowSteps(),ae({type:"modal",close:B.closeWorkflowSteps})},[B,ae]),er=i.useCallback(Je=>{B.openUsage(Je),ae({type:"modal",close:B.closeUsage})},[B,ae]),Ma=i.useCallback(async(Je,Rt)=>{await B.runScript(Je,Rt),Ve({type:"modal",close:B.closeTerminal})},[B,Ve]),di=i.useCallback(()=>{B.closeSettings(),B.openModelOnboarding(),Ve({type:"modal",close:B.closeModelOnboarding})},[B,Ve]),ki=i.useCallback(()=>{B.setFileWorkspace("project"),B.openFiles()},[B]),Ds=i.useCallback(async()=>{en(!0);try{await h()}finally{en(!1)}},[h]),tr=i.useCallback(Je=>{Jt(Je),Sn(void 0),ce("missions")},[ce]),qi=i.useCallback(Je=>{Je.type==="planning"?B.openPlanningWithSession(Je.id):Je.type==="subtask"?B.openSubtaskWithSession(Je.id):Je.type==="mission_interview"?(Jt(void 0),Sn(Je.id),Ne(void 0),ce("missions")):(Je.type==="milestone_interview"||Je.type==="slice_interview")&&(Sn(void 0),Jt(void 0),Ne(Je.id),ce("missions"))},[ce,B]),nr=i.useCallback(()=>{},[]),ei=i.useCallback(()=>{},[]),[Gr,Kr]=i.useState(!1),[Jr,oa]=i.useState(!1),[Vi,sr]=i.useState(null),ir=y6(r,o,Gr);i.useEffect(()=>{!a||l===0||oa(!0)},[a,l]),i.useEffect(()=>{let Je=!1;return t6(c.host).then(Rt=>{Je||sr(Rt)}),()=>{Je=!0}},[c.host,r.activeProfileId,r.desktopMode,r.host,r.profiles]),i.useEffect(()=>{r.host==="desktop-shell"&&r.desktopMode==="local"&&(r.localServer?.status!=="ready"||!r.localServer.port||window.location.port!==String(r.localServer.port)&&(window.location.href=`http://localhost:${r.localServer.port}`))},[r]),i.useEffect(()=>{if(r.host!=="desktop-shell"||r.desktopMode!=="remote")return;const Je=r.profiles.find(rn=>rn.id===r.activeProfileId);if(!Je||typeof window>"u")return;const Rt=v6(Je.serverUrl,Je.authToken??null);window.location.href!==Rt&&(window.location.href=Rt)},[r]);const Yr=!u&&!C&&d.length===0&&!y&&!!m,ar=()=>{if(Yr)return t.jsx(HO,{errorMessage:m??"Failed to fetch projects",isRetrying:Ot,onRetry:Ds,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(Gt)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(c6,{addToast:n,onClose:()=>bt(!1)})})})});if(Te==="overview")return t.jsx(Is,{children:t.jsx(g$,{projects:d,loading:u,onSelectProject:we,onAddProject:Ce,onPauseProject:mt,onResumeProject:Nt,onRemoveProject:Pt,nodes:f})});const Je=Be==="graph"?Le:wr(Be)?Be:null;return Je?t.jsx(Is,{children:t.jsx(kz,{taskView:Je,context:{projectId:y?.id,tasks:w&&k.tasks.length>0?k.tasks:ue,workflowSteps:is,openTaskDetail:(Rt,rn)=>Jn(Rt,rn),renderTaskCard:Rt=>t.jsx(Do,{task:Rt,projectId:y?.id,onOpenDetail:rn=>Jn(rn),addToast:n,workflowStepNameLookup:xs,disableDrag:!0}),addToast:n}})}):Be==="skills"?!Xt||!On?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(u6,{addToast:n,projectId:y?.id,onClose:()=>ce("board")})})}):Be==="chat"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(d6,{addToast:n,projectId:y?.id,experimentalFeatures:_n})})}):Be==="mailbox"?t.jsx(Is,{children:t.jsx(m4,{projectId:y?.id,addToast:n,onUnreadCountChange:on})}):Be==="missions"?t.jsx(Is,{children:t.jsx(o4,{isInline:!0,isOpen:!0,onClose:()=>{Jt(void 0),Sn(void 0),Ne(void 0),ce("board")},addToast:n,projectId:y?.id,onSelectTask:Rt=>{const rn=ue.find(es=>es.id===Rt);rn&&Jn(rn)},availableTasks:ue.map(Rt=>({id:Rt.id,title:Rt.title})),resumeSessionId:Kt,targetMissionId:dn,milestoneSliceResumeSessionId:tn,onMilestoneSliceResumeFetchError:()=>Ne(void 0)})}):Be==="agents"&&In?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(i6,{addToast:n,projectId:y?.id,onOpenTaskLogs:bs,agentOnboardingEnabled:Rs})})}):Be==="documents"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a6,{projectId:y?.id,addToast:n,onOpenDetail:Jn})})}):Be==="stash-recovery"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(p6,{})})}):Be==="insights"?!Xt||!Pn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(r6,{projectId:y?.id,addToast:n,onClose:()=>ce("board"),onCreateTask:$e})})}):Be==="research"?!Xt||!as?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(o6,{projectId:y?.id,addToast:n,onOpenSettings:Rt=>B.openSettings(Rt),readinessVersion:Ie})})}):Be==="evals"?!Xt||!Wn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(l6,{projectId:y?.id,onOpenSettings:Rt=>B.openSettings(Rt),onOpenTaskDetail:Rt=>{Ba(Rt,y?.id).then(rn=>Jn(rn)).catch(rn=>n(rn instanceof Error?rn.message:"Failed to open task detail","error"))}})})}):Be==="memory"?!Xt||!kn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(m6,{addToast:n,projectId:y?.id})})}):Be==="devserver"||Be==="dev-server"?!Xt||!Vn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(h6,{addToast:n,projectId:y?.id})})}):Be==="board"?t.jsx(Is,{children:t.jsx(n_,{tasks:Bt,projectId:y?.id,maxConcurrent:Dn,onMoveTask:Ee,onPauseTask:ft,onOpenDetail:Jn,addToast:n,onQuickCreate:Qe,onNewTask:Hi,onPlanningMode:ja,onSubtaskBreakdown:Ya,autoMerge:de,onToggleAutoMerge:vs,globalPaused:nt,onUpdateTask:Ye,onRetryTask:xt,onArchiveTask:wt,onUnarchiveTask:St,onDeleteTask:ht,onArchiveAllDone:Fe,onLoadArchivedTasks:J,searchQuery:T,availableModels:Ns,onOpenDetailWithTab:gs,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,onOpenMission:tr,lastFetchTimeMs:Ze})}):t.jsx(Is,{children:t.jsx(i$,{tasks:w&&k.tasks.length>0?k.tasks:ue,projectId:y?.id,onMoveTask:Ee,onRetryTask:xt,onDeleteTask:ht,onMergeTask:tt,onResetTask:Me,onDuplicateTask:dt,onOpenDetail:(Rt,rn)=>Jn(Rt,void 0,rn),addToast:n,globalPaused:nt,onNewTask:Hi,onQuickCreate:Qe,onPlanningMode:ja,onSubtaskBreakdown:Ya,availableModels:Ns,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn,taskStuckTimeoutMs:_t,searchQuery:T,lastFetchTimeMs:Ze,prAuthAvailable:Mt})})};if(!gt)return t.jsxs(t.Fragment,{children:[t.jsx(VO,{stage:vt}),t.jsx(Wv,{toasts:e,onRemove:s})]});const Aa=!B.modelOnboardingOpen&&mO(),Wi=!B.modelOnboardingOpen&&!Aa&&Lr()&&!Uv();return t.jsx(b$,{value:{pushNav:ae,replaceCurrent:Ve},children:t.jsxs(DT,{openFile:wi,children:[t.jsx(IC,{shellHost:c.host,onOpenSettings:Ui,onOpenGitHubImport:Qa,onOpenPlanning:Zs,onResumePlanning:Na,activePlanningSessionCount:q.length,onOpenUsage:er,onOpenActivityLog:Sa,onOpenSystemStats:Za,onOpenMailbox:()=>ct("mailbox"),mailboxUnreadCount:nn,mailboxPendingApprovalCount:sn,chatHasUnreadResponse:xn,stashOrphanCount:Qt,onOpenSchedules:Ca,onOpenGitManager:Xa,onOpenNodes:ra,showNodesButton:Fn,onOpenWorkflowSteps:_a,onOpenScripts:Ea,onRunScript:Ma,onToggleTerminal:Mn,onOpenFiles:ci,filesOpen:B.filesOpen,onOpenTodos:Ai,todosOpen:B.todosOpen,todosEnabled:$s,globalPaused:nt,enginePaused:ot,onToggleGlobalPause:As,onToggleEnginePause:bn,view:Be,onChangeView:Te==="project"&&y?ct:void 0,showSkillsTab:On,showAgentsTab:In,searchQuery:T,onSearchChange:H,branchFilter:Q,baseBranchFilter:O,branchOptions:It,baseBranchOptions:Lt,onBranchFilterChange:D,onBaseBranchFilterChange:$,projects:X,currentProject:y,onSelectProject:we,onViewAllProjects:P,projectId:y?.id,mobileNavEnabled:ze,availableNodes:f,currentNode:p,onSelectNode:Je=>{Je===null?b():v(Je)},isRemote:w,experimentalFeatures:{insights:Pn,memoryView:kn,devServer:Vn,devServerView:Vn,researchView:as,evalsView:Wn},pluginDashboardViews:Re,shellConnectionControl:!ze&&Vi?t.jsx(Bg,{status:Vi,onError:Je=>n(Je,"error")}):void 0}),Te==="project"&&y&&!Gt&&Be!=="missions"&&!B.isPlanningOpen&&!he&&t.jsx(rF,{sessions:xe,onResumeSession:qi,onDismissSession:nr,onDismissAll:ei}),Te==="project"&&y&&t.jsx(cF,{onOpenSettings:()=>B.openSettings("general")}),Te==="project"&&y&&Aa&&t.jsx(fF,{onResume:B.openModelOnboarding}),Te==="project"&&y&&Wi&&t.jsx(gF,{onOpenModelOnboarding:B.openModelOnboarding,onOpenSettings:Je=>B.openSettings(Je)}),Te==="project"&&y&&E&&_&&K&&!U&&t.jsx(hF,{latestVersion:_,currentVersion:K,onDismiss:A}),Te==="project"&&y&&At?.taskIdIntegrity?.status==="anomaly"&&At.taskIdIntegrity.recommendedAction&&t.jsx(mF,{report:At.taskIdIntegrity,recommendedAction:At.taskIdIntegrity.recommendedAction,onRefresh:(Je,Rt)=>{zt(rn=>rn?{...rn,status:Je.status==="anomaly"||!rn.database.healthy?"degraded":"ok",taskIdIntegrity:{...Je,recommendedAction:Rt}}:null)}}),Te==="project"&&y&&!R&&F&&!yn&&t.jsx(Ov,{hasAiProvider:x,hasGithub:N,onDismiss:vn}),Te==="project"&&y&&Zt&&t.jsx(pF,{pendingCount:Math.max(sn,1),onOpenMailbox:()=>ct("mailbox"),onDismiss:()=>{at.current.set(Zt.dedupeKey,Math.max(Date.now(),Zt.updatedAtMs)),Wg(at.current),ve(null)}}),t.jsx("div",{className:`project-content${Te==="project"&&y&&(!ze||!Dt)?" project-content--with-footer":""}${ze&&!Dt?" project-content--with-mobile-nav":""}`,children:ar()}),Te==="project"&&y&&!Gt&&t.jsx(tF,{tasks:w&&k.tasks.length>0?k.tasks:ue,projectId:y.id,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,backgroundSessions:fe,backgroundGenerating:Z,backgroundNeedsInput:re,onOpenBackgroundSession:qi,onDismissBackgroundSession:L,lastFetchTimeMs:Ze,currentProjectPath:y.path,onOpenProjectDirectory:ki,keyboardOpen:Dt}),t.jsx(xF,{view:Be,onChangeView:Te==="project"&&y?ct:()=>{},footerVisible:Te==="project"&&!!y,modalOpen:B.anyModalOpen,keyboardOpen:Dt,onOpenSettings:Ui,onOpenActivityLog:Sa,onOpenSystemStats:Za,onOpenMailbox:()=>ct("mailbox"),onOpenNodes:ra,mailboxUnreadCount:nn,mailboxPendingApprovalCount:sn,chatHasUnreadResponse:xn,stashOrphanCount:Qt,onOpenGitManager:Xa,onOpenWorkflowSteps:_a,onOpenSchedules:Ca,onOpenScripts:Ea,onToggleTerminal:Mn,onOpenFiles:ci,onOpenTodos:Ai,todosOpen:B.todosOpen,onOpenGitHubImport:Qa,onOpenPlanning:Zs,onResumePlanning:Na,activePlanningSessionCount:q.length,onOpenUsage:()=>er(null),onViewAllProjects:P,onRunScript:Ma,projectId:y?.id,showSkillsTab:On,experimentalFeatures:{insights:Pn,memoryView:kn,devServer:Vn,devServerView:Vn,todoView:$s,researchView:as,evalsView:Wn,nodesView:Fn},pluginDashboardViews:Re,shellConnectionControl:ze&&Vi?t.jsx(Bg,{status:Vi,onError:Je=>n(Je,"error")}):void 0}),Te==="project"&&y&&Be!=="chat"&&Be!=="mailbox"&&Be!=="insights"&&Be!=="evals"&&Be!=="devserver"&&Be!=="dev-server"&&Be!=="graph"&&!wr(Be)&&t.jsx(BF,{projectId:y.id,addToast:n,showFAB:Oe,open:W,onOpenChange:Y,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn}),t.jsx(UO,{projectId:y?.id,tasks:ue,projects:d,currentProject:y,addToast:n,toasts:e,removeToast:s,modalManager:B,projectActions:{handleAddProject:Ce,handleSetupComplete:qe,handleModelOnboardingComplete:et},taskHandlers:{handleModalCreate:Ft,handlePlanningTaskCreated:cn,handlePlanningTasksCreated:pn,handleSubtaskTasksCreated:jn,handleGitHubImport:Un},taskOperations:{moveTask:Ee,deleteTask:ht,mergeTask:tt,retryTask:xt,resetTask:Me,duplicateTask:dt},deepLink:{handleDetailClose:ie},settings:{prAuthAvailable:Mt,themeMode:le,colorTheme:ke,dashboardFontScalePct:He,setThemeMode:ye,setColorTheme:je,setDashboardFontScalePct:ne},onSettingsClose:rs,onReopenOnboarding:di}),t.jsx(n6,{open:_e}),a&&t.jsxs(t.Fragment,{children:[t.jsx(Jz,{open:ir,shellApi:a,shellState:r,onComplete:()=>Kr(!0)}),t.jsx(Yz,{open:Jr,shellApi:a,shellState:r,onClose:()=>oa(!1)})]})]})})}function k6(){return t.jsx(tz,{children:t.jsx(Wz,{children:t.jsx(eO,{children:t.jsx(Iz,{children:t.jsx(WC,{children:t.jsx(w6,{})})})})})})}function my(e){e.postMessage({type:"SKIP_WAITING"})}function Gg(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&my(e)})}function j6(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,Hu("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&my(s.waiting),s.installing&&Gg(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&Gg(a)})}).catch(s=>{console.log("SW registration failed:",s)})}Pj();vj();cy();ay();vy.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(yj,{children:t.jsx(k6,{})})}));j6();export{s1 as $,Js as A,Qn as B,Xn as C,HC as D,Z3 as E,xa as F,gc as G,au as H,$n as I,ql as J,$8 as K,jt as L,qo as M,jk as N,BL as O,zn as P,Gd as Q,ps as R,Xi as S,zr as T,os as U,Ci as V,Tn as W,mn as X,LL as Y,ls as Z,En as _,gn as a,u5 as a$,ML as a0,AL as a1,i1 as a2,Y3 as a3,a1 as a4,c3 as a5,d3 as a6,cS as a7,zu as a8,Fr as a9,w8 as aA,y8 as aB,v8 as aC,b8 as aD,Oj as aE,Po as aF,h8 as aG,f8 as aH,p8 as aI,C8 as aJ,N8 as aK,S8 as aL,E8 as aM,p5 as aN,P8 as aO,To as aP,eu as aQ,Gk as aR,$i as aS,Ok as aT,lw as aU,Cs as aV,m$ as aW,Hs as aX,ob as aY,Dk as aZ,d5 as a_,Ga as aa,xi as ab,vi as ac,Li as ad,a8 as ae,d8 as af,c8 as ag,Kl as ah,u8 as ai,r8 as aj,m8 as ak,o8 as al,l8 as am,ms as an,zo as ao,Co as ap,Vs as aq,ij as ar,Oi as as,eb as at,ta as au,_y as av,g8 as aw,x8 as ax,j8 as ay,k8 as az,qn as b,P3 as b$,m5 as b0,h5 as b1,Cc as b2,QF as b3,uh as b4,Zr as b5,wg as b6,Y0 as b7,Ar as b8,V0 as b9,Om as bA,Zi as bB,J5 as bC,K5 as bD,Y5 as bE,H6 as bF,U6 as bG,B6 as bH,q6 as bI,Z6 as bJ,e3 as bK,Y6 as bL,G6 as bM,K6 as bN,J6 as bO,W6 as bP,V6 as bQ,z6 as bR,Q6 as bS,fD as bT,A3 as bU,M3 as bV,D3 as bW,_3 as bX,R3 as bY,I3 as bZ,T3 as b_,Q5 as ba,X5 as bb,G0 as bc,kF as bd,J0 as be,wF as bf,n8 as bg,s8 as bh,Z5 as bi,e8 as bj,t8 as bk,i8 as bl,wv as bm,MF as bn,aa as bo,Jv as bp,H0 as bq,ks as br,ba as bs,pc as bt,vF as bu,Da as bv,ab as bw,EF as bx,Ys as by,nb as bz,it as c,NN as c$,TS as c0,$3 as c1,Vu as c2,AS as c3,RS as c4,IS as c5,MS as c6,E3 as c7,wc as c8,Vk as c9,x3 as cA,p3 as cB,v3 as cC,f3 as cD,y3 as cE,g3 as cF,b3 as cG,Dy as cH,wN as cI,k3 as cJ,kN as cK,j3 as cL,fi as cM,zi as cN,VF as cO,tD as cP,t3 as cQ,g5 as cR,Dj as cS,_6 as cT,hg as cU,r5 as cV,M6 as cW,R6 as cX,F6 as cY,O6 as cZ,$N as c_,Cr as ca,v5 as cb,y5 as cc,w5 as cd,k5 as ce,j5 as cf,N5 as cg,S5 as ch,x5 as ci,db as cj,tk as ck,I as cl,ec as cm,Do as cn,Er as co,x1 as cp,Cj as cq,Ej as cr,mN as cs,hN as ct,z5 as cu,m3 as cv,u3 as cw,B5 as cx,h3 as cy,w3 as cz,a5 as d,e5 as d$,Fi as d0,SN as d1,EN as d2,CN as d3,_N as d4,MN as d5,i3 as d6,o5 as d7,l5 as d8,c5 as d9,Xp as dA,I8 as dB,T8 as dC,X6 as dD,C5 as dE,_5 as dF,R5 as dG,M5 as dH,E5 as dI,A5 as dJ,I5 as dK,uu as dL,qm as dM,G3 as dN,J3 as dO,O0 as dP,dw as dQ,za as dR,Os as dS,qw as dT,T5 as dU,X3 as dV,Ho as dW,YT as dX,ma as dY,K3 as dZ,t5 as d_,sa as da,M8 as db,A8 as dc,b5 as dd,I6 as de,tu as df,js as dg,hD as dh,HL as di,VL as dj,WL as dk,pa as dl,Kd as dm,KL as dn,P6 as dp,A6 as dq,$6 as dr,T6 as ds,D6 as dt,L6 as du,Ua as dv,D8 as dw,FC as dx,Nc as dy,R8 as dz,s5 as e,tb as e0,V3 as e1,q3 as e2,O3 as e3,F3 as e4,_L as e5,Ra as e6,Q3 as e7,U3 as e8,B3 as e9,s3 as eA,Rk as eB,o3 as eC,l3 as eD,r3 as eE,dS as ea,H3 as eb,W3 as ec,P5 as ed,P0 as ee,z3 as ef,L3 as eg,bi as eh,C3 as ei,N3 as ej,S3 as ek,$5 as el,U5 as em,ru as en,V5 as eo,W5 as ep,q5 as eq,O5 as er,L5 as es,F5 as et,D5 as eu,H5 as ev,f5 as ew,_8 as ex,a3 as ey,n3 as ez,Ba as f,i5 as g,Ws as h,Ur as i,Bn as j,cc as k,G5 as l,_s as m,n1 as n,n5 as o,oi as p,CF as q,RL as r,yi as s,Gn as t,Mi as u,li as v,fs as w,kc as x,sl as y,Se as z};
692
+ `)[0]?.trim()||rs?.title||"",ys=new Set(Jd),cs=vs.filter(P=>ys.has(P.id)).sort((P,Ce)=>{const qe=Jd.indexOf(P.id),et=Jd.indexOf(Ce.id);return qe!==et?qe-et:vg(P,Ce)}),ss=vs.filter(P=>P.authenticated&&!ys.has(P.id)),te=vs.filter(P=>!P.authenticated&&!ys.has(P.id)),we=P=>{const Ce=Ze[P.id]==="timeout"||Ze[P.id]==="failed"||Ze[P.id]==="cancelled",qe=P.loginInProgress&&!Ce;if(P.id==="llama-cpp"&&P.type==="cli")return t.jsx(WL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.id==="claude-cli"&&P.type==="cli")return t.jsx(HL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.id==="cursor-cli"&&P.type==="cli")return t.jsx(VL,{authenticated:P.authenticated,onToggled:()=>{qt()}},P.id);if(P.type==="api_key"){const et=$u(P.id),mt=PO(P);return t.jsxs("div",{"data-testid":`onboarding-provider-card-${P.id}`,className:`onboarding-provider-card${P.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${P.id}`,"aria-hidden":"true",children:t.jsx(zn,{provider:P.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsxs("strong",{className:"onboarding-provider-card__name",children:[t.jsx(ib,{size:14,className:"onboarding-provider-key-icon"}),P.name]}),t.jsx("span",{className:"onboarding-provider-card__description",children:et.description}),t.jsx(Gt,{status:Bt(P)}),P.authenticated&&P.keyHint&&t.jsxs("span",{className:"auth-key-hint",children:["Key: ",P.keyHint]})]}),t.jsx("div",{className:"onboarding-provider-card__actions onboarding-provider-card__actions--api-key",children:t.jsx(DO,{provider:P,apiKeyInfo:mt,inputValue:B[P.id]??"",isSaving:$===P.id,error:ze[P.id],success:Ve[P.id],isConnected:P.authenticated,onInputChange:zt,onSave:Zn,onClear:vn})})]},P.id)}return t.jsxs("div",{"data-testid":`onboarding-provider-card-${P.id}`,className:`onboarding-provider-card${P.authenticated?" onboarding-provider-card--connected":""}`,children:[t.jsx("div",{className:"onboarding-provider-card__icon","data-testid":`onboarding-provider-icon-${P.id}`,"aria-hidden":"true",children:t.jsx(zn,{provider:P.id,size:"md"})}),t.jsxs("div",{className:"onboarding-provider-card__body",children:[t.jsx("strong",{className:"onboarding-provider-card__name",children:P.name}),t.jsx("span",{className:"onboarding-provider-card__description",children:$u(P.id).description}),t.jsx(Gt,{status:Bt(P)})]}),t.jsx("div",{className:"onboarding-provider-card__actions",children:$===P.id?P.authenticated?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void At(P.id),children:"Cancel"})]}):qe?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void At(P.id),children:"Cancel"})]}):P.authenticated?t.jsx("button",{className:"btn btn-sm",onClick:()=>Dn(P.id),children:"Logout"}):t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>_e(P.id),children:"Login"})}),($===P.id||qe)&&X[P.id]&&t.jsx(Kd,{instructions:X[P.id],"data-testid":`onboarding-login-instructions-${P.id}`}),($===P.id||qe)&&ke[P.id]&&t.jsx(KL,{value:ye[P.id]??"",onChange:et=>je(mt=>({...mt,[P.id]:et})),onSubmit:()=>void ut(P.id),prompt:ke[P.id].prompt,placeholder:ke[P.id].placeholder,helpText:ke[P.id].helpText,disabled:ne===P.id,submitLabel:ne===P.id?"Submitting…":"Submit code","data-testid":`onboarding-manual-code-${P.id}`}),Ze[P.id]==="timeout"&&$!==P.id&&t.jsx("p",{className:"onboarding-helper-text onboarding-inline-feedback",children:"Login timed out. Please try again."}),Ze[P.id]==="failed"&&$!==P.id&&t.jsx("p",{className:"field-error onboarding-inline-feedback",children:"Login failed. Please try again."})]},P.id)};return t.jsx("div",{className:"modal-overlay open",role:"dialog","aria-modal":"true","aria-labelledby":"onboarding-title",children:t.jsxs("div",{className:"modal model-onboarding-modal",ref:J,children:[t.jsxs("div",{className:"model-onboarding-header",children:[t.jsxs("h2",{id:"onboarding-title",className:"model-onboarding-title",children:[v==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(ls,{size:24})," Set Up AI ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),v==="github"&&t.jsxs(t.Fragment,{children:[t.jsx(ii,{size:24})," Connect GitHub ",t.jsx("span",{className:"onboarding-optional-badge",children:"Optional"})]}),v==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx(Dm,{size:24})," Set Up Your Project"]}),v==="first-task"&&t.jsxs(t.Fragment,{children:[t.jsx(Dm,{size:24})," Create Your First Task"]}),v==="complete"&&t.jsxs(t.Fragment,{children:[t.jsx(Xn,{size:24})," All Set!"]})]}),v!=="complete"&&t.jsx("button",{className:"modal-close",onClick:Mt,"aria-label":"Skip onboarding",title:"Skip for now",children:t.jsx(mn,{size:20})})]}),t.jsx("div",{className:"model-onboarding-steps",children:on.map((P,Ce)=>{const qe=ln>Ce,et=y.includes(P.key)&&qe,mt=j.includes(P.key)&&!y.includes(P.key)&&qe,Nt=et||mt;return t.jsxs("div",{className:"onboarding-step-wrapper",children:[Ce>0&&t.jsx("div",{className:`model-onboarding-step-connector ${Ce<=ln?"done":""}`}),Nt?t.jsxs("button",{className:`model-onboarding-step-indicator ${v===P.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,onClick:()=>b(P.key),"aria-label":`Go back to ${P.label}`,title:`Review ${P.label}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(Xn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ce+1}),t.jsx("span",{className:"step-label",children:P.label})]}):t.jsxs("div",{className:`model-onboarding-step-indicator ${v===P.key?"active":""} ${et?"done":""} ${mt?"skipped":""}`,children:[t.jsx("span",{className:"step-number",children:et?t.jsx(Xn,{size:14}):mt?t.jsx("span",{className:"onboarding-step-skip-mark",children:"–"}):Ce+1}),t.jsx("span",{className:"step-label",children:P.label})]})]},P.key)})}),t.jsxs("div",{className:"model-onboarding-content",ref:Fe,children:[v==="ai-setup"&&t.jsxs("div",{className:"model-onboarding-ai-setup",children:[t.jsx("p",{className:"model-onboarding-description",children:"Fusion uses AI models to plan, write, and review code for you. Connect an AI provider below to get started — you can use a hosted service or enter an API key."}),t.jsx("p",{className:"onboarding-helper-text model-onboarding-primary-helper",children:"You only need one provider to get started."}),t.jsx("p",{className:"onboarding-helper-text",children:"Research runs require provider credentials and an enabled Research View. After onboarding, verify these in Settings → Authentication and Settings → Experimental Features."}),$s&&t.jsxs("div",{className:"card",children:[t.jsx("h3",{className:"onboarding-section-title",children:"Connect remote Fusion server"}),t.jsx("p",{className:"onboarding-helper-text",children:"Your native shell needs an active remote profile before dashboard handoff can complete."}),t.jsx("label",{htmlFor:"onboarding-shell-profile-name",className:"onboarding-apikey-field-label",children:"Profile name"}),t.jsx("input",{id:"onboarding-shell-profile-name",className:"input",value:oe,onChange:P=>Ee(P.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-server-url",className:"onboarding-apikey-field-label",children:"Server URL"}),t.jsx("input",{id:"onboarding-shell-server-url",className:"input",placeholder:"https://your-fusion-host",value:ft,onChange:P=>ht(P.target.value)}),t.jsx("label",{htmlFor:"onboarding-shell-token",className:"onboarding-apikey-field-label",children:"Auth token (optional)"}),t.jsx("input",{id:"onboarding-shell-token",className:"input",type:"password",value:tt,onChange:P=>xt(P.target.value)}),dt&&t.jsx("small",{className:"field-error",children:dt}),t.jsxs("div",{className:"onboarding-apikey-input-row",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void st?.openConnectionManager(),children:"Open manager"}),t.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:()=>void Wn(),disabled:!ft.trim()||Me,children:Me?"Saving…":"Save remote server"})]})]}),!M&&H.length>0&&(()=>{const P=H.filter(Nt=>Nt.id!=="github"&&Nt.authenticated).length,Ce=H.filter(Nt=>Nt.id!=="github").length,qe=Object.keys(Dt).filter(Nt=>!H.find(Pt=>Pt.id===Nt)?.authenticated).length;if(Ce===0)return null;let et="onboarding-provider-summary",mt="";return P>0?(et+=" onboarding-provider-summary--connected",mt=`✓ ${P} of ${Ce} provider${Ce!==1?"s":""} connected`):qe>0?(et+=" onboarding-provider-summary--skipped",mt=`${qe} provider${qe!==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(pa,{slotId:"onboarding-recommendation-card",projectId:s}),t.jsx(fi,{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."})}),H.length>0&&!H.some(P=>P.authenticated)&&t.jsx("p",{className:"onboarding-helper-text",children:"Skip this step if you'd like — you can always add providers later from Settings."}),M?t.jsxs("div",{className:"model-onboarding-loading",children:[t.jsx(jt,{size:24,className:"animate-spin"}),t.jsx("span",{children:"Loading providers…"})]}):H.length===0?t.jsx("div",{className:"model-onboarding-empty",children:"No AI providers are configured. Please check your Fusion configuration."}):t.jsxs(t.Fragment,{children:[t.jsx(pa,{slotId:"onboarding-provider-card",projectId:s,renderPlaceholder:!1,actions:{refreshAuthProviders:()=>{qt()}}}),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"}),cs.length>0?t.jsx("div",{className:"model-onboarding-providers",children:cs.map(P=>we(P))}):t.jsx("p",{className:"onboarding-helper-text",children:"No quick-start providers are available in this environment."})]}),ss.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:ss.map(P=>we(P))})]}),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(fi,{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."})}),Z.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(_s,{models:Z,value:q,onChange:de,placeholder:"Select a default model…",label:"Default model"})}),q&&t.jsx("div",{className:"onboarding-model-preview",children:t.jsxs("small",{className:"settings-muted",children:["Selected:"," ",Z.find(P=>P.id===q)?.name??q]})})]}),t.jsx(fi,{summary:"Advanced provider settings",className:"onboarding-provider-advanced",children:t.jsxs("div",{"data-testid":"onboarding-advanced-provider-settings",children:[te.length>0?t.jsx("div",{className:"model-onboarding-providers",children:te.map(P=>we(P))}):t.jsx("p",{className:"onboarding-helper-text",children:"All currently available providers are already shown above."}),rt.length>0?t.jsx("div",{className:"onboarding-custom-provider-list",children:rt.map(P=>t.jsxs("div",{className:"onboarding-custom-provider-item",children:[t.jsx(zn,{provider:P.id,size:"sm"}),t.jsx("span",{children:P.name||P.id})]},P.id))}):null,ce?t.jsx(QL,{onSave:hn,onCancel:()=>{Re(!1),ue(void 0)},saving:Le,error:Ue}):t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>Re(!0),children:"Add custom provider"})]})}),As&&t.jsx(fi,{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."})}),bn&&t.jsx(fi,{summary:"What is an API key?",children:t.jsx("p",{className:"onboarding-helper-text",children:"An API key is a secret token that authenticates Fusion with the provider. You can find your key in the provider's dashboard under API settings. Keys are stored securely on your machine."})}),t.jsx(pa,{slotId:"onboarding-setup-help",projectId:s})]})]}),v==="github"&&t.jsxs("div",{className:"model-onboarding-github",children:[It?t.jsx("p",{className:"model-onboarding-description",children:Lt?"GitHub CLI is already authenticated — issue imports and pull request tracking work right now. You're all set; no further action needed.":"GitHub is connected — issue imports and pull request tracking are available. You're all set; no further action needed."}):t.jsx("p",{className:"model-onboarding-description",children:"Connecting GitHub unlocks issue imports and pull request tracking. You can skip this — task creation works without it."}),!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"})]})}),as&&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(fi,{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."})}),Pe?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(ii,{size:16,className:"onboarding-provider-title-icon"}),"GitHub"]}),t.jsx("span",{"data-testid":"onboarding-auth-status-github",children:t.jsx(Ot,{status:kn})})]}),Ke&&($==="github"?t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Logging out…"}):t.jsx("button",{className:"btn btn-sm",onClick:()=>Dn("github"),children:"Disconnect"}))]}),(kn==="not-connected"||kn==="pending")&&t.jsxs("div",{className:"onboarding-github-connect-cta","data-testid":"onboarding-github-connect-cta",children:[$==="github"||at?t.jsxs("div",{className:"onboarding-github-connect-actions",children:[t.jsx("button",{className:"btn btn-sm",disabled:!0,children:"Waiting for login…"}),t.jsx("button",{className:"btn btn-sm",onClick:()=>void At("github"),children:"Cancel"})]}):t.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>_e("github"),children:[t.jsx(ii,{size:16}),"Connect"]}),($==="github"||at)&&X.github&&t.jsx(Kd,{instructions:X.github,"data-testid":"onboarding-login-instructions-github"})]}),kn==="connected"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--success",children:Lt?"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."}),kn==="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:()=>_e("github"),children:"Retry"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Y,children:"Skip for now"})]})]}),kn==="pending"&&t.jsx("div",{className:"onboarding-github-feedback onboarding-github-feedback--info",children:"Waiting for GitHub authorization…"}),kn==="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:()=>_e("github"),children:"Connect anyway"})})]}),kn==="not-connected"&&t.jsx("p",{className:"onboarding-helper-text",children:"No worries if you're not ready — connect GitHub anytime from Settings → Authentication."})]}):t.jsxs("div",{className:"model-onboarding-github-optional",children:[t.jsx("div",{className:"optional-icon optional-icon--github","aria-hidden":"true",children:t.jsx(zn,{provider:"github",size:"lg"})}),Lt?t.jsx("p",{children:"GitHub CLI is already authenticated, so imports and PR tracking work now. OAuth from the dashboard is optional and only controls dashboard-managed connect/disconnect."}):t.jsx("p",{children:"GitHub OAuth isn't connected yet. You can set it up in Settings → Authentication, or continue now and connect later."}),t.jsxs("div",{className:"model-onboarding-github-optional__actions",children:[t.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>b("project-setup"),children:Lt?"Continue with gh CLI auth →":"Continue without GitHub →"}),Lt&&($==="github"||at?t.jsxs("button",{className:"btn btn-sm",disabled:!0,children:[t.jsx(jt,{size:14,className:"onboarding-spinner"}),"Waiting for OAuth login…"]}):t.jsxs("button",{className:"btn btn-sm",onClick:()=>_e("github"),children:[t.jsx(zn,{provider:"github",size:"sm"}),"Connect OAuth (optional)"]}))]}),Lt&&($==="github"||at)&&X.github&&t.jsx(Kd,{instructions:X.github,"data-testid":"onboarding-login-instructions-github"})]})]}),v==="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:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"}),t.jsx("p",{className:"onboarding-helper-text",children:"In the setup wizard, pick an existing directory or paste a GitHub clone URL."})]}),t.jsx(fi,{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."})})]}),v==="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."}),x&&rs?t.jsxs("div",{className:"onboarding-task-created",children:[t.jsx(Xn,{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:rs.id}),Ns&&t.jsx("p",{className:"onboarding-task-created__description",children:Ns}),t.jsx("p",{className:"onboarding-task-created__hint",children:"Your task has been created and will appear on the board."}),t.jsxs("div",{className:"onboarding-task-created__actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:_n,children:"View Task"}),t.jsx("button",{type:"button",className:"btn",onClick:Pn,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:R,onChange:P=>{F(P.target.value),U(null)},placeholder:"Example: Build a login page with email and password",rows:4}),t.jsx("div",{className:"onboarding-first-task-form__actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",onClick:_t,disabled:E,"data-testid":"onboarding-first-task-submit",children:E?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Creating task…"})]}):"Create First Task"})})]}),K&&t.jsxs("div",{className:"onboarding-task-error",role:"alert","data-testid":"onboarding-task-error",children:[t.jsx("p",{className:"field-error",children:K}),t.jsx("p",{className:"onboarding-helper-text",children:"Your text has been preserved — fix the issue and try again."})]})]}):t.jsxs("div",{className:"onboarding-project-prerequisite","data-testid":"onboarding-project-prerequisite",children:[t.jsx("p",{className:"onboarding-helper-text",children:"A project must be selected before you can create tasks or import from GitHub."}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:a,"data-testid":"onboarding-open-setup-wizard",children:"Set Up Project"})]}),t.jsx($O,{items:In}),Fn&&t.jsxs(t.Fragment,{children:[t.jsx(fi,{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:G,disabled:xe,children:[t.jsx("div",{className:"cta-icon",children:t.jsx($n,{size:24})}),t.jsxs("div",{className:"cta-content",children:[t.jsx("strong",{children:"Create a New Task"}),t.jsx("span",{children:"Describe what you need built and AI will work on it"})]})]}),t.jsxs("button",{className:`onboarding-cta-card${It?"":" onboarding-cta-card--disabled"}`,"data-testid":"cta-github-import",onClick:Oe,disabled:xe||!It,children:[t.jsx("div",{className:"cta-icon",children:t.jsx(ii,{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"}),!It&&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."]})]})]})]}),v==="complete"&&t.jsxs("div",{className:"model-onboarding-complete",children:[t.jsx(Xn,{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:[v==="ai-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:Mt,disabled:xe,children:"Skip for now"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ne,children:"Skip setup →"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,children:"Next →"})]}),v==="github"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"onboarding-skip-step-link",onClick:Ne,children:"Skip GitHub →"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,children:"Next →"})]}),v==="project-setup"&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:tn,disabled:!Fn,children:"Next →"})]}),v==="first-task"&&!x&&t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn btn-sm",onClick:W,children:"← Back"}),t.jsx("button",{className:"btn btn-primary",onClick:ot,disabled:xe,children:xe?t.jsxs(t.Fragment,{children:[t.jsx(jt,{size:16,className:"animate-spin"}),t.jsx("span",{children:"Saving…"})]}):"Finish Setup"})]}),v==="complete"&&t.jsxs("button",{className:"btn btn-primary",onClick:Xt,children:[t.jsx(Xn,{size:16}),t.jsx("span",{children:"Get Started"})]})]})]})})}function Wv({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 FO=i.lazy(()=>En(()=>import("./SetupWizardModal-SVUr5Mpm.js"),__vite__mapDeps([13,1,14,15,16,17,5,6,18])).then(e=>({default:e.SetupWizardModal}))),zO=i.lazy(()=>En(()=>import("./SettingsModal-3Jxv4PMI.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23])).then(e=>({default:e.SettingsModal})));function BO(){(typeof window<"u"&&window.requestIdleCallback||(n=>globalThis.setTimeout(n,200)))(()=>{En(()=>import("./SettingsModal-3Jxv4PMI.js"),__vite__mapDeps([19,1,20,21,22,2,5,6,23]))},{timeout:1500})}function UO({projectId:e,tasks:n,projects:s,currentProject:a,addToast:r,toasts:o,removeToast:l,modalManager:c,projectActions:d,taskHandlers:u,taskOperations:m,deepLink:h,settings:f,onSettingsClose:p,onReopenOnboarding:g}){const[w,v]=i.useState(null),b=c.detailTask?(()=>{const N=n.find(R=>R.id===c.detailTask?.id);return N?"prompt"in c.detailTask?{...c.detailTask,...N,prompt:c.detailTask.prompt,log:c.detailTask.log}:N:c.detailTask})():null,y=p??c.closeSettings,S=i.useCallback(()=>{c.openNewTask()},[c]),j=i.useCallback(()=>{c.openGitHubImport()},[c]),C=i.useCallback(N=>{v(null),c.closeModelOnboarding(),c.openDetailTask(N)},[c]),x=i.useCallback(async N=>{const R=await u.handleModalCreate(N);return c.modelOnboardingOpen&&v(R),R},[u.handleModalCreate,c.modelOnboardingOpen]);return i.useEffect(()=>{!c.modelOnboardingOpen&&w&&v(null)},[c.modelOnboardingOpen,w]),i.useEffect(()=>{BO()},[]),t.jsxs(t.Fragment,{children:[b&&t.jsx(Ia,{children:t.jsx(ZP,{task:b,projectId:e,tasks:n,onClose:h.handleDetailClose,onOpenDetail:c.openDetailTask,mobileHeaderMode:c.detailTaskOrigin==="list-mobile"?"back":"close",onMoveTask:m.moveTask,onDeleteTask:m.deleteTask,onMergeTask:m.mergeTask,onRetryTask:m.retryTask,onResetTask:m.resetTask,onDuplicateTask:m.duplicateTask,onTaskUpdated:c.updateDetailTask,addToast:r,prAuthAvailable:f.prAuthAvailable,initialTab:c.detailTaskInitialTab})}),c.settingsOpen&&t.jsx(Ia,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(zO,{onClose:y,addToast:r,initialSection:c.settingsInitialSection,projectId:e,themeMode:f.themeMode,colorTheme:f.colorTheme,onThemeModeChange:f.setThemeMode,onColorThemeChange:f.setColorTheme,dashboardFontScalePct:f.dashboardFontScalePct,onDashboardFontScaleChange:f.setDashboardFontScalePct,onReopenOnboarding:g})})}),t.jsx(p4,{isOpen:c.githubImportOpen,onClose:c.closeGitHubImport,onImport:u.handleGitHubImport,tasks:n,projectId:e}),t.jsx(Ia,{children:t.jsx(y4,{isOpen:c.isPlanningOpen,onClose:c.closePlanning,onTaskCreated:u.handlePlanningTaskCreated,onTasksCreated:u.handlePlanningTasksCreated,tasks:n,initialPlan:c.planningInitialPlan??void 0,projectId:e,resumeSessionId:c.planningResumeSessionId})}),t.jsx(Ia,{children:t.jsx(A4,{isOpen:c.isSubtaskOpen,onClose:c.closeSubtask,initialDescription:c.subtaskInitialDescription??"",onTasksCreated:u.handleSubtaskTasksCreated,projectId:e,resumeSessionId:c.subtaskResumeSessionId})}),t.jsx(X4,{isOpen:c.terminalOpen,onClose:c.closeTerminal,initialCommand:c.terminalInitialCommand,projectId:e}),t.jsx(eD,{isOpen:c.scriptsOpen,onClose:c.closeScripts,addToast:r,onRunScript:c.runScript,projectId:e}),c.filesOpen&&t.jsx(jD,{initialWorkspace:c.fileBrowserWorkspace,initialFile:c.fileBrowserInitialFile,isOpen:!0,onClose:c.closeFiles,onWorkspaceChange:c.setFileWorkspace,projectId:e}),c.todosOpen&&t.jsx(SD,{isOpen:!0,onClose:c.closeTodos,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan}),t.jsx(PD,{isOpen:c.usageOpen,onClose:c.closeUsage,projectId:e,anchorRect:c.usageAnchorRect}),t.jsx(dL,{isOpen:c.systemStatsOpen,onClose:c.closeSystemStats,projectId:e}),c.schedulesOpen&&t.jsx(eL,{onClose:c.closeSchedules,addToast:r,projectId:e}),t.jsx(Ia,{children:t.jsx(iL,{isOpen:c.newTaskModalOpen,onClose:c.closeNewTask,tasks:n,onCreateTask:x,addToast:r,projectId:e,onPlanningMode:c.openPlanningWithInitialPlan,onSubtaskBreakdown:c.openSubtaskBreakdown})}),t.jsx(fL,{isOpen:c.activityLogOpen,onClose:c.closeActivityLog,tasks:n,projectId:e,projects:s,currentProject:a,onOpenTaskDetail:N=>{const R=n.find(F=>F.id===N);R&&c.openDetailTask(R)}}),t.jsx(Ia,{children:t.jsx(bL,{isOpen:c.gitManagerOpen,onClose:c.closeGitManager,tasks:n,addToast:r,projectId:e})}),t.jsx(Ia,{children:t.jsx(EL,{isOpen:c.workflowStepsOpen,onClose:c.closeWorkflowSteps,addToast:r,projectId:e})}),t.jsx(UL,{isOpen:c.agentsOpen,onClose:c.closeAgents,addToast:r,projectId:e}),c.setupWizardOpen&&t.jsx(i.Suspense,{fallback:null,children:t.jsx(FO,{onProjectRegistered:d.handleSetupComplete,onClose:c.closeSetupWizard})}),c.modelOnboardingOpen&&t.jsx(OO,{onComplete:d.handleModelOnboardingComplete,addToast:r,projectId:e??"",onOpenSetupWizard:d.handleAddProject,onOpenNewTask:S,onOpenGitHubImport:j,firstCreatedTask:w,onViewTask:C}),t.jsx(Wv,{toasts:o,onRemove:l})]})}function HO({errorMessage:e,isRetrying:n,onRetry:s,onManageConnection:a}){return t.jsxs("div",{className:"project-overview-empty",role:"alert","aria-live":"polite",children:[t.jsx("h2",{children:"Can't reach the Fusion backend"}),t.jsx("p",{className:"settings-muted",children:"Fusion couldn't load your projects right now. Please make sure the backend is running and try again."}),t.jsxs("p",{className:"settings-muted",children:["Error: ",e]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn btn-primary",onClick:s,disabled:n,children:n?"Retrying…":"Retry Connection"}),a&&t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Manage Connection"})]})]})}const Du=[{id:"projects",label:"Loading projects"},{id:"project",label:"Selecting project"},{id:"tasks",label:"Fetching tasks"}];function qO(e,n){if(n==="ready")return"done";const s=Du.findIndex(r=>r.id===n),a=Du.findIndex(r=>r.id===e);return a<s?"done":a===s?"active":"pending"}function VO({stage:e}){const[n]=i.useState(()=>hj());return t.jsx("div",{className:"dashboard-loader",role:"status","aria-live":"polite","aria-label":n?"Updating Fusion dashboard":"Loading Fusion dashboard","data-stage":e,"data-version-update":n?"true":void 0,children:t.jsxs("div",{className:"dashboard-loader__content",children:[t.jsx("h1",{className:"dashboard-loader__logo",children:"Fusion"}),n?t.jsx("p",{className:"dashboard-loader__message dashboard-loader__message--update",children:"Updating to a new frontend version..."}):t.jsx("p",{className:"dashboard-loader__message",children:"Initializing dashboard..."}),t.jsx("ol",{className:"dashboard-loader__steps","aria-label":"Dashboard loading progress",children:Du.map(s=>{const a=qO(s.id,e);return t.jsxs("li",{className:`dashboard-loader__step dashboard-loader__step--${a}`,"data-testid":`dashboard-loader-step-${s.id}`,children:[t.jsx("span",{className:"dashboard-loader__step-icon","aria-hidden":"true",children:a==="done"?"✓":a==="active"?t.jsx(jt,{className:"dashboard-loader__spinner animate-spin",size:14}):"•"}),t.jsx("span",{className:"dashboard-loader__step-label",children:s.label})]},s.id)})})]})})}const WO=5e3;function GO(e,n,s){return e||n&&s===0?"idle":n&&s>0?"paused":s>0?"running":"idle"}function KO(e,n,s){let a=0,r=0,o=0,l=0,c=0;for(const d of e){switch(d.column){case"in-progress":a++,ec(d,n,s)&&o++;break;case"todo":l++;break;case"in-review":c++;break}d.blockedBy&&d.blockedBy.length>0&&r++}return{runningTaskCount:a,blockedTaskCount:r,stuckTaskCount:o,queuedTaskCount:l,inReviewCount:c}}function JO(e,n,s,a){const[r,o]=i.useState({globalPause:!1,enginePaused:!1,maxConcurrent:2}),[l,c]=i.useState(!0),[d,u]=i.useState(null),m=i.useRef(null),h=i.useRef(null),f=i.useCallback(async()=>{h.current&&h.current.abort(),h.current=new AbortController;try{c(!0),u(null);const v=await y1(n);o(v)}catch(v){if(v instanceof Error&&v.name==="AbortError")return;u(v instanceof Error?v.message:"Failed to fetch executor stats")}finally{c(!1)}},[n]);i.useEffect(()=>(f(),()=>{h.current&&h.current.abort()}),[f]),i.useEffect(()=>(m.current&&clearInterval(m.current),m.current=setInterval(()=>{f()},WO),()=>{m.current&&(clearInterval(m.current),m.current=null)}),[f]);const p=KO(e,s,a),g=GO(r.globalPause,r.enginePaused,p.runningTaskCount);return{stats:{...p,executorState:g,maxConcurrent:r.maxConcurrent,lastActivityAt:r.lastActivityAt},loading:l,error:d,refresh:f}}const YO={planning:Oi,subtask:Fa,mission_interview:Es,milestone_interview:Es,slice_interview:Es},QO={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"};function XO({sessions:e,generating:n,needsInput:s,onOpenSession:a,onDismissSession:r}){const{confirm:o}=li(),[l,c]=i.useState(!1),[d,u]=i.useState(new Set),m=i.useRef(null),h=i.useRef(new Map),f=i.useRef(null),{activeTabMap:p}=Wr(),g=i.useMemo(()=>Ja(),[]);if(i.useEffect(()=>{if(!l)return;const b=y=>{m.current&&!m.current.contains(y.target)&&c(!1)};return document.addEventListener("mousedown",b),()=>document.removeEventListener("mousedown",b)},[l]),i.useEffect(()=>{const b=new Set,y=new Map;for(const S of e){const j=p.get(S.id),C=[S.status,S.updatedAt,j?.tabId??S.lockedByTab??"",j?.stale?"stale":"fresh"].join("|"),x=h.current.get(S.id);x&&x!==C&&b.add(S.id),y.set(S.id,C)}if(h.current=y,b.size!==0)return u(b),f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{u(new Set),f.current=null},500),()=>{f.current&&(clearTimeout(f.current),f.current=null)}},[p,e]),e.length===0)return null;const w=e.length,v=s>0;return t.jsxs("div",{ref:m,className:"background-tasks-indicator",children:[t.jsxs("button",{className:`background-tasks-indicator__pill${v?" background-tasks-indicator__pill--attention":""}`,onClick:()=>c(b=>!b),title:`${w} background AI task${w!==1?"s":""}${s>0?` (${s} need${s!==1?"":"s"} input)`:""}`,children:[n>0&&t.jsx(jt,{size:12,style:{animation:"spin 1s linear infinite"}}),s>0&&n===0&&t.jsx(tu,{size:12}),t.jsxs("span",{children:["AI ",w]})]}),l&&t.jsxs("div",{className:"background-tasks-indicator__popover",children:[t.jsx("div",{className:"background-tasks-indicator__popover-header",children:"Background Tasks"}),t.jsx("div",{className:"background-tasks-indicator__popover-list",children:e.map(b=>{const y=YO[b.type],S=b.status==="generating",j=b.status==="awaiting_input",C=b.status==="error",x=p.get(b.id),N=x?.tabId??b.lockedByTab??null,R=!!(N&&N!==g&&!x?.stale),F=d.has(b.id);return t.jsxs("div",{className:`background-tasks-indicator__item${F?" background-tasks-indicator__item--updated":""}`,style:{transition:"background-color 220ms ease, transform 220ms ease",backgroundColor:F?"var(--color-accent-soft, rgba(59, 130, 246, 0.14))":void 0,transform:F?"translateY(-1px)":void 0},onClick:async()=>{R&&!await o({title:"Open Active Session",message:"This session is active in another tab. Open anyway?"})||(a(b),c(!1))},children:[C?t.jsx(Vs,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--color-error)"}}):t.jsx(y,{size:14,className:"background-tasks-indicator__session-icon"}),t.jsxs("div",{className:"background-tasks-indicator__session-content",children:[t.jsx("div",{className:"background-tasks-indicator__session-title",children:b.title}),t.jsxs("div",{className:"background-tasks-indicator__session-meta",children:[C?"Failed":QO[b.type],S&&" — generating...",j&&!R&&" — needs input",j&&R&&" — active in another tab"]})]}),S&&t.jsx(jt,{size:14,className:"background-tasks-indicator__session-icon",style:{animation:"spin 1s linear infinite",color:"var(--color-success)"}}),j&&!R&&t.jsx(tu,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--triage)"}}),j&&R&&t.jsx(yc,{size:14,className:"background-tasks-indicator__session-icon",style:{color:"var(--text-muted)"}}),t.jsx("button",{className:"background-tasks-indicator__item-dismiss",onClick:E=>{E.stopPropagation(),r(b.id)},title:"Dismiss",children:t.jsx(mn,{size:12})})]},b.id)})})]})]})}function ZO(e){if(!e)return"no activity";const n=Date.now(),s=new Date(e).getTime(),a=n-s,r=Math.floor(a/1e3),o=Math.floor(r/60),l=Math.floor(o/60),c=Math.floor(l/24);return c>0?`${c}d ago`:l>0?`${l}h ago`:o>0?`${o}m ago`:r>10?`${r}s ago`:"just now"}function eF(e){switch(e){case"running":return{label:"Running",color:"var(--color-success)",icon:os};case"paused":return{label:"Paused",color:"var(--triage)",icon:Ci};case"idle":default:return{label:"Idle",color:"var(--text-muted)",icon:ls}}}function tF({tasks:e,projectId:n,taskStuckTimeoutMs:s,staleHighFanoutBlockerAgeThresholdMs:a,backgroundSessions:r,backgroundGenerating:o,backgroundNeedsInput:l,onOpenBackgroundSession:c,onDismissBackgroundSession:d,lastFetchTimeMs:u,currentProjectPath:m,onOpenProjectDirectory:h,keyboardOpen:f}){if(f)return null;const{stats:p,loading:g,error:w}=JO(e,n,s,u),[v,b]=i.useState(!1),y=i.useMemo(()=>eF(p.executorState),[p.executorState]),S=i.useMemo(()=>ZO(p.lastActivityAt),[p.lastActivityAt]),j=i.useMemo(()=>{const x=tm(e,{staleHighFanoutAgeThresholdMs:a??Lb});return Array.from(x.values()).map(R=>R.escalation).filter(R=>!!R).sort((R,F)=>F.activeTodoCount!==R.activeTodoCount?F.activeTodoCount-R.activeTodoCount:F.totalActiveCount!==R.totalActiveCount?F.totalActiveCount-R.totalActiveCount:F.blockingAgeMs!==R.blockingAgeMs?F.blockingAgeMs-R.blockingAgeMs:R.blockerId.localeCompare(F.blockerId,"en",{numeric:!0,sensitivity:"base"}))[0]??null},[e,a]),C=y.icon;return w?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(zr,{size:14}),w]})}):g&&p.runningTaskCount===0?t.jsx("div",{className:"executor-status-bar executor-status-bar--loading",role:"status","aria-label":"Executor status",children:t.jsx("span",{className:"executor-status-bar__loading-text",children:"Loading..."})}):t.jsxs("div",{className:`executor-status-bar ${p.executorState==="running"?"executor-status-bar--running":""}`,role:"status","aria-label":"Executor status",children:[r&&r.length>0&&c&&d&&t.jsxs(t.Fragment,{children:[t.jsx(XO,{sessions:r,generating:o??0,needsInput:l??0,onOpenSession:c,onDismissSession:d}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--queued","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Queued"}),t.jsx("span",{className:"executor-status-bar__count",children:p.queuedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--running ${p.runningTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Running"}),t.jsx("span",{className:"executor-status-bar__count",children:p.runningTaskCount}),t.jsx("span",{className:"executor-status-bar__separator","aria-hidden":"true",children:"/"}),t.jsx("span",{className:"executor-status-bar__max",children:p.maxConcurrent})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),p.stuckTaskCount>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--stuck",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--stuck executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Stuck"}),t.jsx("span",{className:"executor-status-bar__count executor-status-bar__count--error",children:p.stuckTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:`executor-status-bar__indicator executor-status-bar__indicator--blocked ${p.blockedTaskCount>0?"executor-status-bar__indicator--active":""}`,"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Blocked"}),t.jsx("span",{className:`executor-status-bar__count ${p.blockedTaskCount>0?"executor-status-bar__count--warning":""}`,children:p.blockedTaskCount})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--review","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"In Review"}),t.jsx("span",{className:"executor-status-bar__count",children:p.inReviewCount})]}),j&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--fanout",children:[t.jsx("span",{className:"executor-status-bar__indicator executor-status-bar__indicator--fanout executor-status-bar__indicator--active","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__label",children:"Escalated"}),t.jsxs("span",{className:"executor-status-bar__fanout-summary",title:`Escalated blocker ${j.blockerId}: ${j.activeTodoCount} todo waiting (threshold ${Xu}), ${j.totalActiveCount} active total`,children:[j.blockerId," · ",j.activeTodoCount," todo"]})]})]}),m&&h&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--project-directory",children:[t.jsx("button",{className:`executor-status-bar__folder-toggle${v?" executor-status-bar__folder-toggle--active":""}`,onClick:()=>b(x=>!x),"aria-label":v?"Hide project directory":"Show project directory","aria-expanded":v,"data-testid":"executor-project-path-toggle",title:v?"Hide project directory":"Show project directory",children:t.jsx(js,{size:12,"aria-hidden":"true"})}),v&&t.jsx("button",{className:"executor-status-bar__project-path",onClick:h,title:m,"data-testid":"executor-project-path-link",children:m})]})]}),t.jsx("div",{className:"executor-status-bar__spacer"}),t.jsxs("div",{className:"executor-status-bar__segment executor-status-bar__segment--time",children:[t.jsx(ta,{size:12,className:"executor-status-bar__icon","aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__time",children:S})]}),t.jsx("span",{className:"executor-status-bar__divider","aria-hidden":"true"}),t.jsxs("div",{className:"executor-status-bar__segment",children:[t.jsx(C,{size:12,style:{color:y.color},"aria-hidden":"true"}),t.jsx("span",{className:"executor-status-bar__state",style:{color:y.color},children:y.label})]})]})}const nF={planning:Oi,subtask:Fa,mission_interview:Es,milestone_interview:Es,slice_interview:Es},sF={planning:"Planning",subtask:"Subtask Breakdown",mission_interview:"Mission Interview",milestone_interview:"Milestone Interview",slice_interview:"Slice Interview"},Gv="fusion:session-banner-dismissed";function So(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function iF(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(Gv);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n)){const o=typeof r=="number"?r:So(r);s.set(a,o)}return s}catch{return new Map}}function aF(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(Gv,JSON.stringify(n))}catch{}}const Qi=iF();function rF({sessions:e,onResumeSession:n,onDismissSession:s,onDismissAll:a}){const[r,o]=i.useState(0),l=()=>{aF(Qi),o(g=>g+1)};i.useEffect(()=>{if(Qi.size===0)return;const g=new Map(e.map(v=>[v.id,v]));let w=!1;for(const[v,b]of Qi){const y=g.get(v);if(!y)continue;if(!(y.status==="awaiting_input"||y.status==="error")){Qi.delete(v),w=!0;continue}So(y.updatedAt)>b&&(Qi.delete(v),w=!0)}w&&l()},[e]);const c=i.useMemo(()=>e.filter(g=>{if(g.status!=="awaiting_input"&&g.status!=="error")return!1;const w=Qi.get(g.id);return w===void 0?!0:So(g.updatedAt)>w}),[e,r]);if(c.length===0)return null;const d=c.filter(g=>g.status==="awaiting_input").length,u=c.filter(g=>g.status==="error").length;let m="";d>0&&u>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input, ${u} failed`:d>0?m=`${d} AI session${d===1?"":"s"} need${d===1?"s":""} your input`:u>0&&(m=`${u} AI session${u===1?"":"s"} failed`);const h=g=>{Qi.set(g.id,Math.max(So(g.updatedAt),Date.now())),l()},f=g=>{Qi.delete(g.id),l(),n(g)},p=()=>{const g=Date.now();for(const w of c)Qi.set(w.id,Math.max(So(w.updatedAt),g));l(),a()};return t.jsxs("section",{className:"session-notification-banner",role:"region","aria-live":"polite","aria-label":"AI sessions needing input or failed",children:[t.jsxs("div",{className:"session-notification-banner__header",children:[t.jsxs("div",{className:"session-notification-banner__headline",children:[t.jsx(Vs,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:m})]}),t.jsxs("button",{className:"session-notification-banner__dismiss-all",onClick:p,children:[t.jsx(mn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Dismiss all"})]})]}),t.jsx("div",{className:"session-notification-banner__list",children:c.map(g=>{const w=nF[g.type],v=g.status==="error";return t.jsxs("article",{className:`session-notification-banner__item${v?" session-notification-banner__item--error":""}`,"data-session-type":g.type,"data-session-status":g.status,children:[t.jsxs("div",{className:"session-notification-banner__item-main",children:[v?t.jsx(Vs,{size:16,className:"session-notification-banner__type-icon session-notification-banner__type-icon--error","aria-hidden":"true"}):t.jsx(w,{size:16,className:"session-notification-banner__type-icon","aria-hidden":"true"}),t.jsxs("div",{className:"session-notification-banner__text",children:[t.jsx("p",{className:"session-notification-banner__title",title:g.title,children:g.title}),t.jsx("p",{className:"session-notification-banner__meta",children:v?"Failed":sF[g.type]})]})]}),t.jsxs("div",{className:"session-notification-banner__actions",children:[t.jsx("button",{className:"session-notification-banner__resume",onClick:()=>f(g),children:v?"Retry":"Resume"}),t.jsx("button",{className:"session-notification-banner__dismiss",onClick:()=>{h(g),s(g.id)},"aria-label":`Dismiss ${g.title}`,children:t.jsx(mn,{size:14,"aria-hidden":"true"})})]})]},g.id)})})]})}const Kv="fusion:cli-binary-banner-dismissed";function oF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(Kv)==="1"}catch{return!1}}function lF(){if(!(typeof window>"u"))try{window.localStorage.setItem(Kv,"1")}catch{}}function cF({onOpenSettings:e}){const[n,s]=i.useState(null),[a,r]=i.useState(()=>oF()),[o,l]=i.useState(!1),[c,d]=i.useState(null);i.useEffect(()=>{if(a)return;let y=!1;return mN().then(S=>{y||s(S)}).catch(()=>{}),()=>{y=!0}},[a]);const u=i.useCallback(async()=>{l(!0),d(null);try{const y=await hN();s({binary:y.binary,expectedVersion:y.expectedVersion,state:y.state,install:y.install}),y.installResult.success||d(y.installResult.permissionsHint||y.installResult.stderr||`Install failed (exit ${y.installResult.exitCode??"n/a"})`)}catch(y){d(y instanceof Error?y.message:String(y))}finally{l(!1)}},[]),m=i.useCallback(()=>{lF(),r(!0)},[]);if(a||!n||n.state==="installed"||n.state==="skipped")return null;const h=n.state==="version-mismatch",f=n.binary.version,p=n.expectedVersion,g=h?"Update the Fusion CLI":"Install the Fusion CLI",w=h?t.jsxs(t.Fragment,{children:["Your installed ",t.jsx("code",{children:"fn"}),"/",t.jsx("code",{children:"fusion"})," CLI is"," ",t.jsxs("strong",{children:["v",f??"unknown"]})," but this dashboard expects"," ",t.jsxs("strong",{children:["v",p]}),". Update to stay in sync."]}):t.jsxs(t.Fragment,{children:["Get the ",t.jsx("code",{children:"fn"})," and ",t.jsx("code",{children:"fusion"})," commands on your terminal so you can drive Fusion from anywhere. One click below or copy the command into your shell."]}),v=h?"Update with npm":"Install with npm",b=h?"Updating…":"Installing…";return t.jsxs("div",{className:"cli-binary-banner",role:"status",children:[t.jsxs("div",{className:"cli-binary-banner__body",children:[t.jsx("div",{className:"cli-binary-banner__title",children:g}),t.jsx("div",{className:"cli-binary-banner__text",children:w}),t.jsxs("div",{className:"cli-binary-banner__actions",children:[t.jsx("button",{type:"button",className:"cli-binary-banner__primary",onClick:()=>void u(),disabled:o,children:o?b:v}),t.jsx("button",{type:"button",className:"cli-binary-banner__secondary",onClick:e,children:"Open Settings"})]}),c&&t.jsx("div",{className:"cli-binary-banner__error",children:c})]}),t.jsx("button",{type:"button",className:"cli-binary-banner__dismiss","aria-label":"Dismiss",onClick:m,children:t.jsx(mn,{size:16})})]})}const dF={duplicate_active_id:"Duplicate active task ID",id_in_active_and_archived:"Task ID present in active and archived storage",next_sequence_at_or_below_used:"Allocator next sequence overlaps an existing task ID",task_row_outside_known_prefix:"Task row uses a prefix outside allocator state"};function uF(e){return e.length<=5?e.join(", "):`${e.slice(0,5).join(", ")} +${e.length-5} more`}function mF({report:e,recommendedAction:n,onRefresh:s}){const[a,r]=i.useState(!1),[o,l]=i.useState(null);if(e.status!=="anomaly")return null;const c=async()=>{r(!0),l(null);try{const d=await Lj();s?.(d.taskIdIntegrity,d.taskIdIntegrity.recommendedAction)}catch(d){l(d instanceof Error?d.message:"Failed to refresh integrity status.")}finally{r(!1)}};return t.jsxs("section",{className:"task-id-integrity-banner",role:"alert","aria-live":"assertive",children:[t.jsxs("div",{className:"task-id-integrity-banner__header",children:[t.jsxs("div",{className:"task-id-integrity-banner__headline-wrap",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx(zr,{"aria-hidden":"true"}),t.jsx("h2",{className:"task-id-integrity-banner__headline",children:"Task ID integrity anomaly detected"})]}),t.jsxs("button",{type:"button",className:"btn btn-sm task-id-integrity-banner__refresh",onClick:()=>{c()},disabled:a,children:[t.jsx(ps,{className:a?"task-id-integrity-banner__refresh-icon task-id-integrity-banner__refresh-icon--spinning":"task-id-integrity-banner__refresh-icon","aria-hidden":"true"}),a?"Re-checking…":"Re-check"]})]}),t.jsx("p",{className:"task-id-integrity-banner__body",children:"Fusion found allocator state that can cause task IDs to be reused or overwrite live task records."}),t.jsx("ul",{className:"task-id-integrity-banner__list",children:e.anomalies.map(d=>t.jsxs("li",{className:"task-id-integrity-banner__item",children:[t.jsx("strong",{className:"task-id-integrity-banner__item-title",children:dF[d.kind]}),t.jsx("span",{className:"task-id-integrity-banner__item-detail",children:d.details}),t.jsx("code",{className:"task-id-integrity-banner__ids",children:uF(d.affectedIds)})]},`${d.kind}:${d.prefix}:${d.affectedIds.join(",")}`))}),t.jsx("p",{className:"task-id-integrity-banner__footer",children:n}),o?t.jsx("p",{className:"task-id-integrity-banner__error",children:o}):null]})}function hF({latestVersion:e,currentVersion:n,onDismiss:s}){return t.jsxs("div",{className:"update-available-banner",role:"status","aria-live":"polite",children:[t.jsxs("p",{className:"update-available-banner__text",children:["Update available: v",e," (current: v",n,"). Run ",t.jsx("code",{children:"fn update"})," for an installed CLI, or pull this source checkout."," ",t.jsx("a",{className:"update-available-banner__link",href:"https://github.com/Runfusion/Fusion/blob/main/CHANGELOG.md",target:"_blank",rel:"noreferrer",children:"Release notes"})," ","·"," ",t.jsx("a",{className:"update-available-banner__link",href:"https://runfusion.ai",target:"_blank",rel:"noreferrer",children:"Learn more"})]}),t.jsx("button",{type:"button",className:"update-available-banner__dismiss touch-target","aria-label":"Dismiss update notice",onClick:s,children:t.jsx(mn,{size:16,"aria-hidden":"true"})})]})}function pF({pendingCount:e,onOpenMailbox:n,onDismiss:s}){const a=e===1?"request":"requests";return t.jsx("section",{className:"approval-notification-banner",role:"region","aria-live":"polite","aria-label":"Approval requests",children:t.jsxs("div",{className:"approval-notification-banner__content",children:[t.jsxs("div",{className:"approval-notification-banner__headline",children:[t.jsx("span",{className:"status-dot","aria-hidden":"true"}),t.jsx(zr,{"aria-hidden":"true"}),t.jsxs("span",{children:[e," approval ",a," need your attention"]})]}),t.jsxs("div",{className:"approval-notification-banner__actions",children:[t.jsxs("button",{type:"button",className:"btn btn-sm",onClick:n,children:[t.jsx(ma,{"aria-hidden":"true"}),t.jsx("span",{children:"Open Mailbox"})]}),t.jsx("button",{type:"button",className:"btn-icon approval-notification-banner__dismiss",onClick:s,"aria-label":"Dismiss approval notification banner",children:t.jsx(mn,{"aria-hidden":"true"})})]})]})})}function fF({onResume:e}){const n=hO();if(!n)return null;const s=n.completedSteps.length,a=ua.length,r=s>0?`${s} of ${a} step${s!==1?"s":""} complete — You're on the `:"You're on the ";return t.jsxs("section",{className:"onboarding-resume-card",role:"region","aria-label":"Resume onboarding",children:[t.jsxs("div",{className:"onboarding-resume-card__main",children:[t.jsx("div",{className:"onboarding-resume-card__icon","aria-hidden":"true",children:t.jsx(ms,{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:()=>{pi("onboarding:resumed",{source:"resume-card",resumedFromStep:n.currentStep}),e()},children:[t.jsx(os,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Continue onboarding"})]})})]})}function gF({onOpenSettings:e,onOpenModelOnboarding:n}){const s=Lr(),a=Uv(),[r,o]=i.useState(!0),[l,c]=i.useState(!1),[d,u]=i.useState(!1),[m,h]=i.useState({needsAiProvider:!1,needsDefaultModel:!1,needsGitHub:!1});i.useEffect(()=>{if(!s||a){o(!1);return}let b=!1;return(async()=>{try{o(!0),c(!1);const[S,j]=await Promise.all([Po(),na()]);if(b)return;const C=S.providers??[],x=C.find(_=>_.id==="github"),R=!C.some(_=>_.id!=="github"&&_.authenticated),F=!j.defaultProvider&&!j.defaultModelId,E=x?!x.authenticated:!1;h({needsAiProvider:R,needsDefaultModel:F,needsGitHub:E})}catch{b||c(!0)}finally{b||o(!1)}})(),()=>{b=!0}},[s,a]);const f=i.useCallback(()=>{uO(),u(!0)},[]),p=i.useCallback(()=>{n()},[n]),g=i.useCallback(()=>{e("global-models")},[e]),w=i.useCallback(()=>{e("authentication")},[e]),v=i.useMemo(()=>{const b=[];return m.needsAiProvider&&b.push({id:"ai-provider",title:"Connect AI Provider",description:"Connect an AI provider to enable AI agents for task planning and code generation",actionLabel:"Set Up AI",onAction:p,icon:ls}),m.needsDefaultModel&&b.push({id:"default-model",title:"Select Default Model",description:"Choose a default AI model for task execution",actionLabel:"Choose Model",onAction:g,icon:ib}),m.needsGitHub&&b.push({id:"github",title:"Connect GitHub",description:"Connect GitHub to import issues and track pull requests",actionLabel:"Connect GitHub",onAction:w,icon:ii}),b},[m.needsAiProvider,m.needsDefaultModel,m.needsGitHub,w,g,p]);return!s||a||d||r||l||v.length===0?null:t.jsxs("section",{className:"post-onboarding-recommendations",role:"region","aria-label":"Setup recommendations",children:[t.jsxs("div",{className:"post-onboarding-recommendations__main",children:[t.jsx("div",{className:"post-onboarding-recommendations__icon","aria-hidden":"true",children:t.jsx(Oi,{size:18,"aria-hidden":!0})}),t.jsxs("div",{className:"post-onboarding-recommendations__content",children:[t.jsx("h2",{className:"post-onboarding-recommendations__title",children:"Recommended Next Steps"}),t.jsx("p",{className:"post-onboarding-recommendations__description",children:"Complete these setup items to get the most out of Fusion."}),t.jsx("ul",{className:"post-onboarding-recommendations__list",children:v.map(b=>{const y=b.icon;return t.jsxs("li",{className:"post-onboarding-recommendations__item",children:[t.jsx("span",{className:"post-onboarding-recommendations__item-icon","aria-hidden":"true",children:t.jsx(y,{size:14,"aria-hidden":!0})}),t.jsxs("span",{className:"post-onboarding-recommendations__item-text",children:[t.jsx("strong",{children:b.title}),t.jsx("span",{children:b.description})]}),t.jsx("button",{type:"button",className:"btn btn-sm btn-primary",onClick:b.onAction,children:b.actionLabel})]},b.id)})}),t.jsx(pa,{slotId:"post-onboarding-recommendation",renderPlaceholder:!1,actions:{openSettingsSection:e,openModelOnboarding:n}})]})]}),t.jsx("button",{type:"button",className:"post-onboarding-recommendations__dismiss",onClick:f,"aria-label":"Dismiss recommendations",children:t.jsx(mn,{size:16,"aria-hidden":!0})})]})}function bF({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 po(e){return e>99?"99+":String(e)}function xF({view:e,onChangeView:n,footerVisible:s,modalOpen:a=!1,keyboardOpen:r=!1,onOpenSettings:o,onOpenActivityLog:l,onOpenSystemStats:c,onOpenMailbox:d,mailboxUnreadCount:u=0,mailboxPendingApprovalCount:m=0,chatHasUnreadResponse:h=!1,stashOrphanCount:f=0,onOpenGitManager:p,onOpenWorkflowSteps:g,onOpenSchedules:w,onOpenScripts:v,onToggleTerminal:b,onOpenFiles:y,onOpenTodos:S,todosOpen:j=!1,onOpenGitHubImport:C,onOpenPlanning:x,onResumePlanning:N,activePlanningSessionCount:R=0,onOpenUsage:F,onRunScript:E,projectId:_,onViewAllProjects:K,showSkillsTab:U,experimentalFeatures:A,onOpenNodes:T,pluginDashboardViews:H=[],shellConnectionControl:Q}){const se=oi(),[O,M]=i.useState(!1),[D,$]=i.useState(!1),[k,X]=i.useState({}),[le,ke]=i.useState(!1),He=i.useMemo(()=>Object.entries(k).sort(([ae],[Ve])=>ae.localeCompare(Ve)),[k]);i.useEffect(()=>{if(!D)return;let ae=!1;return ke(!0),$o(_).then(Ve=>{ae||X(Ve)}).catch(()=>{ae||X({})}).finally(()=>{ae||ke(!1)}),()=>{ae=!0}},[D,_]);const ye=i.useCallback(()=>M(!1),[]),je=i.useCallback(ae=>{ye(),ae?.()},[ye]);if(i.useEffect(()=>{if(!O)return;const ae=Ve=>{Ve.key==="Escape"&&M(!1)};return document.addEventListener("keydown",ae),()=>document.removeEventListener("keydown",ae)},[O]),se!=="mobile"||a||r)return null;const ne=R>0&&N?N:x,fe=!!U,Z=!!A?.todoView,re=fe,q=fe&&!re,he=H.filter(ae=>ae.view.placement==="primary").sort((ae,Ve)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(Ve.view.order??Number.MAX_SAFE_INTEGER)).slice(0,1),B=new Set(he.map(ae=>`${ae.pluginId}:${ae.view.viewId}`)),pe=H.filter(ae=>!B.has(`${ae.pluginId}:${ae.view.viewId}`)).sort((ae,Ve)=>(ae.view.order??Number.MAX_SAFE_INTEGER)-(Ve.view.order??Number.MAX_SAFE_INTEGER)),ze=e==="documents"||!!A?.evalsView&&e==="evals"||e==="research"||e==="insights"||e==="memory"||e==="devserver"||e==="dev-server"||j&&Z||e==="skills"&&!re||e==="graph"||e==="stash-recovery"||wr(e)&&!he.some(ae=>Eo(ae.pluginId,ae.view.viewId)===e);return t.jsxs(t.Fragment,{children:[t.jsxs("nav",{className:`mobile-nav-bar${s?" mobile-nav-bar--with-footer":""}`,role:"tablist","aria-label":"Primary navigation",children:[t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="board"||e==="list"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-tasks",role:"tab","aria-selected":e==="board"||e==="list",onClick:()=>{n(e==="board"||e==="list"?e:"board")},children:[t.jsx(va,{}),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(Qn,{}),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(Es,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Missions"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="chat"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-chat",role:"tab","aria-selected":e==="chat",onClick:()=>n("chat"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(Zi,{}),h&&e!=="chat"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Unread chat response"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Chat"})]}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${e==="mailbox"?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-mailbox",role:"tab","aria-selected":e==="mailbox",onClick:()=>n("mailbox"),children:[t.jsxs("span",{className:"mobile-nav-tab-icon-wrapper",children:[t.jsx(za,{}),m>0&&e!=="mailbox"&&t.jsx("span",{className:"status-dot status-dot--pending mobile-nav-chat-unread-dot","aria-label":"Pending approvals"})]}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-nav-tab-badge",children:po(u)})]}),re&&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(ls,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"Skills"})]}),he.map(ae=>{const Ve=Eo(ae.pluginId,ae.view.viewId),Te=Ql(ae.view.icon);return t.jsxs("button",{type:"button",className:`mobile-nav-tab${e===Ve||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?" mobile-nav-tab--active":""}`,"data-testid":`mobile-nav-tab-plugin-${ae.pluginId}-${ae.view.viewId}`,role:"tab","aria-selected":e===Ve||e==="graph"&&ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph",onClick:()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":Ve),children:[t.jsx(Te,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsxs("button",{type:"button",className:`mobile-nav-tab${ze?" mobile-nav-tab--active":""}`,"data-testid":"mobile-nav-tab-more",role:"tab","aria-selected":!1,onClick:()=>M(ae=>!ae),children:[t.jsx(nu,{}),t.jsx("span",{className:"mobile-nav-tab-label",children:"More"})]})]}),O&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"mobile-more-sheet-backdrop",onClick:ye}),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"}),Q?t.jsx("div",{className:"mobile-more-shell-connection","data-testid":"mobile-more-shell-connection",children:Q}):null,t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-mailbox",onClick:()=>je(d),children:[t.jsx(za,{}),t.jsx("span",{children:"Mailbox"}),u>0&&t.jsx("span",{className:"mobile-more-item-badge mobile-more-item-badge--unread",children:po(u)}),m>0&&t.jsx("span",{className:"mobile-more-item-badge",children:po(m)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-activity",onClick:()=>je(l),children:[t.jsx(Js,{}),t.jsx("span",{children:"Activity Log"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-system-stats",onClick:()=>je(c),children:[t.jsx(Cr,{}),t.jsx("span",{children:"System Stats"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-git",onClick:()=>je(p),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:()=>je(b),children:[t.jsx(ea,{}),t.jsx("span",{children:"Terminal"})]}),t.jsx("button",{type:"button",className:"mobile-more-split-toggle","data-testid":"mobile-more-terminal-split-toggle",onClick:()=>$(ae=>!ae),"aria-expanded":D,"aria-haspopup":"menu","aria-label":"Show scripts",children:t.jsx(qn,{size:14,className:`mobile-more-chevron${D?" mobile-more-chevron--open":""}`})})]}),D&&t.jsx("div",{className:"mobile-more-submenu",role:"menu","aria-label":"Scripts submenu",children:le?t.jsxs("div",{className:"mobile-more-submenu-loading","data-testid":"mobile-more-scripts-loading",children:[t.jsx(jt,{className:"animate-spin"}),t.jsx("span",{children:"Loading scripts…"})]}):He.length>0?t.jsxs(t.Fragment,{children:[He.map(([ae,Ve])=>t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":`mobile-more-script-item-${ae}`,onClick:()=>{E&&E(ae,Ve),ye(),$(!1)},children:[t.jsx(os,{}),t.jsx("span",{children:ae})]},ae)),v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem mobile-more-subitem--manage","data-testid":"mobile-more-scripts-manage",onClick:()=>{ye(),$(!1),v()},children:[t.jsx(Si,{}),t.jsx("span",{children:"Manage Scripts…"})]})]}):v&&t.jsxs("button",{type:"button",className:"mobile-more-item mobile-more-subitem","data-testid":"mobile-more-scripts-manage",onClick:()=>{ye(),$(!1),v()},children:[t.jsx(Si,{}),t.jsx("span",{children:"No scripts — add one…"})]})}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-files",onClick:()=>je(y),children:[t.jsx(js,{}),t.jsx("span",{children:"Files"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-planning",onClick:()=>je(ne),children:[t.jsx(Oi,{}),t.jsx("span",{children:"Planning"}),R>0&&t.jsx("span",{className:"mobile-more-item-badge",children:po(R)})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-workflow",onClick:()=>je(g),children:[t.jsx(Wl,{}),t.jsx("span",{children:"Workflow Steps"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-schedules",onClick:()=>je(w),children:[t.jsx(ta,{}),t.jsx("span",{children:"Automation"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-github",onClick:()=>je(C),children:[t.jsx(bF,{}),t.jsx("span",{children:"Import from GitHub"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-usage",onClick:()=>je(F),children:[t.jsx(Js,{}),t.jsx("span",{children:"Usage"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-projects",onClick:()=>je(K),children:[t.jsx(bc,{}),t.jsx("span",{children:"Projects"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-documents",onClick:()=>je(()=>n("documents")),children:[t.jsx(xa,{}),t.jsx("span",{children:"Documents"})]}),A?.evalsView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-evals",onClick:()=>je(()=>n("evals")),children:[t.jsx(Es,{}),t.jsx("span",{children:"Evals"})]}),q&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-skills",onClick:()=>je(()=>n("skills")),children:[t.jsx(ls,{}),t.jsx("span",{children:"Skills"})]}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-stash-recovery",onClick:()=>je(()=>n("stash-recovery")),children:[t.jsx(Oa,{}),t.jsx("span",{children:"Stash Recovery"}),f>0?t.jsx("span",{className:"mobile-more-item-badge",children:po(f)}):null]}),A?.researchView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-research",onClick:()=>je(()=>n("research")),children:[t.jsx(Xi,{}),t.jsx("span",{children:"Research"})]}),A?.insights&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-insights",onClick:()=>je(()=>n("insights")),children:[t.jsx(ms,{}),t.jsx("span",{children:"Insights"})]}),A?.memoryView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-memory",onClick:()=>je(()=>n("memory")),children:[t.jsx(Io,{}),t.jsx("span",{children:"Memory"})]}),A?.devServerView&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-dev-server",onClick:()=>{je(()=>n("dev-server"))},children:[t.jsx(Cr,{}),t.jsx("span",{children:"Dev Server"})]}),A?.nodesView&&T&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-nodes",onClick:()=>je(T),children:[t.jsx(jk,{}),t.jsx("span",{children:"Nodes"})]}),Z&&t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-todos",onClick:()=>je(()=>S?.()),children:[t.jsx(Bu,{}),t.jsx("span",{children:"Todos"})]}),pe.map(ae=>{const Ve=Eo(ae.pluginId,ae.view.viewId),Te=Ql(ae.view.icon);return t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":`mobile-more-item-plugin-${ae.pluginId}-${ae.view.viewId}`,onClick:()=>je(()=>n(ae.pluginId==="fusion-plugin-dependency-graph"&&ae.view.viewId==="graph"?"graph":Ve)),children:[t.jsx(Te,{}),t.jsx("span",{children:ae.view.label})]},`${ae.pluginId}:${ae.view.viewId}`)}),t.jsx("div",{className:"mobile-more-separator"}),t.jsxs("button",{type:"button",className:"mobile-more-item","data-testid":"mobile-more-item-settings",onClick:()=>je(o),children:[t.jsx(Co,{}),t.jsx("span",{children:"Settings"})]})]})]})]})}function yg(e){return e.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Jv(e,n){const s=n.trim();if(!s)return!0;const a=yg(s);return yg(e).includes(a)||e.toLowerCase().includes(s.toLowerCase())}function vF({agents:e,filter:n,highlightedIndex:s,visible:a,onSelect:r,position:o="below",roomMemberIds:l,roomName:c}){const d=i.useMemo(()=>e.filter(g=>Jv(g.name,n)),[e,n]),u=!!l,m=u&&n.trim().length>0,h=i.useMemo(()=>u?d.filter(g=>l?.has(g.id)):d,[d,l,u]),f=i.useMemo(()=>u?d.filter(g=>!l?.has(g.id)):[],[d,l,u]),p=m?[...h,...f]:h;return a?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${o}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":"Agent mention suggestions",children:p.length===0?t.jsx("div",{className:"agent-mention-empty",children:"No agents found"}):t.jsxs(t.Fragment,{children:[u&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:c?`Members of #${c}`:"Room members"}),h.map((g,w)=>t.jsxs("button",{type:"button",className:`agent-mention-item${w===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:v=>v.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":w===s,children:[t.jsx(cc,{agent:g,size:20}),u&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":"Room member"}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)),u&&!m&&f.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:"Type to search other agents"}),u&&m&&f.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:"Other agents"}),f.map((g,w)=>{const v=h.length+w;return t.jsxs("button",{type:"button",className:`agent-mention-item${v===s?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${g.id}`,onMouseDown:b=>b.preventDefault(),onClick:()=>r(g),role:"option","aria-selected":v===s,children:[t.jsx(cc,{agent:g,size:20}),t.jsx("span",{className:"agent-mention-name",children:g.name}),t.jsx("span",{className:"agent-mention-role",children:g.role})]},g.id)})]})]})}):null}function wg(e){const{sessionId:n,tempUserMessageId:s,setStreamingText:a,setStreamingThinking:r,setStreamingToolCalls:o,cancelStreamingFlushesRef:l,addToast:c,onDone:d,onError:u,onFallbackSession:m}=e;let h="",f="",p=[],g,w=null,v=null;const b=()=>{w=null,a(h)},y=()=>{v=null,r(f)},S=()=>{w!==null&&(cancelAnimationFrame(w),w=null),v!==null&&(cancelAnimationFrame(v),v=null)};return l.current=S,{handlers:{onThinking:C=>{f+=C,v===null&&(v=requestAnimationFrame(y))},onText:C=>{h+=C,w===null&&(w=requestAnimationFrame(b))},onToolStart:C=>{p=[...p,{toolName:C.toolName,args:C.args,isError:!1,status:"running"}],o(p)},onToolEnd:C=>{const x=[...p];for(let N=x.length-1;N>=0;N--){const R=x[N];if(R?.toolName===C.toolName&&R.status==="running"){x[N]={...R,status:"completed",isError:C.isError,result:C.result},p=x,o(x);return}}p=[...x,{toolName:C.toolName,isError:C.isError,result:C.result,status:"completed"}],o(p)},onFallback:C=>{g=C,m?.(C,n),c?.(`Primary model unavailable. Switched to fallback ${C.fallbackModel}.`,"warning")},onDone:C=>{S(),d({messageId:C.messageId,message:C.message,accumulated:{text:h,thinking:f,toolCalls:p,fallbackInfo:g}})},onError:C=>{S(),u(C,s)}},cancelFlushes:S}}const yF=["load failed","failed to fetch","networkerror when attempting to fetch resource.","connection aborted","connection closed unexpectedly","network error"];function wF(e){const n=e.trim().toLowerCase();return n?yF.some(s=>n.includes(s)):!1}function kF(){const e=i.useRef(null),n=i.useRef(null);i.useEffect(()=>{if(typeof document>"u")return;const r=()=>{const o=Date.now();if(document.visibilityState==="hidden"){e.current=o;return}document.visibilityState==="visible"&&(n.current=o)};return r(),document.addEventListener("visibilitychange",r),()=>document.removeEventListener("visibilitychange",r)},[]);const s=i.useCallback(()=>typeof document<"u"&&document.visibilityState==="hidden",[]),a=i.useCallback((r=5e3)=>{const o=e.current;if(o===null)return!1;const l=Date.now();if(s())return l-o<=r;const c=n.current;return c===null||c<o?!1:l-c<=r},[s]);return i.useMemo(()=>({isHiddenNow:s,wasRecentlyHidden:a}),[s,a])}const yr="__fn_agent__";function Yv(e,n){const s=typeof e=="string"?e.trim():"",a=typeof n=="string"?n.trim():"";return!s||!a?{}:{modelProvider:s,modelId:a}}function Ll(e,n,s){const a=typeof e=="string"?e.trim():"",r=Yv(n,s),o=a||(r.modelProvider&&r.modelId?yr:"");return o?{agentId:o,...r}:null}function Ol(e,n,s){const a=Yv(n,s),r=a.modelProvider??"",o=a.modelId??"";return`${e}::${r}/${o}`}function kg(e){const n=typeof e=="string"?e.trim():"",s=n.indexOf("/");return!n||s<=0||s>=n.length-1?{}:{modelProvider:n.slice(0,s),modelId:n.slice(s+1)}}function jF(e){const n=e?.toolCalls;if(!Array.isArray(n))return;const s=n.map(a=>{if(!a||typeof a!="object")return null;const r=a,o=typeof r.toolName=="string"?r.toolName:"";if(!o)return null;const l=r.args;return{toolName:o,...l&&typeof l=="object"?{args:l}:{},isError:!!r.isError,result:r.result,status:"completed"}}).filter(a=>a!==null);return s.length>0?s:void 0}function NF(e){const n=e?.fallback;if(!n||typeof n!="object")return;const s=n,a=typeof s.primaryModel=="string"?s.primaryModel:"",r=typeof s.fallbackModel=="string"?s.fallbackModel:"",o=s.triggerPoint;if(!(!a||!r||o!=="session-creation"&&o!=="prompt-time"))return{primaryModel:a,fallbackModel:r,triggerPoint:o}}function fr(e){return{id:e.id,sessionId:e.sessionId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput,toolCalls:jF(e.metadata),fallbackInfo:NF(e.metadata),createdAt:e.createdAt}}function SF(e,n){const[s,a]=i.useState(null),[r,o]=i.useState([]),[l,c]=i.useState(!1),[d,u]=i.useState([]),[m,h]=i.useState(!1),[f,p]=i.useState(!1),[g,w]=i.useState(""),[v,b]=i.useState(""),[y,S]=i.useState([]),[j,C]=i.useState(""),x=i.useRef(null),N=i.useRef(!1),R=i.useRef(null),F=i.useRef(""),E=i.useRef(f);E.current=f;const _=i.useRef(null),K=i.useRef(""),U=i.useRef(null),A=i.useRef(s);A.current=s;const T=i.useRef(0),H=3,Q=i.useRef(!1);i.useEffect(()=>{F.current=j},[j]);const se=i.useCallback(async()=>{c(!0);try{const q=await uh(e);o(q.sessions)}catch(q){console.error("[useQuickChat] Failed to refresh sessions:",q)}finally{c(!1)}},[e]),O=i.useCallback(async q=>{const L={agentId:q.agentId};return q.modelProvider&&q.modelId&&(L.modelProvider=q.modelProvider,L.modelId=q.modelId),(await V0(L,e)).session},[e]),M=i.useCallback((q,L)=>{if(x.current||!q)return!0;N.current=!1,L&&(w(L.streamingText),b(L.streamingThinking),S(L.toolCalls)),p(!0);const{handlers:xe}=wg({sessionId:q,tempUserMessageId:"",setStreamingText:w,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(he,B)=>{const pe=kg(he.fallbackModel);o(ze=>ze.map(ae=>ae.id===B?{...ae,...pe}:ae)),a(ze=>ze&&ze.id===B?{...ze,...pe}:ze)},onDone:()=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,Zr(q,{limit:50},e).then(he=>{u(he.messages.map(fr))}).catch(()=>{})},onError:he=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null;const B=typeof he=="string"&&he.trim()?he:"Failed to get response";n?.(B,"error"),Zr(q,{limit:50},e).then(pe=>{u(pe.messages.map(fr))}).catch(()=>{})}});return x.current=Y0(q,xe,e,{...typeof L?.replayFromEventId=="number"?{lastEventId:L.replayFromEventId}:{}}),!0},[n,e]),D=i.useCallback(async(q,L,xe)=>{const he=Ll(q,L,xe);if(!he)return;const B=Ol(he.agentId,he.modelProvider,he.modelId);c(!0);try{const{session:pe}=await q0({agentId:he.agentId,modelProvider:he.modelProvider,modelId:he.modelId},e);if(pe)a(pe),K.current=B,pe.isGenerating&&M(pe.id,pe.inFlightGeneration);else{const ze=await O(he);a(ze),K.current=B}T.current=0}catch(pe){console.error("[useQuickChat] Failed to initialize session:",pe),T.current+=1,T.current<=H&&n?.("Failed to initialize chat","error")}finally{c(!1)}},[M,e,n,O]),$=i.useCallback(async()=>{if(s){h(!0);try{const q=await Zr(s.id,{limit:50},e);u(q.messages.map(fr))}catch(q){console.error("[useQuickChat] Failed to load messages:",q)}finally{h(!1)}}},[s,e]);i.useEffect(()=>{s?$():u([])},[s,$]),i.useEffect(()=>{if(!s?.isGenerating||(x.current||M(s.id,s.inFlightGeneration),!E.current||x.current||!s))return;const q=setInterval(async()=>{if(!E.current||x.current||!s){clearInterval(q);return}try{if(!(await W0(s.id,e)).session.isGenerating){clearInterval(q);const xe=await Zr(s.id,{limit:50},e);u(xe.messages.map(fr)),w(""),b(""),S([]),p(!1)}}catch{}},3e3);return()=>clearInterval(q)},[s,M,e]);const k=i.useCallback(async()=>{if(s){h(!0);try{const q=await Zr(s.id,{limit:50},e);u(q.messages.map(fr))}catch(q){console.error("[useQuickChat] Failed to reload messages:",q)}finally{h(!1)}}},[s,e]),X=i.useCallback(()=>{R.current?.(),R.current=null,F.current="",C(""),w(""),b(""),S([]),p(!1)},[]),le=i.useCallback(async(q,L,xe)=>{const he=Ll(q,L,xe);if(!he)return;const B=Ol(he.agentId,he.modelProvider,he.modelId);U.current=he;const pe=B===K.current&&A.current;if(pe||(x.current&&(x.current.close(),x.current=null),X()),pe){await k();return}a(null),u([]),K.current=B,await D(he.agentId,he.modelProvider,he.modelId)},[D,k,X]),ke=i.useCallback(async q=>{const L=Ll(q.agentId,q.modelProvider??void 0,q.modelId??void 0);L&&(U.current=L,K.current=Ol(L.agentId,L.modelProvider,L.modelId),x.current&&(x.current.close(),x.current=null),X(),a(q),q.isGenerating&&M(q.id,q.inFlightGeneration))},[M,X]),He=i.useCallback(async(q,L)=>{await le(yr,q,L)},[le]),ye=i.useCallback(async(q,L,xe)=>{const B=Ll(q??"",L,xe)??U.current;if(!B)return;U.current=B;const pe=Ol(B.agentId,B.modelProvider,B.modelId);Q.current=!0,T.current=0,x.current&&(x.current.close(),x.current=null),X(),u([]),a(null),c(!0);try{const ze=await O(B);a(ze),K.current=pe;const ae=await uh(e);o(ae.sessions)}catch(ze){console.error("[useQuickChat] Failed to start a fresh session:",ze),n?.("Failed to start a new chat","error")}finally{Q.current=!1,c(!1)}},[n,O,e,X]),je=i.useCallback(()=>{s&&(N.current=!0,R.current?.(),R.current=null,x.current?.close(),x.current=null,G0(s.id,e).catch(()=>{}),p(!1),w(""),b(""),S([]))},[s,e]),ne=i.useCallback(()=>{F.current="",C("")},[]),fe=i.useRef(()=>Promise.resolve()),Z=kF(),re=i.useCallback((q,L)=>{if(!s||!q.trim()&&(!L||L.length===0))return Promise.resolve();if(E.current)return L&&L.length>0?Promise.reject(new Error("Cannot send attachments while a response is streaming")):(F.current=q,C(q),Promise.resolve());const xe=new Promise((he,B)=>{_.current={resolve:he,reject:B},N.current=!1,x.current&&(x.current.close(),x.current=null);const pe=`temp-${Date.now()}`,ze={id:pe,sessionId:s.id,role:"user",content:q,createdAt:new Date().toISOString()};u(Ve=>[...Ve,ze]),w(""),b(""),S([]),p(!0);const{handlers:ae}=wg({sessionId:s.id,tempUserMessageId:pe,setStreamingText:w,setStreamingThinking:b,setStreamingToolCalls:S,cancelStreamingFlushesRef:R,addToast:n,onFallbackSession:(Ve,Te)=>{const rt=kg(Ve.fallbackModel);o(Be=>Be.map(ce=>ce.id===Te?{...ce,...rt}:ce)),a(Be=>Be&&Be.id===Te?{...Be,...rt}:Be)},onDone:({messageId:Ve,message:Te,accumulated:rt})=>{const Be=Te?fr(Te):{id:Ve||`msg-${Date.now()}`,sessionId:s.id,role:"assistant",content:rt.text,thinkingOutput:rt.thinking||void 0,toolCalls:rt.toolCalls.length>0?rt.toolCalls:void 0,fallbackInfo:rt.fallbackInfo,createdAt:new Date().toISOString()};u(Re=>[...Re,Be]),w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,_.current?.resolve(),_.current=null;const ce=F.current.trim();ce&&(F.current="",C(""),fe.current(ce))},onError:Ve=>{w(""),b(""),S([]),p(!1),E.current=!1,x.current=null,console.error("[useQuickChat] Stream error:",Ve);const Te=typeof Ve=="string"&&Ve.trim()?Ve:"Failed to get response";if(typeof Ve=="string"&&wF(Ve)&&(Z.isHiddenNow()||Z.wasRecentlyHidden(5e3))?(console.info("[useQuickChat] Suppressed tab-suspension stream error:",Ve),_.current?.resolve()):(n?.(Te,"error"),_.current?.reject(new Error(Te))),_.current=null,!N.current){const Be=F.current.trim();Be&&(F.current="",C(""),fe.current(Be))}k()}});x.current=J0(s.id,q,ae,L,e)});return xe.catch(()=>{}),xe},[s,e,n,k,Z]);return fe.current=re,i.useEffect(()=>()=>{x.current&&(x.current.close(),x.current=null)},[]),i.useMemo(()=>({activeSession:s,sessions:r,sessionsLoading:l,messages:d,messagesLoading:m,isStreaming:f,streamingText:g,streamingThinking:v,streamingToolCalls:y,pendingMessage:j,sendMessage:re,stopStreaming:je,clearPendingMessage:ne,switchSession:le,selectSession:ke,startModelChat:He,startFreshSession:ye,refreshSessions:se,loadMessages:$,reloadMessages:k,skipNextSessionInitRef:Q}),[s,r,l,d,m,f,g,v,y,j,re,je,ne,le,ke,He,ye,se,$,k])}function CF(e,n){const[s,a]=i.useState([]),[r,o]=i.useState(null),[l,c]=i.useState(!1),d=i.useCallback(async p=>{c(!0);try{const g=n?.filterState,w=g&&g!=="all"?{state:g}:void 0,v=n?.showSystemAgents??!1,b=await Ur({...w,...p,includeEphemeral:p?.includeEphemeral??v},e),y=Array.from(new Map(b.map(S=>[S.id,S])).values());a(y)}catch(g){console.error("Failed to load agents:",g)}finally{c(!1)}},[e,n?.filterState,n?.showSystemAgents]),u=i.useCallback(async()=>{try{const p=await r1(e);o(p)}catch(p){console.error("Failed to load agent stats:",p)}},[e]);i.useEffect(()=>{d(),u()},[d,u]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=()=>{d(),u()};return yi(`/api/events${p}`,{events:{"agent:created":g,"agent:updated":g,"agent:deleted":g,"agent:stateChanged":g,"approval:requested":g,"approval:updated":g,"approval:decided":g}})},[e,d,u]);const m=i.useCallback(async()=>{await Promise.all([d(),u()])},[d,u]),h=n?.showSystemAgents??!1,f=s.filter(p=>p.state!=="active"&&p.state!=="running"?!1:h||!HC(p));return{agents:s,activeAgents:f,stats:r,isLoading:l,loadAgents:d,loadStats:u,refreshAgents:m}}function EF({visible:e,position:n,files:s,selectedIndex:a,onSelect:r,loading:o}){return e?t.jsxs("div",{className:"file-mention-popup",style:{top:n.top,left:n.left},"data-testid":"file-mention-popup",onMouseDown:l=>{l.preventDefault()},children:[o&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!o&&s.length===0&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:"No files found"}),!o&&s.length>0&&t.jsx("ul",{className:"file-mention-popup-list",role:"listbox",children:s.map((l,c)=>{const d=NC(l.path),u=l.name;return t.jsxs("li",{className:`file-mention-popup-item${c===a?" file-mention-popup-item--selected":""}`,onClick:()=>r(l),onMouseEnter:()=>{},role:"option","aria-selected":c===a,"data-testid":`file-mention-item-${c}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(nb,{size:14})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:u}),d&&t.jsx("span",{className:"file-mention-popup-item-path",children:d})]})]},l.path)})})]}):null}const _F=200;function MF(e={}){const{projectId:n,workspace:s="project"}=e,[a,r]=i.useState(!1),[o,l]=i.useState(""),[c,d]=i.useState(-1),[u,m]=i.useState([]),[h,f]=i.useState(!1),[p,g]=i.useState(0),w=i.useRef(null),v=i.useRef(null);i.useEffect(()=>()=>{w.current&&clearTimeout(w.current),v.current?.abort()},[]);const b=i.useCallback((x,N)=>{if(N<0||N>x.length){r(!1);return}const R=F=>/[a-zA-Z0-9/_.-]/.test(F);for(let F=N-1;F>=0;F--){if(x[F]==="#")if(F===0){const E=x.slice(F+1,N);d(F),l(E),g(0),r(!0);return}else{const E=x[F-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const _=x.slice(F+1,N);d(F),l(_),g(0),r(!0);return}r(!1);return}if(!R(x[F])){r(!1);return}}r(!1)},[]),y=i.useCallback(()=>{r(!1),l(""),d(-1),m([]),g(0),f(!1)},[]),S=i.useCallback(async x=>{if(!x.trim()){m([]),f(!1);return}v.current?.abort(),v.current=new AbortController;try{f(!0);const N=await uS(x,s,n);m(N.files),g(0)}catch(N){N.name!=="AbortError"&&m([])}finally{f(!1)}},[s,n]);i.useEffect(()=>{if(a)return w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{S(o)},_F),()=>{w.current&&clearTimeout(w.current)}},[o,a,S]);const j=i.useCallback((x,N)=>{if(!a||c<0)return N;const R=N.slice(0,c),F=N.slice(c+1),E=F.match(/[\s]|$/),_=E?E.index:F.length,K=F.slice(_);return`${R}#${x.path}${K}`},[a,c]),C=i.useCallback((x,N)=>{if(!a||u.length===0)return!1;switch(x.key){case"ArrowDown":return x.preventDefault(),g(R=>Math.min(R+1,u.length-1)),!0;case"ArrowUp":return x.preventDefault(),g(R=>Math.max(R-1,0)),!0;case"Enter":case"Tab":return u[p]?(x.preventDefault(),!0):!1;case"Escape":return x.preventDefault(),y(),!0;default:return!1}},[a,u,p,y]);return{mentionActive:a,files:u,loading:h,mentionQuery:o,selectedIndex:p,setSelectedIndex:g,detectMention:b,selectFile:j,dismissMention:y,handleKeyDown:C}}function AF(e){return`${e.name?.trim()||e.id} (${e.role})`}function fo(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 RF(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 Hl(e,n){return e.length<=n?e:`${e.slice(0,n)}…`}function IF(e){if(!e)return null;const n=Object.entries(e);return n.length===0?null:n.map(([s,a])=>{const r=typeof a=="string"?a:(()=>{try{return JSON.stringify(a)}catch{return String(a)}})();return`${s}=${Hl(r,50)}`}).join(", ")}function TF(e){if(e===void 0)return null;if(typeof e=="string")return Hl(e,200);try{return Hl(JSON.stringify(e),200)}catch{return Hl(String(e),200)}}function Qv(e,n=!1){if(!e||e.length===0)return null;const s=(f,p)=>{const g=f.status==="running",w=f.status==="completed"&&f.isError,v=IF(f.args),b=TF(f.result),y=g?v:b?`result: ${b}`:v?`args: ${v}`:null,S=n?null:y,j=g?"running":w?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${g?" chat-tool-call--running":""}${w?" chat-tool-call--error":""}`,open:g,children:[t.jsxs("summary",{children:[t.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),t.jsx("span",{className:"chat-tool-call-name",title:f.toolName,children:f.toolName}),S&&t.jsx("span",{className:"chat-tool-call-preview",title:S,children:S}),t.jsx("span",{className:"chat-tool-call-status-text",children:j})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[v&&t.jsxs("div",{className:"chat-tool-call-row",children:[t.jsx("span",{className:"chat-tool-call-label",children:"args"}),t.jsx("span",{className:"chat-tool-call-value",children:v})]}),b&&t.jsxs("div",{className:`chat-tool-call-row${w?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:b})]})]})]},`${f.toolName}-${p}`)},a=`chat-tool-calls${n?" chat-tool-calls--compact":""}`;if(e.length===1)return t.jsxs("div",{className:a,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Om,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),s(e[0],0)]});const r=e.filter(f=>f.status==="running").length,o=e.filter(f=>f.status==="completed"&&f.isError).length,l=r>0,c=Array.from(new Set(e.map(f=>f.toolName))),d=c.slice(0,5),u=Math.max(0,c.length-d.length),m=u>0?`${d.join(", ")}, +${u} more`:d.join(", "),h=l?`(${r} running)`:o>0?`(${o} ${o===1?"error":"errors"})`:null;return t.jsx("div",{className:a,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:`chat-tool-calls-group${n?" chat-tool-calls-group--compact":""}`,"data-testid":"chat-tool-calls-group",open:l,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Om,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[e.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:m,children:m}),h&&t.jsx("span",{className:"chat-tool-calls-group-status",children:h})]}),e.map((f,p)=>s(f,p))]})})}const Xv={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 jg(e){const n=/(^|[\s])\/([^\s]*)$/.exec(e);if(!n)return null;const s=n[1]??"",a=n[2]??"",r=n.index+s.length;return{filter:a,start:r,end:e.length}}function PF(e,n){const s=e.slice(0,n),a=/(^|[\s])@([\w-]*)$/.exec(s);if(!a)return null;const r=a[2]??"",o=s.length-r.length-1;return{filter:r,start:o,end:n}}const Fl={width:320,height:400},$F=new Set(["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/x-log","text/csv","application/xml","text/markdown"]),DF=[".png",".jpg",".jpeg",".gif",".webp",".txt",".json",".yaml",".yml",".log",".csv",".xml",".md"];function LF(e){return e.type.startsWith("image/")}function OF(e){if($F.has(e.type))return!0;const n=e.name.toLowerCase();return DF.some(s=>n.endsWith(s))}const gr={width:280,height:260},Ls=768,br=8;function FF(e,n){const s=i.useCallback(()=>{if(typeof window>"u")return 0;const j=getComputedStyle(document.documentElement).getPropertyValue("--executor-footer-height").trim();return j&&parseFloat(j)||0},[]),a=i.useCallback(()=>typeof window<"u"&&window.innerWidth<=768?{x:4,y:4+s()}:{x:24,y:24+s()},[s]),[r,o]=i.useState(()=>{if(typeof window>"u")return a();const j=`fusion-quick-chat-position-${e||"default"}`;try{const C=localStorage.getItem(j);if(C){const x=JSON.parse(C);if(typeof x.x=="number"&&typeof x.y=="number"&&!isNaN(x.x)&&!isNaN(x.y))return x}}catch{}return a()}),[l,c]=i.useState(!1),d=i.useRef(null),u=i.useRef(r),m=i.useRef(null),h=i.useRef(null),f=n??i.useRef(!1);i.useEffect(()=>{u.current=r},[r]);const p=i.useCallback(j=>{if(typeof window>"u")return j;const C=48,x=window.innerWidth<=768?4:8,N=window.innerWidth<=768?44:0,R=window.innerWidth>768?s():0,F=window.innerWidth-C-x,E=window.innerHeight-C-x-N-R;return{x:Math.max(x,Math.min(F,j.x)),y:Math.max(x,Math.min(E,j.y))}},[s]),g=i.useCallback(j=>{if(typeof window>"u")return;const C=`fusion-quick-chat-position-${e||"default"}`;try{localStorage.setItem(C,JSON.stringify(j))}catch{}},[e]),w=i.useCallback(()=>{if(!d.current)return;const j=h.current,C=m.current;j&&C!==null&&typeof j.releasePointerCapture=="function"&&j.releasePointerCapture(C),d.current=null,m.current=null,h.current=null,c(!1),document.body.style.userSelect="",f.current&&g(u.current),document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y)},[g]),v=i.useCallback(j=>{if(!d.current||m.current!==null&&j.pointerId!==m.current)return;const C=j.clientX-d.current.pointerX,x=j.clientY-d.current.pointerY;if((Math.abs(C)>=5||Math.abs(x)>=5)&&(f.current=!0),!f.current)return;const N=d.current.x-C,R=d.current.y-x,F=p({x:N,y:R});u.current=F,o(F)},[p]),b=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||w()},[w]),y=i.useCallback(j=>{m.current!==null&&j.pointerId!==m.current||w()},[w]),S=i.useCallback(j=>{if(j.button!==0&&j.pointerType==="mouse")return;const C=j.currentTarget;j.preventDefault(),typeof C.setPointerCapture=="function"&&C.setPointerCapture(j.pointerId);const x=u.current;d.current={x:x.x,y:x.y,pointerX:j.clientX,pointerY:j.clientY},m.current=j.pointerId,h.current=C,f.current=!1,c(!0),document.body.style.userSelect="none",document.addEventListener("pointermove",v,{passive:!0}),document.addEventListener("pointerup",b),document.addEventListener("pointercancel",y)},[y,v,b]);return i.useEffect(()=>()=>{document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b),document.removeEventListener("pointercancel",y),document.body.style.userSelect=""},[y,v,b]),{position:r,isDragging:l,handlePointerDown:S}}function zF(e,n,s){const a=`fusion:quick-chat-size-${e||"default"}`,r=i.useCallback(()=>typeof window<"u"&&window.innerWidth>Ls,[]),o=i.useCallback((f,p,g)=>{if(typeof window>"u")return f;const w=Math.max(gr.width,window.innerWidth-p-br),v=Math.max(gr.height,window.innerHeight-g-br);return{width:Math.max(gr.width,Math.min(w,f.width)),height:Math.max(gr.height,Math.min(v,f.height))}},[]),l=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth<=Ls)return Fl;try{const f=localStorage.getItem(a);if(!f)return Fl;const p=JSON.parse(f);return typeof p.width!="number"||typeof p.height!="number"?Fl:{width:p.width,height:p.height}}catch{return Fl}},[a]),[c,d]=i.useState(l),[u,m]=i.useState({right:0,bottom:0});i.useEffect(()=>{if(!r())return;const f={right:n+u.right,bottom:s+u.bottom};d(p=>o(p,f.right,f.bottom))},[o,r,n,s,u]),i.useEffect(()=>{if(r())try{localStorage.setItem(a,JSON.stringify(c))}catch{}},[r,c,a]);const h=i.useCallback(f=>{if(!r())return;const p=f.currentTarget.dataset.resizeDirection;if(!p)return;f.preventDefault(),f.stopPropagation();const g=f.currentTarget;typeof g.setPointerCapture=="function"&&g.setPointerCapture(f.pointerId);const w={pointerX:f.clientX,pointerY:f.clientY,width:c.width,height:c.height,anchorRight:u.right,anchorBottom:u.bottom};document.body.style.userSelect="none";const v=y=>{const S=y.clientX-w.pointerX,j=y.clientY-w.pointerY;let C=w.width,x=w.height,N=w.anchorRight,R=w.anchorBottom;if(p.includes("w")&&(C=w.width-S),p.includes("e")){const A=S;C=w.width+A,N=w.anchorRight-A}if(p.includes("n")&&(x=w.height-j),p.includes("s")){const A=j;x=w.height+A,R=w.anchorBottom-A}const F=n+N,E=s+R,_=o({width:C,height:x},F,E),K=Math.max(br-n,Math.min(window.innerWidth-n-gr.width-br,N)),U=Math.max(br-s,Math.min(window.innerHeight-s-gr.height-br,R));d(_),m({right:K,bottom:U})},b=y=>{typeof g.releasePointerCapture=="function"&&g.releasePointerCapture(y.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",v),document.removeEventListener("pointerup",b);try{localStorage.setItem(a,JSON.stringify({width:c.width,height:c.height}))}catch{}};document.addEventListener("pointermove",v),document.addEventListener("pointerup",b)},[u.bottom,u.right,o,s,n,r,c.height,c.width,a]);return{panelSize:c,anchorOffset:u,handleResizeStart:h}}const Ng=i.memo(function({message:n,forcePlain:s,mentionAgentsByName:a,roomContext:r,onToggleRender:o}){const l=n.role==="user",c=i.useMemo(()=>{if(!l)return null;const u=n.content,m=/@([\w-]+)/g,h=[];let f=0,p=m.exec(u);for(;p;){const[g,w=""]=p,v=p.index;v>f&&h.push(u.slice(f,v));const b=w.replace(/_/g," ").toLowerCase(),y=a.get(b);if(y){const S=!!(r&&!r.memberIds.has(y.id)),j=S?`Not a member of ${r?.roomName}`:void 0;h.push(t.jsxs("span",{className:`chat-mention-chip${S?" chat-mention-chip--non-member":""}`,title:j,"aria-label":j,children:["@",y.name.replace(/\s+/g,"_")]},`${y.id}-${v}`))}else h.push(g);f=v+g.length,p=m.exec(u)}return f<u.length&&h.push(u.slice(f)),h.length===0?u:h},[l,n.content,a,r]),d=i.useMemo(()=>l?null:s?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:n.content}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(xi,{remarkPlugins:[vi],components:Xv,children:n.content})}),[l,s,n.content]);return t.jsxs("div",{className:`quick-chat-panel-message ${l?"quick-chat-panel-message--sent":"quick-chat-panel-message--received"}`,"data-testid":`quick-chat-message-${n.id}`,children:[l?t.jsx("p",{children:c}):t.jsxs(t.Fragment,{children:[d,t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${s?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":s?"Show rendered markdown":"Show plain text",onClick:()=>o(n.id),children:s?t.jsx(zu,{size:14}):t.jsx(Fr,{size:14})})]}),Qv(n.toolCalls,!0)]})});function BF({projectId:e,addToast:n,showFAB:s=!0,open:a,onOpenChange:r,favoriteProviders:o=[],favoriteModels:l=[],onToggleFavorite:c,onToggleModelFavorite:d,roomContext:u=null}){const{agents:m}=CF(e),[h,f]=i.useState(!1),p=a!==void 0,g=p?a:h,w=p?ie=>{r?.(typeof ie=="function"?ie(g):ie)}:f,{keyboardOpen:v}=aa({enabled:g}),b=oi(),y=b==="mobile",[S,j]=i.useState("agent"),[C,x]=i.useState(""),[N,R]=i.useState(!1),[F,E]=i.useState("model"),[_,K]=i.useState(""),[U,A]=i.useState(""),[T,H]=i.useState([]),[Q,se]=i.useState(!1),[O,M]=i.useState(""),[D,$]=i.useState(""),[k,X]=i.useState(""),[le,ke]=i.useState([]),[He,ye]=i.useState(!1),[je,ne]=i.useState(!1),[fe,Z]=i.useState(""),[re,q]=i.useState(0),[L,xe]=i.useState(""),[he,B]=i.useState(!1),[pe,ze]=i.useState(0),[ae,Ve]=i.useState(-1),[Te,rt]=i.useState(()=>new Set),[Be,ce]=i.useState(!1),[Re,Le]=i.useState([]),[ct,Ue]=i.useState(!1),[ue,oe]=i.useState(!1),[,Ee]=i.useState(!1),[ft,ht]=i.useState({top:0,left:0}),tt=MF({projectId:e}),xt=i.useCallback(ie=>{if(!ie||!tt.mentionActive)return;const $e=ie.getBoundingClientRect();ht({top:$e.top-260,left:$e.left+8})},[tt.mentionActive]),Me=i.useRef(!1),Ye=i.useRef(!1),dt=i.useRef(!1),wt=i.useRef(""),St=i.useRef(!1),Fe=i.useRef(C),J=i.useRef(O),me=i.useRef(0),Ze=i.useRef(null),be=i.useRef(null),gt=i.useRef(0),{position:$t,isDragging:Ie,handlePointerDown:ge}=FF(e,Me),st=$t.y+60,{panelSize:yt,anchorOffset:pt,handleResizeStart:vt}=zF(e,$t.x,st),Ut=typeof window<"u"&&window.innerWidth>Ls,{activeSession:Dt,messages:nn,isStreaming:on,streamingText:sn,streamingThinking:ln,streamingToolCalls:xn,sessions:qt,sessionsLoading:Qt,messagesLoading:hn,sendMessage:Zt,stopStreaming:ve,pendingMessage:Pe,clearPendingMessage:Ke,switchSession:at,selectSession:We,startModelChat:It,startFreshSession:Lt,refreshSessions:Bt,skipNextSessionInitRef:Gt}=SF(e,n),bt=i.useRef(null),Ot=i.useRef(null),en=i.useRef(null),Kt=i.useRef(null),Sn=i.useRef(null),dn=i.useRef([]),Jt=i.useRef(!1),tn=i.useRef(!1),Ne=i.useRef(!1),W=i.useRef(null),Y=i.useRef(!1),_e=i.useRef(!1),ut=i.useRef({isOpen:!1,sessionId:null});i.useEffect(()=>{if(!g||typeof window>"u"||typeof document>"u"||window.innerWidth>Ls)return;const ie=window.scrollY,$e=document.documentElement,Qe=document.body,Ft={htmlOverflow:$e.style.overflow,bodyOverflow:Qe.style.overflow};return window.scrollTo(0,0),$e.style.overflow="hidden",Qe.style.overflow="hidden",()=>{$e.style.overflow=Ft.htmlOverflow,Qe.style.overflow=Ft.bodyOverflow,window.scrollTo(0,ie)}},[g]),i.useLayoutEffect(()=>{if(!g||typeof window>"u"||!window.visualViewport)return;const ie=bt.current;if(!ie)return;const $e=window.visualViewport,Qe=()=>{Y.current||(ie.style.setProperty("--vv-height",`${$e.height}px`),ie.style.setProperty("--vv-offset-top",`${$e.offsetTop||0}px`))};return Qe(),$e.addEventListener("resize",Qe),$e.addEventListener("scroll",Qe),()=>{$e.removeEventListener("resize",Qe),$e.removeEventListener("scroll",Qe)}},[g]);const At=O||D,zt=i.useMemo(()=>fo(At),[At]),yn=i.useMemo(()=>S==="model"&&Dt?.modelProvider&&Dt?.modelId?`${Dt.modelProvider}/${Dt.modelId}`:At,[Dt?.modelId,Dt?.modelProvider,S,At]),Zn=i.useMemo(()=>fo(yn),[yn]),vn=i.useMemo(()=>T.find(ie=>`${ie.provider}/${ie.id}`===yn)??null,[yn,T]),Dn=i.useMemo(()=>RF(vn,Zn),[vn,Zn]),de=i.useMemo(()=>S==="model"?zt?`${yr}::${zt.modelProvider}/${zt.modelId}`:"":C?`${C}::`:"",[S,C,zt]),ot=!(S==="agent"?!!C:!!zt)||!Dt,_t=i.useMemo(()=>!!C&&qt.some(ie=>!ie.modelProvider&&!ie.modelId&&ie.agentId===C),[C,qt]);i.useEffect(()=>{Fe.current=C},[C]),i.useEffect(()=>{J.current=O},[O]),i.useEffect(()=>{if(m.length===0){x(""),j("model");return}if(St.current&&_t)return;m.some($e=>$e.id===C)||x(m[0]?.id??"")},[m,_t,C]),i.useEffect(()=>{!g||Ye.current||(Ye.current=!0,dt.current=!1,se(!0),Ws().then(ie=>{const $e=ie.models??[];if(H($e),J.current||$e.length===0)return;const Qe=ie.defaultProvider,Ft=ie.defaultModelId;if(Qe&&Ft){const pn=`${Qe}/${Ft}`;if($e.some(Un=>`${Un.provider}/${Un.id}`===pn)){$(pn),J.current||M(pn),St.current||j("model");return}}$("");const cn=$e[0];cn&&!J.current&&M(`${cn.provider}/${cn.id}`)}).catch(ie=>{console.error("[QuickChatFAB] Failed to load models:",ie),H([]),$("")}).finally(()=>{dt.current=!0,se(!1)}))},[g,m.length,O]),i.useEffect(()=>{!g||!e||(ye(!0),H0(e).then(ie=>{ke(ie)}).catch(()=>{ke([])}).finally(()=>{ye(!1)}))},[g,e]),i.useEffect(()=>{g&&Bt()},[g,Bt]),i.useEffect(()=>{if(!g||Qt||St.current||qt.length===0)return;const ie=qt[0];ie&&(ie.modelProvider&&ie.modelId?(j("model"),M(`${ie.modelProvider}/${ie.modelId}`)):(j("agent"),x(ie.agentId)),St.current=!0)},[g,qt,Qt]),i.useEffect(()=>{if(!g){wt.current="";return}if(!St.current&&qt.length===0&&Ye.current&&!dt.current)return;if(!de){wt.current="";return}if(Gt.current){wt.current=de;return}const $e=de===wt.current&&!Dt&&!Qt;if(!(de===wt.current&&!$e)){if(wt.current=de,S==="model"&&zt){It(zt.modelProvider,zt.modelId);return}S==="agent"&&C&&at(C)}},[g,S,zt,C,de,Dt,Qt,It,at,Gt]),i.useEffect(()=>{g||(B(!1),xe(""),Ve(-1),ne(!1),Z(""),q(0),dn.current.forEach(ie=>{ie.previewUrl&&URL.revokeObjectURL(ie.previewUrl)}),Le([]))},[g]),i.useEffect(()=>{dn.current=Re},[Re]),i.useEffect(()=>{if(!g){Jt.current=!1;return}typeof window>"u"||(Jt.current=window.innerWidth<=Ls)},[g]),i.useEffect(()=>{if(!g||ot||!Jt.current)return;const ie=Kt.current;if(!ie)return;const $e=document.activeElement,Qe=$e?bt.current?.contains($e):!1,Ft=$e===document.body,cn=$e===W.current;if(!Qe&&!Ft&&!cn){Jt.current=!1;return}if(cn){ie.focus({preventScroll:!0}),Jt.current=!1;return}const pn=requestAnimationFrame(()=>{ie.focus(),Jt.current=!1});return()=>cancelAnimationFrame(pn)},[g,ot]),i.useEffect(()=>()=>{dn.current.forEach(ie=>{ie.previewUrl&&URL.revokeObjectURL(ie.previewUrl)})},[]);const G=i.useCallback(()=>{R(!0),E("model"),K(m[0]?.id??""),A(O||D||"")},[m,D,O]),Oe=i.useMemo(()=>m.find(ie=>ie.id===C)??null,[m,C]),Mt=i.useMemo(()=>{const ie=fe.trim().toLowerCase();return(ie?le.filter(Qe=>Qe.name.toLowerCase().includes(ie)):le).slice(0,10)},[le,fe]),Xt=i.useMemo(()=>{const ie=m.filter(Ft=>Jv(Ft.name,L));if(!u)return ie;const $e=ie.filter(Ft=>u.memberIds.has(Ft.id));if(L.trim().length===0)return $e;const Qe=ie.filter(Ft=>!u.memberIds.has(Ft.id));return[...$e,...Qe]},[m,L,u]),_n=i.useMemo(()=>{const ie=new Map;for(const $e of m)ie.set($e.name.toLowerCase(),$e);return ie},[m]);i.useEffect(()=>{q(0)},[Mt]),i.useEffect(()=>{ze(0)},[L,he]),i.useEffect(()=>()=>{Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null),be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),i.useEffect(()=>{if(!g)return;const ie=Qe=>{const Ft=Qe.target;bt.current?.contains(Ft)||Ot.current?.contains(Ft)||Ft.closest(".model-combobox-dropdown--portal")||w(!1)},$e=Qe=>{Qe.key==="Escape"&&w(!1)};return document.addEventListener("mousedown",ie),document.addEventListener("keydown",$e),()=>{document.removeEventListener("mousedown",ie),document.removeEventListener("keydown",$e)}},[g,w]);const Pn=i.useCallback(()=>{const ie=en.current;if(!ie)return;const Qe=ie.scrollTop+ie.clientHeight>=ie.scrollHeight-50;oe(!Qe),_e.current=!Qe},[]),kn=i.useCallback(ie=>{if(!ie.isConnected)return;let $e=0,Qe=0,Ft=-1;const cn=6,pn=()=>{if(ie.isConnected){if(ie.scrollTop=ie.scrollHeight,ie.scrollHeight===Ft?Qe+=1:(Qe=0,Ft=ie.scrollHeight),$e+=1,$e>=cn||Qe>=2){oe(!1),_e.current=!1;return}window.requestAnimationFrame(pn)}};pn()},[]),Vn=i.useCallback(()=>{const ie=en.current;ie&&kn(ie)},[kn]);i.useLayoutEffect(()=>{const ie=Dt?.id??null,$e=ut.current;if(ut.current={isOpen:g,sessionId:ie},!g||!ie)return;const Qe=!$e.isOpen&&g,Ft=$e.isOpen&&$e.sessionId!==ie;if(!Qe&&!Ft)return;const cn=en.current;cn&&kn(cn)},[g,Dt?.id,kn]),i.useEffect(()=>{if(!y||!g||!Dt)return;const ie=()=>{const Qe=en.current;Qe&&kn(Qe)},$e=()=>{document.visibilityState==="visible"&&ie()};return document.addEventListener("visibilitychange",$e),window.addEventListener("pageshow",ie),()=>{document.removeEventListener("visibilitychange",$e),window.removeEventListener("pageshow",ie)}},[y,g,Dt,kn]),i.useEffect(()=>{g&&(_e.current||Vn())},[nn,sn,ln,on,g,Vn]);const $s=i.useMemo(()=>{const ie=new Map(m.map(Qe=>[Qe.id,Qe.name?.trim()||Qe.id])),$e=new Map(T.map(Qe=>[`${Qe.provider}/${Qe.id}`,Qe.name?.trim()||""]));return qt.map((Qe,Ft)=>{const cn=Qe.title?.trim()||`Session ${Ft+1}`;let pn=null;if(Qe.agentId&&Qe.agentId!==yr)pn=ie.get(Qe.agentId)||Qe.agentId;else if(Qe.modelProvider&&Qe.modelId){const jn=`${Qe.modelProvider}/${Qe.modelId}`,Un=$e.get(jn);pn=Un?`${Un} [${jn}]`:jn}return{id:Qe.id,label:pn?`${cn} — ${pn}`:cn}})},[m,T,qt]),vs=i.useMemo(()=>S==="agent"?Oe?`Message ${Oe.name||Oe.id}`:"Select an agent to start chatting":Dn?`Message ${Dn}`:"Select a model to start chatting",[S,Oe,Dn]),As=i.useCallback(ie=>{const $e=qt.find(Qe=>Qe.id===ie);$e&&(St.current=!0,$e.modelProvider&&$e.modelId?(j("model"),M(`${$e.modelProvider}/${$e.modelId}`)):(j("agent"),x($e.agentId)),We($e))},[We,qt]),bn=i.useCallback(async()=>{if(!Qt){if(St.current=!0,F==="agent"){if(!_)return;j("agent"),x(_),await Lt(_)}else{const ie=fo(U||O||D);if(!ie)return;j("model"),M(`${ie.modelProvider}/${ie.modelId}`),await Lt(yr,ie.modelProvider,ie.modelId)}await Bt(),R(!1),E("model")}},[D,_,F,U,Bt,O,Qt,Lt]),Ht=Pe.length>50?`${Pe.slice(0,50)}…`:Pe,On=i.useCallback(ie=>{if(!ie||ie.length===0)return;const $e=[];for(let Qe=0;Qe<ie.length;Qe+=1){const Ft=ie[Qe];OF(Ft)&&$e.push({file:Ft,previewUrl:LF(Ft)?URL.createObjectURL(Ft):""})}$e.length>0&&Le(Qe=>[...Qe,...$e])},[]),Fn=i.useCallback(ie=>{Le($e=>{const Qe=$e[ie];return Qe?.previewUrl&&URL.revokeObjectURL(Qe.previewUrl),$e.filter((Ft,cn)=>cn!==ie)})},[]),as=i.useCallback(ie=>{On(ie.clipboardData?.files)},[On]),Wn=i.useCallback(()=>{if(typeof window>"u"||window.innerWidth>Ls)return;const ie=Kt.current;!ie||ie.disabled||ie.focus({preventScroll:!0})},[]),Rs=i.useCallback(()=>{typeof window>"u"||window.innerWidth>Ls||(Ne.current=!0)},[]),In=i.useCallback(async()=>{const ie=k.trim(),$e=dn.current;if(!(!ie&&$e.length===0)&&!ot){if(X(""),B(!1),xe(""),Ve(-1),ie==="/help"){ce(!0),Wn(),Ne.current=!1;return}if(ie==="/clear"||ie==="/new"){ve(),Ke(),$e.forEach(Qe=>{Qe.previewUrl&&URL.revokeObjectURL(Qe.previewUrl)}),Le(Qe=>Qe.filter(Ft=>!$e.includes(Ft)));try{if(S==="model"){const Qe=fo(At);if(!Qe)return;await Lt(yr,Qe.modelProvider,Qe.modelId)}else C&&await Lt(C)}catch{n("Failed to clear conversation","error")}finally{Wn(),Ne.current=!1}return}try{ce(!1),await Zt(ie,$e.map(Qe=>Qe.file)),$e.forEach(Qe=>{Qe.previewUrl&&URL.revokeObjectURL(Qe.previewUrl)}),Le(Qe=>Qe.filter(Ft=>!$e.includes(Ft)))}catch{}finally{Wn(),Ne.current=!1}}},[n,S,Ke,Wn,ot,k,At,C,Zt,Lt,ve]),rs=i.useCallback(ie=>{ie.preventDefault(),gt.current+=1,Ue(!0)},[]),Ns=i.useCallback(ie=>{ie.preventDefault(),ie.dataTransfer.dropEffect="copy",Ue(!0)},[]),ys=i.useCallback(ie=>{ie.preventDefault(),gt.current=Math.max(0,gt.current-1),gt.current===0&&Ue(!1)},[]),cs=i.useCallback(ie=>{ie.preventDefault(),gt.current=0,Ue(!1),On(ie.dataTransfer?.files)},[On]),ss=i.useCallback((ie,$e)=>{const Qe=PF(ie,$e);if(Qe){B(!0),xe(Qe.filter),Ve(Qe.start);return}B(!1),xe(""),Ve(-1)},[]),te=i.useCallback(ie=>{X($e=>{const Qe=jg($e);if(!Qe)return $e;const Ft=`/skill:${ie.name} `,cn=$e.slice(0,Qe.start)+Ft+$e.slice(Qe.end);return window.requestAnimationFrame(()=>{Kt.current&&Kt.current.focus()}),cn}),ne(!1),Z(""),q(0)},[]),we=i.useCallback(ie=>{const $e=Kt.current;if(!$e||ae<0)return;const Qe=$e.selectionStart??me.current,Ft=$e.selectionEnd??Qe,cn=Math.max(Qe,Ft),pn=Math.min(ae,cn),Un=`${`@${ie.name.replace(/\s+/g,"_")}`} `,gs=k.slice(0,pn)+Un+k.slice(cn),bs=pn+Un.length;X(gs),B(!1),xe(""),ze(0),Ve(-1),window.requestAnimationFrame(()=>{Kt.current&&(Kt.current.focus(),Kt.current.setSelectionRange(bs,bs))})},[ae,k]),P=i.useCallback(ie=>{const $e=ie.target.value,Qe=ie.target.selectionStart??$e.length;me.current=Qe,X($e),Be&&$e.trim().length>0&&ce(!1),ss($e,Qe);const Ft=jg($e);Ft?(ne(!0),Z(Ft.filter)):(ne(!1),Z("")),tt.detectMention($e,Qe),Ee(tt.mentionActive),tt.mentionActive&&xt(ie.target)},[Be,ss,tt,xt]),Ce=i.useCallback(()=>{if(Ne.current){window.requestAnimationFrame(()=>{Wn()});return}typeof window<"u"&&window.innerWidth<=Ls&&bt.current&&(Y.current=!0,bt.current.style.removeProperty("--vv-height"),bt.current.style.removeProperty("--vv-offset-top"),window.setTimeout(()=>{Y.current=!1},450)),Ze.current!==null&&window.clearTimeout(Ze.current),Ze.current=window.setTimeout(()=>{B(!1),xe(""),Ve(-1),Ee(!1),tt.dismissMention(),Ze.current=null},120),be.current!==null&&window.clearTimeout(be.current),be.current=window.setTimeout(()=>{ne(!1),be.current=null},120)},[tt,Wn]),qe=i.useCallback(()=>{Y.current=!1,Ze.current!==null&&(window.clearTimeout(Ze.current),Ze.current=null),be.current!==null&&(window.clearTimeout(be.current),be.current=null)},[]),et=i.useCallback(ie=>{const $e=ie.currentTarget,Qe=$e.selectionStart??$e.value.length;me.current=Qe,ss($e.value,Qe),tt.detectMention($e.value,Qe),Ee(tt.mentionActive),tt.mentionActive&&xt($e)},[ss,tt,xt]),mt=i.useCallback(ie=>{ie.key!=="Escape"&&et(ie)},[et]),Nt=i.useCallback(ie=>{rt($e=>{const Qe=new Set($e);return Qe.has(ie)?Qe.delete(ie):Qe.add(ie),Qe})},[]),Pt=i.useCallback((ie,$e=!1)=>$e?t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--plain",children:ie}):t.jsx("div",{className:"quick-chat-message-content quick-chat-message-content--markdown",children:t.jsx(xi,{remarkPlugins:[vi],components:Xv,children:ie})}),[]),an=i.useCallback(ie=>{if(me.current=ie.currentTarget.selectionStart??me.current,tt.mentionActive&&tt.files.length>0){if(tt.handleKeyDown(ie,k),ie.key==="Enter"||ie.key==="Tab"){const $e=tt.files[tt.selectedIndex];if($e){const Qe=tt.selectFile($e,k);X(Qe),tt.dismissMention(),Ee(!1)}}return}if(he&&ie.key==="ArrowDown"){ie.preventDefault(),Xt.length>0&&ze($e=>($e+1)%Xt.length);return}if(he&&ie.key==="ArrowUp"){ie.preventDefault(),Xt.length>0&&ze($e=>$e===0?Xt.length-1:$e-1);return}if(he&&ie.key==="Enter"){ie.preventDefault();const $e=Xt[pe]??Xt[0];$e&&we($e);return}if(he&&ie.key==="Escape"){ie.preventDefault(),ie.stopPropagation(),B(!1),xe(""),Ve(-1);return}if(je&&Mt.length>0&&ie.key==="ArrowDown"){ie.preventDefault(),q($e=>($e+1)%Mt.length);return}if(je&&Mt.length>0&&ie.key==="ArrowUp"){ie.preventDefault(),q($e=>$e===0?Mt.length-1:$e-1);return}if(je&&(ie.key==="Enter"||ie.key==="Tab")){ie.preventDefault();const $e=Mt[re]??Mt[0];$e&&te($e);return}if(je&&ie.key==="Escape"){ie.preventDefault(),ne(!1),Z("");return}ie.key!=="Enter"||ie.shiftKey||(ie.preventDefault(),In())},[he,Xt,pe,we,In,tt,k,je,Mt,re,te]),Cn=i.useCallback(()=>{if(Me.current){Me.current=!1;return}if(g){w(!1);return}typeof window<"u"&&window.innerWidth<=Ls&&W.current?.focus({preventScroll:!0}),w(!0)},[g,w]);return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:W,type:"text",className:"quick-chat-stealth-input","aria-hidden":"true",tabIndex:-1}),s&&t.jsx("button",{ref:Ot,type:"button",className:"quick-chat-fab","aria-label":"Open quick chat","data-testid":"quick-chat-fab","data-dragging":Ie?"true":"false",style:{right:$t.x,bottom:$t.y},onPointerDown:ge,onClick:Cn,children:t.jsx(Zi,{size:24})}),g&&t.jsxs("div",{className:`quick-chat-panel${y&&v?" quick-chat-panel--keyboard-open":""}`,ref:bt,"data-testid":"quick-chat-panel",style:{...Ut?{right:$t.x+pt.right,bottom:st+pt.bottom,width:yt.width,height:yt.height}:{}},children:[Ut&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"n","data-testid":"quick-chat-resize-n",onPointerDown:vt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from top"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"s","data-testid":"quick-chat-resize-s",onPointerDown:vt,role:"separator","aria-orientation":"horizontal","aria-label":"Resize panel from bottom"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"e","data-testid":"quick-chat-resize-e",onPointerDown:vt,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from right"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"w","data-testid":"quick-chat-resize-w",onPointerDown:vt,role:"separator","aria-orientation":"vertical","aria-label":"Resize panel from left"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"nw","data-testid":"quick-chat-resize-nw",onPointerDown:vt,role:"separator","aria-label":"Resize panel from top-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"ne","data-testid":"quick-chat-resize-ne",onPointerDown:vt,role:"separator","aria-label":"Resize panel from top-right corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"sw","data-testid":"quick-chat-resize-sw",onPointerDown:vt,role:"separator","aria-label":"Resize panel from bottom-left corner"}),t.jsx("div",{className:"quick-chat-resize-handle","data-resize-direction":"se","data-testid":"quick-chat-resize-se",onPointerDown:vt,role:"separator","aria-label":"Resize panel from bottom-right corner"})]}),t.jsxs("div",{className:"quick-chat-panel-header",children:[t.jsxs("div",{className:"quick-chat-panel-title-wrap",children:[t.jsx("h3",{children:"Quick Chat"}),S==="model"&&Dn&&(()=>{const ie=vn?.provider??Zn?.modelProvider??"";return b==="mobile"&&Dn.length>12&&ie?t.jsx("span",{className:"quick-chat-model-tag quick-chat-model-tag--icon","data-testid":"quick-chat-model-tag",title:Dn,"aria-label":Dn,children:t.jsx(zn,{provider:ie,size:"sm"})}):t.jsx("span",{className:"quick-chat-model-tag","data-testid":"quick-chat-model-tag",title:Dn,children:Dn})})()]}),t.jsxs("div",{className:"quick-chat-panel-header-actions",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-new-chat-btn","data-testid":"quick-chat-new-thread","aria-label":"Start a new chat",onClick:G,disabled:Qt,children:t.jsx($n,{size:16})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":"Close quick chat","data-testid":"quick-chat-close",onClick:()=>w(!1),children:t.jsx(mn,{size:16})})]})]}),t.jsxs("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-session-select",children:[t.jsx("label",{htmlFor:"quick-chat-session-select",className:"visually-hidden",children:"Select session"}),t.jsxs("select",{id:"quick-chat-session-select",value:Dt?.id??"",onChange:ie=>As(ie.target.value),"data-testid":"quick-chat-session-dropdown",children:[t.jsx("option",{value:"",disabled:!0,children:Qt?"Loading sessions…":"Select a session"}),$s.map(ie=>t.jsx("option",{value:ie.id,children:ie.label},ie.id))]})]}),N&&t.jsxs("div",{className:"quick-chat-new-session-chooser","data-testid":"quick-chat-new-session-chooser",children:[t.jsxs("div",{className:"quick-chat-inline-mode-toggle","data-testid":"quick-chat-inline-mode-toggle",children:[t.jsx("button",{type:"button",className:`quick-chat-mode-btn${F==="model"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-model",onClick:()=>E("model"),children:"Model"}),t.jsx("button",{type:"button",className:`quick-chat-mode-btn${F==="agent"?" quick-chat-mode-btn--active":""}`,"data-testid":"quick-chat-inline-mode-agent",onClick:()=>E("agent"),children:"Agent"})]}),F==="agent"?t.jsxs("div",{className:"quick-chat-panel-agent-select",children:[t.jsx("label",{htmlFor:"quick-chat-new-agent-select",className:"visually-hidden",children:"Select agent for new chat"}),t.jsx("select",{id:"quick-chat-new-agent-select",value:_,onChange:ie=>K(ie.target.value),"data-testid":"quick-chat-new-agent-select",children:m.map(ie=>t.jsx("option",{value:ie.id,children:AF(ie)},ie.id))})]}):t.jsx("div",{className:"quick-chat-panel-agent-select","data-testid":"quick-chat-new-model-select",children:t.jsx(_s,{id:"quick-chat-new-model-select",models:T,value:U,onChange:A,label:"Select model override",placeholder:Q?"Loading models…":"Select a model",disabled:Q||T.length===0,favoriteProviders:o,favoriteModels:l,onToggleFavorite:c,onToggleModelFavorite:d})}),t.jsxs("div",{className:"quick-chat-new-session-actions",children:[t.jsx("button",{type:"button",className:"btn","data-testid":"quick-chat-new-session-cancel",onClick:()=>{R(!1),E("model")},children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary","data-testid":"quick-chat-new-session-submit",onClick:()=>void bn(),disabled:Qt||(F==="agent"?!_:!fo(U||O||D)),children:"Create"})]})]}),t.jsx("div",{className:"quick-chat-panel-messages",ref:en,"data-testid":"quick-chat-messages",onScroll:Pn,children:Qt?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):on?t.jsxs(t.Fragment,{children:[nn.map(ie=>t.jsx(Ng,{message:ie,forcePlain:ie.role!=="user"&&Te.has(ie.id),mentionAgentsByName:_n,roomContext:u,onToggleRender:Nt},ie.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Pt("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")}),t.jsxs("div",{className:"quick-chat-panel-message quick-chat-panel-message--received quick-chat-panel-message--streaming","data-testid":"quick-chat-streaming-message",children:[sn?t.jsxs(t.Fragment,{children:[t.jsx("div",{"data-testid":"quick-chat-streaming-text",children:Pt(sn,Te.has("__streaming__"))}),t.jsx("button",{type:"button",className:`quick-chat-message-render-toggle${Te.has("__streaming__")?" quick-chat-message-render-toggle--plain":""}`,"data-testid":"quick-chat-message-render-toggle","aria-label":Te.has("__streaming__")?"Show rendered markdown":"Show plain text",onClick:()=>Nt("__streaming__"),children:Te.has("__streaming__")?t.jsx(zu,{size:14}):t.jsx(Fr,{size:14})})]}):t.jsx("p",{className:"quick-chat-panel-waiting","data-testid":"quick-chat-waiting",children:ln?"Thinking…":"Connecting…"}),Qv(xn,!0),ln&&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:ln})]})]})]}):hn?t.jsx("div",{className:"quick-chat-panel-empty",children:"Loading conversation…"}):nn.length===0&&!sn&&!ln&&!on&&!Be?t.jsx("div",{className:"quick-chat-panel-empty",children:"No messages yet. Start the conversation!"}):t.jsxs(t.Fragment,{children:[nn.map(ie=>t.jsx(Ng,{message:ie,forcePlain:ie.role!=="user"&&Te.has(ie.id),mentionAgentsByName:_n,roomContext:u,onToggleRender:Nt},ie.id)),Be&&t.jsx("div",{className:"quick-chat-panel-message quick-chat-panel-message--received","data-testid":"quick-chat-help-message",children:Pt("Available commands:\n- `/new` or `/clear` — Clear conversation and start fresh\n- `/skill:{name}` — Use a specific skill\n- `/help` — Show this help")})]})}),ue&&t.jsxs("button",{type:"button",className:"btn btn-sm quick-chat-jump-to-latest","data-testid":"quick-chat-jump-to-latest",onClick:Vn,children:[t.jsx(gn,{size:14}),"Latest"]}),Re.length>0&&t.jsx("div",{className:"quick-chat-attachment-previews","data-testid":"quick-chat-attachment-previews",children:Re.map((ie,$e)=>t.jsxs("div",{className:"quick-chat-attachment-preview","data-testid":`quick-chat-attachment-preview-${$e}`,children:[ie.previewUrl?t.jsx("img",{src:ie.previewUrl,alt:ie.file.name}):t.jsx("span",{className:"quick-chat-attachment-preview-name",children:ie.file.name}),t.jsx("button",{type:"button",className:"quick-chat-attachment-remove","data-testid":`quick-chat-attachment-remove-${$e}`,"aria-label":`Remove ${ie.file.name}`,onClick:()=>Fn($e),children:"×"})]},`${ie.file.name}-${$e}`))}),t.jsx("div",{className:"quick-chat-panel-input",children:t.jsxs("div",{className:`quick-chat-input-wrapper${ct?" quick-chat-input-wrapper--dragover":""}`,onDragEnter:rs,onDragOver:Ns,onDragLeave:ys,onDrop:cs,children:[t.jsx("input",{ref:Sn,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,tabIndex:-1,"aria-hidden":"true",className:"quick-chat-attachment-input",onChange:ie=>{On(ie.target.files),ie.target.value=""}}),t.jsxs("div",{className:"quick-chat-input-row","data-testid":"quick-chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon quick-chat-attach-btn","data-testid":"quick-chat-attach-btn","aria-label":"Attach files",onClick:()=>Sn.current?.click(),children:t.jsx(ab,{size:16})}),t.jsx("input",{ref:Kt,type:"text",value:k,onChange:P,onKeyDown:an,onKeyUp:mt,onClick:et,onBlur:Ce,onFocus:qe,onPaste:as,onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||document.activeElement!==ie.currentTarget&&(ie.preventDefault(),ie.currentTarget.focus({preventScroll:!0}))},placeholder:vs,disabled:ot,"data-testid":"quick-chat-input"}),on?t.jsx("button",{type:"button",className:"chat-input-stop quick-chat-send-btn",onPointerDown:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),ie.pointerType&&ie.pointerType!=="mouse"&&(tn.current=!0,ve()))},onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),tn.current=!0,ve())},onMouseDown:ie=>{typeof window>"u"||window.innerWidth>Ls||ie.preventDefault()},onClick:()=>{if(tn.current){tn.current=!1;return}ve()},"aria-label":"Stop generation","data-testid":"quick-chat-stop",children:t.jsx($i,{size:14})}):t.jsx("button",{type:"button",className:"quick-chat-send-btn",onPointerDown:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),ie.pointerType&&ie.pointerType!=="mouse"&&(tn.current=!0,Rs(),Wn(),In()))},onTouchStart:ie=>{typeof window>"u"||window.innerWidth>Ls||(ie.preventDefault(),tn.current=!0,Rs(),Wn(),In())},onMouseDown:ie=>{typeof window>"u"||window.innerWidth>Ls||ie.preventDefault()},onClick:()=>{if(tn.current){tn.current=!1;return}In()},disabled:ot||k.trim().length===0&&Re.length===0,"data-testid":"quick-chat-send",children:t.jsx(Da,{size:16})})]}),t.jsx(vF,{agents:m,filter:L,highlightedIndex:pe,visible:he,onSelect:we,position:"above",roomMemberIds:u?.memberIds,roomName:u?.roomName}),t.jsx(EF,{visible:tt.mentionActive&&!he,position:ft,files:tt.files,selectedIndex:tt.selectedIndex,onSelect:ie=>{const $e=tt.selectFile(ie,k);X($e),tt.dismissMention(),Ee(!1),Kt.current?.focus()},loading:tt.loading}),je&&t.jsx("div",{className:"chat-skill-menu","data-testid":"quick-chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:He?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):Mt.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:fe?"No skills found":"No skills available"}):Mt.map((ie,$e)=>t.jsxs("button",{type:"button",role:"option","aria-selected":$e===re,className:`chat-skill-menu-item${$e===re?" chat-skill-menu-item--highlighted":""}`,onMouseDown:Qe=>Qe.preventDefault(),onMouseEnter:()=>q($e),onClick:()=>te(ie),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:ie.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:ie.relativePath,children:ie.relativePath})]},ie.id))}),Pe&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Ht}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:Ke,children:"×"})]})]})})]})]})}function go(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function Sg(e){return e.status==="generating"||e.status==="awaiting_input"}function bo(e){return e==="complete"||e==="error"}function UF(e){const[n,s]=i.useState([]),a=i.useRef(new Map),r=i.useRef(new Map),{sessions:o,broadcastUpdate:l,broadcastCompleted:c,requestSync:d}=Wr(),u=i.useCallback(()=>{Wu(e).then(p=>{const g=p.filter(v=>{const b=go(v.updatedAt),y=r.current.get(v.id);return y===void 0?!0:b<=y?!1:(r.current.delete(v.id),!0)}),w=new Map;for(const v of g)w.set(v.id,go(v.updatedAt));a.current=w,s(g)}).catch(p=>{console.warn("[useBackgroundSessions] Failed to fetch AI sessions:",p)})},[e]);i.useEffect(()=>{d(),u()},[u,d]),i.useEffect(()=>{s(p=>{if(o.size===0)return p;let g=!1;const w=new Map(p.map(v=>[v.id,v]));for(const v of o.values()){if(e&&v.projectId&&v.projectId!==e)continue;const b=v.lastEventTimestamp,y=a.current.get(v.sessionId)??0;if(b<y)continue;const S=r.current.get(v.sessionId);if(S!==void 0&&b<=S)continue;if(S!==void 0&&b>S&&!bo(v.status)&&r.current.delete(v.sessionId),bo(v.status)){w.delete(v.sessionId)&&(g=!0),a.current.set(v.sessionId,b);continue}const j=w.get(v.sessionId),C=v.type??j?.type,x=v.title??j?.title;if(!j&&(!C||!x))continue;const N={id:v.sessionId,type:C??"planning",status:v.status,title:x??"AI Session",projectId:v.projectId??j?.projectId??e??null,lockedByTab:v.owningTabId??j?.lockedByTab??null,updatedAt:v.updatedAt??j?.updatedAt??new Date(b).toISOString()},R=w.get(v.sessionId);(!R||R.status!==N.status||R.title!==N.title||R.type!==N.type||R.projectId!==N.projectId||R.lockedByTab!==N.lockedByTab||R.updatedAt!==N.updatedAt)&&(w.set(v.sessionId,N),a.current.set(v.sessionId,b),g=!0)}return g?[...w.values()].sort((v,b)=>go(b.updatedAt)-go(v.updatedAt)):p})},[e,o]),i.useEffect(()=>{const p=e?`?projectId=${encodeURIComponent(e)}`:"",g=v=>{try{const b=JSON.parse(v.data),y=go(b.updatedAt)||Date.now();s(S=>{const j=a.current.get(b.id)??0;if(y<j)return S;const C=r.current.get(b.id);if(C!==void 0&&y<=C)return S;if(C!==void 0&&y>C&&!bo(b.status)&&r.current.delete(b.id),a.current.set(b.id,y),bo(b.status))return S.filter(N=>N.id!==b.id);const x=S.findIndex(N=>N.id===b.id);if(x>=0){const N=[...S];return N[x]=b,N}return Sg(b)?[b,...S]:S}),l({sessionId:b.id,status:b.status,needsInput:b.status==="awaiting_input",type:b.type,title:b.title,projectId:b.projectId,owningTabId:b.lockedByTab,updatedAt:b.updatedAt,timestamp:y}),bo(b.status)&&c({sessionId:b.id,status:b.status,timestamp:y})}catch{}},w=v=>{try{const b=JSON.parse(v.data),y=Date.now();r.current.set(b,y),a.current.set(b,Math.max(a.current.get(b)??0,y)),c({sessionId:b,status:"complete",timestamp:y}),s(S=>S.filter(j=>j.id!==b))}catch{}};return yi(`/api/events${p}`,{events:{"ai_session:updated":g,"ai_session:deleted":w},onReconnect:()=>{u()}})},[c,l,e,u]);const m=i.useCallback(async p=>{const w=n.find(S=>S.id===p)?.type,v=Ja();let b=!1;if(w==="planning")try{await pb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of planning session ${p} despite lock by another tab`)}else if(w==="subtask")try{await bb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of subtask session ${p} despite lock by another tab`)}else if(w==="mission_interview")try{await kb(p,e,v)}catch(S){b=!0,S instanceof Error&&S.message.includes("locked")&&console.warn(`[useBackgroundSessions] Forcing dismiss of mission interview session ${p} despite lock by another tab`)}b&&console.warn(`[useBackgroundSessions] Cancellation failed for session ${p}, attempting delete anyway`);const y=Date.now();r.current.set(p,y),a.current.set(p,Math.max(a.current.get(p)??0,y)),c({sessionId:p,status:"complete",timestamp:y});try{await jb(p)}catch{}s(S=>S.filter(j=>j.id!==p))},[c,e,n]),h=i.useMemo(()=>n.filter(p=>Sg(p)),[n]),f=i.useMemo(()=>h.filter(p=>p.type==="planning"),[h]);return{sessions:h,generating:h.filter(p=>p.status==="generating").length,needsInput:h.filter(p=>p.status==="awaiting_input").length,planningSessions:f,dismissSession:m,refresh:u}}const mc="fusion:hide-session-banners",Lu="fusion:session-banner-pref-changed";function HF(){if(typeof window>"u")return!1;try{return window.localStorage.getItem(mc)==="1"}catch{return!1}}function qF(e){if(typeof window>"u")return()=>{};const n=a=>{a.key===mc&&e()},s=()=>e();return window.addEventListener("storage",n),window.addEventListener(Lu,s),()=>{window.removeEventListener("storage",n),window.removeEventListener(Lu,s)}}function D8(e){if(!(typeof window>"u"))try{e?window.localStorage.setItem(mc,"1"):window.localStorage.removeItem(mc),window.dispatchEvent(new Event(Lu))}catch{}}function VF(){return i.useSyncExternalStore(qF,HF,()=>!1)}function Ss(e){return{...e,column:Db(e.column),dependencies:Array.isArray(e.dependencies)?e.dependencies:[],steps:Array.isArray(e.steps)?e.steps:[],log:Array.isArray(e.log)?e.log:[]}}function Cg(e,n){return!e&&!n?0:e?n?e.localeCompare(n):1:-1}function WF(e,n){return{...n,columnMovedAt:e.columnMovedAt??n.columnMovedAt,executionStartedAt:e.executionStartedAt??n.executionStartedAt,executionCompletedAt:e.executionCompletedAt??n.executionCompletedAt,worktree:n.worktree??e.worktree,modifiedFiles:n.modifiedFiles??e.modifiedFiles,timedExecutionMs:n.timedExecutionMs??e.timedExecutionMs,workflowStepResults:n.workflowStepResults??e.workflowStepResults,tokenUsage:n.tokenUsage??e.tokenUsage,mergeDetails:n.mergeDetails??e.mergeDetails}}function Yd(e,n){if(Cg(n.updatedAt,e.updatedAt)<0)return e;if(e.column===n.column)return WF(e,n);const a=Cg(e.columnMovedAt,n.columnMovedAt);return e.columnMovedAt&&!n.columnMovedAt?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:a>=0?{...n,column:e.column,columnMovedAt:e.columnMovedAt}:n}function GF(e){const n=e?.projectId,s=e?.searchQuery,a=e?.sseEnabled??!0,[r,o]=i.useState([]),[l,c]=i.useState(!1),d=i.useRef(l);d.current=l;const u=i.useRef(r),m=i.useRef(0),h=i.useRef(0),f=i.useRef(s),p=i.useRef(null),g=i.useRef(void 0),w=i.useRef(0),v=i.useRef(n);u.current=r,f.current=s,v.current!==n&&(v.current=n,w.current++);const b=1e3,y=i.useCallback(async se=>{const O=++m.current,M=n,D=se?.searchQueryOverride??f.current,$=se?.includeArchivedOverride??d.current;try{const k=await Oj(void 0,void 0,M,D,$);if(m.current!==O||n!==M)return;o(k.map(Ss)),g.current=Date.now()}catch{if(m.current!==O||n!==M)return;if(se?.clearOnError){o([]);return}o(k=>k)}},[n]);p.current=y;const S=i.useCallback(async()=>{d.current||(c(!0),d.current=!0,await p.current({includeArchivedOverride:!0}))},[]),j=i.useRef(s);i.useEffect(()=>{if(s===void 0&&j.current===void 0)return;j.current=s;const se=setTimeout(()=>{y({searchQueryOverride:s})},300);return()=>clearTimeout(se)},[s]),i.useEffect(()=>{y({clearOnError:!0});const se=()=>{if(document.visibilityState!=="visible")return;const O=Date.now();O-h.current<b||(h.current=O,y())};return document.addEventListener("visibilitychange",se),()=>{document.removeEventListener("visibilitychange",se)}},[y]),i.useEffect(()=>{if(a===!1)return;const se=w.current,O=n?`?projectId=${encodeURIComponent(n)}`:"",M=()=>w.current!==se;let D=!0;const $=ye=>{if(M())return;const je=Ss(JSON.parse(ye.data));if(f.current){p.current({searchQueryOverride:f.current});return}o(ne=>{const fe=ne.findIndex(L=>L.id===je.id);if(fe===-1)return[...ne,je];const Z=ne[fe],re=Yd(Z,je);if(re===Z)return ne;const q=[...ne];return q[fe]=re,q}),g.current=Date.now()},k=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:je,to:ne}=JSON.parse(ye.data),fe=Ss(je),Z={...fe,column:Db(ne,fe.column)};o(re=>{const q=re.findIndex(xe=>xe.id===Z.id);if(q===-1)return[...re,Z];const L=[...re];return L[q]=Z,L}),g.current=Date.now()},X=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const je=Ss(JSON.parse(ye.data));o(ne=>{const fe=ne.findIndex(L=>L.id===je.id);if(fe===-1)return[...ne,je];const Z=ne[fe],re=Yd(Z,je);if(re===Z)return ne;const q=[...ne];return q[fe]=re,q}),g.current=Date.now()},le=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const je=Ss(JSON.parse(ye.data));o(ne=>ne.filter(fe=>fe.id!==je.id))},ke=ye=>{if(M())return;if(f.current){p.current({searchQueryOverride:f.current});return}const{task:je}=JSON.parse(ye.data),fe={...Ss(je),column:"done"};o(Z=>{const re=Z.findIndex(L=>L.id===fe.id);if(re===-1)return[...Z,fe];const q=[...Z];return q[re]=fe,q})},He=yi(`/api/events${O}`,{events:{"task:created":$,"task:moved":k,"task:updated":X,"task:deleted":le,"task:merged":ke},onReconnect:()=>{D&&(M()||p.current())}});return()=>{D=!1,He()}},[n,a]);const C=i.useCallback(async se=>{const O=Ss(await db(se,n));return o(M=>M.some(D=>D.id===O.id)?M:[...M,O]),O},[n]),x=i.useCallback(async(se,O,M)=>Ss(await zj(se,O,n,M)),[n]),N=i.useCallback(async se=>Ss(await ub(se,n)),[n]),R=i.useCallback(async(se,O)=>Ss(await Bj(se,n,O)),[n]),F=i.useCallback(async se=>Uj(se,n),[n]),E=i.useCallback(async se=>Ss(await Hj(se,n)),[n]),_=i.useCallback(async se=>Ss(await qj(se,n)),[n]),K=i.useCallback(async se=>{const O=Ss(await Vj(se,n));return o(M=>M.some(D=>D.id===O.id)?M:[...M,O]),O},[n]),U=i.useCallback(async(se,O)=>{const M=u.current.find($=>$.id===se),D=M?{...M,...O,updatedAt:new Date().toISOString()}:void 0;D&&o($=>$.map(k=>k.id===se?D:k));try{const $=Ss(await Us(se,O,n));return o(k=>k.map(X=>X.id===se?$:X)),$}catch($){throw M&&o(k=>k.map(X=>X.id===se?M:X)),$}},[n]),A=i.useCallback(async se=>{const O=Ss(await Gj(se,n));return o(M=>M.map(D=>D.id===se?O:D)),O},[n]),T=i.useCallback(async se=>{const O=Ss(await Kj(se,n));return o(M=>M.map(D=>D.id===se?O:D)),O},[n]),H=i.useCallback(async()=>{const O=(await Jj(n)).map(Ss);return o(M=>M.map(D=>O.find(k=>k.id===D.id)||D)),O},[n]),Q=i.useCallback(se=>{if(se.length===0)return;if(f.current){p.current({searchQueryOverride:f.current});return}const O=se.map(Ss);o(M=>{let D=M;for(const $ of O){const k=D.findIndex(ke=>ke.id===$.id);if(k===-1){D===M&&(D=[...M]),D.push($);continue}const X=D[k],le=Yd(X,$);le!==X&&(D===M&&(D=[...M]),D[k]=le)}return D}),g.current=Date.now()},[]);return{tasks:r,createTask:C,moveTask:x,pauseTask:N,deleteTask:R,mergeTask:F,retryTask:E,resetTask:_,duplicateTask:K,updateTask:U,archiveTask:A,unarchiveTask:T,archiveAllDone:H,loadArchivedTasks:S,includeArchived:l,ingestCreatedTasks:Q,lastFetchTimeMs:g.current}}const KF=5e3,JF=1e3;function YF(e){const s=(d1(e)?e.nodeMappings??e.projectNodeMappings??e.pathMappings??[]:[]).filter(a=>!!a?.nodeId&&!!a?.path).map(a=>({nodeId:a.nodeId,nodeName:a.nodeName,path:a.path,available:a.available!==!1}));return s.length>0?s:e.nodeId&&e.path?[{nodeId:e.nodeId,nodeName:e._sourceNodeName,path:e.path,available:!0}]:[]}function Eg(e){return e.map(n=>({...n,nodeMappings:YF(n)}))}function QF(){const[e,n]=i.useState([]),[s,a]=i.useState(!0),[r,o]=i.useState(null),l=i.useRef(null),c=i.useRef(0),d=i.useCallback(async()=>{try{o(null);const f=await ih();n(Eg(f))}catch(f){o(f instanceof Error?f.message:"Failed to fetch projects")}},[]);i.useEffect(()=>{let f=!1;async function p(){a(!0);const w=performance.now();try{const v=await ih(),b=Eg(v),y=Math.round(performance.now()-w);console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${y}ms (${b.length} projects)`),f||(n(b),o(null))}catch(v){const b=Math.round(performance.now()-w);console.warn(`[useProjects] initial fetch failed after ${b}ms: ${v instanceof Error?v.message:String(v)}`),f||o(v instanceof Error?v.message:"Failed to fetch projects")}finally{f||a(!1)}}p();const g=()=>{if(document.visibilityState!=="visible")return;const w=Date.now();w-c.current<JF||(c.current=w,d())};return document.addEventListener("visibilitychange",g),()=>{f=!0,document.removeEventListener("visibilitychange",g)}},[d]),i.useEffect(()=>{if(!s)return l.current=setInterval(()=>{d()},KF),()=>{l.current&&(clearInterval(l.current),l.current=null)}},[s,d]);const u=i.useCallback(async f=>{const p=await x1(f);return n(g=>[...g,p]),p},[]),m=i.useCallback(async(f,p)=>{const g=await S1(f,p);return n(w=>w.map(v=>v.id===f?g:v)),g},[]),h=i.useCallback(async f=>{await vb(f),n(p=>p.filter(g=>g.id!==f))},[]);return{projects:e,loading:s,error:r,refresh:d,register:u,update:m,unregister:h}}const XF="kb-dashboard-current-project";function ZF(e){return e??"local"}function ez(e,n={}){const{nodeId:s=null}=n,[a,r]=i.useState(null),[o,l]=i.useState(!0),c=i.useRef(!1),d=i.useRef(!1),u=i.useRef(null),m=ZF(s);i.useEffect(()=>{let p=!1;async function g(){try{const w=await na();if(p)return;u.current=w.dashboardCurrentProjectIdByNode??{};const v=u.current[m];if(v){const b=e.find(y=>y.id===v);b&&(r(b),c.current=!0)}if(!v)try{const b=localStorage.getItem(XF);if(b){const y=JSON.parse(b);y?.id&&e.some(j=>j.id===y.id)&&(r(y),c.current=!0,u.current={...u.current,[m]:y.id},await Bn({dashboardCurrentProjectIdByNode:u.current}).catch(()=>{}))}}catch{}}catch{}finally{p||l(!1)}}return g(),()=>{p=!0}},[m,e]),i.useEffect(()=>{if(!o){if(a){if(!e.some(w=>w.id===a.id)&&e.length>0){const w=e.find(v=>v.status==="active");r(w||e[0]||null);return}const g={...u.current,[m]:a.id};u.current=g,Bn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}else if(e.length>0&&!d.current){const p=e.find(g=>g.status==="active");p&&r(p)}}},[a,e,o,m]);const h=i.useCallback(p=>{if(d.current=!1,r(p),p){const g={...u.current,[m]:p.id};u.current=g,Bn({dashboardCurrentProjectIdByNode:g}).catch(()=>{})}},[m]),f=i.useCallback(()=>{d.current=!0,r(null);const p={...u.current};delete p[m],u.current=p,Bn({dashboardCurrentProjectIdByNode:p}).catch(()=>{})},[m]);return{currentProject:a,setCurrentProject:h,clearCurrentProject:f,loading:o}}const Zv=i.createContext(null);function tz({children:e}){const[n,s]=i.useState([]),a=i.useRef(0),r=i.useRef(new Map),o=i.useCallback(c=>{const d=r.current.get(c);d!==void 0&&(clearTimeout(d),r.current.delete(c)),s(u=>u.filter(m=>m.id!==c))},[]),l=i.useCallback((c,d="info")=>{const u=a.current++;s(h=>[...h,{id:u,message:c,type:d}]);const m=setTimeout(()=>o(u),4e3);r.current.set(u,m)},[o]);return i.useEffect(()=>()=>{r.current.forEach(c=>clearTimeout(c)),r.current.clear()},[]),ga.createElement(Zv.Provider,{value:{toasts:n,addToast:l,removeToast:o}},e)}function nz(){const e=i.useContext(Zv);if(!e)throw new Error("useToast must be used within ToastProvider");return e}const ey="kb-dashboard-theme-mode",ty="kb-dashboard-color-theme",ny="kb-dashboard-font-scale-pct",Ou=100,sz=85,iz=125,sy=[...BC],Fu="theme-data",xo="theme-data.css";function az(){const e=document.baseURI||(typeof document.location<"u"?document.location.href:"");return e?e.startsWith("http://")||e.startsWith("https://")?new URL(`/${xo}`,e).toString():e.startsWith("file://")?e.endsWith("/")?e.slice(0,-1)+`/${xo}`:e.replace(/\/[^/]+$/,`/${xo}`):`/${xo}`:`/${xo}`}const Qs=typeof window<"u",rz=Qs?i.useLayoutEffect:i.useEffect;function iy(e){return e==="dark"||e==="light"||e==="system"}function _g(){if(!Qs)return"dark";try{const e=localStorage.getItem(ey);if(iy(e))return e}catch{}return"dark"}function Mg(){if(!Qs)return"default";try{const e=localStorage.getItem(ty);if(e&&sy.includes(e))return e}catch{}return"default"}function Ag(e){if(Qs)try{localStorage.setItem(ey,e)}catch{}}function Rg(e){if(Qs)try{localStorage.setItem(ty,e)}catch{}}function Fo(e){return typeof e!="number"||!Number.isFinite(e)?Ou:Math.min(iz,Math.max(sz,Math.round(e)))}function Ig(){if(!Qs)return Ou;try{const e=Number(localStorage.getItem(ny));return Fo(e)}catch{return Ou}}function Tg(e){if(Qs)try{localStorage.setItem(ny,String(Fo(e)))}catch{}}function oz(e,n){return e==="system"?n?"dark":"light":e}function lz(e,n,s,a){if(!Qs)return;const r=oz(e,a);document.documentElement.setAttribute("data-theme",r),document.documentElement.setAttribute("data-color-theme",n),document.documentElement.style.fontSize=`${Fo(s)}%`}function Pg(){if(!Qs)return;const e=az(),n=document.getElementById(Fu);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=Fu,document.head.appendChild(s)}function $g(){if(!Qs)return;const e=document.getElementById(Fu);e&&e.remove()}function cz(){const[e,n]=i.useState(()=>_g()),[s,a]=i.useState(()=>Mg()),[r,o]=i.useState(()=>Ig()),[l,c]=i.useState(!0),[d,u]=i.useState(()=>Qs?window.matchMedia("(prefers-color-scheme: dark)").matches:!0),m=i.useRef(e),h=i.useRef(s),f=i.useRef(r),p=i.useRef(!1),g=i.useRef(!1),w=i.useRef(!1);i.useEffect(()=>{m.current=e},[e]),i.useEffect(()=>{h.current=s},[s]),i.useEffect(()=>{f.current=r},[r]),i.useEffect(()=>{if(!Qs||!l)return;let S=!1;return na().then(j=>{if(!S&&(iy(j.themeMode)&&!p.current&&(m.current!==j.themeMode&&(m.current=j.themeMode,n(j.themeMode)),_g()!==j.themeMode&&Ag(j.themeMode)),j.colorTheme&&sy.includes(j.colorTheme)&&!g.current&&(h.current!==j.colorTheme&&(h.current=j.colorTheme,a(j.colorTheme)),Mg()!==j.colorTheme&&Rg(j.colorTheme)),!w.current)){const C=Fo(j.dashboardFontScalePct);f.current!==C&&(f.current=C,o(C)),Ig()!==C&&Tg(C)}}).catch(j=>{console.warn("[useTheme] Failed to hydrate theme from global settings",j)}).finally(()=>{S||c(!1)}),()=>{S=!0}},[l]),i.useEffect(()=>{if(!Qs)return;const S=window.matchMedia("(prefers-color-scheme: dark)"),j=C=>{u(C.matches)};return S.addEventListener("change",j),()=>S.removeEventListener("change",j)},[]),rz(()=>{lz(e,s,r,d)},[e,s,r,d]),i.useEffect(()=>{!Qs||l||(s!=="default"?Pg():$g())},[s,l]);const v=i.useCallback(S=>{p.current=!0,m.current=S,n(S),Ag(S),Bn({themeMode:S}).catch(j=>{console.warn("[useTheme] Failed to persist themeMode to global settings",j)})},[]),b=i.useCallback(S=>{g.current=!0,h.current=S,a(S),Rg(S),S!=="default"?Pg():$g(),Bn({colorTheme:S}).catch(j=>{console.warn("[useTheme] Failed to persist colorTheme to global settings",j)})},[]),y=i.useCallback(S=>{const j=Fo(S);w.current=!0,f.current=j,o(j),Tg(j),Bn({dashboardFontScalePct:j}).catch(C=>{console.warn("[useTheme] Failed to persist dashboardFontScalePct to global settings",C)})},[]);return{themeMode:e,colorTheme:s,dashboardFontScalePct:r,setThemeMode:v,setColorTheme:b,setDashboardFontScalePct:y,isSystemDark:d}}function dz(e){const{planningSessions:n}=e,[s,a]=i.useState(!1),[r,o]=i.useState(!1),[l,c]=i.useState(null),[d,u]=i.useState(void 0),[m,h]=i.useState(!1),[f,p]=i.useState(null),[g,w]=i.useState(void 0),[v,b]=i.useState(null),[y,S]=i.useState("definition"),[j,C]=i.useState(null),[x,N]=i.useState(!1),[R,F]=i.useState(void 0),[E,_]=i.useState(!1),[K,U]=i.useState(!1),[A,T]=i.useState(!1),[H,Q]=i.useState(null),[se,O]=i.useState(!1),[M,D]=i.useState(!1),[$,k]=i.useState(void 0),[X,le]=i.useState(!1),[ke,He]=i.useState(!1),[ye,je]=i.useState("project"),[ne,fe]=i.useState(null),[Z,re]=i.useState(!1),[q,L]=i.useState(!1),[xe,he]=i.useState(!1),[B,pe]=i.useState(!1),[ze,ae]=i.useState(!1),[Ve,Te]=i.useState(!1),[rt,Be]=i.useState(!1),ce=!!(v||x||s||r||m||M||X||ke||Z||q||xe||ze||B||A||se||E||K||Ve||rt),Re=i.useCallback(()=>a(!0),[]),Le=i.useCallback(()=>a(!1),[]),ct=i.useCallback(()=>o(!0),[]),Ue=i.useCallback(bt=>{c(bt),o(!0)},[]),ue=i.useCallback(()=>{const bt=n[0];bt&&(u(bt.id),o(!0))},[n]),oe=i.useCallback(bt=>{u(bt),o(!0)},[]),Ee=i.useCallback(()=>{o(!1),c(null),u(void 0)},[]),ft=i.useCallback(bt=>{p(bt),h(!0)},[]),ht=i.useCallback(bt=>{w(bt),h(!0)},[]),tt=i.useCallback(()=>{h(!1),p(null),w(void 0)},[]),xt=i.useCallback((bt,Ot="definition",en)=>{b(bt),S(Ot),C(en?.origin??null)},[]),Me=i.useCallback(bt=>{b(bt),S("changes"),C(null)},[]),Ye=i.useCallback(bt=>{b(Ot=>Ot&&{...Ot,...bt})},[]),dt=i.useCallback(()=>{b(null),C(null)},[]),wt=i.useCallback(bt=>{F(bt),N(!0)},[]),St=i.useCallback(()=>{N(!1),F(void 0)},[]),Fe=i.useCallback(()=>_(!0),[]),J=i.useCallback(()=>_(!1),[]),me=i.useCallback(()=>U(!0),[]),Ze=i.useCallback(()=>U(!1),[]),be=i.useCallback(bt=>{Q(bt??null),T(!0)},[]),gt=i.useCallback(()=>{T(!1),Q(null)},[]),$t=i.useCallback(()=>O(!0),[]),Ie=i.useCallback(()=>O(!1),[]),ge=i.useCallback(()=>{D(bt=>!bt)},[]),st=i.useCallback(()=>{D(!1),k(void 0)},[]),yt=i.useCallback((bt,Ot)=>{bt&&je(bt),fe(Ot??null),le(!0)},[]),pt=i.useCallback(()=>{le(!1),fe(null)},[]),vt=i.useCallback(()=>He(!0),[]),Ut=i.useCallback(()=>He(!1),[]),Dt=i.useCallback(bt=>{je(bt)},[]),nn=i.useCallback(()=>re(!0),[]),on=i.useCallback(()=>re(!1),[]),sn=i.useCallback(()=>L(!0),[]),ln=i.useCallback(()=>L(!1),[]),xn=i.useCallback(()=>he(!0),[]),qt=i.useCallback(()=>he(!1),[]),Qt=i.useCallback(()=>pe(!0),[]),hn=i.useCallback(()=>pe(!1),[]),Zt=i.useCallback(()=>ae(!0),[]),ve=i.useCallback(()=>ae(!1),[]),Pe=i.useCallback(async(bt,Ot)=>{ae(!1),k(Ot),D(!0)},[]),Ke=i.useCallback(()=>Te(!0),[]),at=i.useCallback(()=>Te(!1),[]),We=i.useCallback(()=>Be(!0),[]),It=i.useCallback(()=>Be(!1),[]),Lt=i.useCallback((bt,Ot)=>{Ot(`Created ${bt.id} from planning mode`,"success"),o(!1),c(null)},[]),Bt=i.useCallback((bt,Ot)=>{const en=bt.map(Kt=>Kt.id).join(", ");Ot(`Created ${en} from planning mode`,"success"),o(!1),c(null)},[]),Gt=i.useCallback((bt,Ot)=>{const en=bt.map(Kt=>Kt.id).join(", ");Ot(`Created ${en} from subtask breakdown`,"success"),h(!1),p(null)},[]);return{newTaskModalOpen:s,isPlanningOpen:r,planningInitialPlan:l,planningResumeSessionId:d,isSubtaskOpen:m,subtaskInitialDescription:f,subtaskResumeSessionId:g,detailTask:v,detailTaskInitialTab:y,detailTaskOrigin:j,settingsOpen:x,settingsInitialSection:R,schedulesOpen:E,githubImportOpen:K,usageOpen:A,usageAnchorRect:H,systemStatsOpen:se,terminalOpen:M,terminalInitialCommand:$,filesOpen:X,todosOpen:ke,fileBrowserWorkspace:ye,fileBrowserInitialFile:ne,activityLogOpen:Z,gitManagerOpen:q,workflowStepsOpen:xe,agentsOpen:B,scriptsOpen:ze,setupWizardOpen:Ve,modelOnboardingOpen:rt,anyModalOpen:ce,openNewTask:Re,closeNewTask:Le,openPlanning:ct,openPlanningWithInitialPlan:Ue,resumePlanning:ue,openPlanningWithSession:oe,closePlanning:Ee,openSubtaskBreakdown:ft,openSubtaskWithSession:ht,closeSubtask:tt,openDetailTask:xt,openDetailWithChangesTab:Me,updateDetailTask:Ye,closeDetailTask:dt,openSettings:wt,closeSettings:St,openSchedules:Fe,closeSchedules:J,openGitHubImport:me,closeGitHubImport:Ze,openUsage:be,closeUsage:gt,openSystemStats:$t,closeSystemStats:Ie,toggleTerminal:ge,closeTerminal:st,openFiles:yt,closeFiles:pt,openTodos:vt,closeTodos:Ut,setFileWorkspace:Dt,openActivityLog:nn,closeActivityLog:on,openGitManager:sn,closeGitManager:ln,openWorkflowSteps:xn,closeWorkflowSteps:qt,openAgents:Qt,closeAgents:hn,openScripts:Zt,closeScripts:ve,runScript:Pe,openSetupWizard:Ke,closeSetupWizard:at,openModelOnboarding:We,closeModelOnboarding:It,onPlanningTaskCreated:Lt,onPlanningTasksCreated:Bt,onSubtaskTasksCreated:Gt}}function uz(e){const[n,s]=i.useState(2),[a,r]=i.useState("."),[o,l]=i.useState(!0),[c,d]=i.useState(!1),[u,m]=i.useState(!1),[h,f]=i.useState(void 0),[p,g]=i.useState(7200*1e3),[w,v]=i.useState(!1),[b,y]=i.useState(!1),[S,j]=i.useState(!1),[C,x]=i.useState({}),[N,R]=i.useState(!1),[F,E]=i.useState(!1),[_,K]=i.useState(!1),[U,A]=i.useState(!1),[T,H]=i.useState(!0),Q=i.useCallback(async()=>{const[k,X]=await Promise.allSettled([Xj(e),kc(e)]);if(k.status==="fulfilled"&&(s(k.value.maxConcurrent),r(k.value.rootDir)),X.status==="fulfilled"){const le=X.value;l(!!le.autoMerge),d(!!le.globalPause),m(!!le.enginePaused),y(!!le.prAuthAvailable),f(le.taskStuckTimeoutMs),g(le.staleHighFanoutBlockerAgeThresholdMs??7200*1e3),v(le.showQuickChatFAB===!0),x(le.experimentalFeatures??{});const ke=le.experimentalFeatures??{};R(ke.insights===!0),E(ke.memoryView===!0),K(ke.devServerView===!0||ke.devServer===!0),A(ke.todoView===!0);const He=le.autoReloadOnVersionChange!==!1;H(He),zc(He)}j(!0)},[e]);i.useEffect(()=>{j(!1),x({}),R(!1),E(!1),K(!1),A(!1),Q()},[Q]);const se=i.useCallback(async()=>{const k=!o;l(k);try{await sl({autoMerge:k},e)}catch{l(!k)}},[o,e]),O=i.useCallback(async()=>{const k=!c;d(k);try{await sl({globalPause:k,globalPauseReason:k?"manual":void 0},e)}catch{d(!k)}},[c,e]),M=i.useCallback(async()=>{const k=!u;m(k);try{await sl({enginePaused:k},e)}catch{m(!k)}},[u,e]),D=i.useCallback(async()=>{const k=!w;v(k);try{await sl({showQuickChatFAB:k},e)}catch{v(!k)}},[w,e]),$=i.useCallback(async()=>{const k=!T;H(k),zc(k);try{await Bn({autoReloadOnVersionChange:k})}catch{H(!k),zc(!k)}},[T]);return{maxConcurrent:n,rootDir:a,autoMerge:o,globalPaused:c,enginePaused:u,taskStuckTimeoutMs:h,staleHighFanoutBlockerAgeThresholdMs:p,showQuickChatFAB:w,prAuthAvailable:b,settingsLoaded:S,experimentalFeatures:C,insightsEnabled:N,memoryEnabled:F,devServerEnabled:_,todosEnabled:U,autoReloadOnVersionChange:T,toggleAutoMerge:se,toggleGlobalPause:O,toggleEnginePause:M,toggleShowQuickChatFAB:D,toggleAutoReloadOnVersionChange:$,refresh:Q}}function mz(e){const{projectId:n,projects:s,projectsLoading:a,currentProject:r,setCurrentProject:o,addToast:l,openTaskDetail:c,closeTaskDetail:d}=e,u=i.useRef(!1),m=i.useRef(!1),h=i.useRef(null);return i.useEffect(()=>{if(!m.current){const b=window.location.pathname.match(/^\/tasks\/([A-Z]+-\d+)\/?$/);if(b){const y=b[1];if(/^[A-Z]+-\d+$/.test(y)){const S=new URLSearchParams(window.location.search);S.set("task",y);const j=S.toString(),C=window.history.state??{};window.history.replaceState(C,"",j?`/?${j}`:"/"),m.current=!0}}}const p=new URLSearchParams(window.location.search),g=p.get("project"),w=p.get("task");if(!w||a)return;if(g){const b=s.find(y=>y.id===g);if(!b){l(`Project '${g}' not found`,"error");return}r?.id!==b.id&&o(b)}if(u.current)return;u.current=!0,Ba(w,g??n).then(b=>{c(b),h.current=w}).catch(()=>{l(`Task ${w} not found`,"error")})},[n,s,a,r,o,l,c]),{handleDetailClose:i.useCallback(()=>{if(h.current){const p=new URLSearchParams(window.location.search);p.delete("task");const g=p.toString(),w=window.history.state??{};window.history.replaceState(w,"",g?`${window.location.pathname}?${g}`:window.location.pathname),h.current=null}d()},[d])}}function hz(){const[e,n]=i.useState([]),[s,a]=i.useState([]),[r,o]=i.useState([]),l=i.useRef(s),c=i.useRef(r);i.useEffect(()=>{Ws().then(m=>{n(m.models),l.current=m.favoriteProviders,c.current=m.favoriteModels,a(m.favoriteProviders),o(m.favoriteModels)}).catch(()=>{})},[]),i.useEffect(()=>{l.current=s},[s]),i.useEffect(()=>{c.current=r},[r]);const d=i.useCallback(async m=>{const h=l.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];l.current=p,a(()=>p);try{await Bn({favoriteProviders:p,favoriteModels:c.current})}catch(g){throw l.current=h,a(()=>h),g}},[]),u=i.useCallback(async m=>{const h=c.current,p=h.includes(m)?h.filter(g=>g!==m):[m,...h];c.current=p,o(()=>p);try{await Bn({favoriteProviders:l.current,favoriteModels:p})}catch(g){throw c.current=h,o(()=>h),g}},[]);return{availableModels:e,favoriteProviders:s,favoriteModels:r,toggleFavoriteProvider:d,toggleFavoriteModel:u}}function pz({projectId:e,setupWizardOpen:n,openModelOnboarding:s,openSettings:a}){const r=i.useRef(!1),o=i.useRef(n);o.current=n,i.useEffect(()=>{if(n||!e||r.current)return;r.current=!0;let l=!1,c=!1;Po().then(({providers:d})=>{const u=d.some(h=>h.authenticated);if(d.length>0&&!u||d.length>0&&u)return na().then(h=>{const f=!!(h.defaultProvider&&h.defaultModelId);(h.modelOnboardingComplete===!1||h.modelOnboardingComplete===void 0)&&(!u||!f)&&!Lr()?l=!0:!u&&!Lr()&&(c=!0)})}).then(()=>{if(o.current){r.current=!1;return}l?(pi("onboarding:auto-triggered",{trigger:"first-run"}),s()):c&&(pi("onboarding:auto-triggered",{trigger:"missing-provider"}),a("authentication"))}).catch(()=>{})},[e,n,s,a])}const Dg="kb-update-banner-dismissed";function fz(){const[e,n]=i.useState(!0),[s,a]=i.useState(!1),[r,o]=i.useState(null),[l,c]=i.useState(null),[d,u]=i.useState(!1);i.useEffect(()=>{const h=sessionStorage.getItem(Dg)==="true";u(h);let f=!1;return Zj().then(p=>{f||p.disabled||(a(p.updateAvailable===!0),o(typeof p.latestVersion=="string"?p.latestVersion:null),c(typeof p.currentVersion=="string"?p.currentVersion:null))}).catch(()=>{}).finally(()=>{f||n(!1)}),()=>{f=!0}},[]);const m=i.useCallback(()=>{u(!0),sessionStorage.setItem(Dg,"true")},[]);return{updateAvailable:s,latestVersion:r,currentVersion:l,loading:e,dismissed:d,dismiss:m}}const gz=["board","list","graph","agents","missions","chat","documents","research","evals","skills","mailbox","insights","memory","devserver","dev-server","stash-recovery"];function bz(e){return e!==null&&gz.includes(e)}function Qd(e){return e!==null&&(bz(e)||wr(e))}const xz=Xo("fusion-plugin-roadmap","roadmaps");function Lg(e){return e==="devserver"?"dev-server":e}function Og(e){return e!=="roadmaps"?"board":Rb("fusion-plugin-roadmap","roadmaps")?xz:"board"}function vz(e){const{projectsLoading:n,projectsError:s,currentProjectLoading:a,currentProject:r,projectsLength:o,setupWizardOpen:l,openSetupWizard:c,themeMode:d,setThemeMode:u}=e,[m,h]=i.useState(()=>{if(typeof window<"u"){const b=window.localStorage.getItem("kb-dashboard-view-mode");if(b==="overview"||b==="project")return b}return"overview"}),[f,p]=i.useState(()=>{const b=Gn("kb-dashboard-task-view");return b==="roadmaps"?Og(b):Qd(b)?b:"board"}),g=i.useRef(!1);i.useEffect(()=>{window.localStorage.setItem("kb-dashboard-view-mode",m)},[m]),i.useEffect(()=>{const b=Gn("kb-dashboard-task-view",r?.id);if(b==="roadmaps")p(Og(b));else if(Qd(b)){const y=!g.current&&b==="devserver";p(y?"devserver":Lg(b))}else p("board");r?.id&&(g.current=!0)},[r?.id]),i.useEffect(()=>{fs("kb-dashboard-task-view",f,r?.id)},[r?.id,f]),i.useEffect(()=>{if(typeof window>"u")return;const b=new URLSearchParams(window.location.search).get("view");b&&Qd(b)&&p(Lg(b))},[]),i.useEffect(()=>{n||a||r&&m==="overview"&&h("project")},[n,a,r,m]),i.useEffect(()=>{if(n||a||l||s||o>0||r)return;const b=window.setTimeout(()=>{c()},500);return()=>window.clearTimeout(b)},[n,s,o,a,r,l,c]);const w=i.useCallback(b=>{p(b)},[]),v=i.useCallback(()=>{const b=["dark","light","system"],y=b.indexOf(d),S=b[(y+1)%b.length];u(S)},[d,u]);return{viewMode:m,setViewMode:h,taskView:f,setTaskView:p,handleChangeTaskView:w,handleToggleTheme:v}}const Xd=new Map,yz=6e4;function wz(e){const[n,s]=i.useState([]),[a,r]=i.useState(!0),[o,l]=i.useState(null),[c,d]=i.useState(0),u=i.useRef(!1),m=i.useCallback(()=>{const h=e??"default";Xd.delete(h),d(f=>f+1)},[e]);return i.useEffect(()=>{const h=e??"default";let f=!1;async function p(){const g=Xd.get(h);if(g&&Date.now()<g.expiresAt){if(f)return;s(g.views),r(!1);return}u.current||r(!0),l(null);try{const w=await U0(e);if(f)return;Xd.set(h,{views:w,expiresAt:Date.now()+yz}),s(w)}catch(w){if(f)return;l(w instanceof Error?w.message:"Failed to fetch plugin dashboard views")}finally{f||(r(!1),u.current=!0)}}return p(),()=>{f=!0}},[e,c]),i.useMemo(()=>({views:n,loading:a,error:o,refetch:m}),[n,a,o,m])}function kz({taskView:e,context:n}){return t.jsx(_C,{viewId:e,context:n})}let Fg=!1;function Or(e,n){return function(){return i.createElement("span",null,`Bundled plugin view unavailable: ${e}#${n}`)}}async function jz(){const e="@fusion-plugin-examples/dependency-graph/dashboard-view",n="DependencyGraphDashboardView",a=(await En(()=>import("./dashboard-view-Czurx3BJ.js"),__vite__mapDeps([24,1,25,5,6,26])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}async function Nz(){const e="@fusion-plugin-examples/roadmap/dashboard-view",n="RoadmapDashboardView",a=(await En(()=>import("./dashboard-view-BWGH_fAq.js"),__vite__mapDeps([27,1,25,28])))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}async function Sz(){const e="@fusion-plugin-examples/cli-printing-press/dashboard-view",n="CliPrintingPressWizardView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}catch{return{default:Or(e,n)}}}async function Cz(){const e="@fusion-plugin-examples/cli-printing-press/manage-view",n="CliPrintingPressManageView";try{const a=(await import(e))[n];return a?{default:a}:(console.warn(`[plugin-views] Missing export ${n} from ${e}`),{default:Or(e,n)})}catch{return{default:Or(e,n)}}}function ay(){Fg||(Fg=!0,ll("fusion-plugin-dependency-graph","graph",i.lazy(jz)),ll("fusion-plugin-roadmap","roadmaps",i.lazy(Nz)),ll("fusion-plugin-cli-printing-press","wizard",i.lazy(Sz)),ll("fusion-plugin-cli-printing-press","manage",i.lazy(Cz)))}function Ez(e){const{setCurrentProject:n,clearCurrentProject:s,setViewMode:a,currentProject:r,refreshProjects:o,toggleFavoriteProvider:l,toggleFavoriteModel:c,addToast:d,openSettings:u,openSetupWizard:m,closeSetupWizard:h,closeModelOnboarding:f}=e,p=i.useCallback(R=>{n(R),a("project")},[n,a]),g=i.useCallback(()=>{s(),a("overview")},[s,a]),w=i.useCallback(()=>{u()},[u]),v=i.useCallback(()=>{m()},[m]),b=i.useCallback(R=>{h(),n(R),a("project"),d(`Project ${R.name} registered successfully`,"success"),o()},[h,n,a,d,o]),y=i.useCallback(()=>{f()},[f]),S=i.useCallback(async R=>{try{await j1(R.id),d(`Project ${R.name} paused`,"success"),await o()}catch{d(`Failed to pause project ${R.name}`,"error")}},[d,o]),j=i.useCallback(async R=>{try{await N1(R.id),d(`Project ${R.name} resumed`,"success"),await o()}catch{d(`Failed to resume project ${R.name}`,"error")}},[d,o]),C=i.useCallback(async R=>{try{await vb(R.id),d(`Project ${R.name} removed`,"success"),r?.id===R.id&&(s(),a("overview")),await o()}catch{d(`Failed to remove project ${R.name}`,"error")}},[r,s,a,d,o]),x=i.useCallback(async R=>{try{await l(R)}catch{d("Failed to update favorites","error")}},[l,d]),N=i.useCallback(async R=>{try{await c(R)}catch{d("Failed to update model favorites","error")}},[c,d]);return{handleSelectProject:p,handleViewAllProjects:g,handleOpenSettings:w,handleAddProject:v,handleSetupComplete:b,handleModelOnboardingComplete:y,handlePauseProject:S,handleResumeProject:j,handleRemoveProject:C,handleToggleFavorite:x,handleToggleModelFavorite:N}}function _z(e){const{createTask:n,ingestCreatedTasks:s,onPlanningTaskCreated:a,onPlanningTasksCreated:r,onSubtaskTasksCreated:o,addToast:l}=e,c=i.useCallback(async p=>n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),d=i.useCallback(async p=>await n({...p,column:"triage",source:{sourceType:"dashboard_ui"}}),[n]),u=i.useCallback(p=>{s([p]),a(p,l)},[l,s,a]),m=i.useCallback(p=>{s(p),r(p,l)},[l,s,r]),h=i.useCallback(p=>{s(p),o(p,l)},[l,s,o]),f=i.useCallback(p=>{l(`Imported ${p.id} from GitHub`,"success")},[l]);return{handleBoardQuickCreate:c,handleModalCreate:d,handlePlanningTaskCreated:u,handlePlanningTasksCreated:m,handleSubtaskTasksCreated:h,handleGitHubImport:f}}function Mz(e,n){const{projectId:s,searchQuery:a}=n??{},[r,o]=i.useState([]),[l,c]=i.useState([]),[d,u]=i.useState(null),[m,h]=i.useState(!1),[f,p]=i.useState(null),g=i.useRef(null),w=i.useCallback(async()=>{if(!e){o([]),c([]),u(null),h(!1),p(null);return}g.current?.abort();const b=new AbortController;g.current=b,h(!0),p(null);try{const y=[Q0(e),X0(e)];s&&(y.push(Z0(e,s,a)),y.push(eC(e,s)));const S=await Promise.allSettled(y);if(b.signal.aborted)return;const j=S[0],C=S[1];if(j.status==="rejected"){p(`Failed to fetch node health: ${j.reason}`),h(!1);return}if(u(j.value),C.status==="rejected"){p(`Failed to fetch projects: ${C.reason}`),h(!1);return}if(o(C.value),s&&S[2]){const x=S[2];if(x.status==="rejected"){p(`Failed to fetch tasks: ${x.reason}`),h(!1);return}x.status==="fulfilled"&&c(x.value)}h(!1)}catch(y){b.signal.aborted||(p(y instanceof Error?y.message:"Unknown error"),h(!1))}},[e,s,a]);i.useEffect(()=>(w(),()=>{g.current?.abort()}),[w]);const v=i.useCallback(()=>{w()},[w]);return{projects:r,tasks:l,health:d,loading:m,error:f,refresh:v}}function Az(e){const[n,s]=i.useState(!1),[a,r]=i.useState(null);return i.useEffect(()=>{if(!e){s(!1),r(null);return}const o=`/api/proxy/${encodeURIComponent(e)}/events`;return yi(o,{events:{"task:created":l=>{r({type:"task:created",data:l.data})},"task:moved":l=>{r({type:"task:moved",data:l.data})},"task:updated":l=>{r({type:"task:updated",data:l.data})},"task:deleted":l=>{r({type:"task:deleted",data:l.data})},"task:merged":l=>{r({type:"task:merged",data:l.data})}},onOpen:()=>s(!0),onError:()=>s(!1)})},[e]),{isConnected:n,lastEvent:a}}const Rz="fusion-dashboard-current-node",ry=i.createContext(null);function Iz({children:e}){const[n,s]=i.useState(null),[a,r]=i.useState(!0),o=i.useRef(!1),l=i.useRef(void 0);i.useEffect(()=>{let m=!1;async function h(){try{const f=await na();if(m)return;l.current=f.dashboardCurrentNodeId;const p=f.dashboardCurrentNodeId;if(p&&(o.current=!0),!p)try{const g=localStorage.getItem(Rz);if(g){const w=JSON.parse(g);w?.id&&w?.type==="remote"&&(l.current=w.id,await Bn({dashboardCurrentNodeId:w.id}).catch(()=>{}))}}catch{}}catch{}finally{m||r(!1)}}return h(),()=>{m=!0}},[]),i.useEffect(()=>{if(!a)if(n&&n.type==="remote"&&n.id){const m=n.id;l.current!==m&&(l.current=m,Bn({dashboardCurrentNodeId:m}).catch(()=>{}))}else n===null&&l.current!==void 0&&(l.current=void 0,Bn({dashboardCurrentNodeId:void 0}).catch(()=>{}))},[n,a]);const c=i.useCallback(m=>{s(m)},[]),d=i.useCallback(()=>{s(null),l.current=void 0,Bn({dashboardCurrentNodeId:void 0}).catch(()=>{})},[]),u={currentNode:n,currentNodeId:n?.id??null,isRemote:n!==null&&n.type==="remote",setCurrentNode:c,clearCurrentNode:d};return t.jsx(ry.Provider,{value:u,children:e})}function Tz(){const e=i.useContext(ry);if(e===null)throw new Error("useNodeContext must be used within a NodeProvider");return e}const Pz=["shellKind","shellMode","profileId","serverBaseUrl","serverLabel","shellCanOpenConnectionManager","hostKind","mode","connectionId","serverUrl","canOpenConnectionManager"],$z=["__FUSION_SHELL_HOST_CONTEXT__","__fusionShellHostContext","__FUSION_SHELL_CONTEXT__"];let hc=null,zg=!1;function Dz(e){if(typeof e=="boolean")return e;if(typeof e=="string"){if(e==="1"||e==="true")return!0;if(e==="0"||e==="false")return!1}}function Lz(e){if(!(typeof e!="string"||e.trim().length===0))try{const n=new URL(e);return n.protocol!=="http:"&&n.protocol!=="https:"?void 0:n.toString().replace(/\/$/,"")}catch{return}}function oy(e){if(e==="browser"||e==="desktop-shell"||e==="mobile-shell")return e;if(e==="desktop")return"desktop-shell";if(e==="mobile")return"mobile-shell"}function Oz(e){return e==="local"||e==="remote"?e:void 0}function ly(e){const n=Oz(e.mode),s=typeof e.connectionId=="string"&&e.connectionId.trim()?e.connectionId:void 0,a=Lz(e.serverUrl),r=Dz(e.canOpenConnectionManager);return{kind:e.kind,...n?{mode:n}:{},...s?{connectionId:s}:{},...a?{serverUrl:a}:{},...r!==void 0?{canOpenConnectionManager:r}:{}}}function Fz(e){for(const n of $z){const s=e[n];if(!s||typeof s!="object")continue;const a=s,r=oy(a.kind??a.shellKind??a.hostKind);if(r)return r==="browser"?{kind:r}:ly({kind:r,mode:a.mode??a.shellMode,connectionId:a.connectionId??a.profileId,serverUrl:a.serverUrl??a.serverBaseUrl,canOpenConnectionManager:a.canOpenConnectionManager??a.shellCanOpenConnectionManager})}return null}function zz(e){let n;try{n=new URL(e.location.href)}catch{return null}const s=n.searchParams,a=oy(s.get("hostKind")??s.get("kind")??s.get("shellKind"));return a?a==="browser"?{kind:a}:ly({kind:a,mode:s.get("mode")??s.get("shellMode"),connectionId:s.get("connectionId")??s.get("profileId"),serverUrl:s.get("serverUrl")??s.get("serverBaseUrl"),canOpenConnectionManager:s.get("canOpenConnectionManager")??s.get("shellCanOpenConnectionManager")}):null}function Bz(e){try{const n=new URL(e.location.href);let s=!1;for(const r of Pz)n.searchParams.has(r)&&(n.searchParams.delete(r),s=!0);if(!s)return;const a=n.pathname+(n.search?n.search:"")+n.hash;e.history.replaceState(e.history.state,"",a)}catch{}}function Uz(e=window){const n=Fz(e);if(n)return n;const s=zz(e);return s||(typeof e.fusionAPI<"u"?{kind:"desktop-shell"}:{kind:"browser"})}function cy(e=window){return!zg&&typeof window<"u"&&(hc=Uz(e),Bz(e),zg=!0),hc??{kind:"browser"}}function Hz(){return hc||(typeof window>"u"?{kind:"browser"}:cy(window))}const qz={kind:"browser"},dy=i.createContext({host:qz,isNativeShell:!1,kind:"browser"});function Vz(e){const n=e.kind!=="browser";return{host:e,isNativeShell:n,kind:e.kind,...n?{mode:e.mode,connectionId:e.connectionId,serverUrl:e.serverUrl,canOpenConnectionManager:e.canOpenConnectionManager}:{}}}function Wz({children:e}){const n=i.useMemo(()=>Vz(Hz()),[]);return t.jsx(dy.Provider,{value:n,children:e})}function Gz(){return i.useContext(dy)}function Kz(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function Jz({open:e,shellApi:n,shellState:s,onComplete:a}){const[r,o]=i.useState(s.desktopMode??"remote"),[l,c]=i.useState("Remote Server"),[d,u]=i.useState(""),[m,h]=i.useState(""),[f,p]=i.useState(null),[g,w]=i.useState(!1),[v,b]=i.useState(!1),y=s.host==="desktop-shell";i.useEffect(()=>{y&&o(s.desktopMode??"remote")},[y,s.desktopMode]);const S=i.useMemo(()=>y&&r==="local"?!0:d.trim().length>0,[y,r,d]);return e?t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-onboarding-modal",children:[t.jsx("div",{className:"modal-header",children:t.jsx("h2",{children:"Welcome to Fusion"})}),t.jsxs("div",{className:"native-shell-onboarding-body",children:[t.jsx("p",{children:"Fusion helps you plan, run, and review AI-assisted engineering work."}),y&&t.jsxs("div",{className:"native-shell-onboarding-mode-row",children:[t.jsx("button",{type:"button",className:`btn ${r==="local"?"btn-primary":""}`,onClick:()=>o("local"),children:"Local Fusion"}),t.jsx("button",{type:"button",className:`btn ${r==="remote"?"btn-primary":""}`,onClick:()=>o("remote"),children:"Remote Server"})]}),(!y||r==="remote")&&t.jsxs(t.Fragment,{children:[t.jsx("button",{type:"button",className:"btn",onClick:async()=>{p(null),w(!0);try{const j=await n.startQrScan();u(j.serverUrl),h(j.authToken??"")}catch(j){p(j.message)}finally{w(!1)}},disabled:g,children:g?"Scanning…":"Scan QR"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-profile-name",children:"Profile name"}),t.jsx("input",{id:"native-shell-onboarding-profile-name",className:"input",value:l,onChange:j=>c(j.target.value)}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-server-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-onboarding-server-url",className:"input",value:d,onChange:j=>u(j.target.value),placeholder:"https://your-fusion-host"}),t.jsx("label",{className:"native-shell-onboarding-label",htmlFor:"native-shell-onboarding-auth-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-onboarding-auth-token",className:"input",type:"password",value:m,onChange:j=>h(j.target.value)})]}),f&&t.jsx("p",{className:"form-error",role:"alert",children:f})]}),t.jsx("div",{className:"modal-actions",children:t.jsx("button",{type:"button",className:"btn btn-primary",disabled:!S||v,onClick:async()=>{p(null),b(!0);try{if(y&&r==="local"){await n.setDesktopMode("local"),a();return}const j=await n.saveProfile({name:l.trim()||"Remote Server",serverUrl:d,authToken:m||null});if(y&&await n.setDesktopMode("remote"),await n.setActiveProfile(j.id),typeof window<"u"&&s.host!=="web"){window.location.href=Kz(j.serverUrl,j.authToken??null);return}a()}catch(j){p(j.message)}finally{b(!1)}},children:v?"Saving…":"Continue"})})]})}):null}function Yz({open:e,shellApi:n,shellState:s,onClose:a}){const r=i.useMemo(()=>s.profiles.find(x=>x.id===s.activeProfileId)??null,[s.activeProfileId,s.profiles]),[o,l]=i.useState(null),[c,d]=i.useState({}),[u,m]=i.useState(null),[h,f]=i.useState(null);if(!e)return null;const p=o==="__new__",g=p?null:s.profiles.find(x=>x.id===o)??r,w=c.name??g?.name??"",v=c.serverUrl??g?.serverUrl??"",b=c.authToken??g?.authToken??"",y=()=>{l(null),d({}),f(null)},S=async()=>{f(null);try{const x=new URL(v.trim());if(!/^https?:$/.test(x.protocol))throw new Error("Server URL must use http or https");const N=await n.saveProfile({id:p?void 0:o??g?.id,name:w||"Remote Server",serverUrl:v,authToken:b||null});await n.setActiveProfile(N.id),l(N.id),d({})}catch(x){f(x.message)}},j=async()=>{f(null);try{const x=await n.startQrScan();l("__new__"),d({name:"",serverUrl:x.serverUrl,authToken:x.authToken??""})}catch(x){f(x.message)}},C=async()=>{u&&(await n.deleteProfile(u.id),m(null),y())};return t.jsx("div",{className:"modal-overlay open",children:t.jsxs("div",{className:"modal native-shell-connection-manager",role:"dialog","aria-label":"Connection Manager",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h2",{children:"Connection Manager"}),t.jsx("button",{type:"button",className:"modal-close",onClick:a,"aria-label":"Close",children:"×"})]}),s.host==="desktop-shell"&&t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:`btn ${s.desktopMode==="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("local"),children:"Local"}),t.jsx("button",{type:"button",className:`btn ${s.desktopMode!=="local"?"btn-primary":""}`,onClick:()=>void n.setDesktopMode("remote"),children:"Remote"})]}),t.jsx("div",{className:"native-shell-connection-manager__profiles",children:s.profiles.length===0?t.jsxs("div",{className:"card native-shell-connection-manager__empty-state",children:[t.jsx("p",{className:"settings-muted",children:"No remote servers saved yet."}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add server"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void j(),children:"Scan QR"})]})]}):s.profiles.map(x=>t.jsxs("div",{className:"card native-shell-connection-manager__profile",children:[t.jsxs("div",{children:[t.jsx("strong",{children:x.name}),t.jsx("div",{className:"settings-muted",children:x.serverUrl}),x.id===s.activeProfileId&&t.jsx("span",{className:"native-shell-connection-manager__active-pill",children:"Active"})]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Edit ${x.name}`,onClick:()=>{l(x.id),d(x)},children:"Edit"}),t.jsx("button",{type:"button",className:"btn btn-sm","aria-label":`Use ${x.name}`,onClick:()=>void n.setActiveProfile(x.id),children:"Use"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger","aria-label":`Delete ${x.name}`,onClick:()=>m(x),children:"Delete"})]})]},x.id))}),t.jsxs("div",{className:"native-shell-connection-manager__mode-row",children:[t.jsx("button",{type:"button",className:"btn",onClick:()=>{l("__new__"),d({name:"",serverUrl:"",authToken:""}),f(null)},children:"Add connection"}),s.host==="mobile-shell"&&t.jsx("button",{type:"button",className:"btn",onClick:()=>void j(),children:"Scan QR"})]}),t.jsxs("div",{className:"form-group native-shell-connection-manager__editor",children:[t.jsx("label",{htmlFor:"native-shell-connection-manager-name",children:"Name"}),t.jsx("input",{id:"native-shell-connection-manager-name",className:"input",value:w,onChange:x=>d(N=>({...N,name:x.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-url",children:"Server URL"}),t.jsx("input",{id:"native-shell-connection-manager-url",className:"input",value:v,onChange:x=>d(N=>({...N,serverUrl:x.target.value}))}),t.jsx("label",{htmlFor:"native-shell-connection-manager-token",children:"Auth token (optional)"}),t.jsx("input",{id:"native-shell-connection-manager-token",className:"input",type:"password",value:b??"",onChange:x=>d(N=>({...N,authToken:x.target.value}))}),h&&t.jsx("p",{className:"form-error",role:"alert",children:h})]}),u&&t.jsxs("div",{className:"native-shell-connection-manager__delete-confirm",role:"alertdialog","aria-label":"Delete server confirmation",children:[t.jsxs("p",{children:["Delete ",t.jsx("strong",{children:u.name}),"? This removes the saved profile."]}),t.jsxs("div",{className:"native-shell-connection-manager__profile-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>m(null),children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-sm btn-danger",onClick:()=>void C(),children:"Delete"})]})]}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:a,children:"Close"}),t.jsx("button",{type:"button",className:"btn",onClick:y,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void S(),disabled:!v.trim(),children:"Save"})]})]})})}function Qz(e){if(e.hostKind==="desktop-shell"&&e.mode==="local")return{title:"Desktop local mode",actionLabel:"Switch server",dotClassName:"status-dot status-dot--online"};const n=e.profileLabel??e.profileId,s=e.serverOrigin,a=n&&s?`${n} · ${s}`:n??s;return e.mode==="remote"?{title:a??"Connection info unavailable",actionLabel:e.hostKind==="desktop-shell"?"Switch server":"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}:{title:a??"Connection info unavailable",actionLabel:"Manage connections",dotClassName:a?"status-dot status-dot--online":"status-dot status-dot--pending"}}function Bg({status:e,onError:n}){if(e.hostKind==="browser"||!e.available)return null;const s=Qz(e),a=i.useCallback(async()=>{const r=await e.openConnectionManager();!r.ok&&r.reason==="failed"&&n?.(r.error??"Failed to open connection manager")},[n,e]);return t.jsxs("button",{type:"button",className:"btn shell-connection-status",onClick:()=>void a(),"data-testid":"shell-connection-status-button",children:[t.jsx("span",{className:s.dotClassName,"aria-hidden":"true"}),t.jsx("span",{className:"shell-connection-status__kind",children:e.hostKind==="desktop-shell"?"Desktop":"Mobile"}),t.jsx("span",{className:"shell-connection-status__summary",title:s.title,children:s.title}),t.jsx("span",{className:"shell-connection-status__action",children:s.actionLabel})]})}function Xz(e){if(e)try{return new URL(e).origin}catch{return}}function Zz(e,n){const s=e.profiles.find(a=>a.id===e.activeProfileId)??null;return s||(n.kind==="browser"||!n.connectionId?null:e.profiles.find(a=>a.id===n.connectionId)??null)}async function e6(e){if(!e?.getState)return null;try{return await e.getState()}catch{return null}}async function t6(e,n=window){const s=n.fusionAPI,a=n.fusionShell,r=await e6(a),o=r?Zz(r,e):null,l=e.kind==="browser"?void 0:e.mode??r?.desktopMode,c=o?.id??(e.kind==="browser"?void 0:e.connectionId),d=o?.name,u=Xz(o?.serverUrl??(e.kind==="browser"?void 0:e.serverUrl)),m=e.kind==="desktop-shell"&&typeof s?.openConnectionManager=="function",h=e.kind==="mobile-shell"&&typeof a?.openConnectionManager=="function",f=m||h;return{hostKind:e.kind,available:f,...l?{mode:l}:{},...c?{profileId:c}:{},...d?{profileLabel:d}:{},...u?{serverOrigin:u}:{},openConnectionManager:async()=>{try{return m?(await s.openConnectionManager?.(),{ok:!0}):h?(await a.openConnectionManager(),{ok:!0}):{ok:!1,reason:"unsupported"}}catch(p){return{ok:!1,reason:"failed",error:p instanceof Error?p.message:String(p)}}}}}function n6({open:e}){const[n,s]=i.useState(""),a=i.useRef(null);i.useEffect(()=>{e&&a.current?.focus()},[e]);const r=i.useCallback(()=>{const l=n.trim();l&&(Cj(l),window.location.reload())},[n]),o=i.useCallback(()=>{Ej(),window.location.reload()},[]);return e?t.jsx("div",{className:"modal-overlay open auth-token-recovery-overlay",role:"presentation",onKeyDownCapture:l=>{l.key==="Escape"&&(l.preventDefault(),l.stopPropagation())},children:t.jsxs("div",{className:"modal modal-md",role:"dialog","aria-modal":"true","aria-labelledby":"auth-token-recovery-title","aria-describedby":"auth-token-recovery-description",children:[t.jsx("div",{className:"modal-header auth-token-recovery-header",children:t.jsx("h3",{id:"auth-token-recovery-title",children:"Authentication token required"})}),t.jsxs("div",{className:"auth-token-recovery-content",children:[t.jsx("p",{id:"auth-token-recovery-description",children:"This dashboard session can't authenticate with the daemon. Set a replacement token or clear the current token and retry."}),t.jsxs("div",{className:"auth-token-recovery-field",children:[t.jsx("label",{htmlFor:"auth-token-recovery-input",children:"Replacement token"}),t.jsx("input",{ref:a,id:"auth-token-recovery-input",className:"input",type:"password",value:n,onChange:l=>s(l.target.value),placeholder:"Paste token",autoComplete:"off",spellCheck:!1})]})]}),t.jsxs("div",{className:"modal-actions auth-token-recovery-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,children:"Clear token and retry"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:r,disabled:n.trim().length===0,children:"Set token and reload"})]})]})}):null}const s6=200,i6=i.lazy(()=>En(()=>import("./AgentsView-B6IKroR1.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])).then(e=>({default:e.AgentsView}))),a6=i.lazy(()=>En(()=>import("./DocumentsView-C4Ky-ZkQ.js"),__vite__mapDeps([32,1,5,6,33])).then(e=>({default:e.DocumentsView}))),r6=i.lazy(()=>En(()=>import("./InsightsView-BGbXkJpz.js"),__vite__mapDeps([34,1,22,5,6,35])).then(e=>({default:e.InsightsView}))),o6=i.lazy(()=>En(()=>import("./ResearchView-BMxwiVk9.js"),__vite__mapDeps([36,1,5,6,37])).then(e=>({default:e.ResearchView}))),l6=i.lazy(()=>En(()=>import("./EvalsView-B-z_KLLW.js"),__vite__mapDeps([38,1,5,6,39])).then(e=>({default:e.EvalsView}))),c6=i.lazy(()=>En(()=>import("./NodesView-Hjxwv7rE.js"),__vite__mapDeps([40,1,17,30,5,6,41])).then(e=>({default:e.NodesView}))),d6=i.lazy(()=>En(()=>import("./ChatView-DKstOyUm.js"),__vite__mapDeps([42,1,5,6,43])).then(e=>({default:e.ChatView}))),u6=i.lazy(()=>En(()=>import("./SkillsView-COs7muvr.js"),__vite__mapDeps([44,1,5,6,45])).then(e=>({default:e.SkillsView}))),m6=i.lazy(()=>En(()=>import("./MemoryView-CRbaCcG_.js"),__vite__mapDeps([46,1,20,21,5,6,47])).then(e=>({default:e.MemoryView}))),h6=i.lazy(()=>En(()=>import("./DevServerView-DQQcGd2N.js"),__vite__mapDeps([48,1,5,6,49])).then(e=>({default:e.DevServerView})));i.lazy(()=>En(()=>import("./TodoView-CDtkPdrq.js"),__vite__mapDeps([11,1,5,6,12])).then(e=>({default:e.TodoView})));const p6=i.lazy(()=>En(()=>import("./StashRecoveryView-BhB_6Fvq.js"),__vite__mapDeps([50,1,5,6,51])).then(e=>({default:e.StashRecoveryView})));function f6(){(typeof window<"u"&&window.requestIdleCallback||(n=>setTimeout(n,200)))(()=>{En(()=>import("./AgentsView-B6IKroR1.js"),__vite__mapDeps([29,1,3,4,30,15,5,6,31])),En(()=>import("./DocumentsView-C4Ky-ZkQ.js"),__vite__mapDeps([32,1,5,6,33])),En(()=>import("./InsightsView-BGbXkJpz.js"),__vite__mapDeps([34,1,22,5,6,35])),En(()=>import("./ResearchView-BMxwiVk9.js"),__vite__mapDeps([36,1,5,6,37])),En(()=>import("./EvalsView-B-z_KLLW.js"),__vite__mapDeps([38,1,5,6,39])),En(()=>import("./NodesView-Hjxwv7rE.js"),__vite__mapDeps([40,1,17,30,5,6,41])),En(()=>import("./ChatView-DKstOyUm.js"),__vite__mapDeps([42,1,5,6,43])),En(()=>import("./SkillsView-COs7muvr.js"),__vite__mapDeps([44,1,5,6,45])),En(()=>import("./MemoryView-CRbaCcG_.js"),__vite__mapDeps([46,1,20,21,5,6,47])),En(()=>import("./DevServerView-DQQcGd2N.js"),__vite__mapDeps([48,1,5,6,49])),En(()=>import("./TodoView-CDtkPdrq.js"),__vite__mapDeps([11,1,5,6,12])),En(()=>import("./StashRecoveryView-BhB_6Fvq.js"),__vite__mapDeps([50,1,5,6,51]))})}ay();const Zd="kb-setup-warning-dismissed",g6="kb-chat-active-session",Ug="kb-dashboard-working-branch-filter",Hg="kb-dashboard-base-branch-filter",qg="__fusion:no-branch__",uy="fusion:approval-banner-dismissed";function b6(e,n){return e==="awaiting-approval"&&n!=="awaiting-approval"}function Vg(e){if(!e)return 0;const n=Date.parse(e);return Number.isFinite(n)?n:0}function x6(){if(typeof window>"u")return new Map;try{const e=window.localStorage.getItem(uy);if(!e)return new Map;const n=JSON.parse(e),s=new Map;for(const[a,r]of Object.entries(n))typeof r=="number"&&Number.isFinite(r)&&s.set(a,r);return s}catch{return new Map}}function Wg(e){if(!(typeof window>"u"))try{const n={};for(const[s,a]of e)n[s]=a;window.localStorage.setItem(uy,JSON.stringify(n))}catch{}}function v6(e,n){const s=new URL(e);return n&&s.searchParams.set("rt",n),s.toString()}function y6(e,n,s){return!n||s||e.host==="web"?!1:e.host==="mobile-shell"?!e.activeProfileId:e.desktopMode==="local"?!1:!e.activeProfileId}function w6(){const{toasts:e,addToast:n,removeToast:s}=nz(),{shellApi:a,state:r,ready:o,openConnectionManagerSignal:l}=Bv(),c=Gz();i.useEffect(()=>{f6()},[]);const{projects:d,loading:u,error:m,refresh:h}=QF(),{nodes:f}=Cc(),{currentNode:p,currentNodeId:g,isRemote:w,setCurrentNode:v,clearCurrentNode:b}=Tz(),{currentProject:y,setCurrentProject:S,clearCurrentProject:j,loading:C}=ez(d,{nodeId:g}),{hasAiProvider:x,hasGithub:N,loading:R,hasWarnings:F}=Lv(y?.id),{updateAvailable:E,latestVersion:_,currentVersion:K,dismissed:U,dismiss:A}=fz();i.useEffect(()=>{if(g&&!p&&f.length>0){const Je=f.find(Rt=>Rt.id===g);if(Je){v(Je);return}}g&&f.length>0&&(f.some(Rt=>Rt.id===g)||b())},[g,p,f,v,b]);const[T,H]=i.useState(""),[Q,se]=i.useState(""),[O,M]=i.useState("");i.useEffect(()=>{se(Gn(Ug,y?.id)??""),M(Gn(Hg,y?.id)??"")},[y?.id]);const D=i.useCallback(Je=>{se(Je),fs(Ug,Je,y?.id)},[y?.id]),$=i.useCallback(Je=>{M(Je),fs(Hg,Je,y?.id)},[y?.id]),k=Mz(g,{projectId:y?.id,searchQuery:T||void 0});Az(g);const X=w&&k.projects.length>0?k.projects:d,{themeMode:le,colorTheme:ke,dashboardFontScalePct:He,setThemeMode:ye,setColorTheme:je,setDashboardFontScalePct:ne}=cz(),{sessions:fe,generating:Z,needsInput:re,planningSessions:q,dismissSession:L}=UF(y?.id),xe=fe.filter(Je=>Je.status==="awaiting_input"||Je.status==="error"),he=VF(),B=dz({projectId:y?.id,planningSessions:q}),ze=oi()==="mobile",{pushNav:ae,replaceCurrent:Ve}=x$({enabled:!0}),{viewMode:Te,setViewMode:rt,taskView:Be,handleChangeTaskView:ce}=vz({projectsLoading:u,projectsError:m,currentProjectLoading:C,currentProject:y,projectsLength:d.length,setupWizardOpen:B.setupWizardOpen,openSetupWizard:B.openSetupWizard,themeMode:le,setThemeMode:ye}),{views:Re}=wz(y?.id),Le=i.useMemo(()=>{const Je=Re.find(Rt=>Rt.pluginId==="fusion-plugin-dependency-graph"&&Rt.view.viewId==="graph");return Je?`plugin:${Je.pluginId}:${Je.view.viewId}`:Rb("fusion-plugin-dependency-graph","graph")?"plugin:fusion-plugin-dependency-graph:graph":null},[Re]),ct=i.useCallback(Je=>{Je==="missions"&&(Sn(void 0),Jt(void 0),Ne(void 0));const Rt=Be;ce(Je),Rt!==Je&&ae({type:"view",revert:()=>ce(Rt)})},[ce,Be,ae]),Ue=Be==="board"||Be==="list",{tasks:ue,createTask:oe,moveTask:Ee,pauseTask:ft,deleteTask:ht,mergeTask:tt,retryTask:xt,resetTask:Me,updateTask:Ye,duplicateTask:dt,archiveTask:wt,unarchiveTask:St,archiveAllDone:Fe,loadArchivedTasks:J,ingestCreatedTasks:me,lastFetchTimeMs:Ze}=GF({...y?{projectId:y.id}:{},searchQuery:T||void 0,sseEnabled:Ue}),be=w&&k.tasks.length>0?k.tasks:ue,[gt,$t]=i.useState(!1),[Ie,ge]=i.useState(0),st=i.useRef(performance.now()),yt=i.useRef(!1),pt=i.useRef(!1),vt=i.useMemo(()=>u?"projects":C?"project":"tasks",[u,C]);i.useEffect(()=>{if(!u&&!yt.current){yt.current=!0;const Je=`projects loaded at ${Math.round(performance.now()-st.current)}ms from mount`;console.log(`[App] ${Je}`)}if(!C&&!pt.current){pt.current=!0;const Je=`current-project resolved at ${Math.round(performance.now()-st.current)}ms from mount`;console.log(`[App] ${Je}`)}},[u,C]),i.useEffect(()=>{if(gt||u||C)return;const Je=performance.now(),Rt=window.setTimeout(()=>{const rn=`dashboard ready at ${Math.round(performance.now()-st.current)}ms from mount (settle delay=${Math.round(performance.now()-Je)}ms)`;console.log(`[App] ${rn}`),$t(!0)},s6);return()=>{window.clearTimeout(Rt)}},[gt,u,C]);const{keyboardOpen:Ut}=aa({enabled:ze}),Dt=ze&&Ut&&!B.anyModalOpen;Mi(Dt);const[nn,on]=i.useState(0),[sn,ln]=i.useState(0),[xn,qt]=i.useState(!1),[Qt,hn]=i.useState(0),[Zt,ve]=i.useState(null),Pe=i.useRef(new Map),Ke=i.useRef(new Set),at=i.useRef(x6()),We=i.useCallback(()=>{Nb(y?.id).then(Je=>{on(Je.unreadCount),ln(Je.pendingApprovalCount??0)}).catch(Je=>{console.warn("[App] Failed to fetch mailbox unread count:",Je)})},[y?.id]);i.useEffect(()=>{const Je=new Map,Rt=new Set;for(const rn of ue)Je.set(rn.id,rn.status),rn.status==="awaiting-approval"&&Rt.add(`task:${rn.id}`);Pe.current=Je,Ke.current=Rt},[ue]),i.useEffect(()=>{We();const Je=new URLSearchParams;y?.id&&Je.set("projectId",y.id);const Rt=Je.size>0?`?${Je.toString()}`:"",rn=es=>{const Hn=at.current.get(es.dedupeKey);Hn!==void 0&&es.updatedAtMs<=Hn||ve(es)};return yi(`/api/events${Rt}`,{onReconnect:We,events:{"message:sent":We,"message:received":We,"message:read":We,"message:deleted":We,"approval:requested":es=>{We();try{const Hn=JSON.parse(es.data),Bs=Hn.id?`approval:${Hn.id}`:Hn.taskId?`task:${Hn.taskId}`:void 0;if(!Bs||Ke.current.has(Bs))return;Ke.current.add(Bs),rn({dedupeKey:Bs,updatedAtMs:Vg(Hn.updatedAt??Hn.createdAt)})}catch{}},"approval:updated":We,"approval:decided":We,"task:updated":es=>{try{const Hn=JSON.parse(es.data);if(!Hn?.id)return;const Bs=`task:${Hn.id}`,rr=Pe.current.get(Hn.id);if(Pe.current.set(Hn.id,Hn.status),Hn.status!=="awaiting-approval"){Ke.current.delete(Bs),at.current.delete(Bs),Wg(at.current);return}if(Ke.current.has(Bs))return;b6(Hn.status,rr)&&(Ke.current.add(Bs),rn({dedupeKey:Bs,updatedAtMs:Vg(Hn.updatedAt)}),We())}catch{}}}})},[y?.id,We]),i.useEffect(()=>{Be==="chat"&&qt(!1)},[Be]),i.useEffect(()=>{let Je=!1;const Rt=async()=>{try{const es=await I("/stash-recovery/orphans");Je||hn(es.count??0)}catch{Je||hn(0)}};Rt();const rn=window.setInterval(()=>void Rt(),3e4);return()=>{Je=!0,window.clearInterval(rn)}},[y?.id]),i.useEffect(()=>{const Je=new URLSearchParams;y?.id&&Je.set("projectId",y.id);const Rt=Je.size>0?`?${Je.toString()}`:"";return yi(`/api/events${Rt}`,{events:{"chat:message:added":rn=>{try{const es=JSON.parse(rn.data),Hn=Gn(g6,y?.id);if(!Hn||es.role!=="assistant"||Be==="chat"||es.sessionId!==Hn||es.projectId&&y?.id&&es.projectId!==y.id)return;qt(!0)}catch{}}}})},[y?.id,Be]);const It=i.useMemo(()=>Array.from(new Set(be.map(Je=>Je.branch?.trim()).filter(Je=>!!(Je&&Je.length>0)))).sort((Je,Rt)=>Je.localeCompare(Rt)),[be]),Lt=i.useMemo(()=>Array.from(new Set(be.map(Je=>Je.baseBranch?.trim()).filter(Je=>!!(Je&&Je.length>0)))).sort((Je,Rt)=>Je.localeCompare(Rt)),[be]),Bt=i.useMemo(()=>be.filter(Je=>{const Rt=Je.branch?.trim()??"",rn=Je.baseBranch?.trim()??"";if(Q===qg){if(Rt.length>0)return!1}else if(Q.length>0&&Rt!==Q)return!1;if(O===qg){if(rn.length>0)return!1}else if(O.length>0&&rn!==O)return!1;return!0}),[be,Q,O]),[Gt,bt]=i.useState(!1),[Ot,en]=i.useState(!1),[Kt,Sn]=i.useState(void 0),[dn,Jt]=i.useState(void 0),[tn,Ne]=i.useState(void 0),[W,Y]=i.useState(!1),[_e,ut]=i.useState(!1),[At,zt]=i.useState(null),[yn,Zn]=i.useState(()=>Gn(Zd,y?.id)==="true");i.useEffect(()=>{Zn(Gn(Zd,y?.id)==="true")},[y?.id]),i.useEffect(()=>{let Je=!1;return Dj().then(Rt=>{Je||zt(Rt)}).catch(()=>{Je||zt(null)}),()=>{Je=!0}},[]),i.useEffect(()=>{const Je=()=>{ut(!0)};return window.addEventListener(cu,Je),()=>{window.removeEventListener(cu,Je)}},[]);const vn=i.useCallback(()=>{fs(Zd,"true",y?.id),Zn(!0)},[y?.id]),{maxConcurrent:Dn,autoMerge:de,globalPaused:nt,enginePaused:ot,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,showQuickChatFAB:Oe,prAuthAvailable:Mt,settingsLoaded:Xt,experimentalFeatures:_n,insightsEnabled:Pn,memoryEnabled:kn,devServerEnabled:Vn,todosEnabled:$s,toggleAutoMerge:vs,toggleGlobalPause:As,toggleEnginePause:bn,refresh:Ht}=uz(y?.id),On=_n.skillsView===!0,Fn=_n.nodesView===!0,as=_n.researchView===!0,Wn=_n.evalsView===!0,Rs=_n.agentOnboarding===!0,In=!0,rs=i.useCallback(()=>{B.closeSettings(),ge(Je=>Je+1),Ht()},[B,Ht]);i.useEffect(()=>{if(Xt&&!wr(Be)){if(Be==="graph"&&!Le){ce("board");return}Be==="skills"&&!On&&ce("board"),Be==="insights"&&!Pn&&ce("board"),Be==="memory"&&!kn&&ce("board"),(Be==="devserver"||Be==="dev-server")&&!Vn&&ce("board"),Be==="research"&&!as&&ce("board"),Be==="evals"&&!Wn&&ce("board")}},[Be,Xt,On,Pn,ce,In,kn,Vn,as,Wn,Le]),i.useEffect(()=>{Gt&&!Fn&&bt(!1)},[Gt,Fn]);const{availableModels:Ns,favoriteProviders:ys,favoriteModels:cs,toggleFavoriteProvider:ss,toggleFavoriteModel:te}=hz();pz({projectId:y?.id,setupWizardOpen:B.setupWizardOpen,openModelOnboarding:B.openModelOnboarding,openSettings:B.openSettings});const{handleSelectProject:we,handleViewAllProjects:P,handleAddProject:Ce,handleSetupComplete:qe,handleModelOnboardingComplete:et,handlePauseProject:mt,handleResumeProject:Nt,handleRemoveProject:Pt,handleToggleFavorite:an,handleToggleModelFavorite:Cn}=Ez({setCurrentProject:S,clearCurrentProject:j,setViewMode:rt,currentProject:y,refreshProjects:h,toggleFavoriteProvider:ss,toggleFavoriteModel:te,addToast:n,openSettings:B.openSettings,openSetupWizard:B.openSetupWizard,closeSetupWizard:B.closeSetupWizard,closeModelOnboarding:B.closeModelOnboarding}),{handleDetailClose:ie}=mz({projectId:y?.id,projects:d,projectsLoading:u,currentProject:y,setCurrentProject:S,addToast:n,openTaskDetail:B.openDetailTask,closeTaskDetail:B.closeDetailTask}),$e=i.useCallback(async({insightId:Je,title:Rt,description:rn})=>{await oe({title:Rt,description:rn,column:"triage",source:{sourceType:"dashboard_ui",sourceMetadata:{origin:"insights",insightId:Je}}})},[oe]),{handleBoardQuickCreate:Qe,handleModalCreate:Ft,handlePlanningTaskCreated:cn,handlePlanningTasksCreated:pn,handleSubtaskTasksCreated:jn,handleGitHubImport:Un}=_z({createTask:oe,ingestCreatedTasks:me,onPlanningTaskCreated:B.onPlanningTaskCreated,onPlanningTasksCreated:B.onPlanningTasksCreated,onSubtaskTasksCreated:B.onSubtaskTasksCreated,addToast:n}),gs=i.useCallback((Je,Rt)=>{Rt==="changes"?B.openDetailWithChangesTab(Je):B.openDetailTask(Je,Rt),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),bs=i.useCallback(async Je=>{try{const Rt=await Ba(Je,y?.id);B.openDetailTask(Rt,"logs"),ae({type:"modal",close:B.closeDetailTask})}catch(Rt){n(`Failed to open task logs: ${Rt.message}`,"error")}},[B,y?.id,n,ae]),[is,ds]=i.useState([]);i.useEffect(()=>{let Je=!1;return Ko(y?.id).then(Rt=>{Je||ds(Rt)}).catch(()=>{Je||ds([])}),()=>{Je=!0}},[y?.id]);const xs=i.useMemo(()=>new Map(is.map(Je=>[Je.id,Je.name])),[is]);i.useCallback(()=>{Fn&&bt(Je=>!Je)},[Fn]);const ra=i.useCallback(()=>{Fn&&(Gt?bt(!1):(bt(!0),ae({type:"view",revert:()=>bt(!1)})))},[Fn,Gt,ae]),Jn=i.useCallback((Je,Rt,rn)=>{B.openDetailTask(Je,Rt,rn),ae({type:"modal",close:B.closeDetailTask})},[B,ae]),Ui=i.useCallback(Je=>{B.openSettings(Je),ae({type:"modal",close:rs})},[B,ae,rs]),Hi=i.useCallback(()=>{B.openNewTask(),ae({type:"modal",close:B.closeNewTask})},[B,ae]),Zs=i.useCallback(()=>{B.openPlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),ja=i.useCallback(Je=>{B.openPlanningWithInitialPlan(Je),ae({type:"modal",close:B.closePlanning})},[B,ae]),Na=i.useCallback(()=>{B.resumePlanning(),ae({type:"modal",close:B.closePlanning})},[B,ae]),Ya=i.useCallback(Je=>{B.openSubtaskBreakdown(Je),ae({type:"modal",close:B.closeSubtask})},[B,ae]),Qa=i.useCallback(()=>{B.openGitHubImport(),ae({type:"modal",close:B.closeGitHubImport})},[B,ae]),Mn=i.useCallback(()=>{B.terminalOpen?B.toggleTerminal():(B.toggleTerminal(),ae({type:"modal",close:B.closeTerminal}))},[B,ae]),ci=i.useCallback((Je,Rt)=>{B.openFiles(Je,Rt),ae({type:"modal",close:B.closeFiles})},[B,ae]),wi=i.useCallback((Je,Rt)=>{B.openFiles(Rt?.workspace,Je),ae({type:"modal",close:B.closeFiles})},[B,ae]),Ai=i.useCallback(()=>{B.openTodos(),ae({type:"modal",close:B.closeTodos})},[B,ae]),Sa=i.useCallback(()=>{B.openActivityLog(),ae({type:"modal",close:B.closeActivityLog})},[B,ae]),Xa=i.useCallback(()=>{B.openGitManager(),ae({type:"modal",close:B.closeGitManager})},[B,ae]),Za=i.useCallback(()=>{B.openSystemStats(),ae({type:"modal",close:B.closeSystemStats})},[B,ae]),Ca=i.useCallback(()=>{B.openSchedules(),ae({type:"modal",close:B.closeSchedules})},[B,ae]),Ea=i.useCallback(()=>{B.openScripts(),ae({type:"modal",close:B.closeScripts})},[B,ae]),_a=i.useCallback(()=>{B.openWorkflowSteps(),ae({type:"modal",close:B.closeWorkflowSteps})},[B,ae]),er=i.useCallback(Je=>{B.openUsage(Je),ae({type:"modal",close:B.closeUsage})},[B,ae]),Ma=i.useCallback(async(Je,Rt)=>{await B.runScript(Je,Rt),Ve({type:"modal",close:B.closeTerminal})},[B,Ve]),di=i.useCallback(()=>{B.closeSettings(),B.openModelOnboarding(),Ve({type:"modal",close:B.closeModelOnboarding})},[B,Ve]),ki=i.useCallback(()=>{B.setFileWorkspace("project"),B.openFiles()},[B]),Ds=i.useCallback(async()=>{en(!0);try{await h()}finally{en(!1)}},[h]),tr=i.useCallback(Je=>{Jt(Je),Sn(void 0),ce("missions")},[ce]),qi=i.useCallback(Je=>{Je.type==="planning"?B.openPlanningWithSession(Je.id):Je.type==="subtask"?B.openSubtaskWithSession(Je.id):Je.type==="mission_interview"?(Jt(void 0),Sn(Je.id),Ne(void 0),ce("missions")):(Je.type==="milestone_interview"||Je.type==="slice_interview")&&(Sn(void 0),Jt(void 0),Ne(Je.id),ce("missions"))},[ce,B]),nr=i.useCallback(()=>{},[]),ei=i.useCallback(()=>{},[]),[Gr,Kr]=i.useState(!1),[Jr,oa]=i.useState(!1),[Vi,sr]=i.useState(null),ir=y6(r,o,Gr);i.useEffect(()=>{!a||l===0||oa(!0)},[a,l]),i.useEffect(()=>{let Je=!1;return t6(c.host).then(Rt=>{Je||sr(Rt)}),()=>{Je=!0}},[c.host,r.activeProfileId,r.desktopMode,r.host,r.profiles]),i.useEffect(()=>{r.host==="desktop-shell"&&r.desktopMode==="local"&&(r.localServer?.status!=="ready"||!r.localServer.port||window.location.port!==String(r.localServer.port)&&(window.location.href=`http://localhost:${r.localServer.port}`))},[r]),i.useEffect(()=>{if(r.host!=="desktop-shell"||r.desktopMode!=="remote")return;const Je=r.profiles.find(rn=>rn.id===r.activeProfileId);if(!Je||typeof window>"u")return;const Rt=v6(Je.serverUrl,Je.authToken??null);window.location.href!==Rt&&(window.location.href=Rt)},[r]);const Yr=!u&&!C&&d.length===0&&!y&&!!m,ar=()=>{if(Yr)return t.jsx(HO,{errorMessage:m??"Failed to fetch projects",isRetrying:Ot,onRetry:Ds,onManageConnection:a?()=>{a.openConnectionManager()}:void 0});if(Gt)return t.jsx("div",{className:"nodes-management-overlay",children:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(c6,{addToast:n,onClose:()=>bt(!1)})})})});if(Te==="overview")return t.jsx(Is,{children:t.jsx(g$,{projects:d,loading:u,onSelectProject:we,onAddProject:Ce,onPauseProject:mt,onResumeProject:Nt,onRemoveProject:Pt,nodes:f})});const Je=Be==="graph"?Le:wr(Be)?Be:null;return Je?t.jsx(Is,{children:t.jsx(kz,{taskView:Je,context:{projectId:y?.id,tasks:w&&k.tasks.length>0?k.tasks:ue,workflowSteps:is,openTaskDetail:(Rt,rn)=>Jn(Rt,rn),renderTaskCard:Rt=>t.jsx(Do,{task:Rt,projectId:y?.id,onOpenDetail:rn=>Jn(rn),addToast:n,workflowStepNameLookup:xs,disableDrag:!0}),addToast:n}})}):Be==="skills"?!Xt||!On?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(u6,{addToast:n,projectId:y?.id,onClose:()=>ce("board")})})}):Be==="chat"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(d6,{addToast:n,projectId:y?.id,experimentalFeatures:_n})})}):Be==="mailbox"?t.jsx(Is,{children:t.jsx(m4,{projectId:y?.id,addToast:n,onUnreadCountChange:on})}):Be==="missions"?t.jsx(Is,{children:t.jsx(o4,{isInline:!0,isOpen:!0,onClose:()=>{Jt(void 0),Sn(void 0),Ne(void 0),ce("board")},addToast:n,projectId:y?.id,onSelectTask:Rt=>{const rn=ue.find(es=>es.id===Rt);rn&&Jn(rn)},availableTasks:ue.map(Rt=>({id:Rt.id,title:Rt.title})),resumeSessionId:Kt,targetMissionId:dn,milestoneSliceResumeSessionId:tn,onMilestoneSliceResumeFetchError:()=>Ne(void 0)})}):Be==="agents"&&In?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(i6,{addToast:n,projectId:y?.id,onOpenTaskLogs:bs,agentOnboardingEnabled:Rs})})}):Be==="documents"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(a6,{projectId:y?.id,addToast:n,onOpenDetail:Jn})})}):Be==="stash-recovery"?t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(p6,{})})}):Be==="insights"?!Xt||!Pn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(r6,{projectId:y?.id,addToast:n,onClose:()=>ce("board"),onCreateTask:$e})})}):Be==="research"?!Xt||!as?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(o6,{projectId:y?.id,addToast:n,onOpenSettings:Rt=>B.openSettings(Rt),readinessVersion:Ie})})}):Be==="evals"?!Xt||!Wn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(l6,{projectId:y?.id,onOpenSettings:Rt=>B.openSettings(Rt),onOpenTaskDetail:Rt=>{Ba(Rt,y?.id).then(rn=>Jn(rn)).catch(rn=>n(rn instanceof Error?rn.message:"Failed to open task detail","error"))}})})}):Be==="memory"?!Xt||!kn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(m6,{addToast:n,projectId:y?.id})})}):Be==="devserver"||Be==="dev-server"?!Xt||!Vn?null:t.jsx(Is,{children:t.jsx(i.Suspense,{fallback:null,children:t.jsx(h6,{addToast:n,projectId:y?.id})})}):Be==="board"?t.jsx(Is,{children:t.jsx(n_,{tasks:Bt,projectId:y?.id,maxConcurrent:Dn,onMoveTask:Ee,onPauseTask:ft,onOpenDetail:Jn,addToast:n,onQuickCreate:Qe,onNewTask:Hi,onPlanningMode:ja,onSubtaskBreakdown:Ya,autoMerge:de,onToggleAutoMerge:vs,globalPaused:nt,onUpdateTask:Ye,onRetryTask:xt,onArchiveTask:wt,onUnarchiveTask:St,onDeleteTask:ht,onArchiveAllDone:Fe,onLoadArchivedTasks:J,searchQuery:T,availableModels:Ns,onOpenDetailWithTab:gs,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,onOpenMission:tr,lastFetchTimeMs:Ze})}):t.jsx(Is,{children:t.jsx(i$,{tasks:w&&k.tasks.length>0?k.tasks:ue,projectId:y?.id,onMoveTask:Ee,onRetryTask:xt,onDeleteTask:ht,onMergeTask:tt,onResetTask:Me,onDuplicateTask:dt,onOpenDetail:(Rt,rn)=>Jn(Rt,void 0,rn),addToast:n,globalPaused:nt,onNewTask:Hi,onQuickCreate:Qe,onPlanningMode:ja,onSubtaskBreakdown:Ya,availableModels:Ns,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn,taskStuckTimeoutMs:_t,searchQuery:T,lastFetchTimeMs:Ze,prAuthAvailable:Mt})})};if(!gt)return t.jsxs(t.Fragment,{children:[t.jsx(VO,{stage:vt}),t.jsx(Wv,{toasts:e,onRemove:s})]});const Aa=!B.modelOnboardingOpen&&mO(),Wi=!B.modelOnboardingOpen&&!Aa&&Lr()&&!Uv();return t.jsx(b$,{value:{pushNav:ae,replaceCurrent:Ve},children:t.jsxs(DT,{openFile:wi,children:[t.jsx(IC,{shellHost:c.host,onOpenSettings:Ui,onOpenGitHubImport:Qa,onOpenPlanning:Zs,onResumePlanning:Na,activePlanningSessionCount:q.length,onOpenUsage:er,onOpenActivityLog:Sa,onOpenSystemStats:Za,onOpenMailbox:()=>ct("mailbox"),mailboxUnreadCount:nn,mailboxPendingApprovalCount:sn,chatHasUnreadResponse:xn,stashOrphanCount:Qt,onOpenSchedules:Ca,onOpenGitManager:Xa,onOpenNodes:ra,showNodesButton:Fn,onOpenWorkflowSteps:_a,onOpenScripts:Ea,onRunScript:Ma,onToggleTerminal:Mn,onOpenFiles:ci,filesOpen:B.filesOpen,onOpenTodos:Ai,todosOpen:B.todosOpen,todosEnabled:$s,globalPaused:nt,enginePaused:ot,onToggleGlobalPause:As,onToggleEnginePause:bn,view:Be,onChangeView:Te==="project"&&y?ct:void 0,showSkillsTab:On,showAgentsTab:In,searchQuery:T,onSearchChange:H,branchFilter:Q,baseBranchFilter:O,branchOptions:It,baseBranchOptions:Lt,onBranchFilterChange:D,onBaseBranchFilterChange:$,projects:X,currentProject:y,onSelectProject:we,onViewAllProjects:P,projectId:y?.id,mobileNavEnabled:ze,availableNodes:f,currentNode:p,onSelectNode:Je=>{Je===null?b():v(Je)},isRemote:w,experimentalFeatures:{insights:Pn,memoryView:kn,devServer:Vn,devServerView:Vn,researchView:as,evalsView:Wn},pluginDashboardViews:Re,shellConnectionControl:!ze&&Vi?t.jsx(Bg,{status:Vi,onError:Je=>n(Je,"error")}):void 0}),Te==="project"&&y&&!Gt&&Be!=="missions"&&!B.isPlanningOpen&&!he&&t.jsx(rF,{sessions:xe,onResumeSession:qi,onDismissSession:nr,onDismissAll:ei}),Te==="project"&&y&&t.jsx(cF,{onOpenSettings:()=>B.openSettings("general")}),Te==="project"&&y&&Aa&&t.jsx(fF,{onResume:B.openModelOnboarding}),Te==="project"&&y&&Wi&&t.jsx(gF,{onOpenModelOnboarding:B.openModelOnboarding,onOpenSettings:Je=>B.openSettings(Je)}),Te==="project"&&y&&E&&_&&K&&!U&&t.jsx(hF,{latestVersion:_,currentVersion:K,onDismiss:A}),Te==="project"&&y&&At?.taskIdIntegrity?.status==="anomaly"&&At.taskIdIntegrity.recommendedAction&&t.jsx(mF,{report:At.taskIdIntegrity,recommendedAction:At.taskIdIntegrity.recommendedAction,onRefresh:(Je,Rt)=>{zt(rn=>rn?{...rn,status:Je.status==="anomaly"||!rn.database.healthy?"degraded":"ok",taskIdIntegrity:{...Je,recommendedAction:Rt}}:null)}}),Te==="project"&&y&&!R&&F&&!yn&&t.jsx(Ov,{hasAiProvider:x,hasGithub:N,onDismiss:vn}),Te==="project"&&y&&Zt&&t.jsx(pF,{pendingCount:Math.max(sn,1),onOpenMailbox:()=>ct("mailbox"),onDismiss:()=>{at.current.set(Zt.dedupeKey,Math.max(Date.now(),Zt.updatedAtMs)),Wg(at.current),ve(null)}}),t.jsx("div",{className:`project-content${Te==="project"&&y&&(!ze||!Dt)?" project-content--with-footer":""}${ze&&!Dt?" project-content--with-mobile-nav":""}`,children:ar()}),Te==="project"&&y&&!Gt&&t.jsx(tF,{tasks:w&&k.tasks.length>0?k.tasks:ue,projectId:y.id,taskStuckTimeoutMs:_t,staleHighFanoutBlockerAgeThresholdMs:G,backgroundSessions:fe,backgroundGenerating:Z,backgroundNeedsInput:re,onOpenBackgroundSession:qi,onDismissBackgroundSession:L,lastFetchTimeMs:Ze,currentProjectPath:y.path,onOpenProjectDirectory:ki,keyboardOpen:Dt}),t.jsx(xF,{view:Be,onChangeView:Te==="project"&&y?ct:()=>{},footerVisible:Te==="project"&&!!y,modalOpen:B.anyModalOpen,keyboardOpen:Dt,onOpenSettings:Ui,onOpenActivityLog:Sa,onOpenSystemStats:Za,onOpenMailbox:()=>ct("mailbox"),onOpenNodes:ra,mailboxUnreadCount:nn,mailboxPendingApprovalCount:sn,chatHasUnreadResponse:xn,stashOrphanCount:Qt,onOpenGitManager:Xa,onOpenWorkflowSteps:_a,onOpenSchedules:Ca,onOpenScripts:Ea,onToggleTerminal:Mn,onOpenFiles:ci,onOpenTodos:Ai,todosOpen:B.todosOpen,onOpenGitHubImport:Qa,onOpenPlanning:Zs,onResumePlanning:Na,activePlanningSessionCount:q.length,onOpenUsage:()=>er(null),onViewAllProjects:P,onRunScript:Ma,projectId:y?.id,showSkillsTab:On,experimentalFeatures:{insights:Pn,memoryView:kn,devServer:Vn,devServerView:Vn,todoView:$s,researchView:as,evalsView:Wn,nodesView:Fn},pluginDashboardViews:Re,shellConnectionControl:ze&&Vi?t.jsx(Bg,{status:Vi,onError:Je=>n(Je,"error")}):void 0}),Te==="project"&&y&&Be!=="chat"&&Be!=="mailbox"&&Be!=="insights"&&Be!=="evals"&&Be!=="devserver"&&Be!=="dev-server"&&Be!=="graph"&&!wr(Be)&&t.jsx(BF,{projectId:y.id,addToast:n,showFAB:Oe,open:W,onOpenChange:Y,favoriteProviders:ys,favoriteModels:cs,onToggleFavorite:an,onToggleModelFavorite:Cn}),t.jsx(UO,{projectId:y?.id,tasks:ue,projects:d,currentProject:y,addToast:n,toasts:e,removeToast:s,modalManager:B,projectActions:{handleAddProject:Ce,handleSetupComplete:qe,handleModelOnboardingComplete:et},taskHandlers:{handleModalCreate:Ft,handlePlanningTaskCreated:cn,handlePlanningTasksCreated:pn,handleSubtaskTasksCreated:jn,handleGitHubImport:Un},taskOperations:{moveTask:Ee,deleteTask:ht,mergeTask:tt,retryTask:xt,resetTask:Me,duplicateTask:dt},deepLink:{handleDetailClose:ie},settings:{prAuthAvailable:Mt,themeMode:le,colorTheme:ke,dashboardFontScalePct:He,setThemeMode:ye,setColorTheme:je,setDashboardFontScalePct:ne},onSettingsClose:rs,onReopenOnboarding:di}),t.jsx(n6,{open:_e}),a&&t.jsxs(t.Fragment,{children:[t.jsx(Jz,{open:ir,shellApi:a,shellState:r,onComplete:()=>Kr(!0)}),t.jsx(Yz,{open:Jr,shellApi:a,shellState:r,onClose:()=>oa(!1)})]})]})})}function k6(){return t.jsx(tz,{children:t.jsx(Wz,{children:t.jsx(eO,{children:t.jsx(Iz,{children:t.jsx(WC,{children:t.jsx(w6,{})})})})})})}function my(e){e.postMessage({type:"SKIP_WAITING"})}function Gg(e){e.addEventListener("statechange",()=>{e.state==="installed"&&navigator.serviceWorker.controller&&my(e)})}function j6(){if(!("serviceWorker"in navigator))return;const e=!!navigator.serviceWorker.controller;let n=!1;navigator.serviceWorker.addEventListener("controllerchange",()=>{n||!e||(n=!0,Hu("service worker activated new version"))}),navigator.serviceWorker.register("/sw.js").then(s=>{console.log("SW registered:",s.scope),s.waiting&&navigator.serviceWorker.controller&&my(s.waiting),s.installing&&Gg(s.installing),s.addEventListener("updatefound",()=>{const a=s.installing;a&&Gg(a)})}).catch(s=>{console.log("SW registration failed:",s)})}Pj();vj();cy();ay();vy.createRoot(document.getElementById("root")).render(t.jsx(i.StrictMode,{children:t.jsx(yj,{children:t.jsx(k6,{})})}));j6();export{s1 as $,Js as A,Qn as B,Xn as C,HC as D,Z3 as E,xa as F,gc as G,au as H,$n as I,ql as J,$8 as K,jt as L,qo as M,jk as N,BL as O,zn as P,Gd as Q,ps as R,Xi as S,zr as T,os as U,Ci as V,Tn as W,mn as X,LL as Y,ls as Z,En as _,gn as a,u5 as a$,ML as a0,AL as a1,i1 as a2,Y3 as a3,a1 as a4,c3 as a5,d3 as a6,cS as a7,zu as a8,Fr as a9,w8 as aA,y8 as aB,v8 as aC,b8 as aD,Oj as aE,Po as aF,h8 as aG,f8 as aH,p8 as aI,C8 as aJ,N8 as aK,S8 as aL,E8 as aM,p5 as aN,P8 as aO,To as aP,eu as aQ,Gk as aR,$i as aS,Ok as aT,lw as aU,Cs as aV,m$ as aW,Hs as aX,ob as aY,Dk as aZ,d5 as a_,Ga as aa,xi as ab,vi as ac,Li as ad,a8 as ae,d8 as af,c8 as ag,Kl as ah,u8 as ai,r8 as aj,m8 as ak,o8 as al,l8 as am,ms as an,zo as ao,Co as ap,Vs as aq,ij as ar,Oi as as,eb as at,ta as au,_y as av,g8 as aw,x8 as ax,j8 as ay,k8 as az,qn as b,P3 as b$,m5 as b0,h5 as b1,Cc as b2,QF as b3,uh as b4,Zr as b5,wg as b6,Y0 as b7,Ar as b8,V0 as b9,Om as bA,Zi as bB,J5 as bC,K5 as bD,Y5 as bE,H6 as bF,U6 as bG,B6 as bH,q6 as bI,Z6 as bJ,e3 as bK,Y6 as bL,G6 as bM,K6 as bN,J6 as bO,W6 as bP,V6 as bQ,z6 as bR,Q6 as bS,fD as bT,A3 as bU,M3 as bV,D3 as bW,_3 as bX,R3 as bY,I3 as bZ,T3 as b_,Q5 as ba,X5 as bb,G0 as bc,kF as bd,J0 as be,wF as bf,n8 as bg,s8 as bh,Z5 as bi,e8 as bj,t8 as bk,i8 as bl,wv as bm,MF as bn,aa as bo,Jv as bp,H0 as bq,ks as br,ba as bs,pc as bt,vF as bu,Da as bv,ab as bw,EF as bx,Ys as by,nb as bz,it as c,NN as c$,TS as c0,$3 as c1,Vu as c2,AS as c3,RS as c4,IS as c5,MS as c6,E3 as c7,wc as c8,Vk as c9,x3 as cA,p3 as cB,v3 as cC,f3 as cD,y3 as cE,g3 as cF,b3 as cG,Dy as cH,wN as cI,k3 as cJ,kN as cK,j3 as cL,fi as cM,zi as cN,VF as cO,tD as cP,t3 as cQ,g5 as cR,Dj as cS,_6 as cT,hg as cU,r5 as cV,M6 as cW,R6 as cX,F6 as cY,O6 as cZ,$N as c_,Cr as ca,v5 as cb,y5 as cc,w5 as cd,k5 as ce,j5 as cf,N5 as cg,S5 as ch,x5 as ci,db as cj,tk as ck,I as cl,ec as cm,Do as cn,Er as co,x1 as cp,Cj as cq,Ej as cr,mN as cs,hN as ct,z5 as cu,m3 as cv,u3 as cw,B5 as cx,h3 as cy,w3 as cz,a5 as d,e5 as d$,Fi as d0,SN as d1,EN as d2,CN as d3,_N as d4,MN as d5,i3 as d6,o5 as d7,l5 as d8,c5 as d9,Xp as dA,I8 as dB,T8 as dC,X6 as dD,C5 as dE,_5 as dF,R5 as dG,M5 as dH,E5 as dI,A5 as dJ,I5 as dK,uu as dL,qm as dM,G3 as dN,J3 as dO,O0 as dP,dw as dQ,za as dR,Os as dS,qw as dT,T5 as dU,X3 as dV,Ho as dW,YT as dX,ma as dY,K3 as dZ,t5 as d_,sa as da,M8 as db,A8 as dc,b5 as dd,I6 as de,tu as df,js as dg,hD as dh,HL as di,VL as dj,WL as dk,pa as dl,Kd as dm,KL as dn,P6 as dp,A6 as dq,$6 as dr,T6 as ds,D6 as dt,L6 as du,Ua as dv,D8 as dw,FC as dx,Nc as dy,R8 as dz,s5 as e,tb as e0,V3 as e1,q3 as e2,O3 as e3,F3 as e4,_L as e5,Ra as e6,Q3 as e7,U3 as e8,B3 as e9,s3 as eA,Rk as eB,o3 as eC,l3 as eD,r3 as eE,dS as ea,H3 as eb,W3 as ec,P5 as ed,P0 as ee,z3 as ef,L3 as eg,bi as eh,C3 as ei,N3 as ej,S3 as ek,$5 as el,U5 as em,ru as en,V5 as eo,W5 as ep,q5 as eq,O5 as er,L5 as es,F5 as et,D5 as eu,H5 as ev,f5 as ew,_8 as ex,a3 as ey,n3 as ez,Ba as f,i5 as g,Ws as h,Ur as i,Bn as j,cc as k,G5 as l,_s as m,n1 as n,n5 as o,oi as p,CF as q,RL as r,yi as s,Gn as t,Mi as u,li as v,fs as w,kc as x,sl as y,Se as z};