@runfusion/fusion 0.54.0 → 0.55.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 (135) hide show
  1. package/dist/bin.js +3384 -768
  2. package/dist/client/.vite/manifest.json +283 -251
  3. package/dist/client/assets/AgentDetailView-B_VfFSlt.js +18 -0
  4. package/dist/client/assets/{AgentDetailView-BzSyldiW.css → AgentDetailView-D7UY2Tup.css} +1 -1
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-D2AQ6swg.js → AgentPermissionPolicyEditor-QZhz41AU.js} +1 -1
  6. package/dist/client/assets/{AgentsView-DwEFPKuN.js → AgentsView-hkhJ8SUq.js} +6 -6
  7. package/dist/client/assets/ChatView-B4WnXLYA.js +6 -0
  8. package/dist/client/assets/{CommandCenter-BABqoSkg.js → CommandCenter-B3fAajUO.js} +16 -16
  9. package/dist/client/assets/{DevServerView-DlgOzRdC.js → DevServerView-BR0ngFBw.js} +1 -1
  10. package/dist/client/assets/{DirectoryPicker-BwMSmxYS.js → DirectoryPicker-BiS41Hca.js} +1 -1
  11. package/dist/client/assets/DocumentsView-BnRvIUpa.js +1 -0
  12. package/dist/client/assets/{EvalsView-CQBNrO5n.js → EvalsView-Bvx18QyC.js} +1 -1
  13. package/dist/client/assets/{ExperimentalAgentOnboardingModal-2SDqP2lc.js → ExperimentalAgentOnboardingModal-CKGJcfXI.js} +1 -1
  14. package/dist/client/assets/{GoalsView-BgkX-_SB.js → GoalsView-Bj1yVIiv.js} +1 -1
  15. package/dist/client/assets/{InsightsView-CJY4eZcO.js → InsightsView-DBX8DI60.js} +2 -2
  16. package/dist/client/assets/{MemoryView-5Crtfanz.js → MemoryView-CqkRH2fa.js} +1 -1
  17. package/dist/client/assets/{PiExtensionsManager-COmzskVa.js → PiExtensionsManager-BMMmGWe2.js} +2 -2
  18. package/dist/client/assets/PluginManager-C1bdfN2W.js +1 -0
  19. package/dist/client/assets/{PullRequestView-DAHh0FVM.js → PullRequestView-D0CsXWLl.js} +2 -2
  20. package/dist/client/assets/{ResearchView-cSUka3sd.js → ResearchView-CVgmXAlj.js} +1 -1
  21. package/dist/client/assets/{SecretsView-ChFAfFRY.js → SecretsView-Bv_gw5Ix.js} +1 -1
  22. package/dist/client/assets/{SessionTerminal-D4R3ScvQ.css → SessionTerminal-BvK8A98c.css} +1 -1
  23. package/dist/client/assets/{SessionTerminal-CtQKDaqI.js → SessionTerminal-VLdVV3Ji.js} +1 -1
  24. package/dist/client/assets/{SettingsModal-BzZNPNIh.css → SettingsModal-4t8rV7rh.css} +1 -1
  25. package/dist/client/assets/{SettingsModal-pAz_hOoN.js → SettingsModal-D7YgojbV.js} +1 -1
  26. package/dist/client/assets/SettingsModal-gcrh5EOG.js +21 -0
  27. package/dist/client/assets/SetupWizardModal-DvmTlFP_.js +2 -0
  28. package/dist/client/assets/{ShadcnColorPicker-CsfgWpf6.js → ShadcnColorPicker-DM2fqGwl.js} +1 -1
  29. package/dist/client/assets/{SkillsView-BSUplEYb.js → SkillsView-Bb-JTo99.js} +1 -1
  30. package/dist/client/assets/{TodoView-DhBseLvM.js → TodoView-bV-7deOh.js} +1 -1
  31. package/dist/client/assets/{WorkflowNodeEditor-Bi12CNif.js → WorkflowNodeEditor-Ui1q_fFI.js} +3 -3
  32. package/dist/client/assets/{agentSkills-qVb0x_G3.js → agentSkills-DGFyuKuP.js} +1 -1
  33. package/dist/client/assets/{app-DczBmsP4.js → app--OM-ul6R.js} +3 -3
  34. package/dist/client/assets/{app-BhtYYxin.js → app-BCvqf8qq.js} +3 -3
  35. package/dist/client/assets/app-BZqqEiWR.js +13 -0
  36. package/dist/client/assets/{app-5S4z84u5.js → app-DQeH1UDD.js} +3 -3
  37. package/dist/client/assets/{app-Cts0__Vx.js → app-FiYwRatp.js} +3 -3
  38. package/dist/client/assets/{app-_GFUqcMK.js → app-rGdYcsAA.js} +3 -3
  39. package/dist/client/assets/{architectureDiagram-3BPJPVTR-DEt4eIEQ.js → architectureDiagram-3BPJPVTR-DP7vOyXY.js} +1 -1
  40. package/dist/client/assets/{blockDiagram-GPEHLZMM-CJuX0UM_.js → blockDiagram-GPEHLZMM-Di9v1pV8.js} +1 -1
  41. package/dist/client/assets/{c4Diagram-AAUBKEIU-a46Lm113.js → c4Diagram-AAUBKEIU-Dvb8RSfr.js} +1 -1
  42. package/dist/client/assets/channel-C5g9M3Sk.js +1 -0
  43. package/dist/client/assets/{chunk-2J33WTMH-iBhwyS0c.js → chunk-2J33WTMH-gLcAuGjI.js} +1 -1
  44. package/dist/client/assets/{chunk-4BX2VUAB-C7lS5wER.js → chunk-4BX2VUAB-B-B0wjkx.js} +1 -1
  45. package/dist/client/assets/{chunk-55IACEB6-CQ6YOncn.js → chunk-55IACEB6-XUDeC0Co.js} +1 -1
  46. package/dist/client/assets/{chunk-727SXJPM-CveMaMKK.js → chunk-727SXJPM-1eebiGA2.js} +1 -1
  47. package/dist/client/assets/{chunk-AQP2D5EJ-DErjGUEk.js → chunk-AQP2D5EJ-D9VOB5QS.js} +1 -1
  48. package/dist/client/assets/{chunk-FMBD7UC4-DXUvEFfJ.js → chunk-FMBD7UC4-EFNFEaAz.js} +1 -1
  49. package/dist/client/assets/{chunk-ND2GUHAM-w5RqSj1J.js → chunk-ND2GUHAM-CbeQailD.js} +1 -1
  50. package/dist/client/assets/{chunk-QZHKN3VN-CAi0lJ7V.js → chunk-QZHKN3VN-D55N6EBz.js} +1 -1
  51. package/dist/client/assets/classDiagram-4FO5ZUOK-B-wdlvD6.js +1 -0
  52. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-B-wdlvD6.js +1 -0
  53. package/dist/client/assets/{cose-bilkent-S5V4N54A-Ck2h4uV5.js → cose-bilkent-S5V4N54A-B0zbhkX3.js} +1 -1
  54. package/dist/client/assets/createLucideIcon-CshVyKO4.js +21 -0
  55. package/dist/client/assets/{dagre-BM42HDAG-BCRTXNj6.js → dagre-BM42HDAG-BL6peXwl.js} +1 -1
  56. package/dist/client/assets/dashboard-view-Bsdq3OM4.css +1 -0
  57. package/dist/client/assets/dashboard-view-CS1H5SQN.js +1 -0
  58. package/dist/client/assets/dashboard-view-DafOfnxI.js +1 -0
  59. package/dist/client/assets/{dashboard-view-D9rF_PCq.js → dashboard-view-Db3n_W85.js} +1320 -1335
  60. package/dist/client/assets/{diagram-2AECGRRQ-DTTk-DYO.js → diagram-2AECGRRQ-cYKwSHk7.js} +1 -1
  61. package/dist/client/assets/{diagram-5GNKFQAL-jDc9kMi2.js → diagram-5GNKFQAL-DHIwTGuM.js} +1 -1
  62. package/dist/client/assets/{diagram-KO2AKTUF-CcLmzlGr.js → diagram-KO2AKTUF-DfHBJ4aX.js} +1 -1
  63. package/dist/client/assets/{diagram-LMA3HP47-DCW8XKQj.js → diagram-LMA3HP47-pWhYmB6Z.js} +1 -1
  64. package/dist/client/assets/{diagram-OG6HWLK6-wbbKquPs.js → diagram-OG6HWLK6-GzWqbi_m.js} +1 -1
  65. package/dist/client/assets/{erDiagram-TEJ5UH35-Fo933Mo7.js → erDiagram-TEJ5UH35-CCVm5eiR.js} +1 -1
  66. package/dist/client/assets/{flowDiagram-I6XJVG4X-Dfum7HZP.js → flowDiagram-I6XJVG4X-CUTdnU6S.js} +1 -1
  67. package/dist/client/assets/{folder-open-B8vOwFeP.js → folder-open-DOCy9GVC.js} +1 -1
  68. package/dist/client/assets/{ganttDiagram-6RSMTGT7-BzEBCn01.js → ganttDiagram-6RSMTGT7-CW4ENJaC.js} +1 -1
  69. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-CgovghHs.js → gitGraphDiagram-PVQCEYII-QXXMfSzp.js} +1 -1
  70. package/dist/client/assets/index-B6ttSchA.js +1336 -0
  71. package/dist/client/assets/index-CPE2Kwra.css +1 -0
  72. package/dist/client/assets/{infoDiagram-5YYISTIA-BzpU4Wys.js → infoDiagram-5YYISTIA-CZyHbj0n.js} +1 -1
  73. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-cpp5pozu.js → ishikawaDiagram-YF4QCWOH-Dea84lqZ.js} +1 -1
  74. package/dist/client/assets/{journeyDiagram-JHISSGLW-BVjcw6oo.js → journeyDiagram-JHISSGLW-Db2iKGU5.js} +1 -1
  75. package/dist/client/assets/{kanban-definition-UN3LZRKU-4unAhBzo.js → kanban-definition-UN3LZRKU-CB9loIqR.js} +1 -1
  76. package/dist/client/assets/loader-circle-CMNcxXXr.js +16 -0
  77. package/dist/client/assets/{mermaid.core-DzIyUj9t.js → mermaid.core-CoQ8aCb0.js} +4 -4
  78. package/dist/client/assets/{mindmap-definition-RKZ34NQL-Be_yfVir.js → mindmap-definition-RKZ34NQL-JPb2wF-K.js} +1 -1
  79. package/dist/client/assets/{pieDiagram-4H26LBE5-Cfnw2aji.js → pieDiagram-4H26LBE5-pdZzOreP.js} +1 -1
  80. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-BFlC-_Uo.js → quadrantDiagram-W4KKPZXB-Dh9Ids90.js} +1 -1
  81. package/dist/client/assets/{requirementDiagram-4Y6WPE33-DpVPzCOx.js → requirementDiagram-4Y6WPE33-BVPOSvHU.js} +1 -1
  82. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-DM-gKKP0.js → sankeyDiagram-5OEKKPKP-BqSMUpsx.js} +1 -1
  83. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-DjhZCZhd.js → sequenceDiagram-3UESZ5HK-B8nepQ6X.js} +1 -1
  84. package/dist/client/assets/{shield-alert-DCfkjjYc.js → shield-alert-CtSaIQNY.js} +1 -1
  85. package/dist/client/assets/{stateDiagram-AJRCARHV-BCA96rdI.js → stateDiagram-AJRCARHV-CQv9RdRp.js} +1 -1
  86. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-DHds08RS.js → stateDiagram-v2-BHNVJYJU-BZ_mlvie.js} +1 -1
  87. package/dist/client/assets/{timeline-definition-PNZ67QCA-CHW2OQRw.js → timeline-definition-PNZ67QCA-CAjwM-Z5.js} +1 -1
  88. package/dist/client/assets/{upload-EJc5PJPz.js → upload-0_pT1euA.js} +1 -1
  89. package/dist/client/assets/{users-C-e-99Vp.js → users--1B6mnm8.js} +1 -1
  90. package/dist/client/assets/{vennDiagram-CIIHVFJN-shGh4eBY.js → vennDiagram-CIIHVFJN-BO3Um3rH.js} +1 -1
  91. package/dist/client/assets/{wardley-L42UT6IY-l0RGrVhn.js → wardley-L42UT6IY-BzqJcqDA.js} +1 -1
  92. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-C-USmO8A.js → wardleyDiagram-YWT4CUSO-Bctxc6_5.js} +1 -1
  93. package/dist/client/assets/{xychartDiagram-2RQKCTM6-CHX9Umta.js → xychartDiagram-2RQKCTM6-CgDuiMFR.js} +1 -1
  94. package/dist/client/assets/zoom-out-DzDzWQt1.js +21 -0
  95. package/dist/client/index.html +13 -4
  96. package/dist/client/version.json +1 -1
  97. package/dist/droid-cli/package.json +1 -1
  98. package/dist/extension.js +2066 -271
  99. package/dist/pi-claude-cli/package.json +1 -1
  100. package/dist/plugin-sdk/index.d.ts +61 -1
  101. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  102. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  103. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  104. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +70 -25
  105. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  106. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  107. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  108. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  109. package/dist/plugins/fusion-plugin-linear-import/bundled.js +658 -0
  110. package/dist/plugins/fusion-plugin-linear-import/manifest.json +48 -0
  111. package/dist/plugins/fusion-plugin-linear-import/package.json +11 -0
  112. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  113. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  114. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  115. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  116. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  117. package/package.json +2 -1
  118. package/skill/fusion/SKILL.md +2 -2
  119. package/skill/fusion/references/engine-tools.md +1 -0
  120. package/skill/fusion/references/extension-tools.md +81 -0
  121. package/skill/fusion/references/fusion-capabilities.md +7 -0
  122. package/dist/client/assets/AgentDetailView-BJditQat.js +0 -18
  123. package/dist/client/assets/ChatView-B4bjPXFN.js +0 -6
  124. package/dist/client/assets/DocumentsView-BfaRXFg5.js +0 -1
  125. package/dist/client/assets/PluginManager-CGWXqZMa.js +0 -1
  126. package/dist/client/assets/SettingsModal-BYaotQ2o.js +0 -21
  127. package/dist/client/assets/SetupWizardModal-eHZHi8VP.js +0 -2
  128. package/dist/client/assets/app-B1VYocx2.js +0 -13
  129. package/dist/client/assets/channel-BGI9APMr.js +0 -1
  130. package/dist/client/assets/classDiagram-4FO5ZUOK-g6hCcufy.js +0 -1
  131. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-g6hCcufy.js +0 -1
  132. package/dist/client/assets/dashboard-view-BfLJ60Kd.js +0 -1
  133. package/dist/client/assets/index-BjELA24x.js +0 -1336
  134. package/dist/client/assets/index-DwGW7OJh.css +0 -1
  135. package/dist/client/assets/zoom-out-NWbVkreR.js +0 -41
