@runfusion/fusion 0.31.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/bin.js +78395 -59001
  2. package/dist/client/.vite/manifest.json +549 -0
  3. package/dist/client/assets/{AgentDetailView-Dx7T1-gM.js → AgentDetailView-CnFf_eBZ.js} +3 -3
  4. package/dist/client/assets/{AgentPermissionPolicyEditor-Cbd6SG_T.css → AgentPermissionPolicyEditor-CGxjOr6G.css} +1 -1
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-Ia7QkynK.js → AgentPermissionPolicyEditor-Cmkt9Z01.js} +2 -2
  6. package/dist/client/assets/{AgentsView-DBbdPWV-.js → AgentsView-LkVv9hph.js} +3 -3
  7. package/dist/client/assets/ChatView-DYjECCRG.js +1 -0
  8. package/dist/client/assets/{DevServerView-DotHOFZt.js → DevServerView-D7legPr1.js} +1 -1
  9. package/dist/client/assets/{DevServerView-DlZpuAnj.css → DevServerView-VTQY28P7.css} +1 -1
  10. package/dist/client/assets/{DirectoryPicker-CIj3ZGKv.js → DirectoryPicker-DctpCNrd.js} +1 -1
  11. package/dist/client/assets/DocumentsView-DORp5JjC.js +1 -0
  12. package/dist/client/assets/EvalsView-CYVJ1pbc.js +1 -0
  13. package/dist/client/assets/{ExperimentalAgentOnboardingModal-U7fXDhhN.js → ExperimentalAgentOnboardingModal-BULVNAiq.js} +1 -1
  14. package/dist/client/assets/GoalsView-Cg136Jcn.css +1 -0
  15. package/dist/client/assets/GoalsView-bmpZKOI_.js +1 -0
  16. package/dist/client/assets/{InsightsView-B0J4mhzV.css → InsightsView-C9-mqVvf.css} +1 -1
  17. package/dist/client/assets/InsightsView-mmtem0RU.js +11 -0
  18. package/dist/client/assets/{MemoryView-D-HLtRrr.js → MemoryView-HVpO1fCH.js} +2 -2
  19. package/dist/client/assets/{NodesView-w3ms-XX2.js → NodesView-CM0eoCP8.js} +3 -3
  20. package/dist/client/assets/{PiExtensionsManager-DFAZAfNn.js → PiExtensionsManager-Cyfas2VT.js} +2 -2
  21. package/dist/client/assets/{PluginManager-DN1VG7Qm.js → PluginManager-C7QDE3Lk.js} +1 -1
  22. package/dist/client/assets/ReliabilityView-C1C1j1SD.js +1 -0
  23. package/dist/client/assets/ReliabilityView-D9AsVv5l.css +1 -0
  24. package/dist/client/assets/ResearchView-Bn2WxwnQ.js +1 -0
  25. package/dist/client/assets/SecretsView-BFhVwJu6.css +1 -0
  26. package/dist/client/assets/SecretsView-DgrrgzFc.js +1 -0
  27. package/dist/client/assets/SettingsModal-BCZrCLl3.js +31 -0
  28. package/dist/client/assets/{SettingsModal-sp7SNwS9.css → SettingsModal-BZBV2kLr.css} +1 -1
  29. package/dist/client/assets/{SettingsModal-1Y8N6MkL.css → SettingsModal-DZrJ5PFH.css} +1 -1
  30. package/dist/client/assets/{SettingsModal-BRRPoxku.js → SettingsModal-YCJM5is3.js} +1 -1
  31. package/dist/client/assets/{SetupWizardModal-B4eA3bpz.js → SetupWizardModal-BT-mj3VD.js} +1 -1
  32. package/dist/client/assets/{SkillsView-DZIfZoF5.js → SkillsView-Db7dYpqd.js} +1 -1
  33. package/dist/client/assets/{StashRecoveryView-mKXYsqam.js → StashRecoveryView-CSYYcWux.js} +1 -1
  34. package/dist/client/assets/TodoView-zqCqfy26.js +6 -0
  35. package/dist/client/assets/{dashboard-view-DOY8-BIx.js → dashboard-view-PpcsMDvN.js} +1 -1
  36. package/dist/client/assets/{folder-open-C_fxRMq1.js → folder-open-mxsFQlAX.js} +1 -1
  37. package/dist/client/assets/index-Ba-F8c1g.js +732 -0
  38. package/dist/client/assets/index-D4HhaIOp.css +1 -0
  39. package/dist/client/assets/{upload-xjku_93-.js → upload-j7JjaJzG.js} +1 -1
  40. package/dist/client/assets/{users-CbALDtDk.js → users-DZ_0WcB6.js} +1 -1
  41. package/dist/client/index.html +15 -27
  42. package/dist/client/version.json +1 -1
  43. package/dist/droid-cli/package.json +1 -1
  44. package/dist/extension.js +51638 -35198
  45. package/dist/pi-claude-cli/package.json +1 -1
  46. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  47. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  48. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  49. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  50. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  51. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  52. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  53. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  54. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  55. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  56. package/package.json +1 -1
  57. package/skill/fusion/SKILL.md +1 -1
  58. package/skill/fusion/references/cli-commands.md +1 -1
  59. package/skill/fusion/references/engine-tools.md +1 -0
  60. package/skill/fusion/references/extension-tools.md +12 -2
  61. package/skill/fusion/references/fusion-capabilities.md +3 -2
  62. package/skill/fusion/workflows/task-management.md +1 -1
  63. package/dist/client/assets/ChatView-DYpoWnCc.js +0 -1
  64. package/dist/client/assets/DocumentsView-Dt27gDYa.js +0 -1
  65. package/dist/client/assets/EvalsView-HfWTc8Uv.js +0 -1
  66. package/dist/client/assets/InsightsView-C8bsAlMv.js +0 -11
  67. package/dist/client/assets/ReliabilityView-D0Rtd7pX.css +0 -1
  68. package/dist/client/assets/ReliabilityView-DAuqE-zi.js +0 -1
  69. package/dist/client/assets/ResearchView-YoxEFtNB.js +0 -1
  70. package/dist/client/assets/SettingsModal-B86XhYB1.js +0 -31
  71. package/dist/client/assets/TodoView-C6sLLEQu.js +0 -6
  72. package/dist/client/assets/index-DTFPgu6_.js +0 -695
  73. package/dist/client/assets/index-DdvAZIzj.css +0 -1
