@runfusion/fusion 0.77.0-beta.3 → 0.77.0-beta.5

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 (179) hide show
  1. package/dist/bin.js +13158 -10683
  2. package/dist/child-process-worker.js +9200 -6239
  3. package/dist/client/.vite/manifest.json +301 -274
  4. package/dist/client/assets/{AgentDetailView-D-mPbGXe.js → AgentDetailView-CSK_Rnlk.js} +3 -3
  5. package/dist/client/assets/{AgentPermissionPolicyEditor-Bq3z2QY0.js → AgentPermissionPolicyEditor-kG44Adcm.js} +1 -1
  6. package/dist/client/assets/{AgentsView-CYg6b9n0.js → AgentsView-ClKwKWnU.js} +4 -4
  7. package/dist/client/assets/ChatView-DoOqgkPX.js +13 -0
  8. package/dist/client/assets/{CommandCenter-DDCbSURT.js → CommandCenter-CJxvPbgn.js} +3 -3
  9. package/dist/client/assets/{DevServerView-DJ459OYL.js → DevServerView-C4nyLONX.js} +1 -1
  10. package/dist/client/assets/{DirectoryPicker-ClOKp7d1.js → DirectoryPicker-BIvXWIB5.js} +1 -1
  11. package/dist/client/assets/DocumentsView-DH_aZysM.js +1 -0
  12. package/dist/client/assets/{EvalsView-DGJFQc1W.js → EvalsView-klRK-GJQ.js} +1 -1
  13. package/dist/client/assets/{ExperimentalAgentOnboardingModal-CMy3zvnk.js → ExperimentalAgentOnboardingModal-CgBmukIm.js} +1 -1
  14. package/dist/client/assets/{GoalsView-D-z3Rf4g.js → GoalsView-ysh3X2x6.js} +1 -1
  15. package/dist/client/assets/{InsightsView-By1AFGbM.js → InsightsView-BbMjCu7J.js} +3 -3
  16. package/dist/client/assets/MemoryView-B3IgA8Bx.js +3 -0
  17. package/dist/client/assets/{PiExtensionsManager-_8u94B1u.js → PiExtensionsManager-CZlIw7C3.js} +1 -1
  18. package/dist/client/assets/PluginManager-vy0YZ2Nx.js +1 -0
  19. package/dist/client/assets/{PullRequestView-NkCEKKpG.js → PullRequestView-DhhsJV8I.js} +2 -2
  20. package/dist/client/assets/ReportModal-CQMn4i1y.js +21 -0
  21. package/dist/client/assets/ReportModal-lzN_xrnM.css +1 -0
  22. package/dist/client/assets/{ResearchView-BCxXqB8F.js → ResearchView-CVwfs4l3.js} +2 -2
  23. package/dist/client/assets/{SecretsView-CxK0XDc2.js → SecretsView-CrJfHle9.js} +1 -1
  24. package/dist/client/assets/{SessionTerminal-CuVsOYc8.js → SessionTerminal-BRI8W1-G.js} +1 -1
  25. package/dist/client/assets/{SettingsModal-BtV1tIIf.js → SettingsModal-B6U5Umru.js} +1 -1
  26. package/dist/client/assets/SettingsModal-C5ic1ls7.css +1 -0
  27. package/dist/client/assets/SettingsModal-h1A_aFqD.js +21 -0
  28. package/dist/client/assets/{SettingsTextareaRow-YR4pGawU.js → SettingsTextareaRow-O7-u9uMC.js} +1 -1
  29. package/dist/client/assets/SetupWizardModal-nXfJp8cA.js +2 -0
  30. package/dist/client/assets/{SkillsView-B4Jc91WM.js → SkillsView-CoWAjvWU.js} +1 -1
  31. package/dist/client/assets/{WorkflowNodeEditor-DGtYlSHs.js → WorkflowNodeEditor-BFMM3RF_.js} +2 -2
  32. package/dist/client/assets/{agent-import-generation-CHAXFtOA.js → agent-import-generation-BqDmtTur.js} +1 -1
  33. package/dist/client/assets/{agentsOrgChartLayout-DsahEyq7.js → agentsOrgChartLayout-C4cLqlV6.js} +1 -1
  34. package/dist/client/assets/app-BBSLJDbV.js +13 -0
  35. package/dist/client/assets/app-BKwOvuxE.js +5 -0
  36. package/dist/client/assets/app-Bvr57EZQ.js +5 -0
  37. package/dist/client/assets/app-C_PTWuI1.js +13 -0
  38. package/dist/client/assets/app-DKx18PHE.js +13 -0
  39. package/dist/client/assets/app-DRW5hIgr.js +13 -0
  40. package/dist/client/assets/app-DwvelD-n.js +13 -0
  41. package/dist/client/assets/{architectureDiagram-3BPJPVTR-BKJBR8ob.js → architectureDiagram-3BPJPVTR-CdxcwdRe.js} +1 -1
  42. package/dist/client/assets/{blockDiagram-GPEHLZMM-CqpNEYwI.js → blockDiagram-GPEHLZMM-CfQrRfHR.js} +1 -1
  43. package/dist/client/assets/{c4Diagram-AAUBKEIU-CouyKoYs.js → c4Diagram-AAUBKEIU-Cx7-2SOm.js} +1 -1
  44. package/dist/client/assets/channel-B4WN1jC_.js +1 -0
  45. package/dist/client/assets/{chunk-2J33WTMH-WHWSsNaC.js → chunk-2J33WTMH-D8jvgP3M.js} +1 -1
  46. package/dist/client/assets/{chunk-4BX2VUAB-B-EVACQc.js → chunk-4BX2VUAB-B5tBx_s_.js} +1 -1
  47. package/dist/client/assets/{chunk-55IACEB6-CVvNjEpv.js → chunk-55IACEB6-C-F-HQ5Z.js} +1 -1
  48. package/dist/client/assets/{chunk-727SXJPM-CV4EKLRh.js → chunk-727SXJPM-BP8Ln-8C.js} +1 -1
  49. package/dist/client/assets/{chunk-AQP2D5EJ-DtDpuURf.js → chunk-AQP2D5EJ-DMnTmRmn.js} +1 -1
  50. package/dist/client/assets/{chunk-FMBD7UC4-DPejtS21.js → chunk-FMBD7UC4-D_YdfnNc.js} +1 -1
  51. package/dist/client/assets/{chunk-ND2GUHAM-DGDxBRA_.js → chunk-ND2GUHAM-CULXyuXq.js} +1 -1
  52. package/dist/client/assets/{chunk-QZHKN3VN-D2k1MIuX.js → chunk-QZHKN3VN-CT1BWEJL.js} +1 -1
  53. package/dist/client/assets/classDiagram-4FO5ZUOK-CKE8RSOv.js +1 -0
  54. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-CKE8RSOv.js +1 -0
  55. package/dist/client/assets/{cose-bilkent-S5V4N54A-Cr6PW7Dk.js → cose-bilkent-S5V4N54A-M-3DXa6e.js} +1 -1
  56. package/dist/client/assets/{dagre-BM42HDAG-QKrqYGWy.js → dagre-BM42HDAG-Bsiqvroz.js} +1 -1
  57. package/dist/client/assets/{dashboard-view-BQRwsBoj.js → dashboard-view-BEBh_Ei5.js} +1 -1
  58. package/dist/client/assets/{dashboard-view-BcNU4vFB.js → dashboard-view-Bo_gFjdO.js} +1 -1
  59. package/dist/client/assets/{dashboard-view-CkPDyljq.js → dashboard-view-CnFFG3cW.js} +1 -1
  60. package/dist/client/assets/{dashboard-view-BksOkReD.js → dashboard-view-DAHn20ph.js} +1 -1
  61. package/dist/client/assets/{diagram-2AECGRRQ-BBFXrRQl.js → diagram-2AECGRRQ-CZiHoXo5.js} +1 -1
  62. package/dist/client/assets/{diagram-5GNKFQAL-_T4nM0jp.js → diagram-5GNKFQAL-BoJVz4Or.js} +1 -1
  63. package/dist/client/assets/{diagram-KO2AKTUF-BAKmsx_j.js → diagram-KO2AKTUF-DivGQuAL.js} +1 -1
  64. package/dist/client/assets/{diagram-LMA3HP47-Xdsdd6Gx.js → diagram-LMA3HP47-DkMK7OJp.js} +1 -1
  65. package/dist/client/assets/{diagram-OG6HWLK6-tIHxhnE8.js → diagram-OG6HWLK6-DFFvRcpW.js} +1 -1
  66. package/dist/client/assets/{erDiagram-TEJ5UH35-HZSbfe0g.js → erDiagram-TEJ5UH35--217vrom.js} +1 -1
  67. package/dist/client/assets/{flowDiagram-I6XJVG4X-C4O3r0DX.js → flowDiagram-I6XJVG4X-CQgWO3xf.js} +1 -1
  68. package/dist/client/assets/{folder-open-15UiPjYb.js → folder-open-DR6cRcNR.js} +1 -1
  69. package/dist/client/assets/{ganttDiagram-6RSMTGT7-DGsKKMEu.js → ganttDiagram-6RSMTGT7-BjDMUrS3.js} +1 -1
  70. package/dist/client/assets/{gitGraphDiagram-PVQCEYII-BY4kgtHp.js → gitGraphDiagram-PVQCEYII-gKUcDnln.js} +1 -1
  71. package/dist/client/assets/index-Dki2LBAp.css +1 -0
  72. package/dist/client/assets/index-oxnX59eO.js +2774 -0
  73. package/dist/client/assets/{infoDiagram-5YYISTIA-lJBWxF8I.js → infoDiagram-5YYISTIA-BA91T8S5.js} +1 -1
  74. package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-CrE_q16o.js → ishikawaDiagram-YF4QCWOH-0BY5xe-c.js} +1 -1
  75. package/dist/client/assets/{journeyDiagram-JHISSGLW-9V42jgFW.js → journeyDiagram-JHISSGLW-B_OwenbQ.js} +1 -1
  76. package/dist/client/assets/{kanban-definition-UN3LZRKU-B_T-7Vyf.js → kanban-definition-UN3LZRKU-GLabUTKp.js} +1 -1
  77. package/dist/client/assets/{mermaid.core-CwJ7S3PS.js → mermaid.core-BXo4rxYI.js} +4 -4
  78. package/dist/client/assets/{mindmap-definition-RKZ34NQL-MYNSgM6G.js → mindmap-definition-RKZ34NQL-DZl6LPoE.js} +1 -1
  79. package/dist/client/assets/{pieDiagram-4H26LBE5-CtT-wbYj.js → pieDiagram-4H26LBE5-DtHq-4py.js} +1 -1
  80. package/dist/client/assets/pixelify-sans-cyrillic-400-normal-DfOZNMlW.woff +0 -0
  81. package/dist/client/assets/pixelify-sans-latin-400-normal-DLrIX9QE.woff2 +0 -0
  82. package/dist/client/assets/pixelify-sans-latin-400-normal-JapMNN6Z.woff +0 -0
  83. package/dist/client/assets/pixelify-sans-latin-ext-400-normal-BkfTUL4s.woff +0 -0
  84. package/dist/client/assets/pixelify-sans-latin-ext-400-normal-DdH6zlBQ.woff2 +0 -0
  85. package/dist/client/assets/{puzzle-CXdFNN8H.js → puzzle-OVm-I1L4.js} +1 -1
  86. package/dist/client/assets/{quadrantDiagram-W4KKPZXB-3klC5x4k.js → quadrantDiagram-W4KKPZXB-BdjXhd5d.js} +1 -1
  87. package/dist/client/assets/{requirementDiagram-4Y6WPE33-CHfFrsBL.js → requirementDiagram-4Y6WPE33-BoFVjELN.js} +1 -1
  88. package/dist/client/assets/{sankeyDiagram-5OEKKPKP-Dtktw7Dy.js → sankeyDiagram-5OEKKPKP-B0qyJh-P.js} +1 -1
  89. package/dist/client/assets/{sequenceDiagram-3UESZ5HK-CuXPMjTU.js → sequenceDiagram-3UESZ5HK-ByY62Eqp.js} +1 -1
  90. package/dist/client/assets/{shield-alert-D9xqzJwR.js → shield-alert-CDy69fl7.js} +1 -1
  91. package/dist/client/assets/{standing-instructions-template-CcpV_LRP.js → standing-instructions-template-BsnnRlwm.js} +2 -2
  92. package/dist/client/assets/{stateDiagram-AJRCARHV-Bj_rDJwQ.js → stateDiagram-AJRCARHV-CwJ-_Phi.js} +1 -1
  93. package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-D-YYF-kX.js → stateDiagram-v2-BHNVJYJU-Cfvhq8mV.js} +1 -1
  94. package/dist/client/assets/{timeline-definition-PNZ67QCA-DXalwFMD.js → timeline-definition-PNZ67QCA-Co8VfGN9.js} +1 -1
  95. package/dist/client/assets/{upload-CWVc30BQ.js → upload-CkqDbEeE.js} +1 -1
  96. package/dist/client/assets/{useDiscoveredSkillsCache-D2M95Nn0.js → useDiscoveredSkillsCache-BHUasRiZ.js} +1 -1
  97. package/dist/client/assets/{users-q_-iLqv9.js → users-B8DkpbXD.js} +1 -1
  98. package/dist/client/assets/{vennDiagram-CIIHVFJN-0-aTlrbe.js → vennDiagram-CIIHVFJN-XSJteQrL.js} +1 -1
  99. package/dist/client/assets/{wardley-L42UT6IY-Bz_e_5wx.js → wardley-L42UT6IY-Btc0FRfF.js} +1 -1
  100. package/dist/client/assets/{wardleyDiagram-YWT4CUSO-DsQu4YnA.js → wardleyDiagram-YWT4CUSO--IcDNmrf.js} +1 -1
  101. package/dist/client/assets/{xychartDiagram-2RQKCTM6-K6GQdwVG.js → xychartDiagram-2RQKCTM6-CZW93G6X.js} +1 -1
  102. package/dist/client/index.html +4 -4
  103. package/dist/client/theme-data.css +183 -1
  104. package/dist/client/version.json +1 -1
  105. package/dist/droid-cli/package.json +1 -1
  106. package/dist/extension.js +10390 -7118
  107. package/dist/migrations/0000_initial.sql +3 -0
  108. package/dist/migrations/0061_fn_066_activity_log_task_id_index.sql +7 -0
  109. package/dist/migrations/0062_remove_task_subtask_splitting.sql +2 -0
  110. package/dist/migrations/0063_fn_090_ai_merge_review_reconciliation.sql +2 -0
  111. package/dist/migrations/0064_fn_094_task_repository_scope.sql +2 -0
  112. package/dist/pi-claude-cli/package.json +1 -1
  113. package/dist/pi-claude-cli/src/__tests__/event-bridge.test.ts +29 -1
  114. package/dist/pi-claude-cli/src/event-bridge.ts +10 -4
  115. package/dist/plugin-sdk/index.d.ts +301 -189
  116. package/dist/plugin-sdk/index.js +45 -105
  117. package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +47 -106
  118. package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
  119. package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +47 -106
  120. package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
  121. package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +45 -105
  122. package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
  123. package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +45 -105
  124. package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
  125. package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +45 -105
  126. package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
  127. package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +45 -105
  128. package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
  129. package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +47 -106
  130. package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
  131. package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +47 -106
  132. package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
  133. package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +45 -105
  134. package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
  135. package/dist/plugins/fusion-plugin-linear-import/bundled.js +45 -105
  136. package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
  137. package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +47 -106
  138. package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
  139. package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +45 -105
  140. package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
  141. package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +45 -105
  142. package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
  143. package/dist/plugins/fusion-plugin-quality/bundled.js +45 -105
  144. package/dist/plugins/fusion-plugin-quality/package.json +1 -1
  145. package/dist/plugins/fusion-plugin-reports/bundled.js +45 -105
  146. package/dist/plugins/fusion-plugin-reports/package.json +1 -1
  147. package/dist/plugins/fusion-plugin-roadmap/bundled.js +45 -105
  148. package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
  149. package/dist/plugins/fusion-plugin-todos/bundled.js +45 -105
  150. package/dist/plugins/fusion-plugin-todos/package.json +1 -1
  151. package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +45 -105
  152. package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
  153. package/package.json +1 -1
  154. package/skill/fusion/SKILL.md +1 -1
  155. package/skill/fusion/references/extension-tools.md +19 -1
  156. package/skill/fusion/references/fusion-capabilities.md +3 -1
  157. package/skill/fusion/references/task-structure.md +1 -1
  158. package/skill/fusion/workflows/specifications.md +2 -2
  159. package/dist/client/assets/ChatView-qnlDeWDu.js +0 -13
  160. package/dist/client/assets/DocumentsView-D3Yb4WqD.js +0 -1
  161. package/dist/client/assets/MemoryView-Dhe8ydZR.js +0 -3
  162. package/dist/client/assets/PluginManager-ByNlw3zN.js +0 -1
  163. package/dist/client/assets/ReportModal-DovuZwdY.js +0 -21
  164. package/dist/client/assets/ReportModal-M3uh98sc.css +0 -1
  165. package/dist/client/assets/SettingsModal-C-tiAvqQ.js +0 -21
  166. package/dist/client/assets/SettingsModal-C0FY8MPW.css +0 -1
  167. package/dist/client/assets/SetupWizardModal-DrbeWku9.js +0 -2
  168. package/dist/client/assets/app-BgpuMvTU.js +0 -13
  169. package/dist/client/assets/app-BlexHhbW.js +0 -13
  170. package/dist/client/assets/app-BsuUOR0P.js +0 -13
  171. package/dist/client/assets/app-DQVOujmO.js +0 -13
  172. package/dist/client/assets/app-DjyTRx1N.js +0 -5
  173. package/dist/client/assets/app-Dniggype.js +0 -13
  174. package/dist/client/assets/app-EV-lyZ0T.js +0 -5
  175. package/dist/client/assets/channel-D7yWYIo9.js +0 -1
  176. package/dist/client/assets/classDiagram-4FO5ZUOK-cuSqS34E.js +0 -1
  177. package/dist/client/assets/classDiagram-v2-Q7XG4LA2-cuSqS34E.js +0 -1
  178. package/dist/client/assets/index-4c8KmZSa.js +0 -2818
  179. package/dist/client/assets/index-Bg6JQgJj.css +0 -1
