@runfusion/fusion 0.50.0 → 0.51.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bin.js +815 -352
- package/dist/client/.vite/manifest.json +242 -241
- package/dist/client/assets/{AgentDetailView-D2oYUApl.js → AgentDetailView-CjwOlcMI.js} +1 -1
- package/dist/client/assets/{AgentPermissionPolicyEditor-DGgx46f3.js → AgentPermissionPolicyEditor-CD8znNHS.js} +1 -1
- package/dist/client/assets/{AgentsView-Dhf5Vq_T.js → AgentsView-CTjNaKu-.js} +3 -3
- package/dist/client/assets/ChatView-DCWypaw3.js +19 -0
- package/dist/client/assets/{CommandCenter-DzQhGq_J.js → CommandCenter-C4v0FMxx.js} +9 -9
- package/dist/client/assets/{DevServerView-DjJYp6Jj.js → DevServerView-BE_o7v9j.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-CYPYp9T4.js → DirectoryPicker-BpcPo65A.js} +1 -1
- package/dist/client/assets/{DocumentsView-CeQVRVdp.js → DocumentsView-Cpma23hu.js} +1 -1
- package/dist/client/assets/{EvalsView-D250mVR5.js → EvalsView-DYSobhb7.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-B1EEY_bl.js → ExperimentalAgentOnboardingModal-D_iQqD-n.js} +1 -1
- package/dist/client/assets/{GoalsView-CUh8JBnJ.css → GoalsView-4-eEOeqw.css} +1 -1
- package/dist/client/assets/{GoalsView-MftVwE9g.js → GoalsView-B6Wfxk59.js} +1 -1
- package/dist/client/assets/{InsightsView-CbWItYe8.js → InsightsView-DZyMvYQ8.js} +1 -1
- package/dist/client/assets/{MemoryView-Ct0nOTES.js → MemoryView-B9Z6cRma.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-DSQwngX-.js → PiExtensionsManager-BQt3JU60.js} +1 -1
- package/dist/client/assets/{PluginManager-DqLxCiNg.js → PluginManager-DEsUstVo.js} +1 -1
- package/dist/client/assets/PullRequestView-B7k8ogy4.js +6 -0
- package/dist/client/assets/PullRequestView-NkeImY1n.css +1 -0
- package/dist/client/assets/{ResearchView-CJQL9XKC.js → ResearchView-BseF58_R.js} +1 -1
- package/dist/client/assets/{SecretsView-ChN9aTbi.js → SecretsView-bkNS5VBC.js} +1 -1
- package/dist/client/assets/{SessionTerminal-BVon9kbr.js → SessionTerminal-BSllyqgF.js} +1 -1
- package/dist/client/assets/{SettingsModal-CIC5jhgo.js → SettingsModal-DAH7LuLw.js} +1 -1
- package/dist/client/assets/SettingsModal-Dso0K76J.js +21 -0
- package/dist/client/assets/{SetupWizardModal-C6EGjmbd.js → SetupWizardModal-Bm6bG31V.js} +2 -2
- package/dist/client/assets/{ShadcnColorPicker-4e_aXoGX.js → ShadcnColorPicker-CLiOvo7W.js} +1 -1
- package/dist/client/assets/{SkillsView-Dz8dDwfP.js → SkillsView-D_UEJY_f.js} +1 -1
- package/dist/client/assets/{TodoView-DvJFzoOv.js → TodoView-CMCoPep1.js} +1 -1
- package/dist/client/assets/{WorkflowNodeEditor-DrdTCstS.js → WorkflowNodeEditor-BeQcn0Wa.js} +1 -1
- package/dist/client/assets/{agentSkills-B2dD5Nm5.js → agentSkills-BiipFw1z.js} +1 -1
- package/dist/client/assets/{app-D27ewSC0.js → app-A1yCJR4Q.js} +3 -3
- package/dist/client/assets/{app-BYq4S7Cb.js → app-Bfiafek7.js} +3 -3
- package/dist/client/assets/{app-OPrfgjjn.js → app-Bh-Xj32t.js} +3 -3
- package/dist/client/assets/{app-k1K9zAjp.js → app-DxJHfzxz.js} +3 -3
- package/dist/client/assets/{app-dATBczl3.js → app-T5iMjZpX.js} +2 -2
- package/dist/client/assets/{app-DFLDkeOE.js → app-zR_n4GL2.js} +3 -3
- package/dist/client/assets/{architectureDiagram-3BPJPVTR-ClO0MnzR.js → architectureDiagram-3BPJPVTR-glwWkaDt.js} +1 -1
- package/dist/client/assets/{blockDiagram-GPEHLZMM-C4cyy4WE.js → blockDiagram-GPEHLZMM-C8DhxwG4.js} +1 -1
- package/dist/client/assets/{c4Diagram-AAUBKEIU-NHPC9TJo.js → c4Diagram-AAUBKEIU-CQXf6PzI.js} +1 -1
- package/dist/client/assets/channel-BY6zFSV1.js +1 -0
- package/dist/client/assets/{chunk-2J33WTMH-CGYIKTVR.js → chunk-2J33WTMH-kak65s83.js} +1 -1
- package/dist/client/assets/{chunk-4BX2VUAB-BkCCD0tE.js → chunk-4BX2VUAB-B_yEpoxU.js} +1 -1
- package/dist/client/assets/{chunk-55IACEB6-Be3yOIDe.js → chunk-55IACEB6-C9lQVeH5.js} +1 -1
- package/dist/client/assets/{chunk-727SXJPM-DxjyMaQQ.js → chunk-727SXJPM-D4SVzqNs.js} +1 -1
- package/dist/client/assets/{chunk-AQP2D5EJ-BC0PjN0W.js → chunk-AQP2D5EJ-DBHuj4BH.js} +1 -1
- package/dist/client/assets/{chunk-FMBD7UC4-DoWxmM8k.js → chunk-FMBD7UC4-BJ3ghjau.js} +1 -1
- package/dist/client/assets/{chunk-ND2GUHAM-EOpuc9pP.js → chunk-ND2GUHAM-CE4tkh6e.js} +1 -1
- package/dist/client/assets/{chunk-QZHKN3VN-DiRyx9QZ.js → chunk-QZHKN3VN-DmVw_cEu.js} +1 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-CeX_WCiC.js +1 -0
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-CeX_WCiC.js +1 -0
- package/dist/client/assets/{cose-bilkent-S5V4N54A-CfVoUUxT.js → cose-bilkent-S5V4N54A-DI_-BOYE.js} +1 -1
- package/dist/client/assets/{dagre-BM42HDAG-BfILvxLb.js → dagre-BM42HDAG-ywUbHZxt.js} +1 -1
- package/dist/client/assets/{dashboard-view-wFC1pe4d.js → dashboard-view-DJvdban3.js} +1 -1
- package/dist/client/assets/{dashboard-view-C9YIcx-O.js → dashboard-view-r4NTTh_X.js} +1633 -1633
- package/dist/client/assets/{diagram-2AECGRRQ-6mdmbH-5.js → diagram-2AECGRRQ-CAGucHCe.js} +1 -1
- package/dist/client/assets/{diagram-5GNKFQAL-CY7MMwO1.js → diagram-5GNKFQAL-D_1uzVtW.js} +1 -1
- package/dist/client/assets/{diagram-KO2AKTUF-D05XnQqd.js → diagram-KO2AKTUF-D7zY4Nlm.js} +1 -1
- package/dist/client/assets/{diagram-LMA3HP47-B18FTOJG.js → diagram-LMA3HP47-C1T9eOzA.js} +1 -1
- package/dist/client/assets/{diagram-OG6HWLK6-xmXlYf5m.js → diagram-OG6HWLK6-sWxhPvzU.js} +1 -1
- package/dist/client/assets/{erDiagram-TEJ5UH35-4XlgVLCs.js → erDiagram-TEJ5UH35-DfHtnaNg.js} +1 -1
- package/dist/client/assets/{flowDiagram-I6XJVG4X-BYl3ps7f.js → flowDiagram-I6XJVG4X-Brbb_Jlh.js} +1 -1
- package/dist/client/assets/{folder-open-BH6FwmO7.js → folder-open-BLwukrE0.js} +1 -1
- package/dist/client/assets/{ganttDiagram-6RSMTGT7-4vxuH9Dx.js → ganttDiagram-6RSMTGT7-CLvZ7891.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-PVQCEYII-BESmFgXT.js → gitGraphDiagram-PVQCEYII-DD56Jsa3.js} +1 -1
- package/dist/client/assets/index-DAv17W73.js +1317 -0
- package/dist/client/assets/index-DhBnj8YN.css +1 -0
- package/dist/client/assets/{infoDiagram-5YYISTIA-DvjdjtwB.js → infoDiagram-5YYISTIA-uXai801q.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-Cis5IoEm.js → ishikawaDiagram-YF4QCWOH-C_bWlUP_.js} +1 -1
- package/dist/client/assets/{journeyDiagram-JHISSGLW-C20pB1W8.js → journeyDiagram-JHISSGLW-B2kB9niE.js} +1 -1
- package/dist/client/assets/{kanban-definition-UN3LZRKU-CiVfCeU3.js → kanban-definition-UN3LZRKU-BJwlpR9z.js} +1 -1
- package/dist/client/assets/{mermaid.core-CW0vCXA6.js → mermaid.core-0hUjZF5S.js} +4 -4
- package/dist/client/assets/{mindmap-definition-RKZ34NQL-E5rPHUdw.js → mindmap-definition-RKZ34NQL-DsTgTpX-.js} +1 -1
- package/dist/client/assets/{pieDiagram-4H26LBE5-DVIFbPjH.js → pieDiagram-4H26LBE5-BUQsNWHN.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-W4KKPZXB-C8qPRe_x.js → quadrantDiagram-W4KKPZXB-DOYWgfAz.js} +1 -1
- package/dist/client/assets/{requirementDiagram-4Y6WPE33-DQ-pwXh3.js → requirementDiagram-4Y6WPE33-DUnPKaMd.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-5OEKKPKP-BnghLuUc.js → sankeyDiagram-5OEKKPKP-Btl4NRo-.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-3UESZ5HK-ChlGxGVk.js → sequenceDiagram-3UESZ5HK-b0hyJ_Wr.js} +1 -1
- package/dist/client/assets/{shield-alert-BfOnDO6O.js → shield-alert-yWvC7t2v.js} +1 -1
- package/dist/client/assets/{stateDiagram-AJRCARHV-ByUvNEch.js → stateDiagram-AJRCARHV-orREjkd9.js} +1 -1
- package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-Df38ITSP.js → stateDiagram-v2-BHNVJYJU-DYJRRNh-.js} +1 -1
- package/dist/client/assets/{timeline-definition-PNZ67QCA-bsAGc83D.js → timeline-definition-PNZ67QCA-DZga7lqO.js} +1 -1
- package/dist/client/assets/{upload-BK1crTqn.js → upload-BsYRkl_8.js} +1 -1
- package/dist/client/assets/{users-DW8jC2Z9.js → users-dyoJEvrM.js} +1 -1
- package/dist/client/assets/{vennDiagram-CIIHVFJN-BBIj6LFN.js → vennDiagram-CIIHVFJN-C2P26V71.js} +1 -1
- package/dist/client/assets/{wardley-L42UT6IY-De6JFroy.js → wardley-L42UT6IY-ckctH9bL.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-YWT4CUSO-P1LOLx0_.js → wardleyDiagram-YWT4CUSO-9It3QAYs.js} +1 -1
- package/dist/client/assets/{xychartDiagram-2RQKCTM6-v1G4ki6U.js → xychartDiagram-2RQKCTM6-Dj3sSBqg.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/extension.js +584 -296
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/plugin-sdk/index.d.ts +6 -0
- package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/manifest.json +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/package.json +1 -1
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/skill/fusion/references/best-practices.md +3 -3
- package/skill/fusion/references/extension-tools.md +1 -1
- package/skill/fusion/references/fusion-capabilities.md +1 -1
- package/skill/fusion/workflows/task-management.md +1 -1
- package/dist/client/assets/ChatView-DpgpxHva.js +0 -19
- package/dist/client/assets/PullRequestView-CpdE3Yo_.css +0 -1
- package/dist/client/assets/PullRequestView-D0WgwdAi.js +0 -6
- package/dist/client/assets/SettingsModal-B4WANQnu.js +0 -21
- package/dist/client/assets/channel-Q2WKocEP.js +0 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-CPFl2Aqd.js +0 -1
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-CPFl2Aqd.js +0 -1
- package/dist/client/assets/index-B9jtBwFy.css +0 -1
- package/dist/client/assets/index-DFeBJ3GM.js +0 -1302
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import{r as a,j as e,b as lr,R as ur}from"./vendor-react-SZ_qB27O.js";import{c as ls,aA as st,ay as Ze,dK as Vs,dL as us,bU as zt,dM as Qs,aD as ce,dN as pn,dp as Ct,dO as dr,dP as Lt,dQ as mr,dq as xn,dr as xt,dR as hr,dS as Ws,dT as fr,dU as gr,dV as pr,dW as br,ai as ja,dX as vr,az as rs,bB as Xs,dY as yr,dZ as xr,d_ as Wn,d$ as wr,e0 as Cr,e1 as Sr,e2 as kr,e3 as Nr,e4 as Mr,f as wn,e5 as Rr,e6 as Ta,bo as Ar,al as jr,bb as bn,a1 as Tr,c0 as Er,e7 as _r,i as $r,e8 as Ea,e9 as Dr,dz as Fr,W as Lr,ea as Pr,s as _a,v as $a,G as Ir,H as Or,V as zr,P as bt,di as Ys,dh as Br,X as Hr,aK as Ur,J as Xn,dw as It,I as Js,bO as qr,bs as Zs,o as un,eb as ea,ec as ta,cE as na,bu as Ot,D as Kr,F as Gr,ed as Cn,dj as sa,b8 as Vr,cn as Qr,bM as aa,bP as Wr}from"./index-DAv17W73.js";import{u as Le}from"./vendor-i18n-GF3RlKbq.js";import{SessionTerminal as ra}from"./SessionTerminal-BSllyqgF.js";import"./vendor-reactflow-Bg-Qjzh8.js";import"./vendor-xterm-BNq00GSj.js";import"./vendor-codemirror-jBKmHyH0.js";import"./shield-alert-yWvC7t2v.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 Xr=[["path",{d:"M5 3h14",key:"7usisc"}],["path",{d:"m18 13-6-6-6 6",key:"1kf1n9"}],["path",{d:"M12 7v14",key:"1akyts"}]],Yr=ls("arrow-up-to-line",Xr);/**
|
|
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 Jr=[["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"}]],Da=ls("hash",Jr);/**
|
|
12
|
+
* @license lucide-react v1.7.0 - ISC
|
|
13
|
+
*
|
|
14
|
+
* This source code is licensed under the ISC license.
|
|
15
|
+
* See the LICENSE file in the root directory of this source tree.
|
|
16
|
+
*/const Zr=[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z",key:"1ngwbx"}]],ia=ls("wrench",Zr);function oa(n){const{sessionId:s,tempUserMessageId:r,initialText:l,initialThinking:o,initialToolCalls:u,setStreamingText:b,setStreamingThinking:d,setStreamingToolCalls:c,cancelStreamingFlushesRef:m,addToast:$,onDone:x,onError:y,onFallbackSession:k}=n;let S=l??"",T=o??"",N=u?[...u]:[],L,v=null,W=null;const H=()=>{v=null,b(S)},le=()=>{W=null,d(T)},j=()=>{v!==null&&(cancelAnimationFrame(v),v=null),W!==null&&(cancelAnimationFrame(W),W=null)};return m.current=j,{handlers:{onThinking:P=>{T+=P,W===null&&(W=requestAnimationFrame(le))},onText:P=>{S+=P,v===null&&(v=requestAnimationFrame(H))},onToolStart:P=>{N=[...N,{toolName:P.toolName,args:P.args,isError:!1,status:"running"}],c(N)},onToolEnd:P=>{const z=[...N];for(let F=z.length-1;F>=0;F--){const U=z[F];if(U?.toolName===P.toolName&&U.status==="running"){z[F]={...U,status:"completed",isError:P.isError,result:P.result},N=z,c(z);return}}N=[...z,{toolName:P.toolName,isError:P.isError,result:P.result,status:"completed"}],c(N)},onFallback:P=>{L=P,k?.(P,s),$?.(`Primary model unavailable. Switched to fallback ${P.fallbackModel}.`,"warning")},onDone:P=>{j(),x({messageId:P.messageId,message:P.message,accumulated:{text:S,thinking:T,toolCalls:N,fallbackInfo:L}})},onError:P=>{j(),y(P,r)}},cancelFlushes:j}}const ei="fusion:chat-pending:";function ds(n){return n?`${ei}${n}`:null}function ti(n){const s=ds(n);if(!s||typeof window>"u")return[];try{const r=localStorage.getItem(s);if(!r)return[];try{const o=JSON.parse(r);if(Array.isArray(o))return o.filter(u=>typeof u=="string"&&u.trim().length>0)}catch{}const l=r.trim();return l?[l]:[]}catch{return[]}}function Yn(n,s){const r=ds(n);if(!(!r||typeof window>"u"))try{const l=s.filter(o=>o.trim().length>0);if(l.length===0){localStorage.removeItem(r);return}localStorage.setItem(r,JSON.stringify(l))}catch{}}function dn(n){const s=ds(n);if(!(!s||typeof window>"u"))try{localStorage.removeItem(s)}catch{}}const Jn="kb-chat-active-session";function ca(n){const s=typeof n=="string"?n.trim():"",r=s.indexOf("/");return!s||r<=0||r>=s.length-1?{}:{modelProvider:s.slice(0,r),modelId:s.slice(r+1)}}function ni(n){const s=n?.toolCalls;if(!Array.isArray(s))return;const r=s.map(l=>{if(!l||typeof l!="object")return null;const o=l,u=typeof o.toolName=="string"?o.toolName:"";if(!u)return null;const b=o.args;return{toolName:u,...b&&typeof b=="object"?{args:b}:{},isError:!!o.isError,result:o.result,status:"completed"}}).filter(l=>l!==null);return r.length>0?r:void 0}function si(n){const s=n?.fallback;if(!s||typeof s!="object")return;const r=s,l=typeof r.primaryModel=="string"?r.primaryModel:"",o=typeof r.fallbackModel=="string"?r.fallbackModel:"",u=r.triggerPoint;if(!(!l||!o||u!=="session-creation"&&u!=="prompt-time"))return{primaryModel:l,fallbackModel:o,triggerPoint:u}}function ai(n){const s=n?.failureInfo;if(!s||typeof s!="object")return;const r=s,l=typeof r.summary=="string"?r.summary.trim():"";if(!l)return;const o=(()=>{const u=r.reference;if(!u||typeof u!="object")return;const b=u,d=typeof b.kind=="string"?b.kind.trim():"",c=typeof b.id=="string"?b.id.trim():"";if(!(!d||!c))return{kind:d,id:c,...typeof b.label=="string"&&b.label.trim()?{label:b.label.trim()}:{}}})();return{summary:l,...typeof r.errorClass=="string"&&r.errorClass.trim()?{errorClass:r.errorClass.trim()}:{},...typeof r.code=="string"&&r.code.trim()?{code:r.code.trim()}:{},...typeof r.detail=="string"&&r.detail.trim()?{detail:r.detail.trim()}:{},...o?{reference:o}:{}}}function la(n,s){const r="Failed to get response";return typeof n=="string"?{summary:n.trim()||r}:{summary:typeof n.summary=="string"&&n.summary.trim()?n.summary.trim():r,...typeof n.errorClass=="string"&&n.errorClass.trim()?{errorClass:n.errorClass.trim()}:{},...typeof n.code=="string"&&n.code.trim()?{code:n.code.trim()}:{},...typeof n.detail=="string"&&n.detail.trim()?{detail:n.detail.trim()}:{},...n.reference?{reference:n.reference}:{}}}function Zn(n){return{id:n.id,sessionId:n.sessionId,role:n.role,content:n.content,thinkingOutput:n.thinkingOutput,toolCalls:ni(n.metadata),fallbackInfo:si(n.metadata),failureInfo:ai(n.metadata),attachments:n.attachments,createdAt:n.createdAt}}function ri(n,s){const r=a.useCallback(p=>p?`${st.CHAT_SESSIONS_PREFIX}${p}`:null,[]),l=a.useCallback((p,w)=>p&&w?`${st.CHAT_MESSAGES_PREFIX}${p}:${w}`:null,[]),o=a.useCallback(p=>{const w=r(p);return w?Ze(w,{maxAgeMs:Vs})??[]:[]},[r]),[u,b]=a.useState(()=>o(n)),[d,c]=a.useState(null),[m,$]=a.useState(()=>o(n).length===0),[x,y]=a.useState([]),[k,S]=a.useState(!1),[T,N]=a.useState(!1),[L,v]=a.useState(""),[W,H]=a.useState(""),[le,j]=a.useState([]),[Q,P]=a.useState([]),[z,F]=a.useState(""),[U,C]=a.useState(!1),{agentsMap:I}=us(n),E=a.useRef(null),Y=a.useRef(null),R=a.useRef(!1),_=a.useRef([]),D=a.useRef(()=>!1),g=a.useRef(null),O=a.useRef(u),f=a.useRef(d),ie=a.useRef(x),q=a.useRef(T);O.current=u,f.current=d,ie.current=x,q.current=T,a.useEffect(()=>{_.current=Q},[Q]);const K=a.useRef(new Set),me=a.useRef(0),ge=a.useRef(n);ge.current!==n&&(zt({view:"useChat",trigger:"project-context-change",projectId:n,replayAttempted:!1,detail:{previousProjectId:ge.current??null}}),ge.current=n,me.current++);const oe=a.useCallback(async()=>{O.current.length===0&&$(!0);try{const w=[...(await Qs(n)).sessions].sort((G,ae)=>new Date(ae.updatedAt).getTime()-new Date(G.updatedAt).getTime());b(w);const A=r(n);A&&ce(A,w,{maxBytes:5e5})}catch{const p=o(n);if(O.current.length===0&&p.length===0){const w=r(n);w&&pn(w)}}finally{$(!1)}},[r,n]);a.useEffect(()=>{const p=o(n);b(p),$(p.length===0)},[n,o]),a.useEffect(()=>{oe()},[oe,n]);const ve=a.useRef(()=>{}),ye=a.useRef(!1);a.useEffect(()=>{ye.current=!1,Y.current=null},[n]),a.useEffect(()=>{if(m||ye.current||f.current)return;const p=Ct(Jn,n);if(!p){ye.current=!0;return}const w=u.find(A=>A.id===p);if(w){ye.current=!0,ve.current(p,w);return}ye.current=!0},[m,u,n]);const Ge=a.useCallback((p,w)=>{const A=l(p,w);return A?Ze(A,{maxAgeMs:Vs})??[]:[]},[l]),Ve=a.useCallback((p,w)=>{const A=Ge(n,p);return A.length>0?(y(A),S(!1),!0):(w?.clearOnMiss!==!1&&y([]),!1)},[n,Ge]),xe=a.useCallback(async(p,w)=>{const A=typeof w?.offset=="number"&&w.offset>0||typeof w?.before=="string",G=l(n,p),ae=A?[]:Ge(n,p),V=ae.length>0;!A&&V?(y(ae),S(!1)):S(!0);try{const J=await dr(p,{limit:50,order:"desc",...w},n),X=J.messages.slice().reverse().map(Zn),Z=f.current?.id===p||w?.commitForStreamingAttach===!0&&Y.current?.sessionId===p;A?Z&&(y(re=>[...X,...re]),C(J.messages.length>=50)):Z&&(y(X),C(J.messages.length>=50),G&&ce(G,X,{maxBytes:5e5}))}catch{!A&&ie.current.length===0&&V&&(y(ae),S(!1))}finally{S(!1)}},[l,n,Ge]),$e=a.useCallback(()=>{g.current?.(),g.current=null,_.current=[],P([]),v(""),H(""),j([]),N(!1)},[]),Bt=a.useCallback(p=>{const w=f.current?.id;if(typeof p=="number"){const A=_.current.filter((G,ae)=>ae!==p);_.current=A,P(A),Yn(w,A);return}dn(w),_.current=[],P([])},[]),he=a.useCallback(()=>{const[p,...w]=_.current,A=p?.trim();if(!A)return;const G=f.current?.id;_.current=w,P(w),Yn(G,w),Nt.current(A)},[]),et=a.useCallback(async(p,w)=>{try{const{session:A}=await Lt(p,n);if(f.current?.id!==p||_.current.length===0)return;if(A.isGenerating||A.inFlightGeneration){D.current(p,A.inFlightGeneration,{silent:w?.silent,priorThreadLoadAlreadyStarted:!0});return}he()}catch{}},[he,n]),de=a.useCallback((p,w,A)=>{if(E.current||!p)return!0;R.current=!1;const G=ie.current,ae=G.length===0||G[0]?.sessionId!==p;Y.current={sessionId:p,replayFromEventId:typeof w?.replayFromEventId=="number"?w.replayFromEventId:null},ae&&!A?.priorThreadLoadAlreadyStarted&&(Ve(p,{clearOnMiss:!1}),xe(p,{commitForStreamingAttach:!0})),w&&(v(w.streamingText),H(w.streamingThinking),j(w.toolCalls)),N(!0);const{handlers:V}=oa({sessionId:p,tempUserMessageId:"",initialText:w?.streamingText,initialThinking:w?.streamingThinking,initialToolCalls:w?.toolCalls,setStreamingText:v,setStreamingThinking:H,setStreamingToolCalls:j,cancelStreamingFlushesRef:g,addToast:A?.silent?void 0:s,onFallbackSession:(X,Z)=>{const re=ca(X.fallbackModel);b(ne=>ne.map(te=>te.id===Z?{...te,...re}:te)),c(ne=>ne&&ne.id===Z?{...ne,...re}:ne)},onDone:()=>{v(""),H(""),j([]),N(!1),q.current=!1,E.current=null,Y.current=null,xe(p),he()},onError:X=>{v(""),H(""),j([]),N(!1),q.current=!1,E.current=null,Y.current=null;const Z=la(X);A?.silent||s?.(Z.summary,"error"),xe(p),et(p,{silent:A?.silent})}});zt({view:"useChat",trigger:"sse-open",projectId:n,replayAttempted:typeof w?.replayFromEventId=="number",replayFromEventId:w?.replayFromEventId??null,lastEventId:w?.replayFromEventId??null});const J=mr(p,V,n,{...typeof w?.replayFromEventId=="number"?{lastEventId:w.replayFromEventId}:{}});return E.current=J,!0},[s,he,et,Ve,xe,n]);D.current=de;const Ee=a.useCallback((p,w)=>{const A=f.current?.id??null;if(p&&A===p&&!w)return;E.current&&(E.current.close(),E.current=null),Y.current=null;const G=w??u.find(ae=>ae.id===p);c(G||null),f.current=G||null,p&&Lt(p,n).then(({session:ae})=>{!ae.isGenerating||!ae.inFlightGeneration||c(V=>!V||V.id!==p?V:{...V,...ae})}).catch(()=>{}),$e(),C(!1),p?(Ve(p),xe(p)):y([]),G?.isGenerating&&de(G.id,G.inFlightGeneration,{priorThreadLoadAlreadyStarted:!0}),p?xn(Jn,p,n):xt(Jn,n)},[de,Ve,u,xe,n,$e]);ve.current=Ee,a.useEffect(()=>{const p=d?.id;if(!p)return;const w=ti(p);if(w.length===0)return;_.current=w,P(w);let A=!1;return Lt(p,n).then(({session:G})=>{if(!(A||f.current?.id!==p||_.current.length===0)){if(G.isGenerating){E.current||de(p,G.inFlightGeneration);return}!q.current&&!E.current&&he()}}).catch(()=>{}),()=>{A=!0}},[d?.id,de,he,n]);const kt=a.useCallback(async p=>{const w=f.current?.id,A=await hr(p,n);E.current&&(E.current.close(),E.current=null),Y.current=null;const G={id:A.session.id,title:A.session.title,agentId:A.session.agentId,status:A.session.status,modelProvider:A.session.modelProvider,modelId:A.session.modelId,createdAt:A.session.createdAt,updatedAt:A.session.updatedAt};return b(ae=>ae.some(V=>V.id===G.id)?ae:[G,...ae]),dn(w),$e(),Ee(G.id,G),G},[n,$e,Ee]),Sn=a.useCallback(async p=>{dn(p),await Ws(p,{status:"archived"},n),b(w=>w.filter(A=>A.id!==p)),d?.id===p&&(Y.current=null,c(null),y([]))},[d,n]),at=a.useCallback(async(p,w)=>{const A=w.trim()||null,G=u,ae=d;b(V=>V.map(J=>J.id===p?{...J,title:A}:J)),c(V=>V?.id===p?{...V,title:A}:V);try{const J=(await Ws(p,{title:A},n)).session;b(X=>X.map(Z=>Z.id===p?{...Z,title:J.title,updatedAt:J.updatedAt}:Z)),c(X=>X?.id===p?{...X,title:J.title,updatedAt:J.updatedAt}:X)}catch(V){throw b(G),c(ae),s?.("Failed to rename conversation","error"),V}},[d,s,n,u]),Ht=a.useCallback(async p=>{dn(p),d?.id===p&&E.current&&(E.current.close(),E.current=null),d?.id===p&&(Y.current=null),await fr(p,n);const w=l(n,p);w&&pn(w),b(A=>A.filter(G=>G.id!==p)),d?.id===p&&(c(null),y([]))},[d,l,n]),_e=a.useCallback(async()=>{if(!d||!U)return;const p=ie.current[0]?.createdAt;p&&await xe(d.id,{before:p})},[d,U,xe]),Ut=a.useCallback(()=>{d&&(R.current=!0,g.current?.(),g.current=null,E.current?.close(),E.current=null,Y.current=null,gr(d.id,n).catch(()=>{}),N(!1),q.current=!1,v(""),H(""),j([]),he())},[d,n,he]),Nt=a.useRef(()=>{}),Mt=pr(),rt=a.useCallback(async p=>{try{await oe();const w=await Lt(p,n);f.current?.id===p&&c(A=>!A||A.id!==p?A:{...A,...w.session}),w.session.isGenerating?(v(""),H(""),j([]),N(!0),q.current=!0,de(p,w.session.inFlightGeneration,{silent:!0})):(v(""),H(""),j([]),N(!1),q.current=!1,await xe(p))}catch{}},[de,xe,n,oe]),it=a.useCallback((p,w)=>{if(!d)return;if(q.current){const V=p.trim();if(!V)return;const J=[..._.current,V];_.current=J,P(J),Yn(d.id,J);return}R.current=!1,E.current&&(E.current.close(),E.current=null),Y.current=null;const A=`temp-${Date.now()}`,G={id:A,sessionId:d.id,role:"user",content:p,createdAt:new Date().toISOString()};y(V=>[...V,G]),v(""),H(""),j([]),N(!0),q.current=!0;const{handlers:ae}=oa({sessionId:d.id,tempUserMessageId:A,setStreamingText:v,setStreamingThinking:H,setStreamingToolCalls:j,cancelStreamingFlushesRef:g,addToast:s,onFallbackSession:(V,J)=>{const X=ca(V.fallbackModel);b(Z=>Z.map(re=>re.id===J?{...re,...X}:re)),c(Z=>Z&&Z.id===J?{...Z,...X}:Z)},onDone:({messageId:V,message:J,accumulated:X})=>{const Z=J?{...Zn(J),...X.text.length>0?{content:X.text}:{}}:{id:V||`msg-${Date.now()}`,sessionId:d.id,role:"assistant",content:X.text,thinkingOutput:X.thinking,toolCalls:X.toolCalls.length>0?X.toolCalls:void 0,fallbackInfo:X.fallbackInfo,createdAt:new Date().toISOString()};K.current.add(Z.id),y(re=>[...re,Z]),v(""),H(""),j([]),N(!1),q.current=!1,E.current=null,Y.current=null,setTimeout(()=>{K.current.delete(Z.id)},1e3),oe(),he()},onError:(V,J)=>{const X=la(V),Z=typeof V=="string"?V:X.summary,re=vr(Z);y(ne=>{const te=ne.filter(fe=>fe.id!==J);return re?te:[...te,{id:`error-${Date.now()}`,sessionId:d.id,role:"assistant",content:X.summary,failureInfo:X,createdAt:new Date().toISOString()}]}),v(""),H(""),j([]),N(!1),q.current=!1,E.current=null,Y.current=null,console.error("[useChat] Stream error:",V),re?(console.info("[useChat] Suppressed tab-suspension stream error:",V),d?.id&&(v(""),H(""),j([]),N(!0),q.current=!0,rt(d.id))):(s?.(X.summary,"error"),oe()),R.current||he()}});E.current=br(d.id,p,ae,w,n)},[d,n,oe,s,de,rt,he]);Nt.current=it;const kn=z?u.filter(p=>p.title?.toLowerCase().includes(z.toLowerCase())||p.agentId.toLowerCase().includes(z.toLowerCase())):u;return a.useEffect(()=>{if(!d?.id||d.isGenerating!==!0||E.current)return;const p=typeof d.inFlightGeneration?.replayFromEventId=="number"?d.inFlightGeneration.replayFromEventId:null,w=Y.current;w?.sessionId===d.id&&w.replayFromEventId===p||de(d.id,d.inFlightGeneration,{silent:!0})},[d?.id,d?.isGenerating,d?.inFlightGeneration,de]),a.useEffect(()=>{if(!f.current?.isGenerating||(E.current||de(f.current.id,f.current.inFlightGeneration),!q.current||E.current||!f.current))return;const p=setInterval(async()=>{if(!q.current||E.current||!f.current){clearInterval(p);return}try{(await Qs(n)).sessions.find(G=>G.id===f.current?.id)?.isGenerating||(clearInterval(p),await xe(f.current.id),v(""),H(""),j([]),N(!1),q.current=!1,he())}catch{}},3e3);return()=>clearInterval(p)},[de,xe,n,d,he]),a.useEffect(()=>Mt.onBecameVisible(()=>{const w=f.current;if(!w||E.current)return;const A=me.current;Lt(w.id,n).then(G=>{if(!(me.current!==A||E.current)){if(G.session.isGenerating){v(""),H(""),j([]),N(!0),q.current=!0,de(w.id,G.session.inFlightGeneration,{silent:!0});return}q.current&&(v(""),H(""),j([]),N(!1),q.current=!1,he(),xe(w.id))}}).catch(()=>{})}),[de,xe,n,Mt,he]),a.useEffect(()=>{const p=me.current,w=n?`?projectId=${encodeURIComponent(n)}`:"",A=()=>me.current!==p,G=re=>{if(A())return;const ne=JSON.parse(re.data);b(te=>te.some(fe=>fe.id===ne.id)?te:[ne,...te])},ae=re=>{if(A())return;const ne=JSON.parse(re.data);b(te=>[...te.map(pe=>pe.id===ne.id?ne:pe)]),f.current?.id===ne.id&&(c(ne),ne.isGenerating&&!E.current&&de(ne.id,ne.inFlightGeneration))},V=re=>{if(A())return;const{id:ne}=JSON.parse(re.data);b(fe=>fe.filter(pe=>pe.id!==ne));const te=l(n,ne);te&&pn(te),f.current?.id===ne&&(c(null),y([]))},J=re=>{if(A())return;const ne=JSON.parse(re.data),te=Zn(ne);if(!K.current.has(te.id)){if(f.current?.id===te.sessionId&&q.current&&!E.current&&te.role==="assistant"){y(fe=>fe.some(pe=>pe.id===te.id)?fe:[...fe,te]),v(""),H(""),j([]),N(!1),q.current=!1,he();return}f.current?.id===te.sessionId&&!q.current&&y(fe=>{if(fe.some(pe=>pe.id===te.id))return fe;if(te.role==="user"){const pe=fe.findIndex(ke=>ke.role==="user"&&ke.id.startsWith("temp-")&&ke.content.trim()===te.content.trim());if(pe>=0){const ke=[...fe];return ke[pe]=te,ke}}return[...fe,te]})}},X=re=>{if(A())return;const{id:ne}=JSON.parse(re.data);y(te=>te.filter(fe=>fe.id!==ne))};return ja(`/api/events${w}`,{events:{"chat:session:created":G,"chat:session:updated":ae,"chat:session:deleted":V,"chat:message:added":J,"chat:message:deleted":X}})},[de,l,n,he]),a.useEffect(()=>()=>{E.current&&(E.current.close(),E.current=null),Y.current=null},[]),{sessions:u,activeSession:d,sessionsLoading:m,messages:x,messagesLoading:k,isStreaming:T,streamingText:L,streamingThinking:W,streamingToolCalls:le,pendingMessages:Q,selectSession:Ee,createSession:kt,archiveSession:Sn,renameSession:at,deleteSession:Ht,sendMessage:it,stopStreaming:Ut,clearPendingMessage:Bt,loadMoreMessages:_e,hasMoreMessages:U,searchQuery:z,setSearchQuery:F,filteredSessions:kn,refreshSessions:oe,agentsMap:I}}function mn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function ii(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function es(n,s){const r=ii(),l=s?.warm===!0,o=mn(),u=new Map;let b=!1,d=!1;return{mark(m){b||d||!r||u.has(m)||u.set(m,mn())},complete:m=>{if(!r||b||d){b=!0;return}b=!0,u.set("complete",mn());const $=Array.from(u.entries()).sort((S,T)=>S[1]-T[1]);let x=o;const y={};for(const[S,T]of $)y[S]=Math.max(0,T-x),x=T;const k=Math.max(0,mn()-o);try{console.debug("[room-open]",{roomId:n,warm:l,totalMs:k,phases:y,...m??{}})}catch{}},cancel(){d=!0,b=!0}}}const Je="fusion:chat-active-room";class Fa extends Error{roomId;constructor(s,r){super(s),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=r}}function is(n){return[...n].sort((s,r)=>new Date(r.updatedAt).getTime()-new Date(s.updatedAt).getTime())}function vt(n,s){const r=n.findIndex(o=>o.id===s.id);if(r===-1)return is([s,...n]);const l=[...n];return l[r]=s,is(l)}function Ke(n){try{return JSON.parse(n.data)}catch{return null}}function oi(n,s,r){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:n,role:"user",content:s,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...r?.length?{attachments:r}:{},createdAt:new Date().toISOString()}}function ua(n,s,r){if(n.some(o=>o.id===s.id))return n;const l=r?n.findIndex(o=>o.id===r):-1;if(l>=0){const o=[...n];return o[l]=s,o}if(s.role==="user"){const o=n.findIndex(u=>u.role==="user"&&u.id.startsWith("temp-")&&u.content.trim()===s.content.trim());if(o>=0){const u=[...n];return u[o]=s,u}}return[...n,s]}function ci(n,s){const{t:r}=Le("app"),l=`${st.CHAT_ROOMS}:${n??"global"}`,o=`${st.ACTIVE_CHAT_ROOM_ID}:${n??"global"}`,u=a.useCallback(R=>`${st.CHAT_ROOM_MESSAGES_PREFIX}${n??"global"}:${R}`,[n]),b=a.useCallback(R=>`${st.CHAT_ROOM_MEMBERS_PREFIX}${n??"global"}:${R}`,[n]),[d,c]=a.useState(()=>{const R=Ze(l,{maxAgeMs:rs});return Array.isArray(R)?R:[]}),[m,$]=a.useState(()=>d.length===0),[x,y]=a.useState(null),[k,S]=a.useState(()=>{const R=Ze(o,{maxAgeMs:Xs});return R?d.find(_=>_.id===R)??null:null}),[T,N]=a.useState([]),[L,v]=a.useState([]),[W,H]=a.useState(!1),le=a.useRef(d),j=a.useRef(k),Q=a.useRef(0),P=a.useRef(n);le.current=d,j.current=k,P.current!==n&&(P.current=n,Q.current+=1);const z=a.useCallback(async R=>{if(!R){N([]),v([]),H(!1);return}const _=es(R.id,{warm:!1});_.mark("select");const D=Ze(u(R.id),{maxAgeMs:yr}),g=Ze(b(R.id),{maxAgeMs:rs}),O=Array.isArray(D)&&D.length>0,f=Array.isArray(g)&&g.length>0;O||f?(_.mark("cache-hit"),O&&(v(D),_.mark("hydrate")),f&&N(g),H(!1)):(v([]),H(!0));try{const[ie,q]=await Promise.all([xr(R.id,n),Wn(R.id,{limit:100,order:"desc"},n)]);_.mark("members-fetch"),_.mark("messages-fetch"),ce(b(R.id),ie.members,{maxBytes:5e5}),ce(u(R.id),q.messages,{maxBytes:5e5}),j.current?.id===R.id&&(N(ie.members),v(q.messages),_.mark("hydrate"))}catch{!O&&!f&&(N([]),v([]))}finally{H(!1),_.complete({warm:O,membersCached:f})}},[b,u,n]),F=a.useCallback(async()=>{le.current.length===0&&$(!0);try{const R=await wr({},n),_=is(R.rooms);c(_),ce(l,_,{maxBytes:5e5}),y(null);const D=Ze(o,{maxAgeMs:Xs})??Ct(Je,n);if(D){const g=_.find(O=>O.id===D)??null;g?(S(g),z(g)):(xt(Je,n),ce(o,"",{maxBytes:5e5}))}}catch(R){const _=R instanceof Error?R.message:r("chatRooms.error.failedToLoad","Failed to load chat rooms");y(_),s?.(_,"error")}finally{$(!1)}},[o,s,z,n,l]),U=a.useCallback(R=>{if(!R){j.current=null,S(null),xt(Je,n),ce(o,"",{maxBytes:5e5}),z(null);return}const _=le.current.find(D=>D.id===R)??null;j.current=_,S(_),_&&(xn(Je,_.id,n),ce(o,_.id,{maxBytes:5e5}),z(_))},[o,z,n]),C=a.useCallback(async R=>{const D=(await Cr({name:R.name,memberAgentIds:R.memberAgentIds},n)).room;return c(g=>vt(g,D)),j.current=D,S(D),xn(Je,D.id,n),ce(o,D.id,{maxBytes:5e5}),await z(D),D},[o,z,n]),I=a.useCallback(async R=>{await Sr(R,n),c(_=>_.filter(D=>D.id!==R)),ce(u(R),[],{maxBytes:5e5}),ce(b(R),[],{maxBytes:5e5}),j.current?.id===R&&(j.current=null,S(null),N([]),v([]),xt(Je,n),ce(o,"",{maxBytes:5e5}))},[o,b,u,n]),E=a.useCallback(async(R,_)=>{const D=j.current,g=D?.id;if(!g)throw new Error(r("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const O=es(g,{warm:!1}),f=_?.files?.map(K=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,filename:K.name,originalName:K.name,mimeType:K.type||"application/octet-stream",size:K.size,createdAt:new Date().toISOString()})),ie=oi(g,R,f?.length?f:_?.attachments);j.current?.id===g&&v(K=>{const me=[...K,ie];return ce(u(g),me,{maxBytes:5e5}),me});let q=!1;try{const K=[];if(_?.files?.length)for(const ve of _.files)try{const ye=await kr(g,ve,n);K.push(ye.attachment)}catch{throw new Error(r("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:ve.name}))}const me=[..._?.attachments??[],...K],ge=await Nr(g,{content:R,...me.length?{attachments:me}:{}},n);q=!0,ge.message?.createdAt&&D&&c(ve=>vt(ve,{...D,updatedAt:ge.message.createdAt})),j.current?.id===g&&v(ve=>{const ye=ua(ve,ge.message,ie.id);return ce(u(g),ye,{maxBytes:5e5}),ye});const oe=await Wn(g,{limit:100,order:"desc"},n);if(ce(u(g),oe.messages,{maxBytes:5e5}),j.current?.id!==g)return;v(oe.messages),O.mark("hydrate")}catch(K){let me=null;try{const oe=await Wn(g,{limit:100,order:"desc"},n);me=oe.messages,ce(u(g),oe.messages,{maxBytes:5e5}),j.current?.id===g&&(v(oe.messages),O.mark("hydrate"))}catch{j.current?.id===g&&v(oe=>{const ve=oe.filter(ye=>ye.id!==ie.id);return ce(u(g),ve,{maxBytes:5e5}),ve})}const ge=me?.some(oe=>oe.role==="user"&&oe.content.trim()===ie.content.trim());if(q||ge){const oe=K instanceof Error&&K.message.trim()?K.message:r("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new Fa(oe,g)}throw K}finally{O.complete({source:"send-room-message"})}},[u,n]),Y=a.useCallback(async R=>{!R||!le.current.some(_=>_.id===R)||(await Mr(R,n),ce(u(R),[],{maxBytes:5e5}),j.current?.id===R&&v([]))},[u,n]);return a.useEffect(()=>{F()},[F]),a.useEffect(()=>{const R=Q.current,_=n?`/api/events?projectId=${encodeURIComponent(n)}`:"/api/events";return ja(_,{onReconnect:()=>{zt({view:"useChatRooms",trigger:"sse-reconnect",projectId:n,replayAttempted:!1});const D=j.current?.id;if(D){const g=es(D,{warm:!0});g.mark("sse-reconnect-refresh"),F().finally(()=>g.complete({source:"sse-reconnect"}));return}F()},events:{"chat:room:created":D=>{if(Q.current!==R)return;const g=Ke(D);g&&c(O=>vt(O,g))},"chat:room:updated":D=>{if(Q.current!==R)return;const g=Ke(D);g&&(c(O=>vt(O,g)),j.current?.id===g.id&&S(g))},"chat:room:deleted":D=>{if(Q.current!==R)return;const g=Ke(D);g?.id&&(c(O=>O.filter(f=>f.id!==g.id)),ce(u(g.id),[],{maxBytes:5e5}),ce(b(g.id),[],{maxBytes:5e5}),j.current?.id===g.id&&(j.current=null,S(null),N([]),v([]),xt(Je,n),ce(o,"",{maxBytes:5e5})))},"chat:room:member:added":D=>{if(Q.current!==R)return;const g=Ke(D);!g||j.current?.id!==g.roomId||N(O=>{if(O.some(ie=>ie.agentId===g.agentId))return O;const f=[...O,g];return ce(b(g.roomId),f,{maxBytes:5e5}),f})},"chat:room:member:removed":D=>{if(Q.current!==R)return;const g=Ke(D);!g||j.current?.id!==g.roomId||N(O=>{const f=O.filter(ie=>ie.agentId!==g.agentId);return ce(b(g.roomId),f,{maxBytes:5e5}),f})},"chat:room:message:added":D=>{if(Q.current!==R)return;const g=Ke(D);g&&(c(O=>{const f=O.find(ie=>ie.id===g.roomId);return f?vt(O,{...f,updatedAt:g.createdAt}):O}),j.current?.id===g.roomId&&v(O=>{const f=ua(O,g);return f===O?O:(ce(u(g.roomId),f,{maxBytes:5e5}),f)}))},"chat:room:message:updated":D=>{if(Q.current!==R)return;const g=Ke(D);!g||j.current?.id!==g.roomId||v(O=>{const f=O.map(ie=>ie.id===g.id?g:ie);return ce(u(g.roomId),f,{maxBytes:5e5}),f})},"chat:room:message:deleted":D=>{if(Q.current!==R)return;const g=Ke(D);g?.id&&v(O=>{const f=O.filter(q=>q.id!==g.id),ie=j.current?.id;return ie&&ce(u(ie),f,{maxBytes:5e5}),f})},"chat:room:messages:cleared":D=>{if(Q.current!==R)return;const g=Ke(D);g?.roomId&&(ce(u(g.roomId),[],{maxBytes:5e5}),j.current?.id===g.roomId&&v([]),c(O=>{const f=O.find(ie=>ie.id===g.roomId);return f?vt(O,{...f,updatedAt:new Date().toISOString()}):O}))}}})},[o,b,u,n,F]),a.useEffect(()=>{k&&(d.some(R=>R.id===k.id)||(j.current=null,S(null),N([]),v([]),xt(Je,n),ce(o,"",{maxBytes:5e5})))},[k,o,n,d]),{rooms:d,roomsLoading:m,roomsError:x,activeRoom:k,activeRoomMembers:T,messages:L,messagesLoading:W,selectRoom:U,createRoom:C,deleteRoom:I,sendRoomMessage:E,clearRoom:Y,refreshRooms:F}}const Pt={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},da=200;function os(n){if(!n)return null;const s=new Date(n).getTime();return Number.isFinite(s)?s:null}function La(n){const s=Object.entries(n);if(s.length<=da)return n;const r=s.map(([l,o])=>({id:l,timestamp:o,value:os(o)??0})).sort((l,o)=>o.value-l.value).slice(0,da);return Object.fromEntries(r.map(({id:l,timestamp:o})=>[l,o]))}function hn(n){if(!n)return{};try{const s=JSON.parse(n);if(!s||typeof s!="object")return{};const r={};for(const[l,o]of Object.entries(s))typeof l=="string"&&typeof o=="string"&&(r[l]=o);return La(r)}catch{return{}}}function li(n){const[s,r]=a.useState(()=>{try{return hn(Ct(Pt.direct,n))}catch{return{}}}),[l,o]=a.useState(()=>{try{return hn(Ct(Pt.room,n))}catch{return{}}});a.useEffect(()=>{try{r(hn(Ct(Pt.direct,n)))}catch{r({})}try{o(hn(Ct(Pt.room,n)))}catch{o({})}},[n]);const u=a.useMemo(()=>({direct:s,room:l}),[s,l]),b=a.useCallback((x,y)=>{const k=La(y);try{xn(Pt[x],JSON.stringify(k),n)}catch{}return k},[n]),d=a.useCallback((x,y)=>{if(x==="direct"){r(k=>b(x,y(k)));return}o(k=>b(x,y(k)))},[b]),c=a.useCallback((x,y,k)=>{const S=os(k);if(S===null)return!1;const T=u[x][y],N=os(T);return N===null?!0:S>N},[u]),m=a.useCallback((x,y,k)=>{if(!y)return;const S=k??new Date().toISOString();d(x,T=>({...T,[y]:S}))},[d]),$=a.useCallback((x,y)=>{y.length!==0&&d(x,k=>{const S={...k};for(const T of y)T.id&&(S[T.id]=T.lastActivityAt??new Date().toISOString());return S})},[d]);return{isUnread:c,markRead:m,markAllRead:$}}const ui=["AskUserQuestion","ask_user","ask_followup_question","request_user_input","elicit","ask_question","fn_ask_question"],di=new Set(ui.map(n=>n.toLowerCase()));function mi(n){return di.has(n.toLowerCase())}function hi(n){if(!mi(n.toolName))return null;const s=St(n.args);if(!s)return null;const r=Array.isArray(s.questions)?s.questions:null,l=r?r.map((o,u)=>ma(o,u)).filter(fa):[ma(s,0)].filter(fa);return l.length>0?{questions:l}:null}function fi(n,s){return n.map(r=>{const l=s[r.id];return`> Q: ${r.question}
|
|
17
|
+
${yi(r,l)}`}).join(`
|
|
18
|
+
|
|
19
|
+
`)}function ma(n,s){const r=St(n);if(!r)return null;const l=Fe(r.question,r.prompt,r.message,r.text,r.title);if(!l)return null;const o=vi(xi(r.options,r.choices,r.enum,r.values)),u=pi(Fe(r.type,r.questionType,r.inputType,r.responseType)),b=!!(r.multiSelect??r.multiselect??r.multiple??r.allowMultiple??r.multiple_choice);if((u==="single_select"||u==="multi_select")&&o.length===0)return null;const d=gi(r,o,u,b);return(d==="single_select"||d==="multi_select")&&o.length===0?null:{id:Fe(r.id,r.name,r.key)??`q-${s}`,type:d,question:l,header:Fe(r.header,r.heading)??void 0,description:Fe(r.description,r.details,r.helpText)??void 0,options:o.length>0?o:void 0,multiSelect:d==="multi_select"?!0:b||void 0}}function gi(n,s,r,l){return r?r==="multi_select"&&s.length===0||r==="single_select"&&s.length===0?"text":r:bi(n,s)?"confirm":s.length>0?l?"multi_select":"single_select":"text"}function pi(n){if(!n)return null;const s=n.toLowerCase().replace(/[\s-]+/g,"_");return s==="text"||s==="free_text"||s==="input"?"text":s==="single_select"||s==="select"||s==="choice"?"single_select":s==="multi_select"||s==="multiple_select"||s==="checkbox"?"multi_select":s==="confirm"||s==="confirmation"||s==="boolean"||s==="yes_no"?"confirm":null}function bi(n,s){const r=Fe(n.type,n.schemaType,n.inputType,n.responseType)?.toLowerCase().replace(/[\s-]+/g,"_");if(r==="boolean"||r==="confirm"||r==="confirmation"||r==="yes_no")return!0;const l=St(n.schema)??St(n.inputSchema)??St(n.parameters),o=Fe(l?.type,l?.format)?.toLowerCase().replace(/[\s-]+/g,"_");if(o==="boolean"||o==="yes_no")return!0;if(s.length!==2)return!1;const u=s.map(b=>b.label.trim().toLowerCase());return u.includes("yes")&&u.includes("no")}function vi(n){return n?n.map((s,r)=>{const l=St(s);if(!l)return typeof s=="string"||typeof s=="number"||typeof s=="boolean"?{id:`opt-${r}`,label:String(s)}:null;const o=Fe(l.label,l.text,l.name,l.title,l.value,l.id);return o?{id:Fe(l.id,l.value,l.key)??`opt-${r}`,label:o,description:Fe(l.description,l.details,l.helpText)??void 0}:null}).filter(wi):[]}function yi(n,s){if(s===void 0)return"(no answer)";if(n.type==="confirm")return s===!0?"Yes":"No";if(Array.isArray(s)){const r=s.map(l=>ha(n,l)).filter(Boolean);return r.length>0?r.join(", "):"(no answer)"}return n.type==="single_select"?ha(n,String(s))??String(s):String(s).trim()||"(no answer)"}function ha(n,s){return n.options?.find(r=>r.id===s)?.label??null}function St(n){return n&&typeof n=="object"&&!Array.isArray(n)?n:null}function Fe(...n){for(const s of n){if(typeof s=="string"&&s.trim().length>0)return s.trim();if(typeof s=="number"||typeof s=="boolean")return String(s)}return null}function xi(...n){return n.find(Array.isArray)??null}function fa(n){return n!==null}function wi(n){return n!==null}function Ci({parsed:n,answered:s=!1,submittedAnswer:r,compact:l=!1,disabled:o=!1,onSubmit:u}){const{t:b}=Le("app"),[d,c]=a.useState({}),m=a.useRef(new Map),$=a.useMemo(()=>n.questions.every(S=>ki(S,d[S.id])),[d,n.questions]);a.useLayoutEffect(()=>{for(const S of m.current.values())S.style.height="0",S.style.height=`${S.scrollHeight}px`},[d]);const x=a.useCallback((S,T)=>{c(N=>({...N,[S]:T}))},[]),y=a.useCallback((S,T,N)=>{c(L=>{const v=L[S],W=Array.isArray(v)?v:[];return{...L,[S]:N?[...W,T]:W.filter(H=>H!==T)}})},[]),k=a.useCallback(()=>{if(!$||s||o)return;const S=fi(n.questions,d);u(S,d)},[d,s,o,$,u,n.questions]);return e.jsxs("section",{className:`chat-question-response${l?" chat-question-response--compact":""}${s?" chat-question-response--answered":""}`,"data-testid":"chat-question-response","aria-label":b("chat.questionResponseLabel","Question from assistant"),children:[e.jsxs("div",{className:"chat-question-response__header",children:[e.jsx("span",{className:"chat-question-response__eyebrow",children:b("chat.questionResponseEyebrow","Assistant question")}),s&&e.jsx("span",{className:"chat-question-response__answered-label",children:b("chat.questionAnsweredLabel","Answered")})]}),e.jsx("div",{className:"chat-question-response__questions",children:n.questions.map((S,T)=>e.jsxs("article",{className:"chat-question-response__question",children:[S.header&&e.jsx("p",{className:"chat-question-response__question-header",children:S.header}),e.jsx("h4",{className:"chat-question-response__question-text",children:S.question}),S.description&&e.jsx("p",{className:"chat-question-response__description",children:S.description}),s?null:e.jsx(Si,{question:S,questionIndex:T,value:d[S.id],disabled:o,setQuestionAnswer:x,toggleMultiSelect:y,textareaRefs:m})]},S.id))}),s?e.jsxs("div",{className:"chat-question-response__submitted","data-testid":"chat-question-response-submitted-answer",children:[e.jsx("span",{className:"chat-question-response__submitted-label",children:b("chat.questionSubmittedAnswerLabel","Submitted answer")}),e.jsx("pre",{children:r||b("chat.questionAnsweredWithoutContent","A later user reply answered this question.")})]}):e.jsxs("div",{className:"chat-question-response__actions",children:[e.jsx("p",{className:"chat-question-response__hint",children:b("chat.questionSelectHint","Answer all questions to continue the chat.")}),e.jsx("button",{type:"button",className:"btn btn-primary chat-question-response__submit","data-testid":"chat-question-response-submit",disabled:!$||o,onClick:k,children:b("chat.questionSubmit","Send answer")})]})]})}function Si({question:n,questionIndex:s,value:r,disabled:l,setQuestionAnswer:o,toggleMultiSelect:u,textareaRefs:b}){const{t:d}=Le("app");if(n.type==="text")return e.jsx("textarea",{className:"input chat-question-response__textarea","data-testid":`chat-question-response-text-${n.id}`,placeholder:d("chat.questionTextPlaceholder","Type your answer here…"),value:typeof r=="string"?r:"",disabled:l,rows:3,ref:y=>{y?b.current.set(n.id,y):b.current.delete(n.id)},onChange:y=>o(n.id,y.target.value)});if(n.type==="confirm")return e.jsxs("div",{className:"chat-question-response__confirm-group",role:"group","aria-label":n.question,children:[e.jsx("button",{type:"button",className:`btn chat-question-response__confirm${r===!0?" chat-question-response__confirm--selected":""}`,"data-testid":`chat-question-response-option-${n.id}-yes`,disabled:l,onClick:()=>o(n.id,!0),children:d("chat.questionConfirmYes","Yes")}),e.jsx("button",{type:"button",className:`btn chat-question-response__confirm${r===!1?" chat-question-response__confirm--selected":""}`,"data-testid":`chat-question-response-option-${n.id}-no`,disabled:l,onClick:()=>o(n.id,!1),children:d("chat.questionConfirmNo","No")})]});const c=n.options??[],m=Array.isArray(r)?r:[],$=`chat-question-${n.id}-${s}`,x=n.type==="multi_select";return e.jsx("div",{className:"chat-question-response__options",role:x?"group":"radiogroup","aria-label":n.question,children:c.map(y=>{const k=x?m.includes(y.id):r===y.id;return e.jsxs("label",{className:`chat-question-response__option${k?" chat-question-response__option--selected":""}`,"data-testid":`chat-question-response-option-${n.id}-${y.id}`,children:[e.jsx("input",{type:x?"checkbox":"radio",name:x?void 0:$,value:y.id,checked:k,disabled:l,onChange:S=>{x?u(n.id,y.id,S.target.checked):o(n.id,y.id)}}),e.jsxs("span",{className:"chat-question-response__option-content",children:[e.jsx("span",{className:"chat-question-response__option-label",children:y.label}),y.description&&e.jsx("span",{className:"chat-question-response__option-description",children:y.description})]})]},y.id)})})}function ki(n,s){return n.type==="text"?typeof s=="string"&&s.trim().length>0:n.type==="multi_select"?Array.isArray(s)&&s.length>0:n.type==="confirm"?typeof s=="boolean":typeof s=="string"&&s.trim().length>0}function ga(n){return n.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function Pa(n,s){const r=s.trim();if(!r)return!0;const l=ga(r);return ga(n).includes(l)||n.toLowerCase().includes(r.toLowerCase())}function pa({agents:n,filter:s,highlightedIndex:r,visible:l,onSelect:o,position:u="below",roomMemberIds:b,roomName:d}){const{t:c}=Le("app"),m=a.useMemo(()=>n.filter(T=>Pa(T.name,s)),[n,s]),$=!!b,x=$&&s.trim().length>0,y=a.useMemo(()=>$?m.filter(T=>b?.has(T.id)):m,[m,b,$]),k=a.useMemo(()=>$?m.filter(T=>!b?.has(T.id)):[],[m,b,$]),S=x?[...y,...k]:y;return l?e.jsx("div",{className:`agent-mention-popup agent-mention-popup--${u}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":c("agentMention.suggestionsLabel","Agent mention suggestions"),children:S.length===0?e.jsx("div",{className:"agent-mention-empty",children:c("agentMention.noAgentsFound","No agents found")}):e.jsxs(e.Fragment,{children:[$&&e.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:d?c("agentMention.membersOf","Members of #{{roomName}}",{roomName:d}):c("agentMention.roomMembers","Room members")}),y.map((T,N)=>e.jsxs("button",{type:"button",className:`agent-mention-item${N===r?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${T.id}`,onMouseDown:L=>L.preventDefault(),onClick:()=>o(T),role:"option","aria-selected":N===r,children:[e.jsx(wn,{agent:T,size:20}),$&&e.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":c("agentMention.roomMemberBadge","Room member")}),e.jsx("span",{className:"agent-mention-name",children:T.name}),e.jsx("span",{className:"agent-mention-role",children:T.role})]},T.id)),$&&!x&&k.length>0&&e.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:c("agentMention.typeToSearch","Type to search other agents")}),$&&x&&k.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:c("agentMention.otherAgents","Other agents")}),k.map((T,N)=>{const L=y.length+N;return e.jsxs("button",{type:"button",className:`agent-mention-item${L===r?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${T.id}`,onMouseDown:v=>v.preventDefault(),onClick:()=>o(T),role:"option","aria-selected":L===r,children:[e.jsx(wn,{agent:T,size:20}),e.jsx("span",{className:"agent-mention-name",children:T.name}),e.jsx("span",{className:"agent-mention-role",children:T.role})]},T.id)})]})]})}):null}function Ni(n,s){return n+s}function Mi({visible:n,position:s,tasks:r,files:l,selectedIndex:o,onSelectTask:u,onSelectFile:b,loading:d}){const{t:c}=Le("app");if(!n)return null;const m=r.length>0,$=l.length>0;return e.jsxs("div",{className:"file-mention-popup",style:{top:s.top,left:s.left},"data-testid":"file-mention-popup",onMouseDown:x=>{x.preventDefault()},children:[d&&e.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:e.jsx("span",{className:"spinner"})}),!d&&!m&&!$&&e.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:c("fileMention.empty","No tasks or files found")}),!d&&(m||$)&&e.jsxs("div",{className:"file-mention-popup-groups",children:[m&&e.jsxs("div",{className:"file-mention-popup-group",children:[e.jsx("div",{className:"file-mention-popup-group-header",children:c("fileMention.taskHeader","Tasks")}),e.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":c("fileMention.taskMatches","Task matches"),children:r.map((x,y)=>{const k=y;return e.jsxs("li",{className:`file-mention-popup-item${k===o?" file-mention-popup-item--selected":""}`,onClick:()=>u(x),role:"option","aria-selected":k===o,"data-testid":`task-mention-item-${k}`,children:[e.jsx("span",{className:"file-mention-popup-icon",children:e.jsx(Da,{})}),e.jsxs("div",{className:"file-mention-popup-info",children:[e.jsxs("div",{className:"file-mention-popup-task-row",children:[e.jsx("span",{className:"file-mention-popup-task-id",children:x.id}),e.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${x.column}`,children:x.column})]}),e.jsx("span",{className:"file-mention-popup-item-path",children:x.title})]})]},x.id)})})]}),$&&e.jsxs("div",{className:"file-mention-popup-group",children:[e.jsx("div",{className:"file-mention-popup-group-header",children:c("fileMention.fileHeader","Files")}),e.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":c("fileMention.fileMatches","File matches"),children:l.map((x,y)=>{const k=Ni(r.length,y),S=Rr(x.path);return e.jsxs("li",{className:`file-mention-popup-item${k===o?" file-mention-popup-item--selected":""}`,onClick:()=>b(x),role:"option","aria-selected":k===o,"data-testid":`file-mention-item-${k}`,children:[e.jsx("span",{className:"file-mention-popup-icon",children:e.jsx(Ta,{})}),e.jsxs("div",{className:"file-mention-popup-info",children:[e.jsx("span",{className:"file-mention-popup-item-name",children:x.name}),S&&e.jsx("span",{className:"file-mention-popup-item-path",children:S})]})]},x.path)})})]})]})]})}function Ri(n,s=[],r){const l=n.trim().replace(/^#/,""),o=(b,d)=>r?r(b,d):d;if(!l)return{ok:!1,error:o("createRoom.nameRequired","Room name is required.")};if(/[A-Z]/.test(l))return{ok:!1,error:o("createRoom.lowercase","Use lowercase letters only.")};const u=l.toLowerCase();return u.length>80?{ok:!1,error:o("createRoom.maxLength","Room names can be at most 80 characters.")}:/^[a-z0-9_-]+$/.test(u)?/^[-_]|[-_]$/.test(u)?{ok:!1,error:o("createRoom.noEdgeChars","Room names cannot start or end with a hyphen or underscore.")}:s.some(b=>b.toLowerCase()===u)?{ok:!1,error:o("createRoom.duplicate","A room with this name already exists.")}:{ok:!0,name:u}:{ok:!1,error:o("createRoom.validChars","Use lowercase letters, numbers, hyphens, or underscores only.")}}function Ai({isOpen:n,onClose:s,onCreate:r,projectId:l,existingRoomNames:o=[]}){const{t:u}=Le("app"),[b,d]=a.useState(""),[c,m]=a.useState([]),[$,x]=a.useState(""),[y,k]=a.useState([]),[S,T]=a.useState(!1),[N,L]=a.useState(null),[v,W]=a.useState(!1),H=a.useRef(null),le=a.useRef(null);a.useEffect(()=>{n&&(le.current=document.activeElement instanceof HTMLElement?document.activeElement:null,T(!0),L(null),Ar(void 0,l).then(C=>m(C)).catch(()=>{m([]),L(u("createRoom.failedLoadAgents","Failed to load agents."))}).finally(()=>T(!1)))},[n,l]),a.useEffect(()=>{if(!n){d(""),x(""),k([]),L(null),W(!1);return}const C=window.requestAnimationFrame(()=>H.current?.focus());return()=>window.cancelAnimationFrame(C)},[n]),a.useEffect(()=>{if(!n)return;const C=I=>{I.key==="Escape"&&s()};return document.addEventListener("keydown",C),()=>document.removeEventListener("keydown",C)},[n,s]),a.useEffect(()=>{n||le.current?.focus()},[n]);const j=a.useMemo(()=>Ri(b,o,u),[b,o,u]),Q=a.useMemo(()=>{const C=$.trim().toLowerCase();return C?c.filter(I=>I.name.toLowerCase().includes(C)):c},[c,$]),P=a.useMemo(()=>c.filter(C=>y.includes(C.id)),[c,y]),z=j.ok&&y.length>0&&!v&&!S;if(!n)return null;const F=C=>{v||k(I=>I.includes(C)?I.filter(E=>E!==C):[...I,C])},U=async()=>{if(!j.ok){L(j.error);return}if(y.length===0){L(u("createRoom.selectMember","Select at least one member."));return}L(null),W(!0);try{await r({name:j.name,displayName:`#${j.name}`,memberAgentIds:y}),s()}catch(C){L(C instanceof Error?C.message:u("createRoom.failedCreate","Failed to create room."))}finally{W(!1)}};return lr.createPortal(e.jsx("div",{className:"modal-overlay open",onClick:C=>C.target===C.currentTarget&&s(),children:e.jsxs("div",{className:"modal modal-lg create-room-modal",role:"dialog","aria-modal":"true","aria-label":u("createRoom.title","Create room"),onClick:C=>C.stopPropagation(),children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{children:u("createRoom.title","Create room")}),e.jsx("button",{type:"button",className:"modal-close","aria-label":u("actions.close","Close"),onClick:s,children:"×"})]}),e.jsxs("div",{className:"form-group create-room-modal-name-group",children:[e.jsx("label",{htmlFor:"create-room-name",children:u("createRoom.nameLabel","Room name")}),e.jsxs("div",{className:"create-room-modal-name-field",children:[e.jsx("span",{"aria-hidden":"true",className:"create-room-modal-name-hash",children:"#"}),e.jsx("input",{ref:H,id:"create-room-name",className:"input",value:b,disabled:v,onChange:C=>{const I=C.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();d(I)}})]}),!j.ok&&e.jsx("div",{className:"form-error",children:j.error})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"create-room-member-search",children:u("createRoom.members","Members")}),e.jsx("input",{id:"create-room-member-search",className:"input",placeholder:u("createRoom.searchAgents","Search agents"),value:$,disabled:v,onChange:C=>x(C.target.value)})]}),P.length>0&&e.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:P.map(C=>e.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>F(C.id),disabled:v,children:[C.name," ×"]},C.id))}),e.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:S?e.jsx("div",{className:"create-room-modal-empty",children:e.jsx(jr,{label:u("createRoom.loadingAgents","Loading agents...")})}):Q.length===0?e.jsx("div",{className:"create-room-modal-empty",children:c.length===0?u("createRoom.noAgents","No agents in this project yet."):u("createRoom.noMatch","No agents match your search.")}):Q.map(C=>{const I=y.includes(C.id);return e.jsxs("button",{type:"button",className:`create-room-modal-member-row${I?" create-room-modal-member-row--selected":""}`,onClick:()=>F(C.id),disabled:v,children:[e.jsx(wn,{agent:C,size:20}),e.jsx("span",{children:C.name}),e.jsx("span",{className:"create-room-modal-member-role",children:C.role})]},C.id)})}),N&&e.jsx("div",{className:"form-group",children:e.jsx("div",{className:"form-error",children:N})}),e.jsxs("div",{className:"modal-actions",children:[e.jsx("button",{type:"button",className:"btn",onClick:s,disabled:v,children:u("actions.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void U(),disabled:!z,children:v?u("createRoom.creating","Creating..."):u("createRoom.create","Create room")})]})]})}),document.body)}function ji({cliSessionId:n,tier:s,projectId:r,renderTranscript:l,renderComposer:o,queuedCount:u=0,terminalProps:b}){const{t:d}=Le("app"),c=s==="generic",[m,$]=a.useState(c?"terminal":"transcript");if(c)return e.jsx("div",{className:"cli-chat-surface cli-chat-surface--generic","data-tier":"generic",children:e.jsx(ra,{sessionId:n,projectId:r,...b})});const x=m==="terminal";return e.jsxs("div",{className:"cli-chat-surface","data-tier":s,"data-view":m,children:[e.jsxs("div",{className:"cli-chat-surface__toolbar",role:"tablist","aria-label":d("cliChat.viewToggleLabel","Chat view"),children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":!x,className:`cli-chat-surface__tab${x?"":" is-active"}`,onClick:()=>$("transcript"),children:[e.jsx(bn,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:d("cliChat.transcriptTab","Transcript")})]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":x,className:`cli-chat-surface__tab${x?" is-active":""}`,onClick:()=>$("terminal"),children:[e.jsx(Tr,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:d("cliChat.terminalTab","Terminal")})]})]}),e.jsx("div",{className:"cli-chat-surface__body",children:x?e.jsx(ra,{sessionId:n,projectId:r,...b}):l()}),!x&&e.jsxs("div",{className:"cli-chat-surface__composer",children:[u>0&&e.jsx("div",{className:"cli-chat-surface__queued",role:"status","aria-live":"polite",children:d("cliChat.queued","{{count}} message queued — will send when the agent is ready",{count:u})}),o()]})]})}const Ti=200,Ei=8,_i=8;function ba(){return new DOMException("The operation was aborted.","AbortError")}function va(n,s){return s.aborted?Promise.reject(ba()):new Promise((r,l)=>{const o=()=>l(ba());s.addEventListener("abort",o,{once:!0}),n.then(u=>{s.removeEventListener("abort",o),r(u)},u=>{s.removeEventListener("abort",o),l(u)})})}function ya(n,s,r){const l=n.slice(0,s),o=n.slice(s+1),u=o.match(/[\s]|$/),b=u?u.index??o.length:o.length,d=o.slice(b);return`${l}${r}${d}`}function $i(n={}){const{projectId:s,workspace:r="project"}=n,[l,o]=a.useState(!1),[u,b]=a.useState(""),[d,c]=a.useState(-1),[m,$]=a.useState([]),[x,y]=a.useState([]),[k,S]=a.useState(!1),[T,N]=a.useState(0),L=a.useRef(null),v=a.useRef(null),W=[...m.map(F=>({kind:"task",task:F})),...x.map(F=>({kind:"file",file:F}))];a.useEffect(()=>()=>{L.current&&clearTimeout(L.current),v.current?.abort()},[]);const H=a.useCallback((F,U)=>{if(U<0||U>F.length){o(!1);return}const C=I=>/[a-zA-Z0-9/_.-]/.test(I);for(let I=U-1;I>=0;I--){if(F[I]==="#"){if(I===0){const Y=F.slice(I+1,U);c(I),b(Y),N(0),o(!0);return}const E=F[I-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const Y=F.slice(I+1,U);c(I),b(Y),N(0),o(!0);return}o(!1);return}if(!C(F[I])){o(!1);return}}o(!1)},[]),le=a.useCallback(()=>{v.current?.abort(),o(!1),b(""),c(-1),$([]),y([]),N(0),S(!1)},[]),j=a.useCallback(async F=>{if(!F.trim()){$([]),y([]),S(!1);return}v.current?.abort();const U=new AbortController;v.current=U;try{S(!0);const[C,I]=await Promise.allSettled([va(Er(20,0,s,F),U.signal),va(_r(F,r,s),U.signal)]);if(U.signal.aborted)return;const E=C.status==="fulfilled"?C.value.slice(0,Ei).map(R=>({id:R.id,title:R.title??"",column:R.column})):[],Y=I.status==="fulfilled"?I.value.files.slice(0,_i):[];$(E),y(Y),N(0)}catch(C){C.name!=="AbortError"&&($([]),y([]))}finally{U.signal.aborted||S(!1)}},[r,s]);a.useEffect(()=>{if(l)return L.current&&clearTimeout(L.current),L.current=setTimeout(()=>{j(u)},Ti),()=>{L.current&&clearTimeout(L.current)}},[u,l,j]);const Q=a.useCallback((F,U)=>!l||d<0?U:ya(U,d,`#${F.id}`),[l,d]),P=a.useCallback((F,U)=>!l||d<0?U:ya(U,d,`#${F.path}`),[l,d]),z=a.useCallback((F,U)=>{if(!l||W.length===0)return!1;switch(F.key){case"ArrowDown":return F.preventDefault(),N(C=>Math.min(C+1,W.length-1)),!0;case"ArrowUp":return F.preventDefault(),N(C=>Math.max(C-1,0)),!0;case"Enter":case"Tab":return W[T]?(F.preventDefault(),!0):!1;case"Escape":return F.preventDefault(),le(),!0;default:return!1}},[l,W,T,le]);return{mentionActive:l,tasks:m,files:x,combinedItems:W,loading:k,mentionQuery:u,selectedIndex:T,setSelectedIndex:N,detectMention:H,selectTask:Q,selectFile:P,dismissMention:le,handleKeyDown:z}}const ts=new Map,vn=new Map;function ms(n){return n??"global"}function cs(n){return`${st.DISCOVERED_SKILLS_PREFIX}${ms(n)}`}function yt(n){return Ze(cs(n),{maxAgeMs:rs})}function Di(n,s){for(const r of vn.get(n)??[])r(s)}async function Fi(n){const s=ms(n),r=ts.get(s);if(r)return r;const l=$r(n).finally(()=>{ts.delete(s)});return ts.set(s,l),l}function Li(n){const[s,r]=a.useState(()=>yt(n)??[]),[l,o]=a.useState(()=>yt(n)===null),u=a.useRef(yt(n)!==null),b=ms(n);a.useEffect(()=>{const m=yt(n)??[];r(m),o(yt(n)===null),u.current=yt(n)!==null},[n]),a.useEffect(()=>{const m=vn.get(b)??new Set;return m.add(r),vn.set(b,m),()=>{m.delete(r),m.size===0&&vn.delete(b)}},[b]);const d=a.useCallback(async()=>{try{const m=await Fi(n);u.current=!0,ce(cs(n),m,{maxBytes:5e5}),Di(b,m)}catch{u.current||pn(cs(n))}finally{o(!1)}},[n,b]);a.useEffect(()=>{d()},[d]);const c=a.useCallback(async()=>{o(!0),await d()},[d]);return{skills:s,loading:l,refresh:c}}function Pi(n,s){const r=n.reduce((l,o)=>l+(o.content?.length??0),0)+(s?.length??0);return Math.ceil(r/4)}function xa(n){if(!Number.isFinite(n)||n<=0)return"0";if(n<1e3)return String(Math.round(n));const s=n/1e3;return s<10?`~${Number(s.toFixed(1))}k`:`${Math.round(s)}k`}const hs=640,Ii=200,wa="__SKIP__";let ns=!1;function Oi(n,s=hs){return n>s?"auto":"hidden"}function zi(n,s=hs){return Math.max(40,Math.min(n,s))}function Ia(n,s){const r=new Date(n),o=new Date().getTime()-r.getTime(),u=Math.floor(o/1e3),b=Math.floor(u/60),d=Math.floor(b/60),c=Math.floor(d/24);return u<60?s("chat.relativeTimeJustNow","just now"):b<60?s("chat.relativeTimeMinutes","{{count}}m ago",{count:b}):d<24?s("chat.relativeTimeHours","{{count}}h ago",{count:d}):c<7?s("chat.relativeTimeDays","{{count}}d ago",{count:c}):r.toLocaleDateString()}function Ca(n,s){if(!n||!s)return null;const r=s.toLowerCase();if(r.includes("claude")){let o=s.replace(/^claude[- ]/i,"Claude ").replace(/sonnet[- ](\d+)[- ](\d+)/i,"Sonnet $1.$2").replace(/sonnet[- ](\d+)/i,"Sonnet $1").replace(/haiku[- ](\d+)/i,"Haiku $1").replace(/opus[- ](\d+)/i,"Opus $1").replace(/sonnet/i,"Sonnet").replace(/haiku/i,"Haiku").replace(/opus/i,"Opus").replace(/-/g," ").trim();return o=o.replace(/\s+/g," "),o.length>30?o.slice(0,30)+"…":o}if(r.includes("gpt")||r.includes("openai")){const o=s.replace(/^gpt-4-turbo$/i,"GPT-4 Turbo").replace(/^gpt-4o-mini$/i,"GPT-4o Mini").replace(/^gpt-4o$/i,"GPT-4o").replace(/^gpt-4$/i,"GPT-4").replace(/^gpt-o1-preview$/i,"GPT-o1 Preview").replace(/^gpt-o1-mini$/i,"GPT-o1 Mini").replace(/^gpt-o1$/i,"GPT-o1").replace(/^gpt/i,"GPT").trim();return o.length>30?o.slice(0,30)+"…":o}if(r.includes("gemini")){const o=s.replace(/^gemini[- ]/i,"Gemini ").replace(/pro[- ](\d+)[- ](\d+)/i,"Pro $1.$2").replace(/pro[- ](\d+)/i,"Pro $1").replace(/-/g," ").replace(/\s+/g," ").trim();return o.length>30?o.slice(0,30)+"…":o}const l=s.replace(/-/g," ").replace(/^\w/,o=>o.toUpperCase()).replace(/\s+/g," ").trim();return l.length>30?l.slice(0,30)+"…":l}function yn(n,s){return n.length<=s?n:`${n.slice(0,s)}…`}function Bi(n){if(!n)return null;const s=Object.entries(n);return s.length===0?null:s.map(([r,l])=>{const o=typeof l=="string"?l:(()=>{try{return JSON.stringify(l)}catch{return String(l)}})();return`${r}=${yn(o,50)}`}).join(", ")}function Hi(n){if(n===void 0)return null;if(typeof n=="string")return yn(n,200);try{return yn(JSON.stringify(n),200)}catch{return yn(String(n),200)}}function Ui(n){if(!n)return null;if(n.kind==="mailbox"||n.kind==="mailbox-message"){const s=typeof window>"u"?"/":window.location.pathname||"/",r=new URLSearchParams(typeof window>"u"?"":window.location.search);return r.set("view","mailbox"),r.set("mailbox-message",n.id),`${s}?${r.toString()}#message-${encodeURIComponent(n.id)}`}return null}function qi(n,s){if(!n)return null;const r=n.label??`${n.kind} ${n.id}`,l=Ui(n),o=`chat-failure-reference-${n.kind}-${n.id}`.replace(/[^a-zA-Z0-9_-]+/g,"-").toLowerCase();return e.jsxs("div",{className:"chat-message-failure-reference",children:[e.jsx("span",{className:"chat-message-failure-reference-label",children:s("chat.failureReferenceLabel","Reference")}),e.jsx("span",{className:"chat-message-failure-reference-value",children:r}),l?e.jsx("a",{className:"btn btn-sm chat-message-failure-reference-link",href:l,children:s("chat.openMailboxMessage","Open mailbox message")}):e.jsxs("details",{className:"chat-message-failure-reference-details",children:[e.jsx("summary",{className:"btn btn-sm chat-message-failure-reference-link",children:s("chat.viewFailureDetails","View failure details")}),e.jsxs("dl",{className:"chat-message-failure-reference-meta",id:o,children:[e.jsxs("div",{children:[e.jsx("dt",{children:s("chat.failureReferenceKind","Kind")}),e.jsx("dd",{children:n.kind})]}),e.jsxs("div",{children:[e.jsx("dt",{children:s("chat.failureReferenceId","ID")}),e.jsx("dd",{children:n.id})]}),n.label&&e.jsxs("div",{children:[e.jsx("dt",{children:s("chat.failureReferenceMetaLabel","Label")}),e.jsx("dd",{children:n.label})]})]})]})]})}function Oa(n,s,r){if(!n||n.length===0)return null;const l=(k,S)=>{const T=hi(k);if(T){const j=r?.isAwaitingAnswer===!0;return e.jsx(Ci,{parsed:T,answered:!j,submittedAnswer:r?.submittedAnswer,disabled:!j,onSubmit:(Q,P)=>r?.onQuestionSubmit?.(Q,P)},`${k.toolName}-${S}`)}const N=k.status==="running",L=k.status==="completed"&&k.isError,v=Bi(k.args),W=Hi(k.result),H=N?v:W?`${s("chat.toolCallResultPrefix","result")}: ${W}`:v?`${s("chat.toolCallArgsPrefix","args")}: ${v}`:null,le=N?s("chat.toolCallStatusRunning","running"):L?s("chat.toolCallStatusError","error"):s("chat.toolCallStatusCompleted","completed");return e.jsxs("details",{className:`chat-tool-call${N?" chat-tool-call--running":""}${L?" chat-tool-call--error":""}`,open:N,children:[e.jsxs("summary",{children:[e.jsx("span",{className:"chat-tool-call-status-dot","aria-hidden":"true"}),e.jsx("span",{className:"chat-tool-call-name",title:k.toolName,children:k.toolName}),H&&e.jsx("span",{className:"chat-tool-call-preview",title:H,children:H}),e.jsx("span",{className:"chat-tool-call-status-text",children:le})]}),e.jsxs("div",{className:"chat-tool-call-content",children:[v&&e.jsxs("div",{className:"chat-tool-call-row",children:[e.jsx("span",{className:"chat-tool-call-label",children:s("chat.toolCallArgsPrefix","args")}),e.jsx("span",{className:"chat-tool-call-value",children:v})]}),W&&e.jsxs("div",{className:`chat-tool-call-row${L?" chat-tool-call-row--error":""}`,children:[e.jsx("span",{className:"chat-tool-call-label",children:s("chat.toolCallResultPrefix","result")}),e.jsx("span",{className:"chat-tool-call-value",children:W})]})]})]},`${k.toolName}-${S}`)},o="chat-tool-calls";if(n.length===1)return e.jsxs("div",{className:o,"data-testid":"chat-tool-calls",children:[e.jsxs("div",{className:"chat-tool-calls-header",children:[e.jsx(ia,{size:12,"aria-hidden":"true"}),e.jsx("span",{children:s("chat.toolCallsHeader","Tool calls")})]}),l(n[0],0)]});const u=n.filter(k=>k.status==="running").length,b=n.filter(k=>k.status==="completed"&&k.isError).length,d=u>0,c=Array.from(new Set(n.map(k=>k.toolName))),m=c.slice(0,5),$=Math.max(0,c.length-m.length),x=$>0?`${m.join(", ")}, +${$} more`:m.join(", "),y=d?`(${u} ${s("chat.toolCallStatusRunning","running")})`:b>0?`(${b} ${b===1?s("chat.toolCallStatusError","error"):s("chat.toolCallStatusErrors","errors")})`:null;return e.jsx("div",{className:o,"data-testid":"chat-tool-calls",children:e.jsxs("details",{className:"chat-tool-calls-group","data-testid":"chat-tool-calls-group",open:d,children:[e.jsxs("summary",{className:"chat-tool-calls-group-summary",children:[e.jsx(ia,{size:12,"aria-hidden":"true"}),e.jsx("span",{className:"chat-tool-calls-count",children:s("chat.toolCallsCount","{{count}} tool calls",{count:n.length})}),e.jsx("span",{className:"chat-tool-calls-names",title:x,children:x}),y&&e.jsx("span",{className:"chat-tool-calls-group-status",children:y})]}),n.map((k,S)=>l(k,S))]})})}const za={p:({children:n,...s})=>e.jsx("p",{...s,children:sa(n)}),li:({children:n,...s})=>e.jsx("li",{...s,children:sa(n)}),pre:({children:n,...s})=>e.jsx("pre",{...s,className:"chat-markdown-pre",children:n}),code:({children:n,...s})=>{const r=typeof n=="string"?n:ur.Children.toArray(n).join(""),l=Cn(r);return l.length===1&&typeof l[0]=="string"?e.jsx("code",{...s,children:n}):e.jsx("code",{...s,children:l})},table:({children:n,...s})=>e.jsx("table",{...s,className:"chat-markdown-table",children:n})},wt="__fn_agent__",Ki=280,fn=180,gn=500,Sa="fusion:chat-sidebar-width",ss="fusion:chat-scope",Gi="fusion:chat-draft:";function ka(n,s){return s?`${Gi}${n}:${s}`:null}function Na(n){if(!n)return"";try{return localStorage.getItem(n)??""}catch{return""}}const Vi=["image/png","image/jpeg","image/gif","image/webp","text/plain","application/json","text/yaml","text/markdown","text/csv","application/xml","text/x-log"];function Ma(n){const s=/(^|[\s])\/([^\s]*)$/.exec(n);if(!s)return null;const r=s[1]??"",l=s[2]??"",o=s.index+r.length;return{filter:l,start:o,end:n.length}}function Qi(n,s){const r=n.slice(0,s),l=/(^|[\s\n])@([\w-]*)$/.exec(r);if(!l)return null;const o=l[2]??"",u=r.length-o.length-1;return{filter:o,start:u,end:s}}function Wi(n){const s=n?.runtimeConfig;if(!s||typeof s!="object")return null;const r=Reflect.get(s,"modelProvider"),l=Reflect.get(s,"modelId");return typeof r!="string"||r.trim().length===0||typeof l!="string"||l.trim().length===0?null:{provider:r,modelId:l}}function Ra(n,s,r){if(n?.modelProvider&&n?.modelId)return{provider:n.modelProvider,modelId:n.modelId};const l=Wi(s??void 0);return l||(r.provider&&r.modelId?{provider:r.provider,modelId:r.modelId}:null)}function Xi({projectId:n,defaultModel:s,onClose:r,onCreate:l}){const{t:o}=Le("app"),[u,b]=a.useState("agent"),{agents:d,loading:c}=us(n),[m,$]=a.useState(""),{models:x,favoriteProviders:y,favoriteModels:k,loading:S,refresh:T}=Ea(),N=s.provider&&s.modelId?`${s.provider}/${s.modelId}`:"",[L,v]=a.useState(N),[W,H]=a.useState(y),[le,j]=a.useState(k);a.useEffect(()=>{H(y)},[y]),a.useEffect(()=>{j(k)},[k]),a.useEffect(()=>{N&&v(C=>C||N)},[N]);const Q=a.useCallback(async C=>{const I=W,Y=I.includes(C)?I.filter(R=>R!==C):[C,...I];H(Y);try{await aa({favoriteProviders:Y,favoriteModels:le}),await T()}catch{H(I)}},[W,le,T]),P=a.useCallback(async C=>{const I=le,Y=I.includes(C)?I.filter(R=>R!==C):[C,...I];j(Y);try{await aa({favoriteProviders:W,favoriteModels:Y}),await T()}catch{j(I)}},[le,W,T]),z=L||N,F=C=>{if(C.preventDefault(),u==="agent"){if(!m)return;l({agentId:m});return}if(!z)return;const I=z.indexOf("/");if(I<=0)return;const E=z.slice(0,I),Y=z.slice(I+1);l({agentId:wt,modelProvider:E,modelId:Y})},U=u==="agent"?!m:!z;return e.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:r,role:"dialog","aria-modal":"true",children:e.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:C=>C.stopPropagation(),children:[e.jsx("h3",{children:o("chat.newChatTitle","New Chat")}),e.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[e.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${u==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{b("agent")},children:o("chat.newChatModeAgent","Agent")}),e.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${u==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{b("model"),$(""),v(C=>C||N)},children:o("chat.newChatModeModel","Model")})]}),e.jsxs("form",{onSubmit:F,children:[u==="agent"&&e.jsxs("label",{className:"chat-new-dialog-model-label",children:[o("chat.newChatModeAgent","Agent"),c?e.jsx("div",{className:"chat-new-dialog-loading",children:o("chat.loadingAgents","Loading agents...")}):d.length===0?e.jsx("div",{className:"chat-new-dialog-empty",children:o("chat.noAgentsAvailable","No agents available")}):e.jsx("div",{className:"chat-new-dialog-agent-list",children:d.map(C=>e.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${m===C.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>$(C.id),"data-testid":`agent-option-${C.id}`,children:[e.jsx(Ot,{size:16}),e.jsx("span",{className:"chat-new-dialog-agent-name",children:C.name}),e.jsx("span",{className:"chat-new-dialog-agent-role",children:C.role})]},C.id))})]}),u==="model"&&e.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:S?e.jsx("div",{className:"chat-new-dialog-loading",children:o("chat.loadingModels","Loading models...")}):e.jsx(Wr,{models:x,value:L,onChange:v,label:o("chat.newChatModeModel","Model"),placeholder:o("chat.selectModel","Select a model"),favoriteProviders:W,onToggleFavorite:Q,favoriteModels:le,onToggleModelFavorite:P})}),e.jsxs("div",{className:"chat-new-dialog-actions",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:r,children:o("chat.cancel","Cancel")}),e.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:U,children:o("chat.create","Create")})]})]})]})})}function Aa(n,s){return n.slice(s+1).find(r=>r.role==="user")?.content}const as=a.memo(function({message:s,forcePlain:r,agentName:l,hideAssistantIdentity:o,showAssistantModelTag:u,activeModelTag:b,activeModelProvider:d,activeSessionId:c,mentionAgentsByName:m,roomContext:$,copyAction:x,onScrollToTop:y,isAwaitingQuestionAnswer:k,submittedQuestionAnswer:S,onQuestionSubmit:T}){const{t:N}=Le("app"),L=s.role==="assistant",v=L?s.failureInfo:void 0,W=L&&(!o||!!v),H=a.useMemo(()=>{if(L)return null;const Q=s.content,P=/@([\w-]+)/g,z=[];let F=0,U=P.exec(Q);for(;U;){const[C,I=""]=U,E=U.index;E>F&&z.push(Q.slice(F,E));const Y=I.replace(/_/g," ").toLowerCase(),R=m.get(Y);if(R){const _=!!($&&!$.memberIds.has(R.id)),D=_?N("chat.mentionNonMember","Not a member of {{roomName}}",{roomName:$?.roomName}):void 0;z.push(e.jsxs("span",{className:`chat-mention-chip${_?" chat-mention-chip--non-member":""}`,title:D,"aria-label":D,children:["@",R.name.replace(/\s+/g,"_")]},`${R.id}-${E}`))}else z.push(C);F=E+C.length,U=P.exec(Q)}return F<Q.length&&z.push(Q.slice(F)),z.length===0?Q:z},[L,s.content,m,$]),le=a.useMemo(()=>{const Q=s.attachments;if(!Q||Q.length===0)return null;const P=s.roomId?`/api/chat/rooms/${encodeURIComponent(s.roomId)}/attachments/`:c?`/api/chat/sessions/${encodeURIComponent(c)}/attachments/`:null;return P?e.jsx("div",{className:"chat-message-attachments",children:Q.map(z=>{const F=z.mimeType.startsWith("image/"),U=z.id||z.filename,C=`${P}${encodeURIComponent(z.filename)}`;return F?e.jsx("a",{className:"chat-message-attachment-link","data-testid":"chat-message-attachment",href:C,target:"_blank",rel:"noopener noreferrer",children:e.jsx("img",{className:"chat-message-attachment",src:C,alt:z.originalName})},U):e.jsxs("a",{className:"chat-message-attachment-file","data-testid":"chat-message-attachment",href:C,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ta,{size:14}),e.jsx("span",{children:z.originalName})]},U)})}):null},[s.attachments,s.roomId,c]),j=a.useMemo(()=>L?v?e.jsxs("div",{className:"chat-message-content chat-message-content--failure",children:[e.jsxs("div",{className:"chat-message-failure-summary-row",children:[e.jsx("span",{className:"status-dot status-dot--error","aria-hidden":"true"}),e.jsx("span",{className:"chat-message-failure-label",children:N("chat.responseFailed","Response failed")})]}),e.jsx("div",{className:"chat-message-failure-summary",children:v.summary}),(v.errorClass||v.code)&&e.jsxs("div",{className:"chat-message-failure-badges",children:[v.errorClass&&e.jsx("span",{className:"chat-message-failure-badge",children:v.errorClass}),v.code&&e.jsx("span",{className:"chat-message-failure-badge",children:v.code})]}),(v.detail||v.reference)&&e.jsxs("details",{className:"chat-message-failure-details",children:[e.jsxs("summary",{children:[e.jsx(Vr,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:N("chat.failureDetails","Failure details")})]}),v.detail&&e.jsx("pre",{className:"chat-message-failure-detail",children:Cn(v.detail)}),qi(v.reference,N)]})]}):r?e.jsx("div",{className:"chat-message-content chat-message-content--plain",children:s.content}):e.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:e.jsx(_a,{remarkPlugins:[$a],components:za,children:s.content})}):null,[v,r,L,s.content]);return e.jsxs("div",{className:`chat-message chat-message--${s.role}${v?" chat-message--failure":""}`,"data-testid":`chat-message-${s.id}`,"data-message-id":s.id,children:[W&&e.jsxs("div",{className:"chat-message-avatar",children:[d?e.jsx(It,{provider:d,size:"sm"}):e.jsx(Ot,{size:14}),e.jsx("span",{children:l}),u&&b&&e.jsx("span",{className:"chat-model-tag",children:b})]}),L?j:e.jsx("div",{className:"chat-message-content",children:H}),L&&!v&&(x||y)&&e.jsxs("div",{className:"chat-message-actions",children:[x,y&&e.jsx("button",{type:"button",className:"btn-icon chat-message-scroll-to-top-action","aria-label":N("chat.scrollMessageToTop","Scroll message to top"),"data-testid":`chat-message-scroll-to-top-${s.id}`,onClick:()=>y(s.id),children:e.jsx(Yr,{size:14})})]}),Oa(s.toolCalls,N,{isAwaitingAnswer:k,submittedAnswer:S,onQuestionSubmit:T}),s.thinkingOutput&&e.jsxs("details",{className:"chat-message-thinking",children:[e.jsx("summary",{children:N("chat.thinking","Thinking")}),e.jsx("pre",{className:"chat-message-thinking-content",children:Cn(s.thinkingOutput)})]}),le,e.jsx("div",{className:"chat-message-time",children:Ia(s.createdAt,N)})]})});function ro({projectId:n,addToast:s,floating:r=!1,compactLayout:l=!1,onPopOut:o,onMaximize:u,onMinimize:b,onClose:d}){const{t:c}=Le("app");a.useEffect(()=>(zt({view:"ChatView",trigger:ns?"route-active":"remount",projectId:n,replayAttempted:!1}),ns=!1,()=>{ns=!0,zt({view:"ChatView",trigger:"route-inactive",projectId:n,replayAttempted:!1})}),[n]);const{activeSession:m,sessionsLoading:$,messages:x,messagesLoading:y,isStreaming:k,streamingText:S,streamingThinking:T,streamingToolCalls:N,selectSession:L,createSession:v,archiveSession:W,renameSession:H,deleteSession:le,sendMessage:j,stopStreaming:Q,pendingMessages:P,clearPendingMessage:z,loadMoreMessages:F,hasMoreMessages:U,searchQuery:C,setSearchQuery:I,filteredSessions:E,agentsMap:Y}=ri(n,s),[R,_]=a.useState(!1),D=!0,[g,O]=a.useState(()=>{try{if(localStorage.getItem(ss)==="rooms"&&D)return"rooms"}catch{}return"direct"}),f=ci(n,s),{isUnread:ie,markRead:q}=li(n),[K,me]=a.useState(()=>{const t=ka(g,g==="rooms"?f.activeRoom?.id:m?.id);return Na(t)}),[ge,oe]=a.useState(null),[ve,ye]=a.useState(null),[Ge,Ve]=a.useState(""),[xe,$e]=a.useState(null),[Bt,he]=a.useState(null),[et,de]=a.useState(!0),[Ee,kt]=a.useState(Ki),[Sn,at]=a.useState(!1),{agentsMap:Ht}=us(n),_e=a.useMemo(()=>Y.size>0?Y:Ht,[Ht,Y]),{models:Ut,defaultProvider:Nt,defaultModelId:Mt}=Ea(),rt=a.useMemo(()=>({provider:Nt,modelId:Mt}),[Mt,Nt]),{skills:it,loading:kn}=Li(n),[p,w]=a.useState(!1),[A,G]=a.useState(""),[ae,V]=a.useState(0),[J,X]=a.useState(""),[Z,re]=a.useState(!1),[ne,te]=a.useState(0),[fe,pe]=a.useState(-1),[ke,Ba]=a.useState(!1),[Ae,Nn]=a.useState([]),[fs,ot]=a.useState(!1),[gs,qt]=a.useState(!1),[ct,ps]=a.useState({}),[Kt,Qe]=a.useState(!1),[Gt,Rt]=a.useState(!1),{pushNav:bs}=Dr(),[,Vt]=a.useState(!1),[Ha,Ua]=a.useState({top:0,left:0}),ue=$i({projectId:n}),Mn=a.useCallback(t=>{if(!t||!ue.mentionActive)return;const i=t.getBoundingClientRect();Ua({top:i.top-260,left:i.left+8})},[ue.mentionActive]),vs=a.useRef(null),ys=a.useRef(null),xs=a.useRef(null),ws=a.useRef(null),Ne=a.useRef(!1),Qt=a.useRef(null),Cs=a.useRef(null),We=a.useRef(null),Wt=a.useRef(0),Rn=a.useRef(null),At=a.useRef(null),Pe=a.useRef(null),Me=a.useRef(null),An=a.useRef(null),Xt=a.useRef(!1),Ie=a.useRef(null),Oe=a.useRef(null),Se=a.useRef(null),Yt=a.useRef(null),Ss=a.useRef([]),lt=a.useRef(0),jt=a.useRef(new Map),jn=a.useRef(!1),Jt=a.useRef(!1),ze=a.useRef(null),Tn=a.useRef(!1),Zt=Fr(),tt=Zt==="mobile",En=Zt==="tablet",ks=a.useRef(null),[qa,Ns]=a.useState(!1);a.useLayoutEffect(()=>{if(!r){Ns(!1);return}const t=ks.current;if(!t||typeof ResizeObserver>"u")return;const i=()=>{Ns(t.getBoundingClientRect().width<=768)};i();const h=new ResizeObserver(i);return h.observe(t),()=>h.disconnect()},[r]);const se=tt||qa||l;a.useEffect(()=>{m?.id&&q("direct",m.id,m.lastMessageAt??m.updatedAt)},[m?.id,m?.lastMessageAt,m?.updatedAt,q]),a.useEffect(()=>{f.activeRoom?.id&&q("room",f.activeRoom.id,f.activeRoom.updatedAt)},[f.activeRoom?.id,f.activeRoom?.updatedAt,q]),a.useEffect(()=>{if(!m?.id||x.length===0)return;const t=x[x.length-1];q("direct",m.id,t?.createdAt??m.lastMessageAt??m.updatedAt)},[m?.id,m?.lastMessageAt,m?.updatedAt,q,x]),a.useEffect(()=>{if(!f.activeRoom?.id||f.messages.length===0)return;const t=f.messages[f.messages.length-1];q("room",f.activeRoom.id,t?.createdAt??f.activeRoom.updatedAt)},[q,f.activeRoom?.id,f.activeRoom?.updatedAt,f.messages]),a.useEffect(()=>{try{const t=localStorage.getItem(Sa);if(!t)return;const i=Number.parseInt(t,10);if(Number.isNaN(i))return;const h=Math.max(fn,Math.min(gn,i));kt(h)}catch{}},[]),a.useEffect(()=>{try{const t=localStorage.getItem(ss);if(t==="direct"){O("direct");return}t==="rooms"&&D&&O("rooms")}catch{}},[D]),a.useEffect(()=>{try{localStorage.setItem(ss,g)}catch{}},[D,g]);const Re=ka(g,g==="rooms"?f.activeRoom?.id:m?.id),_n=a.useRef(Re);a.useEffect(()=>{Re!==_n.current&&(_n.current=Re,me(Na(Re)))},[Re]),a.useEffect(()=>{if(!(!Re||_n.current!==Re))try{if(K){localStorage.setItem(Re,K);return}localStorage.removeItem(Re)}catch{}},[Re,K]);const be=g==="rooms"&&!!f.activeRoom,{keyboardOverlap:Ms,keyboardOpen:en}=Lr({enabled:(se||En)&&(!!m||be),allowNonMobileViewport:En}),Tt=En&&en,je=a.useMemo(()=>{const t=A.trim().toLowerCase();return(t?it.filter(h=>h.name.toLowerCase().includes(t)):it).slice(0,10)},[it,A]),ut=a.useMemo(()=>Array.from(_e.values()),[_e]),Be=a.useMemo(()=>g!=="rooms"||!f.activeRoom?null:{roomId:f.activeRoom.id,roomName:f.activeRoom.name,memberIds:new Set(f.activeRoomMembers.map(t=>t.agentId))},[D,g,f.activeRoom,f.activeRoomMembers]),nt=a.useMemo(()=>{const t=ut.filter(M=>Pa(M.name,J));if(!Be)return t;const i=t.filter(M=>Be.memberIds.has(M.id));if(J.trim().length===0)return i;const h=t.filter(M=>!Be.memberIds.has(M.id));return[...i,...h]},[ut,J,Be]),$n=a.useMemo(()=>{const t=new Map;for(const i of ut)t.set(i.name.toLowerCase(),i);return t},[ut]),Ka=a.useMemo(()=>je.map(t=>t.id).join("\0"),[je]);a.useEffect(()=>{V(0)},[Ka]),a.useEffect(()=>{te(0)},[J,Z]),a.useEffect(()=>()=>{Pe.current!==null&&window.clearTimeout(Pe.current)},[]),a.useEffect(()=>{const t=ys.current;if(!t||!U||y)return;const i=new IntersectionObserver(h=>{h[0].isIntersecting&&F()},{threshold:.1});return i.observe(t),()=>i.disconnect()},[U,y,F]);const dt=a.useCallback(()=>be?f.activeRoom?.id??null:m?.id??null,[be,f.activeRoom?.id,m?.id]),Rs=a.useCallback((t,i)=>typeof CSS<"u"&&typeof CSS.escape=="function"?t.querySelector(`.chat-message[data-message-id="${CSS.escape(i)}"]`):t.querySelector(`.chat-message[data-message-id="${i.replace(/"/g,'\\"')}"]`),[]),tn=a.useCallback(()=>{const t=Me.current,i=dt();if(!t||!i)return;const h=t.scrollTop,M=t.querySelectorAll(".chat-message[data-message-id]"),B=Array.from(M).find(we=>we.offsetTop+we.offsetHeight>=h)??M[0]??null,ee=B?.getAttribute("data-message-id")??null,Ce=B?B.offsetTop-h:0;At.current={threadId:i,scrollTop:h,scrollHeight:t.scrollHeight,clientHeight:t.clientHeight,anchorMessageId:ee,anchorOffset:Ce,wasPinnedBefore:!Ne.current,capturedAtMs:typeof performance<"u"?performance.now():Date.now()}},[dt]),As=a.useCallback(()=>{const t=Me.current;if(!t)return;const h=t.scrollTop+t.clientHeight>=t.scrollHeight-50;qt(!h),Ne.current=!h,tn()},[tn]),He=a.useCallback((t,i)=>{if(!t.isConnected||!i?.force&&Ne.current)return;let h=0,M=0,B=-1;const ee=6,Ce=()=>{if(t.isConnected&&!(!i?.force&&Ne.current)){if(t.scrollTop=t.scrollHeight,t.scrollHeight===B?M+=1:(M=0,B=t.scrollHeight),h+=1,h>=ee||M>=2){qt(!1),Ne.current=!1;return}window.requestAnimationFrame(Ce)}};Ce()},[]),Et=be?f.messages:x;a.useLayoutEffect(()=>{const t=Me.current,i=dt(),h=At.current;if(!t||!i||!h||h.threadId!==i||h.wasPinnedBefore)return;const M=(typeof performance<"u"?performance.now():Date.now())-h.capturedAtMs,B=t.scrollHeight>t.clientHeight,ee=M>3e3,Ce=h.scrollTop<=0&&h.anchorOffset<=0&&B;if(!Ne.current||ee||Ce){At.current=null;return}let we=h.scrollTop;if(h.anchorMessageId){const qe=Rs(t,h.anchorMessageId);qe?we=qe.offsetTop-h.anchorOffset:we=h.scrollTop+(t.scrollHeight-h.scrollHeight)}else we=h.scrollTop+(t.scrollHeight-h.scrollHeight);t.scrollTop=Math.max(0,we),Ne.current=!0,qt(!0),At.current=null},[Et,dt,Rs]);const Dn=a.useCallback(t=>{},[Et.length,be]),De=a.useCallback(t=>{Dn(t);const i=Me.current;i&&(At.current=null,Ne.current=!1,He(i))},[He,Dn]);a.useLayoutEffect(()=>{We.current!==null&&(window.clearTimeout(We.current),We.current=null);const t=be?f.activeRoom?.id??null:m?.id??null;if(!t){Qt.current=null;return}const i={threadId:t,loaded:be?!f.messagesLoading:!y,hasMessages:be?f.messages.length>0:x.length>0},h=Qt.current,M=h?.threadId!==t,B=h?.threadId===t&&!h.loaded&&i.loaded,ee=h?.threadId===t&&!h.hasMessages&&i.hasMessages;if(!(h===null||M||B||ee))return;const we=Me.current;if(we)return Dn(M?"thread-change":B?"finished-loading":ee?"first-messages":"mount"),He(we,{force:!0}),be||(We.current=window.setTimeout(()=>{if(We.current=null,Ne.current)return;const qe=Me.current;qe&&He(qe)},250)),Qt.current=i,()=>{We.current!==null&&(window.clearTimeout(We.current),We.current=null)}},[be,f.activeRoom?.id,f.messages.length,f.messagesLoading,m?.id,x.length,y,He]),a.useEffect(()=>{!k||Ne.current||De("streaming")},[k,S,T,De]),a.useEffect(()=>{const t=dt();if(!t){Wt.current=0,Rn.current=null;return}if(Rn.current!==t){Rn.current=t,Wt.current=Et.length;return}const i=Wt.current,h=Et.length,M=h>i,B=!Ne.current;Wt.current=h,M&&B&&De("new-message")},[Et,dt,De]),a.useEffect(()=>{Ms<=0||!Me.current||De("keyboard")},[Ms,De]),Pr(tt&&en),a.useLayoutEffect(()=>{if(!tt||!m&&!be||typeof window>"u")return;const t=An.current,i=window.visualViewport;if(!t||!i)return;const h=B=>{if(!(B instanceof HTMLElement))return!1;if(B.tagName==="TEXTAREA")return!0;if(B.tagName!=="INPUT")return!1;const ee=B.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(ee)},M=()=>{if(Xt.current){t.classList.remove("chat-thread--keyboard-active"),t.style.transform="",t.style.willChange="";return}const B=Math.max(0,window.innerHeight-i.offsetTop-i.height),ee=i.offsetTop||0;t.style.setProperty("--vv-height",`${i.height}px`),t.style.setProperty("--vv-offset-top",`${ee}px`),t.style.setProperty("--keyboard-overlap",`${B}px`);const Ce=(B>0||ee>0)&&h(document.activeElement);t.classList.toggle("chat-thread--keyboard-active",Ce),Ce&&ee>0?(t.style.transform=`translateY(${ee}px)`,t.style.willChange="transform"):(t.style.transform="",t.style.willChange="")};return M(),i.addEventListener("resize",M),i.addEventListener("scroll",M),document.addEventListener("focusin",M),document.addEventListener("focusout",M),window.addEventListener("pageshow",M),document.addEventListener("visibilitychange",M),()=>{i.removeEventListener("resize",M),i.removeEventListener("scroll",M),document.removeEventListener("focusin",M),document.removeEventListener("focusout",M),window.removeEventListener("pageshow",M),document.removeEventListener("visibilitychange",M),t.classList.remove("chat-thread--keyboard-active"),t.style.transform="",t.style.willChange=""}},[m,tt,be]),a.useEffect(()=>{const t=()=>oe(null);if(ge)return document.addEventListener("click",t),()=>document.removeEventListener("click",t)},[ge]),a.useEffect(()=>{if(!tt||!en)return;const t=i=>{i.target?.closest(".chat-messages")||i.preventDefault()};return document.addEventListener("touchmove",t,{passive:!1}),()=>{document.removeEventListener("touchmove",t)}},[tt,en]),a.useEffect(()=>{const t=Cs.current;if(Cs.current=g,g==="rooms"&&!f.activeRoom){Qt.current=null;return}if(!(g==="direct"&&(t===null||t==="rooms"))&&!(g==="rooms"&&(t===null||t==="direct")))return;const M=Me.current;M&&(He(M,{force:!0}),Ne.current=!1,qt(!1))},[g,f.activeRoom,He]),a.useEffect(()=>{if(!m&&!be||be&&!se)return;const t=()=>{const h=!Ne.current;tn(),h&&se&&Me.current&&De("visibility-restore")},i=()=>{document.visibilityState==="visible"&&t()};return document.addEventListener("visibilitychange",i),window.addEventListener("pageshow",t),()=>{document.removeEventListener("visibilitychange",i),window.removeEventListener("pageshow",t)}},[se,tt,m,be,tn,De]),a.useEffect(()=>{if(be||typeof ResizeObserver>"u")return;const t=Me.current;if(!t)return;const i=new ResizeObserver(()=>{Ne.current||He(t)});return i.observe(t),()=>{i.disconnect()}},[be,He,m?.id,g]),a.useEffect(()=>{Ss.current=Ae},[Ae]),a.useEffect(()=>()=>{for(const t of Ss.current)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);for(const t of jt.current.values())window.clearTimeout(t);jt.current.clear()},[]);const mt=a.useCallback(t=>{if(!t||t.length===0)return;const i=[];for(const h of Array.from(t)){if(!Vi.includes(h.type))continue;const M=h.type.startsWith("image/");i.push({file:h,previewUrl:M?URL.createObjectURL(h):""})}i.length>0&&Nn(h=>[...h,...i])},[]),js=a.useCallback(t=>{Nn(i=>{const h=i[t];return h?.previewUrl&&URL.revokeObjectURL(h.previewUrl),i.filter((M,B)=>B!==t)})},[]),Ts=a.useCallback(t=>{const i=t.clipboardData?.files;if(!i||i.length===0)return;const h=Array.from(i).filter(M=>M.type.startsWith("image/"));h.length!==0&&mt(h)},[mt]),Ga=a.useCallback(async t=>{try{await v(t),_(!1),se&&de(!1)}catch{s(c("chat.failedToCreateSession","Failed to create chat session"),"error")}},[v,s,se]),Te=a.useCallback(t=>{const i=t??Se.current;if(!i)return;const h=Zt==="tablet"?Ii:hs;i.style.height="auto",i.style.height=`${zi(i.scrollHeight,h)}px`,i.style.overflowY=Oi(i.scrollHeight,h)},[Zt]),Es=a.useCallback(t=>{Se.current=t,t&&Te(t)},[Te]);a.useLayoutEffect(()=>{Te()},[g,K,m?.id,f.activeRoom?.id,Te]);const ht=a.useCallback(()=>{if(me(""),Re)try{localStorage.removeItem(Re)}catch{}w(!1),G(""),re(!1),X(""),pe(-1),Nn(t=>{for(const i of t)i.previewUrl&&URL.revokeObjectURL(i.previewUrl);return[]})},[Re]),ft=a.useCallback(()=>{Jt.current=!0,ze.current!=null&&clearTimeout(ze.current),ze.current=window.setTimeout(()=>{Jt.current=!1,ze.current=null},700)},[]),gt=a.useCallback(()=>Tn.current?!1:(Tn.current=!0,window.setTimeout(()=>{Tn.current=!1},0),!0),[]),Fn=a.useCallback(()=>Jt.current?(Jt.current=!1,ze.current!=null&&(clearTimeout(ze.current),ze.current=null),!0):!1,[]);a.useEffect(()=>()=>{ze.current!=null&&clearTimeout(ze.current)},[]);const _t=a.useCallback(()=>{const t=K.trim(),i=Ae.map(h=>h.file);if(!(!t&&i.length===0||!m)){if(t==="/clear"||t==="/new"){ht(),z(),Q(),v({agentId:m.agentId,modelProvider:m.modelProvider??void 0,modelId:m.modelId??void 0}).catch(()=>{s(c("chat.failedToClearConversation","Failed to clear conversation"),"error")});return}ht(),j(t,i)}},[K,Ae,m,ht,Q,z,v,s,j]),$t=a.useCallback(async()=>{const t=K.trim(),i=Ae.map(h=>h.file);if(!(!t&&i.length===0)){if(g==="rooms"){if(!f.activeRoom)return;if(t==="/clear"||t==="/new"){ht();try{await f.clearRoom(f.activeRoom.id)}catch{s(c("chat.failedToClearRoomConversation","Failed to clear room conversation"),"error")}return}if(jn.current)return;jn.current=!0;const h=K;ht();try{await f.sendRoomMessage(t,{files:i})}catch(M){if(M instanceof Fa){const ee=M.message.trim()?M.message:c("chat.messageSentButReplyFailed","Message sent, but assistant reply failed");s(c("chat.messageSentButReplyFailedDetail","Message sent, but assistant reply failed: {{detail}}",{detail:ee}),"error");return}me(h);const B=M instanceof Error&&M.message.trim()?M.message:c("chat.failedToSendRoomMessage","Failed to send room message");s(B,"error")}finally{jn.current=!1}return}_t()}},[K,Ae,D,g,f,f.clearRoom,ht,s,_t]),nn=a.useCallback(async t=>{if(g==="rooms"){if(!f.activeRoom)return;try{await f.sendRoomMessage(t)}catch(i){const h=i instanceof Error&&i.message.trim()?i.message:c("chat.failedToSendRoomMessage","Failed to send room message");s(h,"error")}return}m&&j(t)},[m,s,D,g,f,j,c]),Ln=a.useCallback(t=>{me(i=>{const h=Ma(i);if(!h)return i;const M=`/skill:${t.name} `,B=i.slice(0,h.start)+M+i.slice(h.end);return window.requestAnimationFrame(()=>{Se.current&&(Te(Se.current),Se.current.focus())}),B}),w(!1),G(""),V(0)},[Te]),sn=a.useCallback(t=>{const i=Se.current;if(!i||fe<0)return;const h=i.selectionStart??lt.current,M=i.selectionEnd??h,B=Math.max(h,M),ee=Math.min(fe,B),we=`${`@${t.name.replace(/\s+/g,"_")}`} `,qe=K.slice(0,ee)+we+K.slice(B),pt=ee+we.length;me(qe),re(!1),X(""),te(0),pe(-1),window.requestAnimationFrame(()=>{Se.current&&(Te(Se.current),Se.current.focus(),Se.current.setSelectionRange(pt,pt))})},[fe,K,Te]),Dt=a.useCallback((t,i)=>{const M=Se.current?.selectionStart??lt.current,B=K.lastIndexOf("#",M),ee=B>=0?B+i.length:t.length;me(t),ue.dismissMention(),Vt(!1),window.requestAnimationFrame(()=>{Se.current&&(Te(Se.current),Se.current.focus(),Se.current.setSelectionRange(ee,ee))})},[ue,K,Te]),_s=a.useCallback(t=>{if(lt.current=t.currentTarget.selectionStart??lt.current,ue.mentionActive&&ue.combinedItems.length>0){if(ue.handleKeyDown(t,K),t.key==="Enter"||t.key==="Tab"){const i=ue.combinedItems[ue.selectedIndex];i?.kind==="task"?Dt(ue.selectTask(i.task,K),`#${i.task.id}`):i?.kind==="file"&&Dt(ue.selectFile(i.file,K),`#${i.file.path}`)}return}if(Z&&t.key==="ArrowDown"){t.preventDefault(),nt.length>0&&te(i=>(i+1)%nt.length);return}if(Z&&t.key==="ArrowUp"){t.preventDefault(),nt.length>0&&te(i=>i===0?nt.length-1:i-1);return}if(Z&&t.key==="Enter"){t.preventDefault();const i=nt[ne]??nt[0];i&&sn(i);return}if(Z&&t.key==="Escape"){t.preventDefault(),re(!1),X(""),pe(-1);return}if(p&&t.key==="ArrowDown"){t.preventDefault(),je.length>0&&V(i=>(i+1)%je.length);return}if(p&&t.key==="ArrowUp"){t.preventDefault(),je.length>0&&V(i=>i===0?je.length-1:i-1);return}if(p&&(t.key==="Enter"||t.key==="Tab")&&je.length>0){t.preventDefault();const i=je[ae]??je[0];i&&Ln(i);return}if(p&&t.key==="Escape"){t.preventDefault(),w(!1);return}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),$t())},[Z,nt,ne,sn,p,je,ae,Ln,$t,ue,Dt,K]),an=a.useCallback((t,i)=>{const h=Qi(t,i);if(h){re(!0),X(h.filter),pe(h.start);return}re(!1),X(""),pe(-1)},[]),$s=a.useCallback(t=>{const i=t.target,h=i.value,M=i.selectionStart??h.length;Te(i),lt.current=M,me(h);const B=Ma(h);B?(w(!0),G(B.filter)):(w(!1),G("")),an(h,M),ue.detectMention(h,M),Vt(ue.mentionActive),ue.mentionActive&&Mn(i)},[an,Te]),rn=a.useCallback(t=>{const i=t.currentTarget,h=i.selectionStart??i.value.length;lt.current=h,an(i.value,h),ue.detectMention(i.value,h),Vt(ue.mentionActive),ue.mentionActive&&Mn(i)},[an,ue,Mn]),Ds=a.useCallback(t=>{t.key!=="Escape"&&rn(t)},[rn]),Fs=a.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(Xt.current=!0,Ie.current!==null&&window.clearTimeout(Ie.current),Ie.current=window.setTimeout(()=>{Xt.current=!1,Ie.current=null},450),(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0),Oe.current!==null&&window.clearTimeout(Oe.current),Oe.current=window.setTimeout(()=>{Oe.current=null,document.activeElement?.tagName!=="TEXTAREA"&&(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},350)),Pe.current!==null&&window.clearTimeout(Pe.current),Pe.current=window.setTimeout(()=>{w(!1),re(!1),X(""),pe(-1),Vt(!1),ue.dismissMention(),Pe.current=null},120)},[ue]),Ls=a.useCallback(()=>{Xt.current=!1,Ie.current!==null&&(window.clearTimeout(Ie.current),Ie.current=null),Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null),Oe.current!==null&&(window.clearTimeout(Oe.current),Oe.current=null)},[]);a.useEffect(()=>()=>{Ie.current!==null&&window.clearTimeout(Ie.current),Oe.current!==null&&window.clearTimeout(Oe.current)},[]);const Va=a.useCallback(async t=>{oe(null);try{await W(t),s(c("chat.conversationArchived","Conversation archived"),"success")}catch{s(c("chat.failedToArchiveConversation","Failed to archive conversation"),"error")}},[W,s]),Ps=a.useCallback(t=>{const i=E.find(h=>h.id===t)??(m?.id===t?m:null);oe(null),Qe(!1),Ve(i?.title??""),ye({sessionId:t,title:i?.title??""})},[m,E]),Is=a.useCallback(async()=>{if(ve)try{await H(ve.sessionId,Ge),ye(null),Ve(""),s(c("chat.conversationRenamed","Conversation renamed"),"success")}catch{}},[s,ve,H,Ge,c]),Qa=a.useCallback(async t=>{$e(null),oe(null);try{await le(t),s(c("chat.conversationDeleted","Conversation deleted"),"success")}catch{s(c("chat.failedToDeleteConversation","Failed to delete conversation"),"error")}},[le,s]),Ft=a.useCallback(t=>{try{localStorage.setItem(Sa,String(t))}catch{}},[]),Wa=a.useCallback(t=>{if(se||Tt)return;t.preventDefault(),t.stopPropagation();const i=t.currentTarget;typeof i.setPointerCapture=="function"&&i.setPointerCapture(t.pointerId);const h=t.clientX,M=Ee;let B=M;document.body.style.userSelect="none";const ee=we=>{const qe=we.clientX-h,pt=Math.max(fn,Math.min(gn,M+qe));B=pt,kt(pt),Ft(pt)},Ce=we=>{typeof i.releasePointerCapture=="function"&&i.releasePointerCapture(we.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",ee),document.removeEventListener("pointerup",Ce),Ft(B)};document.addEventListener("pointermove",ee),document.addEventListener("pointerup",Ce)},[se,Ft,Ee,Tt]),Xa=a.useCallback(t=>{if(se||Tt||t.key!=="ArrowLeft"&&t.key!=="ArrowRight")return;t.preventDefault();const i=t.shiftKey?50:10,h=t.key==="ArrowLeft"?-i:i,M=Math.max(fn,Math.min(gn,Ee+h));kt(M),Ft(M)},[se,Ft,Ee,Tt]),Os=a.useCallback(t=>{const i=E.find(h=>h.id===t);q("direct",t,i?.lastMessageAt??i?.updatedAt),L(t),Qe(!1),se&&de(!1)},[E,se,q,L]),Pn=a.useCallback(()=>{L(""),de(!0),Qe(!1)},[L]),In=a.useCallback(()=>{f.selectRoom(null),de(!0),Qe(!1)},[f]),Ya=()=>e.jsxs("div",{className:"chat-empty-state",children:[e.jsx(bn,{size:48,strokeWidth:1.5}),e.jsx("h2",{children:c("chat.startNewConversation","Start a new conversation")}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>_(!0),children:[e.jsx(bt,{size:16}),c("chat.newChat","New Chat")]})]}),Ue=Ra(m,m?.agentId?_e.get(m.agentId)??null:null,rt),On=a.useMemo(()=>{if(!Ue?.provider||!Ue.modelId)return null;const t=Ut.find(i=>i.provider===Ue.provider&&i.id===Ue.modelId);return t?.contextWindow?t.contextWindow:null},[Ue?.modelId,Ue?.provider,Ut]),Ja=a.useMemo(()=>Pi(x,k?S:void 0),[k,x,S]),Xe=Ca(Ue?.provider,Ue?.modelId),Ye=Ue?.provider??null,on=!!(m||k||x.length>0),cn=g==="rooms"?be:!!m,zs=a.useRef(cn);a.useEffect(()=>{const t=zs.current;zs.current=cn,se&&(t||!cn||bs({type:"view",revert:g==="rooms"?In:Pn}))},[g,Pn,In,cn,se,bs]);const zn=m?.agentId===wt?Xe??"Fusion":m?.title||_e.get(m?.agentId??"")?.name||m?.agentId||"Chat",Bs=!!(Xe&&Xe!==zn),Za=!se&&on&&On!==null,Hs=xa(Ja),ln=On!==null?xa(On):null,Bn=ln?c("chat.contextWindowAria","Estimated {{used}} of {{total}} context tokens",{used:Hs,total:ln}):null,er=se&&g==="direct"&&!!m,Hn=_e.get(m?.agentId??"")?.name||(m?.agentId===wt?Xe??"Fusion":m?.agentId?.slice(0,30)??"Fusion"),Un=!1,qn=m?.agentId===wt,tr=t=>t.length>50?`${t.slice(0,50)}…`:t,nr=a.useCallback(()=>{Ba(t=>!t)},[]);a.useEffect(()=>{if(!Kt)return;const t=i=>{xs.current?.contains(i.target)||Qe(!1)};return document.addEventListener("mousedown",t),()=>{document.removeEventListener("mousedown",t)}},[Kt]),a.useEffect(()=>{if(!Gt)return;const t=h=>{ws.current?.contains(h.target)||Rt(!1)},i=h=>{h.key==="Escape"&&Rt(!1)};return document.addEventListener("mousedown",t),document.addEventListener("keydown",i),()=>{document.removeEventListener("mousedown",t),document.removeEventListener("keydown",i)}},[Gt]),a.useEffect(()=>{(!se||g!=="direct"||et)&&Qe(!1)},[se,g,et]),a.useEffect(()=>{Rt(!1)},[f.activeRoom?.id]);const Kn=a.useCallback((t,i)=>{const h=jt.current.get(t);h&&window.clearTimeout(h),ps(B=>({...B,[t]:i}));const M=window.setTimeout(()=>{ps(B=>{const{[t]:ee,...Ce}=B;return Ce}),jt.current.delete(t)},2e3);jt.current.set(t,M)},[]),Us=a.useCallback(async(t,i)=>{try{if(!navigator.clipboard?.writeText)throw new Error("Clipboard API unavailable");await navigator.clipboard.writeText(i),Kn(t,"success")}catch{Kn(t,"error")}},[Kn]),sr=a.useCallback((t,i=!1)=>i?e.jsx("div",{className:"chat-message-content chat-message-content--plain",children:t}):e.jsx("div",{className:"chat-message-content chat-message-content--markdown",children:e.jsx(_a,{remarkPlugins:[$a],components:za,children:t})}),[]),Gn=m?.agentId===wt,Vn=a.useCallback((t,i,h)=>e.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${ct[t]==="success"?" chat-message-copy-action--success":""}${ct[t]==="error"?" chat-message-copy-action--error":""}`,"data-testid":h??`chat-copy-response-${t}`,"aria-label":ct[t]==="success"?c("chat.responseCopied","Response copied"):ct[t]==="error"?c("chat.copyFailed","Copy failed"):c("chat.copyResponse","Copy response"),onClick:()=>{Us(t,i)},children:ct[t]==="success"?e.jsx(Ir,{size:14}):e.jsx(Or,{size:14})}),[ct,Us]),Qn=a.useCallback(t=>{const i=Me.current;if(!i)return;const h=`[data-testid="chat-message-${t}"]`,M=i.querySelector(h);if(!M)return;const B=M.getBoundingClientRect().top-i.getBoundingClientRect().top+i.scrollTop,ee=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;i.scrollTo({top:B,behavior:ee?"auto":"smooth"})},[]),qs=m?.cliExecutorAdapterId??null,ar=!!qs,rr=qs==="generic"?"generic":"hybrid",ir=m?.cliSessionFile||m?.id||"",Ks=()=>e.jsxs("div",{className:"chat-messages",ref:Me,onScroll:As,children:[e.jsx("div",{ref:ys,className:"chat-load-more-sentinel",children:U&&y&&e.jsx("div",{className:"chat-loading-older",children:c("chat.loadingOlderMessages","Loading older messages…")})}),k?e.jsxs(e.Fragment,{children:[x.map((t,i)=>e.jsx(as,{message:t,forcePlain:ke,agentName:Hn,hideAssistantIdentity:qn,showAssistantModelTag:Un,activeModelTag:Xe,activeModelProvider:Ye,activeSessionId:m?.id??null,mentionAgentsByName:$n,roomContext:null,copyAction:Gn&&t.role==="assistant"?Vn(t.id,t.content):void 0,onScrollToTop:Qn,isAwaitingQuestionAnswer:t.role==="assistant"&&i===x.length-1&&!k,submittedQuestionAnswer:Aa(x,i),onQuestionSubmit:nn},t.id)),e.jsxs("div",{className:"chat-message chat-message--assistant chat-message--streaming",children:[!qn&&e.jsxs("div",{className:"chat-message-avatar",children:[Ye?e.jsx(It,{provider:Ye,size:"sm"}):e.jsx(Ot,{size:14}),e.jsx("span",{children:Hn}),Un]}),S?sr(S,ke):e.jsx("div",{className:"chat-message-content chat-message-content--waiting",children:T?c("chat.thinkingStatus","Thinking…"):c("chat.workingStatus","Working…")}),Gn&&S&&Vn("__streaming__",S,"chat-copy-response-streaming"),Oa(N,c,{isAwaitingAnswer:!0,onQuestionSubmit:nn}),T&&e.jsxs("details",{className:"chat-message-thinking",children:[e.jsx("summary",{children:c("chat.thinking","Thinking")}),e.jsx("pre",{className:"chat-message-thinking-content",children:Cn(T)})]}),e.jsxs("div",{className:"chat-typing-indicator",children:[e.jsx("span",{}),e.jsx("span",{}),e.jsx("span",{})]})]})]}):y?e.jsx("div",{className:"chat-empty-state",children:c("chat.loadingMessages","Loading messages...")}):x.length===0&&!m?Ya():x.length===0&&m?e.jsx("div",{className:"chat-empty-state",children:c("chat.noMessagesYet","No messages yet. Start the conversation!")}):e.jsx(e.Fragment,{children:x.map((t,i)=>e.jsx(as,{message:t,forcePlain:ke,agentName:Hn,hideAssistantIdentity:qn,showAssistantModelTag:Un,activeModelTag:Xe,activeModelProvider:Ye,activeSessionId:m?.id??null,mentionAgentsByName:$n,roomContext:null,copyAction:Gn&&t.role==="assistant"?Vn(t.id,t.content):void 0,onScrollToTop:Qn,isAwaitingQuestionAnswer:t.role==="assistant"&&i===x.length-1&&!k,submittedQuestionAnswer:Aa(x,i),onQuestionSubmit:nn},t.id))}),e.jsx("div",{ref:vs})]}),Gs=()=>e.jsxs("div",{className:"chat-input-area",children:[e.jsx("input",{ref:Yt,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:t=>{mt(t.target.files),t.target.value=""}}),p&&e.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":c("chat.skillSuggestions","Skill suggestions"),children:kn?e.jsx("div",{className:"chat-skill-menu-empty",children:c("chat.loadingSkills","Loading skills…")}):je.length===0?e.jsx("div",{className:"chat-skill-menu-empty",children:A?c("chat.noSkillsFound","No skills found"):c("chat.noSkillsAvailable","No skills available")}):je.map((t,i)=>e.jsxs("button",{type:"button",role:"option","aria-selected":i===ae,className:`chat-skill-menu-item${i===ae?" chat-skill-menu-item--highlighted":""}`,onMouseDown:h=>h.preventDefault(),onMouseEnter:()=>V(i),onClick:()=>Ln(t),children:[e.jsx("span",{className:"chat-skill-menu-item-name",children:t.name}),e.jsx("span",{className:"chat-skill-menu-item-description",title:t.relativePath,children:t.relativePath})]},t.id))}),Ae.length>0&&e.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:Ae.map((t,i)=>e.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${i}`,children:[t.previewUrl?e.jsx("img",{src:t.previewUrl,alt:t.file.name}):e.jsx("span",{className:"chat-attachment-preview-name",children:t.file.name}),e.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>js(i),"data-testid":`chat-attachment-remove-${i}`,"aria-label":`Remove ${t.file.name}`,children:"×"})]},t.previewUrl||`${t.file.name}-${i}`))}),P.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"chat-pending-stack","data-testid":"chat-pending-stack",children:P.map((t,i)=>e.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[e.jsx("span",{children:c("chat.queuedMessage","Queued: {{preview}}",{preview:tr(t)})}),e.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":c("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":`chat-pending-dismiss-${i}`,onClick:()=>z(i),children:"×"})]},`${i}-${t}`))}),e.jsx("div",{className:"chat-pending-divider","aria-hidden":"true"})]}),e.jsxs("div",{className:"chat-input-row",children:[e.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":c("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:e.jsx(ea,{size:16})}),e.jsxs("div",{className:`chat-input-wrapper${fs?" chat-input-wrapper--dragover":""}`,onDragOver:t=>{t.preventDefault(),ot(!0)},onDragLeave:()=>ot(!1),onDrop:t=>{t.preventDefault(),ot(!1),mt(t.dataTransfer.files)},children:[e.jsx("textarea",{ref:Es,className:"chat-input-textarea",placeholder:c("chat.typeMessage","Type a message..."),value:K,onChange:$s,onKeyDown:_s,onKeyUp:Ds,onClick:rn,onBlur:Fs,onFocus:Ls,onPaste:Ts,onTouchStart:t=>{typeof window>"u"||window.innerWidth>768||ta()&&(document.activeElement,t.currentTarget)},rows:1,"data-testid":"chat-input"}),e.jsx(pa,{agents:ut,filter:J,highlightedIndex:ne,visible:Z,onSelect:sn,position:"below",roomMemberIds:Be?.memberIds,roomName:Be?.roomName}),e.jsx(Mi,{visible:ue.mentionActive&&!Z,position:Ha,tasks:ue.tasks,files:ue.files,selectedIndex:ue.selectedIndex,onSelectTask:t=>{Dt(ue.selectTask(t,K),`#${t.id}`)},onSelectFile:t=>{Dt(ue.selectFile(t,K),`#${t.path}`)},loading:ue.loading})]}),k?e.jsx("button",{className:"chat-input-stop",onPointerDown:t=>{if(t.pointerType&&t.pointerType!=="mouse"){if(t.preventDefault(),!gt())return;ft(),Q()}},onTouchStart:t=>{t.preventDefault(),gt()&&(ft(),Q())},onMouseDown:t=>{t.preventDefault()},onClick:()=>{Fn()||Q()},"aria-label":c("chat.stopGeneration","Stop generation"),"data-testid":"chat-stop-btn",children:e.jsx(Qr,{size:14})}):e.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:t=>{if(t.pointerType&&t.pointerType!=="mouse"){if(t.preventDefault(),!gt())return;ft(),_t()}},onTouchStart:t=>{t.preventDefault(),gt()&&(ft(),_t())},onMouseDown:t=>{t.preventDefault()},onClick:()=>{Fn()||_t()},disabled:!K.trim()&&Ae.length===0,"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:e.jsx(na,{size:16})})]})]}),or=se?void 0:{width:`${Ee}px`},cr=e.jsxs("div",{className:"chat-sidebar-scope-toggle chat-view-header-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[e.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${g==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":g==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>O("direct"),children:[e.jsx(bn,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:c("chat.scopeDirect","Direct")})]}),e.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${g==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":g==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>O("rooms"),children:[e.jsx(Da,{size:14,"aria-hidden":"true"}),e.jsx("span",{children:c("chat.scopeRooms","Rooms")})]})]});return e.jsxs("div",{ref:ks,className:`chat-view${r?" chat-view--floating":""}${se?" chat-view--narrow":""}`,children:[e.jsx(zr,{icon:bn,title:c("chat.title","Chat"),actions:e.jsxs(e.Fragment,{children:[cr,se?null:e.jsxs("button",{className:"btn btn-sm btn-primary chat-view-header-new-chat",onClick:()=>_(!0),"data-testid":"chat-new-btn",children:[e.jsx(bt,{size:14}),c("chat.newChat","New Chat")]}),!r&&o?e.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:o,"aria-label":c("chat.popOut","Pop out chat"),title:c("chat.popOut","Pop out chat"),"data-testid":"chat-pop-out",children:e.jsx(Ys,{size:16})}):null,r&&u?e.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:u,"aria-label":c("chat.maximizeToChatView","Open in Chat view"),title:c("chat.maximizeToChatView","Open in Chat view"),"data-testid":"chat-modal-maximize",children:e.jsx(Ys,{size:16})}):null,r&&b?e.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:b,"aria-label":c("chat.minimizeToQuickChat","Minimize to quick chat"),title:c("chat.minimizeToQuickChat","Minimize to quick chat"),"data-testid":"chat-modal-minimize",children:e.jsx(Br,{size:16})}):null,r&&d?e.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:d,"aria-label":c("chat.closeChat","Close chat"),title:c("chat.closeChat","Close chat"),"data-testid":"chat-modal-close",children:e.jsx(Hr,{size:16})}):null]})}),e.jsxs("div",{className:"chat-view__body",children:[e.jsxs("div",{className:`chat-sidebar${et?"":" chat-sidebar--hidden"}`,style:or,children:[g==="direct"?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"chat-sidebar-search-container",children:e.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[e.jsx(Ur,{size:14,className:"chat-sidebar-search-icon"}),e.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:c("chat.searchConversations","Search conversations..."),value:C,onChange:t=>I(t.target.value),"data-testid":"chat-search-input"})]})}),e.jsx("div",{className:"chat-session-list chat-sidebar-list",children:$?e.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:c("chat.loadingConversations","Loading...")}):E.length===0?e.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:c("chat.noConversationsYet","No conversations yet")}):E.map(t=>{const i=m?.id===t.id,h=!i&&ie("direct",t.id,t.lastMessageAt??t.updatedAt),M=Ra(t,_e.get(t.agentId)??null,rt),B=Ca(M?.provider,M?.modelId)??"Fusion";return e.jsxs("div",{className:`chat-session-item${i?" chat-session-item--active":""}`,onClick:()=>Os(t.id),onContextMenu:ee=>{ee.preventDefault(),oe({sessionId:t.id,x:ee.clientX,y:ee.clientY})},"data-testid":`chat-session-${t.id}`,children:[e.jsx("button",{className:"chat-session-delete-btn",onClick:ee=>{ee.stopPropagation(),$e(t.id)},"data-testid":"chat-session-delete-btn","aria-label":c("chat.deleteConversation","Delete conversation"),children:e.jsx(Xn,{size:14})}),e.jsxs("div",{className:"chat-session-title",children:[t.title||c("chat.untitledSession","Untitled"),h?e.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${t.id}`,"aria-label":c("chat.unreadMessages","Unread messages")}):null]}),e.jsx("div",{className:"chat-session-preview",children:t.lastMessagePreview||c("chat.noMessages","No messages")}),e.jsxs("div",{className:"chat-session-meta",children:[e.jsxs("span",{className:"chat-session-meta-model",children:[M?.provider?e.jsx(It,{provider:M.provider,size:"sm"}):null,e.jsx("span",{children:_e.get(t.agentId)?.name||(t.agentId===wt?B:t.agentId.slice(0,30))})]}),e.jsx("span",{children:t.updatedAt?Ia(t.updatedAt,c):""})]})]},t.id)})})]}):e.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!se&&e.jsx("div",{className:"chat-sidebar-rooms-header","data-testid":"chat-sidebar-rooms-header",children:e.jsxs("button",{type:"button",className:"btn btn-sm btn-primary","data-testid":"chat-create-room-btn",onClick:()=>at(!0),children:[e.jsx(bt,{size:14}),c("chat.createRoom","Create room")]})}),f.rooms.length===0?e.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:c("chat.noRoomsYet","No rooms yet.")}):e.jsx("div",{className:"chat-session-list chat-sidebar-list",children:f.rooms.map(t=>{const i=f.activeRoom?.id===t.id,h=!i&&ie("room",t.id,t.updatedAt);return e.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${i?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${t.slug}`,onClick:()=>{q("room",t.id,t.updatedAt),f.selectRoom(t.id),se&&de(!1)},onKeyDown:M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),q("room",t.id,t.updatedAt),f.selectRoom(t.id),se&&de(!1))},children:[e.jsxs("span",{className:"chat-room-item-details",children:[e.jsxs("span",{className:"chat-room-item-name-row",children:[e.jsxs("span",{className:"chat-room-item-name",children:["#",t.name]}),h?e.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${t.id}`,"aria-label":c("chat.unreadMessages","Unread messages")}):null]}),i?e.jsx("span",{className:"chat-room-item-meta",children:c("chat.roomMemberCount","{{count}} member",{count:f.activeRoomMembers.length,defaultValue_one:"{{count}} member",defaultValue_other:"{{count}} members"})}):null]}),e.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${t.slug}`,"aria-label":c("chat.deleteRoom","Delete room {{name}}",{name:t.name}),onClick:M=>{M.stopPropagation(),he(t.id)},children:e.jsx(Xn,{size:14})})]},t.id)})})]}),g==="rooms"?se?e.jsx("div",{className:"chat-sidebar-footer",children:e.jsxs("button",{type:"button",className:"btn btn-sm btn-primary chat-sidebar-footer-btn","data-testid":"chat-create-room-btn",onClick:()=>at(!0),children:[e.jsx(bt,{size:14}),c("chat.createRoom","Create room")]})}):null:se?e.jsx("div",{className:"chat-sidebar-footer",children:e.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:()=>_(!0),"data-testid":"chat-new-btn",children:[e.jsx(bt,{size:14}),c("chat.newChat","New Chat")]})}):null]}),!se&&et&&!Tt&&e.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":fn,"aria-valuemax":gn,"aria-valuenow":Ee,"aria-label":c("chat.resizeSidebar","Resize chat sidebar"),tabIndex:0,onPointerDown:Wa,onKeyDown:Xa}),ge&&e.jsxs("div",{className:"chat-session-context-menu",style:{top:ge.y,left:ge.x},onClick:t=>t.stopPropagation(),children:[e.jsxs("button",{onClick:()=>Ps(ge.sessionId),"data-testid":"chat-context-rename",children:[e.jsx(Js,{size:14}),c("chat.rename","Rename")]}),e.jsxs("button",{onClick:()=>Va(ge.sessionId),"data-testid":"chat-context-archive",children:[e.jsx(qr,{size:14}),c("chat.archive","Archive")]}),e.jsxs("button",{onClick:()=>{oe(null),$e(ge.sessionId)},"data-testid":"chat-context-delete",children:[e.jsx(Xn,{size:14}),c("chat.delete","Delete")]})]}),ve&&e.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>ye(null),children:e.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:t=>t.stopPropagation(),children:[e.jsx("h3",{children:c("chat.renameConversationTitle","Rename Conversation")}),e.jsx("p",{className:"chat-view-delete-dialog-copy",children:c("chat.renameConversationBody","Choose a new name for this conversation. Leave it blank to show Untitled.")}),e.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-input",children:c("chat.conversationName","Conversation name")}),e.jsx("input",{id:"chat-rename-input",className:"input chat-rename-input",type:"text",value:Ge,placeholder:c("chat.renamePlaceholder","Untitled"),"data-testid":"chat-rename-input",onChange:t=>Ve(t.target.value),onKeyDown:t=>{t.key==="Enter"&&(t.preventDefault(),Is())},autoFocus:!0}),e.jsxs("div",{className:"chat-new-dialog-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>ye(null),children:c("chat.cancel","Cancel")}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void Is(),"data-testid":"chat-rename-save",children:c("chat.save","Save")})]})]})}),xe&&e.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>$e(null),children:e.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:t=>t.stopPropagation(),children:[e.jsx("h3",{children:c("chat.deleteConversationTitle","Delete Conversation?")}),e.jsx("p",{className:"chat-view-delete-dialog-copy",children:c("chat.deleteConversationBody","This action cannot be undone. All messages in this conversation will be permanently deleted.")}),e.jsxs("div",{className:"chat-new-dialog-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>$e(null),children:c("chat.cancel","Cancel")}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Qa(xe),children:c("chat.delete","Delete")})]})]})}),Bt&&e.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>he(null),children:e.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:t=>t.stopPropagation(),children:[e.jsx("h3",{children:c("chat.deleteRoomTitle","Delete Room?")}),e.jsx("p",{className:"chat-view-delete-dialog-copy",children:c("chat.deleteRoomBody","This action cannot be undone. This room and all its messages will be permanently deleted.")}),e.jsxs("div",{className:"chat-new-dialog-actions",children:[e.jsx("button",{className:"btn btn-sm",onClick:()=>he(null),children:c("chat.cancel","Cancel")}),e.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await f.deleteRoom(Bt),he(null)}catch{s(c("chat.failedToDeleteRoom","Failed to delete room"),"error")}})()},children:c("chat.delete","Delete")})]})]})}),g==="rooms"?e.jsxs("div",{ref:An,className:"chat-thread",children:[f.activeRoom?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"chat-room-thread-header",children:[se&&e.jsx("button",{className:"btn-icon",onClick:In,"data-testid":"chat-back-btn",children:e.jsx(Zs,{size:16})}),e.jsxs("div",{className:"chat-room-switcher-menu",ref:ws,children:[e.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":Gt,onClick:()=>Rt(t=>!t),children:[e.jsxs("span",{className:"chat-thread-header-title",children:["#",f.activeRoom.name]}),e.jsx(un,{size:16,"aria-hidden":"true"})]}),Gt&&e.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:f.rooms.map(t=>e.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${t.id===f.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${t.id}`,onClick:()=>{q("room",t.id,t.updatedAt),f.selectRoom(t.id),Rt(!1)},children:["#",t.name]},t.id))})]}),e.jsx("div",{className:"chat-room-thread-members",children:f.activeRoomMembers.map(t=>e.jsx(wn,{agent:_e.get(t.agentId)??{id:t.agentId,name:t.agentId.slice(0,30)}},t.agentId))})]}),e.jsxs("div",{className:"chat-messages",ref:Me,onScroll:As,children:[f.messagesLoading?e.jsx("div",{className:"chat-empty-state",children:c("chat.loadingMessages","Loading messages...")}):f.messages.filter(t=>t.content.trim()!==wa).length===0?e.jsx("div",{className:"chat-empty-state",children:c("chat.noMessagesYet","No messages yet. Start the conversation!")}):f.messages.filter(t=>t.content.trim()!==wa).map(t=>{const i=t.senderAgentId?_e.get(t.senderAgentId)?.name??t.senderAgentId.slice(0,30):c("chat.you","You"),h={id:t.id,sessionId:t.roomId,role:t.role,content:t.content,thinkingOutput:t.thinkingOutput??void 0,toolCalls:void 0,fallbackInfo:void 0,attachments:t.attachments,createdAt:t.createdAt};return e.jsx(as,{message:h,forcePlain:ke,agentName:i,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:f.activeRoom?.id??null,mentionAgentsByName:$n,roomContext:Be,onScrollToTop:Qn,isAwaitingQuestionAnswer:!1,onQuestionSubmit:nn},t.id)}),e.jsx("div",{ref:vs})]}),f.activeRoom&&gs&&e.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>De("fab-click"),children:[e.jsx(un,{size:14}),c("chat.latest","Latest")]})]}):e.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:c("chat.selectRoomOrCreate","Select a room or create one")}),f.activeRoom&&e.jsxs("div",{className:"chat-input-area",children:[e.jsx("input",{ref:Yt,type:"file",accept:"image/*,.txt,.json,.yaml,.yml,.log,.csv,.xml,.md",multiple:!0,style:{display:"none"},onChange:t=>{mt(t.target.files),t.target.value=""}}),Ae.length>0&&e.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:Ae.map((t,i)=>e.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${i}`,children:[t.previewUrl?e.jsx("img",{src:t.previewUrl,alt:t.file.name}):e.jsx("span",{className:"chat-attachment-preview-name",children:t.file.name}),e.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>js(i),"data-testid":`chat-attachment-remove-${i}`,"aria-label":`Remove ${t.file.name}`,children:"×"})]},t.previewUrl||`${t.file.name}-${i}`))}),e.jsxs("div",{className:"chat-input-row",children:[e.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":c("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:e.jsx(ea,{size:16})}),e.jsxs("div",{className:`chat-input-wrapper${fs?" chat-input-wrapper--dragover":""}`,onDragOver:t=>{t.preventDefault(),ot(!0)},onDragLeave:()=>ot(!1),onDrop:t=>{t.preventDefault(),ot(!1),mt(t.dataTransfer.files)},children:[e.jsx("textarea",{ref:Es,className:"chat-input-textarea",placeholder:c("chat.typeMessage","Type a message..."),value:K,onChange:$s,onKeyDown:_s,onKeyUp:Ds,onClick:rn,onBlur:Fs,onFocus:Ls,onPaste:Ts,onTouchStart:t=>{typeof window>"u"||window.innerWidth>768||ta()&&(document.activeElement,t.currentTarget)},rows:1,"data-testid":"chat-input"}),e.jsx(pa,{agents:ut,filter:J,highlightedIndex:ne,visible:Z,onSelect:sn,position:"below",roomMemberIds:Be?.memberIds,roomName:Be?.roomName})]}),e.jsx("button",{type:"button",className:"chat-input-send",onPointerDown:t=>{if(t.pointerType&&t.pointerType!=="mouse"){if(t.preventDefault(),!gt())return;ft(),$t()}},onTouchStart:t=>{t.preventDefault(),gt()&&(ft(),$t())},onMouseDown:t=>{t.preventDefault()},onClick:()=>{Fn()||$t()},disabled:!K.trim()&&Ae.length===0,"data-testid":"chat-send-btn",style:{touchAction:"manipulation"},children:e.jsx(na,{size:16})})]})]})]}):e.jsxs("div",{ref:An,className:"chat-thread",children:[(on||!se)&&e.jsxs("div",{className:"chat-thread-header",children:[se&&on&&e.jsx("button",{className:"btn-icon",onClick:Pn,"data-testid":"chat-back-btn",children:e.jsx(Zs,{size:16})}),e.jsx("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:er?e.jsxs("div",{className:"chat-mobile-session-menu",ref:xs,children:[e.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":Kt,onClick:()=>Qe(t=>!t),children:[Ye?e.jsx(It,{provider:Ye,size:"md"}):e.jsx(Ot,{size:16}),e.jsx("span",{className:"chat-thread-header-title",children:zn}),Bs&&e.jsx("span",{className:"chat-model-tag",children:Xe}),e.jsx(un,{size:16,"aria-hidden":"true"})]}),Kt&&e.jsxs("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:[E.map(t=>e.jsxs("div",{className:`chat-mobile-session-option-row${m?.id===t.id?" chat-mobile-session-option-row--active":""}`,role:"none",children:[e.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${m?.id===t.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${t.id}`,onClick:()=>Os(t.id),children:e.jsx("span",{className:"chat-mobile-session-option-title",children:t.title||c("chat.untitledSession","Untitled")})}),e.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-rename","data-testid":`chat-mobile-session-rename-${t.id}`,"aria-label":c("chat.renameConversationAria","Rename conversation {{title}}",{title:t.title||c("chat.untitledSession","Untitled")}),onClick:()=>Ps(t.id),children:e.jsx(Js,{size:14})})]},t.id)),e.jsxs("button",{type:"button",role:"menuitem",className:"chat-mobile-session-new","data-testid":"chat-mobile-session-new",onClick:()=>{Qe(!1),_(!0)},children:[e.jsx(bt,{size:16,"aria-hidden":"true"}),e.jsx("span",{children:c("chat.newChat","New Chat")})]})]})]}):e.jsxs(e.Fragment,{children:[Ye?e.jsx(It,{provider:Ye,size:"md"}):e.jsx(Ot,{size:16}),e.jsx("span",{className:"chat-thread-header-title",children:zn}),Bs&&e.jsx("span",{className:"chat-model-tag",children:Xe}),Za&&ln&&Bn?e.jsxs("span",{className:"chat-thread-header-context","data-testid":"chat-thread-context-window",title:Bn,"aria-label":Bn,children:[Hs," / ",ln]}):null]})}),on&&e.jsx("button",{type:"button",className:`chat-thread-header-render-toggle${ke?" chat-thread-header-render-toggle--plain":""}`,"data-testid":"chat-thread-render-toggle","aria-label":ke?c("chat.showRenderedMarkdown","Show all messages as rendered Markdown"):c("chat.showPlainText","Show all messages as plain text"),onClick:nr,children:ke?e.jsx(Kr,{size:14}):e.jsx(Gr,{size:14})})]}),ar?e.jsx(ji,{cliSessionId:ir,tier:rr,projectId:n,renderTranscript:Ks,renderComposer:()=>m?Gs():null}):e.jsxs(e.Fragment,{children:[Ks(),gs&&e.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>De("fab-click"),children:[e.jsx(un,{size:14}),c("chat.latest","Latest")]}),m&&Gs()]})]}),e.jsx(Ai,{isOpen:Sn,onClose:()=>at(!1),projectId:n,existingRoomNames:f.rooms.map(t=>t.name),onCreate:async t=>{await f.createRoom({name:t.name,memberAgentIds:t.memberAgentIds}),g!=="rooms"&&O("rooms"),at(!1),se&&de(!1)}})]}),R&&e.jsx(Xi,{projectId:n,defaultModel:rt,onClose:()=>_(!1),onCreate:Ga})]})}export{ro as ChatView,zi as clampChatInputHeight,Oi as resolveChatInputOverflowY,Ra as resolveSessionProvider};
|