@@ -1 +1 @@
1
- .agent-policy-editor{padding:var(--space-lg);border:1px solid var(--border);border-radius:var(--radius-lg);display:flex;flex-direction:column;gap:var(--space-md)}.agent-policy-table{display:flex;flex-direction:column;gap:var(--space-sm)}.agent-policy-row{display:grid;grid-template-columns:1fr 220px;gap:var(--space-md);padding:var(--space-sm);border:1px solid var(--border);border-radius:var(--radius-md);background:var(--surface)}.agent-policy-cell{display:flex;flex-direction:column;gap:var(--space-xs)}.agent-policy-description{color:var(--text-muted);font-size:.75rem}.agent-policy-inherit-note{color:var(--text-dim);font-size:.75rem}.agent-policy-examples,.agent-policy-exempt-list{margin:0;padding-left:var(--space-lg);display:grid;gap:var(--space-xs)}.agent-policy-examples code,.agent-policy-exempt-list code{font-family:var(--font-mono);font-size:.75rem}.agent-policy-exempt{border:1px solid var(--border);border-radius:var(--radius-md);background:var(--surface);padding:var(--space-sm);color:var(--text-muted)}.agent-policy-exempt summary{cursor:pointer;color:var(--text);font-weight:600}.agent-policy-exempt p{margin:var(--space-sm) 0}@media(max-width:768px){.agent-policy-row{grid-template-columns:1fr}.agent-policy-examples,.agent-policy-exempt-list{padding-left:var(--space-md)}}
1
+ .agent-policy-editor{padding:var(--space-lg);border:1px solid var(--border);border-radius:var(--radius-lg);display:flex;flex-direction:column;gap:var(--space-md)}.agent-policy-table{display:flex;flex-direction:column;gap:var(--space-sm)}.agent-policy-row{display:grid;grid-template-columns:1fr 220px;gap:var(--space-md);padding:var(--space-sm);border:1px solid var(--border);border-radius:var(--radius-md);background:var(--surface)}.agent-policy-cell{display:flex;flex-direction:column;gap:var(--space-xs)}.agent-policy-description{color:var(--text-muted);font-size:.75rem}.agent-policy-inherit-note{color:var(--text-dim);font-size:.75rem}.agent-policy-examples,.agent-policy-exempt-list{margin:0;padding-left:var(--space-xl);display:grid;gap:var(--space-xs)}.agent-policy-examples code,.agent-policy-exempt-list code{font-family:var(--font-mono);font-size:.75rem}.agent-policy-exempt{border:1px solid var(--border);border-radius:var(--radius-md);background:var(--surface);padding:var(--space-sm);color:var(--text-muted)}.agent-policy-exempt summary{cursor:pointer;color:var(--text);font-weight:600}.agent-policy-exempt p{margin:var(--space-sm) 0}@media(max-width:768px){.agent-policy-row{grid-template-columns:1fr}.agent-policy-examples,.agent-policy-exempt-list{padding-left:var(--space-lg)}}
@@ -1,6 +1,6 @@
1
- import{c as f,dH as h,es as j,et as k}from"./index-DTFPgu6_.js";import{j as e}from"./vendor-react-K0fH_qHe.js";/**
1
+ import{c as f,dN as h,ey as j,ez as k}from"./index-Ba-F8c1g.js";import{j as e}from"./vendor-react-K0fH_qHe.js";/**
2
2
  * @license lucide-react v1.7.0 - ISC
3
3
  *
4
4
  * This source code is licensed under the ISC license.
5
5
  * See the LICENSE file in the root directory of this source tree.
6
- */const I=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],T=f("star",I),b=["allow","require-approval","block"],E={git_write:{label:"Git writes",description:"Commits, branch updates, and merge-affecting git changes."},file_write_delete:{label:"File writes/deletes",description:"Create, edit, or remove files in the workspace."},command_execution:{label:"Command execution",description:"Runs shell commands and scripts."},network_api:{label:"Network/API",description:"Outbound network or API access."},task_agent_mutation:{label:"Task/agent mutation",description:"Task state changes, delegation, or agent lifecycle actions."}};function P(){return{git_write:"allow",file_write_delete:"allow",command_execution:"allow",network_api:"allow",task_agent_mutation:"allow"}}const d={unrestricted:{git_write:"allow",file_write_delete:"allow",command_execution:"allow",network_api:"allow",task_agent_mutation:"allow"},"approval-required":{git_write:"require-approval",file_write_delete:"require-approval",command_execution:"require-approval",network_api:"require-approval",task_agent_mutation:"require-approval"},"locked-down":{git_write:"block",file_write_delete:"block",command_execution:"block",network_api:"block",task_agent_mutation:"block"}};function N(t){return d[t]}function u(t,n){return h.every(l=>t[l]===n[l])}function R(t){return u(t,d.unrestricted)?"unrestricted":u(t,d["approval-required"])?"approval-required":u(t,d["locked-down"])?"locked-down":"custom"}function A({value:t,projectDefault:n,mode:l,onChange:s,disabled:m=!1}){const w=t?R(t.rules):"unrestricted",x=l==="agent-override"&&!t?"inherit":t?.presetId==="custom"?w:t?.presetId??"unrestricted",p=t?.rules??P(),v=r=>{if(l==="agent-override"&&r==="inherit"){s(void 0);return}if(r==="custom"){s({presetId:"custom",rules:{...p}});return}s({presetId:r,rules:N(r)})},g=(r,a)=>{if(l==="agent-override"&&a==="inherit"){if(!t)return;const c={...t.rules};c[r]=n?.[r]??"allow",s({presetId:"custom",rules:c});return}const o={...p,[r]:a};s({presetId:"custom",rules:o})};return e.jsxs("div",{className:"agent-policy-editor card",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-policy-preset",children:"Preset"}),e.jsxs("select",{id:"agent-policy-preset",className:"select",value:x,onChange:r=>v(r.target.value),disabled:m,children:[l==="agent-override"?e.jsx("option",{value:"inherit",children:"Inherit project default"}):null,e.jsx("option",{value:"unrestricted",children:"Unrestricted"}),e.jsx("option",{value:"approval-required",children:"Approval Required"}),e.jsx("option",{value:"locked-down",children:"Locked Down"}),e.jsx("option",{value:"custom",children:"Custom"})]})]}),e.jsx("div",{className:"agent-policy-table",role:"table","aria-label":"Permission policy categories",children:h.map(r=>{const a=E[r]??{label:r,description:""},o=n?.[r]??"allow",c=p[r]??"allow",_=l==="agent-override"&&!t?"inherit":c;return e.jsxs("div",{className:"agent-policy-row",role:"row","data-category":r,children:[e.jsxs("div",{className:"agent-policy-cell",children:[e.jsx("strong",{children:a.label}),e.jsx("div",{className:"agent-policy-description",children:a.description}),e.jsx("ul",{className:"agent-policy-examples","aria-label":`${a.label} examples`,children:(j[r]??[]).map(i=>e.jsx("li",{children:e.jsx("code",{children:i})},`${r}-${i}`))})]}),e.jsxs("div",{className:"agent-policy-cell",children:[e.jsxs("select",{className:"select",value:_,onChange:i=>g(r,i.target.value),disabled:m,children:[l==="agent-override"?e.jsx("option",{value:"inherit",children:"Inherit"}):null,b.map(i=>e.jsx("option",{value:i,children:i==="require-approval"?"Require approval":i[0]?.toUpperCase()+i.slice(1)},i))]}),l==="agent-override"&&_==="inherit"?e.jsxs("div",{className:"agent-policy-inherit-note",children:["from project default: ",o==="require-approval"?"Require approval":o]}):null]})]},r)})}),e.jsxs("details",{className:"agent-policy-exempt",open:!1,children:[e.jsx("summary",{children:"Tools exempt from approval policy"}),e.jsx("p",{children:"These coordination tools bypass approval policy so heartbeats and inter-agent messaging cannot deadlock. They are not user-configurable."}),e.jsx("ul",{className:"agent-policy-exempt-list",children:k.map(r=>e.jsx("li",{children:e.jsx("code",{children:r})},r))})]})]})}export{A,T as S};
6
+ */const I=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],T=f("star",I),b=["allow","require-approval","block"],E={git_write:{label:"Git writes",description:"Commits, branch updates, and merge-affecting git changes."},file_write_delete:{label:"File writes/deletes",description:"Create, edit, or remove files in the workspace."},command_execution:{label:"Command execution",description:"Runs shell commands and scripts."},network_api:{label:"Network/API",description:"Outbound network or API access."},task_agent_mutation:{label:"Task/agent mutation",description:"Task state changes, delegation, or agent lifecycle actions."}};function N(){return{git_write:"allow",file_write_delete:"allow",command_execution:"allow",network_api:"allow",task_agent_mutation:"allow"}}const d={unrestricted:{git_write:"allow",file_write_delete:"allow",command_execution:"allow",network_api:"allow",task_agent_mutation:"allow"},"approval-required":{git_write:"require-approval",file_write_delete:"require-approval",command_execution:"require-approval",network_api:"require-approval",task_agent_mutation:"require-approval"},"locked-down":{git_write:"block",file_write_delete:"block",command_execution:"block",network_api:"block",task_agent_mutation:"block"}};function P(t){return d[t]}function u(t,n){return h.every(l=>t[l]===n[l])}function R(t){return u(t,d.unrestricted)?"unrestricted":u(t,d["approval-required"])?"approval-required":u(t,d["locked-down"])?"locked-down":"custom"}function A({value:t,projectDefault:n,mode:l,onChange:s,disabled:m=!1}){const w=t?R(t.rules):"unrestricted",x=l==="agent-override"&&!t?"inherit":t?.presetId==="custom"?w:t?.presetId??"unrestricted",p=t?.rules??N(),v=r=>{if(l==="agent-override"&&r==="inherit"){s(void 0);return}if(r==="custom"){s({presetId:"custom",rules:{...p}});return}s({presetId:r,rules:P(r)})},g=(r,a)=>{if(l==="agent-override"&&a==="inherit"){if(!t)return;const c={...t.rules};c[r]=n?.[r]??"allow",s({presetId:"custom",rules:c});return}const o={...p,[r]:a};s({presetId:"custom",rules:o})};return e.jsxs("div",{className:"agent-policy-editor card",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"agent-policy-preset",children:"Preset"}),e.jsxs("select",{id:"agent-policy-preset",className:"select",value:x,onChange:r=>v(r.target.value),disabled:m,children:[l==="agent-override"?e.jsx("option",{value:"inherit",children:"Inherit project default"}):null,e.jsx("option",{value:"unrestricted",children:"Unrestricted"}),e.jsx("option",{value:"approval-required",children:"Approval Required"}),e.jsx("option",{value:"locked-down",children:"Locked Down"}),e.jsx("option",{value:"custom",children:"Custom"})]})]}),e.jsx("div",{className:"agent-policy-table",role:"table","aria-label":"Permission policy categories",children:h.map(r=>{const a=E[r]??{label:r,description:""},o=n?.[r]??"allow",c=p[r]??"allow",_=l==="agent-override"&&!t?"inherit":c;return e.jsxs("div",{className:"agent-policy-row",role:"row","data-category":r,children:[e.jsxs("div",{className:"agent-policy-cell",children:[e.jsx("strong",{children:a.label}),e.jsx("div",{className:"agent-policy-description",children:a.description}),e.jsx("ul",{className:"agent-policy-examples","aria-label":`${a.label} examples`,children:(j[r]??[]).map(i=>e.jsx("li",{children:e.jsx("code",{children:i})},`${r}-${i}`))})]}),e.jsxs("div",{className:"agent-policy-cell",children:[e.jsxs("select",{className:"select",value:_,onChange:i=>g(r,i.target.value),disabled:m,children:[l==="agent-override"?e.jsx("option",{value:"inherit",children:"Inherit"}):null,b.map(i=>e.jsx("option",{value:i,children:i==="require-approval"?"Require approval":i[0]?.toUpperCase()+i.slice(1)},i))]}),l==="agent-override"&&_==="inherit"?e.jsxs("div",{className:"agent-policy-inherit-note",children:["from project default: ",o==="require-approval"?"Require approval":o]}):null]})]},r)})}),e.jsxs("details",{className:"agent-policy-exempt",open:!1,children:[e.jsx("summary",{children:"Tools exempt from approval policy"}),e.jsx("p",{children:"These coordination tools bypass approval policy so heartbeats and inter-agent messaging cannot deadlock. They are not user-configurable."}),e.jsx("ul",{className:"agent-policy-exempt-list",children:k.map(r=>e.jsx("li",{children:e.jsx("code",{children:r})},r))})]})]})}export{A,T as S};
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-Dx7T1-gM.js","assets/vendor-react-K0fH_qHe.js","assets/index-DTFPgu6_.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/vendor-codemirror-jBKmHyH0.js","assets/index-DdvAZIzj.css","assets/AgentPermissionPolicyEditor-Ia7QkynK.js","assets/AgentPermissionPolicyEditor-Cbd6SG_T.css","assets/ExperimentalAgentOnboardingModal-U7fXDhhN.js","assets/ExperimentalAgentOnboardingModal-BNpveCEk.css","assets/AgentDetailView-CY-O6VkV.css"])))=>i.map(i=>d[i]);
2
- import{c as at,A as Ze,C as ct,Z as Na,s as ya,r as wt,F as Ct,f as ka,a as wa,b as ta,B as St,u as aa,d as gt,e as Ca,g as Sa,h as Aa,i as Ra,j as Ot,k as dt,P as Ta,l as Ma,m as _a,n as Ea,o as Dt,G as $a,S as La,L as ht,T as pt,R as qe,X as Ht,p as Ia,q as Pa,t as it,v as za,w as Bt,x as Fa,y as Oa,z as Ee,D as xt,E as Da,M as Ha,H as Ba,I as Wt,N as Gt,J as Vt,K as Wa,O as Ga,Q as Va,U as Ka,V as bt,W as Kt,Y as Ua,_ as Ya,$ as Xa,a0 as rt,a1 as qa,a2 as Ut,a3 as Za,a4 as Ja,a5 as Qa}from"./index-DTFPgu6_.js";import{r as a,j as e,a as es}from"./vendor-react-K0fH_qHe.js";import{A as ts,S as as,E as ss,f as ns}from"./ExperimentalAgentOnboardingModal-U7fXDhhN.js";import{U as At}from"./upload-xjku_93-.js";import{F as ls}from"./folder-open-C_fxRMq1.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.js";/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/AgentDetailView-CnFf_eBZ.js","assets/vendor-react-K0fH_qHe.js","assets/index-Ba-F8c1g.js","assets/vendor-xterm-DzcZoU0P.js","assets/vendor-xterm-LZoznX6r.css","assets/vendor-codemirror-jBKmHyH0.js","assets/index-D4HhaIOp.css","assets/AgentPermissionPolicyEditor-Cmkt9Z01.js","assets/AgentPermissionPolicyEditor-CGxjOr6G.css","assets/ExperimentalAgentOnboardingModal-BULVNAiq.js","assets/ExperimentalAgentOnboardingModal-BNpveCEk.css","assets/AgentDetailView-CY-O6VkV.css"])))=>i.map(i=>d[i]);
2
+ import{c as at,A as Ze,C as ct,Z as Na,s as ya,r as wt,F as Ct,f as ka,a as wa,b as ta,B as St,u as aa,d as gt,e as Ca,g as Sa,h as Aa,i as Ra,j as Ot,k as dt,P as Ta,l as Ma,m as _a,n as Ea,o as Dt,G as $a,S as La,L as ht,T as pt,R as qe,X as Ht,p as Ia,q as Pa,t as it,v as za,w as Bt,x as Fa,y as Oa,z as Ee,D as xt,E as Da,M as Ha,H as Ba,I as Wt,N as Gt,J as Vt,K as Wa,O as Ga,Q as Va,U as Ka,V as bt,W as Kt,Y as Ua,_ as Ya,$ as Xa,a0 as rt,a1 as qa,a2 as Ut,a3 as Za,a4 as Ja,a5 as Qa}from"./index-Ba-F8c1g.js";import{r as a,j as e,a as es}from"./vendor-react-K0fH_qHe.js";import{A as ts,S as as,E as ss,f as ns}from"./ExperimentalAgentOnboardingModal-BULVNAiq.js";import{U as At}from"./upload-j7JjaJzG.js";import{F as ls}from"./folder-open-mxsFQlAX.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.js";/**
3
3
  * @license lucide-react v1.7.0 - ISC
4
4
  *
5
5
  * This source code is licensed under the ISC license.
@@ -31,4 +31,4 @@ reportsTo: null
31
31
  skills:
32
32
  - review
33
33
  ---
34
- Agent instructions go here...`,value:j,onChange:i=>{f("paste"),y([]),k(i.target.value),F(null)},rows:8,"aria-label":"Manifest content"})]}),e.jsxs("p",{className:"agent-import-file-hint",children:["Current input: ",d]}),ie&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(pt,{size:14}),ie]})]}),x==="preview"&&e.jsxs("div",{className:"agent-import-preview",children:[e.jsxs("div",{className:"agent-import-company",children:[e.jsx("span",{className:"agent-import-company-label",children:"Company"}),e.jsx("span",{className:"agent-import-company-name",children:C})]}),e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Ct,{size:14}),e.jsxs("span",{children:[E.length," agent",E.length!==1?"s":""," found"]})]}),E.length>0&&e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>I(E.map(i=>i.name)),children:"Select all agents"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>I([]),children:"Clear agents"})]}),E.length>0?e.jsx("div",{className:"agent-import-agent-list",children:E.map((i,v)=>e.jsxs("div",{className:"agent-import-agent-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select agent ${i.name}`,checked:b.includes(i.name),onChange:()=>Oe(i.name)})}),e.jsx("span",{className:"agent-import-agent-icon",children:i.icon||"🤖"}),e.jsxs("div",{className:"agent-import-agent-details",children:[e.jsx("span",{className:"agent-import-agent-name",children:i.name}),e.jsxs("span",{className:"agent-import-agent-meta",children:[i.title&&e.jsxs("span",{className:"agent-import-agent-title",children:[i.title," · "]}),e.jsx("span",{className:"agent-import-agent-role",children:i.role}),i.reportsTo&&e.jsxs("span",{className:"agent-import-agent-reports",children:[" · reports to ",i.reportsTo]}),i.skills&&i.skills.length>0&&e.jsxs("span",{className:"agent-import-agent-model",children:[" · skills: ",i.skills.join(", ")]})]}),i.instructionsText&&e.jsxs("span",{className:"agent-import-agent-instructions",children:[i.instructionsText.slice(0,100),i.instructionsText.length>100?"...":""]})]})]},v))}):e.jsx("p",{className:"agent-import-empty",children:"No agents found in the manifest."}),R.length>0&&e.jsxs("div",{className:"agent-import-skills-section",children:[e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Ct,{size:14}),e.jsxs("span",{children:[R.length," skill",R.length!==1?"s":""," found"]})]}),e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>q(R.map(i=>i.name)),children:"Select all skills"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>q([]),children:"Clear skills"})]}),e.jsx("div",{className:"agent-import-skill-list",children:R.map((i,v)=>e.jsxs("div",{className:"agent-import-skill-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select skill ${i.name}`,checked:$.includes(i.name),onChange:()=>Pe(i.name)})}),e.jsx("span",{className:"agent-import-skill-icon",children:"⚡"}),e.jsxs("div",{className:"agent-import-skill-details",children:[e.jsx("span",{className:"agent-import-skill-name",children:i.name}),i.description&&e.jsx("span",{className:"agent-import-skill-description",children:i.description})]})]},`${i.name}-${v}`))})]}),ge&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(pt,{size:14}),ge]})]}),x==="result"&&N&&e.jsxs("div",{className:"agent-import-result",children:[e.jsx("div",{className:"agent-import-result-icon",children:e.jsx(ct,{size:32})}),e.jsx("h3",{className:"agent-import-result-title",children:"Import Complete"}),e.jsxs("p",{className:"agent-import-result-company",children:["From ",e.jsx("strong",{children:N.companyName??"Unknown"})]}),e.jsxs("div",{className:"agent-import-result-stats",children:[N.created.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[N.created.length," created"]})}),N.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[N.skipped.length," skipped (already exist)"]})}),N.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[N.errors.length," error",N.errors.length!==1?"s":""]})})]}),N.created.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:N.created.map((i,v)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(ct,{size:12}),e.jsx("span",{children:i.name})]},v))}),N.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:N.errors.map((i,v)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(Ht,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},v))}),N.skills&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-import-result-divider"}),e.jsx("h4",{className:"agent-import-result-section-title",children:"Skills"}),e.jsxs("div",{className:"agent-import-result-stats",children:[N.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[N.skills.imported.length," skill",N.skills.imported.length!==1?"s":""," imported"]})}),N.skills.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[N.skills.skipped.length," skill",N.skills.skipped.length!==1?"s":""," skipped (already exist)"]})}),N.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[N.skills.errors.length," skill",N.skills.errors.length!==1?"s":""," error",N.skills.errors.length!==1?"s":""]})}),N.skills.imported.length===0&&N.skills.skipped.length===0&&N.skills.errors.length===0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsx("span",{children:"No skills in package"})})]}),N.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:N.skills.imported.map((i,v)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(ct,{size:12}),e.jsx("span",{children:i.name})]},v))}),N.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:N.skills.errors.map((i,v)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(Ht,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},v))})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[x==="preview"&&e.jsx("button",{className:"btn",onClick:()=>o("input"),disabled:K,children:"Back"}),e.jsx("button",{className:"btn",onClick:Le,disabled:K,children:x==="result"?"Close":"Cancel"}),x==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void xe(),disabled:Ne||(d==="directory"?A.length===0:d==="browse"?!U:!j.trim()),children:Ne?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:14,className:"spin"}),"Parsing..."]}):"Preview"}),x==="preview"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void Ae(),disabled:K||D===0&&L===0,children:K?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:14,className:"spin"}),Ie]}):`Import ${Re}`})]})]})}):null}const Nt="fn-agent-org-chart-layout";function Qt(n){return n==="auto"||n==="horizontal"||n==="vertical"}const Rs=768,Ts={nodeWidth:220,siblingGap:24,rootGap:24,chartPadding:24},Ms={nodeWidth:160,siblingGap:8,rootGap:8,chartPadding:8};function sa(n){return n.children.length===0?1:n.children.reduce((r,p)=>r+sa(p),0)}function _s(n){return n<=Rs?Ms:Ts}function Es(n,r){const p=sa(n);return p*r.nodeWidth+Math.max(0,p-1)*r.siblingGap}function $s(n,r=Number.POSITIVE_INFINITY){const p=_s(r);if(n.length===0)return p.nodeWidth;const m=n.map(o=>Es(o,p)).reduce((o,d)=>o+d,0),x=Math.max(0,n.length-1)*p.rootGap;return m+x+p.chartPadding*2}function Ls(n){const r=n.preference??"auto";if(r!=="auto")return r;const p=Number.isFinite(n.availableWidth)&&n.availableWidth>0?n.availableWidth:0;return p===0||n.tree.length<=1?"horizontal":$s(n.tree,p)>p?"vertical":"horizontal"}const ea=a.lazy(()=>Ya(()=>import("./AgentDetailView-Dx7T1-gM.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(n=>({default:n.AgentDetailView}))),yt=[{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:"✦"}],kt=[.1,.25,.5,1,2,3,5,10],Is=.25,Ps=3,ot=16,Xe=32;function Rt(n){switch(n){case"running":return"agent-badge--running";case"active":return"agent-badge--active";case"paused":return"agent-badge--paused";case"error":return"agent-badge--error";case"idle":default:return"agent-badge--idle"}}function Tt(n,r){switch(r){case"running":return`${n}--running`;case"active":return`${n}--active`;case"paused":return`${n}--paused`;case"error":return`${n}--error`;case"idle":default:return`${n}--idle`}}function na(n){return n.children.length===0?1:n.children.reduce((r,p)=>r+na(p),0)}function Mt(n,r){return n.state==="error"?{title:void 0,label:"Error"}:{title:r.reason??r.label,label:r.stateDerived?null:r.label}}function la({node:n,onSelect:r,getHealthStatus:p,selectedAgentId:u,registerNodeElement:m,linksRef:x}){const{agent:o,children:d}=n,f=p(o),j=Mt(o,f),k=Rt(o.state),A=Tt("org-chart-node-card",o.state),y=na(n),C={"--org-chart-subtree-leaves":String(y)};return e.jsxs("div",{className:`org-chart-node${d.length>0?" org-chart-node--has-children":""}`,style:C,children:[e.jsxs("div",{ref:T=>m(o.id,T),"data-agent-id":o.id,className:`org-chart-node-card ${A}${u===o.id?" agent-card--selected":""}`,onClick:()=>r(o.id),role:"button",tabIndex:0,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.key===" "&&T.preventDefault(),r(o.id))},children:[e.jsxs("div",{className:"org-chart-node__header",children:[e.jsx("span",{className:"org-chart-node__icon",children:e.jsx(dt,{agent:o,size:20})}),e.jsx("span",{className:"org-chart-node__name",children:o.name})]}),e.jsxs("div",{className:"org-chart-node__meta",children:[e.jsx("span",{className:`org-chart-node__badge ${k}`,children:o.state}),e.jsxs("span",{className:"org-chart-node__health",style:{color:f.color},title:j.title,children:[f.icon,j.label&&e.jsx("span",{className:"text-secondary",children:j.label})]})]})]}),d.length>0&&e.jsx("div",{className:"org-chart-children",role:"group","aria-label":`${o.name} employees`,children:d.map(T=>(x.current.push({parentId:o.id,childId:T.agent.id}),e.jsx(la,{node:T,onSelect:r,getHealthStatus:p,selectedAgentId:u,registerNodeElement:m,linksRef:x},T.agent.id)))})]})}function zs({links:n,nodeElements:r,canvasRef:p,viewportRef:u,layoutMode:m,transform:x}){const[o,d]=a.useState([]);return a.useLayoutEffect(()=>{const f=p.current,j=u.current;if(!f||!j||n.length===0){d([]);return}const k=()=>{const y=f.getBoundingClientRect(),C=n.flatMap(({parentId:T,childId:E})=>{const H=r.get(T),R=r.get(E);if(!H||!R)return[];const _=H.getBoundingClientRect(),b=R.getBoundingClientRect(),I=(_.left-y.left)/x.scale,$=(_.top-y.top)/x.scale,q=(b.left-y.left)/x.scale,Ne=(b.top-y.top)/x.scale;if(m==="vertical"){const N=I,me=$+_.height/x.scale/2,ge=q,S=Ne+b.height/x.scale/2,Z=N-(N-ge)/2;return[`M ${N} ${me} L ${Z} ${me} L ${Z} ${S} L ${ge} ${S}`]}const le=I+_.width/x.scale/2,K=$+_.height/x.scale,ae=q+b.width/x.scale/2,ie=Ne,F=K+(ie-K)/2;return[`M ${le} ${K} L ${le} ${F} L ${ae} ${F} L ${ae} ${ie}`]});d(C)};k();const A=new ResizeObserver(k);return A.observe(f),A.observe(j),r.forEach(y=>A.observe(y)),()=>A.disconnect()},[p,m,n,r,x.scale,u]),e.jsx("svg",{className:"agent-org-chart-connectors","aria-hidden":"true",children:o.map((f,j)=>e.jsx("path",{d:f},`${j}-${f}`))})}function Vs({addToast:n,projectId:r,onOpenTaskLogs:p,agentOnboardingEnabled:u=!1}){const[m,x]=a.useState(!1),d=Ia()==="mobile",[f,j]=a.useState("all"),{agents:k,stats:A,isLoading:y,loadAgents:C,refreshAgents:T}=Pa(r,{filterState:f,showSystemAgents:m}),[E,H]=a.useState(!1),[R,_]=a.useState(null),[b,I]=a.useState(!1),[$,q]=a.useState(null),[Ne,le]=a.useState(null),K=d&&!!$,[ae,ie]=a.useState("dashboard"),[F,N]=a.useState(null),[me,ge]=a.useState(!1),[S,Z]=a.useState(()=>{if(typeof window>"u")return"list";const t=it("fn-agent-view",r);return t==="list"||t==="board"||t==="org"?t:"list"}),[re,$e]=a.useState(()=>{if(typeof window>"u")return"auto";const t=it(Nt,r);return Qt(t)?t:"auto"}),[ee,te]=a.useState([]),[ye,U]=a.useState(!1),[he,ke]=a.useState(0),[oe,J]=a.useState(!1),[ce,pe]=a.useState(!1),[G,B]=a.useState({scale:1,x:0,y:0}),[Le,Fe]=a.useState(!1),we=a.useRef(null),de=a.useRef(null),xe=a.useRef(null),Ae=a.useRef(new Map),D=a.useRef([]),L=a.useRef(new Map),Q=a.useRef(null),be=a.useRef(null),Re=a.useRef(!1),{confirm:Ie}=za(),Oe=a.useRef(null),Pe=a.useId();a.useEffect(()=>{const t=it("fn-agent-view",r);if(t==="list"||t==="board"||t==="org"){Z(t);return}Z("list")},[r]),a.useEffect(()=>{Bt("fn-agent-view",S,r)},[S,r]),a.useEffect(()=>{const t=it(Nt,r);$e(Qt(t)?t:"auto")},[r]),a.useEffect(()=>{Bt(Nt,re,r)},[re,r]);const[i,v]=a.useState(null),O=a.useRef(null),[se,P]=a.useState(null),[Y,Ce]=a.useState(null),[De,Te]=a.useState({}),[Ve,st]=a.useState(1),[Ke,He]=a.useState(!1),[Me,Je]=a.useState(new Set),[ze,Se]=a.useState(new Map),Be=a.useRef(!0);a.useEffect(()=>(Be.current=!0,()=>{Be.current=!1}),[]),a.useEffect(()=>{Fa(r).then(t=>{Be.current&&st(t.heartbeatMultiplier??1)}).catch(()=>{})},[r]);const Qe=a.useCallback(async t=>{const l=Number.isFinite(t)&&t>0?t:1;st(l),He(!0);try{await Oa({heartbeatMultiplier:l},r),n(`Heartbeat speed set to ×${l.toFixed(1)}`,"success")}catch(c){n(`Failed to save heartbeat multiplier: ${Ee(c)}`,"error")}finally{Be.current&&He(!1)}},[r,n]),s=a.useMemo(()=>ze.size===0?k:k.map(t=>{const l=ze.get(t.id);return l?{...t,state:l}:t}),[k,ze]),w=a.useMemo(()=>s.filter(t=>m||!xt(t)),[s,m]),_e=a.useMemo(()=>s.filter(t=>t.state!=="active"&&t.state!=="running"?!1:m||!xt(t)),[s,m]),V=a.useMemo(()=>{if(m)return ee;const t=l=>xt(l.agent)?null:{...l,children:l.children.map(t).filter(c=>c!==null)};return ee.map(t).filter(l=>l!==null)},[ee,m]);a.useEffect(()=>{if(S!=="org")return;const t=de.current;if(!t)return;const l=()=>{ke(t.clientWidth)};l();const c=typeof ResizeObserver<"u"?new ResizeObserver(l):null;return c?.observe(t),window.addEventListener("resize",l),()=>{c?.disconnect(),window.removeEventListener("resize",l)}},[S,V.length]),a.useEffect(()=>{if(S!=="org")return;let t=!1;return U(!0),Da(r,{includeEphemeral:m}).then(l=>{t||te(l)}).catch(l=>{t||(n(`Failed to load org chart: ${Ee(l)}`,"error"),te([]))}).finally(()=>{t||U(!1)}),()=>{t=!0}},[S,r,m,n]),a.useEffect(()=>{const t=setInterval(()=>{C()},3e4);return()=>{clearInterval(t)}},[C]),a.useEffect(()=>{if(!oe)return;const t=c=>{const g=c.target;g&&(we.current?.contains(g)||Oe.current?.contains(g)||J(!1))},l=c=>{c.key==="Escape"&&(J(!1),Oe.current?.focus())};return document.addEventListener("mousedown",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",l)}},[oe]);const ve=async(t,l)=>{if(!Me.has(t)){Je(c=>new Set(c).add(t)),Se(c=>{const g=new Map(c);return g.set(t,l),g});try{await Za(t,l,r),n(`Agent state updated to ${l}`,"success"),await C(),Se(c=>{const g=new Map(c);return g.delete(t),g})}catch(c){Se(g=>{const M=new Map(g);return M.delete(t),M}),n(`Failed to update state: ${Ee(c)}`,"error")}finally{Je(c=>{const g=new Set(c);return g.delete(t),g})}}},ia=async(t,l)=>{if(await Ie({title:"Delete Agent",message:`Delete agent "${l}"? This cannot be undone.`,danger:!0}))try{await Qa(t,r),n(`Agent "${l}" deleted`,"success"),await C()}catch(g){n(`Failed to delete agent: ${Ee(g)}`,"error")}},ra=async(t,l)=>{const c=k.find(g=>g.id===t);if(c){if(c.role===l){v(null);return}try{await rt(t,{role:l},r),n(`Agent role updated to ${yt.find(g=>g.value===l)?.label??l}`,"success"),v(null),C()}catch(g){n(`Failed to update role: ${Ee(g)}`,"error")}}},oa=(t,l)=>{t.key==="Escape"&&v(null)},ca=async(t,l)=>{Y===t.id&&(Ce(null),Te(c=>{const g={...c};return delete g[t.id],g})),P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:l}},r),n(`Heartbeat interval updated to ${Ut(l)} for ${t.name}`,"success"),C()}catch(c){n(`Failed to update heartbeat interval: ${Ee(c)}`,"error")}finally{P(null)}},_t=async t=>{const l=De[t.id]??"";if(l.trim()===""){n("Please enter a heartbeat interval in minutes","error");return}const c=Number(l);if(isNaN(c)){n("Heartbeat interval must be a valid number","error");return}if(c<=0){n("Heartbeat interval must be greater than 0","error");return}if(c>=1&&c<5){P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:qa}},r),n(`Heartbeat interval set to 5 minutes (minimum). ${c} minute${c!==1?"s":""} was below the 5-minute minimum.`,"success"),Ce(null),Te(M=>{const z={...M};return delete z[t.id],z}),C()}catch(M){n(`Failed to update heartbeat interval: ${Ee(M)}`,"error")}finally{P(null)}return}const g=Math.round(c*6e4);P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:g}},r),n(`Heartbeat interval updated to ${Ut(g)} for ${t.name}`,"success"),Ce(null),Te(M=>{const z={...M};return delete z[t.id],z}),C()}catch(M){n(`Failed to update heartbeat interval: ${Ee(M)}`,"error")}finally{P(null)}},da=t=>{const l=wt(t.runtimeConfig?.heartbeatIntervalMs),c=Math.round(l/6e4);Ce(t.id),Te(g=>({...g,[t.id]:String(c)}))},ue=a.useCallback((t,l)=>{q(t),ie(l?.initialTab??"dashboard"),N(l?.initialRunId??null),ge(l?.preferActiveRun??!1)},[]),We=a.useCallback(()=>{q(null),ie("dashboard"),N(null),ge(!1)},[]),Et=a.useCallback(t=>{ue(t)},[ue]),ua=a.useCallback(t=>{le(t),ue(t)},[ue]),ma=a.useCallback(async({agentId:t,deleted:l})=>{await T(),l&&$===t&&We()},[T,$,We]),ga=a.useCallback(t=>{ue(t),d&&pe(!1)},[d,ue]),ha=async(t,l)=>{Se(c=>{const g=new Map(c);return g.set(t,"running"),g});try{await Ja(t,r,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),n(`Heartbeat run started for ${l}`,"success"),await C(),Se(c=>{const g=new Map(c);return g.delete(t),g})}catch(c){Se(g=>{const M=new Map(g);return M.delete(t),M}),n(`Failed to start heartbeat run: ${Ee(c)}`,"error")}},Ge=a.useCallback(t=>Math.min(Ps,Math.max(Is,t)),[]),X=a.useCallback(t=>{const l=de.current,c=xe.current?.querySelector(".agent-org-chart");if(!l||!c)return{...t,scale:Ge(t.scale)};const g=Ge(t.scale),M=c.scrollWidth*g,z=c.scrollHeight*g,fe=l.clientWidth,je=l.clientHeight,h=Math.min(Xe,fe-M-Xe),W=Xe,ne=Math.min(Xe,je-z-Xe),tt=Xe;return{scale:g,x:Math.max(h,Math.min(W,t.x)),y:Math.max(ne,Math.min(tt,t.y))}},[Ge]),nt=a.useCallback((t,l,c)=>{const g=de.current;g&&B(M=>{const z=Ge(t),fe=g.getBoundingClientRect(),je=l-fe.left,h=c-fe.top,W=(je-M.x)/M.scale,ne=(h-M.y)/M.scale;return X({scale:z,x:je-W*z,y:h-ne*z})})},[Ge,X]),Ue=a.useCallback(()=>{const t=de.current,l=xe.current?.querySelector(".agent-org-chart");if(!t||!l)return;const c=t.clientWidth,g=t.clientHeight,M=l.scrollWidth,z=l.scrollHeight;if(M<=0||z<=0)return;const fe=Ge(Math.min(c/M,g/z,1)),je=(c-M*fe)/2,h=(g-z*fe)/2;B(X({scale:fe,x:je,y:h}))},[Ge,X]),ut=a.useCallback(t=>{Z(t),t!=="org"&&B({scale:1,x:0,y:0}),d&&$&&We()},[We,d,$]),$t=t=>yt.find(l=>l.value===t)?.label??t,lt=a.useMemo(()=>Ls({tree:V,availableWidth:he,preference:re}),[V,re,he]),Lt=a.useCallback(t=>{$e(t),B({scale:1,x:0,y:0})},[]);a.useEffect(()=>{B({scale:1,x:0,y:0}),Re.current=!1},[r,lt]),a.useLayoutEffect(()=>{S!=="org"||ye||V.length===0||Re.current||(Ue(),Re.current=!0)},[S,V.length,Ue,ye]);const pa=a.useCallback((t,l)=>{l?Ae.current.set(t,l):Ae.current.delete(t)},[]),It=a.useCallback(()=>e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn-icon touch-target",onClick:()=>B(t=>X({...t,scale:t.scale*.9})),"aria-label":"Zoom out org chart",title:"Zoom out",children:e.jsx(ps,{size:16})}),e.jsxs("span",{className:"agent-org-chart-controls__zoom-label","aria-live":"polite",children:[Math.round(G.scale*100),"%"]}),e.jsx("button",{type:"button",className:"btn-icon touch-target",onClick:()=>B(t=>X({...t,scale:t.scale*1.1})),"aria-label":"Zoom in org chart",title:"Zoom in",children:e.jsx(gs,{size:16})}),e.jsxs("button",{type:"button",className:"btn touch-target btn-sm agent-org-chart-controls__fit-btn",onClick:Ue,"aria-label":"Fit org chart",title:"Fit org chart",children:[e.jsx(Ha,{size:16}),"Fit"]}),e.jsxs("button",{type:"button",className:"btn touch-target btn-sm",onClick:()=>B(t=>X({...t,x:0,y:0})),"aria-label":"Center org chart",title:"Center org chart",children:[e.jsx(Ba,{size:16}),"Center"]})]}),[X,Ue,G.scale]),xa=a.useCallback(t=>{if(!(t.ctrlKey||t.metaKey))return;t.preventDefault();const l=t.deltaY>0?.9:1.1;nt(G.scale*l,t.clientX,t.clientY)},[G.scale,nt]),ba=a.useCallback(t=>{if(t.target.closest(".org-chart-node-card"))return;if(t.currentTarget.setPointerCapture?.(t.pointerId),L.current.set(t.pointerId,{x:t.clientX,y:t.clientY}),L.current.size===1){Q.current={x:t.clientX-G.x,y:t.clientY-G.y,pointerId:t.pointerId},Fe(!0);return}if(L.current.size===2){const c=Array.from(L.current.values()),g=c[0].x-c[1].x,M=c[0].y-c[1].y;be.current={distance:Math.hypot(g,M),scale:G.scale,centerX:(c[0].x+c[1].x)/2,centerY:(c[0].y+c[1].y)/2},Q.current=null}},[G.scale,G.x,G.y]),va=a.useCallback(t=>{if(L.current.has(t.pointerId)){if(L.current.set(t.pointerId,{x:t.clientX,y:t.clientY}),L.current.size>=2){const l=Array.from(L.current.values()),c=be.current;if(!c)return;const g=l[0].x-l[1].x,M=l[0].y-l[1].y,z=Math.hypot(g,M),fe=c.scale*(z/c.distance);nt(fe,c.centerX,c.centerY);return}!Q.current||Q.current.pointerId!==t.pointerId||B(l=>X({...l,x:t.clientX-Q.current.x,y:t.clientY-Q.current.y}))}},[X,nt]),Pt=a.useCallback(t=>{L.current.delete(t.pointerId),L.current.size<2&&(be.current=null),L.current.size===0&&(Q.current=null,Fe(!1))},[]),fa=a.useCallback(t=>{if(t.key==="ArrowLeft")B(l=>X({...l,x:l.x+ot}));else if(t.key==="ArrowRight")B(l=>X({...l,x:l.x-ot}));else if(t.key==="ArrowUp")B(l=>X({...l,y:l.y+ot}));else if(t.key==="ArrowDown")B(l=>X({...l,y:l.y-ot}));else if(t.key==="+"||t.key==="=")B(l=>X({...l,scale:l.scale*1.1}));else if(t.key==="-")B(l=>X({...l,scale:l.scale*.9}));else if(t.key==="0")Ue();else if(t.key==="Home")B({scale:1,x:0,y:0});else return;t.preventDefault()},[X,Ue]),zt=a.useCallback(()=>{const t=[{value:"horizontal",label:"Horizontal",icon:e.jsx(Gt,{size:16}),ariaLabel:"Horizontal layout"},{value:"vertical",label:"Vertical",icon:e.jsx(Wt,{size:16}),ariaLabel:"Vertical layout"},{value:"auto",label:"Auto",icon:e.jsx(qe,{size:16}),ariaLabel:"Automatic layout"}];return e.jsx("div",{className:"agent-org-chart-layout-toggle","data-testid":"agent-org-chart-layout-toggle",children:t.map(l=>{const c=re===l.value;return e.jsxs("button",{type:"button",className:`btn-icon touch-target agent-org-chart-layout-toggle__button${c?" btn-icon--active":""}`,onClick:()=>Lt(l.value),"aria-pressed":c,"aria-label":l.ariaLabel,title:l.ariaLabel,"data-layout-value":l.value,children:[l.icon,e.jsx("span",{className:"agent-org-chart-layout-toggle__text",children:l.label})]},l.value)})})},[Lt,re]),ja=t=>Array.isArray(t.metadata?.skills)?t.metadata.skills:[],mt=t=>Xa(t),Ft=y&&k.length===0,et=a.useCallback(()=>{H(!0)},[]);return e.jsxs("div",{className:"agents-view",children:[e.jsxs("div",{className:"agents-view-header",children:[e.jsxs("div",{className:"agents-view-title",children:[e.jsx(St,{size:24}),e.jsx("h2",{children:"Agents"})]}),e.jsxs("div",{className:"agents-view-controls",children:[e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>ut("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:e.jsx(Wt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>ut("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:e.jsx(Ze,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="org"?" active":""}`,onClick:()=>ut("org"),title:"Org Chart view","aria-label":"Org Chart view","aria-pressed":S==="org",children:e.jsx(Gt,{size:16})})]}),e.jsxs("div",{className:"agents-view-primary-actions",children:[e.jsx("button",{ref:Oe,className:`btn-icon agent-controls-trigger${oe?" agent-controls-trigger--active":""}`,onClick:()=>J(t=>!t),title:"Controls","aria-label":"Controls","aria-haspopup":"dialog","aria-expanded":oe,"aria-controls":Pe,children:e.jsx(us,{size:16})}),e.jsx("button",{className:"btn-icon",onClick:()=>void C(),title:"Refresh","aria-label":"Refresh",children:e.jsx(qe,{size:16,className:y?"spin":void 0})}),!d&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm agent-import-trigger",onClick:()=>{I(!0),J(!1)},"aria-label":"Import",title:"Import",children:[e.jsx(At,{size:16}),"Import"]}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{et(),J(!1)},"aria-label":"New Agent",title:"New Agent",children:[e.jsx(Vt,{size:16}),"New Agent"]})]}),oe&&e.jsxs("div",{ref:we,id:Pe,className:"agent-controls-panel agent-controls-panel--scrollable",role:"dialog","aria-label":"Agent controls","aria-modal":"false",children:[e.jsx("div",{className:"agent-controls",children:e.jsxs("div",{className:"agent-controls-filters",children:[e.jsxs("div",{className:"agent-state-filter",children:[e.jsx(Wa,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:t=>j(t.target.value),"aria-label":"Filter agents by state",children:[e.jsx("option",{value:"all",children:"All States"}),e.jsx("option",{value:"idle",children:"Idle"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"running",children:"Running"}),e.jsx("option",{value:"paused",children:"Paused"}),e.jsx("option",{value:"error",children:"Error"})]})]}),e.jsxs("label",{className:"checkbox-label agent-system-filter",children:[e.jsx("input",{type:"checkbox",checked:m,onChange:t=>x(t.target.checked),"aria-label":"Show system agents"}),"Show system agents"]})]})}),d&&e.jsxs("div",{className:"agent-controls-mobile-actions",children:[e.jsxs("button",{className:"btn btn-sm agent-import-trigger",onClick:()=>{I(!0),J(!1)},"aria-label":"Import",title:"Import",children:[e.jsx(At,{size:16}),"Import"]}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{et(),J(!1)},"aria-label":"New Agent",title:"New Agent",children:[e.jsx(Vt,{size:16}),"New Agent"]})]}),e.jsx("div",{className:"agent-global-controls agent-controls-actions",children:e.jsxs("div",{className:"heartbeat-multiplier-group",children:[e.jsxs("div",{className:"heartbeat-multiplier-controls",children:[e.jsx("label",{htmlFor:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-label",children:"Heartbeat Speed"}),e.jsx("input",{id:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-slider touch-target",type:"range",min:.1,max:10,step:.1,value:Ve,onChange:t=>{const l=Number(t.target.value);Qe(Number.isFinite(l)&&l>0?l:1)},disabled:Ke}),e.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",Ve.toFixed(1)]}),e.jsx("select",{className:"heartbeat-multiplier-preset",value:String(kt.reduce((t,l)=>Math.abs(l-Ve)<Math.abs(t-Ve)?l:t,kt[0])),onChange:t=>{const l=Number(t.target.value);Qe(Number.isFinite(l)&&l>0?l:1)},disabled:Ke,"aria-label":"Heartbeat speed preset",children:kt.map(t=>e.jsxs("option",{value:String(t),children:["×",t]},t))})]}),e.jsx("small",{className:"text-secondary",children:"Scales all agent heartbeat intervals. ×0.5 = twice as fast, ×2.0 = twice as slow. Default: ×1.0"})]})}),e.jsx(xs,{agents:w})]})]})]})]}),e.jsx(Cs,{isOpen:E,onClose:()=>{H(!1),_(null)},onCreated:()=>{H(!1),_(null),C()},projectId:r,prefillDraft:R,agentOnboardingEnabled:u,existingAgents:k,onPrefillDraft:_}),e.jsx(As,{isOpen:b,onClose:()=>I(!1),onImported:()=>void C(),projectId:r}),e.jsx(ks,{stats:A,activeAgents:_e,projectId:r,isOpen:ce,onToggle:()=>pe(t=>!t),onSelectAgent:ga,onOpenTaskLogs:p}),S==="org"?e.jsx("div",{className:"agents-org-full-view",children:e.jsx("div",{className:"agents-view-content agents-view-content--org-full",children:$?e.jsxs("div",{className:"agents-org-detail-view","data-testid":"agents-org-detail-view",children:[e.jsx("button",{type:"button",className:"btn btn-sm agents-org-detail-back",onClick:We,"aria-label":"Back to org chart",children:"Back to org chart"}),e.jsx(a.Suspense,{fallback:null,children:e.jsx(ea,{inline:!0,showInlineBackButton:!1,agentId:$,projectId:r,onClose:We,addToast:n,onChildClick:Et,initialTab:ae,initialRunId:F,preferActiveRun:me},$)})]}):Ft?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):e.jsxs("div",{className:"agent-org-chart-shell","data-testid":"agent-org-chart-shell",children:[d?e.jsxs("div",{className:"agent-org-chart-controls","data-testid":"agent-org-chart-controls",children:[zt(),It()]}):e.jsxs("div",{className:"agent-org-chart-toolbar",children:[zt(),e.jsx("div",{className:"agent-org-chart-controls","data-testid":"agent-org-chart-controls",children:It()})]}),e.jsx("div",{ref:de,className:"agent-org-chart-viewport","data-testid":"agent-org-chart-viewport",tabIndex:0,role:"region","aria-label":"Org chart canvas",onWheel:xa,onPointerDown:ba,onPointerMove:va,onPointerUp:Pt,onPointerCancel:Pt,onKeyDown:fa,"data-panning":Le?"true":"false",children:e.jsxs("div",{ref:xe,className:"agent-org-chart-canvas","data-panning":Le?"true":"false",style:{transform:`translate(${G.x}px, ${G.y}px) scale(${G.scale})`},children:[e.jsx("div",{className:`agent-org-chart${lt==="vertical"?" agent-org-chart--vertical":""}`,"data-testid":"agent-org-chart","data-layout-mode":lt,children:ye?e.jsxs("div",{className:"agent-org-chart__loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{size:18,className:"spin"}),e.jsx("span",{children:"Loading org chart..."})]}):V.length===0?e.jsx(ft,{onCtaClick:et}):(D.current=[],V.map(t=>e.jsx(la,{node:t,onSelect:ua,getHealthStatus:mt,selectedAgentId:Ne,registerNodeElement:pa,linksRef:D},t.agent.id)))}),e.jsx(zs,{links:D.current,nodeElements:Ae.current,canvasRef:xe,viewportRef:de,layoutMode:lt,transform:G})]})})]})})}):e.jsxs("div",{className:"agents-split-layout",children:[e.jsx("div",{className:`agents-split-sidebar${K?" agents-split-sidebar--hidden-mobile":""}`,children:e.jsx("div",{className:"agents-view-content",children:Ft?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):S==="board"?e.jsx("div",{className:"agent-board",children:w.length===0?e.jsx(ft,{onCtaClick:et}):w.map(t=>{const l=mt(t),c=Mt(t,l),g=Rt(t.state),M=Tt("agent-board-card",t.state);return e.jsx("div",{className:`agent-board-card ${M}${$===t.id?" agent-card--selected":""}`,children:e.jsxs("div",{className:"agent-board-clickable",onClick:()=>ue(t.id),role:"button",tabIndex:0,onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.key===" "&&z.preventDefault(),ue(t.id))},children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:e.jsx(dt,{agent:t,size:20})}),e.jsx("span",{className:"agent-board-badge badge text-secondary",children:$t(t.role)}),e.jsx("span",{className:`agent-board-badge badge ${g}`,children:t.state}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"agent-board-badge badge agent-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),t.pendingApprovalCount]}):null]}),e.jsx("div",{className:"agent-board-name",children:t.name}),e.jsx("div",{className:"agent-board-id",children:t.id}),e.jsxs("div",{className:"agent-board-health",style:{color:l.color},title:c.title,children:[l.icon,c.label?` ${c.label}`:""]})]})},t.id)})}):e.jsx("div",{className:"agent-list",children:w.length===0?e.jsx(ft,{onCtaClick:et}):w.map(t=>{const l=mt(t),c=Mt(t,l),g=Rt(t.state),M=Tt("agent-card",t.state),z=wt(t.runtimeConfig?.heartbeatIntervalMs),fe=Ga(z),je=se===t.id;return e.jsxs("div",{className:`agent-card agent-card--clickable ${M}${$===t.id?" agent-card--selected":""}`,onClick:h=>{const W=h.target;if(W===h.currentTarget){ue(t.id);return}const ne=W.closest('button, select, input, [role="button"]');ne&&ne!==h.currentTarget||ue(t.id)},role:"button",tabIndex:0,onKeyDown:h=>{h.target===h.currentTarget&&(h.key==="Enter"||h.key===" ")&&(h.key===" "&&h.preventDefault(),ue(t.id))},"aria-label":`Open details for ${t.name}`,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info",children:[i===t.id?e.jsx("select",{ref:O,className:"select agent-role-select",value:t.role,onChange:h=>void ra(t.id,h.target.value),onKeyDown:h=>oa(h,t.id),onBlur:()=>v(null),autoFocus:!0,children:yt.map(h=>e.jsxs("option",{value:h.value,children:[h.icon," ",h.label]},h.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:h=>{h.stopPropagation(),v(t.id)},title:"Click to change role",role:"button",tabIndex:0,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.stopPropagation(),v(t.id))},children:e.jsx(dt,{agent:t,size:20})}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:t.name}),e.jsx("span",{className:"agent-id text-secondary",children:t.id})]}),e.jsx(ta,{size:20,className:"agent-card-chevron"})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:`badge ${g}`,children:t.state}),e.jsxs("span",{className:"badge",style:{color:l.color},title:c.title,children:[l.icon,c.label?` ${c.label}`:""]}),e.jsx("span",{className:"badge text-secondary",children:$t(t.role)}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),t.pendingApprovalCount]}):null,(()=>{const h=ja(t);if(h.length===0)return null;const W=h.slice(0,2),ne=h.length-2;return e.jsxs(e.Fragment,{children:[W.map(tt=>e.jsx("span",{className:"badge badge-skill",title:tt,children:ns(tt)},tt)),ne>0&&e.jsxs("span",{className:"badge badge-skill",children:["+",ne]})]})})()]})]}),e.jsxs("div",{className:"agent-card-body",children:[t.state==="error"&&t.lastError?e.jsx(Va,{errorText:t.lastError,issueContext:{surface:"AgentsView list",agentId:t.id,agentName:t.name,agentState:t.state,taskId:t.taskId}}):null,t.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:t.taskId})]}),e.jsxs("div",{className:"agent-heartbeat-control",children:[e.jsx("span",{className:"text-secondary",children:"Heartbeat:"}),Y===t.id?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"input agent-heartbeat-custom-input",value:De[t.id]??"",onChange:h=>Te(W=>({...W,[t.id]:h.target.value})),onKeyDown:h=>{h.key==="Enter"?_t(t):h.key==="Escape"&&(Ce(null),Te(W=>{const ne={...W};return delete ne[t.id],ne}))},disabled:je,"aria-label":`Custom heartbeat interval in minutes for ${t.name}`}),e.jsx("span",{className:"text-secondary",children:"min"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void _t(t),disabled:je,title:"Save custom interval",children:"Save"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{Ce(null),Te(h=>{const W={...h};return delete W[t.id],W})},disabled:je,title:"Cancel custom interval",children:"Cancel"})]}):e.jsx(e.Fragment,{children:e.jsxs("select",{className:"select agent-heartbeat-select",value:z,onChange:h=>{const W=h.target.value;W==="__custom__"?da(t):ca(t,Number(W))},disabled:je,"aria-label":`Set heartbeat interval for ${t.name}`,children:[fe.map(h=>e.jsx("option",{value:h.value,children:h.label},h.value)),Ka.some(h=>h.value===z)&&e.jsx("option",{value:"__custom__",children:"Custom..."})]})}),je&&e.jsx("span",{className:"agent-heartbeat-saving text-secondary",children:"Saving…"}),t.lastHeartbeatAt&&(()=>{const h=new Date(t.lastHeartbeatAt),W=new Date(h.getTime()+z),ne=t.state==="active"||t.state==="running";return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"agent-heartbeat-last text-secondary",title:h.toLocaleString(),children:["Last: ",h.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})]}),ne&&e.jsxs("span",{className:"agent-heartbeat-next text-secondary",title:W.toLocaleString(),children:["Next: ",W.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})]})]})})()]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs("div",{className:"agent-card-actions-group agent-card-actions-group--primary",children:[t.state==="idle"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"active"),disabled:Me.has(t.id),title:"Activate",children:[e.jsx(bt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Start"})]}),t.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ha(t.id,t.name),disabled:Me.has(t.id),title:"Run Now","aria-label":`Run now for ${t.name}`,children:[e.jsx(Ze,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Run Now"})]}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"paused"),disabled:Me.has(t.id),title:"Pause",children:[e.jsx(Kt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Pause"})]})]}),t.state==="paused"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"active"),disabled:Me.has(t.id),title:"Resume",children:[e.jsx(bt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Resume"})]}),t.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>ue(t.id,{initialTab:"runs",initialRunId:null,preferActiveRun:!0}),title:"View live run details","aria-label":`View live run details for ${t.name}`,children:[e.jsx(Ze,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Running"})]}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"paused"),disabled:Me.has(t.id),title:"Pause",children:[e.jsx(Kt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Pause"})]})]}),t.state==="error"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"active"),disabled:Me.has(t.id),title:"Retry",children:[e.jsx(bt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Retry"})]})]}),e.jsxs("div",{className:"agent-card-actions-group agent-card-actions-group--secondary",children:[e.jsxs("button",{className:"btn btn-sm agent-card-details-btn",onClick:()=>ue(t.id),title:`View details for ${t.name}`,"aria-label":`View details for ${t.name}`,children:[e.jsx(rs,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Details"})]}),(t.state==="idle"||t.state==="paused")&&e.jsxs("button",{className:"btn btn-sm btn-danger",onClick:()=>void ia(t.id,t.name),title:"Delete",children:[e.jsx(Ua,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Delete"})]})]})]})]},t.id)})})})}),e.jsx("div",{className:`agents-split-detail${d&&!$?" agents-split-detail--hidden-mobile":""}`,children:$?e.jsx(a.Suspense,{fallback:null,children:e.jsx(ea,{inline:!0,showInlineBackButton:d,agentId:$,projectId:r,onClose:We,addToast:n,onChildClick:Et,initialTab:ae,initialRunId:F,preferActiveRun:me,onMutationSuccess:ma},$)}):e.jsxs("div",{className:"agents-detail-empty-state",children:[e.jsx(St,{size:48}),e.jsx("h3",{children:"Select an agent"}),e.jsx("p",{children:"Choose an agent from the sidebar to view details"})]})})]})]})}export{Vs as AgentsView};
34
+ Agent instructions go here...`,value:j,onChange:i=>{f("paste"),y([]),k(i.target.value),F(null)},rows:8,"aria-label":"Manifest content"})]}),e.jsxs("p",{className:"agent-import-file-hint",children:["Current input: ",d]}),ie&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(pt,{size:14}),ie]})]}),x==="preview"&&e.jsxs("div",{className:"agent-import-preview",children:[e.jsxs("div",{className:"agent-import-company",children:[e.jsx("span",{className:"agent-import-company-label",children:"Company"}),e.jsx("span",{className:"agent-import-company-name",children:C})]}),e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Ct,{size:14}),e.jsxs("span",{children:[E.length," agent",E.length!==1?"s":""," found"]})]}),E.length>0&&e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>I(E.map(i=>i.name)),children:"Select all agents"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>I([]),children:"Clear agents"})]}),E.length>0?e.jsx("div",{className:"agent-import-agent-list",children:E.map((i,v)=>e.jsxs("div",{className:"agent-import-agent-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select agent ${i.name}`,checked:b.includes(i.name),onChange:()=>Oe(i.name)})}),e.jsx("span",{className:"agent-import-agent-icon",children:i.icon||"🤖"}),e.jsxs("div",{className:"agent-import-agent-details",children:[e.jsx("span",{className:"agent-import-agent-name",children:i.name}),e.jsxs("span",{className:"agent-import-agent-meta",children:[i.title&&e.jsxs("span",{className:"agent-import-agent-title",children:[i.title," · "]}),e.jsx("span",{className:"agent-import-agent-role",children:i.role}),i.reportsTo&&e.jsxs("span",{className:"agent-import-agent-reports",children:[" · reports to ",i.reportsTo]}),i.skills&&i.skills.length>0&&e.jsxs("span",{className:"agent-import-agent-model",children:[" · skills: ",i.skills.join(", ")]})]}),i.instructionsText&&e.jsxs("span",{className:"agent-import-agent-instructions",children:[i.instructionsText.slice(0,100),i.instructionsText.length>100?"...":""]})]})]},v))}):e.jsx("p",{className:"agent-import-empty",children:"No agents found in the manifest."}),R.length>0&&e.jsxs("div",{className:"agent-import-skills-section",children:[e.jsxs("div",{className:"agent-import-count",children:[e.jsx(Ct,{size:14}),e.jsxs("span",{children:[R.length," skill",R.length!==1?"s":""," found"]})]}),e.jsxs("div",{className:"agent-import-selection-controls",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>q(R.map(i=>i.name)),children:"Select all skills"}),e.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>q([]),children:"Clear skills"})]}),e.jsx("div",{className:"agent-import-skill-list",children:R.map((i,v)=>e.jsxs("div",{className:"agent-import-skill-item",children:[e.jsx("label",{className:"checkbox-label",children:e.jsx("input",{type:"checkbox","aria-label":`Select skill ${i.name}`,checked:$.includes(i.name),onChange:()=>Pe(i.name)})}),e.jsx("span",{className:"agent-import-skill-icon",children:"⚡"}),e.jsxs("div",{className:"agent-import-skill-details",children:[e.jsx("span",{className:"agent-import-skill-name",children:i.name}),i.description&&e.jsx("span",{className:"agent-import-skill-description",children:i.description})]})]},`${i.name}-${v}`))})]}),ge&&e.jsxs("p",{className:"agent-dialog-error",children:[e.jsx(pt,{size:14}),ge]})]}),x==="result"&&N&&e.jsxs("div",{className:"agent-import-result",children:[e.jsx("div",{className:"agent-import-result-icon",children:e.jsx(ct,{size:32})}),e.jsx("h3",{className:"agent-import-result-title",children:"Import Complete"}),e.jsxs("p",{className:"agent-import-result-company",children:["From ",e.jsx("strong",{children:N.companyName??"Unknown"})]}),e.jsxs("div",{className:"agent-import-result-stats",children:[N.created.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[N.created.length," created"]})}),N.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[N.skipped.length," skipped (already exist)"]})}),N.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[N.errors.length," error",N.errors.length!==1?"s":""]})})]}),N.created.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:N.created.map((i,v)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(ct,{size:12}),e.jsx("span",{children:i.name})]},v))}),N.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:N.errors.map((i,v)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(Ht,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},v))}),N.skills&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-import-result-divider"}),e.jsx("h4",{className:"agent-import-result-section-title",children:"Skills"}),e.jsxs("div",{className:"agent-import-result-stats",children:[N.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--success",children:e.jsxs("span",{children:[N.skills.imported.length," skill",N.skills.imported.length!==1?"s":""," imported"]})}),N.skills.skipped.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsxs("span",{children:[N.skills.skipped.length," skill",N.skills.skipped.length!==1?"s":""," skipped (already exist)"]})}),N.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--error",children:e.jsxs("span",{children:[N.skills.errors.length," skill",N.skills.errors.length!==1?"s":""," error",N.skills.errors.length!==1?"s":""]})}),N.skills.imported.length===0&&N.skills.skipped.length===0&&N.skills.errors.length===0&&e.jsx("div",{className:"agent-import-result-stat agent-import-result-stat--skipped",children:e.jsx("span",{children:"No skills in package"})})]}),N.skills.imported.length>0&&e.jsx("div",{className:"agent-import-result-agents",children:N.skills.imported.map((i,v)=>e.jsxs("div",{className:"agent-import-result-agent",children:[e.jsx(ct,{size:12}),e.jsx("span",{children:i.name})]},v))}),N.skills.errors.length>0&&e.jsx("div",{className:"agent-import-result-errors",children:N.skills.errors.map((i,v)=>e.jsxs("div",{className:"agent-import-result-error",children:[e.jsx(Ht,{size:12}),e.jsxs("span",{children:[i.name,": ",i.error]})]},v))})]})]})]}),e.jsxs("div",{className:"agent-dialog-footer",children:[x==="preview"&&e.jsx("button",{className:"btn",onClick:()=>o("input"),disabled:K,children:"Back"}),e.jsx("button",{className:"btn",onClick:Le,disabled:K,children:x==="result"?"Close":"Cancel"}),x==="input"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void xe(),disabled:Ne||(d==="directory"?A.length===0:d==="browse"?!U:!j.trim()),children:Ne?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:14,className:"spin"}),"Parsing..."]}):"Preview"}),x==="preview"&&e.jsx("button",{className:"btn btn-task-create",onClick:()=>void Ae(),disabled:K||D===0&&L===0,children:K?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:14,className:"spin"}),Ie]}):`Import ${Re}`})]})]})}):null}const Nt="fn-agent-org-chart-layout";function Qt(n){return n==="auto"||n==="horizontal"||n==="vertical"}const Rs=768,Ts={nodeWidth:220,siblingGap:24,rootGap:24,chartPadding:24},Ms={nodeWidth:160,siblingGap:8,rootGap:8,chartPadding:8};function sa(n){return n.children.length===0?1:n.children.reduce((r,p)=>r+sa(p),0)}function _s(n){return n<=Rs?Ms:Ts}function Es(n,r){const p=sa(n);return p*r.nodeWidth+Math.max(0,p-1)*r.siblingGap}function $s(n,r=Number.POSITIVE_INFINITY){const p=_s(r);if(n.length===0)return p.nodeWidth;const m=n.map(o=>Es(o,p)).reduce((o,d)=>o+d,0),x=Math.max(0,n.length-1)*p.rootGap;return m+x+p.chartPadding*2}function Ls(n){const r=n.preference??"auto";if(r!=="auto")return r;const p=Number.isFinite(n.availableWidth)&&n.availableWidth>0?n.availableWidth:0;return p===0||n.tree.length<=1?"horizontal":$s(n.tree,p)>p?"vertical":"horizontal"}const ea=a.lazy(()=>Ya(()=>import("./AgentDetailView-CnFf_eBZ.js"),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11])).then(n=>({default:n.AgentDetailView}))),yt=[{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:"✦"}],kt=[.1,.25,.5,1,2,3,5,10],Is=.25,Ps=3,ot=16,Xe=32;function Rt(n){switch(n){case"running":return"agent-badge--running";case"active":return"agent-badge--active";case"paused":return"agent-badge--paused";case"error":return"agent-badge--error";case"idle":default:return"agent-badge--idle"}}function Tt(n,r){switch(r){case"running":return`${n}--running`;case"active":return`${n}--active`;case"paused":return`${n}--paused`;case"error":return`${n}--error`;case"idle":default:return`${n}--idle`}}function na(n){return n.children.length===0?1:n.children.reduce((r,p)=>r+na(p),0)}function Mt(n,r){return n.state==="error"?{title:void 0,label:"Error"}:{title:r.reason??r.label,label:r.stateDerived?null:r.label}}function la({node:n,onSelect:r,getHealthStatus:p,selectedAgentId:u,registerNodeElement:m,linksRef:x}){const{agent:o,children:d}=n,f=p(o),j=Mt(o,f),k=Rt(o.state),A=Tt("org-chart-node-card",o.state),y=na(n),C={"--org-chart-subtree-leaves":String(y)};return e.jsxs("div",{className:`org-chart-node${d.length>0?" org-chart-node--has-children":""}`,style:C,children:[e.jsxs("div",{ref:T=>m(o.id,T),"data-agent-id":o.id,className:`org-chart-node-card ${A}${u===o.id?" agent-card--selected":""}`,onClick:()=>r(o.id),role:"button",tabIndex:0,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.key===" "&&T.preventDefault(),r(o.id))},children:[e.jsxs("div",{className:"org-chart-node__header",children:[e.jsx("span",{className:"org-chart-node__icon",children:e.jsx(dt,{agent:o,size:20})}),e.jsx("span",{className:"org-chart-node__name",children:o.name})]}),e.jsxs("div",{className:"org-chart-node__meta",children:[e.jsx("span",{className:`org-chart-node__badge ${k}`,children:o.state}),e.jsxs("span",{className:"org-chart-node__health",style:{color:f.color},title:j.title,children:[f.icon,j.label&&e.jsx("span",{className:"text-secondary",children:j.label})]})]})]}),d.length>0&&e.jsx("div",{className:"org-chart-children",role:"group","aria-label":`${o.name} employees`,children:d.map(T=>(x.current.push({parentId:o.id,childId:T.agent.id}),e.jsx(la,{node:T,onSelect:r,getHealthStatus:p,selectedAgentId:u,registerNodeElement:m,linksRef:x},T.agent.id)))})]})}function zs({links:n,nodeElements:r,canvasRef:p,viewportRef:u,layoutMode:m,transform:x}){const[o,d]=a.useState([]);return a.useLayoutEffect(()=>{const f=p.current,j=u.current;if(!f||!j||n.length===0){d([]);return}const k=()=>{const y=f.getBoundingClientRect(),C=n.flatMap(({parentId:T,childId:E})=>{const H=r.get(T),R=r.get(E);if(!H||!R)return[];const _=H.getBoundingClientRect(),b=R.getBoundingClientRect(),I=(_.left-y.left)/x.scale,$=(_.top-y.top)/x.scale,q=(b.left-y.left)/x.scale,Ne=(b.top-y.top)/x.scale;if(m==="vertical"){const N=I,me=$+_.height/x.scale/2,ge=q,S=Ne+b.height/x.scale/2,Z=N-(N-ge)/2;return[`M ${N} ${me} L ${Z} ${me} L ${Z} ${S} L ${ge} ${S}`]}const le=I+_.width/x.scale/2,K=$+_.height/x.scale,ae=q+b.width/x.scale/2,ie=Ne,F=K+(ie-K)/2;return[`M ${le} ${K} L ${le} ${F} L ${ae} ${F} L ${ae} ${ie}`]});d(C)};k();const A=new ResizeObserver(k);return A.observe(f),A.observe(j),r.forEach(y=>A.observe(y)),()=>A.disconnect()},[p,m,n,r,x.scale,u]),e.jsx("svg",{className:"agent-org-chart-connectors","aria-hidden":"true",children:o.map((f,j)=>e.jsx("path",{d:f},`${j}-${f}`))})}function Vs({addToast:n,projectId:r,onOpenTaskLogs:p,agentOnboardingEnabled:u=!1}){const[m,x]=a.useState(!1),d=Ia()==="mobile",[f,j]=a.useState("all"),{agents:k,stats:A,isLoading:y,loadAgents:C,refreshAgents:T}=Pa(r,{filterState:f,showSystemAgents:m}),[E,H]=a.useState(!1),[R,_]=a.useState(null),[b,I]=a.useState(!1),[$,q]=a.useState(null),[Ne,le]=a.useState(null),K=d&&!!$,[ae,ie]=a.useState("dashboard"),[F,N]=a.useState(null),[me,ge]=a.useState(!1),[S,Z]=a.useState(()=>{if(typeof window>"u")return"list";const t=it("fn-agent-view",r);return t==="list"||t==="board"||t==="org"?t:"list"}),[re,$e]=a.useState(()=>{if(typeof window>"u")return"auto";const t=it(Nt,r);return Qt(t)?t:"auto"}),[ee,te]=a.useState([]),[ye,U]=a.useState(!1),[he,ke]=a.useState(0),[oe,J]=a.useState(!1),[ce,pe]=a.useState(!1),[G,B]=a.useState({scale:1,x:0,y:0}),[Le,Fe]=a.useState(!1),we=a.useRef(null),de=a.useRef(null),xe=a.useRef(null),Ae=a.useRef(new Map),D=a.useRef([]),L=a.useRef(new Map),Q=a.useRef(null),be=a.useRef(null),Re=a.useRef(!1),{confirm:Ie}=za(),Oe=a.useRef(null),Pe=a.useId();a.useEffect(()=>{const t=it("fn-agent-view",r);if(t==="list"||t==="board"||t==="org"){Z(t);return}Z("list")},[r]),a.useEffect(()=>{Bt("fn-agent-view",S,r)},[S,r]),a.useEffect(()=>{const t=it(Nt,r);$e(Qt(t)?t:"auto")},[r]),a.useEffect(()=>{Bt(Nt,re,r)},[re,r]);const[i,v]=a.useState(null),O=a.useRef(null),[se,P]=a.useState(null),[Y,Ce]=a.useState(null),[De,Te]=a.useState({}),[Ve,st]=a.useState(1),[Ke,He]=a.useState(!1),[Me,Je]=a.useState(new Set),[ze,Se]=a.useState(new Map),Be=a.useRef(!0);a.useEffect(()=>(Be.current=!0,()=>{Be.current=!1}),[]),a.useEffect(()=>{Fa(r).then(t=>{Be.current&&st(t.heartbeatMultiplier??1)}).catch(()=>{})},[r]);const Qe=a.useCallback(async t=>{const l=Number.isFinite(t)&&t>0?t:1;st(l),He(!0);try{await Oa({heartbeatMultiplier:l},r),n(`Heartbeat speed set to ×${l.toFixed(1)}`,"success")}catch(c){n(`Failed to save heartbeat multiplier: ${Ee(c)}`,"error")}finally{Be.current&&He(!1)}},[r,n]),s=a.useMemo(()=>ze.size===0?k:k.map(t=>{const l=ze.get(t.id);return l?{...t,state:l}:t}),[k,ze]),w=a.useMemo(()=>s.filter(t=>m||!xt(t)),[s,m]),_e=a.useMemo(()=>s.filter(t=>t.state!=="active"&&t.state!=="running"?!1:m||!xt(t)),[s,m]),V=a.useMemo(()=>{if(m)return ee;const t=l=>xt(l.agent)?null:{...l,children:l.children.map(t).filter(c=>c!==null)};return ee.map(t).filter(l=>l!==null)},[ee,m]);a.useEffect(()=>{if(S!=="org")return;const t=de.current;if(!t)return;const l=()=>{ke(t.clientWidth)};l();const c=typeof ResizeObserver<"u"?new ResizeObserver(l):null;return c?.observe(t),window.addEventListener("resize",l),()=>{c?.disconnect(),window.removeEventListener("resize",l)}},[S,V.length]),a.useEffect(()=>{if(S!=="org")return;let t=!1;return U(!0),Da(r,{includeEphemeral:m}).then(l=>{t||te(l)}).catch(l=>{t||(n(`Failed to load org chart: ${Ee(l)}`,"error"),te([]))}).finally(()=>{t||U(!1)}),()=>{t=!0}},[S,r,m,n]),a.useEffect(()=>{const t=setInterval(()=>{C()},3e4);return()=>{clearInterval(t)}},[C]),a.useEffect(()=>{if(!oe)return;const t=c=>{const g=c.target;g&&(we.current?.contains(g)||Oe.current?.contains(g)||J(!1))},l=c=>{c.key==="Escape"&&(J(!1),Oe.current?.focus())};return document.addEventListener("mousedown",t),document.addEventListener("touchstart",t),document.addEventListener("keydown",l),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("touchstart",t),document.removeEventListener("keydown",l)}},[oe]);const ve=async(t,l)=>{if(!Me.has(t)){Je(c=>new Set(c).add(t)),Se(c=>{const g=new Map(c);return g.set(t,l),g});try{await Za(t,l,r),n(`Agent state updated to ${l}`,"success"),await C(),Se(c=>{const g=new Map(c);return g.delete(t),g})}catch(c){Se(g=>{const M=new Map(g);return M.delete(t),M}),n(`Failed to update state: ${Ee(c)}`,"error")}finally{Je(c=>{const g=new Set(c);return g.delete(t),g})}}},ia=async(t,l)=>{if(await Ie({title:"Delete Agent",message:`Delete agent "${l}"? This cannot be undone.`,danger:!0}))try{await Qa(t,r),n(`Agent "${l}" deleted`,"success"),await C()}catch(g){n(`Failed to delete agent: ${Ee(g)}`,"error")}},ra=async(t,l)=>{const c=k.find(g=>g.id===t);if(c){if(c.role===l){v(null);return}try{await rt(t,{role:l},r),n(`Agent role updated to ${yt.find(g=>g.value===l)?.label??l}`,"success"),v(null),C()}catch(g){n(`Failed to update role: ${Ee(g)}`,"error")}}},oa=(t,l)=>{t.key==="Escape"&&v(null)},ca=async(t,l)=>{Y===t.id&&(Ce(null),Te(c=>{const g={...c};return delete g[t.id],g})),P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:l}},r),n(`Heartbeat interval updated to ${Ut(l)} for ${t.name}`,"success"),C()}catch(c){n(`Failed to update heartbeat interval: ${Ee(c)}`,"error")}finally{P(null)}},_t=async t=>{const l=De[t.id]??"";if(l.trim()===""){n("Please enter a heartbeat interval in minutes","error");return}const c=Number(l);if(isNaN(c)){n("Heartbeat interval must be a valid number","error");return}if(c<=0){n("Heartbeat interval must be greater than 0","error");return}if(c>=1&&c<5){P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:qa}},r),n(`Heartbeat interval set to 5 minutes (minimum). ${c} minute${c!==1?"s":""} was below the 5-minute minimum.`,"success"),Ce(null),Te(M=>{const z={...M};return delete z[t.id],z}),C()}catch(M){n(`Failed to update heartbeat interval: ${Ee(M)}`,"error")}finally{P(null)}return}const g=Math.round(c*6e4);P(t.id);try{await rt(t.id,{runtimeConfig:{...t.runtimeConfig??{},heartbeatIntervalMs:g}},r),n(`Heartbeat interval updated to ${Ut(g)} for ${t.name}`,"success"),Ce(null),Te(M=>{const z={...M};return delete z[t.id],z}),C()}catch(M){n(`Failed to update heartbeat interval: ${Ee(M)}`,"error")}finally{P(null)}},da=t=>{const l=wt(t.runtimeConfig?.heartbeatIntervalMs),c=Math.round(l/6e4);Ce(t.id),Te(g=>({...g,[t.id]:String(c)}))},ue=a.useCallback((t,l)=>{q(t),ie(l?.initialTab??"dashboard"),N(l?.initialRunId??null),ge(l?.preferActiveRun??!1)},[]),We=a.useCallback(()=>{q(null),ie("dashboard"),N(null),ge(!1)},[]),Et=a.useCallback(t=>{ue(t)},[ue]),ua=a.useCallback(t=>{le(t),ue(t)},[ue]),ma=a.useCallback(async({agentId:t,deleted:l})=>{await T(),l&&$===t&&We()},[T,$,We]),ga=a.useCallback(t=>{ue(t),d&&pe(!1)},[d,ue]),ha=async(t,l)=>{Se(c=>{const g=new Map(c);return g.set(t,"running"),g});try{await Ja(t,r,{source:"on_demand",triggerDetail:"Triggered from dashboard"}),n(`Heartbeat run started for ${l}`,"success"),await C(),Se(c=>{const g=new Map(c);return g.delete(t),g})}catch(c){Se(g=>{const M=new Map(g);return M.delete(t),M}),n(`Failed to start heartbeat run: ${Ee(c)}`,"error")}},Ge=a.useCallback(t=>Math.min(Ps,Math.max(Is,t)),[]),X=a.useCallback(t=>{const l=de.current,c=xe.current?.querySelector(".agent-org-chart");if(!l||!c)return{...t,scale:Ge(t.scale)};const g=Ge(t.scale),M=c.scrollWidth*g,z=c.scrollHeight*g,fe=l.clientWidth,je=l.clientHeight,h=Math.min(Xe,fe-M-Xe),W=Xe,ne=Math.min(Xe,je-z-Xe),tt=Xe;return{scale:g,x:Math.max(h,Math.min(W,t.x)),y:Math.max(ne,Math.min(tt,t.y))}},[Ge]),nt=a.useCallback((t,l,c)=>{const g=de.current;g&&B(M=>{const z=Ge(t),fe=g.getBoundingClientRect(),je=l-fe.left,h=c-fe.top,W=(je-M.x)/M.scale,ne=(h-M.y)/M.scale;return X({scale:z,x:je-W*z,y:h-ne*z})})},[Ge,X]),Ue=a.useCallback(()=>{const t=de.current,l=xe.current?.querySelector(".agent-org-chart");if(!t||!l)return;const c=t.clientWidth,g=t.clientHeight,M=l.scrollWidth,z=l.scrollHeight;if(M<=0||z<=0)return;const fe=Ge(Math.min(c/M,g/z,1)),je=(c-M*fe)/2,h=(g-z*fe)/2;B(X({scale:fe,x:je,y:h}))},[Ge,X]),ut=a.useCallback(t=>{Z(t),t!=="org"&&B({scale:1,x:0,y:0}),d&&$&&We()},[We,d,$]),$t=t=>yt.find(l=>l.value===t)?.label??t,lt=a.useMemo(()=>Ls({tree:V,availableWidth:he,preference:re}),[V,re,he]),Lt=a.useCallback(t=>{$e(t),B({scale:1,x:0,y:0})},[]);a.useEffect(()=>{B({scale:1,x:0,y:0}),Re.current=!1},[r,lt]),a.useLayoutEffect(()=>{S!=="org"||ye||V.length===0||Re.current||(Ue(),Re.current=!0)},[S,V.length,Ue,ye]);const pa=a.useCallback((t,l)=>{l?Ae.current.set(t,l):Ae.current.delete(t)},[]),It=a.useCallback(()=>e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn-icon touch-target",onClick:()=>B(t=>X({...t,scale:t.scale*.9})),"aria-label":"Zoom out org chart",title:"Zoom out",children:e.jsx(ps,{size:16})}),e.jsxs("span",{className:"agent-org-chart-controls__zoom-label","aria-live":"polite",children:[Math.round(G.scale*100),"%"]}),e.jsx("button",{type:"button",className:"btn-icon touch-target",onClick:()=>B(t=>X({...t,scale:t.scale*1.1})),"aria-label":"Zoom in org chart",title:"Zoom in",children:e.jsx(gs,{size:16})}),e.jsxs("button",{type:"button",className:"btn touch-target btn-sm agent-org-chart-controls__fit-btn",onClick:Ue,"aria-label":"Fit org chart",title:"Fit org chart",children:[e.jsx(Ha,{size:16}),"Fit"]}),e.jsxs("button",{type:"button",className:"btn touch-target btn-sm",onClick:()=>B(t=>X({...t,x:0,y:0})),"aria-label":"Center org chart",title:"Center org chart",children:[e.jsx(Ba,{size:16}),"Center"]})]}),[X,Ue,G.scale]),xa=a.useCallback(t=>{if(!(t.ctrlKey||t.metaKey))return;t.preventDefault();const l=t.deltaY>0?.9:1.1;nt(G.scale*l,t.clientX,t.clientY)},[G.scale,nt]),ba=a.useCallback(t=>{if(t.target.closest(".org-chart-node-card"))return;if(t.currentTarget.setPointerCapture?.(t.pointerId),L.current.set(t.pointerId,{x:t.clientX,y:t.clientY}),L.current.size===1){Q.current={x:t.clientX-G.x,y:t.clientY-G.y,pointerId:t.pointerId},Fe(!0);return}if(L.current.size===2){const c=Array.from(L.current.values()),g=c[0].x-c[1].x,M=c[0].y-c[1].y;be.current={distance:Math.hypot(g,M),scale:G.scale,centerX:(c[0].x+c[1].x)/2,centerY:(c[0].y+c[1].y)/2},Q.current=null}},[G.scale,G.x,G.y]),va=a.useCallback(t=>{if(L.current.has(t.pointerId)){if(L.current.set(t.pointerId,{x:t.clientX,y:t.clientY}),L.current.size>=2){const l=Array.from(L.current.values()),c=be.current;if(!c)return;const g=l[0].x-l[1].x,M=l[0].y-l[1].y,z=Math.hypot(g,M),fe=c.scale*(z/c.distance);nt(fe,c.centerX,c.centerY);return}!Q.current||Q.current.pointerId!==t.pointerId||B(l=>X({...l,x:t.clientX-Q.current.x,y:t.clientY-Q.current.y}))}},[X,nt]),Pt=a.useCallback(t=>{L.current.delete(t.pointerId),L.current.size<2&&(be.current=null),L.current.size===0&&(Q.current=null,Fe(!1))},[]),fa=a.useCallback(t=>{if(t.key==="ArrowLeft")B(l=>X({...l,x:l.x+ot}));else if(t.key==="ArrowRight")B(l=>X({...l,x:l.x-ot}));else if(t.key==="ArrowUp")B(l=>X({...l,y:l.y+ot}));else if(t.key==="ArrowDown")B(l=>X({...l,y:l.y-ot}));else if(t.key==="+"||t.key==="=")B(l=>X({...l,scale:l.scale*1.1}));else if(t.key==="-")B(l=>X({...l,scale:l.scale*.9}));else if(t.key==="0")Ue();else if(t.key==="Home")B({scale:1,x:0,y:0});else return;t.preventDefault()},[X,Ue]),zt=a.useCallback(()=>{const t=[{value:"horizontal",label:"Horizontal",icon:e.jsx(Gt,{size:16}),ariaLabel:"Horizontal layout"},{value:"vertical",label:"Vertical",icon:e.jsx(Wt,{size:16}),ariaLabel:"Vertical layout"},{value:"auto",label:"Auto",icon:e.jsx(qe,{size:16}),ariaLabel:"Automatic layout"}];return e.jsx("div",{className:"agent-org-chart-layout-toggle","data-testid":"agent-org-chart-layout-toggle",children:t.map(l=>{const c=re===l.value;return e.jsxs("button",{type:"button",className:`btn-icon touch-target agent-org-chart-layout-toggle__button${c?" btn-icon--active":""}`,onClick:()=>Lt(l.value),"aria-pressed":c,"aria-label":l.ariaLabel,title:l.ariaLabel,"data-layout-value":l.value,children:[l.icon,e.jsx("span",{className:"agent-org-chart-layout-toggle__text",children:l.label})]},l.value)})})},[Lt,re]),ja=t=>Array.isArray(t.metadata?.skills)?t.metadata.skills:[],mt=t=>Xa(t),Ft=y&&k.length===0,et=a.useCallback(()=>{H(!0)},[]);return e.jsxs("div",{className:"agents-view",children:[e.jsxs("div",{className:"agents-view-header",children:[e.jsxs("div",{className:"agents-view-title",children:[e.jsx(St,{size:24}),e.jsx("h2",{children:"Agents"})]}),e.jsxs("div",{className:"agents-view-controls",children:[e.jsxs("div",{className:"view-toggle",children:[e.jsx("button",{className:`view-toggle-btn${S==="list"?" active":""}`,onClick:()=>ut("list"),title:"List view","aria-label":"List view","aria-pressed":S==="list",children:e.jsx(Wt,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="board"?" active":""}`,onClick:()=>ut("board"),title:"Board view","aria-label":"Board view","aria-pressed":S==="board",children:e.jsx(Ze,{size:16})}),e.jsx("button",{className:`view-toggle-btn${S==="org"?" active":""}`,onClick:()=>ut("org"),title:"Org Chart view","aria-label":"Org Chart view","aria-pressed":S==="org",children:e.jsx(Gt,{size:16})})]}),e.jsxs("div",{className:"agents-view-primary-actions",children:[e.jsx("button",{ref:Oe,className:`btn-icon agent-controls-trigger${oe?" agent-controls-trigger--active":""}`,onClick:()=>J(t=>!t),title:"Controls","aria-label":"Controls","aria-haspopup":"dialog","aria-expanded":oe,"aria-controls":Pe,children:e.jsx(us,{size:16})}),e.jsx("button",{className:"btn-icon",onClick:()=>void C(),title:"Refresh","aria-label":"Refresh",children:e.jsx(qe,{size:16,className:y?"spin":void 0})}),!d&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm agent-import-trigger",onClick:()=>{I(!0),J(!1)},"aria-label":"Import",title:"Import",children:[e.jsx(At,{size:16}),"Import"]}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{et(),J(!1)},"aria-label":"New Agent",title:"New Agent",children:[e.jsx(Vt,{size:16}),"New Agent"]})]}),oe&&e.jsxs("div",{ref:we,id:Pe,className:"agent-controls-panel agent-controls-panel--scrollable",role:"dialog","aria-label":"Agent controls","aria-modal":"false",children:[e.jsx("div",{className:"agent-controls",children:e.jsxs("div",{className:"agent-controls-filters",children:[e.jsxs("div",{className:"agent-state-filter",children:[e.jsx(Wa,{size:14}),e.jsxs("select",{className:"agent-state-filter-select",value:f,onChange:t=>j(t.target.value),"aria-label":"Filter agents by state",children:[e.jsx("option",{value:"all",children:"All States"}),e.jsx("option",{value:"idle",children:"Idle"}),e.jsx("option",{value:"active",children:"Active"}),e.jsx("option",{value:"running",children:"Running"}),e.jsx("option",{value:"paused",children:"Paused"}),e.jsx("option",{value:"error",children:"Error"})]})]}),e.jsxs("label",{className:"checkbox-label agent-system-filter",children:[e.jsx("input",{type:"checkbox",checked:m,onChange:t=>x(t.target.checked),"aria-label":"Show system agents"}),"Show system agents"]})]})}),d&&e.jsxs("div",{className:"agent-controls-mobile-actions",children:[e.jsxs("button",{className:"btn btn-sm agent-import-trigger",onClick:()=>{I(!0),J(!1)},"aria-label":"Import",title:"Import",children:[e.jsx(At,{size:16}),"Import"]}),e.jsxs("button",{className:"btn btn-task-create btn-sm",onClick:()=>{et(),J(!1)},"aria-label":"New Agent",title:"New Agent",children:[e.jsx(Vt,{size:16}),"New Agent"]})]}),e.jsx("div",{className:"agent-global-controls agent-controls-actions",children:e.jsxs("div",{className:"heartbeat-multiplier-group",children:[e.jsxs("div",{className:"heartbeat-multiplier-controls",children:[e.jsx("label",{htmlFor:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-label",children:"Heartbeat Speed"}),e.jsx("input",{id:"globalHeartbeatMultiplier",className:"heartbeat-multiplier-slider touch-target",type:"range",min:.1,max:10,step:.1,value:Ve,onChange:t=>{const l=Number(t.target.value);Qe(Number.isFinite(l)&&l>0?l:1)},disabled:Ke}),e.jsxs("span",{className:"heartbeat-multiplier-value",children:["×",Ve.toFixed(1)]}),e.jsx("select",{className:"heartbeat-multiplier-preset",value:String(kt.reduce((t,l)=>Math.abs(l-Ve)<Math.abs(t-Ve)?l:t,kt[0])),onChange:t=>{const l=Number(t.target.value);Qe(Number.isFinite(l)&&l>0?l:1)},disabled:Ke,"aria-label":"Heartbeat speed preset",children:kt.map(t=>e.jsxs("option",{value:String(t),children:["×",t]},t))})]}),e.jsx("small",{className:"text-secondary",children:"Scales all agent heartbeat intervals. ×0.5 = twice as fast, ×2.0 = twice as slow. Default: ×1.0"})]})}),e.jsx(xs,{agents:w})]})]})]})]}),e.jsx(Cs,{isOpen:E,onClose:()=>{H(!1),_(null)},onCreated:()=>{H(!1),_(null),C()},projectId:r,prefillDraft:R,agentOnboardingEnabled:u,existingAgents:k,onPrefillDraft:_}),e.jsx(As,{isOpen:b,onClose:()=>I(!1),onImported:()=>void C(),projectId:r}),e.jsx(ks,{stats:A,activeAgents:_e,projectId:r,isOpen:ce,onToggle:()=>pe(t=>!t),onSelectAgent:ga,onOpenTaskLogs:p}),S==="org"?e.jsx("div",{className:"agents-org-full-view",children:e.jsx("div",{className:"agents-view-content agents-view-content--org-full",children:$?e.jsxs("div",{className:"agents-org-detail-view","data-testid":"agents-org-detail-view",children:[e.jsx("button",{type:"button",className:"btn btn-sm agents-org-detail-back",onClick:We,"aria-label":"Back to org chart",children:"Back to org chart"}),e.jsx(a.Suspense,{fallback:null,children:e.jsx(ea,{inline:!0,showInlineBackButton:!1,agentId:$,projectId:r,onClose:We,addToast:n,onChildClick:Et,initialTab:ae,initialRunId:F,preferActiveRun:me},$)})]}):Ft?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):e.jsxs("div",{className:"agent-org-chart-shell","data-testid":"agent-org-chart-shell",children:[d?e.jsxs("div",{className:"agent-org-chart-controls","data-testid":"agent-org-chart-controls",children:[zt(),It()]}):e.jsxs("div",{className:"agent-org-chart-toolbar",children:[zt(),e.jsx("div",{className:"agent-org-chart-controls","data-testid":"agent-org-chart-controls",children:It()})]}),e.jsx("div",{ref:de,className:"agent-org-chart-viewport","data-testid":"agent-org-chart-viewport",tabIndex:0,role:"region","aria-label":"Org chart canvas",onWheel:xa,onPointerDown:ba,onPointerMove:va,onPointerUp:Pt,onPointerCancel:Pt,onKeyDown:fa,"data-panning":Le?"true":"false",children:e.jsxs("div",{ref:xe,className:`agent-org-chart-canvas agent-org-chart-canvas--zoom-${Math.round((G.scale??1)*100)}`,"data-panning":Le?"true":"false",style:{transform:`translate(${G.x}px, ${G.y}px) scale(${G.scale})`},children:[e.jsx("div",{className:`agent-org-chart${lt==="vertical"?" agent-org-chart--vertical":""}`,"data-testid":"agent-org-chart","data-layout-mode":lt,children:ye?e.jsxs("div",{className:"agent-org-chart__loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{size:18,className:"spin"}),e.jsx("span",{children:"Loading org chart..."})]}):V.length===0?e.jsx(ft,{onCtaClick:et}):(D.current=[],V.map(t=>e.jsx(la,{node:t,onSelect:ua,getHealthStatus:mt,selectedAgentId:Ne,registerNodeElement:pa,linksRef:D},t.agent.id)))}),e.jsx(zs,{links:D.current,nodeElements:Ae.current,canvasRef:xe,viewportRef:de,layoutMode:lt,transform:G})]})})]})})}):e.jsxs("div",{className:"agents-split-layout",children:[e.jsx("div",{className:`agents-split-sidebar${K?" agents-split-sidebar--hidden-mobile":""}`,children:e.jsx("div",{className:"agents-view-content",children:Ft?e.jsxs("div",{className:"agents-view-loading",role:"status","aria-live":"polite",children:[e.jsx(qe,{size:18,className:"spin"}),e.jsx("span",{children:"Loading agents..."})]}):S==="board"?e.jsx("div",{className:"agent-board",children:w.length===0?e.jsx(ft,{onCtaClick:et}):w.map(t=>{const l=mt(t),c=Mt(t,l),g=Rt(t.state),M=Tt("agent-board-card",t.state);return e.jsx("div",{className:`agent-board-card ${M}${$===t.id?" agent-card--selected":""}`,children:e.jsxs("div",{className:"agent-board-clickable",onClick:()=>ue(t.id),role:"button",tabIndex:0,onKeyDown:z=>{(z.key==="Enter"||z.key===" ")&&(z.key===" "&&z.preventDefault(),ue(t.id))},children:[e.jsxs("div",{className:"agent-board-header",children:[e.jsx("span",{className:"agent-board-icon",children:e.jsx(dt,{agent:t,size:20})}),e.jsx("span",{className:"agent-board-badge badge text-secondary",children:$t(t.role)}),e.jsx("span",{className:`agent-board-badge badge ${g}`,children:t.state}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"agent-board-badge badge agent-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),t.pendingApprovalCount]}):null]}),e.jsx("div",{className:"agent-board-name",children:t.name}),e.jsx("div",{className:"agent-board-id",children:t.id}),e.jsxs("div",{className:"agent-board-health",style:{color:l.color},title:c.title,children:[l.icon,c.label?` ${c.label}`:""]})]})},t.id)})}):e.jsx("div",{className:"agent-list",children:w.length===0?e.jsx(ft,{onCtaClick:et}):w.map(t=>{const l=mt(t),c=Mt(t,l),g=Rt(t.state),M=Tt("agent-card",t.state),z=wt(t.runtimeConfig?.heartbeatIntervalMs),fe=Ga(z),je=se===t.id;return e.jsxs("div",{className:`agent-card agent-card--clickable ${M}${$===t.id?" agent-card--selected":""}`,onClick:h=>{const W=h.target;if(W===h.currentTarget){ue(t.id);return}const ne=W.closest('button, select, input, [role="button"]');ne&&ne!==h.currentTarget||ue(t.id)},role:"button",tabIndex:0,onKeyDown:h=>{h.target===h.currentTarget&&(h.key==="Enter"||h.key===" ")&&(h.key===" "&&h.preventDefault(),ue(t.id))},"aria-label":`Open details for ${t.name}`,children:[e.jsxs("div",{className:"agent-card-header",children:[e.jsxs("div",{className:"agent-info",children:[i===t.id?e.jsx("select",{ref:O,className:"select agent-role-select",value:t.role,onChange:h=>void ra(t.id,h.target.value),onKeyDown:h=>oa(h,t.id),onBlur:()=>v(null),autoFocus:!0,children:yt.map(h=>e.jsxs("option",{value:h.value,children:[h.icon," ",h.label]},h.value))}):e.jsx("span",{className:"agent-icon agent-icon--clickable",onClick:h=>{h.stopPropagation(),v(t.id)},title:"Click to change role",role:"button",tabIndex:0,onKeyDown:h=>{(h.key==="Enter"||h.key===" ")&&(h.stopPropagation(),v(t.id))},children:e.jsx(dt,{agent:t,size:20})}),e.jsxs("div",{className:"agent-meta",children:[e.jsx("span",{className:"agent-name",children:t.name}),e.jsx("span",{className:"agent-id text-secondary",children:t.id})]}),e.jsx(ta,{size:20,className:"agent-card-chevron"})]}),e.jsxs("div",{className:"agent-badges",children:[e.jsx("span",{className:`badge ${g}`,children:t.state}),e.jsxs("span",{className:"badge",style:{color:l.color},title:c.title,children:[l.icon,c.label?` ${c.label}`:""]}),e.jsx("span",{className:"badge text-secondary",children:$t(t.role)}),(t.pendingApprovalCount??0)>0?e.jsxs("span",{className:"badge agent-approval-badge",title:"Pending approvals",children:[e.jsx("span",{className:"status-dot status-dot--pending"}),t.pendingApprovalCount]}):null,(()=>{const h=ja(t);if(h.length===0)return null;const W=h.slice(0,2),ne=h.length-2;return e.jsxs(e.Fragment,{children:[W.map(tt=>e.jsx("span",{className:"badge badge-skill",title:tt,children:ns(tt)},tt)),ne>0&&e.jsxs("span",{className:"badge badge-skill",children:["+",ne]})]})})()]})]}),e.jsxs("div",{className:"agent-card-body",children:[t.state==="error"&&t.lastError?e.jsx(Va,{errorText:t.lastError,issueContext:{surface:"AgentsView list",agentId:t.id,agentName:t.name,agentState:t.state,taskId:t.taskId}}):null,t.taskId&&e.jsxs("div",{className:"agent-task",children:[e.jsx("span",{className:"text-secondary",children:"Working on:"}),e.jsx("span",{className:"badge",children:t.taskId})]}),e.jsxs("div",{className:"agent-heartbeat-control",children:[e.jsx("span",{className:"text-secondary",children:"Heartbeat:"}),Y===t.id?e.jsxs(e.Fragment,{children:[e.jsx("input",{type:"text",inputMode:"numeric",pattern:"[0-9]*",className:"input agent-heartbeat-custom-input",value:De[t.id]??"",onChange:h=>Te(W=>({...W,[t.id]:h.target.value})),onKeyDown:h=>{h.key==="Enter"?_t(t):h.key==="Escape"&&(Ce(null),Te(W=>{const ne={...W};return delete ne[t.id],ne}))},disabled:je,"aria-label":`Custom heartbeat interval in minutes for ${t.name}`}),e.jsx("span",{className:"text-secondary",children:"min"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>void _t(t),disabled:je,title:"Save custom interval",children:"Save"}),e.jsx("button",{className:"btn btn-sm",onClick:()=>{Ce(null),Te(h=>{const W={...h};return delete W[t.id],W})},disabled:je,title:"Cancel custom interval",children:"Cancel"})]}):e.jsx(e.Fragment,{children:e.jsxs("select",{className:"select agent-heartbeat-select",value:z,onChange:h=>{const W=h.target.value;W==="__custom__"?da(t):ca(t,Number(W))},disabled:je,"aria-label":`Set heartbeat interval for ${t.name}`,children:[fe.map(h=>e.jsx("option",{value:h.value,children:h.label},h.value)),Ka.some(h=>h.value===z)&&e.jsx("option",{value:"__custom__",children:"Custom..."})]})}),je&&e.jsx("span",{className:"agent-heartbeat-saving text-secondary",children:"Saving…"}),t.lastHeartbeatAt&&(()=>{const h=new Date(t.lastHeartbeatAt),W=new Date(h.getTime()+z),ne=t.state==="active"||t.state==="running";return e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"agent-heartbeat-last text-secondary",title:h.toLocaleString(),children:["Last: ",h.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})]}),ne&&e.jsxs("span",{className:"agent-heartbeat-next text-secondary",title:W.toLocaleString(),children:["Next: ",W.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})]})]})})()]})]}),e.jsxs("div",{className:"agent-card-actions",children:[e.jsxs("div",{className:"agent-card-actions-group agent-card-actions-group--primary",children:[t.state==="idle"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"active"),disabled:Me.has(t.id),title:"Activate",children:[e.jsx(bt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Start"})]}),t.state==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ha(t.id,t.name),disabled:Me.has(t.id),title:"Run Now","aria-label":`Run now for ${t.name}`,children:[e.jsx(Ze,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Run Now"})]}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"paused"),disabled:Me.has(t.id),title:"Pause",children:[e.jsx(Kt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Pause"})]})]}),t.state==="paused"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"active"),disabled:Me.has(t.id),title:"Resume",children:[e.jsx(bt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Resume"})]}),t.state==="running"&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{className:"btn btn-sm",onClick:()=>ue(t.id,{initialTab:"runs",initialRunId:null,preferActiveRun:!0}),title:"View live run details","aria-label":`View live run details for ${t.name}`,children:[e.jsx(Ze,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Running"})]}),e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"paused"),disabled:Me.has(t.id),title:"Pause",children:[e.jsx(Kt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Pause"})]})]}),t.state==="error"&&e.jsxs("button",{className:"btn btn-sm",onClick:()=>void ve(t.id,"active"),disabled:Me.has(t.id),title:"Retry",children:[e.jsx(bt,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Retry"})]})]}),e.jsxs("div",{className:"agent-card-actions-group agent-card-actions-group--secondary",children:[e.jsxs("button",{className:"btn btn-sm agent-card-details-btn",onClick:()=>ue(t.id),title:`View details for ${t.name}`,"aria-label":`View details for ${t.name}`,children:[e.jsx(rs,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Details"})]}),(t.state==="idle"||t.state==="paused")&&e.jsxs("button",{className:"btn btn-sm btn-danger",onClick:()=>void ia(t.id,t.name),title:"Delete",children:[e.jsx(Ua,{size:14})," ",e.jsx("span",{className:"agent-card-action-label",children:"Delete"})]})]})]})]},t.id)})})})}),e.jsx("div",{className:`agents-split-detail${d&&!$?" agents-split-detail--hidden-mobile":""}`,children:$?e.jsx(a.Suspense,{fallback:null,children:e.jsx(ea,{inline:!0,showInlineBackButton:d,agentId:$,projectId:r,onClose:We,addToast:n,onChildClick:Et,initialTab:ae,initialRunId:F,preferActiveRun:me,onMutationSuccess:ma},$)}):e.jsxs("div",{className:"agents-detail-empty-state",children:[e.jsx(St,{size:48}),e.jsx("h3",{children:"Select an agent"}),e.jsx("p",{children:"Choose an agent from the sidebar to view details"})]})})]})]})}export{Vs as AgentsView};
@@ -0,0 +1 @@
1
+ import{r as s,a as sn,j as t,R as nn}from"./vendor-react-K0fH_qHe.js";import{a8 as an,a6 as rn,ba as on,i as St,bb as vs,ab as cn,bc as ln,t as dn,bd as un,be as xs,bf as mn,bg as Ot,w as hn,bh as fn,bi as gn,bj as pn,bk as bn,bl as vn,bm as xn,bn as yn,s as wn,bo as Sn,k as $s,bp as jn,bq as Cn,br as Nn,bs as kn,p as Mn,bt as Rn,bu as An,u as En,h as Ps,bv as Tn,ag as Fs,ah as Ls,bw as In,bx as Dn,S as $n,Y as Gt,P as at,J as nt,au as Pn,by as ys,a as bt,bz as ws,bA as Ss,B as rt,ad as Fn,ae as Ln,a$ as wt,bB as zn,bC as _n,aY as Un,bD as js,bE as Hn,T as On,bF as Cs,bG as Gn,j as Ns,m as Kn}from"./index-Ba-F8c1g.js";import"./vendor-xterm-DzcZoU0P.js";import"./vendor-codemirror-jBKmHyH0.js";const Kt="kb-chat-active-session";function ks(n){const r=typeof n=="string"?n.trim():"",d=r.indexOf("/");return!r||d<=0||d>=r.length-1?{}:{modelProvider:r.slice(0,d),modelId:r.slice(d+1)}}function Bn(n){const r=n?.toolCalls;if(!Array.isArray(r))return;const d=r.map(i=>{if(!i||typeof i!="object")return null;const f=i,p=typeof f.toolName=="string"?f.toolName:"";if(!p)return null;const m=f.args;return{toolName:p,...m&&typeof m=="object"?{args:m}:{},isError:!!f.isError,result:f.result,status:"completed"}}).filter(i=>i!==null);return d.length>0?d:void 0}function Wn(n){const r=n?.fallback;if(!r||typeof r!="object")return;const d=r,i=typeof d.primaryModel=="string"?d.primaryModel:"",f=typeof d.fallbackModel=="string"?d.fallbackModel:"",p=d.triggerPoint;if(!(!i||!f||p!=="session-creation"&&p!=="prompt-time"))return{primaryModel:i,fallbackModel:f,triggerPoint:p}}function Vn(n){const r=n?.failureInfo;if(!r||typeof r!="object")return;const d=r,i=typeof d.summary=="string"?d.summary.trim():"";if(!i)return;const f=(()=>{const p=d.reference;if(!p||typeof p!="object")return;const m=p,S=typeof m.kind=="string"?m.kind.trim():"",F=typeof m.id=="string"?m.id.trim():"";if(!(!S||!F))return{kind:S,id:F,...typeof m.label=="string"&&m.label.trim()?{label:m.label.trim()}:{}}})();return{summary:i,...typeof d.errorClass=="string"&&d.errorClass.trim()?{errorClass:d.errorClass.trim()}:{},...typeof d.code=="string"&&d.code.trim()?{code:d.code.trim()}:{},...typeof d.detail=="string"&&d.detail.trim()?{detail:d.detail.trim()}:{},...f?{reference:f}:{}}}function Ms(n){return typeof n=="string"?{summary:n.trim()||"Failed to get response"}:{summary:typeof n.summary=="string"&&n.summary.trim()?n.summary.trim():"Failed to get response",...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()}:{},...n.reference?{reference:n.reference}:{}}}function Bt(n){return{id:n.id,sessionId:n.sessionId,role:n.role,content:n.content,thinkingOutput:n.thinkingOutput,toolCalls:Bn(n.metadata),fallbackInfo:Wn(n.metadata),failureInfo:Vn(n.metadata),attachments:n.attachments,createdAt:n.createdAt}}function qn(n,r){const d=s.useCallback(l=>l?`${an.CHAT_SESSIONS_PREFIX}${l}`:null,[]),i=s.useCallback(l=>{const h=d(l);return h?rn(h,{maxAgeMs:on})??[]:[]},[d]),[f,p]=s.useState(()=>i(n)),[m,S]=s.useState(null),[F,G]=s.useState(()=>i(n).length===0),[Z,v]=s.useState([]),[U,N]=s.useState(!1),[te,j]=s.useState(!1),[K,y]=s.useState(""),[I,C]=s.useState(""),[L,w]=s.useState([]),[se,V]=s.useState(""),[$,u]=s.useState(""),[R,o]=s.useState(!0),[D,H]=s.useState(new Map),g=s.useRef(null),B=s.useRef(null),ue=s.useRef(!1),me=s.useRef(""),ye=s.useRef(null),we=s.useRef(f),ee=s.useRef(m),O=s.useRef(te);we.current=f,ee.current=m,O.current=te,s.useEffect(()=>{me.current=se},[se]);const Me=s.useRef(new Set),ie=s.useRef(0),Se=s.useRef(n);Se.current!==n&&(Se.current=n,ie.current++),s.useEffect(()=>{const l=ie.current;St(void 0,n).then(h=>{if(ie.current!==l)return;const x=new Map;for(const k of h)x.set(k.id,k);H(x)}).catch(()=>{})},[n]);const he=s.useCallback(async()=>{we.current.length===0&&G(!0);try{const h=[...(await vs(n)).sessions].sort((k,Y)=>new Date(Y.updatedAt).getTime()-new Date(k.updatedAt).getTime());p(h);const x=d(n);x&&cn(x,h,{maxBytes:5e5})}catch{const l=i(n);if(we.current.length===0&&l.length===0){const h=d(n);h&&ln(h)}}finally{G(!1)}},[d,n]);s.useEffect(()=>{const l=i(n);p(l),G(l.length===0)},[n,i]),s.useEffect(()=>{he()},[he,n]);const it=s.useRef(()=>{}),ve=s.useRef(!1);s.useEffect(()=>{ve.current=!1,B.current=null},[n]),s.useEffect(()=>{if(F||ve.current||ee.current)return;const l=dn(Kt,n);if(!l){ve.current=!0;return}const h=f.find(x=>x.id===l);if(h){ve.current=!0,it.current(l,h);return}ve.current=!0},[F,f,n]);const W=s.useCallback(async(l,h)=>{N(!0);try{const x=await un(l,{limit:50,...h},n),k=x.messages.map(Bt);h?.offset&&h.offset>0?v(Y=>[...k,...Y]):v(k),o(x.messages.length>=50)}catch{}finally{N(!1)}},[n]),He=s.useCallback(()=>{ye.current?.(),ye.current=null,me.current="",V(""),y(""),C(""),w([]),j(!1)},[]),ot=s.useCallback(()=>{me.current="",V("")},[]),ne=s.useCallback(()=>{const l=me.current.trim();l&&(me.current="",V(""),ze.current(l))},[]),ae=s.useCallback((l,h,x)=>{if(g.current||!l)return!0;ue.current=!1,h&&(y(h.streamingText),C(h.streamingThinking),w(h.toolCalls)),j(!0);const{handlers:k}=xs({sessionId:l,tempUserMessageId:"",setStreamingText:y,setStreamingThinking:C,setStreamingToolCalls:w,cancelStreamingFlushesRef:ye,addToast:x?.silent?void 0:r,onFallbackSession:(E,q)=>{const X=ks(E.fallbackModel);p(A=>A.map(P=>P.id===q?{...P,...X}:P)),S(A=>A&&A.id===q?{...A,...X}:A)},onDone:()=>{y(""),C(""),w([]),j(!1),O.current=!1,g.current=null,B.current=null,W(l),ne()},onError:E=>{y(""),C(""),w([]),j(!1),O.current=!1,g.current=null,B.current=null;const q=Ms(E);x?.silent||r?.(q.summary,"error"),W(l),ne()}}),Y=mn(l,k,n,{...typeof h?.replayFromEventId=="number"?{lastEventId:h.replayFromEventId}:{}});return g.current=Y,B.current={sessionId:l,replayFromEventId:typeof h?.replayFromEventId=="number"?h.replayFromEventId:null},!0},[r,W,n,ne]),Le=s.useCallback((l,h)=>{const x=ee.current?.id??null;if(l&&x===l&&!h)return;g.current&&(g.current.close(),g.current=null),B.current=null;const k=h??f.find(Y=>Y.id===l);S(k||null),l&&Ot(l,n).then(({session:Y})=>{!Y.isGenerating||!Y.inFlightGeneration||S(E=>!E||E.id!==l?E:{...E,...Y})}).catch(()=>{}),He(),o(!0),l?W(l):v([]),k?.isGenerating&&ae(k.id,k.inFlightGeneration),l?hn(Kt,l,n):fn(Kt,n)},[ae,f,W,n,He]);it.current=Le;const jt=s.useCallback(async l=>{const h=await gn(l,n);g.current&&(g.current.close(),g.current=null),B.current=null;const x={id:h.session.id,title:h.session.title,agentId:h.session.agentId,status:h.session.status,modelProvider:h.session.modelProvider,modelId:h.session.modelId,createdAt:h.session.createdAt,updatedAt:h.session.updatedAt};return p(k=>k.some(Y=>Y.id===x.id)?k:[x,...k]),He(),Le(x.id,x),v([]),x},[n,He,Le]),ct=s.useCallback(async l=>{await pn(l,{status:"archived"},n),p(h=>h.filter(x=>x.id!==l)),m?.id===l&&(B.current=null,S(null),v([]))},[m,n]),Re=s.useCallback(async l=>{m?.id===l&&g.current&&(g.current.close(),g.current=null),m?.id===l&&(B.current=null),await bn(l,n),p(h=>h.filter(x=>x.id!==l)),m?.id===l&&(S(null),v([]))},[m,n]),Ae=s.useCallback(async()=>{!m||!R||await W(m.id,{offset:Z.length})},[m,R,W,Z.length]),Ye=s.useCallback(()=>{m&&(ue.current=!0,ye.current?.(),ye.current=null,g.current?.close(),g.current=null,B.current=null,vn(m.id,n).catch(()=>{}),j(!1),O.current=!1,y(""),C(""),w([]),ne())},[m,n,ne]),ze=s.useRef(()=>{}),_e=xn(),Ee=s.useCallback(async l=>{try{await he();const h=await Ot(l,n);ee.current?.id===l&&S(x=>!x||x.id!==l?x:{...x,...h.session}),h.session.isGenerating?(y(""),C(""),w([]),j(!0),O.current=!0,ae(l,h.session.inFlightGeneration,{silent:!0})):(y(""),C(""),w([]),j(!1),O.current=!1,await W(l))}catch{}},[ae,W,n,he]),je=s.useCallback((l,h)=>{if(!m)return;if(O.current){me.current=l,V(l);return}ue.current=!1,g.current&&(g.current.close(),g.current=null),B.current=null;const x=`temp-${Date.now()}`,k={id:x,sessionId:m.id,role:"user",content:l,createdAt:new Date().toISOString()};v(E=>[...E,k]),y(""),C(""),w([]),j(!0);const{handlers:Y}=xs({sessionId:m.id,tempUserMessageId:x,setStreamingText:y,setStreamingThinking:C,setStreamingToolCalls:w,cancelStreamingFlushesRef:ye,addToast:r,onFallbackSession:(E,q)=>{const X=ks(E.fallbackModel);p(A=>A.map(P=>P.id===q?{...P,...X}:P)),S(A=>A&&A.id===q?{...A,...X}:A)},onDone:({messageId:E,message:q,accumulated:X})=>{const A=q?{...Bt(q),...X.text.length>0?{content:X.text}:{}}:{id:E||`msg-${Date.now()}`,sessionId:m.id,role:"assistant",content:X.text,thinkingOutput:X.thinking,toolCalls:X.toolCalls.length>0?X.toolCalls:void 0,fallbackInfo:X.fallbackInfo,createdAt:new Date().toISOString()};Me.current.add(A.id),v(P=>[...P,A]),y(""),C(""),w([]),j(!1),O.current=!1,g.current=null,B.current=null,setTimeout(()=>{Me.current.delete(A.id)},1e3),he(),ne()},onError:(E,q)=>{const X=Ms(E),A=typeof E=="string"?E:X.summary,P=Sn(A);v(J=>{const T=J.filter(Q=>Q.id!==q);return P?T:[...T,{id:`error-${Date.now()}`,sessionId:m.id,role:"assistant",content:X.summary,failureInfo:X,createdAt:new Date().toISOString()}]}),y(""),C(""),w([]),j(!1),O.current=!1,g.current=null,B.current=null,console.error("[useChat] Stream error:",E),P?(console.info("[useChat] Suppressed tab-suspension stream error:",E),m?.id&&(y(""),C(""),w([]),j(!0),O.current=!0,Ee(m.id))):(r?.(X.summary,"error"),he()),ue.current||ne()}});g.current=yn(m.id,l,Y,h,n)},[m,n,he,r,ae,Ee,ne]);ze.current=je;const Te=$?f.filter(l=>l.title?.toLowerCase().includes($.toLowerCase())||l.agentId.toLowerCase().includes($.toLowerCase())):f;return s.useEffect(()=>{if(!m?.id||m.isGenerating!==!0||g.current)return;const l=typeof m.inFlightGeneration?.replayFromEventId=="number"?m.inFlightGeneration.replayFromEventId:null,h=B.current;h?.sessionId===m.id&&h.replayFromEventId===l||ae(m.id,m.inFlightGeneration,{silent:!0})},[m?.id,m?.isGenerating,m?.inFlightGeneration,ae]),s.useEffect(()=>{if(!ee.current?.isGenerating||(g.current||ae(ee.current.id,ee.current.inFlightGeneration),!O.current||g.current||!ee.current))return;const l=setInterval(async()=>{if(!O.current||g.current||!ee.current){clearInterval(l);return}try{(await vs(n)).sessions.find(k=>k.id===ee.current?.id)?.isGenerating||(clearInterval(l),await W(ee.current.id),y(""),C(""),w([]),j(!1),O.current=!1,ne())}catch{}},3e3);return()=>clearInterval(l)},[ae,W,n,m,ne]),s.useEffect(()=>_e.onBecameVisible(()=>{const h=ee.current;if(!h||g.current)return;const x=ie.current;Ot(h.id,n).then(k=>{if(!(ie.current!==x||g.current)){if(k.session.isGenerating){y(""),C(""),w([]),j(!0),O.current=!0,ae(h.id,k.session.inFlightGeneration,{silent:!0});return}O.current&&(y(""),C(""),w([]),j(!1),O.current=!1,ne(),W(h.id))}}).catch(()=>{})}),[ae,W,n,_e,ne]),s.useEffect(()=>{const l=ie.current,h=n?`?projectId=${encodeURIComponent(n)}`:"",x=()=>ie.current!==l,k=P=>{if(x())return;const J=JSON.parse(P.data);p(T=>T.some(Q=>Q.id===J.id)?T:[J,...T])},Y=P=>{if(x())return;const J=JSON.parse(P.data);p(T=>[...T.map(oe=>oe.id===J.id?J:oe)]),ee.current?.id===J.id&&(S(J),J.isGenerating&&!g.current&&ae(J.id,J.inFlightGeneration))},E=P=>{if(x())return;const{id:J}=JSON.parse(P.data);p(T=>T.filter(Q=>Q.id!==J)),ee.current?.id===J&&(S(null),v([]))},q=P=>{if(x())return;const J=JSON.parse(P.data),T=Bt(J);if(!Me.current.has(T.id)){if(ee.current?.id===T.sessionId&&O.current&&!g.current&&T.role==="assistant"){v(Q=>Q.some(oe=>oe.id===T.id)?Q:[...Q,T]),y(""),C(""),w([]),j(!1),O.current=!1,ne();return}ee.current?.id===T.sessionId&&!O.current&&v(Q=>{if(Q.some(oe=>oe.id===T.id))return Q;if(T.role==="user"){const oe=Q.findIndex(ce=>ce.role==="user"&&ce.id.startsWith("temp-")&&ce.content.trim()===T.content.trim());if(oe>=0){const ce=[...Q];return ce[oe]=T,ce}}return[...Q,T]})}},X=P=>{if(x())return;const{id:J}=JSON.parse(P.data);v(T=>T.filter(Q=>Q.id!==J))};return wn(`/api/events${h}`,{events:{"chat:session:created":k,"chat:session:updated":Y,"chat:session:deleted":E,"chat:message:added":q,"chat:message:deleted":X}})},[ae,n,ne]),s.useEffect(()=>()=>{g.current&&(g.current.close(),g.current=null),B.current=null},[]),{sessions:f,activeSession:m,sessionsLoading:F,messages:Z,messagesLoading:U,isStreaming:te,streamingText:K,streamingThinking:I,streamingToolCalls:L,pendingMessage:se,selectSession:Le,createSession:jt,archiveSession:ct,deleteSession:Re,sendMessage:je,stopStreaming:Ye,clearPendingMessage:ot,loadMoreMessages:Ae,hasMoreMessages:R,searchQuery:$,setSearchQuery:u,filteredSessions:Te,refreshSessions:he,agentsMap:D}}function Xn(n,r=[]){const d=n.trim().replace(/^#/,"");if(!d)return{ok:!1,error:"Room name is required."};if(/[A-Z]/.test(d))return{ok:!1,error:"Use lowercase letters only."};const i=d.toLowerCase();return i.length>80?{ok:!1,error:"Room names can be at most 80 characters."}:/^[a-z0-9_-]+$/.test(i)?/^[-_]|[-_]$/.test(i)?{ok:!1,error:"Room names cannot start or end with a hyphen or underscore."}:r.some(f=>f.toLowerCase()===i)?{ok:!1,error:"A room with this name already exists."}:{ok:!0,name:i}:{ok:!1,error:"Use lowercase letters, numbers, hyphens, or underscores only."}}function Yn({isOpen:n,onClose:r,onCreate:d,projectId:i,existingRoomNames:f=[]}){const[p,m]=s.useState(""),[S,F]=s.useState([]),[G,Z]=s.useState(""),[v,U]=s.useState([]),[N,te]=s.useState(!1),[j,K]=s.useState(null),[y,I]=s.useState(!1),C=s.useRef(null),L=s.useRef(null);s.useEffect(()=>{n&&(L.current=document.activeElement instanceof HTMLElement?document.activeElement:null,te(!0),K(null),St(void 0,i).then(o=>F(o)).catch(()=>{F([]),K("Failed to load agents.")}).finally(()=>te(!1)))},[n,i]),s.useEffect(()=>{if(!n){m(""),Z(""),U([]),K(null),I(!1);return}const o=window.requestAnimationFrame(()=>C.current?.focus());return()=>window.cancelAnimationFrame(o)},[n]),s.useEffect(()=>{if(!n)return;const o=D=>{D.key==="Escape"&&r()};return document.addEventListener("keydown",o),()=>document.removeEventListener("keydown",o)},[n,r]),s.useEffect(()=>{n||L.current?.focus()},[n]);const w=s.useMemo(()=>Xn(p,f),[p,f]),se=s.useMemo(()=>{const o=G.trim().toLowerCase();return o?S.filter(D=>D.name.toLowerCase().includes(o)):S},[S,G]),V=s.useMemo(()=>S.filter(o=>v.includes(o.id)),[S,v]),$=w.ok&&v.length>0&&!y&&!N;if(!n)return null;const u=o=>{y||U(D=>D.includes(o)?D.filter(H=>H!==o):[...D,o])},R=async()=>{if(!w.ok){K(w.error);return}if(v.length===0){K("Select at least one member.");return}K(null),I(!0);try{await d({name:w.name,displayName:`#${w.name}`,memberAgentIds:v}),r()}catch(o){K(o instanceof Error?o.message:"Failed to create room.")}finally{I(!1)}};return sn.createPortal(t.jsx("div",{className:"modal-overlay open",onClick:o=>o.target===o.currentTarget&&r(),children:t.jsxs("div",{className:"modal modal-lg create-room-modal",role:"dialog","aria-modal":"true","aria-label":"Create room",onClick:o=>o.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:"Create room"}),t.jsx("button",{type:"button",className:"modal-close","aria-label":"Close",onClick:r,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:"Room name"}),t.jsxs("div",{className:"create-room-modal-name-field",children:[t.jsx("span",{"aria-hidden":"true",className:"create-room-modal-name-hash",children:"#"}),t.jsx("input",{ref:C,id:"create-room-name",className:"input",value:p,disabled:y,onChange:o=>{const D=o.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();m(D)}})]}),!w.ok&&t.jsx("div",{className:"form-error",children:w.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:"Members"}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:"Search agents",value:G,disabled:y,onChange:o=>Z(o.target.value)})]}),V.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:V.map(o=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>u(o.id),disabled:y,children:[o.name," ×"]},o.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:N?t.jsx("div",{className:"create-room-modal-empty",children:"Loading agents..."}):se.length===0?t.jsx("div",{className:"create-room-modal-empty",children:S.length===0?"No agents in this project yet.":"No agents match your search."}):se.map(o=>{const D=v.includes(o.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${D?" create-room-modal-member-row--selected":""}`,onClick:()=>u(o.id),disabled:y,children:[t.jsx($s,{agent:o,size:20}),t.jsx("span",{children:o.name}),t.jsx("span",{className:"create-room-modal-member-role",children:o.role})]},o.id)})}),j&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:j})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:y,children:"Cancel"}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void R(),disabled:!$,children:y?"Creating...":"Create room"})]})]})}),document.body)}const Jn=640;function Qn(n){return Math.max(40,Math.min(n,Jn))}function zs(n){const r=new Date(n),i=new Date().getTime()-r.getTime(),f=Math.floor(i/1e3),p=Math.floor(f/60),m=Math.floor(p/60),S=Math.floor(m/24);return f<60?"just now":p<60?`${p}m ago`:m<24?`${m}h ago`:S<7?`${S}d ago`:r.toLocaleDateString()}function Rs(n,r){if(!n||!r)return null;const d=r.toLowerCase();if(d.includes("claude")){let f=r.replace(/^claude[- ]/i,"Claude ").replace(/sonnet[- ](\d+)[- ](\d+)/i,"Sonnet $1.$2").replace(/sonnet[- ](\d+)/i,"Sonnet $1").replace(/haiku[- ](\d+)/i,"Haiku $1").replace(/opus[- ](\d+)/i,"Opus $1").replace(/sonnet/i,"Sonnet").replace(/haiku/i,"Haiku").replace(/opus/i,"Opus").replace(/-/g," ").trim();return f=f.replace(/\s+/g," "),f.length>30?f.slice(0,30)+"…":f}if(d.includes("gpt")||d.includes("openai")){const f=r.replace(/^gpt-4-turbo$/i,"GPT-4 Turbo").replace(/^gpt-4o-mini$/i,"GPT-4o Mini").replace(/^gpt-4o$/i,"GPT-4o").replace(/^gpt-4$/i,"GPT-4").replace(/^gpt-o1-preview$/i,"GPT-o1 Preview").replace(/^gpt-o1-mini$/i,"GPT-o1 Mini").replace(/^gpt-o1$/i,"GPT-o1").replace(/^gpt/i,"GPT").trim();return f.length>30?f.slice(0,30)+"…":f}if(d.includes("gemini")){const f=r.replace(/^gemini[- ]/i,"Gemini ").replace(/pro[- ](\d+)[- ](\d+)/i,"Pro $1.$2").replace(/pro[- ](\d+)/i,"Pro $1").replace(/-/g," ").replace(/\s+/g," ").trim();return f.length>30?f.slice(0,30)+"…":f}const i=r.replace(/-/g," ").replace(/^\w/,f=>f.toUpperCase()).replace(/\s+/g," ").trim();return i.length>30?i.slice(0,30)+"…":i}function yt(n,r){return n.length<=r?n:`${n.slice(0,r)}…`}function Zn(n){if(!n)return null;const r=Object.entries(n);return r.length===0?null:r.map(([d,i])=>{const f=typeof i=="string"?i:(()=>{try{return JSON.stringify(i)}catch{return String(i)}})();return`${d}=${yt(f,50)}`}).join(", ")}function ea(n){if(n===void 0)return null;if(typeof n=="string")return yt(n,200);try{return yt(JSON.stringify(n),200)}catch{return yt(String(n),200)}}function ta(n){if(!n)return null;if(n.kind==="mailbox"||n.kind==="mailbox-message"){const r=typeof window>"u"?"/":window.location.pathname||"/",d=new URLSearchParams(typeof window>"u"?"":window.location.search);return d.set("view","mailbox"),d.set("mailbox-message",n.id),`${r}?${d.toString()}#message-${encodeURIComponent(n.id)}`}return null}function sa(n){if(!n)return null;const r=n.label??`${n.kind} ${n.id}`,d=ta(n),i=`chat-failure-reference-${n.kind}-${n.id}`.replace(/[^a-zA-Z0-9_-]+/g,"-").toLowerCase();return t.jsxs("div",{className:"chat-message-failure-reference",children:[t.jsx("span",{className:"chat-message-failure-reference-label",children:"Reference"}),t.jsx("span",{className:"chat-message-failure-reference-value",children:r}),d?t.jsx("a",{className:"btn btn-sm chat-message-failure-reference-link",href:d,children:"Open mailbox message"}):t.jsxs("details",{className:"chat-message-failure-reference-details",children:[t.jsx("summary",{className:"btn btn-sm chat-message-failure-reference-link",children:"View failure details"}),t.jsxs("dl",{className:"chat-message-failure-reference-meta",id:i,children:[t.jsxs("div",{children:[t.jsx("dt",{children:"Kind"}),t.jsx("dd",{children:n.kind})]}),t.jsxs("div",{children:[t.jsx("dt",{children:"ID"}),t.jsx("dd",{children:n.id})]}),n.label&&t.jsxs("div",{children:[t.jsx("dt",{children:"Label"}),t.jsx("dd",{children:n.label})]})]})]})]})}function _s(n){if(!n||n.length===0)return null;const r=(v,U)=>{const N=v.status==="running",te=v.status==="completed"&&v.isError,j=Zn(v.args),K=ea(v.result),y=N?j:K?`result: ${K}`:j?`args: ${j}`:null,I=N?"running":te?"error":"completed";return t.jsxs("details",{className:`chat-tool-call${N?" chat-tool-call--running":""}${te?" chat-tool-call--error":""}`,open:N,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:v.toolName,children:v.toolName}),y&&t.jsx("span",{className:"chat-tool-call-preview",title:y,children:y}),t.jsx("span",{className:"chat-tool-call-status-text",children:I})]}),t.jsxs("div",{className:"chat-tool-call-content",children:[j&&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:j})]}),K&&t.jsxs("div",{className:`chat-tool-call-row${te?" chat-tool-call-row--error":""}`,children:[t.jsx("span",{className:"chat-tool-call-label",children:"result"}),t.jsx("span",{className:"chat-tool-call-value",children:K})]})]})]},`${v.toolName}-${U}`)},d="chat-tool-calls";if(n.length===1)return t.jsxs("div",{className:d,"data-testid":"chat-tool-calls",children:[t.jsxs("div",{className:"chat-tool-calls-header",children:[t.jsx(Cs,{size:12,"aria-hidden":"true"}),t.jsx("span",{children:"Tool calls"})]}),r(n[0],0)]});const i=n.filter(v=>v.status==="running").length,f=n.filter(v=>v.status==="completed"&&v.isError).length,p=i>0,m=Array.from(new Set(n.map(v=>v.toolName))),S=m.slice(0,5),F=Math.max(0,m.length-S.length),G=F>0?`${S.join(", ")}, +${F} more`:S.join(", "),Z=p?`(${i} running)`:f>0?`(${f} ${f===1?"error":"errors"})`:null;return t.jsx("div",{className:d,"data-testid":"chat-tool-calls",children:t.jsxs("details",{className:"chat-tool-calls-group","data-testid":"chat-tool-calls-group",open:p,children:[t.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[t.jsx(Cs,{size:12,"aria-hidden":"true"}),t.jsxs("span",{className:"chat-tool-calls-count",children:[n.length," tool calls"]}),t.jsx("span",{className:"chat-tool-calls-names",title:G,children:G}),Z&&t.jsx("span",{className:"chat-tool-calls-group-status",children:Z})]}),n.map((v,U)=>r(v,U))]})})}const Us={p:({children:n,...r})=>t.jsx("p",{...r,children:js(n)}),li:({children:n,...r})=>t.jsx("li",{...r,children:js(n)}),pre:({children:n,...r})=>t.jsx("pre",{...r,className:"chat-markdown-pre",children:n}),code:({children:n,...r})=>{const d=typeof n=="string"?n:nn.Children.toArray(n).join(""),i=wt(d);return i.length===1&&typeof i[0]=="string"?t.jsx("code",{...r,children:n}):t.jsx("code",{...r,children:i})},table:({children:n,...r})=>t.jsx("table",{...r,className:"chat-markdown-table",children:n})},Xe="__fn_agent__",na=280,vt=180,xt=500,As="fusion:chat-sidebar-width",Wt="fusion:chat-scope",aa="fusion:chat-draft:";function Es(n,r){return r?`${aa}${n}:${r}`:null}function Ts(n){if(!n)return"";try{return localStorage.getItem(n)??""}catch{return""}}const ra=["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/markdown","text/csv","application/xml","text/x-log"];function Is(n){const r=/(^|[\s])\/([^\s]*)$/.exec(n);if(!r)return null;const d=r[1]??"",i=r[2]??"",f=r.index+d.length;return{filter:i,start:f,end:n.length}}function ia(n,r){const d=n.slice(0,r),i=/(^|[\s\n])@([\w-]*)$/.exec(d);if(!i)return null;const f=i[2]??"",p=d.length-f.length-1;return{filter:f,start:p,end:r}}function oa(n){const r=n?.runtimeConfig;if(!r||typeof r!="object")return null;const d=Reflect.get(r,"modelProvider"),i=Reflect.get(r,"modelId");return typeof d!="string"||d.trim().length===0||typeof i!="string"||i.trim().length===0?null:{provider:d,modelId:i}}function Ds(n,r,d){if(n?.modelProvider&&n?.modelId)return{provider:n.modelProvider,modelId:n.modelId};const i=oa(r??void 0);return i||(d.provider&&d.modelId?{provider:d.provider,modelId:d.modelId}:null)}function ca({projectId:n,onClose:r,onCreate:d}){const[i,f]=s.useState("agent"),[p,m]=s.useState([]),[S,F]=s.useState(!0),[G,Z]=s.useState(""),[v,U]=s.useState([]),[N,te]=s.useState(!0),[j,K]=s.useState(""),[y,I]=s.useState([]),[C,L]=s.useState([]);s.useEffect(()=>{let u=!1;return F(!0),St(void 0,n).then(R=>{u||m(R)}).catch(()=>{u||m([])}).finally(()=>{u||F(!1)}),()=>{u=!0}},[n]),s.useEffect(()=>{te(!0),Ps().then(u=>{U(u.models),I(u.favoriteProviders),L(u.favoriteModels)}).catch(()=>{U([]),I([]),L([])}).finally(()=>{te(!1)})},[]);const w=s.useCallback(async u=>{const R=y,D=R.includes(u)?R.filter(H=>H!==u):[u,...R];I(D);try{await Ns({favoriteProviders:D,favoriteModels:C})}catch{I(R)}},[y,C]),se=s.useCallback(async u=>{const R=C,D=R.includes(u)?R.filter(H=>H!==u):[u,...R];L(D);try{await Ns({favoriteProviders:y,favoriteModels:D})}catch{L(R)}},[C,y]),V=u=>{if(u.preventDefault(),i==="agent"){if(!G)return;d({agentId:G});return}if(!j)return;const R=j.indexOf("/");if(R<=0)return;const o=j.slice(0,R),D=j.slice(R+1);d({agentId:Xe,modelProvider:o,modelId:D})},$=i==="agent"?!G:!j;return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:r,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:u=>u.stopPropagation(),children:[t.jsx("h3",{children:"New Chat"}),t.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${i==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{f("agent"),K("")},children:"Agent"}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${i==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{f("model"),Z("")},children:"Model"})]}),t.jsxs("form",{onSubmit:V,children:[i==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:["Agent",S?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading agents..."}):p.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:"No agents available"}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:p.map(u=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${G===u.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>Z(u.id),"data-testid":`agent-option-${u.id}`,children:[t.jsx(rt,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:u.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:u.role})]},u.id))})]}),i==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:N?t.jsx("div",{className:"chat-new-dialog-loading",children:"Loading models..."}):t.jsx(Kn,{models:v,value:j,onChange:K,label:"Model",placeholder:"Select a model",favoriteProviders:y,onToggleFavorite:w,favoriteModels:C,onToggleModelFavorite:se})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:r,children:"Cancel"}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:$,children:"Create"})]})]})]})})}const Vt=s.memo(function({message:r,forcePlain:d,agentName:i,hideAssistantIdentity:f,showAssistantModelTag:p,activeModelTag:m,activeModelProvider:S,activeSessionId:F,mentionAgentsByName:G,roomContext:Z,copyAction:v}){const U=r.role==="assistant",N=U?r.failureInfo:void 0,te=U&&(!f||!!N),j=s.useMemo(()=>{if(U)return null;const I=r.content,C=/@([\w-]+)/g,L=[];let w=0,se=C.exec(I);for(;se;){const[V,$=""]=se,u=se.index;u>w&&L.push(I.slice(w,u));const R=$.replace(/_/g," ").toLowerCase(),o=G.get(R);if(o){const D=!!(Z&&!Z.memberIds.has(o.id)),H=D?`Not a member of ${Z?.roomName}`:void 0;L.push(t.jsxs("span",{className:`chat-mention-chip${D?" chat-mention-chip--non-member":""}`,title:H,"aria-label":H,children:["@",o.name.replace(/\s+/g,"_")]},`${o.id}-${u}`))}else L.push(V);w=u+V.length,se=C.exec(I)}return w<I.length&&L.push(I.slice(w)),L.length===0?I:L},[U,r.content,G,Z]),K=s.useMemo(()=>{const I=r.attachments;if(!I||I.length===0)return null;const C=r.roomId?`/api/chat/rooms/${encodeURIComponent(r.roomId)}/attachments/`:F?`/api/chat/sessions/${encodeURIComponent(F)}/attachments/`:null;return C?t.jsx("div",{className:"chat-message-attachments",children:I.map(L=>{const w=L.mimeType.startsWith("image/"),se=L.id||L.filename,V=`${C}${encodeURIComponent(L.filename)}`;return w?t.jsx("a",{className:"chat-message-attachment-link","data-testid":"chat-message-attachment",href:V,target:"_blank",rel:"noopener noreferrer",children:t.jsx("img",{className:"chat-message-attachment",src:V,alt:L.originalName})},se):t.jsxs("a",{className:"chat-message-attachment-file","data-testid":"chat-message-attachment",href:V,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(Hn,{size:14}),t.jsx("span",{children:L.originalName})]},se)})}):null},[r.attachments,r.roomId,F]),y=s.useMemo(()=>U?N?t.jsxs("div",{className:"chat-message-content chat-message-content--failure",children:[t.jsxs("div",{className:"chat-message-failure-summary-row",children:[t.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),t.jsx("span",{className:"chat-message-failure-label",children:"Response failed"})]}),t.jsx("div",{className:"chat-message-failure-summary",children:N.summary}),(N.errorClass||N.code)&&t.jsxs("div",{className:"chat-message-failure-badges",children:[N.errorClass&&t.jsx("span",{className:"chat-message-failure-badge",children:N.errorClass}),N.code&&t.jsx("span",{className:"chat-message-failure-badge",children:N.code})]}),(N.detail||N.reference)&&t.jsxs("details",{className:"chat-message-failure-details",children:[t.jsxs("summary",{children:[t.jsx(On,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:"Failure details"})]}),N.detail&&t.jsx("pre",{className:"chat-message-failure-detail",children:wt(N.detail)}),sa(N.reference)]})]}):d?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:r.content}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(Fs,{remarkPlugins:[Ls],components:Us,children:r.content})}):null,[N,d,U,r.content]);return t.jsxs("div",{className:`chat-message chat-message--${r.role}${N?" chat-message--failure":""}`,"data-testid":`chat-message-${r.id}`,children:[te&&t.jsxs("div",{className:"chat-message-avatar",children:[S?t.jsx(at,{provider:S,size:"sm"}):t.jsx(rt,{size:14}),t.jsx("span",{children:i}),p&&m&&t.jsx("span",{className:"chat-model-tag",children:m})]}),U?y:t.jsx("div",{className:"chat-message-content",children:j}),!N&&v,_s(r.toolCalls),r.thinkingOutput&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:wt(r.thinkingOutput)})]}),K,t.jsx("div",{className:"chat-message-time",children:zs(r.createdAt)})]})});function ga({projectId:n,addToast:r,experimentalFeatures:d}){const{activeSession:i,sessionsLoading:f,messages:p,messagesLoading:m,isStreaming:S,streamingText:F,streamingThinking:G,streamingToolCalls:Z,selectSession:v,createSession:U,archiveSession:N,deleteSession:te,sendMessage:j,stopStreaming:K,pendingMessage:y,clearPendingMessage:I,searchQuery:C,setSearchQuery:L,filteredSessions:w}=qn(n,r),[se,V]=s.useState(!1),$=d?.chatRooms===!0,[u,R]=s.useState(()=>{try{if(localStorage.getItem(Wt)==="rooms"&&$)return"rooms"}catch{}return"direct"}),o=jn(n,r),{isUnread:D,markRead:H}=Cn(n),[g,B]=s.useState(()=>{const e=Es(u,u==="rooms"?o.activeRoom?.id:i?.id);return Ts(e)}),[ue,me]=s.useState(null),[ye,we]=s.useState(null),[ee,O]=s.useState(null),[Me,ie]=s.useState(!0),[Se,he]=s.useState(na),[it,ve]=s.useState(!1),[W,He]=s.useState(new Map),[ot,ne]=s.useState({provider:null,modelId:null}),[ae,Le]=s.useState([]),[jt,ct]=s.useState(!0),[Re,Ae]=s.useState(!1),[Ye,ze]=s.useState(""),[_e,Ee]=s.useState(0),[je,Te]=s.useState(""),[l,h]=s.useState(!1),[x,k]=s.useState(0),[Y,E]=s.useState(-1),[q,X]=s.useState(!1),[A,P]=s.useState([]),[J,T]=s.useState(!1),[Q,oe]=s.useState(!1),[ce,qt]=s.useState({}),[lt,Oe]=s.useState(!1),[dt,Je]=s.useState(!1),{pushNav:Xt}=Nn(),[,Qe]=s.useState(!1),[Hs,Os]=s.useState({top:0,left:0}),z=kn({projectId:n}),Ct=s.useCallback(e=>{if(!e||!z.mentionActive)return;const a=e.getBoundingClientRect();Os({top:a.top-260,left:a.left+8})},[z.mentionActive]),Yt=s.useRef(null),Jt=s.useRef(null),Qt=s.useRef(null),Ie=s.useRef(!1),Nt=s.useRef(null),Zt=s.useRef(null),De=s.useRef(null),$e=s.useRef(null),Ce=s.useRef(null),pe=s.useRef(null),fe=s.useRef(null),es=s.useRef(null),ts=s.useRef([]),Ze=s.useRef(0),et=s.useRef(new Map),M=Mn()==="mobile";s.useEffect(()=>{i?.id&&H("direct",i.id,i.lastMessageAt??i.updatedAt)},[i?.id,i?.lastMessageAt,i?.updatedAt,H]),s.useEffect(()=>{o.activeRoom?.id&&H("room",o.activeRoom.id,o.activeRoom.updatedAt)},[o.activeRoom?.id,o.activeRoom?.updatedAt,H]),s.useEffect(()=>{if(!i?.id||p.length===0)return;const e=p[p.length-1];H("direct",i.id,e?.createdAt??i.lastMessageAt??i.updatedAt)},[i?.id,i?.lastMessageAt,i?.updatedAt,H,p]),s.useEffect(()=>{if(!o.activeRoom?.id||o.messages.length===0)return;const e=o.messages[o.messages.length-1];H("room",o.activeRoom.id,e?.createdAt??o.activeRoom.updatedAt)},[H,o.activeRoom?.id,o.activeRoom?.updatedAt,o.messages]),s.useEffect(()=>{try{const e=localStorage.getItem(As);if(!e)return;const a=Number.parseInt(e,10);if(Number.isNaN(a))return;const c=Math.max(vt,Math.min(xt,a));he(c)}catch{}},[]),s.useEffect(()=>{try{const e=localStorage.getItem(Wt);if(e==="direct"){R("direct");return}e==="rooms"&&$&&R("rooms")}catch{}},[$]),s.useEffect(()=>{if(!$&&u==="rooms"){R("direct");return}try{localStorage.setItem(Wt,u)}catch{}},[$,u]);const le=Es(u,u==="rooms"?o.activeRoom?.id:i?.id),kt=s.useRef(le);s.useEffect(()=>{le!==kt.current&&(kt.current=le,B(Ts(le)))},[le]),s.useEffect(()=>{if(!(!le||kt.current!==le))try{if(g){localStorage.setItem(le,g);return}localStorage.removeItem(le)}catch{}},[le,g]);const de=$&&u==="rooms"&&!!o.activeRoom,{keyboardOverlap:ut,viewportHeight:ss,viewportOffsetTop:ns,keyboardOpen:tt}=Rn({enabled:M&&(!!i||de)}),as=ss!==null&&(ut>0||ns>0),rs=tt&&as?{"--keyboard-overlap":`${ut}px`,"--vv-offset-top":`${ns}px`,"--vv-height":`${ss}px`}:{},is=`chat-thread${tt&&as?" chat-thread--keyboard-active":""}`,be=s.useMemo(()=>{const e=Ye.trim().toLowerCase();return(e?ae.filter(c=>c.name.toLowerCase().includes(e)):ae).slice(0,10)},[ae,Ye]),Ge=s.useMemo(()=>Array.from(W.values()),[W]),Ne=s.useMemo(()=>!$||u!=="rooms"||!o.activeRoom?null:{roomId:o.activeRoom.id,roomName:o.activeRoom.name,memberIds:new Set(o.activeRoomMembers.map(e=>e.agentId))},[$,u,o.activeRoom,o.activeRoomMembers]),Ue=s.useMemo(()=>{const e=Ge.filter(b=>An(b.name,je));if(!Ne)return e;const a=e.filter(b=>Ne.memberIds.has(b.id));if(je.trim().length===0)return a;const c=e.filter(b=>!Ne.memberIds.has(b.id));return[...a,...c]},[Ge,je,Ne]),Mt=s.useMemo(()=>{const e=new Map;for(const a of Ge)e.set(a.name.toLowerCase(),a);return e},[Ge]);s.useEffect(()=>{Ee(0)},[be]),s.useEffect(()=>{k(0)},[je,l]),s.useEffect(()=>()=>{Ce.current!==null&&window.clearTimeout(Ce.current)},[]);const os=s.useCallback(()=>{const e=pe.current;if(!e)return;const c=e.scrollTop+e.clientHeight>=e.scrollHeight-50;oe(!c),Ie.current=!c},[]),ge=s.useCallback(e=>{if(!e.isConnected)return;let a=0,c=0,b=-1;const _=6,re=()=>{if(e.isConnected){if(e.scrollTop=e.scrollHeight,e.scrollHeight===b?c+=1:(c=0,b=e.scrollHeight),a+=1,a>=_||c>=2){oe(!1),Ie.current=!1;return}window.requestAnimationFrame(re)}};re()},[]),Ke=s.useCallback(()=>{const e=pe.current;e&&ge(e)},[ge]);s.useLayoutEffect(()=>{$e.current!==null&&(window.clearTimeout($e.current),$e.current=null);const e=de?o.activeRoom?.id??null:i?.id??null;if(!e){Nt.current=null;return}const a={threadId:e,loaded:de?!o.messagesLoading:!m,hasMessages:de?o.messages.length>0:p.length>0},c=Nt.current,b=c?.threadId!==e,_=c?.threadId===e&&!c.loaded&&a.loaded,re=c?.threadId===e&&!c.hasMessages&&a.hasMessages;if(!(c===null||b||_||re))return;const ke=pe.current;if(ke)return ge(ke),de||($e.current=window.setTimeout(()=>{if($e.current=null,Ie.current)return;const Ve=pe.current;Ve&&ge(Ve)},250)),Nt.current=a,()=>{$e.current!==null&&(window.clearTimeout($e.current),$e.current=null)}},[de,o.activeRoom?.id,o.messages.length,o.messagesLoading,i?.id,p.length,m,ge]);const Gs=de?o.messages:p;s.useEffect(()=>{Ie.current||Ke()},[Gs,F,G,S,Ke]),s.useEffect(()=>{ut<=0||!pe.current||Ke()},[ut,Ke]),En(M&&tt),s.useEffect(()=>{const e=()=>me(null);if(ue)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[ue]),s.useEffect(()=>{if(!M||!tt)return;const e=a=>{a.target?.closest(".chat-messages")||a.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[M,tt]),s.useEffect(()=>{if(!M||!i)return;const e=()=>{const a=fe.current;a&&document.activeElement===a&&(a.blur(),window.setTimeout(()=>{a.focus({preventScroll:!0})},0))};return document.addEventListener("visibilitychange",e),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",e),window.removeEventListener("pageshow",e)}},[M,i]),s.useEffect(()=>{const e=Zt.current;if(Zt.current=u,u!=="direct"||e!==null&&e!=="rooms")return;const a=pe.current;a&&(ge(a),Ie.current=!1,oe(!1))},[u,ge]),s.useEffect(()=>{if(!i&&!de||de&&!M)return;const e=()=>{const c=pe.current;c&&(ge(c),Ie.current=!1,oe(!1),De.current!==null&&(window.clearTimeout(De.current),De.current=null),De.current=window.setTimeout(()=>{if(De.current=null,Ie.current)return;const b=pe.current;b&&ge(b)},250))},a=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",a),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",a),window.removeEventListener("pageshow",e),De.current!==null&&(window.clearTimeout(De.current),De.current=null)}},[M,i,de,ge]),s.useEffect(()=>{if(de||typeof ResizeObserver>"u")return;const e=pe.current;if(!e)return;const a=new ResizeObserver(()=>{Ie.current||ge(e)});return a.observe(e),()=>{a.disconnect()}},[de,ge,i?.id,u]),s.useEffect(()=>{let e=!1;const a=n;return St(void 0,n).then(c=>{if(e||a!==n)return;const b=new Map;for(const _ of c)b.set(_.id,_);He(b)}).catch(()=>{}),()=>{e=!0}},[n]),s.useEffect(()=>{let e=!1;return Ps().then(a=>{e||ne({provider:a.defaultProvider??null,modelId:a.defaultModelId??null})}).catch(()=>{e||ne({provider:null,modelId:null})}),()=>{e=!0}},[]),s.useEffect(()=>{let e=!1;return ct(!0),Tn(n).then(a=>{e||Le(a)}).catch(()=>{e||Le([])}).finally(()=>{e||ct(!1)}),()=>{e=!0}},[n]),s.useEffect(()=>{ts.current=A},[A]),s.useEffect(()=>()=>{for(const e of ts.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of et.current.values())window.clearTimeout(e);et.current.clear()},[]);const mt=s.useCallback(e=>{if(!e||e.length===0)return;const a=[];for(const c of Array.from(e)){if(!ra.includes(c.type))continue;const b=c.type.startsWith("image/");a.push({file:c,previewUrl:b?URL.createObjectURL(c):""})}a.length>0&&P(c=>[...c,...a])},[]),Ks=s.useCallback(e=>{P(a=>{const c=a[e];return c?.previewUrl&&URL.revokeObjectURL(c.previewUrl),a.filter((b,_)=>_!==e)})},[]),Bs=s.useCallback(e=>{const a=e.clipboardData?.files;if(!a||a.length===0)return;const c=Array.from(a).filter(b=>b.type.startsWith("image/"));c.length!==0&&mt(c)},[mt]),Ws=s.useCallback(async e=>{try{await U(e),V(!1),M&&ie(!1)}catch{r("Failed to create chat session","error")}},[U,r,M]),xe=s.useCallback(e=>{const a=e??fe.current;a&&(a.style.height="auto",a.style.height=`${Qn(a.scrollHeight)}px`)},[]),cs=s.useCallback(e=>{fe.current=e,e&&xe(e)},[xe]);s.useLayoutEffect(()=>{xe()},[u,g,i?.id,o.activeRoom?.id,xe]);const Be=s.useCallback(()=>{if(B(""),le)try{localStorage.removeItem(le)}catch{}Ae(!1),ze(""),h(!1),Te(""),E(-1),P(e=>{for(const a of e)a.previewUrl&&URL.revokeObjectURL(a.previewUrl);return[]})},[le]),Rt=s.useCallback(()=>{const e=g.trim(),a=A.map(c=>c.file);if(!(!e&&a.length===0||!i)){if(e==="/clear"||e==="/new"){Be(),I(),K(),U({agentId:i.agentId,modelProvider:i.modelProvider??void 0,modelId:i.modelId??void 0}).catch(()=>{r("Failed to clear conversation","error")});return}Be(),j(e,a)}},[g,A,i,Be,K,I,U,r,j]),At=s.useCallback(async()=>{const e=g.trim();if(e){if($&&u==="rooms"){if(!o.activeRoom)return;if(e==="/clear"||e==="/new"){Be();try{await o.clearRoom(o.activeRoom.id)}catch{r("Failed to clear room conversation","error")}return}const a=g;Be();try{await o.sendRoomMessage(e,{files:A.map(c=>c.file)})}catch(c){B(a);const b=c instanceof Error&&c.message.trim()?c.message:"Failed to send room message";r(b,"error")}return}Rt()}},[g,A,$,u,o,o.clearRoom,Be,r,Rt]),Et=s.useCallback(e=>{B(a=>{const c=Is(a);if(!c)return a;const b=`/skill:${e.name} `,_=a.slice(0,c.start)+b+a.slice(c.end);return window.requestAnimationFrame(()=>{fe.current&&(xe(fe.current),fe.current.focus())}),_}),Ae(!1),ze(""),Ee(0)},[xe]),ht=s.useCallback(e=>{const a=fe.current;if(!a||Y<0)return;const c=a.selectionStart??Ze.current,b=a.selectionEnd??c,_=Math.max(c,b),re=Math.min(Y,_),ke=`${`@${e.name.replace(/\s+/g,"_")}`} `,Ve=g.slice(0,re)+ke+g.slice(_),qe=re+ke.length;B(Ve),h(!1),Te(""),k(0),E(-1),window.requestAnimationFrame(()=>{fe.current&&(xe(fe.current),fe.current.focus(),fe.current.setSelectionRange(qe,qe))})},[Y,g,xe]),ls=s.useCallback(e=>{if(Ze.current=e.currentTarget.selectionStart??Ze.current,z.mentionActive&&z.files.length>0){if(z.handleKeyDown(e,g),e.key==="Enter"||e.key==="Tab"){const a=z.files[z.selectedIndex];if(a){const c=z.selectFile(a,g);B(c),z.dismissMention(),Qe(!1)}}return}if(l&&e.key==="ArrowDown"){e.preventDefault(),Ue.length>0&&k(a=>(a+1)%Ue.length);return}if(l&&e.key==="ArrowUp"){e.preventDefault(),Ue.length>0&&k(a=>a===0?Ue.length-1:a-1);return}if(l&&e.key==="Enter"){e.preventDefault();const a=Ue[x]??Ue[0];a&&ht(a);return}if(l&&e.key==="Escape"){e.preventDefault(),h(!1),Te(""),E(-1);return}if(Re&&e.key==="ArrowDown"){e.preventDefault(),be.length>0&&Ee(a=>(a+1)%be.length);return}if(Re&&e.key==="ArrowUp"){e.preventDefault(),be.length>0&&Ee(a=>a===0?be.length-1:a-1);return}if(Re&&(e.key==="Enter"||e.key==="Tab")&&be.length>0){e.preventDefault();const a=be[_e]??be[0];a&&Et(a);return}if(Re&&e.key==="Escape"){e.preventDefault(),Ae(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),At())},[l,Ue,x,ht,Re,be,_e,Et,At,z,g]),ft=s.useCallback((e,a)=>{const c=ia(e,a);if(c){h(!0),Te(c.filter),E(c.start);return}h(!1),Te(""),E(-1)},[]),ds=s.useCallback(e=>{const a=e.target,c=a.value,b=a.selectionStart??c.length;xe(a),Ze.current=b,B(c);const _=Is(c);_?(Ae(!0),ze(_.filter)):(Ae(!1),ze("")),ft(c,b),z.detectMention(c,b),Qe(z.mentionActive),z.mentionActive&&Ct(a)},[ft,xe]),gt=s.useCallback(e=>{const a=e.currentTarget,c=a.selectionStart??a.value.length;Ze.current=c,ft(a.value,c),z.detectMention(a.value,c),Qe(z.mentionActive),z.mentionActive&&Ct(a)},[ft,z,Ct]),us=s.useCallback(e=>{e.key!=="Escape"&&gt(e)},[gt]),ms=s.useCallback(()=>{Ce.current!==null&&window.clearTimeout(Ce.current),Ce.current=window.setTimeout(()=>{Ae(!1),h(!1),Te(""),E(-1),Qe(!1),z.dismissMention(),Ce.current=null},120)},[z]),hs=s.useCallback(()=>{Ce.current!==null&&(window.clearTimeout(Ce.current),Ce.current=null),typeof window<"u"&&window.innerWidth<=768&&queueMicrotask(()=>{(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)})},[]),Vs=s.useCallback(async e=>{me(null);try{await N(e),r("Conversation archived","success")}catch{r("Failed to archive conversation","error")}},[N,r]),qs=s.useCallback(async e=>{we(null),me(null);try{await te(e),r("Conversation deleted","success")}catch{r("Failed to delete conversation","error")}},[te,r]),st=s.useCallback(e=>{try{localStorage.setItem(As,String(e))}catch{}},[]),Xs=s.useCallback(e=>{if(M)return;e.preventDefault(),e.stopPropagation();const a=e.currentTarget;typeof a.setPointerCapture=="function"&&a.setPointerCapture(e.pointerId);const c=e.clientX,b=Se;let _=b;document.body.style.userSelect="none";const re=ke=>{const Ve=ke.clientX-c,qe=Math.max(vt,Math.min(xt,b+Ve));_=qe,he(qe),st(qe)},We=ke=>{typeof a.releasePointerCapture=="function"&&a.releasePointerCapture(ke.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",re),document.removeEventListener("pointerup",We),st(_)};document.addEventListener("pointermove",re),document.addEventListener("pointerup",We)},[M,st,Se]),Ys=s.useCallback(e=>{if(M||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const a=e.shiftKey?50:10,c=e.key==="ArrowLeft"?-a:a,b=Math.max(vt,Math.min(xt,Se+c));he(b),st(b)},[M,st,Se]),fs=s.useCallback(e=>{const a=w.find(c=>c.id===e);H("direct",e,a?.lastMessageAt??a?.updatedAt),v(e),Oe(!1),M&&ie(!1)},[w,M,H,v]),Tt=s.useCallback(()=>{v(""),ie(!0),Oe(!1)},[v]),It=s.useCallback(()=>{o.selectRoom(null),ie(!0),Oe(!1)},[o]),Js=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(Gn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:"Start a new conversation"}),t.jsxs("button",{className:"btn btn-primary",onClick:()=>V(!0),children:[t.jsx(nt,{size:16}),"New Chat"]})]}),Dt=Ds(i,i?.agentId?W.get(i.agentId)??null:null,ot),Pe=Rs(Dt?.provider,Dt?.modelId),Fe=Dt?.provider??null,$t=!!(i||S||p.length>0),pt=u==="rooms"?de:!!i,gs=s.useRef(pt);s.useEffect(()=>{const e=gs.current;gs.current=pt,M&&(e||!pt||Xt({type:"view",revert:u==="rooms"?It:Tt}))},[u,Tt,It,pt,M,Xt]);const Pt=i?.agentId===Xe?Pe??"Fusion":i?.title||W.get(i?.agentId??"")?.name||i?.agentId||"Chat",ps=!!(Pe&&Pe!==Pt),Qs=M&&u==="direct"&&!!i,Ft=W.get(i?.agentId??"")?.name||(i?.agentId===Xe?Pe??"Fusion":i?.agentId?.slice(0,30)??"Fusion"),Lt=!1,zt=i?.agentId===Xe,Zs=y.length>50?`${y.slice(0,50)}…`:y,en=s.useCallback(()=>{X(e=>!e)},[]);s.useEffect(()=>{if(!lt)return;const e=a=>{Jt.current?.contains(a.target)||Oe(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[lt]),s.useEffect(()=>{if(!dt)return;const e=c=>{Qt.current?.contains(c.target)||Je(!1)},a=c=>{c.key==="Escape"&&Je(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",a)}},[dt]),s.useEffect(()=>{(!M||u!=="direct"||Me)&&Oe(!1)},[M,u,Me]),s.useEffect(()=>{Je(!1)},[o.activeRoom?.id]);const _t=s.useCallback((e,a)=>{const c=et.current.get(e);c&&window.clearTimeout(c),qt(_=>({..._,[e]:a}));const b=window.setTimeout(()=>{qt(_=>{const{[e]:re,...We}=_;return We}),et.current.delete(e)},2e3);et.current.set(e,b)},[]),bs=s.useCallback(async(e,a)=>{try{if(!navigator.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(a),_t(e,"success")}catch{_t(e,"error")}},[_t]),tn=s.useCallback((e,a=!1)=>a?t.jsx("div",{className:"chat-message-content chat-message-content--plain",children:e}):t.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:t.jsx(Fs,{remarkPlugins:[Ls],components:Us,children:e})}),[]),Ut=i?.agentId===Xe,Ht=s.useCallback((e,a,c)=>t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${ce[e]==="success"?" chat-message-copy-action--success":""}${ce[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":c??`chat-copy-response-${e}`,"aria-label":ce[e]==="success"?"Response copied":ce[e]==="error"?"Copy failed":"Copy response",onClick:()=>{bs(e,a)},children:ce[e]==="success"?t.jsx(In,{size:14}):t.jsx(Dn,{size:14})}),[ce,bs]);return t.jsxs("div",{className:"chat-view",children:[t.jsxs("div",{className:`chat-sidebar${Me?"":" chat-sidebar--hidden"}`,style:M?void 0:{width:`${Se}px`},children:[$&&t.jsxs("div",{className:"chat-sidebar-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[t.jsx("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${u==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":u==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>R("direct"),children:"Direct"}),t.jsx("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${u==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":u==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>R("rooms"),children:"Rooms"})]}),!$||u==="direct"?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-sidebar-search-container",children:t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx($n,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:"Search conversations...",value:C,onChange:e=>L(e.target.value),"data-testid":"chat-search-input"})]})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:f?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:"Loading..."}):w.length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:"No conversations yet"}):w.map(e=>{const a=i?.id===e.id,c=!a&&D("direct",e.id,e.lastMessageAt??e.updatedAt),b=Ds(e,W.get(e.agentId)??null,ot),_=Rs(b?.provider,b?.modelId)??"Fusion";return t.jsxs("div",{className:`chat-session-item${a?" chat-session-item--active":""}`,onClick:()=>fs(e.id),onContextMenu:re=>{re.preventDefault(),me({sessionId:e.id,x:re.clientX,y:re.clientY})},"data-testid":`chat-session-${e.id}`,children:[t.jsx("button",{className:"chat-session-delete-btn",onClick:re=>{re.stopPropagation(),we(e.id)},"data-testid":"chat-session-delete-btn","aria-label":"Delete conversation",children:t.jsx(Gt,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[e.title||"Untitled",c?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":"Unread messages"}):null]}),t.jsx("div",{className:"chat-session-preview",children:e.lastMessagePreview||"No messages"}),t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[b?.provider?t.jsx(at,{provider:b.provider,size:"sm"}):null,t.jsx("span",{children:W.get(e.agentId)?.name||(e.agentId===Xe?_:e.agentId.slice(0,30))})]}),t.jsx("span",{children:e.updatedAt?zs(e.updatedAt):""})]})]},e.id)})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!M&&t.jsx("div",{className:"chat-sidebar-rooms-header","data-testid":"chat-sidebar-rooms-header",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary","data-testid":"chat-create-room-btn",onClick:()=>ve(!0),children:[t.jsx(nt,{size:14}),"Create room"]})}),o.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:"No rooms yet."}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:o.rooms.map(e=>{const a=o.activeRoom?.id===e.id,c=!a&&D("room",e.id,e.updatedAt);return t.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${a?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${e.slug}`,onClick:()=>{H("room",e.id,e.updatedAt),o.selectRoom(e.id),M&&ie(!1)},onKeyDown:b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),H("room",e.id,e.updatedAt),o.selectRoom(e.id),M&&ie(!1))},children:[t.jsxs("span",{className:"chat-room-item-details",children:[t.jsxs("span",{className:"chat-room-item-name-row",children:[t.jsxs("span",{className:"chat-room-item-name",children:["#",e.name]}),c?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":"Unread messages"}):null]}),a?t.jsxs("span",{className:"chat-room-item-meta",children:[o.activeRoomMembers.length," ",o.activeRoomMembers.length===1?"member":"members"]}):null]}),t.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${e.slug}`,"aria-label":`Delete room ${e.name}`,onClick:b=>{b.stopPropagation(),O(e.id)},children:t.jsx(Gt,{size:14})})]},e.id)})})]}),u==="rooms"?M?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary chat-sidebar-footer-btn","data-testid":"chat-create-room-btn",onClick:()=>ve(!0),children:[t.jsx(nt,{size:14}),"Create room"]})}):null:t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:()=>V(!0),"data-testid":"chat-new-btn",children:[t.jsx(nt,{size:14}),"New Chat"]})})]}),!M&&Me&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":vt,"aria-valuemax":xt,"aria-valuenow":Se,"aria-label":"Resize chat sidebar",tabIndex:0,onPointerDown:Xs,onKeyDown:Ys}),ue&&t.jsxs("div",{className:"chat-session-context-menu",style:{top:ue.y,left:ue.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>Vs(ue.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Pn,{size:14}),"Archive"]}),t.jsxs("button",{onClick:()=>{me(null),we(ue.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(Gt,{size:14}),"Delete"]})]}),ye&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>we(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:"Delete Conversation?"}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:"This action cannot be undone. All messages in this conversation will be permanently deleted."}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>we(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void qs(ye),children:"Delete"})]})]})}),$&&ee&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>O(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:"Delete Room?"}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:"This action cannot be undone. This room and all its messages will be permanently deleted."}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>O(null),children:"Cancel"}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await o.deleteRoom(ee),O(null)}catch{r("Failed to delete room","error")}})()},children:"Delete"})]})]})}),$&&u==="rooms"?t.jsxs("div",{className:is,style:rs,children:[o.activeRoom?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-room-thread-header",children:[M&&t.jsx("button",{className:"btn-icon",onClick:It,"data-testid":"chat-back-btn",children:t.jsx(ys,{size:16})}),t.jsxs("div",{className:"chat-room-switcher-menu",ref:Qt,children:[t.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":dt,onClick:()=>Je(e=>!e),children:[t.jsxs("span",{className:"chat-thread-header-title",children:["#",o.activeRoom.name]}),t.jsx(bt,{size:16,"aria-hidden":"true"})]}),dt&&t.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:o.rooms.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${e.id===o.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${e.id}`,onClick:()=>{H("room",e.id,e.updatedAt),o.selectRoom(e.id),Je(!1)},children:["#",e.name]},e.id))})]}),t.jsx("div",{className:"chat-room-thread-members",children:o.activeRoomMembers.map(e=>t.jsx($s,{agent:W.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:pe,onScroll:os,children:[o.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:"Loading messages..."}):o.messages.length===0?t.jsx("div",{className:"chat-empty-state",children:"No messages yet. Start the conversation!"}):o.messages.map(e=>{const a=e.senderAgentId?W.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):"You",c={id:e.id,sessionId:e.roomId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput??void 0,toolCalls:void 0,fallbackInfo:void 0,attachments:e.attachments,createdAt:e.createdAt};return t.jsx(Vt,{message:c,forcePlain:q,agentName:a,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:o.activeRoom?.id??null,mentionAgentsByName:Mt,roomContext:Ne},e.id)}),t.jsx("div",{ref:Yt})]}),o.activeRoom&&Q&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:Ke,children:[t.jsx(bt,{size:14}),"Latest"]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:"Select a room or create one"}),o.activeRoom&&t.jsx("div",{className:"chat-input-area",children:t.jsxs("div",{className:"chat-input-row",children:[t.jsxs("div",{className:"chat-input-wrapper",children:[t.jsx("textarea",{ref:cs,className:"chat-input-textarea",placeholder:"Type a message...",value:g,onChange:ds,onKeyDown:ls,onKeyUp:us,onClick:gt,onBlur:ms,onFocus:hs,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||document.activeElement!==e.currentTarget&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))},rows:1,"data-testid":"chat-input"}),t.jsx(ws,{agents:Ge,filter:je,highlightedIndex:x,visible:l,onSelect:ht,position:"below",roomMemberIds:Ne?.memberIds,roomName:Ne?.roomName})]}),t.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:e=>{e.pointerType&&e.pointerType!=="mouse"&&e.preventDefault()},onMouseDown:e=>{e.preventDefault()},onClick:()=>{At()},disabled:!g.trim(),"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:t.jsx(Ss,{size:16})})]})})]}):t.jsxs("div",{className:is,style:rs,children:[($t||!M)&&t.jsxs("div",{className:"chat-thread-header",children:[M&&$t&&t.jsx("button",{className:"btn-icon",onClick:Tt,"data-testid":"chat-back-btn",children:t.jsx(ys,{size:16})}),t.jsx("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:Qs?t.jsxs("div",{className:"chat-mobile-session-menu",ref:Jt,children:[t.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":lt,onClick:()=>Oe(e=>!e),children:[Fe?t.jsx(at,{provider:Fe,size:"md"}):t.jsx(rt,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Pt}),ps&&t.jsx("span",{className:"chat-model-tag",children:Pe}),t.jsx(bt,{size:16,"aria-hidden":"true"})]}),lt&&t.jsx("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:w.map(e=>t.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${i?.id===e.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${e.id}`,onClick:()=>fs(e.id),children:t.jsx("span",{className:"chat-mobile-session-option-title",children:e.title||"Untitled"})},e.id))})]}):t.jsxs(t.Fragment,{children:[Fe?t.jsx(at,{provider:Fe,size:"md"}):t.jsx(rt,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Pt}),ps&&t.jsx("span",{className:"chat-model-tag",children:Pe})]})}),$t&&t.jsx("button",{type:"button",className:`chat-thread-header-render-toggle${q?" chat-thread-header-render-toggle--plain":""}`,"data-testid":"chat-thread-render-toggle","aria-label":q?"Show all messages as rendered Markdown":"Show all messages as plain text",onClick:en,children:q?t.jsx(Fn,{size:14}):t.jsx(Ln,{size:14})}),!M&&t.jsxs("button",{className:"btn btn-sm btn-primary chat-thread-header-new-chat",onClick:()=>V(!0),"data-testid":"chat-thread-new-chat-btn",children:[t.jsx(nt,{size:14}),"New Chat"]})]}),t.jsxs("div",{className:"chat-messages",ref:pe,onScroll:os,children:[S?t.jsxs(t.Fragment,{children:[p.map(e=>t.jsx(Vt,{message:e,forcePlain:q,agentName:Ft,hideAssistantIdentity:zt,showAssistantModelTag:Lt,activeModelTag:Pe,activeModelProvider:Fe,activeSessionId:i?.id??null,mentionAgentsByName:Mt,roomContext:null,copyAction:Ut&&e.role==="assistant"?Ht(e.id,e.content):void 0},e.id)),t.jsxs("div",{className:"chat-message chat-message--assistant chat-message--streaming",children:[!zt&&t.jsxs("div",{className:"chat-message-avatar",children:[Fe?t.jsx(at,{provider:Fe,size:"sm"}):t.jsx(rt,{size:14}),t.jsx("span",{children:Ft}),Lt]}),F?tn(F,q):t.jsx("div",{className:"chat-message-content chat-message-content--waiting",children:G?"Thinking…":"Connecting…"}),Ut&&F&&Ht("__streaming__",F,"chat-copy-response-streaming"),_s(Z),G&&t.jsxs("details",{className:"chat-message-thinking",children:[t.jsx("summary",{children:"Thinking"}),t.jsx("pre",{className:"chat-message-thinking-content",children:wt(G)})]}),t.jsxs("div",{className:"chat-typing-indicator",children:[t.jsx("span",{}),t.jsx("span",{}),t.jsx("span",{})]})]})]}):m?t.jsx("div",{className:"chat-empty-state",children:"Loading messages..."}):p.length===0&&!i?Js():p.length===0&&i?t.jsx("div",{className:"chat-empty-state",children:"No messages yet. Start the conversation!"}):t.jsx(t.Fragment,{children:p.map(e=>t.jsx(Vt,{message:e,forcePlain:q,agentName:Ft,hideAssistantIdentity:zt,showAssistantModelTag:Lt,activeModelTag:Pe,activeModelProvider:Fe,activeSessionId:i?.id??null,mentionAgentsByName:Mt,roomContext:null,copyAction:Ut&&e.role==="assistant"?Ht(e.id,e.content):void 0},e.id))}),t.jsx("div",{ref:Yt})]}),Q&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:Ke,children:[t.jsx(bt,{size:14}),"Latest"]}),i&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:es,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:e=>{mt(e.target.files),e.target.value=""}}),Re&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":"Skill suggestions",children:jt?t.jsx("div",{className:"chat-skill-menu-empty",children:"Loading skills…"}):be.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:Ye?"No skills found":"No skills available"}):be.map((e,a)=>t.jsxs("button",{type:"button",role:"option","aria-selected":a===_e,className:`chat-skill-menu-item${a===_e?" chat-skill-menu-item--highlighted":""}`,onMouseDown:c=>c.preventDefault(),onMouseEnter:()=>Ee(a),onClick:()=>Et(e),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.relativePath,children:e.relativePath})]},e.id))}),A.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:A.map((e,a)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${a}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>Ks(a),"data-testid":`chat-attachment-remove-${a}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${a}`))}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":"Attach files",onClick:()=>es.current?.click(),children:t.jsx(zn,{size:16})}),t.jsxs("div",{className:`chat-input-wrapper${J?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),T(!0)},onDragLeave:()=>T(!1),onDrop:e=>{e.preventDefault(),T(!1),mt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:cs,className:"chat-input-textarea",placeholder:"Type a message...",value:g,onChange:ds,onKeyDown:ls,onKeyUp:us,onClick:gt,onBlur:ms,onFocus:hs,onPaste:Bs,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||document.activeElement!==e.currentTarget&&(e.preventDefault(),e.currentTarget.focus({preventScroll:!0}))},rows:1,"data-testid":"chat-input"}),t.jsx(ws,{agents:Ge,filter:je,highlightedIndex:x,visible:l,onSelect:ht,position:"below",roomMemberIds:Ne?.memberIds,roomName:Ne?.roomName}),t.jsx(_n,{visible:z.mentionActive&&!l,position:Hs,files:z.files,selectedIndex:z.selectedIndex,onSelect:e=>{const a=z.selectFile(e,g);B(a),z.dismissMention(),Qe(!1),fe.current?.focus()},loading:z.loading}),y&&t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:`Queued: ${Zs}`}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":"Dismiss queued message","data-testid":"chat-pending-dismiss",onClick:I,children:"×"})]})]}),S?t.jsx("button",{className:"chat-input-stop",onClick:K,"aria-label":"Stop generation","data-testid":"chat-stop-btn",children:t.jsx(Un,{size:14})}):t.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:e=>{e.pointerType&&e.pointerType!=="mouse"&&e.preventDefault()},onMouseDown:e=>{e.preventDefault()},onClick:()=>{Rt()},disabled:!g.trim()&&A.length===0,"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:t.jsx(Ss,{size:16})})]})]})]}),$&&t.jsx(Yn,{isOpen:it,onClose:()=>ve(!1),projectId:n,existingRoomNames:o.rooms.map(e=>e.name),onCreate:async e=>{await o.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),u!=="rooms"&&R("rooms"),ve(!1),M&&ie(!1)}}),se&&t.jsx(ca,{projectId:n,onClose:()=>V(!1),onCreate:Ws})]})}export{ga as ChatView,Qn as clampChatInputHeight,Ds as resolveSessionProvider};