@@ -1,6 +0,0 @@
1
- import{r as s,j as t,b as Ua}from"./vendor-react-SZ_qB27O.js";import{c as Ka,aA as et,ay as qe,dL as _s,dM as es,bU as jt,dN as $s,aD as ie,dO as on,dx as vt,dP as Os,dQ as Et,dR as Ga,dy as dn,dK as pt,dS as Va,dT as Bs,dU as Wa,dV as Xa,dW as qa,dX as Qa,ai as pa,dY as Ya,az as Xn,bB as zs,dZ as Ja,d_ as Za,d$ as $n,e0 as er,e1 as tr,e2 as nr,e3 as sr,e4 as ar,e5 as rr,f as un,e6 as or,e7 as ir,bo as cr,al as lr,bb as cn,a2 as dr,c0 as ur,e8 as mr,i as hr,e9 as ba,ea as fr,dv as gr,W as pr,eb as br,ec as Hs,G as vr,H as yr,V as wr,P as ht,di as Us,dh as xr,X as Cr,aK as Sr,J as On,ds as Bn,I as Ks,bO as Mr,bs as Gs,o as Zt,ed as zn,ee as Vs,ef as Ws,eg as Xs,bu as qn,D as kr,F as Rr,eh as Ar,bM as qs,bP as Nr}from"./index-BjELA24x.js";import{u as tt}from"./vendor-i18n-GF3RlKbq.js";import{SessionTerminal as Qs}from"./SessionTerminal-CtQKDaqI.js";import"./vendor-reactflow-CnI7NMXG.js";import"./vendor-xterm-BNq00GSj.js";import"./vendor-codemirror-jBKmHyH0.js";import"./shield-alert-DCfkjjYc.js";/**
2
- * @license lucide-react v1.7.0 - ISC
3
- *
4
- * This source code is licensed under the ISC license.
5
- * See the LICENSE file in the root directory of this source tree.
6
- */const Er=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],va=Ka("hash",Er);function Ys(n){const{sessionId:r,tempUserMessageId:i,initialText:g,initialThinking:c,initialToolCalls:d,setStreamingText:b,setStreamingThinking:p,setStreamingToolCalls:o,cancelStreamingFlushesRef:f,addToast:B,onDone:C,onError:M,onFallbackSession:N}=n;let F=g??"",E=c??"",A=d?[...d]:[],W,k=null,ae=null;const G=()=>{k=null,b(F)},ue=()=>{ae=null,p(E)},R=()=>{k!==null&&(cancelAnimationFrame(k),k=null),ae!==null&&(cancelAnimationFrame(ae),ae=null)};return f.current=R,{handlers:{onThinking:U=>{E+=U,ae===null&&(ae=requestAnimationFrame(ue))},onText:U=>{F+=U,k===null&&(k=requestAnimationFrame(G))},onToolStart:U=>{A=[...A,{toolName:U.toolName,args:U.args,isError:!1,status:"running"}],o(A)},onToolEnd:U=>{const X=[...A];for(let _=X.length-1;_>=0;_--){const V=X[_];if(V?.toolName===U.toolName&&V.status==="running"){X[_]={...V,status:"completed",isError:U.isError,result:U.result},A=X,o(X);return}}A=[...X,{toolName:U.toolName,isError:U.isError,result:U.result,status:"completed"}],o(A)},onFallback:U=>{W=U,N?.(U,r),B?.(`Primary model unavailable. Switched to fallback ${U.fallbackModel}.`,"warning")},onDone:U=>{R(),C({messageId:U.messageId,message:U.message,accumulated:{text:F,thinking:E,toolCalls:A,fallbackInfo:W}})},onError:(U,X)=>{R(),M(U,i,X)}},cancelFlushes:R}}const Tr="fusion:chat-pending:";function ts(n){return n?`${Tr}${n}`:null}function jr(n){const r=ts(n);if(!r||typeof window>"u")return[];try{const i=localStorage.getItem(r);if(!i)return[];try{const c=JSON.parse(i);if(Array.isArray(c))return c.filter(d=>typeof d=="string"&&d.trim().length>0)}catch{}const g=i.trim();return g?[g]:[]}catch{return[]}}function Hn(n,r){const i=ts(n);if(!(!i||typeof window>"u"))try{const g=r.filter(c=>c.trim().length>0);if(g.length===0){localStorage.removeItem(i);return}localStorage.setItem(i,JSON.stringify(g))}catch{}}function en(n){const r=ts(n);if(!(!r||typeof window>"u"))try{localStorage.removeItem(r)}catch{}}const Un="kb-chat-active-session",Dr="task-planner:";function Qn(n){return n.agentId.startsWith(Dr)}function Fr(n){return Qn(n)&&!n.lastMessageAt&&!n.lastMessagePreview}function Js(n){const r=typeof n=="string"?n.trim():"",i=r.indexOf("/");return!r||i<=0||i>=r.length-1?{}:{modelProvider:r.slice(0,i),modelId:r.slice(i+1)}}function Ir(n){const r=n?.toolCalls;if(!Array.isArray(r))return;const i=r.map(g=>{if(!g||typeof g!="object")return null;const c=g,d=typeof c.toolName=="string"?c.toolName:"";if(!d)return null;const b=c.args;return{toolName:d,...b&&typeof b=="object"?{args:b}:{},isError:!!c.isError,result:c.result,status:"completed"}}).filter(g=>g!==null);return i.length>0?i:void 0}function Pr(n){const r=n?.fallback;if(!r||typeof r!="object")return;const i=r,g=typeof i.primaryModel=="string"?i.primaryModel:"",c=typeof i.fallbackModel=="string"?i.fallbackModel:"",d=i.triggerPoint;if(!(!g||!c||d!=="session-creation"&&d!=="prompt-time"))return{primaryModel:g,fallbackModel:c,triggerPoint:d}}function Lr(n){const r=n?.failureInfo;if(!r||typeof r!="object")return;const i=r,g=typeof i.summary=="string"?i.summary.trim():"";if(!g)return;const c=(()=>{const d=i.reference;if(!d||typeof d!="object")return;const b=d,p=typeof b.kind=="string"?b.kind.trim():"",o=typeof b.id=="string"?b.id.trim():"";if(!(!p||!o))return{kind:p,id:o,...typeof b.label=="string"&&b.label.trim()?{label:b.label.trim()}:{}}})();return{summary:g,...typeof i.errorClass=="string"&&i.errorClass.trim()?{errorClass:i.errorClass.trim()}:{},...typeof i.code=="string"&&i.code.trim()?{code:i.code.trim()}:{},...typeof i.detail=="string"&&i.detail.trim()?{detail:i.detail.trim()}:{},...c?{reference:c}:{}}}function Zs(n,r){const i="Failed to get response";return typeof n=="string"?{summary:n.trim()||i}:{summary:typeof n.summary=="string"&&n.summary.trim()?n.summary.trim():i,...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 tn(n){return{id:n.id,sessionId:n.sessionId,role:n.role,content:n.content,thinkingOutput:n.thinkingOutput,toolCalls:Ir(n.metadata),fallbackInfo:Pr(n.metadata),failureInfo:Lr(n.metadata),attachments:n.attachments,createdAt:n.createdAt}}function ea(n,r){if(n.some(c=>c.id===r.id))return n;const i=n.findIndex(c=>c.role==="user"&&c.id.startsWith("temp-")&&c.sessionId===r.sessionId&&c.content.trim()===r.content.trim());if(i<0)return[...n,r];const g=[...n];return g[i]=r,g}function _r(n,r){const i=s.useCallback(h=>h?`${et.CHAT_SESSIONS_PREFIX}${h}`:null,[]),g=s.useCallback((h,v)=>h&&v?`${et.CHAT_MESSAGES_PREFIX}${h}:${v}`:null,[]),c=s.useCallback(h=>{const v=i(h);return v?(qe(v,{maxAgeMs:_s})??[]).filter($=>!Qn($)):[]},[i]),[d,b]=s.useState(()=>c(n)),[p,o]=s.useState(null),[f,B]=s.useState(()=>c(n).length===0),[C,M]=s.useState([]),[N,F]=s.useState(!1),[E,A]=s.useState(!1),[W,k]=s.useState(""),[ae,G]=s.useState(""),[ue,R]=s.useState([]),[le,U]=s.useState([]),[X,_]=s.useState(""),[V,y]=s.useState(!1),{agentsMap:P}=es(n),j=s.useRef(null),q=s.useRef(null),S=s.useRef(!1),T=s.useRef([]),D=s.useRef(()=>!1),m=s.useRef(null),I=s.useRef(d),l=s.useRef(p),re=s.useRef(C),O=s.useRef(E);I.current=d,l.current=p,re.current=C,O.current=E,s.useEffect(()=>{T.current=le},[le]);const z=s.useRef(new Set),he=s.useRef(0),pe=s.useRef(n);pe.current!==n&&(jt({view:"useChat",trigger:"project-context-change",projectId:n,replayAttempted:!1,detail:{previousProjectId:pe.current??null}}),pe.current=n,he.current++);const te=s.useCallback(async()=>{I.current.length===0&&B(!0);try{const v=[...(await $s(n)).sessions].sort(($,se)=>new Date(se.updatedAt).getTime()-new Date($.updatedAt).getTime());b(v);const x=i(n);x&&ie(x,v,{maxBytes:5e5})}catch{const h=c(n);if(I.current.length===0&&h.length===0){const v=i(n);v&&on(v)}}finally{B(!1)}},[i,n]);s.useEffect(()=>{const h=c(n);b(h),B(h.length===0)},[n,c]),s.useEffect(()=>{te()},[te,n]);const ve=s.useRef(()=>{}),ye=s.useRef(!1);s.useEffect(()=>{ye.current=!1,q.current=null},[n]),s.useEffect(()=>{if(f||ye.current||l.current)return;const h=vt(Un,n);if(!h){ye.current=!0;return}const v=d.find(x=>x.id===h);if(v){ye.current=!0,ve.current(h,v);return}ye.current=!0},[f,d,n]);const Ke=s.useCallback((h,v)=>{const x=g(h,v);return x?qe(x,{maxAgeMs:_s})??[]:[]},[g]),Ge=s.useCallback((h,v)=>{const x=Ke(n,h);return x.length>0?(M(x),F(!1),!0):(v?.clearOnMiss!==!1&&M([]),!1)},[n,Ke]),we=s.useCallback(async(h,v)=>{const x=typeof v?.offset=="number"&&v.offset>0||typeof v?.before=="string",$=g(n,h),se=x?[]:Ke(n,h),H=se.length>0;!x&&H?(M(se),F(!1)):F(!0);try{const Q=await Os(h,{limit:50,order:"desc",...v},n),Y=Q.messages.slice().reverse().map(tn),K=l.current?.id===h||v?.commitForStreamingAttach===!0&&q.current?.sessionId===h;x?K&&(M(oe=>[...Y,...oe]),y(Q.messages.length>=50)):K&&(M(Y),y(Q.messages.length>=50),$&&ie($,Y,{maxBytes:5e5}))}catch{!x&&re.current.length===0&&H&&(M(se),F(!1))}finally{F(!1)}},[g,n,Ke]),Fe=s.useCallback(()=>{m.current?.(),m.current=null,T.current=[],U([]),k(""),G(""),R([]),A(!1)},[]),Dt=s.useCallback(h=>{const v=l.current?.id;if(typeof h=="number"){const x=T.current.filter(($,se)=>se!==h);T.current=x,U(x),Hn(v,x);return}en(v),T.current=[],U([])},[]),fe=s.useCallback(()=>{const[h,...v]=T.current,x=h?.trim();if(!x)return;const $=l.current?.id;T.current=v,U(v),Hn($,v),wt.current(x)},[]),Qe=s.useCallback(async(h,v)=>{try{const{session:x}=await Et(h,n);if(l.current?.id!==h||T.current.length===0)return;if(x.isGenerating||x.inFlightGeneration){D.current(h,x.inFlightGeneration,{silent:v?.silent,priorThreadLoadAlreadyStarted:!0});return}fe()}catch{}},[fe,n]),me=s.useCallback((h,v,x)=>{if(j.current||!h)return!0;S.current=!1;const $=re.current,se=$.length===0||$[0]?.sessionId!==h;q.current={sessionId:h,replayFromEventId:typeof v?.replayFromEventId=="number"?v.replayFromEventId:null},se&&!x?.priorThreadLoadAlreadyStarted&&(Ge(h,{clearOnMiss:!1}),we(h,{commitForStreamingAttach:!0})),v&&(k(v.streamingText),G(v.streamingThinking),R(v.toolCalls)),A(!0);const{handlers:H}=Ys({sessionId:h,tempUserMessageId:"",initialText:v?.streamingText,initialThinking:v?.streamingThinking,initialToolCalls:v?.toolCalls,setStreamingText:k,setStreamingThinking:G,setStreamingToolCalls:R,cancelStreamingFlushesRef:m,addToast:x?.silent?void 0:r,onFallbackSession:(Y,K)=>{const oe=Js(Y.fallbackModel);b(J=>J.map(ee=>ee.id===K?{...ee,...oe}:ee)),o(J=>J&&J.id===K?{...J,...oe}:J)},onDone:()=>{k(""),G(""),R([]),A(!1),O.current=!1,j.current=null,q.current=null,we(h),fe()},onError:Y=>{k(""),G(""),R([]),A(!1),O.current=!1,j.current=null,q.current=null;const K=Zs(Y);x?.silent||r?.(K.summary,"error"),we(h),Qe(h,{silent:x?.silent})}});jt({view:"useChat",trigger:"sse-open",projectId:n,replayAttempted:typeof v?.replayFromEventId=="number",replayFromEventId:v?.replayFromEventId??null,lastEventId:v?.replayFromEventId??null});const Q=Ga(h,H,n,{...typeof v?.replayFromEventId=="number"?{lastEventId:v.replayFromEventId}:{}});return j.current=Q,!0},[r,fe,Qe,Ge,we,n]);D.current=me;const Te=s.useCallback((h,v)=>{const x=l.current?.id??null;if(h&&x===h&&!v)return;j.current&&(j.current.close(),j.current=null),q.current=null;const $=v??d.find(se=>se.id===h);o($||null),l.current=$||null,h&&Et(h,n).then(({session:se})=>{!se.isGenerating||!se.inFlightGeneration||o(H=>!H||H.id!==h?H:{...H,...se})}).catch(()=>{}),Fe(),y(!1),h?(Ge(h),we(h)):M([]),$?.isGenerating&&me($.id,$.inFlightGeneration,{priorThreadLoadAlreadyStarted:!0}),h?dn(Un,h,n):pt(Un,n)},[me,Ge,d,we,n,Fe]);ve.current=Te,s.useEffect(()=>{const h=p?.id;if(!h)return;const v=jr(h);if(v.length===0)return;T.current=v,U(v);let x=!1;return Et(h,n).then(({session:$})=>{if(!(x||l.current?.id!==h||T.current.length===0)){if($.isGenerating){j.current||me(h,$.inFlightGeneration);return}!O.current&&!j.current&&fe()}}).catch(()=>{}),()=>{x=!0}},[p?.id,me,fe,n]);const yt=s.useCallback(async h=>{const v=l.current?.id,x=await Va(h,n);j.current&&(j.current.close(),j.current=null),q.current=null;const $={id:x.session.id,title:x.session.title,agentId:x.session.agentId,status:x.session.status,modelProvider:x.session.modelProvider,modelId:x.session.modelId,createdAt:x.session.createdAt,updatedAt:x.session.updatedAt};return b(se=>se.some(H=>H.id===$.id)?se:[$,...se]),en(v),Fe(),Te($.id,$),$},[n,Fe,Te]),mn=s.useCallback(async h=>{en(h),await Bs(h,{status:"archived"},n),b(v=>v.filter(x=>x.id!==h)),p?.id===h&&(q.current=null,o(null),M([]))},[p,n]),nt=s.useCallback(async(h,v)=>{const x=v.trim()||null,$=d,se=p;b(H=>H.map(Q=>Q.id===h?{...Q,title:x}:Q)),o(H=>H?.id===h?{...H,title:x}:H);try{const Q=(await Bs(h,{title:x},n)).session;b(Y=>Y.map(K=>K.id===h?{...K,title:Q.title,updatedAt:Q.updatedAt}:K)),o(Y=>Y?.id===h?{...Y,title:Q.title,updatedAt:Q.updatedAt}:Y)}catch(H){throw b($),o(se),r?.("Failed to rename conversation","error"),H}},[p,r,n,d]),Ft=s.useCallback(async h=>{en(h),p?.id===h&&j.current&&(j.current.close(),j.current=null),p?.id===h&&(q.current=null),await Wa(h,n);const v=g(n,h);v&&on(v),b(x=>x.filter($=>$.id!==h)),p?.id===h&&(o(null),M([]))},[p,g,n]),je=s.useCallback(async()=>{if(!p||!V)return;const h=re.current[0]?.createdAt;h&&await we(p.id,{before:h})},[p,V,we]),It=s.useCallback(()=>{p&&(S.current=!0,m.current?.(),m.current=null,j.current?.close(),j.current=null,q.current=null,Xa(p.id,n).catch(()=>{}),A(!1),O.current=!1,k(""),G(""),R([]),fe())},[p,n,fe]),wt=s.useRef(()=>{}),xt=qa(),st=s.useCallback(async h=>{try{await te();const v=await Et(h,n);l.current?.id===h&&o(x=>!x||x.id!==h?x:{...x,...v.session}),v.session.isGenerating?(k(""),G(""),R([]),A(!0),O.current=!0,me(h,v.session.inFlightGeneration,{silent:!0})):(k(""),G(""),R([]),A(!1),O.current=!1,await we(h))}catch{}},[me,we,n,te]),at=s.useCallback((h,v)=>{if(!p)return;if(O.current){const H=h.trim();if(!H)return;const Q=[...T.current,H];T.current=Q,U(Q),Hn(p.id,Q);return}S.current=!1,j.current&&(j.current.close(),j.current=null),q.current=null;const x=`temp-${Date.now()}`,$={id:x,sessionId:p.id,role:"user",content:h,createdAt:new Date().toISOString()};M(H=>[...H,$]),k(""),G(""),R([]),A(!0),O.current=!0;const{handlers:se}=Ys({sessionId:p.id,tempUserMessageId:x,setStreamingText:k,setStreamingThinking:G,setStreamingToolCalls:R,cancelStreamingFlushesRef:m,addToast:r,onFallbackSession:(H,Q)=>{const Y=Js(H.fallbackModel);b(K=>K.map(oe=>oe.id===Q?{...oe,...Y}:oe)),o(K=>K&&K.id===Q?{...K,...Y}:K)},onDone:({messageId:H,message:Q,accumulated:Y})=>{const K=Q?{...tn(Q),...Y.text.length>0?{content:Y.text}:{}}:{id:H||`msg-${Date.now()}`,sessionId:p.id,role:"assistant",content:Y.text,thinkingOutput:Y.thinking,toolCalls:Y.toolCalls.length>0?Y.toolCalls:void 0,fallbackInfo:Y.fallbackInfo,createdAt:new Date().toISOString()};z.current.add(K.id),M(oe=>[...oe,K]),k(""),G(""),R([]),A(!1),O.current=!1,j.current=null,q.current=null,setTimeout(()=>{z.current.delete(K.id)},1e3),te(),fe()},onError:(H,Q,Y)=>{const K=Zs(H),oe=typeof H=="string"?H:K.summary,J=Ya(oe),ee=Y?.requestAccepted===!0;M(de=>{const ge=ee?de:de.filter(De=>De.id!==Q);return J?ge:[...ge,{id:`error-${Date.now()}`,sessionId:p.id,role:"assistant",content:K.summary,failureInfo:K,createdAt:new Date().toISOString()}]}),k(""),G(""),R([]),A(!1),O.current=!1,j.current=null,q.current=null,console.error("[useChat] Stream error:",H),J?(console.info("[useChat] Suppressed tab-suspension stream error:",H),p?.id&&(k(""),G(""),R([]),A(!0),O.current=!0,st(p.id))):(r?.(K.summary,"error"),ee&&Os(p.id,{limit:50,order:"desc"},n).then(de=>{if(l.current?.id!==p.id)return;const ge=de.messages.slice().reverse().map(tn);M(De=>ge.reduce(ea,De))}).catch(()=>{}),te()),S.current||fe()}});j.current=Qa(p.id,h,se,v,n)},[p,n,te,r,me,st,fe]);wt.current=at;const hn=X?d.filter(h=>h.title?.toLowerCase().includes(X.toLowerCase())||h.agentId.toLowerCase().includes(X.toLowerCase())):d;return s.useEffect(()=>{if(!p?.id||p.isGenerating!==!0||j.current)return;const h=typeof p.inFlightGeneration?.replayFromEventId=="number"?p.inFlightGeneration.replayFromEventId:null,v=q.current;v?.sessionId===p.id&&v.replayFromEventId===h||me(p.id,p.inFlightGeneration,{silent:!0})},[p?.id,p?.isGenerating,p?.inFlightGeneration,me]),s.useEffect(()=>{if(!l.current?.isGenerating||(j.current||me(l.current.id,l.current.inFlightGeneration),!O.current||j.current||!l.current))return;const h=setInterval(async()=>{if(!O.current||j.current||!l.current){clearInterval(h);return}try{(await $s(n)).sessions.find($=>$.id===l.current?.id)?.isGenerating||(clearInterval(h),await we(l.current.id),k(""),G(""),R([]),A(!1),O.current=!1,fe())}catch{}},3e3);return()=>clearInterval(h)},[me,we,n,p,fe]),s.useEffect(()=>xt.onBecameVisible(()=>{const v=l.current;if(!v||j.current)return;const x=he.current;Et(v.id,n).then($=>{if(!(he.current!==x||j.current)){if($.session.isGenerating){k(""),G(""),R([]),A(!0),O.current=!0,me(v.id,$.session.inFlightGeneration,{silent:!0});return}O.current&&(k(""),G(""),R([]),A(!1),O.current=!1,fe(),we(v.id))}}).catch(()=>{})}),[me,we,n,xt,fe]),s.useEffect(()=>{const h=he.current,v=n?`?projectId=${encodeURIComponent(n)}`:"",x=()=>he.current!==h,$=oe=>{if(x())return;const J=JSON.parse(oe.data);if(Qn(J)){Fr(J)||te();return}b(ee=>ee.some(de=>de.id===J.id)?ee:[J,...ee])},se=oe=>{if(x())return;const J=JSON.parse(oe.data);b(ee=>[...ee.map(ge=>ge.id===J.id?J:ge)]),l.current?.id===J.id&&(o(J),J.isGenerating&&!j.current&&me(J.id,J.inFlightGeneration))},H=oe=>{if(x())return;const{id:J}=JSON.parse(oe.data);b(de=>de.filter(ge=>ge.id!==J));const ee=g(n,J);ee&&on(ee),l.current?.id===J&&(o(null),M([]))},Q=oe=>{if(x())return;const J=JSON.parse(oe.data),ee=tn(J);if(I.current.some(de=>de.id===ee.sessionId)||te(),!z.current.has(ee.id)){if(l.current?.id===ee.sessionId&&O.current&&!j.current&&ee.role==="assistant"){M(de=>de.some(ge=>ge.id===ee.id)?de:[...de,ee]),k(""),G(""),R([]),A(!1),O.current=!1,fe();return}l.current?.id===ee.sessionId&&!O.current&&M(de=>de.some(ge=>ge.id===ee.id)?de:ee.role==="user"?ea(de,ee):[...de,ee])}},Y=oe=>{if(x())return;const{id:J}=JSON.parse(oe.data);M(ee=>ee.filter(de=>de.id!==J))};return pa(`/api/events${v}`,{events:{"chat:session:created":$,"chat:session:updated":se,"chat:session:deleted":H,"chat:message:added":Q,"chat:message:deleted":Y}})},[me,g,n,fe,te]),s.useEffect(()=>()=>{j.current&&(j.current.close(),j.current=null),q.current=null},[]),{sessions:d,activeSession:p,sessionsLoading:f,messages:C,messagesLoading:N,isStreaming:E,streamingText:W,streamingThinking:ae,streamingToolCalls:ue,pendingMessages:le,selectSession:Te,createSession:yt,archiveSession:mn,renameSession:nt,deleteSession:Ft,sendMessage:at,stopStreaming:It,clearPendingMessage:Dt,loadMoreMessages:je,hasMoreMessages:V,searchQuery:X,setSearchQuery:_,filteredSessions:hn,refreshSessions:te,agentsMap:P}}function nn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function $r(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function Kn(n,r){const i=$r(),g=r?.warm===!0,c=nn(),d=new Map;let b=!1,p=!1;return{mark(f){b||p||!i||d.has(f)||d.set(f,nn())},complete:f=>{if(!i||b||p){b=!0;return}b=!0,d.set("complete",nn());const B=Array.from(d.entries()).sort((F,E)=>F[1]-E[1]);let C=c;const M={};for(const[F,E]of B)M[F]=Math.max(0,E-C),C=E;const N=Math.max(0,nn()-c);try{console.debug("[room-open]",{roomId:n,warm:g,totalMs:N,phases:M,...f??{}})}catch{}},cancel(){p=!0,b=!0}}}const Xe="fusion:chat-active-room";class ya extends Error{roomId;constructor(r,i){super(r),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=i}}function Yn(n){return[...n].sort((r,i)=>new Date(i.updatedAt).getTime()-new Date(r.updatedAt).getTime())}function ft(n,r){const i=n.findIndex(c=>c.id===r.id);if(i===-1)return Yn([r,...n]);const g=[...n];return g[i]=r,Yn(g)}function Ue(n){try{return JSON.parse(n.data)}catch{return null}}function Or(n,r,i){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:n,role:"user",content:r,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...i?.length?{attachments:i}:{},createdAt:new Date().toISOString()}}function ta(n,r,i){if(n.some(c=>c.id===r.id))return n;const g=i?n.findIndex(c=>c.id===i):-1;if(g>=0){const c=[...n];return c[g]=r,c}if(r.role==="user"){const c=n.findIndex(d=>d.role==="user"&&d.id.startsWith("temp-")&&d.content.trim()===r.content.trim());if(c>=0){const d=[...n];return d[c]=r,d}}return[...n,r]}function Br(n,r){const{t:i}=tt("app"),g=`${et.CHAT_ROOMS}:${n??"global"}`,c=`${et.ACTIVE_CHAT_ROOM_ID}:${n??"global"}`,d=s.useCallback(S=>`${et.CHAT_ROOM_MESSAGES_PREFIX}${n??"global"}:${S}`,[n]),b=s.useCallback(S=>`${et.CHAT_ROOM_MEMBERS_PREFIX}${n??"global"}:${S}`,[n]),[p,o]=s.useState(()=>{const S=qe(g,{maxAgeMs:Xn});return Array.isArray(S)?S:[]}),[f,B]=s.useState(()=>p.length===0),[C,M]=s.useState(null),[N,F]=s.useState(()=>{const S=qe(c,{maxAgeMs:zs});return S?p.find(T=>T.id===S)??null:null}),[E,A]=s.useState([]),[W,k]=s.useState([]),[ae,G]=s.useState(!1),ue=s.useRef(p),R=s.useRef(N),le=s.useRef(0),U=s.useRef(n);ue.current=p,R.current=N,U.current!==n&&(U.current=n,le.current+=1);const X=s.useCallback(async S=>{if(!S){A([]),k([]),G(!1);return}const T=Kn(S.id,{warm:!1});T.mark("select");const D=qe(d(S.id),{maxAgeMs:Ja}),m=qe(b(S.id),{maxAgeMs:Xn}),I=Array.isArray(D)&&D.length>0,l=Array.isArray(m)&&m.length>0;I||l?(T.mark("cache-hit"),I&&(k(D),T.mark("hydrate")),l&&A(m),G(!1)):(k([]),G(!0));try{const[re,O]=await Promise.all([Za(S.id,n),$n(S.id,{limit:100,order:"desc"},n)]);T.mark("members-fetch"),T.mark("messages-fetch"),ie(b(S.id),re.members,{maxBytes:5e5}),ie(d(S.id),O.messages,{maxBytes:5e5}),R.current?.id===S.id&&(A(re.members),k(O.messages),T.mark("hydrate"))}catch{!I&&!l&&(A([]),k([]))}finally{G(!1),T.complete({warm:I,membersCached:l})}},[b,d,n]),_=s.useCallback(async()=>{ue.current.length===0&&B(!0);try{const S=await er({},n),T=Yn(S.rooms);o(T),ie(g,T,{maxBytes:5e5}),M(null);const D=qe(c,{maxAgeMs:zs})??vt(Xe,n);if(D){const m=T.find(I=>I.id===D)??null;m?(F(m),X(m)):(pt(Xe,n),ie(c,"",{maxBytes:5e5}))}}catch(S){const T=S instanceof Error?S.message:i("chatRooms.error.failedToLoad","Failed to load chat rooms");M(T),r?.(T,"error")}finally{B(!1)}},[c,r,X,n,g]),V=s.useCallback(S=>{if(!S){R.current=null,F(null),pt(Xe,n),ie(c,"",{maxBytes:5e5}),X(null);return}const T=ue.current.find(D=>D.id===S)??null;R.current=T,F(T),T&&(dn(Xe,T.id,n),ie(c,T.id,{maxBytes:5e5}),X(T))},[c,X,n]),y=s.useCallback(async S=>{const D=(await tr({name:S.name,memberAgentIds:S.memberAgentIds},n)).room;return o(m=>ft(m,D)),R.current=D,F(D),dn(Xe,D.id,n),ie(c,D.id,{maxBytes:5e5}),await X(D),D},[c,X,n]),P=s.useCallback(async S=>{await nr(S,n),o(T=>T.filter(D=>D.id!==S)),ie(d(S),[],{maxBytes:5e5}),ie(b(S),[],{maxBytes:5e5}),R.current?.id===S&&(R.current=null,F(null),A([]),k([]),pt(Xe,n),ie(c,"",{maxBytes:5e5}))},[c,b,d,n]),j=s.useCallback(async(S,T)=>{const D=R.current,m=D?.id;if(!m)throw new Error(i("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const I=Kn(m,{warm:!1}),l=T?.files?.map(z=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,filename:z.name,originalName:z.name,mimeType:z.type||"application/octet-stream",size:z.size,createdAt:new Date().toISOString()})),re=Or(m,S,l?.length?l:T?.attachments);R.current?.id===m&&k(z=>{const he=[...z,re];return ie(d(m),he,{maxBytes:5e5}),he});let O=!1;try{const z=[];if(T?.files?.length)for(const ve of T.files)try{const ye=await sr(m,ve,n);z.push(ye.attachment)}catch{throw new Error(i("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:ve.name}))}const he=[...T?.attachments??[],...z],pe=await ar(m,{content:S,...he.length?{attachments:he}:{}},n);O=!0,pe.message?.createdAt&&D&&o(ve=>ft(ve,{...D,updatedAt:pe.message.createdAt})),R.current?.id===m&&k(ve=>{const ye=ta(ve,pe.message,re.id);return ie(d(m),ye,{maxBytes:5e5}),ye});const te=await $n(m,{limit:100,order:"desc"},n);if(ie(d(m),te.messages,{maxBytes:5e5}),R.current?.id!==m)return;k(te.messages),I.mark("hydrate")}catch(z){let he=null;try{const te=await $n(m,{limit:100,order:"desc"},n);he=te.messages,ie(d(m),te.messages,{maxBytes:5e5}),R.current?.id===m&&(k(te.messages),I.mark("hydrate"))}catch{!O&&R.current?.id===m&&k(te=>{const ve=te.filter(ye=>ye.id!==re.id);return ie(d(m),ve,{maxBytes:5e5}),ve})}const pe=he?.some(te=>te.role==="user"&&te.content.trim()===re.content.trim());if(O||pe){const te=z instanceof Error&&z.message.trim()?z.message:i("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new ya(te,m)}throw z}finally{I.complete({source:"send-room-message"})}},[d,n]),q=s.useCallback(async S=>{!S||!ue.current.some(T=>T.id===S)||(await rr(S,n),ie(d(S),[],{maxBytes:5e5}),R.current?.id===S&&k([]))},[d,n]);return s.useEffect(()=>{_()},[_]),s.useEffect(()=>{const S=le.current,T=n?`/api/events?projectId=${encodeURIComponent(n)}`:"/api/events";return pa(T,{onReconnect:()=>{jt({view:"useChatRooms",trigger:"sse-reconnect",projectId:n,replayAttempted:!1});const D=R.current?.id;if(D){const m=Kn(D,{warm:!0});m.mark("sse-reconnect-refresh"),_().finally(()=>m.complete({source:"sse-reconnect"}));return}_()},events:{"chat:room:created":D=>{if(le.current!==S)return;const m=Ue(D);m&&o(I=>ft(I,m))},"chat:room:updated":D=>{if(le.current!==S)return;const m=Ue(D);m&&(o(I=>ft(I,m)),R.current?.id===m.id&&F(m))},"chat:room:deleted":D=>{if(le.current!==S)return;const m=Ue(D);m?.id&&(o(I=>I.filter(l=>l.id!==m.id)),ie(d(m.id),[],{maxBytes:5e5}),ie(b(m.id),[],{maxBytes:5e5}),R.current?.id===m.id&&(R.current=null,F(null),A([]),k([]),pt(Xe,n),ie(c,"",{maxBytes:5e5})))},"chat:room:member:added":D=>{if(le.current!==S)return;const m=Ue(D);!m||R.current?.id!==m.roomId||A(I=>{if(I.some(re=>re.agentId===m.agentId))return I;const l=[...I,m];return ie(b(m.roomId),l,{maxBytes:5e5}),l})},"chat:room:member:removed":D=>{if(le.current!==S)return;const m=Ue(D);!m||R.current?.id!==m.roomId||A(I=>{const l=I.filter(re=>re.agentId!==m.agentId);return ie(b(m.roomId),l,{maxBytes:5e5}),l})},"chat:room:message:added":D=>{if(le.current!==S)return;const m=Ue(D);m&&(o(I=>{const l=I.find(re=>re.id===m.roomId);return l?ft(I,{...l,updatedAt:m.createdAt}):I}),R.current?.id===m.roomId&&k(I=>{const l=ta(I,m);return l===I?I:(ie(d(m.roomId),l,{maxBytes:5e5}),l)}))},"chat:room:message:updated":D=>{if(le.current!==S)return;const m=Ue(D);!m||R.current?.id!==m.roomId||k(I=>{const l=I.map(re=>re.id===m.id?m:re);return ie(d(m.roomId),l,{maxBytes:5e5}),l})},"chat:room:message:deleted":D=>{if(le.current!==S)return;const m=Ue(D);m?.id&&k(I=>{const l=I.filter(O=>O.id!==m.id),re=R.current?.id;return re&&ie(d(re),l,{maxBytes:5e5}),l})},"chat:room:messages:cleared":D=>{if(le.current!==S)return;const m=Ue(D);m?.roomId&&(ie(d(m.roomId),[],{maxBytes:5e5}),R.current?.id===m.roomId&&k([]),o(I=>{const l=I.find(re=>re.id===m.roomId);return l?ft(I,{...l,updatedAt:new Date().toISOString()}):I}))}}})},[c,b,d,n,_]),s.useEffect(()=>{N&&(p.some(S=>S.id===N.id)||(R.current=null,F(null),A([]),k([]),pt(Xe,n),ie(c,"",{maxBytes:5e5})))},[N,c,n,p]),{rooms:p,roomsLoading:f,roomsError:C,activeRoom:N,activeRoomMembers:E,messages:W,messagesLoading:ae,selectRoom:V,createRoom:y,deleteRoom:P,sendRoomMessage:j,clearRoom:q,refreshRooms:_}}const Tt={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},na=200;function Jn(n){if(!n)return null;const r=new Date(n).getTime();return Number.isFinite(r)?r:null}function wa(n){const r=Object.entries(n);if(r.length<=na)return n;const i=r.map(([g,c])=>({id:g,timestamp:c,value:Jn(c)??0})).sort((g,c)=>c.value-g.value).slice(0,na);return Object.fromEntries(i.map(({id:g,timestamp:c})=>[g,c]))}function sn(n){if(!n)return{};try{const r=JSON.parse(n);if(!r||typeof r!="object")return{};const i={};for(const[g,c]of Object.entries(r))typeof g=="string"&&typeof c=="string"&&(i[g]=c);return wa(i)}catch{return{}}}function zr(n){const[r,i]=s.useState(()=>{try{return sn(vt(Tt.direct,n))}catch{return{}}}),[g,c]=s.useState(()=>{try{return sn(vt(Tt.room,n))}catch{return{}}});s.useEffect(()=>{try{i(sn(vt(Tt.direct,n)))}catch{i({})}try{c(sn(vt(Tt.room,n)))}catch{c({})}},[n]);const d=s.useMemo(()=>({direct:r,room:g}),[r,g]),b=s.useCallback((C,M)=>{const N=wa(M);try{dn(Tt[C],JSON.stringify(N),n)}catch{}return N},[n]),p=s.useCallback((C,M)=>{if(C==="direct"){i(N=>b(C,M(N)));return}c(N=>b(C,M(N)))},[b]),o=s.useCallback((C,M,N)=>{const F=Jn(N);if(F===null)return!1;const E=d[C][M],A=Jn(E);return A===null?!0:F>A},[d]),f=s.useCallback((C,M,N)=>{if(!M)return;const F=N??new Date().toISOString();p(C,E=>({...E,[M]:F}))},[p]),B=s.useCallback((C,M)=>{M.length!==0&&p(C,N=>{const F={...N};for(const E of M)E.id&&(F[E.id]=E.lastActivityAt??new Date().toISOString());return F})},[p]);return{isUnread:o,markRead:f,markAllRead:B}}function sa(n){return n.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function xa(n,r){const i=r.trim();if(!i)return!0;const g=sa(i);return sa(n).includes(g)||n.toLowerCase().includes(i.toLowerCase())}function aa({agents:n,filter:r,highlightedIndex:i,visible:g,onSelect:c,position:d="below",roomMemberIds:b,roomName:p}){const{t:o}=tt("app"),f=s.useMemo(()=>n.filter(E=>xa(E.name,r)),[n,r]),B=!!b,C=B&&r.trim().length>0,M=s.useMemo(()=>B?f.filter(E=>b?.has(E.id)):f,[f,b,B]),N=s.useMemo(()=>B?f.filter(E=>!b?.has(E.id)):[],[f,b,B]),F=C?[...M,...N]:M;return g?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${d}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":o("agentMention.suggestionsLabel","Agent mention suggestions"),children:F.length===0?t.jsx("div",{className:"agent-mention-empty",children:o("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[B&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:p?o("agentMention.membersOf","Members of #{{roomName}}",{roomName:p}):o("agentMention.roomMembers","Room members")}),M.map((E,A)=>t.jsxs("button",{type:"button",className:`agent-mention-item${A===i?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${E.id}`,onMouseDown:W=>W.preventDefault(),onClick:()=>c(E),role:"option","aria-selected":A===i,children:[t.jsx(un,{agent:E,size:20}),B&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":o("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:E.name}),t.jsx("span",{className:"agent-mention-role",children:E.role})]},E.id)),B&&!C&&N.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:o("agentMention.typeToSearch","Type to search other agents")}),B&&C&&N.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:o("agentMention.otherAgents","Other agents")}),N.map((E,A)=>{const W=M.length+A;return t.jsxs("button",{type:"button",className:`agent-mention-item${W===i?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${E.id}`,onMouseDown:k=>k.preventDefault(),onClick:()=>c(E),role:"option","aria-selected":W===i,children:[t.jsx(un,{agent:E,size:20}),t.jsx("span",{className:"agent-mention-name",children:E.name}),t.jsx("span",{className:"agent-mention-role",children:E.role})]},E.id)})]})]})}):null}function Hr(n,r){return n+r}function Ur({visible:n,position:r,tasks:i,files:g,selectedIndex:c,onSelectTask:d,onSelectFile:b,loading:p}){const{t:o}=tt("app");if(!n)return null;const f=i.length>0,B=g.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:r.top,left:r.left},"data-testid":"file-mention-popup",onMouseDown:C=>{C.preventDefault()},children:[p&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!p&&!f&&!B&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:o("fileMention.empty","No tasks or files found")}),!p&&(f||B)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[f&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:o("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":o("fileMention.taskMatches","Task matches"),children:i.map((C,M)=>{const N=M;return t.jsxs("li",{className:`file-mention-popup-item${N===c?" file-mention-popup-item--selected":""}`,onClick:()=>d(C),role:"option","aria-selected":N===c,"data-testid":`task-mention-item-${N}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(va,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsxs("div",{className:"file-mention-popup-task-row",children:[t.jsx("span",{className:"file-mention-popup-task-id",children:C.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${C.column}`,children:C.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:C.title})]})]},C.id)})})]}),B&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:o("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":o("fileMention.fileMatches","File matches"),children:g.map((C,M)=>{const N=Hr(i.length,M),F=or(C.path);return t.jsxs("li",{className:`file-mention-popup-item${N===c?" file-mention-popup-item--selected":""}`,onClick:()=>b(C),role:"option","aria-selected":N===c,"data-testid":`file-mention-item-${N}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(ir,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:C.name}),F&&t.jsx("span",{className:"file-mention-popup-item-path",children:F})]})]},C.path)})})]})]})]})}function Kr(n,r=[],i){const g=n.trim().replace(/^#/,""),c=(b,p)=>i?i(b,p):p;if(!g)return{ok:!1,error:c("createRoom.nameRequired","Room name is required.")};if(/[A-Z]/.test(g))return{ok:!1,error:c("createRoom.lowercase","Use lowercase letters only.")};const d=g.toLowerCase();return d.length>80?{ok:!1,error:c("createRoom.maxLength","Room names can be at most 80 characters.")}:/^[a-z0-9_-]+$/.test(d)?/^[-_]|[-_]$/.test(d)?{ok:!1,error:c("createRoom.noEdgeChars","Room names cannot start or end with a hyphen or underscore.")}:r.some(b=>b.toLowerCase()===d)?{ok:!1,error:c("createRoom.duplicate","A room with this name already exists.")}:{ok:!0,name:d}:{ok:!1,error:c("createRoom.validChars","Use lowercase letters, numbers, hyphens, or underscores only.")}}function Gr({isOpen:n,onClose:r,onCreate:i,projectId:g,existingRoomNames:c=[]}){const{t:d}=tt("app"),[b,p]=s.useState(""),[o,f]=s.useState([]),[B,C]=s.useState(""),[M,N]=s.useState([]),[F,E]=s.useState(!1),[A,W]=s.useState(null),[k,ae]=s.useState(!1),G=s.useRef(null),ue=s.useRef(null);s.useEffect(()=>{n&&(ue.current=document.activeElement instanceof HTMLElement?document.activeElement:null,E(!0),W(null),cr(void 0,g).then(y=>f(y)).catch(()=>{f([]),W(d("createRoom.failedLoadAgents","Failed to load agents."))}).finally(()=>E(!1)))},[n,g]),s.useEffect(()=>{if(!n){p(""),C(""),N([]),W(null),ae(!1);return}const y=window.requestAnimationFrame(()=>G.current?.focus());return()=>window.cancelAnimationFrame(y)},[n]),s.useEffect(()=>{if(!n)return;const y=P=>{P.key==="Escape"&&r()};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[n,r]),s.useEffect(()=>{n||ue.current?.focus()},[n]);const R=s.useMemo(()=>Kr(b,c,d),[b,c,d]),le=s.useMemo(()=>{const y=B.trim().toLowerCase();return y?o.filter(P=>P.name.toLowerCase().includes(y)):o},[o,B]),U=s.useMemo(()=>o.filter(y=>M.includes(y.id)),[o,M]),X=R.ok&&M.length>0&&!k&&!F;if(!n)return null;const _=y=>{k||N(P=>P.includes(y)?P.filter(j=>j!==y):[...P,y])},V=async()=>{if(!R.ok){W(R.error);return}if(M.length===0){W(d("createRoom.selectMember","Select at least one member."));return}W(null),ae(!0);try{await i({name:R.name,displayName:`#${R.name}`,memberAgentIds:M}),r()}catch(y){W(y instanceof Error?y.message:d("createRoom.failedCreate","Failed to create room."))}finally{ae(!1)}};return Ua.createPortal(t.jsx("div",{className:"modal-overlay open",onClick:y=>y.target===y.currentTarget&&r(),children:t.jsxs("div",{className:"modal modal-lg create-room-modal",role:"dialog","aria-modal":"true","aria-label":d("createRoom.title","Create room"),onClick:y=>y.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:d("createRoom.title","Create room")}),t.jsx("button",{type:"button",className:"modal-close","aria-label":d("actions.close","Close"),onClick:r,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:d("createRoom.nameLabel","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:G,id:"create-room-name",className:"input",value:b,disabled:k,onChange:y=>{const P=y.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();p(P)}})]}),!R.ok&&t.jsx("div",{className:"form-error",children:R.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:d("createRoom.members","Members")}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:d("createRoom.searchAgents","Search agents"),value:B,disabled:k,onChange:y=>C(y.target.value)})]}),U.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:U.map(y=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>_(y.id),disabled:k,children:[y.name," ×"]},y.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:F?t.jsx("div",{className:"create-room-modal-empty",children:t.jsx(lr,{label:d("createRoom.loadingAgents","Loading agents...")})}):le.length===0?t.jsx("div",{className:"create-room-modal-empty",children:o.length===0?d("createRoom.noAgents","No agents in this project yet."):d("createRoom.noMatch","No agents match your search.")}):le.map(y=>{const P=M.includes(y.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${P?" create-room-modal-member-row--selected":""}`,onClick:()=>_(y.id),disabled:k,children:[t.jsx(un,{agent:y,size:20}),t.jsx("span",{children:y.name}),t.jsx("span",{className:"create-room-modal-member-role",children:y.role})]},y.id)})}),A&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:A})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:k,children:d("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void V(),disabled:!X,children:k?d("createRoom.creating","Creating..."):d("createRoom.create","Create room")})]})]})}),document.body)}function Vr({cliSessionId:n,tier:r,projectId:i,renderTranscript:g,renderComposer:c,queuedCount:d=0,terminalProps:b}){const{t:p}=tt("app"),o=r==="generic",[f,B]=s.useState(o?"terminal":"transcript");if(o)return t.jsx("div",{className:"cli-chat-surface cli-chat-surface--generic","data-tier":"generic",children:t.jsx(Qs,{sessionId:n,projectId:i,...b})});const C=f==="terminal";return t.jsxs("div",{className:"cli-chat-surface","data-tier":r,"data-view":f,children:[t.jsxs("div",{className:"cli-chat-surface__toolbar",role:"tablist","aria-label":p("cliChat.viewToggleLabel","Chat view"),children:[t.jsxs("button",{type:"button",role:"tab","aria-selected":!C,className:`cli-chat-surface__tab${C?"":" is-active"}`,onClick:()=>B("transcript"),children:[t.jsx(cn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:p("cliChat.transcriptTab","Transcript")})]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":C,className:`cli-chat-surface__tab${C?" is-active":""}`,onClick:()=>B("terminal"),children:[t.jsx(dr,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:p("cliChat.terminalTab","Terminal")})]})]}),t.jsx("div",{className:"cli-chat-surface__body",children:C?t.jsx(Qs,{sessionId:n,projectId:i,...b}):g()}),!C&&t.jsxs("div",{className:"cli-chat-surface__composer",children:[d>0&&t.jsx("div",{className:"cli-chat-surface__queued",role:"status","aria-live":"polite",children:p("cliChat.queued","{{count}} message queued — will send when the agent is ready",{count:d})}),c()]})]})}const Wr=200,Xr=8,qr=8;function ra(){return new DOMException("The operation was aborted.","AbortError")}function oa(n,r){return r.aborted?Promise.reject(ra()):new Promise((i,g)=>{const c=()=>g(ra());r.addEventListener("abort",c,{once:!0}),n.then(d=>{r.removeEventListener("abort",c),i(d)},d=>{r.removeEventListener("abort",c),g(d)})})}function ia(n,r,i){const g=n.slice(0,r),c=n.slice(r+1),d=c.match(/[\s]|$/),b=d?d.index??c.length:c.length,p=c.slice(b);return`${g}${i}${p}`}function Qr(n={}){const{projectId:r,workspace:i="project"}=n,[g,c]=s.useState(!1),[d,b]=s.useState(""),[p,o]=s.useState(-1),[f,B]=s.useState([]),[C,M]=s.useState([]),[N,F]=s.useState(!1),[E,A]=s.useState(0),W=s.useRef(null),k=s.useRef(null),ae=[...f.map(_=>({kind:"task",task:_})),...C.map(_=>({kind:"file",file:_}))];s.useEffect(()=>()=>{W.current&&clearTimeout(W.current),k.current?.abort()},[]);const G=s.useCallback((_,V)=>{if(V<0||V>_.length){c(!1);return}const y=P=>/[a-zA-Z0-9/_.-]/.test(P);for(let P=V-1;P>=0;P--){if(_[P]==="#"){if(P===0){const q=_.slice(P+1,V);o(P),b(q),A(0),c(!0);return}const j=_[P-1];if(/[\s,.;:!?'"()[\]{}]/.test(j)){const q=_.slice(P+1,V);o(P),b(q),A(0),c(!0);return}c(!1);return}if(!y(_[P])){c(!1);return}}c(!1)},[]),ue=s.useCallback(()=>{k.current?.abort(),c(!1),b(""),o(-1),B([]),M([]),A(0),F(!1)},[]),R=s.useCallback(async _=>{if(!_.trim()){B([]),M([]),F(!1);return}k.current?.abort();const V=new AbortController;k.current=V;try{F(!0);const[y,P]=await Promise.allSettled([oa(ur(20,0,r,_),V.signal),oa(mr(_,i,r),V.signal)]);if(V.signal.aborted)return;const j=y.status==="fulfilled"?y.value.slice(0,Xr).map(S=>({id:S.id,title:S.title??"",column:S.column})):[],q=P.status==="fulfilled"?P.value.files.slice(0,qr):[];B(j),M(q),A(0)}catch(y){y.name!=="AbortError"&&(B([]),M([]))}finally{V.signal.aborted||F(!1)}},[i,r]);s.useEffect(()=>{if(g)return W.current&&clearTimeout(W.current),W.current=setTimeout(()=>{R(d)},Wr),()=>{W.current&&clearTimeout(W.current)}},[d,g,R]);const le=s.useCallback((_,V)=>!g||p<0?V:ia(V,p,`#${_.id}`),[g,p]),U=s.useCallback((_,V)=>!g||p<0?V:ia(V,p,`#${_.path}`),[g,p]),X=s.useCallback((_,V)=>{if(!g||ae.length===0)return!1;switch(_.key){case"ArrowDown":return _.preventDefault(),A(y=>Math.min(y+1,ae.length-1)),!0;case"ArrowUp":return _.preventDefault(),A(y=>Math.max(y-1,0)),!0;case"Enter":case"Tab":return ae[E]?(_.preventDefault(),!0):!1;case"Escape":return _.preventDefault(),ue(),!0;default:return!1}},[g,ae,E,ue]);return{mentionActive:g,tasks:f,files:C,combinedItems:ae,loading:N,mentionQuery:d,selectedIndex:E,setSelectedIndex:A,detectMention:G,selectTask:le,selectFile:U,dismissMention:ue,handleKeyDown:X}}const Gn=new Map,ln=new Map;function ns(n){return n??"global"}function Zn(n){return`${et.DISCOVERED_SKILLS_PREFIX}${ns(n)}`}function gt(n){return qe(Zn(n),{maxAgeMs:Xn})}function Yr(n,r){for(const i of ln.get(n)??[])i(r)}async function Jr(n){const r=ns(n),i=Gn.get(r);if(i)return i;const g=hr(n).finally(()=>{Gn.delete(r)});return Gn.set(r,g),g}function Zr(n){const[r,i]=s.useState(()=>gt(n)??[]),[g,c]=s.useState(()=>gt(n)===null),d=s.useRef(gt(n)!==null),b=ns(n);s.useEffect(()=>{const f=gt(n)??[];i(f),c(gt(n)===null),d.current=gt(n)!==null},[n]),s.useEffect(()=>{const f=ln.get(b)??new Set;return f.add(i),ln.set(b,f),()=>{f.delete(i),f.size===0&&ln.delete(b)}},[b]);const p=s.useCallback(async()=>{try{const f=await Jr(n);d.current=!0,ie(Zn(n),f,{maxBytes:5e5}),Yr(b,f)}catch{d.current||on(Zn(n))}finally{c(!1)}},[n,b]);s.useEffect(()=>{p()},[p]);const o=s.useCallback(async()=>{c(!0),await p()},[p]);return{skills:r,loading:g,refresh:o}}function eo(n,r){const i=n.reduce((g,c)=>g+(c.content?.length??0),0)+(r?.length??0);return Math.ceil(i/4)}function ca(n){if(!Number.isFinite(n)||n<=0)return"0";if(n<1e3)return String(Math.round(n));const r=n/1e3;return r<10?`~${Number(r.toFixed(1))}k`:`${Math.round(r)}k`}const ss=640,to=200,la="__SKIP__";let Vn=!1;function no(n,r=ss){return n>r?"auto":"hidden"}function so(n,r=ss){return Math.max(40,Math.min(n,r))}function ao(n,r){const i=new Date(n),c=new Date().getTime()-i.getTime(),d=Math.floor(c/1e3),b=Math.floor(d/60),p=Math.floor(b/60),o=Math.floor(p/24);return d<60?r("chat.relativeTimeJustNow","just now"):b<60?r("chat.relativeTimeMinutes","{{count}}m ago",{count:b}):p<24?r("chat.relativeTimeHours","{{count}}h ago",{count:p}):o<7?r("chat.relativeTimeDays","{{count}}d ago",{count:o}):i.toLocaleDateString()}const bt="__fn_agent__",ro=280,an=180,rn=500,da="fusion:chat-sidebar-width",Wn="fusion:chat-scope",oo="fusion:chat-draft:";function ua(n,r){return n.slice(r+1).find(i=>i.role==="user")?.content}function ma(n,r){return r?`${oo}${n}:${r}`:null}function ha(n){if(!n)return"";try{return localStorage.getItem(n)??""}catch{return""}}const io=["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/markdown","text/csv","application/xml","text/x-log"];function fa(n){const r=/(^|[\s])\/([^\s]*)$/.exec(n);if(!r)return null;const i=r[1]??"",g=r[2]??"",c=r.index+i.length;return{filter:g,start:c,end:n.length}}function co(n,r){const i=n.slice(0,r),g=/(^|[\s\n])@([\w-]*)$/.exec(i);if(!g)return null;const c=g[2]??"",d=i.length-c.length-1;return{filter:c,start:d,end:r}}function lo(n){const r=n?.runtimeConfig;if(!r||typeof r!="object")return null;const i=Reflect.get(r,"modelProvider"),g=Reflect.get(r,"modelId");return typeof i!="string"||i.trim().length===0||typeof g!="string"||g.trim().length===0?null:{provider:i,modelId:g}}function ga(n,r,i){if(n?.modelProvider&&n?.modelId)return{provider:n.modelProvider,modelId:n.modelId};const g=lo(r??void 0);return g||(i.provider&&i.modelId?{provider:i.provider,modelId:i.modelId}:null)}function uo({projectId:n,defaultModel:r,onClose:i,onCreate:g}){const{t:c}=tt("app"),[d,b]=s.useState("agent"),{agents:p,loading:o}=es(n),[f,B]=s.useState(""),{models:C,favoriteProviders:M,favoriteModels:N,loading:F,refresh:E}=ba(),A=r.provider&&r.modelId?`${r.provider}/${r.modelId}`:"",[W,k]=s.useState(A),[ae,G]=s.useState(M),[ue,R]=s.useState(N);s.useEffect(()=>{G(M)},[M]),s.useEffect(()=>{R(N)},[N]),s.useEffect(()=>{A&&k(y=>y||A)},[A]);const le=s.useCallback(async y=>{const P=ae,q=P.includes(y)?P.filter(S=>S!==y):[y,...P];G(q);try{await qs({favoriteProviders:q,favoriteModels:ue}),await E()}catch{G(P)}},[ae,ue,E]),U=s.useCallback(async y=>{const P=ue,q=P.includes(y)?P.filter(S=>S!==y):[y,...P];R(q);try{await qs({favoriteProviders:ae,favoriteModels:q}),await E()}catch{R(P)}},[ue,ae,E]),X=W||A,_=y=>{if(y.preventDefault(),d==="agent"){if(!f)return;g({agentId:f});return}if(!X)return;const P=X.indexOf("/");if(P<=0)return;const j=X.slice(0,P),q=X.slice(P+1);g({agentId:bt,modelProvider:j,modelId:q})},V=d==="agent"?!f:!X;return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:i,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:y=>y.stopPropagation(),children:[t.jsx("h3",{children:c("chat.newChatTitle","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${d==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{b("agent")},children:c("chat.newChatModeAgent","Agent")}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${d==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{b("model"),B(""),k(y=>y||A)},children:c("chat.newChatModeModel","Model")})]}),t.jsxs("form",{onSubmit:_,children:[d==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:[c("chat.newChatModeAgent","Agent"),o?t.jsx("div",{className:"chat-new-dialog-loading",children:c("chat.loadingAgents","Loading agents...")}):p.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:c("chat.noAgentsAvailable","No agents available")}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:p.map(y=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${f===y.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>B(y.id),"data-testid":`agent-option-${y.id}`,children:[t.jsx(qn,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:y.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:y.role})]},y.id))})]}),d==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:F?t.jsx("div",{className:"chat-new-dialog-loading",children:c("chat.loadingModels","Loading models...")}):t.jsx(Nr,{models:C,value:W,onChange:k,label:c("chat.newChatModeModel","Model"),placeholder:c("chat.selectModel","Select a model"),favoriteProviders:ae,onToggleFavorite:le,favoriteModels:ue,onToggleModelFavorite:U})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:i,children:c("chat.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:V,children:c("chat.create","Create")})]})]})]})})}function wo({projectId:n,addToast:r,floating:i=!1,compactLayout:g=!1,onPopOut:c,onMaximize:d,onMinimize:b,onClose:p}){const{t:o}=tt("app");s.useEffect(()=>(jt({view:"ChatView",trigger:Vn?"route-active":"remount",projectId:n,replayAttempted:!1}),Vn=!1,()=>{Vn=!0,jt({view:"ChatView",trigger:"route-inactive",projectId:n,replayAttempted:!1})}),[n]);const{activeSession:f,sessionsLoading:B,messages:C,messagesLoading:M,isStreaming:N,streamingText:F,streamingThinking:E,streamingToolCalls:A,selectSession:W,createSession:k,archiveSession:ae,renameSession:G,deleteSession:ue,sendMessage:R,stopStreaming:le,pendingMessages:U,clearPendingMessage:X,loadMoreMessages:_,hasMoreMessages:V,searchQuery:y,setSearchQuery:P,filteredSessions:j,agentsMap:q}=_r(n,r),[S,T]=s.useState(!1),D=!0,[m,I]=s.useState(()=>{try{if(localStorage.getItem(Wn)==="rooms"&&D)return"rooms"}catch{}return"direct"}),l=Br(n,r),{isUnread:re,markRead:O}=zr(n),[z,he]=s.useState(()=>{const e=ma(m,m==="rooms"?l.activeRoom?.id:f?.id);return ha(e)}),[pe,te]=s.useState(null),[ve,ye]=s.useState(null),[Ke,Ge]=s.useState(""),[we,Fe]=s.useState(null),[Dt,fe]=s.useState(null),[Qe,me]=s.useState(!0),[Te,yt]=s.useState(ro),[mn,nt]=s.useState(!1),{agentsMap:Ft}=es(n),je=s.useMemo(()=>q.size>0?q:Ft,[Ft,q]),{models:It,defaultProvider:wt,defaultModelId:xt}=ba(),st=s.useMemo(()=>({provider:wt,modelId:xt}),[xt,wt]),{skills:at,loading:hn}=Zr(n),[h,v]=s.useState(!1),[x,$]=s.useState(""),[se,H]=s.useState(0),[Q,Y]=s.useState(""),[K,oe]=s.useState(!1),[J,ee]=s.useState(0),[de,ge]=s.useState(-1),[De,Ca]=s.useState(!1),[Ae,fn]=s.useState([]),[as,rt]=s.useState(!1),[rs,Pt]=s.useState(!1),[ot,os]=s.useState({}),[Lt,Ve]=s.useState(!1),[_t,Ct]=s.useState(!1),{pushNav:is}=fr(),[,$t]=s.useState(!1),[Sa,Ma]=s.useState({top:0,left:0}),ce=Qr({projectId:n}),gn=s.useCallback(e=>{if(!e||!ce.mentionActive)return;const a=e.getBoundingClientRect();Ma({top:a.top-260,left:a.left+8})},[ce.mentionActive]),cs=s.useRef(null),ls=s.useRef(null),ds=s.useRef(null),us=s.useRef(null),Me=s.useRef(!1),Ot=s.useRef(null),ms=s.useRef(null),We=s.useRef(null),Bt=s.useRef(0),pn=s.useRef(null),St=s.useRef(null),Pe=s.useRef(null),ke=s.useRef(null),bn=s.useRef(null),zt=s.useRef(!1),Le=s.useRef(null),_e=s.useRef(null),Se=s.useRef(null),Ht=s.useRef(null),hs=s.useRef([]),it=s.useRef(0),Mt=s.useRef(new Map),vn=s.useRef(!1),Ut=gr(),Ye=Ut==="mobile",yn=Ut==="tablet",fs=s.useRef(null),[ka,gs]=s.useState(!1);s.useLayoutEffect(()=>{if(!i){gs(!1);return}const e=fs.current;if(!e||typeof ResizeObserver>"u")return;const a=()=>{gs(e.getBoundingClientRect().width<=768)};a();const u=new ResizeObserver(a);return u.observe(e),()=>u.disconnect()},[i]);const ne=Ye||ka||g;s.useEffect(()=>{f?.id&&O("direct",f.id,f.lastMessageAt??f.updatedAt)},[f?.id,f?.lastMessageAt,f?.updatedAt,O]),s.useEffect(()=>{l.activeRoom?.id&&O("room",l.activeRoom.id,l.activeRoom.updatedAt)},[l.activeRoom?.id,l.activeRoom?.updatedAt,O]),s.useEffect(()=>{if(!f?.id||C.length===0)return;const e=C[C.length-1];O("direct",f.id,e?.createdAt??f.lastMessageAt??f.updatedAt)},[f?.id,f?.lastMessageAt,f?.updatedAt,O,C]),s.useEffect(()=>{if(!l.activeRoom?.id||l.messages.length===0)return;const e=l.messages[l.messages.length-1];O("room",l.activeRoom.id,e?.createdAt??l.activeRoom.updatedAt)},[O,l.activeRoom?.id,l.activeRoom?.updatedAt,l.messages]),s.useEffect(()=>{try{const e=localStorage.getItem(da);if(!e)return;const a=Number.parseInt(e,10);if(Number.isNaN(a))return;const u=Math.max(an,Math.min(rn,a));yt(u)}catch{}},[]),s.useEffect(()=>{try{const e=localStorage.getItem(Wn);if(e==="direct"){I("direct");return}e==="rooms"&&D&&I("rooms")}catch{}},[D]),s.useEffect(()=>{try{localStorage.setItem(Wn,m)}catch{}},[D,m]);const Re=ma(m,m==="rooms"?l.activeRoom?.id:f?.id),wn=s.useRef(Re);s.useEffect(()=>{Re!==wn.current&&(wn.current=Re,he(ha(Re)))},[Re]),s.useEffect(()=>{if(!(!Re||wn.current!==Re))try{if(z){localStorage.setItem(Re,z);return}localStorage.removeItem(Re)}catch{}},[Re,z]);const be=m==="rooms"&&!!l.activeRoom,{keyboardOverlap:ps,keyboardOpen:Kt}=pr({enabled:(ne||yn)&&(!!f||be),allowNonMobileViewport:yn}),kt=yn&&Kt,Ne=s.useMemo(()=>{const e=x.trim().toLowerCase();return(e?at.filter(u=>u.name.toLowerCase().includes(e)):at).slice(0,10)},[at,x]),ct=s.useMemo(()=>Array.from(je.values()),[je]),$e=s.useMemo(()=>m!=="rooms"||!l.activeRoom?null:{roomId:l.activeRoom.id,roomName:l.activeRoom.name,memberIds:new Set(l.activeRoomMembers.map(e=>e.agentId))},[D,m,l.activeRoom,l.activeRoomMembers]),Je=s.useMemo(()=>{const e=ct.filter(w=>xa(w.name,Q));if(!$e)return e;const a=e.filter(w=>$e.memberIds.has(w.id));if(Q.trim().length===0)return a;const u=e.filter(w=>!$e.memberIds.has(w.id));return[...a,...u]},[ct,Q,$e]),xn=s.useMemo(()=>{const e=new Map;for(const a of ct)e.set(a.name.toLowerCase(),a);return e},[ct]),Ra=s.useMemo(()=>Ne.map(e=>e.id).join("\0"),[Ne]);s.useEffect(()=>{H(0)},[Ra]),s.useEffect(()=>{ee(0)},[Q,K]),s.useEffect(()=>()=>{Pe.current!==null&&window.clearTimeout(Pe.current)},[]),s.useEffect(()=>{const e=ls.current;if(!e||!V||M)return;const a=new IntersectionObserver(u=>{u[0].isIntersecting&&_()},{threshold:.1});return a.observe(e),()=>a.disconnect()},[V,M,_]);const lt=s.useCallback(()=>be?l.activeRoom?.id??null:f?.id??null,[be,l.activeRoom?.id,f?.id]),bs=s.useCallback((e,a)=>typeof CSS<"u"&&typeof CSS.escape=="function"?e.querySelector(`.chat-message[data-message-id="${CSS.escape(a)}"]`):e.querySelector(`.chat-message[data-message-id="${a.replace(/"/g,'\\"')}"]`),[]),Gt=s.useCallback(()=>{const e=ke.current,a=lt();if(!e||!a)return;const u=e.scrollTop,w=e.querySelectorAll(".chat-message[data-message-id]"),L=Array.from(w).find(xe=>xe.offsetTop+xe.offsetHeight>=u)??w[0]??null,Z=L?.getAttribute("data-message-id")??null,Ce=L?L.offsetTop-u:0;St.current={threadId:a,scrollTop:u,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,anchorMessageId:Z,anchorOffset:Ce,wasPinnedBefore:!Me.current,capturedAtMs:typeof performance<"u"?performance.now():Date.now()}},[lt]),vs=s.useCallback(()=>{const e=ke.current;if(!e)return;const u=e.scrollTop+e.clientHeight>=e.scrollHeight-50;Pt(!u),Me.current=!u,Gt()},[Gt]),Oe=s.useCallback((e,a)=>{if(!e.isConnected||!a?.force&&Me.current)return;let u=0,w=0,L=-1;const Z=6,Ce=()=>{if(e.isConnected&&!(!a?.force&&Me.current)){if(e.scrollTop=e.scrollHeight,e.scrollHeight===L?w+=1:(w=0,L=e.scrollHeight),u+=1,u>=Z||w>=2){Pt(!1),Me.current=!1;return}window.requestAnimationFrame(Ce)}};Ce()},[]),Rt=be?l.messages:C;s.useLayoutEffect(()=>{const e=ke.current,a=lt(),u=St.current;if(!e||!a||!u||u.threadId!==a||u.wasPinnedBefore)return;const w=(typeof performance<"u"?performance.now():Date.now())-u.capturedAtMs,L=e.scrollHeight>e.clientHeight,Z=w>3e3,Ce=u.scrollTop<=0&&u.anchorOffset<=0&&L;if(!Me.current||Z||Ce){St.current=null;return}let xe=u.scrollTop;if(u.anchorMessageId){const He=bs(e,u.anchorMessageId);He?xe=He.offsetTop-u.anchorOffset:xe=u.scrollTop+(e.scrollHeight-u.scrollHeight)}else xe=u.scrollTop+(e.scrollHeight-u.scrollHeight);e.scrollTop=Math.max(0,xe),Me.current=!0,Pt(!0),St.current=null},[Rt,lt,bs]);const Cn=s.useCallback(e=>{},[Rt.length,be]),Ie=s.useCallback(e=>{Cn(e);const a=ke.current;a&&(St.current=null,Me.current=!1,Oe(a))},[Oe,Cn]);s.useLayoutEffect(()=>{We.current!==null&&(window.clearTimeout(We.current),We.current=null);const e=be?l.activeRoom?.id??null:f?.id??null;if(!e){Ot.current=null;return}const a={threadId:e,loaded:be?!l.messagesLoading:!M,hasMessages:be?l.messages.length>0:C.length>0},u=Ot.current,w=u?.threadId!==e,L=u?.threadId===e&&!u.loaded&&a.loaded,Z=u?.threadId===e&&!u.hasMessages&&a.hasMessages;if(!(u===null||w||L||Z))return;const xe=ke.current;if(xe)return Cn(w?"thread-change":L?"finished-loading":Z?"first-messages":"mount"),Oe(xe,{force:!0}),be||(We.current=window.setTimeout(()=>{if(We.current=null,Me.current)return;const He=ke.current;He&&Oe(He)},250)),Ot.current=a,()=>{We.current!==null&&(window.clearTimeout(We.current),We.current=null)}},[be,l.activeRoom?.id,l.messages.length,l.messagesLoading,f?.id,C.length,M,Oe]),s.useEffect(()=>{!N||Me.current||Ie("streaming")},[N,F,E,Ie]),s.useEffect(()=>{const e=lt();if(!e){Bt.current=0,pn.current=null;return}if(pn.current!==e){pn.current=e,Bt.current=Rt.length;return}const a=Bt.current,u=Rt.length,w=u>a,L=!Me.current;Bt.current=u,w&&L&&Ie("new-message")},[Rt,lt,Ie]),s.useEffect(()=>{ps<=0||!ke.current||Ie("keyboard")},[ps,Ie]),br(Ye&&Kt),s.useLayoutEffect(()=>{if(!Ye||!f&&!be||typeof window>"u")return;const e=bn.current,a=window.visualViewport;if(!e||!a)return;const u=L=>{if(!(L instanceof HTMLElement))return!1;if(L.tagName==="TEXTAREA")return!0;if(L.tagName!=="INPUT")return!1;const Z=L.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(Z)},w=()=>{if(zt.current){e.classList.remove("chat-thread--keyboard-active"),e.style.transform="",e.style.willChange="";return}const L=Math.max(0,window.innerHeight-a.offsetTop-a.height),Z=a.offsetTop||0;e.style.setProperty("--vv-height",`${a.height}px`),e.style.setProperty("--vv-offset-top",`${Z}px`),e.style.setProperty("--keyboard-overlap",`${L}px`);const Ce=(L>0||Z>0)&&u(document.activeElement);e.classList.toggle("chat-thread--keyboard-active",Ce),Ce&&Z>0?(e.style.transform=`translateY(${Z}px)`,e.style.willChange="transform"):(e.style.transform="",e.style.willChange="")};return w(),a.addEventListener("resize",w),a.addEventListener("scroll",w),document.addEventListener("focusin",w),document.addEventListener("focusout",w),window.addEventListener("pageshow",w),document.addEventListener("visibilitychange",w),()=>{a.removeEventListener("resize",w),a.removeEventListener("scroll",w),document.removeEventListener("focusin",w),document.removeEventListener("focusout",w),window.removeEventListener("pageshow",w),document.removeEventListener("visibilitychange",w),e.classList.remove("chat-thread--keyboard-active"),e.style.transform="",e.style.willChange=""}},[f,Ye,be]),s.useEffect(()=>{const e=()=>te(null);if(pe)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[pe]),s.useEffect(()=>{if(!Ye||!Kt)return;const e=a=>{a.target?.closest(".chat-messages")||a.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[Ye,Kt]),s.useEffect(()=>{const e=ms.current;if(ms.current=m,m==="rooms"&&!l.activeRoom){Ot.current=null;return}if(!(m==="direct"&&(e===null||e==="rooms"))&&!(m==="rooms"&&(e===null||e==="direct")))return;const w=ke.current;w&&(Oe(w,{force:!0}),Me.current=!1,Pt(!1))},[m,l.activeRoom,Oe]),s.useEffect(()=>{if(!f&&!be||be&&!ne)return;const e=()=>{const u=!Me.current;Gt(),u&&ne&&ke.current&&Ie("visibility-restore")},a=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",a),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",a),window.removeEventListener("pageshow",e)}},[ne,Ye,f,be,Gt,Ie]),s.useEffect(()=>{if(be||typeof ResizeObserver>"u")return;const e=ke.current;if(!e)return;const a=new ResizeObserver(()=>{Me.current||Oe(e)});return a.observe(e),()=>{a.disconnect()}},[be,Oe,f?.id,m]),s.useEffect(()=>{hs.current=Ae},[Ae]),s.useEffect(()=>()=>{for(const e of hs.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of Mt.current.values())window.clearTimeout(e);Mt.current.clear()},[]);const dt=s.useCallback(e=>{if(!e||e.length===0)return;const a=[];for(const u of Array.from(e)){if(!io.includes(u.type))continue;const w=u.type.startsWith("image/");a.push({file:u,previewUrl:w?URL.createObjectURL(u):""})}a.length>0&&fn(u=>[...u,...a])},[]),ys=s.useCallback(e=>{fn(a=>{const u=a[e];return u?.previewUrl&&URL.revokeObjectURL(u.previewUrl),a.filter((w,L)=>L!==e)})},[]),ws=s.useCallback(e=>{const a=e.clipboardData?.files;if(!a||a.length===0)return;const u=Array.from(a).filter(w=>w.type.startsWith("image/"));u.length!==0&&dt(u)},[dt]),Aa=s.useCallback(async e=>{try{await k(e),T(!1),ne&&me(!1)}catch{r(o("chat.failedToCreateSession","Failed to create chat session"),"error")}},[k,r,ne]),Ee=s.useCallback(e=>{const a=e??Se.current;if(!a)return;const u=Ut==="tablet"?to:ss;a.style.height="auto",a.style.height=`${so(a.scrollHeight,u)}px`,a.style.overflowY=no(a.scrollHeight,u)},[Ut]),xs=s.useCallback(e=>{Se.current=e,e&&Ee(e)},[Ee]);s.useLayoutEffect(()=>{Ee()},[m,z,f?.id,l.activeRoom?.id,Ee]);const ut=s.useCallback(()=>{if(he(""),Re)try{localStorage.removeItem(Re)}catch{}v(!1),$(""),oe(!1),Y(""),ge(-1),fn(e=>{for(const a of e)a.previewUrl&&URL.revokeObjectURL(a.previewUrl);return[]})},[Re]),Sn=s.useCallback(()=>{const e=z.trim(),a=Ae.map(u=>u.file);if(!(!e&&a.length===0||!f)){if(e==="/clear"||e==="/new"){ut(),X(),le(),k({agentId:f.agentId,modelProvider:f.modelProvider??void 0,modelId:f.modelId??void 0}).catch(()=>{r(o("chat.failedToClearConversation","Failed to clear conversation"),"error")});return}ut(),R(e,a)}},[z,Ae,f,ut,le,X,k,r,R]),Mn=s.useCallback(async()=>{const e=z.trim(),a=Ae.map(u=>u.file);if(!(!e&&a.length===0)){if(m==="rooms"){if(!l.activeRoom)return;if(e==="/clear"||e==="/new"){ut();try{await l.clearRoom(l.activeRoom.id)}catch{r(o("chat.failedToClearRoomConversation","Failed to clear room conversation"),"error")}return}if(vn.current)return;vn.current=!0;const u=z;ut();try{await l.sendRoomMessage(e,{files:a})}catch(w){if(w instanceof ya){const Z=w.message.trim()?w.message:o("chat.messageSentButReplyFailed","Message sent, but assistant reply failed");r(o("chat.messageSentButReplyFailedDetail","Message sent, but assistant reply failed: {{detail}}",{detail:Z}),"error");return}he(u);const L=w instanceof Error&&w.message.trim()?w.message:o("chat.failedToSendRoomMessage","Failed to send room message");r(L,"error")}finally{vn.current=!1}return}Sn()}},[z,Ae,D,m,l,l.clearRoom,ut,r,Sn]),Vt=s.useCallback(async e=>{if(m==="rooms"){if(!l.activeRoom)return;try{await l.sendRoomMessage(e)}catch(a){const u=a instanceof Error&&a.message.trim()?a.message:o("chat.failedToSendRoomMessage","Failed to send room message");r(u,"error")}return}f&&R(e)},[f,r,D,m,l,R,o]),kn=s.useCallback(e=>{he(a=>{const u=fa(a);if(!u)return a;const w=`/skill:${e.name} `,L=a.slice(0,u.start)+w+a.slice(u.end);return window.requestAnimationFrame(()=>{Se.current&&(Ee(Se.current),Se.current.focus())}),L}),v(!1),$(""),H(0)},[Ee]),Wt=s.useCallback(e=>{const a=Se.current;if(!a||de<0)return;const u=a.selectionStart??it.current,w=a.selectionEnd??u,L=Math.max(u,w),Z=Math.min(de,L),xe=`${`@${e.name.replace(/\s+/g,"_")}`} `,He=z.slice(0,Z)+xe+z.slice(L),mt=Z+xe.length;he(He),oe(!1),Y(""),ee(0),ge(-1),window.requestAnimationFrame(()=>{Se.current&&(Ee(Se.current),Se.current.focus(),Se.current.setSelectionRange(mt,mt))})},[de,z,Ee]),At=s.useCallback((e,a)=>{const w=Se.current?.selectionStart??it.current,L=z.lastIndexOf("#",w),Z=L>=0?L+a.length:e.length;he(e),ce.dismissMention(),$t(!1),window.requestAnimationFrame(()=>{Se.current&&(Ee(Se.current),Se.current.focus(),Se.current.setSelectionRange(Z,Z))})},[ce,z,Ee]),Cs=s.useCallback(e=>{if(it.current=e.currentTarget.selectionStart??it.current,ce.mentionActive&&ce.combinedItems.length>0){if(ce.handleKeyDown(e,z),e.key==="Enter"||e.key==="Tab"){const a=ce.combinedItems[ce.selectedIndex];a?.kind==="task"?At(ce.selectTask(a.task,z),`#${a.task.id}`):a?.kind==="file"&&At(ce.selectFile(a.file,z),`#${a.file.path}`)}return}if(K&&e.key==="ArrowDown"){e.preventDefault(),Je.length>0&&ee(a=>(a+1)%Je.length);return}if(K&&e.key==="ArrowUp"){e.preventDefault(),Je.length>0&&ee(a=>a===0?Je.length-1:a-1);return}if(K&&e.key==="Enter"){e.preventDefault();const a=Je[J]??Je[0];a&&Wt(a);return}if(K&&e.key==="Escape"){e.preventDefault(),oe(!1),Y(""),ge(-1);return}if(h&&e.key==="ArrowDown"){e.preventDefault(),Ne.length>0&&H(a=>(a+1)%Ne.length);return}if(h&&e.key==="ArrowUp"){e.preventDefault(),Ne.length>0&&H(a=>a===0?Ne.length-1:a-1);return}if(h&&(e.key==="Enter"||e.key==="Tab")&&Ne.length>0){e.preventDefault();const a=Ne[se]??Ne[0];a&&kn(a);return}if(h&&e.key==="Escape"){e.preventDefault(),v(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Mn())},[K,Je,J,Wt,h,Ne,se,kn,Mn,ce,At,z]),Xt=s.useCallback((e,a)=>{const u=co(e,a);if(u){oe(!0),Y(u.filter),ge(u.start);return}oe(!1),Y(""),ge(-1)},[]),Ss=s.useCallback(e=>{const a=e.target,u=a.value,w=a.selectionStart??u.length;Ee(a),it.current=w,he(u);const L=fa(u);L?(v(!0),$(L.filter)):(v(!1),$("")),Xt(u,w),ce.detectMention(u,w),$t(ce.mentionActive),ce.mentionActive&&gn(a)},[Xt,Ee]),qt=s.useCallback(e=>{const a=e.currentTarget,u=a.selectionStart??a.value.length;it.current=u,Xt(a.value,u),ce.detectMention(a.value,u),$t(ce.mentionActive),ce.mentionActive&&gn(a)},[Xt,ce,gn]),Ms=s.useCallback(e=>{e.key!=="Escape"&&qt(e)},[qt]),ks=s.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(zt.current=!0,Le.current!==null&&window.clearTimeout(Le.current),Le.current=window.setTimeout(()=>{zt.current=!1,Le.current=null},450),(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0),_e.current!==null&&window.clearTimeout(_e.current),_e.current=window.setTimeout(()=>{_e.current=null,document.activeElement?.tagName!=="TEXTAREA"&&(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},350)),Pe.current!==null&&window.clearTimeout(Pe.current),Pe.current=window.setTimeout(()=>{v(!1),oe(!1),Y(""),ge(-1),$t(!1),ce.dismissMention(),Pe.current=null},120)},[ce]),Rs=s.useCallback(()=>{zt.current=!1,Le.current!==null&&(window.clearTimeout(Le.current),Le.current=null),Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null),_e.current!==null&&(window.clearTimeout(_e.current),_e.current=null)},[]);s.useEffect(()=>()=>{Le.current!==null&&window.clearTimeout(Le.current),_e.current!==null&&window.clearTimeout(_e.current)},[]);const Na=s.useCallback(async e=>{te(null);try{await ae(e),r(o("chat.conversationArchived","Conversation archived"),"success")}catch{r(o("chat.failedToArchiveConversation","Failed to archive conversation"),"error")}},[ae,r]),As=s.useCallback(e=>{const a=j.find(u=>u.id===e)??(f?.id===e?f:null);te(null),Ve(!1),Ge(a?.title??""),ye({sessionId:e,title:a?.title??""})},[f,j]),Ns=s.useCallback(async()=>{if(ve)try{await G(ve.sessionId,Ke),ye(null),Ge(""),r(o("chat.conversationRenamed","Conversation renamed"),"success")}catch{}},[r,ve,G,Ke,o]),Ea=s.useCallback(async e=>{Fe(null),te(null);try{await ue(e),r(o("chat.conversationDeleted","Conversation deleted"),"success")}catch{r(o("chat.failedToDeleteConversation","Failed to delete conversation"),"error")}},[ue,r]),Nt=s.useCallback(e=>{try{localStorage.setItem(da,String(e))}catch{}},[]),Ta=s.useCallback(e=>{if(ne||kt)return;e.preventDefault(),e.stopPropagation();const a=e.currentTarget;typeof a.setPointerCapture=="function"&&a.setPointerCapture(e.pointerId);const u=e.clientX,w=Te;let L=w;document.body.style.userSelect="none";const Z=xe=>{const He=xe.clientX-u,mt=Math.max(an,Math.min(rn,w+He));L=mt,yt(mt),Nt(mt)},Ce=xe=>{typeof a.releasePointerCapture=="function"&&a.releasePointerCapture(xe.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",Z),document.removeEventListener("pointerup",Ce),Nt(L)};document.addEventListener("pointermove",Z),document.addEventListener("pointerup",Ce)},[ne,Nt,Te,kt]),ja=s.useCallback(e=>{if(ne||kt||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const a=e.shiftKey?50:10,u=e.key==="ArrowLeft"?-a:a,w=Math.max(an,Math.min(rn,Te+u));yt(w),Nt(w)},[ne,Nt,Te,kt]),Es=s.useCallback(e=>{const a=j.find(u=>u.id===e);O("direct",e,a?.lastMessageAt??a?.updatedAt),W(e),Ve(!1),ne&&me(!1)},[j,ne,O,W]),Rn=s.useCallback(()=>{W(""),me(!0),Ve(!1)},[W]),An=s.useCallback(()=>{l.selectRoom(null),me(!0),Ve(!1)},[l]),Da=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(cn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:o("chat.startNewConversation","Start a new conversation")}),t.jsxs("button",{className:"btn btn-primary",onClick:()=>T(!0),children:[t.jsx(ht,{size:16}),o("chat.newChat","New Chat")]})]}),Be=ga(f,f?.agentId?je.get(f.agentId)??null:null,st),Nn=s.useMemo(()=>{if(!Be?.provider||!Be.modelId)return null;const e=It.find(a=>a.provider===Be.provider&&a.id===Be.modelId);return e?.contextWindow?e.contextWindow:null},[Be?.modelId,Be?.provider,It]),Fa=s.useMemo(()=>eo(C,N?F:void 0),[N,C,F]),ze=Hs(Be?.provider,Be?.modelId),Ze=Be?.provider??null,Qt=!!(f||N||C.length>0),Yt=m==="rooms"?be:!!f,Ts=s.useRef(Yt);s.useEffect(()=>{const e=Ts.current;Ts.current=Yt,ne&&(e||!Yt||is({type:"view",revert:m==="rooms"?An:Rn}))},[m,Rn,An,Yt,ne,is]);const En=f?.agentId===bt?ze??"Fusion":f?.title||je.get(f?.agentId??"")?.name||f?.agentId||"Chat",js=!!(ze&&ze!==En),Ia=!ne&&Qt&&Nn!==null,Ds=ca(Fa),Jt=Nn!==null?ca(Nn):null,Tn=Jt?o("chat.contextWindowAria","Estimated {{used}} of {{total}} context tokens",{used:Ds,total:Jt}):null,Pa=ne&&m==="direct"&&!!f,jn=je.get(f?.agentId??"")?.name||(f?.agentId===bt?ze??"Fusion":f?.agentId?.slice(0,30)??"Fusion"),Dn=!1,Fn=f?.agentId===bt,La=e=>e.length>50?`${e.slice(0,50)}…`:e,_a=s.useCallback(()=>{Ca(e=>!e)},[]);s.useEffect(()=>{if(!Lt)return;const e=a=>{ds.current?.contains(a.target)||Ve(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[Lt]),s.useEffect(()=>{if(!_t)return;const e=u=>{us.current?.contains(u.target)||Ct(!1)},a=u=>{u.key==="Escape"&&Ct(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",a),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",a)}},[_t]),s.useEffect(()=>{(!ne||m!=="direct"||Qe)&&Ve(!1)},[ne,m,Qe]),s.useEffect(()=>{Ct(!1)},[l.activeRoom?.id]);const In=s.useCallback((e,a)=>{const u=Mt.current.get(e);u&&window.clearTimeout(u),os(L=>({...L,[e]:a}));const w=window.setTimeout(()=>{os(L=>{const{[e]:Z,...Ce}=L;return Ce}),Mt.current.delete(e)},2e3);Mt.current.set(e,w)},[]),Fs=s.useCallback(async(e,a)=>{try{if(!navigator.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(a),In(e,"success")}catch{In(e,"error")}},[In]),Pn=f?.agentId===bt,Ln=s.useCallback((e,a,u)=>t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${ot[e]==="success"?" chat-message-copy-action--success":""}${ot[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":u??`chat-copy-response-${e}`,"aria-label":ot[e]==="success"?o("chat.responseCopied","Response copied"):ot[e]==="error"?o("chat.copyFailed","Copy failed"):o("chat.copyResponse","Copy response"),onClick:()=>{Fs(e,a)},children:ot[e]==="success"?t.jsx(vr,{size:14}):t.jsx(yr,{size:14})}),[ot,Fs]),_n=s.useCallback(e=>{const a=ke.current;if(!a)return;const u=`[data-testid="chat-message-${e}"]`,w=a.querySelector(u);if(!w)return;const L=w.getBoundingClientRect().top-a.getBoundingClientRect().top+a.scrollTop,Z=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;a.scrollTo({top:L,behavior:Z?"auto":"smooth"})},[]),Is=f?.cliExecutorAdapterId??null,$a=!!Is,Oa=Is==="generic"?"generic":"hybrid",Ba=f?.cliSessionFile||f?.id||"",Ps=()=>t.jsxs("div",{className:"chat-messages",ref:ke,onScroll:vs,children:[t.jsx("div",{ref:ls,className:"chat-load-more-sentinel",children:V&&M&&t.jsx("div",{className:"chat-loading-older",children:o("chat.loadingOlderMessages","Loading older messages…")})}),N?t.jsxs(t.Fragment,{children:[C.map((e,a)=>t.jsx(zn,{message:e,forcePlain:De,agentName:jn,hideAssistantIdentity:Fn,showAssistantModelTag:Dn,activeModelTag:ze,activeModelProvider:Ze,activeSessionId:f?.id??null,mentionAgentsByName:xn,roomContext:null,copyAction:Pn&&e.role==="assistant"?Ln(e.id,e.content):void 0,onScrollToTop:_n,isAwaitingQuestionAnswer:e.role==="assistant"&&a===C.length-1&&!N,submittedQuestionAnswer:ua(C,a),onQuestionSubmit:Vt},e.id)),t.jsx(Ar,{streamingText:F,streamingThinking:E,streamingToolCalls:A,forcePlain:De,agentName:jn,hideAssistantIdentity:Fn,showAssistantModelTag:Dn,activeModelTag:ze,activeModelProvider:Ze,copyAction:Pn&&F?Ln("__streaming__",F,"chat-copy-response-streaming"):void 0,onQuestionSubmit:Vt})]}):M?t.jsx("div",{className:"chat-empty-state",children:o("chat.loadingMessages","Loading messages...")}):C.length===0&&!f?Da():C.length===0&&f?t.jsx("div",{className:"chat-empty-state",children:o("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsx(t.Fragment,{children:C.map((e,a)=>t.jsx(zn,{message:e,forcePlain:De,agentName:jn,hideAssistantIdentity:Fn,showAssistantModelTag:Dn,activeModelTag:ze,activeModelProvider:Ze,activeSessionId:f?.id??null,mentionAgentsByName:xn,roomContext:null,copyAction:Pn&&e.role==="assistant"?Ln(e.id,e.content):void 0,onScrollToTop:_n,isAwaitingQuestionAnswer:e.role==="assistant"&&a===C.length-1&&!N,submittedQuestionAnswer:ua(C,a),onQuestionSubmit:Vt},e.id))}),t.jsx("div",{ref:cs})]}),Ls=()=>t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Ht,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:e=>{dt(e.target.files),e.target.value=""}}),h&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":o("chat.skillSuggestions","Skill suggestions"),children:hn?t.jsx("div",{className:"chat-skill-menu-empty",children:o("chat.loadingSkills","Loading skills…")}):Ne.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:x?o("chat.noSkillsFound","No skills found"):o("chat.noSkillsAvailable","No skills available")}):Ne.map((e,a)=>t.jsxs("button",{type:"button",role:"option","aria-selected":a===se,className:`chat-skill-menu-item${a===se?" chat-skill-menu-item--highlighted":""}`,onMouseDown:u=>u.preventDefault(),onMouseEnter:()=>H(a),onClick:()=>kn(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))}),Ae.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:Ae.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:()=>ys(a),"data-testid":`chat-attachment-remove-${a}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${a}`))}),U.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-pending-stack","data-testid":"chat-pending-stack",children:U.map((e,a)=>t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:o("chat.queuedMessage","Queued: {{preview}}",{preview:La(e)})}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":o("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":`chat-pending-dismiss-${a}`,onClick:()=>X(a),children:"×"})]},`${a}-${e}`))}),t.jsx("div",{className:"chat-pending-divider","aria-hidden":"true"})]}),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":o("chat.attachFiles","Attach files"),onClick:()=>Ht.current?.click(),children:t.jsx(Vs,{size:16})}),t.jsxs("div",{className:`chat-input-wrapper${as?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),rt(!0)},onDragLeave:()=>rt(!1),onDrop:e=>{e.preventDefault(),rt(!1),dt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:xs,className:"chat-input-textarea",placeholder:o("chat.typeMessage","Type a message..."),value:z,onChange:Ss,onKeyDown:Cs,onKeyUp:Ms,onClick:qt,onBlur:ks,onFocus:Rs,onPaste:ws,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||Ws()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(aa,{agents:ct,filter:Q,highlightedIndex:J,visible:K,onSelect:Wt,position:"below",roomMemberIds:$e?.memberIds,roomName:$e?.roomName}),t.jsx(Ur,{visible:ce.mentionActive&&!K,position:Sa,tasks:ce.tasks,files:ce.files,selectedIndex:ce.selectedIndex,onSelectTask:e=>{At(ce.selectTask(e,z),`#${e.id}`)},onSelectFile:e=>{At(ce.selectFile(e,z),`#${e.path}`)},loading:ce.loading})]}),t.jsx(Xs,{isStreaming:N,canSend:!!(z.trim()||Ae.length>0),onSend:Sn,onStop:le})]})]}),za=ne?void 0:{width:`${Te}px`},Ha=t.jsxs("div",{className:"chat-sidebar-scope-toggle chat-view-header-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${m==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":m==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>I("direct"),children:[t.jsx(cn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:o("chat.scopeDirect","Direct")})]}),t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${m==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":m==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>I("rooms"),children:[t.jsx(va,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:o("chat.scopeRooms","Rooms")})]})]});return t.jsxs("div",{ref:fs,className:`chat-view${i?" chat-view--floating":""}${ne?" chat-view--narrow":""}`,children:[t.jsx(wr,{icon:cn,title:o("chat.title","Chat"),actions:t.jsxs(t.Fragment,{children:[Ha,ne?null:t.jsxs("button",{className:"btn btn-sm btn-primary chat-view-header-new-chat",onClick:()=>T(!0),"data-testid":"chat-new-btn",children:[t.jsx(ht,{size:14}),o("chat.newChat","New Chat")]}),!i&&c?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:c,"aria-label":o("chat.popOut","Pop out chat"),title:o("chat.popOut","Pop out chat"),"data-testid":"chat-pop-out",children:t.jsx(Us,{size:16})}):null,i&&d?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:d,"aria-label":o("chat.maximizeToChatView","Open in Chat view"),title:o("chat.maximizeToChatView","Open in Chat view"),"data-testid":"chat-modal-maximize",children:t.jsx(Us,{size:16})}):null,i&&b?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:b,"aria-label":o("chat.minimizeToQuickChat","Minimize to quick chat"),title:o("chat.minimizeToQuickChat","Minimize to quick chat"),"data-testid":"chat-modal-minimize",children:t.jsx(xr,{size:16})}):null,i&&p?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:p,"aria-label":o("chat.closeChat","Close chat"),title:o("chat.closeChat","Close chat"),"data-testid":"chat-modal-close",children:t.jsx(Cr,{size:16})}):null]})}),t.jsxs("div",{className:"chat-view__body",children:[t.jsxs("div",{className:`chat-sidebar${Qe?"":" chat-sidebar--hidden"}`,style:za,children:[m==="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(Sr,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:o("chat.searchConversations","Search conversations..."),value:y,onChange:e=>P(e.target.value),"data-testid":"chat-search-input"})]})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:B?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:o("chat.loadingConversations","Loading...")}):j.length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:o("chat.noConversationsYet","No conversations yet")}):j.map(e=>{const a=f?.id===e.id,u=!a&&re("direct",e.id,e.lastMessageAt??e.updatedAt),w=ga(e,je.get(e.agentId)??null,st),L=Hs(w?.provider,w?.modelId)??"Fusion";return t.jsxs("div",{className:`chat-session-item${a?" chat-session-item--active":""}`,onClick:()=>Es(e.id),onContextMenu:Z=>{Z.preventDefault(),te({sessionId:e.id,x:Z.clientX,y:Z.clientY})},"data-testid":`chat-session-${e.id}`,children:[t.jsx("button",{className:"chat-session-delete-btn",onClick:Z=>{Z.stopPropagation(),Fe(e.id)},"data-testid":"chat-session-delete-btn","aria-label":o("chat.deleteConversation","Delete conversation"),children:t.jsx(On,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[e.title||o("chat.untitledSession","Untitled"),u?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":o("chat.unreadMessages","Unread messages")}):null]}),t.jsx("div",{className:"chat-session-preview",children:e.lastMessagePreview||o("chat.noMessages","No messages")}),t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[w?.provider?t.jsx(Bn,{provider:w.provider,size:"sm"}):null,t.jsx("span",{children:je.get(e.agentId)?.name||(e.agentId===bt?L:e.agentId.slice(0,30))})]}),t.jsx("span",{children:e.updatedAt?ao(e.updatedAt,o):""})]})]},e.id)})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!ne&&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:()=>nt(!0),children:[t.jsx(ht,{size:14}),o("chat.createRoom","Create room")]})}),l.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:o("chat.noRoomsYet","No rooms yet.")}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:l.rooms.map(e=>{const a=l.activeRoom?.id===e.id,u=!a&&re("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:()=>{O("room",e.id,e.updatedAt),l.selectRoom(e.id),ne&&me(!1)},onKeyDown:w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),O("room",e.id,e.updatedAt),l.selectRoom(e.id),ne&&me(!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]}),u?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":o("chat.unreadMessages","Unread messages")}):null]}),a?t.jsx("span",{className:"chat-room-item-meta",children:o("chat.roomMemberCount","{{count}} member",{count:l.activeRoomMembers.length,defaultValue_one:"{{count}} member",defaultValue_other:"{{count}} members"})}):null]}),t.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${e.slug}`,"aria-label":o("chat.deleteRoom","Delete room {{name}}",{name:e.name}),onClick:w=>{w.stopPropagation(),fe(e.id)},children:t.jsx(On,{size:14})})]},e.id)})})]}),m==="rooms"?ne?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:()=>nt(!0),children:[t.jsx(ht,{size:14}),o("chat.createRoom","Create room")]})}):null:ne?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:()=>T(!0),"data-testid":"chat-new-btn",children:[t.jsx(ht,{size:14}),o("chat.newChat","New Chat")]})}):null]}),!ne&&Qe&&!kt&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":an,"aria-valuemax":rn,"aria-valuenow":Te,"aria-label":o("chat.resizeSidebar","Resize chat sidebar"),tabIndex:0,onPointerDown:Ta,onKeyDown:ja}),pe&&t.jsxs("div",{className:"chat-session-context-menu",style:{top:pe.y,left:pe.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>As(pe.sessionId),"data-testid":"chat-context-rename",children:[t.jsx(Ks,{size:14}),o("chat.rename","Rename")]}),t.jsxs("button",{onClick:()=>Na(pe.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Mr,{size:14}),o("chat.archive","Archive")]}),t.jsxs("button",{onClick:()=>{te(null),Fe(pe.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(On,{size:14}),o("chat.delete","Delete")]})]}),ve&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>ye(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:o("chat.renameConversationTitle","Rename Conversation")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:o("chat.renameConversationBody","Choose a new name for this conversation. Leave it blank to show Untitled.")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-input",children:o("chat.conversationName","Conversation name")}),t.jsx("input",{id:"chat-rename-input",className:"input chat-rename-input",type:"text",value:Ke,placeholder:o("chat.renamePlaceholder","Untitled"),"data-testid":"chat-rename-input",onChange:e=>Ge(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),Ns())},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>ye(null),children:o("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void Ns(),"data-testid":"chat-rename-save",children:o("chat.save","Save")})]})]})}),we&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>Fe(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:o("chat.deleteConversationTitle","Delete Conversation?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:o("chat.deleteConversationBody","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:()=>Fe(null),children:o("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Ea(we),children:o("chat.delete","Delete")})]})]})}),Dt&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>fe(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:o("chat.deleteRoomTitle","Delete Room?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:o("chat.deleteRoomBody","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:()=>fe(null),children:o("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await l.deleteRoom(Dt),fe(null)}catch{r(o("chat.failedToDeleteRoom","Failed to delete room"),"error")}})()},children:o("chat.delete","Delete")})]})]})}),m==="rooms"?t.jsxs("div",{ref:bn,className:"chat-thread",children:[l.activeRoom?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-room-thread-header",children:[ne&&t.jsx("button",{className:"btn-icon",onClick:An,"data-testid":"chat-back-btn",children:t.jsx(Gs,{size:16})}),t.jsxs("div",{className:"chat-room-switcher-menu",ref:us,children:[t.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":_t,onClick:()=>Ct(e=>!e),children:[t.jsxs("span",{className:"chat-thread-header-title",children:["#",l.activeRoom.name]}),t.jsx(Zt,{size:16,"aria-hidden":"true"})]}),_t&&t.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:l.rooms.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${e.id===l.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${e.id}`,onClick:()=>{O("room",e.id,e.updatedAt),l.selectRoom(e.id),Ct(!1)},children:["#",e.name]},e.id))})]}),t.jsx("div",{className:"chat-room-thread-members",children:l.activeRoomMembers.map(e=>t.jsx(un,{agent:je.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:ke,onScroll:vs,children:[l.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:o("chat.loadingMessages","Loading messages...")}):l.messages.filter(e=>e.content.trim()!==la).length===0?t.jsx("div",{className:"chat-empty-state",children:o("chat.noMessagesYet","No messages yet. Start the conversation!")}):l.messages.filter(e=>e.content.trim()!==la).map(e=>{const a=e.senderAgentId?je.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):o("chat.you","You"),u={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(zn,{message:u,forcePlain:De,agentName:a,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:l.activeRoom?.id??null,mentionAgentsByName:xn,roomContext:$e,onScrollToTop:_n,isAwaitingQuestionAnswer:!1,onQuestionSubmit:Vt},e.id)}),t.jsx("div",{ref:cs})]}),l.activeRoom&&rs&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>Ie("fab-click"),children:[t.jsx(Zt,{size:14}),o("chat.latest","Latest")]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:o("chat.selectRoomOrCreate","Select a room or create one")}),l.activeRoom&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Ht,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:e=>{dt(e.target.files),e.target.value=""}}),Ae.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:Ae.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:()=>ys(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":o("chat.attachFiles","Attach files"),onClick:()=>Ht.current?.click(),children:t.jsx(Vs,{size:16})}),t.jsxs("div",{className:`chat-input-wrapper${as?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),rt(!0)},onDragLeave:()=>rt(!1),onDrop:e=>{e.preventDefault(),rt(!1),dt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:xs,className:"chat-input-textarea",placeholder:o("chat.typeMessage","Type a message..."),value:z,onChange:Ss,onKeyDown:Cs,onKeyUp:Ms,onClick:qt,onBlur:ks,onFocus:Rs,onPaste:ws,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||Ws()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(aa,{agents:ct,filter:Q,highlightedIndex:J,visible:K,onSelect:Wt,position:"below",roomMemberIds:$e?.memberIds,roomName:$e?.roomName})]}),t.jsx(Xs,{isStreaming:!1,canSend:!!(z.trim()||Ae.length>0),onSend:Mn})]})]})]}):t.jsxs("div",{ref:bn,className:"chat-thread",children:[(Qt||!ne)&&t.jsxs("div",{className:"chat-thread-header",children:[ne&&Qt&&t.jsx("button",{className:"btn-icon",onClick:Rn,"data-testid":"chat-back-btn",children:t.jsx(Gs,{size:16})}),t.jsx("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:Pa?t.jsxs("div",{className:"chat-mobile-session-menu",ref:ds,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:()=>Ve(e=>!e),children:[Ze?t.jsx(Bn,{provider:Ze,size:"md"}):t.jsx(qn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:En}),js&&t.jsx("span",{className:"chat-model-tag",children:ze}),t.jsx(Zt,{size:16,"aria-hidden":"true"})]}),Lt&&t.jsxs("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:[j.map(e=>t.jsxs("div",{className:`chat-mobile-session-option-row${f?.id===e.id?" chat-mobile-session-option-row--active":""}`,role:"none",children:[t.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${f?.id===e.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${e.id}`,onClick:()=>Es(e.id),children:t.jsx("span",{className:"chat-mobile-session-option-title",children:e.title||o("chat.untitledSession","Untitled")})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-rename","data-testid":`chat-mobile-session-rename-${e.id}`,"aria-label":o("chat.renameConversationAria","Rename conversation {{title}}",{title:e.title||o("chat.untitledSession","Untitled")}),onClick:()=>As(e.id),children:t.jsx(Ks,{size:14})})]},e.id)),t.jsxs("button",{type:"button",role:"menuitem",className:"chat-mobile-session-new","data-testid":"chat-mobile-session-new",onClick:()=>{Ve(!1),T(!0)},children:[t.jsx(ht,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:o("chat.newChat","New Chat")})]})]})]}):t.jsxs(t.Fragment,{children:[Ze?t.jsx(Bn,{provider:Ze,size:"md"}):t.jsx(qn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:En}),js&&t.jsx("span",{className:"chat-model-tag",children:ze}),Ia&&Jt&&Tn?t.jsxs("span",{className:"chat-thread-header-context","data-testid":"chat-thread-context-window",title:Tn,"aria-label":Tn,children:[Ds," / ",Jt]}):null]})}),Qt&&t.jsx("button",{type:"button",className:`chat-thread-header-render-toggle${De?" chat-thread-header-render-toggle--plain":""}`,"data-testid":"chat-thread-render-toggle","aria-label":De?o("chat.showRenderedMarkdown","Show all messages as rendered Markdown"):o("chat.showPlainText","Show all messages as plain text"),onClick:_a,children:De?t.jsx(kr,{size:14}):t.jsx(Rr,{size:14})})]}),$a?t.jsx(Vr,{cliSessionId:Ba,tier:Oa,projectId:n,renderTranscript:Ps,renderComposer:()=>f?Ls():null}):t.jsxs(t.Fragment,{children:[Ps(),rs&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>Ie("fab-click"),children:[t.jsx(Zt,{size:14}),o("chat.latest","Latest")]}),f&&Ls()]})]}),t.jsx(Gr,{isOpen:mn,onClose:()=>nt(!1),projectId:n,existingRoomNames:l.rooms.map(e=>e.name),onCreate:async e=>{await l.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),m!=="rooms"&&I("rooms"),nt(!1),ne&&me(!1)}})]}),S&&t.jsx(uo,{projectId:n,defaultModel:st,onClose:()=>T(!1),onCreate:Aa})]})}export{wo as ChatView,so as clampChatInputHeight,no as resolveChatInputOverflowY,ga as resolveSessionProvider};
@@ -1 +0,0 @@
1
- import{r as a,j as e}from"./vendor-react-SZ_qB27O.js";import{ay as le,az as ie,aA as Be,aB as qe,aC as he,aD as Ke,aE as de,aF as Qe,aG as ue,aH as _e,aI as Ve,V as Ge,aJ as U,D as We,F as Xe,aK as Ie,X as me,R as Je,al as I,p as Ye,s as fe,v as pe,aL as J,aM as Ze,aN as et,o as xe,C as tt,ad as st}from"./index-BjELA24x.js";import{u as O}from"./vendor-i18n-GF3RlKbq.js";import"./vendor-reactflow-CnI7NMXG.js";import"./vendor-xterm-BNq00GSj.js";import"./vendor-codemirror-jBKmHyH0.js";function at(t){const{projectId:i,searchQuery:h,includeProjectFiles:d=!0}=t??{},o=i?`${Be.DOCUMENTS_PREFIX}${i}`:null,[s,c]=a.useState(()=>{if(!o)return[];const w=le(o,{maxAgeMs:ie});return Array.isArray(w)?w:[]}),[f,r]=a.useState([]),[p,u]=a.useState(()=>s.length===0),[j,b]=a.useState(null),k=a.useRef(null),g=a.useRef(s.length>0),x=a.useRef(null),P=a.useCallback(async()=>{k.current&&k.current.abort();const w=new AbortController;k.current=w;const z=!g.current;z&&u(!0),b(null);const E=qe(h?{q:h}:void 0,i),T=d?he(i):Promise.resolve({files:[]}),[v,S]=await Promise.allSettled([E,T]);if(w.signal.aborted)return;let M=null;if(v.status==="fulfilled"){if(c(v.value),o){const A=v.value.length>500?v.value.slice(0,500):v.value;Ke(o,A,{maxBytes:5e5})}g.current=!0}else M=v.reason instanceof Error?v.reason.message:String(v.reason);if(S.status==="fulfilled"){const A=S.value.files,R=h?.trim().toLowerCase(),F=R?A.filter(H=>H.name.toLowerCase().includes(R)||H.path.toLowerCase().includes(R)):A;r(F)}b(M),z&&u(!1)},[o,d,i,h]);return a.useEffect(()=>{if(!o){g.current=!1,c([]),u(!0);return}const w=le(o,{maxAgeMs:ie});Array.isArray(w)?(c(w),g.current=!0,u(!1)):(g.current=!1,c([]),u(!0))},[o]),a.useEffect(()=>(x.current&&clearTimeout(x.current),x.current=setTimeout(()=>{P()},300),()=>{x.current&&clearTimeout(x.current)}),[P]),a.useEffect(()=>(P(),()=>{k.current&&k.current.abort()}),[]),{documents:s,projectFiles:f,loading:p,error:j,refresh:P}}function nt(t,i){const[h,d]=a.useState([]),[o,s]=a.useState(!0),[c,f]=a.useState(null),r=a.useRef(null),p=a.useRef(!1),u=i?.showHidden??!1,j=a.useCallback(async b=>{r.current&&r.current.abort();const k=new AbortController;r.current=k;const g=!p.current;g&&s(!0),f(null);try{const x=await he(t,{showHidden:b?.showHidden??u});if(k.signal.aborted)return;d(x.files),p.current=!0}catch(x){if(k.signal.aborted)return;f(x instanceof Error?x.message:String(x))}finally{!k.signal.aborted&&g&&s(!1)}},[t,u]);return a.useEffect(()=>(p.current=!1,j({showHidden:u}),()=>{r.current&&r.current.abort()}),[j,u]),{files:h,loading:o,error:c,refresh:j}}const ct=768;function Y(t){return t?new Date(t).toLocaleString():""}function je(t){return t<1024?`${t} B`:t<1024*1024?`${(t/1024).toFixed(t>=10*1024?0:1)} KB`:`${(t/(1024*1024)).toFixed(1)} MB`}function we(t,i=200){return t.length<=i?t:`${t.substring(0,i)}…`}function ot({document:t,renderMarkdown:i,onToggleMarkdown:h}){const{t:d}=O("app"),[o,s]=a.useState(!1),c=we(t.content),f=t.content.length>200;return e.jsxs("div",{className:"document-card",children:[e.jsxs("div",{className:"document-card-header",children:[e.jsxs("div",{className:"document-card-key",children:[e.jsx(U,{size:14}),e.jsx("span",{className:"document-card-key-text",children:t.key}),e.jsxs("span",{className:"document-card-revision-badge",children:["v",t.revision]})]}),e.jsx("div",{className:"document-card-actions",children:e.jsx("button",{className:"btn btn-sm document-card-expand-btn",onClick:()=>s(r=>!r),title:o?d("documents.collapse","Collapse"):d("documents.expand","Expand"),"aria-label":o?d("documents.collapseContent","Collapse content"):d("documents.expandContent","Expand content"),children:o?e.jsx(st,{size:14}):e.jsx(xe,{size:14})})})]}),e.jsxs("div",{className:"document-card-meta",children:[e.jsx("span",{className:"document-card-author",children:t.author}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{className:"document-card-date",children:Y(t.updatedAt)})]}),e.jsxs("div",{className:`document-card-content${o?" document-card-content--expanded":""}`,children:[o?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"document-card-content-header",children:e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:h,"aria-label":i?d("documents.switchToPlainText","Switch to plain text"):d("documents.switchToMarkdown","Switch to markdown"),"aria-pressed":i,title:i?d("documents.switchToPlainText","Switch to plain text"):d("documents.switchToMarkdown","Switch to markdown"),children:i?d("documents.markdown","Markdown"):d("documents.plain","Plain")})}),i?e.jsx("div",{className:"document-card-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(fe,{remarkPlugins:[pe],children:t.content})})}):e.jsx("pre",{className:"document-card-content-text",children:t.content})]}):e.jsx("p",{className:"document-card-preview",children:c}),f&&!o&&e.jsx("p",{className:"document-card-preview-truncated",children:"…"})]})]})}function rt({taskId:t,taskTitle:i,documents:h,onOpenTask:d,renderMarkdownStates:o,onToggleMarkdown:s}){const{t:c}=O("app"),[f,r]=a.useState(!1);return e.jsxs("div",{className:"documents-group",children:[e.jsxs("div",{className:"documents-group-header",children:[e.jsxs("button",{className:"documents-group-toggle-btn",onClick:()=>r(p=>!p),"aria-expanded":f,"aria-label":`${f?c("documents.collapse","Collapse"):c("documents.expand","Expand")} documents for task ${t}`,children:[e.jsx("span",{className:"documents-group-toggle","aria-hidden":"true",children:f?e.jsx(xe,{size:16}):e.jsx(tt,{size:16})}),e.jsx("span",{className:"documents-group-task-id",children:t}),e.jsx("span",{className:"documents-group-task-title",children:i||c("documents.untitled","Untitled")})]}),e.jsx("span",{className:"documents-group-count",children:c("documents.docCount","{{count}} doc{{plural}}",{count:h.length,plural:h.length!==1?"s":""})}),e.jsx("button",{className:"documents-group-task-link",onClick:()=>d(t),"aria-label":c("documents.openTaskAria","Open task {{taskId}}: {{title}}",{taskId:t,title:i||c("documents.untitled","Untitled")}),children:c("documents.openTask","Open task")})]}),f&&e.jsx("div",{className:"documents-group-content",children:h.map(p=>e.jsx(ot,{document:p,renderMarkdown:o.get(p.id)??!1,onToggleMarkdown:()=>s(p.id)},p.id))})]})}function lt({artifact:t,projectId:i,onOpenTask:h,onExpandMedia:d}){const{t:o}=O("app"),s=J(t.id,i),c=Ze(o,t.type),f=t.content?we(t.content,320):t.description,r=t.title||o("documents.untitledArtifact","Untitled artifact"),p=t.type==="image"||t.type==="video",u=a.useCallback(j=>{(j.key==="Enter"||j.key===" ")&&(j.preventDefault(),d(t))},[t,d]);return e.jsxs("article",{className:"document-card documents-artifact-card","aria-label":o("documents.artifactCardLabel","Artifact {{title}}",{title:r}),children:[p?e.jsxs("div",{className:"documents-artifact-preview documents-artifact-preview--expandable",role:"button",tabIndex:0,"aria-label":o("documents.expandArtifact","Expand {{title}}",{title:r}),onClick:()=>d(t),onKeyDown:u,children:[t.type==="image"?e.jsx("img",{className:"documents-artifact-media",src:s,alt:r,loading:"lazy"}):e.jsx("video",{className:"documents-artifact-media",src:s,muted:!0,preload:"metadata","aria-label":o("documents.artifactVideoLabel","Video artifact: {{title}}",{title:r})}),e.jsx("span",{className:"documents-artifact-expand-hint",children:o("documents.expandArtifactHint","Click to expand")})]}):e.jsx("div",{className:"documents-artifact-preview",children:e.jsx(et,{artifact:t,mediaUrl:s,title:r,preview:f,t:o})}),e.jsxs("div",{className:"documents-artifact-body",children:[e.jsxs("div",{className:"documents-artifact-header",children:[e.jsx("span",{className:"documents-artifact-type-badge",children:c}),e.jsx("span",{className:"documents-artifact-author",children:t.authorId})]}),e.jsx("h3",{className:"documents-artifact-title",children:r}),t.description&&e.jsx("p",{className:"documents-artifact-description",children:t.description}),e.jsxs("div",{className:"documents-artifact-meta",children:[e.jsx("span",{children:Y(t.createdAt)}),t.sizeBytes!==void 0&&e.jsx("span",{children:je(t.sizeBytes)})]}),t.taskId&&e.jsx("button",{className:"documents-group-task-link documents-artifact-task-link",onClick:()=>h(t.taskId),"aria-label":o("documents.openTaskAria","Open task {{taskId}}: {{title}}",{taskId:t.taskId,title:t.taskTitle||o("documents.untitled","Untitled")}),children:o("documents.openTask","Open task")})]})]})}function pt({projectId:t,addToast:i,onOpenDetail:h,onOpenArtifactTaskDetail:d,onSendSelectionToTask:o}){const{t:s}=O("app"),[c,f]=a.useState("project"),[r,p]=a.useState(""),[u,j]=a.useState(null),[b,k]=a.useState(!1),[g,x]=a.useState(null),[P,w]=a.useState(!1),[z,E]=a.useState(null),[T,v]=a.useState(!1),S=a.useRef(0),M=a.useRef(!1),A=a.useRef(null),R=a.useRef(null),[F,H]=a.useState(!1),[ke,Z]=a.useState(new Map),[y,B]=a.useState(null),ee=a.useRef(null),q=a.useRef(null),[te,be]=a.useState(!1),ge=de(A,{locked:te}),ve=de(R,{locked:te}),K=F?ge:ve,Ne=c==="tasks"?r.trim():"",ye=c==="artifacts"?r.trim():"",{documents:D,loading:Q,error:Ce,refresh:se}=at({projectId:t,searchQuery:Ne||void 0,includeProjectFiles:!1}),{files:C,loading:_,error:Se,refresh:ae}=nt(t,{showHidden:b}),{artifacts:L,loading:V,error:Fe,refresh:ne}=Qe({projectId:t,searchQuery:ye||void 0});a.useEffect(()=>{const n=()=>{v(window.innerWidth<=ct)};return n(),window.addEventListener("resize",n),()=>{window.removeEventListener("resize",n)}},[]),a.useEffect(()=>{M.current=!1,f("project"),j(null),k(!1),x(null),E(null),w(!1),H(!1),Z(new Map),B(null)},[t]),a.useEffect(()=>{M.current||Q||_||V||(C.length>0?f("project"):D.length>0?f("tasks"):L.length>0&&f("artifacts"),M.current=!0)},[L.length,V,D.length,Q,C.length,_]);const G=a.useMemo(()=>{const n=new Map;for(const l of D){const m=n.get(l.taskId)||[];n.set(l.taskId,[...m,l])}return Array.from(n.entries()).map(([l,m])=>{const N=[...m].sort((Ue,Oe)=>Oe.updatedAt.localeCompare(Ue.updatedAt));return{taskId:l,taskTitle:N[0]?.taskTitle,documents:N,latestUpdated:N[0]?.updatedAt??""}}).sort((l,m)=>m.latestUpdated.localeCompare(l.latestUpdated))},[D]),W=a.useMemo(()=>{const n=r.trim().toLowerCase();return n?C.filter(l=>{const m=l.path.toLowerCase(),N=l.name.toLowerCase();return m.includes(n)||N.includes(n)}):C},[C,r]);a.useEffect(()=>{if(!u)return;C.some(l=>l.path===u.path)||(j(null),x(null),E(null),w(!1))},[C,u]);const Ee=a.useCallback(n=>{p(n.target.value)},[]),Te=a.useCallback(()=>{p("")},[]),X=a.useCallback(n=>{f(n)},[]),Ae=a.useCallback(async n=>{try{const l=await ue(n,t);h(l)}catch{i(`Failed to open task ${n}`,"error")}},[t,h,i]),Le=a.useCallback(async n=>{try{const l=await ue(n,t);(d??h)(l)}catch{i(`Failed to open task ${n}`,"error")}},[t,d,h,i]),Pe=a.useCallback(async n=>{j(n),w(!0),E(null),x(null);const l=S.current+1;S.current=l;try{const m=await _e("project",n.path,t);if(S.current!==l)return;x(m.content)}catch(m){if(S.current!==l)return;const N=m instanceof Error?m.message:`Failed to open ${n.path}`;E(N),i(N,"error")}finally{S.current===l&&w(!1)}},[t,i]),Me=a.useCallback(()=>{j(null),x(null),E(null),w(!1)},[]),Re=a.useCallback(n=>{Z(l=>{const m=new Map(l),N=m.get(n)??!1;return m.set(n,!N),m})},[]),De=a.useCallback(n=>{q.current=document.activeElement instanceof HTMLElement?document.activeElement:null,B(n)},[]),$=a.useCallback(()=>{B(null),q.current?.focus(),q.current=null},[]);a.useEffect(()=>{if(!y)return;const n=document.body.style.overflow;document.body.style.overflow="hidden",ee.current?.focus();const l=m=>{m.key==="Escape"&&(m.preventDefault(),$())};return document.addEventListener("keydown",l),()=>{document.body.style.overflow=n,document.removeEventListener("keydown",l)}},[$,y]);const ze=a.useCallback(n=>{n.target===n.currentTarget&&$()},[$]),ce=c==="project"?Se:c==="tasks"?Ce:Fe,He=a.useCallback(async()=>{if(c==="project"){await ae();return}if(c==="tasks"){await se();return}await ne()},[c,ne,ae,se]),oe=c==="project"?W.length:c==="tasks"?D.length:L.length,$e=u&&o&&K?e.jsx(Ve,{selectedText:K.selectedText,anchorRect:K.anchorRect,filePath:u.path,onSubmit:o,onOpenChange:be}):null,re=c==="project"?s("documents.searchProjectFiles","Search project markdown files…"):c==="tasks"?s("documents.searchTaskDocuments","Search task documents…"):s("documents.searchArtifacts","Search artifacts…");return e.jsxs("div",{className:"documents-view",children:[e.jsxs("div",{className:"documents-view-header",children:[e.jsx(Ge,{icon:U,title:s("documents.title","Artifacts"),actions:e.jsx("span",{className:"documents-view-count",children:s("documents.resultCount","{{count}} result{{plural}}",{count:oe,plural:oe!==1?"s":""})})}),e.jsxs("div",{className:"documents-controls-row",children:[e.jsxs("div",{className:"documents-tab-bar",role:"tablist","aria-label":s("documents.sectionsLabel","Documents sections"),children:[e.jsxs("button",{className:`btn documents-tab${c==="project"?" active":""}`,role:"tab","aria-selected":c==="project","aria-label":s("documents.showProjectFiles","Show project markdown files"),onClick:()=>X("project"),children:[s("documents.projectFilesTab","Project Files"),e.jsx("span",{className:"documents-tab-count",children:C.length})]}),e.jsxs("button",{className:`btn documents-tab${c==="tasks"?" active":""}`,role:"tab","aria-selected":c==="tasks","aria-label":s("documents.showTaskDocuments","Show task documents"),onClick:()=>X("tasks"),children:[s("documents.taskDocumentsTab","Task Documents"),e.jsx("span",{className:"documents-tab-count",children:G.length})]}),e.jsxs("button",{className:`btn documents-tab${c==="artifacts"?" active":""}`,role:"tab","aria-selected":c==="artifacts","aria-label":s("documents.showArtifacts","Show artifacts"),onClick:()=>X("artifacts"),children:[s("documents.artifactsTab","Artifacts"),e.jsx("span",{className:"documents-tab-count",children:L.length})]})]}),c==="project"&&e.jsxs("button",{className:"btn btn-sm documents-hidden-toggle",onClick:()=>k(n=>!n),"aria-pressed":b,"aria-label":b?s("documents.hideHidden","Hide hidden project files"):s("documents.showHidden","Show hidden project files"),title:b?s("documents.hideHiddenFiles","Hide hidden files"):s("documents.showHiddenFiles","Show hidden files"),children:[b?e.jsx(We,{size:14}):e.jsx(Xe,{size:14}),b?s("documents.hideHiddenLabel","Hide Hidden"):s("documents.showHiddenLabel","Show Hidden")]}),e.jsxs("div",{className:"documents-search",children:[e.jsx(Ie,{size:16,className:"documents-search-icon"}),e.jsx("input",{type:"text",className:"documents-search-input",placeholder:re,value:r,onChange:Ee,"aria-label":re}),r&&e.jsx("button",{className:"documents-search-clear",onClick:Te,"aria-label":s("documents.clearSearch","Clear search"),children:e.jsx(me,{size:16})})]})]})]}),e.jsx("div",{className:"documents-view-content",children:ce?e.jsxs("div",{className:"documents-view-error",children:[e.jsx("p",{children:s("documents.failedToLoad","Failed to load {{type}}: {{error}}",{type:c==="project"?s("documents.projectFiles","project files"):c==="tasks"?s("documents.taskDocuments","task documents"):s("documents.artifacts","artifacts"),error:ce})}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void He(),"aria-label":s("documents.retryLoading","Retry loading documents"),children:[e.jsx(Je,{size:16}),s("documents.retry","Retry")]})]}):c==="project"?_&&C.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:e.jsx(I,{label:s("documents.loadingProjectFiles","Loading project markdown files…")})})}):W.length===0?e.jsx("div",{className:"documents-view-empty",children:r.trim()?e.jsx("p",{children:s("documents.noMatchProject",'No project markdown files match "{{query}}".',{query:r.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(U,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:s("documents.noMarkdownFiles","No Markdown files found in this project.")})]})}):e.jsxs("div",{className:`documents-project-layout${T?" documents-project-layout--mobile":""}`,children:[(!T||!u)&&e.jsx("aside",{className:"documents-view-sidebar","aria-label":s("documents.projectMarkdownFilesLabel","Project markdown files"),children:e.jsx("ul",{className:"markdown-file-list",children:W.map(n=>{const l=u?.path===n.path;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item${l?" markdown-file-item--selected":""}`,onClick:()=>void Pe(n),"aria-label":`Open ${n.path}`,"aria-current":l?"true":void 0,children:[e.jsx("span",{className:"markdown-file-item-name",children:n.name}),e.jsx("span",{className:"markdown-file-item-path",children:n.path}),e.jsxs("span",{className:"markdown-file-item-meta",children:[je(n.size)," · ",Y(n.mtime)]})]})},n.path)})})}),(!T||u)&&e.jsxs("section",{className:"documents-view-main","aria-label":s("documents.projectFilePreviewLabel","Project file content preview"),children:[T&&u&&e.jsxs("button",{className:"btn btn-sm documents-mobile-back",onClick:Me,"aria-label":s("documents.backToFilesList","Back to project files list"),children:[e.jsx(Ye,{size:14}),s("documents.backToFiles","Back to files")]}),u?e.jsxs("div",{className:"documents-content-viewer",children:[e.jsxs("div",{className:"documents-content-header",children:[e.jsx("p",{className:"documents-file-path-header",children:u.path}),e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>H(n=>!n),"aria-label":F?s("documents.switchToPlainText","Switch to plain text"):s("documents.switchToMarkdown","Switch to markdown"),"aria-pressed":F,title:F?s("documents.switchToPlainText","Switch to plain text"):s("documents.switchToMarkdown","Switch to markdown"),children:F?s("documents.markdown","Markdown"):s("documents.plain","Plain")})]}),P?e.jsx("p",{className:"documents-content-state",children:e.jsx(I,{label:s("documents.loadingFileContent","Loading file content…")})}):z?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:z}):F?e.jsx("div",{ref:A,className:"documents-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(fe,{remarkPlugins:[pe],children:g??""})})}):e.jsx("pre",{ref:R,className:"document-card-content-text documents-content-viewer-text",children:g??""}),$e]}):e.jsx("div",{className:"documents-view-empty",children:e.jsx("p",{children:s("documents.selectFile","Select a Markdown file to view its content.")})})]})]}):c==="artifacts"?V&&L.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:s("documents.loadingArtifacts","Loading artifacts…")})}):L.length===0?e.jsx("div",{className:"documents-view-empty",children:r.trim()?e.jsx("p",{children:s("documents.noMatchArtifacts",'No artifacts match "{{query}}".',{query:r.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(U,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:s("documents.noArtifacts","No artifacts yet.")}),e.jsx("p",{className:"documents-view-empty-hint",children:s("documents.artifactsCreatedBy","Artifacts are created by agents, users, and system tools.")})]})}):e.jsx("div",{className:`documents-artifact-gallery${T?" documents-artifact-gallery--mobile":""}`,children:L.map(n=>e.jsx(lt,{artifact:n,projectId:t,onOpenTask:Le,onExpandMedia:De},n.id))}):Q&&D.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:e.jsx(I,{label:s("documents.loadingTaskDocuments","Loading task documents…")})})}):G.length===0?e.jsx("div",{className:"documents-view-empty",children:r.trim()?e.jsx("p",{children:s("documents.noMatchTask",'No task documents match "{{query}}".',{query:r.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(U,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:s("documents.noTaskDocuments","No task documents yet.")}),e.jsx("p",{className:"documents-view-empty-hint",children:s("documents.documentsCreatedIn","Documents are created in task detail tabs.")})]})}):e.jsx("div",{className:"documents-task-list-wrap",children:e.jsx("div",{className:"documents-view-list",children:G.map(({taskId:n,taskTitle:l,documents:m})=>e.jsx(rt,{taskId:n,taskTitle:l,documents:m,onOpenTask:Ae,renderMarkdownStates:ke,onToggleMarkdown:Re},n))})})}),y&&e.jsx("div",{className:"modal-overlay open documents-artifact-lightbox-overlay",role:"dialog","aria-modal":"true","aria-label":s("documents.lightboxLabel","Artifact media preview"),onClick:ze,children:e.jsxs("div",{className:"documents-artifact-lightbox",onClick:n=>n.stopPropagation(),children:[e.jsxs("div",{className:"documents-artifact-lightbox-header",children:[e.jsx("h3",{className:"documents-artifact-lightbox-title",children:y.title||s("documents.untitledArtifact","Untitled artifact")}),e.jsx("button",{ref:ee,className:"modal-close",onClick:$,"aria-label":s("documents.closeLightbox","Close artifact preview"),children:e.jsx(me,{size:20})})]}),e.jsx("div",{className:"documents-artifact-lightbox-media-frame",children:y.type==="image"?e.jsx("img",{className:"documents-artifact-lightbox-media",src:J(y.id,t),alt:y.title||s("documents.untitledArtifact","Untitled artifact")}):e.jsx("video",{className:"documents-artifact-lightbox-media",src:J(y.id,t),controls:!0,autoPlay:!0,"aria-label":s("documents.artifactVideoLabel","Video artifact: {{title}}",{title:y.title||s("documents.untitledArtifact","Untitled artifact")})})})]})})]})}export{pt as DocumentsView};
@@ -1 +0,0 @@
1
- import{r as d,j as e}from"./vendor-react-SZ_qB27O.js";import{ae as Me,af as Ue,ag as $e,ah as ce,ai as qe,X as ge,aj as Ve,ak as Te,al as de,P as pe,am as me,J as he,R as be,an as We,a3 as Ke,ao as Qe,ap as Je,aq as Ye,ar as Xe,as as Ze,at as es,au as ss,av as O,aw as ns,ax as is}from"./index-BjELA24x.js";import{D as ts}from"./DirectoryPicker-BwMSmxYS.js";import{u as as}from"./vendor-i18n-GF3RlKbq.js";import"./vendor-reactflow-CnI7NMXG.js";import"./vendor-xterm-BNq00GSj.js";import"./vendor-codemirror-jBKmHyH0.js";import"./folder-open-B8vOwFeP.js";const Ne="fusion-plugin-agent-browser",ye={enabled:{type:"boolean",label:"Enable Agent Browser",group:"General"},installChannel:{type:"enum",label:"Install Channel",enumValues:["stable","beta","nightly"],defaultValue:"stable",group:"General"},commandTimeoutMs:{type:"number",label:"Command Timeout (ms)",defaultValue:12e4,group:"General"},headlessMode:{type:"boolean",label:"Headless Mode",defaultValue:!0,group:"Browser"},allowedDomains:{type:"array",label:"Allowed Domains",itemType:"string",group:"Browser"},promptExecutorSystem:{type:"string",label:"Executor System Prompt",multiline:!0,group:"Prompt Contributions"},promptExecutorTask:{type:"string",label:"Executor Task Prompt",multiline:!0,group:"Prompt Contributions"},promptTriage:{type:"string",label:"Triage Prompt",multiline:!0,group:"Prompt Contributions"},promptReviewer:{type:"string",label:"Reviewer Prompt",multiline:!0,group:"Prompt Contributions"},promptHeartbeat:{type:"string",label:"Heartbeat Prompt",multiline:!0,group:"Prompt Contributions"},skillExposure:{type:"enum",label:"Skill Exposure",enumValues:["none","selected","all"],defaultValue:"selected",group:"Skills"}},xe={General:"plugins.agentBrowser.groupGeneral",Browser:"plugins.agentBrowser.groupBrowser","Prompt Contributions":"plugins.agentBrowser.groupPromptContributions",Skills:"plugins.agentBrowser.groupSkills"},fe={"Enable Agent Browser":"plugins.agentBrowser.labelEnabled","Install Channel":"plugins.agentBrowser.labelInstallChannel","Command Timeout (ms)":"plugins.agentBrowser.labelCommandTimeoutMs","Headless Mode":"plugins.agentBrowser.labelHeadlessMode","Allowed Domains":"plugins.agentBrowser.labelAllowedDomains","Executor System Prompt":"plugins.agentBrowser.labelPromptExecutorSystem","Executor Task Prompt":"plugins.agentBrowser.labelPromptExecutorTask","Triage Prompt":"plugins.agentBrowser.labelPromptTriage","Reviewer Prompt":"plugins.agentBrowser.labelPromptReviewer","Heartbeat Prompt":"plugins.agentBrowser.labelPromptHeartbeat","Skill Exposure":"plugins.agentBrowser.labelSkillExposure"},je=[{id:"fusion-plugin-hermes-runtime",name:"Hermes Runtime",description:"Runtime provider for Hermes CLI-backed execution.",category:"runtime",path:"./plugins/fusion-plugin-hermes-runtime",experimental:!0},{id:"fusion-plugin-paperclip-runtime",name:"Paperclip Runtime",description:"Runtime provider for Paperclip agent connections.",category:"runtime",path:"./plugins/fusion-plugin-paperclip-runtime"},{id:"fusion-plugin-openclaw-runtime",name:"OpenClaw Runtime",description:"Runtime provider for OpenClaw execution.",category:"runtime",path:"./plugins/fusion-plugin-openclaw-runtime",experimental:!0},{id:"fusion-plugin-droid-runtime",name:"Droid Runtime",description:"Runtime provider for Droid CLI execution.",category:"runtime",path:"./plugins/fusion-plugin-droid-runtime",experimental:!0},{id:"fusion-plugin-dependency-graph",name:"Dependency Graph",description:"Dashboard plugin for task dependency graph visualization.",category:"integration",path:"./plugins/fusion-plugin-dependency-graph"},{id:"fusion-plugin-reports",name:"Reports",description:"View report history, compare runs side-by-side, and export standalone HTML summaries.",category:"integration",path:"./plugins/fusion-plugin-reports"},{id:"fusion-plugin-whatsapp-chat",name:"WhatsApp Chat",description:"Pairs to WhatsApp Web (multi-device) with QR or pairing code, then bridges direct chats to a Fusion agent.",category:"integration",path:"./plugins/fusion-plugin-whatsapp-chat"},{id:"fusion-plugin-cli-printing-press",name:"CLI Printing Press",description:"Guided wizard for drafting external service CLI definitions.",category:"integration",path:"./plugins/fusion-plugin-cli-printing-press"},{id:"fusion-plugin-compound-engineering",name:"Compound Engineering",description:"A dedicated dashboard surface for compound-engineering artifacts and interactive ce-* sessions.",category:"integration",path:"./plugins/fusion-plugin-compound-engineering"},{id:Ne,name:"Agent Browser",description:"Built-in integration metadata. Package install support lands in FN-3101.",category:"integration",hasSetup:!0}],F={started:"var(--color-success)",loaded:"var(--color-warning)",error:"var(--color-error)",stopped:"var(--color-muted)",installed:"var(--color-info)"};function ls(r){const o=r.settingsSchema,n=o&&Object.keys(o).length>0;return r.id!==Ne?n?o:void 0:n?{...ye,...o}:ye}function rs(r){const o=new Map,n=[];for(const[j,y]of Object.entries(r))if(y.group){const v=o.get(y.group)??[];v.push([j,y]),o.set(y.group,v)}else n.push([j,y]);return{grouped:o,ungrouped:n}}function Se(r,o="plugin-error-text"){return r.state!=="error"||!r.error?null:e.jsx("p",{className:o,title:r.error,children:r.error})}function ys({addToast:r,projectId:o}){const{t:n}=as("app"),[j,y]=d.useState([]),[v,z]=d.useState(!0),[ve,A]=d.useState(!1),[E,L]=d.useState(""),[_,H]=d.useState(!1),[M,U]=d.useState(!1),[w,$]=d.useState(null),[c,G]=d.useState(null),[m,x]=d.useState({}),[we,q]=d.useState(!1),[V,T]=d.useState(null),[W,Pe]=d.useState([]),[Ce,K]=d.useState(!0),[Q,J]=d.useState(null),[b,Re]=d.useState(""),[f,Ie]=d.useState(""),[Ee,Y]=d.useState(null),P=d.useRef(null),[Be,D]=d.useState({}),[ke,X]=d.useState(null),[B,Z]=d.useState(null),{confirm:Fe}=Me(),h=d.useCallback(async()=>{try{z(!0);const s=await Ue(o);y(s)}catch(s){r(n("plugins.loadFailed","Failed to load plugins: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}finally{z(!1)}},[o,r]),S=d.useCallback(async(s=b,i=f)=>{try{K(!0),J(null);const l=await $e(s,i||void 0,o);Pe(l)}catch(l){const u=l instanceof Error?l.message:String(l);J(u)}finally{K(!1)}},[o,f,b]);d.useEffect(()=>{h()},[h]),d.useEffect(()=>(P.current&&clearTimeout(P.current),P.current=setTimeout(()=>{S(b,f)},300),()=>{P.current&&clearTimeout(P.current)}),[S,f,b]),d.useEffect(()=>{const s=je.filter(l=>l.hasSetup&&j.some(u=>u.id===l.id));if(s.length===0)return;let i=!1;return Promise.all(s.map(async l=>{try{const u=await ce(l.id,o);if(i)return;D(g=>({...g,[l.id]:u}))}catch{if(i)return;D(u=>({...u,[l.id]:{hasSetup:!0,setupCheckDeferred:!0,deferredReason:"plugin-not-started",pluginState:"installed"}}))}})),()=>{i=!0}},[j,o]);const Ae=d.useRef([]);Ae.current=j,d.useEffect(()=>{const s=o?`?projectId=${encodeURIComponent(o)}`:"",i=l=>{try{const u=JSON.parse(l.data);if(u.scope==="project"&&(u.projectId??o)!==o)return;switch(u.transition){case"installing":case"enabled":case"disabled":case"settings-updated":S(b,f),y(g=>{const a=g.findIndex(t=>t.id===u.pluginId);if(a>=0){const t=[...g];return t[a]={...t[a],enabled:u.enabled,state:u.state,settings:u.settings,error:u.error},t}else return h(),g});break;case"state-changed":y(g=>{const a=g.findIndex(t=>t.id===u.pluginId);if(a>=0){const t=[...g];return t[a]={...t[a],state:u.state,error:u.error},t}return g});break;case"uninstalled":y(g=>g.filter(a=>a.id!==u.pluginId)),S(b,f);break;case"error":y(g=>{const a=g.findIndex(t=>t.id===u.pluginId);if(a>=0){const t=[...g];return t[a]={...t[a],state:u.state,error:u.error},t}return g});break}}catch{}};return qe(`/api/events${s}`,{events:{"plugin:lifecycle":i},onReconnect:()=>{h(),S(b,f)}})},[o,h,S,f,b]);const ee=async()=>{if(!E.trim()){r(n("plugins.installPathRequired","Please enter a plugin path"),"error");return}try{H(!0),await O({path:E,...M?{aiScanOnLoad:!0}:{}},o),r(n("plugins.installedGlobally","Plugin installed globally"),"success"),A(!1),L(""),U(!1),await h()}catch(s){r(n("plugins.installFailed","Failed to install plugin: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}finally{H(!1)}},Le=async s=>{if(!s.path){r(n("plugins.builtinNoPackage","{{name}} is built in and does not have an installable package yet",{name:s.name}),"warning");return}try{T(s.id),await O({path:s.path},o),r(n("plugins.builtinInstalledGlobally","{{name}} installed globally",{name:s.name}),"success"),await h()}catch(i){r(n("plugins.builtinInstallFailed","Failed to install {{name}}: {{error}}",{name:s.name,error:i instanceof Error?i.message:String(i)}),"error")}finally{T(null)}},Ge=async s=>{if(!s.path){r(n("plugins.registryNotInstallable","{{name}} is not available for one-click install yet",{name:s.name}),"warning");return}try{Y(s.id),await O({path:s.path},o),r(n("plugins.registryInstalled","{{name}} installed and enabled",{name:s.name}),"success"),await h(),await S(b,f)}catch(i){r(n("plugins.registryInstallFailed","Failed to install {{name}}: {{error}}",{name:s.name,error:i instanceof Error?i.message:String(i)}),"error")}finally{Y(null)}},se=async s=>{try{Z(s.id);const i=await is(s.id,o);if(!i.success){r(n("plugins.setupInstallFailed","Failed to install {{name}} setup: {{error}}",{name:s.name,error:i.error??n("plugins.unknownError","unknown error")}),"error");return}r(n("plugins.setupInstalled","{{name}} setup installed",{name:s.name}),"success"),X(s.id);const l=await ce(s.id,o);D(u=>({...u,[s.id]:l}))}catch(i){r(n("plugins.setupInstallFailed","Failed to install {{name}} setup: {{error}}",{name:s.name,error:i instanceof Error?i.message:String(i)}),"error")}finally{Z(null),X(null)}},ne=async s=>{try{const i=await es(s.id,o);if(i.state==="error"){r(n("plugins.enableFailed","Failed to enable {{name}}: {{error}}",{name:s.name,error:i.error??n("plugins.unknownError","unknown error")}),"error"),await h();return}r(n("plugins.enabledForProject","{{name}} enabled for this project",{name:s.name}),"success"),await h()}catch(i){r(n("plugins.enablePluginFailed","Failed to enable plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},ie=async s=>{try{await Ze(s.id,o),r(n("plugins.disabledForProject","{{name}} disabled for this project",{name:s.name}),"success"),await h()}catch(i){r(n("plugins.disablePluginFailed","Failed to disable plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},te=async s=>{try{$(s.id),await Xe(s.id,o),r(n("plugins.reloaded","{{name}} reloaded",{name:s.name}),"success"),await h()}catch(i){r(n("plugins.reloadFailed","Failed to reload plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}finally{$(null)}},ae=async s=>{if(await Fe({title:n("plugins.uninstallTitle","Uninstall Plugin Globally"),message:n("plugins.uninstallConfirm",'Are you sure you want to uninstall "{{name}}" globally (all projects)?',{name:s.name}),danger:!0}))try{await ss(s.id,o),r(n("plugins.uninstalledGlobally","{{name}} uninstalled globally",{name:s.name}),"success"),await h(),G(null)}catch(l){r(n("plugins.uninstallFailed","Failed to uninstall plugin: {{error}}",{error:l instanceof Error?l.message:String(l)}),"error")}},De=async(s,i)=>{try{await Qe(s.id,{aiScanOnLoad:i},o),r(i?n("plugins.aiScanEnabled","AI scan on load enabled"):n("plugins.aiScanDisabled","AI scan on load disabled"),"success"),await h()}catch(l){r(n("plugins.updateFailed","Failed to update plugin: {{error}}",{error:l instanceof Error?l.message:String(l)}),"error")}},Oe=async s=>{try{await Je(s.id,o),r(n("plugins.rescanned","{{name}} rescanned",{name:s.name}),"success"),await h()}catch(i){r(n("plugins.rescanFailed","Failed to rescan plugin: {{error}}",{error:i instanceof Error?i.message:String(i)}),"error")}},k=async s=>{G(s);try{q(!0);const i=await ns(s.id,o);x(i)}catch{x({})}finally{q(!1)}},ze=async()=>{if(c)try{await Ye(c.id,m,o),r(n("plugins.settingsSaved","Settings saved"),"success")}catch(s){r(n("plugins.saveSettingsFailed","Failed to save settings: {{error}}",{error:s instanceof Error?s.message:String(s)}),"error")}};if(c)return e.jsxs("div",{className:"plugin-manager-detail","data-testid":"plugin-manager-detail",children:[e.jsxs("div",{className:"plugin-manager-detail-header",children:[e.jsx("button",{className:"btn-icon",onClick:()=>G(null),"aria-label":n("plugins.backToList","Back to plugin list"),children:e.jsx(ge,{size:16})}),e.jsxs("div",{className:"plugin-detail-title",children:[e.jsxs("div",{className:"plugin-detail-title-copy",children:[e.jsx("h4",{className:"plugin-detail-name",children:c.name}),Se(c,"plugin-error-text plugin-error-text--detail")]}),e.jsx("span",{className:"plugin-state-badge",style:{color:F[c.state]||F.installed},children:c.state})]})]}),e.jsxs("div",{className:"plugin-detail-content",children:[e.jsxs("div",{className:"plugin-detail-card",children:[c.description&&e.jsx("p",{className:"plugin-description",children:c.description}),c.author&&e.jsxs("p",{className:"plugin-detail-meta-row",children:[e.jsx("span",{className:"text-muted",children:n("plugins.author","Author:")}),c.author]}),c.homepage&&e.jsxs("p",{className:"plugin-detail-meta-row plugin-homepage",children:[e.jsx("span",{className:"text-muted",children:n("plugins.homepage","Homepage:")}),e.jsxs("a",{href:c.homepage,target:"_blank",rel:"noopener noreferrer",children:[c.homepage,e.jsx(Ve,{size:12})]})]}),e.jsxs("p",{className:"plugin-detail-meta-row",children:[e.jsx("span",{className:"text-muted",children:n("plugins.version","Version:")}),c.version]})]}),e.jsxs("div",{className:"plugin-detail-card",children:[e.jsx("h5",{className:"plugin-detail-section-heading",children:n("plugins.securityScan","Security Scan")}),e.jsxs("div",{className:"plugin-security-row",children:[e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:!!c.aiScanOnLoad,onChange:s=>void De(c,s.target.checked)}),n("plugins.enableAiScanBeforeLoad","Enable AI scan before load/reload")]}),e.jsxs("button",{className:"btn btn-secondary btn-sm",onClick:()=>void Oe(c),children:[e.jsx(Te,{size:14})," ",n("plugins.rescanAndReload","Rescan and Reload")]})]}),e.jsx("p",{className:"text-muted",children:n("plugins.aiScanHint","Turning this on only updates configuration. Use Rescan and Reload to run it now.")}),c.lastSecurityScan?e.jsxs("div",{className:"plugin-security-results",children:[e.jsxs("div",{className:"plugin-security-header",children:[e.jsx("span",{className:`plugin-state-badge plugin-security-badge plugin-security-badge--${c.lastSecurityScan.verdict}`,children:c.lastSecurityScan.verdict}),e.jsx("span",{className:"text-muted",children:c.lastSecurityScan.scannedAt})]}),e.jsx("p",{className:"plugin-security-summary",children:c.lastSecurityScan.summary}),e.jsxs("details",{children:[e.jsx("summary",{children:n("plugins.findings","Findings ({{count}})",{count:c.lastSecurityScan.findings.length})}),e.jsx("ul",{className:"plugin-security-findings",children:c.lastSecurityScan.findings.map((s,i)=>e.jsxs("li",{children:[e.jsx("strong",{children:s.severity})," ",s.category," — ",s.file,": ",s.reason]},`${s.file}-${i}`))})]})]}):e.jsx("p",{className:"text-muted",children:n("plugins.noSecurityScan","No security scan has been run yet.")})]}),e.jsxs("div",{className:"plugin-detail-card",children:[e.jsx("h5",{className:"plugin-detail-section-heading",children:n("plugins.settings","Settings")}),we?e.jsx("p",{className:"text-muted",children:e.jsx(de,{label:n("plugins.loading","Loading...")})}):(()=>{const s=ls(c);return s&&Object.keys(s).length>0?e.jsxs("div",{className:"plugin-settings-form",children:[(()=>{const{grouped:i,ungrouped:l}=rs(s),u=[];l.length>0&&u.push({title:null,entries:l});for(const[g,a]of i.entries())u.push({title:g,entries:a});return u.map(g=>e.jsxs("div",{className:g.title?"plugin-settings-group":void 0,children:[g.title&&e.jsx("h6",{className:"plugin-settings-group-heading",children:xe[g.title]?n(xe[g.title],g.title):g.title}),g.entries.map(([a,t])=>{const N=`setting-${a}-help`,C=t.label?fe[t.label]?n(fe[t.label],t.label):t.label:a;return e.jsxs("div",{className:"form-group",children:[e.jsxs("label",{htmlFor:`setting-${a}`,children:[C,t.required&&" *"]}),t.type==="string"&&!t.multiline&&e.jsx("input",{className:"input",type:"text",id:`setting-${a}`,value:m[a]??"",onChange:p=>x({...m,[a]:p.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?N:void 0}),t.type==="string"&&t.multiline&&e.jsx("textarea",{className:"input",id:`setting-${a}`,rows:4,value:m[a]??"",onChange:p=>x({...m,[a]:p.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?N:void 0}),t.type==="password"&&e.jsx("input",{className:"input",type:"password",id:`setting-${a}`,value:m[a]??"",onChange:p=>x({...m,[a]:p.target.value}),placeholder:t.description,"aria-describedby":t.description&&!t.required?N:void 0}),t.type==="number"&&e.jsx("input",{className:"input",type:"number",id:`setting-${a}`,value:m[a]??"",onChange:p=>x({...m,[a]:Number(p.target.value)}),"aria-describedby":t.description&&!t.required?N:void 0}),t.type==="boolean"&&e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:m[a]??!1,onChange:p=>x({...m,[a]:p.target.checked})}),t.description]}),t.type==="enum"&&e.jsxs("select",{className:"select",id:`setting-${a}`,value:m[a]??"",onChange:p=>x({...m,[a]:p.target.value}),"aria-describedby":t.description&&!t.required?N:void 0,children:[e.jsx("option",{value:"",children:n("plugins.selectOption","Select...")}),t.enumValues?.map(p=>e.jsx("option",{value:p,children:p},p))]}),t.type==="array"&&e.jsxs("div",{className:"plugin-settings-array",children:[m[a]?.map((p,R)=>e.jsxs("div",{className:"plugin-settings-array-item",children:[e.jsx("input",{className:"input",type:t.itemType==="number"?"number":"text",value:p??"",onChange:ue=>{const I=ue.target.value,oe=[...m[a]||[]];oe[R]=t.itemType==="number"?Number(I):I,x({...m,[a]:oe})}}),e.jsx("button",{className:"btn-icon",onClick:()=>{const I=[...m[a]||[]];I.splice(R,1),x({...m,[a]:I})},"aria-label":n("plugins.removeItem","Remove item"),children:e.jsx(ge,{size:14})})]},R)),e.jsxs("button",{className:"btn btn-secondary",onClick:()=>{const p=m[a]||[],R=t.itemType==="number"?0:"";x({...m,[a]:[...p,R]})},children:[e.jsx(pe,{size:14})," ",n("plugins.addItem","Add Item")]})]}),t.description&&!t.required&&!t.multiline&&e.jsx("span",{id:N,className:"form-help",children:t.description})]},a)})]},g.title??"ungrouped"))})(),e.jsx("button",{className:"btn btn-primary",onClick:ze,children:n("plugins.saveSettings","Save Settings")})]}):e.jsx("p",{className:"text-muted",children:n("plugins.noConfigurableSettings","No configurable settings.")})})()]}),e.jsxs("div",{className:"plugin-detail-actions",children:[c.state==="started"&&e.jsxs("button",{className:"btn btn-secondary",onClick:()=>te(c),disabled:w===c.id,children:[e.jsx(me,{size:14,className:w===c.id?"spin":""}),w===c.id?n("plugins.reloading","Reloading..."):n("plugins.reload","Reload")]}),c.enabled?e.jsx("button",{className:"btn btn-secondary",onClick:()=>ie(c),children:n("plugins.disableInProject","Disable in Project")}):e.jsx("button",{className:"btn btn-primary",onClick:()=>ne(c),children:n("plugins.enableInProject","Enable in Project")}),e.jsxs("button",{className:"btn btn-danger",onClick:()=>ae(c),children:[e.jsx(he,{size:14})," ",n("plugins.uninstallGlobally","Uninstall Globally")]})]})]})]});const le=new Map(j.map(s=>[s.id,s])),re=j,_e=()=>e.jsxs("section",{className:"plugin-registry-section","aria-label":n("plugins.browseRegistry","Browse Registry"),children:[e.jsxs("div",{className:"plugin-registry-header",children:[e.jsxs("div",{className:"plugin-registry-heading-copy",children:[e.jsx("h4",{className:"plugin-registry-heading",children:n("plugins.browseRegistry","Browse Registry")}),e.jsx("p",{className:"plugin-registry-description",children:n("plugins.registryDescription","Discover curated runtimes and integrations that can be added to this Fusion workspace.")})]}),e.jsxs("div",{className:"plugin-registry-controls",children:[e.jsxs("label",{className:"plugin-registry-category-label",children:[e.jsx("span",{className:"sr-only",children:n("plugins.registryCategory","Registry category")}),e.jsxs("select",{className:"select plugin-registry-category-select",value:f,onChange:s=>Ie(s.target.value),"aria-label":n("plugins.registryCategory","Registry category"),children:[e.jsx("option",{value:"",children:n("plugins.registryCategoryAll","All Categories")}),e.jsx("option",{value:"runtime",children:n("plugins.registryCategoryRuntime","Runtime")}),e.jsx("option",{value:"integration",children:n("plugins.registryCategoryIntegration","Integration")})]})]}),e.jsxs("label",{className:"plugin-registry-search-label",children:[e.jsx("span",{className:"sr-only",children:n("plugins.searchRegistry","Search registry")}),e.jsx("input",{className:"input plugin-registry-search-input",type:"search",value:b,onChange:s=>Re(s.target.value),placeholder:n("plugins.searchRegistryPlaceholder","Search registry plugins")})]})]})]}),Ce?e.jsxs("div",{className:"plugin-registry-state",role:"status",children:[e.jsx(be,{size:14,className:"spin"}),n("plugins.registryLoading","Loading registry...")]}):Q?e.jsxs("div",{className:"plugin-registry-state plugin-registry-state--error",role:"alert",children:[e.jsx("span",{children:n("plugins.registryLoadFailed","Failed to load registry: {{error}}",{error:Q})}),e.jsx("button",{className:"btn btn-secondary btn-sm plugin-registry-retry",onClick:()=>void S(b,f),children:n("plugins.retry","Retry")})]}):W.length===0?e.jsx("div",{className:"plugin-registry-state",children:b.trim()?n("plugins.registryEmptySearch","No registry plugins match your search."):n("plugins.registryEmpty","No registry plugins are available.")}):e.jsx("div",{className:"plugin-registry-list","aria-label":n("plugins.registryPluginResults","Registry plugin results"),children:W.map(s=>{const i=le.get(s.id),l=Ee===s.id;return e.jsxs("div",{className:"plugin-registry-item",children:[e.jsxs("div",{className:"plugin-registry-meta",children:[e.jsxs("div",{className:"plugin-registry-title-row",children:[e.jsx("span",{className:"plugin-registry-name",children:s.name}),e.jsxs("span",{className:"plugin-registry-version",children:["v",s.version]}),e.jsx("span",{className:"plugin-registry-badge",children:s.category}),s.installed&&e.jsxs("span",{className:"plugin-registry-status plugin-registry-status--installed",children:[n("plugins.statusInstalled","Installed"),s.installedVersion&&s.installedVersion!==s.version?` · v${s.installedVersion}`:""]})]}),e.jsx("span",{className:"plugin-registry-description-text",children:s.description}),e.jsx("span",{className:"plugin-registry-author",children:n("plugins.registryByAuthor","By {{author}}",{author:s.author})})]}),e.jsx("div",{className:"plugin-registry-actions",children:s.installed?e.jsx("button",{className:"btn btn-secondary btn-sm plugin-registry-action",onClick:()=>{i?k(i):h()},children:n("plugins.manage","Manage")}):s.canInstall?e.jsx("button",{className:"btn btn-primary btn-sm plugin-registry-action",onClick:()=>void Ge(s),disabled:l,children:l?n("plugins.installing","Installing..."):n("plugins.installFromRegistry","Install")}):e.jsx("span",{className:"plugin-registry-coming-soon",children:n("plugins.registryComingSoon","Coming Soon")})})]},s.id)})})]}),He=()=>e.jsxs("section",{className:"plugin-builtins-section","aria-label":n("plugins.builtinPlugins","Built-in Plugins"),children:[e.jsxs("div",{className:"plugin-builtins-header",children:[e.jsx("h4",{className:"plugin-builtins-heading",children:n("plugins.builtinPlugins","Built-in Plugins")}),e.jsx("p",{className:"plugin-builtins-description",children:n("plugins.builtinPluginsCatalog","Built-in plugin catalog for runtimes and integrations.")})]}),e.jsx("div",{className:"plugin-builtins-list","aria-label":n("plugins.builtinPluginRecommendations","Built-in plugin recommendations"),children:je.map(s=>{const i=le.get(s.id),l=!!i,u=Be[s.id],g=!!(u&&"setupCheckDeferred"in u&&u.setupCheckDeferred),a=u&&"status"in u?u.status:void 0,t=l&&s.hasSetup&&u?.hasSetup&&!g&&i?.state==="started"&&(a==="not-installed"||a==="error"),N=l&&u?.hasSetup&&a==="installed",C=ke===s.id,p=!s.path;return e.jsxs("div",{className:"plugin-builtins-item",children:[e.jsxs("div",{className:"plugin-builtins-meta",children:[e.jsx("span",{className:"plugin-builtins-name",children:s.name}),s.experimental&&e.jsx("span",{className:"plugin-builtins-runtime-badge",children:n("plugins.experimental","Experimental")}),e.jsx("span",{className:"plugin-builtins-runtime-badge",children:s.category}),e.jsx("span",{className:`plugin-builtins-status ${l?"plugin-builtins-status--installed":"plugin-builtins-status--available"}`,children:l?n("plugins.statusInstalled","Installed"):p?n("plugins.statusBuiltIn","Built in"):n("plugins.statusNotInstalled","Not installed")}),t&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--warning",children:n("plugins.setupRequired","Setup required")}),N&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--ready",children:n("plugins.setupReady","Setup ready")}),C&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--pending",children:n("plugins.checkingSetup","Checking setup...")}),g&&e.jsx("span",{className:"plugin-builtins-setup-status plugin-builtins-setup-status--deferred",children:n("plugins.startPluginToCheckSetup","Start plugin to check setup")}),e.jsx("span",{className:"plugin-builtins-description-text",children:s.description})]}),p?l&&t?e.jsx("button",{className:"btn btn-primary btn-sm",onClick:()=>void se(s),disabled:B===s.id||C,children:B===s.id?n("plugins.settingUp","Setting up..."):n("plugins.installSetup","Install Setup")}):l&&i?e.jsx("button",{className:"btn btn-secondary btn-sm",onClick:()=>void k(i),children:n("plugins.manage","Manage")}):e.jsx("span",{className:"plugin-builtins-metadata-only",children:n("plugins.builtinMetadataOnly","Built-in metadata only")}):e.jsx("button",{className:`btn ${l&&!t?"btn-secondary":"btn-primary"} btn-sm`,onClick:()=>{if(!l){Le(s);return}if(t){se(s);return}i&&k(i)},disabled:V===s.id||B===s.id||C,children:l?t?B===s.id?n("plugins.settingUp","Setting up..."):n("plugins.installSetup","Install Setup"):n("plugins.manage","Manage"):V===s.id?n("plugins.installing","Installing..."):n("plugins.installNamed","Install {{name}}",{name:s.name})})]},s.id)})})]});return e.jsxs("div",{className:"plugin-manager","data-testid":"plugin-manager",children:[e.jsxs("div",{className:"plugin-manager-header",children:[e.jsx("span",{className:"plugin-manager-header-title",children:n("plugins.installedPlugins","Installed Plugins")}),e.jsxs("div",{className:"plugin-manager-actions",children:[e.jsxs("button",{className:"btn btn-sm",onClick:h,title:n("plugins.refresh","Refresh"),"aria-label":n("plugins.refreshPluginList","Refresh plugin list"),children:[e.jsx(be,{size:14,className:v?"spin":""}),n("plugins.refresh","Refresh")]}),e.jsxs("button",{className:"btn btn-primary btn-sm",onClick:()=>A(!0),children:[e.jsx(pe,{size:14})," ",n("plugins.install","Install")]})]})]}),ve&&e.jsxs("div",{className:"plugin-install-form",children:[e.jsx("p",{className:"plugin-install-hint",children:n("plugins.installHint","Browse to a plugin package root (contains manifest.json) or a built dist directory.")}),e.jsx(ts,{value:E,onChange:L,placeholder:n("plugins.installPathPlaceholder","Absolute path to plugin directory or dist folder"),onInputKeyDown:s=>{s.key==="Enter"&&(s.preventDefault(),ee())}}),e.jsxs("label",{className:"checkbox-label",children:[e.jsx("input",{type:"checkbox",checked:M,onChange:s=>U(s.target.checked)}),n("plugins.enableAiSecurityScan","Enable AI security scan on load")]}),e.jsxs("div",{className:"plugin-install-actions",children:[e.jsx("button",{className:"btn btn-primary",onClick:ee,disabled:_||!E.trim(),children:_?n("plugins.installing","Installing..."):n("plugins.installPluginGlobally","Install Plugin Globally")}),e.jsx("button",{className:"btn btn-secondary",onClick:()=>{A(!1),L("")},children:n("plugins.cancel","Cancel")})]})]}),v?e.jsx("div",{className:"settings-empty-state",children:e.jsx(de,{label:n("plugins.loadingPlugins","Loading plugins...")})}):e.jsxs(e.Fragment,{children:[re.length===0?e.jsxs("div",{className:"settings-empty-state",children:[e.jsx(We,{size:32,className:"text-muted"}),e.jsx("p",{children:n("plugins.noPluginsInstalled","No plugins installed.")}),e.jsx("p",{className:"text-muted",children:n("plugins.noPluginsHint","Install a plugin to get started, or use the built-in catalog below.")})]}):e.jsx("div",{className:"plugin-list",children:re.map(s=>e.jsxs("div",{className:"plugin-item",children:[e.jsx("div",{className:"plugin-info",children:e.jsxs("div",{className:"plugin-copy",children:[e.jsxs("div",{className:"plugin-copy-header",children:[e.jsx("span",{className:"plugin-name",children:s.name}),e.jsxs("span",{className:"plugin-version text-muted",children:["v",s.version]}),e.jsx("span",{className:"plugin-state-badge",style:{color:F[s.state]||F.installed},children:s.state})]}),Se(s)]})}),e.jsxs("div",{className:"plugin-actions",children:[s.state==="started"&&e.jsx("button",{className:"btn-icon",onClick:()=>te(s),disabled:w===s.id,title:n("plugins.reload","Reload"),children:e.jsx(me,{size:14,className:w===s.id?"spin":""})}),e.jsxs("label",{className:"toggle-switch",children:[e.jsx("input",{type:"checkbox",checked:s.enabled,onChange:()=>s.enabled?ie(s):ne(s),"aria-label":s.enabled?n("plugins.disablePlugin","Disable {{name}}",{name:s.name}):n("plugins.enablePlugin","Enable {{name}}",{name:s.name})}),e.jsx("span",{className:"toggle-slider"})]}),e.jsx("button",{className:"btn-icon",onClick:()=>k(s),title:n("plugins.settings","Settings"),children:e.jsx(Ke,{size:14})}),e.jsx("button",{className:"btn-icon",onClick:()=>ae(s),title:n("plugins.uninstallGloballyTitle","Uninstall globally"),children:e.jsx(he,{size:14})})]})]},s.id))}),He(),_e()]})]})}export{ye as AGENT_BROWSER_SETTINGS_SCHEMA,Ne as BUILTIN_AGENT_BROWSER_PLUGIN_ID,je as BUILTIN_PLUGINS,ys as PluginManager,F as STATE_COLORS};