@runfusion/fusion 0.76.0-beta.3 → 0.77.0-beta.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 (175) hide show
  1. package/dist/bin.js +13802 -9587
  2. package/dist/child-process-worker.js +6472 -4028
  3. package/dist/client/.vite/manifest.json +280 -269
  4. package/dist/client/assets/AgentDetailView-0G9qFd4j.js +13 -0
  5. package/dist/client/assets/{AgentDetailView-Cc3ATg8a.css → AgentDetailView-jzgy1BAS.css} +1 -1
  6. package/dist/client/assets/{AgentPermissionPolicyEditor--u9jyUf2.js → AgentPermissionPolicyEditor-BM68g7wo.js} +1 -1
  7. package/dist/client/assets/AgentsView-DkOUZWw4.js +24 -0
  8. package/dist/client/assets/ChatView-BPSm2JIH.js +13 -0
  9. package/dist/client/assets/{CommandCenter-CSRYoveB.js → CommandCenter-DxRSFWNc.js} +26 -26
  10. package/dist/client/assets/CommandCenter-ilm-DbtI.css +1 -0
  11. package/dist/client/assets/{DevServerView-B9So_oYx.js → DevServerView-DO-bqJFE.js} +1 -1
  12. package/dist/client/assets/{DirectoryPicker-BhyDL_2m.js → DirectoryPicker-Cp2gddTE.js} +1 -1
  13. package/dist/client/assets/DocumentsView-D0E-3G96.js +1 -0
  14. package/dist/client/assets/EvalsView-BoFVq5hw.js +1 -0
  15. package/dist/client/assets/ExperimentalAgentOnboardingModal-CS1Sdogm.js +1 -0
  16. package/dist/client/assets/{GoalsView-B6X5_0Ve.js → GoalsView-sybf7JY4.js} +1 -1
  17. package/dist/client/assets/InsightsView-nHa7aShn.js +11 -0
  18. package/dist/client/assets/{MemoryView-DN_3IFmA.css → MemoryView-CdpQqPJJ.css} +1 -1
  19. package/dist/client/assets/MemoryView-D0IG44za.js +3 -0
  20. package/dist/client/assets/{PiExtensionsManager-B8At6fO8.js → PiExtensionsManager-CU76weJe.js} +2 -2
  21. package/dist/client/assets/PluginManager-DyT8XbcG.js +1 -0
  22. package/dist/client/assets/{PullRequestView-B1hZFrWo.js → PullRequestView-CnxWUSen.js} +2 -2
  23. package/dist/client/assets/{ReportModal-C46V_zEa.js → ReportModal-CMrmMQjD.js} +5 -5
  24. package/dist/client/assets/{ResearchView-D8G85BYN.js → ResearchView-BTytQSgy.js} +2 -2
  25. package/dist/client/assets/{SecretsView-CTri9LRK.js → SecretsView-BuSH5J87.js} +1 -1
  26. package/dist/client/assets/SessionTerminal-D04kYRrT.js +2 -0
  27. package/dist/client/assets/SettingsModal-C0FY8MPW.css +1 -0
  28. package/dist/client/assets/{SettingsModal-rUQcSTJp.js → SettingsModal-Dm-ngbRr.js} +1 -1
  29. package/dist/client/assets/{SettingsModal-DmfMotcd.css → SettingsModal-Ds0Yj47X.css} +1 -1
  30. package/dist/client/assets/SettingsModal-xSLhH7Tr.js +21 -0
  31. package/dist/client/assets/{SettingsTextareaRow-BirlBcem.js → SettingsTextareaRow-CHPgocEp.js} +1 -1
  32. package/dist/client/assets/{SetupWizardModal-xnCBM9EL.js → SetupWizardModal-y88aXNIQ.js} +2 -2
  33. package/dist/client/assets/{SkillsView-O5U0ep50.js → SkillsView-CYyQW1Hv.js} +1 -1
  34. package/dist/client/assets/{WorkflowNodeEditor-BX4d2qqF.js → WorkflowNodeEditor-hYeoz1X8.js} +3 -3
  35. package/dist/client/assets/{agent-import-generation-DnqVkPkz.js → agent-import-generation-CjiYXzCr.js} +1 -1
  36. package/dist/client/assets/agentsOrgChartLayout-C0UP_X3z.js +1 -0
  37. package/dist/client/assets/app-BgpuMvTU.js +13 -0
  38. package/dist/client/assets/app-BlexHhbW.js +13 -0
  39. package/dist/client/assets/app-BsuUOR0P.js +13 -0
  40. package/dist/client/assets/app-DQVOujmO.js +13 -0
  41. package/dist/client/assets/app-DjyTRx1N.js +5 -0
  42. package/dist/client/assets/app-Dniggype.js +13 -0
  43. package/dist/client/assets/app-EV-lyZ0T.js +5 -0
  44. package/dist/client/assets/{architectureDiagram-3BPJPVTR-gi467xY0.js → architectureDiagram-3BPJPVTR-Dd6GPcqM.js} +1 -1
  45. package/dist/client/assets/{blockDiagram-GPEHLZMM-B_gpcYiR.js → blockDiagram-GPEHLZMM-CC6pLxlz.js} +1 -1
  46. package/dist/client/assets/{c4Diagram-AAUBKEIU-DeylEYsQ.js → c4Diagram-AAUBKEIU-DxMP_l6y.js} +1 -1
  47. package/dist/client/assets/channel-DlCEMoEf.js +1 -0
  48. package/dist/client/assets/{chunk-2J33WTMH-BL2WY0HN.js → chunk-2J33WTMH-BKYToL43.js} +1 -1
  49. package/dist/client/assets/{chunk-4BX2VUAB-BkLExGMe.js → chunk-4BX2VUAB-Bg6rjQb3.js} +1 -1
  50. package/dist/client/assets/{chunk-55IACEB6-CSTvCF5T.js → chunk-55IACEB6-CPUwbbGa.js} +1 -1
  51. package/dist/client/assets/{chunk-727SXJPM-9J8pKk4x.js → chunk-727SXJPM-DScQBCvv.js} +1 -1
  52. package/dist/client/assets/{chunk-AQP2D5EJ-DXC1vPWr.js → chunk-AQP2D5EJ-DbX7uaXK.js} +1 -1
  53. package/dist/client/assets/{chunk-FMBD7UC4-CFRUb-zD.js → chunk-FMBD7UC4-DvYKea1c.js} +1 -1
  54. package/dist/client/assets/{chunk-ND2GUHAM-B87HFYS8.js → chunk-ND2GUHAM-CH-Tvw7w.js} +1 -1
  55. package/dist/client/assets/{chunk-QZHKN3VN-CTjHiGbd.js → chunk-QZHKN3VN-CbyEvOoM.js} +1 -1
  56. package/dist/client/assets/classDiagram-4FO5ZUOK-Bc92O8Ks.js +1 -0
  57. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-Bc92O8Ks.js +1 -0
  58. package/dist/client/assets/{cose-bilkent-S5V4N54A-D3Edq3L9.js → cose-bilkent-S5V4N54A-BPB5fV3A.js} +1 -1
  59. package/dist/client/assets/{dagre-BM42HDAG-CwwbeQfN.js → dagre-BM42HDAG-CilYJ3rR.js} +1 -1
  60. package/dist/client/assets/{dashboard-view-QxQwJFLz.js → dashboard-view-BnGe8cWo.js} +1 -1
  61. package/dist/client/assets/{dashboard-view-BLAoW3D4.js → dashboard-view-DnVf3tmI.js} +1 -1
  62. package/dist/client/assets/{dashboard-view-DAlJxqiJ.js → dashboard-view-DoLU6FxZ.js} +1 -1
  63. package/dist/client/assets/{dashboard-view-aPzfv99T.js → dashboard-view-dChSM_So.js} +1 -1
  64. package/dist/client/assets/{diagram-2AECGRRQ-koJWWXE4.js → diagram-2AECGRRQ-m9u1Qhyx.js} +1 -1
  65. package/dist/client/assets/{diagram-5GNKFQAL-Yob5cOKT.js → diagram-5GNKFQAL-DVr7Kf0N.js} +1 -1
  66. package/dist/client/assets/{diagram-KO2AKTUF-DelvFSkK.js → diagram-KO2AKTUF-D7sgJDFx.js} +1 -1
  67. package/dist/client/assets/{diagram-LMA3HP47-CMput2h2.js → diagram-LMA3HP47-DNKNDS6r.js} +1 -1
  68. package/dist/client/assets/{diagram-OG6HWLK6-04VXDl79.js → diagram-OG6HWLK6-1Bff4FWn.js} +1 -1
  69. package/dist/client/assets/{erDiagram-TEJ5UH35-C9iP8Uyp.js → erDiagram-TEJ5UH35-DGua1UHN.js} +1 -1
  70. package/dist/client/assets/{flowDiagram-I6XJVG4X-DENQvu_t.js → flowDiagram-I6XJVG4X-UDfDtwsE.js} +1 -1
  71. package/dist/client/assets/{folder-open-D-554oji.js → folder-open-CteOypVk.js} +1 -1
  72. package/dist/client/assets/{ganttDiagram-6RSMTGT7-BqOttZAT.js → ganttDiagram-6RSMTGT7-COdmD328.js} +1 -1
  73. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-CDcydi-5.js → gitGraphDiagram-PVQCEYII-SUSls7Kw.js} +1 -1
  74. package/dist/client/assets/index-0ovTXt3t.css +1 -0
  75. package/dist/client/assets/index-DpCHwyiD.js +2818 -0
  76. package/dist/client/assets/{infoDiagram-5YYISTIA-B5LQQnxt.js → infoDiagram-5YYISTIA-e_DloXj7.js} +1 -1
  77. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-DpFEt7D2.js → ishikawaDiagram-YF4QCWOH-DVWqihXg.js} +1 -1
  78. package/dist/client/assets/{journeyDiagram-JHISSGLW-MELtgu22.js → journeyDiagram-JHISSGLW-BcPY-XP0.js} +1 -1
  79. package/dist/client/assets/{kanban-definition-UN3LZRKU-h33PLATd.js → kanban-definition-UN3LZRKU-BCFG2Jle.js} +1 -1
  80. package/dist/client/assets/{mermaid.core-Dk2mUPOq.js → mermaid.core-5yPje9Bi.js} +4 -4
  81. package/dist/client/assets/{mindmap-definition-RKZ34NQL-B_T4O2-B.js → mindmap-definition-RKZ34NQL-DDApeT3K.js} +1 -1
  82. package/dist/client/assets/{pieDiagram-4H26LBE5-B1YIFkRl.js → pieDiagram-4H26LBE5-N61_jyeP.js} +1 -1
  83. package/dist/client/assets/{puzzle-hvecxlpJ.js → puzzle-BkaCP30D.js} +1 -1
  84. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-BoGQR_hO.js → quadrantDiagram-W4KKPZXB-C5qHiApF.js} +1 -1
  85. package/dist/client/assets/{requirementDiagram-4Y6WPE33-BSDmUBIx.js → requirementDiagram-4Y6WPE33-C71okgzt.js} +1 -1
  86. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-Dz_GqOa5.js → sankeyDiagram-5OEKKPKP-B2iKyLjB.js} +1 -1
  87. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-B6twjYUH.js → sequenceDiagram-3UESZ5HK-DfdoYKKk.js} +1 -1
  88. package/dist/client/assets/{shield-alert-BX4WRJOv.js → shield-alert-BNSeDB8l.js} +1 -1
  89. package/dist/client/assets/standing-instructions-template-pZtzo1lK.js +20 -0
  90. package/dist/client/assets/standing-instructions-template-w7Ouw_37.css +1 -0
  91. package/dist/client/assets/{stateDiagram-AJRCARHV-DuwqWLx-.js → stateDiagram-AJRCARHV-lS-sUi12.js} +1 -1
  92. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-Bu8Sk187.js → stateDiagram-v2-BHNVJYJU-DXJNDrV9.js} +1 -1
  93. package/dist/client/assets/{timeline-definition-PNZ67QCA-BS6VnqSI.js → timeline-definition-PNZ67QCA-CCwvX81K.js} +1 -1
  94. package/dist/client/assets/{upload-CaDoyaMW.js → upload-CDovVbu2.js} +1 -1
  95. package/dist/client/assets/useDiscoveredSkillsCache-BYqP-afh.js +1 -0
  96. package/dist/client/assets/{users-C5uCLwVM.js → users-CTqECGLo.js} +1 -1
  97. package/dist/client/assets/{vennDiagram-CIIHVFJN-CUbzqT5Y.js → vennDiagram-CIIHVFJN-DaiR5nv9.js} +1 -1
  98. package/dist/client/assets/{wardley-L42UT6IY-Mv-NotFS.js → wardley-L42UT6IY-hA5IHyPW.js} +1 -1
  99. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-DuYpvLZX.js → wardleyDiagram-YWT4CUSO-CILUNESc.js} +1 -1
  100. package/dist/client/assets/{xychartDiagram-2RQKCTM6-24_7QXdw.js → xychartDiagram-2RQKCTM6-72eNMmjz.js} +1 -1
  101. package/dist/client/index.html +2 -2
  102. package/dist/client/version.json +1 -1
  103. package/dist/droid-cli/package.json +1 -1
  104. package/dist/extension.js +10671 -6904
  105. package/dist/migrations/0059_fn_9037_tasks_source_agent_index.sql +3 -0
  106. package/dist/migrations/0060_fn_9059_workspace_coordination_leases.sql +10 -0
  107. package/dist/pi-claude-cli/package.json +1 -1
  108. package/dist/plugin-sdk/index.d.ts +190 -9
  109. package/dist/plugin-sdk/index.js +74 -28
  110. package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +83 -29
  111. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  112. package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +83 -29
  113. package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
  114. package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +74 -28
  115. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  116. package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +74 -28
  117. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  118. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +1096 -73
  119. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  120. package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +74 -28
  121. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  122. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +74 -28
  123. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  124. package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +83 -29
  125. package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
  126. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +302 -71
  127. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  128. package/dist/plugins/fusion-plugin-linear-import/bundled.js +74 -28
  129. package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
  130. package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +83 -29
  131. package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
  132. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +74 -28
  133. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  134. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +74 -28
  135. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  136. package/dist/plugins/fusion-plugin-quality/bundled.js +176 -46
  137. package/dist/plugins/fusion-plugin-quality/package.json +1 -1
  138. package/dist/plugins/fusion-plugin-reports/bundled.js +74 -28
  139. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  140. package/dist/plugins/fusion-plugin-roadmap/bundled.js +74 -28
  141. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  142. package/dist/plugins/fusion-plugin-todos/bundled.js +74 -28
  143. package/dist/plugins/fusion-plugin-todos/package.json +1 -1
  144. package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +74 -28
  145. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  146. package/package.json +1 -1
  147. package/skill/fusion/references/extension-tools.md +2 -0
  148. package/dist/client/assets/AgentDetailView-T767kKTg.js +0 -13
  149. package/dist/client/assets/AgentsView-6Ifu7qDr.js +0 -24
  150. package/dist/client/assets/ChatView-BV3lixQi.js +0 -13
  151. package/dist/client/assets/CommandCenter-CE4rYjHn.css +0 -1
  152. package/dist/client/assets/DocumentsView-pbERA7O-.js +0 -1
  153. package/dist/client/assets/EvalsView-DJQ4ltCg.js +0 -1
  154. package/dist/client/assets/ExperimentalAgentOnboardingModal-BwJuzkzB.js +0 -1
  155. package/dist/client/assets/InsightsView-CJgI0J7S.js +0 -11
  156. package/dist/client/assets/MemoryView-BHq1AHPu.js +0 -3
  157. package/dist/client/assets/PluginManager-k7hV7_9e.js +0 -1
  158. package/dist/client/assets/SessionTerminal-BRf6r4Vp.js +0 -2
  159. package/dist/client/assets/SettingsModal-B30rPfYC.css +0 -1
  160. package/dist/client/assets/SettingsModal-D0RBeZik.js +0 -21
  161. package/dist/client/assets/agentsOrgChartLayout-CKuzbhFf.js +0 -1
  162. package/dist/client/assets/app-B2FwULu2.js +0 -5
  163. package/dist/client/assets/app-B6nJaqAl.js +0 -13
  164. package/dist/client/assets/app-CGXZeIRc.js +0 -13
  165. package/dist/client/assets/app-CGtkeBF5.js +0 -13
  166. package/dist/client/assets/app-CNzN1Plu.js +0 -13
  167. package/dist/client/assets/app-DLs-f5yM.js +0 -13
  168. package/dist/client/assets/app-DsvtcRUG.js +0 -5
  169. package/dist/client/assets/channel-BoE8DeM4.js +0 -1
  170. package/dist/client/assets/classDiagram-4FO5ZUOK-qnbLX_9_.js +0 -1
  171. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-qnbLX_9_.js +0 -1
  172. package/dist/client/assets/index-CXTd3LAB.css +0 -1
  173. package/dist/client/assets/index-CtYRoouR.js +0 -2818
  174. package/dist/client/assets/standing-instructions-template-BJY317CC.js +0 -20
  175. package/dist/client/assets/standing-instructions-template-Ddi_4TIk.css +0 -1
