@runfusion/fusion 0.74.0-beta.2 → 0.74.0-beta.4
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 +5416 -3166
- package/dist/child-process-worker.js +3540 -1656
- package/dist/client/.vite/manifest.json +272 -272
- package/dist/client/assets/AgentDetailView-BGXTnuBR.js +13 -0
- package/dist/client/assets/AgentDetailView-CH11Ydji.css +1 -0
- package/dist/client/assets/{AgentPermissionPolicyEditor-BycC7HhP.js → AgentPermissionPolicyEditor-DswM202p.js} +1 -1
- package/dist/client/assets/AgentsView-CEpZDrmC.js +24 -0
- package/dist/client/assets/{ChatView-DAsZY1We.js → ChatView-BXXX0q6G.js} +3 -3
- package/dist/client/assets/CommandCenter-CqjN1-9X.js +97 -0
- package/dist/client/assets/DevServerView-BUO7JRi6.js +1 -0
- package/dist/client/assets/{DirectoryPicker-DsCk3Nsw.js → DirectoryPicker-CiP4h5C7.js} +1 -1
- package/dist/client/assets/{DocumentsView-8EI6KNBY.js → DocumentsView-DwLD0h2S.js} +1 -1
- package/dist/client/assets/EvalsView-C9juKffD.js +1 -0
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-ce6DROKD.js → ExperimentalAgentOnboardingModal-DYvw9TEh.js} +1 -1
- package/dist/client/assets/{GoalsView-BVlTtw-u.js → GoalsView-BD1AkfVN.js} +1 -1
- package/dist/client/assets/{InsightsView-BKQeROkb.js → InsightsView-Q0mu759R.js} +1 -1
- package/dist/client/assets/{MemoryView-DCzTnxsV.js → MemoryView-DCTqPpCG.js} +1 -1
- package/dist/client/assets/{PiExtensionsManager-C94HwDz5.js → PiExtensionsManager-CSe_uGfa.js} +1 -1
- package/dist/client/assets/{PluginManager-C3DegklW.js → PluginManager-DPm8YQC0.js} +1 -1
- package/dist/client/assets/{PullRequestView-CrE89UL7.js → PullRequestView-BpJgNDLH.js} +2 -2
- package/dist/client/assets/{ReportModal-BD1ZUDdV.js → ReportModal-iGmTZqiF.js} +1 -1
- package/dist/client/assets/ResearchView-BfgKB-6z.js +2 -0
- package/dist/client/assets/{SecretsView-6qK8Idb7.js → SecretsView-CqvQLK7z.js} +1 -1
- package/dist/client/assets/SessionTerminal-A9di8GAo.js +2 -0
- package/dist/client/assets/SettingsModal-BsCUsAXe.js +21 -0
- package/dist/client/assets/{SettingsModal-BkOSlfyr.js → SettingsModal-D-iyPGZE.js} +1 -1
- package/dist/client/assets/SettingsModal-DmfMotcd.css +1 -0
- package/dist/client/assets/{SettingsTextareaRow-Btyx5kaR.js → SettingsTextareaRow-DwgHxMMY.js} +1 -1
- package/dist/client/assets/{SetupWizardModal-Blhx-dRt.js → SetupWizardModal-CrSnLN44.js} +2 -2
- package/dist/client/assets/{SkillsView-DGE5kYc3.js → SkillsView-C_STy7KI.js} +1 -1
- package/dist/client/assets/{TodoView-YSGI7ATd.js → TodoView-BJJNGNLq.js} +1 -1
- package/dist/client/assets/{WorkflowNodeEditor-CZiEThu2.js → WorkflowNodeEditor-Jp5i_Vxu.js} +3 -3
- package/dist/client/assets/{WorkflowNodeEditor-nCx4nqoL.css → WorkflowNodeEditor-sZ96V3Kd.css} +1 -1
- package/dist/client/assets/{agent-import-generation-DQeNZMAm.js → agent-import-generation-DbVrl8ou.js} +1 -1
- package/dist/client/assets/{app-Dn1u7zJ9.js → app-BYs5Cx-j.js} +2 -2
- package/dist/client/assets/{app-DaikOPcV.js → app-CTV8PCYh.js} +3 -3
- package/dist/client/assets/{app-DJIiVHdA.js → app-CwdZxrJI.js} +2 -2
- package/dist/client/assets/{app-hQw_x2KJ.js → app-DE-MPJxA.js} +2 -2
- package/dist/client/assets/{app-DxTbBEMH.js → app-e8c4wb5t.js} +2 -2
- package/dist/client/assets/{app-DMZ_RusZ.js → app-yKugq_Ld.js} +2 -2
- package/dist/client/assets/{architectureDiagram-3BPJPVTR-DhaJNKa4.js → architectureDiagram-3BPJPVTR-Ctz8GX1N.js} +1 -1
- package/dist/client/assets/{blockDiagram-GPEHLZMM-pKpg7gJU.js → blockDiagram-GPEHLZMM-WI_YPphw.js} +1 -1
- package/dist/client/assets/{c4Diagram-AAUBKEIU-DVPXKJnr.js → c4Diagram-AAUBKEIU-BLwS5Zfh.js} +1 -1
- package/dist/client/assets/channel-CMMrQrQu.js +1 -0
- package/dist/client/assets/{chunk-2J33WTMH-CHt90T5z.js → chunk-2J33WTMH-DeXlX12-.js} +1 -1
- package/dist/client/assets/{chunk-4BX2VUAB-DsWFYy0a.js → chunk-4BX2VUAB-zvCEraJR.js} +1 -1
- package/dist/client/assets/{chunk-55IACEB6-D8XiXEo8.js → chunk-55IACEB6-BgZq96DR.js} +1 -1
- package/dist/client/assets/{chunk-727SXJPM-DlUYBn_Y.js → chunk-727SXJPM-CayoVGXL.js} +1 -1
- package/dist/client/assets/{chunk-AQP2D5EJ-BSdPOr9q.js → chunk-AQP2D5EJ-BmaktpVP.js} +1 -1
- package/dist/client/assets/{chunk-FMBD7UC4-B9IAeBld.js → chunk-FMBD7UC4-qYWgZPF8.js} +1 -1
- package/dist/client/assets/{chunk-ND2GUHAM-CmxnYQrR.js → chunk-ND2GUHAM-DIovauCc.js} +1 -1
- package/dist/client/assets/{chunk-QZHKN3VN-Dxp6Po_j.js → chunk-QZHKN3VN-DXWnr9LE.js} +1 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-CqxyehbN.js +1 -0
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-CqxyehbN.js +1 -0
- package/dist/client/assets/common-13IRj_PO.js +1 -0
- package/dist/client/assets/common-BBynATth.js +1 -0
- package/dist/client/assets/common-BG-vw0tL.js +1 -0
- package/dist/client/assets/common-DSo46rnH.js +1 -0
- package/dist/client/assets/common-DbOCE-0i.js +1 -0
- package/dist/client/assets/common-DnXF4Jmj.js +1 -0
- package/dist/client/assets/{cose-bilkent-S5V4N54A-BNl3bhpS.js → cose-bilkent-S5V4N54A-Dee9mTjK.js} +1 -1
- package/dist/client/assets/{dagre-BM42HDAG-DFs7WCcz.js → dagre-BM42HDAG-CU-v2zoi.js} +1 -1
- package/dist/client/assets/{dashboard-view-DnoTcnIo.js → dashboard-view-BM790i02.js} +1 -1
- package/dist/client/assets/{dashboard-view-ZGxLEL9r.js → dashboard-view-CG4rzThC.js} +1 -1
- package/dist/client/assets/{dashboard-view-vc8kgLMs.js → dashboard-view-COary9sK.js} +1 -1
- package/dist/client/assets/{diagram-2AECGRRQ-C2PVozvu.js → diagram-2AECGRRQ-DIqdnJ5B.js} +1 -1
- package/dist/client/assets/{diagram-5GNKFQAL-DFJ5b9H8.js → diagram-5GNKFQAL-ChpdUlpb.js} +1 -1
- package/dist/client/assets/{diagram-KO2AKTUF-D335CW-c.js → diagram-KO2AKTUF-BxmzOp-c.js} +1 -1
- package/dist/client/assets/{diagram-LMA3HP47-DSfhroAW.js → diagram-LMA3HP47-DLEx-0rl.js} +1 -1
- package/dist/client/assets/{diagram-OG6HWLK6-8iGveM-Z.js → diagram-OG6HWLK6-DEpkJ3cG.js} +1 -1
- package/dist/client/assets/{erDiagram-TEJ5UH35-Xc56MEEi.js → erDiagram-TEJ5UH35-C3Rjr78a.js} +1 -1
- package/dist/client/assets/{flowDiagram-I6XJVG4X-DjCU9WbD.js → flowDiagram-I6XJVG4X-aPbBbeiH.js} +1 -1
- package/dist/client/assets/{folder-open-BRrB44UX.js → folder-open-BnNbfyzc.js} +1 -1
- package/dist/client/assets/{ganttDiagram-6RSMTGT7-CXQE1bea.js → ganttDiagram-6RSMTGT7-BEzAwvJ4.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-PVQCEYII--mrSABLC.js → gitGraphDiagram-PVQCEYII-Y4hB2swQ.js} +1 -1
- package/dist/client/assets/index-8wtfjIkg.js +2675 -0
- package/dist/client/assets/index-Bp3UBLOz.css +1 -0
- package/dist/client/assets/{infoDiagram-5YYISTIA-CTS_nljP.js → infoDiagram-5YYISTIA-pd3J7fRT.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-CpV5x3gk.js → ishikawaDiagram-YF4QCWOH-B968vfOH.js} +1 -1
- package/dist/client/assets/{journeyDiagram-JHISSGLW-BK2QCMnt.js → journeyDiagram-JHISSGLW-V4crhYKX.js} +1 -1
- package/dist/client/assets/{kanban-definition-UN3LZRKU-B4srpspY.js → kanban-definition-UN3LZRKU-Cl8LxR6k.js} +1 -1
- package/dist/client/assets/{mermaid.core-B8DVAt21.js → mermaid.core-rb_bKdHH.js} +4 -4
- package/dist/client/assets/{mindmap-definition-RKZ34NQL-CsmmiPpA.js → mindmap-definition-RKZ34NQL-Cnu-LPHz.js} +1 -1
- package/dist/client/assets/{pieDiagram-4H26LBE5-BahLDqf4.js → pieDiagram-4H26LBE5-C6hPYepr.js} +1 -1
- package/dist/client/assets/{puzzle-BFPQsuIa.js → puzzle-C8AvcmuM.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-W4KKPZXB-Bo3u0wTU.js → quadrantDiagram-W4KKPZXB-CUImgAi-.js} +1 -1
- package/dist/client/assets/{requirementDiagram-4Y6WPE33-DYkYsz7d.js → requirementDiagram-4Y6WPE33-DzDLxIYz.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-5OEKKPKP-BCbh0BSY.js → sankeyDiagram-5OEKKPKP-DSr_oIy8.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-3UESZ5HK-C2AP9GlE.js → sequenceDiagram-3UESZ5HK-DO2E98Hv.js} +1 -1
- package/dist/client/assets/{shield-alert-tlZOi02c.js → shield-alert-Byjz1VmT.js} +1 -1
- package/dist/client/assets/{standing-instructions-template-C0Rzv9Mr.js → standing-instructions-template-Cf9fZ8bv.js} +1 -1
- package/dist/client/assets/{stateDiagram-AJRCARHV-CARkH0ug.js → stateDiagram-AJRCARHV-BYPlDS4u.js} +1 -1
- package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-C2He043y.js → stateDiagram-v2-BHNVJYJU-Ce_6vh1Q.js} +1 -1
- package/dist/client/assets/{timeline-definition-PNZ67QCA-MvbYneEM.js → timeline-definition-PNZ67QCA-CG1FeaKV.js} +1 -1
- package/dist/client/assets/{upload-DWK0F17Z.js → upload-yPsE_DRN.js} +1 -1
- package/dist/client/assets/{users-1AkDfM14.js → users-C_YmWx9d.js} +1 -1
- package/dist/client/assets/{vennDiagram-CIIHVFJN-DOjzzLqc.js → vennDiagram-CIIHVFJN-JLUXqFyb.js} +1 -1
- package/dist/client/assets/{wardley-L42UT6IY-Di70vhu2.js → wardley-L42UT6IY-D_UBzrZ2.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-YWT4CUSO-nK6ARhDv.js → wardleyDiagram-YWT4CUSO-BzwMrdpL.js} +1 -1
- package/dist/client/assets/{xychartDiagram-2RQKCTM6-C7_y76B7.js → xychartDiagram-2RQKCTM6-C5TjbAcZ.js} +1 -1
- package/dist/client/index.html +2 -2
- package/dist/client/sw.js +633 -13
- package/dist/client/version.json +1 -1
- package/dist/extension.js +3999 -2008
- package/package.json +1 -1
- package/skill/fusion/references/engine-tools.md +1 -1
- package/dist/client/assets/AgentDetailView-CoeSgMXS.css +0 -1
- package/dist/client/assets/AgentDetailView-DH4Cn5iG.js +0 -13
- package/dist/client/assets/AgentsView-Dkij8Sm8.js +0 -24
- package/dist/client/assets/CommandCenter-jTzBo-pg.js +0 -97
- package/dist/client/assets/DevServerView-CxlacYJp.js +0 -1
- package/dist/client/assets/EvalsView-kYnaIk11.js +0 -1
- package/dist/client/assets/ResearchView-eMiRw1EM.js +0 -2
- package/dist/client/assets/SessionTerminal-DtFLyUaK.js +0 -2
- package/dist/client/assets/SettingsModal-BTfZlghk.css +0 -1
- package/dist/client/assets/SettingsModal-DSq-_qwo.js +0 -21
- package/dist/client/assets/channel-xFBfK0sX.js +0 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-BFBVD968.js +0 -1
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-BFBVD968.js +0 -1
- package/dist/client/assets/common-BDp2y6CF.js +0 -1
- package/dist/client/assets/common-BnEo5fLN.js +0 -1
- package/dist/client/assets/common-Bzr_Y8h4.js +0 -1
- package/dist/client/assets/common-CvwyFzfv.js +0 -1
- package/dist/client/assets/common-CztCXRkz.js +0 -1
- package/dist/client/assets/common-DPe2mbb7.js +0 -1
- package/dist/client/assets/index-C2xsZoNG.js +0 -2671
- package/dist/client/assets/index-Dv-95s50.css +0 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{r as a,j as t,b as Bi}from"./vendor-react-SZ_qB27O.js";import{c as ei,aq as Et,ao as bt,ap as xa,
|
|
1
|
+
import{r as a,j as t,b as Bi}from"./vendor-react-SZ_qB27O.js";import{c as ei,aq as Et,ao as bt,ap as xa,by as Ms,dx as Oi,dy as Ui,dz as ra,au as X,dA as Hi,bx as Dt,dB as At,br as wa,dC as Ki,dD as Wi,dE as Vi,dF as Xi,dG as qi,dH as Gi,bd as Yi,cR as ya,dI as ke,aY as Qi,bM as ti,bw as xn,dJ as Ji,al as wn,dK as Zi,dL as eo,dM as to,bp as no,aI as ao,b2 as vn,W as so,c_ as io,dN as oo,dO as ro,f as co,aW as lo,dP as uo,dQ as ni,dR as ai,dS as mo,dl as ho,J as fo,dT as go,dU as po,dV as Ns,dW as vo,dX as bo,dY as Rs,y as xo,q as wo,u as yo,dj as ca,C as un,dZ as mn,d_ as js,v as la,P as gt,V as ko,bu as As,d1 as Ts,d0 as Co,X as Es,aH as So,d$ as Mo,x as da,bL as No,e0 as ua,e1 as Ds,e2 as ma,e3 as Is,e4 as Ls,e5 as Ps,e6 as Ro,e7 as jo,bJ as Fs}from"./index-8wtfjIkg.js";import{u as ze}from"./vendor-i18n-GF3RlKbq.js";import{SessionTerminal as _s}from"./SessionTerminal-A9di8GAo.js";import"./vendor-codemirror-jBKmHyH0.js";import"./vendor-reactflow-9C3XTE7_.js";import"./vendor-xterm-BNq00GSj.js";import"./shield-alert-Byjz1VmT.js";/**
|
|
2
2
|
* @license lucide-react v1.7.0 - ISC
|
|
3
3
|
*
|
|
4
4
|
* This source code is licensed under the ISC license.
|
|
@@ -8,6 +8,6 @@ import{r as a,j as t,b as Bi}from"./vendor-react-SZ_qB27O.js";import{c as ei,aq
|
|
|
8
8
|
*
|
|
9
9
|
* This source code is licensed under the ISC license.
|
|
10
10
|
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const To=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],Eo=ei("tag",To);function hn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Do(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function ha(s,r){const u=Do(),g=r?.warm===!0,d=hn(),h=new Map;let C=!1,S=!1;return{mark(R){C||S||!u||h.has(R)||h.set(R,hn())},complete:R=>{if(!u||C||S){C=!0;return}C=!0,h.set("complete",hn());const E=Array.from(h.entries()).sort((T,b)=>T[1]-b[1]);let i=d;const M={};for(const[T,b]of E)M[T]=Math.max(0,b-i),i=b;const k=Math.max(0,hn()-d);try{console.debug("[room-open]",{roomId:s,warm:g,totalMs:k,phases:M,...R??{}})}catch{}},cancel(){S=!0,C=!0}}}const _e="fusion:chat-active-room";class ii extends Error{roomId;constructor(r,u){super(r),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=u}}function ka(s){return[...s].sort((r,u)=>new Date(u.updatedAt).getTime()-new Date(r.updatedAt).getTime())}function Xe(s,r){const u=s.findIndex(d=>d.id===r.id);if(u===-1)return ka([r,...s]);const g=[...s];return g[u]=r,ka(g)}function De(s){try{return JSON.parse(s.data)}catch{return null}}function fa(s){return s.slice().reverse()}function Io(s,r,u){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:s,role:"user",content:r,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...u?.length?{attachments:u}:{},createdAt:new Date().toISOString()}}function _s(s,r,u){if(s.some(d=>d.id===r.id))return s;const g=u?s.findIndex(d=>d.id===u):-1;if(g>=0){const d=[...s];return d[g]=r,d}if(r.role==="user"){const d=s.findIndex(h=>h.role==="user"&&h.id.startsWith("temp-")&&h.content.trim()===r.content.trim());if(d>=0){const h=[...s];return h[d]=r,h}}return[...s,r]}function Lo(s,r){const{t:u}=ze("app"),g=`${Et.CHAT_ROOMS}:${s??"global"}`,d=`${Et.ACTIVE_CHAT_ROOM_ID}:${s??"global"}`,h=a.useCallback(c=>`${Et.CHAT_ROOM_MESSAGES_PREFIX}${s??"global"}:${c}`,[s]),C=a.useCallback(c=>`${Et.CHAT_ROOM_MEMBERS_PREFIX}${s??"global"}:${c}`,[s]),[S,x]=a.useState(()=>{const c=bt(g,{maxAgeMs:xa});return Array.isArray(c)?c:[]}),[R,E]=a.useState(()=>S.length===0),[i,M]=a.useState(null),[k,T]=a.useState(()=>{const c=bt(d,{maxAgeMs:Ms});return c?S.find(p=>p.id===c)??null:null}),[b,l]=a.useState([]),[B,N]=a.useState([]),[W,$]=a.useState(!1),K=a.useRef(S),I=a.useRef(k),ee=a.useRef(0),J=a.useRef(s);K.current=S,I.current=k,J.current!==s&&(J.current=s,ee.current+=1);const Y=a.useCallback(async c=>{if(!c){l([]),N([]),$(!1);return}const p=ha(c.id,{warm:!1});p.mark("select");const y=bt(h(c.id),{maxAgeMs:Oi}),f=bt(C(c.id),{maxAgeMs:xa}),j=Array.isArray(y)&&y.length>0,F=Array.isArray(f)&&f.length>0;j||F?(p.mark("cache-hit"),j&&(N(y),p.mark("hydrate")),F&&l(f),$(!1)):(N([]),$(!0));try{const[Z,ge]=await Promise.all([Ui(c.id,s),ra(c.id,{limit:100,order:"desc"},s)]);p.mark("members-fetch"),p.mark("messages-fetch"),X(C(c.id),Z.members,{maxBytes:5e5});const ae=fa(ge.messages);X(h(c.id),ae,{maxBytes:5e5}),I.current?.id===c.id&&(l(Z.members),N(ae),p.mark("hydrate"))}catch{!j&&!F&&(l([]),N([]))}finally{$(!1),p.complete({warm:j,membersCached:F})}},[C,h,s]),D=a.useCallback(async()=>{K.current.length===0&&E(!0);try{const c=await Hi({},s),p=ka(c.rooms);x(p),X(g,p,{maxBytes:5e5}),M(null);const y=bt(d,{maxAgeMs:Ms})??Dt(_e,s);if(y){const f=p.find(j=>j.id===y)??null;f?(T(f),Y(f)):(At(_e,s),X(d,"",{maxBytes:5e5}))}}catch(c){const p=c instanceof Error?c.message:u("chatRooms.error.failedToLoad","Failed to load chat rooms");M(p),r?.(p,"error")}finally{E(!1)}},[d,r,Y,s,g]),_=a.useCallback(c=>{if(!c){I.current=null,T(null),At(_e,s),X(d,"",{maxBytes:5e5}),Y(null);return}const p=K.current.find(y=>y.id===c)??null;I.current=p,T(p),p&&(wa(_e,p.id,s),X(d,p.id,{maxBytes:5e5}),Y(p))},[d,Y,s]),Q=a.useCallback(async c=>{const y=(await Ki({name:c.name,memberAgentIds:c.memberAgentIds},s)).room;return x(f=>Xe(f,y)),I.current=y,T(y),wa(_e,y.id,s),X(d,y.id,{maxBytes:5e5}),await Y(y),y},[d,Y,s]),O=a.useCallback(async(c,p)=>{const f=(await Vi(c,p,s)).room;return x(j=>Xe(j,f)),I.current?.id===f.id&&(I.current=f,T(f)),f},[s]),A=a.useCallback(async c=>{await Wi(c,s),x(p=>p.filter(y=>y.id!==c)),X(h(c),[],{maxBytes:5e5}),X(C(c),[],{maxBytes:5e5}),I.current?.id===c&&(I.current=null,T(null),l([]),N([]),At(_e,s),X(d,"",{maxBytes:5e5}))},[d,C,h,s]),H=a.useCallback(async(c,p)=>{const y=I.current,f=y?.id;if(!f)throw new Error(u("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const j=ha(f,{warm:!1}),F=p?.files?.map(ae=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,filename:ae.name,originalName:ae.name,mimeType:ae.type||"application/octet-stream",size:ae.size,createdAt:new Date().toISOString()})),Z=Io(f,c,F?.length?F:p?.attachments);I.current?.id===f&&N(ae=>{const de=[...ae,Z];return X(h(f),de,{maxBytes:5e5}),de});let ge=!1;try{const ae=[];if(p?.files?.length)for(const pe of p.files)try{const qe=await Xi(f,pe,s);ae.push(qe.attachment)}catch{throw new Error(u("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:pe.name}))}const de=[...p?.attachments??[],...ae],Ie=await qi(f,{content:c,...de.length?{attachments:de}:{}},s);ge=!0,Ie.message?.createdAt&&y&&x(pe=>Xe(pe,{...y,updatedAt:Ie.message.createdAt})),I.current?.id===f&&N(pe=>{const qe=_s(pe,Ie.message,Z.id);return X(h(f),qe,{maxBytes:5e5}),qe});const ue=await ra(f,{limit:100,order:"desc"},s),Le=fa(ue.messages);if(X(h(f),Le,{maxBytes:5e5}),I.current?.id!==f)return;N(Le),j.mark("hydrate")}catch(ae){let de=null;try{const ue=await ra(f,{limit:100,order:"desc"},s);de=fa(ue.messages),X(h(f),de,{maxBytes:5e5}),I.current?.id===f&&(N(de),j.mark("hydrate"))}catch{!ge&&I.current?.id===f&&N(ue=>{const Le=ue.filter(pe=>pe.id!==Z.id);return X(h(f),Le,{maxBytes:5e5}),Le})}const Ie=de?.some(ue=>ue.role==="user"&&ue.content.trim()===Z.content.trim());if(ge||Ie){const ue=ae instanceof Error&&ae.message.trim()?ae.message:u("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new ii(ue,f)}throw ae}finally{j.complete({source:"send-room-message"})}},[h,s]),le=a.useCallback(async c=>{!c||!K.current.some(p=>p.id===c)||(await Gi(c,s),X(h(c),[],{maxBytes:5e5}),I.current?.id===c&&N([]))},[h,s]);return a.useEffect(()=>{D()},[D]),a.useEffect(()=>{const c=ee.current,p=s?`/api/events?projectId=${encodeURIComponent(s)}`:"/api/events";return Yi(p,{onReconnect:()=>{ya({view:"useChatRooms",trigger:"sse-reconnect",projectId:s,replayAttempted:!1});const y=I.current?.id;if(y){const f=ha(y,{warm:!0});f.mark("sse-reconnect-refresh"),D().finally(()=>f.complete({source:"sse-reconnect"}));return}D()},events:{"chat:room:created":y=>{if(ee.current!==c)return;const f=De(y);f&&x(j=>Xe(j,f))},"chat:room:updated":y=>{if(ee.current!==c)return;const f=De(y);f&&(x(j=>Xe(j,f)),I.current?.id===f.id&&(I.current=f,T(f)))},"chat:room:deleted":y=>{if(ee.current!==c)return;const f=De(y);f?.id&&(x(j=>j.filter(F=>F.id!==f.id)),X(h(f.id),[],{maxBytes:5e5}),X(C(f.id),[],{maxBytes:5e5}),I.current?.id===f.id&&(I.current=null,T(null),l([]),N([]),At(_e,s),X(d,"",{maxBytes:5e5})))},"chat:room:member:added":y=>{if(ee.current!==c)return;const f=De(y);!f||I.current?.id!==f.roomId||l(j=>{if(j.some(Z=>Z.agentId===f.agentId))return j;const F=[...j,f];return X(C(f.roomId),F,{maxBytes:5e5}),F})},"chat:room:member:removed":y=>{if(ee.current!==c)return;const f=De(y);!f||I.current?.id!==f.roomId||l(j=>{const F=j.filter(Z=>Z.agentId!==f.agentId);return X(C(f.roomId),F,{maxBytes:5e5}),F})},"chat:room:message:added":y=>{if(ee.current!==c)return;const f=De(y);f&&(x(j=>{const F=j.find(Z=>Z.id===f.roomId);return F?Xe(j,{...F,updatedAt:f.createdAt}):j}),I.current?.id===f.roomId&&N(j=>{const F=_s(j,f);return F===j?j:(X(h(f.roomId),F,{maxBytes:5e5}),F)}))},"chat:room:message:updated":y=>{if(ee.current!==c)return;const f=De(y);!f||I.current?.id!==f.roomId||N(j=>{const F=j.map(Z=>Z.id===f.id?f:Z);return X(h(f.roomId),F,{maxBytes:5e5}),F})},"chat:room:message:deleted":y=>{if(ee.current!==c)return;const f=De(y);f?.id&&N(j=>{const F=j.filter(ge=>ge.id!==f.id),Z=I.current?.id;return Z&&X(h(Z),F,{maxBytes:5e5}),F})},"chat:room:messages:cleared":y=>{if(ee.current!==c)return;const f=De(y);f?.roomId&&(X(h(f.roomId),[],{maxBytes:5e5}),I.current?.id===f.roomId&&N([]),x(j=>{const F=j.find(Z=>Z.id===f.roomId);return F?Xe(j,{...F,updatedAt:new Date().toISOString()}):j}))}}})},[d,C,h,s,D]),a.useEffect(()=>{k&&(S.some(c=>c.id===k.id)||(I.current=null,T(null),l([]),N([]),At(_e,s),X(d,"",{maxBytes:5e5})))},[k,d,s,S]),{rooms:S,roomsLoading:R,roomsError:i,activeRoom:k,activeRoomMembers:b,messages:B,messagesLoading:W,selectRoom:_,createRoom:Q,updateRoomSettings:O,deleteRoom:A,sendRoomMessage:H,clearRoom:le,refreshRooms:D}}const Tt={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},zs=200;function Ca(s){if(!s)return null;const r=new Date(s).getTime();return Number.isFinite(r)?r:null}function oi(s){const r=Object.entries(s);if(r.length<=zs)return s;const u=r.map(([g,d])=>({id:g,timestamp:d,value:Ca(d)??0})).sort((g,d)=>d.value-g.value).slice(0,zs);return Object.fromEntries(u.map(({id:g,timestamp:d})=>[g,d]))}function fn(s){if(!s)return{};try{const r=JSON.parse(s);if(!r||typeof r!="object")return{};const u={};for(const[g,d]of Object.entries(r))typeof g=="string"&&typeof d=="string"&&(u[g]=d);return oi(u)}catch{return{}}}function Po(s){const[r,u]=a.useState(()=>{try{return fn(Dt(Tt.direct,s))}catch{return{}}}),[g,d]=a.useState(()=>{try{return fn(Dt(Tt.room,s))}catch{return{}}});a.useEffect(()=>{try{u(fn(Dt(Tt.direct,s)))}catch{u({})}try{d(fn(Dt(Tt.room,s)))}catch{d({})}},[s]);const h=a.useMemo(()=>({direct:r,room:g}),[r,g]),C=a.useCallback((i,M)=>{const k=oi(M);try{wa(Tt[i],JSON.stringify(k),s)}catch{}return k},[s]),S=a.useCallback((i,M)=>{if(i==="direct"){u(k=>C(i,M(k)));return}d(k=>C(i,M(k)))},[C]),x=a.useCallback((i,M,k)=>{const T=Ca(k);if(T===null)return!1;const b=h[i][M],l=Ca(b);return l===null?!0:T>l},[h]),R=a.useCallback((i,M,k)=>{if(!M)return;const T=k??new Date().toISOString();S(i,b=>({...b,[M]:T}))},[S]),E=a.useCallback((i,M)=>{M.length!==0&&S(i,k=>{const T={...k};for(const b of M)b.id&&(T[b.id]=b.lastActivityAt??new Date().toISOString());return T})},[S]);return{isUnread:x,markRead:R,markAllRead:E}}const Fo=["",...Zi];function Bs({level:s,onChange:r,defaultThinkingLevel:u="off",showTargetSection:g=!0,models:d=[],favoriteProviders:h=[],favoriteModels:C=[],agents:S=[],agentId:x,modelProvider:R,modelId:E,onChangeModel:i,disabled:M=!1}){const{t:k}=ze("app"),[T,b]=a.useState(!1),[l,B]=a.useState(()=>x&&x!==ke?"agent":"model"),N=a.useRef(null),W=s??"",$=R&&E?`${R}/${E}`:"",K=x&&x!==ke?x:"",I=W!==""||g&&(!!$||!!K),ee="chat-thinking-level-listbox";a.useEffect(()=>{if(!T)return;const c=p=>{const y=p.target;if(!(y instanceof Node))return;const f=N.current?.contains(y),j=y instanceof Element&&!!y.closest(".model-combobox-dropdown--portal");!f&&!j&&b(!1)};return document.addEventListener("pointerdown",c),()=>document.removeEventListener("pointerdown",c)},[T]),a.useEffect(()=>{b(!1),B(K?"agent":"model")},[W,K,$]);const J=a.useMemo(()=>S.find(c=>c.id===K),[S,K]),Y=c=>c===""?k("modelSelection.thinkingDefault","Default ({{level}})",{level:u??"off"}):k(`models.options.${c}`,c==="xhigh"?"Very High":c.charAt(0).toUpperCase()+c.slice(1)),D=c=>{b(!1),r(c)},_=c=>{const p=c.indexOf("/");p<=0||(b(!1),i?.({modelProvider:c.slice(0,p),modelId:c.slice(p+1)}))},Q=c=>{c&&(b(!1),i?.({agentId:c}))},O=c=>{B(c)},A=c=>{c.key==="Escape"&&b(!1)},H=(c,p)=>{if(c.key==="Escape"){c.preventDefault(),b(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),D(p))},le=(c,p)=>{if(c.key==="Escape"){c.preventDefault(),b(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Q(p))};return t.jsxs("div",{className:"chat-thinking-level-root",ref:N,children:[t.jsx("button",{type:"button",className:`btn-icon chat-thinking-btn${I?" chat-thinking-btn--active":""}`,"data-testid":"chat-thinking-btn","aria-haspopup":"dialog","aria-expanded":T,"aria-controls":ee,"aria-label":k("chat.thinkingLevelButton","Thinking level"),title:k("chat.thinkingLevelButton","Thinking level"),disabled:M,onClick:()=>b(c=>!c),onKeyDown:A,children:t.jsx(Qi,{size:16})}),T?t.jsxs("div",{className:"chat-thinking-popover",role:"presentation","data-testid":"chat-thinking-popover",children:[g?t.jsxs("section",{className:"chat-thinking-target-section","aria-label":k("chat.modelAgentSection","Model / Agent"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:k("chat.modelAgentSection","Model / Agent")}),t.jsxs("div",{className:"chat-thinking-mode-toggle","data-testid":"chat-thinking-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${l==="model"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-model","aria-pressed":l==="model",onPointerDown:c=>{c.button===0&&O("model")},onClick:c=>{c.detail===0&&O("model")},children:k("chat.newChatModeModel","Model")}),t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${l==="agent"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-agent","aria-pressed":l==="agent",onPointerDown:c=>{c.button===0&&O("agent")},onClick:c=>{c.detail===0&&O("agent")},children:k("chat.newChatModeAgent","Agent")})]}),l==="model"?t.jsxs("div",{className:"chat-thinking-model-picker","data-testid":"chat-thinking-model-picker",children:[t.jsx(ti,{models:d,value:$,onChange:_,label:k("chat.newChatModeModel","Model"),placeholder:k("chat.selectModel","Select a model"),disabled:!i||d.length===0,favoriteProviders:h,favoriteModels:C,menuWidth:"readable"}),d.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-model-empty",children:k("chat.noModelsAvailable","No models available")}):null]}):t.jsx("div",{className:"chat-thinking-agent-list","data-testid":"chat-thinking-agent-list",children:S.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-agent-empty",children:k("chat.noAgentsAvailable","No agents available")}):S.map(c=>{const p=K===c.id;return t.jsxs("button",{type:"button",className:`chat-thinking-agent-item${p?" chat-thinking-agent-item--selected":""}`,"data-testid":`chat-thinking-agent-${c.id}`,"aria-pressed":p,disabled:!i,onClick:()=>Q(c.id),onKeyDown:y=>le(y,c.id),children:[t.jsx(xn,{size:16}),t.jsx("span",{className:"chat-thinking-agent-name",children:c.name||c.id}),c.role?t.jsx("span",{className:"chat-thinking-agent-role",children:c.role}):null]},c.id)})}),J?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-agent",children:k("chat.currentAgentTarget","Current agent: {{name}}",{name:J.name||J.id})}):$?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-model",children:k("chat.currentModelTarget","Current model: {{model}}",{model:$})}):t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-default",children:k("chat.currentDefaultTarget","Using the default chat target")})]}):null,t.jsxs("section",{className:"chat-thinking-level-section","aria-label":k("chat.thinkingLevelButton","Thinking level"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:k("chat.thinkingLevelSection","Thinking level")}),t.jsx("div",{id:ee,className:"chat-thinking-popover-list",role:"listbox","aria-label":k("chat.thinkingLevelButton","Thinking level"),children:Fo.map(c=>{const p=W===c;return t.jsx("button",{type:"button",role:"option","aria-selected":p,className:`chat-thinking-popover-option${p?" active":""}`,"data-testid":`chat-thinking-option-${c||"default"}`,onClick:()=>D(c),onKeyDown:y=>H(y,c),children:Y(c)},c||"default")})})]})]}):null]})}function Os(s){return s.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function ri(s,r){const u=r.trim();if(!u)return!0;const g=Os(u);return Os(s).includes(g)||s.toLowerCase().includes(u.toLowerCase())}function Us({agents:s,filter:r,highlightedIndex:u,visible:g,onSelect:d,position:h="below",roomMemberIds:C,roomName:S}){const{t:x}=ze("app"),R=a.useMemo(()=>s.filter(b=>ri(b.name,r)),[s,r]),E=!!C,i=E&&r.trim().length>0,M=a.useMemo(()=>E?R.filter(b=>C?.has(b.id)):R,[R,C,E]),k=a.useMemo(()=>E?R.filter(b=>!C?.has(b.id)):[],[R,C,E]),T=i?[...M,...k]:M;return g?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${h}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":x("agentMention.suggestionsLabel","Agent mention suggestions"),children:T.length===0?t.jsx("div",{className:"agent-mention-empty",children:x("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[E&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:S?x("agentMention.membersOf","Members of #{{roomName}}",{roomName:S}):x("agentMention.roomMembers","Room members")}),M.map((b,l)=>t.jsxs("button",{type:"button",className:`agent-mention-item${l===u?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${b.id}`,onMouseDown:B=>B.preventDefault(),onClick:()=>d(b),role:"option","aria-selected":l===u,children:[t.jsx(wn,{agent:b,size:20}),E&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":x("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:b.name}),t.jsx("span",{className:"agent-mention-role",children:b.role})]},b.id)),E&&!i&&k.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:x("agentMention.typeToSearch","Type to search other agents")}),E&&i&&k.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:x("agentMention.otherAgents","Other agents")}),k.map((b,l)=>{const B=M.length+l;return t.jsxs("button",{type:"button",className:`agent-mention-item${B===u?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${b.id}`,onMouseDown:N=>N.preventDefault(),onClick:()=>d(b),role:"option","aria-selected":B===u,children:[t.jsx(wn,{agent:b,size:20}),t.jsx("span",{className:"agent-mention-name",children:b.name}),t.jsx("span",{className:"agent-mention-role",children:b.role})]},b.id)})]})]})}):null}function $o(s,r){return s+r}function _o({visible:s,position:r,tasks:u,files:g,selectedIndex:d,onSelectTask:h,onSelectFile:C,loading:S}){const{t:x}=ze("app");if(!s)return null;const R=u.length>0,E=g.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:r.top,left:r.left},"data-testid":"file-mention-popup",onMouseDown:i=>{i.preventDefault()},children:[S&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!S&&!R&&!E&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:x("fileMention.empty","No tasks or files found")}),!S&&(R||E)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[R&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:x("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":x("fileMention.taskMatches","Task matches"),children:u.map((i,M)=>{const k=M;return t.jsxs("li",{className:`file-mention-popup-item${k===d?" file-mention-popup-item--selected":""}`,onClick:()=>h(i),role:"option","aria-selected":k===d,"data-testid":`task-mention-item-${k}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(si,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsxs("div",{className:"file-mention-popup-task-row",children:[t.jsx("span",{className:"file-mention-popup-task-id",children:i.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${i.column}`,children:i.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:i.title})]})]},i.id)})})]}),E&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:x("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":x("fileMention.fileMatches","File matches"),children:g.map((i,M)=>{const k=$o(u.length,M),T=Ji(i.path);return t.jsxs("li",{className:`file-mention-popup-item${k===d?" file-mention-popup-item--selected":""}`,onClick:()=>C(i),role:"option","aria-selected":k===d,"data-testid":`file-mention-item-${k}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(eo,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:i.name}),T&&t.jsx("span",{className:"file-mention-popup-item-path",children:T})]})]},i.path)})})]})]})]})}function zo(s,r=[],u){const g=s.trim().replace(/^#/,""),d=(C,S)=>u?u(C,S):S;if(!g)return{ok:!1,error:d("createRoom.nameRequired","Room name is required.")};if(/[A-Z]/.test(g))return{ok:!1,error:d("createRoom.lowercase","Use lowercase letters only.")};const h=g.toLowerCase();return h.length>80?{ok:!1,error:d("createRoom.maxLength","Room names can be at most 80 characters.")}:/^[a-z0-9_-]+$/.test(h)?/^[-_]|[-_]$/.test(h)?{ok:!1,error:d("createRoom.noEdgeChars","Room names cannot start or end with a hyphen or underscore.")}:r.some(C=>C.toLowerCase()===h)?{ok:!1,error:d("createRoom.duplicate","A room with this name already exists.")}:{ok:!0,name:h}:{ok:!1,error:d("createRoom.validChars","Use lowercase letters, numbers, hyphens, or underscores only.")}}function Bo({isOpen:s,onClose:r,onCreate:u,projectId:g,existingRoomNames:d=[]}){const{t:h}=ze("app"),[C,S]=a.useState(""),[x,R]=a.useState([]),[E,i]=a.useState(""),[M,k]=a.useState([]),[T,b]=a.useState(!1),[l,B]=a.useState(null),[N,W]=a.useState(!1),$=a.useRef(null),K=a.useRef(null),[I,ee]=a.useState(void 0);a.useLayoutEffect(()=>{s&&ee(to())},[s]),a.useEffect(()=>{s&&(K.current=document.activeElement instanceof HTMLElement?document.activeElement:null,b(!0),B(null),no(void 0,g).then(A=>R(A)).catch(()=>{R([]),B(h("createRoom.failedLoadAgents","Failed to load agents."))}).finally(()=>b(!1)))},[s,g]),a.useEffect(()=>{if(!s){S(""),i(""),k([]),B(null),W(!1);return}const A=window.requestAnimationFrame(()=>$.current?.focus());return()=>window.cancelAnimationFrame(A)},[s]),a.useEffect(()=>{if(!s)return;const A=H=>{H.key==="Escape"&&r()};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[s,r]),a.useEffect(()=>{s||K.current?.focus()},[s]);const J=a.useMemo(()=>zo(C,d,h),[C,d,h]),Y=a.useMemo(()=>{const A=E.trim().toLowerCase();return A?x.filter(H=>H.name.toLowerCase().includes(A)):x},[x,E]),D=a.useMemo(()=>x.filter(A=>M.includes(A.id)),[x,M]),_=J.ok&&M.length>0&&!N&&!T;if(!s)return null;const Q=A=>{N||k(H=>H.includes(A)?H.filter(le=>le!==A):[...H,A])},O=async()=>{if(!J.ok){B(J.error);return}if(M.length===0){B(h("createRoom.selectMember","Select at least one member."));return}B(null),W(!0);try{await u({name:J.name,displayName:`#${J.name}`,memberAgentIds:M}),r()}catch(A){B(A instanceof Error?A.message:h("createRoom.failedCreate","Failed to create room."))}finally{W(!1)}};return Bi.createPortal(t.jsx("div",{className:"modal-overlay open",onClick:A=>A.target===A.currentTarget&&r(),style:I?{zIndex:I}:void 0,children:t.jsxs("div",{className:"modal modal-lg create-room-modal",role:"dialog","aria-modal":"true","aria-label":h("createRoom.title","Create room"),onClick:A=>A.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:h("createRoom.title","Create room")}),t.jsx("button",{type:"button",className:"modal-close","aria-label":h("actions.close","Close"),onClick:r,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:h("createRoom.nameLabel","Room name")}),t.jsxs("div",{className:"create-room-modal-name-field",children:[t.jsx("span",{"aria-hidden":"true",className:"create-room-modal-name-hash",children:"#"}),t.jsx("input",{ref:$,id:"create-room-name",className:"input",value:C,disabled:N,onChange:A=>{const H=A.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();S(H)}})]}),!J.ok&&t.jsx("div",{className:"form-error",children:J.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:h("createRoom.members","Members")}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:h("createRoom.searchAgents","Search agents"),value:E,disabled:N,onChange:A=>i(A.target.value)})]}),D.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:D.map(A=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>Q(A.id),disabled:N,children:[A.name," ×"]},A.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:T?t.jsx("div",{className:"create-room-modal-empty",children:t.jsx(ao,{label:h("createRoom.loadingAgents","Loading agents...")})}):Y.length===0?t.jsx("div",{className:"create-room-modal-empty",children:x.length===0?h("createRoom.noAgents","No agents in this project yet."):h("createRoom.noMatch","No agents match your search.")}):Y.map(A=>{const H=M.includes(A.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${H?" create-room-modal-member-row--selected":""}`,onClick:()=>Q(A.id),disabled:N,children:[t.jsx(wn,{agent:A,size:20}),t.jsx("span",{children:A.name}),t.jsx("span",{className:"create-room-modal-member-role",children:A.role})]},A.id)})}),l&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:l})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:N,children:h("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void O(),disabled:!_,children:N?h("createRoom.creating","Creating..."):h("createRoom.create","Create room")})]})]})}),document.body)}function Oo({cliSessionId:s,tier:r,projectId:u,renderTranscript:g,renderComposer:d,queuedCount:h=0,terminalProps:C}){const{t:S}=ze("app"),x=r==="generic",[R,E]=a.useState(x?"terminal":"transcript");if(x)return t.jsx("div",{className:"cli-chat-surface cli-chat-surface--generic","data-tier":"generic",children:t.jsx($s,{sessionId:s,projectId:u,...C})});const i=R==="terminal";return t.jsxs("div",{className:"cli-chat-surface","data-tier":r,"data-view":R,children:[t.jsxs("div",{className:"cli-chat-surface__toolbar",role:"tablist","aria-label":S("cliChat.viewToggleLabel","Chat view"),children:[t.jsxs("button",{type:"button",role:"tab","aria-selected":!i,className:`cli-chat-surface__tab${i?"":" is-active"}`,onClick:()=>E("transcript"),children:[t.jsx(vn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:S("cliChat.transcriptTab","Transcript")})]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":i,className:`cli-chat-surface__tab${i?" is-active":""}`,onClick:()=>E("terminal"),children:[t.jsx(so,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:S("cliChat.terminalTab","Terminal")})]})]}),t.jsx("div",{className:"cli-chat-surface__body",children:i?t.jsx($s,{sessionId:s,projectId:u,...C}):g()}),!i&&t.jsxs("div",{className:"cli-chat-surface__composer",children:[h>0&&t.jsx("div",{className:"cli-chat-surface__queued",role:"status","aria-live":"polite",children:S("cliChat.queued","{{count}} message queued — will send when the agent is ready",{count:h})}),d()]})]})}const Uo=200,Ho=8,Ko=8;function Hs(){return new DOMException("The operation was aborted.","AbortError")}function Ks(s,r){return r.aborted?Promise.reject(Hs()):new Promise((u,g)=>{const d=()=>g(Hs());r.addEventListener("abort",d,{once:!0}),s.then(h=>{r.removeEventListener("abort",d),u(h)},h=>{r.removeEventListener("abort",d),g(h)})})}function Vs(s,r,u){const g=s.slice(0,r),d=s.slice(r+1),h=d.match(/[\s]|$/),C=h?h.index??d.length:d.length,S=d.slice(C);return`${g}${u}${S}`}function Vo(s={}){const{projectId:r,workspace:u="project"}=s,[g,d]=a.useState(!1),[h,C]=a.useState(""),[S,x]=a.useState(-1),[R,E]=a.useState([]),[i,M]=a.useState([]),[k,T]=a.useState(!1),[b,l]=a.useState(0),B=a.useRef(null),N=a.useRef(null),W=[...R.map(D=>({kind:"task",task:D})),...i.map(D=>({kind:"file",file:D}))];a.useEffect(()=>()=>{B.current&&clearTimeout(B.current),N.current?.abort()},[]);const $=a.useCallback((D,_)=>{if(_<0||_>D.length){d(!1);return}const Q=O=>/[a-zA-Z0-9/_.-]/.test(O);for(let O=_-1;O>=0;O--){if(D[O]==="#"){if(O===0){const H=D.slice(O+1,_);x(O),C(H),l(0),d(!0);return}const A=D[O-1];if(/[\s,.;:!?'"()[\]{}]/.test(A)){const H=D.slice(O+1,_);x(O),C(H),l(0),d(!0);return}d(!1);return}if(!Q(D[O])){d(!1);return}}d(!1)},[]),K=a.useCallback(()=>{N.current?.abort(),d(!1),C(""),x(-1),E([]),M([]),l(0),T(!1)},[]),I=a.useCallback(async D=>{if(!D.trim()){E([]),M([]),T(!1);return}N.current?.abort();const _=new AbortController;N.current=_;try{T(!0);const[Q,O]=await Promise.allSettled([Ks(io(20,0,r,D),_.signal),Ks(oo(D,u,r),_.signal)]);if(_.signal.aborted)return;const A=Q.status==="fulfilled"?Q.value.slice(0,Ho).map(le=>({id:le.id,title:le.title??"",column:le.column})):[],H=O.status==="fulfilled"?O.value.files.slice(0,Ko):[];E(A),M(H),l(0)}catch(Q){Q.name!=="AbortError"&&(E([]),M([]))}finally{_.signal.aborted||T(!1)}},[u,r]);a.useEffect(()=>{if(g)return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{I(h)},Uo),()=>{B.current&&clearTimeout(B.current)}},[h,g,I]);const ee=a.useCallback((D,_)=>!g||S<0?_:Vs(_,S,`#${D.id}`),[g,S]),J=a.useCallback((D,_)=>!g||S<0?_:Vs(_,S,`#${D.path}`),[g,S]),Y=a.useCallback((D,_)=>{if(!g||W.length===0)return!1;switch(D.key){case"ArrowDown":return D.preventDefault(),l(Q=>Math.min(Q+1,W.length-1)),!0;case"ArrowUp":return D.preventDefault(),l(Q=>Math.max(Q-1,0)),!0;case"Enter":case"Tab":return W[b]?(D.preventDefault(),!0):!1;case"Escape":return D.preventDefault(),K(),!0;default:return!1}},[g,W,b,K]);return{mentionActive:g,tasks:R,files:i,combinedItems:W,loading:k,mentionQuery:h,selectedIndex:b,setSelectedIndex:l,detectMention:$,selectTask:ee,selectFile:J,dismissMention:K,handleKeyDown:Y}}const ga=new Map,bn=new Map;function Ma(s){return s??"global"}function Sa(s){return`${Et.DISCOVERED_SKILLS_PREFIX}${Ma(s)}`}function pt(s){return bt(Sa(s),{maxAgeMs:xa})}function Wo(s,r){for(const u of bn.get(s)??[])u(r)}async function Xo(s){const r=Ma(s),u=ga.get(r);if(u)return u;const g=co(s).finally(()=>{ga.delete(r)});return ga.set(r,g),g}function qo(s){const[r,u]=a.useState(()=>pt(s)??[]),[g,d]=a.useState(()=>pt(s)===null),h=a.useRef(pt(s)!==null),C=Ma(s);a.useEffect(()=>{const R=pt(s)??[];u(R),d(pt(s)===null),h.current=pt(s)!==null},[s]),a.useEffect(()=>{const R=bn.get(C)??new Set;return R.add(u),bn.set(C,R),()=>{R.delete(u),R.size===0&&bn.delete(C)}},[C]);const S=a.useCallback(async()=>{try{const R=await Xo(s);h.current=!0,X(Sa(s),R,{maxBytes:5e5}),Wo(C,R)}catch{h.current||ro(Sa(s))}finally{d(!1)}},[s,C]);a.useEffect(()=>{S()},[S]);const x=a.useCallback(async()=>{d(!0),await S()},[S]);return{skills:r,loading:g,refresh:x}}function Go(s,r){const u=s.reduce((g,d)=>g+(d.content?.length??0),0)+(r?.length??0);return Math.ceil(u/4)}function Ws(s){if(!Number.isFinite(s)||s<=0)return"0";if(s<1e3)return String(Math.round(s));const r=s/1e3;return r<10?`~${Number(r.toFixed(1))}k`:`${Math.round(r)}k`}const Na=640,Yo=200,Qo=200,vt=8;function pr(s){const r=s.trim();return r?`${r}
|
|
11
|
+
*/const To=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],Eo=ei("tag",To);function hn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function Do(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function ha(s,r){const u=Do(),g=r?.warm===!0,d=hn(),h=new Map;let C=!1,S=!1;return{mark(R){C||S||!u||h.has(R)||h.set(R,hn())},complete:R=>{if(!u||C||S){C=!0;return}C=!0,h.set("complete",hn());const E=Array.from(h.entries()).sort((T,b)=>T[1]-b[1]);let i=d;const M={};for(const[T,b]of E)M[T]=Math.max(0,b-i),i=b;const k=Math.max(0,hn()-d);try{console.debug("[room-open]",{roomId:s,warm:g,totalMs:k,phases:M,...R??{}})}catch{}},cancel(){S=!0,C=!0}}}const $e="fusion:chat-active-room";class ii extends Error{roomId;constructor(r,u){super(r),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=u}}function ka(s){return[...s].sort((r,u)=>new Date(u.updatedAt).getTime()-new Date(r.updatedAt).getTime())}function Xe(s,r){const u=s.findIndex(d=>d.id===r.id);if(u===-1)return ka([r,...s]);const g=[...s];return g[u]=r,ka(g)}function De(s){try{return JSON.parse(s.data)}catch{return null}}function fa(s){return s.slice().reverse()}function Io(s,r,u){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:s,role:"user",content:r,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...u?.length?{attachments:u}:{},createdAt:new Date().toISOString()}}function $s(s,r,u){if(s.some(d=>d.id===r.id))return s;const g=u?s.findIndex(d=>d.id===u):-1;if(g>=0){const d=[...s];return d[g]=r,d}if(r.role==="user"){const d=s.findIndex(h=>h.role==="user"&&h.id.startsWith("temp-")&&h.content.trim()===r.content.trim());if(d>=0){const h=[...s];return h[d]=r,h}}return[...s,r]}function Lo(s,r){const{t:u}=ze("app"),g=`${Et.CHAT_ROOMS}:${s??"global"}`,d=`${Et.ACTIVE_CHAT_ROOM_ID}:${s??"global"}`,h=a.useCallback(c=>`${Et.CHAT_ROOM_MESSAGES_PREFIX}${s??"global"}:${c}`,[s]),C=a.useCallback(c=>`${Et.CHAT_ROOM_MEMBERS_PREFIX}${s??"global"}:${c}`,[s]),[S,x]=a.useState(()=>{const c=bt(g,{maxAgeMs:xa});return Array.isArray(c)?c:[]}),[R,E]=a.useState(()=>S.length===0),[i,M]=a.useState(null),[k,T]=a.useState(()=>{const c=bt(d,{maxAgeMs:Ms});return c?S.find(p=>p.id===c)??null:null}),[b,l]=a.useState([]),[B,N]=a.useState([]),[V,_]=a.useState(!1),K=a.useRef(S),I=a.useRef(k),ee=a.useRef(0),Z=a.useRef(s);K.current=S,I.current=k,Z.current!==s&&(Z.current=s,ee.current+=1);const Y=a.useCallback(async c=>{if(!c){l([]),N([]),_(!1);return}const p=ha(c.id,{warm:!1});p.mark("select");const y=bt(h(c.id),{maxAgeMs:Oi}),f=bt(C(c.id),{maxAgeMs:xa}),j=Array.isArray(y)&&y.length>0,F=Array.isArray(f)&&f.length>0;j||F?(p.mark("cache-hit"),j&&(N(y),p.mark("hydrate")),F&&l(f),_(!1)):(N([]),_(!0));try{const[J,ge]=await Promise.all([Ui(c.id,s),ra(c.id,{limit:100,order:"desc"},s)]);p.mark("members-fetch"),p.mark("messages-fetch"),X(C(c.id),J.members,{maxBytes:5e5});const ae=fa(ge.messages);X(h(c.id),ae,{maxBytes:5e5}),I.current?.id===c.id&&(l(J.members),N(ae),p.mark("hydrate"))}catch{!j&&!F&&(l([]),N([]))}finally{_(!1),p.complete({warm:j,membersCached:F})}},[C,h,s]),D=a.useCallback(async()=>{K.current.length===0&&E(!0);try{const c=await Hi({},s),p=ka(c.rooms);x(p),X(g,p,{maxBytes:5e5}),M(null);const y=bt(d,{maxAgeMs:Ms})??Dt($e,s);if(y){const f=p.find(j=>j.id===y)??null;f?(T(f),Y(f)):(At($e,s),X(d,"",{maxBytes:5e5}))}}catch(c){const p=c instanceof Error?c.message:u("chatRooms.error.failedToLoad","Failed to load chat rooms");M(p),r?.(p,"error")}finally{E(!1)}},[d,r,Y,s,g]),$=a.useCallback(c=>{if(!c){I.current=null,T(null),At($e,s),X(d,"",{maxBytes:5e5}),Y(null);return}const p=K.current.find(y=>y.id===c)??null;I.current=p,T(p),p&&(wa($e,p.id,s),X(d,p.id,{maxBytes:5e5}),Y(p))},[d,Y,s]),Q=a.useCallback(async c=>{const y=(await Ki({name:c.name,memberAgentIds:c.memberAgentIds},s)).room;return x(f=>Xe(f,y)),I.current=y,T(y),wa($e,y.id,s),X(d,y.id,{maxBytes:5e5}),await Y(y),y},[d,Y,s]),O=a.useCallback(async(c,p)=>{const f=(await Wi(c,p,s)).room;return x(j=>Xe(j,f)),I.current?.id===f.id&&(I.current=f,T(f)),f},[s]),A=a.useCallback(async c=>{await Vi(c,s),x(p=>p.filter(y=>y.id!==c)),X(h(c),[],{maxBytes:5e5}),X(C(c),[],{maxBytes:5e5}),I.current?.id===c&&(I.current=null,T(null),l([]),N([]),At($e,s),X(d,"",{maxBytes:5e5}))},[d,C,h,s]),H=a.useCallback(async(c,p)=>{const y=I.current,f=y?.id;if(!f)throw new Error(u("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const j=ha(f,{warm:!1}),F=p?.files?.map(ae=>({id:`upload-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,filename:ae.name,originalName:ae.name,mimeType:ae.type||"application/octet-stream",size:ae.size,createdAt:new Date().toISOString()})),J=Io(f,c,F?.length?F:p?.attachments);I.current?.id===f&&N(ae=>{const de=[...ae,J];return X(h(f),de,{maxBytes:5e5}),de});let ge=!1;try{const ae=[];if(p?.files?.length)for(const pe of p.files)try{const qe=await Xi(f,pe,s);ae.push(qe.attachment)}catch{throw new Error(u("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:pe.name}))}const de=[...p?.attachments??[],...ae],Ie=await qi(f,{content:c,...de.length?{attachments:de}:{}},s);ge=!0,Ie.message?.createdAt&&y&&x(pe=>Xe(pe,{...y,updatedAt:Ie.message.createdAt})),I.current?.id===f&&N(pe=>{const qe=$s(pe,Ie.message,J.id);return X(h(f),qe,{maxBytes:5e5}),qe});const ue=await ra(f,{limit:100,order:"desc"},s),Le=fa(ue.messages);if(X(h(f),Le,{maxBytes:5e5}),I.current?.id!==f)return;N(Le),j.mark("hydrate")}catch(ae){let de=null;try{const ue=await ra(f,{limit:100,order:"desc"},s);de=fa(ue.messages),X(h(f),de,{maxBytes:5e5}),I.current?.id===f&&(N(de),j.mark("hydrate"))}catch{!ge&&I.current?.id===f&&N(ue=>{const Le=ue.filter(pe=>pe.id!==J.id);return X(h(f),Le,{maxBytes:5e5}),Le})}const Ie=de?.some(ue=>ue.role==="user"&&ue.content.trim()===J.content.trim());if(ge||Ie){const ue=ae instanceof Error&&ae.message.trim()?ae.message:u("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new ii(ue,f)}throw ae}finally{j.complete({source:"send-room-message"})}},[h,s]),le=a.useCallback(async c=>{!c||!K.current.some(p=>p.id===c)||(await Gi(c,s),X(h(c),[],{maxBytes:5e5}),I.current?.id===c&&N([]))},[h,s]);return a.useEffect(()=>{D()},[D]),a.useEffect(()=>{const c=ee.current,p=s?`/api/events?projectId=${encodeURIComponent(s)}`:"/api/events";return Yi(p,{onReconnect:()=>{ya({view:"useChatRooms",trigger:"sse-reconnect",projectId:s,replayAttempted:!1});const y=I.current?.id;if(y){const f=ha(y,{warm:!0});f.mark("sse-reconnect-refresh"),D().finally(()=>f.complete({source:"sse-reconnect"}));return}D()},events:{"chat:room:created":y=>{if(ee.current!==c)return;const f=De(y);f&&x(j=>Xe(j,f))},"chat:room:updated":y=>{if(ee.current!==c)return;const f=De(y);f&&(x(j=>Xe(j,f)),I.current?.id===f.id&&(I.current=f,T(f)))},"chat:room:deleted":y=>{if(ee.current!==c)return;const f=De(y);f?.id&&(x(j=>j.filter(F=>F.id!==f.id)),X(h(f.id),[],{maxBytes:5e5}),X(C(f.id),[],{maxBytes:5e5}),I.current?.id===f.id&&(I.current=null,T(null),l([]),N([]),At($e,s),X(d,"",{maxBytes:5e5})))},"chat:room:member:added":y=>{if(ee.current!==c)return;const f=De(y);!f||I.current?.id!==f.roomId||l(j=>{if(j.some(J=>J.agentId===f.agentId))return j;const F=[...j,f];return X(C(f.roomId),F,{maxBytes:5e5}),F})},"chat:room:member:removed":y=>{if(ee.current!==c)return;const f=De(y);!f||I.current?.id!==f.roomId||l(j=>{const F=j.filter(J=>J.agentId!==f.agentId);return X(C(f.roomId),F,{maxBytes:5e5}),F})},"chat:room:message:added":y=>{if(ee.current!==c)return;const f=De(y);f&&(x(j=>{const F=j.find(J=>J.id===f.roomId);return F?Xe(j,{...F,updatedAt:f.createdAt}):j}),I.current?.id===f.roomId&&N(j=>{const F=$s(j,f);return F===j?j:(X(h(f.roomId),F,{maxBytes:5e5}),F)}))},"chat:room:message:updated":y=>{if(ee.current!==c)return;const f=De(y);!f||I.current?.id!==f.roomId||N(j=>{const F=j.map(J=>J.id===f.id?f:J);return X(h(f.roomId),F,{maxBytes:5e5}),F})},"chat:room:message:deleted":y=>{if(ee.current!==c)return;const f=De(y);f?.id&&N(j=>{const F=j.filter(ge=>ge.id!==f.id),J=I.current?.id;return J&&X(h(J),F,{maxBytes:5e5}),F})},"chat:room:messages:cleared":y=>{if(ee.current!==c)return;const f=De(y);f?.roomId&&(X(h(f.roomId),[],{maxBytes:5e5}),I.current?.id===f.roomId&&N([]),x(j=>{const F=j.find(J=>J.id===f.roomId);return F?Xe(j,{...F,updatedAt:new Date().toISOString()}):j}))}}})},[d,C,h,s,D]),a.useEffect(()=>{k&&(S.some(c=>c.id===k.id)||(I.current=null,T(null),l([]),N([]),At($e,s),X(d,"",{maxBytes:5e5})))},[k,d,s,S]),{rooms:S,roomsLoading:R,roomsError:i,activeRoom:k,activeRoomMembers:b,messages:B,messagesLoading:V,selectRoom:$,createRoom:Q,updateRoomSettings:O,deleteRoom:A,sendRoomMessage:H,clearRoom:le,refreshRooms:D}}const Tt={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},zs=200;function Ca(s){if(!s)return null;const r=new Date(s).getTime();return Number.isFinite(r)?r:null}function oi(s){const r=Object.entries(s);if(r.length<=zs)return s;const u=r.map(([g,d])=>({id:g,timestamp:d,value:Ca(d)??0})).sort((g,d)=>d.value-g.value).slice(0,zs);return Object.fromEntries(u.map(({id:g,timestamp:d})=>[g,d]))}function fn(s){if(!s)return{};try{const r=JSON.parse(s);if(!r||typeof r!="object")return{};const u={};for(const[g,d]of Object.entries(r))typeof g=="string"&&typeof d=="string"&&(u[g]=d);return oi(u)}catch{return{}}}function Po(s){const[r,u]=a.useState(()=>{try{return fn(Dt(Tt.direct,s))}catch{return{}}}),[g,d]=a.useState(()=>{try{return fn(Dt(Tt.room,s))}catch{return{}}});a.useEffect(()=>{try{u(fn(Dt(Tt.direct,s)))}catch{u({})}try{d(fn(Dt(Tt.room,s)))}catch{d({})}},[s]);const h=a.useMemo(()=>({direct:r,room:g}),[r,g]),C=a.useCallback((i,M)=>{const k=oi(M);try{wa(Tt[i],JSON.stringify(k),s)}catch{}return k},[s]),S=a.useCallback((i,M)=>{if(i==="direct"){u(k=>C(i,M(k)));return}d(k=>C(i,M(k)))},[C]),x=a.useCallback((i,M,k)=>{const T=Ca(k);if(T===null)return!1;const b=h[i][M],l=Ca(b);return l===null?!0:T>l},[h]),R=a.useCallback((i,M,k)=>{if(!M)return;const T=k??new Date().toISOString();S(i,b=>({...b,[M]:T}))},[S]),E=a.useCallback((i,M)=>{M.length!==0&&S(i,k=>{const T={...k};for(const b of M)b.id&&(T[b.id]=b.lastActivityAt??new Date().toISOString());return T})},[S]);return{isUnread:x,markRead:R,markAllRead:E}}const Fo=["",...Ji];function Bs({level:s,onChange:r,defaultThinkingLevel:u="off",showTargetSection:g=!0,models:d=[],favoriteProviders:h=[],favoriteModels:C=[],agents:S=[],agentId:x,modelProvider:R,modelId:E,onChangeModel:i,disabled:M=!1}){const{t:k}=ze("app"),[T,b]=a.useState(!1),[l,B]=a.useState(()=>x&&x!==ke?"agent":"model"),N=a.useRef(null),V=s??"",_=R&&E?`${R}/${E}`:"",K=x&&x!==ke?x:"",I=V!==""||g&&(!!_||!!K),ee="chat-thinking-level-listbox";a.useEffect(()=>{if(!T)return;const c=p=>{const y=p.target;if(!(y instanceof Node))return;const f=N.current?.contains(y),j=y instanceof Element&&!!y.closest(".model-combobox-dropdown--portal");!f&&!j&&b(!1)};return document.addEventListener("pointerdown",c),()=>document.removeEventListener("pointerdown",c)},[T]),a.useEffect(()=>{b(!1),B(K?"agent":"model")},[V,K,_]);const Z=a.useMemo(()=>S.find(c=>c.id===K),[S,K]),Y=c=>c===""?k("modelSelection.thinkingDefault","Default ({{level}})",{level:u??"off"}):k(`models.options.${c}`,c==="xhigh"?"Very High":c.charAt(0).toUpperCase()+c.slice(1)),D=c=>{b(!1),r(c)},$=c=>{const p=c.indexOf("/");p<=0||(b(!1),i?.({modelProvider:c.slice(0,p),modelId:c.slice(p+1)}))},Q=c=>{c&&(b(!1),i?.({agentId:c}))},O=c=>{B(c)},A=c=>{c.key==="Escape"&&b(!1)},H=(c,p)=>{if(c.key==="Escape"){c.preventDefault(),b(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),D(p))},le=(c,p)=>{if(c.key==="Escape"){c.preventDefault(),b(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),Q(p))};return t.jsxs("div",{className:"chat-thinking-level-root",ref:N,children:[t.jsx("button",{type:"button",className:`btn-icon chat-thinking-btn${I?" chat-thinking-btn--active":""}`,"data-testid":"chat-thinking-btn","aria-haspopup":"dialog","aria-expanded":T,"aria-controls":ee,"aria-label":k("chat.thinkingLevelButton","Thinking level"),title:k("chat.thinkingLevelButton","Thinking level"),disabled:M,onClick:()=>b(c=>!c),onKeyDown:A,children:t.jsx(Qi,{size:16})}),T?t.jsxs("div",{className:"chat-thinking-popover",role:"presentation","data-testid":"chat-thinking-popover",children:[g?t.jsxs("section",{className:"chat-thinking-target-section","aria-label":k("chat.modelAgentSection","Model / Agent"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:k("chat.modelAgentSection","Model / Agent")}),t.jsxs("div",{className:"chat-thinking-mode-toggle","data-testid":"chat-thinking-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${l==="model"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-model","aria-pressed":l==="model",onPointerDown:c=>{c.button===0&&O("model")},onClick:c=>{c.detail===0&&O("model")},children:k("chat.newChatModeModel","Model")}),t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${l==="agent"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-agent","aria-pressed":l==="agent",onPointerDown:c=>{c.button===0&&O("agent")},onClick:c=>{c.detail===0&&O("agent")},children:k("chat.newChatModeAgent","Agent")})]}),l==="model"?t.jsxs("div",{className:"chat-thinking-model-picker","data-testid":"chat-thinking-model-picker",children:[t.jsx(ti,{models:d,value:_,onChange:$,label:k("chat.newChatModeModel","Model"),placeholder:k("chat.selectModel","Select a model"),disabled:!i||d.length===0,favoriteProviders:h,favoriteModels:C,menuWidth:"readable"}),d.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-model-empty",children:k("chat.noModelsAvailable","No models available")}):null]}):t.jsx("div",{className:"chat-thinking-agent-list","data-testid":"chat-thinking-agent-list",children:S.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-agent-empty",children:k("chat.noAgentsAvailable","No agents available")}):S.map(c=>{const p=K===c.id;return t.jsxs("button",{type:"button",className:`chat-thinking-agent-item${p?" chat-thinking-agent-item--selected":""}`,"data-testid":`chat-thinking-agent-${c.id}`,"aria-pressed":p,disabled:!i,onClick:()=>Q(c.id),onKeyDown:y=>le(y,c.id),children:[t.jsx(xn,{size:16}),t.jsx("span",{className:"chat-thinking-agent-name",children:c.name||c.id}),c.role?t.jsx("span",{className:"chat-thinking-agent-role",children:c.role}):null]},c.id)})}),Z?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-agent",children:k("chat.currentAgentTarget","Current agent: {{name}}",{name:Z.name||Z.id})}):_?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-model",children:k("chat.currentModelTarget","Current model: {{model}}",{model:_})}):t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-default",children:k("chat.currentDefaultTarget","Using the default chat target")})]}):null,t.jsxs("section",{className:"chat-thinking-level-section","aria-label":k("chat.thinkingLevelButton","Thinking level"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:k("chat.thinkingLevelSection","Thinking level")}),t.jsx("div",{id:ee,className:"chat-thinking-popover-list",role:"listbox","aria-label":k("chat.thinkingLevelButton","Thinking level"),children:Fo.map(c=>{const p=V===c;return t.jsx("button",{type:"button",role:"option","aria-selected":p,className:`chat-thinking-popover-option${p?" active":""}`,"data-testid":`chat-thinking-option-${c||"default"}`,onClick:()=>D(c),onKeyDown:y=>H(y,c),children:Y(c)},c||"default")})})]})]}):null]})}function Os(s){return s.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function ri(s,r){const u=r.trim();if(!u)return!0;const g=Os(u);return Os(s).includes(g)||s.toLowerCase().includes(u.toLowerCase())}function Us({agents:s,filter:r,highlightedIndex:u,visible:g,onSelect:d,position:h="below",roomMemberIds:C,roomName:S}){const{t:x}=ze("app"),R=a.useMemo(()=>s.filter(b=>ri(b.name,r)),[s,r]),E=!!C,i=E&&r.trim().length>0,M=a.useMemo(()=>E?R.filter(b=>C?.has(b.id)):R,[R,C,E]),k=a.useMemo(()=>E?R.filter(b=>!C?.has(b.id)):[],[R,C,E]),T=i?[...M,...k]:M;return g?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${h}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":x("agentMention.suggestionsLabel","Agent mention suggestions"),children:T.length===0?t.jsx("div",{className:"agent-mention-empty",children:x("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[E&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:S?x("agentMention.membersOf","Members of #{{roomName}}",{roomName:S}):x("agentMention.roomMembers","Room members")}),M.map((b,l)=>t.jsxs("button",{type:"button",className:`agent-mention-item${l===u?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${b.id}`,onMouseDown:B=>B.preventDefault(),onClick:()=>d(b),role:"option","aria-selected":l===u,children:[t.jsx(wn,{agent:b,size:20}),E&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":x("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:b.name}),t.jsx("span",{className:"agent-mention-role",children:b.role})]},b.id)),E&&!i&&k.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:x("agentMention.typeToSearch","Type to search other agents")}),E&&i&&k.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:x("agentMention.otherAgents","Other agents")}),k.map((b,l)=>{const B=M.length+l;return t.jsxs("button",{type:"button",className:`agent-mention-item${B===u?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${b.id}`,onMouseDown:N=>N.preventDefault(),onClick:()=>d(b),role:"option","aria-selected":B===u,children:[t.jsx(wn,{agent:b,size:20}),t.jsx("span",{className:"agent-mention-name",children:b.name}),t.jsx("span",{className:"agent-mention-role",children:b.role})]},b.id)})]})]})}):null}function _o(s,r){return s+r}function $o({visible:s,position:r,tasks:u,files:g,selectedIndex:d,onSelectTask:h,onSelectFile:C,loading:S}){const{t:x}=ze("app");if(!s)return null;const R=u.length>0,E=g.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:r.top,left:r.left},"data-testid":"file-mention-popup",onMouseDown:i=>{i.preventDefault()},children:[S&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!S&&!R&&!E&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:x("fileMention.empty","No tasks or files found")}),!S&&(R||E)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[R&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:x("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":x("fileMention.taskMatches","Task matches"),children:u.map((i,M)=>{const k=M;return t.jsxs("li",{className:`file-mention-popup-item${k===d?" file-mention-popup-item--selected":""}`,onClick:()=>h(i),role:"option","aria-selected":k===d,"data-testid":`task-mention-item-${k}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(si,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsxs("div",{className:"file-mention-popup-task-row",children:[t.jsx("span",{className:"file-mention-popup-task-id",children:i.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${i.column}`,children:i.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:i.title})]})]},i.id)})})]}),E&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:x("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":x("fileMention.fileMatches","File matches"),children:g.map((i,M)=>{const k=_o(u.length,M),T=Zi(i.path);return t.jsxs("li",{className:`file-mention-popup-item${k===d?" file-mention-popup-item--selected":""}`,onClick:()=>C(i),role:"option","aria-selected":k===d,"data-testid":`file-mention-item-${k}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(eo,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:i.name}),T&&t.jsx("span",{className:"file-mention-popup-item-path",children:T})]})]},i.path)})})]})]})]})}function zo(s,r=[],u){const g=s.trim().replace(/^#/,""),d=(C,S)=>u?u(C,S):S;if(!g)return{ok:!1,error:d("createRoom.nameRequired","Room name is required.")};if(/[A-Z]/.test(g))return{ok:!1,error:d("createRoom.lowercase","Use lowercase letters only.")};const h=g.toLowerCase();return h.length>80?{ok:!1,error:d("createRoom.maxLength","Room names can be at most 80 characters.")}:/^[a-z0-9_-]+$/.test(h)?/^[-_]|[-_]$/.test(h)?{ok:!1,error:d("createRoom.noEdgeChars","Room names cannot start or end with a hyphen or underscore.")}:r.some(C=>C.toLowerCase()===h)?{ok:!1,error:d("createRoom.duplicate","A room with this name already exists.")}:{ok:!0,name:h}:{ok:!1,error:d("createRoom.validChars","Use lowercase letters, numbers, hyphens, or underscores only.")}}function Bo({isOpen:s,onClose:r,onCreate:u,projectId:g,existingRoomNames:d=[]}){const{t:h}=ze("app"),[C,S]=a.useState(""),[x,R]=a.useState([]),[E,i]=a.useState(""),[M,k]=a.useState([]),[T,b]=a.useState(!1),[l,B]=a.useState(null),[N,V]=a.useState(!1),_=a.useRef(null),K=a.useRef(null),[I,ee]=a.useState(void 0);a.useLayoutEffect(()=>{s&&ee(to())},[s]),a.useEffect(()=>{s&&(K.current=document.activeElement instanceof HTMLElement?document.activeElement:null,b(!0),B(null),no(void 0,g).then(A=>R(A)).catch(()=>{R([]),B(h("createRoom.failedLoadAgents","Failed to load agents."))}).finally(()=>b(!1)))},[s,g]),a.useEffect(()=>{if(!s){S(""),i(""),k([]),B(null),V(!1);return}const A=window.requestAnimationFrame(()=>_.current?.focus());return()=>window.cancelAnimationFrame(A)},[s]),a.useEffect(()=>{if(!s)return;const A=H=>{H.key==="Escape"&&r()};return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[s,r]),a.useEffect(()=>{s||K.current?.focus()},[s]);const Z=a.useMemo(()=>zo(C,d,h),[C,d,h]),Y=a.useMemo(()=>{const A=E.trim().toLowerCase();return A?x.filter(H=>H.name.toLowerCase().includes(A)):x},[x,E]),D=a.useMemo(()=>x.filter(A=>M.includes(A.id)),[x,M]),$=Z.ok&&M.length>0&&!N&&!T;if(!s)return null;const Q=A=>{N||k(H=>H.includes(A)?H.filter(le=>le!==A):[...H,A])},O=async()=>{if(!Z.ok){B(Z.error);return}if(M.length===0){B(h("createRoom.selectMember","Select at least one member."));return}B(null),V(!0);try{await u({name:Z.name,displayName:`#${Z.name}`,memberAgentIds:M}),r()}catch(A){B(A instanceof Error?A.message:h("createRoom.failedCreate","Failed to create room."))}finally{V(!1)}};return Bi.createPortal(t.jsx("div",{className:"modal-overlay open",onClick:A=>A.target===A.currentTarget&&r(),style:I?{zIndex:I}:void 0,children:t.jsxs("div",{className:"modal modal-lg create-room-modal",role:"dialog","aria-modal":"true","aria-label":h("createRoom.title","Create room"),onClick:A=>A.stopPropagation(),children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:h("createRoom.title","Create room")}),t.jsx("button",{type:"button",className:"modal-close","aria-label":h("actions.close","Close"),onClick:r,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:h("createRoom.nameLabel","Room name")}),t.jsxs("div",{className:"create-room-modal-name-field",children:[t.jsx("span",{"aria-hidden":"true",className:"create-room-modal-name-hash",children:"#"}),t.jsx("input",{ref:_,id:"create-room-name",className:"input",value:C,disabled:N,onChange:A=>{const H=A.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();S(H)}})]}),!Z.ok&&t.jsx("div",{className:"form-error",children:Z.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:h("createRoom.members","Members")}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:h("createRoom.searchAgents","Search agents"),value:E,disabled:N,onChange:A=>i(A.target.value)})]}),D.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:D.map(A=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>Q(A.id),disabled:N,children:[A.name," ×"]},A.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:T?t.jsx("div",{className:"create-room-modal-empty",children:t.jsx(ao,{label:h("createRoom.loadingAgents","Loading agents...")})}):Y.length===0?t.jsx("div",{className:"create-room-modal-empty",children:x.length===0?h("createRoom.noAgents","No agents in this project yet."):h("createRoom.noMatch","No agents match your search.")}):Y.map(A=>{const H=M.includes(A.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${H?" create-room-modal-member-row--selected":""}`,onClick:()=>Q(A.id),disabled:N,children:[t.jsx(wn,{agent:A,size:20}),t.jsx("span",{children:A.name}),t.jsx("span",{className:"create-room-modal-member-role",children:A.role})]},A.id)})}),l&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:l})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:N,children:h("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void O(),disabled:!$,children:N?h("createRoom.creating","Creating..."):h("createRoom.create","Create room")})]})]})}),document.body)}function Oo({cliSessionId:s,tier:r,projectId:u,renderTranscript:g,renderComposer:d,queuedCount:h=0,terminalProps:C}){const{t:S}=ze("app"),x=r==="generic",[R,E]=a.useState(x?"terminal":"transcript");if(x)return t.jsx("div",{className:"cli-chat-surface cli-chat-surface--generic","data-tier":"generic",children:t.jsx(_s,{sessionId:s,projectId:u,...C})});const i=R==="terminal";return t.jsxs("div",{className:"cli-chat-surface","data-tier":r,"data-view":R,children:[t.jsxs("div",{className:"cli-chat-surface__toolbar",role:"tablist","aria-label":S("cliChat.viewToggleLabel","Chat view"),children:[t.jsxs("button",{type:"button",role:"tab","aria-selected":!i,className:`cli-chat-surface__tab${i?"":" is-active"}`,onClick:()=>E("transcript"),children:[t.jsx(vn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:S("cliChat.transcriptTab","Transcript")})]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":i,className:`cli-chat-surface__tab${i?" is-active":""}`,onClick:()=>E("terminal"),children:[t.jsx(so,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:S("cliChat.terminalTab","Terminal")})]})]}),t.jsx("div",{className:"cli-chat-surface__body",children:i?t.jsx(_s,{sessionId:s,projectId:u,...C}):g()}),!i&&t.jsxs("div",{className:"cli-chat-surface__composer",children:[h>0&&t.jsx("div",{className:"cli-chat-surface__queued",role:"status","aria-live":"polite",children:S("cliChat.queued","{{count}} message queued — will send when the agent is ready",{count:h})}),d()]})]})}const Uo=200,Ho=8,Ko=8;function Hs(){return new DOMException("The operation was aborted.","AbortError")}function Ks(s,r){return r.aborted?Promise.reject(Hs()):new Promise((u,g)=>{const d=()=>g(Hs());r.addEventListener("abort",d,{once:!0}),s.then(h=>{r.removeEventListener("abort",d),u(h)},h=>{r.removeEventListener("abort",d),g(h)})})}function Ws(s,r,u){const g=s.slice(0,r),d=s.slice(r+1),h=d.match(/[\s]|$/),C=h?h.index??d.length:d.length,S=d.slice(C);return`${g}${u}${S}`}function Wo(s={}){const{projectId:r,workspace:u="project"}=s,[g,d]=a.useState(!1),[h,C]=a.useState(""),[S,x]=a.useState(-1),[R,E]=a.useState([]),[i,M]=a.useState([]),[k,T]=a.useState(!1),[b,l]=a.useState(0),B=a.useRef(null),N=a.useRef(null),V=[...R.map(D=>({kind:"task",task:D})),...i.map(D=>({kind:"file",file:D}))];a.useEffect(()=>()=>{B.current&&clearTimeout(B.current),N.current?.abort()},[]);const _=a.useCallback((D,$)=>{if($<0||$>D.length){d(!1);return}const Q=O=>/[a-zA-Z0-9/_.-]/.test(O);for(let O=$-1;O>=0;O--){if(D[O]==="#"){if(O===0){const H=D.slice(O+1,$);x(O),C(H),l(0),d(!0);return}const A=D[O-1];if(/[\s,.;:!?'"()[\]{}]/.test(A)){const H=D.slice(O+1,$);x(O),C(H),l(0),d(!0);return}d(!1);return}if(!Q(D[O])){d(!1);return}}d(!1)},[]),K=a.useCallback(()=>{N.current?.abort(),d(!1),C(""),x(-1),E([]),M([]),l(0),T(!1)},[]),I=a.useCallback(async D=>{if(!D.trim()){E([]),M([]),T(!1);return}N.current?.abort();const $=new AbortController;N.current=$;try{T(!0);const[Q,O]=await Promise.allSettled([Ks(io(20,0,r,D),$.signal),Ks(oo(D,u,r),$.signal)]);if($.signal.aborted)return;const A=Q.status==="fulfilled"?Q.value.slice(0,Ho).map(le=>({id:le.id,title:le.title??"",column:le.column})):[],H=O.status==="fulfilled"?O.value.files.slice(0,Ko):[];E(A),M(H),l(0)}catch(Q){Q.name!=="AbortError"&&(E([]),M([]))}finally{$.signal.aborted||T(!1)}},[u,r]);a.useEffect(()=>{if(g)return B.current&&clearTimeout(B.current),B.current=setTimeout(()=>{I(h)},Uo),()=>{B.current&&clearTimeout(B.current)}},[h,g,I]);const ee=a.useCallback((D,$)=>!g||S<0?$:Ws($,S,`#${D.id}`),[g,S]),Z=a.useCallback((D,$)=>!g||S<0?$:Ws($,S,`#${D.path}`),[g,S]),Y=a.useCallback((D,$)=>{if(!g||V.length===0)return!1;switch(D.key){case"ArrowDown":return D.preventDefault(),l(Q=>Math.min(Q+1,V.length-1)),!0;case"ArrowUp":return D.preventDefault(),l(Q=>Math.max(Q-1,0)),!0;case"Enter":case"Tab":return V[b]?(D.preventDefault(),!0):!1;case"Escape":return D.preventDefault(),K(),!0;default:return!1}},[g,V,b,K]);return{mentionActive:g,tasks:R,files:i,combinedItems:V,loading:k,mentionQuery:h,selectedIndex:b,setSelectedIndex:l,detectMention:_,selectTask:ee,selectFile:Z,dismissMention:K,handleKeyDown:Y}}const ga=new Map,bn=new Map;function Ma(s){return s??"global"}function Sa(s){return`${Et.DISCOVERED_SKILLS_PREFIX}${Ma(s)}`}function pt(s){return bt(Sa(s),{maxAgeMs:xa})}function Vo(s,r){for(const u of bn.get(s)??[])u(r)}async function Xo(s){const r=Ma(s),u=ga.get(r);if(u)return u;const g=co(s).finally(()=>{ga.delete(r)});return ga.set(r,g),g}function qo(s){const[r,u]=a.useState(()=>pt(s)??[]),[g,d]=a.useState(()=>pt(s)===null),h=a.useRef(pt(s)!==null),C=Ma(s);a.useEffect(()=>{const R=pt(s)??[];u(R),d(pt(s)===null),h.current=pt(s)!==null},[s]),a.useEffect(()=>{const R=bn.get(C)??new Set;return R.add(u),bn.set(C,R),()=>{R.delete(u),R.size===0&&bn.delete(C)}},[C]);const S=a.useCallback(async()=>{try{const R=await Xo(s);h.current=!0,X(Sa(s),R,{maxBytes:5e5}),Vo(C,R)}catch{h.current||ro(Sa(s))}finally{d(!1)}},[s,C]);a.useEffect(()=>{S()},[S]);const x=a.useCallback(async()=>{d(!0),await S()},[S]);return{skills:r,loading:g,refresh:x}}function Go(s,r){const u=s.reduce((g,d)=>g+(d.content?.length??0),0)+(r?.length??0);return Math.ceil(u/4)}function Vs(s){if(!Number.isFinite(s)||s<=0)return"0";if(s<1e3)return String(Math.round(s));const r=s/1e3;return r<10?`~${Number(r.toFixed(1))}k`:`${Math.round(r)}k`}const Na=640,Yo=200,Qo=200,vt=8;function pr(s){const r=s.trim();return r?`${r}
|
|
12
12
|
|
|
13
|
-
`:""}function Zo(s,r,u,g,d,h,C){const S=Math.max(vt,h-g-vt),x=Math.max(vt,C-d-vt),R=u?s-g:s;return{x:Math.min(Math.max(vt,R),S),y:Math.min(Math.max(vt,r),x)}}const Xs="__SKIP__";let pa=!1;function Jo(s,r=Na){return s>r?"auto":"hidden"}function er(s,r=Na){return Math.max(40,Math.min(s,r))}function tr(s,r){const u=new Date(s),d=new Date().getTime()-u.getTime(),h=Math.floor(d/1e3),C=Math.floor(h/60),S=Math.floor(C/60),x=Math.floor(S/24);return h<60?r("chat.relativeTimeJustNow","just now"):C<60?r("chat.relativeTimeMinutes","{{count}}m ago",{count:C}):S<24?r("chat.relativeTimeHours","{{count}}h ago",{count:S}):x<7?r("chat.relativeTimeDays","{{count}}d ago",{count:x}):u.toLocaleDateString()}const nr=280,gn=180,pn=500,qs="fusion:chat-sidebar-width",va="fusion:chat-scope",ar="fusion:chat-draft:";function Gs(s,r){return s.slice(r+1).find(u=>u.role==="user")?.content}function Ys(s,r){return r?`${ar}${s}:${r}`:null}function Qs(s){if(!s)return"";try{return localStorage.getItem(s)??""}catch{return""}}const sr=["image/png","image/jpeg","image/gif","image/webp","video/mp4","video/webm","video/quicktime","text/plain","text/markdown","application/json","text/yaml","text/x-toml","text/csv","application/xml"],Zs="image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm,video/quicktime,.txt,.md,.json,.yaml,.yml,.toml,.csv,.xml",ba=Ro;function ir(s,r){const u=s.slice(0,r),g=/(^|[\s\n])@([\w-]*)$/.exec(u);if(!g)return null;const d=g[2]??"",h=u.length-d.length-1;return{filter:d,start:h,end:r}}function or(s){const r=s?.runtimeConfig;if(!r||typeof r!="object")return null;const u=Reflect.get(r,"modelProvider"),g=Reflect.get(r,"modelId");return typeof u!="string"||u.trim().length===0||typeof g!="string"||g.trim().length===0?null:{provider:u,modelId:g}}function Js(s,r,u){if(s?.modelProvider&&s?.modelId)return{provider:s.modelProvider,modelId:s.modelId};const g=or(r??void 0);return g||(u.provider&&u.modelId?{provider:u.provider,modelId:u.modelId}:null)}function rr({projectId:s,defaultModel:r,defaultKind:u,defaultAgentId:g,defaultThinkingLevel:d,defaultSelectedThinkingLevel:h,onClose:C,onCreate:S}){const{t:x}=ze("app"),[R,E]=a.useState(u??"agent"),{agents:i,loading:M}=ni(s),[k,T]=a.useState(g??""),{models:b,favoriteProviders:l,favoriteModels:B,loading:N,refresh:W}=ai(),$=r.provider&&r.modelId?`${r.provider}/${r.modelId}`:"",[K,I]=a.useState($),[ee,J]=a.useState(h??""),[Y,D]=a.useState(l),[_,Q]=a.useState(B);a.useEffect(()=>{D(l)},[l]),a.useEffect(()=>{Q(B)},[B]),a.useEffect(()=>{u&&E(u)},[u]),a.useEffect(()=>{g&&T(p=>p||g)},[g]),a.useEffect(()=>{$&&I(p=>p||$)},[$]),a.useEffect(()=>{h&&J(p=>p||h)},[h]);const O=a.useCallback(async p=>{const y=Y,j=y.includes(p)?y.filter(F=>F!==p):[p,...y];D(j);try{await Fs({favoriteProviders:j,favoriteModels:_}),await W()}catch{D(y)}},[Y,_,W]),A=a.useCallback(async p=>{const y=_,j=y.includes(p)?y.filter(F=>F!==p):[p,...y];Q(j);try{await Fs({favoriteProviders:Y,favoriteModels:j}),await W()}catch{Q(y)}},[_,Y,W]),H=K||$,le=p=>{if(p.preventDefault(),R==="agent"){if(!k)return;S({agentId:k});return}if(!H)return;const y=H.indexOf("/");if(y<=0)return;const f=H.slice(0,y),j=H.slice(y+1);S({agentId:ke,modelProvider:f,modelId:j,thinkingLevel:ee||void 0})},c=R==="agent"?!k:!H;return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:C,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:p=>p.stopPropagation(),children:[t.jsx("h3",{children:x("chat.newChatTitle","New Chat")}),t.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${R==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{E("agent")},children:x("chat.newChatModeAgent","Agent")}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${R==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{E("model"),T(""),I(p=>p||$)},children:x("chat.newChatModeModel","Model")})]}),t.jsxs("form",{onSubmit:le,children:[R==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:[x("chat.newChatModeAgent","Agent"),M?t.jsx("div",{className:"chat-new-dialog-loading",children:x("chat.loadingAgents","Loading agents...")}):i.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:x("chat.noAgentsAvailable","No agents available")}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:i.map(p=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${k===p.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>T(p.id),"data-testid":`agent-option-${p.id}`,children:[t.jsx(xn,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:p.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:p.role})]},p.id))})]}),R==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:N?t.jsx("div",{className:"chat-new-dialog-loading",children:x("chat.loadingModels","Loading models...")}):t.jsx(ti,{models:b,value:K,onChange:I,label:x("chat.newChatModeModel","Model"),placeholder:x("chat.selectModel","Select a model"),favoriteProviders:Y,onToggleFavorite:O,favoriteModels:_,onToggleModelFavorite:A,showThinkingLevel:!0,thinkingLevel:ee,onThinkingLevelChange:J,defaultThinkingLevel:d??"off"})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:C,children:x("chat.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:c,children:x("chat.create","Create")})]})]})]})})}function vr({projectId:s,addToast:r,floating:u=!1,compactLayout:g=!1,onPopOut:d,onMaximize:h,onMinimize:C,onClose:S,chatCommandContext:x,initialComposerDraft:R,initialComposerDraftNonce:E}){const{t:i}=ze("app");a.useEffect(()=>(ya({view:"ChatView",trigger:pa?"route-active":"remount",projectId:s,replayAttempted:!1}),pa=!1,()=>{pa=!0,ya({view:"ChatView",trigger:"route-inactive",projectId:s,replayAttempted:!1})}),[s]);const[M,k]=a.useState(null);a.useEffect(()=>{let e=!1;return k(null),lo(s).then(n=>{e||k(n)}).catch(()=>{e||k(null)}),()=>{e=!0}},[s]);const T=M?.defaultThinkingLevel??"off",b=a.useMemo(()=>M?.chatDefaultKind==="agent"&&M.chatDefaultAgentId?{kind:"agent",agentId:M.chatDefaultAgentId}:M?.chatDefaultKind==="model"&&M.chatDefaultModelProvider&&M.chatDefaultModelId?{kind:"model",modelProvider:M.chatDefaultModelProvider,modelId:M.chatDefaultModelId,thinkingLevel:M.chatDefaultThinkingLevel}:null,[M]),{activeSession:l,sessionsLoading:B,messages:N,messagesLoading:W,isStreaming:$,streamingText:K,streamingThinking:I,streamingToolCalls:ee,selectSession:J,createSession:Y,archiveSession:D,renameSession:_,pinSession:Q,pinnedCount:O,setSessionModel:A,setSessionThinkingLevel:H,deleteSession:le,tags:c=[],selectedTagId:p,setSelectedTagId:y,createTag:f,renameTag:j,deleteTag:F,setSessionTags:Z,sendMessage:ge,editMessageAndResend:ae,stopStreaming:de,pendingMessages:Ie,clearPendingMessage:ue,loadMoreMessages:Le,hasMoreMessages:pe,searchQuery:qe,setSearchQuery:ci,filteredSessions:Pe,agentsMap:yn}=uo(s,r),[li,kn]=a.useState(!1),Be=!0,[L,Ge]=a.useState(()=>{try{if(localStorage.getItem(va)==="rooms"&&Be)return"rooms"}catch{}return"direct"}),w=Lo(s,r),{isUnread:Ra,markRead:he}=Po(s),[q,re]=a.useState(()=>{const e=Ys(L,L==="rooms"?w.activeRoom?.id:l?.id);return Qs(e)}),[G,Ce]=a.useState(null),Cn=a.useRef(null),ja=(e,n,o,m)=>{typeof window>"u"||Ce({sessionId:e,anchorX:n,anchorY:o,anchorRight:m?.anchorRight??!1,x:n,y:o})};a.useLayoutEffect(()=>{if(!G||!Cn.current||typeof window>"u")return;const e=Cn.current,n=e.getBoundingClientRect(),o=n.width||e.offsetWidth||Qo,m=n.height||e.offsetHeight,v=Zo(G.anchorX,G.anchorY,G.anchorRight,o,m,window.innerWidth,window.innerHeight);(v.x!==G.x||v.y!==G.y)&&Ce({...G,...v})},[G]);const[It,Lt]=a.useState(null),[Sn,Mn]=a.useState(""),[Aa,Pt]=a.useState(null),[Ta,Ft]=a.useState(null),[Nn,Ea]=a.useState(""),[Rn,xt]=a.useState(null),[jn,Da]=a.useState(""),[Ia,$t]=a.useState(null),[wt,Oe]=a.useState(!0),[Ye,An]=a.useState(nr),[di,_t]=a.useState(!1),{agentsMap:La}=ni(s),be=a.useMemo(()=>yn.size>0?yn:La,[La,yn]),{models:Tn,favoriteProviders:ui,favoriteModels:mi,defaultProvider:Pa,defaultModelId:Fa}=ai(),zt=a.useMemo(()=>({provider:Pa,modelId:Fa}),[Fa,Pa]),hi=a.useMemo(()=>b?.kind==="model"?{provider:b.modelProvider,modelId:b.modelId}:zt,[b,zt]),{skills:En,loading:fi}=qo(s),[Qe,Ue]=a.useState(!1),[yt,kt]=a.useState(""),[Ze,He]=a.useState(0),[Je,et]=a.useState(""),[Se,tt]=a.useState(!1),[Bt,Ot]=a.useState(0),[Dn,nt]=a.useState(-1),[ve,at]=a.useState([]),[$a,st]=a.useState(!1),[_a,Ut]=a.useState(!1),[it,za]=a.useState({}),[Ht,Me]=a.useState(!1),[Kt,Ct]=a.useState(!1),{pushNav:Ba}=mo(),[,Vt]=a.useState(!1),[gi,pi]=a.useState({top:0,left:0}),V=Vo({projectId:s}),In=a.useCallback(e=>{if(!e||!V.mentionActive)return;const n=e.getBoundingClientRect();pi({top:n.top-260,left:n.left+8})},[V.mentionActive]),Oa=a.useRef(null),Ua=a.useRef(null),Ha=a.useRef(null),Ka=a.useRef(null),me=a.useRef(!1),Wt=a.useRef(null),Va=a.useRef(null),Fe=a.useRef(null),Xt=a.useRef(0),Ln=a.useRef(null),St=a.useRef(null),Ne=a.useRef(null),ce=a.useRef(null),Pn=a.useRef(null),ot=a.useRef(null),[Fn,vi]=a.useState(()=>new Set),qt=a.useRef(!1),Re=a.useRef(null),je=a.useRef(null),te=a.useRef(null),Gt=a.useRef(null),Wa=a.useRef(void 0),$n=a.useRef(!1),Yt=a.useRef(null),Xa=a.useRef([]),rt=a.useRef(0),Mt=a.useRef(new Map),_n=a.useRef(!1),Qt=ho(),Ke=Qt==="mobile",zn=Qt==="tablet",qa=a.useRef(null),[bi,Ga]=a.useState(!1);a.useLayoutEffect(()=>{if(!u){Ga(!1);return}const e=qa.current;if(!e||typeof ResizeObserver>"u")return;const n=()=>{Ga(e.getBoundingClientRect().width<=768)};n();const o=new ResizeObserver(n);return o.observe(e),()=>o.disconnect()},[u]);const z=Ke||bi||g;a.useEffect(()=>{l?.id&&he("direct",l.id,l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,he]),a.useEffect(()=>{w.activeRoom?.id&&he("room",w.activeRoom.id,w.activeRoom.updatedAt)},[w.activeRoom?.id,w.activeRoom?.updatedAt,he]),a.useEffect(()=>{if(!l?.id||N.length===0)return;const e=N[N.length-1];he("direct",l.id,e?.createdAt??l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,he,N]),a.useEffect(()=>{if(!w.activeRoom?.id||w.messages.length===0)return;const e=w.messages[w.messages.length-1];he("room",w.activeRoom.id,e?.createdAt??w.activeRoom.updatedAt)},[he,w.activeRoom?.id,w.activeRoom?.updatedAt,w.messages]),a.useEffect(()=>{try{const e=localStorage.getItem(qs);if(!e)return;const n=Number.parseInt(e,10);if(Number.isNaN(n))return;const o=Math.max(gn,Math.min(pn,n));An(o)}catch{}},[]),a.useEffect(()=>{try{const e=localStorage.getItem(va);if(e==="direct"){Ge("direct");return}e==="rooms"&&Be&&Ge("rooms")}catch{}},[Be]),a.useEffect(()=>{try{localStorage.setItem(va,L)}catch{}},[Be,L]);const fe=Ys(L,L==="rooms"?w.activeRoom?.id:l?.id),Bn=a.useRef(fe),On=a.useRef(!1);a.useEffect(()=>{if(fe!==Bn.current){if(Bn.current=fe,On.current){On.current=!1;return}re(Qs(fe))}},[fe]),a.useEffect(()=>{if(!(!fe||Bn.current!==fe))try{if(q){localStorage.setItem(fe,q);return}localStorage.removeItem(fe)}catch{}},[fe,q]);const se=L==="rooms"&&!!w.activeRoom,{keyboardOverlap:Ya,keyboardOpen:Zt}=fo({enabled:(z||zn)&&(!!l||se),allowNonMobileViewport:zn}),Nt=zn&&Zt,Jt=a.useMemo(()=>{const e=yt.trim().toLowerCase();return(e?En.filter(o=>o.name.toLowerCase().includes(e)):En).slice(0,10)},[En,yt]),Un=a.useMemo(()=>x?go(yt,Ps):[],[x,yt]),xe=a.useMemo(()=>{const e=Un.map(o=>({kind:"command",command:o,disabled:!x?.agentRunning})),n=Jt.map(o=>({kind:"skill",skill:o}));return[...e,...n]},[Un,Jt,x]),ct=a.useMemo(()=>Array.from(be.values()),[be]),Ae=a.useMemo(()=>L!=="rooms"||!w.activeRoom?null:{roomId:w.activeRoom.id,roomName:w.activeRoom.name,memberIds:new Set(w.activeRoomMembers.map(e=>e.agentId))},[Be,L,w.activeRoom,w.activeRoomMembers]),Ve=a.useMemo(()=>{const e=ct.filter(m=>ri(m.name,Je));if(!Ae)return e;const n=e.filter(m=>Ae.memberIds.has(m.id));if(Je.trim().length===0)return n;const o=e.filter(m=>!Ae.memberIds.has(m.id));return[...n,...o]},[ct,Je,Ae]),Hn=a.useMemo(()=>{const e=new Map;for(const n of ct)e.set(n.name.toLowerCase(),n);return e},[ct]),xi=a.useMemo(()=>Jt.map(e=>e.id).join("\0"),[Jt]);a.useEffect(()=>{He(0)},[xi]),a.useEffect(()=>{Ot(0)},[Je,Se]),a.useEffect(()=>()=>{Ne.current!==null&&window.clearTimeout(Ne.current)},[]),a.useEffect(()=>{const e=Ua.current;if(!e||!pe||W)return;const n=new IntersectionObserver(o=>{o[0].isIntersecting&&Le()},{threshold:.1});return n.observe(e),()=>n.disconnect()},[pe,W,Le]);const lt=a.useCallback(()=>se?w.activeRoom?.id??null:l?.id??null,[se,w.activeRoom?.id,l?.id]),Qa=a.useCallback((e,n)=>typeof CSS<"u"&&typeof CSS.escape=="function"?e.querySelector(`.chat-message[data-message-id="${CSS.escape(n)}"]`):e.querySelector(`.chat-message[data-message-id="${n.replace(/"/g,'\\"')}"]`),[]),Za=a.useCallback(()=>{const e=ce.current;if(!e)return;const n=e.getBoundingClientRect().top,o=new Set;e.querySelectorAll(".chat-message--assistant:not(.chat-message--failure)[data-message-id]").forEach(m=>{const v=m.getAttribute("data-message-id");v&&m.getBoundingClientRect().top<n&&o.add(v)}),vi(m=>m.size===o.size&&Array.from(m).every(v=>o.has(v))?m:o)},[]),en=a.useCallback(()=>{!ce.current||ot.current!==null||(ot.current=window.requestAnimationFrame(()=>{ot.current=null,Za()}))},[Za]),tn=a.useCallback(()=>{const e=ce.current,n=lt();if(!e||!n)return;const o=e.scrollTop,m=e.querySelectorAll(".chat-message[data-message-id]"),v=Array.from(m).find(U=>U.offsetTop+U.offsetHeight>=o)??m[0]??null,P=v?.getAttribute("data-message-id")??null,ne=v?v.offsetTop-o:0;St.current={threadId:n,scrollTop:o,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,anchorMessageId:P,anchorOffset:ne,wasPinnedBefore:!me.current,capturedAtMs:typeof performance<"u"?performance.now():Date.now()}},[lt]),Ja=a.useCallback(()=>{const e=ce.current;if(!e)return;const o=e.scrollTop+e.clientHeight>=e.scrollHeight-50;Ut(!o),me.current=!o,tn(),en()},[tn,en]),Te=a.useCallback((e,n)=>{if(!e.isConnected||!n?.force&&me.current)return;let o=0,m=0,v=-1;const P=6,ne=()=>{if(e.isConnected&&!(!n?.force&&me.current)){if(e.scrollTop=e.scrollHeight,e.scrollHeight===v?m+=1:(m=0,v=e.scrollHeight),o+=1,o>=P||m>=2){Ut(!1),me.current=!1;return}window.requestAnimationFrame(ne)}};ne()},[]),dt=se?w.messages:N;a.useLayoutEffect(()=>(en(),()=>{ot.current!==null&&(window.cancelAnimationFrame(ot.current),ot.current=null)}),[dt,en]),a.useLayoutEffect(()=>{const e=ce.current,n=lt(),o=St.current;if(!e||!n||!o||o.threadId!==n||o.wasPinnedBefore)return;const m=(typeof performance<"u"?performance.now():Date.now())-o.capturedAtMs,v=e.scrollHeight>e.clientHeight,P=m>3e3,ne=o.scrollTop<=0&&o.anchorOffset<=0&&v;if(!me.current||P||ne){St.current=null;return}let U=o.scrollTop;if(o.anchorMessageId){const oe=Qa(e,o.anchorMessageId);oe?U=oe.offsetTop-o.anchorOffset:U=o.scrollTop+(e.scrollHeight-o.scrollHeight)}else U=o.scrollTop+(e.scrollHeight-o.scrollHeight);e.scrollTop=Math.max(0,U),me.current=!0,Ut(!0),St.current=null},[dt,lt,Qa]);const Kn=a.useCallback(e=>{},[dt.length,se]),we=a.useCallback(e=>{Kn(e);const n=ce.current;n&&(St.current=null,me.current=!1,Te(n))},[Te,Kn]);a.useLayoutEffect(()=>{Fe.current!==null&&(window.clearTimeout(Fe.current),Fe.current=null);const e=se?w.activeRoom?.id??null:l?.id??null;if(!e){Wt.current=null;return}const n={threadId:e,loaded:se?!w.messagesLoading:!W,hasMessages:se?w.messages.length>0:N.length>0},o=Wt.current,m=o?.threadId!==e,v=o?.threadId===e&&!o.loaded&&n.loaded,P=o?.threadId===e&&!o.hasMessages&&n.hasMessages;if(!(o===null||m||v||P))return;const U=ce.current;if(U)return Kn(m?"thread-change":v?"finished-loading":P?"first-messages":"mount"),Te(U,{force:!0}),se||(Fe.current=window.setTimeout(()=>{if(Fe.current=null,me.current)return;const oe=ce.current;oe&&Te(oe)},250)),Wt.current=n,()=>{Fe.current!==null&&(window.clearTimeout(Fe.current),Fe.current=null)}},[se,w.activeRoom?.id,w.messages.length,w.messagesLoading,l?.id,N.length,W,Te]),a.useEffect(()=>{!$||me.current||we("streaming")},[$,K,I,we]),a.useEffect(()=>{const e=lt();if(!e){Xt.current=0,Ln.current=null;return}if(Ln.current!==e){Ln.current=e,Xt.current=dt.length;return}const n=Xt.current,o=dt.length,m=o>n,v=!me.current;Xt.current=o,m&&v&&we("new-message")},[dt,lt,we]),a.useEffect(()=>{Ya<=0||!ce.current||we("keyboard")},[Ya,we]),po(Ke&&Zt),a.useLayoutEffect(()=>{if(!Ke||!l&&!se||typeof window>"u")return;const e=Pn.current,n=window.visualViewport;if(!e||!n)return;const o=v=>{if(!(v instanceof HTMLElement))return!1;if(v.tagName==="TEXTAREA")return!0;if(v.tagName!=="INPUT")return!1;const P=v.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(P)},m=()=>{if(qt.current){e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange="";return}const v=Math.max(0,window.innerHeight-n.offsetTop-n.height),P=n.offsetTop||0;e.style.setProperty("--vv-height",`${n.height}px`),e.style.setProperty("--vv-offset-top",`${P}px`),e.style.setProperty("--keyboard-overlap",`${v}px`);const ne=(v>0||P>0)&&o(document.activeElement);e.classList.toggle("chat-thread--keyboard-active",ne),e.style.setProperty("--chat-keyboard-accessory-clearance",ne&&ma()?"calc(var(--space-2xl) + var(--space-md))":"0px"),ne&&P>0?(e.style.transform=`translateY(${P}px)`,e.style.willChange="transform"):(e.style.transform="",e.style.willChange="")};return m(),n.addEventListener("resize",m),n.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),window.addEventListener("pageshow",m),document.addEventListener("visibilitychange",m),()=>{n.removeEventListener("resize",m),n.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),window.removeEventListener("pageshow",m),document.removeEventListener("visibilitychange",m),e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange=""}},[l,Ke,se]),a.useEffect(()=>{const e=()=>Ce(null);if(G)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[G]),a.useEffect(()=>{if(!Ke||!Zt)return;const e=n=>{n.target?.closest(".chat-messages")||n.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[Ke,Zt]),a.useEffect(()=>{const e=Va.current;if(Va.current=L,L==="rooms"&&!w.activeRoom){Wt.current=null;return}if(!(L==="direct"&&(e===null||e==="rooms"))&&!(L==="rooms"&&(e===null||e==="direct")))return;const m=ce.current;m&&(Te(m,{force:!0}),me.current=!1,Ut(!1))},[L,w.activeRoom,Te]),a.useEffect(()=>{if(!l&&!se||se&&!z)return;const e=()=>{const o=!me.current;tn(),o&&z&&ce.current&&we("visibility-restore")},n=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pageshow",e)}},[z,Ke,l,se,tn,we]),a.useEffect(()=>{if(se||typeof ResizeObserver>"u")return;const e=ce.current;if(!e)return;const n=new ResizeObserver(()=>{me.current||Te(e)});return n.observe(e),()=>{n.disconnect()}},[se,Te,l?.id,L]),a.useEffect(()=>{Xa.current=ve},[ve]),a.useEffect(()=>()=>{for(const e of Xa.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of Mt.current.values())window.clearTimeout(e);Mt.current.clear()},[]);const ut=a.useCallback(e=>{if(!e||e.length===0)return;const n=[];for(const o of Array.from(e)){if(!sr.includes(o.type))continue;const m=o.type.startsWith("image/");n.push({file:o,previewUrl:m?URL.createObjectURL(o):""})}n.length>0&&at(o=>[...o,...n])},[]),es=a.useCallback(e=>{at(n=>{const o=n[e];return o?.previewUrl&&URL.revokeObjectURL(o.previewUrl),n.filter((m,v)=>v!==e)})},[]),ts=a.useCallback(e=>{ut(e.clipboardData?.files)},[ut]),mt=a.useCallback(async e=>{try{return await Y(e),kn(!1),z&&Oe(!1),!0}catch{return r(i("chat.failedToCreateSession","Failed to create chat session"),"error"),!1}},[Y,r,z,i]),nn=a.useCallback(()=>{if(M?.chatNewSessionMode==="always-default"&&b){if(b.kind==="agent"){mt({agentId:b.agentId});return}mt({agentId:ke,modelProvider:b.modelProvider,modelId:b.modelId,thinkingLevel:b.thinkingLevel});return}kn(!0)},[b,M?.chatNewSessionMode,mt]),ie=a.useCallback(e=>{const n=e??te.current;if(!n)return;const o=Qt==="tablet"?Yo:Na;n.style.height="auto",n.style.height=`${er(n.scrollHeight,o)}px`,n.style.overflowY=Jo(n.scrollHeight,o)},[Qt]),wi=Ns({textareaRef:te,value:q,onChange:re,onResize:()=>ie(te.current),projectId:s}),yi=Ns({textareaRef:Gt,value:q,onChange:re,onResize:()=>ie(Gt.current),projectId:s}),ki=a.useCallback(e=>{te.current=e,e&&ie(e)},[ie]),Ci=a.useCallback(e=>{Gt.current=e,e&&ie(e)},[ie]);a.useLayoutEffect(()=>{ie(L==="rooms"?Gt.current:te.current),$n.current&&($n.current=!1,te.current?.focus())},[L,q,l?.id,w.activeRoom?.id,ie]),a.useEffect(()=>{if(E===void 0||E===Wa.current||!R?.trim())return;Wa.current=E;const e=n=>{n&&(On.current=!0),Ge("direct"),$n.current=!0,re(R)};if(!$&&M?.chatNewSessionMode==="always-default"&&b){const n=b.kind==="agent"?{agentId:b.agentId}:{agentId:ke,modelProvider:b.modelProvider,modelId:b.modelId,thinkingLevel:b.thinkingLevel};mt(n).then(o=>e(o||L!=="direct"));return}e(L!=="direct")},[b,L,M?.chatNewSessionMode,mt,R,E,$,ie]);const ht=a.useCallback(()=>{if(re(""),fe)try{localStorage.removeItem(fe)}catch{}Ue(!1),kt(""),tt(!1),et(""),nt(-1),at(e=>{for(const n of e)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);return[]})},[fe]),Vn=a.useCallback(()=>{const e=q.trim(),n=ve.map(m=>m.file);if(!e&&n.length===0||!l)return;if(x){const m=vo(e,Ps);if(m){if(!x.agentRunning){r(i("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}if(n.length>0){r(i("chat.commandNoAttachments","Attachments aren't supported with commands — remove them before sending"),"warning");return}ht(),m.command.run({taskId:x.taskId,projectId:x.projectId,remainder:m.remainder}).then(()=>{r(i("chat.commandSteerSuccess","Sent to the running agent"),"success")}).catch(v=>{const P=v instanceof Error&&v.message.trim()?v.message:i("chat.commandSteerFailed","Failed to send to the running agent");r(P,"error")});return}}if(e==="/clear"||e==="/new"){if(l.agentId.startsWith(bo)){ht(),r(i("chat.newNotAllowedForTaskChat","This chat is tied to a task — /new and /clear can't clear it"),"warning");return}ht(),ue(),de(),Y({agentId:l.agentId,modelProvider:l.modelProvider??void 0,modelId:l.modelId??void 0,thinkingLevel:l.thinkingLevel??void 0}).catch(()=>{r(i("chat.failedToClearConversation","Failed to clear conversation"),"error")});return}const o=new Set(n);re("");try{ge(e,n,{onDelivered:()=>{at(m=>{for(const v of m)o.has(v.file)&&v.previewUrl&&URL.revokeObjectURL(v.previewUrl);return m.filter(v=>!o.has(v.file))})},onFailed:()=>{re(m=>m||e)}})}catch{re(e)}},[q,ve,l,ht,de,ue,Y,r,ge,x,i]),Wn=a.useCallback(async()=>{const e=q.trim(),n=ve.map(o=>o.file);if(!(!e&&n.length===0)){if(L==="rooms"){if(!w.activeRoom)return;if(e==="/clear"||e==="/new"){ht();try{await w.clearRoom(w.activeRoom.id)}catch{r(i("chat.failedToClearRoomConversation","Failed to clear room conversation"),"error")}return}if(_n.current)return;_n.current=!0;const o=q,m=new Set(n);re("");try{await w.sendRoomMessage(e,{files:n}),at(v=>{for(const P of v)m.has(P.file)&&P.previewUrl&&URL.revokeObjectURL(P.previewUrl);return v.filter(P=>!m.has(P.file))})}catch(v){if(v instanceof ii){at(U=>{for(const oe of U)m.has(oe.file)&&oe.previewUrl&&URL.revokeObjectURL(oe.previewUrl);return U.filter(oe=>!m.has(oe.file))});const ne=v.message.trim()?v.message:i("chat.messageSentButReplyFailed","Message sent, but assistant reply failed");r(i("chat.messageSentButReplyFailedDetail","Message sent, but assistant reply failed: {{detail}}",{detail:ne}),"error");return}re(o);const P=v instanceof Error&&v.message.trim()?v.message:i("chat.failedToSendRoomMessage","Failed to send room message");r(P,"error")}finally{_n.current=!1}return}Vn()}},[q,ve,Be,L,w,w.clearRoom,ht,r,Vn]),an=a.useCallback(async e=>{if(L==="rooms"){if(!w.activeRoom)return;try{await w.sendRoomMessage(e)}catch(n){const o=n instanceof Error&&n.message.trim()?n.message:i("chat.failedToSendRoomMessage","Failed to send room message");r(o,"error")}return}l&&ge(e)},[l,r,Be,L,w,ge,i]),Xn=a.useCallback(e=>{re(n=>{const o=ba(n);if(!o)return n;const m=`/skill:${e.name} `,v=n.slice(0,o.start)+m+n.slice(o.end);return window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus())}),v}),Ue(!1),kt(""),He(0)},[ie]),qn=a.useCallback((e,n)=>{if(n){r(i("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}re(o=>{const m=ba(o);if(!m)return o;const v=`${e.trigger} `,P=o.slice(0,m.start)+v+o.slice(m.end);return window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus())}),P}),Ue(!1),kt(""),He(0)},[ie,r,i]),sn=a.useCallback(e=>{const n=te.current;if(!n||Dn<0)return;const o=n.selectionStart??rt.current,m=n.selectionEnd??o,v=Math.max(o,m),P=Math.min(Dn,v),U=`${`@${e.name.replace(/\s+/g,"_")}`} `,oe=q.slice(0,P)+U+q.slice(v),ft=P+U.length;re(oe),tt(!1),et(""),Ot(0),nt(-1),window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus(),te.current.setSelectionRange(ft,ft))})},[Dn,q,ie]),Rt=a.useCallback((e,n)=>{const m=te.current?.selectionStart??rt.current,v=q.lastIndexOf("#",m),P=v>=0?v+n.length:e.length;re(e),V.dismissMention(),Vt(!1),window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus(),te.current.setSelectionRange(P,P))})},[V,q,ie]),ns=a.useCallback(e=>{if(rt.current=e.currentTarget.selectionStart??rt.current,V.mentionActive&&V.combinedItems.length>0){if(V.handleKeyDown(e,q),e.key==="Enter"||e.key==="Tab"){const n=V.combinedItems[V.selectedIndex];n?.kind==="task"?Rt(V.selectTask(n.task,q),`#${n.task.id}`):n?.kind==="file"&&Rt(V.selectFile(n.file,q),`#${n.file.path}`)}return}if(Se&&e.key==="ArrowDown"){e.preventDefault(),Ve.length>0&&Ot(n=>(n+1)%Ve.length);return}if(Se&&e.key==="ArrowUp"){e.preventDefault(),Ve.length>0&&Ot(n=>n===0?Ve.length-1:n-1);return}if(Se&&e.key==="Enter"){e.preventDefault();const n=Ve[Bt]??Ve[0];n&&sn(n);return}if(Se&&e.key==="Escape"){e.preventDefault(),tt(!1),et(""),nt(-1);return}if(Qe&&e.key==="ArrowDown"){e.preventDefault(),xe.length>0&&He(n=>(n+1)%xe.length);return}if(Qe&&e.key==="ArrowUp"){e.preventDefault(),xe.length>0&&He(n=>n===0?xe.length-1:n-1);return}if(Qe&&(e.key==="Enter"||e.key==="Tab")&&xe.length>0){e.preventDefault();const n=xe[Ze]??xe[0];n?.kind==="skill"?Xn(n.skill):n?.kind==="command"&&qn(n.command,n.disabled);return}if(Qe&&e.key==="Escape"){e.preventDefault(),Ue(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Wn())},[Se,Ve,Bt,sn,Qe,xe,Ze,Xn,qn,Wn,V,Rt,q]),on=a.useCallback((e,n)=>{const o=ir(e,n);if(o){tt(!0),et(o.filter),nt(o.start);return}tt(!1),et(""),nt(-1)},[]),as=a.useCallback(e=>{const n=e.target,o=n.value,m=n.selectionStart??o.length;ie(n),rt.current=m,re(o);const v=ba(o);v?(Ue(!0),kt(v.filter)):(Ue(!1),kt("")),on(o,m),V.detectMention(o,m),Vt(V.mentionActive),V.mentionActive&&In(n)},[on,ie]),rn=a.useCallback(e=>{const n=e.currentTarget,o=n.selectionStart??n.value.length;rt.current=o,on(n.value,o),V.detectMention(n.value,o),Vt(V.mentionActive),V.mentionActive&&In(n)},[on,V,In]),ss=a.useCallback(e=>{e.key!=="Escape"&&rn(e)},[rn]),is=a.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(qt.current=!0,Re.current!==null&&window.clearTimeout(Re.current),Re.current=window.setTimeout(()=>{qt.current=!1,Re.current=null},450),(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0),je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{je.current=null,document.activeElement?.tagName!=="TEXTAREA"&&(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},350)),Ne.current!==null&&window.clearTimeout(Ne.current),Ne.current=window.setTimeout(()=>{Ue(!1),tt(!1),et(""),nt(-1),Vt(!1),V.dismissMention(),Ne.current=null},120)},[V]),os=a.useCallback(()=>{qt.current=!1,Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null),Ne.current!==null&&(window.clearTimeout(Ne.current),Ne.current=null),je.current!==null&&(window.clearTimeout(je.current),je.current=null)},[]);a.useEffect(()=>()=>{Re.current!==null&&window.clearTimeout(Re.current),je.current!==null&&window.clearTimeout(je.current)},[]);const Si=a.useCallback(async e=>{Ce(null);try{await D(e),r(i("chat.conversationArchived","Conversation archived"),"success")}catch{r(i("chat.failedToArchiveConversation","Failed to archive conversation"),"error")}},[D,r]),rs=a.useCallback(e=>{const n=Pe.find(o=>o.id===e)??(l?.id===e?l:null);Ce(null),Me(!1),Mn(n?.title??""),Lt({sessionId:e,title:n?.title??""})},[l,Pe]),cs=a.useCallback(async()=>{if(It)try{await _(It.sessionId,Sn),Lt(null),Mn(""),r(i("chat.conversationRenamed","Conversation renamed"),"success")}catch{}},[r,It,_,Sn,i]),ls=a.useCallback(async(e,n)=>{Ce(null),Me(!1);try{await Q(e,n),r(n?i("chat.conversationPinned","Conversation pinned"):i("chat.conversationUnpinned","Conversation unpinned"),"success")}catch{}},[r,Q,i]),Mi=a.useCallback(async e=>{Pt(null),Ce(null);try{await le(e),r(i("chat.conversationDeleted","Conversation deleted"),"success")}catch{r(i("chat.failedToDeleteConversation","Failed to delete conversation"),"error")}},[le,r]),jt=a.useCallback(e=>{try{localStorage.setItem(qs,String(e))}catch{}},[]),Ni=a.useCallback(e=>{if(z||Nt)return;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;typeof n.setPointerCapture=="function"&&n.setPointerCapture(e.pointerId);const o=e.clientX,m=Ye;let v=m;document.body.style.userSelect="none";const P=U=>{const oe=U.clientX-o,ft=Math.max(gn,Math.min(pn,m+oe));v=ft,An(ft),jt(ft)},ne=U=>{typeof n.releasePointerCapture=="function"&&n.releasePointerCapture(U.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",P),document.removeEventListener("pointerup",ne),jt(v)};document.addEventListener("pointermove",P),document.addEventListener("pointerup",ne)},[z,jt,Ye,Nt]),Ri=a.useCallback(e=>{if(z||Nt||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const n=e.shiftKey?50:10,o=e.key==="ArrowLeft"?-n:n,m=Math.max(gn,Math.min(pn,Ye+o));An(m),jt(m)},[z,jt,Ye,Nt]),ds=a.useCallback(e=>{const n=Pe.find(o=>o.id===e);he("direct",e,n?.lastMessageAt??n?.updatedAt),J(e),Me(!1),z&&Oe(!1)},[Pe,z,he,J]),Gn=a.useCallback(()=>{J(""),Oe(!0),Me(!1)},[J]),Yn=a.useCallback(()=>{w.selectRoom(null),Oe(!0),Me(!1)},[w]),ji=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(vn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:i("chat.startNewConversation","Start a new conversation")}),t.jsxs("button",{className:"btn btn-primary",onClick:nn,children:[t.jsx(gt,{size:16}),i("chat.newChat","New Chat")]})]}),Ee=Js(l,l?.agentId?be.get(l.agentId)??null:null,zt),Qn=a.useMemo(()=>{if(!Ee?.provider||!Ee.modelId)return null;const e=Tn.find(n=>n.provider===Ee.provider&&n.id===Ee.modelId);return e?.contextWindow?e.contextWindow:null},[Ee?.modelId,Ee?.provider,Tn]),Ai=a.useMemo(()=>Go(N,$?K:void 0),[$,N,K]),$e=Rs(Ee?.provider,Ee?.modelId),We=Ee?.provider??null,Zn=!!(l||$||N.length>0),cn=z&&!wt&&(L==="rooms"?se:Zn),ln=z?cn:L==="rooms"?se:!!l,us=a.useRef(ln);a.useEffect(()=>{const e=us.current;us.current=ln,z&&(e||!ln||Ba({type:"view",revert:L==="rooms"?Yn:Gn}))},[L,Gn,Yn,ln,z,Ba]);const ms=l?.agentId===ke?$e??"Fusion":l?.title||be.get(l?.agentId??"")?.name||l?.agentId||"Chat",Ti=l?.title||i("chat.untitledSession","Untitled"),Ei=!!($e&&$e!==ms),Di=!z&&Zn&&Qn!==null,hs=Ws(Ai),dn=Qn!==null?Ws(Qn):null,Jn=dn?i("chat.contextWindowAria","Estimated {{used}} of {{total}} context tokens",{used:hs,total:dn}):null,Ii=cn&&L==="direct"&&!!l,fs=cn&&L==="direct",gs=cn&&L==="rooms",ea=be.get(l?.agentId??"")?.name||(l?.agentId===ke?$e??"Fusion":l?.agentId?.slice(0,30)??"Fusion"),ta=!1,na=l?.agentId===ke,Li=e=>e.length>50?`${e.slice(0,50)}…`:e;a.useEffect(()=>{if(!Ht)return;const e=n=>{Ha.current?.contains(n.target)||Me(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[Ht]),a.useEffect(()=>{if(!Kt)return;const e=o=>{Ka.current?.contains(o.target)||Ct(!1)},n=o=>{o.key==="Escape"&&Ct(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",n),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",n)}},[Kt]),a.useEffect(()=>{(!z||L!=="direct"||wt)&&Me(!1)},[z,L,wt]),a.useEffect(()=>{Ct(!1)},[w.activeRoom?.id]);const ps=a.useCallback((e,n)=>{const o=Mt.current.get(e);o&&window.clearTimeout(o),za(v=>({...v,[e]:n}));const m=window.setTimeout(()=>{za(v=>{const{[e]:P,...ne}=v;return ne}),Mt.current.delete(e)},2e3);Mt.current.set(e,m)},[]),vs=a.useCallback(async(e,n)=>{const o=await xo(n);ps(e,o?"success":"error")},[ps]),aa=l?.agentId===ke,sa=a.useCallback((e,n,o)=>t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${it[e]==="success"?" chat-message-copy-action--success":""}${it[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":o??`chat-copy-response-${e}`,"aria-label":it[e]==="success"?i("chat.responseCopied","Response copied"):it[e]==="error"?i("chat.copyFailed","Copy failed"):i("chat.copyResponse","Copy response"),onClick:()=>{vs(e,n)},children:it[e]==="success"?t.jsx(wo,{size:14}):t.jsx(yo,{size:14})}),[it,vs]),ia=a.useCallback(e=>{const n=ce.current;if(!n)return;const o=`[data-testid="chat-message-${e}"]`,m=n.querySelector(o);if(!m)return;const v=m.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop,P=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;n.scrollTo({top:v,behavior:P?"auto":"smooth"})},[]),bs=l?.cliExecutorAdapterId??null,oa=!!bs,Pi=bs==="generic"?"generic":"hybrid",Fi=l?.cliSessionFile||l?.id||"",xs=!oa&&!$,ws=()=>t.jsxs("div",{className:"chat-messages",ref:ce,onScroll:Ja,children:[t.jsx("div",{ref:Ua,className:"chat-load-more-sentinel",children:pe&&W&&t.jsx("div",{className:"chat-loading-older",children:i("chat.loadingOlderMessages","Loading older messages…")})}),$?t.jsxs(t.Fragment,{children:[N.map((e,n)=>t.jsx(ua,{message:e,forcePlain:!1,agentName:ea,hideAssistantIdentity:na,showAssistantModelTag:ta,activeModelTag:$e,activeModelProvider:We,activeSessionId:l?.id??null,projectId:s,mentionAgentsByName:Hn,roomContext:null,copyAction:aa&&e.role==="assistant"?sa(e.id,e.content):void 0,onScrollToTop:ia,isTopClipped:Fn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===N.length-1&&!$,submittedQuestionAnswer:Gs(N,n),onQuestionSubmit:an,canEdit:xs,onEditMessage:ae},e.id)),t.jsx(jo,{streamingText:K,streamingThinking:I,streamingToolCalls:ee,forcePlain:!1,agentName:ea,hideAssistantIdentity:na,showAssistantModelTag:ta,activeModelTag:$e,activeModelProvider:We,copyAction:aa&&K?sa("__streaming__",K,"chat-copy-response-streaming"):void 0,onQuestionSubmit:an})]}):W?t.jsx("div",{className:"chat-empty-state",children:i("chat.loadingMessages","Loading messages...")}):N.length===0&&!l?ji():N.length===0&&l?t.jsx("div",{className:"chat-empty-state",children:i("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsx(t.Fragment,{children:N.map((e,n)=>t.jsx(ua,{message:e,forcePlain:!1,agentName:ea,hideAssistantIdentity:na,showAssistantModelTag:ta,activeModelTag:$e,activeModelProvider:We,activeSessionId:l?.id??null,projectId:s,mentionAgentsByName:Hn,roomContext:null,copyAction:aa&&e.role==="assistant"?sa(e.id,e.content):void 0,onScrollToTop:ia,isTopClipped:Fn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===N.length-1&&!$,submittedQuestionAnswer:Gs(N,n),onQuestionSubmit:an,canEdit:xs,onEditMessage:ae},e.id))}),t.jsx("div",{ref:Oa})]}),ys=()=>t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file","data-testid":"chat-file-input",accept:Zs,multiple:!0,style:{display:"none"},onChange:e=>{ut(e.target.files),e.target.value=""}}),Qe&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":i("chat.skillSuggestions","Skill suggestions"),children:fi&&Un.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:i("chat.loadingSkills","Loading skills…")}):xe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:yt?i("chat.noSkillsFound","No skills found"):i("chat.noSkillsAvailable","No skills available")}):xe.map((e,n)=>e.kind==="command"?t.jsxs("button",{type:"button",role:"option","aria-selected":n===Ze,"aria-disabled":e.disabled,className:`chat-skill-menu-item chat-command-menu-item${n===Ze?" chat-skill-menu-item--highlighted":""}${e.disabled?" chat-command-menu-item--disabled":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>He(n),onClick:()=>qn(e.command,e.disabled),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.command.trigger}),t.jsx("span",{className:"chat-skill-menu-item-description",children:e.disabled?i("chat.commandNoRunningAgentHint","No running agent to steer"):e.command.description})]},`command-${e.command.trigger}`):t.jsxs("button",{type:"button",role:"option","aria-selected":n===Ze,className:`chat-skill-menu-item${n===Ze?" chat-skill-menu-item--highlighted":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>He(n),onClick:()=>Xn(e.skill),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.skill.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.skill.relativePath,children:e.skill.relativePath})]},e.skill.id))}),ve.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ve.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),Ie.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-pending-stack","data-testid":"chat-pending-stack",children:Ie.map((e,n)=>t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:i("chat.queuedMessage","Queued: {{preview}}",{preview:Li(e)})}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":i("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":`chat-pending-dismiss-${n}`,onClick:()=>ue(n),children:"×"})]},`${n}-${e}`))}),t.jsx("div",{className:"chat-pending-divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":i("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Ds,{size:16})}),!oa&&t.jsx(Bs,{level:l?.thinkingLevel,defaultThinkingLevel:T,models:Tn,favoriteProviders:ui,favoriteModels:mi,agents:Array.from(be.values()),agentId:l?.agentId,modelProvider:l?.modelProvider,modelId:l?.modelId,onChange:e=>{l&&H(l.id,e)},onChangeModel:e=>{l&&A(l.id,e)},disabled:!l}),t.jsxs("div",{className:`chat-input-wrapper${$a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),st(!0)},onDragLeave:()=>st(!1),onDrop:e=>{e.preventDefault(),st(!1),ut(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:ki,className:"chat-input-textarea",placeholder:i("chat.typeMessage","Type a message..."),value:q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:rn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ma()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Us,{agents:ct,filter:Je,highlightedIndex:Bt,visible:Se,onSelect:sn,position:"below",roomMemberIds:Ae?.memberIds,roomName:Ae?.roomName}),t.jsx(_o,{visible:V.mentionActive&&!Se,position:gi,tasks:V.tasks,files:V.files,selectedIndex:V.selectedIndex,onSelectTask:e=>{Rt(V.selectTask(e,q),`#${e.id}`)},onSelectFile:e=>{Rt(V.selectFile(e,q),`#${e.path}`)},loading:V.loading})]}),t.jsx(Is,{...wi.micProps}),t.jsx(Ls,{isStreaming:$,canSend:!!(q.trim()||ve.length>0),onSend:Vn,onStop:de})]})]}),$i=z?void 0:{width:`${Ye}px`},ks=Pe.filter(e=>e.pinnedAt!=null),Cs=Pe.filter(e=>e.pinnedAt==null),ye=G?Pe.find(e=>e.id===G.sessionId)??(l?.id===G.sessionId?l:void 0):void 0,Ss=a.useCallback(async()=>{const e=Nn.trim();if(!e)return;let n;try{n=await f(e)}catch{r(i("chat.failedToCreateTag","Failed to create tag"),"error");return}if(G?.sessionId){const o=(ye?.tags??[]).map(m=>m.id);if(!o.includes(n.id))try{await Z(G.sessionId,[...o,n.id])}catch{r(i("chat.failedToUpdateTags","Failed to update tags"),"error");return}}Ea("")},[r,G,ye,f,Nn,Z,i]),_i=Ii?t.jsxs("div",{className:"chat-mobile-session-menu",ref:Ha,children:[t.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":Ht,onClick:()=>Me(e=>!e),children:[We?t.jsx(ca,{provider:We,size:"md"}):t.jsx(xn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Ti}),t.jsx(un,{size:16,"aria-hidden":"true"})]}),Ht&&t.jsxs("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:[[{id:"pinned",label:i("chat.pinned","Pinned"),testId:"chat-mobile-pinned-divider",sessions:ks},{id:"recent",label:i("chat.recent","Recent"),testId:"chat-mobile-recent-divider",sessions:Cs}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-mobile-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>t.jsxs("div",{className:`chat-mobile-session-option-row${l?.id===n.id?" chat-mobile-session-option-row--active":""}`,role:"none",children:[t.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${l?.id===n.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${n.id}`,onClick:()=>ds(n.id),children:t.jsxs("span",{className:"chat-mobile-session-option-title",children:[n.title||i("chat.untitledSession","Untitled"),n.pinnedAt?t.jsx(mn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":i("chat.pinned","Pinned")}):null]})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-pin","data-testid":`chat-mobile-session-pin-${n.id}`,"aria-label":n.pinnedAt?i("chat.unpinConversationAria","Unpin conversation {{title}}",{title:n.title||i("chat.untitledSession","Untitled")}):i("chat.pinConversationAria","Pin conversation {{title}}",{title:n.title||i("chat.untitledSession","Untitled")}),title:!n.pinnedAt&&O>=3?i("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:!n.pinnedAt&&O>=3,onClick:()=>ls(n.id,!n.pinnedAt),children:n.pinnedAt?t.jsx(js,{size:14}):t.jsx(mn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-rename","data-testid":`chat-mobile-session-rename-${n.id}`,"aria-label":i("chat.renameConversationAria","Rename conversation {{title}}",{title:n.title||i("chat.untitledSession","Untitled")}),onClick:()=>rs(n.id),children:t.jsx(la,{size:14})})]},n.id))]},e.id)),t.jsxs("button",{type:"button",role:"menuitem",className:"chat-mobile-session-new","data-testid":"chat-mobile-session-new",onClick:()=>{Me(!1),nn()},children:[t.jsx(gt,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:i("chat.newChat","New Chat")})]})]})]}):null,zi=t.jsxs("div",{className:"chat-sidebar-scope-toggle chat-view-header-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${L==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":L==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>Ge("direct"),children:[t.jsx(vn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:i("chat.scopeDirect","Direct")})]}),t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${L==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":L==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>Ge("rooms"),children:[t.jsx(si,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:i("chat.scopeRooms","Rooms")})]})]});return t.jsxs("div",{ref:qa,className:`chat-view${u?" chat-view--floating":""}${z?" chat-view--narrow":""}${fs?" chat-view--mobile-direct-thread":""}`,children:[t.jsx(ko,{icon:vn,title:i("chat.title","Chat"),actions:t.jsxs(t.Fragment,{children:[fs?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn-icon chat-back-btn",onClick:Gn,"data-testid":"chat-back-btn","aria-label":i("chat.backToConversations","Back to conversations"),children:t.jsx(As,{size:16})}),_i]}):zi,z?null:t.jsxs("button",{className:"btn btn-sm btn-primary chat-view-header-new-chat",onClick:nn,"data-testid":"chat-new-btn",children:[t.jsx(gt,{size:14}),i("chat.newChat","New Chat")]}),!u&&d?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:d,"aria-label":i("chat.popOut","Pop out chat"),title:i("chat.popOut","Pop out chat"),"data-testid":"chat-pop-out",children:t.jsx(Ts,{size:16})}):null,u&&h?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:h,"aria-label":i("chat.maximizeToChatView","Open in Chat view"),title:i("chat.maximizeToChatView","Open in Chat view"),"data-testid":"chat-modal-maximize",children:t.jsx(Ts,{size:16})}):null,u&&C?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:C,"aria-label":i("chat.minimizeToQuickChat","Minimize to quick chat"),title:i("chat.minimizeToQuickChat","Minimize to quick chat"),"data-testid":"chat-modal-minimize",children:t.jsx(Co,{size:16})}):null,u&&S?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:S,"aria-label":i("chat.closeChat","Close chat"),title:i("chat.closeChat","Close chat"),"data-testid":"chat-modal-close",children:t.jsx(Es,{size:16})}):null]})}),t.jsxs("div",{className:"chat-view__body",children:[t.jsxs("div",{className:`chat-sidebar${wt?"":" chat-sidebar--hidden"}`,style:$i,children:[L==="direct"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-sidebar-search-container",children:[t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(So,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:i("chat.searchConversations","Search conversations..."),value:qe,onChange:e=>ci(e.target.value),"data-testid":"chat-search-input"})]}),t.jsxs("label",{className:"chat-tag-filter",htmlFor:"chat-tag-filter",children:[t.jsx(Eo,{size:14,"aria-hidden":"true"}),t.jsxs("select",{id:"chat-tag-filter",value:p??"",onChange:e=>y(e.target.value||null),"data-testid":"chat-tag-filter","aria-label":i("chat.filterByTag","Filter conversations by tag"),children:[t.jsx("option",{value:"",children:i("chat.allTags","All tags")}),c.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]}),p?t.jsx("button",{type:"button",className:"btn-icon","aria-label":i("chat.clearTagFilter","Clear tag filter"),onClick:()=>y(null),children:t.jsx(Es,{size:14})}):null]})]}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:B?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:i("chat.loadingConversations","Loading...")}):Pe.length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:i("chat.noConversationsYet","No conversations yet")}):t.jsx(t.Fragment,{children:[{id:"pinned",label:i("chat.pinned","Pinned"),testId:"chat-pinned-divider",sessions:ks},{id:"recent",label:i("chat.recent","Recent"),testId:"chat-recent-divider",sessions:Cs}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>{const o=l?.id===n.id,m=!o&&Ra("direct",n.id,n.lastMessageAt??n.updatedAt),v=Js(n,be.get(n.agentId)??null,zt),P=Rs(v?.provider,v?.modelId)??"Fusion",ne=n.title||i("chat.untitledSession","Untitled");return t.jsxs("div",{className:`chat-session-item${o?" chat-session-item--active":""}`,onClick:()=>ds(n.id),onContextMenu:U=>{U.preventDefault(),ja(n.id,U.clientX,U.clientY)},"data-testid":`chat-session-${n.id}`,children:[t.jsx("button",{type:"button",className:"btn-icon chat-session-menu-btn","data-testid":"chat-session-menu-btn","aria-label":i("chat.conversationActionsAria","Conversation actions for {{title}}",{title:ne}),"aria-haspopup":"menu","aria-expanded":G?.sessionId===n.id,onClick:U=>{if(U.stopPropagation(),G?.sessionId===n.id){Ce(null);return}const oe=U.currentTarget.getBoundingClientRect();ja(n.id,oe.right,oe.bottom,{anchorRight:!0})},children:t.jsx(Mo,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[ne,n.pinnedAt?t.jsx(mn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":i("chat.pinned","Pinned")}):null,m?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${n.id}`,"aria-label":i("chat.unreadMessages","Unread messages")}):null]}),t.jsx("div",{className:"chat-session-preview",children:n.lastMessagePreview||i("chat.noMessages","No messages")}),(n.tags??[]).length>0?t.jsx("div",{className:"chat-session-tags","data-testid":`chat-session-tags-${n.id}`,children:(n.tags??[]).map(U=>t.jsx("span",{className:"chat-session-tag",children:U.name},U.id))}):null,n.matchedMessagePreview?t.jsx("div",{className:"chat-session-preview chat-session-preview--matched","data-testid":`chat-session-matched-preview-${n.id}`,children:i("chat.matchedInMessage",'Matched: "{{preview}}"',{preview:n.matchedMessagePreview})}):null,t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[v?.provider?t.jsx(ca,{provider:v.provider,size:"sm"}):null,t.jsx("span",{children:be.get(n.agentId)?.name||(n.agentId===ke?P:n.agentId.slice(0,30))})]}),t.jsx("span",{children:n.updatedAt?tr(n.updatedAt,i):""})]})]},n.id)})]},e.id))})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!z&&t.jsx("div",{className:"chat-sidebar-rooms-header","data-testid":"chat-sidebar-rooms-header",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary","data-testid":"chat-create-room-btn",onClick:()=>_t(!0),children:[t.jsx(gt,{size:14}),i("chat.createRoom","Create room")]})}),w.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:i("chat.noRoomsYet","No rooms yet.")}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:w.rooms.map(e=>{const n=w.activeRoom?.id===e.id,o=!n&&Ra("room",e.id,e.updatedAt);return t.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${n?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${e.slug}`,onClick:()=>{he("room",e.id,e.updatedAt),w.selectRoom(e.id),z&&Oe(!1)},onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),he("room",e.id,e.updatedAt),w.selectRoom(e.id),z&&Oe(!1))},children:[t.jsxs("span",{className:"chat-room-item-details",children:[t.jsxs("span",{className:"chat-room-item-name-row",children:[t.jsxs("span",{className:"chat-room-item-name",children:["#",e.name]}),o?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":i("chat.unreadMessages","Unread messages")}):null]}),n?t.jsx("span",{className:"chat-room-item-meta",children:i("chat.roomMemberCount","{{count}} member",{count:w.activeRoomMembers.length,defaultValue_one:"{{count}} member",defaultValue_other:"{{count}} members"})}):null]}),t.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${e.slug}`,"aria-label":i("chat.deleteRoom","Delete room {{name}}",{name:e.name}),onClick:m=>{m.stopPropagation(),Ft(e.id)},children:t.jsx(da,{size:14})})]},e.id)})})]}),L==="rooms"?z?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary chat-sidebar-footer-btn","data-testid":"chat-create-room-btn",onClick:()=>_t(!0),children:[t.jsx(gt,{size:14}),i("chat.createRoom","Create room")]})}):null:z?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:nn,"data-testid":"chat-new-btn",children:[t.jsx(gt,{size:14}),i("chat.newChat","New Chat")]})}):null]}),!z&&wt&&!Nt&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":gn,"aria-valuemax":pn,"aria-valuenow":Ye,"aria-label":i("chat.resizeSidebar","Resize chat sidebar"),tabIndex:0,onPointerDown:Ni,onKeyDown:Ri}),G&&t.jsxs("div",{className:"chat-session-context-menu",ref:Cn,role:"menu",style:{top:G.y,left:G.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>ls(G.sessionId,!ye?.pinnedAt),"data-testid":"chat-context-pin",title:O>=3&&!ye?.pinnedAt?i("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:O>=3&&!ye?.pinnedAt,children:[ye?.pinnedAt?t.jsx(js,{size:14}):t.jsx(mn,{size:14}),ye?.pinnedAt?i("chat.unpin","Unpin"):i("chat.pin","Pin")]}),t.jsxs("button",{onClick:()=>rs(G.sessionId),"data-testid":"chat-context-rename",children:[t.jsx(la,{size:14}),i("chat.rename","Rename")]}),t.jsxs("div",{className:"chat-session-tag-menu",role:"group","aria-label":i("chat.conversationTags","Conversation tags"),children:[c.map(e=>{const n=(ye?.tags??[]).some(o=>o.id===e.id);return t.jsxs("div",{className:"chat-tag-menu-item",children:[t.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,"data-testid":`chat-context-tag-${e.id}`,onClick:()=>void Z(G.sessionId,n?(ye?.tags??[]).filter(o=>o.id!==e.id).map(o=>o.id):[...(ye?.tags??[]).map(o=>o.id),e.id]).catch(()=>r(i("chat.failedToUpdateTags","Failed to update tags"),"error")),children:[n?"✓ ":"",e.name]}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":i("chat.renameTag","Rename tag {{name}}",{name:e.name}),"data-testid":`chat-context-rename-tag-${e.id}`,onClick:o=>{o.stopPropagation(),Da(e.name),xt(e)},children:t.jsx(la,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":i("chat.deleteTag","Delete tag {{name}}",{name:e.name}),"data-testid":`chat-context-delete-tag-${e.id}`,onClick:o=>{o.stopPropagation(),$t(e)},children:t.jsx(da,{size:14})})]},e.id)}),t.jsxs("div",{className:"chat-tag-create-row",children:[t.jsx("input",{className:"input",value:Nn,placeholder:i("chat.newTag","New tag"),"aria-label":i("chat.newTag","New tag"),onChange:e=>Ea(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),Ss())}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Ss(),children:i("chat.addTag","Add")})]})]}),t.jsxs("button",{onClick:()=>Si(G.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(No,{size:14}),i("chat.archive","Archive")]}),t.jsxs("button",{onClick:()=>{Ce(null),Pt(G.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(da,{size:14}),i("chat.delete","Delete")]})]}),It&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>Lt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-dialog-title",children:i("chat.renameConversationTitle","Rename Conversation")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:i("chat.renameConversationBody","Choose a new name for this conversation. Leave it blank to show Untitled.")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-input",children:i("chat.conversationName","Conversation name")}),t.jsx("input",{id:"chat-rename-input",className:"input chat-rename-input",type:"text",value:Sn,placeholder:i("chat.renamePlaceholder","Untitled"),"data-testid":"chat-rename-input",onChange:e=>Mn(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),cs())},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Lt(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void cs(),"data-testid":"chat-rename-save",children:i("chat.save","Save")})]})]})}),Rn&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>xt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-tag-dialog-title",children:i("chat.renameTagTitle","Rename tag")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-tag-input",children:i("chat.tagName","Tag name")}),t.jsx("input",{id:"chat-rename-tag-input",className:"input chat-rename-input",value:jn,"data-testid":"chat-rename-tag-input",onChange:e=>Da(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),j(Rn.id,jn).then(()=>xt(null)).catch(()=>r(i("chat.failedToRenameTag","Failed to rename tag"),"error")))},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>xt(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary","data-testid":"chat-rename-tag-save",onClick:()=>void j(Rn.id,jn).then(()=>xt(null)).catch(()=>r(i("chat.failedToRenameTag","Failed to rename tag"),"error")),children:i("chat.save","Save")})]})]})}),Ia&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>$t(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-delete-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-delete-tag-dialog-title",children:i("chat.deleteTagTitle","Delete tag?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:i("chat.deleteTagBody","This removes the tag from all conversations, but does not delete conversations.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>$t(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger","data-testid":"chat-delete-tag-confirm",onClick:()=>void F(Ia.id).then(()=>$t(null)).catch(()=>r(i("chat.failedToDeleteTag","Failed to delete tag"),"error")),children:i("chat.delete","Delete")})]})]})}),Aa&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>Pt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:i("chat.deleteConversationTitle","Delete Conversation?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:i("chat.deleteConversationBody","This action cannot be undone. All messages in this conversation will be permanently deleted.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Pt(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Mi(Aa),children:i("chat.delete","Delete")})]})]})}),Ta&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>Ft(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:i("chat.deleteRoomTitle","Delete Room?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:i("chat.deleteRoomBody","This action cannot be undone. This room and all its messages will be permanently deleted.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Ft(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await w.deleteRoom(Ta),Ft(null)}catch{r(i("chat.failedToDeleteRoom","Failed to delete room"),"error")}})()},children:i("chat.delete","Delete")})]})]})}),L==="rooms"?t.jsxs("div",{ref:Pn,className:"chat-thread",children:[w.activeRoom?t.jsxs(t.Fragment,{children:[(!z||gs)&&t.jsxs("div",{className:"chat-room-thread-header",children:[gs&&t.jsx("button",{className:"btn-icon",onClick:Yn,"data-testid":"chat-back-btn",children:t.jsx(As,{size:16})}),t.jsxs("div",{className:"chat-room-switcher-menu",ref:Ka,children:[t.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":Kt,onClick:()=>Ct(e=>!e),children:[t.jsxs("span",{className:"chat-thread-header-title",children:["#",w.activeRoom.name]}),t.jsx(un,{size:16,"aria-hidden":"true"})]}),Kt&&t.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:w.rooms.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${e.id===w.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${e.id}`,onClick:()=>{he("room",e.id,e.updatedAt),w.selectRoom(e.id),Ct(!1)},children:["#",e.name]},e.id))})]}),t.jsx("div",{className:"chat-room-thread-members",children:w.activeRoomMembers.map(e=>t.jsx(wn,{agent:be.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:ce,onScroll:Ja,children:[w.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:i("chat.loadingMessages","Loading messages...")}):w.messages.filter(e=>e.content.trim()!==Xs).length===0?t.jsx("div",{className:"chat-empty-state",children:i("chat.noMessagesYet","No messages yet. Start the conversation!")}):w.messages.filter(e=>e.content.trim()!==Xs).map(e=>{const n=e.senderAgentId?be.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):i("chat.you","You"),o={id:e.id,sessionId:e.roomId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput??void 0,toolCalls:void 0,fallbackInfo:void 0,attachments:e.attachments,createdAt:e.createdAt};return t.jsx(ua,{message:o,forcePlain:!1,agentName:n,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:w.activeRoom?.id??null,projectId:s,mentionAgentsByName:Hn,roomContext:Ae,onScrollToTop:ia,isTopClipped:Fn.has(e.id),isAwaitingQuestionAnswer:!1,onQuestionSubmit:an},e.id)}),t.jsx("div",{ref:Oa})]}),w.activeRoom&&_a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(un,{size:14}),i("chat.latest","Latest")]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:i("chat.selectRoomOrCreate","Select a room or create one")}),w.activeRoom&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file",accept:Zs,multiple:!0,style:{display:"none"},onChange:e=>{ut(e.target.files),e.target.value=""}}),ve.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ve.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":i("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Ds,{size:16})}),t.jsx(Bs,{level:w.activeRoom.thinkingLevel,defaultThinkingLevel:T,showTargetSection:!1,onChange:e=>{w.updateRoomSettings(w.activeRoom.id,{thinkingLevel:e||null}).catch(()=>{r(i("chat.failedToUpdateRoomThinkingLevel","Failed to update room thinking effort"),"error")})}}),t.jsxs("div",{className:`chat-input-wrapper${$a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),st(!0)},onDragLeave:()=>st(!1),onDrop:e=>{e.preventDefault(),st(!1),ut(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:Ci,className:"chat-input-textarea",placeholder:i("chat.typeMessage","Type a message..."),value:q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:rn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ma()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Us,{agents:ct,filter:Je,highlightedIndex:Bt,visible:Se,onSelect:sn,position:"below",roomMemberIds:Ae?.memberIds,roomName:Ae?.roomName})]}),t.jsx(Is,{...yi.micProps}),t.jsx(Ls,{isStreaming:!1,canSend:!!(q.trim()||ve.length>0),onSend:Wn})]})]})]}):t.jsxs("div",{ref:Pn,className:"chat-thread",children:[!z&&(Zn||!z)&&t.jsx("div",{className:"chat-thread-header",children:t.jsxs("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:[We?t.jsx(ca,{provider:We,size:"md"}):t.jsx(xn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:ms}),Ei&&t.jsx("span",{className:"chat-model-tag",children:$e}),Di&&dn&&Jn?t.jsxs("span",{className:"chat-thread-header-context","data-testid":"chat-thread-context-window",title:Jn,"aria-label":Jn,children:[hs," / ",dn]}):null]})}),oa?t.jsx(Oo,{cliSessionId:Fi,tier:Pi,projectId:s,renderTranscript:ws,renderComposer:()=>l?ys():null}):t.jsxs(t.Fragment,{children:[ws(),_a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(un,{size:14}),i("chat.latest","Latest")]}),l&&ys()]})]}),t.jsx(Bo,{isOpen:di,onClose:()=>_t(!1),projectId:s,existingRoomNames:w.rooms.map(e=>e.name),onCreate:async e=>{await w.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),L!=="rooms"&&Ge("rooms"),_t(!1),z&&Oe(!1)}})]}),li&&t.jsx(rr,{projectId:s,defaultModel:hi,defaultKind:b?.kind,defaultAgentId:b?.kind==="agent"?b.agentId:void 0,defaultThinkingLevel:T,defaultSelectedThinkingLevel:b?.kind==="model"?b.thinkingLevel:void 0,onClose:()=>kn(!1),onCreate:mt})]})}export{vr as ChatView,pr as buildIssueChatPrefill,er as clampChatInputHeight,Zo as resolveChatContextMenuPosition,Jo as resolveChatInputOverflowY,Js as resolveSessionProvider};
|
|
13
|
+
`:""}function Jo(s,r,u,g,d,h,C){const S=Math.max(vt,h-g-vt),x=Math.max(vt,C-d-vt),R=u?s-g:s;return{x:Math.min(Math.max(vt,R),S),y:Math.min(Math.max(vt,r),x)}}const Xs="__SKIP__";let pa=!1;function Zo(s,r=Na){return s>r?"auto":"hidden"}function er(s,r=Na){return Math.max(40,Math.min(s,r))}function tr(s,r){const u=new Date(s),d=new Date().getTime()-u.getTime(),h=Math.floor(d/1e3),C=Math.floor(h/60),S=Math.floor(C/60),x=Math.floor(S/24);return h<60?r("chat.relativeTimeJustNow","just now"):C<60?r("chat.relativeTimeMinutes","{{count}}m ago",{count:C}):S<24?r("chat.relativeTimeHours","{{count}}h ago",{count:S}):x<7?r("chat.relativeTimeDays","{{count}}d ago",{count:x}):u.toLocaleDateString()}const nr=280,gn=180,pn=500,qs="fusion:chat-sidebar-width",va="fusion:chat-scope",ar="fusion:chat-draft:";function Gs(s,r){return s.slice(r+1).find(u=>u.role==="user")?.content}function Ys(s,r){return r?`${ar}${s}:${r}`:null}function Qs(s){if(!s)return"";try{return localStorage.getItem(s)??""}catch{return""}}const sr=["image/png","image/jpeg","image/gif","image/webp","video/mp4","video/webm","video/quicktime","text/plain","text/markdown","application/json","text/yaml","text/x-toml","text/csv","application/xml"],Js="image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm,video/quicktime,.txt,.md,.json,.yaml,.yml,.toml,.csv,.xml",ba=Ro;function ir(s,r){const u=s.slice(0,r),g=/(^|[\s\n])@([\w-]*)$/.exec(u);if(!g)return null;const d=g[2]??"",h=u.length-d.length-1;return{filter:d,start:h,end:r}}function or(s){const r=s?.runtimeConfig;if(!r||typeof r!="object")return null;const u=Reflect.get(r,"modelProvider"),g=Reflect.get(r,"modelId");return typeof u!="string"||u.trim().length===0||typeof g!="string"||g.trim().length===0?null:{provider:u,modelId:g}}function Zs(s,r,u){if(s?.modelProvider&&s?.modelId)return{provider:s.modelProvider,modelId:s.modelId};const g=or(r??void 0);return g||(u.provider&&u.modelId?{provider:u.provider,modelId:u.modelId}:null)}function rr({projectId:s,defaultModel:r,defaultKind:u,defaultAgentId:g,defaultThinkingLevel:d,defaultSelectedThinkingLevel:h,onClose:C,onCreate:S}){const{t:x}=ze("app"),[R,E]=a.useState(u??"agent"),{agents:i,loading:M}=ni(s),[k,T]=a.useState(g??""),{models:b,favoriteProviders:l,favoriteModels:B,loading:N,refresh:V}=ai(),_=r.provider&&r.modelId?`${r.provider}/${r.modelId}`:"",[K,I]=a.useState(_),[ee,Z]=a.useState(h??""),[Y,D]=a.useState(l),[$,Q]=a.useState(B);a.useEffect(()=>{D(l)},[l]),a.useEffect(()=>{Q(B)},[B]),a.useEffect(()=>{u&&E(u)},[u]),a.useEffect(()=>{g&&T(p=>p||g)},[g]),a.useEffect(()=>{_&&I(p=>p||_)},[_]),a.useEffect(()=>{h&&Z(p=>p||h)},[h]);const O=a.useCallback(async p=>{const y=Y,j=y.includes(p)?y.filter(F=>F!==p):[p,...y];D(j);try{await Fs({favoriteProviders:j,favoriteModels:$}),await V()}catch{D(y)}},[Y,$,V]),A=a.useCallback(async p=>{const y=$,j=y.includes(p)?y.filter(F=>F!==p):[p,...y];Q(j);try{await Fs({favoriteProviders:Y,favoriteModels:j}),await V()}catch{Q(y)}},[$,Y,V]),H=K||_,le=p=>{if(p.preventDefault(),R==="agent"){if(!k)return;S({agentId:k});return}if(!H)return;const y=H.indexOf("/");if(y<=0)return;const f=H.slice(0,y),j=H.slice(y+1);S({agentId:ke,modelProvider:f,modelId:j,thinkingLevel:ee||void 0})},c=R==="agent"?!k:!H;return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:C,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:p=>p.stopPropagation(),children:[t.jsx("h3",{children:x("chat.newChatTitle","New Chat")}),t.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${R==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{E("agent")},children:x("chat.newChatModeAgent","Agent")}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${R==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{E("model"),T(""),I(p=>p||_)},children:x("chat.newChatModeModel","Model")})]}),t.jsxs("form",{onSubmit:le,children:[R==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:[x("chat.newChatModeAgent","Agent"),M?t.jsx("div",{className:"chat-new-dialog-loading",children:x("chat.loadingAgents","Loading agents...")}):i.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:x("chat.noAgentsAvailable","No agents available")}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:i.map(p=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${k===p.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>T(p.id),"data-testid":`agent-option-${p.id}`,children:[t.jsx(xn,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:p.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:p.role})]},p.id))})]}),R==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:N?t.jsx("div",{className:"chat-new-dialog-loading",children:x("chat.loadingModels","Loading models...")}):t.jsx(ti,{models:b,value:K,onChange:I,label:x("chat.newChatModeModel","Model"),placeholder:x("chat.selectModel","Select a model"),favoriteProviders:Y,onToggleFavorite:O,favoriteModels:$,onToggleModelFavorite:A,showThinkingLevel:!0,thinkingLevel:ee,onThinkingLevelChange:Z,defaultThinkingLevel:d??"off"})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:C,children:x("chat.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:c,children:x("chat.create","Create")})]})]})]})})}function vr({projectId:s,addToast:r,floating:u=!1,compactLayout:g=!1,onPopOut:d,onMaximize:h,onMinimize:C,onClose:S,chatCommandContext:x,initialComposerDraft:R,initialComposerDraftNonce:E}){const{t:i}=ze("app");a.useEffect(()=>(ya({view:"ChatView",trigger:pa?"route-active":"remount",projectId:s,replayAttempted:!1}),pa=!1,()=>{pa=!0,ya({view:"ChatView",trigger:"route-inactive",projectId:s,replayAttempted:!1})}),[s]);const[M,k]=a.useState(null);a.useEffect(()=>{let e=!1;return k(null),lo(s).then(n=>{e||k(n)}).catch(()=>{e||k(null)}),()=>{e=!0}},[s]);const T=M?.defaultThinkingLevel??"off",b=a.useMemo(()=>M?.chatDefaultKind==="agent"&&M.chatDefaultAgentId?{kind:"agent",agentId:M.chatDefaultAgentId}:M?.chatDefaultKind==="model"&&M.chatDefaultModelProvider&&M.chatDefaultModelId?{kind:"model",modelProvider:M.chatDefaultModelProvider,modelId:M.chatDefaultModelId,thinkingLevel:M.chatDefaultThinkingLevel}:null,[M]),{activeSession:l,sessionsLoading:B,messages:N,messagesLoading:V,isStreaming:_,streamingText:K,streamingThinking:I,streamingToolCalls:ee,selectSession:Z,createSession:Y,archiveSession:D,renameSession:$,pinSession:Q,pinnedCount:O,setSessionModel:A,setSessionThinkingLevel:H,deleteSession:le,tags:c=[],selectedTagId:p,setSelectedTagId:y,createTag:f,renameTag:j,deleteTag:F,setSessionTags:J,sendMessage:ge,editMessageAndResend:ae,stopStreaming:de,pendingMessages:Ie,clearPendingMessage:ue,loadMoreMessages:Le,hasMoreMessages:pe,searchQuery:qe,setSearchQuery:ci,filteredSessions:Pe,agentsMap:yn}=uo(s,r),[li,kn]=a.useState(!1),Be=!0,[L,Ge]=a.useState(()=>{try{if(localStorage.getItem(va)==="rooms"&&Be)return"rooms"}catch{}return"direct"}),w=Lo(s,r),{isUnread:Ra,markRead:he}=Po(s),[q,re]=a.useState(()=>{const e=Ys(L,L==="rooms"?w.activeRoom?.id:l?.id);return Qs(e)}),[G,Ce]=a.useState(null),Cn=a.useRef(null),ja=(e,n,o,m)=>{typeof window>"u"||Ce({sessionId:e,anchorX:n,anchorY:o,anchorRight:m?.anchorRight??!1,x:n,y:o})};a.useLayoutEffect(()=>{if(!G||!Cn.current||typeof window>"u")return;const e=Cn.current,n=e.getBoundingClientRect(),o=n.width||e.offsetWidth||Qo,m=n.height||e.offsetHeight,v=Jo(G.anchorX,G.anchorY,G.anchorRight,o,m,window.innerWidth,window.innerHeight);(v.x!==G.x||v.y!==G.y)&&Ce({...G,...v})},[G]);const[It,Lt]=a.useState(null),[Sn,Mn]=a.useState(""),[Aa,Pt]=a.useState(null),[Ta,Ft]=a.useState(null),[Nn,Ea]=a.useState(""),[Rn,xt]=a.useState(null),[jn,Da]=a.useState(""),[Ia,_t]=a.useState(null),[wt,Oe]=a.useState(!0),[Ye,An]=a.useState(nr),[di,$t]=a.useState(!1),{agentsMap:La}=ni(s),be=a.useMemo(()=>yn.size>0?yn:La,[La,yn]),{models:Tn,favoriteProviders:ui,favoriteModels:mi,defaultProvider:Pa,defaultModelId:Fa}=ai(),zt=a.useMemo(()=>({provider:Pa,modelId:Fa}),[Fa,Pa]),hi=a.useMemo(()=>b?.kind==="model"?{provider:b.modelProvider,modelId:b.modelId}:zt,[b,zt]),{skills:En,loading:fi}=qo(s),[Qe,Ue]=a.useState(!1),[yt,kt]=a.useState(""),[Je,He]=a.useState(0),[Ze,et]=a.useState(""),[Se,tt]=a.useState(!1),[Bt,Ot]=a.useState(0),[Dn,nt]=a.useState(-1),[ve,at]=a.useState([]),[_a,st]=a.useState(!1),[$a,Ut]=a.useState(!1),[it,za]=a.useState({}),[Ht,Me]=a.useState(!1),[Kt,Ct]=a.useState(!1),{pushNav:Ba}=mo(),[,Wt]=a.useState(!1),[gi,pi]=a.useState({top:0,left:0}),W=Wo({projectId:s}),In=a.useCallback(e=>{if(!e||!W.mentionActive)return;const n=e.getBoundingClientRect();pi({top:n.top-260,left:n.left+8})},[W.mentionActive]),Oa=a.useRef(null),Ua=a.useRef(null),Ha=a.useRef(null),Ka=a.useRef(null),me=a.useRef(!1),Vt=a.useRef(null),Wa=a.useRef(null),Fe=a.useRef(null),Xt=a.useRef(0),Ln=a.useRef(null),St=a.useRef(null),Ne=a.useRef(null),ce=a.useRef(null),Pn=a.useRef(null),ot=a.useRef(null),[Fn,vi]=a.useState(()=>new Set),qt=a.useRef(!1),Re=a.useRef(null),je=a.useRef(null),te=a.useRef(null),Gt=a.useRef(null),Va=a.useRef(void 0),_n=a.useRef(!1),Yt=a.useRef(null),Xa=a.useRef([]),rt=a.useRef(0),Mt=a.useRef(new Map),$n=a.useRef(!1),Qt=ho(),Ke=Qt==="mobile",zn=Qt==="tablet",qa=a.useRef(null),[bi,Ga]=a.useState(!1);a.useLayoutEffect(()=>{if(!u){Ga(!1);return}const e=qa.current;if(!e||typeof ResizeObserver>"u")return;const n=()=>{Ga(e.getBoundingClientRect().width<=768)};n();const o=new ResizeObserver(n);return o.observe(e),()=>o.disconnect()},[u]);const z=Ke||bi||g;a.useEffect(()=>{l?.id&&he("direct",l.id,l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,he]),a.useEffect(()=>{w.activeRoom?.id&&he("room",w.activeRoom.id,w.activeRoom.updatedAt)},[w.activeRoom?.id,w.activeRoom?.updatedAt,he]),a.useEffect(()=>{if(!l?.id||N.length===0)return;const e=N[N.length-1];he("direct",l.id,e?.createdAt??l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,he,N]),a.useEffect(()=>{if(!w.activeRoom?.id||w.messages.length===0)return;const e=w.messages[w.messages.length-1];he("room",w.activeRoom.id,e?.createdAt??w.activeRoom.updatedAt)},[he,w.activeRoom?.id,w.activeRoom?.updatedAt,w.messages]),a.useEffect(()=>{try{const e=localStorage.getItem(qs);if(!e)return;const n=Number.parseInt(e,10);if(Number.isNaN(n))return;const o=Math.max(gn,Math.min(pn,n));An(o)}catch{}},[]),a.useEffect(()=>{try{const e=localStorage.getItem(va);if(e==="direct"){Ge("direct");return}e==="rooms"&&Be&&Ge("rooms")}catch{}},[Be]),a.useEffect(()=>{try{localStorage.setItem(va,L)}catch{}},[Be,L]);const fe=Ys(L,L==="rooms"?w.activeRoom?.id:l?.id),Bn=a.useRef(fe),On=a.useRef(!1);a.useEffect(()=>{if(fe!==Bn.current){if(Bn.current=fe,On.current){On.current=!1;return}re(Qs(fe))}},[fe]),a.useEffect(()=>{if(!(!fe||Bn.current!==fe))try{if(q){localStorage.setItem(fe,q);return}localStorage.removeItem(fe)}catch{}},[fe,q]);const se=L==="rooms"&&!!w.activeRoom,{keyboardOverlap:Ya,keyboardOpen:Jt}=fo({enabled:(z||zn)&&(!!l||se),allowNonMobileViewport:zn}),Nt=zn&&Jt,Zt=a.useMemo(()=>{const e=yt.trim().toLowerCase();return(e?En.filter(o=>o.name.toLowerCase().includes(e)):En).slice(0,10)},[En,yt]),Un=a.useMemo(()=>x?go(yt,Ps):[],[x,yt]),xe=a.useMemo(()=>{const e=Un.map(o=>({kind:"command",command:o,disabled:!x?.agentRunning})),n=Zt.map(o=>({kind:"skill",skill:o}));return[...e,...n]},[Un,Zt,x]),ct=a.useMemo(()=>Array.from(be.values()),[be]),Ae=a.useMemo(()=>L!=="rooms"||!w.activeRoom?null:{roomId:w.activeRoom.id,roomName:w.activeRoom.name,memberIds:new Set(w.activeRoomMembers.map(e=>e.agentId))},[Be,L,w.activeRoom,w.activeRoomMembers]),We=a.useMemo(()=>{const e=ct.filter(m=>ri(m.name,Ze));if(!Ae)return e;const n=e.filter(m=>Ae.memberIds.has(m.id));if(Ze.trim().length===0)return n;const o=e.filter(m=>!Ae.memberIds.has(m.id));return[...n,...o]},[ct,Ze,Ae]),Hn=a.useMemo(()=>{const e=new Map;for(const n of ct)e.set(n.name.toLowerCase(),n);return e},[ct]),xi=a.useMemo(()=>Zt.map(e=>e.id).join("\0"),[Zt]);a.useEffect(()=>{He(0)},[xi]),a.useEffect(()=>{Ot(0)},[Ze,Se]),a.useEffect(()=>()=>{Ne.current!==null&&window.clearTimeout(Ne.current)},[]),a.useEffect(()=>{const e=Ua.current;if(!e||!pe||V)return;const n=new IntersectionObserver(o=>{o[0].isIntersecting&&Le()},{threshold:.1});return n.observe(e),()=>n.disconnect()},[pe,V,Le]);const lt=a.useCallback(()=>se?w.activeRoom?.id??null:l?.id??null,[se,w.activeRoom?.id,l?.id]),Qa=a.useCallback((e,n)=>typeof CSS<"u"&&typeof CSS.escape=="function"?e.querySelector(`.chat-message[data-message-id="${CSS.escape(n)}"]`):e.querySelector(`.chat-message[data-message-id="${n.replace(/"/g,'\\"')}"]`),[]),Ja=a.useCallback(()=>{const e=ce.current;if(!e)return;const n=e.getBoundingClientRect().top,o=new Set;e.querySelectorAll(".chat-message--assistant:not(.chat-message--failure)[data-message-id]").forEach(m=>{const v=m.getAttribute("data-message-id");v&&m.getBoundingClientRect().top<n&&o.add(v)}),vi(m=>m.size===o.size&&Array.from(m).every(v=>o.has(v))?m:o)},[]),en=a.useCallback(()=>{!ce.current||ot.current!==null||(ot.current=window.requestAnimationFrame(()=>{ot.current=null,Ja()}))},[Ja]),tn=a.useCallback(()=>{const e=ce.current,n=lt();if(!e||!n)return;const o=e.scrollTop,m=e.querySelectorAll(".chat-message[data-message-id]"),v=Array.from(m).find(U=>U.offsetTop+U.offsetHeight>=o)??m[0]??null,P=v?.getAttribute("data-message-id")??null,ne=v?v.offsetTop-o:0;St.current={threadId:n,scrollTop:o,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,anchorMessageId:P,anchorOffset:ne,wasPinnedBefore:!me.current,capturedAtMs:typeof performance<"u"?performance.now():Date.now()}},[lt]),Za=a.useCallback(()=>{const e=ce.current;if(!e)return;const o=e.scrollTop+e.clientHeight>=e.scrollHeight-50;Ut(!o),me.current=!o,tn(),en()},[tn,en]),Te=a.useCallback((e,n)=>{if(!e.isConnected||!n?.force&&me.current)return;let o=0,m=0,v=-1;const P=6,ne=()=>{if(e.isConnected&&!(!n?.force&&me.current)){if(e.scrollTop=e.scrollHeight,e.scrollHeight===v?m+=1:(m=0,v=e.scrollHeight),o+=1,o>=P||m>=2){Ut(!1),me.current=!1;return}window.requestAnimationFrame(ne)}};ne()},[]),dt=se?w.messages:N;a.useLayoutEffect(()=>(en(),()=>{ot.current!==null&&(window.cancelAnimationFrame(ot.current),ot.current=null)}),[dt,en]),a.useLayoutEffect(()=>{const e=ce.current,n=lt(),o=St.current;if(!e||!n||!o||o.threadId!==n||o.wasPinnedBefore)return;const m=(typeof performance<"u"?performance.now():Date.now())-o.capturedAtMs,v=e.scrollHeight>e.clientHeight,P=m>3e3,ne=o.scrollTop<=0&&o.anchorOffset<=0&&v;if(!me.current||P||ne){St.current=null;return}let U=o.scrollTop;if(o.anchorMessageId){const oe=Qa(e,o.anchorMessageId);oe?U=oe.offsetTop-o.anchorOffset:U=o.scrollTop+(e.scrollHeight-o.scrollHeight)}else U=o.scrollTop+(e.scrollHeight-o.scrollHeight);e.scrollTop=Math.max(0,U),me.current=!0,Ut(!0),St.current=null},[dt,lt,Qa]);const Kn=a.useCallback(e=>{},[dt.length,se]),we=a.useCallback(e=>{Kn(e);const n=ce.current;n&&(St.current=null,me.current=!1,Te(n))},[Te,Kn]);a.useLayoutEffect(()=>{Fe.current!==null&&(window.clearTimeout(Fe.current),Fe.current=null);const e=se?w.activeRoom?.id??null:l?.id??null;if(!e){Vt.current=null;return}const n={threadId:e,loaded:se?!w.messagesLoading:!V,hasMessages:se?w.messages.length>0:N.length>0},o=Vt.current,m=o?.threadId!==e,v=o?.threadId===e&&!o.loaded&&n.loaded,P=o?.threadId===e&&!o.hasMessages&&n.hasMessages;if(!(o===null||m||v||P))return;const U=ce.current;if(U)return Kn(m?"thread-change":v?"finished-loading":P?"first-messages":"mount"),Te(U,{force:!0}),se||(Fe.current=window.setTimeout(()=>{if(Fe.current=null,me.current)return;const oe=ce.current;oe&&Te(oe)},250)),Vt.current=n,()=>{Fe.current!==null&&(window.clearTimeout(Fe.current),Fe.current=null)}},[se,w.activeRoom?.id,w.messages.length,w.messagesLoading,l?.id,N.length,V,Te]),a.useEffect(()=>{!_||me.current||we("streaming")},[_,K,I,we]),a.useEffect(()=>{const e=lt();if(!e){Xt.current=0,Ln.current=null;return}if(Ln.current!==e){Ln.current=e,Xt.current=dt.length;return}const n=Xt.current,o=dt.length,m=o>n,v=!me.current;Xt.current=o,m&&v&&we("new-message")},[dt,lt,we]),a.useEffect(()=>{Ya<=0||!ce.current||we("keyboard")},[Ya,we]),po(Ke&&Jt),a.useLayoutEffect(()=>{if(!Ke||!l&&!se||typeof window>"u")return;const e=Pn.current,n=window.visualViewport;if(!e||!n)return;const o=v=>{if(!(v instanceof HTMLElement))return!1;if(v.tagName==="TEXTAREA")return!0;if(v.tagName!=="INPUT")return!1;const P=v.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(P)},m=()=>{if(qt.current){e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange="";return}const v=Math.max(0,window.innerHeight-n.offsetTop-n.height),P=n.offsetTop||0;e.style.setProperty("--vv-height",`${n.height}px`),e.style.setProperty("--vv-offset-top",`${P}px`),e.style.setProperty("--keyboard-overlap",`${v}px`);const ne=(v>0||P>0)&&o(document.activeElement);e.classList.toggle("chat-thread--keyboard-active",ne),e.style.setProperty("--chat-keyboard-accessory-clearance",ne&&ma()?"calc(var(--space-2xl) + var(--space-md))":"0px"),ne&&P>0?(e.style.transform=`translateY(${P}px)`,e.style.willChange="transform"):(e.style.transform="",e.style.willChange="")};return m(),n.addEventListener("resize",m),n.addEventListener("scroll",m),document.addEventListener("focusin",m),document.addEventListener("focusout",m),window.addEventListener("pageshow",m),document.addEventListener("visibilitychange",m),()=>{n.removeEventListener("resize",m),n.removeEventListener("scroll",m),document.removeEventListener("focusin",m),document.removeEventListener("focusout",m),window.removeEventListener("pageshow",m),document.removeEventListener("visibilitychange",m),e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange=""}},[l,Ke,se]),a.useEffect(()=>{const e=()=>Ce(null);if(G)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[G]),a.useEffect(()=>{if(!Ke||!Jt)return;const e=n=>{n.target?.closest(".chat-messages")||n.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[Ke,Jt]),a.useEffect(()=>{const e=Wa.current;if(Wa.current=L,L==="rooms"&&!w.activeRoom){Vt.current=null;return}if(!(L==="direct"&&(e===null||e==="rooms"))&&!(L==="rooms"&&(e===null||e==="direct")))return;const m=ce.current;m&&(Te(m,{force:!0}),me.current=!1,Ut(!1))},[L,w.activeRoom,Te]),a.useEffect(()=>{if(!l&&!se||se&&!z)return;const e=()=>{const o=!me.current;tn(),o&&z&&ce.current&&we("visibility-restore")},n=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pageshow",e)}},[z,Ke,l,se,tn,we]),a.useEffect(()=>{if(se||typeof ResizeObserver>"u")return;const e=ce.current;if(!e)return;const n=new ResizeObserver(()=>{me.current||Te(e)});return n.observe(e),()=>{n.disconnect()}},[se,Te,l?.id,L]),a.useEffect(()=>{Xa.current=ve},[ve]),a.useEffect(()=>()=>{for(const e of Xa.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of Mt.current.values())window.clearTimeout(e);Mt.current.clear()},[]);const ut=a.useCallback(e=>{if(!e||e.length===0)return;const n=[];for(const o of Array.from(e)){if(!sr.includes(o.type))continue;const m=o.type.startsWith("image/");n.push({file:o,previewUrl:m?URL.createObjectURL(o):""})}n.length>0&&at(o=>[...o,...n])},[]),es=a.useCallback(e=>{at(n=>{const o=n[e];return o?.previewUrl&&URL.revokeObjectURL(o.previewUrl),n.filter((m,v)=>v!==e)})},[]),ts=a.useCallback(e=>{ut(e.clipboardData?.files)},[ut]),mt=a.useCallback(async e=>{try{return await Y(e),kn(!1),z&&Oe(!1),!0}catch{return r(i("chat.failedToCreateSession","Failed to create chat session"),"error"),!1}},[Y,r,z,i]),nn=a.useCallback(()=>{if(M?.chatNewSessionMode==="always-default"&&b){if(b.kind==="agent"){mt({agentId:b.agentId});return}mt({agentId:ke,modelProvider:b.modelProvider,modelId:b.modelId,thinkingLevel:b.thinkingLevel});return}kn(!0)},[b,M?.chatNewSessionMode,mt]),ie=a.useCallback(e=>{const n=e??te.current;if(!n)return;const o=Qt==="tablet"?Yo:Na;n.style.height="auto",n.style.height=`${er(n.scrollHeight,o)}px`,n.style.overflowY=Zo(n.scrollHeight,o)},[Qt]),wi=Ns({textareaRef:te,value:q,onChange:re,onResize:()=>ie(te.current),projectId:s}),yi=Ns({textareaRef:Gt,value:q,onChange:re,onResize:()=>ie(Gt.current),projectId:s}),ki=a.useCallback(e=>{te.current=e,e&&ie(e)},[ie]),Ci=a.useCallback(e=>{Gt.current=e,e&&ie(e)},[ie]);a.useLayoutEffect(()=>{ie(L==="rooms"?Gt.current:te.current),_n.current&&(_n.current=!1,te.current?.focus())},[L,q,l?.id,w.activeRoom?.id,ie]),a.useEffect(()=>{if(E===void 0||E===Va.current||!R?.trim())return;Va.current=E;const e=n=>{n&&(On.current=!0),Ge("direct"),_n.current=!0,re(R)};if(!_&&M?.chatNewSessionMode==="always-default"&&b){const n=b.kind==="agent"?{agentId:b.agentId}:{agentId:ke,modelProvider:b.modelProvider,modelId:b.modelId,thinkingLevel:b.thinkingLevel};mt(n).then(o=>e(o||L!=="direct"));return}e(L!=="direct")},[b,L,M?.chatNewSessionMode,mt,R,E,_,ie]);const ht=a.useCallback(()=>{if(re(""),fe)try{localStorage.removeItem(fe)}catch{}Ue(!1),kt(""),tt(!1),et(""),nt(-1),at(e=>{for(const n of e)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);return[]})},[fe]),Wn=a.useCallback(()=>{const e=q.trim(),n=ve.map(m=>m.file);if(!e&&n.length===0||!l)return;if(x){const m=vo(e,Ps);if(m){if(!x.agentRunning){r(i("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}if(n.length>0){r(i("chat.commandNoAttachments","Attachments aren't supported with commands — remove them before sending"),"warning");return}ht(),m.command.run({taskId:x.taskId,projectId:x.projectId,remainder:m.remainder}).then(()=>{r(i("chat.commandSteerSuccess","Sent to the running agent"),"success")}).catch(v=>{const P=v instanceof Error&&v.message.trim()?v.message:i("chat.commandSteerFailed","Failed to send to the running agent");r(P,"error")});return}}if(e==="/clear"||e==="/new"){if(l.agentId.startsWith(bo)){ht(),r(i("chat.newNotAllowedForTaskChat","This chat is tied to a task — /new and /clear can't clear it"),"warning");return}ht(),ue(),de(),Y({agentId:l.agentId,modelProvider:l.modelProvider??void 0,modelId:l.modelId??void 0,thinkingLevel:l.thinkingLevel??void 0}).catch(()=>{r(i("chat.failedToClearConversation","Failed to clear conversation"),"error")});return}const o=new Set(n);re("");try{ge(e,n,{onDelivered:()=>{at(m=>{for(const v of m)o.has(v.file)&&v.previewUrl&&URL.revokeObjectURL(v.previewUrl);return m.filter(v=>!o.has(v.file))})},onFailed:()=>{re(m=>m||e)}})}catch{re(e)}},[q,ve,l,ht,de,ue,Y,r,ge,x,i]),Vn=a.useCallback(async()=>{const e=q.trim(),n=ve.map(o=>o.file);if(!(!e&&n.length===0)){if(L==="rooms"){if(!w.activeRoom)return;if(e==="/clear"||e==="/new"){ht();try{await w.clearRoom(w.activeRoom.id)}catch{r(i("chat.failedToClearRoomConversation","Failed to clear room conversation"),"error")}return}if($n.current)return;$n.current=!0;const o=q,m=new Set(n);re("");try{await w.sendRoomMessage(e,{files:n}),at(v=>{for(const P of v)m.has(P.file)&&P.previewUrl&&URL.revokeObjectURL(P.previewUrl);return v.filter(P=>!m.has(P.file))})}catch(v){if(v instanceof ii){at(U=>{for(const oe of U)m.has(oe.file)&&oe.previewUrl&&URL.revokeObjectURL(oe.previewUrl);return U.filter(oe=>!m.has(oe.file))});const ne=v.message.trim()?v.message:i("chat.messageSentButReplyFailed","Message sent, but assistant reply failed");r(i("chat.messageSentButReplyFailedDetail","Message sent, but assistant reply failed: {{detail}}",{detail:ne}),"error");return}re(o);const P=v instanceof Error&&v.message.trim()?v.message:i("chat.failedToSendRoomMessage","Failed to send room message");r(P,"error")}finally{$n.current=!1}return}Wn()}},[q,ve,Be,L,w,w.clearRoom,ht,r,Wn]),an=a.useCallback(async e=>{if(L==="rooms"){if(!w.activeRoom)return;try{await w.sendRoomMessage(e)}catch(n){const o=n instanceof Error&&n.message.trim()?n.message:i("chat.failedToSendRoomMessage","Failed to send room message");r(o,"error")}return}l&&ge(e)},[l,r,Be,L,w,ge,i]),Xn=a.useCallback(e=>{re(n=>{const o=ba(n);if(!o)return n;const m=`/skill:${e.name} `,v=n.slice(0,o.start)+m+n.slice(o.end);return window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus())}),v}),Ue(!1),kt(""),He(0)},[ie]),qn=a.useCallback((e,n)=>{if(n){r(i("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}re(o=>{const m=ba(o);if(!m)return o;const v=`${e.trigger} `,P=o.slice(0,m.start)+v+o.slice(m.end);return window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus())}),P}),Ue(!1),kt(""),He(0)},[ie,r,i]),sn=a.useCallback(e=>{const n=te.current;if(!n||Dn<0)return;const o=n.selectionStart??rt.current,m=n.selectionEnd??o,v=Math.max(o,m),P=Math.min(Dn,v),U=`${`@${e.name.replace(/\s+/g,"_")}`} `,oe=q.slice(0,P)+U+q.slice(v),ft=P+U.length;re(oe),tt(!1),et(""),Ot(0),nt(-1),window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus(),te.current.setSelectionRange(ft,ft))})},[Dn,q,ie]),Rt=a.useCallback((e,n)=>{const m=te.current?.selectionStart??rt.current,v=q.lastIndexOf("#",m),P=v>=0?v+n.length:e.length;re(e),W.dismissMention(),Wt(!1),window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus(),te.current.setSelectionRange(P,P))})},[W,q,ie]),ns=a.useCallback(e=>{if(rt.current=e.currentTarget.selectionStart??rt.current,W.mentionActive&&W.combinedItems.length>0){if(W.handleKeyDown(e,q),e.key==="Enter"||e.key==="Tab"){const n=W.combinedItems[W.selectedIndex];n?.kind==="task"?Rt(W.selectTask(n.task,q),`#${n.task.id}`):n?.kind==="file"&&Rt(W.selectFile(n.file,q),`#${n.file.path}`)}return}if(Se&&e.key==="ArrowDown"){e.preventDefault(),We.length>0&&Ot(n=>(n+1)%We.length);return}if(Se&&e.key==="ArrowUp"){e.preventDefault(),We.length>0&&Ot(n=>n===0?We.length-1:n-1);return}if(Se&&e.key==="Enter"){e.preventDefault();const n=We[Bt]??We[0];n&&sn(n);return}if(Se&&e.key==="Escape"){e.preventDefault(),tt(!1),et(""),nt(-1);return}if(Qe&&e.key==="ArrowDown"){e.preventDefault(),xe.length>0&&He(n=>(n+1)%xe.length);return}if(Qe&&e.key==="ArrowUp"){e.preventDefault(),xe.length>0&&He(n=>n===0?xe.length-1:n-1);return}if(Qe&&(e.key==="Enter"||e.key==="Tab")&&xe.length>0){e.preventDefault();const n=xe[Je]??xe[0];n?.kind==="skill"?Xn(n.skill):n?.kind==="command"&&qn(n.command,n.disabled);return}if(Qe&&e.key==="Escape"){e.preventDefault(),Ue(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Vn())},[Se,We,Bt,sn,Qe,xe,Je,Xn,qn,Vn,W,Rt,q]),on=a.useCallback((e,n)=>{const o=ir(e,n);if(o){tt(!0),et(o.filter),nt(o.start);return}tt(!1),et(""),nt(-1)},[]),as=a.useCallback(e=>{const n=e.target,o=n.value,m=n.selectionStart??o.length;ie(n),rt.current=m,re(o);const v=ba(o);v?(Ue(!0),kt(v.filter)):(Ue(!1),kt("")),on(o,m),W.detectMention(o,m),Wt(W.mentionActive),W.mentionActive&&In(n)},[on,ie]),rn=a.useCallback(e=>{const n=e.currentTarget,o=n.selectionStart??n.value.length;rt.current=o,on(n.value,o),W.detectMention(n.value,o),Wt(W.mentionActive),W.mentionActive&&In(n)},[on,W,In]),ss=a.useCallback(e=>{e.key!=="Escape"&&rn(e)},[rn]),is=a.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(qt.current=!0,Re.current!==null&&window.clearTimeout(Re.current),Re.current=window.setTimeout(()=>{qt.current=!1,Re.current=null},450),(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0),je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{je.current=null,document.activeElement?.tagName!=="TEXTAREA"&&(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},350)),Ne.current!==null&&window.clearTimeout(Ne.current),Ne.current=window.setTimeout(()=>{Ue(!1),tt(!1),et(""),nt(-1),Wt(!1),W.dismissMention(),Ne.current=null},120)},[W]),os=a.useCallback(()=>{qt.current=!1,Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null),Ne.current!==null&&(window.clearTimeout(Ne.current),Ne.current=null),je.current!==null&&(window.clearTimeout(je.current),je.current=null)},[]);a.useEffect(()=>()=>{Re.current!==null&&window.clearTimeout(Re.current),je.current!==null&&window.clearTimeout(je.current)},[]);const Si=a.useCallback(async e=>{Ce(null);try{await D(e),r(i("chat.conversationArchived","Conversation archived"),"success")}catch{r(i("chat.failedToArchiveConversation","Failed to archive conversation"),"error")}},[D,r]),rs=a.useCallback(e=>{const n=Pe.find(o=>o.id===e)??(l?.id===e?l:null);Ce(null),Me(!1),Mn(n?.title??""),Lt({sessionId:e,title:n?.title??""})},[l,Pe]),cs=a.useCallback(async()=>{if(It)try{await $(It.sessionId,Sn),Lt(null),Mn(""),r(i("chat.conversationRenamed","Conversation renamed"),"success")}catch{}},[r,It,$,Sn,i]),ls=a.useCallback(async(e,n)=>{Ce(null),Me(!1);try{await Q(e,n),r(n?i("chat.conversationPinned","Conversation pinned"):i("chat.conversationUnpinned","Conversation unpinned"),"success")}catch{}},[r,Q,i]),Mi=a.useCallback(async e=>{Pt(null),Ce(null);try{await le(e),r(i("chat.conversationDeleted","Conversation deleted"),"success")}catch{r(i("chat.failedToDeleteConversation","Failed to delete conversation"),"error")}},[le,r]),jt=a.useCallback(e=>{try{localStorage.setItem(qs,String(e))}catch{}},[]),Ni=a.useCallback(e=>{if(z||Nt)return;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;typeof n.setPointerCapture=="function"&&n.setPointerCapture(e.pointerId);const o=e.clientX,m=Ye;let v=m;document.body.style.userSelect="none";const P=U=>{const oe=U.clientX-o,ft=Math.max(gn,Math.min(pn,m+oe));v=ft,An(ft),jt(ft)},ne=U=>{typeof n.releasePointerCapture=="function"&&n.releasePointerCapture(U.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",P),document.removeEventListener("pointerup",ne),jt(v)};document.addEventListener("pointermove",P),document.addEventListener("pointerup",ne)},[z,jt,Ye,Nt]),Ri=a.useCallback(e=>{if(z||Nt||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const n=e.shiftKey?50:10,o=e.key==="ArrowLeft"?-n:n,m=Math.max(gn,Math.min(pn,Ye+o));An(m),jt(m)},[z,jt,Ye,Nt]),ds=a.useCallback(e=>{const n=Pe.find(o=>o.id===e);he("direct",e,n?.lastMessageAt??n?.updatedAt),Z(e),Me(!1),z&&Oe(!1)},[Pe,z,he,Z]),Gn=a.useCallback(()=>{Z(""),Oe(!0),Me(!1)},[Z]),Yn=a.useCallback(()=>{w.selectRoom(null),Oe(!0),Me(!1)},[w]),ji=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(vn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:i("chat.startNewConversation","Start a new conversation")}),t.jsxs("button",{className:"btn btn-primary",onClick:nn,children:[t.jsx(gt,{size:16}),i("chat.newChat","New Chat")]})]}),Ee=Zs(l,l?.agentId?be.get(l.agentId)??null:null,zt),Qn=a.useMemo(()=>{if(!Ee?.provider||!Ee.modelId)return null;const e=Tn.find(n=>n.provider===Ee.provider&&n.id===Ee.modelId);return e?.contextWindow?e.contextWindow:null},[Ee?.modelId,Ee?.provider,Tn]),Ai=a.useMemo(()=>Go(N,_?K:void 0),[_,N,K]),_e=Rs(Ee?.provider,Ee?.modelId),Ve=Ee?.provider??null,Jn=!!(l||_||N.length>0),cn=z&&!wt&&(L==="rooms"?se:Jn),ln=z?cn:L==="rooms"?se:!!l,us=a.useRef(ln);a.useEffect(()=>{const e=us.current;us.current=ln,z&&(e||!ln||Ba({type:"view",revert:L==="rooms"?Yn:Gn}))},[L,Gn,Yn,ln,z,Ba]);const ms=l?.agentId===ke?_e??"Fusion":l?.title||be.get(l?.agentId??"")?.name||l?.agentId||"Chat",Ti=l?.title||i("chat.untitledSession","Untitled"),Ei=!!(_e&&_e!==ms),Di=!z&&Jn&&Qn!==null,hs=Vs(Ai),dn=Qn!==null?Vs(Qn):null,Zn=dn?i("chat.contextWindowAria","Estimated {{used}} of {{total}} context tokens",{used:hs,total:dn}):null,Ii=cn&&L==="direct"&&!!l,fs=cn&&L==="direct",gs=cn&&L==="rooms",ea=be.get(l?.agentId??"")?.name||(l?.agentId===ke?_e??"Fusion":l?.agentId?.slice(0,30)??"Fusion"),ta=!1,na=l?.agentId===ke,Li=e=>e.length>50?`${e.slice(0,50)}…`:e;a.useEffect(()=>{if(!Ht)return;const e=n=>{Ha.current?.contains(n.target)||Me(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[Ht]),a.useEffect(()=>{if(!Kt)return;const e=o=>{Ka.current?.contains(o.target)||Ct(!1)},n=o=>{o.key==="Escape"&&Ct(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",n),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",n)}},[Kt]),a.useEffect(()=>{(!z||L!=="direct"||wt)&&Me(!1)},[z,L,wt]),a.useEffect(()=>{Ct(!1)},[w.activeRoom?.id]);const ps=a.useCallback((e,n)=>{const o=Mt.current.get(e);o&&window.clearTimeout(o),za(v=>({...v,[e]:n}));const m=window.setTimeout(()=>{za(v=>{const{[e]:P,...ne}=v;return ne}),Mt.current.delete(e)},2e3);Mt.current.set(e,m)},[]),vs=a.useCallback(async(e,n)=>{const o=await xo(n);ps(e,o?"success":"error")},[ps]),aa=l?.agentId===ke,sa=a.useCallback((e,n,o)=>t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${it[e]==="success"?" chat-message-copy-action--success":""}${it[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":o??`chat-copy-response-${e}`,"aria-label":it[e]==="success"?i("chat.responseCopied","Response copied"):it[e]==="error"?i("chat.copyFailed","Copy failed"):i("chat.copyResponse","Copy response"),onClick:()=>{vs(e,n)},children:it[e]==="success"?t.jsx(wo,{size:14}):t.jsx(yo,{size:14})}),[it,vs]),ia=a.useCallback(e=>{const n=ce.current;if(!n)return;const o=`[data-testid="chat-message-${e}"]`,m=n.querySelector(o);if(!m)return;const v=m.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop,P=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;n.scrollTo({top:v,behavior:P?"auto":"smooth"})},[]),bs=l?.cliExecutorAdapterId??null,oa=!!bs,Pi=bs==="generic"?"generic":"hybrid",Fi=l?.cliSessionFile||l?.id||"",xs=!oa&&!_,ws=()=>t.jsxs("div",{className:"chat-messages",ref:ce,onScroll:Za,children:[t.jsx("div",{ref:Ua,className:"chat-load-more-sentinel",children:pe&&V&&t.jsx("div",{className:"chat-loading-older",children:i("chat.loadingOlderMessages","Loading older messages…")})}),_?t.jsxs(t.Fragment,{children:[N.map((e,n)=>t.jsx(ua,{message:e,forcePlain:!1,agentName:ea,hideAssistantIdentity:na,showAssistantModelTag:ta,activeModelTag:_e,activeModelProvider:Ve,activeSessionId:l?.id??null,projectId:s,mentionAgentsByName:Hn,roomContext:null,copyAction:aa&&e.role==="assistant"?sa(e.id,e.content):void 0,onScrollToTop:ia,isTopClipped:Fn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===N.length-1&&!_,submittedQuestionAnswer:Gs(N,n),onQuestionSubmit:an,canEdit:xs,onEditMessage:ae},e.id)),t.jsx(jo,{streamingText:K,streamingThinking:I,streamingToolCalls:ee,forcePlain:!1,agentName:ea,hideAssistantIdentity:na,showAssistantModelTag:ta,activeModelTag:_e,activeModelProvider:Ve,copyAction:aa&&K?sa("__streaming__",K,"chat-copy-response-streaming"):void 0,onQuestionSubmit:an})]}):V?t.jsx("div",{className:"chat-empty-state",children:i("chat.loadingMessages","Loading messages...")}):N.length===0&&!l?ji():N.length===0&&l?t.jsx("div",{className:"chat-empty-state",children:i("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsx(t.Fragment,{children:N.map((e,n)=>t.jsx(ua,{message:e,forcePlain:!1,agentName:ea,hideAssistantIdentity:na,showAssistantModelTag:ta,activeModelTag:_e,activeModelProvider:Ve,activeSessionId:l?.id??null,projectId:s,mentionAgentsByName:Hn,roomContext:null,copyAction:aa&&e.role==="assistant"?sa(e.id,e.content):void 0,onScrollToTop:ia,isTopClipped:Fn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===N.length-1&&!_,submittedQuestionAnswer:Gs(N,n),onQuestionSubmit:an,canEdit:xs,onEditMessage:ae},e.id))}),t.jsx("div",{ref:Oa})]}),ys=()=>t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file","data-testid":"chat-file-input",accept:Js,multiple:!0,style:{display:"none"},onChange:e=>{ut(e.target.files),e.target.value=""}}),Qe&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":i("chat.skillSuggestions","Skill suggestions"),children:fi&&Un.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:i("chat.loadingSkills","Loading skills…")}):xe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:yt?i("chat.noSkillsFound","No skills found"):i("chat.noSkillsAvailable","No skills available")}):xe.map((e,n)=>e.kind==="command"?t.jsxs("button",{type:"button",role:"option","aria-selected":n===Je,"aria-disabled":e.disabled,className:`chat-skill-menu-item chat-command-menu-item${n===Je?" chat-skill-menu-item--highlighted":""}${e.disabled?" chat-command-menu-item--disabled":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>He(n),onClick:()=>qn(e.command,e.disabled),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.command.trigger}),t.jsx("span",{className:"chat-skill-menu-item-description",children:e.disabled?i("chat.commandNoRunningAgentHint","No running agent to steer"):e.command.description})]},`command-${e.command.trigger}`):t.jsxs("button",{type:"button",role:"option","aria-selected":n===Je,className:`chat-skill-menu-item${n===Je?" chat-skill-menu-item--highlighted":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>He(n),onClick:()=>Xn(e.skill),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.skill.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.skill.relativePath,children:e.skill.relativePath})]},e.skill.id))}),ve.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ve.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),Ie.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-pending-stack","data-testid":"chat-pending-stack",children:Ie.map((e,n)=>t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:i("chat.queuedMessage","Queued: {{preview}}",{preview:Li(e)})}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":i("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":`chat-pending-dismiss-${n}`,onClick:()=>ue(n),children:"×"})]},`${n}-${e}`))}),t.jsx("div",{className:"chat-pending-divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":i("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Ds,{size:16})}),!oa&&t.jsx(Bs,{level:l?.thinkingLevel,defaultThinkingLevel:T,models:Tn,favoriteProviders:ui,favoriteModels:mi,agents:Array.from(be.values()),agentId:l?.agentId,modelProvider:l?.modelProvider,modelId:l?.modelId,onChange:e=>{l&&H(l.id,e)},onChangeModel:e=>{l&&A(l.id,e)},disabled:!l}),t.jsxs("div",{className:`chat-input-wrapper${_a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),st(!0)},onDragLeave:()=>st(!1),onDrop:e=>{e.preventDefault(),st(!1),ut(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:ki,className:"chat-input-textarea",placeholder:i("chat.typeMessage","Type a message..."),value:q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:rn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ma()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Us,{agents:ct,filter:Ze,highlightedIndex:Bt,visible:Se,onSelect:sn,position:"below",roomMemberIds:Ae?.memberIds,roomName:Ae?.roomName}),t.jsx($o,{visible:W.mentionActive&&!Se,position:gi,tasks:W.tasks,files:W.files,selectedIndex:W.selectedIndex,onSelectTask:e=>{Rt(W.selectTask(e,q),`#${e.id}`)},onSelectFile:e=>{Rt(W.selectFile(e,q),`#${e.path}`)},loading:W.loading})]}),t.jsx(Is,{...wi.micProps}),t.jsx(Ls,{isStreaming:_,canSend:!!(q.trim()||ve.length>0),onSend:Wn,onStop:de})]})]}),_i=z?void 0:{width:`${Ye}px`},ks=Pe.filter(e=>e.pinnedAt!=null),Cs=Pe.filter(e=>e.pinnedAt==null),ye=G?Pe.find(e=>e.id===G.sessionId)??(l?.id===G.sessionId?l:void 0):void 0,Ss=a.useCallback(async()=>{const e=Nn.trim();if(!e)return;let n;try{n=await f(e)}catch{r(i("chat.failedToCreateTag","Failed to create tag"),"error");return}if(G?.sessionId){const o=(ye?.tags??[]).map(m=>m.id);if(!o.includes(n.id))try{await J(G.sessionId,[...o,n.id])}catch{r(i("chat.failedToUpdateTags","Failed to update tags"),"error");return}}Ea("")},[r,G,ye,f,Nn,J,i]),$i=Ii?t.jsxs("div",{className:"chat-mobile-session-menu",ref:Ha,children:[t.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":Ht,onClick:()=>Me(e=>!e),children:[Ve?t.jsx(ca,{provider:Ve,size:"md"}):t.jsx(xn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:Ti}),t.jsx(un,{size:16,"aria-hidden":"true"})]}),Ht&&t.jsxs("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:[[{id:"pinned",label:i("chat.pinned","Pinned"),testId:"chat-mobile-pinned-divider",sessions:ks},{id:"recent",label:i("chat.recent","Recent"),testId:"chat-mobile-recent-divider",sessions:Cs}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-mobile-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>t.jsxs("div",{className:`chat-mobile-session-option-row${l?.id===n.id?" chat-mobile-session-option-row--active":""}`,role:"none",children:[t.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${l?.id===n.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${n.id}`,onClick:()=>ds(n.id),children:t.jsxs("span",{className:"chat-mobile-session-option-title",children:[n.title||i("chat.untitledSession","Untitled"),n.pinnedAt?t.jsx(mn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":i("chat.pinned","Pinned")}):null]})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-pin","data-testid":`chat-mobile-session-pin-${n.id}`,"aria-label":n.pinnedAt?i("chat.unpinConversationAria","Unpin conversation {{title}}",{title:n.title||i("chat.untitledSession","Untitled")}):i("chat.pinConversationAria","Pin conversation {{title}}",{title:n.title||i("chat.untitledSession","Untitled")}),title:!n.pinnedAt&&O>=3?i("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:!n.pinnedAt&&O>=3,onClick:()=>ls(n.id,!n.pinnedAt),children:n.pinnedAt?t.jsx(js,{size:14}):t.jsx(mn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-rename","data-testid":`chat-mobile-session-rename-${n.id}`,"aria-label":i("chat.renameConversationAria","Rename conversation {{title}}",{title:n.title||i("chat.untitledSession","Untitled")}),onClick:()=>rs(n.id),children:t.jsx(la,{size:14})})]},n.id))]},e.id)),t.jsxs("button",{type:"button",role:"menuitem",className:"chat-mobile-session-new","data-testid":"chat-mobile-session-new",onClick:()=>{Me(!1),nn()},children:[t.jsx(gt,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:i("chat.newChat","New Chat")})]})]})]}):null,zi=t.jsxs("div",{className:"chat-sidebar-scope-toggle chat-view-header-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${L==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":L==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>Ge("direct"),children:[t.jsx(vn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:i("chat.scopeDirect","Direct")})]}),t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${L==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":L==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>Ge("rooms"),children:[t.jsx(si,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:i("chat.scopeRooms","Rooms")})]})]});return t.jsxs("div",{ref:qa,className:`chat-view${u?" chat-view--floating":""}${z?" chat-view--narrow":""}${fs?" chat-view--mobile-direct-thread":""}`,children:[t.jsx(ko,{icon:vn,title:i("chat.title","Chat"),actions:t.jsxs(t.Fragment,{children:[fs?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn-icon chat-back-btn",onClick:Gn,"data-testid":"chat-back-btn","aria-label":i("chat.backToConversations","Back to conversations"),children:t.jsx(As,{size:16})}),$i]}):zi,z?null:t.jsxs("button",{className:"btn btn-sm btn-primary chat-view-header-new-chat",onClick:nn,"data-testid":"chat-new-btn",children:[t.jsx(gt,{size:14}),i("chat.newChat","New Chat")]}),!u&&d?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:d,"aria-label":i("chat.popOut","Pop out chat"),title:i("chat.popOut","Pop out chat"),"data-testid":"chat-pop-out",children:t.jsx(Ts,{size:16})}):null,u&&h?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:h,"aria-label":i("chat.maximizeToChatView","Open in Chat view"),title:i("chat.maximizeToChatView","Open in Chat view"),"data-testid":"chat-modal-maximize",children:t.jsx(Ts,{size:16})}):null,u&&C?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:C,"aria-label":i("chat.minimizeToQuickChat","Minimize to quick chat"),title:i("chat.minimizeToQuickChat","Minimize to quick chat"),"data-testid":"chat-modal-minimize",children:t.jsx(Co,{size:16})}):null,u&&S?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:S,"aria-label":i("chat.closeChat","Close chat"),title:i("chat.closeChat","Close chat"),"data-testid":"chat-modal-close",children:t.jsx(Es,{size:16})}):null]})}),t.jsxs("div",{className:"chat-view__body",children:[t.jsxs("div",{className:`chat-sidebar${wt?"":" chat-sidebar--hidden"}`,style:_i,children:[L==="direct"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-sidebar-search-container",children:[t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(So,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:i("chat.searchConversations","Search conversations..."),value:qe,onChange:e=>ci(e.target.value),"data-testid":"chat-search-input"})]}),t.jsxs("label",{className:"chat-tag-filter",htmlFor:"chat-tag-filter",children:[t.jsx(Eo,{size:14,"aria-hidden":"true"}),t.jsxs("select",{id:"chat-tag-filter",value:p??"",onChange:e=>y(e.target.value||null),"data-testid":"chat-tag-filter","aria-label":i("chat.filterByTag","Filter conversations by tag"),children:[t.jsx("option",{value:"",children:i("chat.allTags","All tags")}),c.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]}),p?t.jsx("button",{type:"button",className:"btn-icon","aria-label":i("chat.clearTagFilter","Clear tag filter"),onClick:()=>y(null),children:t.jsx(Es,{size:14})}):null]})]}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:B?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:i("chat.loadingConversations","Loading...")}):Pe.length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:i("chat.noConversationsYet","No conversations yet")}):t.jsx(t.Fragment,{children:[{id:"pinned",label:i("chat.pinned","Pinned"),testId:"chat-pinned-divider",sessions:ks},{id:"recent",label:i("chat.recent","Recent"),testId:"chat-recent-divider",sessions:Cs}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>{const o=l?.id===n.id,m=!o&&Ra("direct",n.id,n.lastMessageAt??n.updatedAt),v=Zs(n,be.get(n.agentId)??null,zt),P=Rs(v?.provider,v?.modelId)??"Fusion",ne=n.title||i("chat.untitledSession","Untitled");return t.jsxs("div",{className:`chat-session-item${o?" chat-session-item--active":""}`,onClick:()=>ds(n.id),onContextMenu:U=>{U.preventDefault(),ja(n.id,U.clientX,U.clientY)},"data-testid":`chat-session-${n.id}`,children:[t.jsx("button",{type:"button",className:"btn-icon chat-session-menu-btn","data-testid":"chat-session-menu-btn","aria-label":i("chat.conversationActionsAria","Conversation actions for {{title}}",{title:ne}),"aria-haspopup":"menu","aria-expanded":G?.sessionId===n.id,onClick:U=>{if(U.stopPropagation(),G?.sessionId===n.id){Ce(null);return}const oe=U.currentTarget.getBoundingClientRect();ja(n.id,oe.right,oe.bottom,{anchorRight:!0})},children:t.jsx(Mo,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[ne,n.pinnedAt?t.jsx(mn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":i("chat.pinned","Pinned")}):null,m?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${n.id}`,"aria-label":i("chat.unreadMessages","Unread messages")}):null]}),t.jsx("div",{className:"chat-session-preview",children:n.lastMessagePreview||i("chat.noMessages","No messages")}),(n.tags??[]).length>0?t.jsx("div",{className:"chat-session-tags","data-testid":`chat-session-tags-${n.id}`,children:(n.tags??[]).map(U=>t.jsx("span",{className:"chat-session-tag",children:U.name},U.id))}):null,n.matchedMessagePreview?t.jsx("div",{className:"chat-session-preview chat-session-preview--matched","data-testid":`chat-session-matched-preview-${n.id}`,children:i("chat.matchedInMessage",'Matched: "{{preview}}"',{preview:n.matchedMessagePreview})}):null,t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[v?.provider?t.jsx(ca,{provider:v.provider,size:"sm"}):null,t.jsx("span",{children:be.get(n.agentId)?.name||(n.agentId===ke?P:n.agentId.slice(0,30))})]}),t.jsx("span",{children:n.updatedAt?tr(n.updatedAt,i):""})]})]},n.id)})]},e.id))})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!z&&t.jsx("div",{className:"chat-sidebar-rooms-header","data-testid":"chat-sidebar-rooms-header",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary","data-testid":"chat-create-room-btn",onClick:()=>$t(!0),children:[t.jsx(gt,{size:14}),i("chat.createRoom","Create room")]})}),w.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:i("chat.noRoomsYet","No rooms yet.")}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:w.rooms.map(e=>{const n=w.activeRoom?.id===e.id,o=!n&&Ra("room",e.id,e.updatedAt);return t.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${n?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${e.slug}`,onClick:()=>{he("room",e.id,e.updatedAt),w.selectRoom(e.id),z&&Oe(!1)},onKeyDown:m=>{(m.key==="Enter"||m.key===" ")&&(m.preventDefault(),he("room",e.id,e.updatedAt),w.selectRoom(e.id),z&&Oe(!1))},children:[t.jsxs("span",{className:"chat-room-item-details",children:[t.jsxs("span",{className:"chat-room-item-name-row",children:[t.jsxs("span",{className:"chat-room-item-name",children:["#",e.name]}),o?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":i("chat.unreadMessages","Unread messages")}):null]}),n?t.jsx("span",{className:"chat-room-item-meta",children:i("chat.roomMemberCount","{{count}} member",{count:w.activeRoomMembers.length,defaultValue_one:"{{count}} member",defaultValue_other:"{{count}} members"})}):null]}),t.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${e.slug}`,"aria-label":i("chat.deleteRoom","Delete room {{name}}",{name:e.name}),onClick:m=>{m.stopPropagation(),Ft(e.id)},children:t.jsx(da,{size:14})})]},e.id)})})]}),L==="rooms"?z?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary chat-sidebar-footer-btn","data-testid":"chat-create-room-btn",onClick:()=>$t(!0),children:[t.jsx(gt,{size:14}),i("chat.createRoom","Create room")]})}):null:z?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:nn,"data-testid":"chat-new-btn",children:[t.jsx(gt,{size:14}),i("chat.newChat","New Chat")]})}):null]}),!z&&wt&&!Nt&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":gn,"aria-valuemax":pn,"aria-valuenow":Ye,"aria-label":i("chat.resizeSidebar","Resize chat sidebar"),tabIndex:0,onPointerDown:Ni,onKeyDown:Ri}),G&&t.jsxs("div",{className:"chat-session-context-menu",ref:Cn,role:"menu",style:{top:G.y,left:G.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>ls(G.sessionId,!ye?.pinnedAt),"data-testid":"chat-context-pin",title:O>=3&&!ye?.pinnedAt?i("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:O>=3&&!ye?.pinnedAt,children:[ye?.pinnedAt?t.jsx(js,{size:14}):t.jsx(mn,{size:14}),ye?.pinnedAt?i("chat.unpin","Unpin"):i("chat.pin","Pin")]}),t.jsxs("button",{onClick:()=>rs(G.sessionId),"data-testid":"chat-context-rename",children:[t.jsx(la,{size:14}),i("chat.rename","Rename")]}),t.jsxs("div",{className:"chat-session-tag-menu",role:"group","aria-label":i("chat.conversationTags","Conversation tags"),children:[c.map(e=>{const n=(ye?.tags??[]).some(o=>o.id===e.id);return t.jsxs("div",{className:"chat-tag-menu-item",children:[t.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,"data-testid":`chat-context-tag-${e.id}`,onClick:()=>void J(G.sessionId,n?(ye?.tags??[]).filter(o=>o.id!==e.id).map(o=>o.id):[...(ye?.tags??[]).map(o=>o.id),e.id]).catch(()=>r(i("chat.failedToUpdateTags","Failed to update tags"),"error")),children:[n?"✓ ":"",e.name]}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":i("chat.renameTag","Rename tag {{name}}",{name:e.name}),"data-testid":`chat-context-rename-tag-${e.id}`,onClick:o=>{o.stopPropagation(),Da(e.name),xt(e)},children:t.jsx(la,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":i("chat.deleteTag","Delete tag {{name}}",{name:e.name}),"data-testid":`chat-context-delete-tag-${e.id}`,onClick:o=>{o.stopPropagation(),_t(e)},children:t.jsx(da,{size:14})})]},e.id)}),t.jsxs("div",{className:"chat-tag-create-row",children:[t.jsx("input",{className:"input",value:Nn,placeholder:i("chat.newTag","New tag"),"aria-label":i("chat.newTag","New tag"),onChange:e=>Ea(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),Ss())}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Ss(),children:i("chat.addTag","Add")})]})]}),t.jsxs("button",{onClick:()=>Si(G.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(No,{size:14}),i("chat.archive","Archive")]}),t.jsxs("button",{onClick:()=>{Ce(null),Pt(G.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(da,{size:14}),i("chat.delete","Delete")]})]}),It&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>Lt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-dialog-title",children:i("chat.renameConversationTitle","Rename Conversation")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:i("chat.renameConversationBody","Choose a new name for this conversation. Leave it blank to show Untitled.")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-input",children:i("chat.conversationName","Conversation name")}),t.jsx("input",{id:"chat-rename-input",className:"input chat-rename-input",type:"text",value:Sn,placeholder:i("chat.renamePlaceholder","Untitled"),"data-testid":"chat-rename-input",onChange:e=>Mn(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),cs())},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Lt(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void cs(),"data-testid":"chat-rename-save",children:i("chat.save","Save")})]})]})}),Rn&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>xt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-tag-dialog-title",children:i("chat.renameTagTitle","Rename tag")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-tag-input",children:i("chat.tagName","Tag name")}),t.jsx("input",{id:"chat-rename-tag-input",className:"input chat-rename-input",value:jn,"data-testid":"chat-rename-tag-input",onChange:e=>Da(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),j(Rn.id,jn).then(()=>xt(null)).catch(()=>r(i("chat.failedToRenameTag","Failed to rename tag"),"error")))},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>xt(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary","data-testid":"chat-rename-tag-save",onClick:()=>void j(Rn.id,jn).then(()=>xt(null)).catch(()=>r(i("chat.failedToRenameTag","Failed to rename tag"),"error")),children:i("chat.save","Save")})]})]})}),Ia&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>_t(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-delete-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-delete-tag-dialog-title",children:i("chat.deleteTagTitle","Delete tag?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:i("chat.deleteTagBody","This removes the tag from all conversations, but does not delete conversations.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>_t(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger","data-testid":"chat-delete-tag-confirm",onClick:()=>void F(Ia.id).then(()=>_t(null)).catch(()=>r(i("chat.failedToDeleteTag","Failed to delete tag"),"error")),children:i("chat.delete","Delete")})]})]})}),Aa&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>Pt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:i("chat.deleteConversationTitle","Delete Conversation?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:i("chat.deleteConversationBody","This action cannot be undone. All messages in this conversation will be permanently deleted.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Pt(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Mi(Aa),children:i("chat.delete","Delete")})]})]})}),Ta&&t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",onClick:()=>Ft(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:i("chat.deleteRoomTitle","Delete Room?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:i("chat.deleteRoomBody","This action cannot be undone. This room and all its messages will be permanently deleted.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Ft(null),children:i("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await w.deleteRoom(Ta),Ft(null)}catch{r(i("chat.failedToDeleteRoom","Failed to delete room"),"error")}})()},children:i("chat.delete","Delete")})]})]})}),L==="rooms"?t.jsxs("div",{ref:Pn,className:"chat-thread",children:[w.activeRoom?t.jsxs(t.Fragment,{children:[(!z||gs)&&t.jsxs("div",{className:"chat-room-thread-header",children:[gs&&t.jsx("button",{className:"btn-icon",onClick:Yn,"data-testid":"chat-back-btn",children:t.jsx(As,{size:16})}),t.jsxs("div",{className:"chat-room-switcher-menu",ref:Ka,children:[t.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":Kt,onClick:()=>Ct(e=>!e),children:[t.jsxs("span",{className:"chat-thread-header-title",children:["#",w.activeRoom.name]}),t.jsx(un,{size:16,"aria-hidden":"true"})]}),Kt&&t.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:w.rooms.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${e.id===w.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${e.id}`,onClick:()=>{he("room",e.id,e.updatedAt),w.selectRoom(e.id),Ct(!1)},children:["#",e.name]},e.id))})]}),t.jsx("div",{className:"chat-room-thread-members",children:w.activeRoomMembers.map(e=>t.jsx(wn,{agent:be.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:ce,onScroll:Za,children:[w.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:i("chat.loadingMessages","Loading messages...")}):w.messages.filter(e=>e.content.trim()!==Xs).length===0?t.jsx("div",{className:"chat-empty-state",children:i("chat.noMessagesYet","No messages yet. Start the conversation!")}):w.messages.filter(e=>e.content.trim()!==Xs).map(e=>{const n=e.senderAgentId?be.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):i("chat.you","You"),o={id:e.id,sessionId:e.roomId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput??void 0,toolCalls:void 0,fallbackInfo:void 0,attachments:e.attachments,createdAt:e.createdAt};return t.jsx(ua,{message:o,forcePlain:!1,agentName:n,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:w.activeRoom?.id??null,projectId:s,mentionAgentsByName:Hn,roomContext:Ae,onScrollToTop:ia,isTopClipped:Fn.has(e.id),isAwaitingQuestionAnswer:!1,onQuestionSubmit:an},e.id)}),t.jsx("div",{ref:Oa})]}),w.activeRoom&&$a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(un,{size:14}),i("chat.latest","Latest")]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:i("chat.selectRoomOrCreate","Select a room or create one")}),w.activeRoom&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file",accept:Js,multiple:!0,style:{display:"none"},onChange:e=>{ut(e.target.files),e.target.value=""}}),ve.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ve.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":i("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Ds,{size:16})}),t.jsx(Bs,{level:w.activeRoom.thinkingLevel,defaultThinkingLevel:T,showTargetSection:!1,onChange:e=>{w.updateRoomSettings(w.activeRoom.id,{thinkingLevel:e||null}).catch(()=>{r(i("chat.failedToUpdateRoomThinkingLevel","Failed to update room thinking effort"),"error")})}}),t.jsxs("div",{className:`chat-input-wrapper${_a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),st(!0)},onDragLeave:()=>st(!1),onDrop:e=>{e.preventDefault(),st(!1),ut(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:Ci,className:"chat-input-textarea",placeholder:i("chat.typeMessage","Type a message..."),value:q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:rn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ma()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Us,{agents:ct,filter:Ze,highlightedIndex:Bt,visible:Se,onSelect:sn,position:"below",roomMemberIds:Ae?.memberIds,roomName:Ae?.roomName})]}),t.jsx(Is,{...yi.micProps}),t.jsx(Ls,{isStreaming:!1,canSend:!!(q.trim()||ve.length>0),onSend:Vn})]})]})]}):t.jsxs("div",{ref:Pn,className:"chat-thread",children:[!z&&(Jn||!z)&&t.jsx("div",{className:"chat-thread-header",children:t.jsxs("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:[Ve?t.jsx(ca,{provider:Ve,size:"md"}):t.jsx(xn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:ms}),Ei&&t.jsx("span",{className:"chat-model-tag",children:_e}),Di&&dn&&Zn?t.jsxs("span",{className:"chat-thread-header-context","data-testid":"chat-thread-context-window",title:Zn,"aria-label":Zn,children:[hs," / ",dn]}):null]})}),oa?t.jsx(Oo,{cliSessionId:Fi,tier:Pi,projectId:s,renderTranscript:ws,renderComposer:()=>l?ys():null}):t.jsxs(t.Fragment,{children:[ws(),$a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(un,{size:14}),i("chat.latest","Latest")]}),l&&ys()]})]}),t.jsx(Bo,{isOpen:di,onClose:()=>$t(!1),projectId:s,existingRoomNames:w.rooms.map(e=>e.name),onCreate:async e=>{await w.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),L!=="rooms"&&Ge("rooms"),$t(!1),z&&Oe(!1)}})]}),li&&t.jsx(rr,{projectId:s,defaultModel:hi,defaultKind:b?.kind,defaultAgentId:b?.kind==="agent"?b.agentId:void 0,defaultThinkingLevel:T,defaultSelectedThinkingLevel:b?.kind==="model"?b.thinkingLevel:void 0,onClose:()=>kn(!1),onCreate:mt})]})}export{vr as ChatView,pr as buildIssueChatPrefill,er as clampChatInputHeight,Jo as resolveChatContextMenuPosition,Zo as resolveChatInputOverflowY,Zs as resolveSessionProvider};
|