@@ -0,0 +1,13 @@
1
+ import{r as a,j as t}from"./vendor-react-SZ_qB27O.js";import{c as _s,S as nn,r as kt,e as ss,cL as rs,dq as Ar,dr as Tr,ds as Gn,b as W,dt as Er,du as Nt,dv as Rt,dw as aa,dx as Dr,dy as Ir,dz as Lr,dA as Fr,dB as Pr,dC as _r,bj as $r,d0 as sa,ar as cn,dD as Or,dE as Br,bU as zr,K as Ur,aK as Hr,b5 as on,a2 as Kr,db as Vr,dF as qr,dG as Wr,a_ as Gr,dH as Xr,dI as $s,dJ as Os,dK as Qr,dL as Yr,W as Jr,dM as Zr,dN as eo,dO as Ge,dP as os,dQ as is,dR as to,dS as no,dT as cs,G as ao,dU as so,z as ro,B as oo,aI as io,V as co,P as an,dg as ls,X as ds,aJ as lo,dV as uo,dW as us,dX as ms,F as Xn,dY as mo,D as hs,cY as ho,dZ as Qn,C as fs,d_ as gs,d$ as ps,e0 as Yn,e1 as vs,e2 as bs,c5 as Bs,e3 as ws,e4 as fo,dl as zs,e5 as go,e6 as po,cX as xs,cx as vo}from"./index-oxnX59eO.js";import{e7 as ai,e8 as si}from"./index-oxnX59eO.js";import{u as Xe}from"./vendor-i18n-Duky4gdQ.js";import{SessionTerminal as ys}from"./SessionTerminal-BRI8W1-G.js";import{u as bo}from"./useDiscoveredSkillsCache-BHUasRiZ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";import"./shield-alert-CDy69fl7.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 wo=[["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"}]],Us=_s("hash",wo);/**
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 xo=[["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"}]],yo=_s("tag",xo);function sn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Co(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function Jn(r,o){const u=Co(),f=o?.warm===!0,d=sn(),m=new Map;let k=!1,x=!1;return{mark(E){k||x||!u||m.has(E)||m.set(E,sn())},complete:E=>{if(!u||k||x){k=!0;return}k=!0,m.set("complete",sn());const I=Array.from(m.entries()).sort((j,S)=>j[1]-S[1]);let s=d;const D={};for(const[j,S]of I)D[j]=Math.max(0,S-s),s=S;const C=Math.max(0,sn()-d);try{console.debug("[room-open]",{roomId:r,warm:f,totalMs:C,phases:D,...E??{}})}catch{}},cancel(){x=!0,k=!0}}}const $e="fusion:chat-active-room";class Hs extends Error{roomId;constructor(o,u){super(o),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=u}}function ra(r){return[...r].sort((o,u)=>new Date(u.updatedAt).getTime()-new Date(o.updatedAt).getTime())}function We(r,o){const u=r.findIndex(d=>d.id===o.id);if(u===-1)return ra([o,...r]);const f=[...r];return f[u]=o,ra(f)}function Fe(r){try{return JSON.parse(r.data)}catch{return null}}function Zn(r){return r.slice().reverse()}function ko(r,o,u){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:r,role:"user",content:o,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...u?.length?{attachments:u}:{},createdAt:new Date().toISOString()}}function Cs(r,o,u){if(r.some(d=>d.id===o.id))return r;const f=u?r.findIndex(d=>d.id===u):-1;if(f>=0){const d=[...r];return d[f]=o,d}if(o.role==="user"){const d=r.findIndex(m=>m.role==="user"&&m.id.startsWith("temp-")&&m.content.trim()===o.content.trim());if(d>=0){const m=[...r];return m[d]=o,m}}return[...r,o]}function Ro(r,o){const{t:u}=Xe("app"),f=`${nn.CHAT_ROOMS}:${r??"global"}`,d=`${nn.ACTIVE_CHAT_ROOM_ID}:${r??"global"}`,m=a.useCallback(v=>`${nn.CHAT_ROOM_MESSAGES_PREFIX}${r??"global"}:${v}`,[r]),k=a.useCallback(v=>`${nn.CHAT_ROOM_MEMBERS_PREFIX}${r??"global"}:${v}`,[r]),[x,y]=a.useState(()=>{const v=kt(f,{maxAgeMs:ss});return Array.isArray(v)?v:[]}),[E,I]=a.useState(()=>x.length===0),[s,D]=a.useState(null),[C,j]=a.useState(()=>{const v=kt(d,{maxAgeMs:rs});return v?x.find(g=>g.id===v)??null:null}),[S,R]=a.useState([]),[l,L]=a.useState([]),[_,Y]=a.useState(!1),z=a.useRef(x),N=a.useRef(C),se=a.useRef(l),H=a.useRef(0),ae=a.useRef(r);z.current=x,N.current=C,se.current=l,ae.current!==r&&(ae.current=r,H.current+=1);const A=a.useCallback(async v=>{if(!v){R([]),L([]),Y(!1);return}const g=Jn(v.id,{warm:!1});g.mark("select");const w=kt(m(v.id),{maxAgeMs:Ar}),h=kt(k(v.id),{maxAgeMs:ss}),M=Array.isArray(w)&&w.length>0,F=Array.isArray(h)&&h.length>0,K=N.current?.id===v.id&&se.current.length>0&&se.current.every(de=>de.roomId===v.id);M||F?(g.mark("cache-hit"),M&&!K&&(L(w),g.mark("hydrate")),F&&R(h)):K||L([]),Y(!M&&!K);try{const[de,ee]=await Promise.all([Tr(v.id,r),Gn(v.id,{limit:100,order:"desc"},r)]);g.mark("members-fetch"),g.mark("messages-fetch"),W(k(v.id),de.members,{maxBytes:5e5});const ne=Zn(ee.messages);W(m(v.id),ne,{maxBytes:5e5}),N.current?.id===v.id&&(R(de.members),L(ne),g.mark("hydrate"))}catch{!M&&!F&&(R([]),L([]))}finally{N.current?.id===v.id&&Y(!1),g.complete({warm:M||K,membersCached:F})}},[k,m,r]),$=a.useCallback(async()=>{z.current.length===0&&I(!0);try{const v=await Er({},r),g=ra(v.rooms);y(g),W(f,g,{maxBytes:5e5}),D(null);const w=kt(d,{maxAgeMs:rs})??Nt($e,r);if(w){const h=g.find(M=>M.id===w)??null;h?(j(h),A(h)):(Rt($e,r),W(d,"",{maxBytes:5e5}))}}catch(v){const g=v instanceof Error?v.message:u("chatRooms.error.failedToLoad","Failed to load chat rooms");D(g),o?.(g,"error")}finally{I(!1)}},[d,o,A,r,f]),J=a.useCallback(v=>{if(!v){N.current=null,j(null),Rt($e,r),W(d,"",{maxBytes:5e5}),A(null);return}const g=z.current.find(w=>w.id===v)??null;N.current=g,j(g),g&&(aa($e,g.id,r),W(d,g.id,{maxBytes:5e5}),A(g))},[d,A,r]),Q=a.useCallback(async v=>{const w=(await Dr({name:v.name,memberAgentIds:v.memberAgentIds},r)).room;return y(h=>We(h,w)),N.current=w,j(w),aa($e,w.id,r),W(d,w.id,{maxBytes:5e5}),await A(w),w},[d,A,r]),T=a.useCallback(async(v,g)=>{const h=(await Ir(v,g,r)).room;return y(M=>We(M,h)),N.current?.id===h.id&&(N.current=h,j(h)),h},[r]),B=a.useCallback(async v=>{await Lr(v,r),y(g=>g.filter(w=>w.id!==v)),W(m(v),[],{maxBytes:5e5}),W(k(v),[],{maxBytes:5e5}),N.current?.id===v&&(N.current=null,j(null),R([]),L([]),Rt($e,r),W(d,"",{maxBytes:5e5}))},[d,k,m,r]),re=a.useCallback(async(v,g)=>{const w=N.current,h=w?.id;if(!h)throw new Error(u("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const M=Jn(h,{warm:!1}),F=g?.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()})),K=ko(h,v,F?.length?F:g?.attachments);N.current?.id===h&&L(ee=>{const ne=[...ee,K];return W(m(h),ne,{maxBytes:5e5}),ne});let de=!1;try{const ee=[];if(g?.files?.length)for(const ve of g.files)try{const ge=await Fr(h,ve,r);ee.push(ge.attachment)}catch{throw new Error(u("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:ve.name}))}const ne=[...g?.attachments??[],...ee],pe=await Pr(h,{content:v,...ne.length?{attachments:ne}:{}},r);de=!0;try{g?.onDelivered?.()}catch{}pe.message?.createdAt&&w&&y(ve=>We(ve,{...w,updatedAt:pe.message.createdAt})),N.current?.id===h&&L(ve=>{const ge=Cs(ve,pe.message,K.id);return W(m(h),ge,{maxBytes:5e5}),ge});const ue=await Gn(h,{limit:100,order:"desc"},r),ke=Zn(ue.messages);if(W(m(h),ke,{maxBytes:5e5}),N.current?.id!==h)return;L(ke),M.mark("hydrate")}catch(ee){let ne=null;try{const ue=await Gn(h,{limit:100,order:"desc"},r);ne=Zn(ue.messages),W(m(h),ne,{maxBytes:5e5}),N.current?.id===h&&(L(ne),M.mark("hydrate"))}catch{!de&&N.current?.id===h&&L(ue=>{const ke=ue.filter(ve=>ve.id!==K.id);return W(m(h),ke,{maxBytes:5e5}),ke})}const pe=ne?.some(ue=>ue.role==="user"&&ue.content.trim()===K.content.trim());if(de||pe){const ue=ee instanceof Error&&ee.message.trim()?ee.message:u("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new Hs(ue,h)}throw ee}finally{M.complete({source:"send-room-message"})}},[m,r]),Ce=a.useCallback(async v=>{!v||!z.current.some(g=>g.id===v)||(await _r(v,r),W(m(v),[],{maxBytes:5e5}),N.current?.id===v&&L([]))},[m,r]);return a.useEffect(()=>{$()},[$]),a.useEffect(()=>{const v=H.current,g=r?`/api/events?projectId=${encodeURIComponent(r)}`:"/api/events";return $r(g,{onReconnect:()=>{sa({view:"useChatRooms",trigger:"sse-reconnect",projectId:r,replayAttempted:!1});const w=N.current?.id;if(w){const h=Jn(w,{warm:!0});h.mark("sse-reconnect-refresh"),$().finally(()=>h.complete({source:"sse-reconnect"}));return}$()},events:{"chat:room:created":w=>{if(H.current!==v)return;const h=Fe(w);h&&y(M=>We(M,h))},"chat:room:updated":w=>{if(H.current!==v)return;const h=Fe(w);h&&(y(M=>We(M,h)),N.current?.id===h.id&&(N.current=h,j(h)))},"chat:room:deleted":w=>{if(H.current!==v)return;const h=Fe(w);h?.id&&(y(M=>M.filter(F=>F.id!==h.id)),W(m(h.id),[],{maxBytes:5e5}),W(k(h.id),[],{maxBytes:5e5}),N.current?.id===h.id&&(N.current=null,j(null),R([]),L([]),Rt($e,r),W(d,"",{maxBytes:5e5})))},"chat:room:member:added":w=>{if(H.current!==v)return;const h=Fe(w);!h||N.current?.id!==h.roomId||R(M=>{if(M.some(K=>K.agentId===h.agentId))return M;const F=[...M,h];return W(k(h.roomId),F,{maxBytes:5e5}),F})},"chat:room:member:removed":w=>{if(H.current!==v)return;const h=Fe(w);!h||N.current?.id!==h.roomId||R(M=>{const F=M.filter(K=>K.agentId!==h.agentId);return W(k(h.roomId),F,{maxBytes:5e5}),F})},"chat:room:message:added":w=>{if(H.current!==v)return;const h=Fe(w);h&&(y(M=>{const F=M.find(K=>K.id===h.roomId);return F?We(M,{...F,updatedAt:h.createdAt}):M}),N.current?.id===h.roomId&&L(M=>{const F=Cs(M,h);return F===M?M:(W(m(h.roomId),F,{maxBytes:5e5}),F)}))},"chat:room:message:updated":w=>{if(H.current!==v)return;const h=Fe(w);!h||N.current?.id!==h.roomId||L(M=>{const F=M.map(K=>K.id===h.id?h:K);return W(m(h.roomId),F,{maxBytes:5e5}),F})},"chat:room:message:deleted":w=>{if(H.current!==v)return;const h=Fe(w);h?.id&&L(M=>{const F=M.filter(de=>de.id!==h.id),K=N.current?.id;return K&&W(m(K),F,{maxBytes:5e5}),F})},"chat:room:messages:cleared":w=>{if(H.current!==v)return;const h=Fe(w);h?.roomId&&(W(m(h.roomId),[],{maxBytes:5e5}),N.current?.id===h.roomId&&L([]),y(M=>{const F=M.find(K=>K.id===h.roomId);return F?We(M,{...F,updatedAt:new Date().toISOString()}):M}))}}})},[d,k,m,r,$]),a.useEffect(()=>{C&&(x.some(v=>v.id===C.id)||(N.current=null,j(null),R([]),L([]),Rt($e,r),W(d,"",{maxBytes:5e5})))},[C,d,r,x]),{rooms:x,roomsLoading:E,roomsError:s,activeRoom:C,activeRoomMembers:S,messages:l,messagesLoading:_,selectRoom:J,createRoom:Q,updateRoomSettings:T,deleteRoom:B,sendRoomMessage:re,clearRoom:Ce,refreshRooms:$}}const Mt={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},ks=200;function oa(r){if(!r)return null;const o=new Date(r).getTime();return Number.isFinite(o)?o:null}function Ks(r){const o=Object.entries(r);if(o.length<=ks)return r;const u=o.map(([f,d])=>({id:f,timestamp:d,value:oa(d)??0})).sort((f,d)=>d.value-f.value).slice(0,ks);return Object.fromEntries(u.map(({id:f,timestamp:d})=>[f,d]))}function rn(r){if(!r)return{};try{const o=JSON.parse(r);if(!o||typeof o!="object")return{};const u={};for(const[f,d]of Object.entries(o))typeof f=="string"&&typeof d=="string"&&(u[f]=d);return Ks(u)}catch{return{}}}function Mo(r){const[o,u]=a.useState(()=>{try{return rn(Nt(Mt.direct,r))}catch{return{}}}),[f,d]=a.useState(()=>{try{return rn(Nt(Mt.room,r))}catch{return{}}});a.useEffect(()=>{try{u(rn(Nt(Mt.direct,r)))}catch{u({})}try{d(rn(Nt(Mt.room,r)))}catch{d({})}},[r]);const m=a.useMemo(()=>({direct:o,room:f}),[o,f]),k=a.useCallback((s,D)=>{const C=Ks(D);try{aa(Mt[s],JSON.stringify(C),r)}catch{}return C},[r]),x=a.useCallback((s,D)=>{if(s==="direct"){u(C=>k(s,D(C)));return}d(C=>k(s,D(C)))},[k]),y=a.useCallback((s,D,C)=>{const j=oa(C);if(j===null)return!1;const S=m[s][D],R=oa(S);return R===null?!0:j>R},[m]),E=a.useCallback((s,D,C)=>{if(!D)return;const j=C??new Date().toISOString();x(s,S=>({...S,[D]:j}))},[x]),I=a.useCallback((s,D)=>{D.length!==0&&x(s,C=>{const j={...C};for(const S of D)S.id&&(j[S.id]=S.lastActivityAt??new Date().toISOString());return j})},[x]);return{isUnread:y,markRead:E,markAllRead:I}}function Rs(r){return r.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Vs(r,o){const u=o.trim();if(!u)return!0;const f=Rs(u);return Rs(r).includes(f)||r.toLowerCase().includes(u.toLowerCase())}function Ms({agents:r,filter:o,highlightedIndex:u,visible:f,onSelect:d,position:m="below",roomMemberIds:k,roomName:x}){const{t:y}=Xe("app"),E=a.useMemo(()=>r.filter(S=>Vs(S.name,o)),[r,o]),I=!!k,s=I&&o.trim().length>0,D=a.useMemo(()=>I?E.filter(S=>k?.has(S.id)):E,[E,k,I]),C=a.useMemo(()=>I?E.filter(S=>!k?.has(S.id)):[],[E,k,I]),j=s?[...D,...C]:D;return f?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${m}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":y("agentMention.suggestionsLabel","Agent mention suggestions"),children:j.length===0?t.jsx("div",{className:"agent-mention-empty",children:y("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[I&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:x?y("agentMention.membersOf","Members of #{{roomName}}",{roomName:x}):y("agentMention.roomMembers","Room members")}),D.map((S,R)=>t.jsxs("button",{type:"button",className:`agent-mention-item${R===u?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${S.id}`,onMouseDown:l=>l.preventDefault(),onClick:()=>d(S),role:"option","aria-selected":R===u,children:[t.jsx(cn,{agent:S,size:20}),I&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":y("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:S.name}),t.jsx("span",{className:"agent-mention-role",children:S.role})]},S.id)),I&&!s&&C.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:y("agentMention.typeToSearch","Type to search other agents")}),I&&s&&C.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:y("agentMention.otherAgents","Other agents")}),C.map((S,R)=>{const l=D.length+R;return t.jsxs("button",{type:"button",className:`agent-mention-item${l===u?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${S.id}`,onMouseDown:L=>L.preventDefault(),onClick:()=>d(S),role:"option","aria-selected":l===u,children:[t.jsx(cn,{agent:S,size:20}),t.jsx("span",{className:"agent-mention-name",children:S.name}),t.jsx("span",{className:"agent-mention-role",children:S.role})]},S.id)})]})]})}):null}function So(r,o){return r+o}function No({visible:r,position:o,tasks:u,files:f,selectedIndex:d,onSelectTask:m,onSelectFile:k,loading:x}){const{t:y}=Xe("app");if(!r)return null;const E=u.length>0,I=f.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:o.top,left:o.left},"data-testid":"file-mention-popup",onMouseDown:s=>{s.preventDefault()},children:[x&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!x&&!E&&!I&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:y("fileMention.empty","No tasks or files found")}),!x&&(E||I)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[E&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:y("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":y("fileMention.taskMatches","Task matches"),children:u.map((s,D)=>{const C=D;return t.jsxs("li",{className:`file-mention-popup-item${C===d?" file-mention-popup-item--selected":""}`,onClick:()=>m(s),role:"option","aria-selected":C===d,"data-testid":`task-mention-item-${C}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Us,{})}),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:s.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${s.column}`,children:s.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:s.title})]})]},s.id)})})]}),I&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:y("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":y("fileMention.fileMatches","File matches"),children:f.map((s,D)=>{const C=So(u.length,D),j=Or(s.path);return t.jsxs("li",{className:`file-mention-popup-item${C===d?" file-mention-popup-item--selected":""}`,onClick:()=>k(s),role:"option","aria-selected":C===d,"data-testid":`file-mention-item-${C}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(Br,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:s.name}),j&&t.jsx("span",{className:"file-mention-popup-item-path",children:j})]})]},s.path)})})]})]})]})}function jo(r,o=[],u){const f=r.trim().replace(/^#/,""),d=(k,x)=>u?u(k,x):x;if(!f)return{ok:!1,error:d("createRoom.nameRequired","Room name is required.")};if(/[A-Z]/.test(f))return{ok:!1,error:d("createRoom.lowercase","Use lowercase letters only.")};const m=f.toLowerCase();return m.length>80?{ok:!1,error:d("createRoom.maxLength","Room names can be at most 80 characters.")}:/^[a-z0-9_-]+$/.test(m)?/^[-_]|[-_]$/.test(m)?{ok:!1,error:d("createRoom.noEdgeChars","Room names cannot start or end with a hyphen or underscore.")}:o.some(k=>k.toLowerCase()===m)?{ok:!1,error:d("createRoom.duplicate","A room with this name already exists.")}:{ok:!0,name:m}:{ok:!1,error:d("createRoom.validChars","Use lowercase letters, numbers, hyphens, or underscores only.")}}function Ao({isOpen:r,onClose:o,onCreate:u,projectId:f,existingRoomNames:d=[]}){const{t:m}=Xe("app"),[k,x]=a.useState(""),[y,E]=a.useState([]),[I,s]=a.useState(""),[D,C]=a.useState([]),[j,S]=a.useState("idle"),[R,l]=a.useState(null),[L,_]=a.useState(!1),Y=a.useRef(null),z=a.useRef(null),N=a.useRef(null),se=a.useRef(0);a.useEffect(()=>{const T=++se.current;if(!r)return;N.current=document.activeElement instanceof HTMLElement?document.activeElement:null,E([]),S("loading"),l(null);let B=!1;const re=()=>!B&&se.current===T;return zr(void 0,f).then(Ce=>{re()&&(E(Ce),C(v=>v.filter(g=>Ce.some(w=>w.id===g))),S("loaded"))}).catch(()=>{re()&&(E([]),S("failed"))}),()=>{B=!0,++se.current}},[r,f]),a.useEffect(()=>{if(!r){x(""),s(""),C([]),E([]),S("idle"),l(null),_(!1);return}const T=window.requestAnimationFrame(()=>{const B=document.activeElement;B instanceof HTMLElement&&z.current?.contains(B)||Y.current?.focus()});return()=>window.cancelAnimationFrame(T)},[r]),a.useEffect(()=>{if(!r)return;const T=B=>{B.key==="Escape"&&o()};return document.addEventListener("keydown",T),()=>document.removeEventListener("keydown",T)},[r,o]),a.useEffect(()=>{r||N.current?.focus()},[r]);const H=a.useMemo(()=>jo(k,d,m),[k,d,m]),ae=a.useMemo(()=>{const T=I.trim().toLowerCase();return T?y.filter(B=>B.name.toLowerCase().includes(T)):y},[y,I]),A=a.useMemo(()=>y.filter(T=>D.includes(T.id)),[y,D]),$=H.ok&&D.length>0&&!L&&j==="loaded";if(!r)return null;const J=T=>{L||C(B=>B.includes(T)?B.filter(re=>re!==T):[...B,T])},Q=async()=>{if(!H.ok){l(H.error);return}if(D.length===0){l(m("createRoom.selectMember","Select at least one member."));return}l(null),_(!0);try{await u({name:H.name,displayName:`#${H.name}`,memberAgentIds:D}),o()}catch(T){l(T instanceof Error?T.message:m("createRoom.failedCreate","Failed to create room."))}finally{_(!1)}};return t.jsx(Ur,{windowKey:"create-room",title:m("createRoom.title","Create room"),ariaLabel:m("createRoom.title","Create room"),onClose:o,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",{ref:z,className:"modal create-room-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:m("createRoom.title","Create room")}),t.jsx("button",{type:"button",className:"modal-close","aria-label":m("actions.close","Close"),onClick:o,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:m("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:Y,id:"create-room-name",className:"input",value:k,disabled:L,onChange:T=>{const B=T.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();x(B)}})]}),!H.ok&&t.jsx("div",{className:"form-error",children:H.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:m("createRoom.members","Members")}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:m("createRoom.searchAgents","Search agents"),value:I,disabled:L,onChange:T=>s(T.target.value)})]}),A.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:A.map(T=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>J(T.id),disabled:L,children:[T.name," ×"]},T.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:j==="idle"||j==="loading"?t.jsx("div",{className:"create-room-modal-empty",children:t.jsx(Hr,{label:m("createRoom.loadingAgents","Loading agents...")})}):j==="failed"?t.jsx("div",{className:"create-room-modal-empty",children:m("createRoom.failedLoadAgents","Failed to load agents.")}):ae.length===0?t.jsx("div",{className:"create-room-modal-empty",children:y.length===0?m("createRoom.noAgents","No agents in this project yet."):m("createRoom.noMatch","No agents match your search.")}):ae.map(T=>{const B=D.includes(T.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${B?" create-room-modal-member-row--selected":""}`,onClick:()=>J(T.id),disabled:L,children:[t.jsx(cn,{agent:T,size:20}),t.jsx("span",{children:T.name}),t.jsx("span",{className:"create-room-modal-member-role",children:T.role})]},T.id)})}),R&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:R})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:o,disabled:L,children:m("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void Q(),disabled:!$,children:L?m("createRoom.creating","Creating..."):m("createRoom.create","Create room")})]})]})})}function To({cliSessionId:r,tier:o,projectId:u,renderTranscript:f,renderComposer:d,queuedCount:m=0,terminalProps:k}){const{t:x}=Xe("app"),y=o==="generic",[E,I]=a.useState(y?"terminal":"transcript");if(y)return t.jsx("div",{className:"cli-chat-surface cli-chat-surface--generic","data-tier":"generic",children:t.jsx(ys,{sessionId:r,projectId:u,...k})});const s=E==="terminal";return t.jsxs("div",{className:"cli-chat-surface","data-tier":o,"data-view":E,children:[t.jsxs("div",{className:"cli-chat-surface__toolbar",role:"tablist","aria-label":x("cliChat.viewToggleLabel","Chat view"),children:[t.jsxs("button",{type:"button",role:"tab","aria-selected":!s,className:`cli-chat-surface__tab${s?"":" is-active"}`,onClick:()=>I("transcript"),children:[t.jsx(on,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:x("cliChat.transcriptTab","Transcript")})]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":s,className:`cli-chat-surface__tab${s?" is-active":""}`,onClick:()=>I("terminal"),children:[t.jsx(Kr,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:x("cliChat.terminalTab","Terminal")})]})]}),t.jsx("div",{className:"cli-chat-surface__body",children:s?t.jsx(ys,{sessionId:r,projectId:u,...k}):f()}),!s&&t.jsxs("div",{className:"cli-chat-surface__composer",children:[m>0&&t.jsx("div",{className:"cli-chat-surface__queued",role:"status","aria-live":"polite",children:x("cliChat.queued","{{count}} message queued — will send when the agent is ready",{count:m})}),d()]})]})}const Eo=200,Do=8,Io=8;function Ss(){return new DOMException("The operation was aborted.","AbortError")}function Ns(r,o){return o.aborted?Promise.reject(Ss()):new Promise((u,f)=>{const d=()=>f(Ss());o.addEventListener("abort",d,{once:!0}),r.then(m=>{o.removeEventListener("abort",d),u(m)},m=>{o.removeEventListener("abort",d),f(m)})})}function js(r,o,u){const f=r.slice(0,o),d=r.slice(o+1),m=d.match(/[\s]|$/),k=m?m.index??d.length:d.length,x=d.slice(k);return`${f}${u}${x}`}function Lo(r={}){const{projectId:o,workspace:u="project"}=r,[f,d]=a.useState(!1),[m,k]=a.useState(""),[x,y]=a.useState(-1),[E,I]=a.useState([]),[s,D]=a.useState([]),[C,j]=a.useState(!1),[S,R]=a.useState(0),l=a.useRef(null),L=a.useRef(null),_=[...E.map(A=>({kind:"task",task:A})),...s.map(A=>({kind:"file",file:A}))];a.useEffect(()=>()=>{l.current&&clearTimeout(l.current),L.current?.abort()},[]);const Y=a.useCallback((A,$)=>{if($<0||$>A.length){d(!1);return}const J=Q=>/[a-zA-Z0-9/_.-]/.test(Q);for(let Q=$-1;Q>=0;Q--){if(A[Q]==="#"){if(Q===0){const B=A.slice(Q+1,$);y(Q),k(B),R(0),d(!0);return}const T=A[Q-1];if(/[\s,.;:!?'"()[\]{}]/.test(T)){const B=A.slice(Q+1,$);y(Q),k(B),R(0),d(!0);return}d(!1);return}if(!J(A[Q])){d(!1);return}}d(!1)},[]),z=a.useCallback(()=>{L.current?.abort(),d(!1),k(""),y(-1),I([]),D([]),R(0),j(!1)},[]),N=a.useCallback(async A=>{if(!A.trim()){I([]),D([]),j(!1);return}L.current?.abort();const $=new AbortController;L.current=$;try{j(!0);const[J,Q]=await Promise.allSettled([Ns(Vr(20,0,o,A),$.signal),Ns(qr(A,u,o),$.signal)]);if($.signal.aborted)return;const T=J.status==="fulfilled"?J.value.slice(0,Do).map(re=>({id:re.id,title:re.title??"",column:re.column})):[],B=Q.status==="fulfilled"?Q.value.files.slice(0,Io):[];I(T),D(B),R(0)}catch(J){J.name!=="AbortError"&&(I([]),D([]))}finally{$.signal.aborted||j(!1)}},[u,o]);a.useEffect(()=>{if(f)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{N(m)},Eo),()=>{l.current&&clearTimeout(l.current)}},[m,f,N]);const se=a.useCallback((A,$)=>!f||x<0?$:js($,x,`#${A.id}`),[f,x]),H=a.useCallback((A,$)=>!f||x<0?$:js($,x,`#${A.path}`),[f,x]),ae=a.useCallback((A,$)=>{if(!f||_.length===0)return!1;switch(A.key){case"ArrowDown":return A.preventDefault(),R(J=>Math.min(J+1,_.length-1)),!0;case"ArrowUp":return A.preventDefault(),R(J=>Math.max(J-1,0)),!0;case"Enter":case"Tab":return _[S]?(A.preventDefault(),!0):!1;case"Escape":return A.preventDefault(),z(),!0;default:return!1}},[f,_,S,z]);return{mentionActive:f,tasks:E,files:s,combinedItems:_,loading:C,mentionQuery:m,selectedIndex:S,setSelectedIndex:R,detectMention:Y,selectTask:se,selectFile:H,dismissMention:z,handleKeyDown:ae}}function Fo(r,o){const u=r.reduce((f,d)=>f+(d.content?.length??0),0)+(o?.length??0);return Math.ceil(u/4)}function As(r){if(!Number.isFinite(r)||r<=0)return"0";if(r<1e3)return String(Math.round(r));const o=r/1e3;return o<10?`~${Number(o.toFixed(1))}k`:`${Math.round(o)}k`}const Ts="above",Po=200,ft=8;function Zo(r){const o=r.trim();return o?`${o}
12
+
13
+ `:""}function _o(r,o,u,f,d,m,k){const x=Math.max(ft,m-f-ft),y=Math.max(ft,k-d-ft),E=u?r-f:r;return{x:Math.min(Math.max(ft,E),x),y:Math.min(Math.max(ft,o),y)}}const Es="__SKIP__";let ea=!1;function $o(r,o){const u=new Date(r),d=new Date().getTime()-u.getTime(),m=Math.floor(d/1e3),k=Math.floor(m/60),x=Math.floor(k/60),y=Math.floor(x/24);return m<60?o("chat.relativeTimeJustNow","just now"):k<60?o("chat.relativeTimeMinutes","{{count}}m ago",{count:k}):x<24?o("chat.relativeTimeHours","{{count}}h ago",{count:x}):y<7?o("chat.relativeTimeDays","{{count}}d ago",{count:y}):u.toLocaleDateString()}const ta="fusion:chat-scope",Oo="fusion:chat-draft:";function Ds(r,o){return r.slice(o+1).find(u=>u.role==="user")?.content}function Is(r,o){return o?`${Oo}${r}:${o}`:null}function Ls(r){if(!r)return"";try{return localStorage.getItem(r)??""}catch{return""}}const Bo=["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"],Fs="image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm,video/quicktime,.txt,.md,.json,.yaml,.yml,.toml,.csv,.xml",na=fo;function zo(r,o){const u=r.slice(0,o),f=/(^|[\s\n])@([\w-]*)$/.exec(u);if(!f)return null;const d=f[2]??"",m=u.length-d.length-1;return{filter:d,start:m,end:o}}function Uo(r){const o=r?.runtimeConfig;if(!o||typeof o!="object")return null;const u=Reflect.get(o,"modelProvider"),f=Reflect.get(o,"modelId");return typeof u!="string"||u.trim().length===0||typeof f!="string"||f.trim().length===0?null:{provider:u,modelId:f}}function Ps(r,o,u){if(r?.modelProvider&&r?.modelId)return{provider:r.modelProvider,modelId:r.modelId};const f=Uo(o??void 0);return f||(u.provider&&u.modelId?{provider:u.provider,modelId:u.modelId}:null)}function Ho({projectId:r,defaultModel:o,defaultKind:u,defaultAgentId:f,defaultThinkingLevel:d,defaultSelectedThinkingLevel:m,onClose:k,onCreate:x}){const{t:y}=Xe("app"),[E,I]=a.useState(u??"agent"),{agents:s,loading:D}=$s(r),[C,j]=a.useState(f??""),{models:S,favoriteProviders:R,favoriteModels:l,loading:L,refresh:_}=Os(),Y=o.provider&&o.modelId?`${o.provider}/${o.modelId}`:"",[z,N]=a.useState(Y),[se,H]=a.useState(m??""),[ae,A]=a.useState(R),[$,J]=a.useState(l);a.useEffect(()=>{A(R)},[R]),a.useEffect(()=>{J(l)},[l]),a.useEffect(()=>{u&&I(u)},[u]),a.useEffect(()=>{f&&j(g=>g||f)},[f]),a.useEffect(()=>{Y&&N(g=>g||Y)},[Y]),a.useEffect(()=>{m&&H(g=>g||m)},[m]);const Q=a.useCallback(async g=>{const w=ae,M=w.includes(g)?w.filter(F=>F!==g):[g,...w];A(M);try{await xs({favoriteProviders:M,favoriteModels:$}),await _()}catch{A(w)}},[ae,$,_]),T=a.useCallback(async g=>{const w=$,M=w.includes(g)?w.filter(F=>F!==g):[g,...w];J(M);try{await xs({favoriteProviders:ae,favoriteModels:M}),await _()}catch{J(w)}},[$,ae,_]),B=z||Y,re=g=>{if(g.preventDefault(),E==="agent"){if(!C)return;x({agentId:C});return}if(!B)return;const w=B.indexOf("/");if(w<=0)return;const h=B.slice(0,w),M=B.slice(w+1);x({agentId:Ge,modelProvider:h,modelId:M,thinkingLevel:se||void 0})},Ce=E==="agent"?!C:!B,v=zs(k,{enabled:!0});return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",...v,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:y("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${E==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{I("agent")},children:y("chat.newChatModeAgent","Agent")}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${E==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{I("model"),j(""),N(g=>g||Y)},children:y("chat.newChatModeModel","Model")})]}),t.jsxs("form",{onSubmit:re,children:[E==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:[y("chat.newChatModeAgent","Agent"),D?t.jsx("div",{className:"chat-new-dialog-loading",children:y("chat.loadingAgents","Loading agents...")}):s.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:y("chat.noAgentsAvailable","No agents available")}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:s.map(g=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${C===g.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>j(g.id),"data-testid":`agent-option-${g.id}`,children:[t.jsx(Bs,{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))})]}),E==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:L?t.jsx("div",{className:"chat-new-dialog-loading",children:y("chat.loadingModels","Loading models...")}):t.jsx(vo,{models:S,value:z,onChange:N,label:y("chat.newChatModeModel","Model"),placeholder:y("chat.selectModel","Select a model"),favoriteProviders:ae,onToggleFavorite:Q,favoriteModels:$,onToggleModelFavorite:T,showThinkingLevel:!0,thinkingLevel:se,onThinkingLevelChange:H,defaultThinkingLevel:d??"off"})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:k,children:y("chat.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:Ce,children:y("chat.create","Create")})]})]})]})})}function St({children:r,onClose:o}){const u=zs(o,{enabled:!0});return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",...u,children:r})}function ei({projectId:r,addToast:o,floating:u=!1,compactLayout:f=!1,onPopOut:d,onMaximize:m,onClose:k,chatCommandContext:x,initialComposerDraft:y,initialComposerDraftNonce:E,onSendAsReport:I}){const{t:s}=Xe("app"),D=Wr();a.useEffect(()=>(sa({view:"ChatView",trigger:ea?"route-active":"remount",projectId:r,replayAttempted:!1}),ea=!1,()=>{ea=!0,sa({view:"ChatView",trigger:"route-inactive",projectId:r,replayAttempted:!1})}),[r]);const[C,j]=a.useState(null);a.useEffect(()=>{let e=!1;return j(null),Gr(r).then(n=>{e||j(n)}).catch(()=>{e||j(null)}),()=>{e=!0}},[r]);const S=C?.defaultThinkingLevel??"off",R=a.useMemo(()=>C?.chatDefaultKind==="agent"&&C.chatDefaultAgentId?{kind:"agent",agentId:C.chatDefaultAgentId}:C?.chatDefaultKind==="model"&&C.chatDefaultModelProvider&&C.chatDefaultModelId?{kind:"model",modelProvider:C.chatDefaultModelProvider,modelId:C.chatDefaultModelId,thinkingLevel:C.chatDefaultThinkingLevel}:null,[C]),{activeSession:l,sessionsLoading:L,messages:_,messagesLoading:Y,isStreaming:z,streamingText:N,streamingThinking:se,streamingToolCalls:H,selectSession:ae,createSession:A,archiveSession:$,archivedSessions:J,refreshArchivedSessions:Q,unarchiveSession:T,renameSession:B,pinSession:re,pinnedCount:Ce,setSessionModel:v,setSessionThinkingLevel:g,deleteSession:w,tags:h=[],selectedTagId:M,setSelectedTagId:F,createTag:K,renameTag:de,deleteTag:ee,setSessionTags:ne,sendMessage:pe,editMessageAndResend:ue,stopStreaming:ke,pendingMessages:ve,pendingQueueAction:ge,clearPendingMessage:ln,updatePendingMessage:qs,movePendingMessage:Ws,forceSendPendingMessage:Gs,loadMoreMessages:ia,hasMoreMessages:dn,searchQuery:Xs,setSearchQuery:Qs,filteredSessions:Oe,agentsMap:un}=Xr(r,o),[Ys,mn]=a.useState(!1),Pe=!0,[P,Be]=a.useState(()=>{try{if(localStorage.getItem(ta)==="rooms"&&Pe)return"rooms"}catch{}return"direct"}),b=Ro(r,o),{isUnread:ca,markRead:he}=Mo(r),[V,oe]=a.useState(()=>{const e=Is(P,P==="rooms"?b.activeRoom?.id:l?.id);return Ls(e)}),[q,Re]=a.useState(null),[Qe,Js]=a.useState(!1),hn=a.useRef(null),la=(e,n,i,c)=>{typeof window>"u"||Re({sessionId:e,anchorX:n,anchorY:i,anchorRight:c?.anchorRight??!1,x:n,y:i})};a.useLayoutEffect(()=>{if(!q||!hn.current||typeof window>"u")return;const e=hn.current,n=e.getBoundingClientRect(),i=n.width||e.offsetWidth||Po,c=n.height||e.offsetHeight,p=_o(q.anchorX,q.anchorY,q.anchorRight,i,c,window.innerWidth,window.innerHeight);(p.x!==q.x||p.y!==q.y)&&Re({...q,...p})},[q]);const[jt,At]=a.useState(null),[fn,gn]=a.useState(""),[da,Tt]=a.useState(null),[ua,Et]=a.useState(null),[pn,ma]=a.useState(""),[vn,gt]=a.useState(null),[bn,ha]=a.useState(""),[fa,Dt]=a.useState(null),[Zs,ze]=a.useState(!1),[er,It]=a.useState(!1),{agentsMap:ga}=$s(r),Me=a.useMemo(()=>un.size>0?un:ga,[ga,un]),{models:wn,favoriteProviders:tr,favoriteModels:nr,defaultProvider:pa,defaultModelId:va}=Os(),Lt=a.useMemo(()=>({provider:pa,modelId:va}),[va,pa]),ar=a.useMemo(()=>R?.kind==="model"?{provider:R.modelProvider,modelId:R.modelId}:Lt,[R,Lt]),{skills:xn,loading:sr}=bo(r),[Ye,Ue]=a.useState(!1),[pt,vt]=a.useState(""),[Je,He]=a.useState(0),[Ze,et]=a.useState(""),[Se,tt]=a.useState(!1),[Ft,Pt]=a.useState(0),[yn,nt]=a.useState(-1),[fe,_t]=a.useState([]),[ba,at]=a.useState(!1),[wa,$t]=a.useState(!1),[st,xa]=a.useState({}),{pushNav:ya,removeNav:Ca}=Qr(),[,Ot]=a.useState(!1),[rr,or]=a.useState({top:0,left:0}),U=Lo({projectId:r}),Cn=a.useCallback(e=>{if(!e||!U.mentionActive)return;const n=e.getBoundingClientRect();or({top:n.top-260,left:n.left+8})},[U.mentionActive]),ka=a.useRef(null),Ra=a.useRef(null),le=a.useRef(!1),Bt=a.useRef(null),Ma=a.useRef(null),_e=a.useRef(null),zt=a.useRef(0),kn=a.useRef(null),bt=a.useRef(null),Ne=a.useRef(null),ie=a.useRef(null),Rn=a.useRef(null),rt=a.useRef(null),[Mn,ir]=a.useState(()=>new Set),Ut=a.useRef(!1),je=a.useRef(null),Ae=a.useRef(null),Z=a.useRef(null),wt=a.useRef(null),Ht=a.useRef(null),Kt=a.useRef(null),Sa=a.useRef(void 0),Sn=a.useRef(!1),Vt=a.useRef(null),Na=a.useRef([]),ot=a.useRef(0),xt=a.useRef(new Map),Nn=a.useRef(!1),ja=Yr(),Ke=ja==="mobile",Aa=ja==="tablet",Ta=a.useRef(null),[cr,Ea]=a.useState(!1);a.useLayoutEffect(()=>{if(!u){Ea(!1);return}const e=Ta.current;if(!e||typeof ResizeObserver>"u")return;const n=()=>{Ea(e.getBoundingClientRect().width<=768)};n();const i=new ResizeObserver(n);return i.observe(e),()=>i.disconnect()},[u]);const Te=Ke||cr||f;a.useEffect(()=>{l?.id&&he("direct",l.id,l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,he]),a.useEffect(()=>{b.activeRoom?.id&&he("room",b.activeRoom.id,b.activeRoom.updatedAt)},[b.activeRoom?.id,b.activeRoom?.updatedAt,he]),a.useEffect(()=>{if(!l?.id||_.length===0)return;const e=_[_.length-1];he("direct",l.id,e?.createdAt??l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,he,_]),a.useEffect(()=>{if(!b.activeRoom?.id||b.messages.length===0)return;const e=b.messages[b.messages.length-1];he("room",b.activeRoom.id,e?.createdAt??b.activeRoom.updatedAt)},[he,b.activeRoom?.id,b.activeRoom?.updatedAt,b.messages]),a.useEffect(()=>{try{const e=localStorage.getItem(ta);if(e==="direct"){Be("direct");return}e==="rooms"&&Pe&&Be("rooms")}catch{}},[Pe]),a.useEffect(()=>{try{localStorage.setItem(ta,P)}catch{}},[Pe,P]);const me=Is(P,P==="rooms"?b.activeRoom?.id:l?.id),jn=a.useRef(me),An=a.useRef(!1);a.useEffect(()=>{if(me!==jn.current){if(jn.current=me,An.current){An.current=!1;return}oe(Ls(me))}},[me]),a.useEffect(()=>{if(!(!me||jn.current!==me))try{if(V){localStorage.setItem(me,V);return}localStorage.removeItem(me)}catch{}},[me,V]);const te=P==="rooms"&&!!b.activeRoom,{keyboardOverlap:Da,keyboardOpen:Tn}=Jr({enabled:(Te||Aa)&&(!!l||te),allowNonMobileViewport:Aa}),qt=a.useMemo(()=>{const e=pt.trim().toLowerCase();return(e?xn.filter(i=>i.name.toLowerCase().includes(e)):xn).slice(0,10)},[xn,pt]),En=a.useMemo(()=>x?Zr(pt,ws):[],[x,pt]),be=a.useMemo(()=>{const e=En.map(i=>({kind:"command",command:i,disabled:!x?.agentRunning})),n=qt.map(i=>({kind:"skill",skill:i}));return[...e,...n]},[En,qt,x]),it=a.useMemo(()=>Array.from(Me.values()),[Me]),Ee=a.useMemo(()=>P!=="rooms"||!b.activeRoom?null:{roomId:b.activeRoom.id,roomName:b.activeRoom.name,memberIds:new Set(b.activeRoomMembers.map(e=>e.agentId))},[Pe,P,b.activeRoom,b.activeRoomMembers]),Ve=a.useMemo(()=>{const e=it.filter(c=>Vs(c.name,Ze));if(!Ee)return e;const n=e.filter(c=>Ee.memberIds.has(c.id));if(Ze.trim().length===0)return n;const i=e.filter(c=>!Ee.memberIds.has(c.id));return[...n,...i]},[it,Ze,Ee]),Dn=a.useMemo(()=>{const e=new Map;for(const n of it)e.set(n.name.toLowerCase(),n);return e},[it]),lr=a.useMemo(()=>qt.map(e=>e.id).join("\0"),[qt]);a.useEffect(()=>{He(0)},[lr]),a.useEffect(()=>{Pt(0)},[Ze,Se]),a.useEffect(()=>()=>{Ne.current!==null&&window.clearTimeout(Ne.current)},[]),a.useEffect(()=>{const e=Ra.current;if(!e||!dn||Y)return;const n=new IntersectionObserver(i=>{i[0].isIntersecting&&ia()},{threshold:.1});return n.observe(e),()=>n.disconnect()},[dn,Y,ia]);const ct=a.useCallback(()=>te?b.activeRoom?.id??null:l?.id??null,[te,b.activeRoom?.id,l?.id]),Ia=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,'\\"')}"]`),[]),La=a.useCallback(()=>{const e=ie.current;if(!e)return;const n=e.getBoundingClientRect().top,i=new Set;e.querySelectorAll(".chat-message--assistant:not(.chat-message--failure)[data-message-id]").forEach(c=>{const p=c.getAttribute("data-message-id");p&&c.getBoundingClientRect().top<n&&i.add(p)}),ir(c=>c.size===i.size&&Array.from(c).every(p=>i.has(p))?c:i)},[]),Wt=a.useCallback(()=>{!ie.current||rt.current!==null||(rt.current=window.requestAnimationFrame(()=>{rt.current=null,La()}))},[La]),Gt=a.useCallback(()=>{const e=ie.current,n=ct();if(!e||!n)return;const i=e.scrollTop,c=e.querySelectorAll(".chat-message[data-message-id]"),p=Array.from(c).find(G=>G.offsetTop+G.offsetHeight>=i)??c[0]??null,O=p?.getAttribute("data-message-id")??null,X=p?p.offsetTop-i:0;bt.current={threadId:n,scrollTop:i,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,anchorMessageId:O,anchorOffset:X,wasPinnedBefore:!le.current,capturedAtMs:typeof performance<"u"?performance.now():Date.now()}},[ct]),Fa=a.useCallback(()=>{const e=ie.current;if(!e)return;const i=e.scrollTop+e.clientHeight>=e.scrollHeight-50;$t(!i),le.current=!i,Gt(),Wt()},[Gt,Wt]),De=a.useCallback((e,n)=>{if(!e.isConnected||!n?.force&&le.current)return;let i=0,c=0,p=-1;const O=6,X=()=>{if(e.isConnected&&!(!n?.force&&le.current)){if(e.scrollTop=e.scrollHeight,e.scrollHeight===p?c+=1:(c=0,p=e.scrollHeight),i+=1,i>=O||c>=2){$t(!1),le.current=!1;return}window.requestAnimationFrame(X)}};X()},[]),lt=te?b.messages:_;a.useLayoutEffect(()=>(Wt(),()=>{rt.current!==null&&(window.cancelAnimationFrame(rt.current),rt.current=null)}),[lt,Wt]),a.useLayoutEffect(()=>{const e=ie.current,n=ct(),i=bt.current;if(!e||!n||!i||i.threadId!==n||i.wasPinnedBefore)return;const c=(typeof performance<"u"?performance.now():Date.now())-i.capturedAtMs,p=e.scrollHeight>e.clientHeight,O=c>3e3,X=i.scrollTop<=0&&i.anchorOffset<=0&&p;if(!le.current||O||X){bt.current=null;return}let G=i.scrollTop;if(i.anchorMessageId){const ye=Ia(e,i.anchorMessageId);ye?G=ye.offsetTop-i.anchorOffset:G=i.scrollTop+(e.scrollHeight-i.scrollHeight)}else G=i.scrollTop+(e.scrollHeight-i.scrollHeight);e.scrollTop=Math.max(0,G),le.current=!0,$t(!0),bt.current=null},[lt,ct,Ia]);const In=a.useCallback(e=>{},[lt.length,te]),we=a.useCallback(e=>{In(e);const n=ie.current;n&&(bt.current=null,le.current=!1,De(n))},[De,In]);a.useLayoutEffect(()=>{_e.current!==null&&(window.clearTimeout(_e.current),_e.current=null);const e=te?b.activeRoom?.id??null:l?.id??null;if(!e){Bt.current=null;return}const n={threadId:e,loaded:te?!b.messagesLoading:!Y,hasMessages:te?b.messages.length>0:_.length>0},i=Bt.current,c=i?.threadId!==e,p=i?.threadId===e&&!i.loaded&&n.loaded,O=i?.threadId===e&&!i.hasMessages&&n.hasMessages;if(!(i===null||c||p||O))return;const G=ie.current;if(G)return In(c?"thread-change":p?"finished-loading":O?"first-messages":"mount"),De(G,{force:!0}),te||(_e.current=window.setTimeout(()=>{if(_e.current=null,le.current)return;const ye=ie.current;ye&&De(ye)},250)),Bt.current=n,()=>{_e.current!==null&&(window.clearTimeout(_e.current),_e.current=null)}},[te,b.activeRoom?.id,b.messages.length,b.messagesLoading,l?.id,_.length,Y,De]),a.useEffect(()=>{!z||le.current||we("streaming")},[z,N,se,we]),a.useEffect(()=>{const e=ct();if(!e){zt.current=0,kn.current=null;return}if(kn.current!==e){kn.current=e,zt.current=lt.length;return}const n=zt.current,i=lt.length,c=i>n,p=!le.current;zt.current=i,c&&p&&we("new-message")},[lt,ct,we]),a.useEffect(()=>{Da<=0||!ie.current||we("keyboard")},[Da,we]),eo(Ke&&Tn),a.useLayoutEffect(()=>{if(!Ke||!l&&!te||typeof window>"u")return;const e=Rn.current,n=window.visualViewport;if(!e||!n)return;const i=p=>{if(!(p instanceof HTMLElement))return!1;if(p.tagName==="TEXTAREA")return!0;if(p.tagName!=="INPUT")return!1;const O=p.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(O)},c=()=>{if(Ut.current){e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange="";return}const p=Math.max(0,window.innerHeight-n.offsetTop-n.height),O=n.offsetTop||0;e.style.setProperty("--vv-height",`${n.height}px`),e.style.setProperty("--vv-offset-top",`${O}px`),e.style.setProperty("--keyboard-overlap",`${p}px`);const X=(p>0||O>0)&&i(document.activeElement);e.classList.toggle("chat-thread--keyboard-active",X),e.style.setProperty("--chat-keyboard-accessory-clearance",X&&Yn()?"calc(var(--space-2xl) + var(--space-md))":"0px"),X&&O>0?(e.style.transform=`translateY(${O}px)`,e.style.willChange="transform"):(e.style.transform="",e.style.willChange="")};return c(),n.addEventListener("resize",c),n.addEventListener("scroll",c),document.addEventListener("focusin",c),document.addEventListener("focusout",c),window.addEventListener("pageshow",c),document.addEventListener("visibilitychange",c),()=>{n.removeEventListener("resize",c),n.removeEventListener("scroll",c),document.removeEventListener("focusin",c),document.removeEventListener("focusout",c),window.removeEventListener("pageshow",c),document.removeEventListener("visibilitychange",c),e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange=""}},[l,Ke,te]),a.useEffect(()=>{const e=()=>Re(null);if(q)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[q]),a.useEffect(()=>{if(!Ke||!Tn)return;const e=n=>{n.target?.closest(".chat-messages")||n.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[Ke,Tn]),a.useEffect(()=>{const e=Ma.current;if(Ma.current=P,P==="rooms"&&!b.activeRoom){Bt.current=null;return}if(!(P==="direct"&&(e===null||e==="rooms"))&&!(P==="rooms"&&(e===null||e==="direct")))return;const c=ie.current;c&&(De(c,{force:!0}),le.current=!1,$t(!1))},[P,b.activeRoom,De]),a.useEffect(()=>{if(!l&&!te||te&&!Te)return;const e=()=>{const i=!le.current;Gt(),i&&Te&&ie.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)}},[Te,Ke,l,te,Gt,we]),a.useEffect(()=>{if(te||typeof ResizeObserver>"u")return;const e=ie.current;if(!e)return;const n=new ResizeObserver(()=>{le.current||De(e)});return n.observe(e),()=>{n.disconnect()}},[te,De,l?.id,P]),a.useEffect(()=>{Na.current=fe},[fe]),a.useEffect(()=>()=>{for(const e of Na.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of xt.current.values())window.clearTimeout(e);xt.current.clear()},[]);const dt=a.useCallback(e=>{if(!e||e.length===0)return;const n=[];for(const i of Array.from(e)){if(!Bo.includes(i.type))continue;const c=i.type.startsWith("image/");n.push({file:i,previewUrl:c?URL.createObjectURL(i):""})}n.length>0&&_t(i=>[...i,...n])},[]),Pa=a.useCallback(e=>{_t(n=>{const i=n[e];return i?.previewUrl&&URL.revokeObjectURL(i.previewUrl),n.filter((c,p)=>p!==e)})},[]),_a=a.useCallback(e=>{dt(e.clipboardData?.files)},[dt]),ut=a.useCallback(async e=>{try{return await A(e),Be("direct"),mn(!1),ze(!0),!0}catch{return o(s("chat.failedToCreateSession","Failed to create chat session"),"error"),!1}},[A,o,Te,s]),$a=a.useCallback(()=>{if(C?.chatNewSessionMode==="always-default"&&R){if(R.kind==="agent"){ut({agentId:R.agentId});return}ut({agentId:Ge,modelProvider:R.modelProvider,modelId:R.modelId,thinkingLevel:R.thinkingLevel});return}mn(!0)},[R,C?.chatNewSessionMode,ut]),ce=a.useCallback(e=>{if(!e||e===Z.current){Ht.current?.resize();return}e===wt.current&&Kt.current?.resize()},[]),dr=os({textareaRef:Z,value:V,onChange:oe,onResize:()=>ce(Z.current),projectId:r}),ur=os({textareaRef:wt,value:V,onChange:oe,onResize:()=>ce(wt.current),projectId:r}),mr=a.useCallback(e=>{Ht.current?.destroy(),Ht.current=null,Z.current=e,e&&(Ht.current=is(e))},[]),hr=a.useCallback(e=>{Kt.current?.destroy(),Kt.current=null,wt.current=e,e&&(Kt.current=is(e))},[]);a.useLayoutEffect(()=>{ce(P==="rooms"?wt.current:Z.current),Sn.current&&(Sn.current=!1,Z.current?.focus())},[P,V,l?.id,b.activeRoom?.id,ce]),a.useEffect(()=>{if(E===void 0||E===Sa.current||!y?.trim())return;Sa.current=E;const e=n=>{n&&(An.current=!0),Be("direct"),Sn.current=!0,oe(y)};if(!z&&C?.chatNewSessionMode==="always-default"&&R){const n=R.kind==="agent"?{agentId:R.agentId}:{agentId:Ge,modelProvider:R.modelProvider,modelId:R.modelId,thinkingLevel:R.thinkingLevel};ut(n).then(i=>e(i||P!=="direct"));return}e(P!=="direct")},[R,P,C?.chatNewSessionMode,ut,y,E,z,ce]);const mt=a.useCallback(()=>{if(oe(""),me)try{localStorage.removeItem(me)}catch{}Ue(!1),vt(""),tt(!1),et(""),nt(-1),_t(e=>{for(const n of e)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);return[]})},[me]),qe=a.useCallback(e=>{_t(n=>{const i=n.filter(c=>e.has(c.file));for(const c of i)c.previewUrl&&URL.revokeObjectURL(c.previewUrl);return n.filter(c=>!e.has(c.file))})},[]),Ln=a.useCallback(()=>{const e=V.trim(),n=fe.map(c=>c.file);if(!e&&n.length===0||!l)return;if(x){const c=to(e,ws);if(c){if(!x.agentRunning){o(s("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}if(n.length>0){o(s("chat.commandNoAttachments","Attachments aren't supported with commands — remove them before sending"),"warning");return}mt(),c.command.run({taskId:x.taskId,projectId:x.projectId,remainder:c.remainder}).then(()=>{o(s("chat.commandSteerSuccess","Sent to the running agent"),"success")}).catch(p=>{const O=p instanceof Error&&p.message.trim()?p.message:s("chat.commandSteerFailed","Failed to send to the running agent");o(O,"error")});return}}if(e==="/clear"||e==="/new"){if(n.length>0){o(s("chat.clearNoAttachments","Remove the attachments before running /clear or /new — they would be discarded unsent"),"warning");return}if(l.agentId.startsWith(no)){mt(),o(s("chat.newNotAllowedForTaskChat","This chat is tied to a task — /new and /clear can't clear it"),"warning");return}mt(),ln(),ke().then(()=>A({agentId:l.agentId,modelProvider:l.modelProvider??void 0,modelId:l.modelId??void 0,thinkingLevel:l.thinkingLevel??void 0})).catch(()=>{o(s("chat.failedToClearConversation","Failed to clear conversation"),"error")});return}if(z&&n.length>0){o(s("chat.attachmentsNotQueued","Attachments can't be queued while a reply is streaming — wait for it to finish"),"warning");return}const i=new Set(n);oe("");try{pe(e,n,{onAccepted:()=>qe(i),onDelivered:()=>qe(i),onFailed:()=>{oe(c=>c||e)}})}catch{oe(e)}},[V,fe,l,mt,ke,ln,A,o,pe,x,z,qe,s]),Fn=a.useCallback(async()=>{const e=V.trim(),n=fe.map(i=>i.file);if(!(!e&&n.length===0)){if(P==="rooms"){if(!b.activeRoom)return;if(e==="/clear"||e==="/new"){if(n.length>0){o(s("chat.clearNoAttachments","Remove the attachments before running /clear or /new — they would be discarded unsent"),"warning");return}mt();try{await b.clearRoom(b.activeRoom.id)}catch{o(s("chat.failedToClearRoomConversation","Failed to clear room conversation"),"error")}return}if(Nn.current)return;Nn.current=!0;const i=V,c=new Set(n);oe("");try{await b.sendRoomMessage(e,{files:n,onDelivered:()=>qe(c)}),qe(c)}catch(p){if(p instanceof Hs){qe(c);const X=p.message.trim()?p.message:s("chat.messageSentButReplyFailed","Message sent, but assistant reply failed");o(s("chat.messageSentButReplyFailedDetail","Message sent, but assistant reply failed: {{detail}}",{detail:X}),"error");return}oe(i);const O=p instanceof Error&&p.message.trim()?p.message:s("chat.failedToSendRoomMessage","Failed to send room message");o(O,"error")}finally{Nn.current=!1}return}Ln()}},[V,fe,Pe,P,b,b.clearRoom,mt,o,Ln,qe]),Xt=a.useCallback(async e=>{if(P==="rooms"){if(!b.activeRoom)return;try{await b.sendRoomMessage(e)}catch(n){const i=n instanceof Error&&n.message.trim()?n.message:s("chat.failedToSendRoomMessage","Failed to send room message");o(i,"error")}return}l&&pe(e)},[l,o,Pe,P,b,pe,s]),Pn=a.useCallback(e=>{oe(n=>{const i=na(n);if(!i)return n;const c=`/skill:${e.name} `,p=n.slice(0,i.start)+c+n.slice(i.end);return window.requestAnimationFrame(()=>{Z.current&&(ce(Z.current),Z.current.focus())}),p}),Ue(!1),vt(""),He(0)},[ce]),_n=a.useCallback((e,n)=>{if(n){o(s("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}oe(i=>{const c=na(i);if(!c)return i;const p=`${e.trigger} `,O=i.slice(0,c.start)+p+i.slice(c.end);return window.requestAnimationFrame(()=>{Z.current&&(ce(Z.current),Z.current.focus())}),O}),Ue(!1),vt(""),He(0)},[ce,o,s]),Qt=a.useCallback(e=>{const n=Z.current;if(!n||yn<0)return;const i=n.selectionStart??ot.current,c=n.selectionEnd??i,p=Math.max(i,c),O=Math.min(yn,p),G=`${`@${e.name.replace(/\s+/g,"_")}`} `,ye=V.slice(0,O)+G+V.slice(p),as=O+G.length;oe(ye),tt(!1),et(""),Pt(0),nt(-1),window.requestAnimationFrame(()=>{Z.current&&(ce(Z.current),Z.current.focus(),Z.current.setSelectionRange(as,as))})},[yn,V,ce]),yt=a.useCallback((e,n)=>{const c=Z.current?.selectionStart??ot.current,p=V.lastIndexOf("#",c),O=p>=0?p+n.length:e.length;oe(e),U.dismissMention(),Ot(!1),window.requestAnimationFrame(()=>{Z.current&&(ce(Z.current),Z.current.focus(),Z.current.setSelectionRange(O,O))})},[U,V,ce]),Oa=a.useCallback(e=>{if(ot.current=e.currentTarget.selectionStart??ot.current,U.mentionActive&&U.combinedItems.length>0){if(U.handleKeyDown(e,V),e.key==="Enter"||e.key==="Tab"){const n=U.combinedItems[U.selectedIndex];n?.kind==="task"?yt(U.selectTask(n.task,V),`#${n.task.id}`):n?.kind==="file"&&yt(U.selectFile(n.file,V),`#${n.file.path}`)}return}if(Se&&e.key==="ArrowDown"){e.preventDefault(),Ve.length>0&&Pt(n=>(n+1)%Ve.length);return}if(Se&&e.key==="ArrowUp"){e.preventDefault(),Ve.length>0&&Pt(n=>n===0?Ve.length-1:n-1);return}if(Se&&e.key==="Enter"){e.preventDefault();const n=Ve[Ft]??Ve[0];n&&Qt(n);return}if(Se&&e.key==="Escape"){e.preventDefault(),tt(!1),et(""),nt(-1);return}if(Ye&&e.key==="ArrowDown"){e.preventDefault(),be.length>0&&He(n=>(n+1)%be.length);return}if(Ye&&e.key==="ArrowUp"){e.preventDefault(),be.length>0&&He(n=>n===0?be.length-1:n-1);return}if(Ye&&(e.key==="Enter"||e.key==="Tab")&&be.length>0){e.preventDefault();const n=be[Je]??be[0];n?.kind==="skill"?Pn(n.skill):n?.kind==="command"&&_n(n.command,n.disabled);return}if(Ye&&e.key==="Escape"){e.preventDefault(),Ue(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Fn())},[Se,Ve,Ft,Qt,Ye,be,Je,Pn,_n,Fn,U,yt,V]),Yt=a.useCallback((e,n)=>{const i=zo(e,n);if(i){tt(!0),et(i.filter),nt(i.start);return}tt(!1),et(""),nt(-1)},[]),Ba=a.useCallback(e=>{const n=e.target,i=n.value,c=n.selectionStart??i.length;ce(n),ot.current=c,oe(i);const p=na(i);p?(Ue(!0),vt(p.filter)):(Ue(!1),vt("")),Yt(i,c),U.detectMention(i,c),Ot(U.mentionActive),U.mentionActive&&Cn(n)},[Yt,ce]),Jt=a.useCallback(e=>{const n=e.currentTarget,i=n.selectionStart??n.value.length;ot.current=i,Yt(n.value,i),U.detectMention(n.value,i),Ot(U.mentionActive),U.mentionActive&&Cn(n)},[Yt,U,Cn]),za=a.useCallback(e=>{e.key!=="Escape"&&Jt(e)},[Jt]),Ua=a.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(Ut.current=!0,je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{Ut.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)),Ne.current!==null&&window.clearTimeout(Ne.current),Ne.current=window.setTimeout(()=>{Ue(!1),tt(!1),et(""),nt(-1),Ot(!1),U.dismissMention(),Ne.current=null},120)},[U]),Ha=a.useCallback(()=>{Ut.current=!1,je.current!==null&&(window.clearTimeout(je.current),je.current=null),Ne.current!==null&&(window.clearTimeout(Ne.current),Ne.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 fr=a.useCallback(async e=>{Re(null);try{await $(e),o(s("chat.conversationArchived","Conversation archived"),"success")}catch{o(s("chat.failedToArchiveConversation","Failed to archive conversation"),"error")}},[$,o]),gr=a.useCallback(async e=>{try{await T(e),o(s("chat.conversationRestored","Conversation restored"),"success")}catch{o(s("chat.failedToRestoreConversation","Failed to restore conversation"),"error")}},[T,o,s]),pr=a.useCallback(e=>{const n=Oe.find(i=>i.id===e)??(l?.id===e?l:null);Re(null),gn(n?.title??""),At({sessionId:e,title:n?.title??""})},[l,Oe]),Ka=a.useCallback(async()=>{if(jt)try{await B(jt.sessionId,fn),At(null),gn(""),o(s("chat.conversationRenamed","Conversation renamed"),"success")}catch{}},[o,jt,B,fn,s]),vr=a.useCallback(async(e,n)=>{Re(null);try{await re(e,n),o(n?s("chat.conversationPinned","Conversation pinned"):s("chat.conversationUnpinned","Conversation unpinned"),"success")}catch{}},[o,re,s]),br=a.useCallback(async e=>{Tt(null),Re(null);try{await w(e),o(s("chat.conversationDeleted","Conversation deleted"),"success")}catch{o(s("chat.failedToDeleteConversation","Failed to delete conversation"),"error")}},[w,o]),wr=a.useCallback(e=>{const n=Oe.find(i=>i.id===e);he("direct",e,n?.lastMessageAt??n?.updatedAt),ae(e),ze(!0)},[Oe,he,ae]),Zt=a.useCallback(()=>{ze(!1)},[]),en=a.useCallback(()=>{ze(!1)},[]),Va=a.useCallback(()=>{const e=P==="rooms"?en:Zt;e(),Ca?.(e)},[P,Zt,en,Ca]),xr=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(on,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:s("chat.startNewConversation","Start a new conversation")}),t.jsxs("button",{className:"btn btn-primary",onClick:$a,children:[t.jsx(an,{size:16}),s("chat.newChat","New Chat")]})]}),Ie=Ps(l,l?.agentId?Me.get(l.agentId)??null:null,Lt),$n=a.useMemo(()=>{if(!Ie?.provider||!Ie.modelId)return null;const e=wn.find(n=>n.provider===Ie.provider&&n.id===Ie.modelId);return e?.contextWindow?e.contextWindow:null},[Ie?.modelId,Ie?.provider,wn]),yr=a.useMemo(()=>Fo(_,z?N:void 0),[z,_,N]),ht=cs(Ie?.provider,Ie?.modelId),Ct=Ie?.provider??null,On=!!(l||z||_.length>0),Le=Zs&&(P==="rooms"?te:On),qa=a.useRef(Le);a.useEffect(()=>{const e=qa.current;qa.current=Le,!(e||!Le)&&ya({type:"view",revert:P==="rooms"?en:Zt})},[P,Zt,en,Le,ya]);const Wa=l?.title?.trim()||s("chat.untitledConversation","Untitled conversation"),Cr=!!ht,kr=!Te&&On&&$n!==null,Ga=As(yr),tn=$n!==null?As($n):null,Bn=tn?s("chat.contextWindowAria","Estimated {{used}} of {{total}} context tokens",{used:Ga,total:tn}):null,zn=Me.get(l?.agentId??"")?.name||(l?.agentId===Ge?ht??"Fusion":l?.agentId?.slice(0,30)??"Fusion"),Un=!1,Hn=l?.agentId===Ge,Xa=a.useCallback((e,n)=>{const i=xt.current.get(e);i&&window.clearTimeout(i),xa(p=>({...p,[e]:n}));const c=window.setTimeout(()=>{xa(p=>{const{[e]:O,...X}=p;return X}),xt.current.delete(e)},2e3);xt.current.set(e,c)},[]),Qa=a.useCallback(async(e,n)=>{const i=await ao(n);Xa(e,i?"success":"error")},[Xa]),Kn=l?.agentId===Ge,Vn=a.useCallback((e,n,i,c,p=!0)=>{const O=Kn&&i==="assistant",X=p&&i==="assistant"&&I?so(n,s("chat.reportFallbackTitle","Chat report")):null;if(!(!O&&!X?.handoff))return t.jsxs(t.Fragment,{children:[O&&t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${st[e]==="success"?" chat-message-copy-action--success":""}${st[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":c??`chat-copy-response-${e}`,"aria-label":st[e]==="success"?s("chat.responseCopied","Response copied"):st[e]==="error"?s("chat.copyFailed","Copy failed"):s("chat.copyResponse","Copy response"),onClick:()=>{Qa(e,n)},children:st[e]==="success"?t.jsx(ro,{size:14}):t.jsx(oo,{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&&o(s("chat.reportTrimmed","Message trimmed to 2000 characters for mail"),"warning"),I?.(X.handoff)},children:t.jsx(io,{size:14})})]})},[o,st,Qa,I,Kn,s]),qn=a.useCallback(e=>{const n=ie.current;if(!n)return;const i=`[data-testid="chat-message-${e}"]`,c=n.querySelector(i);if(!c)return;const p=c.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop,O=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;n.scrollTo({top:p,behavior:O?"auto":"smooth"})},[]),Ya=l?.cliExecutorAdapterId??null,Wn=!!Ya,Rr=Ya==="generic"?"generic":"hybrid",Mr=l?.cliSessionFile||l?.id||"",Ja=!Wn&&!z,Za=()=>t.jsxs("div",{className:"chat-messages",ref:ie,onScroll:Fa,children:[t.jsx("div",{ref:Ra,className:"chat-load-more-sentinel",children:dn&&Y&&t.jsx("div",{className:"chat-loading-older",children:s("chat.loadingOlderMessages","Loading older messages…")})}),z?t.jsxs(t.Fragment,{children:[_.map((e,n)=>t.jsx(Qn,{message:e,forcePlain:!1,agentName:zn,hideAssistantIdentity:Hn,showAssistantModelTag:Un,activeModelTag:ht,activeModelProvider:Ct,activeSessionId:l?.id??null,projectId:r,mentionAgentsByName:Dn,roomContext:null,copyAction:Vn(e.id,e.content,e.role),onScrollToTop:qn,isTopClipped:Mn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===_.length-1&&!z,submittedQuestionAnswer:Ds(_,n),onQuestionSubmit:Xt,canEdit:Ja,onEditMessage:ue},e.id)),t.jsx(go,{streamingText:N,streamingThinking:se,streamingToolCalls:H,forcePlain:!1,agentName:zn,hideAssistantIdentity:Hn,showAssistantModelTag:Un,activeModelTag:ht,activeModelProvider:Ct,copyAction:Kn&&N?Vn("__streaming__",N,"assistant","chat-copy-response-streaming",!1):void 0,onQuestionSubmit:Xt})]}):Y&&_.length===0?t.jsx("div",{className:"chat-empty-state",children:s("chat.loadingMessages","Loading messages...")}):_.length===0&&!l?xr():_.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(Qn,{message:e,forcePlain:!1,agentName:zn,hideAssistantIdentity:Hn,showAssistantModelTag:Un,activeModelTag:ht,activeModelProvider:Ct,activeSessionId:l?.id??null,projectId:r,mentionAgentsByName:Dn,roomContext:null,copyAction:Vn(e.id,e.content,e.role),onScrollToTop:qn,isTopClipped:Mn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===_.length-1&&!z,submittedQuestionAnswer:Ds(_,n),onQuestionSubmit:Xt,canEdit:Ja,onEditMessage:ue},e.id))}),t.jsx("div",{ref:ka})]}),es=()=>t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Vt,type:"file","data-testid":"chat-file-input",accept:Fs,multiple:!0,style:{display:"none"},onChange:e=>{dt(e.target.files),e.target.value=""}}),Ye&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":s("chat.skillSuggestions","Skill suggestions"),children:sr&&En.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:s("chat.loadingSkills","Loading skills…")}):be.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:pt?s("chat.noSkillsFound","No skills found"):s("chat.noSkillsAvailable","No skills available")}):be.map((e,n)=>e.kind==="command"?t.jsxs("button",{type:"button",role:"option","aria-selected":n===Je,"aria-disabled":e.disabled,className:`chat-skill-menu-item chat-command-menu-item${n===Je?" chat-skill-menu-item--highlighted":""}${e.disabled?" chat-command-menu-item--disabled":""}`,onMouseDown:i=>i.preventDefault(),onMouseEnter:()=>He(n),onClick:()=>_n(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===Je,className:`chat-skill-menu-item${n===Je?" chat-skill-menu-item--highlighted":""}`,onMouseDown:i=>i.preventDefault(),onMouseEnter:()=>He(n),onClick:()=>Pn(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))}),fe.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:fe.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:()=>Pa(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),t.jsx(po,{messages:ve,disabled:ge,onEdit:qs??(()=>{}),onMove:Ws??(()=>{}),onDelete:ln,onForceSend:Gs??(()=>{}),testIdPrefix:"chat-pending"}),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:()=>Vt.current?.click(),disabled:ge,children:t.jsx(gs,{size:16})}),!Wn&&t.jsx(ps,{level:l?.thinkingLevel,defaultThinkingLevel:S,models:wn,favoriteProviders:tr,favoriteModels:nr,agents:Array.from(Me.values()),agentId:l?.agentId,modelProvider:l?.modelProvider,modelId:l?.modelId,onChange:e=>{l&&g(l.id,e)},onChangeModel:e=>{l&&v(l.id,e)},disabled:!l||ge}),t.jsxs("div",{className:`chat-input-wrapper${ba?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),at(!0)},onDragLeave:()=>at(!1),onDrop:e=>{e.preventDefault(),at(!1),dt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:mr,className:"chat-input-textarea",placeholder:s("chat.typeMessage","Type a message..."),value:V,onChange:Ba,onKeyDown:Oa,onKeyUp:za,onClick:Jt,onBlur:Ua,onFocus:Ha,onPaste:_a,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||Yn()&&(document.activeElement,e.currentTarget)},rows:1,disabled:ge,"data-testid":"chat-input"}),t.jsx(Ms,{agents:it,filter:Ze,highlightedIndex:Ft,visible:Se,onSelect:Qt,position:Ts,roomMemberIds:Ee?.memberIds,roomName:Ee?.roomName}),t.jsx(No,{visible:U.mentionActive&&!Se,position:rr,tasks:U.tasks,files:U.files,selectedIndex:U.selectedIndex,onSelectTask:e=>{yt(U.selectTask(e,V),`#${e.id}`)},onSelectFile:e=>{yt(U.selectFile(e,V),`#${e.path}`)},loading:U.loading})]}),t.jsx(vs,{...dr.micProps,disabled:ge}),t.jsx(bs,{isStreaming:z,canSend:!ge&&!!(V.trim()||fe.length>0),onSend:Ln,onStop:ke})]})]}),ts=Qe?J:Oe,Sr=ts.filter(e=>e.pinnedAt!=null),Nr=ts.filter(e=>e.pinnedAt==null),xe=q?Oe.find(e=>e.id===q.sessionId)??(l?.id===q.sessionId?l:void 0):void 0,ns=a.useCallback(async()=>{const e=pn.trim();if(!e)return;let n;try{n=await K(e)}catch{o(s("chat.failedToCreateTag","Failed to create tag"),"error");return}if(q?.sessionId){const i=(xe?.tags??[]).map(c=>c.id);if(!i.includes(n.id))try{await ne(q.sessionId,[...i,n.id])}catch{o(s("chat.failedToUpdateTags","Failed to update tags"),"error");return}}ma("")},[o,q,xe,K,pn,ne,s]),jr=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${P==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":P==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>Be("direct"),children:[t.jsx(on,{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${P==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":P==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>Be("rooms"),children:[t.jsx(Us,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.scopeRooms","Rooms")})]})]});return t.jsxs("div",{ref:Ta,className:`chat-view${u?" chat-view--floating":""}${Te?" chat-view--narrow":""}${Le?" chat-view--detail":""}${D==="full-width"?" chat-view--full-width":""}`,children:[t.jsx(co,{icon:on,title:s("chat.title","Chat"),actions:t.jsxs(t.Fragment,{children:[Le?null:jr,t.jsxs("button",{className:"btn btn-sm btn-primary chat-view-header-new-chat",onClick:$a,"data-testid":"chat-new-btn",children:[t.jsx(an,{size:14}),s("chat.newChat","New Chat")]}),!u&&d?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:d,"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,u&&m?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:m,"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,u&&k?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:k,"aria-label":s("chat.closeChat","Close chat"),title:s("chat.closeChat","Close chat"),"data-testid":"chat-modal-close",children:t.jsx(ds,{size:16})}):null]})}),t.jsxs("div",{className:"chat-view__body",children:[t.jsxs("div",{className:`chat-sidebar${Le?" chat-sidebar--hidden":""}`,children:[P==="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(lo,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:s("chat.searchConversations","Search conversations..."),value:Xs,onChange:e=>Qs(e.target.value),"data-testid":"chat-search-input"})]}),t.jsxs("label",{className:"chat-tag-filter",htmlFor:"chat-tag-filter",children:[t.jsx(yo,{size:14,"aria-hidden":"true"}),t.jsxs("select",{id:"chat-tag-filter",value:M??"",onChange:e=>F(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")}),h.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]}),M?t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.clearTagFilter","Clear tag filter"),onClick:()=>F(null),children:t.jsx(ds,{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=!Qe;Js(e),e&&Q()},children:Qe?"Active conversations":"Archived conversations"})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:L?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:s("chat.loadingConversations","Loading...")}):(Qe?J:Oe).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:Sr},{id:"recent",label:s("chat.recent","Recent"),testId:"chat-recent-divider",sessions:Nr}].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 i=l?.id===n.id,c=!i&&ca("direct",n.id,n.lastMessageAt??n.updatedAt),p=Ps(n,Me.get(n.agentId)??null,Lt),O=cs(p?.provider,p?.modelId)??"Fusion",X=n.title||s("chat.untitledSession","Untitled");return t.jsxs("div",{className:`chat-session-item${i?" chat-session-item--active":""}`,onClick:()=>wr(n.id),onContextMenu:G=>{G.preventDefault(),la(n.id,G.clientX,G.clientY)},"data-testid":Qe?`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":q?.sessionId===n.id,onClick:G=>{if(G.stopPropagation(),q?.sessionId===n.id){Re(null);return}const ye=G.currentTarget.getBoundingClientRect();la(n.id,ye.right,ye.bottom,{anchorRight:!0})},children:t.jsx(uo,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[X,n.pinnedAt?t.jsx(us,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":s("chat.pinned","Pinned")}):null,c?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(G=>t.jsx("span",{className:"chat-session-tag",children:G.name},G.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,Qe?t.jsx("button",{type:"button",className:"btn btn-sm btn-secondary","data-testid":`chat-archived-restore-${n.id}`,onClick:G=>{G.stopPropagation(),gr(n.id)},children:s("chat.restore","Restore")}):null,t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[p?.provider?t.jsx(ms,{provider:p.provider,size:"sm"}):null,t.jsx("span",{children:Me.get(n.agentId)?.name||(n.agentId===Ge?O:n.agentId.slice(0,30))})]}),t.jsx("span",{children:n.updatedAt?$o(n.updatedAt,s):""})]})]},n.id)})]},e.id))})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!Te&&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:()=>It(!0),children:[t.jsx(an,{size:14}),s("chat.createRoom","Create room")]})}),b.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:b.rooms.map(e=>{const n=b.activeRoom?.id===e.id,i=!n&&ca("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:()=>{he("room",e.id,e.updatedAt),b.selectRoom(e.id),ze(!0)},onKeyDown:c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),he("room",e.id,e.updatedAt),b.selectRoom(e.id),ze(!0))},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]}),i?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:b.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:c=>{c.stopPropagation(),Et(e.id)},children:t.jsx(Xn,{size:14})})]},e.id)})})]}),P==="rooms"&&Te?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:()=>It(!0),children:[t.jsx(an,{size:14}),s("chat.createRoom","Create room")]})}):null]}),q&&t.jsxs("div",{className:"chat-session-context-menu",ref:hn,role:"menu",style:{top:q.y,left:q.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>vr(q.sessionId,!xe?.pinnedAt),"data-testid":"chat-context-pin",title:Ce>=3&&!xe?.pinnedAt?s("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:Ce>=3&&!xe?.pinnedAt,children:[xe?.pinnedAt?t.jsx(mo,{size:14}):t.jsx(us,{size:14}),xe?.pinnedAt?s("chat.unpin","Unpin"):s("chat.pin","Pin")]}),t.jsxs("button",{onClick:()=>pr(q.sessionId),"data-testid":"chat-context-rename",children:[t.jsx(hs,{size:14}),s("chat.rename","Rename")]}),t.jsxs("div",{className:"chat-session-tag-menu",role:"group","aria-label":s("chat.conversationTags","Conversation tags"),children:[h.map(e=>{const n=(xe?.tags??[]).some(i=>i.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 ne(q.sessionId,n?(xe?.tags??[]).filter(i=>i.id!==e.id).map(i=>i.id):[...(xe?.tags??[]).map(i=>i.id),e.id]).catch(()=>o(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:i=>{i.stopPropagation(),ha(e.name),gt(e)},children:t.jsx(hs,{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:i=>{i.stopPropagation(),Dt(e)},children:t.jsx(Xn,{size:14})})]},e.id)}),t.jsxs("div",{className:"chat-tag-create-row",children:[t.jsx("input",{className:"input",value:pn,placeholder:s("chat.newTag","New tag"),"aria-label":s("chat.newTag","New tag"),onChange:e=>ma(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:()=>fr(q.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(ho,{size:14}),s("chat.archive","Archive")]}),t.jsxs("button",{onClick:()=>{Re(null),Tt(q.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(Xn,{size:14}),s("chat.delete","Delete")]})]}),jt&&t.jsx(St,{onClose:()=>At(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:fn,placeholder:s("chat.renamePlaceholder","Untitled"),"data-testid":"chat-rename-input",onChange:e=>gn(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),Ka())},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>At(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void Ka(),"data-testid":"chat-rename-save",children:s("chat.save","Save")})]})]})}),vn&&t.jsx(St,{onClose:()=>gt(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:bn,"data-testid":"chat-rename-tag-input",onChange:e=>ha(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),de(vn.id,bn).then(()=>gt(null)).catch(()=>o(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:()=>gt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary","data-testid":"chat-rename-tag-save",onClick:()=>void de(vn.id,bn).then(()=>gt(null)).catch(()=>o(s("chat.failedToRenameTag","Failed to rename tag"),"error")),children:s("chat.save","Save")})]})]})}),fa&&t.jsx(St,{onClose:()=>Dt(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:()=>Dt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger","data-testid":"chat-delete-tag-confirm",onClick:()=>void ee(fa.id).then(()=>Dt(null)).catch(()=>o(s("chat.failedToDeleteTag","Failed to delete tag"),"error")),children:s("chat.delete","Delete")})]})]})}),da&&t.jsx(St,{onClose:()=>Tt(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:()=>Tt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void br(da),children:s("chat.delete","Delete")})]})]})}),ua&&t.jsx(St,{onClose:()=>Et(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:()=>Et(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await b.deleteRoom(ua),Et(null)}catch{o(s("chat.failedToDeleteRoom","Failed to delete room"),"error")}})()},children:s("chat.delete","Delete")})]})]})}),Le&&Pe&&P==="rooms"?t.jsxs("div",{ref:Rn,className:"chat-thread",children:[b.activeRoom?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-room-thread-header",children:[t.jsx("button",{type:"button",className:"btn btn-sm chat-thread-header-back chat-back-btn",onClick:Va,"data-testid":"chat-back-btn","aria-label":s("chat.backToConversations","Back to conversations"),children:"< BACK"}),t.jsxs("span",{className:"chat-thread-header-title",children:["#",b.activeRoom.name]}),t.jsx("div",{className:"chat-room-thread-members",children:b.activeRoomMembers.map(e=>t.jsx(cn,{agent:Me.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:ie,onScroll:Fa,children:[b.messagesLoading&&b.messages.length===0?t.jsx("div",{className:"chat-empty-state",children:s("chat.loadingMessages","Loading messages...")}):b.messages.filter(e=>e.content.trim()!==Es).length===0?t.jsx("div",{className:"chat-empty-state",children:s("chat.noMessagesYet","No messages yet. Start the conversation!")}):b.messages.filter(e=>e.content.trim()!==Es).map(e=>{const n=e.senderAgentId?Me.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):s("chat.you","You"),i={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(Qn,{message:i,forcePlain:!1,agentName:n,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:b.activeRoom?.id??null,projectId:r,mentionAgentsByName:Dn,roomContext:Ee,onScrollToTop:qn,isTopClipped:Mn.has(e.id),isAwaitingQuestionAnswer:!1,onQuestionSubmit:Xt},e.id)}),t.jsx("div",{ref:ka})]}),b.activeRoom&&wa&&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(fs,{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")}),b.activeRoom&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Vt,type:"file",accept:Fs,multiple:!0,style:{display:"none"},onChange:e=>{dt(e.target.files),e.target.value=""}}),fe.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:fe.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:()=>Pa(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:()=>Vt.current?.click(),children:t.jsx(gs,{size:16})}),t.jsx(ps,{level:b.activeRoom.thinkingLevel,defaultThinkingLevel:S,showTargetSection:!1,onChange:e=>{b.updateRoomSettings(b.activeRoom.id,{thinkingLevel:e||null}).catch(()=>{o(s("chat.failedToUpdateRoomThinkingLevel","Failed to update room thinking effort"),"error")})}}),t.jsxs("div",{className:`chat-input-wrapper${ba?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),at(!0)},onDragLeave:()=>at(!1),onDrop:e=>{e.preventDefault(),at(!1),dt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:hr,className:"chat-input-textarea",placeholder:s("chat.typeMessage","Type a message..."),value:V,onChange:Ba,onKeyDown:Oa,onKeyUp:za,onClick:Jt,onBlur:Ua,onFocus:Ha,onPaste:_a,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||Yn()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Ms,{agents:it,filter:Ze,highlightedIndex:Ft,visible:Se,onSelect:Qt,position:Ts,roomMemberIds:Ee?.memberIds,roomName:Ee?.roomName})]}),t.jsx(vs,{...ur.micProps}),t.jsx(bs,{isStreaming:!1,canSend:!!(V.trim()||fe.length>0),onSend:Fn})]})]})]}):Le?t.jsxs("div",{ref:Rn,className:"chat-thread",children:[On&&t.jsxs("div",{className:"chat-thread-header",children:[t.jsx("button",{type:"button",className:"btn btn-sm chat-thread-header-back chat-back-btn",onClick:Va,"data-testid":"chat-back-btn","aria-label":s("chat.backToConversations","Back to conversations"),children:"< BACK"}),t.jsxs("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:[Ct?t.jsx(ms,{provider:Ct,size:"md"}):t.jsx(Bs,{size:16}),t.jsx("span",{className:"chat-thread-header-title",title:Wa,children:Wa}),Cr&&t.jsx("span",{className:"chat-model-tag",children:ht}),kr&&tn&&Bn?t.jsxs("span",{className:"chat-thread-header-context","data-testid":"chat-thread-context-window",title:Bn,"aria-label":Bn,children:[Ga," / ",tn]}):null]})]}),Wn?t.jsx(To,{cliSessionId:Mr,tier:Rr,projectId:r,renderTranscript:Za,renderComposer:()=>l?es():null}):t.jsxs(t.Fragment,{children:[Za(),wa&&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(fs,{size:14}),s("chat.latest","Latest")]}),l&&es()]})]}):null,t.jsx(Ao,{isOpen:er,onClose:()=>It(!1),projectId:r,existingRoomNames:b.rooms.map(e=>e.name),onCreate:async e=>{await b.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),P!=="rooms"&&Be("rooms"),It(!1),ze(!0)}})]}),Ys&&t.jsx(Ho,{projectId:r,defaultModel:ar,defaultKind:R?.kind,defaultAgentId:R?.kind==="agent"?R.agentId:void 0,defaultThinkingLevel:S,defaultSelectedThinkingLevel:R?.kind==="model"?R.thinkingLevel:void 0,onClose:()=>mn(!1),onCreate:ut})]})}export{ei as ChatView,Zo as buildIssueChatPrefill,ai as clampChatInputHeight,_o as resolveChatContextMenuPosition,si as resolveChatInputOverflowY,Ps as resolveSessionProvider};