@@ -0,0 +1,13 @@
1
+ import{r as a,j as t}from"./vendor-react-SZ_qB27O.js";import{c as si,S as mn,r as jt,e as Rs,cJ as js,du as Xi,dv as qi,dw as da,b as Q,dx as Gi,dy as Dt,dz as At,dA as ya,dB as Qi,dC as Yi,dD as Ji,dE as Zi,dF as eo,dG as to,bh as no,c_ as Ca,dH as Ce,db as ao,cv as ii,c3 as wn,dI as so,dJ as io,ar as yn,dK as oo,dL as ro,bS as co,K as lo,aK as uo,b3 as xn,a2 as mo,d9 as ho,dM as fo,aY as go,dN as po,dO as oi,dP as ri,dQ as vo,dR as bo,W as xo,dS as wo,dT as yo,dU as As,dV as Co,dW as ko,dX as Ts,G as So,dY as Mo,z as No,B as Ro,aI as jo,dZ as ua,C as hn,d_ as fn,d$ as Es,cW as Ds,D as ma,P as pt,V as Ao,bU as Is,de as Ls,dd as To,X as Ps,aJ as Eo,e0 as Do,F as ha,e1 as fa,e2 as Fs,e3 as ga,e4 as $s,e5 as _s,e6 as zs,e7 as Io,dj as ci,e8 as Lo,cV as Bs}from"./index-DpCHwyiD.js";import{u as _e}from"./vendor-i18n-Duky4gdQ.js";import{SessionTerminal as Os}from"./SessionTerminal-D04kYRrT.js";import{u as Po}from"./useDiscoveredSkillsCache-BYqP-afh.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";import"./shield-alert-BNSeDB8l.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 Fo=[["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"}]],li=si("hash",Fo);/**
7
+ * @license lucide-react v1.7.0 - ISC
8
+ *
9
+ * This source code is licensed under the ISC license.
10
+ * See the LICENSE file in the root directory of this source tree.
11
+ */const $o=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],_o=si("tag",$o);function gn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function zo(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function pa(i,r){const h=zo(),p=r?.warm===!0,m=gn(),f=new Map;let M=!1,C=!1;return{mark(I){M||C||!h||f.has(I)||f.set(I,gn())},complete:I=>{if(!h||M||C){M=!0;return}M=!0,f.set("complete",gn());const D=Array.from(f.entries()).sort((A,N)=>A[1]-N[1]);let k=m;const s={};for(const[A,N]of D)s[A]=Math.max(0,N-k),k=N;const v=Math.max(0,gn()-m);try{console.debug("[room-open]",{roomId:i,warm:p,totalMs:v,phases:s,...I??{}})}catch{}},cancel(){C=!0,M=!0}}}const $e="fusion:chat-active-room";class di extends Error{roomId;constructor(r,h){super(r),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=h}}function ka(i){return[...i].sort((r,h)=>new Date(h.updatedAt).getTime()-new Date(r.updatedAt).getTime())}function Ge(i,r){const h=i.findIndex(m=>m.id===r.id);if(h===-1)return ka([r,...i]);const p=[...i];return p[h]=r,ka(p)}function Ie(i){try{return JSON.parse(i.data)}catch{return null}}function va(i){return i.slice().reverse()}function Bo(i,r,h){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:i,role:"user",content:r,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...h?.length?{attachments:h}:{},createdAt:new Date().toISOString()}}function Hs(i,r,h){if(i.some(m=>m.id===r.id))return i;const p=h?i.findIndex(m=>m.id===h):-1;if(p>=0){const m=[...i];return m[p]=r,m}if(r.role==="user"){const m=i.findIndex(f=>f.role==="user"&&f.id.startsWith("temp-")&&f.content.trim()===r.content.trim());if(m>=0){const f=[...i];return f[m]=r,f}}return[...i,r]}function Oo(i,r){const{t:h}=_e("app"),p=`${mn.CHAT_ROOMS}:${i??"global"}`,m=`${mn.ACTIVE_CHAT_ROOM_ID}:${i??"global"}`,f=a.useCallback(c=>`${mn.CHAT_ROOM_MESSAGES_PREFIX}${i??"global"}:${c}`,[i]),M=a.useCallback(c=>`${mn.CHAT_ROOM_MEMBERS_PREFIX}${i??"global"}:${c}`,[i]),[C,b]=a.useState(()=>{const c=jt(p,{maxAgeMs:Rs});return Array.isArray(c)?c:[]}),[I,D]=a.useState(()=>C.length===0),[k,s]=a.useState(null),[v,A]=a.useState(()=>{const c=jt(m,{maxAgeMs:js});return c?C.find(S=>S.id===c)??null:null}),[N,y]=a.useState([]),[l,P]=a.useState([]),[$,U]=a.useState(!1),B=a.useRef(C),j=a.useRef(v),Y=a.useRef(0),se=a.useRef(i);B.current=C,j.current=v,se.current!==i&&(se.current=i,Y.current+=1);const J=a.useCallback(async c=>{if(!c){y([]),P([]),U(!1);return}const S=pa(c.id,{warm:!1});S.mark("select");const g=jt(f(c.id),{maxAgeMs:Xi}),u=jt(M(c.id),{maxAgeMs:Rs}),T=Array.isArray(g)&&g.length>0,L=Array.isArray(u)&&u.length>0;T||L?(S.mark("cache-hit"),T&&(P(g),S.mark("hydrate")),L&&y(u),U(!1)):(P([]),U(!0));try{const[W,ve]=await Promise.all([qi(c.id,i),da(c.id,{limit:100,order:"desc"},i)]);S.mark("members-fetch"),S.mark("messages-fetch"),Q(M(c.id),W.members,{maxBytes:5e5});const ee=va(ve.messages);Q(f(c.id),ee,{maxBytes:5e5}),j.current?.id===c.id&&(y(W.members),P(ee),S.mark("hydrate"))}catch{!T&&!L&&(y([]),P([]))}finally{U(!1),S.complete({warm:T,membersCached:L})}},[M,f,i]),E=a.useCallback(async()=>{B.current.length===0&&D(!0);try{const c=await Gi({},i),S=ka(c.rooms);b(S),Q(p,S,{maxBytes:5e5}),s(null);const g=jt(m,{maxAgeMs:js})??Dt($e,i);if(g){const u=S.find(T=>T.id===g)??null;u?(A(u),J(u)):(At($e,i),Q(m,"",{maxBytes:5e5}))}}catch(c){const S=c instanceof Error?c.message:h("chatRooms.error.failedToLoad","Failed to load chat rooms");s(S),r?.(S,"error")}finally{D(!1)}},[m,r,J,i,p]),O=a.useCallback(c=>{if(!c){j.current=null,A(null),At($e,i),Q(m,"",{maxBytes:5e5}),J(null);return}const S=B.current.find(g=>g.id===c)??null;j.current=S,A(S),S&&(ya($e,S.id,i),Q(m,S.id,{maxBytes:5e5}),J(S))},[m,J,i]),R=a.useCallback(async c=>{const g=(await Qi({name:c.name,memberAgentIds:c.memberAgentIds},i)).room;return b(u=>Ge(u,g)),j.current=g,A(g),ya($e,g.id,i),Q(m,g.id,{maxBytes:5e5}),await J(g),g},[m,J,i]),_=a.useCallback(async(c,S)=>{const u=(await Yi(c,S,i)).room;return b(T=>Ge(T,u)),j.current?.id===u.id&&(j.current=u,A(u)),u},[i]),ce=a.useCallback(async c=>{await Ji(c,i),b(S=>S.filter(g=>g.id!==c)),Q(f(c),[],{maxBytes:5e5}),Q(M(c),[],{maxBytes:5e5}),j.current?.id===c&&(j.current=null,A(null),y([]),P([]),At($e,i),Q(m,"",{maxBytes:5e5}))},[m,M,f,i]),ae=a.useCallback(async(c,S)=>{const g=j.current,u=g?.id;if(!u)throw new Error(h("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const T=pa(u,{warm:!1}),L=S?.files?.map(ee=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,filename:ee.name,originalName:ee.name,mimeType:ee.type||"application/octet-stream",size:ee.size,createdAt:new Date().toISOString()})),W=Bo(u,c,L?.length?L:S?.attachments);j.current?.id===u&&P(ee=>{const he=[...ee,W];return Q(f(u),he,{maxBytes:5e5}),he});let ve=!1;try{const ee=[];if(S?.files?.length)for(const fe of S.files)try{const ze=await Zi(u,fe,i);ee.push(ze.attachment)}catch{throw new Error(h("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:fe.name}))}const he=[...S?.attachments??[],...ee],ke=await eo(u,{content:c,...he.length?{attachments:he}:{}},i);ve=!0;try{S?.onDelivered?.()}catch{}ke.message?.createdAt&&g&&b(fe=>Ge(fe,{...g,updatedAt:ke.message.createdAt})),j.current?.id===u&&P(fe=>{const ze=Hs(fe,ke.message,W.id);return Q(f(u),ze,{maxBytes:5e5}),ze});const ie=await da(u,{limit:100,order:"desc"},i),Le=va(ie.messages);if(Q(f(u),Le,{maxBytes:5e5}),j.current?.id!==u)return;P(Le),T.mark("hydrate")}catch(ee){let he=null;try{const ie=await da(u,{limit:100,order:"desc"},i);he=va(ie.messages),Q(f(u),he,{maxBytes:5e5}),j.current?.id===u&&(P(he),T.mark("hydrate"))}catch{!ve&&j.current?.id===u&&P(ie=>{const Le=ie.filter(fe=>fe.id!==W.id);return Q(f(u),Le,{maxBytes:5e5}),Le})}const ke=he?.some(ie=>ie.role==="user"&&ie.content.trim()===W.content.trim());if(ve||ke){const ie=ee instanceof Error&&ee.message.trim()?ee.message:h("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new di(ie,u)}throw ee}finally{T.complete({source:"send-room-message"})}},[f,i]),me=a.useCallback(async c=>{!c||!B.current.some(S=>S.id===c)||(await to(c,i),Q(f(c),[],{maxBytes:5e5}),j.current?.id===c&&P([]))},[f,i]);return a.useEffect(()=>{E()},[E]),a.useEffect(()=>{const c=Y.current,S=i?`/api/events?projectId=${encodeURIComponent(i)}`:"/api/events";return no(S,{onReconnect:()=>{Ca({view:"useChatRooms",trigger:"sse-reconnect",projectId:i,replayAttempted:!1});const g=j.current?.id;if(g){const u=pa(g,{warm:!0});u.mark("sse-reconnect-refresh"),E().finally(()=>u.complete({source:"sse-reconnect"}));return}E()},events:{"chat:room:created":g=>{if(Y.current!==c)return;const u=Ie(g);u&&b(T=>Ge(T,u))},"chat:room:updated":g=>{if(Y.current!==c)return;const u=Ie(g);u&&(b(T=>Ge(T,u)),j.current?.id===u.id&&(j.current=u,A(u)))},"chat:room:deleted":g=>{if(Y.current!==c)return;const u=Ie(g);u?.id&&(b(T=>T.filter(L=>L.id!==u.id)),Q(f(u.id),[],{maxBytes:5e5}),Q(M(u.id),[],{maxBytes:5e5}),j.current?.id===u.id&&(j.current=null,A(null),y([]),P([]),At($e,i),Q(m,"",{maxBytes:5e5})))},"chat:room:member:added":g=>{if(Y.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||y(T=>{if(T.some(W=>W.agentId===u.agentId))return T;const L=[...T,u];return Q(M(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:member:removed":g=>{if(Y.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||y(T=>{const L=T.filter(W=>W.agentId!==u.agentId);return Q(M(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:message:added":g=>{if(Y.current!==c)return;const u=Ie(g);u&&(b(T=>{const L=T.find(W=>W.id===u.roomId);return L?Ge(T,{...L,updatedAt:u.createdAt}):T}),j.current?.id===u.roomId&&P(T=>{const L=Hs(T,u);return L===T?T:(Q(f(u.roomId),L,{maxBytes:5e5}),L)}))},"chat:room:message:updated":g=>{if(Y.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||P(T=>{const L=T.map(W=>W.id===u.id?u:W);return Q(f(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:message:deleted":g=>{if(Y.current!==c)return;const u=Ie(g);u?.id&&P(T=>{const L=T.filter(ve=>ve.id!==u.id),W=j.current?.id;return W&&Q(f(W),L,{maxBytes:5e5}),L})},"chat:room:messages:cleared":g=>{if(Y.current!==c)return;const u=Ie(g);u?.roomId&&(Q(f(u.roomId),[],{maxBytes:5e5}),j.current?.id===u.roomId&&P([]),b(T=>{const L=T.find(W=>W.id===u.roomId);return L?Ge(T,{...L,updatedAt:new Date().toISOString()}):T}))}}})},[m,M,f,i,E]),a.useEffect(()=>{v&&(C.some(c=>c.id===v.id)||(j.current=null,A(null),y([]),P([]),At($e,i),Q(m,"",{maxBytes:5e5})))},[v,m,i,C]),{rooms:C,roomsLoading:I,roomsError:k,activeRoom:v,activeRoomMembers:N,messages:l,messagesLoading:$,selectRoom:O,createRoom:R,updateRoomSettings:_,deleteRoom:ce,sendRoomMessage:ae,clearRoom:me,refreshRooms:E}}const Tt={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},Us=200;function Sa(i){if(!i)return null;const r=new Date(i).getTime();return Number.isFinite(r)?r:null}function ui(i){const r=Object.entries(i);if(r.length<=Us)return i;const h=r.map(([p,m])=>({id:p,timestamp:m,value:Sa(m)??0})).sort((p,m)=>m.value-p.value).slice(0,Us);return Object.fromEntries(h.map(({id:p,timestamp:m})=>[p,m]))}function pn(i){if(!i)return{};try{const r=JSON.parse(i);if(!r||typeof r!="object")return{};const h={};for(const[p,m]of Object.entries(r))typeof p=="string"&&typeof m=="string"&&(h[p]=m);return ui(h)}catch{return{}}}function Ho(i){const[r,h]=a.useState(()=>{try{return pn(Dt(Tt.direct,i))}catch{return{}}}),[p,m]=a.useState(()=>{try{return pn(Dt(Tt.room,i))}catch{return{}}});a.useEffect(()=>{try{h(pn(Dt(Tt.direct,i)))}catch{h({})}try{m(pn(Dt(Tt.room,i)))}catch{m({})}},[i]);const f=a.useMemo(()=>({direct:r,room:p}),[r,p]),M=a.useCallback((k,s)=>{const v=ui(s);try{ya(Tt[k],JSON.stringify(v),i)}catch{}return v},[i]),C=a.useCallback((k,s)=>{if(k==="direct"){h(v=>M(k,s(v)));return}m(v=>M(k,s(v)))},[M]),b=a.useCallback((k,s,v)=>{const A=Sa(v);if(A===null)return!1;const N=f[k][s],y=Sa(N);return y===null?!0:A>y},[f]),I=a.useCallback((k,s,v)=>{if(!s)return;const A=v??new Date().toISOString();C(k,N=>({...N,[s]:A}))},[C]),D=a.useCallback((k,s)=>{s.length!==0&&C(k,v=>{const A={...v};for(const N of s)N.id&&(A[N.id]=N.lastActivityAt??new Date().toISOString());return A})},[C]);return{isUnread:b,markRead:I,markAllRead:D}}const Uo=["",...so];function Ks({level:i,onChange:r,defaultThinkingLevel:h="off",showTargetSection:p=!0,models:m=[],favoriteProviders:f=[],favoriteModels:M=[],agents:C=[],agentId:b,modelProvider:I,modelId:D,onChangeModel:k,disabled:s=!1}){const{t:v}=_e("app"),[A,N]=a.useState(!1),[y,l]=a.useState(()=>b&&b!==Ce?"agent":"model"),P=a.useRef(null),$=i??"",U=I&&D?`${I}/${D}`:"",B=b&&b!==Ce?b:"",j=$!==""||p&&(!!U||!!B),Y="chat-thinking-level-listbox";a.useEffect(()=>{if(!A)return;const c=S=>{const g=S.target;if(!(g instanceof Node))return;!P.current?.contains(g)&&!io(g)&&N(!1)};return document.addEventListener("pointerdown",c),document.addEventListener("touchstart",c),()=>{document.removeEventListener("pointerdown",c),document.removeEventListener("touchstart",c)}},[A]),a.useEffect(()=>{N(!1),l(B?"agent":"model")},[$,B,U]);const se=a.useMemo(()=>C.find(c=>c.id===B),[C,B]),J=c=>c===""?v("modelSelection.thinkingDefault","Default ({{level}})",{level:h??"off"}):v(`models.options.${c}`,c==="xhigh"?"Very High":c.charAt(0).toUpperCase()+c.slice(1)),E=c=>{N(!1),r(c)},O=c=>{const S=c.indexOf("/");S<=0||(N(!1),k?.({modelProvider:c.slice(0,S),modelId:c.slice(S+1)}))},R=c=>{c&&(N(!1),k?.({agentId:c}))},_=c=>{l(c)},ce=c=>{c.key==="Escape"&&N(!1)},ae=(c,S)=>{if(c.key==="Escape"){c.preventDefault(),N(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),E(S))},me=(c,S)=>{if(c.key==="Escape"){c.preventDefault(),N(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),R(S))};return t.jsxs("div",{className:"chat-thinking-level-root",ref:P,children:[t.jsx("button",{type:"button",className:`btn-icon chat-thinking-btn${j?" chat-thinking-btn--active":""}`,"data-testid":"chat-thinking-btn","aria-haspopup":"dialog","aria-expanded":A,"aria-controls":Y,"aria-label":v("chat.thinkingLevelButton","Thinking level"),title:v("chat.thinkingLevelButton","Thinking level"),disabled:s,onClick:()=>N(c=>!c),onKeyDown:ce,children:t.jsx(ao,{size:16})}),A?t.jsxs("div",{className:"chat-thinking-popover",role:"presentation","data-testid":"chat-thinking-popover",children:[p?t.jsxs("section",{className:"chat-thinking-target-section","aria-label":v("chat.modelAgentSection","Model / Agent"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:v("chat.modelAgentSection","Model / Agent")}),t.jsxs("div",{className:"chat-thinking-mode-toggle","data-testid":"chat-thinking-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${y==="model"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-model","aria-pressed":y==="model",onPointerDown:c=>{c.button===0&&_("model")},onClick:c=>{c.detail===0&&_("model")},children:v("chat.newChatModeModel","Model")}),t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${y==="agent"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-agent","aria-pressed":y==="agent",onPointerDown:c=>{c.button===0&&_("agent")},onClick:c=>{c.detail===0&&_("agent")},children:v("chat.newChatModeAgent","Agent")})]}),y==="model"?t.jsxs("div",{className:"chat-thinking-model-picker","data-testid":"chat-thinking-model-picker",children:[t.jsx(ii,{models:m,value:U,onChange:O,label:v("chat.newChatModeModel","Model"),placeholder:v("chat.selectModel","Select a model"),disabled:!k||m.length===0,favoriteProviders:f,favoriteModels:M,menuWidth:"readable"}),m.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-model-empty",children:v("chat.noModelsAvailable","No models available")}):null]}):t.jsx("div",{className:"chat-thinking-agent-list","data-testid":"chat-thinking-agent-list",children:C.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-agent-empty",children:v("chat.noAgentsAvailable","No agents available")}):C.map(c=>{const S=B===c.id;return t.jsxs("button",{type:"button",className:`chat-thinking-agent-item${S?" chat-thinking-agent-item--selected":""}`,"data-testid":`chat-thinking-agent-${c.id}`,"aria-pressed":S,disabled:!k,onClick:()=>R(c.id),onKeyDown:g=>me(g,c.id),children:[t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thinking-agent-name",children:c.name||c.id}),c.role?t.jsx("span",{className:"chat-thinking-agent-role",children:c.role}):null]},c.id)})}),se?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-agent",children:v("chat.currentAgentTarget","Current agent: {{name}}",{name:se.name||se.id})}):U?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-model",children:v("chat.currentModelTarget","Current model: {{model}}",{model:U})}):t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-default",children:v("chat.currentDefaultTarget","Using the default chat target")})]}):null,t.jsxs("section",{className:"chat-thinking-level-section","aria-label":v("chat.thinkingLevelButton","Thinking level"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:v("chat.thinkingLevelSection","Thinking level")}),t.jsx("div",{id:Y,className:"chat-thinking-popover-list",role:"listbox","aria-label":v("chat.thinkingLevelButton","Thinking level"),children:Uo.map(c=>{const S=$===c;return t.jsx("button",{type:"button",role:"option","aria-selected":S,className:`chat-thinking-popover-option${S?" active":""}`,"data-testid":`chat-thinking-option-${c||"default"}`,onClick:()=>E(c),onKeyDown:g=>ae(g,c),children:J(c)},c||"default")})})]})]}):null]})}function Ws(i){return i.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function mi(i,r){const h=r.trim();if(!h)return!0;const p=Ws(h);return Ws(i).includes(p)||i.toLowerCase().includes(h.toLowerCase())}function Vs({agents:i,filter:r,highlightedIndex:h,visible:p,onSelect:m,position:f="below",roomMemberIds:M,roomName:C}){const{t:b}=_e("app"),I=a.useMemo(()=>i.filter(N=>mi(N.name,r)),[i,r]),D=!!M,k=D&&r.trim().length>0,s=a.useMemo(()=>D?I.filter(N=>M?.has(N.id)):I,[I,M,D]),v=a.useMemo(()=>D?I.filter(N=>!M?.has(N.id)):[],[I,M,D]),A=k?[...s,...v]:s;return p?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${f}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":b("agentMention.suggestionsLabel","Agent mention suggestions"),children:A.length===0?t.jsx("div",{className:"agent-mention-empty",children:b("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[D&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:C?b("agentMention.membersOf","Members of #{{roomName}}",{roomName:C}):b("agentMention.roomMembers","Room members")}),s.map((N,y)=>t.jsxs("button",{type:"button",className:`agent-mention-item${y===h?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${N.id}`,onMouseDown:l=>l.preventDefault(),onClick:()=>m(N),role:"option","aria-selected":y===h,children:[t.jsx(yn,{agent:N,size:20}),D&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":b("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:N.name}),t.jsx("span",{className:"agent-mention-role",children:N.role})]},N.id)),D&&!k&&v.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:b("agentMention.typeToSearch","Type to search other agents")}),D&&k&&v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:b("agentMention.otherAgents","Other agents")}),v.map((N,y)=>{const l=s.length+y;return t.jsxs("button",{type:"button",className:`agent-mention-item${l===h?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${N.id}`,onMouseDown:P=>P.preventDefault(),onClick:()=>m(N),role:"option","aria-selected":l===h,children:[t.jsx(yn,{agent:N,size:20}),t.jsx("span",{className:"agent-mention-name",children:N.name}),t.jsx("span",{className:"agent-mention-role",children:N.role})]},N.id)})]})]})}):null}function Ko(i,r){return i+r}function Wo({visible:i,position:r,tasks:h,files:p,selectedIndex:m,onSelectTask:f,onSelectFile:M,loading:C}){const{t:b}=_e("app");if(!i)return null;const I=h.length>0,D=p.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:r.top,left:r.left},"data-testid":"file-mention-popup",onMouseDown:k=>{k.preventDefault()},children:[C&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!C&&!I&&!D&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:b("fileMention.empty","No tasks or files found")}),!C&&(I||D)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[I&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:b("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":b("fileMention.taskMatches","Task matches"),children:h.map((k,s)=>{const v=s;return t.jsxs("li",{className:`file-mention-popup-item${v===m?" file-mention-popup-item--selected":""}`,onClick:()=>f(k),role:"option","aria-selected":v===m,"data-testid":`task-mention-item-${v}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(li,{})}),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:k.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${k.column}`,children:k.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:k.title})]})]},k.id)})})]}),D&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:b("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":b("fileMention.fileMatches","File matches"),children:p.map((k,s)=>{const v=Ko(h.length,s),A=oo(k.path);return t.jsxs("li",{className:`file-mention-popup-item${v===m?" file-mention-popup-item--selected":""}`,onClick:()=>M(k),role:"option","aria-selected":v===m,"data-testid":`file-mention-item-${v}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(ro,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:k.name}),A&&t.jsx("span",{className:"file-mention-popup-item-path",children:A})]})]},k.path)})})]})]})]})}function Vo(i,r=[],h){const p=i.trim().replace(/^#/,""),m=(M,C)=>h?h(M,C):C;if(!p)return{ok:!1,error:m("createRoom.nameRequired","Room name is required.")};if(/[A-Z]/.test(p))return{ok:!1,error:m("createRoom.lowercase","Use lowercase letters only.")};const f=p.toLowerCase();return f.length>80?{ok:!1,error:m("createRoom.maxLength","Room names can be at most 80 characters.")}:/^[a-z0-9_-]+$/.test(f)?/^[-_]|[-_]$/.test(f)?{ok:!1,error:m("createRoom.noEdgeChars","Room names cannot start or end with a hyphen or underscore.")}:r.some(M=>M.toLowerCase()===f)?{ok:!1,error:m("createRoom.duplicate","A room with this name already exists.")}:{ok:!0,name:f}:{ok:!1,error:m("createRoom.validChars","Use lowercase letters, numbers, hyphens, or underscores only.")}}function Xo({isOpen:i,onClose:r,onCreate:h,projectId:p,existingRoomNames:m=[]}){const{t:f}=_e("app"),[M,C]=a.useState(""),[b,I]=a.useState([]),[D,k]=a.useState(""),[s,v]=a.useState([]),[A,N]=a.useState(!1),[y,l]=a.useState(null),[P,$]=a.useState(!1),U=a.useRef(null),B=a.useRef(null);a.useEffect(()=>{i&&(B.current=document.activeElement instanceof HTMLElement?document.activeElement:null,N(!0),l(null),co(void 0,p).then(R=>I(R)).catch(()=>{I([]),l(f("createRoom.failedLoadAgents","Failed to load agents."))}).finally(()=>N(!1)))},[i,p]),a.useEffect(()=>{if(!i){C(""),k(""),v([]),l(null),$(!1);return}const R=window.requestAnimationFrame(()=>U.current?.focus());return()=>window.cancelAnimationFrame(R)},[i]),a.useEffect(()=>{if(!i)return;const R=_=>{_.key==="Escape"&&r()};return document.addEventListener("keydown",R),()=>document.removeEventListener("keydown",R)},[i,r]),a.useEffect(()=>{i||B.current?.focus()},[i]);const j=a.useMemo(()=>Vo(M,m,f),[M,m,f]),Y=a.useMemo(()=>{const R=D.trim().toLowerCase();return R?b.filter(_=>_.name.toLowerCase().includes(R)):b},[b,D]),se=a.useMemo(()=>b.filter(R=>s.includes(R.id)),[b,s]),J=j.ok&&s.length>0&&!P&&!A;if(!i)return null;const E=R=>{P||v(_=>_.includes(R)?_.filter(ce=>ce!==R):[..._,R])},O=async()=>{if(!j.ok){l(j.error);return}if(s.length===0){l(f("createRoom.selectMember","Select at least one member."));return}l(null),$(!0);try{await h({name:j.name,displayName:`#${j.name}`,memberAgentIds:s}),r()}catch(R){l(R instanceof Error?R.message:f("createRoom.failedCreate","Failed to create room."))}finally{$(!1)}};return t.jsx(lo,{windowKey:"create-room",title:f("createRoom.title","Create room"),ariaLabel:f("createRoom.title","Create room"),onClose:r,modal:!0,hideHeader:!0,dragHandleSelector:".modal-header",className:"floating-window--create-room",defaultSize:{width:640,height:640},minSize:{width:360,height:400},persistGeometryKey:"floating-window:create-room",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,layer:"utility",children:t.jsxs("div",{className:"modal create-room-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:f("createRoom.title","Create room")}),t.jsx("button",{type:"button",className:"modal-close","aria-label":f("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:f("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:U,id:"create-room-name",className:"input",value:M,disabled:P,onChange:R=>{const _=R.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();C(_)}})]}),!j.ok&&t.jsx("div",{className:"form-error",children:j.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:f("createRoom.members","Members")}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:f("createRoom.searchAgents","Search agents"),value:D,disabled:P,onChange:R=>k(R.target.value)})]}),se.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:se.map(R=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>E(R.id),disabled:P,children:[R.name," ×"]},R.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:A?t.jsx("div",{className:"create-room-modal-empty",children:t.jsx(uo,{label:f("createRoom.loadingAgents","Loading agents...")})}):Y.length===0?t.jsx("div",{className:"create-room-modal-empty",children:b.length===0?f("createRoom.noAgents","No agents in this project yet."):f("createRoom.noMatch","No agents match your search.")}):Y.map(R=>{const _=s.includes(R.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${_?" create-room-modal-member-row--selected":""}`,onClick:()=>E(R.id),disabled:P,children:[t.jsx(yn,{agent:R,size:20}),t.jsx("span",{children:R.name}),t.jsx("span",{className:"create-room-modal-member-role",children:R.role})]},R.id)})}),y&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:y})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:P,children:f("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void O(),disabled:!J,children:P?f("createRoom.creating","Creating..."):f("createRoom.create","Create room")})]})]})})}function qo({cliSessionId:i,tier:r,projectId:h,renderTranscript:p,renderComposer:m,queuedCount:f=0,terminalProps:M}){const{t:C}=_e("app"),b=r==="generic",[I,D]=a.useState(b?"terminal":"transcript");if(b)return t.jsx("div",{className:"cli-chat-surface cli-chat-surface--generic","data-tier":"generic",children:t.jsx(Os,{sessionId:i,projectId:h,...M})});const k=I==="terminal";return t.jsxs("div",{className:"cli-chat-surface","data-tier":r,"data-view":I,children:[t.jsxs("div",{className:"cli-chat-surface__toolbar",role:"tablist","aria-label":C("cliChat.viewToggleLabel","Chat view"),children:[t.jsxs("button",{type:"button",role:"tab","aria-selected":!k,className:`cli-chat-surface__tab${k?"":" is-active"}`,onClick:()=>D("transcript"),children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:C("cliChat.transcriptTab","Transcript")})]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":k,className:`cli-chat-surface__tab${k?" is-active":""}`,onClick:()=>D("terminal"),children:[t.jsx(mo,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:C("cliChat.terminalTab","Terminal")})]})]}),t.jsx("div",{className:"cli-chat-surface__body",children:k?t.jsx(Os,{sessionId:i,projectId:h,...M}):p()}),!k&&t.jsxs("div",{className:"cli-chat-surface__composer",children:[f>0&&t.jsx("div",{className:"cli-chat-surface__queued",role:"status","aria-live":"polite",children:C("cliChat.queued","{{count}} message queued — will send when the agent is ready",{count:f})}),m()]})]})}const Go=200,Qo=8,Yo=8;function Xs(){return new DOMException("The operation was aborted.","AbortError")}function qs(i,r){return r.aborted?Promise.reject(Xs()):new Promise((h,p)=>{const m=()=>p(Xs());r.addEventListener("abort",m,{once:!0}),i.then(f=>{r.removeEventListener("abort",m),h(f)},f=>{r.removeEventListener("abort",m),p(f)})})}function Gs(i,r,h){const p=i.slice(0,r),m=i.slice(r+1),f=m.match(/[\s]|$/),M=f?f.index??m.length:m.length,C=m.slice(M);return`${p}${h}${C}`}function Jo(i={}){const{projectId:r,workspace:h="project"}=i,[p,m]=a.useState(!1),[f,M]=a.useState(""),[C,b]=a.useState(-1),[I,D]=a.useState([]),[k,s]=a.useState([]),[v,A]=a.useState(!1),[N,y]=a.useState(0),l=a.useRef(null),P=a.useRef(null),$=[...I.map(E=>({kind:"task",task:E})),...k.map(E=>({kind:"file",file:E}))];a.useEffect(()=>()=>{l.current&&clearTimeout(l.current),P.current?.abort()},[]);const U=a.useCallback((E,O)=>{if(O<0||O>E.length){m(!1);return}const R=_=>/[a-zA-Z0-9/_.-]/.test(_);for(let _=O-1;_>=0;_--){if(E[_]==="#"){if(_===0){const ae=E.slice(_+1,O);b(_),M(ae),y(0),m(!0);return}const ce=E[_-1];if(/[\s,.;:!?'"()[\]{}]/.test(ce)){const ae=E.slice(_+1,O);b(_),M(ae),y(0),m(!0);return}m(!1);return}if(!R(E[_])){m(!1);return}}m(!1)},[]),B=a.useCallback(()=>{P.current?.abort(),m(!1),M(""),b(-1),D([]),s([]),y(0),A(!1)},[]),j=a.useCallback(async E=>{if(!E.trim()){D([]),s([]),A(!1);return}P.current?.abort();const O=new AbortController;P.current=O;try{A(!0);const[R,_]=await Promise.allSettled([qs(ho(20,0,r,E),O.signal),qs(fo(E,h,r),O.signal)]);if(O.signal.aborted)return;const ce=R.status==="fulfilled"?R.value.slice(0,Qo).map(me=>({id:me.id,title:me.title??"",column:me.column})):[],ae=_.status==="fulfilled"?_.value.files.slice(0,Yo):[];D(ce),s(ae),y(0)}catch(R){R.name!=="AbortError"&&(D([]),s([]))}finally{O.signal.aborted||A(!1)}},[h,r]);a.useEffect(()=>{if(p)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{j(f)},Go),()=>{l.current&&clearTimeout(l.current)}},[f,p,j]);const Y=a.useCallback((E,O)=>!p||C<0?O:Gs(O,C,`#${E.id}`),[p,C]),se=a.useCallback((E,O)=>!p||C<0?O:Gs(O,C,`#${E.path}`),[p,C]),J=a.useCallback((E,O)=>{if(!p||$.length===0)return!1;switch(E.key){case"ArrowDown":return E.preventDefault(),y(R=>Math.min(R+1,$.length-1)),!0;case"ArrowUp":return E.preventDefault(),y(R=>Math.max(R-1,0)),!0;case"Enter":case"Tab":return $[N]?(E.preventDefault(),!0):!1;case"Escape":return E.preventDefault(),B(),!0;default:return!1}},[p,$,N,B]);return{mentionActive:p,tasks:I,files:k,combinedItems:$,loading:v,mentionQuery:f,selectedIndex:N,setSelectedIndex:y,detectMention:U,selectTask:Y,selectFile:se,dismissMention:B,handleKeyDown:J}}function Zo(i,r){const h=i.reduce((p,m)=>p+(m.content?.length??0),0)+(r?.length??0);return Math.ceil(h/4)}function Qs(i){if(!Number.isFinite(i)||i<=0)return"0";if(i<1e3)return String(Math.round(i));const r=i/1e3;return r<10?`~${Number(r.toFixed(1))}k`:`${Math.round(r)}k`}const Ma=640,er=200,tr=200,vt=8;function yr(i){const r=i.trim();return r?`${r}
12
+
13
+ `:""}function nr(i,r,h,p,m,f,M){const C=Math.max(vt,f-p-vt),b=Math.max(vt,M-m-vt),I=h?i-p:i;return{x:Math.min(Math.max(vt,I),C),y:Math.min(Math.max(vt,r),b)}}const Ys="__SKIP__";let ba=!1;function ar(i,r=Ma){return i>r?"auto":"hidden"}function sr(i,r=Ma){return Math.max(40,Math.min(i,r))}function ir(i,r){const h=new Date(i),m=new Date().getTime()-h.getTime(),f=Math.floor(m/1e3),M=Math.floor(f/60),C=Math.floor(M/60),b=Math.floor(C/24);return f<60?r("chat.relativeTimeJustNow","just now"):M<60?r("chat.relativeTimeMinutes","{{count}}m ago",{count:M}):C<24?r("chat.relativeTimeHours","{{count}}h ago",{count:C}):b<7?r("chat.relativeTimeDays","{{count}}d ago",{count:b}):h.toLocaleDateString()}const or=280,vn=180,bn=500,Js="fusion:chat-sidebar-width",xa="fusion:chat-scope",rr="fusion:chat-draft:";function Zs(i,r){return i.slice(r+1).find(h=>h.role==="user")?.content}function ei(i,r){return r?`${rr}${i}:${r}`:null}function ti(i){if(!i)return"";try{return localStorage.getItem(i)??""}catch{return""}}const cr=["image/png","image/jpeg","image/gif","image/webp","video/mp4","video/webm","video/quicktime","text/plain","text/markdown","application/json","text/yaml","text/x-toml","text/csv","application/xml"],ni="image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm,video/quicktime,.txt,.md,.json,.yaml,.yml,.toml,.csv,.xml",wa=Io;function lr(i,r){const h=i.slice(0,r),p=/(^|[\s\n])@([\w-]*)$/.exec(h);if(!p)return null;const m=p[2]??"",f=h.length-m.length-1;return{filter:m,start:f,end:r}}function dr(i){const r=i?.runtimeConfig;if(!r||typeof r!="object")return null;const h=Reflect.get(r,"modelProvider"),p=Reflect.get(r,"modelId");return typeof h!="string"||h.trim().length===0||typeof p!="string"||p.trim().length===0?null:{provider:h,modelId:p}}function ai(i,r,h){if(i?.modelProvider&&i?.modelId)return{provider:i.modelProvider,modelId:i.modelId};const p=dr(r??void 0);return p||(h.provider&&h.modelId?{provider:h.provider,modelId:h.modelId}:null)}function ur({projectId:i,defaultModel:r,defaultKind:h,defaultAgentId:p,defaultThinkingLevel:m,defaultSelectedThinkingLevel:f,onClose:M,onCreate:C}){const{t:b}=_e("app"),[I,D]=a.useState(h??"agent"),{agents:k,loading:s}=oi(i),[v,A]=a.useState(p??""),{models:N,favoriteProviders:y,favoriteModels:l,loading:P,refresh:$}=ri(),U=r.provider&&r.modelId?`${r.provider}/${r.modelId}`:"",[B,j]=a.useState(U),[Y,se]=a.useState(f??""),[J,E]=a.useState(y),[O,R]=a.useState(l);a.useEffect(()=>{E(y)},[y]),a.useEffect(()=>{R(l)},[l]),a.useEffect(()=>{h&&D(h)},[h]),a.useEffect(()=>{p&&A(g=>g||p)},[p]),a.useEffect(()=>{U&&j(g=>g||U)},[U]),a.useEffect(()=>{f&&se(g=>g||f)},[f]);const _=a.useCallback(async g=>{const u=J,L=u.includes(g)?u.filter(W=>W!==g):[g,...u];E(L);try{await Bs({favoriteProviders:L,favoriteModels:O}),await $()}catch{E(u)}},[J,O,$]),ce=a.useCallback(async g=>{const u=O,L=u.includes(g)?u.filter(W=>W!==g):[g,...u];R(L);try{await Bs({favoriteProviders:J,favoriteModels:L}),await $()}catch{R(u)}},[O,J,$]),ae=B||U,me=g=>{if(g.preventDefault(),I==="agent"){if(!v)return;C({agentId:v});return}if(!ae)return;const u=ae.indexOf("/");if(u<=0)return;const T=ae.slice(0,u),L=ae.slice(u+1);C({agentId:Ce,modelProvider:T,modelId:L,thinkingLevel:Y||void 0})},c=I==="agent"?!v:!ae,S=ci(M,{enabled:!0});return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",...S,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("h3",{children:b("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${I==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{D("agent")},children:b("chat.newChatModeAgent","Agent")}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${I==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{D("model"),A(""),j(g=>g||U)},children:b("chat.newChatModeModel","Model")})]}),t.jsxs("form",{onSubmit:me,children:[I==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:[b("chat.newChatModeAgent","Agent"),s?t.jsx("div",{className:"chat-new-dialog-loading",children:b("chat.loadingAgents","Loading agents...")}):k.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:b("chat.noAgentsAvailable","No agents available")}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:k.map(g=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${v===g.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>A(g.id),"data-testid":`agent-option-${g.id}`,children:[t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:g.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:g.role})]},g.id))})]}),I==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:P?t.jsx("div",{className:"chat-new-dialog-loading",children:b("chat.loadingModels","Loading models...")}):t.jsx(ii,{models:N,value:B,onChange:j,label:b("chat.newChatModeModel","Model"),placeholder:b("chat.selectModel","Select a model"),favoriteProviders:J,onToggleFavorite:_,favoriteModels:O,onToggleModelFavorite:ce,showThinkingLevel:!0,thinkingLevel:Y,onThinkingLevelChange:se,defaultThinkingLevel:m??"off"})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:M,children:b("chat.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:c,children:b("chat.create","Create")})]})]})]})})}function Et({children:i,onClose:r}){const h=ci(r,{enabled:!0});return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",...h,children:i})}function Cr({projectId:i,addToast:r,floating:h=!1,compactLayout:p=!1,onPopOut:m,onMaximize:f,onMinimize:M,onClose:C,chatCommandContext:b,initialComposerDraft:I,initialComposerDraftNonce:D,onSendAsReport:k}){const{t:s}=_e("app");a.useEffect(()=>(Ca({view:"ChatView",trigger:ba?"route-active":"remount",projectId:i,replayAttempted:!1}),ba=!1,()=>{ba=!0,Ca({view:"ChatView",trigger:"route-inactive",projectId:i,replayAttempted:!1})}),[i]);const[v,A]=a.useState(null);a.useEffect(()=>{let e=!1;return A(null),go(i).then(n=>{e||A(n)}).catch(()=>{e||A(null)}),()=>{e=!0}},[i]);const N=v?.defaultThinkingLevel??"off",y=a.useMemo(()=>v?.chatDefaultKind==="agent"&&v.chatDefaultAgentId?{kind:"agent",agentId:v.chatDefaultAgentId}:v?.chatDefaultKind==="model"&&v.chatDefaultModelProvider&&v.chatDefaultModelId?{kind:"model",modelProvider:v.chatDefaultModelProvider,modelId:v.chatDefaultModelId,thinkingLevel:v.chatDefaultThinkingLevel}:null,[v]),{activeSession:l,sessionsLoading:P,messages:$,messagesLoading:U,isStreaming:B,streamingText:j,streamingThinking:Y,streamingToolCalls:se,selectSession:J,createSession:E,archiveSession:O,archivedSessions:R,refreshArchivedSessions:_,unarchiveSession:ce,renameSession:ae,pinSession:me,pinnedCount:c,setSessionModel:S,setSessionThinkingLevel:g,deleteSession:u,tags:T=[],selectedTagId:L,setSelectedTagId:W,createTag:ve,renameTag:ee,deleteTag:he,setSessionTags:ke,sendMessage:ie,editMessageAndResend:Le,stopStreaming:fe,pendingMessages:ze,clearPendingMessage:Cn,loadMoreMessages:Na,hasMoreMessages:kn,searchQuery:hi,setSearchQuery:fi,filteredSessions:Be,agentsMap:Sn}=po(i,r),[gi,Mn]=a.useState(!1),Oe=!0,[F,Qe]=a.useState(()=>{try{if(localStorage.getItem(xa)==="rooms"&&Oe)return"rooms"}catch{}return"direct"}),w=Oo(i,r),{isUnread:Ra,markRead:de}=Ho(i),[q,oe]=a.useState(()=>{const e=ei(F,F==="rooms"?w.activeRoom?.id:l?.id);return ti(e)}),[G,Se]=a.useState(null),[Ye,pi]=a.useState(!1),Nn=a.useRef(null),ja=(e,n,o,d)=>{typeof window>"u"||Se({sessionId:e,anchorX:n,anchorY:o,anchorRight:d?.anchorRight??!1,x:n,y:o})};a.useLayoutEffect(()=>{if(!G||!Nn.current||typeof window>"u")return;const e=Nn.current,n=e.getBoundingClientRect(),o=n.width||e.offsetWidth||tr,d=n.height||e.offsetHeight,x=nr(G.anchorX,G.anchorY,G.anchorRight,o,d,window.innerWidth,window.innerHeight);(x.x!==G.x||x.y!==G.y)&&Se({...G,...x})},[G]);const[It,Lt]=a.useState(null),[Rn,jn]=a.useState(""),[Aa,Pt]=a.useState(null),[Ta,Ft]=a.useState(null),[An,Ea]=a.useState(""),[Tn,bt]=a.useState(null),[En,Da]=a.useState(""),[Ia,$t]=a.useState(null),[xt,He]=a.useState(!0),[Je,Dn]=a.useState(or),[vi,_t]=a.useState(!1),{agentsMap:La}=oi(i),be=a.useMemo(()=>Sn.size>0?Sn:La,[La,Sn]),{models:In,favoriteProviders:bi,favoriteModels:xi,defaultProvider:Pa,defaultModelId:Fa}=ri(),zt=a.useMemo(()=>({provider:Pa,modelId:Fa}),[Fa,Pa]),wi=a.useMemo(()=>y?.kind==="model"?{provider:y.modelProvider,modelId:y.modelId}:zt,[y,zt]),{skills:Ln,loading:yi}=Po(i),[Ze,Ue]=a.useState(!1),[wt,yt]=a.useState(""),[et,Ke]=a.useState(0),[tt,nt]=a.useState(""),[Me,at]=a.useState(!1),[Bt,Ot]=a.useState(0),[Pn,st]=a.useState(-1),[ge,Ht]=a.useState([]),[$a,it]=a.useState(!1),[_a,Ut]=a.useState(!1),[ot,za]=a.useState({}),[Kt,Ne]=a.useState(!1),[Wt,Ct]=a.useState(!1),{pushNav:Ba}=vo(),[,Vt]=a.useState(!1),[Ci,ki]=a.useState({top:0,left:0}),V=Jo({projectId:i}),Fn=a.useCallback(e=>{if(!e||!V.mentionActive)return;const n=e.getBoundingClientRect();ki({top:n.top-260,left:n.left+8})},[V.mentionActive]),Oa=a.useRef(null),Ha=a.useRef(null),Ua=a.useRef(null),Ka=a.useRef(null),le=a.useRef(!1),Xt=a.useRef(null),Wa=a.useRef(null),Pe=a.useRef(null),qt=a.useRef(0),$n=a.useRef(null),kt=a.useRef(null),Re=a.useRef(null),re=a.useRef(null),_n=a.useRef(null),rt=a.useRef(null),[zn,Si]=a.useState(()=>new Set),Gt=a.useRef(!1),je=a.useRef(null),Ae=a.useRef(null),Z=a.useRef(null),Qt=a.useRef(null),Va=a.useRef(void 0),Bn=a.useRef(!1),Yt=a.useRef(null),Xa=a.useRef([]),ct=a.useRef(0),St=a.useRef(new Map),On=a.useRef(!1),Jt=bo(),We=Jt==="mobile",Hn=Jt==="tablet",qa=a.useRef(null),[Mi,Ga]=a.useState(!1);a.useLayoutEffect(()=>{if(!h){Ga(!1);return}const e=qa.current;if(!e||typeof ResizeObserver>"u")return;const n=()=>{Ga(e.getBoundingClientRect().width<=768)};n();const o=new ResizeObserver(n);return o.observe(e),()=>o.disconnect()},[h]);const H=We||Mi||p;a.useEffect(()=>{l?.id&&de("direct",l.id,l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,de]),a.useEffect(()=>{w.activeRoom?.id&&de("room",w.activeRoom.id,w.activeRoom.updatedAt)},[w.activeRoom?.id,w.activeRoom?.updatedAt,de]),a.useEffect(()=>{if(!l?.id||$.length===0)return;const e=$[$.length-1];de("direct",l.id,e?.createdAt??l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,de,$]),a.useEffect(()=>{if(!w.activeRoom?.id||w.messages.length===0)return;const e=w.messages[w.messages.length-1];de("room",w.activeRoom.id,e?.createdAt??w.activeRoom.updatedAt)},[de,w.activeRoom?.id,w.activeRoom?.updatedAt,w.messages]),a.useEffect(()=>{try{const e=localStorage.getItem(Js);if(!e)return;const n=Number.parseInt(e,10);if(Number.isNaN(n))return;const o=Math.max(vn,Math.min(bn,n));Dn(o)}catch{}},[]),a.useEffect(()=>{try{const e=localStorage.getItem(xa);if(e==="direct"){Qe("direct");return}e==="rooms"&&Oe&&Qe("rooms")}catch{}},[Oe]),a.useEffect(()=>{try{localStorage.setItem(xa,F)}catch{}},[Oe,F]);const ue=ei(F,F==="rooms"?w.activeRoom?.id:l?.id),Un=a.useRef(ue),Kn=a.useRef(!1);a.useEffect(()=>{if(ue!==Un.current){if(Un.current=ue,Kn.current){Kn.current=!1;return}oe(ti(ue))}},[ue]),a.useEffect(()=>{if(!(!ue||Un.current!==ue))try{if(q){localStorage.setItem(ue,q);return}localStorage.removeItem(ue)}catch{}},[ue,q]);const te=F==="rooms"&&!!w.activeRoom,{keyboardOverlap:Qa,keyboardOpen:Zt}=xo({enabled:(H||Hn)&&(!!l||te),allowNonMobileViewport:Hn}),Mt=Hn&&Zt,en=a.useMemo(()=>{const e=wt.trim().toLowerCase();return(e?Ln.filter(o=>o.name.toLowerCase().includes(e)):Ln).slice(0,10)},[Ln,wt]),Wn=a.useMemo(()=>b?wo(wt,zs):[],[b,wt]),xe=a.useMemo(()=>{const e=Wn.map(o=>({kind:"command",command:o,disabled:!b?.agentRunning})),n=en.map(o=>({kind:"skill",skill:o}));return[...e,...n]},[Wn,en,b]),lt=a.useMemo(()=>Array.from(be.values()),[be]),Te=a.useMemo(()=>F!=="rooms"||!w.activeRoom?null:{roomId:w.activeRoom.id,roomName:w.activeRoom.name,memberIds:new Set(w.activeRoomMembers.map(e=>e.agentId))},[Oe,F,w.activeRoom,w.activeRoomMembers]),Ve=a.useMemo(()=>{const e=lt.filter(d=>mi(d.name,tt));if(!Te)return e;const n=e.filter(d=>Te.memberIds.has(d.id));if(tt.trim().length===0)return n;const o=e.filter(d=>!Te.memberIds.has(d.id));return[...n,...o]},[lt,tt,Te]),Vn=a.useMemo(()=>{const e=new Map;for(const n of lt)e.set(n.name.toLowerCase(),n);return e},[lt]),Ni=a.useMemo(()=>en.map(e=>e.id).join("\0"),[en]);a.useEffect(()=>{Ke(0)},[Ni]),a.useEffect(()=>{Ot(0)},[tt,Me]),a.useEffect(()=>()=>{Re.current!==null&&window.clearTimeout(Re.current)},[]),a.useEffect(()=>{const e=Ha.current;if(!e||!kn||U)return;const n=new IntersectionObserver(o=>{o[0].isIntersecting&&Na()},{threshold:.1});return n.observe(e),()=>n.disconnect()},[kn,U,Na]);const dt=a.useCallback(()=>te?w.activeRoom?.id??null:l?.id??null,[te,w.activeRoom?.id,l?.id]),Ya=a.useCallback((e,n)=>typeof CSS<"u"&&typeof CSS.escape=="function"?e.querySelector(`.chat-message[data-message-id="${CSS.escape(n)}"]`):e.querySelector(`.chat-message[data-message-id="${n.replace(/"/g,'\\"')}"]`),[]),Ja=a.useCallback(()=>{const e=re.current;if(!e)return;const n=e.getBoundingClientRect().top,o=new Set;e.querySelectorAll(".chat-message--assistant:not(.chat-message--failure)[data-message-id]").forEach(d=>{const x=d.getAttribute("data-message-id");x&&d.getBoundingClientRect().top<n&&o.add(x)}),Si(d=>d.size===o.size&&Array.from(d).every(x=>o.has(x))?d:o)},[]),tn=a.useCallback(()=>{!re.current||rt.current!==null||(rt.current=window.requestAnimationFrame(()=>{rt.current=null,Ja()}))},[Ja]),nn=a.useCallback(()=>{const e=re.current,n=dt();if(!e||!n)return;const o=e.scrollTop,d=e.querySelectorAll(".chat-message[data-message-id]"),x=Array.from(d).find(K=>K.offsetTop+K.offsetHeight>=o)??d[0]??null,z=x?.getAttribute("data-message-id")??null,X=x?x.offsetTop-o:0;kt.current={threadId:n,scrollTop:o,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,anchorMessageId:z,anchorOffset:X,wasPinnedBefore:!le.current,capturedAtMs:typeof performance<"u"?performance.now():Date.now()}},[dt]),Za=a.useCallback(()=>{const e=re.current;if(!e)return;const o=e.scrollTop+e.clientHeight>=e.scrollHeight-50;Ut(!o),le.current=!o,nn(),tn()},[nn,tn]),Ee=a.useCallback((e,n)=>{if(!e.isConnected||!n?.force&&le.current)return;let o=0,d=0,x=-1;const z=6,X=()=>{if(e.isConnected&&!(!n?.force&&le.current)){if(e.scrollTop=e.scrollHeight,e.scrollHeight===x?d+=1:(d=0,x=e.scrollHeight),o+=1,o>=z||d>=2){Ut(!1),le.current=!1;return}window.requestAnimationFrame(X)}};X()},[]),ut=te?w.messages:$;a.useLayoutEffect(()=>(tn(),()=>{rt.current!==null&&(window.cancelAnimationFrame(rt.current),rt.current=null)}),[ut,tn]),a.useLayoutEffect(()=>{const e=re.current,n=dt(),o=kt.current;if(!e||!n||!o||o.threadId!==n||o.wasPinnedBefore)return;const d=(typeof performance<"u"?performance.now():Date.now())-o.capturedAtMs,x=e.scrollHeight>e.clientHeight,z=d>3e3,X=o.scrollTop<=0&&o.anchorOffset<=0&&x;if(!le.current||z||X){kt.current=null;return}let K=o.scrollTop;if(o.anchorMessageId){const pe=Ya(e,o.anchorMessageId);pe?K=pe.offsetTop-o.anchorOffset:K=o.scrollTop+(e.scrollHeight-o.scrollHeight)}else K=o.scrollTop+(e.scrollHeight-o.scrollHeight);e.scrollTop=Math.max(0,K),le.current=!0,Ut(!0),kt.current=null},[ut,dt,Ya]);const Xn=a.useCallback(e=>{},[ut.length,te]),we=a.useCallback(e=>{Xn(e);const n=re.current;n&&(kt.current=null,le.current=!1,Ee(n))},[Ee,Xn]);a.useLayoutEffect(()=>{Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null);const e=te?w.activeRoom?.id??null:l?.id??null;if(!e){Xt.current=null;return}const n={threadId:e,loaded:te?!w.messagesLoading:!U,hasMessages:te?w.messages.length>0:$.length>0},o=Xt.current,d=o?.threadId!==e,x=o?.threadId===e&&!o.loaded&&n.loaded,z=o?.threadId===e&&!o.hasMessages&&n.hasMessages;if(!(o===null||d||x||z))return;const K=re.current;if(K)return Xn(d?"thread-change":x?"finished-loading":z?"first-messages":"mount"),Ee(K,{force:!0}),te||(Pe.current=window.setTimeout(()=>{if(Pe.current=null,le.current)return;const pe=re.current;pe&&Ee(pe)},250)),Xt.current=n,()=>{Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null)}},[te,w.activeRoom?.id,w.messages.length,w.messagesLoading,l?.id,$.length,U,Ee]),a.useEffect(()=>{!B||le.current||we("streaming")},[B,j,Y,we]),a.useEffect(()=>{const e=dt();if(!e){qt.current=0,$n.current=null;return}if($n.current!==e){$n.current=e,qt.current=ut.length;return}const n=qt.current,o=ut.length,d=o>n,x=!le.current;qt.current=o,d&&x&&we("new-message")},[ut,dt,we]),a.useEffect(()=>{Qa<=0||!re.current||we("keyboard")},[Qa,we]),yo(We&&Zt),a.useLayoutEffect(()=>{if(!We||!l&&!te||typeof window>"u")return;const e=_n.current,n=window.visualViewport;if(!e||!n)return;const o=x=>{if(!(x instanceof HTMLElement))return!1;if(x.tagName==="TEXTAREA")return!0;if(x.tagName!=="INPUT")return!1;const z=x.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(z)},d=()=>{if(Gt.current){e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange="";return}const x=Math.max(0,window.innerHeight-n.offsetTop-n.height),z=n.offsetTop||0;e.style.setProperty("--vv-height",`${n.height}px`),e.style.setProperty("--vv-offset-top",`${z}px`),e.style.setProperty("--keyboard-overlap",`${x}px`);const X=(x>0||z>0)&&o(document.activeElement);e.classList.toggle("chat-thread--keyboard-active",X),e.style.setProperty("--chat-keyboard-accessory-clearance",X&&ga()?"calc(var(--space-2xl) + var(--space-md))":"0px"),X&&z>0?(e.style.transform=`translateY(${z}px)`,e.style.willChange="transform"):(e.style.transform="",e.style.willChange="")};return d(),n.addEventListener("resize",d),n.addEventListener("scroll",d),document.addEventListener("focusin",d),document.addEventListener("focusout",d),window.addEventListener("pageshow",d),document.addEventListener("visibilitychange",d),()=>{n.removeEventListener("resize",d),n.removeEventListener("scroll",d),document.removeEventListener("focusin",d),document.removeEventListener("focusout",d),window.removeEventListener("pageshow",d),document.removeEventListener("visibilitychange",d),e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange=""}},[l,We,te]),a.useEffect(()=>{const e=()=>Se(null);if(G)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[G]),a.useEffect(()=>{if(!We||!Zt)return;const e=n=>{n.target?.closest(".chat-messages")||n.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[We,Zt]),a.useEffect(()=>{const e=Wa.current;if(Wa.current=F,F==="rooms"&&!w.activeRoom){Xt.current=null;return}if(!(F==="direct"&&(e===null||e==="rooms"))&&!(F==="rooms"&&(e===null||e==="direct")))return;const d=re.current;d&&(Ee(d,{force:!0}),le.current=!1,Ut(!1))},[F,w.activeRoom,Ee]),a.useEffect(()=>{if(!l&&!te||te&&!H)return;const e=()=>{const o=!le.current;nn(),o&&H&&re.current&&we("visibility-restore")},n=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pageshow",e)}},[H,We,l,te,nn,we]),a.useEffect(()=>{if(te||typeof ResizeObserver>"u")return;const e=re.current;if(!e)return;const n=new ResizeObserver(()=>{le.current||Ee(e)});return n.observe(e),()=>{n.disconnect()}},[te,Ee,l?.id,F]),a.useEffect(()=>{Xa.current=ge},[ge]),a.useEffect(()=>()=>{for(const e of Xa.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of St.current.values())window.clearTimeout(e);St.current.clear()},[]);const mt=a.useCallback(e=>{if(!e||e.length===0)return;const n=[];for(const o of Array.from(e)){if(!cr.includes(o.type))continue;const d=o.type.startsWith("image/");n.push({file:o,previewUrl:d?URL.createObjectURL(o):""})}n.length>0&&Ht(o=>[...o,...n])},[]),es=a.useCallback(e=>{Ht(n=>{const o=n[e];return o?.previewUrl&&URL.revokeObjectURL(o.previewUrl),n.filter((d,x)=>x!==e)})},[]),ts=a.useCallback(e=>{mt(e.clipboardData?.files)},[mt]),ht=a.useCallback(async e=>{try{return await E(e),Mn(!1),H&&He(!1),!0}catch{return r(s("chat.failedToCreateSession","Failed to create chat session"),"error"),!1}},[E,r,H,s]),an=a.useCallback(()=>{if(v?.chatNewSessionMode==="always-default"&&y){if(y.kind==="agent"){ht({agentId:y.agentId});return}ht({agentId:Ce,modelProvider:y.modelProvider,modelId:y.modelId,thinkingLevel:y.thinkingLevel});return}Mn(!0)},[y,v?.chatNewSessionMode,ht]),ne=a.useCallback(e=>{const n=e??Z.current;if(!n)return;const o=Jt==="tablet"?er:Ma;n.style.height="auto",n.style.height=`${sr(n.scrollHeight,o)}px`,n.style.overflowY=ar(n.scrollHeight,o)},[Jt]),Ri=As({textareaRef:Z,value:q,onChange:oe,onResize:()=>ne(Z.current),projectId:i}),ji=As({textareaRef:Qt,value:q,onChange:oe,onResize:()=>ne(Qt.current),projectId:i}),Ai=a.useCallback(e=>{Z.current=e,e&&ne(e)},[ne]),Ti=a.useCallback(e=>{Qt.current=e,e&&ne(e)},[ne]);a.useLayoutEffect(()=>{ne(F==="rooms"?Qt.current:Z.current),Bn.current&&(Bn.current=!1,Z.current?.focus())},[F,q,l?.id,w.activeRoom?.id,ne]),a.useEffect(()=>{if(D===void 0||D===Va.current||!I?.trim())return;Va.current=D;const e=n=>{n&&(Kn.current=!0),Qe("direct"),Bn.current=!0,oe(I)};if(!B&&v?.chatNewSessionMode==="always-default"&&y){const n=y.kind==="agent"?{agentId:y.agentId}:{agentId:Ce,modelProvider:y.modelProvider,modelId:y.modelId,thinkingLevel:y.thinkingLevel};ht(n).then(o=>e(o||F!=="direct"));return}e(F!=="direct")},[y,F,v?.chatNewSessionMode,ht,I,D,B,ne]);const ft=a.useCallback(()=>{if(oe(""),ue)try{localStorage.removeItem(ue)}catch{}Ue(!1),yt(""),at(!1),nt(""),st(-1),Ht(e=>{for(const n of e)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);return[]})},[ue]),Xe=a.useCallback(e=>{Ht(n=>{const o=n.filter(d=>e.has(d.file));for(const d of o)d.previewUrl&&URL.revokeObjectURL(d.previewUrl);return n.filter(d=>!e.has(d.file))})},[]),qn=a.useCallback(()=>{const e=q.trim(),n=ge.map(d=>d.file);if(!e&&n.length===0||!l)return;if(b){const d=Co(e,zs);if(d){if(!b.agentRunning){r(s("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}if(n.length>0){r(s("chat.commandNoAttachments","Attachments aren't supported with commands — remove them before sending"),"warning");return}ft(),d.command.run({taskId:b.taskId,projectId:b.projectId,remainder:d.remainder}).then(()=>{r(s("chat.commandSteerSuccess","Sent to the running agent"),"success")}).catch(x=>{const z=x instanceof Error&&x.message.trim()?x.message:s("chat.commandSteerFailed","Failed to send to the running agent");r(z,"error")});return}}if(e==="/clear"||e==="/new"){if(n.length>0){r(s("chat.clearNoAttachments","Remove the attachments before running /clear or /new — they would be discarded unsent"),"warning");return}if(l.agentId.startsWith(ko)){ft(),r(s("chat.newNotAllowedForTaskChat","This chat is tied to a task — /new and /clear can't clear it"),"warning");return}ft(),Cn(),fe(),E({agentId:l.agentId,modelProvider:l.modelProvider??void 0,modelId:l.modelId??void 0,thinkingLevel:l.thinkingLevel??void 0}).catch(()=>{r(s("chat.failedToClearConversation","Failed to clear conversation"),"error")});return}if(B&&n.length>0){r(s("chat.attachmentsNotQueued","Attachments can't be queued while a reply is streaming — wait for it to finish"),"warning");return}const o=new Set(n);oe("");try{ie(e,n,{onAccepted:()=>Xe(o),onDelivered:()=>Xe(o),onFailed:()=>{oe(d=>d||e)}})}catch{oe(e)}},[q,ge,l,ft,fe,Cn,E,r,ie,b,B,Xe,s]),Gn=a.useCallback(async()=>{const e=q.trim(),n=ge.map(o=>o.file);if(!(!e&&n.length===0)){if(F==="rooms"){if(!w.activeRoom)return;if(e==="/clear"||e==="/new"){if(n.length>0){r(s("chat.clearNoAttachments","Remove the attachments before running /clear or /new — they would be discarded unsent"),"warning");return}ft();try{await w.clearRoom(w.activeRoom.id)}catch{r(s("chat.failedToClearRoomConversation","Failed to clear room conversation"),"error")}return}if(On.current)return;On.current=!0;const o=q,d=new Set(n);oe("");try{await w.sendRoomMessage(e,{files:n,onDelivered:()=>Xe(d)}),Xe(d)}catch(x){if(x instanceof di){Xe(d);const X=x.message.trim()?x.message:s("chat.messageSentButReplyFailed","Message sent, but assistant reply failed");r(s("chat.messageSentButReplyFailedDetail","Message sent, but assistant reply failed: {{detail}}",{detail:X}),"error");return}oe(o);const z=x instanceof Error&&x.message.trim()?x.message:s("chat.failedToSendRoomMessage","Failed to send room message");r(z,"error")}finally{On.current=!1}return}qn()}},[q,ge,Oe,F,w,w.clearRoom,ft,r,qn,Xe]),sn=a.useCallback(async e=>{if(F==="rooms"){if(!w.activeRoom)return;try{await w.sendRoomMessage(e)}catch(n){const o=n instanceof Error&&n.message.trim()?n.message:s("chat.failedToSendRoomMessage","Failed to send room message");r(o,"error")}return}l&&ie(e)},[l,r,Oe,F,w,ie,s]),Qn=a.useCallback(e=>{oe(n=>{const o=wa(n);if(!o)return n;const d=`/skill:${e.name} `,x=n.slice(0,o.start)+d+n.slice(o.end);return window.requestAnimationFrame(()=>{Z.current&&(ne(Z.current),Z.current.focus())}),x}),Ue(!1),yt(""),Ke(0)},[ne]),Yn=a.useCallback((e,n)=>{if(n){r(s("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}oe(o=>{const d=wa(o);if(!d)return o;const x=`${e.trigger} `,z=o.slice(0,d.start)+x+o.slice(d.end);return window.requestAnimationFrame(()=>{Z.current&&(ne(Z.current),Z.current.focus())}),z}),Ue(!1),yt(""),Ke(0)},[ne,r,s]),on=a.useCallback(e=>{const n=Z.current;if(!n||Pn<0)return;const o=n.selectionStart??ct.current,d=n.selectionEnd??o,x=Math.max(o,d),z=Math.min(Pn,x),K=`${`@${e.name.replace(/\s+/g,"_")}`} `,pe=q.slice(0,z)+K+q.slice(x),gt=z+K.length;oe(pe),at(!1),nt(""),Ot(0),st(-1),window.requestAnimationFrame(()=>{Z.current&&(ne(Z.current),Z.current.focus(),Z.current.setSelectionRange(gt,gt))})},[Pn,q,ne]),Nt=a.useCallback((e,n)=>{const d=Z.current?.selectionStart??ct.current,x=q.lastIndexOf("#",d),z=x>=0?x+n.length:e.length;oe(e),V.dismissMention(),Vt(!1),window.requestAnimationFrame(()=>{Z.current&&(ne(Z.current),Z.current.focus(),Z.current.setSelectionRange(z,z))})},[V,q,ne]),ns=a.useCallback(e=>{if(ct.current=e.currentTarget.selectionStart??ct.current,V.mentionActive&&V.combinedItems.length>0){if(V.handleKeyDown(e,q),e.key==="Enter"||e.key==="Tab"){const n=V.combinedItems[V.selectedIndex];n?.kind==="task"?Nt(V.selectTask(n.task,q),`#${n.task.id}`):n?.kind==="file"&&Nt(V.selectFile(n.file,q),`#${n.file.path}`)}return}if(Me&&e.key==="ArrowDown"){e.preventDefault(),Ve.length>0&&Ot(n=>(n+1)%Ve.length);return}if(Me&&e.key==="ArrowUp"){e.preventDefault(),Ve.length>0&&Ot(n=>n===0?Ve.length-1:n-1);return}if(Me&&e.key==="Enter"){e.preventDefault();const n=Ve[Bt]??Ve[0];n&&on(n);return}if(Me&&e.key==="Escape"){e.preventDefault(),at(!1),nt(""),st(-1);return}if(Ze&&e.key==="ArrowDown"){e.preventDefault(),xe.length>0&&Ke(n=>(n+1)%xe.length);return}if(Ze&&e.key==="ArrowUp"){e.preventDefault(),xe.length>0&&Ke(n=>n===0?xe.length-1:n-1);return}if(Ze&&(e.key==="Enter"||e.key==="Tab")&&xe.length>0){e.preventDefault();const n=xe[et]??xe[0];n?.kind==="skill"?Qn(n.skill):n?.kind==="command"&&Yn(n.command,n.disabled);return}if(Ze&&e.key==="Escape"){e.preventDefault(),Ue(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Gn())},[Me,Ve,Bt,on,Ze,xe,et,Qn,Yn,Gn,V,Nt,q]),rn=a.useCallback((e,n)=>{const o=lr(e,n);if(o){at(!0),nt(o.filter),st(o.start);return}at(!1),nt(""),st(-1)},[]),as=a.useCallback(e=>{const n=e.target,o=n.value,d=n.selectionStart??o.length;ne(n),ct.current=d,oe(o);const x=wa(o);x?(Ue(!0),yt(x.filter)):(Ue(!1),yt("")),rn(o,d),V.detectMention(o,d),Vt(V.mentionActive),V.mentionActive&&Fn(n)},[rn,ne]),cn=a.useCallback(e=>{const n=e.currentTarget,o=n.selectionStart??n.value.length;ct.current=o,rn(n.value,o),V.detectMention(n.value,o),Vt(V.mentionActive),V.mentionActive&&Fn(n)},[rn,V,Fn]),ss=a.useCallback(e=>{e.key!=="Escape"&&cn(e)},[cn]),is=a.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(Gt.current=!0,je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{Gt.current=!1,je.current=null},450),(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0),Ae.current!==null&&window.clearTimeout(Ae.current),Ae.current=window.setTimeout(()=>{Ae.current=null,document.activeElement?.tagName!=="TEXTAREA"&&(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},350)),Re.current!==null&&window.clearTimeout(Re.current),Re.current=window.setTimeout(()=>{Ue(!1),at(!1),nt(""),st(-1),Vt(!1),V.dismissMention(),Re.current=null},120)},[V]),os=a.useCallback(()=>{Gt.current=!1,je.current!==null&&(window.clearTimeout(je.current),je.current=null),Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null),Ae.current!==null&&(window.clearTimeout(Ae.current),Ae.current=null)},[]);a.useEffect(()=>()=>{je.current!==null&&window.clearTimeout(je.current),Ae.current!==null&&window.clearTimeout(Ae.current)},[]);const rs=a.useCallback(async e=>{Se(null);try{await O(e),r(s("chat.conversationArchived","Conversation archived"),"success")}catch{r(s("chat.failedToArchiveConversation","Failed to archive conversation"),"error")}},[O,r]),Ei=a.useCallback(async e=>{try{await ce(e),r(s("chat.conversationRestored","Conversation restored"),"success")}catch{r(s("chat.failedToRestoreConversation","Failed to restore conversation"),"error")}},[ce,r,s]),cs=a.useCallback(e=>{const n=Be.find(o=>o.id===e)??(l?.id===e?l:null);Se(null),Ne(!1),jn(n?.title??""),Lt({sessionId:e,title:n?.title??""})},[l,Be]),ls=a.useCallback(async()=>{if(It)try{await ae(It.sessionId,Rn),Lt(null),jn(""),r(s("chat.conversationRenamed","Conversation renamed"),"success")}catch{}},[r,It,ae,Rn,s]),ds=a.useCallback(async(e,n)=>{Se(null),Ne(!1);try{await me(e,n),r(n?s("chat.conversationPinned","Conversation pinned"):s("chat.conversationUnpinned","Conversation unpinned"),"success")}catch{}},[r,me,s]),Di=a.useCallback(async e=>{Pt(null),Se(null);try{await u(e),r(s("chat.conversationDeleted","Conversation deleted"),"success")}catch{r(s("chat.failedToDeleteConversation","Failed to delete conversation"),"error")}},[u,r]),Rt=a.useCallback(e=>{try{localStorage.setItem(Js,String(e))}catch{}},[]),Ii=a.useCallback(e=>{if(H||Mt)return;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;typeof n.setPointerCapture=="function"&&n.setPointerCapture(e.pointerId);const o=e.clientX,d=Je;let x=d;document.body.style.userSelect="none";const z=K=>{const pe=K.clientX-o,gt=Math.max(vn,Math.min(bn,d+pe));x=gt,Dn(gt),Rt(gt)},X=K=>{typeof n.releasePointerCapture=="function"&&n.releasePointerCapture(K.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",z),document.removeEventListener("pointerup",X),Rt(x)};document.addEventListener("pointermove",z),document.addEventListener("pointerup",X)},[H,Rt,Je,Mt]),Li=a.useCallback(e=>{if(H||Mt||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const n=e.shiftKey?50:10,o=e.key==="ArrowLeft"?-n:n,d=Math.max(vn,Math.min(bn,Je+o));Dn(d),Rt(d)},[H,Rt,Je,Mt]),us=a.useCallback(e=>{const n=Be.find(o=>o.id===e);de("direct",e,n?.lastMessageAt??n?.updatedAt),J(e),Ne(!1),H&&He(!1)},[Be,H,de,J]),Jn=a.useCallback(()=>{J(""),He(!0),Ne(!1)},[J]),Zn=a.useCallback(()=>{w.selectRoom(null),He(!0),Ne(!1)},[w]),Pi=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(xn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:s("chat.startNewConversation","Start a new conversation")}),t.jsxs("button",{className:"btn btn-primary",onClick:an,children:[t.jsx(pt,{size:16}),s("chat.newChat","New Chat")]})]}),De=ai(l,l?.agentId?be.get(l.agentId)??null:null,zt),ea=a.useMemo(()=>{if(!De?.provider||!De.modelId)return null;const e=In.find(n=>n.provider===De.provider&&n.id===De.modelId);return e?.contextWindow?e.contextWindow:null},[De?.modelId,De?.provider,In]),Fi=a.useMemo(()=>Zo($,B?j:void 0),[B,$,j]),Fe=Ts(De?.provider,De?.modelId),qe=De?.provider??null,ta=!!(l||B||$.length>0),ln=H&&!xt&&(F==="rooms"?te:ta),dn=H?ln:F==="rooms"?te:!!l,ms=a.useRef(dn);a.useEffect(()=>{const e=ms.current;ms.current=dn,H&&(e||!dn||Ba({type:"view",revert:F==="rooms"?Zn:Jn}))},[F,Jn,Zn,dn,H,Ba]);const hs=l?.agentId===Ce?Fe??"Fusion":l?.title||be.get(l?.agentId??"")?.name||l?.agentId||"Chat",$i=l?.title||s("chat.untitledSession","Untitled"),_i=!!(Fe&&Fe!==hs),zi=!H&&ta&&ea!==null,fs=Qs(Fi),un=ea!==null?Qs(ea):null,na=un?s("chat.contextWindowAria","Estimated {{used}} of {{total}} context tokens",{used:fs,total:un}):null,Bi=ln&&F==="direct"&&!!l,gs=ln&&F==="direct",ps=ln&&F==="rooms",aa=be.get(l?.agentId??"")?.name||(l?.agentId===Ce?Fe??"Fusion":l?.agentId?.slice(0,30)??"Fusion"),sa=!1,ia=l?.agentId===Ce,Oi=e=>e.length>50?`${e.slice(0,50)}…`:e;a.useEffect(()=>{if(!Kt)return;const e=n=>{Ua.current?.contains(n.target)||Ne(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[Kt]),a.useEffect(()=>{if(!Wt)return;const e=o=>{Ka.current?.contains(o.target)||Ct(!1)},n=o=>{o.key==="Escape"&&Ct(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",n),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",n)}},[Wt]),a.useEffect(()=>{(!H||F!=="direct"||xt)&&Ne(!1)},[H,F,xt]),a.useEffect(()=>{Ct(!1)},[w.activeRoom?.id]);const vs=a.useCallback((e,n)=>{const o=St.current.get(e);o&&window.clearTimeout(o),za(x=>({...x,[e]:n}));const d=window.setTimeout(()=>{za(x=>{const{[e]:z,...X}=x;return X}),St.current.delete(e)},2e3);St.current.set(e,d)},[]),bs=a.useCallback(async(e,n)=>{const o=await So(n);vs(e,o?"success":"error")},[vs]),oa=l?.agentId===Ce,ra=a.useCallback((e,n,o,d,x=!0)=>{const z=oa&&o==="assistant",X=x&&o==="assistant"&&k?Mo(n,s("chat.reportFallbackTitle","Chat report")):null;if(!(!z&&!X?.handoff))return t.jsxs(t.Fragment,{children:[z&&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":d??`chat-copy-response-${e}`,"aria-label":ot[e]==="success"?s("chat.responseCopied","Response copied"):ot[e]==="error"?s("chat.copyFailed","Copy failed"):s("chat.copyResponse","Copy response"),onClick:()=>{bs(e,n)},children:ot[e]==="success"?t.jsx(No,{size:14}):t.jsx(Ro,{size:14})}),X?.handoff&&t.jsx("button",{type:"button",className:"btn-icon","data-testid":`chat-send-as-report-${e}`,"aria-label":s("chat.sendAsReport","Send as report"),onClick:()=>{X.truncated&&r(s("chat.reportTrimmed","Message trimmed to 2000 characters for mail"),"warning"),k?.(X.handoff)},children:t.jsx(jo,{size:14})})]})},[r,ot,bs,k,oa,s]),ca=a.useCallback(e=>{const n=re.current;if(!n)return;const o=`[data-testid="chat-message-${e}"]`,d=n.querySelector(o);if(!d)return;const x=d.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop,z=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;n.scrollTo({top:x,behavior:z?"auto":"smooth"})},[]),xs=l?.cliExecutorAdapterId??null,la=!!xs,Hi=xs==="generic"?"generic":"hybrid",Ui=l?.cliSessionFile||l?.id||"",ws=!la&&!B,ys=()=>t.jsxs("div",{className:"chat-messages",ref:re,onScroll:Za,children:[t.jsx("div",{ref:Ha,className:"chat-load-more-sentinel",children:kn&&U&&t.jsx("div",{className:"chat-loading-older",children:s("chat.loadingOlderMessages","Loading older messages…")})}),B?t.jsxs(t.Fragment,{children:[$.map((e,n)=>t.jsx(fa,{message:e,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,activeSessionId:l?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:null,copyAction:ra(e.id,e.content,e.role),onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===$.length-1&&!B,submittedQuestionAnswer:Zs($,n),onQuestionSubmit:sn,canEdit:ws,onEditMessage:Le},e.id)),t.jsx(Lo,{streamingText:j,streamingThinking:Y,streamingToolCalls:se,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,copyAction:oa&&j?ra("__streaming__",j,"assistant","chat-copy-response-streaming",!1):void 0,onQuestionSubmit:sn})]}):U?t.jsx("div",{className:"chat-empty-state",children:s("chat.loadingMessages","Loading messages...")}):$.length===0&&!l?Pi():$.length===0&&l?t.jsx("div",{className:"chat-empty-state",children:s("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsx(t.Fragment,{children:$.map((e,n)=>t.jsx(fa,{message:e,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,activeSessionId:l?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:null,copyAction:ra(e.id,e.content,e.role),onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===$.length-1&&!B,submittedQuestionAnswer:Zs($,n),onQuestionSubmit:sn,canEdit:ws,onEditMessage:Le},e.id))}),t.jsx("div",{ref:Oa})]}),Cs=()=>t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file","data-testid":"chat-file-input",accept:ni,multiple:!0,style:{display:"none"},onChange:e=>{mt(e.target.files),e.target.value=""}}),Ze&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":s("chat.skillSuggestions","Skill suggestions"),children:yi&&Wn.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:s("chat.loadingSkills","Loading skills…")}):xe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:wt?s("chat.noSkillsFound","No skills found"):s("chat.noSkillsAvailable","No skills available")}):xe.map((e,n)=>e.kind==="command"?t.jsxs("button",{type:"button",role:"option","aria-selected":n===et,"aria-disabled":e.disabled,className:`chat-skill-menu-item chat-command-menu-item${n===et?" chat-skill-menu-item--highlighted":""}${e.disabled?" chat-command-menu-item--disabled":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>Ke(n),onClick:()=>Yn(e.command,e.disabled),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.command.trigger}),t.jsx("span",{className:"chat-skill-menu-item-description",children:e.disabled?s("chat.commandNoRunningAgentHint","No running agent to steer"):e.command.description})]},`command-${e.command.trigger}`):t.jsxs("button",{type:"button",role:"option","aria-selected":n===et,className:`chat-skill-menu-item${n===et?" chat-skill-menu-item--highlighted":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>Ke(n),onClick:()=>Qn(e.skill),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.skill.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.skill.relativePath,children:e.skill.relativePath})]},e.skill.id))}),ge.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ge.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,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:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),ze.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-pending-stack","data-testid":"chat-pending-stack",children:ze.map((e,n)=>t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:s("chat.queuedMessage","Queued: {{preview}}",{preview:Oi(e)})}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":s("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":`chat-pending-dismiss-${n}`,onClick:()=>Cn(n),children:"×"})]},`${n}-${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":s("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Fs,{size:16})}),!la&&t.jsx(Ks,{level:l?.thinkingLevel,defaultThinkingLevel:N,models:In,favoriteProviders:bi,favoriteModels:xi,agents:Array.from(be.values()),agentId:l?.agentId,modelProvider:l?.modelProvider,modelId:l?.modelId,onChange:e=>{l&&g(l.id,e)},onChangeModel:e=>{l&&S(l.id,e)},disabled:!l}),t.jsxs("div",{className:`chat-input-wrapper${$a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),it(!0)},onDragLeave:()=>it(!1),onDrop:e=>{e.preventDefault(),it(!1),mt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:Ai,className:"chat-input-textarea",placeholder:s("chat.typeMessage","Type a message..."),value:q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:cn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ga()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Vs,{agents:lt,filter:tt,highlightedIndex:Bt,visible:Me,onSelect:on,position:"below",roomMemberIds:Te?.memberIds,roomName:Te?.roomName}),t.jsx(Wo,{visible:V.mentionActive&&!Me,position:Ci,tasks:V.tasks,files:V.files,selectedIndex:V.selectedIndex,onSelectTask:e=>{Nt(V.selectTask(e,q),`#${e.id}`)},onSelectFile:e=>{Nt(V.selectFile(e,q),`#${e.path}`)},loading:V.loading})]}),t.jsx($s,{...Ri.micProps}),t.jsx(_s,{isStreaming:B,canSend:!!(q.trim()||ge.length>0),onSend:qn,onStop:fe})]})]}),Ki=H?void 0:{width:`${Je}px`},ks=Ye?R:Be,Ss=ks.filter(e=>e.pinnedAt!=null),Ms=ks.filter(e=>e.pinnedAt==null),ye=G?Be.find(e=>e.id===G.sessionId)??(l?.id===G.sessionId?l:void 0):void 0,Ns=a.useCallback(async()=>{const e=An.trim();if(!e)return;let n;try{n=await ve(e)}catch{r(s("chat.failedToCreateTag","Failed to create tag"),"error");return}if(G?.sessionId){const o=(ye?.tags??[]).map(d=>d.id);if(!o.includes(n.id))try{await ke(G.sessionId,[...o,n.id])}catch{r(s("chat.failedToUpdateTags","Failed to update tags"),"error");return}}Ea("")},[r,G,ye,ve,An,ke,s]),Wi=Bi?t.jsxs("div",{className:"chat-mobile-session-menu",ref:Ua,children:[t.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":Kt,onClick:()=>Ne(e=>!e),children:[qe?t.jsx(ua,{provider:qe,size:"md"}):t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:$i}),t.jsx(hn,{size:16,"aria-hidden":"true"})]}),Kt&&t.jsxs("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:[[{id:"pinned",label:s("chat.pinned","Pinned"),testId:"chat-mobile-pinned-divider",sessions:Ss},{id:"recent",label:s("chat.recent","Recent"),testId:"chat-mobile-recent-divider",sessions:Ms}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-mobile-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>t.jsxs("div",{className:`chat-mobile-session-option-row${l?.id===n.id?" chat-mobile-session-option-row--active":""}`,role:"none",children:[t.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${l?.id===n.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${n.id}`,onClick:()=>us(n.id),children:t.jsxs("span",{className:"chat-mobile-session-option-title",children:[n.title||s("chat.untitledSession","Untitled"),n.pinnedAt?t.jsx(fn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":s("chat.pinned","Pinned")}):null]})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-pin","data-testid":`chat-mobile-session-pin-${n.id}`,"aria-label":n.pinnedAt?s("chat.unpinConversationAria","Unpin conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}):s("chat.pinConversationAria","Pin conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}),title:!n.pinnedAt&&c>=3?s("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:!n.pinnedAt&&c>=3,onClick:()=>ds(n.id,!n.pinnedAt),children:n.pinnedAt?t.jsx(Es,{size:14}):t.jsx(fn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-archive","data-testid":`chat-mobile-session-archive-${n.id}`,"aria-label":s("chat.archive","Archive"),onClick:()=>void rs(n.id),children:t.jsx(Ds,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-rename","data-testid":`chat-mobile-session-rename-${n.id}`,"aria-label":s("chat.renameConversationAria","Rename conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}),onClick:()=>cs(n.id),children:t.jsx(ma,{size:14})})]},n.id))]},e.id)),t.jsxs("button",{type:"button",role:"menuitem",className:"chat-mobile-session-new","data-testid":"chat-mobile-session-new",onClick:()=>{Ne(!1),an()},children:[t.jsx(pt,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.newChat","New Chat")})]})]})]}):null,Vi=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${F==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":F==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>Qe("direct"),children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.scopeDirect","Direct")})]}),t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${F==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":F==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>Qe("rooms"),children:[t.jsx(li,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.scopeRooms","Rooms")})]})]});return t.jsxs("div",{ref:qa,className:`chat-view${h?" chat-view--floating":""}${H?" chat-view--narrow":""}${gs?" chat-view--mobile-direct-thread":""}`,children:[t.jsx(Ao,{icon:xn,title:s("chat.title","Chat"),actions:t.jsxs(t.Fragment,{children:[gs?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn-icon chat-back-btn",onClick:Jn,"data-testid":"chat-back-btn","aria-label":s("chat.backToConversations","Back to conversations"),children:t.jsx(Is,{size:16})}),Wi]}):Vi,H?null:t.jsxs("button",{className:"btn btn-sm btn-primary chat-view-header-new-chat",onClick:an,"data-testid":"chat-new-btn",children:[t.jsx(pt,{size:14}),s("chat.newChat","New Chat")]}),!h&&m?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:m,"aria-label":s("chat.popOut","Pop out chat"),title:s("chat.popOut","Pop out chat"),"data-testid":"chat-pop-out",children:t.jsx(Ls,{size:16})}):null,h&&f?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:f,"aria-label":s("chat.maximizeToChatView","Open in Chat view"),title:s("chat.maximizeToChatView","Open in Chat view"),"data-testid":"chat-modal-maximize",children:t.jsx(Ls,{size:16})}):null,h&&M?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:M,"aria-label":s("chat.minimizeToQuickChat","Minimize to quick chat"),title:s("chat.minimizeToQuickChat","Minimize to quick chat"),"data-testid":"chat-modal-minimize",children:t.jsx(To,{size:16})}):null,h&&C?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:C,"aria-label":s("chat.closeChat","Close chat"),title:s("chat.closeChat","Close chat"),"data-testid":"chat-modal-close",children:t.jsx(Ps,{size:16})}):null]})}),t.jsxs("div",{className:"chat-view__body",children:[t.jsxs("div",{className:`chat-sidebar${xt?"":" chat-sidebar--hidden"}`,style:Ki,children:[F==="direct"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-sidebar-search-container",children:[t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(Eo,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:s("chat.searchConversations","Search conversations..."),value:hi,onChange:e=>fi(e.target.value),"data-testid":"chat-search-input"})]}),t.jsxs("label",{className:"chat-tag-filter",htmlFor:"chat-tag-filter",children:[t.jsx(_o,{size:14,"aria-hidden":"true"}),t.jsxs("select",{id:"chat-tag-filter",value:L??"",onChange:e=>W(e.target.value||null),"data-testid":"chat-tag-filter","aria-label":s("chat.filterByTag","Filter conversations by tag"),children:[t.jsx("option",{value:"",children:s("chat.allTags","All tags")}),T.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]}),L?t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.clearTagFilter","Clear tag filter"),onClick:()=>W(null),children:t.jsx(Ps,{size:14})}):null]})]}),t.jsx("div",{className:"chat-archived-toggle",children:t.jsx("button",{type:"button",className:"btn btn-sm btn-secondary","data-testid":"chat-archived-toggle",onClick:()=>{const e=!Ye;pi(e),e&&_()},children:Ye?"Active conversations":"Archived conversations"})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:P?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:s("chat.loadingConversations","Loading...")}):(Ye?R:Be).length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:s("chat.noConversationsYet","No conversations yet")}):t.jsx(t.Fragment,{children:[{id:"pinned",label:s("chat.pinned","Pinned"),testId:"chat-pinned-divider",sessions:Ss},{id:"recent",label:s("chat.recent","Recent"),testId:"chat-recent-divider",sessions:Ms}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>{const o=l?.id===n.id,d=!o&&Ra("direct",n.id,n.lastMessageAt??n.updatedAt),x=ai(n,be.get(n.agentId)??null,zt),z=Ts(x?.provider,x?.modelId)??"Fusion",X=n.title||s("chat.untitledSession","Untitled");return t.jsxs("div",{className:`chat-session-item${o?" chat-session-item--active":""}`,onClick:()=>us(n.id),onContextMenu:K=>{K.preventDefault(),ja(n.id,K.clientX,K.clientY)},"data-testid":Ye?`chat-archived-session-${n.id}`:`chat-session-${n.id}`,children:[t.jsx("button",{type:"button",className:"btn-icon chat-session-menu-btn","data-testid":"chat-session-menu-btn","aria-label":s("chat.conversationActionsAria","Conversation actions for {{title}}",{title:X}),"aria-haspopup":"menu","aria-expanded":G?.sessionId===n.id,onClick:K=>{if(K.stopPropagation(),G?.sessionId===n.id){Se(null);return}const pe=K.currentTarget.getBoundingClientRect();ja(n.id,pe.right,pe.bottom,{anchorRight:!0})},children:t.jsx(Do,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[X,n.pinnedAt?t.jsx(fn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":s("chat.pinned","Pinned")}):null,d?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${n.id}`,"aria-label":s("chat.unreadMessages","Unread messages")}):null]}),t.jsx("div",{className:"chat-session-preview",children:n.lastMessagePreview||s("chat.noMessages","No messages")}),(n.tags??[]).length>0?t.jsx("div",{className:"chat-session-tags","data-testid":`chat-session-tags-${n.id}`,children:(n.tags??[]).map(K=>t.jsx("span",{className:"chat-session-tag",children:K.name},K.id))}):null,n.matchedMessagePreview?t.jsx("div",{className:"chat-session-preview chat-session-preview--matched","data-testid":`chat-session-matched-preview-${n.id}`,children:s("chat.matchedInMessage",'Matched: "{{preview}}"',{preview:n.matchedMessagePreview})}):null,Ye?t.jsx("button",{type:"button",className:"btn btn-sm btn-secondary","data-testid":`chat-archived-restore-${n.id}`,onClick:K=>{K.stopPropagation(),Ei(n.id)},children:"Restore"}):null,t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[x?.provider?t.jsx(ua,{provider:x.provider,size:"sm"}):null,t.jsx("span",{children:be.get(n.agentId)?.name||(n.agentId===Ce?z:n.agentId.slice(0,30))})]}),t.jsx("span",{children:n.updatedAt?ir(n.updatedAt,s):""})]})]},n.id)})]},e.id))})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!H&&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:()=>_t(!0),children:[t.jsx(pt,{size:14}),s("chat.createRoom","Create room")]})}),w.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:s("chat.noRoomsYet","No rooms yet.")}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:w.rooms.map(e=>{const n=w.activeRoom?.id===e.id,o=!n&&Ra("room",e.id,e.updatedAt);return t.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${n?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${e.slug}`,onClick:()=>{de("room",e.id,e.updatedAt),w.selectRoom(e.id),H&&He(!1)},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),de("room",e.id,e.updatedAt),w.selectRoom(e.id),H&&He(!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]}),o?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":s("chat.unreadMessages","Unread messages")}):null]}),n?t.jsx("span",{className:"chat-room-item-meta",children:s("chat.roomMemberCount","{{count}} member",{count:w.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":s("chat.deleteRoom","Delete room {{name}}",{name:e.name}),onClick:d=>{d.stopPropagation(),Ft(e.id)},children:t.jsx(ha,{size:14})})]},e.id)})})]}),F==="rooms"?H?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:()=>_t(!0),children:[t.jsx(pt,{size:14}),s("chat.createRoom","Create room")]})}):null:H?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:an,"data-testid":"chat-new-btn",children:[t.jsx(pt,{size:14}),s("chat.newChat","New Chat")]})}):null]}),!H&&xt&&!Mt&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":vn,"aria-valuemax":bn,"aria-valuenow":Je,"aria-label":s("chat.resizeSidebar","Resize chat sidebar"),tabIndex:0,onPointerDown:Ii,onKeyDown:Li}),G&&t.jsxs("div",{className:"chat-session-context-menu",ref:Nn,role:"menu",style:{top:G.y,left:G.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>ds(G.sessionId,!ye?.pinnedAt),"data-testid":"chat-context-pin",title:c>=3&&!ye?.pinnedAt?s("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:c>=3&&!ye?.pinnedAt,children:[ye?.pinnedAt?t.jsx(Es,{size:14}):t.jsx(fn,{size:14}),ye?.pinnedAt?s("chat.unpin","Unpin"):s("chat.pin","Pin")]}),t.jsxs("button",{onClick:()=>cs(G.sessionId),"data-testid":"chat-context-rename",children:[t.jsx(ma,{size:14}),s("chat.rename","Rename")]}),t.jsxs("div",{className:"chat-session-tag-menu",role:"group","aria-label":s("chat.conversationTags","Conversation tags"),children:[T.map(e=>{const n=(ye?.tags??[]).some(o=>o.id===e.id);return t.jsxs("div",{className:"chat-tag-menu-item",children:[t.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,"data-testid":`chat-context-tag-${e.id}`,onClick:()=>void ke(G.sessionId,n?(ye?.tags??[]).filter(o=>o.id!==e.id).map(o=>o.id):[...(ye?.tags??[]).map(o=>o.id),e.id]).catch(()=>r(s("chat.failedToUpdateTags","Failed to update tags"),"error")),children:[n?"✓ ":"",e.name]}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.renameTag","Rename tag {{name}}",{name:e.name}),"data-testid":`chat-context-rename-tag-${e.id}`,onClick:o=>{o.stopPropagation(),Da(e.name),bt(e)},children:t.jsx(ma,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.deleteTag","Delete tag {{name}}",{name:e.name}),"data-testid":`chat-context-delete-tag-${e.id}`,onClick:o=>{o.stopPropagation(),$t(e)},children:t.jsx(ha,{size:14})})]},e.id)}),t.jsxs("div",{className:"chat-tag-create-row",children:[t.jsx("input",{className:"input",value:An,placeholder:s("chat.newTag","New tag"),"aria-label":s("chat.newTag","New tag"),onChange:e=>Ea(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),Ns())}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Ns(),children:s("chat.addTag","Add")})]})]}),t.jsxs("button",{onClick:()=>rs(G.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Ds,{size:14}),s("chat.archive","Archive")]}),t.jsxs("button",{onClick:()=>{Se(null),Pt(G.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(ha,{size:14}),s("chat.delete","Delete")]})]}),It&&t.jsx(Et,{onClose:()=>Lt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-dialog-title",children:s("chat.renameConversationTitle","Rename Conversation")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("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:s("chat.conversationName","Conversation name")}),t.jsx("input",{id:"chat-rename-input",className:"input chat-rename-input",type:"text",value:Rn,placeholder:s("chat.renamePlaceholder","Untitled"),"data-testid":"chat-rename-input",onChange:e=>jn(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),ls())},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Lt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void ls(),"data-testid":"chat-rename-save",children:s("chat.save","Save")})]})]})}),Tn&&t.jsx(Et,{onClose:()=>bt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-tag-dialog-title",children:s("chat.renameTagTitle","Rename tag")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-tag-input",children:s("chat.tagName","Tag name")}),t.jsx("input",{id:"chat-rename-tag-input",className:"input chat-rename-input",value:En,"data-testid":"chat-rename-tag-input",onChange:e=>Da(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),ee(Tn.id,En).then(()=>bt(null)).catch(()=>r(s("chat.failedToRenameTag","Failed to rename tag"),"error")))},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>bt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary","data-testid":"chat-rename-tag-save",onClick:()=>void ee(Tn.id,En).then(()=>bt(null)).catch(()=>r(s("chat.failedToRenameTag","Failed to rename tag"),"error")),children:s("chat.save","Save")})]})]})}),Ia&&t.jsx(Et,{onClose:()=>$t(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-delete-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-delete-tag-dialog-title",children:s("chat.deleteTagTitle","Delete tag?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.deleteTagBody","This removes the tag from all conversations, but does not delete conversations.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>$t(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger","data-testid":"chat-delete-tag-confirm",onClick:()=>void he(Ia.id).then(()=>$t(null)).catch(()=>r(s("chat.failedToDeleteTag","Failed to delete tag"),"error")),children:s("chat.delete","Delete")})]})]})}),Aa&&t.jsx(Et,{onClose:()=>Pt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:s("chat.deleteConversationTitle","Delete Conversation?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("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:()=>Pt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Di(Aa),children:s("chat.delete","Delete")})]})]})}),Ta&&t.jsx(Et,{onClose:()=>Ft(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:s("chat.deleteRoomTitle","Delete Room?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("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:()=>Ft(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await w.deleteRoom(Ta),Ft(null)}catch{r(s("chat.failedToDeleteRoom","Failed to delete room"),"error")}})()},children:s("chat.delete","Delete")})]})]})}),F==="rooms"?t.jsxs("div",{ref:_n,className:"chat-thread",children:[w.activeRoom?t.jsxs(t.Fragment,{children:[(!H||ps)&&t.jsxs("div",{className:"chat-room-thread-header",children:[ps&&t.jsx("button",{className:"btn-icon",onClick:Zn,"data-testid":"chat-back-btn",children:t.jsx(Is,{size:16})}),t.jsxs("div",{className:"chat-room-switcher-menu",ref:Ka,children:[t.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":Wt,onClick:()=>Ct(e=>!e),children:[t.jsxs("span",{className:"chat-thread-header-title",children:["#",w.activeRoom.name]}),t.jsx(hn,{size:16,"aria-hidden":"true"})]}),Wt&&t.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:w.rooms.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${e.id===w.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${e.id}`,onClick:()=>{de("room",e.id,e.updatedAt),w.selectRoom(e.id),Ct(!1)},children:["#",e.name]},e.id))})]}),t.jsx("div",{className:"chat-room-thread-members",children:w.activeRoomMembers.map(e=>t.jsx(yn,{agent:be.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:re,onScroll:Za,children:[w.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:s("chat.loadingMessages","Loading messages...")}):w.messages.filter(e=>e.content.trim()!==Ys).length===0?t.jsx("div",{className:"chat-empty-state",children:s("chat.noMessagesYet","No messages yet. Start the conversation!")}):w.messages.filter(e=>e.content.trim()!==Ys).map(e=>{const n=e.senderAgentId?be.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):s("chat.you","You"),o={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(fa,{message:o,forcePlain:!1,agentName:n,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:w.activeRoom?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:Te,onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:!1,onQuestionSubmit:sn},e.id)}),t.jsx("div",{ref:Oa})]}),w.activeRoom&&_a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(hn,{size:14}),s("chat.latest","Latest")]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:s("chat.selectRoomOrCreate","Select a room or create one")}),w.activeRoom&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file",accept:ni,multiple:!0,style:{display:"none"},onChange:e=>{mt(e.target.files),e.target.value=""}}),ge.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ge.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,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:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),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":s("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Fs,{size:16})}),t.jsx(Ks,{level:w.activeRoom.thinkingLevel,defaultThinkingLevel:N,showTargetSection:!1,onChange:e=>{w.updateRoomSettings(w.activeRoom.id,{thinkingLevel:e||null}).catch(()=>{r(s("chat.failedToUpdateRoomThinkingLevel","Failed to update room thinking effort"),"error")})}}),t.jsxs("div",{className:`chat-input-wrapper${$a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),it(!0)},onDragLeave:()=>it(!1),onDrop:e=>{e.preventDefault(),it(!1),mt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:Ti,className:"chat-input-textarea",placeholder:s("chat.typeMessage","Type a message..."),value:q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:cn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ga()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Vs,{agents:lt,filter:tt,highlightedIndex:Bt,visible:Me,onSelect:on,position:"below",roomMemberIds:Te?.memberIds,roomName:Te?.roomName})]}),t.jsx($s,{...ji.micProps}),t.jsx(_s,{isStreaming:!1,canSend:!!(q.trim()||ge.length>0),onSend:Gn})]})]})]}):t.jsxs("div",{ref:_n,className:"chat-thread",children:[!H&&(ta||!H)&&t.jsx("div",{className:"chat-thread-header",children:t.jsxs("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:[qe?t.jsx(ua,{provider:qe,size:"md"}):t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:hs}),_i&&t.jsx("span",{className:"chat-model-tag",children:Fe}),zi&&un&&na?t.jsxs("span",{className:"chat-thread-header-context","data-testid":"chat-thread-context-window",title:na,"aria-label":na,children:[fs," / ",un]}):null]})}),la?t.jsx(qo,{cliSessionId:Ui,tier:Hi,projectId:i,renderTranscript:ys,renderComposer:()=>l?Cs():null}):t.jsxs(t.Fragment,{children:[ys(),_a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(hn,{size:14}),s("chat.latest","Latest")]}),l&&Cs()]})]}),t.jsx(Xo,{isOpen:vi,onClose:()=>_t(!1),projectId:i,existingRoomNames:w.rooms.map(e=>e.name),onCreate:async e=>{await w.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),F!=="rooms"&&Qe("rooms"),_t(!1),H&&He(!1)}})]}),gi&&t.jsx(ur,{projectId:i,defaultModel:wi,defaultKind:y?.kind,defaultAgentId:y?.kind==="agent"?y.agentId:void 0,defaultThinkingLevel:N,defaultSelectedThinkingLevel:y?.kind==="model"?y.thinkingLevel:void 0,onClose:()=>Mn(!1),onCreate:ht})]})}export{Cr as ChatView,yr as buildIssueChatPrefill,sr as clampChatInputHeight,nr as resolveChatContextMenuPosition,ar as resolveChatInputOverflowY,ai as resolveSessionProvider};