@runfusion/fusion 0.77.0-beta.2 → 0.77.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 +12324 -8618
- package/dist/child-process-worker.js +8252 -6106
- package/dist/client/.vite/manifest.json +294 -267
- package/dist/client/assets/{AgentDetailView-Dew3af1O.js → AgentDetailView-CH6GtXl9.js} +3 -3
- package/dist/client/assets/{AgentPermissionPolicyEditor-CxPQffiY.js → AgentPermissionPolicyEditor-YTEpMhUx.js} +1 -1
- package/dist/client/assets/{AgentsView-Cr4LDGdt.js → AgentsView-XOHHDo4a.js} +4 -4
- package/dist/client/assets/ChatView-gH7QX3TI.js +13 -0
- package/dist/client/assets/{CommandCenter-DCC90LOP.js → CommandCenter-BsH-R15f.js} +3 -3
- package/dist/client/assets/{DevServerView-B5b520w6.js → DevServerView-CKOa-lkc.js} +1 -1
- package/dist/client/assets/{DirectoryPicker-1JvRd5mC.js → DirectoryPicker-DHUYTE-j.js} +1 -1
- package/dist/client/assets/DocumentsView-BPzrxeP-.js +1 -0
- package/dist/client/assets/{EvalsView-a3LhgRSo.js → EvalsView-DojCiv47.js} +1 -1
- package/dist/client/assets/{ExperimentalAgentOnboardingModal-vdVa8h7F.js → ExperimentalAgentOnboardingModal-DuurZ8qe.js} +1 -1
- package/dist/client/assets/{GoalsView-Dz2o91fd.js → GoalsView-DDWPXcG1.js} +1 -1
- package/dist/client/assets/{InsightsView-De3R_46d.js → InsightsView-CgkMOD1A.js} +3 -3
- package/dist/client/assets/MemoryView-Cj49_z7O.js +3 -0
- package/dist/client/assets/{PiExtensionsManager-C9JABO_4.js → PiExtensionsManager-B_rRJiOd.js} +1 -1
- package/dist/client/assets/PluginManager-Dxwi88oY.js +1 -0
- package/dist/client/assets/{PullRequestView-DT8vTeVi.js → PullRequestView-z-5v2hQT.js} +2 -2
- package/dist/client/assets/ReportModal-DmOPEYWp.js +21 -0
- package/dist/client/assets/ReportModal-lzN_xrnM.css +1 -0
- package/dist/client/assets/{ResearchView-cNsjYu8F.js → ResearchView-D90Jbzbx.js} +2 -2
- package/dist/client/assets/{SecretsView-BAmf7KyS.js → SecretsView-CSyjZl5L.js} +1 -1
- package/dist/client/assets/SessionTerminal-Bwb8nGmU.js +2 -0
- package/dist/client/assets/SettingsModal-BAzmMjr9.js +21 -0
- package/dist/client/assets/SettingsModal-C5ic1ls7.css +1 -0
- package/dist/client/assets/{SettingsModal-C_9RiEI7.js → SettingsModal-CJof1Ett.js} +1 -1
- package/dist/client/assets/{SettingsTextareaRow-D8RHSj8b.js → SettingsTextareaRow-BYchnHfW.js} +1 -1
- package/dist/client/assets/SetupWizardModal-NqV-erVf.js +2 -0
- package/dist/client/assets/{SkillsView-DyeCwYit.js → SkillsView-BUrkIJ-p.js} +1 -1
- package/dist/client/assets/{WorkflowNodeEditor-C5Jc9w_A.js → WorkflowNodeEditor-DcPk2A1Z.js} +1 -1
- package/dist/client/assets/{agent-import-generation-SCPNeF25.js → agent-import-generation-X16OLfrL.js} +1 -1
- package/dist/client/assets/{agentsOrgChartLayout-CqKtNCjy.js → agentsOrgChartLayout-BhPIXckU.js} +1 -1
- package/dist/client/assets/app-B-TfWH9b.js +5 -0
- package/dist/client/assets/app-B2RDV_-t.js +13 -0
- package/dist/client/assets/app-CDo0mF2S.js +5 -0
- package/dist/client/assets/app-Cc18kAQS.js +13 -0
- package/dist/client/assets/app-DFF79EUn.js +13 -0
- package/dist/client/assets/app-DSeFHxgj.js +13 -0
- package/dist/client/assets/app-Ducr0y6r.js +13 -0
- package/dist/client/assets/{architectureDiagram-3BPJPVTR-Cz2HYn0b.js → architectureDiagram-3BPJPVTR-WArMtdqy.js} +1 -1
- package/dist/client/assets/{blockDiagram-GPEHLZMM-IimJVscG.js → blockDiagram-GPEHLZMM-emScogdV.js} +1 -1
- package/dist/client/assets/{c4Diagram-AAUBKEIU-C-xii7zn.js → c4Diagram-AAUBKEIU-CBY7-E0T.js} +1 -1
- package/dist/client/assets/channel-CP2ySYs0.js +1 -0
- package/dist/client/assets/{chunk-2J33WTMH-DQ-9Xccu.js → chunk-2J33WTMH-Bcai1sOm.js} +1 -1
- package/dist/client/assets/{chunk-4BX2VUAB-DmdAX9Bx.js → chunk-4BX2VUAB-hjiKRusj.js} +1 -1
- package/dist/client/assets/{chunk-55IACEB6-IF2bk5IL.js → chunk-55IACEB6-DpO9nIb0.js} +1 -1
- package/dist/client/assets/{chunk-727SXJPM-AeYpIzVu.js → chunk-727SXJPM-B9JanA0o.js} +1 -1
- package/dist/client/assets/{chunk-AQP2D5EJ-DV942DD9.js → chunk-AQP2D5EJ-D6zdnEUE.js} +1 -1
- package/dist/client/assets/{chunk-FMBD7UC4-Bt_riVlZ.js → chunk-FMBD7UC4-CRkrJ51d.js} +1 -1
- package/dist/client/assets/{chunk-ND2GUHAM-CbyjNbXR.js → chunk-ND2GUHAM-BLQsKt7a.js} +1 -1
- package/dist/client/assets/{chunk-QZHKN3VN-DqiRniYQ.js → chunk-QZHKN3VN-MCOlJ723.js} +1 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-DKkOBtzM.js +1 -0
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-DKkOBtzM.js +1 -0
- package/dist/client/assets/{cose-bilkent-S5V4N54A-UCvthviL.js → cose-bilkent-S5V4N54A-Cv1XmKKG.js} +1 -1
- package/dist/client/assets/{dagre-BM42HDAG-DnMlT1Oi.js → dagre-BM42HDAG-flnNS_RW.js} +1 -1
- package/dist/client/assets/{dashboard-view-C9D0aoRW.js → dashboard-view-CC1aH-lp.js} +1 -1
- package/dist/client/assets/{dashboard-view-myjM9tr8.js → dashboard-view-CrV-rL9Q.js} +1 -1
- package/dist/client/assets/{dashboard-view-JysoyDRX.js → dashboard-view-DEAYb_TZ.js} +1 -1
- package/dist/client/assets/{dashboard-view-Cz0sp2Wl.js → dashboard-view-Dz7kqcJc.js} +1 -1
- package/dist/client/assets/{diagram-2AECGRRQ-BYFiqXGw.js → diagram-2AECGRRQ-Z3S7b_6_.js} +1 -1
- package/dist/client/assets/{diagram-5GNKFQAL-DZU3pSYq.js → diagram-5GNKFQAL-BAZHdMFq.js} +1 -1
- package/dist/client/assets/{diagram-KO2AKTUF-0ybdKuMm.js → diagram-KO2AKTUF-C2y3S8F0.js} +1 -1
- package/dist/client/assets/{diagram-LMA3HP47-Rxbgnbsp.js → diagram-LMA3HP47-Bfz0_IvT.js} +1 -1
- package/dist/client/assets/{diagram-OG6HWLK6-BAU_hTeV.js → diagram-OG6HWLK6-BBmSQsTI.js} +1 -1
- package/dist/client/assets/{erDiagram-TEJ5UH35-zr8HrwTt.js → erDiagram-TEJ5UH35-DnpdQi66.js} +1 -1
- package/dist/client/assets/{flowDiagram-I6XJVG4X-CrTw0iFw.js → flowDiagram-I6XJVG4X-IybTR_zf.js} +1 -1
- package/dist/client/assets/{folder-open-DnAlsXXn.js → folder-open-Dntm63x4.js} +1 -1
- package/dist/client/assets/{ganttDiagram-6RSMTGT7-CCORsxxz.js → ganttDiagram-6RSMTGT7-DEQOe2E9.js} +1 -1
- package/dist/client/assets/{gitGraphDiagram-PVQCEYII-C07wWSjj.js → gitGraphDiagram-PVQCEYII-BOKc-h63.js} +1 -1
- package/dist/client/assets/index-DXpztECA.css +1 -0
- package/dist/client/assets/index-I32FijPT.js +2821 -0
- package/dist/client/assets/{infoDiagram-5YYISTIA-hAeccD_4.js → infoDiagram-5YYISTIA-LqaYIdbj.js} +1 -1
- package/dist/client/assets/{ishikawaDiagram-YF4QCWOH-WLCzv-NH.js → ishikawaDiagram-YF4QCWOH-a8qd512s.js} +1 -1
- package/dist/client/assets/{journeyDiagram-JHISSGLW-ClnasNhy.js → journeyDiagram-JHISSGLW-BgoNyeiy.js} +1 -1
- package/dist/client/assets/{kanban-definition-UN3LZRKU-CAuARhUz.js → kanban-definition-UN3LZRKU-Bqwow7D3.js} +1 -1
- package/dist/client/assets/{mermaid.core-Bh02RvfX.js → mermaid.core-B2zD934i.js} +4 -4
- package/dist/client/assets/{mindmap-definition-RKZ34NQL-KNTlbW4V.js → mindmap-definition-RKZ34NQL-CCTOigWu.js} +1 -1
- package/dist/client/assets/{pieDiagram-4H26LBE5-BouAfBEw.js → pieDiagram-4H26LBE5-Bq5DtXKR.js} +1 -1
- package/dist/client/assets/pixelify-sans-cyrillic-400-normal-DfOZNMlW.woff +0 -0
- package/dist/client/assets/pixelify-sans-latin-400-normal-DLrIX9QE.woff2 +0 -0
- package/dist/client/assets/pixelify-sans-latin-400-normal-JapMNN6Z.woff +0 -0
- package/dist/client/assets/pixelify-sans-latin-ext-400-normal-BkfTUL4s.woff +0 -0
- package/dist/client/assets/pixelify-sans-latin-ext-400-normal-DdH6zlBQ.woff2 +0 -0
- package/dist/client/assets/{puzzle-CC8Ur3Cy.js → puzzle-VhTPiCit.js} +1 -1
- package/dist/client/assets/{quadrantDiagram-W4KKPZXB-wTdkCUJU.js → quadrantDiagram-W4KKPZXB-CGMP3nUx.js} +1 -1
- package/dist/client/assets/{requirementDiagram-4Y6WPE33-BnjY4Tc_.js → requirementDiagram-4Y6WPE33-Ckeu_szu.js} +1 -1
- package/dist/client/assets/{sankeyDiagram-5OEKKPKP-C-QsS08u.js → sankeyDiagram-5OEKKPKP-SWbBDD4d.js} +1 -1
- package/dist/client/assets/{sequenceDiagram-3UESZ5HK-DD36MILE.js → sequenceDiagram-3UESZ5HK-CiJrmL_G.js} +1 -1
- package/dist/client/assets/{shield-alert-DcXc56Fy.js → shield-alert-BBDlP6A5.js} +1 -1
- package/dist/client/assets/{standing-instructions-template-BF5y1BLz.js → standing-instructions-template-viu_kgDX.js} +2 -2
- package/dist/client/assets/{stateDiagram-AJRCARHV-WTq1wQr1.js → stateDiagram-AJRCARHV-DTCzK5Gt.js} +1 -1
- package/dist/client/assets/{stateDiagram-v2-BHNVJYJU-eILJdjII.js → stateDiagram-v2-BHNVJYJU-BIGAwFTT.js} +1 -1
- package/dist/client/assets/{timeline-definition-PNZ67QCA-PRNwI0NR.js → timeline-definition-PNZ67QCA-BQZEFEug.js} +1 -1
- package/dist/client/assets/{upload-qH_64O-B.js → upload-D5w3Ehwp.js} +1 -1
- package/dist/client/assets/{useDiscoveredSkillsCache-C-GPCNaO.js → useDiscoveredSkillsCache-D6zMSIaS.js} +1 -1
- package/dist/client/assets/{users-D2UesRE4.js → users-Bohihi_o.js} +1 -1
- package/dist/client/assets/{vennDiagram-CIIHVFJN-CG2Z4T4O.js → vennDiagram-CIIHVFJN-DnHguEv8.js} +1 -1
- package/dist/client/assets/{wardley-L42UT6IY-gO_fGvF9.js → wardley-L42UT6IY-BOqYltGN.js} +1 -1
- package/dist/client/assets/{wardleyDiagram-YWT4CUSO-BkyNpjUb.js → wardleyDiagram-YWT4CUSO-Re0Ery2M.js} +1 -1
- package/dist/client/assets/{xychartDiagram-2RQKCTM6-CMlZsiPq.js → xychartDiagram-2RQKCTM6-CnVq21b2.js} +1 -1
- package/dist/client/index.html +4 -4
- package/dist/client/theme-data.css +183 -1
- package/dist/client/version.json +1 -1
- package/dist/droid-cli/package.json +1 -1
- package/dist/extension.js +9275 -6726
- package/dist/pi-claude-cli/package.json +1 -1
- package/dist/pi-claude-cli/src/__tests__/event-bridge.test.ts +29 -1
- package/dist/pi-claude-cli/src/event-bridge.ts +10 -4
- package/dist/plugin-sdk/index.d.ts +25 -3
- package/dist/plugin-sdk/index.js +10 -1
- package/dist/plugins/fusion-plugin-acp-runtime/bundled.js +12 -2
- package/dist/plugins/fusion-plugin-acp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-claude-runtime/bundled.js +12 -2
- package/dist/plugins/fusion-plugin-claude-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-cli-printing-press/package.json +1 -1
- package/dist/plugins/fusion-plugin-compound-engineering/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-compound-engineering/package.json +1 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-cursor-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-dependency-graph/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-dependency-graph/package.json +1 -1
- package/dist/plugins/fusion-plugin-droid-runtime/bundled.js +12 -2
- package/dist/plugins/fusion-plugin-droid-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-grok-runtime/bundled.js +12 -2
- package/dist/plugins/fusion-plugin-grok-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-hermes-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-linear-import/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-linear-import/package.json +1 -1
- package/dist/plugins/fusion-plugin-omp-runtime/bundled.js +12 -2
- package/dist/plugins/fusion-plugin-omp-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-openclaw-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-paperclip-runtime/package.json +1 -1
- package/dist/plugins/fusion-plugin-quality/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-quality/package.json +1 -1
- package/dist/plugins/fusion-plugin-reports/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-reports/package.json +1 -1
- package/dist/plugins/fusion-plugin-roadmap/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-roadmap/package.json +1 -1
- package/dist/plugins/fusion-plugin-todos/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-todos/package.json +1 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/bundled.js +10 -1
- package/dist/plugins/fusion-plugin-whatsapp-chat/package.json +1 -1
- package/package.json +1 -1
- package/skill/fusion/SKILL.md +1 -1
- package/skill/fusion/references/extension-tools.md +17 -0
- package/skill/fusion/references/fusion-capabilities.md +2 -0
- package/dist/client/assets/ChatView-cNYtYx05.js +0 -13
- package/dist/client/assets/DocumentsView-ksK9f7xt.js +0 -1
- package/dist/client/assets/MemoryView-Cagk2wZG.js +0 -3
- package/dist/client/assets/PluginManager-D2csmdQa.js +0 -1
- package/dist/client/assets/ReportModal-M3uh98sc.css +0 -1
- package/dist/client/assets/ReportModal-YMP6V4vu.js +0 -21
- package/dist/client/assets/SessionTerminal-BjGcxq22.js +0 -2
- package/dist/client/assets/SettingsModal-C0FY8MPW.css +0 -1
- package/dist/client/assets/SettingsModal-DLfy2e_5.js +0 -21
- package/dist/client/assets/SetupWizardModal-DRJ96pHQ.js +0 -2
- package/dist/client/assets/app-BgpuMvTU.js +0 -13
- package/dist/client/assets/app-BlexHhbW.js +0 -13
- package/dist/client/assets/app-BsuUOR0P.js +0 -13
- package/dist/client/assets/app-DQVOujmO.js +0 -13
- package/dist/client/assets/app-DjyTRx1N.js +0 -5
- package/dist/client/assets/app-Dniggype.js +0 -13
- package/dist/client/assets/app-EV-lyZ0T.js +0 -5
- package/dist/client/assets/channel-D-UHgx8G.js +0 -1
- package/dist/client/assets/classDiagram-4FO5ZUOK-Do-8MdAc.js +0 -1
- package/dist/client/assets/classDiagram-v2-Q7XG4LA2-Do-8MdAc.js +0 -1
- package/dist/client/assets/index-B_z7OKl4.js +0 -2818
- package/dist/client/assets/index-DPo-IAb2.css +0 -1
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import{r as a,j as t}from"./vendor-react-SZ_qB27O.js";import{c as si,S as mn,r as jt,e as Rs,cJ as js,du as Xi,dv as qi,dw as da,b as J,dx as Gi,dy as Dt,dz as At,dA as ya,dB as Qi,dC as Yi,dD as Ji,dE as Zi,dF as eo,dG as to,bh as no,c_ as Ca,dH as Ce,db as ao,cv as ii,c3 as wn,dI as so,dJ as io,ar as yn,dK as oo,dL as ro,bS as co,K as lo,aK as uo,b3 as xn,a2 as mo,d9 as ho,dM as fo,aY as go,dN as po,dO as oi,dP as ri,dQ as vo,dR as bo,W as xo,dS as wo,dT as yo,dU as As,dV as Co,dW as ko,dX as Ts,G as So,dY as Mo,z as No,B as Ro,aI as jo,dZ as ua,C as hn,d_ as fn,d$ as Es,cW as Ds,D as ma,P as pt,V as Ao,bU as Is,de as Ls,dd as To,X as Ps,aJ as Eo,e0 as Do,F as ha,e1 as fa,e2 as Fs,e3 as ga,e4 as $s,e5 as _s,e6 as zs,e7 as Io,dj as ci,e8 as Lo,cV as Bs}from"./index-B_z7OKl4.js";import{u as _e}from"./vendor-i18n-Duky4gdQ.js";import{SessionTerminal as Os}from"./SessionTerminal-BjGcxq22.js";import{u as Po}from"./useDiscoveredSkillsCache-C-GPCNaO.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";import"./shield-alert-DcXc56Fy.js";/**
|
|
2
|
-
* @license lucide-react v1.7.0 - ISC
|
|
3
|
-
*
|
|
4
|
-
* This source code is licensed under the ISC license.
|
|
5
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
6
|
-
*/const Fo=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],li=si("hash",Fo);/**
|
|
7
|
-
* @license lucide-react v1.7.0 - ISC
|
|
8
|
-
*
|
|
9
|
-
* This source code is licensed under the ISC license.
|
|
10
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
11
|
-
*/const $o=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]],_o=si("tag",$o);function gn(){return typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now()}function zo(){try{typeof import.meta<"u"}catch{}try{if(typeof localStorage<"u")return localStorage.getItem("kb-debug-room-open")==="1"}catch{}return!1}function pa(i,r){const h=zo(),p=r?.warm===!0,m=gn(),f=new Map;let N=!1,k=!1;return{mark(D){N||k||!h||f.has(D)||f.set(D,gn())},complete:D=>{if(!h||N||k){N=!0;return}N=!0,f.set("complete",gn());const I=Array.from(f.entries()).sort((R,M)=>R[1]-M[1]);let S=m;const s={};for(const[R,M]of I)s[R]=Math.max(0,M-S),S=M;const v=Math.max(0,gn()-m);try{console.debug("[room-open]",{roomId:i,warm:p,totalMs:v,phases:s,...D??{}})}catch{}},cancel(){k=!0,N=!0}}}const $e="fusion:chat-active-room";class di extends Error{roomId;constructor(r,h){super(r),this.name="RoomMessageDeliveredButReplyFailedError",this.roomId=h}}function ka(i){return[...i].sort((r,h)=>new Date(h.updatedAt).getTime()-new Date(r.updatedAt).getTime())}function Ge(i,r){const h=i.findIndex(m=>m.id===r.id);if(h===-1)return ka([r,...i]);const p=[...i];return p[h]=r,ka(p)}function Ie(i){try{return JSON.parse(i.data)}catch{return null}}function va(i){return i.slice().reverse()}function Bo(i,r,h){return{id:`temp-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,roomId:i,role:"user",content:r,thinkingOutput:null,metadata:null,senderAgentId:null,mentions:[],...h?.length?{attachments:h}:{},createdAt:new Date().toISOString()}}function Hs(i,r,h){if(i.some(m=>m.id===r.id))return i;const p=h?i.findIndex(m=>m.id===h):-1;if(p>=0){const m=[...i];return m[p]=r,m}if(r.role==="user"){const m=i.findIndex(f=>f.role==="user"&&f.id.startsWith("temp-")&&f.content.trim()===r.content.trim());if(m>=0){const f=[...i];return f[m]=r,f}}return[...i,r]}function Oo(i,r){const{t:h}=_e("app"),p=`${mn.CHAT_ROOMS}:${i??"global"}`,m=`${mn.ACTIVE_CHAT_ROOM_ID}:${i??"global"}`,f=a.useCallback(c=>`${mn.CHAT_ROOM_MESSAGES_PREFIX}${i??"global"}:${c}`,[i]),N=a.useCallback(c=>`${mn.CHAT_ROOM_MEMBERS_PREFIX}${i??"global"}:${c}`,[i]),[k,b]=a.useState(()=>{const c=jt(p,{maxAgeMs:Rs});return Array.isArray(c)?c:[]}),[D,I]=a.useState(()=>k.length===0),[S,s]=a.useState(null),[v,R]=a.useState(()=>{const c=jt(m,{maxAgeMs:js});return c?k.find(C=>C.id===c)??null:null}),[M,y]=a.useState([]),[l,P]=a.useState([]),[$,U]=a.useState(!1),z=a.useRef(k),j=a.useRef(v),G=a.useRef(0),ne=a.useRef(i);z.current=k,j.current=v,ne.current!==i&&(ne.current=i,G.current+=1);const Z=a.useCallback(async c=>{if(!c){y([]),P([]),U(!1);return}const C=pa(c.id,{warm:!1});C.mark("select");const g=jt(f(c.id),{maxAgeMs:Xi}),u=jt(N(c.id),{maxAgeMs:Rs}),A=Array.isArray(g)&&g.length>0,L=Array.isArray(u)&&u.length>0;A||L?(C.mark("cache-hit"),A&&(P(g),C.mark("hydrate")),L&&y(u),U(!1)):(P([]),U(!0));try{const[V,ve]=await Promise.all([qi(c.id,i),da(c.id,{limit:100,order:"desc"},i)]);C.mark("members-fetch"),C.mark("messages-fetch"),J(N(c.id),V.members,{maxBytes:5e5});const ae=va(ve.messages);J(f(c.id),ae,{maxBytes:5e5}),j.current?.id===c.id&&(y(V.members),P(ae),C.mark("hydrate"))}catch{!A&&!L&&(y([]),P([]))}finally{U(!1),C.complete({warm:A,membersCached:L})}},[N,f,i]),T=a.useCallback(async()=>{z.current.length===0&&I(!0);try{const c=await Gi({},i),C=ka(c.rooms);b(C),J(p,C,{maxBytes:5e5}),s(null);const g=jt(m,{maxAgeMs:js})??Dt($e,i);if(g){const u=C.find(A=>A.id===g)??null;u?(R(u),Z(u)):(At($e,i),J(m,"",{maxBytes:5e5}))}}catch(c){const C=c instanceof Error?c.message:h("chatRooms.error.failedToLoad","Failed to load chat rooms");s(C),r?.(C,"error")}finally{I(!1)}},[m,r,Z,i,p]),O=a.useCallback(c=>{if(!c){j.current=null,R(null),At($e,i),J(m,"",{maxBytes:5e5}),Z(null);return}const C=z.current.find(g=>g.id===c)??null;j.current=C,R(C),C&&(ya($e,C.id,i),J(m,C.id,{maxBytes:5e5}),Z(C))},[m,Z,i]),ee=a.useCallback(async c=>{const g=(await Qi({name:c.name,memberAgentIds:c.memberAgentIds},i)).room;return b(u=>Ge(u,g)),j.current=g,R(g),ya($e,g.id,i),J(m,g.id,{maxBytes:5e5}),await Z(g),g},[m,Z,i]),W=a.useCallback(async(c,C)=>{const u=(await Yi(c,C,i)).room;return b(A=>Ge(A,u)),j.current?.id===u.id&&(j.current=u,R(u)),u},[i]),E=a.useCallback(async c=>{await Ji(c,i),b(C=>C.filter(g=>g.id!==c)),J(f(c),[],{maxBytes:5e5}),J(N(c),[],{maxBytes:5e5}),j.current?.id===c&&(j.current=null,R(null),y([]),P([]),At($e,i),J(m,"",{maxBytes:5e5}))},[m,N,f,i]),B=a.useCallback(async(c,C)=>{const g=j.current,u=g?.id;if(!u)throw new Error(h("chatRooms.error.selectRoomFirst","Select a room before sending a message"));const A=pa(u,{warm:!1}),L=C?.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()})),V=Bo(u,c,L?.length?L:C?.attachments);j.current?.id===u&&P(ae=>{const he=[...ae,V];return J(f(u),he,{maxBytes:5e5}),he});let ve=!1;try{const ae=[];if(C?.files?.length)for(const fe of C.files)try{const ze=await Zi(u,fe,i);ae.push(ze.attachment)}catch{throw new Error(h("chatRooms.error.failedToUpload","Failed to upload attachment: {{filename}}",{filename:fe.name}))}const he=[...C?.attachments??[],...ae],ke=await eo(u,{content:c,...he.length?{attachments:he}:{}},i);ve=!0;try{C?.onDelivered?.()}catch{}ke.message?.createdAt&&g&&b(fe=>Ge(fe,{...g,updatedAt:ke.message.createdAt})),j.current?.id===u&&P(fe=>{const ze=Hs(fe,ke.message,V.id);return J(f(u),ze,{maxBytes:5e5}),ze});const re=await da(u,{limit:100,order:"desc"},i),Le=va(re.messages);if(J(f(u),Le,{maxBytes:5e5}),j.current?.id!==u)return;P(Le),A.mark("hydrate")}catch(ae){let he=null;try{const re=await da(u,{limit:100,order:"desc"},i);he=va(re.messages),J(f(u),he,{maxBytes:5e5}),j.current?.id===u&&(P(he),A.mark("hydrate"))}catch{!ve&&j.current?.id===u&&P(re=>{const Le=re.filter(fe=>fe.id!==V.id);return J(f(u),Le,{maxBytes:5e5}),Le})}const ke=he?.some(re=>re.role==="user"&&re.content.trim()===V.content.trim());if(ve||ke){const re=ae instanceof Error&&ae.message.trim()?ae.message:h("chatRooms.error.deliveredButRefreshFailed","Message delivered, but failed to refresh room replies");throw new di(re,u)}throw ae}finally{A.complete({source:"send-room-message"})}},[f,i]),oe=a.useCallback(async c=>{!c||!z.current.some(C=>C.id===c)||(await to(c,i),J(f(c),[],{maxBytes:5e5}),j.current?.id===c&&P([]))},[f,i]);return a.useEffect(()=>{T()},[T]),a.useEffect(()=>{const c=G.current,C=i?`/api/events?projectId=${encodeURIComponent(i)}`:"/api/events";return no(C,{onReconnect:()=>{Ca({view:"useChatRooms",trigger:"sse-reconnect",projectId:i,replayAttempted:!1});const g=j.current?.id;if(g){const u=pa(g,{warm:!0});u.mark("sse-reconnect-refresh"),T().finally(()=>u.complete({source:"sse-reconnect"}));return}T()},events:{"chat:room:created":g=>{if(G.current!==c)return;const u=Ie(g);u&&b(A=>Ge(A,u))},"chat:room:updated":g=>{if(G.current!==c)return;const u=Ie(g);u&&(b(A=>Ge(A,u)),j.current?.id===u.id&&(j.current=u,R(u)))},"chat:room:deleted":g=>{if(G.current!==c)return;const u=Ie(g);u?.id&&(b(A=>A.filter(L=>L.id!==u.id)),J(f(u.id),[],{maxBytes:5e5}),J(N(u.id),[],{maxBytes:5e5}),j.current?.id===u.id&&(j.current=null,R(null),y([]),P([]),At($e,i),J(m,"",{maxBytes:5e5})))},"chat:room:member:added":g=>{if(G.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||y(A=>{if(A.some(V=>V.agentId===u.agentId))return A;const L=[...A,u];return J(N(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:member:removed":g=>{if(G.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||y(A=>{const L=A.filter(V=>V.agentId!==u.agentId);return J(N(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:message:added":g=>{if(G.current!==c)return;const u=Ie(g);u&&(b(A=>{const L=A.find(V=>V.id===u.roomId);return L?Ge(A,{...L,updatedAt:u.createdAt}):A}),j.current?.id===u.roomId&&P(A=>{const L=Hs(A,u);return L===A?A:(J(f(u.roomId),L,{maxBytes:5e5}),L)}))},"chat:room:message:updated":g=>{if(G.current!==c)return;const u=Ie(g);!u||j.current?.id!==u.roomId||P(A=>{const L=A.map(V=>V.id===u.id?u:V);return J(f(u.roomId),L,{maxBytes:5e5}),L})},"chat:room:message:deleted":g=>{if(G.current!==c)return;const u=Ie(g);u?.id&&P(A=>{const L=A.filter(ve=>ve.id!==u.id),V=j.current?.id;return V&&J(f(V),L,{maxBytes:5e5}),L})},"chat:room:messages:cleared":g=>{if(G.current!==c)return;const u=Ie(g);u?.roomId&&(J(f(u.roomId),[],{maxBytes:5e5}),j.current?.id===u.roomId&&P([]),b(A=>{const L=A.find(V=>V.id===u.roomId);return L?Ge(A,{...L,updatedAt:new Date().toISOString()}):A}))}}})},[m,N,f,i,T]),a.useEffect(()=>{v&&(k.some(c=>c.id===v.id)||(j.current=null,R(null),y([]),P([]),At($e,i),J(m,"",{maxBytes:5e5})))},[v,m,i,k]),{rooms:k,roomsLoading:D,roomsError:S,activeRoom:v,activeRoomMembers:M,messages:l,messagesLoading:$,selectRoom:O,createRoom:ee,updateRoomSettings:W,deleteRoom:E,sendRoomMessage:B,clearRoom:oe,refreshRooms:T}}const Tt={direct:"fusion:chat-unread:direct",room:"fusion:chat-unread:rooms"},Us=200;function Sa(i){if(!i)return null;const r=new Date(i).getTime();return Number.isFinite(r)?r:null}function ui(i){const r=Object.entries(i);if(r.length<=Us)return i;const h=r.map(([p,m])=>({id:p,timestamp:m,value:Sa(m)??0})).sort((p,m)=>m.value-p.value).slice(0,Us);return Object.fromEntries(h.map(({id:p,timestamp:m})=>[p,m]))}function pn(i){if(!i)return{};try{const r=JSON.parse(i);if(!r||typeof r!="object")return{};const h={};for(const[p,m]of Object.entries(r))typeof p=="string"&&typeof m=="string"&&(h[p]=m);return ui(h)}catch{return{}}}function Ho(i){const[r,h]=a.useState(()=>{try{return pn(Dt(Tt.direct,i))}catch{return{}}}),[p,m]=a.useState(()=>{try{return pn(Dt(Tt.room,i))}catch{return{}}});a.useEffect(()=>{try{h(pn(Dt(Tt.direct,i)))}catch{h({})}try{m(pn(Dt(Tt.room,i)))}catch{m({})}},[i]);const f=a.useMemo(()=>({direct:r,room:p}),[r,p]),N=a.useCallback((S,s)=>{const v=ui(s);try{ya(Tt[S],JSON.stringify(v),i)}catch{}return v},[i]),k=a.useCallback((S,s)=>{if(S==="direct"){h(v=>N(S,s(v)));return}m(v=>N(S,s(v)))},[N]),b=a.useCallback((S,s,v)=>{const R=Sa(v);if(R===null)return!1;const M=f[S][s],y=Sa(M);return y===null?!0:R>y},[f]),D=a.useCallback((S,s,v)=>{if(!s)return;const R=v??new Date().toISOString();k(S,M=>({...M,[s]:R}))},[k]),I=a.useCallback((S,s)=>{s.length!==0&&k(S,v=>{const R={...v};for(const M of s)M.id&&(R[M.id]=M.lastActivityAt??new Date().toISOString());return R})},[k]);return{isUnread:b,markRead:D,markAllRead:I}}const Uo=["",...so];function Ks({level:i,onChange:r,defaultThinkingLevel:h="off",showTargetSection:p=!0,models:m=[],favoriteProviders:f=[],favoriteModels:N=[],agents:k=[],agentId:b,modelProvider:D,modelId:I,onChangeModel:S,disabled:s=!1}){const{t:v}=_e("app"),[R,M]=a.useState(!1),[y,l]=a.useState(()=>b&&b!==Ce?"agent":"model"),P=a.useRef(null),$=i??"",U=D&&I?`${D}/${I}`:"",z=b&&b!==Ce?b:"",j=$!==""||p&&(!!U||!!z),G="chat-thinking-level-listbox";a.useEffect(()=>{if(!R)return;const c=C=>{const g=C.target;if(!(g instanceof Node))return;!P.current?.contains(g)&&!io(g)&&M(!1)};return document.addEventListener("pointerdown",c),document.addEventListener("touchstart",c),()=>{document.removeEventListener("pointerdown",c),document.removeEventListener("touchstart",c)}},[R]),a.useEffect(()=>{M(!1),l(z?"agent":"model")},[$,z,U]);const ne=a.useMemo(()=>k.find(c=>c.id===z),[k,z]),Z=c=>c===""?v("modelSelection.thinkingDefault","Default ({{level}})",{level:h??"off"}):v(`models.options.${c}`,c==="xhigh"?"Very High":c.charAt(0).toUpperCase()+c.slice(1)),T=c=>{M(!1),r(c)},O=c=>{const C=c.indexOf("/");C<=0||(M(!1),S?.({modelProvider:c.slice(0,C),modelId:c.slice(C+1)}))},ee=c=>{c&&(M(!1),S?.({agentId:c}))},W=c=>{l(c)},E=c=>{c.key==="Escape"&&M(!1)},B=(c,C)=>{if(c.key==="Escape"){c.preventDefault(),M(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),T(C))},oe=(c,C)=>{if(c.key==="Escape"){c.preventDefault(),M(!1);return}(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),ee(C))};return t.jsxs("div",{className:"chat-thinking-level-root",ref:P,children:[t.jsx("button",{type:"button",className:`btn-icon chat-thinking-btn${j?" chat-thinking-btn--active":""}`,"data-testid":"chat-thinking-btn","aria-haspopup":"dialog","aria-expanded":R,"aria-controls":G,"aria-label":v("chat.thinkingLevelButton","Thinking level"),title:v("chat.thinkingLevelButton","Thinking level"),disabled:s,onClick:()=>M(c=>!c),onKeyDown:E,children:t.jsx(ao,{size:16})}),R?t.jsxs("div",{className:"chat-thinking-popover",role:"presentation","data-testid":"chat-thinking-popover",children:[p?t.jsxs("section",{className:"chat-thinking-target-section","aria-label":v("chat.modelAgentSection","Model / Agent"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:v("chat.modelAgentSection","Model / Agent")}),t.jsxs("div",{className:"chat-thinking-mode-toggle","data-testid":"chat-thinking-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${y==="model"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-model","aria-pressed":y==="model",onPointerDown:c=>{c.button===0&&W("model")},onClick:c=>{c.detail===0&&W("model")},children:v("chat.newChatModeModel","Model")}),t.jsx("button",{type:"button",className:`chat-thinking-mode-btn${y==="agent"?" chat-thinking-mode-btn--active":""}`,"data-testid":"chat-thinking-mode-agent","aria-pressed":y==="agent",onPointerDown:c=>{c.button===0&&W("agent")},onClick:c=>{c.detail===0&&W("agent")},children:v("chat.newChatModeAgent","Agent")})]}),y==="model"?t.jsxs("div",{className:"chat-thinking-model-picker","data-testid":"chat-thinking-model-picker",children:[t.jsx(ii,{models:m,value:U,onChange:O,label:v("chat.newChatModeModel","Model"),placeholder:v("chat.selectModel","Select a model"),disabled:!S||m.length===0,favoriteProviders:f,favoriteModels:N,menuWidth:"readable"}),m.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-model-empty",children:v("chat.noModelsAvailable","No models available")}):null]}):t.jsx("div",{className:"chat-thinking-agent-list","data-testid":"chat-thinking-agent-list",children:k.length===0?t.jsx("div",{className:"chat-thinking-empty","data-testid":"chat-thinking-agent-empty",children:v("chat.noAgentsAvailable","No agents available")}):k.map(c=>{const C=z===c.id;return t.jsxs("button",{type:"button",className:`chat-thinking-agent-item${C?" chat-thinking-agent-item--selected":""}`,"data-testid":`chat-thinking-agent-${c.id}`,"aria-pressed":C,disabled:!S,onClick:()=>ee(c.id),onKeyDown:g=>oe(g,c.id),children:[t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thinking-agent-name",children:c.name||c.id}),c.role?t.jsx("span",{className:"chat-thinking-agent-role",children:c.role}):null]},c.id)})}),ne?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-agent",children:v("chat.currentAgentTarget","Current agent: {{name}}",{name:ne.name||ne.id})}):U?t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-model",children:v("chat.currentModelTarget","Current model: {{model}}",{model:U})}):t.jsx("div",{className:"chat-thinking-current-target","data-testid":"chat-thinking-current-default",children:v("chat.currentDefaultTarget","Using the default chat target")})]}):null,t.jsxs("section",{className:"chat-thinking-level-section","aria-label":v("chat.thinkingLevelButton","Thinking level"),children:[t.jsx("div",{className:"chat-thinking-section-title",children:v("chat.thinkingLevelSection","Thinking level")}),t.jsx("div",{id:G,className:"chat-thinking-popover-list",role:"listbox","aria-label":v("chat.thinkingLevelButton","Thinking level"),children:Uo.map(c=>{const C=$===c;return t.jsx("button",{type:"button",role:"option","aria-selected":C,className:`chat-thinking-popover-option${C?" active":""}`,"data-testid":`chat-thinking-option-${c||"default"}`,onClick:()=>T(c),onKeyDown:g=>B(g,c),children:Z(c)},c||"default")})})]})]}):null]})}function Ws(i){return i.trim().toLowerCase().replace(/[\s-]+/g,"_").replace(/_+/g,"_")}function mi(i,r){const h=r.trim();if(!h)return!0;const p=Ws(h);return Ws(i).includes(p)||i.toLowerCase().includes(h.toLowerCase())}function Vs({agents:i,filter:r,highlightedIndex:h,visible:p,onSelect:m,position:f="below",roomMemberIds:N,roomName:k}){const{t:b}=_e("app"),D=a.useMemo(()=>i.filter(M=>mi(M.name,r)),[i,r]),I=!!N,S=I&&r.trim().length>0,s=a.useMemo(()=>I?D.filter(M=>N?.has(M.id)):D,[D,N,I]),v=a.useMemo(()=>I?D.filter(M=>!N?.has(M.id)):[],[D,N,I]),R=S?[...s,...v]:s;return p?t.jsx("div",{className:`agent-mention-popup agent-mention-popup--${f}`,"data-testid":"agent-mention-popup",role:"listbox","aria-label":b("agentMention.suggestionsLabel","Agent mention suggestions"),children:R.length===0?t.jsx("div",{className:"agent-mention-empty",children:b("agentMention.noAgentsFound","No agents found")}):t.jsxs(t.Fragment,{children:[I&&t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-members-header",children:k?b("agentMention.membersOf","Members of #{{roomName}}",{roomName:k}):b("agentMention.roomMembers","Room members")}),s.map((M,y)=>t.jsxs("button",{type:"button",className:`agent-mention-item${y===h?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${M.id}`,onMouseDown:l=>l.preventDefault(),onClick:()=>m(M),role:"option","aria-selected":y===h,children:[t.jsx(yn,{agent:M,size:20}),I&&t.jsx("span",{className:"status-dot agent-mention-member-dot","aria-label":b("agentMention.roomMemberBadge","Room member")}),t.jsx("span",{className:"agent-mention-name",children:M.name}),t.jsx("span",{className:"agent-mention-role",children:M.role})]},M.id)),I&&!S&&v.length>0&&t.jsx("div",{className:"agent-mention-hint","data-testid":"agent-mention-other-hint",children:b("agentMention.typeToSearch","Type to search other agents")}),I&&S&&v.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"agent-mention-section-header","data-testid":"agent-mention-others-header",children:b("agentMention.otherAgents","Other agents")}),v.map((M,y)=>{const l=s.length+y;return t.jsxs("button",{type:"button",className:`agent-mention-item${l===h?" agent-mention-item--highlighted":""}`,"data-testid":`agent-mention-item-${M.id}`,onMouseDown:P=>P.preventDefault(),onClick:()=>m(M),role:"option","aria-selected":l===h,children:[t.jsx(yn,{agent:M,size:20}),t.jsx("span",{className:"agent-mention-name",children:M.name}),t.jsx("span",{className:"agent-mention-role",children:M.role})]},M.id)})]})]})}):null}function Ko(i,r){return i+r}function Wo({visible:i,position:r,tasks:h,files:p,selectedIndex:m,onSelectTask:f,onSelectFile:N,loading:k}){const{t:b}=_e("app");if(!i)return null;const D=h.length>0,I=p.length>0;return t.jsxs("div",{className:"file-mention-popup",style:{top:r.top,left:r.left},"data-testid":"file-mention-popup",onMouseDown:S=>{S.preventDefault()},children:[k&&t.jsx("div",{className:"file-mention-popup-loading","data-testid":"file-mention-loading",children:t.jsx("span",{className:"spinner"})}),!k&&!D&&!I&&t.jsx("div",{className:"file-mention-popup-empty","data-testid":"file-mention-empty",children:b("fileMention.empty","No tasks or files found")}),!k&&(D||I)&&t.jsxs("div",{className:"file-mention-popup-groups",children:[D&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:b("fileMention.taskHeader","Tasks")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":b("fileMention.taskMatches","Task matches"),children:h.map((S,s)=>{const v=s;return t.jsxs("li",{className:`file-mention-popup-item${v===m?" file-mention-popup-item--selected":""}`,onClick:()=>f(S),role:"option","aria-selected":v===m,"data-testid":`task-mention-item-${v}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(li,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsxs("div",{className:"file-mention-popup-task-row",children:[t.jsx("span",{className:"file-mention-popup-task-id",children:S.id}),t.jsx("span",{className:`file-mention-popup-column-badge file-mention-popup-column-badge--${S.column}`,children:S.column})]}),t.jsx("span",{className:"file-mention-popup-item-path",children:S.title})]})]},S.id)})})]}),I&&t.jsxs("div",{className:"file-mention-popup-group",children:[t.jsx("div",{className:"file-mention-popup-group-header",children:b("fileMention.fileHeader","Files")}),t.jsx("ul",{className:"file-mention-popup-list",role:"listbox","aria-label":b("fileMention.fileMatches","File matches"),children:p.map((S,s)=>{const v=Ko(h.length,s),R=oo(S.path);return t.jsxs("li",{className:`file-mention-popup-item${v===m?" file-mention-popup-item--selected":""}`,onClick:()=>N(S),role:"option","aria-selected":v===m,"data-testid":`file-mention-item-${v}`,children:[t.jsx("span",{className:"file-mention-popup-icon",children:t.jsx(ro,{})}),t.jsxs("div",{className:"file-mention-popup-info",children:[t.jsx("span",{className:"file-mention-popup-item-name",children:S.name}),R&&t.jsx("span",{className:"file-mention-popup-item-path",children:R})]})]},S.path)})})]})]})]})}function Vo(i,r=[],h){const p=i.trim().replace(/^#/,""),m=(N,k)=>h?h(N,k):k;if(!p)return{ok:!1,error:m("createRoom.nameRequired","Room name is required.")};if(/[A-Z]/.test(p))return{ok:!1,error:m("createRoom.lowercase","Use lowercase letters only.")};const f=p.toLowerCase();return f.length>80?{ok:!1,error:m("createRoom.maxLength","Room names can be at most 80 characters.")}:/^[a-z0-9_-]+$/.test(f)?/^[-_]|[-_]$/.test(f)?{ok:!1,error:m("createRoom.noEdgeChars","Room names cannot start or end with a hyphen or underscore.")}:r.some(N=>N.toLowerCase()===f)?{ok:!1,error:m("createRoom.duplicate","A room with this name already exists.")}:{ok:!0,name:f}:{ok:!1,error:m("createRoom.validChars","Use lowercase letters, numbers, hyphens, or underscores only.")}}function Xo({isOpen:i,onClose:r,onCreate:h,projectId:p,existingRoomNames:m=[]}){const{t:f}=_e("app"),[N,k]=a.useState(""),[b,D]=a.useState([]),[I,S]=a.useState(""),[s,v]=a.useState([]),[R,M]=a.useState("idle"),[y,l]=a.useState(null),[P,$]=a.useState(!1),U=a.useRef(null),z=a.useRef(null),j=a.useRef(null),G=a.useRef(0);a.useEffect(()=>{const E=++G.current;if(!i)return;j.current=document.activeElement instanceof HTMLElement?document.activeElement:null,D([]),M("loading"),l(null);let B=!1;const oe=()=>!B&&G.current===E;return co(void 0,p).then(c=>{oe()&&(D(c),v(C=>C.filter(g=>c.some(u=>u.id===g))),M("loaded"))}).catch(()=>{oe()&&(D([]),M("failed"))}),()=>{B=!0,++G.current}},[i,p]),a.useEffect(()=>{if(!i){k(""),S(""),v([]),D([]),M("idle"),l(null),$(!1);return}const E=window.requestAnimationFrame(()=>{const B=document.activeElement;B instanceof HTMLElement&&z.current?.contains(B)||U.current?.focus()});return()=>window.cancelAnimationFrame(E)},[i]),a.useEffect(()=>{if(!i)return;const E=B=>{B.key==="Escape"&&r()};return document.addEventListener("keydown",E),()=>document.removeEventListener("keydown",E)},[i,r]),a.useEffect(()=>{i||j.current?.focus()},[i]);const ne=a.useMemo(()=>Vo(N,m,f),[N,m,f]),Z=a.useMemo(()=>{const E=I.trim().toLowerCase();return E?b.filter(B=>B.name.toLowerCase().includes(E)):b},[b,I]),T=a.useMemo(()=>b.filter(E=>s.includes(E.id)),[b,s]),O=ne.ok&&s.length>0&&!P&&R==="loaded";if(!i)return null;const ee=E=>{P||v(B=>B.includes(E)?B.filter(oe=>oe!==E):[...B,E])},W=async()=>{if(!ne.ok){l(ne.error);return}if(s.length===0){l(f("createRoom.selectMember","Select at least one member."));return}l(null),$(!0);try{await h({name:ne.name,displayName:`#${ne.name}`,memberAgentIds:s}),r()}catch(E){l(E instanceof Error?E.message:f("createRoom.failedCreate","Failed to create room."))}finally{$(!1)}};return t.jsx(lo,{windowKey:"create-room",title:f("createRoom.title","Create room"),ariaLabel:f("createRoom.title","Create room"),onClose:r,modal:!0,hideHeader:!0,dragHandleSelector:".modal-header",className:"floating-window--create-room",defaultSize:{width:640,height:640},minSize:{width:360,height:400},persistGeometryKey:"floating-window:create-room",suspendGeometryPersistenceOnMobile:!0,suspendGeometryPersistenceOnShortViewport:!0,closeOnOutsidePointerDown:!0,layer:"utility",children:t.jsxs("div",{ref:z,className:"modal create-room-modal",children:[t.jsxs("div",{className:"modal-header",children:[t.jsx("h3",{children:f("createRoom.title","Create room")}),t.jsx("button",{type:"button",className:"modal-close","aria-label":f("actions.close","Close"),onClick:r,children:"×"})]}),t.jsxs("div",{className:"form-group create-room-modal-name-group",children:[t.jsx("label",{htmlFor:"create-room-name",children:f("createRoom.nameLabel","Room name")}),t.jsxs("div",{className:"create-room-modal-name-field",children:[t.jsx("span",{"aria-hidden":"true",className:"create-room-modal-name-hash",children:"#"}),t.jsx("input",{ref:U,id:"create-room-name",className:"input",value:N,disabled:P,onChange:E=>{const B=E.target.value.replace(/^#/,"").replace(/\s+/g,"-").toLowerCase();k(B)}})]}),!ne.ok&&t.jsx("div",{className:"form-error",children:ne.error})]}),t.jsxs("div",{className:"form-group",children:[t.jsx("label",{htmlFor:"create-room-member-search",children:f("createRoom.members","Members")}),t.jsx("input",{id:"create-room-member-search",className:"input",placeholder:f("createRoom.searchAgents","Search agents"),value:I,disabled:P,onChange:E=>S(E.target.value)})]}),T.length>0&&t.jsx("div",{className:"create-room-modal-selected","data-testid":"create-room-selected-chips",children:T.map(E=>t.jsxs("button",{type:"button",className:"btn btn-sm create-room-modal-chip",onClick:()=>ee(E.id),disabled:P,children:[E.name," ×"]},E.id))}),t.jsx("div",{className:"create-room-modal-member-list","data-testid":"create-room-member-list",children:R==="idle"||R==="loading"?t.jsx("div",{className:"create-room-modal-empty",children:t.jsx(uo,{label:f("createRoom.loadingAgents","Loading agents...")})}):R==="failed"?t.jsx("div",{className:"create-room-modal-empty",children:f("createRoom.failedLoadAgents","Failed to load agents.")}):Z.length===0?t.jsx("div",{className:"create-room-modal-empty",children:b.length===0?f("createRoom.noAgents","No agents in this project yet."):f("createRoom.noMatch","No agents match your search.")}):Z.map(E=>{const B=s.includes(E.id);return t.jsxs("button",{type:"button",className:`create-room-modal-member-row${B?" create-room-modal-member-row--selected":""}`,onClick:()=>ee(E.id),disabled:P,children:[t.jsx(yn,{agent:E,size:20}),t.jsx("span",{children:E.name}),t.jsx("span",{className:"create-room-modal-member-role",children:E.role})]},E.id)})}),y&&t.jsx("div",{className:"form-group",children:t.jsx("div",{className:"form-error",children:y})}),t.jsxs("div",{className:"modal-actions",children:[t.jsx("button",{type:"button",className:"btn",onClick:r,disabled:P,children:f("actions.cancel","Cancel")}),t.jsx("button",{type:"button",className:"btn btn-primary",onClick:()=>void W(),disabled:!O,children:P?f("createRoom.creating","Creating..."):f("createRoom.create","Create room")})]})]})})}function qo({cliSessionId:i,tier:r,projectId:h,renderTranscript:p,renderComposer:m,queuedCount:f=0,terminalProps:N}){const{t:k}=_e("app"),b=r==="generic",[D,I]=a.useState(b?"terminal":"transcript");if(b)return t.jsx("div",{className:"cli-chat-surface cli-chat-surface--generic","data-tier":"generic",children:t.jsx(Os,{sessionId:i,projectId:h,...N})});const S=D==="terminal";return t.jsxs("div",{className:"cli-chat-surface","data-tier":r,"data-view":D,children:[t.jsxs("div",{className:"cli-chat-surface__toolbar",role:"tablist","aria-label":k("cliChat.viewToggleLabel","Chat view"),children:[t.jsxs("button",{type:"button",role:"tab","aria-selected":!S,className:`cli-chat-surface__tab${S?"":" is-active"}`,onClick:()=>I("transcript"),children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:k("cliChat.transcriptTab","Transcript")})]}),t.jsxs("button",{type:"button",role:"tab","aria-selected":S,className:`cli-chat-surface__tab${S?" is-active":""}`,onClick:()=>I("terminal"),children:[t.jsx(mo,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:k("cliChat.terminalTab","Terminal")})]})]}),t.jsx("div",{className:"cli-chat-surface__body",children:S?t.jsx(Os,{sessionId:i,projectId:h,...N}):p()}),!S&&t.jsxs("div",{className:"cli-chat-surface__composer",children:[f>0&&t.jsx("div",{className:"cli-chat-surface__queued",role:"status","aria-live":"polite",children:k("cliChat.queued","{{count}} message queued — will send when the agent is ready",{count:f})}),m()]})]})}const Go=200,Qo=8,Yo=8;function Xs(){return new DOMException("The operation was aborted.","AbortError")}function qs(i,r){return r.aborted?Promise.reject(Xs()):new Promise((h,p)=>{const m=()=>p(Xs());r.addEventListener("abort",m,{once:!0}),i.then(f=>{r.removeEventListener("abort",m),h(f)},f=>{r.removeEventListener("abort",m),p(f)})})}function Gs(i,r,h){const p=i.slice(0,r),m=i.slice(r+1),f=m.match(/[\s]|$/),N=f?f.index??m.length:m.length,k=m.slice(N);return`${p}${h}${k}`}function Jo(i={}){const{projectId:r,workspace:h="project"}=i,[p,m]=a.useState(!1),[f,N]=a.useState(""),[k,b]=a.useState(-1),[D,I]=a.useState([]),[S,s]=a.useState([]),[v,R]=a.useState(!1),[M,y]=a.useState(0),l=a.useRef(null),P=a.useRef(null),$=[...D.map(T=>({kind:"task",task:T})),...S.map(T=>({kind:"file",file:T}))];a.useEffect(()=>()=>{l.current&&clearTimeout(l.current),P.current?.abort()},[]);const U=a.useCallback((T,O)=>{if(O<0||O>T.length){m(!1);return}const ee=W=>/[a-zA-Z0-9/_.-]/.test(W);for(let W=O-1;W>=0;W--){if(T[W]==="#"){if(W===0){const B=T.slice(W+1,O);b(W),N(B),y(0),m(!0);return}const E=T[W-1];if(/[\s,.;:!?'"()[\]{}]/.test(E)){const B=T.slice(W+1,O);b(W),N(B),y(0),m(!0);return}m(!1);return}if(!ee(T[W])){m(!1);return}}m(!1)},[]),z=a.useCallback(()=>{P.current?.abort(),m(!1),N(""),b(-1),I([]),s([]),y(0),R(!1)},[]),j=a.useCallback(async T=>{if(!T.trim()){I([]),s([]),R(!1);return}P.current?.abort();const O=new AbortController;P.current=O;try{R(!0);const[ee,W]=await Promise.allSettled([qs(ho(20,0,r,T),O.signal),qs(fo(T,h,r),O.signal)]);if(O.signal.aborted)return;const E=ee.status==="fulfilled"?ee.value.slice(0,Qo).map(oe=>({id:oe.id,title:oe.title??"",column:oe.column})):[],B=W.status==="fulfilled"?W.value.files.slice(0,Yo):[];I(E),s(B),y(0)}catch(ee){ee.name!=="AbortError"&&(I([]),s([]))}finally{O.signal.aborted||R(!1)}},[h,r]);a.useEffect(()=>{if(p)return l.current&&clearTimeout(l.current),l.current=setTimeout(()=>{j(f)},Go),()=>{l.current&&clearTimeout(l.current)}},[f,p,j]);const G=a.useCallback((T,O)=>!p||k<0?O:Gs(O,k,`#${T.id}`),[p,k]),ne=a.useCallback((T,O)=>!p||k<0?O:Gs(O,k,`#${T.path}`),[p,k]),Z=a.useCallback((T,O)=>{if(!p||$.length===0)return!1;switch(T.key){case"ArrowDown":return T.preventDefault(),y(ee=>Math.min(ee+1,$.length-1)),!0;case"ArrowUp":return T.preventDefault(),y(ee=>Math.max(ee-1,0)),!0;case"Enter":case"Tab":return $[M]?(T.preventDefault(),!0):!1;case"Escape":return T.preventDefault(),z(),!0;default:return!1}},[p,$,M,z]);return{mentionActive:p,tasks:D,files:S,combinedItems:$,loading:v,mentionQuery:f,selectedIndex:M,setSelectedIndex:y,detectMention:U,selectTask:G,selectFile:ne,dismissMention:z,handleKeyDown:Z}}function Zo(i,r){const h=i.reduce((p,m)=>p+(m.content?.length??0),0)+(r?.length??0);return Math.ceil(h/4)}function Qs(i){if(!Number.isFinite(i)||i<=0)return"0";if(i<1e3)return String(Math.round(i));const r=i/1e3;return r<10?`~${Number(r.toFixed(1))}k`:`${Math.round(r)}k`}const Ma=640,er=200,tr=200,vt=8;function yr(i){const r=i.trim();return r?`${r}
|
|
12
|
-
|
|
13
|
-
`:""}function nr(i,r,h,p,m,f,N){const k=Math.max(vt,f-p-vt),b=Math.max(vt,N-m-vt),D=h?i-p:i;return{x:Math.min(Math.max(vt,D),k),y:Math.min(Math.max(vt,r),b)}}const Ys="__SKIP__";let ba=!1;function ar(i,r=Ma){return i>r?"auto":"hidden"}function sr(i,r=Ma){return Math.max(40,Math.min(i,r))}function ir(i,r){const h=new Date(i),m=new Date().getTime()-h.getTime(),f=Math.floor(m/1e3),N=Math.floor(f/60),k=Math.floor(N/60),b=Math.floor(k/24);return f<60?r("chat.relativeTimeJustNow","just now"):N<60?r("chat.relativeTimeMinutes","{{count}}m ago",{count:N}):k<24?r("chat.relativeTimeHours","{{count}}h ago",{count:k}):b<7?r("chat.relativeTimeDays","{{count}}d ago",{count:b}):h.toLocaleDateString()}const or=280,vn=180,bn=500,Js="fusion:chat-sidebar-width",xa="fusion:chat-scope",rr="fusion:chat-draft:";function Zs(i,r){return i.slice(r+1).find(h=>h.role==="user")?.content}function ei(i,r){return r?`${rr}${i}:${r}`:null}function ti(i){if(!i)return"";try{return localStorage.getItem(i)??""}catch{return""}}const cr=["image/png","image/jpeg","image/gif","image/webp","video/mp4","video/webm","video/quicktime","text/plain","text/markdown","application/json","text/yaml","text/x-toml","text/csv","application/xml"],ni="image/png,image/jpeg,image/gif,image/webp,video/mp4,video/webm,video/quicktime,.txt,.md,.json,.yaml,.yml,.toml,.csv,.xml",wa=Io;function lr(i,r){const h=i.slice(0,r),p=/(^|[\s\n])@([\w-]*)$/.exec(h);if(!p)return null;const m=p[2]??"",f=h.length-m.length-1;return{filter:m,start:f,end:r}}function dr(i){const r=i?.runtimeConfig;if(!r||typeof r!="object")return null;const h=Reflect.get(r,"modelProvider"),p=Reflect.get(r,"modelId");return typeof h!="string"||h.trim().length===0||typeof p!="string"||p.trim().length===0?null:{provider:h,modelId:p}}function ai(i,r,h){if(i?.modelProvider&&i?.modelId)return{provider:i.modelProvider,modelId:i.modelId};const p=dr(r??void 0);return p||(h.provider&&h.modelId?{provider:h.provider,modelId:h.modelId}:null)}function ur({projectId:i,defaultModel:r,defaultKind:h,defaultAgentId:p,defaultThinkingLevel:m,defaultSelectedThinkingLevel:f,onClose:N,onCreate:k}){const{t:b}=_e("app"),[D,I]=a.useState(h??"agent"),{agents:S,loading:s}=oi(i),[v,R]=a.useState(p??""),{models:M,favoriteProviders:y,favoriteModels:l,loading:P,refresh:$}=ri(),U=r.provider&&r.modelId?`${r.provider}/${r.modelId}`:"",[z,j]=a.useState(U),[G,ne]=a.useState(f??""),[Z,T]=a.useState(y),[O,ee]=a.useState(l);a.useEffect(()=>{T(y)},[y]),a.useEffect(()=>{ee(l)},[l]),a.useEffect(()=>{h&&I(h)},[h]),a.useEffect(()=>{p&&R(g=>g||p)},[p]),a.useEffect(()=>{U&&j(g=>g||U)},[U]),a.useEffect(()=>{f&&ne(g=>g||f)},[f]);const W=a.useCallback(async g=>{const u=Z,L=u.includes(g)?u.filter(V=>V!==g):[g,...u];T(L);try{await Bs({favoriteProviders:L,favoriteModels:O}),await $()}catch{T(u)}},[Z,O,$]),E=a.useCallback(async g=>{const u=O,L=u.includes(g)?u.filter(V=>V!==g):[g,...u];ee(L);try{await Bs({favoriteProviders:Z,favoriteModels:L}),await $()}catch{ee(u)}},[O,Z,$]),B=z||U,oe=g=>{if(g.preventDefault(),D==="agent"){if(!v)return;k({agentId:v});return}if(!B)return;const u=B.indexOf("/");if(u<=0)return;const A=B.slice(0,u),L=B.slice(u+1);k({agentId:Ce,modelProvider:A,modelId:L,thinkingLevel:G||void 0})},c=D==="agent"?!v:!B,C=ci(N,{enabled:!0});return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",...C,role:"dialog","aria-modal":"true",children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:g=>g.stopPropagation(),children:[t.jsx("h3",{children:b("chat.newChatTitle","New Chat")}),t.jsxs("div",{className:"chat-new-dialog-mode-toggle","data-testid":"chat-new-dialog-mode-toggle",children:[t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${D==="agent"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-agent",onClick:()=>{I("agent")},children:b("chat.newChatModeAgent","Agent")}),t.jsx("button",{type:"button",className:`chat-new-dialog-mode-btn${D==="model"?" chat-new-dialog-mode-btn--active":""}`,"data-testid":"chat-new-dialog-mode-model",onClick:()=>{I("model"),R(""),j(g=>g||U)},children:b("chat.newChatModeModel","Model")})]}),t.jsxs("form",{onSubmit:oe,children:[D==="agent"&&t.jsxs("label",{className:"chat-new-dialog-model-label",children:[b("chat.newChatModeAgent","Agent"),s?t.jsx("div",{className:"chat-new-dialog-loading",children:b("chat.loadingAgents","Loading agents...")}):S.length===0?t.jsx("div",{className:"chat-new-dialog-empty",children:b("chat.noAgentsAvailable","No agents available")}):t.jsx("div",{className:"chat-new-dialog-agent-list",children:S.map(g=>t.jsxs("button",{type:"button",className:`chat-new-dialog-agent-item${v===g.id?" chat-new-dialog-agent-item--selected":""}`,onClick:()=>R(g.id),"data-testid":`agent-option-${g.id}`,children:[t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-new-dialog-agent-name",children:g.name}),t.jsx("span",{className:"chat-new-dialog-agent-role",children:g.role})]},g.id))})]}),D==="model"&&t.jsx("div",{className:"chat-new-dialog-model-dropdown","data-testid":"chat-new-dialog-model-section",children:P?t.jsx("div",{className:"chat-new-dialog-loading",children:b("chat.loadingModels","Loading models...")}):t.jsx(ii,{models:M,value:z,onChange:j,label:b("chat.newChatModeModel","Model"),placeholder:b("chat.selectModel","Select a model"),favoriteProviders:Z,onToggleFavorite:W,favoriteModels:O,onToggleModelFavorite:E,showThinkingLevel:!0,thinkingLevel:G,onThinkingLevelChange:ne,defaultThinkingLevel:m??"off"})}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{type:"button",className:"btn btn-sm",onClick:N,children:b("chat.cancel","Cancel")}),t.jsx("button",{type:"submit",className:"btn btn-sm btn-primary",disabled:c,children:b("chat.create","Create")})]})]})]})})}function Et({children:i,onClose:r}){const h=ci(r,{enabled:!0});return t.jsx("div",{className:"chat-new-dialog-backdrop chat-view-dialog-backdrop",...h,children:i})}function Cr({projectId:i,addToast:r,floating:h=!1,compactLayout:p=!1,onPopOut:m,onMaximize:f,onMinimize:N,onClose:k,chatCommandContext:b,initialComposerDraft:D,initialComposerDraftNonce:I,onSendAsReport:S}){const{t:s}=_e("app");a.useEffect(()=>(Ca({view:"ChatView",trigger:ba?"route-active":"remount",projectId:i,replayAttempted:!1}),ba=!1,()=>{ba=!0,Ca({view:"ChatView",trigger:"route-inactive",projectId:i,replayAttempted:!1})}),[i]);const[v,R]=a.useState(null);a.useEffect(()=>{let e=!1;return R(null),go(i).then(n=>{e||R(n)}).catch(()=>{e||R(null)}),()=>{e=!0}},[i]);const M=v?.defaultThinkingLevel??"off",y=a.useMemo(()=>v?.chatDefaultKind==="agent"&&v.chatDefaultAgentId?{kind:"agent",agentId:v.chatDefaultAgentId}:v?.chatDefaultKind==="model"&&v.chatDefaultModelProvider&&v.chatDefaultModelId?{kind:"model",modelProvider:v.chatDefaultModelProvider,modelId:v.chatDefaultModelId,thinkingLevel:v.chatDefaultThinkingLevel}:null,[v]),{activeSession:l,sessionsLoading:P,messages:$,messagesLoading:U,isStreaming:z,streamingText:j,streamingThinking:G,streamingToolCalls:ne,selectSession:Z,createSession:T,archiveSession:O,archivedSessions:ee,refreshArchivedSessions:W,unarchiveSession:E,renameSession:B,pinSession:oe,pinnedCount:c,setSessionModel:C,setSessionThinkingLevel:g,deleteSession:u,tags:A=[],selectedTagId:L,setSelectedTagId:V,createTag:ve,renameTag:ae,deleteTag:he,setSessionTags:ke,sendMessage:re,editMessageAndResend:Le,stopStreaming:fe,pendingMessages:ze,clearPendingMessage:Cn,loadMoreMessages:Na,hasMoreMessages:kn,searchQuery:hi,setSearchQuery:fi,filteredSessions:Be,agentsMap:Sn}=po(i,r),[gi,Mn]=a.useState(!1),Oe=!0,[F,Qe]=a.useState(()=>{try{if(localStorage.getItem(xa)==="rooms"&&Oe)return"rooms"}catch{}return"direct"}),w=Oo(i,r),{isUnread:Ra,markRead:ue}=Ho(i),[Q,ce]=a.useState(()=>{const e=ei(F,F==="rooms"?w.activeRoom?.id:l?.id);return ti(e)}),[Y,Se]=a.useState(null),[Ye,pi]=a.useState(!1),Nn=a.useRef(null),ja=(e,n,o,d)=>{typeof window>"u"||Se({sessionId:e,anchorX:n,anchorY:o,anchorRight:d?.anchorRight??!1,x:n,y:o})};a.useLayoutEffect(()=>{if(!Y||!Nn.current||typeof window>"u")return;const e=Nn.current,n=e.getBoundingClientRect(),o=n.width||e.offsetWidth||tr,d=n.height||e.offsetHeight,x=nr(Y.anchorX,Y.anchorY,Y.anchorRight,o,d,window.innerWidth,window.innerHeight);(x.x!==Y.x||x.y!==Y.y)&&Se({...Y,...x})},[Y]);const[It,Lt]=a.useState(null),[Rn,jn]=a.useState(""),[Aa,Pt]=a.useState(null),[Ta,Ft]=a.useState(null),[An,Ea]=a.useState(""),[Tn,bt]=a.useState(null),[En,Da]=a.useState(""),[Ia,$t]=a.useState(null),[xt,He]=a.useState(!0),[Je,Dn]=a.useState(or),[vi,_t]=a.useState(!1),{agentsMap:La}=oi(i),be=a.useMemo(()=>Sn.size>0?Sn:La,[La,Sn]),{models:In,favoriteProviders:bi,favoriteModels:xi,defaultProvider:Pa,defaultModelId:Fa}=ri(),zt=a.useMemo(()=>({provider:Pa,modelId:Fa}),[Fa,Pa]),wi=a.useMemo(()=>y?.kind==="model"?{provider:y.modelProvider,modelId:y.modelId}:zt,[y,zt]),{skills:Ln,loading:yi}=Po(i),[Ze,Ue]=a.useState(!1),[wt,yt]=a.useState(""),[et,Ke]=a.useState(0),[tt,nt]=a.useState(""),[Me,at]=a.useState(!1),[Bt,Ot]=a.useState(0),[Pn,st]=a.useState(-1),[ge,Ht]=a.useState([]),[$a,it]=a.useState(!1),[_a,Ut]=a.useState(!1),[ot,za]=a.useState({}),[Kt,Ne]=a.useState(!1),[Wt,Ct]=a.useState(!1),{pushNav:Ba}=vo(),[,Vt]=a.useState(!1),[Ci,ki]=a.useState({top:0,left:0}),X=Jo({projectId:i}),Fn=a.useCallback(e=>{if(!e||!X.mentionActive)return;const n=e.getBoundingClientRect();ki({top:n.top-260,left:n.left+8})},[X.mentionActive]),Oa=a.useRef(null),Ha=a.useRef(null),Ua=a.useRef(null),Ka=a.useRef(null),de=a.useRef(!1),Xt=a.useRef(null),Wa=a.useRef(null),Pe=a.useRef(null),qt=a.useRef(0),$n=a.useRef(null),kt=a.useRef(null),Re=a.useRef(null),le=a.useRef(null),_n=a.useRef(null),rt=a.useRef(null),[zn,Si]=a.useState(()=>new Set),Gt=a.useRef(!1),je=a.useRef(null),Ae=a.useRef(null),te=a.useRef(null),Qt=a.useRef(null),Va=a.useRef(void 0),Bn=a.useRef(!1),Yt=a.useRef(null),Xa=a.useRef([]),ct=a.useRef(0),St=a.useRef(new Map),On=a.useRef(!1),Jt=bo(),We=Jt==="mobile",Hn=Jt==="tablet",qa=a.useRef(null),[Mi,Ga]=a.useState(!1);a.useLayoutEffect(()=>{if(!h){Ga(!1);return}const e=qa.current;if(!e||typeof ResizeObserver>"u")return;const n=()=>{Ga(e.getBoundingClientRect().width<=768)};n();const o=new ResizeObserver(n);return o.observe(e),()=>o.disconnect()},[h]);const H=We||Mi||p;a.useEffect(()=>{l?.id&&ue("direct",l.id,l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,ue]),a.useEffect(()=>{w.activeRoom?.id&&ue("room",w.activeRoom.id,w.activeRoom.updatedAt)},[w.activeRoom?.id,w.activeRoom?.updatedAt,ue]),a.useEffect(()=>{if(!l?.id||$.length===0)return;const e=$[$.length-1];ue("direct",l.id,e?.createdAt??l.lastMessageAt??l.updatedAt)},[l?.id,l?.lastMessageAt,l?.updatedAt,ue,$]),a.useEffect(()=>{if(!w.activeRoom?.id||w.messages.length===0)return;const e=w.messages[w.messages.length-1];ue("room",w.activeRoom.id,e?.createdAt??w.activeRoom.updatedAt)},[ue,w.activeRoom?.id,w.activeRoom?.updatedAt,w.messages]),a.useEffect(()=>{try{const e=localStorage.getItem(Js);if(!e)return;const n=Number.parseInt(e,10);if(Number.isNaN(n))return;const o=Math.max(vn,Math.min(bn,n));Dn(o)}catch{}},[]),a.useEffect(()=>{try{const e=localStorage.getItem(xa);if(e==="direct"){Qe("direct");return}e==="rooms"&&Oe&&Qe("rooms")}catch{}},[Oe]),a.useEffect(()=>{try{localStorage.setItem(xa,F)}catch{}},[Oe,F]);const me=ei(F,F==="rooms"?w.activeRoom?.id:l?.id),Un=a.useRef(me),Kn=a.useRef(!1);a.useEffect(()=>{if(me!==Un.current){if(Un.current=me,Kn.current){Kn.current=!1;return}ce(ti(me))}},[me]),a.useEffect(()=>{if(!(!me||Un.current!==me))try{if(Q){localStorage.setItem(me,Q);return}localStorage.removeItem(me)}catch{}},[me,Q]);const se=F==="rooms"&&!!w.activeRoom,{keyboardOverlap:Qa,keyboardOpen:Zt}=xo({enabled:(H||Hn)&&(!!l||se),allowNonMobileViewport:Hn}),Mt=Hn&&Zt,en=a.useMemo(()=>{const e=wt.trim().toLowerCase();return(e?Ln.filter(o=>o.name.toLowerCase().includes(e)):Ln).slice(0,10)},[Ln,wt]),Wn=a.useMemo(()=>b?wo(wt,zs):[],[b,wt]),xe=a.useMemo(()=>{const e=Wn.map(o=>({kind:"command",command:o,disabled:!b?.agentRunning})),n=en.map(o=>({kind:"skill",skill:o}));return[...e,...n]},[Wn,en,b]),lt=a.useMemo(()=>Array.from(be.values()),[be]),Te=a.useMemo(()=>F!=="rooms"||!w.activeRoom?null:{roomId:w.activeRoom.id,roomName:w.activeRoom.name,memberIds:new Set(w.activeRoomMembers.map(e=>e.agentId))},[Oe,F,w.activeRoom,w.activeRoomMembers]),Ve=a.useMemo(()=>{const e=lt.filter(d=>mi(d.name,tt));if(!Te)return e;const n=e.filter(d=>Te.memberIds.has(d.id));if(tt.trim().length===0)return n;const o=e.filter(d=>!Te.memberIds.has(d.id));return[...n,...o]},[lt,tt,Te]),Vn=a.useMemo(()=>{const e=new Map;for(const n of lt)e.set(n.name.toLowerCase(),n);return e},[lt]),Ni=a.useMemo(()=>en.map(e=>e.id).join("\0"),[en]);a.useEffect(()=>{Ke(0)},[Ni]),a.useEffect(()=>{Ot(0)},[tt,Me]),a.useEffect(()=>()=>{Re.current!==null&&window.clearTimeout(Re.current)},[]),a.useEffect(()=>{const e=Ha.current;if(!e||!kn||U)return;const n=new IntersectionObserver(o=>{o[0].isIntersecting&&Na()},{threshold:.1});return n.observe(e),()=>n.disconnect()},[kn,U,Na]);const dt=a.useCallback(()=>se?w.activeRoom?.id??null:l?.id??null,[se,w.activeRoom?.id,l?.id]),Ya=a.useCallback((e,n)=>typeof CSS<"u"&&typeof CSS.escape=="function"?e.querySelector(`.chat-message[data-message-id="${CSS.escape(n)}"]`):e.querySelector(`.chat-message[data-message-id="${n.replace(/"/g,'\\"')}"]`),[]),Ja=a.useCallback(()=>{const e=le.current;if(!e)return;const n=e.getBoundingClientRect().top,o=new Set;e.querySelectorAll(".chat-message--assistant:not(.chat-message--failure)[data-message-id]").forEach(d=>{const x=d.getAttribute("data-message-id");x&&d.getBoundingClientRect().top<n&&o.add(x)}),Si(d=>d.size===o.size&&Array.from(d).every(x=>o.has(x))?d:o)},[]),tn=a.useCallback(()=>{!le.current||rt.current!==null||(rt.current=window.requestAnimationFrame(()=>{rt.current=null,Ja()}))},[Ja]),nn=a.useCallback(()=>{const e=le.current,n=dt();if(!e||!n)return;const o=e.scrollTop,d=e.querySelectorAll(".chat-message[data-message-id]"),x=Array.from(d).find(K=>K.offsetTop+K.offsetHeight>=o)??d[0]??null,_=x?.getAttribute("data-message-id")??null,q=x?x.offsetTop-o:0;kt.current={threadId:n,scrollTop:o,scrollHeight:e.scrollHeight,clientHeight:e.clientHeight,anchorMessageId:_,anchorOffset:q,wasPinnedBefore:!de.current,capturedAtMs:typeof performance<"u"?performance.now():Date.now()}},[dt]),Za=a.useCallback(()=>{const e=le.current;if(!e)return;const o=e.scrollTop+e.clientHeight>=e.scrollHeight-50;Ut(!o),de.current=!o,nn(),tn()},[nn,tn]),Ee=a.useCallback((e,n)=>{if(!e.isConnected||!n?.force&&de.current)return;let o=0,d=0,x=-1;const _=6,q=()=>{if(e.isConnected&&!(!n?.force&&de.current)){if(e.scrollTop=e.scrollHeight,e.scrollHeight===x?d+=1:(d=0,x=e.scrollHeight),o+=1,o>=_||d>=2){Ut(!1),de.current=!1;return}window.requestAnimationFrame(q)}};q()},[]),ut=se?w.messages:$;a.useLayoutEffect(()=>(tn(),()=>{rt.current!==null&&(window.cancelAnimationFrame(rt.current),rt.current=null)}),[ut,tn]),a.useLayoutEffect(()=>{const e=le.current,n=dt(),o=kt.current;if(!e||!n||!o||o.threadId!==n||o.wasPinnedBefore)return;const d=(typeof performance<"u"?performance.now():Date.now())-o.capturedAtMs,x=e.scrollHeight>e.clientHeight,_=d>3e3,q=o.scrollTop<=0&&o.anchorOffset<=0&&x;if(!de.current||_||q){kt.current=null;return}let K=o.scrollTop;if(o.anchorMessageId){const pe=Ya(e,o.anchorMessageId);pe?K=pe.offsetTop-o.anchorOffset:K=o.scrollTop+(e.scrollHeight-o.scrollHeight)}else K=o.scrollTop+(e.scrollHeight-o.scrollHeight);e.scrollTop=Math.max(0,K),de.current=!0,Ut(!0),kt.current=null},[ut,dt,Ya]);const Xn=a.useCallback(e=>{},[ut.length,se]),we=a.useCallback(e=>{Xn(e);const n=le.current;n&&(kt.current=null,de.current=!1,Ee(n))},[Ee,Xn]);a.useLayoutEffect(()=>{Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null);const e=se?w.activeRoom?.id??null:l?.id??null;if(!e){Xt.current=null;return}const n={threadId:e,loaded:se?!w.messagesLoading:!U,hasMessages:se?w.messages.length>0:$.length>0},o=Xt.current,d=o?.threadId!==e,x=o?.threadId===e&&!o.loaded&&n.loaded,_=o?.threadId===e&&!o.hasMessages&&n.hasMessages;if(!(o===null||d||x||_))return;const K=le.current;if(K)return Xn(d?"thread-change":x?"finished-loading":_?"first-messages":"mount"),Ee(K,{force:!0}),se||(Pe.current=window.setTimeout(()=>{if(Pe.current=null,de.current)return;const pe=le.current;pe&&Ee(pe)},250)),Xt.current=n,()=>{Pe.current!==null&&(window.clearTimeout(Pe.current),Pe.current=null)}},[se,w.activeRoom?.id,w.messages.length,w.messagesLoading,l?.id,$.length,U,Ee]),a.useEffect(()=>{!z||de.current||we("streaming")},[z,j,G,we]),a.useEffect(()=>{const e=dt();if(!e){qt.current=0,$n.current=null;return}if($n.current!==e){$n.current=e,qt.current=ut.length;return}const n=qt.current,o=ut.length,d=o>n,x=!de.current;qt.current=o,d&&x&&we("new-message")},[ut,dt,we]),a.useEffect(()=>{Qa<=0||!le.current||we("keyboard")},[Qa,we]),yo(We&&Zt),a.useLayoutEffect(()=>{if(!We||!l&&!se||typeof window>"u")return;const e=_n.current,n=window.visualViewport;if(!e||!n)return;const o=x=>{if(!(x instanceof HTMLElement))return!1;if(x.tagName==="TEXTAREA")return!0;if(x.tagName!=="INPUT")return!1;const _=x.type.toLowerCase();return["","text","search","email","url","tel","password","number"].includes(_)},d=()=>{if(Gt.current){e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange="";return}const x=Math.max(0,window.innerHeight-n.offsetTop-n.height),_=n.offsetTop||0;e.style.setProperty("--vv-height",`${n.height}px`),e.style.setProperty("--vv-offset-top",`${_}px`),e.style.setProperty("--keyboard-overlap",`${x}px`);const q=(x>0||_>0)&&o(document.activeElement);e.classList.toggle("chat-thread--keyboard-active",q),e.style.setProperty("--chat-keyboard-accessory-clearance",q&&ga()?"calc(var(--space-2xl) + var(--space-md))":"0px"),q&&_>0?(e.style.transform=`translateY(${_}px)`,e.style.willChange="transform"):(e.style.transform="",e.style.willChange="")};return d(),n.addEventListener("resize",d),n.addEventListener("scroll",d),document.addEventListener("focusin",d),document.addEventListener("focusout",d),window.addEventListener("pageshow",d),document.addEventListener("visibilitychange",d),()=>{n.removeEventListener("resize",d),n.removeEventListener("scroll",d),document.removeEventListener("focusin",d),document.removeEventListener("focusout",d),window.removeEventListener("pageshow",d),document.removeEventListener("visibilitychange",d),e.classList.remove("chat-thread--keyboard-active"),e.style.setProperty("--chat-keyboard-accessory-clearance","0px"),e.style.transform="",e.style.willChange=""}},[l,We,se]),a.useEffect(()=>{const e=()=>Se(null);if(Y)return document.addEventListener("click",e),()=>document.removeEventListener("click",e)},[Y]),a.useEffect(()=>{if(!We||!Zt)return;const e=n=>{n.target?.closest(".chat-messages")||n.preventDefault()};return document.addEventListener("touchmove",e,{passive:!1}),()=>{document.removeEventListener("touchmove",e)}},[We,Zt]),a.useEffect(()=>{const e=Wa.current;if(Wa.current=F,F==="rooms"&&!w.activeRoom){Xt.current=null;return}if(!(F==="direct"&&(e===null||e==="rooms"))&&!(F==="rooms"&&(e===null||e==="direct")))return;const d=le.current;d&&(Ee(d,{force:!0}),de.current=!1,Ut(!1))},[F,w.activeRoom,Ee]),a.useEffect(()=>{if(!l&&!se||se&&!H)return;const e=()=>{const o=!de.current;nn(),o&&H&&le.current&&we("visibility-restore")},n=()=>{document.visibilityState==="visible"&&e()};return document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",e),()=>{document.removeEventListener("visibilitychange",n),window.removeEventListener("pageshow",e)}},[H,We,l,se,nn,we]),a.useEffect(()=>{if(se||typeof ResizeObserver>"u")return;const e=le.current;if(!e)return;const n=new ResizeObserver(()=>{de.current||Ee(e)});return n.observe(e),()=>{n.disconnect()}},[se,Ee,l?.id,F]),a.useEffect(()=>{Xa.current=ge},[ge]),a.useEffect(()=>()=>{for(const e of Xa.current)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);for(const e of St.current.values())window.clearTimeout(e);St.current.clear()},[]);const mt=a.useCallback(e=>{if(!e||e.length===0)return;const n=[];for(const o of Array.from(e)){if(!cr.includes(o.type))continue;const d=o.type.startsWith("image/");n.push({file:o,previewUrl:d?URL.createObjectURL(o):""})}n.length>0&&Ht(o=>[...o,...n])},[]),es=a.useCallback(e=>{Ht(n=>{const o=n[e];return o?.previewUrl&&URL.revokeObjectURL(o.previewUrl),n.filter((d,x)=>x!==e)})},[]),ts=a.useCallback(e=>{mt(e.clipboardData?.files)},[mt]),ht=a.useCallback(async e=>{try{return await T(e),Mn(!1),H&&He(!1),!0}catch{return r(s("chat.failedToCreateSession","Failed to create chat session"),"error"),!1}},[T,r,H,s]),an=a.useCallback(()=>{if(v?.chatNewSessionMode==="always-default"&&y){if(y.kind==="agent"){ht({agentId:y.agentId});return}ht({agentId:Ce,modelProvider:y.modelProvider,modelId:y.modelId,thinkingLevel:y.thinkingLevel});return}Mn(!0)},[y,v?.chatNewSessionMode,ht]),ie=a.useCallback(e=>{const n=e??te.current;if(!n)return;const o=Jt==="tablet"?er:Ma;n.style.height="auto",n.style.height=`${sr(n.scrollHeight,o)}px`,n.style.overflowY=ar(n.scrollHeight,o)},[Jt]),Ri=As({textareaRef:te,value:Q,onChange:ce,onResize:()=>ie(te.current),projectId:i}),ji=As({textareaRef:Qt,value:Q,onChange:ce,onResize:()=>ie(Qt.current),projectId:i}),Ai=a.useCallback(e=>{te.current=e,e&&ie(e)},[ie]),Ti=a.useCallback(e=>{Qt.current=e,e&&ie(e)},[ie]);a.useLayoutEffect(()=>{ie(F==="rooms"?Qt.current:te.current),Bn.current&&(Bn.current=!1,te.current?.focus())},[F,Q,l?.id,w.activeRoom?.id,ie]),a.useEffect(()=>{if(I===void 0||I===Va.current||!D?.trim())return;Va.current=I;const e=n=>{n&&(Kn.current=!0),Qe("direct"),Bn.current=!0,ce(D)};if(!z&&v?.chatNewSessionMode==="always-default"&&y){const n=y.kind==="agent"?{agentId:y.agentId}:{agentId:Ce,modelProvider:y.modelProvider,modelId:y.modelId,thinkingLevel:y.thinkingLevel};ht(n).then(o=>e(o||F!=="direct"));return}e(F!=="direct")},[y,F,v?.chatNewSessionMode,ht,D,I,z,ie]);const ft=a.useCallback(()=>{if(ce(""),me)try{localStorage.removeItem(me)}catch{}Ue(!1),yt(""),at(!1),nt(""),st(-1),Ht(e=>{for(const n of e)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);return[]})},[me]),Xe=a.useCallback(e=>{Ht(n=>{const o=n.filter(d=>e.has(d.file));for(const d of o)d.previewUrl&&URL.revokeObjectURL(d.previewUrl);return n.filter(d=>!e.has(d.file))})},[]),qn=a.useCallback(()=>{const e=Q.trim(),n=ge.map(d=>d.file);if(!e&&n.length===0||!l)return;if(b){const d=Co(e,zs);if(d){if(!b.agentRunning){r(s("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}if(n.length>0){r(s("chat.commandNoAttachments","Attachments aren't supported with commands — remove them before sending"),"warning");return}ft(),d.command.run({taskId:b.taskId,projectId:b.projectId,remainder:d.remainder}).then(()=>{r(s("chat.commandSteerSuccess","Sent to the running agent"),"success")}).catch(x=>{const _=x instanceof Error&&x.message.trim()?x.message:s("chat.commandSteerFailed","Failed to send to the running agent");r(_,"error")});return}}if(e==="/clear"||e==="/new"){if(n.length>0){r(s("chat.clearNoAttachments","Remove the attachments before running /clear or /new — they would be discarded unsent"),"warning");return}if(l.agentId.startsWith(ko)){ft(),r(s("chat.newNotAllowedForTaskChat","This chat is tied to a task — /new and /clear can't clear it"),"warning");return}ft(),Cn(),fe(),T({agentId:l.agentId,modelProvider:l.modelProvider??void 0,modelId:l.modelId??void 0,thinkingLevel:l.thinkingLevel??void 0}).catch(()=>{r(s("chat.failedToClearConversation","Failed to clear conversation"),"error")});return}if(z&&n.length>0){r(s("chat.attachmentsNotQueued","Attachments can't be queued while a reply is streaming — wait for it to finish"),"warning");return}const o=new Set(n);ce("");try{re(e,n,{onAccepted:()=>Xe(o),onDelivered:()=>Xe(o),onFailed:()=>{ce(d=>d||e)}})}catch{ce(e)}},[Q,ge,l,ft,fe,Cn,T,r,re,b,z,Xe,s]),Gn=a.useCallback(async()=>{const e=Q.trim(),n=ge.map(o=>o.file);if(!(!e&&n.length===0)){if(F==="rooms"){if(!w.activeRoom)return;if(e==="/clear"||e==="/new"){if(n.length>0){r(s("chat.clearNoAttachments","Remove the attachments before running /clear or /new — they would be discarded unsent"),"warning");return}ft();try{await w.clearRoom(w.activeRoom.id)}catch{r(s("chat.failedToClearRoomConversation","Failed to clear room conversation"),"error")}return}if(On.current)return;On.current=!0;const o=Q,d=new Set(n);ce("");try{await w.sendRoomMessage(e,{files:n,onDelivered:()=>Xe(d)}),Xe(d)}catch(x){if(x instanceof di){Xe(d);const q=x.message.trim()?x.message:s("chat.messageSentButReplyFailed","Message sent, but assistant reply failed");r(s("chat.messageSentButReplyFailedDetail","Message sent, but assistant reply failed: {{detail}}",{detail:q}),"error");return}ce(o);const _=x instanceof Error&&x.message.trim()?x.message:s("chat.failedToSendRoomMessage","Failed to send room message");r(_,"error")}finally{On.current=!1}return}qn()}},[Q,ge,Oe,F,w,w.clearRoom,ft,r,qn,Xe]),sn=a.useCallback(async e=>{if(F==="rooms"){if(!w.activeRoom)return;try{await w.sendRoomMessage(e)}catch(n){const o=n instanceof Error&&n.message.trim()?n.message:s("chat.failedToSendRoomMessage","Failed to send room message");r(o,"error")}return}l&&re(e)},[l,r,Oe,F,w,re,s]),Qn=a.useCallback(e=>{ce(n=>{const o=wa(n);if(!o)return n;const d=`/skill:${e.name} `,x=n.slice(0,o.start)+d+n.slice(o.end);return window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus())}),x}),Ue(!1),yt(""),Ke(0)},[ie]),Yn=a.useCallback((e,n)=>{if(n){r(s("chat.commandNoRunningAgent","No running agent to steer"),"warning");return}ce(o=>{const d=wa(o);if(!d)return o;const x=`${e.trigger} `,_=o.slice(0,d.start)+x+o.slice(d.end);return window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus())}),_}),Ue(!1),yt(""),Ke(0)},[ie,r,s]),on=a.useCallback(e=>{const n=te.current;if(!n||Pn<0)return;const o=n.selectionStart??ct.current,d=n.selectionEnd??o,x=Math.max(o,d),_=Math.min(Pn,x),K=`${`@${e.name.replace(/\s+/g,"_")}`} `,pe=Q.slice(0,_)+K+Q.slice(x),gt=_+K.length;ce(pe),at(!1),nt(""),Ot(0),st(-1),window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus(),te.current.setSelectionRange(gt,gt))})},[Pn,Q,ie]),Nt=a.useCallback((e,n)=>{const d=te.current?.selectionStart??ct.current,x=Q.lastIndexOf("#",d),_=x>=0?x+n.length:e.length;ce(e),X.dismissMention(),Vt(!1),window.requestAnimationFrame(()=>{te.current&&(ie(te.current),te.current.focus(),te.current.setSelectionRange(_,_))})},[X,Q,ie]),ns=a.useCallback(e=>{if(ct.current=e.currentTarget.selectionStart??ct.current,X.mentionActive&&X.combinedItems.length>0){if(X.handleKeyDown(e,Q),e.key==="Enter"||e.key==="Tab"){const n=X.combinedItems[X.selectedIndex];n?.kind==="task"?Nt(X.selectTask(n.task,Q),`#${n.task.id}`):n?.kind==="file"&&Nt(X.selectFile(n.file,Q),`#${n.file.path}`)}return}if(Me&&e.key==="ArrowDown"){e.preventDefault(),Ve.length>0&&Ot(n=>(n+1)%Ve.length);return}if(Me&&e.key==="ArrowUp"){e.preventDefault(),Ve.length>0&&Ot(n=>n===0?Ve.length-1:n-1);return}if(Me&&e.key==="Enter"){e.preventDefault();const n=Ve[Bt]??Ve[0];n&&on(n);return}if(Me&&e.key==="Escape"){e.preventDefault(),at(!1),nt(""),st(-1);return}if(Ze&&e.key==="ArrowDown"){e.preventDefault(),xe.length>0&&Ke(n=>(n+1)%xe.length);return}if(Ze&&e.key==="ArrowUp"){e.preventDefault(),xe.length>0&&Ke(n=>n===0?xe.length-1:n-1);return}if(Ze&&(e.key==="Enter"||e.key==="Tab")&&xe.length>0){e.preventDefault();const n=xe[et]??xe[0];n?.kind==="skill"?Qn(n.skill):n?.kind==="command"&&Yn(n.command,n.disabled);return}if(Ze&&e.key==="Escape"){e.preventDefault(),Ue(!1);return}e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),Gn())},[Me,Ve,Bt,on,Ze,xe,et,Qn,Yn,Gn,X,Nt,Q]),rn=a.useCallback((e,n)=>{const o=lr(e,n);if(o){at(!0),nt(o.filter),st(o.start);return}at(!1),nt(""),st(-1)},[]),as=a.useCallback(e=>{const n=e.target,o=n.value,d=n.selectionStart??o.length;ie(n),ct.current=d,ce(o);const x=wa(o);x?(Ue(!0),yt(x.filter)):(Ue(!1),yt("")),rn(o,d),X.detectMention(o,d),Vt(X.mentionActive),X.mentionActive&&Fn(n)},[rn,ie]),cn=a.useCallback(e=>{const n=e.currentTarget,o=n.selectionStart??n.value.length;ct.current=o,rn(n.value,o),X.detectMention(n.value,o),Vt(X.mentionActive),X.mentionActive&&Fn(n)},[rn,X,Fn]),ss=a.useCallback(e=>{e.key!=="Escape"&&cn(e)},[cn]),is=a.useCallback(()=>{typeof window<"u"&&window.innerWidth<=768&&(Gt.current=!0,je.current!==null&&window.clearTimeout(je.current),je.current=window.setTimeout(()=>{Gt.current=!1,je.current=null},450),(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0),Ae.current!==null&&window.clearTimeout(Ae.current),Ae.current=window.setTimeout(()=>{Ae.current=null,document.activeElement?.tagName!=="TEXTAREA"&&(window.scrollY!==0||window.scrollX!==0)&&window.scrollTo(0,0)},350)),Re.current!==null&&window.clearTimeout(Re.current),Re.current=window.setTimeout(()=>{Ue(!1),at(!1),nt(""),st(-1),Vt(!1),X.dismissMention(),Re.current=null},120)},[X]),os=a.useCallback(()=>{Gt.current=!1,je.current!==null&&(window.clearTimeout(je.current),je.current=null),Re.current!==null&&(window.clearTimeout(Re.current),Re.current=null),Ae.current!==null&&(window.clearTimeout(Ae.current),Ae.current=null)},[]);a.useEffect(()=>()=>{je.current!==null&&window.clearTimeout(je.current),Ae.current!==null&&window.clearTimeout(Ae.current)},[]);const rs=a.useCallback(async e=>{Se(null);try{await O(e),r(s("chat.conversationArchived","Conversation archived"),"success")}catch{r(s("chat.failedToArchiveConversation","Failed to archive conversation"),"error")}},[O,r]),Ei=a.useCallback(async e=>{try{await E(e),r(s("chat.conversationRestored","Conversation restored"),"success")}catch{r(s("chat.failedToRestoreConversation","Failed to restore conversation"),"error")}},[E,r,s]),cs=a.useCallback(e=>{const n=Be.find(o=>o.id===e)??(l?.id===e?l:null);Se(null),Ne(!1),jn(n?.title??""),Lt({sessionId:e,title:n?.title??""})},[l,Be]),ls=a.useCallback(async()=>{if(It)try{await B(It.sessionId,Rn),Lt(null),jn(""),r(s("chat.conversationRenamed","Conversation renamed"),"success")}catch{}},[r,It,B,Rn,s]),ds=a.useCallback(async(e,n)=>{Se(null),Ne(!1);try{await oe(e,n),r(n?s("chat.conversationPinned","Conversation pinned"):s("chat.conversationUnpinned","Conversation unpinned"),"success")}catch{}},[r,oe,s]),Di=a.useCallback(async e=>{Pt(null),Se(null);try{await u(e),r(s("chat.conversationDeleted","Conversation deleted"),"success")}catch{r(s("chat.failedToDeleteConversation","Failed to delete conversation"),"error")}},[u,r]),Rt=a.useCallback(e=>{try{localStorage.setItem(Js,String(e))}catch{}},[]),Ii=a.useCallback(e=>{if(H||Mt)return;e.preventDefault(),e.stopPropagation();const n=e.currentTarget;typeof n.setPointerCapture=="function"&&n.setPointerCapture(e.pointerId);const o=e.clientX,d=Je;let x=d;document.body.style.userSelect="none";const _=K=>{const pe=K.clientX-o,gt=Math.max(vn,Math.min(bn,d+pe));x=gt,Dn(gt),Rt(gt)},q=K=>{typeof n.releasePointerCapture=="function"&&n.releasePointerCapture(K.pointerId),document.body.style.userSelect="",document.removeEventListener("pointermove",_),document.removeEventListener("pointerup",q),Rt(x)};document.addEventListener("pointermove",_),document.addEventListener("pointerup",q)},[H,Rt,Je,Mt]),Li=a.useCallback(e=>{if(H||Mt||e.key!=="ArrowLeft"&&e.key!=="ArrowRight")return;e.preventDefault();const n=e.shiftKey?50:10,o=e.key==="ArrowLeft"?-n:n,d=Math.max(vn,Math.min(bn,Je+o));Dn(d),Rt(d)},[H,Rt,Je,Mt]),us=a.useCallback(e=>{const n=Be.find(o=>o.id===e);ue("direct",e,n?.lastMessageAt??n?.updatedAt),Z(e),Ne(!1),H&&He(!1)},[Be,H,ue,Z]),Jn=a.useCallback(()=>{Z(""),He(!0),Ne(!1)},[Z]),Zn=a.useCallback(()=>{w.selectRoom(null),He(!0),Ne(!1)},[w]),Pi=()=>t.jsxs("div",{className:"chat-empty-state",children:[t.jsx(xn,{size:48,strokeWidth:1.5}),t.jsx("h2",{children:s("chat.startNewConversation","Start a new conversation")}),t.jsxs("button",{className:"btn btn-primary",onClick:an,children:[t.jsx(pt,{size:16}),s("chat.newChat","New Chat")]})]}),De=ai(l,l?.agentId?be.get(l.agentId)??null:null,zt),ea=a.useMemo(()=>{if(!De?.provider||!De.modelId)return null;const e=In.find(n=>n.provider===De.provider&&n.id===De.modelId);return e?.contextWindow?e.contextWindow:null},[De?.modelId,De?.provider,In]),Fi=a.useMemo(()=>Zo($,z?j:void 0),[z,$,j]),Fe=Ts(De?.provider,De?.modelId),qe=De?.provider??null,ta=!!(l||z||$.length>0),ln=H&&!xt&&(F==="rooms"?se:ta),dn=H?ln:F==="rooms"?se:!!l,ms=a.useRef(dn);a.useEffect(()=>{const e=ms.current;ms.current=dn,H&&(e||!dn||Ba({type:"view",revert:F==="rooms"?Zn:Jn}))},[F,Jn,Zn,dn,H,Ba]);const hs=l?.agentId===Ce?Fe??"Fusion":l?.title||be.get(l?.agentId??"")?.name||l?.agentId||"Chat",$i=l?.title||s("chat.untitledSession","Untitled"),_i=!!(Fe&&Fe!==hs),zi=!H&&ta&&ea!==null,fs=Qs(Fi),un=ea!==null?Qs(ea):null,na=un?s("chat.contextWindowAria","Estimated {{used}} of {{total}} context tokens",{used:fs,total:un}):null,Bi=ln&&F==="direct"&&!!l,gs=ln&&F==="direct",ps=ln&&F==="rooms",aa=be.get(l?.agentId??"")?.name||(l?.agentId===Ce?Fe??"Fusion":l?.agentId?.slice(0,30)??"Fusion"),sa=!1,ia=l?.agentId===Ce,Oi=e=>e.length>50?`${e.slice(0,50)}…`:e;a.useEffect(()=>{if(!Kt)return;const e=n=>{Ua.current?.contains(n.target)||Ne(!1)};return document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[Kt]),a.useEffect(()=>{if(!Wt)return;const e=o=>{Ka.current?.contains(o.target)||Ct(!1)},n=o=>{o.key==="Escape"&&Ct(!1)};return document.addEventListener("mousedown",e),document.addEventListener("keydown",n),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",n)}},[Wt]),a.useEffect(()=>{(!H||F!=="direct"||xt)&&Ne(!1)},[H,F,xt]),a.useEffect(()=>{Ct(!1)},[w.activeRoom?.id]);const vs=a.useCallback((e,n)=>{const o=St.current.get(e);o&&window.clearTimeout(o),za(x=>({...x,[e]:n}));const d=window.setTimeout(()=>{za(x=>{const{[e]:_,...q}=x;return q}),St.current.delete(e)},2e3);St.current.set(e,d)},[]),bs=a.useCallback(async(e,n)=>{const o=await So(n);vs(e,o?"success":"error")},[vs]),oa=l?.agentId===Ce,ra=a.useCallback((e,n,o,d,x=!0)=>{const _=oa&&o==="assistant",q=x&&o==="assistant"&&S?Mo(n,s("chat.reportFallbackTitle","Chat report")):null;if(!(!_&&!q?.handoff))return t.jsxs(t.Fragment,{children:[_&&t.jsx("button",{type:"button",className:`btn-icon chat-message-copy-action${ot[e]==="success"?" chat-message-copy-action--success":""}${ot[e]==="error"?" chat-message-copy-action--error":""}`,"data-testid":d??`chat-copy-response-${e}`,"aria-label":ot[e]==="success"?s("chat.responseCopied","Response copied"):ot[e]==="error"?s("chat.copyFailed","Copy failed"):s("chat.copyResponse","Copy response"),onClick:()=>{bs(e,n)},children:ot[e]==="success"?t.jsx(No,{size:14}):t.jsx(Ro,{size:14})}),q?.handoff&&t.jsx("button",{type:"button",className:"btn-icon","data-testid":`chat-send-as-report-${e}`,"aria-label":s("chat.sendAsReport","Send as report"),onClick:()=>{q.truncated&&r(s("chat.reportTrimmed","Message trimmed to 2000 characters for mail"),"warning"),S?.(q.handoff)},children:t.jsx(jo,{size:14})})]})},[r,ot,bs,S,oa,s]),ca=a.useCallback(e=>{const n=le.current;if(!n)return;const o=`[data-testid="chat-message-${e}"]`,d=n.querySelector(o);if(!d)return;const x=d.getBoundingClientRect().top-n.getBoundingClientRect().top+n.scrollTop,_=typeof window<"u"&&window.matchMedia?.("(prefers-reduced-motion: reduce)").matches;n.scrollTo({top:x,behavior:_?"auto":"smooth"})},[]),xs=l?.cliExecutorAdapterId??null,la=!!xs,Hi=xs==="generic"?"generic":"hybrid",Ui=l?.cliSessionFile||l?.id||"",ws=!la&&!z,ys=()=>t.jsxs("div",{className:"chat-messages",ref:le,onScroll:Za,children:[t.jsx("div",{ref:Ha,className:"chat-load-more-sentinel",children:kn&&U&&t.jsx("div",{className:"chat-loading-older",children:s("chat.loadingOlderMessages","Loading older messages…")})}),z?t.jsxs(t.Fragment,{children:[$.map((e,n)=>t.jsx(fa,{message:e,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,activeSessionId:l?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:null,copyAction:ra(e.id,e.content,e.role),onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===$.length-1&&!z,submittedQuestionAnswer:Zs($,n),onQuestionSubmit:sn,canEdit:ws,onEditMessage:Le},e.id)),t.jsx(Lo,{streamingText:j,streamingThinking:G,streamingToolCalls:ne,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,copyAction:oa&&j?ra("__streaming__",j,"assistant","chat-copy-response-streaming",!1):void 0,onQuestionSubmit:sn})]}):U?t.jsx("div",{className:"chat-empty-state",children:s("chat.loadingMessages","Loading messages...")}):$.length===0&&!l?Pi():$.length===0&&l?t.jsx("div",{className:"chat-empty-state",children:s("chat.noMessagesYet","No messages yet. Start the conversation!")}):t.jsx(t.Fragment,{children:$.map((e,n)=>t.jsx(fa,{message:e,forcePlain:!1,agentName:aa,hideAssistantIdentity:ia,showAssistantModelTag:sa,activeModelTag:Fe,activeModelProvider:qe,activeSessionId:l?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:null,copyAction:ra(e.id,e.content,e.role),onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:e.role==="assistant"&&n===$.length-1&&!z,submittedQuestionAnswer:Zs($,n),onQuestionSubmit:sn,canEdit:ws,onEditMessage:Le},e.id))}),t.jsx("div",{ref:Oa})]}),Cs=()=>t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file","data-testid":"chat-file-input",accept:ni,multiple:!0,style:{display:"none"},onChange:e=>{mt(e.target.files),e.target.value=""}}),Ze&&t.jsx("div",{className:"chat-skill-menu","data-testid":"chat-skill-menu",role:"listbox","aria-label":s("chat.skillSuggestions","Skill suggestions"),children:yi&&Wn.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:s("chat.loadingSkills","Loading skills…")}):xe.length===0?t.jsx("div",{className:"chat-skill-menu-empty",children:wt?s("chat.noSkillsFound","No skills found"):s("chat.noSkillsAvailable","No skills available")}):xe.map((e,n)=>e.kind==="command"?t.jsxs("button",{type:"button",role:"option","aria-selected":n===et,"aria-disabled":e.disabled,className:`chat-skill-menu-item chat-command-menu-item${n===et?" chat-skill-menu-item--highlighted":""}${e.disabled?" chat-command-menu-item--disabled":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>Ke(n),onClick:()=>Yn(e.command,e.disabled),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.command.trigger}),t.jsx("span",{className:"chat-skill-menu-item-description",children:e.disabled?s("chat.commandNoRunningAgentHint","No running agent to steer"):e.command.description})]},`command-${e.command.trigger}`):t.jsxs("button",{type:"button",role:"option","aria-selected":n===et,className:`chat-skill-menu-item${n===et?" chat-skill-menu-item--highlighted":""}`,onMouseDown:o=>o.preventDefault(),onMouseEnter:()=>Ke(n),onClick:()=>Qn(e.skill),children:[t.jsx("span",{className:"chat-skill-menu-item-name",children:e.skill.name}),t.jsx("span",{className:"chat-skill-menu-item-description",title:e.skill.relativePath,children:e.skill.relativePath})]},e.skill.id))}),ge.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ge.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),ze.length>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"chat-pending-stack","data-testid":"chat-pending-stack",children:ze.map((e,n)=>t.jsxs("div",{className:"chat-pending-message","data-testid":"chat-pending-indicator",children:[t.jsx("span",{children:s("chat.queuedMessage","Queued: {{preview}}",{preview:Oi(e)})}),t.jsx("button",{type:"button",className:"chat-pending-message-dismiss","aria-label":s("chat.dismissQueuedMessage","Dismiss queued message"),"data-testid":`chat-pending-dismiss-${n}`,onClick:()=>Cn(n),children:"×"})]},`${n}-${e}`))}),t.jsx("div",{className:"chat-pending-divider","aria-hidden":"true"})]}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":s("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Fs,{size:16})}),!la&&t.jsx(Ks,{level:l?.thinkingLevel,defaultThinkingLevel:M,models:In,favoriteProviders:bi,favoriteModels:xi,agents:Array.from(be.values()),agentId:l?.agentId,modelProvider:l?.modelProvider,modelId:l?.modelId,onChange:e=>{l&&g(l.id,e)},onChangeModel:e=>{l&&C(l.id,e)},disabled:!l}),t.jsxs("div",{className:`chat-input-wrapper${$a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),it(!0)},onDragLeave:()=>it(!1),onDrop:e=>{e.preventDefault(),it(!1),mt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:Ai,className:"chat-input-textarea",placeholder:s("chat.typeMessage","Type a message..."),value:Q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:cn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ga()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Vs,{agents:lt,filter:tt,highlightedIndex:Bt,visible:Me,onSelect:on,position:"below",roomMemberIds:Te?.memberIds,roomName:Te?.roomName}),t.jsx(Wo,{visible:X.mentionActive&&!Me,position:Ci,tasks:X.tasks,files:X.files,selectedIndex:X.selectedIndex,onSelectTask:e=>{Nt(X.selectTask(e,Q),`#${e.id}`)},onSelectFile:e=>{Nt(X.selectFile(e,Q),`#${e.path}`)},loading:X.loading})]}),t.jsx($s,{...Ri.micProps}),t.jsx(_s,{isStreaming:z,canSend:!!(Q.trim()||ge.length>0),onSend:qn,onStop:fe})]})]}),Ki=H?void 0:{width:`${Je}px`},ks=Ye?ee:Be,Ss=ks.filter(e=>e.pinnedAt!=null),Ms=ks.filter(e=>e.pinnedAt==null),ye=Y?Be.find(e=>e.id===Y.sessionId)??(l?.id===Y.sessionId?l:void 0):void 0,Ns=a.useCallback(async()=>{const e=An.trim();if(!e)return;let n;try{n=await ve(e)}catch{r(s("chat.failedToCreateTag","Failed to create tag"),"error");return}if(Y?.sessionId){const o=(ye?.tags??[]).map(d=>d.id);if(!o.includes(n.id))try{await ke(Y.sessionId,[...o,n.id])}catch{r(s("chat.failedToUpdateTags","Failed to update tags"),"error");return}}Ea("")},[r,Y,ye,ve,An,ke,s]),Wi=Bi?t.jsxs("div",{className:"chat-mobile-session-menu",ref:Ua,children:[t.jsxs("button",{type:"button",className:"btn chat-mobile-session-trigger","data-testid":"chat-mobile-session-trigger","aria-haspopup":"menu","aria-expanded":Kt,onClick:()=>Ne(e=>!e),children:[qe?t.jsx(ua,{provider:qe,size:"md"}):t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:$i}),t.jsx(hn,{size:16,"aria-hidden":"true"})]}),Kt&&t.jsxs("div",{className:"chat-mobile-session-dropdown",role:"menu","data-testid":"chat-mobile-session-dropdown",children:[[{id:"pinned",label:s("chat.pinned","Pinned"),testId:"chat-mobile-pinned-divider",sessions:Ss},{id:"recent",label:s("chat.recent","Recent"),testId:"chat-mobile-recent-divider",sessions:Ms}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-mobile-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>t.jsxs("div",{className:`chat-mobile-session-option-row${l?.id===n.id?" chat-mobile-session-option-row--active":""}`,role:"none",children:[t.jsx("button",{type:"button",role:"menuitem",className:`chat-mobile-session-option${l?.id===n.id?" chat-mobile-session-option--active":""}`,"data-testid":`chat-mobile-session-option-${n.id}`,onClick:()=>us(n.id),children:t.jsxs("span",{className:"chat-mobile-session-option-title",children:[n.title||s("chat.untitledSession","Untitled"),n.pinnedAt?t.jsx(fn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":s("chat.pinned","Pinned")}):null]})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-pin","data-testid":`chat-mobile-session-pin-${n.id}`,"aria-label":n.pinnedAt?s("chat.unpinConversationAria","Unpin conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}):s("chat.pinConversationAria","Pin conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}),title:!n.pinnedAt&&c>=3?s("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:!n.pinnedAt&&c>=3,onClick:()=>ds(n.id,!n.pinnedAt),children:n.pinnedAt?t.jsx(Es,{size:14}):t.jsx(fn,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-archive","data-testid":`chat-mobile-session-archive-${n.id}`,"aria-label":s("chat.archive","Archive"),onClick:()=>void rs(n.id),children:t.jsx(Ds,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon chat-mobile-session-rename","data-testid":`chat-mobile-session-rename-${n.id}`,"aria-label":s("chat.renameConversationAria","Rename conversation {{title}}",{title:n.title||s("chat.untitledSession","Untitled")}),onClick:()=>cs(n.id),children:t.jsx(ma,{size:14})})]},n.id))]},e.id)),t.jsxs("button",{type:"button",role:"menuitem",className:"chat-mobile-session-new","data-testid":"chat-mobile-session-new",onClick:()=>{Ne(!1),an()},children:[t.jsx(pt,{size:16,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.newChat","New Chat")})]})]})]}):null,Vi=t.jsxs("div",{className:"chat-sidebar-scope-toggle chat-view-header-scope-toggle",role:"tablist","data-testid":"chat-sidebar-scope-toggle",children:[t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${F==="direct"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":F==="direct","data-testid":"chat-sidebar-scope-direct",onClick:()=>Qe("direct"),children:[t.jsx(xn,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.scopeDirect","Direct")})]}),t.jsxs("button",{type:"button",role:"tab",className:`chat-sidebar-scope-btn${F==="rooms"?" chat-sidebar-scope-btn--active":""}`,"aria-selected":F==="rooms","data-testid":"chat-sidebar-scope-rooms",onClick:()=>Qe("rooms"),children:[t.jsx(li,{size:14,"aria-hidden":"true"}),t.jsx("span",{children:s("chat.scopeRooms","Rooms")})]})]});return t.jsxs("div",{ref:qa,className:`chat-view${h?" chat-view--floating":""}${H?" chat-view--narrow":""}${gs?" chat-view--mobile-direct-thread":""}`,children:[t.jsx(Ao,{icon:xn,title:s("chat.title","Chat"),actions:t.jsxs(t.Fragment,{children:[gs?t.jsxs(t.Fragment,{children:[t.jsx("button",{className:"btn-icon chat-back-btn",onClick:Jn,"data-testid":"chat-back-btn","aria-label":s("chat.backToConversations","Back to conversations"),children:t.jsx(Is,{size:16})}),Wi]}):Vi,H?null:t.jsxs("button",{className:"btn btn-sm btn-primary chat-view-header-new-chat",onClick:an,"data-testid":"chat-new-btn",children:[t.jsx(pt,{size:14}),s("chat.newChat","New Chat")]}),!h&&m?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:m,"aria-label":s("chat.popOut","Pop out chat"),title:s("chat.popOut","Pop out chat"),"data-testid":"chat-pop-out",children:t.jsx(Ls,{size:16})}):null,h&&f?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:f,"aria-label":s("chat.maximizeToChatView","Open in Chat view"),title:s("chat.maximizeToChatView","Open in Chat view"),"data-testid":"chat-modal-maximize",children:t.jsx(Ls,{size:16})}):null,h&&N?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:N,"aria-label":s("chat.minimizeToQuickChat","Minimize to quick chat"),title:s("chat.minimizeToQuickChat","Minimize to quick chat"),"data-testid":"chat-modal-minimize",children:t.jsx(To,{size:16})}):null,h&&k?t.jsx("button",{type:"button",className:"btn-icon chat-view-header-icon",onClick:k,"aria-label":s("chat.closeChat","Close chat"),title:s("chat.closeChat","Close chat"),"data-testid":"chat-modal-close",children:t.jsx(Ps,{size:16})}):null]})}),t.jsxs("div",{className:"chat-view__body",children:[t.jsxs("div",{className:`chat-sidebar${xt?"":" chat-sidebar--hidden"}`,style:Ki,children:[F==="direct"?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"chat-sidebar-search-container",children:[t.jsxs("div",{className:"chat-sidebar-search-wrapper",children:[t.jsx(Eo,{size:14,className:"chat-sidebar-search-icon"}),t.jsx("input",{type:"text",className:"chat-sidebar-search",placeholder:s("chat.searchConversations","Search conversations..."),value:hi,onChange:e=>fi(e.target.value),"data-testid":"chat-search-input"})]}),t.jsxs("label",{className:"chat-tag-filter",htmlFor:"chat-tag-filter",children:[t.jsx(_o,{size:14,"aria-hidden":"true"}),t.jsxs("select",{id:"chat-tag-filter",value:L??"",onChange:e=>V(e.target.value||null),"data-testid":"chat-tag-filter","aria-label":s("chat.filterByTag","Filter conversations by tag"),children:[t.jsx("option",{value:"",children:s("chat.allTags","All tags")}),A.map(e=>t.jsx("option",{value:e.id,children:e.name},e.id))]}),L?t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.clearTagFilter","Clear tag filter"),onClick:()=>V(null),children:t.jsx(Ps,{size:14})}):null]})]}),t.jsx("div",{className:"chat-archived-toggle",children:t.jsx("button",{type:"button",className:"btn btn-sm btn-secondary","data-testid":"chat-archived-toggle",onClick:()=>{const e=!Ye;pi(e),e&&W()},children:Ye?"Active conversations":"Archived conversations"})}),t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:P?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:s("chat.loadingConversations","Loading...")}):(Ye?ee:Be).length===0?t.jsx("div",{className:"chat-empty-state chat-empty-state--padded",children:s("chat.noConversationsYet","No conversations yet")}):t.jsx(t.Fragment,{children:[{id:"pinned",label:s("chat.pinned","Pinned"),testId:"chat-pinned-divider",sessions:Ss},{id:"recent",label:s("chat.recent","Recent"),testId:"chat-recent-divider",sessions:Ms}].filter(e=>e.sessions.length>0).map(e=>t.jsxs("section",{className:"chat-session-section","data-testid":`chat-session-section-${e.id}`,children:[t.jsx("div",{className:"chat-pinned-divider","data-testid":e.testId,children:e.label}),e.sessions.map(n=>{const o=l?.id===n.id,d=!o&&Ra("direct",n.id,n.lastMessageAt??n.updatedAt),x=ai(n,be.get(n.agentId)??null,zt),_=Ts(x?.provider,x?.modelId)??"Fusion",q=n.title||s("chat.untitledSession","Untitled");return t.jsxs("div",{className:`chat-session-item${o?" chat-session-item--active":""}`,onClick:()=>us(n.id),onContextMenu:K=>{K.preventDefault(),ja(n.id,K.clientX,K.clientY)},"data-testid":Ye?`chat-archived-session-${n.id}`:`chat-session-${n.id}`,children:[t.jsx("button",{type:"button",className:"btn-icon chat-session-menu-btn","data-testid":"chat-session-menu-btn","aria-label":s("chat.conversationActionsAria","Conversation actions for {{title}}",{title:q}),"aria-haspopup":"menu","aria-expanded":Y?.sessionId===n.id,onClick:K=>{if(K.stopPropagation(),Y?.sessionId===n.id){Se(null);return}const pe=K.currentTarget.getBoundingClientRect();ja(n.id,pe.right,pe.bottom,{anchorRight:!0})},children:t.jsx(Do,{size:14})}),t.jsxs("div",{className:"chat-session-title",children:[q,n.pinnedAt?t.jsx(fn,{className:"chat-session-pinned-indicator",size:14,"data-testid":`chat-session-pinned-indicator-${n.id}`,"aria-label":s("chat.pinned","Pinned")}):null,d?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${n.id}`,"aria-label":s("chat.unreadMessages","Unread messages")}):null]}),t.jsx("div",{className:"chat-session-preview",children:n.lastMessagePreview||s("chat.noMessages","No messages")}),(n.tags??[]).length>0?t.jsx("div",{className:"chat-session-tags","data-testid":`chat-session-tags-${n.id}`,children:(n.tags??[]).map(K=>t.jsx("span",{className:"chat-session-tag",children:K.name},K.id))}):null,n.matchedMessagePreview?t.jsx("div",{className:"chat-session-preview chat-session-preview--matched","data-testid":`chat-session-matched-preview-${n.id}`,children:s("chat.matchedInMessage",'Matched: "{{preview}}"',{preview:n.matchedMessagePreview})}):null,Ye?t.jsx("button",{type:"button",className:"btn btn-sm btn-secondary","data-testid":`chat-archived-restore-${n.id}`,onClick:K=>{K.stopPropagation(),Ei(n.id)},children:"Restore"}):null,t.jsxs("div",{className:"chat-session-meta",children:[t.jsxs("span",{className:"chat-session-meta-model",children:[x?.provider?t.jsx(ua,{provider:x.provider,size:"sm"}):null,t.jsx("span",{children:be.get(n.agentId)?.name||(n.agentId===Ce?_:n.agentId.slice(0,30))})]}),t.jsx("span",{children:n.updatedAt?ir(n.updatedAt,s):""})]})]},n.id)})]},e.id))})})]}):t.jsxs("div",{className:"chat-sidebar-rooms","data-testid":"chat-sidebar-rooms",children:[!H&&t.jsx("div",{className:"chat-sidebar-rooms-header","data-testid":"chat-sidebar-rooms-header",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary","data-testid":"chat-create-room-btn",onClick:()=>_t(!0),children:[t.jsx(pt,{size:14}),s("chat.createRoom","Create room")]})}),w.rooms.length===0?t.jsx("div",{className:"chat-sidebar-rooms-empty","data-testid":"chat-sidebar-rooms-empty",children:s("chat.noRoomsYet","No rooms yet.")}):t.jsx("div",{className:"chat-session-list chat-sidebar-list",children:w.rooms.map(e=>{const n=w.activeRoom?.id===e.id,o=!n&&Ra("room",e.id,e.updatedAt);return t.jsxs("div",{role:"button",tabIndex:0,className:`chat-room-item${n?" chat-room-item--active":""}`,"data-testid":`chat-room-item-${e.slug}`,onClick:()=>{ue("room",e.id,e.updatedAt),w.selectRoom(e.id),H&&He(!1)},onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),ue("room",e.id,e.updatedAt),w.selectRoom(e.id),H&&He(!1))},children:[t.jsxs("span",{className:"chat-room-item-details",children:[t.jsxs("span",{className:"chat-room-item-name-row",children:[t.jsxs("span",{className:"chat-room-item-name",children:["#",e.name]}),o?t.jsx("span",{className:"chat-unread-dot","data-testid":`chat-unread-dot-${e.id}`,"aria-label":s("chat.unreadMessages","Unread messages")}):null]}),n?t.jsx("span",{className:"chat-room-item-meta",children:s("chat.roomMemberCount","{{count}} member",{count:w.activeRoomMembers.length,defaultValue_one:"{{count}} member",defaultValue_other:"{{count}} members"})}):null]}),t.jsx("button",{type:"button",className:"btn-icon chat-room-item-delete","data-testid":`chat-room-delete-${e.slug}`,"aria-label":s("chat.deleteRoom","Delete room {{name}}",{name:e.name}),onClick:d=>{d.stopPropagation(),Ft(e.id)},children:t.jsx(ha,{size:14})})]},e.id)})})]}),F==="rooms"?H?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{type:"button",className:"btn btn-sm btn-primary chat-sidebar-footer-btn","data-testid":"chat-create-room-btn",onClick:()=>_t(!0),children:[t.jsx(pt,{size:14}),s("chat.createRoom","Create room")]})}):null:H?t.jsx("div",{className:"chat-sidebar-footer",children:t.jsxs("button",{className:"btn btn-sm btn-primary chat-sidebar-footer-btn",onClick:an,"data-testid":"chat-new-btn",children:[t.jsx(pt,{size:14}),s("chat.newChat","New Chat")]})}):null]}),!H&&xt&&!Mt&&t.jsx("div",{className:"chat-sidebar-resize-handle",role:"separator","aria-orientation":"vertical","aria-valuemin":vn,"aria-valuemax":bn,"aria-valuenow":Je,"aria-label":s("chat.resizeSidebar","Resize chat sidebar"),tabIndex:0,onPointerDown:Ii,onKeyDown:Li}),Y&&t.jsxs("div",{className:"chat-session-context-menu",ref:Nn,role:"menu",style:{top:Y.y,left:Y.x},onClick:e=>e.stopPropagation(),children:[t.jsxs("button",{onClick:()=>ds(Y.sessionId,!ye?.pinnedAt),"data-testid":"chat-context-pin",title:c>=3&&!ye?.pinnedAt?s("chat.pinLimit","You can pin up to 3 conversations"):void 0,disabled:c>=3&&!ye?.pinnedAt,children:[ye?.pinnedAt?t.jsx(Es,{size:14}):t.jsx(fn,{size:14}),ye?.pinnedAt?s("chat.unpin","Unpin"):s("chat.pin","Pin")]}),t.jsxs("button",{onClick:()=>cs(Y.sessionId),"data-testid":"chat-context-rename",children:[t.jsx(ma,{size:14}),s("chat.rename","Rename")]}),t.jsxs("div",{className:"chat-session-tag-menu",role:"group","aria-label":s("chat.conversationTags","Conversation tags"),children:[A.map(e=>{const n=(ye?.tags??[]).some(o=>o.id===e.id);return t.jsxs("div",{className:"chat-tag-menu-item",children:[t.jsxs("button",{type:"button",role:"menuitemcheckbox","aria-checked":n,"data-testid":`chat-context-tag-${e.id}`,onClick:()=>void ke(Y.sessionId,n?(ye?.tags??[]).filter(o=>o.id!==e.id).map(o=>o.id):[...(ye?.tags??[]).map(o=>o.id),e.id]).catch(()=>r(s("chat.failedToUpdateTags","Failed to update tags"),"error")),children:[n?"✓ ":"",e.name]}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.renameTag","Rename tag {{name}}",{name:e.name}),"data-testid":`chat-context-rename-tag-${e.id}`,onClick:o=>{o.stopPropagation(),Da(e.name),bt(e)},children:t.jsx(ma,{size:14})}),t.jsx("button",{type:"button",className:"btn-icon","aria-label":s("chat.deleteTag","Delete tag {{name}}",{name:e.name}),"data-testid":`chat-context-delete-tag-${e.id}`,onClick:o=>{o.stopPropagation(),$t(e)},children:t.jsx(ha,{size:14})})]},e.id)}),t.jsxs("div",{className:"chat-tag-create-row",children:[t.jsx("input",{className:"input",value:An,placeholder:s("chat.newTag","New tag"),"aria-label":s("chat.newTag","New tag"),onChange:e=>Ea(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),Ns())}}),t.jsx("button",{type:"button",className:"btn btn-sm",onClick:()=>void Ns(),children:s("chat.addTag","Add")})]})]}),t.jsxs("button",{onClick:()=>rs(Y.sessionId),"data-testid":"chat-context-archive",children:[t.jsx(Ds,{size:14}),s("chat.archive","Archive")]}),t.jsxs("button",{onClick:()=>{Se(null),Pt(Y.sessionId)},"data-testid":"chat-context-delete",children:[t.jsx(ha,{size:14}),s("chat.delete","Delete")]})]}),It&&t.jsx(Et,{onClose:()=>Lt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-dialog-title",children:s("chat.renameConversationTitle","Rename Conversation")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.renameConversationBody","Choose a new name for this conversation. Leave it blank to show Untitled.")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-input",children:s("chat.conversationName","Conversation name")}),t.jsx("input",{id:"chat-rename-input",className:"input chat-rename-input",type:"text",value:Rn,placeholder:s("chat.renamePlaceholder","Untitled"),"data-testid":"chat-rename-input",onChange:e=>jn(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),ls())},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Lt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void ls(),"data-testid":"chat-rename-save",children:s("chat.save","Save")})]})]})}),Tn&&t.jsx(Et,{onClose:()=>bt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-rename-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-rename-tag-dialog-title",children:s("chat.renameTagTitle","Rename tag")}),t.jsx("label",{className:"chat-rename-label",htmlFor:"chat-rename-tag-input",children:s("chat.tagName","Tag name")}),t.jsx("input",{id:"chat-rename-tag-input",className:"input chat-rename-input",value:En,"data-testid":"chat-rename-tag-input",onChange:e=>Da(e.target.value),onKeyDown:e=>{e.key==="Enter"&&(e.preventDefault(),ae(Tn.id,En).then(()=>bt(null)).catch(()=>r(s("chat.failedToRenameTag","Failed to rename tag"),"error")))},autoFocus:!0}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>bt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-primary","data-testid":"chat-rename-tag-save",onClick:()=>void ae(Tn.id,En).then(()=>bt(null)).catch(()=>r(s("chat.failedToRenameTag","Failed to rename tag"),"error")),children:s("chat.save","Save")})]})]})}),Ia&&t.jsx(Et,{onClose:()=>$t(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"chat-delete-tag-dialog-title",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{id:"chat-delete-tag-dialog-title",children:s("chat.deleteTagTitle","Delete tag?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.deleteTagBody","This removes the tag from all conversations, but does not delete conversations.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>$t(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger","data-testid":"chat-delete-tag-confirm",onClick:()=>void he(Ia.id).then(()=>$t(null)).catch(()=>r(s("chat.failedToDeleteTag","Failed to delete tag"),"error")),children:s("chat.delete","Delete")})]})]})}),Aa&&t.jsx(Et,{onClose:()=>Pt(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:s("chat.deleteConversationTitle","Delete Conversation?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.deleteConversationBody","This action cannot be undone. All messages in this conversation will be permanently deleted.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Pt(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>void Di(Aa),children:s("chat.delete","Delete")})]})]})}),Ta&&t.jsx(Et,{onClose:()=>Ft(null),children:t.jsxs("div",{className:"chat-new-dialog chat-view-dialog",onClick:e=>e.stopPropagation(),children:[t.jsx("h3",{children:s("chat.deleteRoomTitle","Delete Room?")}),t.jsx("p",{className:"chat-view-delete-dialog-copy",children:s("chat.deleteRoomBody","This action cannot be undone. This room and all its messages will be permanently deleted.")}),t.jsxs("div",{className:"chat-new-dialog-actions",children:[t.jsx("button",{className:"btn btn-sm",onClick:()=>Ft(null),children:s("chat.cancel","Cancel")}),t.jsx("button",{className:"btn btn-sm btn-danger",onClick:()=>{(async()=>{try{await w.deleteRoom(Ta),Ft(null)}catch{r(s("chat.failedToDeleteRoom","Failed to delete room"),"error")}})()},children:s("chat.delete","Delete")})]})]})}),F==="rooms"?t.jsxs("div",{ref:_n,className:"chat-thread",children:[w.activeRoom?t.jsxs(t.Fragment,{children:[(!H||ps)&&t.jsxs("div",{className:"chat-room-thread-header",children:[ps&&t.jsx("button",{className:"btn-icon",onClick:Zn,"data-testid":"chat-back-btn",children:t.jsx(Is,{size:16})}),t.jsxs("div",{className:"chat-room-switcher-menu",ref:Ka,children:[t.jsxs("button",{type:"button",className:"chat-room-switcher-trigger","data-testid":"chat-room-switcher-trigger","aria-haspopup":"menu","aria-expanded":Wt,onClick:()=>Ct(e=>!e),children:[t.jsxs("span",{className:"chat-thread-header-title",children:["#",w.activeRoom.name]}),t.jsx(hn,{size:16,"aria-hidden":"true"})]}),Wt&&t.jsx("div",{role:"menu",className:"chat-room-switcher-dropdown","data-testid":"chat-room-switcher-dropdown",children:w.rooms.map(e=>t.jsxs("button",{type:"button",role:"menuitem",className:`chat-room-switcher-option${e.id===w.activeRoom?.id?" chat-room-switcher-option--active":""}`,"data-testid":`chat-room-switcher-option-${e.id}`,onClick:()=>{ue("room",e.id,e.updatedAt),w.selectRoom(e.id),Ct(!1)},children:["#",e.name]},e.id))})]}),t.jsx("div",{className:"chat-room-thread-members",children:w.activeRoomMembers.map(e=>t.jsx(yn,{agent:be.get(e.agentId)??{id:e.agentId,name:e.agentId.slice(0,30)}},e.agentId))})]}),t.jsxs("div",{className:"chat-messages",ref:le,onScroll:Za,children:[w.messagesLoading?t.jsx("div",{className:"chat-empty-state",children:s("chat.loadingMessages","Loading messages...")}):w.messages.filter(e=>e.content.trim()!==Ys).length===0?t.jsx("div",{className:"chat-empty-state",children:s("chat.noMessagesYet","No messages yet. Start the conversation!")}):w.messages.filter(e=>e.content.trim()!==Ys).map(e=>{const n=e.senderAgentId?be.get(e.senderAgentId)?.name??e.senderAgentId.slice(0,30):s("chat.you","You"),o={id:e.id,sessionId:e.roomId,role:e.role,content:e.content,thinkingOutput:e.thinkingOutput??void 0,toolCalls:void 0,fallbackInfo:void 0,attachments:e.attachments,createdAt:e.createdAt};return t.jsx(fa,{message:o,forcePlain:!1,agentName:n,hideAssistantIdentity:!1,showAssistantModelTag:!1,activeModelTag:null,activeModelProvider:null,activeSessionId:w.activeRoom?.id??null,projectId:i,mentionAgentsByName:Vn,roomContext:Te,onScrollToTop:ca,isTopClipped:zn.has(e.id),isAwaitingQuestionAnswer:!1,onQuestionSubmit:sn},e.id)}),t.jsx("div",{ref:Oa})]}),w.activeRoom&&_a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(hn,{size:14}),s("chat.latest","Latest")]})]}):t.jsx("div",{className:"chat-room-empty-pane","data-testid":"chat-rooms-empty-pane",children:s("chat.selectRoomOrCreate","Select a room or create one")}),w.activeRoom&&t.jsxs("div",{className:"chat-input-area",children:[t.jsx("input",{ref:Yt,type:"file",accept:ni,multiple:!0,style:{display:"none"},onChange:e=>{mt(e.target.files),e.target.value=""}}),ge.length>0&&t.jsx("div",{className:"chat-attachment-previews","data-testid":"chat-attachment-previews",children:ge.map((e,n)=>t.jsxs("div",{className:"chat-attachment-preview","data-testid":`chat-attachment-preview-${n}`,children:[e.previewUrl?t.jsx("img",{src:e.previewUrl,alt:e.file.name}):t.jsx("span",{className:"chat-attachment-preview-name",children:e.file.name}),t.jsx("button",{type:"button",className:"chat-attachment-remove",onClick:()=>es(n),"data-testid":`chat-attachment-remove-${n}`,"aria-label":`Remove ${e.file.name}`,children:"×"})]},e.previewUrl||`${e.file.name}-${n}`))}),t.jsxs("div",{className:"chat-input-row",children:[t.jsx("button",{type:"button",className:"btn-icon chat-attach-btn","data-testid":"chat-attach-btn","aria-label":s("chat.attachFiles","Attach files"),onClick:()=>Yt.current?.click(),children:t.jsx(Fs,{size:16})}),t.jsx(Ks,{level:w.activeRoom.thinkingLevel,defaultThinkingLevel:M,showTargetSection:!1,onChange:e=>{w.updateRoomSettings(w.activeRoom.id,{thinkingLevel:e||null}).catch(()=>{r(s("chat.failedToUpdateRoomThinkingLevel","Failed to update room thinking effort"),"error")})}}),t.jsxs("div",{className:`chat-input-wrapper${$a?" chat-input-wrapper--dragover":""}`,onDragOver:e=>{e.preventDefault(),it(!0)},onDragLeave:()=>it(!1),onDrop:e=>{e.preventDefault(),it(!1),mt(e.dataTransfer.files)},children:[t.jsx("textarea",{ref:Ti,className:"chat-input-textarea",placeholder:s("chat.typeMessage","Type a message..."),value:Q,onChange:as,onKeyDown:ns,onKeyUp:ss,onClick:cn,onBlur:is,onFocus:os,onPaste:ts,onTouchStart:e=>{typeof window>"u"||window.innerWidth>768||ga()&&(document.activeElement,e.currentTarget)},rows:1,"data-testid":"chat-input"}),t.jsx(Vs,{agents:lt,filter:tt,highlightedIndex:Bt,visible:Me,onSelect:on,position:"below",roomMemberIds:Te?.memberIds,roomName:Te?.roomName})]}),t.jsx($s,{...ji.micProps}),t.jsx(_s,{isStreaming:!1,canSend:!!(Q.trim()||ge.length>0),onSend:Gn})]})]})]}):t.jsxs("div",{ref:_n,className:"chat-thread",children:[!H&&(ta||!H)&&t.jsx("div",{className:"chat-thread-header",children:t.jsxs("div",{className:"chat-thread-header-identity","data-testid":"chat-thread-header-identity",children:[qe?t.jsx(ua,{provider:qe,size:"md"}):t.jsx(wn,{size:16}),t.jsx("span",{className:"chat-thread-header-title",children:hs}),_i&&t.jsx("span",{className:"chat-model-tag",children:Fe}),zi&&un&&na?t.jsxs("span",{className:"chat-thread-header-context","data-testid":"chat-thread-context-window",title:na,"aria-label":na,children:[fs," / ",un]}):null]})}),la?t.jsx(qo,{cliSessionId:Ui,tier:Hi,projectId:i,renderTranscript:ys,renderComposer:()=>l?Cs():null}):t.jsxs(t.Fragment,{children:[ys(),_a&&t.jsxs("button",{type:"button",className:"btn btn-sm chat-jump-to-latest","data-testid":"chat-jump-to-latest",onClick:()=>we("fab-click"),children:[t.jsx(hn,{size:14}),s("chat.latest","Latest")]}),l&&Cs()]})]}),t.jsx(Xo,{isOpen:vi,onClose:()=>_t(!1),projectId:i,existingRoomNames:w.rooms.map(e=>e.name),onCreate:async e=>{await w.createRoom({name:e.name,memberAgentIds:e.memberAgentIds}),F!=="rooms"&&Qe("rooms"),_t(!1),H&&He(!1)}})]}),gi&&t.jsx(ur,{projectId:i,defaultModel:wi,defaultKind:y?.kind,defaultAgentId:y?.kind==="agent"?y.agentId:void 0,defaultThinkingLevel:M,defaultSelectedThinkingLevel:y?.kind==="model"?y.thinkingLevel:void 0,onClose:()=>Mn(!1),onCreate:ht})]})}export{Cr as ChatView,yr as buildIssueChatPrefill,sr as clampChatInputHeight,nr as resolveChatContextMenuPosition,ar as resolveChatInputOverflowY,ai as resolveSessionProvider};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{r as n,j as e}from"./vendor-react-SZ_qB27O.js";import{r as Ue,e as qe,S as Ht,au as zt,av as Ot,aw as Ye,b as $t,ax as It,ay as fe,az as Bt,aA as Ve,aB as _t,aC as Ut,aD as qt,aE as Vt,aF as Ae,aG as Qt,aH as Qe,V as Gt,aI as ce,E as Wt,y as Kt,aJ as Yt,X as Xt,R as Jt,aK as ke,A as Ge,D as We,aL as Ke,n as De,o as Ee,aM as Zt,aN as Xe,aO as es,aP as ts,aQ as ss,aR as ns,H as as,aS as cs,aT as os}from"./index-B_z7OKl4.js";import{u as rs}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";function is(a){const{projectId:u,searchQuery:m,includeProjectFiles:T=!0}=a??{},g=u?`${Ht.DOCUMENTS_PREFIX}${u}`:null,[w,t]=n.useState(()=>{if(!g)return[];const N=Ue(g,{maxAgeMs:qe});return Array.isArray(N)?N:[]}),[l,i]=n.useState([]),[P,d]=n.useState(()=>w.length===0),[b,k]=n.useState(null),p=n.useRef(null),h=n.useRef(w.length>0),j=n.useRef(null),{capture:C}=zt(u,"useDocuments"),L=n.useCallback(async()=>{const N=C();p.current&&p.current.abort();const M=new AbortController;p.current=M;const J=!h.current;J&&d(!0),k(null);const q=Ot(m?{q:m}:void 0,u),Z=T?Ye(u):Promise.resolve({files:[]}),[S,y]=await Promise.allSettled([q,Z]);if(M.signal.aborted||N.isStale())return;let re=null;if(S.status==="fulfilled"){if(t(S.value),g){const A=S.value.length>500?S.value.slice(0,500):S.value;$t(g,A,{maxBytes:5e5})}h.current=!0}else re=S.reason instanceof Error?S.reason.message:String(S.reason);if(y.status==="fulfilled"){const A=y.value.files,W=m?.trim().toLowerCase(),ie=W?A.filter(ee=>ee.name.toLowerCase().includes(W)||ee.path.toLowerCase().includes(W)):A;i(ie)}k(re),J&&d(!1)},[g,C,T,u,m]);return n.useEffect(()=>{if(i([]),!g){h.current=!1,t([]),d(!0);return}const N=Ue(g,{maxAgeMs:qe});Array.isArray(N)?(t(N),h.current=!0,d(!1)):(h.current=!1,t([]),d(!0))},[g]),n.useEffect(()=>(j.current&&clearTimeout(j.current),j.current=setTimeout(()=>{L()},300),()=>{j.current&&clearTimeout(j.current)}),[L]),n.useEffect(()=>(L(),()=>{p.current&&p.current.abort()}),[]),{documents:w,projectFiles:l,loading:P,error:b,refresh:L}}function ls(a,u){const[m,T]=n.useState([]),[g,w]=n.useState(!0),[t,l]=n.useState(null),i=n.useRef(null),P=n.useRef(!1),d=u?.showHidden??!1,b=n.useCallback(async k=>{i.current&&i.current.abort();const p=new AbortController;i.current=p;const h=!P.current;h&&w(!0),l(null);try{const j=await Ye(a,{showHidden:k?.showHidden??d});if(p.signal.aborted)return;T(j.files),P.current=!0}catch(j){if(p.signal.aborted)return;l(j instanceof Error?j.message:String(j))}finally{!p.signal.aborted&&h&&w(!1)}},[a,d]);return n.useEffect(()=>(P.current=!1,b({showHidden:d}),()=>{i.current&&i.current.abort()}),[b,d]),{files:m,loading:g,error:t,refresh:b}}const ds=768,us={image:ns,doc:ce,pdf:ss,video:ts,audio:es,other:Xe};function oe(a){return a?new Date(a).toLocaleString():""}function ms(a){return a<1024?`${a} B`:a<1024*1024?`${(a/1024).toFixed(a>=10*1024?0:1)} KB`:`${(a/(1024*1024)).toFixed(1)} MB`}function hs(a,u){return u?u.archived?"status-dot status-dot--offline":u.complete?"status-dot status-dot--online":u.intake||u.hold?"status-dot status-dot--pending":"status-dot status-dot--connecting":a==="done"?"status-dot status-dot--online":a==="archived"?"status-dot status-dot--offline":fs.has(a)?"status-dot status-dot--pending":"status-dot status-dot--connecting"}const fs=new Set(["triage","todo"]);function Je(a,u){switch(u){case"image":return a("documents.artifactCategoryImage","Image");case"doc":return a("documents.artifactCategoryDoc","Document");case"pdf":return a("documents.artifactCategoryPdf","PDF");case"video":return a("documents.artifactCategoryVideo","Video");case"audio":return a("documents.artifactCategoryAudioSingle","Audio");case"other":return a("documents.artifactCategoryOtherSingle","Other")}}function ks(a,u){return u?[a.title,a.description,a.taskId,a.taskTitle,a.mimeType,a.authorId].some(m=>m?.toLowerCase().includes(u)):!0}function ps(a){const u=a.mimeType?.toLowerCase().split(";",1)[0]??"";return!!a.content||a.type==="document"||u.startsWith("text/")||u==="application/json"||u==="application/xml"}function js({artifact:a,projectId:u,content:m,loading:T,error:g,renderMarkdown:w,onToggleMarkdown:t,onOpenTask:l,t:i}){const[P,d]=n.useState(null),b=Ae(a),k=Je(i,b),p=a.title||i("documents.untitledArtifact","Untitled artifact"),h=as(a.id,u),j=b==="doc"&&ps(a);n.useEffect(()=>{d(null)},[a.id]);const C=P?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:P}):null,L=b==="image"?e.jsxs(e.Fragment,{children:[C,e.jsx("img",{className:"documents-task-artifact-media",src:h,alt:p,onError:()=>d(i("documents.artifactMediaFailed","Failed to load artifact preview."))})]}):b==="video"?e.jsxs(e.Fragment,{children:[C,e.jsx("video",{className:"documents-task-artifact-media",controls:!0,src:h,"aria-label":i("documents.videoArtifactLabel","Video artifact: {{title}}",{title:p}),onError:()=>d(i("documents.artifactMediaFailed","Failed to load artifact preview."))})]}):b==="audio"?e.jsxs(e.Fragment,{children:[C,e.jsx("audio",{className:"documents-task-artifact-audio",controls:!0,src:h,"aria-label":i("documents.audioArtifactLabel","Audio artifact: {{title}}",{title:p}),onError:()=>d(i("documents.artifactMediaFailed","Failed to load artifact preview."))})]}):b==="pdf"?e.jsxs("div",{className:"documents-task-artifact-pdf",children:[e.jsx("iframe",{title:i("documents.pdfArtifactTitle","PDF artifact: {{title}}",{title:p}),src:h}),e.jsxs("a",{className:"btn btn-sm",href:h,target:"_blank",rel:"noreferrer",children:[e.jsx(cs,{size:14,"aria-hidden":"true"}),i("documents.openInNewTab","Open in new tab")]})]}):b==="doc"&&j?T?e.jsx("p",{className:"documents-content-state",children:e.jsx(ke,{label:i("documents.loadingArtifactContent","Loading artifact content…")})}):g?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:g}):w?e.jsx("div",{className:"documents-content-markdown documents-task-artifact-doc-content",children:e.jsx("div",{className:"markdown-body",children:e.jsx(De,{remarkPlugins:[Ee],children:m??a.content??""})})}):e.jsx("pre",{className:"document-card-content-text documents-content-viewer-text documents-task-artifact-doc-content",children:m??a.content??""}):e.jsxs("div",{className:"documents-task-artifact-download",children:[e.jsx(Xe,{size:24,"aria-hidden":"true"}),e.jsx("p",{children:a.description||i("documents.binaryArtifactFallback","This artifact cannot be previewed inline.")}),e.jsxs("a",{className:"btn btn-sm",href:h,target:"_blank",rel:"noreferrer","data-testid":"task-artifact-open-link",children:[e.jsx(os,{size:14,"aria-hidden":"true"}),i("documents.openArtifact","Open artifact")]})]});return e.jsxs("div",{className:"documents-content-viewer documents-task-artifact-viewer",children:[e.jsxs("div",{className:"documents-content-header documents-task-document-header",children:[e.jsxs("p",{className:"documents-file-path-header",children:[a.taskId," / ",p]}),b==="doc"&&j?e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:t,"aria-label":w?i("documents.switchToPlainText","Switch to plain text"):i("documents.switchToMarkdown","Switch to markdown"),"aria-pressed":w,title:w?i("documents.switchToPlainText","Switch to plain text"):i("documents.switchToMarkdown","Switch to markdown"),children:w?i("documents.markdown","Markdown"):i("documents.plain","Plain")}):null]}),e.jsxs("div",{className:"document-card-meta documents-task-document-meta documents-task-artifact-meta",children:[e.jsx("span",{children:k}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{children:a.authorId||i("documents.unknownAuthor","unknown")}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{children:oe(a.updatedAt)}),a.taskId?e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("button",{className:"documents-task-artifact-open-task",onClick:()=>void l(a.taskId),children:i("documents.openTask","Open task")})]}):null]}),a.description?e.jsx("p",{className:"documents-task-artifact-description",children:a.description}):null,e.jsx("div",{className:`documents-task-artifact-preview documents-task-artifact-preview--${b}`,children:L})]})}function Ss({projectId:a,columnFlagsByTaskId:u,addToast:m,onOpenDetail:T,onOpenArtifactTaskDetail:g,onSendSelectionToTask:w}){const{t}=rs("app"),[l,i]=n.useState("artifacts"),P=It(),[d,b]=n.useState(""),[k,p]=n.useState(null),[h,j]=n.useState(null),[C,L]=n.useState(!1),[N,M]=n.useState(null),[J,q]=n.useState(!1),[Z,S]=n.useState(null),[y,re]=n.useState(!1),A=n.useRef(0),W=n.useRef(null),ie=n.useRef(null),ee=n.useRef(null),Le=n.useRef(null),[K,Me]=n.useState(!1),[Ze,Re]=n.useState(new Map),[et,R]=n.useState(null),[pe,D]=n.useState(""),[le,E]=n.useState(null),[V,F]=n.useState(null),[de,je]=n.useState(!1),[tt,H]=n.useState(null),[st,B]=n.useState(!1),[nt,z]=n.useState(null),[at,xe]=n.useState(!0),te=n.useRef(0),[be,Q]=n.useState(!1),[ue,_]=n.useState(""),[we,ve]=n.useState(!1),[me,He]=n.useState(!1),ct=fe(W,{locked:me}),ot=fe(ie,{locked:me}),rt=fe(ee,{locked:me}),it=fe(Le,{locked:me}),ge=K?ct:ot,Ne=l==="tasks"?d.trim():"",lt=l==="artifacts"?d.trim():"",{documents:se,loading:dt,error:ut,refresh:ne}=is({projectId:a,searchQuery:Ne||void 0,includeProjectFiles:!1}),{files:G,loading:mt,error:ht,refresh:ze}=ls(a,{showHidden:C}),{artifacts:O,loading:ft,error:kt,refresh:Se}=Bt({projectId:a,searchQuery:lt||void 0});n.useEffect(()=>{const s=()=>{re(window.innerWidth<=ds)};return s(),window.addEventListener("resize",s),()=>{window.removeEventListener("resize",s)}},[]),n.useEffect(()=>{i("artifacts"),p(null),j(null),L(!1),M(null),S(null),q(!1),Me(!1),Re(new Map),R(null),D(""),E(null),F(null),je(!1),H(null),B(!1),z(null),xe(!0),Q(!1),_(""),ve(!1)},[a]);const Y=n.useMemo(()=>{const s=Ne.toLowerCase(),c=new Map;for(const o of se){const x=c.get(o.taskId)??{documents:[],artifacts:[]};x.documents.push(o),c.set(o.taskId,x)}for(const o of O){if(!o.taskId||!ks(o,s))continue;const x=c.get(o.taskId)??{documents:[],artifacts:[]};x.artifacts.push(o),c.set(o.taskId,x)}return Array.from(c.entries()).map(([o,x])=>{const I=[...x.documents].sort((v,ae)=>ae.updatedAt.localeCompare(v.updatedAt)),U=[...x.artifacts].sort((v,ae)=>ae.updatedAt.localeCompare(v.updatedAt)),Pe=[I[0]?.updatedAt,U[0]?.updatedAt].filter(Boolean).sort().at(-1)??"",f=I.find(v=>v.taskTitle)?.taskTitle??U.find(v=>v.taskTitle)?.taskTitle;return{taskId:o,taskTitle:f,taskColumn:I.find(v=>v.taskColumn)?.taskColumn??U.find(v=>v.taskColumn)?.taskColumn,documents:I,artifacts:U,latestUpdated:Pe}}).filter(o=>o.documents.length>0||o.artifacts.length>0).sort((o,x)=>x.latestUpdated.localeCompare(o.latestUpdated))},[O,se,Ne]),r=n.useMemo(()=>h?.kind!=="document"?null:se.find(s=>s.id===h.id)??null,[se,h]),$=n.useMemo(()=>h?.kind!=="artifact"?null:O.find(s=>s.id===h.id)??null,[O,h]),he=r??$;n.useEffect(()=>{if(!h)return;Y.some(c=>h.kind==="document"?c.documents.some(o=>o.id===h.id):c.artifacts.some(o=>o.id===h.id))||(j(null),R(null),D(""),E(null),F(null),H(null),B(!1),z(null))},[Y,h]);const Ce=n.useMemo(()=>{const s=d.trim().toLowerCase();return s?G.filter(c=>{const o=c.path.toLowerCase(),x=c.name.toLowerCase();return o.includes(s)||x.includes(s)}):G},[G,d]);n.useEffect(()=>{if(!k)return;G.some(c=>c.path===k.path)||(p(null),M(null),S(null),q(!1))},[G,k]);const pt=n.useCallback(s=>{b(s.target.value)},[]),jt=n.useCallback(()=>{b("")},[]),ye=n.useCallback(s=>{i(s),s!=="tasks"&&(j(null),R(null),D(""),E(null),F(null),H(null),B(!1),z(null)),s!=="project"&&(Q(!1),_(""))},[]),xt=n.useCallback(async s=>{try{const c=await Ve(s,a);T(c)}catch{m(`Failed to open task ${s}`,"error")}},[a,T,m]),Oe=n.useCallback(async s=>{try{const c=await Ve(s,a);(g??T)(c)}catch{m(`Failed to open task ${s}`,"error")}},[a,g,T,m]),bt=n.useCallback(async s=>{p(s),q(!0),S(null),M(null),Q(!1),_("");const c=A.current+1;A.current=c;try{const o=await _t("project",s.path,a);if(A.current!==c)return;M(o.content)}catch(o){if(A.current!==c)return;const x=o instanceof Error?o.message:`Failed to open ${s.path}`;S(x),m(x,"error")}finally{A.current===c&&q(!1)}},[a,m]),wt=n.useCallback(()=>{p(null),M(null),S(null),q(!1),Q(!1),_("")},[]),vt=n.useCallback(()=>{N!==null&&(_(N),Q(!0))},[N]),gt=n.useCallback(()=>{Q(!1),_("")},[]),Nt=n.useCallback(async()=>{if(k){ve(!0);try{await Ut("project",k.path,ue,a),M(ue),Q(!1),_(""),m(t("documents.projectFileSaved","File saved"),"success")}catch(s){m(s instanceof Error?s.message:String(s),"error")}finally{ve(!1)}}},[k,ue,a,m,t]),St=n.useCallback(s=>{j({kind:"document",id:s}),R(null),D(""),E(null),F(null),H(null),B(!1),z(null)},[]),Ct=n.useCallback(s=>{j({kind:"artifact",id:s}),R(null),D(""),E(null),F(null),H(null),z(null),xe(!0)},[]),yt=n.useCallback(()=>{j(null),R(null),D(""),E(null),F(null),H(null),B(!1),z(null)},[]),Tt=n.useCallback(s=>{Re(c=>{const o=new Map(c),x=o.get(s)??!0;return o.set(s,!x),o})},[]),Ft=n.useCallback(()=>{r&&(D(r.content),R(r.id),E({revision:r.revision,contentHash:r.contentHash}),F(null))},[r]),Pt=n.useCallback(()=>{R(null),D(""),E(null),F(null)},[]),At=n.useCallback(()=>{V&&(E(V),F(null))},[V]),Dt=n.useCallback(async()=>{if(!(!r||!le||V)){je(!0);try{await qt(r.taskId,r.key,pe,{expectedRevision:le.revision,expectedContentHash:le.contentHash},a),await ne(),R(null),D(""),E(null),F(null),m(t("documents.taskDocumentSaved","Document saved"),"success")}catch(s){if(typeof s=="object"&&s!==null&&"status"in s&&s.status===409)try{const c=await Vt(r.taskId,r.key,a);await ne(),F({revision:c.revision,contentHash:c.contentHash}),m(t("documents.taskDocumentStale","This document changed since you opened it. Your draft is preserved; review the latest revision, then choose Rebase draft before saving."),"error")}catch(c){m(c instanceof Error?c.message:String(c),"error")}else m(s instanceof Error?s.message:String(s),"error")}finally{je(!1)}}},[r,pe,le,V,a,ne,m,t]);n.useEffect(()=>{if(!$||Ae($)!=="doc"){H(null),B(!1),z(null);return}const s=te.current+1;te.current=s,B(!0),z(null),H(null),Qt($.id,a).then(c=>{te.current===s&&H(c.content??$.content??"")}).catch(c=>{te.current===s&&z(c instanceof Error?c.message:String(c))}).finally(()=>{te.current===s&&B(!1)})},[a,$]);const $e=l==="project"?ht:l==="tasks"?ut:kt,Et=n.useCallback(async()=>{if(l==="project"){await ze();return}if(l==="tasks"){await ne();return}await Se()},[l,Se,ze,ne]),Ie=l==="project"?Ce.length:l==="tasks"?Y.length:O.length,X=r?Ze.get(r.id)??!0:!1,Te=X?rt:it,Fe=r!==null&&et===r.id,Lt=l==="project"&&k&&!be&&w&&ge?e.jsx(Qe,{selectedText:ge.selectedText,anchorRect:ge.anchorRect,filePath:k.path,onSubmit:w,onOpenChange:He}):null,Mt=l==="tasks"&&r&&!Fe&&w&&Te?e.jsx(Qe,{selectedText:Te.selectedText,anchorRect:Te.anchorRect,filePath:`${r.taskId}/${r.key}`,onSubmit:w,onOpenChange:He}):null,Be=l==="project"?t("documents.searchProjectFiles","Search project markdown files…"):l==="tasks"?t("documents.searchTaskDocuments","Search task documents…"):t("documents.searchArtifacts","Search artifacts…");return e.jsxs("div",{className:"documents-view",children:[e.jsxs("div",{className:"documents-view-header",children:[e.jsx(Gt,{icon:ce,title:t("documents.title","Artifacts"),actions:e.jsx("span",{className:"documents-view-count",children:t("documents.resultCount","{{count}} result{{plural}}",{count:Ie,plural:Ie!==1?"s":""})})}),e.jsxs("div",{className:"documents-controls-row",children:[e.jsxs("div",{className:"documents-tab-bar",role:"tablist","aria-label":t("documents.sectionsLabel","Documents sections"),children:[e.jsxs("button",{className:`btn documents-tab${l==="artifacts"?" active":""}`,role:"tab","aria-selected":l==="artifacts","aria-label":t("documents.showArtifacts","Show artifacts"),onClick:()=>ye("artifacts"),children:[t("documents.artifactsTab","Artifacts"),e.jsx("span",{className:"documents-tab-count",children:O.length})]}),e.jsxs("button",{className:`btn documents-tab${l==="project"?" active":""}`,role:"tab","aria-selected":l==="project","aria-label":t("documents.showProjectFiles","Show project markdown files"),onClick:()=>ye("project"),children:[t("documents.projectFilesTab","Project Files"),e.jsx("span",{className:"documents-tab-count",children:G.length})]}),e.jsxs("button",{className:`btn documents-tab${l==="tasks"?" active":""}`,role:"tab","aria-selected":l==="tasks","aria-label":t("documents.showTaskDocuments","Show task documents"),onClick:()=>ye("tasks"),children:[t("documents.taskDocumentsTab","Task Documents"),e.jsx("span",{className:"documents-tab-count",children:Y.length})]})]}),l==="project"&&e.jsxs("button",{className:"btn btn-sm documents-hidden-toggle",onClick:()=>L(s=>!s),"aria-pressed":C,"aria-label":C?t("documents.hideHidden","Hide hidden project files"):t("documents.showHidden","Show hidden project files"),title:C?t("documents.hideHiddenFiles","Hide hidden files"):t("documents.showHiddenFiles","Show hidden files"),children:[C?e.jsx(Wt,{size:14}):e.jsx(Kt,{size:14}),C?t("documents.hideHiddenLabel","Hide Hidden"):t("documents.showHiddenLabel","Show Hidden")]}),e.jsxs("div",{className:"documents-search",children:[e.jsx(Yt,{size:16,className:"documents-search-icon"}),e.jsx("input",{type:"text",className:"documents-search-input",placeholder:Be,value:d,onChange:pt,"aria-label":Be}),d&&e.jsx("button",{className:"documents-search-clear",onClick:jt,"aria-label":t("documents.clearSearch","Clear search"),children:e.jsx(Xt,{size:16})})]})]})]}),e.jsx("div",{className:"documents-view-content",children:$e?e.jsxs("div",{className:"documents-view-error",children:[e.jsx("p",{children:t("documents.failedToLoad","Failed to load {{type}}: {{error}}",{type:l==="project"?t("documents.projectFiles","project files"):l==="tasks"?t("documents.taskDocuments","task documents"):t("documents.artifacts","artifacts"),error:$e})}),e.jsxs("button",{className:"btn btn-primary",onClick:()=>void Et(),"aria-label":t("documents.retryLoading","Retry loading documents"),children:[e.jsx(Jt,{size:16}),t("documents.retry","Retry")]})]}):l==="project"?mt&&G.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:e.jsx(ke,{label:t("documents.loadingProjectFiles","Loading project markdown files…")})})}):Ce.length===0?e.jsx("div",{className:"documents-view-empty",children:d.trim()?e.jsx("p",{children:t("documents.noMatchProject",'No project markdown files match "{{query}}".',{query:d.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:t("documents.noMarkdownFiles","No Markdown files found in this project.")})]})}):e.jsxs("div",{className:`documents-project-layout${y?" documents-project-layout--mobile":""}`,children:[(!y||!k)&&e.jsx("aside",{className:"documents-view-sidebar","aria-label":t("documents.projectMarkdownFilesLabel","Project markdown files"),children:e.jsx("ul",{className:"markdown-file-list",children:Ce.map(s=>{const c=k?.path===s.path;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item${c?" markdown-file-item--selected":""}`,onClick:()=>void bt(s),"aria-label":`Open ${s.path}`,"aria-current":c?"true":void 0,children:[e.jsx("span",{className:"markdown-file-item-name",children:s.name}),e.jsx("span",{className:"markdown-file-item-path",children:s.path}),e.jsxs("span",{className:"markdown-file-item-meta",children:[ms(s.size)," · ",oe(s.mtime)]})]})},s.path)})})}),(!y||k)&&e.jsxs("section",{className:"documents-view-main","aria-label":t("documents.projectFilePreviewLabel","Project file content preview"),children:[y&&k&&e.jsxs("button",{className:"btn btn-sm documents-mobile-back",onClick:wt,"aria-label":t("documents.backToFilesList","Back to project files list"),children:[e.jsx(Ge,{size:14}),t("documents.backToFiles","Back to files")]}),k?e.jsxs("div",{className:"documents-content-viewer",children:[e.jsxs("div",{className:"documents-content-header",children:[e.jsx("p",{className:"documents-file-path-header",children:k.path}),e.jsx("div",{className:"documents-task-document-actions",children:be?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:gt,disabled:we,children:t("documents.cancelEdit","Cancel")}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void Nt(),disabled:we,children:we?t("documents.saving","Saving…"):t("documents.saveProjectFile","Save")})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>Me(s=>!s),"aria-label":K?t("documents.switchToPlainText","Switch to plain text"):t("documents.switchToMarkdown","Switch to markdown"),"aria-pressed":K,title:K?t("documents.switchToPlainText","Switch to plain text"):t("documents.switchToMarkdown","Switch to markdown"),children:K?t("documents.markdown","Markdown"):t("documents.plain","Plain")}),e.jsxs("button",{className:"btn btn-sm",onClick:vt,disabled:J||Z!==null||N===null,"aria-label":t("documents.editProjectFile","Edit project file"),children:[e.jsx(We,{size:14,"aria-hidden":"true"}),t("documents.edit","Edit")]})]})})]}),J?e.jsx("p",{className:"documents-content-state",children:e.jsx(ke,{label:t("documents.loadingFileContent","Loading file content…")})}):Z?e.jsx("p",{className:"documents-content-state documents-content-state--error",children:Z}):be?e.jsx("div",{className:"documents-task-document-editor","aria-label":t("documents.projectFileContentEditor","Project file content editor"),children:e.jsx(Ke,{content:ue,onChange:_,filePath:k.path,forceToolbarActionsVisible:!0})}):K?e.jsx("div",{ref:W,className:"documents-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(De,{remarkPlugins:[Ee],children:N??""})})}):e.jsx("pre",{ref:ie,className:"document-card-content-text documents-content-viewer-text",children:N??""}),Lt]}):e.jsx("div",{className:"documents-view-empty",children:e.jsx("p",{children:t("documents.selectFile","Select a Markdown file to view its content.")})})]})]}):l==="artifacts"?ft&&O.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:t("documents.loadingArtifacts","Loading artifacts…")})}):O.length===0?e.jsx("div",{className:"documents-view-empty",children:d.trim()?e.jsx("p",{children:t("documents.noMatchArtifacts",'No artifacts match "{{query}}".',{query:d.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:t("documents.noArtifacts","No artifacts yet.")}),e.jsx("p",{className:"documents-view-empty-hint",children:t("documents.artifactsCreatedBy","Agents register screenshots, wireframes, mockups, recordings, and documents here as they work on tasks.")})]})}):e.jsx(Zt,{artifacts:O,projectId:a,isMobile:y,addToast:m,onOpenTask:Oe,onArtifactUpdated:()=>void Se()}):dt&&se.length===0?e.jsx("div",{className:"documents-view-loading",children:e.jsx("p",{children:e.jsx(ke,{label:t("documents.loadingTaskDocuments","Loading task documents…")})})}):Y.length===0?e.jsx("div",{className:"documents-view-empty",children:d.trim()?e.jsx("p",{children:t("documents.noMatchTask",'No task documents match "{{query}}".',{query:d.trim()})}):e.jsxs(e.Fragment,{children:[e.jsx(ce,{size:48,className:"documents-view-empty-icon"}),e.jsx("p",{children:t("documents.noTaskDocuments","No task documents yet.")}),e.jsx("p",{className:"documents-view-empty-hint",children:t("documents.documentsCreatedIn","Documents are created in task detail tabs.")})]})}):e.jsxs("div",{className:`documents-project-layout documents-task-documents-layout${y?" documents-project-layout--mobile":""}`,children:[(!y||!he)&&e.jsx("aside",{className:"documents-view-sidebar documents-task-documents-sidebar","aria-label":t("documents.taskDocumentsListLabel","Task documents"),children:Y.map(({taskId:s,taskTitle:c,taskColumn:o,documents:x,artifacts:I})=>{const U=o?P(o):null,Pe=o?hs(o,u?.get(s)):"status-dot";return e.jsxs("section",{className:"documents-task-sidebar-group","aria-labelledby":`documents-task-group-${s}`,children:[e.jsxs("div",{className:"documents-task-sidebar-group-header",children:[e.jsxs("div",{className:"documents-task-sidebar-title-wrap",children:[e.jsxs("h3",{id:`documents-task-group-${s}`,className:"documents-task-sidebar-title",children:[e.jsx("span",{className:"documents-group-task-id",children:s}),e.jsx("span",{className:"documents-group-task-title",children:c||t("documents.untitled","Untitled")})]}),U?e.jsxs("span",{className:"documents-group-status badge","aria-label":t("documents.taskStatusAria","Task status: {{status}}",{status:U}),children:[e.jsx("span",{className:Pe,"aria-hidden":"true"}),e.jsx("span",{children:U})]}):null]}),e.jsxs("div",{className:"documents-task-sidebar-actions",children:[e.jsx("span",{className:"documents-group-count",children:t("documents.taskOutputCount","{{docCount}} doc{{docPlural}} · {{artifactCount}} artifact{{artifactPlural}}",{docCount:x.length,docPlural:x.length!==1?"s":"",artifactCount:I.length,artifactPlural:I.length!==1?"s":""})}),e.jsx("button",{className:"documents-group-task-link",onClick:()=>void xt(s),"aria-label":t("documents.openTaskAria","Open task {{taskId}}: {{title}}",{taskId:s,title:c||t("documents.untitled","Untitled")}),children:t("documents.openTask","Open task")})]})]}),e.jsxs("ul",{className:"markdown-file-list documents-task-document-list",children:[x.map(f=>{const v=r?.id===f.id;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item documents-task-document-item${v?" markdown-file-item--selected":""}`,onClick:()=>St(f.id),"aria-label":t("documents.openTaskDocument","Open {{taskId}} {{key}}",{taskId:f.taskId,key:f.key}),"aria-current":v?"true":void 0,children:[e.jsx("span",{className:"markdown-file-item-name",children:f.key}),e.jsxs("span",{className:"markdown-file-item-path",children:[f.taskId," · ",f.taskTitle||t("documents.untitled","Untitled")]}),e.jsxs("span",{className:"markdown-file-item-meta",children:[t("documents.revisionShort","v{{revision}}",{revision:f.revision})," · ",f.author," · ",oe(f.updatedAt)]})]})},`document-${f.id}`)}),I.length>0?e.jsxs("li",{className:"documents-task-artifacts-subsection","aria-label":t("documents.taskArtifactsSubsection","Task artifacts"),children:[e.jsx("div",{className:"documents-task-artifacts-label",children:t("documents.taskArtifactsLabel","Artifacts")}),e.jsx("ul",{className:"markdown-file-list documents-task-artifact-list",children:I.map(f=>{const v=Ae(f),ae=us[v],Rt=Je(t,v),_e=$?.id===f.id;return e.jsx("li",{className:"markdown-file-list-item",children:e.jsxs("button",{className:`markdown-file-item documents-task-document-item documents-task-artifact-item${_e?" markdown-file-item--selected":""}`,onClick:()=>Ct(f.id),"aria-label":t("documents.openTaskArtifact","Open {{taskId}} artifact {{title}}",{taskId:s,title:f.title||t("documents.untitledArtifact","Untitled artifact")}),"aria-current":_e?"true":void 0,children:[e.jsxs("span",{className:"documents-task-artifact-title-row",children:[e.jsx(ae,{size:14,"aria-hidden":"true"}),e.jsx("span",{className:"markdown-file-item-name",children:f.title||t("documents.untitledArtifact","Untitled artifact")})]}),e.jsxs("span",{className:"markdown-file-item-path",children:[Rt," · ",f.mimeType||f.type]}),e.jsxs("span",{className:"markdown-file-item-meta",children:[f.authorId||t("documents.unknownAuthor","unknown")," · ",oe(f.updatedAt)]})]})},`artifact-${f.id}`)})})]}):null]})]},s)})}),(!y||he)&&e.jsxs("section",{className:"documents-view-main","aria-label":t("documents.taskDocumentPreviewLabel","Task document content preview"),children:[y&&he&&e.jsxs("button",{className:"btn btn-sm documents-mobile-back",onClick:yt,"aria-label":t("documents.backToTaskDocumentsList","Back to task documents list"),children:[e.jsx(Ge,{size:14}),t("documents.backToTaskDocuments","Back to documents")]}),he?$?e.jsx(js,{artifact:$,projectId:a,content:tt,loading:st,error:nt,renderMarkdown:at,onToggleMarkdown:()=>xe(s=>!s),onOpenTask:Oe,t}):r?e.jsxs("div",{className:"documents-content-viewer documents-task-document-viewer",children:[e.jsxs("div",{className:"documents-content-header documents-task-document-header",children:[e.jsxs("p",{className:"documents-file-path-header",children:[r.taskId," / ",r.key]}),e.jsx("div",{className:"documents-task-document-actions",children:Fe?e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm",onClick:Pt,disabled:de,children:t("documents.cancelEdit","Cancel")}),V&&e.jsx("button",{className:"btn btn-sm",onClick:At,disabled:de,children:t("documents.rebaseTaskDocument","Rebase draft")}),e.jsx("button",{className:"btn btn-sm btn-primary",onClick:()=>void Dt(),disabled:de||V!==null,children:de?t("documents.saving","Saving…"):t("documents.saveTaskDocument","Save")})]}):e.jsxs(e.Fragment,{children:[e.jsx("button",{className:"btn btn-sm document-mode-toggle",onClick:()=>Tt(r.id),"aria-label":X?t("documents.switchToPlainText","Switch to plain text"):t("documents.switchToMarkdown","Switch to markdown"),"aria-pressed":X,title:X?t("documents.switchToPlainText","Switch to plain text"):t("documents.switchToMarkdown","Switch to markdown"),children:X?t("documents.markdown","Markdown"):t("documents.plain","Plain")}),e.jsxs("button",{className:"btn btn-sm",onClick:Ft,"aria-label":t("documents.editTaskDocument","Edit task document"),children:[e.jsx(We,{size:14,"aria-hidden":"true"}),t("documents.edit","Edit")]})]})})]}),e.jsxs("div",{className:"document-card-meta documents-task-document-meta",children:[e.jsx("span",{className:"document-card-author",children:r.author}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{children:t("documents.revisionShort","v{{revision}}",{revision:r.revision})}),e.jsx("span",{className:"document-card-separator",children:"·"}),e.jsx("span",{className:"document-card-date",children:oe(r.updatedAt)})]}),Fe?e.jsx("div",{className:"documents-task-document-editor","aria-label":t("documents.taskDocumentContentEditor","Task document content editor"),children:e.jsx(Ke,{content:pe,onChange:D,filePath:r.key.includes(".")?r.key:`${r.key}.md`,forceToolbarActionsVisible:!0})}):X?e.jsx("div",{ref:ee,className:"documents-content-markdown",children:e.jsx("div",{className:"markdown-body",children:e.jsx(De,{remarkPlugins:[Ee],children:r.content})})}):e.jsx("pre",{ref:Le,className:"document-card-content-text documents-content-viewer-text",children:r.content}),Mt]}):null:e.jsx("div",{className:"documents-view-empty",children:e.jsx("p",{children:t("documents.selectTaskDocument","Select a task document or artifact to view its content.")})})]})]})})]})}export{Ss as DocumentsView,hs as getTaskColumnStatusDotClass};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{r as n,j as e}from"./vendor-react-SZ_qB27O.js";import{u as _e,f as Se,a as ke,s as Ke,i as Ue,t as Be,b as we,c as Ce,d as Ge,e as Qe,g as We,h as Ve}from"./SettingsModal-C_9RiEI7.js";import{a as ee,w as te,da as Ye,aY as Xe,V as Ze,db as Je,L as U,aL as Ee}from"./index-B_z7OKl4.js";import{u as De}from"./vendor-i18n-Duky4gdQ.js";import"./vendor-codemirror-CcrtqoCy.js";import"./vendor-reactflow-BlIeoTu4.js";import"./vendor-xterm-BNq00GSj.js";function pe(i){const s=Object.entries(i).flatMap(([m,t])=>Array.isArray(t)?t.filter(Boolean).map(c=>[m,c]):t===void 0||t===""?[]:[[m,String(t)]]);return s.length?`?${s.map(([m,t])=>`${encodeURIComponent(m)}=${encodeURIComponent(t)}`).join("&")}`:""}function et(i){return ee(te("/knowledge/graph/status",i))}function tt(i,s={}){return ee(te(`/knowledge/graph/nodes${pe(s)}`,i))}function st(i,s){return ee(te(`/knowledge/graph/node${pe({id:s})}`,i))}function Fe(i,s){return ee(te(`/knowledge/graph/neighbors${pe(s)}`,i))}function at(i,s){return ee(te(`/knowledge/graph/path${pe(s)}`,i))}function nt(i,s=!1){return ee(te("/knowledge/graph/build",i),{method:"POST",body:JSON.stringify({force:s})})}const J=".fusion/memory/MEMORY.md",rt=5e4,it="0 3 * * *",lt="0 4 * * *";function ge(i){return{memoryEnabled:i.memoryEnabled!==!1,memoryAutoSummarizeEnabled:i.memoryAutoSummarizeEnabled??!1,memoryAutoSummarizeThresholdChars:i.memoryAutoSummarizeThresholdChars??rt,memoryAutoSummarizeSchedule:i.memoryAutoSummarizeSchedule??it,memoryDreamsEnabled:i.memoryDreamsEnabled??!1,memoryDreamsSchedule:i.memoryDreamsSchedule??lt}}function Ae(i,s){return i.some(m=>m.path===s)?s:i.find(m=>m.path===J)?.path??i[0]?.path??J}function ot(i={}){const{projectId:s}=i,[m,t]=n.useState(null),[c,g]=n.useState(!0),[f,M]=n.useState(!1),[E,w]=n.useState(()=>ge({})),[j,k]=n.useState(!0),[o,a]=n.useState(!1),[d,F]=n.useState([]),[B,q]=n.useState(!0),[N,I]=n.useState(J),[D,R]=n.useState(""),[se,G]=n.useState(!1),[p,y]=n.useState(!1),[H,z]=n.useState(!1),[S,P]=n.useState(!1),[Y,$]=n.useState(!1),[x,Q]=n.useState(null),[h,u]=n.useState(!0),[b,W]=n.useState(!1),[ie,ae]=n.useState(!1),{status:ne,loading:be,refresh:_}=_e({projectId:s}),re=n.useCallback(l=>{R(l),y(!0)},[]),X=n.useCallback(async l=>{G(!0);try{const{content:v}=await Se(l,s);I(l),R(v),y(!1)}finally{G(!1)}},[s]),O=n.useCallback(async()=>{q(!0);try{const{files:l}=await ke(s);if(F(l),l.length===0){I(J),R(""),y(!1);return}const v=Ae(l,N);v!==N&&await X(v)}finally{q(!1)}},[s,N,X]);n.useEffect(()=>{let l=!1;async function v(){try{const A=await Ce(s);l||(t(A.content),M(A.exists),g(!1))}catch{l||(t(null),M(!1),g(!1))}}return v(),()=>{l=!0}},[s]),n.useEffect(()=>{let l=!1;async function v(){k(!0);try{const A=await Xe(s);l||w(ge(A))}catch{l||w(ge({}))}finally{l||k(!1)}}return v(),()=>{l=!0}},[s]);const le=n.useRef(N);n.useEffect(()=>{le.current=N},[N]),n.useEffect(()=>{let l=!1;async function v(){q(!0);try{const{files:A}=await ke(s);if(l)return;if(F(A),A.length===0){I(J),R(""),y(!1);return}const ue=Ae(A,le.current),{content:je}=await Se(ue,s);if(l)return;I(ue),R(je),y(!1)}catch{l||(F([]),I(J),R(""),y(!1))}finally{l||q(!1)}}return v(),()=>{l=!0}},[s]),n.useEffect(()=>{let l=!1;async function v(){try{const A=await we(s);l||(Q(A),u(!1))}catch{l||(Q(null),u(!1))}}return v(),()=>{l=!0}},[s]);const oe=n.useCallback(async l=>{a(!0);try{const v=await Ye(l,s);w(ge(v))}finally{a(!1)}},[s]),me=n.useCallback(async l=>{await X(l)},[X]),ce=n.useCallback(async()=>{if(p){z(!0);try{await Ke(N,D,s),y(!1),await O()}finally{z(!1)}}},[D,p,N,s,O]),de=n.useCallback(async()=>{ae(!0);try{const l=await Ue(s);return await _(),l}finally{ae(!1)}},[s,_]),he=n.useCallback(async l=>Be(l,s),[s]),Z=n.useCallback(async()=>{try{const l=await we(s);Q(l)}catch{Q(null)}},[s]),K=n.useCallback(async()=>{try{const l=await Ce(s);t(l.content),M(l.exists)}catch{t(null),M(!1)}},[s]),L=n.useCallback(async l=>{await Ge(l,s),await K()},[s,K]),xe=n.useCallback(async()=>{P(!0);try{const l=await Qe(s);return await Promise.all([K(),Z()]),{success:l.success,summary:l.summary}}finally{P(!1)}},[s,K,Z]),V=n.useCallback(async()=>{$(!0);try{return await We(s)}finally{$(!1)}},[s]),fe=n.useCallback(async l=>{W(!0);try{const v=await Ve(l,s),A=v.path??l;I(A),R(v.content),y(!1),await O()}finally{W(!1)}},[s,O]);return{insightsContent:m,insightsLoading:c,insightsExists:f,refreshInsights:K,saveInsights:L,memorySettings:E,settingsLoading:j,savingMemorySettings:o,saveMemorySettings:oe,memoryFiles:d,memoryFilesLoading:B,selectedFilePath:N,selectedFileContent:D,selectedFileLoading:se,selectedFileDirty:p,setSelectedFileContent:re,selectFile:me,saveSelectedFile:ce,savingSelectedFile:H,reloadMemoryFiles:O,backendStatus:ne,backendLoading:be,extractInsights:xe,extracting:S,triggerDreamNow:V,dreamRunning:Y,auditReport:x,auditLoading:h,refreshAudit:Z,compactMemory:fe,compacting:b,installQmdAction:de,installingQmd:ie,testRetrieval:he}}const Me={limit:50,offset:0};function mt({projectId:i,enabled:s}){const[m,t]=n.useState(null),[c,g]=n.useState(Me),[f,M]=n.useState(null),[E,w]=n.useState(null),[j,k]=n.useState(null),[o,a]=n.useState({direction:"both",depth:1}),[d,F]=n.useState(null),[B,q]=n.useState({fromId:"",toId:"",maxHops:6}),[N,I]=n.useState(null),[D,R]=n.useState(!1),[se,G]=n.useState(!1),[p,y]=n.useState(null),H=n.useRef(0),z=n.useRef(0),S=n.useRef(0),P=n.useCallback(async()=>{try{const h=await et(i);t(h),q(u=>({...u,maxHops:h.pathLimits.defaultMaxHops}))}catch(h){y(h instanceof Error?h.message:String(h))}},[i]);n.useEffect(()=>{P()},[s,P]),n.useEffect(()=>{if(!m?.available)return;const h=++H.current;R(!0);const u=window.setTimeout(()=>void tt(i,c).then(b=>{h===H.current&&M(b)}).catch(b=>{h===H.current&&y(b instanceof Error?b.message:String(b))}).finally(()=>{h===H.current&&R(!1)}),250);return()=>window.clearTimeout(u)},[s,c,i,m?.available]);const Y=n.useCallback(async(h=E)=>{if(!h)return;const u=++z.current;try{const b=await Fe(i,{nodeId:h,...o});u===z.current&&F(b)}catch(b){u===z.current&&y(b instanceof Error?b.message:String(b))}},[o,i,E]),$=n.useCallback(async h=>{const u=++z.current;w(h);try{const[b,W]=await Promise.all([st(i,h),Fe(i,{nodeId:h,...o})]);u===z.current&&(k(b),F(W))}catch(b){u===z.current&&y(b instanceof Error?b.message:String(b))}},[o,i]),x=n.useCallback(async()=>{const h=++S.current;I(null),y(null);try{const u=await at(i,B);h===S.current&&I(u)}catch(u){h===S.current&&y(u instanceof Error?u.message:String(u))}},[B,i]),Q=n.useCallback(async(h=!1)=>{G(!0);try{await nt(i,h),await P()}catch(u){y(u instanceof Error?u.message:String(u))}finally{G(!1)}},[i,P]);return{status:m,filters:c,setFilters:g,nodes:f,loading:D,selectedId:E,detail:j,selectNode:$,neighborOptions:o,setNeighborOptions:a,neighborResults:d,refreshNeighbors:Y,pathInput:B,setPathInput:q,pathResult:N,findPath:x,rebuild:Q,rebuilding:se,refreshStatus:P,error:p,clearFilters:()=>g(Me)}}const ct=["file","module","symbol","doc-concept","rationale"],dt=["function","class","interface","type-alias","enum","variable","namespace","alias"],ht=["contains","imports","re-exports","relates-to","rationale-supports"];function ve({id:i,onSelect:s}){return e.jsx("button",{type:"button",className:"btn btn-ghost knowledge-graph-endpoint",onClick:()=>s(i),children:i})}function Ie({title:i,edges:s,total:m,endpoint:t,onSelect:c}){return e.jsxs("section",{className:"knowledge-graph-edge-list",children:[e.jsxs("h4",{children:[i," ",e.jsxs("span",{children:["showing ",s.length," of ",m]})]}),s.length===0?e.jsx("p",{className:"knowledge-graph-muted",children:"None"}):e.jsx("ul",{children:s.map(g=>e.jsxs("li",{children:[e.jsx("span",{children:g.kind}),e.jsx("span",{className:`knowledge-graph-provenance knowledge-graph-provenance--${g.provenance}`,children:g.provenance}),e.jsx(ve,{id:g[t],onSelect:c})]},g.id))})]})}function ut({projectId:i,addToast:s}){const{t:m}=De("app"),t=mt({projectId:i,enabled:!0}),[c,g]=n.useState(!1);if(n.useEffect(()=>{t.error&&s(t.error,"error")},[s,t.error]),!t.status&&t.error)return e.jsx("div",{className:"knowledge-graph-panel knowledge-graph-error","data-testid":"knowledge-graph-error",children:t.error});if(!t.status)return e.jsx("div",{className:"knowledge-graph-panel","data-testid":"knowledge-graph-loading",children:m("memory.graphLoading","Loading knowledge graph…")});if(!t.status.available)return e.jsxs("div",{className:"knowledge-graph-panel knowledge-graph-empty","data-testid":"knowledge-graph-no-graph",children:[e.jsxs("p",{children:[m("memory.graphUnavailable","Graph unavailable"),": ",t.status.recoveryReason]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>void t.rebuild(!1),children:m("memory.graphBuild","Build graph")})]});const f=a=>t.setFilters({...t.filters,...a,offset:0}),M=a=>{const d=t.filters.kinds??[];f({kinds:d.includes(a)?d.filter(F=>F!==a):[...d,a]})},E=a=>{const d=t.neighborOptions.edgeKinds??[];t.setNeighborOptions({...t.neighborOptions,edgeKinds:d.includes(a)?d.filter(F=>F!==a):[...d,a]})},w=t.selectedId,j=t.status.pathLimits,k=t.pathResult?.outcome==="found"?t.pathResult.path:null,o=t.pathResult?.outcome==="found"?t.pathResult.hops:null;return e.jsxs("section",{className:"knowledge-graph-panel","data-testid":"knowledge-graph-panel",children:[e.jsxs("header",{className:"knowledge-graph-status card",children:[e.jsxs("div",{children:[e.jsxs("strong",{children:[t.status.nodeCount," ",m("memory.graphNodes","nodes")," · ",t.status.edgeCount," ",m("memory.graphEdges","edges")]}),e.jsx("span",{children:t.status.graphDir})]}),e.jsxs("dl",{children:[e.jsxs("div",{children:[e.jsx("dt",{children:"Node kinds"}),e.jsx("dd",{children:Object.entries(t.status.nodeKindCounts??{}).map(([a,d])=>`${a}: ${d}`).join(" · ")||"—"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Edge kinds"}),e.jsx("dd",{children:Object.entries(t.status.edgeKindCounts??{}).map(([a,d])=>`${a}: ${d}`).join(" · ")||"—"})]}),e.jsxs("div",{children:[e.jsx("dt",{children:"Provenance"}),e.jsx("dd",{children:Object.entries(t.status.provenanceCounts??{}).map(([a,d])=>`${a}: ${d}`).join(" · ")||"—"})]})]}),e.jsxs("label",{className:"knowledge-graph-toggle",children:[e.jsx("input",{type:"checkbox",checked:c,onChange:a=>g(a.target.checked)})," ",m("memory.graphForce","Force rebuild")]}),e.jsx("button",{type:"button",className:"btn",disabled:t.rebuilding,onClick:()=>void t.rebuild(c),children:t.rebuilding?m("memory.graphRebuilding","Rebuilding…"):m("memory.graphRebuild","Rebuild")})]}),e.jsxs("section",{className:"knowledge-graph-filters card","aria-label":m("memory.graphFilters","Graph filters"),children:[e.jsx("div",{className:"knowledge-graph-kind-options",children:ct.map(a=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:(t.filters.kinds??[]).includes(a),onChange:()=>M(a)})," ",a]},a))}),e.jsx("input",{className:"input","aria-label":"Path prefix",placeholder:"Path prefix",value:t.filters.pathPrefix??"",onChange:a=>f({pathPrefix:a.target.value})}),e.jsx("input",{className:"input","aria-label":"Node id prefix",placeholder:"Node id prefix",value:t.filters.idPrefix??"",onChange:a=>f({idPrefix:a.target.value})}),e.jsx("input",{className:"input","aria-label":"Name regex",placeholder:"Name regex",value:t.filters.namePattern??"",onChange:a=>f({namePattern:a.target.value})}),e.jsxs("select",{className:"select","aria-label":"FNXC area",value:t.filters.fnxcArea??"",onChange:a=>f({fnxcArea:a.target.value||void 0}),children:[e.jsx("option",{value:"",children:"All FNXC areas"}),t.status.fnxcAreas?.map(a=>e.jsx("option",{value:a,children:a},a))]}),e.jsxs("select",{className:"select","aria-label":"Symbol kind",value:t.filters.symbolKind??"",onChange:a=>f({symbolKind:a.target.value||void 0}),children:[e.jsx("option",{value:"",children:"All symbol kinds"}),dt.map(a=>e.jsx("option",{children:a},a))]}),e.jsxs("select",{className:"select","aria-label":"Owner",value:t.filters.owner??"",onChange:a=>f({owner:a.target.value||void 0}),children:[e.jsx("option",{value:"",children:"All owners"}),e.jsx("option",{value:"file",children:"file"}),e.jsx("option",{value:"derived",children:"derived"})]}),e.jsx("select",{className:"select","aria-label":"Result limit",value:t.filters.limit??50,onChange:a=>f({limit:Number(a.target.value)}),children:[25,50,100,200].map(a=>e.jsxs("option",{value:a,children:[a," results"]},a))}),e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:t.clearFilters,children:m("memory.graphClearFilters","Clear filters")})]}),e.jsxs("div",{className:"knowledge-graph-layout",children:[e.jsxs("section",{className:"card knowledge-graph-results",children:[e.jsxs("h3",{children:[t.nodes?.total??0," ",m("memory.graphResults","results")]}),t.loading?e.jsx("p",{"data-testid":"knowledge-graph-searching",children:"Searching…"}):t.nodes?.nodes.length?e.jsxs(e.Fragment,{children:[e.jsx("ul",{children:t.nodes.nodes.map(a=>e.jsx("li",{children:e.jsxs("button",{type:"button",className:"btn btn-ghost",onClick:()=>void t.selectNode(a.id),children:[e.jsxs("strong",{children:[a.kind,": ",a.name]}),e.jsxs("span",{children:[a.id," · ",a.ownerPath,":",a.source.line]})]})},a.id))}),e.jsxs("div",{className:"knowledge-graph-pagination",children:[e.jsx("button",{type:"button",className:"btn btn-ghost",disabled:!t.filters.offset,onClick:()=>f({offset:Math.max(0,(t.filters.offset??0)-(t.filters.limit??50))}),children:"Previous"}),e.jsx("button",{type:"button",className:"btn btn-ghost",disabled:(t.filters.offset??0)+(t.filters.limit??50)>=(t.nodes?.total??0),onClick:()=>f({offset:(t.filters.offset??0)+(t.filters.limit??50)}),children:"Next"})]})]}):e.jsx("p",{"data-testid":"knowledge-graph-no-results",children:m("memory.graphNoResults","No matching nodes.")})]}),e.jsx("section",{className:"card knowledge-graph-detail",children:t.detail?e.jsxs(e.Fragment,{children:[e.jsx("h3",{children:t.detail.node.name}),e.jsx("p",{children:t.detail.node.id}),e.jsxs("p",{children:[t.detail.node.ownerPath,":",t.detail.node.source.line]}),e.jsx(Ie,{title:"Outgoing",edges:t.detail.outgoing,total:t.detail.outgoingTotal,endpoint:"to",onSelect:a=>void t.selectNode(a)}),e.jsx(Ie,{title:"Incoming",edges:t.detail.incoming,total:t.detail.incomingTotal,endpoint:"from",onSelect:a=>void t.selectNode(a)})]}):e.jsx("p",{className:"knowledge-graph-muted",children:"Select a node to inspect its edges."})})]}),t.detail&&e.jsxs("section",{className:"knowledge-graph-neighbors card",children:[e.jsx("h3",{children:"Neighbors"}),e.jsxs("select",{className:"select","aria-label":"Neighbor direction",value:t.neighborOptions.direction,onChange:a=>t.setNeighborOptions({...t.neighborOptions,direction:a.target.value}),children:[e.jsx("option",{value:"out",children:"Outgoing"}),e.jsx("option",{value:"in",children:"Incoming"}),e.jsx("option",{value:"both",children:"Both directions"})]}),e.jsx("select",{className:"select","aria-label":"Neighbor depth",value:t.neighborOptions.depth,onChange:a=>t.setNeighborOptions({...t.neighborOptions,depth:Number(a.target.value)}),children:[1,2,3].map(a=>e.jsxs("option",{value:a,children:["Depth ",a]},a))}),e.jsx("div",{className:"knowledge-graph-kind-options",children:ht.map(a=>e.jsxs("label",{children:[e.jsx("input",{type:"checkbox",checked:(t.neighborOptions.edgeKinds??[]).includes(a),onChange:()=>E(a)})," ",a]},a))}),e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:()=>void t.refreshNeighbors(),children:"Refresh neighbors"}),t.neighborResults?.neighbors.length?e.jsx("ul",{children:t.neighborResults.neighbors.map(a=>e.jsxs("li",{children:[e.jsxs("span",{children:["distance ",a.distance]}),e.jsx(ve,{id:a.node.id,onSelect:d=>void t.selectNode(d)})]},a.node.id))}):e.jsx("p",{className:"knowledge-graph-muted",children:"No neighbors found."})]}),e.jsxs("section",{className:"knowledge-graph-path card",children:[e.jsx("h3",{children:"Shortest path"}),e.jsx("input",{className:"input","aria-label":"From node id",placeholder:"From node id",value:t.pathInput.fromId,onChange:a=>t.setPathInput({...t.pathInput,fromId:a.target.value})}),e.jsx("input",{className:"input","aria-label":"To node id",placeholder:"To node id",value:t.pathInput.toId,onChange:a=>t.setPathInput({...t.pathInput,toId:a.target.value})}),e.jsx("input",{className:"input","aria-label":"Maximum hops",type:"number",min:"1",max:j.maxHops,value:t.pathInput.maxHops,onChange:a=>t.setPathInput({...t.pathInput,maxHops:Number(a.target.value)})}),w&&e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:()=>t.setPathInput({...t.pathInput,fromId:w}),children:"Use selected as from"}),e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:()=>t.setPathInput({...t.pathInput,toId:w}),children:"Use selected as to"})]}),e.jsx("button",{type:"button",className:"btn",onClick:()=>void t.findPath(),children:"Find path"}),k&&e.jsxs("div",{"data-testid":"knowledge-graph-path-found",children:[e.jsxs("strong",{children:[o," hops"]}),e.jsx("div",{className:"knowledge-graph-path-chain",children:k.nodes.map((a,d)=>e.jsxs("span",{children:[e.jsx(ve,{id:a.id,onSelect:F=>void t.selectNode(F)}),d<k.edges.length&&e.jsx("em",{children:k.edges[d].kind})]},a.id))})]}),t.pathResult?.outcome==="not-found"&&e.jsx("p",{"data-testid":"knowledge-graph-path-not-found",children:"No path exists between these nodes."}),t.pathResult?.outcome==="limit-reached"&&e.jsxs("div",{"data-testid":"knowledge-graph-path-limit-reached",children:[e.jsxs("p",{children:["No path found within ",t.pathResult.maxHops," hops; ",t.pathResult.limit," was reached."]}),t.pathInput.maxHops<j.maxHops&&e.jsx("button",{type:"button",className:"btn btn-ghost",onClick:()=>t.setPathInput({...t.pathInput,maxHops:Math.min(j.maxHops,t.pathInput.maxHops+1)}),children:"Raise hop limit"})]}),t.error&&e.jsx("p",{"data-testid":"knowledge-graph-path-error",className:"knowledge-graph-error",children:t.error})]})]})}const yt={Patterns:"pattern",Principles:"principle",Conventions:"convention",Pitfalls:"pitfall",Context:"context"},gt=72;function pt(i,s){if(i.length<=s)return i;const m=Math.max(1,s-1),t=Math.ceil(m/2),c=Math.floor(m/2);return`${i.slice(0,t)}…${i.slice(i.length-c)}`}function bt(i){const s=`${i.label} — ${i.path}`;return pt(s,gt)}function xt(i){if(!i)return[];const s=[],m=i.split(/(?=^## )/m);for(const t of m){const c=t.trim();if(!c)continue;const g=c.match(/^##\s+(.+?)(\n|$)/);if(g){const f=g[1].trim(),M=yt[f]??f.toLowerCase(),E=c.slice(g[0].length).replace(/<!--[\s\S]*?-->/g,"").trim(),w=E.split(`
|
|
2
|
-
`).reduce((j,k)=>{const o=k.trim();return/^[-*]\s+/.test(k)?j.push(o.replace(/^[-*]\s+/,"")):o.length>0&&j.length>0&&(j[j.length-1]=`${j[j.length-1]}
|
|
3
|
-
${k.trimEnd()}`),j},[]);(w.length>0||E.length>0)&&s.push({name:f,key:M,items:w.length>0?w:E.length>0?[E]:[],expanded:!0})}}return s}function ft(i){if(!i)return null;const s=i.match(/##\s+Last\s+Updated:\s*(\d{4}-\d{2}-\d{2})/i);return s?s[1]:null}function jt(i){return i.reduce((s,m)=>s+m.items.length,0)}function Ft({projectId:i,addToast:s,onSendSelectionToTask:m}){const{t}=De("app"),[c,g]=n.useState("working"),[f,M]=n.useState(new Set),[E,w]=n.useState(!1),[j,k]=n.useState(null),[o,a]=n.useState({memoryEnabled:!0,memoryAutoSummarizeEnabled:!1,memoryAutoSummarizeThresholdChars:5e4,memoryAutoSummarizeSchedule:"0 3 * * *",memoryDreamsEnabled:!1,memoryDreamsSchedule:"0 4 * * *"}),[d,F]=n.useState(""),[B,q]=n.useState(!1),[N,I]=n.useState(null),{insightsContent:D,insightsLoading:R,insightsExists:se,saveInsights:G,memorySettings:p,settingsLoading:y,saveMemorySettings:H,savingMemorySettings:z,backendStatus:S,backendLoading:P,extractInsights:Y,extracting:$,auditReport:x,auditLoading:Q,refreshAudit:h,compactMemory:u,compacting:b,installQmdAction:W,installingQmd:ie,testRetrieval:ae,memoryFiles:ne,memoryFilesLoading:be,selectedFilePath:_,selectedFileContent:re,selectedFileLoading:X,selectedFileDirty:O,setSelectedFileContent:le,selectFile:oe,saveSelectedFile:me,savingSelectedFile:ce,reloadMemoryFiles:de,triggerDreamNow:he,dreamRunning:Z}=ot({projectId:i});n.useEffect(()=>{a(p)},[p]);const K=n.useMemo(()=>o.memoryEnabled!==p.memoryEnabled||o.memoryAutoSummarizeEnabled!==p.memoryAutoSummarizeEnabled||o.memoryAutoSummarizeThresholdChars!==p.memoryAutoSummarizeThresholdChars||o.memoryAutoSummarizeSchedule!==p.memoryAutoSummarizeSchedule||o.memoryDreamsEnabled!==p.memoryDreamsEnabled||o.memoryDreamsSchedule!==p.memoryDreamsSchedule,[o,p]),L=n.useMemo(()=>ne.find(r=>r.path===_),[ne,_]),xe=L?L.layer==="long-term"?t("memory.layerDescLongTerm","Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams."):L.layer==="daily"?t("memory.layerDescDaily","Raw daily observations, open loops, and running context for dream processing."):t("memory.layerDescDreams","Synthesized patterns and open loops promoted from daily memory."):t("memory.editorDefaultDescription","Edits the selected memory file."),V=n.useMemo(()=>xt(D),[D]),fe=n.useMemo(()=>jt(V),[V]),l=n.useMemo(()=>ft(D),[D]),v=n.useCallback(r=>{M(C=>{const T=new Set(C);return T.has(r)?T.delete(r):T.add(r),T})},[]),A=n.useCallback(async r=>{try{await oe(r)}catch{s(t("memory.loadFileFailed","Failed to load memory file"),"error")}},[oe,s]),ue=n.useCallback(async()=>{try{await me(),s(t("memory.memorySaved","Memory saved"),"success")}catch{s(t("memory.saveMemoryFailed","Failed to save memory"),"error")}},[me,s]),je=n.useCallback(async()=>{if(!K)return;const r={};o.memoryEnabled!==p.memoryEnabled&&(r.memoryEnabled=o.memoryEnabled),o.memoryAutoSummarizeEnabled!==p.memoryAutoSummarizeEnabled&&(r.memoryAutoSummarizeEnabled=o.memoryAutoSummarizeEnabled),o.memoryAutoSummarizeThresholdChars!==p.memoryAutoSummarizeThresholdChars&&(r.memoryAutoSummarizeThresholdChars=o.memoryAutoSummarizeThresholdChars),o.memoryAutoSummarizeSchedule!==p.memoryAutoSummarizeSchedule&&(r.memoryAutoSummarizeSchedule=o.memoryAutoSummarizeSchedule),o.memoryDreamsEnabled!==p.memoryDreamsEnabled&&(r.memoryDreamsEnabled=o.memoryDreamsEnabled),o.memoryDreamsSchedule!==p.memoryDreamsSchedule&&(r.memoryDreamsSchedule=o.memoryDreamsSchedule);try{await H(r),s(t("memory.settingsSaved","Memory settings saved"),"success")}catch{s(t("memory.saveSettingsFailed","Failed to save memory settings"),"error")}},[K,o,p,H,s]),Re=n.useCallback(async()=>{try{const r=await W();s(r.qmdAvailable?t("memory.qmdInstallSuccess","qmd installed successfully"):t("memory.qmdInstallUnavailable","qmd install finished, but qmd is still unavailable"),r.qmdAvailable?"success":"info")}catch{s(t("memory.installQmdFailed","Failed to install qmd"),"error")}},[W,s]),ze=n.useCallback(async()=>{q(!0),I(null);try{const r=await ae(d);I(r),s(r.qmdAvailable?t("memory.retrievalTestComplete","Memory retrieval test complete"):t("memory.retrievalTestFallback","qmd is not installed; local fallback was used"),r.qmdAvailable?"success":"info")}catch{s(t("memory.retrievalTestFailed","Failed to test memory retrieval"),"error")}finally{q(!1)}},[d,ae,s]),Le=n.useCallback(async()=>{try{await he(),s(t("memory.dreamProcessingComplete","Dream processing completed"),"success"),await de()}catch(r){s(r instanceof Error?r.message:t("memory.dreamProcessingFailed","Failed to run dream processing"),"error")}},[he,de,s]),Pe=n.useCallback(async()=>{try{await u(_),s(t("memory.fileCompacted","Memory file compacted"),"success")}catch{s(t("memory.compactFailed","Failed to compact memory"),"error")}},[u,_,s]),Ne=n.useCallback(async()=>{try{const r=await Y();s(r.summary,"success")}catch(r){s(r instanceof Error?r.message:t("memory.extractInsightsFailed","Failed to extract insights"),"error")}},[Y,s]),qe=n.useCallback(async()=>{if(j!==null)try{await G(j),w(!1),k(null),s(t("memory.insightsSaved","Insights saved"),"success")}catch{s(t("memory.saveInsightsFailed","Failed to save insights"),"error")}},[j,G,s]),Oe=n.useCallback(()=>{k(D??""),w(!0)},[D]),Te=n.useCallback(()=>{w(!1),k(null)},[]),He=!P&&S!==null,ye=S?.capabilities?.writable??!1;return e.jsxs("div",{className:"memory-view",children:[e.jsx(Ze,{icon:Je,title:t("memory.title","Memory")}),e.jsxs("div",{className:"memory-view-tabs",role:"tablist",children:[e.jsx("button",{type:"button",role:"tab","aria-selected":c==="working",className:`memory-view-tab${c==="working"?" memory-view-tab--active":""}`,onClick:()=>g("working"),"data-testid":"memory-tab-working",children:t("memory.tabWorking","Working Memory")}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="insights",className:`memory-view-tab${c==="insights"?" memory-view-tab--active":""}`,onClick:()=>g("insights"),"data-testid":"memory-tab-insights",children:t("memory.tabInsights","Insights")}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="graph",className:`memory-view-tab${c==="graph"?" memory-view-tab--active":""}`,onClick:()=>g("graph"),"data-testid":"memory-tab-graph",children:t("memory.tabGraph","Knowledge Graph")}),e.jsx("button",{type:"button",role:"tab","aria-selected":c==="engines",className:`memory-view-tab${c==="engines"?" memory-view-tab--active":""}`,onClick:()=>g("engines"),"data-testid":"memory-tab-engines",children:t("memory.tabEngines","Engines")})]}),e.jsxs("div",{className:"memory-view-content",children:[c==="graph"&&e.jsx(ut,{projectId:i,addToast:s}),c==="working"&&e.jsxs("div",{className:"memory-working-tab",children:[He&&!ye&&e.jsx("div",{className:"memory-readonly-banner",children:t("memory.readOnlyBanner","This memory backend is read-only. Changes cannot be saved.")}),be||X?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(U,{size:20,className:"animate-spin"}),e.jsx("span",{children:t("memory.loadingFile","Loading memory file…")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-editor-section",children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryViewFilePath",children:t("memory.fileLabel","Memory File")}),e.jsx("select",{id:"memoryViewFilePath",className:"select",value:_,onChange:r=>{A(r.target.value)},disabled:O,children:ne.map(r=>e.jsx("option",{value:r.path,title:`${r.label} — ${r.path}`,children:bt(r)},r.path))}),e.jsx("small",{children:O?t("memory.fileSwitchDirtyHint","Save or discard the current edits before switching files."):t("memory.fileSwitchHint","Choose any project memory file to view or edit.")})]}),L&&e.jsxs("div",{className:"memory-file-summary",children:[e.jsx("span",{children:L.layer==="long-term"?t("memory.layerLongTerm","Long-term"):L.layer==="daily"?t("memory.layerDaily","Daily"):t("memory.layerDreams","Dreams")}),e.jsx("strong",{children:L.path}),e.jsx("small",{children:t("memory.fileSummary","{{size}} bytes · updated {{updatedAt}}",{size:L.size.toLocaleString(),updatedAt:new Date(L.updatedAt).toLocaleString()})})]}),e.jsxs("div",{className:"form-group memory-editor-form-group",children:[e.jsx("label",{children:L?.label||t("memory.editorLabel","Memory Editor")}),e.jsx("small",{children:xe}),e.jsx("div",{className:"memory-editor-container",children:e.jsx(Ee,{content:re,onChange:le,readOnly:!ye,filePath:_,forceToolbarActionsVisible:!0,onSendSelectionToTask:m})})]})]}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsx("span",{className:"memory-char-count",children:t("memory.charCount","{{count}} characters",{count:re.length})}),e.jsx("div",{className:"memory-flex-spacer"}),ye&&re.length>0&&e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Pe,disabled:b||O,children:b?e.jsxs(e.Fragment,{children:[e.jsx(U,{size:14,className:"animate-spin"}),t("memory.compacting","Compacting…")]}):t("memory.compactSelectedFile","Compact Selected File")}),O&&ye&&e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:ue,disabled:ce,children:ce?e.jsxs(e.Fragment,{children:[e.jsx(U,{size:14,className:"animate-spin"}),t("memory.saving","Saving…")]}):t("memory.save","Save")})]}),e.jsxs("div",{className:"memory-config-section",children:[e.jsxs("div",{className:"memory-settings-group",children:[e.jsxs("div",{className:"form-group memory-toggle-row",children:[e.jsxs("label",{htmlFor:"memoryDreamsEnabled",className:"checkbox-label",title:t("memory.dreamsEnabledTooltip","Daily notes are distilled into DREAMS.md and reusable lessons are promoted into MEMORY.md."),children:[e.jsx("input",{id:"memoryDreamsEnabled",type:"checkbox",checked:o.memoryDreamsEnabled,onChange:r=>{a(C=>({...C,memoryDreamsEnabled:r.target.checked}))},disabled:!o.memoryEnabled||y}),t("memory.dreamsEnabledLabel","Process dreams from daily memory")]}),e.jsx("small",{children:t("memory.dreamsEnabledHint","Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md.")})]}),o.memoryEnabled&&o.memoryDreamsEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryDreamsSchedule",children:t("memory.dreamsScheduleLabel","Dream Schedule")}),e.jsx("input",{id:"memoryDreamsSchedule",type:"text",className:"input",value:o.memoryDreamsSchedule,onChange:r=>{a(C=>({...C,memoryDreamsSchedule:r.target.value}))},placeholder:"0 4 * * *",disabled:y}),e.jsx("small",{children:t("memory.dreamsScheduleHint","Cron expression for dream processing.")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("button",{type:"button",className:"btn btn-sm",onClick:Le,disabled:Z||!o.memoryDreamsEnabled,children:Z?e.jsxs(e.Fragment,{children:[e.jsx(U,{size:14,className:"animate-spin"}),t("memory.dreaming","Dreaming…")]}):t("memory.dreamNow","Dream Now")}),e.jsx("small",{children:t("memory.dreamNowHint","Manually trigger dream processing now.")})]})]})]}),e.jsxs("div",{className:"memory-settings-group",children:[e.jsxs("div",{className:"form-group memory-toggle-row",children:[e.jsxs("label",{htmlFor:"memoryAutoSummarizeEnabled",className:"checkbox-label",children:[e.jsx("input",{id:"memoryAutoSummarizeEnabled",type:"checkbox",checked:o.memoryAutoSummarizeEnabled,onChange:r=>{a(C=>({...C,memoryAutoSummarizeEnabled:r.target.checked}))},disabled:!o.memoryEnabled||y}),t("memory.autoSummarizeLabel","Auto-summarize memory")]}),e.jsx("small",{children:t("memory.autoSummarizeHint","Automatically compacts memory when it exceeds the threshold on a schedule.")})]}),o.memoryEnabled&&o.memoryAutoSummarizeEnabled&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeThresholdChars",children:t("memory.compactionThresholdLabel","Compaction Threshold (chars)")}),e.jsx("input",{id:"memoryAutoSummarizeThresholdChars",type:"number",className:"input",value:o.memoryAutoSummarizeThresholdChars,onChange:r=>{a(C=>({...C,memoryAutoSummarizeThresholdChars:parseInt(r.target.value,10)||5e4}))},min:1e3,disabled:y}),e.jsx("small",{children:t("memory.compactionThresholdHint","Memory will be compacted when it exceeds this character count")})]}),e.jsxs("div",{className:"form-group",children:[e.jsx("label",{htmlFor:"memoryAutoSummarizeSchedule",children:t("memory.autoSummarizeScheduleLabel","Schedule (cron)")}),e.jsx("input",{id:"memoryAutoSummarizeSchedule",type:"text",className:"input",value:o.memoryAutoSummarizeSchedule,onChange:r=>{a(C=>({...C,memoryAutoSummarizeSchedule:r.target.value}))},placeholder:"0 3 * * *",disabled:y}),e.jsx("small",{children:t("memory.autoSummarizeScheduleHint","Cron expression for auto-summarize schedule (default: daily at 3 AM)")})]})]})]}),!o.memoryEnabled&&e.jsx("div",{className:"settings-empty-state memory-status-message",children:t("memory.disabledMessage","Memory is currently disabled. Enable memory tools in Settings to edit these automations.")}),K&&e.jsx("div",{className:"memory-action-bar",children:e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:je,disabled:z||y,children:z?e.jsxs(e.Fragment,{children:[e.jsx(U,{size:14,className:"animate-spin"}),t("memory.saving","Saving…")]}):t("memory.saveSettings","Save Settings")})})]})]})]}),c==="insights"&&e.jsx("div",{className:"memory-insights-tab",children:R?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(U,{size:20,className:"animate-spin"}),e.jsx("span",{children:t("memory.loadingInsights","Loading insights…")})]}):E?e.jsxs("div",{className:"memory-insights-editor-layout",children:[e.jsx("div",{className:"memory-editor-container",children:e.jsx(Ee,{content:j??"",onChange:k,readOnly:!1,filePath:".fusion/memory/memory-insights.md",forceToolbarActionsVisible:!0,onSendSelectionToTask:m})}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Te,children:t("memory.cancel","Cancel")}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:qe,children:t("memory.saveInsights","Save Insights")})]})]}):!se||V.length===0?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx("p",{children:t("memory.noInsights","No insights extracted yet.")}),e.jsx("p",{children:t("memory.noInsightsHint",'Insights are automatically extracted from working memory. Click "Extract Now" to trigger extraction manually.')}),e.jsx("button",{type:"button",className:"btn btn-primary btn-sm memory-empty-extract-button",onClick:Ne,disabled:$,children:$?e.jsxs(e.Fragment,{children:[e.jsx(U,{size:14,className:"animate-spin"}),t("memory.extracting","Extracting…")]}):t("memory.extractNow","Extract Now")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-stats-row",children:[e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value",children:fe}),e.jsx("div",{className:"memory-stat-label",children:t("memory.totalInsights","Total Insights")})]}),e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value",children:V.length}),e.jsx("div",{className:"memory-stat-label",children:t("memory.categories","Categories")})]}),l&&e.jsxs("div",{className:"memory-stat-card",children:[e.jsx("div",{className:"memory-stat-value memory-stat-value--updated",children:l}),e.jsx("div",{className:"memory-stat-label",children:t("memory.lastUpdated","Last Updated")})]})]}),e.jsxs("div",{className:"memory-action-bar",children:[e.jsx("button",{type:"button",className:"btn btn-primary btn-sm",onClick:Ne,disabled:$,children:$?e.jsxs(e.Fragment,{children:[e.jsx(U,{size:14,className:"animate-spin"}),t("memory.extracting","Extracting…")]}):t("memory.extractNow","Extract Now")}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Oe,children:t("memory.editRaw","Edit Raw")})]}),e.jsx("div",{className:"memory-categories-list",children:V.map(r=>{const C=!f.has(r.key);return e.jsxs("div",{className:"memory-category-section",children:[e.jsxs("div",{className:"memory-category-header",onClick:()=>v(r.key),role:"button",tabIndex:0,onKeyDown:T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),v(r.key))},children:[e.jsx("h4",{children:r.name}),e.jsx("span",{className:"memory-category-count",children:r.items.length})]}),C&&e.jsx("div",{className:"memory-category-items",children:r.items.map((T,$e)=>e.jsx("div",{className:"memory-insight-item",children:T.replace(/^-\s+/,"").replace(/^\*\s+/,"")},$e))})]},r.key)})})]})}),c==="engines"&&e.jsx("div",{className:"memory-engines-tab",children:P||Q?e.jsxs("div",{className:"memory-empty-state",children:[e.jsx(U,{size:20,className:"animate-spin"}),e.jsx("span",{children:t("memory.loadingEngineStatus","Loading engine status…")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"memory-engine-card memory-qmd-card",children:[e.jsx("h3",{children:t("memory.qmdIntegrationTitle","QMD Integration")}),S?.qmdAvailable===!0?e.jsxs("div",{className:"memory-engine-status",children:[e.jsx("span",{className:"memory-health-badge memory-health-badge--healthy",children:t("memory.qmdInstalled","Installed")}),e.jsx("span",{className:"memory-char-count",children:t("memory.qmdAvailableOnPath","qmd is available on PATH.")})]}):S?.qmdAvailable===!1?e.jsxs("div",{className:"settings-empty-state memory-status-message",children:[e.jsxs("span",{children:[t("memory.qmdNotInstalled","qmd is not installed. Search will use local files. Install indexed retrieval:")," ",e.jsx("code",{children:S.qmdInstallCommand||"bun install -g @tobilu/qmd"})]}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:Re,disabled:ie,children:ie?t("memory.installing","Installing…"):t("memory.installQmd","Install qmd")})]}):e.jsxs("div",{className:"memory-engine-status",children:[e.jsx("span",{className:"memory-health-badge",children:t("memory.qmdChecking","Checking")}),e.jsx("span",{className:"memory-char-count",children:t("memory.qmdCheckingAvailability","Checking qmd availability…")})]})]}),e.jsxs("div",{className:"memory-engine-card memory-retrieval-card",children:[e.jsx("h3",{children:t("memory.testMemorySearchTitle","Test Memory Search")}),e.jsxs("div",{className:"memory-retrieval-input-row",children:[e.jsx("input",{type:"text",className:"input",value:d,onChange:r=>F(r.target.value),placeholder:t("memory.searchPlaceholder","Search memory with qmd")}),e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:ze,disabled:B,children:B?t("memory.testing","Testing…"):t("memory.testRetrieval","Test Retrieval")})]}),e.jsx("small",{className:"settings-muted",children:t("memory.testSearchHint","Runs the same qmd-backed memory_search path agents use.")}),N&&e.jsxs("div",{className:"memory-test-result",children:[e.jsx("strong",{children:t("memory.testResultCount",'{{count}} result for "{{query}}"',{count:N.results.length,query:N.query,defaultValue_one:'{{count}} result for "{{query}}"',defaultValue_other:'{{count}} results for "{{query}}"'})}),e.jsx("small",{children:t("memory.testResultStatus","qmd {{qmdStatus}} · {{fallbackStatus}}",{qmdStatus:N.qmdAvailable?t("memory.qmdStatusAvailable","available"):t("memory.qmdStatusMissing","missing"),fallbackStatus:N.usedFallback?t("memory.localFallbackUsed","local fallback used"):t("memory.qmdPathUsed","qmd path used")})}),N.results.length>0?e.jsx("ul",{children:N.results.map((r,C)=>e.jsxs("li",{children:[e.jsxs("span",{children:[r.path,":",r.lineStart]}),e.jsx("p",{children:r.snippet})]},`${r.path}-${r.lineStart}-${C}`))}):e.jsx("small",{children:t("memory.noMatchingMemory","No matching memory found.")})]})]}),e.jsxs("div",{className:"memory-engine-card",children:[e.jsx("h3",{children:t("memory.currentBackendTitle","Current Backend")}),e.jsx("div",{className:"memory-engine-status",children:e.jsx("span",{className:"memory-emphasis-text",children:S?.currentBackend==="file"?t("memory.backendFile","File (.fusion/memory/, agent/<agent-name>/memory/)"):S?.currentBackend==="readonly"?t("memory.backendReadonly","Read-Only"):S?.currentBackend==="qmd"?t("memory.backendQmd","QMD (Quantized Memory Distillation)"):S?.currentBackend??"unknown"})}),e.jsxs("div",{className:"memory-capability-row",children:[S?.capabilities?.readable&&e.jsx("span",{className:"memory-capability-badge",children:t("memory.capReadable","Readable")}),S?.capabilities?.writable&&e.jsx("span",{className:"memory-capability-badge",children:t("memory.capWritable","Writable")}),S?.capabilities?.supportsAtomicWrite&&e.jsx("span",{className:"memory-capability-badge",children:t("memory.capAtomicWrites","Atomic Writes")}),S?.capabilities?.persistent&&e.jsx("span",{className:"memory-capability-badge",children:t("memory.capPersistent","Persistent")})]})]}),x&&e.jsxs("div",{className:"memory-engine-card",children:[e.jsxs("div",{className:"memory-health-header",children:[e.jsx("h3",{children:t("memory.healthStatusTitle","Health Status")}),e.jsx("span",{className:`memory-health-badge memory-health-badge--${x.health}`,children:x.health==="healthy"?t("memory.healthHealthy","Healthy"):x.health==="warning"?t("memory.healthWarning","Warning"):t("memory.healthIssues","Issues Found")})]}),e.jsxs("div",{className:"memory-health-grid",children:[e.jsxs("div",{children:[e.jsx("div",{className:"memory-health-label",children:t("memory.workingMemoryLabel","Working Memory")}),e.jsx("div",{className:"memory-emphasis-text",children:t("memory.sizeChars","{{size}} chars",{size:x.workingMemory.size})}),e.jsx("div",{className:"memory-health-detail",children:t("memory.sectionCount","{{count}} sections",{count:x.workingMemory.sectionCount})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"memory-health-label",children:t("memory.insightsMemoryLabel","Insights Memory")}),e.jsx("div",{className:"memory-emphasis-text",children:t("memory.sizeChars","{{size}} chars",{size:x.insightsMemory.size})}),e.jsx("div",{className:"memory-health-detail",children:t("memory.insightCount","{{count}} insights",{count:x.insightsMemory.insightCount})})]})]}),e.jsxs("div",{className:"memory-health-section",children:[e.jsx("div",{className:"memory-health-label",children:t("memory.lastExtractionLabel","Last Extraction")}),e.jsx("div",{className:"memory-emphasis-text",children:x.extraction.success?e.jsx("span",{className:"memory-status-text memory-status-text--success",children:t("memory.extractionSuccess","Success")}):e.jsx("span",{className:"memory-status-text memory-status-text--error",children:t("memory.extractionFailed","Failed")})}),e.jsx("div",{className:"memory-health-detail",children:x.extraction.summary||t("memory.insightsExtracted","{{count}} insights extracted",{count:x.extraction.insightCount})})]}),e.jsxs("div",{className:"memory-health-section",children:[e.jsx("div",{className:"memory-health-label",children:t("memory.pruningLabel","Pruning")}),e.jsx("div",{className:"memory-emphasis-text",children:x.pruning.applied?e.jsx("span",{className:"memory-status-text memory-status-text--warning",children:t("memory.pruningApplied","Applied")}):e.jsx("span",{className:"memory-status-text memory-status-text--muted",children:t("memory.pruningNotNeeded","Not needed")})}),x.pruning.applied&&e.jsx("div",{className:"memory-health-detail",children:x.pruning.reason})]})]}),x&&x.checks.length>0&&e.jsxs("div",{className:"memory-engine-card",children:[e.jsx("h3",{children:t("memory.auditChecksTitle","Audit Checks")}),e.jsx("div",{children:x.checks.map(r=>e.jsxs("div",{className:"memory-audit-check",children:[e.jsx("span",{className:r.passed?"memory-audit-check-passed":"memory-audit-check-failed",children:r.passed?"✓":"✗"}),e.jsxs("div",{className:"memory-audit-check-content",children:[e.jsx("div",{className:"memory-emphasis-text",children:r.name}),e.jsx("div",{className:"memory-health-detail",children:r.details})]})]},r.id))})]}),e.jsx("div",{className:"memory-action-bar",children:e.jsx("button",{type:"button",className:"btn btn-secondary btn-sm",onClick:()=>h(),children:t("memory.runAudit","Run Audit")})}),e.jsxs("div",{className:"memory-settings-note",children:[e.jsx("span",{children:t("memory.settingsNote","Note: Change backend type in")}),e.jsx("button",{type:"button",className:"memory-settings-note-button",onClick:()=>{s(t("memory.settingsNoteToast","Open Settings → Memory to change backend type"),"info")},children:t("memory.settingsNoteLink","Settings → Memory")})]})]})})]})]})}export{Ft as MemoryView};
|