@markus-global/cli 0.12.1-rc.0 → 0.12.2
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/markus.mjs +160 -46
- package/dist/web-ui/assets/{AsyncState-BE4ycfHk.js → AsyncState-C4a4KQ04.js} +1 -1
- package/dist/web-ui/assets/{CommentInput-DQIh2AYB.js → CommentInput-jN8Pjpy4.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-C0L1YkNl.js → ContentRenderer-CkTLvnEu.js} +2 -2
- package/dist/web-ui/assets/{DeliverableShareModal-KlLlP9Fe.js → DeliverableShareModal-BjrQLmcX.js} +1 -1
- package/dist/web-ui/assets/{Deliverables-CiqT2Ipg.js → Deliverables-Cipn4z3F.js} +1 -1
- package/dist/web-ui/assets/{Notifications-82rU7lAf.js → Notifications-DBYrWqIL.js} +1 -1
- package/dist/web-ui/assets/{Search-CNNN3duL.js → Search-poQncU26.js} +1 -1
- package/dist/web-ui/assets/{SendToChat-EsNVdiYI.js → SendToChat-Xk5zlNy3.js} +1 -1
- package/dist/web-ui/assets/{Settings-COmJTMaX.js → Settings-DlhRiM77.js} +1 -1
- package/dist/web-ui/assets/{Store-Cb-RBY68.js → Store-Dp0MGa-t.js} +1 -1
- package/dist/web-ui/assets/{Switch-SqNs6-fd.js → Switch-CZAYoGju.js} +1 -1
- package/dist/web-ui/assets/{Team-DA5MQ-20.js → Team-D5wmT4Mj.js} +10 -10
- package/dist/web-ui/assets/{Work-D4noaLBo.js → Work-B8VUHTW7.js} +1 -1
- package/dist/web-ui/assets/{arc-BOFJ1EJN.js → arc-C7xiSR_L.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-BQ0qr0Vl.js → architectureDiagram-3BPJPVTR-BCM1UC9H.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-kSXlCE5q.js → blockDiagram-GPEHLZMM-Bl9V85eo.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-kCxqEGe5.js → c4Diagram-AAUBKEIU-BgyqGUI_.js} +1 -1
- package/dist/web-ui/assets/channel-xHjc9vd-.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-BgMluOvE.js → chunk-2J33WTMH-2znVHbo8.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-tu9bzY5y.js → chunk-4BX2VUAB-BGXPYXO3.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-DK9D0I2N.js → chunk-55IACEB6-B4GQDwv-.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-D_5Cdc0d.js → chunk-727SXJPM-D9WRILj0.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-BUmO_w99.js → chunk-AQP2D5EJ-DQb0__Jh.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-Ck9FWl7n.js → chunk-FMBD7UC4-lEuLc0aj.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-Mvxy6fm4.js → chunk-ND2GUHAM-Dd5SDfdJ.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-C9xMd3WM.js → chunk-QZHKN3VN-Ds8u_1wB.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-XGbYdlgY.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-XGbYdlgY.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-CUTkidkC.js → cose-bilkent-S5V4N54A-DZTfdLi_.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-CGLda2Em.js → dagre-BM42HDAG-D1B-Tulw.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-DRl88ns2.js → diagram-2AECGRRQ-DITdhssl.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-rf4YhM9A.js → diagram-5GNKFQAL-CEQxFHzH.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-BD8mjYi6.js → diagram-KO2AKTUF-DxCnKGbb.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-DiZICe4t.js → diagram-LMA3HP47-BOYuGZIr.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-Dj0Mw95G.js → diagram-OG6HWLK6-BNJgh7s8.js} +1 -1
- package/dist/web-ui/assets/{docx-preview-DQSKxlsK.js → docx-preview-CrUr10-f.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-BQq31SZZ.js → erDiagram-TEJ5UH35-BuCa252h.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-Cc82cW20.js → flowDiagram-I6XJVG4X-CVvFCkDE.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-D1MzI2Uw.js → ganttDiagram-6RSMTGT7-DmTrMDic.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-D1v-40GN.js → gitGraphDiagram-PVQCEYII-DkQpA-Z8.js} +1 -1
- package/dist/web-ui/assets/index-BEhLix2_.css +1 -0
- package/dist/web-ui/assets/{index-BXWHxoXp.js → index-CIrsLoqm.js} +79 -79
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-COPRgK1x.js → infoDiagram-5YYISTIA-C_rWcDW7.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-BmrWPE_9.js → ishikawaDiagram-YF4QCWOH-C0KnGaRN.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-C7WKxQjK.js → journeyDiagram-JHISSGLW-CuC-5aLM.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-yNU5HtNI.js → kanban-definition-UN3LZRKU-DU1_VSXa.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-B-JixiD0.js → mermaid.core-Bc0iYQ8k.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-CIC2Ov1E.js → mindmap-definition-RKZ34NQL-BVU3rzyG.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-CJn4Ut9d.js → pieDiagram-4H26LBE5-B7Lis7Cn.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-DcRyVlzO.js → quadrantDiagram-W4KKPZXB-DFFsDwCW.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-DiNbCJGt.js → requirementDiagram-4Y6WPE33-DFMxzahh.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP-RHicfbUP.js → sankeyDiagram-5OEKKPKP-CQFj5LUY.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-P1XTa1MM.js → sequenceDiagram-3UESZ5HK-DN_1Aiqe.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-Dbu2PX-0.js → stateDiagram-AJRCARHV-DmePUv3C.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-CFaxbhDx.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-DGJ5VfHk.js → timeline-definition-PNZ67QCA-Cm8EYLTZ.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-B9fLD2oz.js → vennDiagram-CIIHVFJN-BhoN_mu0.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-CH2NYUlK.js → wardley-L42UT6IY-DiYqNtfo.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-efQZMvBj.js → wardleyDiagram-YWT4CUSO-Bd8vpNb4.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-BNcrfIXF.js → xychartDiagram-2RQKCTM6-CHboDSbi.js} +1 -1
- package/dist/web-ui/index.html +2 -2
- package/package.json +1 -1
- package/dist/web-ui/assets/channel-MEPTI8rz.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-C-iFEC5t.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-C-iFEC5t.js +0 -1
- package/dist/web-ui/assets/index-B0GCqbye.css +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-BVoD4Uz4.js +0 -1
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-
|
|
2
|
-
import{r as S,k as Wm,u as Pt,Y as Iv,j as c,q as $o,Z as Xm,$ as zm,w as St,l as te,a0 as Zk,a as qm,b as Zm,P as Yt,c as zh,M as Vk,A as Ns,n as Lr,C as Wo,i as Vm,a1 as Fk,a2 as Uk,a3 as Hk,a4 as Yk,a5 as Gk,a6 as bO,a7 as lc,o as vO,O as Kk,D as Jk,h as Fm,d as eC,a8 as Bv,a9 as nh,aa as tC,ab as yO,ac as sC,ad as rC,ae as Wv,af as iC,ag as nC,ah as oC,_ as Xv,ai as aC,aj as oh,ak as lC,al as ou,am as cC,an as hC,ao as SO,ap as wO,aq as _O,ar as wa,as as kO,at as dC,au as CO,av as Mn,aw as Ic,ax as Bc,ay as uC,az as PO,aA as fC,aB as mC,aC as pC,aD as gC,aE as TO,s as QO,m as $O,aF as OC,aG as xC,aH as au,aI as jO,aJ as bC,aK as lu,aL as cu,aM as vC,aN as hu,aO as yC,aP as RO,aQ as cc,aR as EO,aS as SC,aT as wC,aU as _C,aV as AO,aW as kC,aX as CC,aY as PC,aZ as TC,a_ as QC,a$ as $C,b0 as jC,b1 as RC,b2 as MO,b3 as EC,b4 as AC,p as MC,b5 as LC,b6 as NC,b7 as DC,b8 as IC}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CIrsLoqm.js","assets/index-BEhLix2_.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as S,k as Wm,u as Pt,Y as Iv,j as c,q as $o,Z as Xm,$ as zm,w as St,l as te,a0 as Zk,a as qm,b as Zm,P as Yt,c as zh,M as Vk,A as Ns,n as Lr,C as Wo,i as Vm,a1 as Fk,a2 as Uk,a3 as Hk,a4 as Yk,a5 as Gk,a6 as bO,a7 as lc,o as vO,O as Kk,D as Jk,h as Fm,d as eC,a8 as Bv,a9 as nh,aa as tC,ab as yO,ac as sC,ad as rC,ae as Wv,af as iC,ag as nC,ah as oC,_ as Xv,ai as aC,aj as oh,ak as lC,al as ou,am as cC,an as hC,ao as SO,ap as wO,aq as _O,ar as wa,as as kO,at as dC,au as CO,av as Mn,aw as Ic,ax as Bc,ay as uC,az as PO,aA as fC,aB as mC,aC as pC,aD as gC,aE as TO,s as QO,m as $O,aF as OC,aG as xC,aH as au,aI as jO,aJ as bC,aK as lu,aL as cu,aM as vC,aN as hu,aO as yC,aP as RO,aQ as cc,aR as EO,aS as SC,aT as wC,aU as _C,aV as AO,aW as kC,aX as CC,aY as PC,aZ as TC,a_ as QC,a$ as $C,b0 as jC,b1 as RC,b2 as MO,b3 as EC,b4 as AC,p as MC,b5 as LC,b6 as NC,b7 as DC,b8 as IC}from"./index-CIrsLoqm.js";import{P as zv,E as BC,L as qv,S as WC}from"./AsyncState-C4a4KQ04.js";import{p as XC,r as LO}from"./CommentInput-jN8Pjpy4.js";import{ContentRenderer as kf,resolveFormat as zC}from"./ContentRenderer-CkTLvnEu.js";import{a as qC,c as ZC,D as VC}from"./DeliverableShareModal-BjrQLmcX.js";import{i as FC,S as NO}from"./Switch-CZAYoGju.js";function co(s,e,t){let r=t.initialDeps??[],i,n=!0;function a(){var o,l,h;let d;t.key&&((o=t.debug)!=null&&o.call(t))&&(d=Date.now());const u=s();if(!(u.length!==r.length||u.some((v,b)=>r[b]!==v)))return i;r=u;let p;if(t.key&&((l=t.debug)!=null&&l.call(t))&&(p=Date.now()),i=e(...u),t.key&&((h=t.debug)!=null&&h.call(t))){const v=Math.round((Date.now()-d)*100)/100,b=Math.round((Date.now()-p)*100)/100,g=b/16,O=(m,x)=>{for(m=String(m);m.length<x;)m=" "+m;return m};console.info(`%c⏱ ${O(b,5)} /${O(v,5)} ms`,`
|
|
3
3
|
font-size: .6rem;
|
|
4
4
|
font-weight: bold;
|
|
5
|
-
color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(n&&t.skipInitialOnChange)&&t.onChange(i),n=!1,i}return a.updateDeps=o=>{r=o},a}function DO(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const UC=(s,e)=>Math.abs(s-e)<1.01,HC=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},IO=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},YC=s=>s,GC=s=>{const e=Math.max(s.startIndex-s.overscan,0),t=Math.min(s.endIndex+s.overscan,s.count-1),r=[];for(let i=e;i<=t;i++)r.push(i);return r},KC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;const i=a=>{const{width:o,height:l}=a;e({width:Math.round(o),height:Math.round(l)})};if(i(IO(t)),!r.ResizeObserver)return()=>{};const n=new r.ResizeObserver(a=>{const o=()=>{const l=a[0];if(l?.borderBoxSize){const h=l.borderBoxSize[0];if(h){i({width:h.inlineSize,height:h.blockSize});return}}i(IO(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},BO={passive:!0},WO=typeof window>"u"?!0:"onscrollend"in window,JC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&WO?()=>{}:HC(r,()=>{e(i,!1)},s.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:u,isRtl:f}=s.options;i=u?t.scrollLeft*(f&&-1||1):t.scrollTop,n(),e(i,d)},o=a(!0),l=a(!1);t.addEventListener("scroll",o,BO);const h=s.options.useScrollendEvent&&WO;return h&&t.addEventListener("scrollend",l,BO),()=>{t.removeEventListener("scroll",o),h&&t.removeEventListener("scrollend",l)}},e2=(s,e,t)=>{if(e?.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[t.options.horizontal?"inlineSize":"blockSize"])}return s[t.options.horizontal?"offsetWidth":"offsetHeight"]},t2=(s,{adjustments:e=0,behavior:t},r)=>{var i,n;const a=s+e;(n=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||n.call(i,{[r.options.horizontal?"left":"top"]:a,behavior:t})};class s2{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,r,i;return((i=(r=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let t=null;const r=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(i=>{i.forEach(n=>{const a=()=>{const o=n.target,l=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(o,n,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),t=null},observe:i=>{var n;return(n=r())==null?void 0:n.observe(i,{box:"border-box"})},unobserve:i=>{var n;return(n=r())==null?void 0:n.unobserve(i)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([r,i])=>{typeof i>"u"&&delete t[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:YC,rangeExtractor:GC,onChange:()=>{},measureElement:e2,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,t)},this.maybeNotify=co(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,n)=>{this.scrollAdjustments=0,this.scrollDirection=n?this.getScrollOffset()<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=n,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,r)=>{const i=new Map,n=new Map;for(let a=r-1;a>=0;a--){const o=t[a];if(i.has(o.lane))continue;const l=n.get(o.lane);if(l==null||o.end>l.end?n.set(o.lane,o):o.end<l.end&&i.set(o.lane,!0),i.size===this.options.lanes)break}return n.size===this.options.lanes?Array.from(n.values()).sort((a,o)=>a.end===o.end?a.index-o.index:a.end-o.end)[0]:void 0},this.getMeasurementOptions=co(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,r,i,n,a,o,l)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=co(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l},h)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const p of this.laneAssignments.keys())p>=t&&this.laneAssignments.delete(p);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(p=>{this.itemSizeCache.set(p.key,p.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const u=this.measurementsCache.slice(0,d),f=new Array(o).fill(void 0);for(let p=0;p<d;p++){const v=u[p];v&&(f[v.lane]=p)}for(let p=d;p<t;p++){const v=n(p),b=this.laneAssignments.get(p);let g,O;const m=l==="estimate"||h.has(v);if(b!==void 0&&this.options.lanes>1){g=b;const C=f[g],P=C!==void 0?u[C]:void 0;O=P?P.end+this.options.gap:r+i}else{const C=this.options.lanes===1?u[p-1]:this.getFurthestMeasurement(u,p);O=C?C.end+this.options.gap:r+i,g=C?C.lane:p%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(p,g)}const x=h.get(v),y=typeof x=="number"?x:this.options.estimateSize(p),k=O+y;u[p]={index:p,start:O,size:y,end:k,key:v,lane:g},f[g]=p}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=co(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,r,i,n)=>this.range=t.length>0&&r>0?r2({measurements:t,outerSize:r,scrollOffset:i,lanes:n}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=co(()=>{let t=null,r=null;const i=this.calculateRange();return i&&(t=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,r]},(t,r,i,n,a)=>n===null||a===null?[]:t({startIndex:n,endIndex:a,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const r=this.options.indexAttribute,i=t.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,i-n),o=Math.min(this.options.count-1,i+n);return t>=a&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((a,o)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(o))});return}const r=this.indexFromElement(t),i=this.options.getItemKey(r),n=this.elementsCache.get(i);n!==t&&(n&&this.observer.unobserve(n),this.observer.observe(t),this.elementsCache.set(i,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,r)=>{var i;const n=this.measurementsCache[t];if(!n)return;const a=this.itemSizeCache.get(n.key)??n.size,o=r-a;o!==0&&(((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(n,o,this):n.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,r)),this.notify(!1))},this.getVirtualItems=co(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,r)=>{const i=[];for(let n=0,a=t.length;n<a;n++){const o=t[n],l=r[o];i.push(l)}return i},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const r=this.getMeasurements();if(r.length!==0)return DO(r[Zv(0,r.length-1,i=>DO(r[i]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,r,i=0)=>{if(!this.scrollElement)return 0;const n=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=t>=a+n?"end":"start"),r==="center"?t+=(i-n)/2:r==="end"&&(t-=n);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,r="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const i=this.getSize(),n=this.getScrollOffset(),a=this.measurementsCache[t];if(!a)return;if(r==="auto")if(a.end>=n+i-this.options.scrollPaddingEnd)r="end";else if(a.start<=n+this.options.scrollPaddingStart)r="start";else return[n,r];if(r==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),r];const o=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,r,a.size),r]},this.scrollToOffset=(t,{align:r="start",behavior:i="auto"}={})=>{const n=this.getOffsetForAlignment(t,r),a=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:a,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:r="auto",behavior:i="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getOffsetForIndex(t,r);if(!n)return;const[a,o]=n,l=this.now();this.scrollState={index:t,align:o,behavior:i,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+t,n=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:n,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1)i=((t=r[r.length-1])==null?void 0:t.end)??0;else{const n=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&n.some(o=>o===null);){const o=r[a];n[o.lane]===null&&(n[o.lane]=o.end),a--}i=Math.max(...n.filter(o=>o!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:r,behavior:i})=>{this.options.scrollToFn(t,{behavior:i,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,n=1,a=i!==this.scrollState.lastTargetOffset;if(!a&&UC(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=i,this.scrollState.behavior="auto",this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Zv=(s,e,t,r)=>{for(;s<=e;){const i=(s+e)/2|0,n=t(i);if(n<r)s=i+1;else if(n>r)e=i-1;else return i}return s>0?s-1:0};function r2({measurements:s,outerSize:e,scrollOffset:t,lanes:r}){const i=s.length-1,n=l=>s[l].start;if(s.length<=r)return{startIndex:0,endIndex:i};let a=Zv(0,i,n,t),o=a;if(r===1)for(;o<i&&s[o].end<t+e;)o++;else if(r>1){const l=Array(r).fill(0);for(;o<i&&l.some(d=>d<t+e);){const d=s[o];l[d.lane]=d.end,o++}const h=Array(r).fill(t+e);for(;a>=0&&h.some(d=>d>=t);){const d=s[a];h[d.lane]=d.start,a--}a=Math.max(0,a-a%r),o=Math.min(i,o+(r-1-o%r))}return{startIndex:a,endIndex:o}}const XO=typeof document<"u"?S.useLayoutEffect:S.useEffect;function i2({useFlushSync:s=!0,...e}){const t=S.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?Wm.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=S.useState(()=>new s2(r));return i.setOptions(r),XO(()=>i._didMount(),[]),XO(()=>i._willUpdate()),i}function n2(s){return i2({observeElementRect:KC,observeElementOffset:JC,scrollToFn:t2,...s})}function o2({approval:s,submitting:e,readOnly:t,onClose:r,onDecision:i}){const{t:n}=Pt(["team","common"]);Iv(!0);const[a,o]=S.useState(""),l=typeof s.details?.command=="string"?s.details.command:"",h=typeof s.details?.toolName=="string"?s.details.toolName:"",d=u=>{t||e||i(u,a.trim()||void 0)};return Wm.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:u=>{u.target===u.currentTarget&&r()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-500/15 text-amber-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug break-words",children:s.title||n("team:toolApproval.defaultTitle",{defaultValue:"Tool execution needs approval"})}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[c.jsxs("p",{className:"text-xs text-fg-tertiary",children:[s.agentName,h?` · ${h}`:""]}),t&&c.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-green-500/15 text-green-600",children:[c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M20 6L9 17l-5-5"})}),n("team:toolApproval.resolved",{defaultValue:"Resolved"})]})]})]}),c.jsx("button",{onClick:r,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:n("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[c.jsx("p",{className:"text-sm text-fg-secondary leading-relaxed",children:n("team:toolApproval.lead",{defaultValue:"The agent is paused until you approve or reject this action."})}),s.description&&c.jsx("div",{className:"text-xs text-fg-secondary leading-relaxed [&_p]:my-0 [&_p]:text-xs",children:c.jsx($o,{content:s.description.replace(/\s*Command:[\s\S]*$/,""),className:"text-xs [&_p]:text-xs [&_li]:text-xs"})}),l&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsx("div",{className:"text-[11px] font-medium text-fg-tertiary uppercase tracking-wide",children:n("team:toolApproval.commandLabel",{defaultValue:"Command"})}),c.jsx("pre",{className:"text-xs text-fg-primary bg-surface-overlay border border-border-default rounded-xl px-3 py-2.5 overflow-x-auto whitespace-pre-wrap break-all font-mono leading-relaxed",children:l})]}),!t&&c.jsx("textarea",{rows:2,value:a,onChange:u=>o(u.target.value),placeholder:n("team:toolApproval.commentPlaceholder",{defaultValue:"Optional note (e.g. why you reject)…"}),className:"w-full px-3.5 py-2.5 text-sm bg-surface-overlay border border-border-default rounded-xl text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50 resize-y"})]}),c.jsx("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:t?c.jsx("button",{onClick:r,className:"px-5 py-2 text-sm font-medium text-fg-secondary border border-border-default rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:close",{defaultValue:"Close"})}):c.jsxs(c.Fragment,{children:[c.jsxs("button",{disabled:e,onClick:()=>d(!1),className:"px-5 py-2 text-sm font-medium bg-red-600/85 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[c.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]}),n("common:reject",{defaultValue:"Reject"})]}),c.jsxs("button",{disabled:e,onClick:()=>d(!0),className:"px-5 py-2 text-sm font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors inline-flex items-center gap-2",children:[e&&c.jsxs("svg",{className:"animate-spin h-4 w-4",viewBox:"0 0 24 24",fill:"none",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),n("common:approve",{defaultValue:"Approve"})]})]})})]})}),document.body)}const zO={urgent:"bg-red-500/15 text-red-500",high:"bg-amber-500/15 text-amber-600",normal:"bg-blue-500/15 text-blue-500",low:"bg-surface-overlay text-fg-tertiary"};function a2({notification:s,agentName:e,acknowledging:t,index:r=0,total:i=1,onClose:n,onAcknowledge:a}){const{t:o,i18n:l}=Pt(["team","common"]);Iv(!0);const h=Xm(s.createdAt,o),d=zm(s.createdAt,l.language),u=s.priority||"normal",f=s.metadata??{},p=e||(typeof f.agentName=="string"?f.agentName:void 0),v=i>1,b=r>=i-1,g=Math.max(0,i-r-1);return Wm.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:O=>{O.target===O.currentTarget&&n()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-500/15 text-blue-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),c.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug",children:s.title}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[p&&c.jsx("p",{className:"text-xs text-fg-tertiary",children:p}),u!=="normal"&&c.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${zO[u]??zO.normal}`,children:u}),v&&c.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-surface-overlay text-fg-secondary tabular-nums",children:o("page.notifyReviewProgress",{ns:"team",defaultValue:"{{current}} / {{total}}",current:r+1,total:i})}),(h||d)&&c.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-fg-tertiary tabular-nums",title:d,children:[c.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"9"}),c.jsx("path",{d:"M12 7v5l3 2"})]}),h,h&&d&&c.jsx("span",{className:"text-fg-muted",children:"·"}),d]})]})]}),c.jsx("button",{onClick:n,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:o("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),v&&c.jsx("div",{className:"h-0.5 w-full bg-surface-overlay shrink-0",children:c.jsx("div",{className:"h-full bg-blue-500 transition-[width] duration-200",style:{width:`${(r+1)/i*100}%`}})}),c.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:c.jsx("div",{className:"text-sm text-fg-primary leading-relaxed",children:c.jsx($o,{content:s.body||""})})}),c.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:[c.jsx("button",{onClick:n,className:"px-3.5 py-2 text-sm text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:o("common:close")}),c.jsx("button",{onClick:()=>{a()},disabled:t,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-500 disabled:opacity-50 rounded-lg transition-colors",children:t?o("common:loading"):b?o("page.notifyUserGotIt",{ns:"team",defaultValue:"Got it"}):o("page.notifyReviewNext",{ns:"team",defaultValue:"Next",count:g})})]})]})}),document.body)}const Vv=12,du=400,l2=4,c2=350;function Fv(s){return Math.max(0,s.scrollHeight-s.clientHeight)}function qO(s){return Fv(s)>1}function Wc(s){return Fv(s)-s.scrollTop}function h2(s){return Wc(s)<=Vv}function d2(s,e){return Math.abs(e)<=Math.abs(s)?"none":e<0?"up":e>0?"down":"none"}const u2=new Set(["ArrowUp","PageUp","Home"]),f2=new Set(["ArrowDown","PageDown","End"]);function m2(s){return u2.has(s)?"up":f2.has(s)?"down":"none"}function p2(s,e){return s==null?"none":e>s+1?"up":e<s-1?"down":"none"}function g2(s){return s.scrollable?s.takeover?s.gestureDirection==="up"||s.intentPending?"hold":s.distance<=Vv?"resume":"hold":s.gestureDirection==="up"&&s.gestureActive||!s.programmatic&&s.deltaScrollTop<-4?"handover":"follow":s.takeover?"resume":"follow"}function O2(s){return!s.takeover&&!s.gestureActive}function x2(s,e){return e&&s==="up"}function ho(s,e){return`${s||"_"}::${e??""}`}function b2(s,e){let t=null;for(const r of s)r.start>e+1||(!t||r.start>t.start)&&(t=r);return t??s[0]??null}function v2(s,e){if(h2(e))return{kind:"bottom"};const t=b2(s,e.scrollTop);return t?{kind:"row",id:t.id,delta:e.scrollTop-t.start}:{kind:"bottom"}}function y2(s,e){return s+e}const S2=12;function ZO(s,e=S2){return{kind:"row",id:s,delta:-e}}function VO(s){const e=s.getBoundingClientRect().top,t=s.scrollTop,r=[];for(const i of Array.from(s.querySelectorAll("[data-index]"))){const a=i.querySelector('[id^="msg-"]')?.id?.slice(4);a&&r.push({id:a,start:t+(i.getBoundingClientRect().top-e)})}return r.sort((i,n)=>i.start-n.start),r}function w2(s,e,t,r){const i=s.find(n=>n.id===t);return i?y2(i.start-e.scrollTop,r):null}class _2{constructor(e=120){this.capacity=e}entries=new Map;save(e,t){if(e)for(this.entries.delete(e),this.entries.set(e,t);this.entries.size>this.capacity;){const r=this.entries.keys().next();if(r.done)break;this.entries.delete(r.value)}}get(e){if(!e)return null;const t=this.entries.get(e);return t?(this.entries.delete(e),this.entries.set(e,t),t):null}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const FO=new _2,UO={jump:3,prepend:2,restore:1};function k2(s,e){return!s||s.key!==e.key?!0:UO[e.priority]>=UO[s.priority]}const C2=1e4,HO=300;function P2(s,e){return e-s>C2}function YO(s,e){return s&&e===!0}function T2(s){return s.rendered?s.stable?"apply":"refine":s.stale?s.priority==="restore"?"release-bottom":"release-hold":!s.absent||s.canLoadMore?"keep":s.priority==="restore"?"release-bottom":"release-hold"}function uu(s){return s!=="prepend"}const fu=Object.freeze({text:"",images:[],context:[],replyTo:null});function GO(s){return s.text===""&&s.images.length===0&&s.context.length===0&&s.replyTo===null}function Q2(s){return{text:s.text,images:s.images,context:s.context,replyTo:s.replyTo}}class $2{constructor(e=120){this.capacity=e}entries=new Map;save(e,t){if(!e)return;this.entries.delete(e);const r=Q2(t);if(!GO(r))for(this.entries.set(e,r);this.entries.size>this.capacity;){const i=this.entries.keys().next().value;if(i===void 0)break;this.entries.delete(i)}}get(e){const t=this.peek(e);return GO(t)?fu:(this.entries.delete(e),this.entries.set(e,t),t)}peek(e){return e?this.entries.get(e)??fu:fu}size(){return this.entries.size}clear(){this.entries.clear()}}const _a=new $2;function KO(s){return s.aborted||s.sawTerminal?"finalize":s.serverStatus==="streaming"||s.serverStatus===null?"reattach":"finalize"}function JO(s){switch(s){case"streaming":case"done":case"error":case"stopped":case"idle":case"not_found":return s;default:return null}}function e0(s,e){return!!s&&!!e&&s.has(e)}function j2(s){return s.msgIsStreaming&&s.liveStreamForView}const R2=10*6e4;class E2{bySession=new Map;listeners=new Set;_revision=0;getRevision=()=>this._revision;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});applyServerState(e,t,r,i=Date.now()){const n=this.bySession.get(t);if(n&&n.source==="server"&&n.at>i)return;const a=!n||n.streaming!==r;this.bySession.set(t,{agentId:e,streaming:r,source:"server",at:i}),a&&this.bump()}reconcileFromServer(e,t,r=Date.now()){for(const[i,n]of Object.entries(t))this.applyServerState(e,i,n,r)}applyLocalOptimistic(e,t,r){const i=this.bySession.get(t),n=Date.now();if(i&&i.source==="server"&&i.at>=n)return;const a=!i||i.streaming!==r;this.bySession.set(t,{agentId:e,streaming:r,source:"local",at:n}),a&&this.bump()}isStreaming(e){return e?this.bySession.get(e)?.streaming??!1:!1}isAgentStreaming(e){if(!e)return!1;for(const t of this.bySession.values())if(t.agentId===e&&t.streaming)return!0;return!1}streamingAgentIds(){const e=new Set;for(const t of this.bySession.values())t.streaming&&e.add(t.agentId);return e}hasEntry(e){return this.bySession.has(e)}prune(e=Date.now(),t=R2){for(const[r,i]of this.bySession)!i.streaming&&e-i.at>t&&this.bySession.delete(r)}bump(){this._revision+=1;for(const e of this.listeners)try{e()}catch{}}}const hs=new E2;function ah(){return S.useSyncExternalStore(hs.subscribe,hs.getRevision,hs.getRevision)}function Uv(s){return S.useSyncExternalStore(hs.subscribe,hs.getRevision,hs.getRevision),hs.isAgentStreaming(s)}function A2(s){const e=s?.payload;return!e||typeof e.sessionId!="string"||typeof e.streaming!="boolean"?null:{agentId:typeof e.agentId=="string"?e.agentId:"",sessionId:e.sessionId,streaming:e.streaming}}let t0=!1;function M2(){t0||(t0=!0,St.on("session:stream_state",s=>{const e=A2(s);if(!e)return;const t=Date.parse(s.timestamp??"")||Date.now();hs.applyServerState(e.agentId,e.sessionId,e.streaming,t)}))}async function L2(s,e){if(!(!s||e.length===0)){try{const t=await te.sessions.streamStatusBatch(s,e);hs.reconcileFromServer(s,t.streaming??{},t.at)}catch{}hs.prune()}}function N2(s,e){return!s||s.mode!=="direct"||e.chatMode!=="direct"||!s.sessionId&&!s.preferMain?!1:!!s.agentId&&s.agentId===e.agentId}function Fa({children:s,onClose:e,title:t,width:r="w-[440px]"}){return c.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:e,children:c.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${r} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:i=>i.stopPropagation(),children:[c.jsx("h3",{className:"text-base font-semibold mb-5",children:t}),s]})})}function vo({label:s,children:e}){return c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s}),e]})}function D2({onClose:s,onCreate:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("");return c.jsx(Fa,{onClose:s,title:t("team:modals.createTeam.title"),children:c.jsxs("div",{className:"space-y-4",children:[c.jsx(vo,{label:t("team:modals.createTeam.teamName"),children:c.jsx("input",{value:r,onChange:o=>i(o.target.value),placeholder:t("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:o=>{o.key==="Enter"&&r.trim()&&e(r.trim(),n.trim()||void 0)}})}),c.jsx(vo,{label:t("team:modals.createTeam.description"),children:c.jsx("textarea",{value:n,onChange:o=>a(o.target.value),placeholder:t("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),c.jsx("div",{className:"text-xs text-fg-tertiary",children:t("team:modals.createTeam.hint")}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:c.jsx(Zk,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:c.jsx("span",{className:"text-brand-400 font-medium"}),1:c.jsx("span",{className:"text-brand-400"})}})}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:()=>r.trim()&&e(r.trim(),n.trim()||void 0),disabled:!r.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:t("team:modals.createTeam.createTeam")})]})]})})}function I2({onClose:s,onAdd:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("member"),[o,l]=S.useState(""),[h,d]=S.useState(""),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(!1),O=p?.inviteToken?`${window.location.origin}/#invite?token=${p.inviteToken}`:null,m=async()=>{if(d(""),!r.trim()){d(t("team:modals.addHuman.nameRequired"));return}if(!o.trim()){d(t("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.trim())){d(t("team:modals.addHuman.invalidEmail"));return}f(!0);try{const y=await e(r.trim(),n,o.trim());v({...y,userName:r.trim()})}catch(y){d(y instanceof Error?y.message:String(y))}finally{f(!1)}},x=()=>{O&&(navigator.clipboard.writeText(O),g(!0),setTimeout(()=>g(!1),2e3))};return p?c.jsxs(Fa,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:[c.jsxs("div",{className:"text-center py-4",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:c.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-green-500",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx("div",{className:"text-base font-medium mb-1",children:t("team:modals.addHuman.memberCreated",{name:p.userName})}),O?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:t("team:modals.addHuman.inviteHint")}),c.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:t("team:modals.addHuman.inviteLink")}),c.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:O})]}),c.jsx("button",{onClick:x,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${b?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(b?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):c.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:t("team:modals.addHuman.memberCreatedNoInvite")})]}),c.jsx("div",{className:"flex justify-end pt-3",children:c.jsx("button",{onClick:s,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("common:done")})})]}):c.jsx(Fa,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"text-xs text-fg-secondary bg-surface-primary border border-border-default rounded-lg px-3 py-2.5 leading-relaxed",children:[c.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:t("team:modals.addHuman.sharedInstanceTitle")}),t("team:modals.addHuman.sharedInstanceDesc"),c.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[t("team:modals.addHuman.orgHint")," ",c.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:t("team:modals.addHuman.orgLink")})]})]}),c.jsx(vo,{label:t("team:modals.addHuman.name"),children:c.jsx("input",{value:r,onChange:y=>i(y.target.value),placeholder:t("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),c.jsx(vo,{label:t("team:modals.addHuman.role"),children:c.jsxs("select",{value:n,onChange:y=>a(y.target.value),className:"input",children:[c.jsx("option",{value:"owner",children:t("common:role.owner")}),c.jsx("option",{value:"admin",children:t("common:role.admin")}),c.jsx("option",{value:"member",children:t("common:role.member")}),c.jsx("option",{value:"guest",children:t("common:role.guest")})]})}),c.jsx(vo,{label:t("team:modals.addHuman.emailRequired"),children:c.jsx("input",{value:o,onChange:y=>l(y.target.value),type:"email",placeholder:t("team:modals.addHuman.emailPlaceholder"),className:"input"})}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:t("team:modals.addHuman.inviteFlowHint")}),h&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:h}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:m,disabled:u,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:t(u?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function B2({teamId:s,ungrouped:e,onClose:t,onAdd:r}){const{t:i}=Pt(["team","common"]);return c.jsx(Fa,{onClose:t,title:i("team:modals.addExisting.title"),children:c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:i("team:modals.addExisting.hint")}),e.length===0?c.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:i("team:modals.addExisting.allInTeam")}):c.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:e.map(n=>c.jsxs("button",{onClick:()=>r(n.id,n.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[c.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${n.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:n.name.charAt(0)}),c.jsxs("div",{className:"flex-1",children:[c.jsx("div",{className:"font-medium text-sm",children:n.name}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[n.role," · ",n.type==="agent"?i("team:modals.addExisting.typeAgent"):i("team:modals.addExisting.typeHuman")]})]}),n.status&&c.jsx("span",{className:`w-2 h-2 rounded-full ${n.status==="idle"?"bg-green-400":n.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},n.id))}),c.jsx("div",{className:"flex justify-end pt-2",children:c.jsx("button",{onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:i("common:close")})})]})})}function W2({onClose:s,onConnected:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState(""),[o,l]=S.useState(!1),[h,d]=S.useState(null),[u,f]=S.useState(null),p=async()=>{if(!r.trim()){a(t("team:modals.openClaw.agentNameRequired"));return}const b=r.trim().toLowerCase().replace(/\s+/g,"-");l(!0),a("");try{const g=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:b,agentName:r.trim(),orgId:"default",capabilities:["general"]})});if(!g.ok){const m=await g.json().catch(()=>({}));throw new Error(m.error??`HTTP ${g.status}`)}const O=await g.json();d({externalAgentId:b,markusAgentId:O.registration?.markusAgentId,token:O.token,gatewayUrl:O.gatewayUrl})}catch(g){a(String(g))}l(!1)},v=(b,g)=>{navigator.clipboard.writeText(b),f(g),setTimeout(()=>f(null),2e3)};return c.jsx(Fa,{onClose:s,title:t("team:modals.openClaw.title"),width:"w-[560px]",children:h?(()=>{const b=h.gatewayUrl??`${window.location.origin}/api/gateway`,g=h.token?t("team:modals.openClaw.bearerTokenLine",{token:h.token}):"",O=t("team:modals.openClaw.connectionPromptBody",{gwUrl:b,externalAgentId:h.externalAgentId,tokenSection:g});return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"text-center py-6",children:[c.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),c.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:t("team:modals.openClaw.agentRegistered")}),c.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:c.jsx("strong",{children:r})})]}),c.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:t("team:modals.openClaw.copyInstruction")}),c.jsx("button",{onClick:()=>v(O,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${u==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(u==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),c.jsx("div",{className:"flex justify-end pt-5",children:c.jsx("button",{onClick:()=>{e()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("team:modals.openClaw.done")})})]})})():c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:t("team:modals.openClaw.description")}),c.jsxs("div",{className:"space-y-4",children:[c.jsx(vo,{label:t("team:modals.openClaw.agentName"),children:c.jsx("input",{className:"input",placeholder:t("team:modals.openClaw.agentNamePlaceholder"),value:r,onChange:b=>i(b.target.value),autoFocus:!0})}),n&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:n}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:p,disabled:o,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:t(o?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}function Hv(s){return`group:${s}`}function X2(s){const{chatMode:e,agentTeamId:t,channelTeamId:r,knownTeamIds:i}=s,n=e==="direct"?t:e==="channel"?r:null;return n&&(i instanceof Set?i.has(n):Array.from(i).includes(n))?`team/t/${n}`:"team"}function z2(s,e){return s&&typeof s.tokensUsedToday=="number"&&Number.isFinite(s.tokensUsedToday)?s.tokensUsedToday:typeof e=="number"&&Number.isFinite(e)?e:0}function q2(s){return s?s.filter(e=>e&&typeof e.size=="number"&&e.size>0).slice().sort((e,t)=>t.size-e.size||e.name.localeCompare(t.name)):[]}const Z2=new Set(["workspace","sessions","tool-outputs","daily-logs","role","subagent-logs","worktrees"]);function V2(s){return Z2.has(s)?`agent:profilePage.overview.storageBuckets.${s}`:null}const Cf={idle:{tone:"ok",dotClass:"bg-green-400",running:!0,chipClass:"bg-green-500/10 border border-green-500/20",textClass:"text-green-600",labelKey:"common:status.idle"},working:{tone:"busy",dotClass:"bg-blue-400 animate-pulse",running:!0,chipClass:"bg-blue-500/10 border border-blue-500/20",textClass:"text-blue-500",labelKey:"common:status.working"},error:{tone:"danger",dotClass:"bg-red-400 animate-pulse",running:!0,chipClass:"bg-red-500/10 border border-red-500/20",textClass:"text-red-500",labelKey:"common:status.error"},paused:{tone:"warn",dotClass:"bg-amber-400",running:!1,chipClass:"bg-amber-500/10 border border-amber-500/20",textClass:"text-amber-600",labelKey:"common:status.paused"},offline:{tone:"muted",dotClass:"bg-gray-400",running:!1,chipClass:"bg-gray-500/10 border border-border-default",textClass:"text-fg-tertiary",labelKey:"common:status.offline"}};function qh(s){const e=s?Cf[s]:void 0;return e||{...Cf.offline,labelKey:null}}const F2=Cf.working;function Ol(s,e){const t=qh(s);return!e||!t.running||t.tone==="danger"||t.tone==="busy"?t:F2}const U2=5;function s0(s,e=U2){const t=Array.isArray(s)?s:[];return{shown:t.slice().sort((i,n)=>Date.parse(n.startedAt)-Date.parse(i.startedAt)).slice(0,Math.max(0,e)),total:t.length}}const H2=100;function Y2(s){const e=Array.isArray(s)?s:[];return{heartbeats:e.filter(t=>t.type==="heartbeat"),comms:e.filter(t=>t.type==="a2a")}}const Um=["files","mind","recent","tools","memory","usage"],G2=Um[0];function r0(s,e){return e?"mind":Um.find(r=>r===s)??G2}function K2(s){return s?"right-panel":"page"}function J2(s){const e=s?.deferredItemIds?.length??0,t=s?.droppedItemIds?.length??0,r=s?.inlineCompletedIds?.length??0,i=1,n=i+e+t+r;return{processed:i,deferred:e,dropped:t,inlineCompleted:r,total:n,isBatch:n>1}}let hc=new Map;function eP({agents:s,humans:e,authUser:t,onClose:r,onCreate:i}){const{t:n}=Pt(["team","common"]),[a,o]=S.useState(""),[l,h]=S.useState(new Set),[d,u]=S.useState(""),[f,p]=S.useState(!1),v=S.useMemo(()=>{const m=[];for(const x of s)m.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of e)x.id!==t?.id&&m.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||"Human"});return m},[s,e,t]),b=S.useMemo(()=>{if(!d)return v;const m=d.toLowerCase();return v.filter(x=>x.name.toLowerCase().includes(m)||x.subtitle.toLowerCase().includes(m))},[v,d]),g=m=>{h(x=>{const y=new Set(x);return y.has(m)?y.delete(m):y.add(m),y})},O=async()=>{if(!a.trim()||l.size===0)return;p(!0);const m=[...l],x={},y={};for(const k of m){const C=v.find(P=>P.id===k);C&&(x[k]=C.type,y[k]=C.name)}await i(a.trim(),m,x,y),p(!1)};return c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:m=>m.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:n("modals.createGroupChat.title")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:n("modals.createGroupChat.subtitle")})]}),c.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:c.jsx("input",{value:a,onChange:m=>o(m.target.value),placeholder:n("modals.createGroupChat.groupNamePlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50",autoFocus:!0})}),c.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:c.jsx("input",{value:d,onChange:m=>u(m.target.value),placeholder:n("modals.createGroupChat.searchPlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-1.5 text-xs text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50"})}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[b.length===0&&c.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:n("modals.createGroupChat.noMembersFound")}),b.map(m=>c.jsxs("button",{onClick:()=>g(m.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${l.has(m.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${l.has(m.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:l.has(m.id)&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx(Ns,{name:m.name,size:20,bgClass:m.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate text-[11px] font-medium block",children:m.name}),c.jsx("span",{className:"text-[9px] text-fg-tertiary",children:m.subtitle})]}),c.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${m.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:m.type==="agent"?n("modals.addExisting.typeAgent"):n("modals.addExisting.typeHuman")})]},m.id))]}),c.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("modals.createGroupChat.selected",{count:l.size})}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:r,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:cancel")}),c.jsx("button",{onClick:O,disabled:!a.trim()||l.size===0||f,className:"px-4 py-1.5 text-xs font-medium text-white bg-brand-600 hover:bg-brand-500 rounded-lg transition-colors disabled:opacity-50 disabled:pointer-events-none",children:n(f?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const tP=S.memo(function({authUser:e,agents:t,teams:r,humans:i,tasks:n,externalAgents:a,groupChats:o,chatMode:l,selectedAgent:h,activeChannel:d,activeDmUserId:u,onSelectAgent:f,onSelectChannel:p,onSelectDm:v,onSelectTeam:b,selectedTeamId:g,onRefreshTeams:O,onRefreshAgents:m,onRefreshHumans:x,onRefreshGroupChats:y,onViewProfile:k,onManageGroupMembers:C,unreadByAgent:P,unreadByChannel:_,width:T,onResizeStart:R,hidden:L,onCollapse:M,initialLoading:E,previewMode:B,focused:U,l2Available:F}){const{t:X}=Pt(["team","common"]),ae=qm(),j=Zm(Yt.TEAM),W=zh(),D=e?.role==="owner"||e?.role==="admin",V=S.useMemo(()=>new Set(a.map(q=>q.markusAgentId).filter(Boolean)),[a]);ah();const se=hs.streamingAgentIds(),[fe,z]=S.useState([]),[re,Z]=S.useState(new Set),[A,J]=S.useState(!1),[Y,oe]=S.useState(!1),[K,pe]=S.useState(null),[je,we]=S.useState(!1),[Ge,Qe]=S.useState(!1),[Ee,ye]=S.useState(null),[G,qe]=S.useState(null),[He,Ye]=S.useState(null),[pt,xt]=S.useState(!1),[bt,vt]=S.useState(""),[Pe,Et]=S.useState(null),[Ft,Es]=S.useState(null),[rt,yt]=S.useState(null),[Bt,ut]=S.useState(!1),Ze=S.useRef(null),[Xt,ot]=S.useState(null),At=S.useRef(null),us=S.useRef(null),[he,ce]=S.useState(null),$e=(q,me="success")=>{ce({message:q,type:me}),setTimeout(()=>ce(null),3e3)},[Xe,de]=S.useState(null),[De,ve]=S.useState(!1),st=S.useRef(!1);S.useEffect(()=>{if(B)return;te.governance.getSystemStatus().then(be=>{st.current=!0,de(be.globalPaused)}).catch(()=>{st.current=!0,de(!1)});const q=St.on("system:pause-all",()=>{st.current&&de(!0)}),me=St.on("system:resume-all",()=>{st.current&&de(!1)});return()=>{q(),me()}},[]),S.useEffect(()=>{if(!B)return;const q=setTimeout(()=>{const me=us.current,be=At.current;me&&be&&be.scrollTo({top:me.offsetTop-be.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(q)},[B]);const ze=S.useCallback(()=>{Xe!==null&&ee({title:X(Xe?"modals.resumeAll.title":"modals.pauseAll.title"),message:X(Xe?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:X(Xe?"chat.resume":"chat.pause"),onConfirm:async()=>{ve(!0);try{Xe?(await te.governance.resumeAll(),de(!1)):(await te.governance.pauseAll(),de(!0))}catch{}ve(!1)}})},[Xe]),[Ve,ee]=S.useState(null),Te=(q,me,be,Ie,Ke)=>{ee({title:q,message:me,onConfirm:be,confirmLabel:Ie,checkboxes:Ke})},[Se,Oe]=S.useState(null),[_e,Fe]=S.useState(null),at=S.useRef(null),wt=S.useRef(null),[ht,dt]=S.useState(!1),[Qt,hi]=S.useState(null),[le,$t]=S.useState(""),ge=S.useCallback((q,me=176,be=220)=>{const Ie=window.innerWidth,Ke=window.innerHeight,Je=8;let lt=q.clientX,Rt=q.clientY;return lt+me>Ie-Je&&(lt=Math.max(Je,Ie-me-Je)),Rt+be>Ke-Je&&(Rt=Math.max(Je,Ke-be-Je)),lt=Math.max(Je,Math.min(lt,Ie-me-Je)),Rt=Math.max(Je,Math.min(Rt,Ke-be-Je)),{x:lt,y:Rt}},[]),[Us,gt]=S.useState(hc),Bs=S.useMemo(()=>t.map(q=>q.id).sort().join(","),[t]);S.useEffect(()=>{if(!t.length||!j)return;let q=!1;(async()=>{const lt=[];await Promise.allSettled(t.map(async Rt=>{if(!hc.has(Rt.id))try{const{sessions:Ot}=await te.sessions.listByAgent(Rt.id,1);if(!Ot.length)return;const{messages:cs}=await te.sessions.getMessages(Ot[0].id,1);if(cs.length){const bs=cs[0],ir=bs.metadata?.segments;let zt=bs.content;if(ir&&ir.length>0){const vs=[...ir].reverse().find(es=>es.type==="text");vs&&vs.type==="text"&&(zt=vs.content)}const ks=zt.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);ks&<.push([Rt.id,ks])}}catch{}})),!q&<.length&>(Rt=>{const Ot=new Map(Rt);for(const[cs,bs]of lt)Ot.set(cs,bs);return hc=Ot,Ot})})();const be=new Set(t.map(lt=>lt.id)),Ie=lt=>Fk(lt).replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),Ke=(lt,Rt)=>{if(!lt||!Rt||!be.has(lt))return;const Ot=Ie(Rt);Ot&>(cs=>{const bs=new Map(cs);return bs.set(lt,Ot),hc=bs,bs})},Je=St.on("chat:proactive_message",lt=>{const Rt=lt.payload;Ke(Rt.agentId??"",Rt.message??"")});return()=>{q=!0,Je()}},[Bs,j]);const _t=S.useCallback(()=>{B||te.teams.list().then(q=>z(q.ungrouped)).catch(()=>{})},[B]);S.useEffect(()=>{_t()},[_t]),S.useEffect(()=>{if(!j)return;const q=St.on("team:update",_t),me=St.on("agent:removed",_t);return()=>{q(),me()}},[_t,j]),S.useEffect(()=>{if(!G&&!He&&!Pe&&!Bt&&!rt)return;const q=()=>{qe(null),Ye(null),Et(null),yt(null),ut(!1)},me=setTimeout(()=>document.addEventListener("click",q),0);return()=>{clearTimeout(me),document.removeEventListener("click",q)}},[G,He,Pe,Bt,rt]);const ln=(q,me)=>{Te(`${X("common:delete")} "${me}"?`,X("modals.deleteTeam.message"),async be=>{const Ie=be?.deleteMembers??!0,Ke=be?.purgeFiles??!1;await te.teams.delete(q,Ie,{purgeFiles:Ke}),O(),_t(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},X("contextMenu.deleteTeam"),[{id:"deleteMembers",label:X("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:X("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Fo=async(q,me)=>{try{const Ie=await(me==="start"?te.teams.startAll:te.teams.stopAll)(q),Ke=Ie.success?.length??0,Je=Ie.failed?.length??0;Je>0?$e(X("batchAction.failed",{action:X(`batchAction.operation.${me}`),ok:Ke,fail:Je}),"error"):Ke>0&&$e(X("batchAction.succeeded",{count:Ke,action:X(`batchAction.past.${me}`)}),"success"),m()}catch(be){$e(X("batchAction.failedToRun",{action:X(`batchAction.operation.${me}`),error:be instanceof Error?be.message:String(be)}),"error")}},cn=async(q,me,be)=>{await te.teams.update(q,{managerId:me,managerType:be}),O()},Tl=async q=>{if(!le.trim()){hi(null);return}await te.teams.update(q,{name:le.trim()}),hi(null),O()},Ql=async(q,me)=>{me==="offline"?await te.agents.start(q):await te.agents.stop(q),m()},Os=(q,me)=>{Te(X("modals.removeFromTeam.title"),X("modals.removeFromTeam.message"),async()=>{await te.teams.removeMember(q,me),O(),_t()},X("common:remove"))},rs=(q,me,be,Ie)=>{Te(`${X("common:remove")} "${me}"?`,X(be==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async Ke=>{if(be==="agent"&&Ie){const Je=o.find(lt=>lt.type==="team"&<.teamId===Ie);Je?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+Je.channelKey)}if(be==="agent"){const Je=Ke?.purgeFiles??!1;await te.agents.remove(q,{purgeFiles:Je})}else await te.users.remove(q);m(),O(),x?.(),_t(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},X("common:remove"),be==="agent"?[{id:"purgeFiles",label:X("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},_s=q=>{if(q.isOrgSecretary||q.protected)return!0;if(q.teamId)return!1;const me=(q.role??"").toLowerCase().trim(),be=(q.name??"").trim();return be==="Secretary"||be==="秘书"||me==="secretary"||me.startsWith("secretary")},xr=(q,me,be)=>{const Ie=t.find(Ke=>Ke.id===me);Ie&&_s(Ie)||(wt.current={x:q.clientX,y:q.clientY},at.current=setTimeout(()=>{Oe({agentId:me,fromTeamId:be}),dt(!0)},200))},Uo=q=>{if(!wt.current||!at.current)return;const me=Math.abs(q.clientX-wt.current.x),be=Math.abs(q.clientY-wt.current.y);(me>5||be>5)&&(ht||(clearTimeout(at.current),at.current=null))},$l=async()=>{if(at.current&&(clearTimeout(at.current),at.current=null),wt.current=null,ht&&Se&&_e){const q=_e==="_ungrouped"?void 0:_e;try{if(Se.fromTeamId&&Se.fromTeamId!==q&&await te.teams.removeMember(Se.fromTeamId,Se.agentId),q&&q!==Se.fromTeamId){const me=t.find(be=>be.id===Se.agentId);await te.teams.addMember(q,Se.agentId,"agent")}O(),m(),_t()}catch(me){$e(X("batchAction.moveFailed",{error:me instanceof Error?me.message:String(me)}),"error")}}Oe(null),Fe(null),dt(!1)},zr=S.useMemo(()=>new Map(r.map(q=>[q.id,q])),[r]),xs=S.useMemo(()=>{const q=new Map,me=[];for(const be of t)if(be.teamId&&zr.has(be.teamId)){const Ie=q.get(be.teamId)??[];Ie.push(be),q.set(be.teamId,Ie)}else me.push(be);return{byTeam:q,ungrouped:me}},[t,zr]),Vn=(q,me)=>{const be=l==="direct"&&h===q.id,Ie=V.has(q.id),Ke=q.status==="offline",Je=Ol(q.status,!Ke&&se.has(q.id)),lt=Je.tone==="busy",Rt=Je.dotClass,cs=(void 0)?.managerId===q.id,bs=q.role?.toLowerCase().replace(/[-_]/g," ").trim(),ir=q.name.toLowerCase().trim(),zt=bs&&bs!==ir,ks=Us.get(q.id)||q.currentActivity?.label?.slice(0,60)||"",vs=lt?X("common:status.working"):q.status==="error"?X("common:status.error"):X(Ke?"common:status.offline":"common:status.online");return c.jsx("div",{className:`relative mb-0.5 ${ht&&Se?.agentId===q.id?"opacity-40":""}`,onPointerDown:es=>xr(es,q.id,me),onPointerMove:Uo,onPointerUp:$l,children:c.jsxs("button",{"data-l1-nav-id":`agent:${q.id}`,onClick:()=>{ht||f(q.id)},onContextMenu:es=>{if(!D)return;es.preventDefault();const nr=ge(es);xt(!1),vt(""),Ye({agentId:q.id,teamId:me,...nr})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${ae?"":"touch-none"} ${Ke?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${$i(be)}`,children:[c.jsx(Ns,{name:q.name,avatarUrl:q.avatarUrl,size:28,bgClass:Ke?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:q.name}),zt&&c.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",q.role,")"]}),cs&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),Ie&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-brand-500/20 text-brand-400 font-medium shrink-0 leading-relaxed",children:"EXT"}),Ke&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:X("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:ks||" "})]}),c.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(P?.get(q.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:P.get(q.id)}),q.mailboxDepth!=null&&q.mailboxDepth>0&&c.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:q.mailboxDepth}),c.jsx("span",{title:vs,onClick:es=>{es.stopPropagation(),k(q.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${Rt}`}),ae&&D&&c.jsx("span",{role:"button",tabIndex:0,onClick:es=>{if(es.stopPropagation(),He?.agentId===q.id)Ye(null);else{const nr=ge(es);xt(!1),vt(""),Ye({agentId:q.id,teamId:me,...nr})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:X("chat.moreOptions"),children:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},q.id)},jl=(q,me,be,Ie)=>{const Ke=ht&&_e===q&&Se?.fromTeamId!==q,Je=Xt===q,lt=g===q,Rt=P?(xs.byTeam.get(q)??[]).reduce((qt,qr)=>qt+(P.get(qr.id)??0),0):0,cs=o.find(qt=>qt.type==="team"&&qt.teamId===q)?.channelKey??Hv(q),bs=_?_[cs]??0:0,ir=Rt+bs,zt=xs.byTeam.get(q)??[],ks=zt.filter(qt=>qt.status==="offline").length,vs=zt.length,es=vs>0&&ks===vs,nr=ks>0&&!es,dn=es?"bg-gray-500":nr?"bg-amber-500":"bg-green-500";return c.jsxs("div",{"data-team-id":q,className:`mb-0.5 rounded-lg transition-all duration-500 ${Ke?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${Je?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{ht&&Fe(q)},onPointerLeave:()=>{ht&&_e===q&&Fe(null)},children:[c.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[c.jsxs("button",{"data-l1-nav-id":`team:${q}`,onClick:()=>{b&&q!=="_ungrouped"&&b(q)},onContextMenu:qt=>{if(!D||!me)return;qt.preventDefault();const qr=ge(qt);qe({teamId:q,...qr})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${es?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${$i(lt)}`,children:[c.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${es?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[me?.avatarUrl?c.jsx("img",{src:me.avatarUrl,alt:Ie,className:"w-full h-full rounded-full object-cover",onError:qt=>{qt.target.style.display="none",qt.target.nextElementSibling?.classList.remove("hidden")}}):null,c.jsxs("svg",{className:`w-3 h-3 ${me?.avatarUrl?"hidden":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),vs>0&&c.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${dn}`})]}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[Qt===q?c.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:le,onChange:qt=>$t(qt.target.value),onBlur:()=>Tl(q),onKeyDown:qt=>{qt.key==="Enter"&&Tl(q),qt.key==="Escape"&&hi(null)},onClick:qt=>qt.stopPropagation(),autoFocus:!0}):c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:Ie}),c.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[X("chat.members_other",{count:be}),es&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:X("common:status.offline")}),nr&&c.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[ks,"/",vs]})]})]}),ir>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:ir}),c.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),D&&me&&c.jsx("button",{onClick:qt=>{if(qt.stopPropagation(),G?.teamId===q)qe(null);else{const qr=ge(qt);qe({teamId:q,...qr})}},className:"w-7 h-7 flex items-center justify-center text-fg-muted hover:text-fg-primary rounded-md hover:bg-white/[0.08] transition-colors shrink-0",title:X("chat.moreOptions"),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),Ke&&ht&&c.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:X("chat.dropHere")})]},q)},is=S.useMemo(()=>{const q=new Map,me=[],be=[],Ie=[];for(const Ke of o)if(Ke.channelKey.startsWith("dm:a2a:"))Ie.push(Ke);else if(Ke.type==="custom")be.push(Ke);else if(Ke.teamId){const Je=q.get(Ke.teamId)??[];Je.push(Ke),q.set(Ke.teamId,Je)}else{const Je=r.find(lt=>Ke.name.toLowerCase().includes(lt.name.toLowerCase())||lt.name.toLowerCase().includes(Ke.name.toLowerCase()));if(Je){const lt=q.get(Je.id)??[];lt.push(Ke),q.set(Je.id,lt)}else me.push(Ke)}return{byTeam:q,unmatched:me,custom:be,dmChannels:Ie}},[o,r]),Qr=S.useMemo(()=>{const q=new Map;let me=0;for(const Ke of xs.ungrouped)q.set(Ke.id,me++);for(const Ke of r)for(const Je of xs.byTeam.get(Ke.id)??[])q.set(Je.id,me++);const be=Number.MAX_SAFE_INTEGER,Ie=Ke=>{const Je=Ke.split(":");return Je.length<4?[]:[Je[2],Je[3]].map(lt=>q.get(lt)??be).sort((lt,Rt)=>lt-Rt)};return[...is.dmChannels].sort((Ke,Je)=>{const lt=Ie(Ke.channelKey),Rt=Ie(Je.channelKey),Ot=lt[0]??be,cs=lt[1]??be,bs=Rt[0]??be,ir=Rt[1]??be;return Ot!==bs?Ot-bs:cs!==ir?cs-ir:Ke.channelKey.localeCompare(Je.channelKey)})},[is.dmChannels,xs,r]),[hn,jt]=S.useState(!1),br=l==="channel"&&is.dmChannels.some(q=>q.channelKey===d);S.useEffect(()=>{br&&jt(!0)},[br]);const Rl=S.useMemo(()=>{const q=[];e&&q.push({kind:"dm",id:`dm:${e.id}`,userId:e.id});for(const be of i)be.id!==e?.id&&q.push({kind:"dm",id:`dm:${be.id}`,userId:be.id});for(const be of is.custom)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});for(const be of is.unmatched)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});const me=xs.ungrouped.length>0?xs.ungrouped:r.length===0?t:[];for(const be of me)q.push({kind:"agent",id:`agent:${be.id}`,agentId:be.id});for(const be of r)q.push({kind:"team",id:`team:${be.id}`,teamId:be.id});if(hn)for(const be of Qr)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});return q},[e,i,is,xs,r,t,hn]),El=S.useRef(Rl);El.current=Rl;const Al=S.useCallback(q=>{q.kind==="dm"?v(q.userId):q.kind==="channel"?p(q.channelKey):q.kind==="agent"?f(q.agentId):q.kind==="team"&&b?.(q.teamId),requestAnimationFrame(()=>{document.querySelector(`[data-l1-nav-id="${q.id}"]`)?.scrollIntoView({block:"nearest"})})},[v,p,f,b]);S.useEffect(()=>{if(B||ae||!j||L)return;const q=me=>{const be=W?.keyboardPane??"content";if(be==="l0"||be==="l2"||me.metaKey||me.ctrlKey||me.altKey||Vm(me.target))return;const Ie=me.key.length===1?me.key.toLowerCase():me.key;if(Ie==="h"||Ie==="ArrowLeft"){if(be!=="l1")return;me.preventDefault(),me.stopPropagation(),W?.setL0FocusPageId(Yt.TEAM),W?.setLeftCollapsed(!1),W?.setKeyboardPane("l0");return}if(Ie==="l"||Ie==="ArrowRight"){if(be!=="l1")return;me.preventDefault(),me.stopPropagation(),F&&W?.setKeyboardPane("l2");return}if(be!=="l1"&&!(U&&(Ie==="j"||Ie==="k"||Ie==="ArrowDown"||Ie==="ArrowUp")))return;const Ke=Ie==="j"||Ie==="ArrowDown"?1:Ie==="k"||Ie==="ArrowUp"?-1:0;if(!Ke)return;me.preventDefault(),me.stopPropagation(),W?.setKeyboardPane("l1");const Je=El.current;if(Je.length===0)return;let lt=-1;if(l==="dm"){const Ot=u||e?.id;Ot&&(lt=Je.findIndex(cs=>cs.kind==="dm"&&cs.userId===Ot))}else l==="direct"?lt=Je.findIndex(Ot=>Ot.kind==="agent"&&Ot.agentId===h):l==="channel"&&(lt=Je.findIndex(Ot=>Ot.kind==="channel"&&Ot.channelKey===d),lt<0&&g&&(lt=Je.findIndex(Ot=>Ot.kind==="team"&&Ot.teamId===g)));lt<0&&(lt=Ke>0?-1:0);const Rt=Math.max(0,Math.min(Je.length-1,lt+Ke));Al(Je[Rt])};return document.addEventListener("keydown",q,!0),()=>document.removeEventListener("keydown",q,!0)},[B,ae,j,L,W,U,F,l,u,e?.id,h,d,g,Al]);const $i=q=>q?U?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60";return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l1",className:`bg-surface-primary flex flex-col ${T!=null?"shrink-0":"flex-1 min-w-0"} ${U?"ring-1 ring-inset ring-brand-500/30":""}`,style:L?{display:"none"}:T!=null?{width:T}:void 0,children:[c.jsxs("div",{"data-electron-drag":!0,className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[ae&&c.jsx(Vk,{}),!ae&&M&&c.jsx("button",{onClick:M,className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 bg-brand-500/15 text-brand-500 hover:bg-brand-500/25",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsx("h2",{className:"text-lg font-semibold",children:X("chat.title")}),D&&c.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:Ze,children:[c.jsxs("button",{onClick:()=>ut(!Bt),className:"flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-fg-secondary hover:text-fg-primary bg-surface-elevated/60 hover:bg-surface-elevated rounded-md transition-colors",children:[c.jsx("span",{className:"text-brand-500",children:"+"})," ",X("chat.manage"),c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${Bt?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),Bt&&c.jsxs("div",{ref:q=>{if(!q)return;const me=q.getBoundingClientRect(),be=window.innerWidth,Ie=8;me.right>be-Ie&&(q.style.left="auto",q.style.right="0"),me.left<Ie&&(q.style.left="0",q.style.right="auto")},className:"absolute right-0 top-full mt-1 w-48 max-w-[calc(100vw-1rem)] bg-surface-elevated border border-border-default rounded-lg shadow-xl z-50 overflow-hidden",children:[c.jsxs("button",{onClick:()=>{ut(!1),ye("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),c.jsx("circle",{cx:"12",cy:"5",r:"2"}),c.jsx("path",{d:"M12 7v4"}),c.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),c.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),X("chat.addAgent")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.addAgentDesc")})]}),c.jsxs("button",{onClick:()=>{ut(!1),ye("team")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),c.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),X("chat.newTeam")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.newTeamDesc")})]}),c.jsxs("button",{onClick:()=>{ut(!1),oe(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-green-600 hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M20 8v6"}),c.jsx("path",{d:"M23 11h-6"})]}),X("chat.addHuman")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.addHumanDesc")})]}),c.jsxs("button",{onClick:()=>{ut(!1),Qe(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),c.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),X("chat.newGroupChat")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.newGroupChatDesc")})]}),Xe!==null&&c.jsxs("button",{onClick:()=>{ut(!1),ze()},disabled:De,className:`w-full text-left px-4 py-2.5 text-xs hover:bg-surface-elevated border-t border-border-default transition-colors disabled:opacity-50 ${Xe?"text-green-600":"text-red-500"}`,children:[c.jsx("div",{className:"font-medium flex items-center gap-1.5",children:Xe?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",X("chat.resume")]}):c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",X("contextMenu.stopAll")]})}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X(Xe?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),c.jsxs("div",{ref:At,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.people")}),e&&c.jsxs("button",{"data-l1-nav-id":`dm:${e.id}`,onClick:()=>v(e.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${$i(l==="dm"&&(u===e.id||!u))}`,children:[c.jsx(Ns,{name:e.name,avatarUrl:e.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:e.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:X("chat.myNotes")})]}),c.jsx("span",{className:"text-fg-secondary shrink-0",children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),i.filter(q=>q.id!==e?.id).map(q=>{const me=e?.id?`dm:${[e.id,q.id].sort().join(":")}`:"",be=me&&_?_[me]??0:0;return c.jsxs("button",{"data-l1-nav-id":`dm:${q.id}`,onClick:()=>v(q.id),onContextMenu:Ie=>{if(!D||q.id===e?.id)return;Ie.preventDefault();const Ke=ge(Ie);Et({userId:q.id,...Ke})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${l==="dm"&&u===q.id?U?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[c.jsx(Ns,{name:q.name,avatarUrl:q.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:q.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:q.email||q.role})]}),be>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:be}):c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},q.id)})]}),is.custom.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:X("chat.groups")}),is.custom.map(q=>{const me=l==="channel"&&d===q.channelKey;return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),onContextMenu:be=>{be.preventDefault();const Ie=ge(be);yt({gcId:q.id,...Ie})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${$i(me)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:q.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:X("chat.members_other",{count:q.memberCount??0})})]})]},q.id)})]}),E?c.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((q,me)=>c.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[c.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),c.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),c.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},me))}):t.length===0&&r.length===0?c.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:X("chat.noAgentsYet")}):null,is.unmatched.map(q=>{const me=_?.[q.channelKey]??0;return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${$i(l==="channel"&&d===q.channelKey)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:q.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:X("chat.groupChat")})]}),me>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:me}):q.memberCount!==void 0&&q.memberCount>0?c.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:q.memberCount}):null]},q.id)}),xs.ungrouped.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.agents")}),xs.ungrouped.map(q=>Vn(q))]}),r.length>0&&c.jsxs("div",{className:"mb-2",ref:us,children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.teams")}),r.map(q=>{const me=xs.byTeam.get(q.id)??[],be=q.members?.length||me.length;return jl(q.id,q,be,q.name)})]}),r.length===0&&xs.ungrouped.length===0&&t.length>0&&t.map(q=>Vn(q)),Qr.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsxs("button",{onClick:()=>jt(q=>!q),className:"w-full flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-semibold text-fg-muted uppercase tracking-wider hover:text-fg-secondary transition-colors",children:[c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${hn?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),X("chat.agentDMs"),c.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:Qr.length})]}),hn&&Qr.map(q=>{const me=l==="channel"&&d===q.channelKey,be=_?.[q.channelKey]??0,Ie=q.name.replace(/^DM:\s*/,"");return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 pl-5 py-1.5 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${$i(me)}`,children:[c.jsx("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay/60 text-fg-tertiary text-[9px]",children:c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:Ie}),be>0&&c.jsx("span",{className:"min-w-[14px] h-[14px] flex items-center justify-center text-[8px] font-semibold text-white bg-red-500 rounded-full px-0.5 leading-none",children:be})]},q.id)})]})]})]}),R&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:R,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),G&&(()=>{const q=xs.byTeam.get(G.teamId)??[],me=q.some(Ie=>Ie.status==="offline"),be=q.some(Ie=>Ie.status!=="offline");return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:G.x,top:G.y},onClick:Ie=>Ie.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{const Ie=zr.get(G.teamId);Ie&&(hi(G.teamId),$t(Ie.name)),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),X("contextMenu.renameTeam")]}),me&&c.jsxs("button",{onClick:()=>{Fo(G.teamId,"start"),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),X("contextMenu.startAll")]}),be&&c.jsxs("button",{onClick:()=>{Fo(G.teamId,"stop"),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),X("contextMenu.stopAll")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{qe(null),Lr.navigate(Yt.STORE)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),X("chat.addAgent")]}),fe.length>0&&c.jsxs("button",{onClick:()=>{qe(null),pe(G.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),c.jsx("polyline",{points:"17 11 19 13 23 9"})]}),X("contextMenu.addExisting")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{const Ie=zr.get(G.teamId);Ie&&ln(G.teamId,Ie.name),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.deleteTeam")]})]})})(),He&&(()=>{const q=t.find(Je=>Je.id===He.agentId);if(!q||!D)return null;const be=(He.teamId?zr.get(He.teamId):void 0)?.managerId===q.id,Ie=q.id===e?.id,Ke=_s(q);return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:He.x,top:He.y,maxHeight:Math.max(160,window.innerHeight-He.y-8)},onClick:Je=>Je.stopPropagation(),children:[Ke&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:X("contextMenu.orgSecretaryProtected")}),c.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),c.jsxs("button",{onClick:()=>{Ye(null),k(q.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),X("contextMenu.viewProfile")]}),q.status==="offline"?c.jsxs("button",{onClick:()=>{Ql(q.id,"offline"),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),X("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{Ql(q.id,q.status??"idle"),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),X("contextMenu.stop")]}),!Ke&&He.teamId&&!be&&c.jsxs("button",{onClick:()=>{cn(He.teamId,q.id,"agent"),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),X("contextMenu.setAsManager")]}),!Ke&&He.teamId&&c.jsxs("button",{onClick:()=>{Os(He.teamId,q.id),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),X("contextMenu.removeFromTeam")]}),!Ke&&(()=>{const Je=r.filter(Ot=>Ot.id!==He.teamId);if(Je.length===0)return null;const lt=bt.trim().toLowerCase(),Rt=lt?Je.filter(Ot=>Ot.name.toLowerCase().includes(lt)):Je;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>xt(Ot=>!Ot),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:X("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${pt?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),pt&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:Ot=>Ot.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:bt,onChange:Ot=>vt(Ot.target.value),onKeyDown:Ot=>Ot.stopPropagation(),placeholder:X("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:Rt.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:X("contextMenu.moveToEmpty")}):Rt.map(Ot=>c.jsx("button",{type:"button",onClick:async()=>{He.teamId&&await te.teams.removeMember(He.teamId,q.id),await te.teams.addMember(Ot.id,q.id,"agent"),O(),m(),_t(),Ye(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:Ot.name,children:Ot.name},Ot.id))})]})]})})(),!Ke&&!Ie&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{rs(q.id,q.name,"agent",He.teamId),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.removeFromOrg")]})]})]})})(),Pe&&(()=>{const q=i.find(me=>me.id===Pe.userId);return!q||!D?null:c.jsx("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:Pe.x,top:Pe.y},onClick:me=>me.stopPropagation(),children:c.jsxs("button",{onClick:()=>{rs(q.id,q.name,"human"),Et(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.removeFromOrg")]})})})(),A&&c.jsx(D2,{onClose:()=>J(!1),onCreate:async(q,me)=>{try{const{team:be}=await te.teams.create(q,me);J(!1),O(),ot(be.id),setTimeout(()=>{document.querySelector(`[data-team-id="${be.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>ot(null),3e3)}catch(be){$e(X("chat.failedToCreateTeam",{message:be instanceof Error?be.message:String(be)}),"error")}}}),Y&&c.jsx(I2,{onClose:()=>{oe(!1),x?.()},onAdd:async(q,me,be)=>{const{inviteToken:Ie}=await te.users.create(q,me,void 0,be);return x?.(),{inviteToken:Ie}}}),K!==null&&c.jsx(B2,{teamId:K,ungrouped:fe,onClose:()=>pe(null),onAdd:async(q,me)=>{await te.teams.addMember(K,q,me),pe(null),O(),_t()}}),je&&c.jsx(W2,{onClose:()=>we(!1),onConnected:()=>{we(!1),m(),O()}}),rt&&(()=>{const q=o.find(me=>me.id===rt.gcId);return q?c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:rt.x,top:rt.y},onClick:me=>me.stopPropagation(),children:[q.type==="custom"&&c.jsxs("button",{onClick:()=>{yt(null),C?C(q.channelKey):p(q.channelKey)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),X("contextMenu.manageMembers")]}),c.jsxs("button",{onClick:async()=>{yt(null),Te(X("modals.deleteGroupChat.title"),X("modals.deleteGroupChat.message",{name:q.name}),async()=>{await te.groupChats.delete(q.id),y()},X("modals.deleteGroupChat.confirm"))},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("modals.deleteGroupChat.menuLabel")]})]}):null})(),Ge&&c.jsx(eP,{agents:t,humans:i,authUser:e,onClose:()=>Qe(!1),onCreate:async(q,me,be,Ie)=>{await te.groupChats.create({name:q,memberIds:me,memberTypes:be,memberNames:Ie,creatorId:e?.id,creatorName:e?.name}),Qe(!1),y()}}),Ee&&c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>ye(null),children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:q=>q.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:X(Ee==="agent"?"chat.addAgent":"chat.newTeam")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:X("chat.methodChoiceSubtitle")})]}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsxs("button",{onClick:()=>{const q=Ee;ye(null);const me=t.find(be=>be.role==="secretary")??t.find(be=>be.name?.toLowerCase().includes("secretary"));me?(f(me.id),Lr.navigate(Yt.TEAM,{agentId:me.id,prefillMessage:X(q==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):q==="agent"?Lr.navigate(Yt.STORE):J(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-brand-500/30 bg-brand-500/5 hover:bg-brand-500/10 transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-brand-500",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}),c.jsx("path",{d:"M20 3v4"}),c.jsx("path",{d:"M22 5h-4"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:X("chat.methodSecretary")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:X("chat.methodSecretaryDesc")})]}),c.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500 font-medium shrink-0",children:X("chat.recommended")})]}),c.jsxs("button",{onClick:()=>{const q=Ee;ye(null),q==="agent"?Lr.navigate(Yt.STORE):J(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:bg-surface-overlay transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-fg-secondary",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:X("chat.methodManual")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:X(Ee==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),c.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:c.jsx("button",{onClick:()=>ye(null),className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:X("common:cancel")})})]})}),Ve&&c.jsx(Wo,{title:Ve.title,message:Ve.message,confirmLabel:Ve.confirmLabel,checkboxes:Ve.checkboxes,onConfirm:q=>{Ve.onConfirm(q),ee(null)},onCancel:()=>ee(null)}),he&&c.jsx("div",{className:`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-xl text-sm font-medium ${he.type==="error"?"bg-red-500/10 text-red-500 border border-red-500/30":"bg-surface-elevated/95 text-fg-primary border border-border-default/50"}`,children:he.message})]})});function i0({team:s,agents:e,humans:t,authUser:r,groupChat:i,chatMode:n,selectedAgent:a,activeChannel:o,activeDmUserId:l,teams:h,onSelectAgent:d,onSelectChannel:u,onSelectDm:f,onBack:p,onViewProfile:v,onRefreshAgents:b,onRefreshTeams:g,unreadByAgent:O,width:m,onResizeStart:x,focused:y}){const{t:k}=Pt(["team","common"]),C=zh(),P=Zm(Yt.TEAM),_=r?.role==="owner"||r?.role==="admin";ah();const T=S.useMemo(()=>e.filter(Y=>Y.teamId===s.id),[e,s.id]),R=S.useMemo(()=>{const Y=new Set((s.members??[]).filter(oe=>oe.type==="human").map(oe=>oe.id));return t.filter(oe=>Y.has(oe.id))},[s.members,t]),L=i&&n==="channel"&&o===i.channelKey,M=S.useMemo(()=>{const Y=[];i&&Y.push({kind:"channel",id:`channel:${i.channelKey}`,channelKey:i.channelKey});for(const oe of T)Y.push({kind:"agent",id:`agent:${oe.id}`,agentId:oe.id});for(const oe of R)Y.push({kind:"dm",id:`dm:${oe.id}`,userId:oe.id});return Y},[i,T,R]),E=S.useRef(M);E.current=M;const B=S.useCallback(Y=>{Y.kind==="channel"?u(Y.channelKey):Y.kind==="agent"?d(Y.agentId):f(Y.userId),requestAnimationFrame(()=>{document.querySelector(`[data-l2-nav-id="${Y.id}"]`)?.scrollIntoView({block:"nearest"})})},[u,d,f]);S.useEffect(()=>{if(!P)return;const Y=oe=>{if((C?.keyboardPane??"content")!=="l2"||oe.metaKey||oe.ctrlKey||oe.altKey||Vm(oe.target))return;const pe=oe.key.length===1?oe.key.toLowerCase():oe.key;if(pe==="h"||pe==="ArrowLeft"){oe.preventDefault(),oe.stopPropagation(),C?.setKeyboardPane("l1");return}if(pe==="l"||pe==="ArrowRight"){oe.preventDefault(),oe.stopPropagation();return}const je=pe==="j"||pe==="ArrowDown"?1:pe==="k"||pe==="ArrowUp"?-1:0;if(!je)return;oe.preventDefault(),oe.stopPropagation();const we=E.current;if(we.length===0)return;let Ge=-1;n==="channel"?Ge=we.findIndex(Ee=>Ee.kind==="channel"&&Ee.channelKey===o):n==="direct"?Ge=we.findIndex(Ee=>Ee.kind==="agent"&&Ee.agentId===a):n==="dm"&&l&&(Ge=we.findIndex(Ee=>Ee.kind==="dm"&&Ee.userId===l)),Ge<0&&(Ge=je>0?-1:0);const Qe=Math.max(0,Math.min(we.length-1,Ge+je));B(we[Qe])};return document.addEventListener("keydown",Y,!0),()=>document.removeEventListener("keydown",Y,!0)},[P,C,n,o,a,l,B]);const U=Y=>Y?y?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60",[F,X]=S.useState(null),[ae,j]=S.useState(!1),[W,D]=S.useState(""),[V,se]=S.useState(null),fe=(Y,oe,K,pe,je)=>{se({title:Y,message:oe,onConfirm:K,confirmLabel:pe,checkboxes:je})},z=S.useCallback((Y,oe=176,K=220)=>{const pe=window.innerWidth,je=window.innerHeight,we=8;let Ge=Y.clientX,Qe=Y.clientY;return Ge+oe>pe-we&&(Ge=Math.max(we,pe-oe-we)),Qe+K>je-we&&(Qe=Math.max(we,je-K-we)),Ge=Math.max(we,Math.min(Ge,pe-oe-we)),Qe=Math.max(we,Math.min(Qe,je-K-we)),{x:Ge,y:Qe}},[]);S.useEffect(()=>{if(!F)return;const Y=()=>X(null),oe=setTimeout(()=>document.addEventListener("click",Y),0);return()=>{clearTimeout(oe),document.removeEventListener("click",Y)}},[F]);const re=S.useCallback(async(Y,oe)=>{oe==="offline"?await te.agents.start(Y):await te.agents.stop(Y),b()},[b]),Z=S.useCallback(async Y=>{await te.teams.update(s.id,{managerId:Y,managerType:"agent"}),g()},[s.id,g]),A=S.useCallback(async Y=>{await te.teams.removeMember(s.id,Y),g(),b()},[s.id,g,b]),J=S.useCallback(async(Y,oe)=>{await te.teams.removeMember(s.id,Y),await te.teams.addMember(oe,Y,"agent"),g(),b()},[s.id,g,b]);return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l2",className:`bg-surface-primary flex flex-col shrink-0 ${y?"ring-1 ring-inset ring-brand-500/30":""}`,style:m!=null?{width:m}:{width:260},children:[c.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[c.jsx("button",{onClick:p,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:k("common:back",{defaultValue:"Back"}),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"truncate font-semibold text-sm",children:s.name}),s.description&&c.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:s.description})]})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[i&&c.jsxs("div",{className:"mb-3",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:k("chat.groupChat",{defaultValue:"Group Chat"})}),c.jsxs("button",{"data-l2-nav-id":`channel:${i.channelKey}`,onClick:()=>u(i.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${U(!!L)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:s.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:k("chat.members_other",{count:i.memberCount||T.length+R.length})})]})]})]}),T.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[k("chat.agents",{defaultValue:"Agents"}),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:T.length})]}),T.map(Y=>{const oe=n==="direct"&&a===Y.id,K=s.managerId===Y.id,pe=Y.status==="offline",je=Ol(Y.status,hs.isAgentStreaming(Y.id)).dotClass;return c.jsxs("button",{"data-l2-nav-id":`agent:${Y.id}`,onClick:()=>d(Y.id),onContextMenu:we=>{if(!_)return;we.preventDefault();const Ge=z(we);j(!1),D(""),X({agentId:Y.id,...Ge})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${pe?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${U(oe)}`,children:[c.jsx(Ns,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:pe?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:Y.name}),K&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),pe&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:k("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:Y.role||" "})]}),(O?.get(Y.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:O.get(Y.id)}),c.jsx("span",{title:Y.status,onClick:we=>{we.stopPropagation(),v(Y.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${je}`})]},Y.id)})]}),R.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[k("chat.people"),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:R.length})]}),R.map(Y=>{const oe=Y.id===r?.id,K=n==="dm"&&l===Y.id;return c.jsxs("button",{"data-l2-nav-id":`dm:${Y.id}`,onClick:()=>f(Y.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${U(K)}`,children:[c.jsx(Ns,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[Y.name,oe?` (${k("chat.you",{defaultValue:"You"})})`:""]}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:Y.email||Y.role})]}),c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},Y.id)})]}),T.length===0&&R.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:k("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),x&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:x,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),F&&(()=>{const Y=T.find(K=>K.id===F.agentId);if(!Y||!_)return null;const oe=s.managerId===Y.id;return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:F.x,top:F.y,maxHeight:Math.max(160,window.innerHeight-F.y-8)},onClick:K=>K.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{X(null),v(Y.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),k("contextMenu.viewProfile")]}),Y.status==="offline"?c.jsxs("button",{onClick:()=>{re(Y.id,"offline"),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),k("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{re(Y.id,Y.status??"idle"),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),k("contextMenu.stop")]}),!oe&&c.jsxs("button",{onClick:()=>{Z(Y.id),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),k("contextMenu.setAsManager")]}),c.jsxs("button",{onClick:()=>{A(Y.id),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),k("contextMenu.removeFromTeam")]}),(()=>{const K=h.filter(we=>we.id!==s.id);if(K.length===0)return null;const pe=W.trim().toLowerCase(),je=pe?K.filter(we=>we.name.toLowerCase().includes(pe)):K;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>j(we=>!we),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:k("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${ae?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),ae&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:we=>we.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:W,onChange:we=>D(we.target.value),onKeyDown:we=>we.stopPropagation(),placeholder:k("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:je.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:k("contextMenu.moveToEmpty")}):je.map(we=>c.jsx("button",{type:"button",onClick:()=>{J(Y.id,we.id),X(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:we.name,children:we.name},we.id))})]})]})})(),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{fe(`${k("common:remove")} "${Y.name}"?`,k("modals.removeAgent.message"),async K=>{const pe=K?.purgeFiles??!1;i?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+i.channelKey),await te.agents.remove(Y.id,{purgeFiles:pe}),b(),X(null)},k("common:remove"),[{id:"purgeFiles",label:k("modals.removeAgent.purgeFiles"),defaultChecked:!1}])},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),k("contextMenu.removeFromOrg")]})]})})(),V&&c.jsx(Wo,{title:V.title,message:V.message,confirmLabel:V.confirmLabel,checkboxes:V.checkboxes,onConfirm:Y=>{V.onConfirm(Y),se(null)},onCancel:()=>se(null)})]})}function Pf(){return Pf=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(s[r]=t[r])}return s},Pf.apply(null,arguments)}function sP(s,e){if(s==null)return{};var t={};for(var r in s)if({}.hasOwnProperty.call(s,r)){if(e.indexOf(r)!==-1)continue;t[r]=s[r]}return t}let Tf=[],Yv=[];(()=>{let s="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<s.length;e++)(e%2?Yv:Tf).push(t=t+s[e])})();function rP(s){if(s<768)return!1;for(let e=0,t=Tf.length;;){let r=e+t>>1;if(s<Tf[r])t=r;else if(s>=Yv[r])e=r+1;else return!0;if(e==t)return!1}}function n0(s){return s>=127462&&s<=127487}const o0=8205;function iP(s,e,t=!0,r=!0){return(t?Gv:nP)(s,e,r)}function Gv(s,e,t){if(e==s.length)return e;e&&Kv(s.charCodeAt(e))&&Jv(s.charCodeAt(e-1))&&e--;let r=mu(s,e);for(e+=a0(r);e<s.length;){let i=mu(s,e);if(r==o0||i==o0||t&&rP(i))e+=a0(i),r=i;else if(n0(i)){let n=0,a=e-2;for(;a>=0&&n0(mu(s,a));)n++,a-=2;if(n%2==0)break;e+=2}else break}return e}function nP(s,e,t){for(;e>1;){let r=Gv(s,e-2,t);if(r<e)return r;e--}return 0}function mu(s,e){let t=s.charCodeAt(e);if(!Jv(t)||e+1==s.length)return t;let r=s.charCodeAt(e+1);return Kv(r)?(t-55296<<10)+(r-56320)+65536:t}function Kv(s){return s>=56320&&s<57344}function Jv(s){return s>=55296&&s<56320}function a0(s){return s<65536?1:2}let Lt=class ey{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,r){[e,t]=jo(this,e,t);let i=[];return this.decompose(0,e,i,2),r.length&&r.decompose(0,r.length,i,3),this.decompose(t,this.length,i,1),Jr.from(i,this.length-(t-e)+r.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=jo(this,e,t);let r=[];return this.decompose(e,t,r,0),Jr.from(r,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),r=this.length-this.scanIdentical(e,-1),i=new Da(this),n=new Da(e);for(let a=t,o=t;;){if(i.next(a),n.next(a),a=0,i.lineBreak!=n.lineBreak||i.done!=n.done||i.value!=n.value)return!1;if(o+=i.value.length,i.done||o>=r)return!0}}iter(e=1){return new Da(this,e)}iterRange(e,t=this.length){return new ty(this,e,t)}iterLines(e,t){let r;if(e==null)r=this.iter();else{t==null&&(t=this.lines+1);let i=this.line(e).from;r=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new sy(r)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?ey.empty:e.length<=32?new ls(e):Jr.from(ls.split(e,[]))}};class ls extends Lt{constructor(e,t=oP(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,r,i){for(let n=0;;n++){let a=this.text[n],o=i+a.length;if((t?r:o)>=e)return new aP(i,o,r,a);i=o+1,r++}}decompose(e,t,r,i){let n=e<=0&&t>=this.length?this:new ls(l0(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let a=r.pop(),o=Xc(n.text,a.text.slice(),0,n.length);if(o.length<=32)r.push(new ls(o,a.length+n.length));else{let l=o.length>>1;r.push(new ls(o.slice(0,l)),new ls(o.slice(l)))}}else r.push(n)}replace(e,t,r){if(!(r instanceof ls))return super.replace(e,t,r);[e,t]=jo(this,e,t);let i=Xc(this.text,Xc(r.text,l0(this.text,0,e)),t),n=this.length+r.length-(t-e);return i.length<=32?new ls(i,n):Jr.from(ls.split(i,[]),n)}sliceString(e,t=this.length,r=`
|
|
5
|
+
color: hsl(${Math.max(0,Math.min(120-120*g,120))}deg 100% 31%);`,t?.key)}return t?.onChange&&!(n&&t.skipInitialOnChange)&&t.onChange(i),n=!1,i}return a.updateDeps=o=>{r=o},a}function DO(s,e){if(s===void 0)throw new Error("Unexpected undefined");return s}const UC=(s,e)=>Math.abs(s-e)<1.01,HC=(s,e,t)=>{let r;return function(...i){s.clearTimeout(r),r=s.setTimeout(()=>e.apply(this,i),t)}},IO=s=>{const{offsetWidth:e,offsetHeight:t}=s;return{width:e,height:t}},YC=s=>s,GC=s=>{const e=Math.max(s.startIndex-s.overscan,0),t=Math.min(s.endIndex+s.overscan,s.count-1),r=[];for(let i=e;i<=t;i++)r.push(i);return r},KC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;const i=a=>{const{width:o,height:l}=a;e({width:Math.round(o),height:Math.round(l)})};if(i(IO(t)),!r.ResizeObserver)return()=>{};const n=new r.ResizeObserver(a=>{const o=()=>{const l=a[0];if(l?.borderBoxSize){const h=l.borderBoxSize[0];if(h){i({width:h.inlineSize,height:h.blockSize});return}}i(IO(t))};s.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(o):o()});return n.observe(t,{box:"border-box"}),()=>{n.unobserve(t)}},BO={passive:!0},WO=typeof window>"u"?!0:"onscrollend"in window,JC=(s,e)=>{const t=s.scrollElement;if(!t)return;const r=s.targetWindow;if(!r)return;let i=0;const n=s.options.useScrollendEvent&&WO?()=>{}:HC(r,()=>{e(i,!1)},s.options.isScrollingResetDelay),a=d=>()=>{const{horizontal:u,isRtl:f}=s.options;i=u?t.scrollLeft*(f&&-1||1):t.scrollTop,n(),e(i,d)},o=a(!0),l=a(!1);t.addEventListener("scroll",o,BO);const h=s.options.useScrollendEvent&&WO;return h&&t.addEventListener("scrollend",l,BO),()=>{t.removeEventListener("scroll",o),h&&t.removeEventListener("scrollend",l)}},e2=(s,e,t)=>{if(e?.borderBoxSize){const r=e.borderBoxSize[0];if(r)return Math.round(r[t.options.horizontal?"inlineSize":"blockSize"])}return s[t.options.horizontal?"offsetWidth":"offsetHeight"]},t2=(s,{adjustments:e=0,behavior:t},r)=>{var i,n;const a=s+e;(n=(i=r.scrollElement)==null?void 0:i.scrollTo)==null||n.call(i,{[r.options.horizontal?"left":"top"]:a,behavior:t})};class s2{constructor(e){this.unsubs=[],this.scrollElement=null,this.targetWindow=null,this.isScrolling=!1,this.scrollState=null,this.measurementsCache=[],this.itemSizeCache=new Map,this.laneAssignments=new Map,this.pendingMeasuredCacheIndexes=[],this.prevLanes=void 0,this.lanesChangedFlag=!1,this.lanesSettling=!1,this.scrollRect=null,this.scrollOffset=null,this.scrollDirection=null,this.scrollAdjustments=0,this.elementsCache=new Map,this.now=()=>{var t,r,i;return((i=(r=(t=this.targetWindow)==null?void 0:t.performance)==null?void 0:r.now)==null?void 0:i.call(r))??Date.now()},this.observer=(()=>{let t=null;const r=()=>t||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:t=new this.targetWindow.ResizeObserver(i=>{i.forEach(n=>{const a=()=>{const o=n.target,l=this.indexFromElement(o);if(!o.isConnected){this.observer.unobserve(o);return}this.shouldMeasureDuringScroll(l)&&this.resizeItem(l,this.options.measureElement(o,n,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(a):a()})}));return{disconnect:()=>{var i;(i=r())==null||i.disconnect(),t=null},observe:i=>{var n;return(n=r())==null?void 0:n.observe(i,{box:"border-box"})},unobserve:i=>{var n;return(n=r())==null?void 0:n.unobserve(i)}}})(),this.range=null,this.setOptions=t=>{Object.entries(t).forEach(([r,i])=>{typeof i>"u"&&delete t[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:YC,rangeExtractor:GC,onChange:()=>{},measureElement:e2,initialRect:{width:0,height:0},scrollMargin:0,gap:0,indexAttribute:"data-index",initialMeasurementsCache:[],lanes:1,isScrollingResetDelay:150,enabled:!0,isRtl:!1,useScrollendEvent:!1,useAnimationFrameWithResizeObserver:!1,laneAssignmentMode:"estimate",...t}},this.notify=t=>{var r,i;(i=(r=this.options).onChange)==null||i.call(r,this,t)},this.maybeNotify=co(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),t=>{this.notify(t)},{key:!1,debug:()=>this.options.debug,initialDeps:[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]}),this.cleanup=()=>{this.unsubs.filter(Boolean).forEach(t=>t()),this.unsubs=[],this.observer.disconnect(),this.rafId!=null&&this.targetWindow&&(this.targetWindow.cancelAnimationFrame(this.rafId),this.rafId=null),this.scrollState=null,this.scrollElement=null,this.targetWindow=null},this._didMount=()=>()=>{this.cleanup()},this._willUpdate=()=>{var t;const r=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==r){if(this.cleanup(),!r){this.maybeNotify();return}this.scrollElement=r,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((t=this.scrollElement)==null?void 0:t.window)??null,this.elementsCache.forEach(i=>{this.observer.observe(i)}),this.unsubs.push(this.options.observeElementRect(this,i=>{this.scrollRect=i,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(i,n)=>{this.scrollAdjustments=0,this.scrollDirection=n?this.getScrollOffset()<i?"forward":"backward":null,this.scrollOffset=i,this.isScrolling=n,this.scrollState&&this.scheduleScrollReconcile(),this.maybeNotify()})),this._scrollToOffset(this.getScrollOffset(),{adjustments:void 0,behavior:void 0})}},this.rafId=null,this.getSize=()=>this.options.enabled?(this.scrollRect=this.scrollRect??this.options.initialRect,this.scrollRect[this.options.horizontal?"width":"height"]):(this.scrollRect=null,0),this.getScrollOffset=()=>this.options.enabled?(this.scrollOffset=this.scrollOffset??(typeof this.options.initialOffset=="function"?this.options.initialOffset():this.options.initialOffset),this.scrollOffset):(this.scrollOffset=null,0),this.getFurthestMeasurement=(t,r)=>{const i=new Map,n=new Map;for(let a=r-1;a>=0;a--){const o=t[a];if(i.has(o.lane))continue;const l=n.get(o.lane);if(l==null||o.end>l.end?n.set(o.lane,o):o.end<l.end&&i.set(o.lane,!0),i.size===this.options.lanes)break}return n.size===this.options.lanes?Array.from(n.values()).sort((a,o)=>a.end===o.end?a.index-o.index:a.end-o.end)[0]:void 0},this.getMeasurementOptions=co(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(t,r,i,n,a,o,l)=>(this.prevLanes!==void 0&&this.prevLanes!==o&&(this.lanesChangedFlag=!0),this.prevLanes=o,this.pendingMeasuredCacheIndexes=[],{count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l}),{key:!1}),this.getMeasurements=co(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:t,paddingStart:r,scrollMargin:i,getItemKey:n,enabled:a,lanes:o,laneAssignmentMode:l},h)=>{if(!a)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>t)for(const p of this.laneAssignments.keys())p>=t&&this.laneAssignments.delete(p);this.lanesChangedFlag&&(this.lanesChangedFlag=!1,this.lanesSettling=!0,this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),this.pendingMeasuredCacheIndexes=[]),this.measurementsCache.length===0&&!this.lanesSettling&&(this.measurementsCache=this.options.initialMeasurementsCache,this.measurementsCache.forEach(p=>{this.itemSizeCache.set(p.key,p.size)}));const d=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===t&&(this.lanesSettling=!1);const u=this.measurementsCache.slice(0,d),f=new Array(o).fill(void 0);for(let p=0;p<d;p++){const v=u[p];v&&(f[v.lane]=p)}for(let p=d;p<t;p++){const v=n(p),b=this.laneAssignments.get(p);let g,O;const m=l==="estimate"||h.has(v);if(b!==void 0&&this.options.lanes>1){g=b;const C=f[g],P=C!==void 0?u[C]:void 0;O=P?P.end+this.options.gap:r+i}else{const C=this.options.lanes===1?u[p-1]:this.getFurthestMeasurement(u,p);O=C?C.end+this.options.gap:r+i,g=C?C.lane:p%this.options.lanes,this.options.lanes>1&&m&&this.laneAssignments.set(p,g)}const x=h.get(v),y=typeof x=="number"?x:this.options.estimateSize(p),k=O+y;u[p]={index:p,start:O,size:y,end:k,key:v,lane:g},f[g]=p}return this.measurementsCache=u,u},{key:!1,debug:()=>this.options.debug}),this.calculateRange=co(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(t,r,i,n)=>this.range=t.length>0&&r>0?r2({measurements:t,outerSize:r,scrollOffset:i,lanes:n}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=co(()=>{let t=null,r=null;const i=this.calculateRange();return i&&(t=i.startIndex,r=i.endIndex),this.maybeNotify.updateDeps([this.isScrolling,t,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,t,r]},(t,r,i,n,a)=>n===null||a===null?[]:t({startIndex:n,endIndex:a,overscan:r,count:i}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=t=>{const r=this.options.indexAttribute,i=t.getAttribute(r);return i?parseInt(i,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=t=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const i=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(i!==void 0&&this.range){const n=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),a=Math.max(0,i-n),o=Math.min(this.options.count-1,i+n);return t>=a&&t<=o}return!0},this.measureElement=t=>{if(!t){this.elementsCache.forEach((a,o)=>{a.isConnected||(this.observer.unobserve(a),this.elementsCache.delete(o))});return}const r=this.indexFromElement(t),i=this.options.getItemKey(r),n=this.elementsCache.get(i);n!==t&&(n&&this.observer.unobserve(n),this.observer.observe(t),this.elementsCache.set(i,t)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(t,void 0,this))},this.resizeItem=(t,r)=>{var i;const n=this.measurementsCache[t];if(!n)return;const a=this.itemSizeCache.get(n.key)??n.size,o=r-a;o!==0&&(((i=this.scrollState)==null?void 0:i.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(n,o,this):n.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=o,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(n.index),this.itemSizeCache=new Map(this.itemSizeCache.set(n.key,r)),this.notify(!1))},this.getVirtualItems=co(()=>[this.getVirtualIndexes(),this.getMeasurements()],(t,r)=>{const i=[];for(let n=0,a=t.length;n<a;n++){const o=t[n],l=r[o];i.push(l)}return i},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=t=>{const r=this.getMeasurements();if(r.length!==0)return DO(r[Zv(0,r.length-1,i=>DO(r[i]).start,t)])},this.getMaxScrollOffset=()=>{if(!this.scrollElement)return 0;if("scrollHeight"in this.scrollElement)return this.options.horizontal?this.scrollElement.scrollWidth-this.scrollElement.clientWidth:this.scrollElement.scrollHeight-this.scrollElement.clientHeight;{const t=this.scrollElement.document.documentElement;return this.options.horizontal?t.scrollWidth-this.scrollElement.innerWidth:t.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(t,r,i=0)=>{if(!this.scrollElement)return 0;const n=this.getSize(),a=this.getScrollOffset();r==="auto"&&(r=t>=a+n?"end":"start"),r==="center"?t+=(i-n)/2:r==="end"&&(t-=n);const o=this.getMaxScrollOffset();return Math.max(Math.min(o,t),0)},this.getOffsetForIndex=(t,r="auto")=>{t=Math.max(0,Math.min(t,this.options.count-1));const i=this.getSize(),n=this.getScrollOffset(),a=this.measurementsCache[t];if(!a)return;if(r==="auto")if(a.end>=n+i-this.options.scrollPaddingEnd)r="end";else if(a.start<=n+this.options.scrollPaddingStart)r="start";else return[n,r];if(r==="end"&&t===this.options.count-1)return[this.getMaxScrollOffset(),r];const o=r==="end"?a.end+this.options.scrollPaddingEnd:a.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(o,r,a.size),r]},this.scrollToOffset=(t,{align:r="start",behavior:i="auto"}={})=>{const n=this.getOffsetForAlignment(t,r),a=this.now();this.scrollState={index:null,align:r,behavior:i,startedAt:a,lastTargetOffset:n,stableFrames:0},this._scrollToOffset(n,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollToIndex=(t,{align:r="auto",behavior:i="auto"}={})=>{t=Math.max(0,Math.min(t,this.options.count-1));const n=this.getOffsetForIndex(t,r);if(!n)return;const[a,o]=n,l=this.now();this.scrollState={index:t,align:o,behavior:i,startedAt:l,lastTargetOffset:a,stableFrames:0},this._scrollToOffset(a,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.scrollBy=(t,{behavior:r="auto"}={})=>{const i=this.getScrollOffset()+t,n=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:n,lastTargetOffset:i,stableFrames:0},this._scrollToOffset(i,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var t;const r=this.getMeasurements();let i;if(r.length===0)i=this.options.paddingStart;else if(this.options.lanes===1)i=((t=r[r.length-1])==null?void 0:t.end)??0;else{const n=Array(this.options.lanes).fill(null);let a=r.length-1;for(;a>=0&&n.some(o=>o===null);){const o=r[a];n[o.lane]===null&&(n[o.lane]=o.end),a--}i=Math.max(...n.filter(o=>o!==null))}return Math.max(i-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(t,{adjustments:r,behavior:i})=>{this.options.scrollToFn(t,{behavior:i,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(e)}scheduleScrollReconcile(){if(!this.targetWindow){this.scrollState=null;return}this.rafId==null&&(this.rafId=this.targetWindow.requestAnimationFrame(()=>{this.rafId=null,this.reconcileScroll()}))}reconcileScroll(){if(!this.scrollState||!this.scrollElement)return;if(this.now()-this.scrollState.startedAt>5e3){this.scrollState=null;return}const r=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,i=r?r[0]:this.scrollState.lastTargetOffset,n=1,a=i!==this.scrollState.lastTargetOffset;if(!a&&UC(i,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=n){this.scrollState=null;return}}else this.scrollState.stableFrames=0,a&&(this.scrollState.lastTargetOffset=i,this.scrollState.behavior="auto",this._scrollToOffset(i,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Zv=(s,e,t,r)=>{for(;s<=e;){const i=(s+e)/2|0,n=t(i);if(n<r)s=i+1;else if(n>r)e=i-1;else return i}return s>0?s-1:0};function r2({measurements:s,outerSize:e,scrollOffset:t,lanes:r}){const i=s.length-1,n=l=>s[l].start;if(s.length<=r)return{startIndex:0,endIndex:i};let a=Zv(0,i,n,t),o=a;if(r===1)for(;o<i&&s[o].end<t+e;)o++;else if(r>1){const l=Array(r).fill(0);for(;o<i&&l.some(d=>d<t+e);){const d=s[o];l[d.lane]=d.end,o++}const h=Array(r).fill(t+e);for(;a>=0&&h.some(d=>d>=t);){const d=s[a];h[d.lane]=d.start,a--}a=Math.max(0,a-a%r),o=Math.min(i,o+(r-1-o%r))}return{startIndex:a,endIndex:o}}const XO=typeof document<"u"?S.useLayoutEffect:S.useEffect;function i2({useFlushSync:s=!0,...e}){const t=S.useReducer(()=>({}),{})[1],r={...e,onChange:(n,a)=>{var o;s&&a?Wm.flushSync(t):t(),(o=e.onChange)==null||o.call(e,n,a)}},[i]=S.useState(()=>new s2(r));return i.setOptions(r),XO(()=>i._didMount(),[]),XO(()=>i._willUpdate()),i}function n2(s){return i2({observeElementRect:KC,observeElementOffset:JC,scrollToFn:t2,...s})}function o2({approval:s,submitting:e,readOnly:t,onClose:r,onDecision:i}){const{t:n}=Pt(["team","common"]);Iv(!0);const[a,o]=S.useState(""),l=typeof s.details?.command=="string"?s.details.command:"",h=typeof s.details?.toolName=="string"?s.details.toolName:"",d=u=>{t||e||i(u,a.trim()||void 0)};return Wm.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:u=>{u.target===u.currentTarget&&r()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-amber-500/15 text-amber-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug break-words",children:s.title||n("team:toolApproval.defaultTitle",{defaultValue:"Tool execution needs approval"})}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[c.jsxs("p",{className:"text-xs text-fg-tertiary",children:[s.agentName,h?` · ${h}`:""]}),t&&c.jsxs("span",{className:"inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium bg-green-500/15 text-green-600",children:[c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M20 6L9 17l-5-5"})}),n("team:toolApproval.resolved",{defaultValue:"Resolved"})]})]})]}),c.jsx("button",{onClick:r,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:n("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-5 space-y-4",children:[c.jsx("p",{className:"text-sm text-fg-secondary leading-relaxed",children:n("team:toolApproval.lead",{defaultValue:"The agent is paused until you approve or reject this action."})}),s.description&&c.jsx("div",{className:"text-xs text-fg-secondary leading-relaxed [&_p]:my-0 [&_p]:text-xs",children:c.jsx($o,{content:s.description.replace(/\s*Command:[\s\S]*$/,""),className:"text-xs [&_p]:text-xs [&_li]:text-xs"})}),l&&c.jsxs("div",{className:"space-y-1.5",children:[c.jsx("div",{className:"text-[11px] font-medium text-fg-tertiary uppercase tracking-wide",children:n("team:toolApproval.commandLabel",{defaultValue:"Command"})}),c.jsx("pre",{className:"text-xs text-fg-primary bg-surface-overlay border border-border-default rounded-xl px-3 py-2.5 overflow-x-auto whitespace-pre-wrap break-all font-mono leading-relaxed",children:l})]}),!t&&c.jsx("textarea",{rows:2,value:a,onChange:u=>o(u.target.value),placeholder:n("team:toolApproval.commentPlaceholder",{defaultValue:"Optional note (e.g. why you reject)…"}),className:"w-full px-3.5 py-2.5 text-sm bg-surface-overlay border border-border-default rounded-xl text-fg-primary placeholder:text-fg-tertiary focus:outline-none focus:ring-1 focus:ring-brand-500/50 resize-y"})]}),c.jsx("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:t?c.jsx("button",{onClick:r,className:"px-5 py-2 text-sm font-medium text-fg-secondary border border-border-default rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:close",{defaultValue:"Close"})}):c.jsxs(c.Fragment,{children:[c.jsxs("button",{disabled:e,onClick:()=>d(!1),className:"px-5 py-2 text-sm font-medium bg-red-600/85 text-white rounded-lg hover:bg-red-700 disabled:opacity-50 transition-colors inline-flex items-center gap-1.5",children:[c.jsxs("svg",{width:"13",height:"13",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]}),n("common:reject",{defaultValue:"Reject"})]}),c.jsxs("button",{disabled:e,onClick:()=>d(!0),className:"px-5 py-2 text-sm font-medium bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 transition-colors inline-flex items-center gap-2",children:[e&&c.jsxs("svg",{className:"animate-spin h-4 w-4",viewBox:"0 0 24 24",fill:"none",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),n("common:approve",{defaultValue:"Approve"})]})]})})]})}),document.body)}const zO={urgent:"bg-red-500/15 text-red-500",high:"bg-amber-500/15 text-amber-600",normal:"bg-blue-500/15 text-blue-500",low:"bg-surface-overlay text-fg-tertiary"};function a2({notification:s,agentName:e,acknowledging:t,index:r=0,total:i=1,onClose:n,onAcknowledge:a}){const{t:o,i18n:l}=Pt(["team","common"]);Iv(!0);const h=Xm(s.createdAt,o),d=zm(s.createdAt,l.language),u=s.priority||"normal",f=s.metadata??{},p=e||(typeof f.agentName=="string"?f.agentName:void 0),v=i>1,b=r>=i-1,g=Math.max(0,i-r-1);return Wm.createPortal(c.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:O=>{O.target===O.currentTarget&&n()},children:c.jsxs("div",{className:"w-full max-w-2xl max-h-[85vh] flex flex-col bg-surface-secondary border border-border-default rounded-2xl shadow-2xl overflow-hidden",children:[c.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[c.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-500/15 text-blue-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),c.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug",children:s.title}),c.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[p&&c.jsx("p",{className:"text-xs text-fg-tertiary",children:p}),u!=="normal"&&c.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${zO[u]??zO.normal}`,children:u}),v&&c.jsx("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-surface-overlay text-fg-secondary tabular-nums",children:o("page.notifyReviewProgress",{ns:"team",defaultValue:"{{current}} / {{total}}",current:r+1,total:i})}),(h||d)&&c.jsxs("span",{className:"inline-flex items-center gap-1 text-[11px] text-fg-tertiary tabular-nums",title:d,children:[c.jsxs("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"9"}),c.jsx("path",{d:"M12 7v5l3 2"})]}),h,h&&d&&c.jsx("span",{className:"text-fg-muted",children:"·"}),d]})]})]}),c.jsx("button",{onClick:n,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:o("common:close"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 6L6 18"}),c.jsx("path",{d:"M6 6l12 12"})]})})]}),v&&c.jsx("div",{className:"h-0.5 w-full bg-surface-overlay shrink-0",children:c.jsx("div",{className:"h-full bg-blue-500 transition-[width] duration-200",style:{width:`${(r+1)/i*100}%`}})}),c.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:c.jsx("div",{className:"text-sm text-fg-primary leading-relaxed",children:c.jsx($o,{content:s.body||""})})}),c.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:[c.jsx("button",{onClick:n,className:"px-3.5 py-2 text-sm text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:o("common:close")}),c.jsx("button",{onClick:()=>{a()},disabled:t,className:"px-4 py-2 text-sm font-medium text-white bg-blue-600 hover:bg-blue-500 disabled:opacity-50 rounded-lg transition-colors",children:t?o("common:loading"):b?o("page.notifyUserGotIt",{ns:"team",defaultValue:"Got it"}):o("page.notifyReviewNext",{ns:"team",defaultValue:"Next",count:g})})]})]})}),document.body)}const Vv=12,du=400,l2=4,c2=350;function Fv(s){return Math.max(0,s.scrollHeight-s.clientHeight)}function qO(s){return Fv(s)>1}function Wc(s){return Fv(s)-s.scrollTop}function h2(s){return Wc(s)<=Vv}function d2(s,e){return Math.abs(e)<=Math.abs(s)?"none":e<0?"up":e>0?"down":"none"}const u2=new Set(["ArrowUp","PageUp","Home"]),f2=new Set(["ArrowDown","PageDown","End"]);function m2(s){return u2.has(s)?"up":f2.has(s)?"down":"none"}function p2(s,e){return s==null?"none":e>s+1?"up":e<s-1?"down":"none"}function g2(s){return s.scrollable?s.takeover?s.gestureDirection==="up"||s.intentPending?"hold":s.distance<=Vv?"resume":"hold":s.gestureDirection==="up"&&s.gestureActive||!s.programmatic&&s.deltaScrollTop<-4?"handover":"follow":s.takeover?"resume":"follow"}function O2(s){return!s.takeover&&!s.gestureActive}function x2(s,e){return e&&s==="up"}function ho(s,e){return`${s||"_"}::${e??""}`}function b2(s,e){let t=null;for(const r of s)r.start>e+1||(!t||r.start>t.start)&&(t=r);return t??s[0]??null}function v2(s,e){if(h2(e))return{kind:"bottom"};const t=b2(s,e.scrollTop);return t?{kind:"row",id:t.id,delta:e.scrollTop-t.start}:{kind:"bottom"}}function y2(s,e){return s+e}const S2=12;function ZO(s,e=S2){return{kind:"row",id:s,delta:-e}}function VO(s){const e=s.getBoundingClientRect().top,t=s.scrollTop,r=[];for(const i of Array.from(s.querySelectorAll("[data-index]"))){const a=i.querySelector('[id^="msg-"]')?.id?.slice(4);a&&r.push({id:a,start:t+(i.getBoundingClientRect().top-e)})}return r.sort((i,n)=>i.start-n.start),r}function w2(s,e,t,r){const i=s.find(n=>n.id===t);return i?y2(i.start-e.scrollTop,r):null}class _2{constructor(e=120){this.capacity=e}entries=new Map;save(e,t){if(e)for(this.entries.delete(e),this.entries.set(e,t);this.entries.size>this.capacity;){const r=this.entries.keys().next();if(r.done)break;this.entries.delete(r.value)}}get(e){if(!e)return null;const t=this.entries.get(e);return t?(this.entries.delete(e),this.entries.set(e,t),t):null}delete(e){this.entries.delete(e)}clear(){this.entries.clear()}get size(){return this.entries.size}}const FO=new _2,UO={jump:3,prepend:2,restore:1};function k2(s,e){return!s||s.key!==e.key?!0:UO[e.priority]>=UO[s.priority]}const C2=1e4,HO=300;function P2(s,e){return e-s>C2}function YO(s,e){return s&&e===!0}function T2(s){return s.rendered?s.stable?"apply":"refine":s.stale?s.priority==="restore"?"release-bottom":"release-hold":!s.absent||s.canLoadMore?"keep":s.priority==="restore"?"release-bottom":"release-hold"}function uu(s){return s!=="prepend"}const fu=Object.freeze({text:"",images:[],context:[],replyTo:null});function GO(s){return s.text===""&&s.images.length===0&&s.context.length===0&&s.replyTo===null}function Q2(s){return{text:s.text,images:s.images,context:s.context,replyTo:s.replyTo}}class $2{constructor(e=120){this.capacity=e}entries=new Map;save(e,t){if(!e)return;this.entries.delete(e);const r=Q2(t);if(!GO(r))for(this.entries.set(e,r);this.entries.size>this.capacity;){const i=this.entries.keys().next().value;if(i===void 0)break;this.entries.delete(i)}}get(e){const t=this.peek(e);return GO(t)?fu:(this.entries.delete(e),this.entries.set(e,t),t)}peek(e){return e?this.entries.get(e)??fu:fu}size(){return this.entries.size}clear(){this.entries.clear()}}const _a=new $2;function KO(s){return s.aborted||s.sawTerminal?"finalize":s.serverStatus==="streaming"||s.serverStatus===null?"reattach":"finalize"}function JO(s){switch(s){case"streaming":case"done":case"error":case"stopped":case"idle":case"not_found":return s;default:return null}}function e0(s,e){return!!s&&!!e&&s.has(e)}function j2(s){return s.msgIsStreaming&&s.liveStreamForView}const R2=10*6e4;class E2{bySession=new Map;listeners=new Set;_revision=0;getRevision=()=>this._revision;subscribe=e=>(this.listeners.add(e),()=>{this.listeners.delete(e)});applyServerState(e,t,r,i=Date.now()){const n=this.bySession.get(t);if(n&&n.source==="server"&&n.at>i)return;const a=!n||n.streaming!==r;this.bySession.set(t,{agentId:e,streaming:r,source:"server",at:i}),a&&this.bump()}reconcileFromServer(e,t,r=Date.now()){for(const[i,n]of Object.entries(t))this.applyServerState(e,i,n,r)}applyLocalOptimistic(e,t,r){const i=this.bySession.get(t),n=Date.now();if(i&&i.source==="server"&&i.at>=n)return;const a=!i||i.streaming!==r;this.bySession.set(t,{agentId:e,streaming:r,source:"local",at:n}),a&&this.bump()}isStreaming(e){return e?this.bySession.get(e)?.streaming??!1:!1}isAgentStreaming(e){if(!e)return!1;for(const t of this.bySession.values())if(t.agentId===e&&t.streaming)return!0;return!1}streamingAgentIds(){const e=new Set;for(const t of this.bySession.values())t.streaming&&e.add(t.agentId);return e}hasEntry(e){return this.bySession.has(e)}prune(e=Date.now(),t=R2){for(const[r,i]of this.bySession)!i.streaming&&e-i.at>t&&this.bySession.delete(r)}bump(){this._revision+=1;for(const e of this.listeners)try{e()}catch{}}}const hs=new E2;function ah(){return S.useSyncExternalStore(hs.subscribe,hs.getRevision,hs.getRevision)}function Uv(s){return S.useSyncExternalStore(hs.subscribe,hs.getRevision,hs.getRevision),hs.isAgentStreaming(s)}function A2(s){const e=s?.payload;return!e||typeof e.sessionId!="string"||typeof e.streaming!="boolean"?null:{agentId:typeof e.agentId=="string"?e.agentId:"",sessionId:e.sessionId,streaming:e.streaming}}let t0=!1;function M2(){t0||(t0=!0,St.on("session:stream_state",s=>{const e=A2(s);if(!e)return;const t=Date.parse(s.timestamp??"")||Date.now();hs.applyServerState(e.agentId,e.sessionId,e.streaming,t)}))}async function L2(s,e){if(!(!s||e.length===0)){try{const t=await te.sessions.streamStatusBatch(s,e);hs.reconcileFromServer(s,t.streaming??{},t.at)}catch{}hs.prune()}}function N2(s,e){return!s||s.mode!=="direct"||e.chatMode!=="direct"||!s.sessionId&&!s.preferMain?!1:!!s.agentId&&s.agentId===e.agentId}function Fa({children:s,onClose:e,title:t,width:r="w-[440px]"}){return c.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:e,children:c.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${r} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:i=>i.stopPropagation(),children:[c.jsx("h3",{className:"text-base font-semibold mb-5",children:t}),s]})})}function vo({label:s,children:e}){return c.jsxs("div",{children:[c.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:s}),e]})}function D2({onClose:s,onCreate:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("");return c.jsx(Fa,{onClose:s,title:t("team:modals.createTeam.title"),children:c.jsxs("div",{className:"space-y-4",children:[c.jsx(vo,{label:t("team:modals.createTeam.teamName"),children:c.jsx("input",{value:r,onChange:o=>i(o.target.value),placeholder:t("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:o=>{o.key==="Enter"&&r.trim()&&e(r.trim(),n.trim()||void 0)}})}),c.jsx(vo,{label:t("team:modals.createTeam.description"),children:c.jsx("textarea",{value:n,onChange:o=>a(o.target.value),placeholder:t("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),c.jsx("div",{className:"text-xs text-fg-tertiary",children:t("team:modals.createTeam.hint")}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:c.jsx(Zk,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:c.jsx("span",{className:"text-brand-400 font-medium"}),1:c.jsx("span",{className:"text-brand-400"})}})}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:()=>r.trim()&&e(r.trim(),n.trim()||void 0),disabled:!r.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:t("team:modals.createTeam.createTeam")})]})]})})}function I2({onClose:s,onAdd:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState("member"),[o,l]=S.useState(""),[h,d]=S.useState(""),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(!1),O=p?.inviteToken?`${window.location.origin}/#invite?token=${p.inviteToken}`:null,m=async()=>{if(d(""),!r.trim()){d(t("team:modals.addHuman.nameRequired"));return}if(!o.trim()){d(t("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(o.trim())){d(t("team:modals.addHuman.invalidEmail"));return}f(!0);try{const y=await e(r.trim(),n,o.trim());v({...y,userName:r.trim()})}catch(y){d(y instanceof Error?y.message:String(y))}finally{f(!1)}},x=()=>{O&&(navigator.clipboard.writeText(O),g(!0),setTimeout(()=>g(!1),2e3))};return p?c.jsxs(Fa,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:[c.jsxs("div",{className:"text-center py-4",children:[c.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:c.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-green-500",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx("div",{className:"text-base font-medium mb-1",children:t("team:modals.addHuman.memberCreated",{name:p.userName})}),O?c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:t("team:modals.addHuman.inviteHint")}),c.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:t("team:modals.addHuman.inviteLink")}),c.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:O})]}),c.jsx("button",{onClick:x,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${b?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(b?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):c.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:t("team:modals.addHuman.memberCreatedNoInvite")})]}),c.jsx("div",{className:"flex justify-end pt-3",children:c.jsx("button",{onClick:s,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("common:done")})})]}):c.jsx(Fa,{onClose:s,title:t("team:modals.addHuman.title"),width:"w-[460px]",children:c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"text-xs text-fg-secondary bg-surface-primary border border-border-default rounded-lg px-3 py-2.5 leading-relaxed",children:[c.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:t("team:modals.addHuman.sharedInstanceTitle")}),t("team:modals.addHuman.sharedInstanceDesc"),c.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[t("team:modals.addHuman.orgHint")," ",c.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:t("team:modals.addHuman.orgLink")})]})]}),c.jsx(vo,{label:t("team:modals.addHuman.name"),children:c.jsx("input",{value:r,onChange:y=>i(y.target.value),placeholder:t("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),c.jsx(vo,{label:t("team:modals.addHuman.role"),children:c.jsxs("select",{value:n,onChange:y=>a(y.target.value),className:"input",children:[c.jsx("option",{value:"owner",children:t("common:role.owner")}),c.jsx("option",{value:"admin",children:t("common:role.admin")}),c.jsx("option",{value:"member",children:t("common:role.member")}),c.jsx("option",{value:"guest",children:t("common:role.guest")})]})}),c.jsx(vo,{label:t("team:modals.addHuman.emailRequired"),children:c.jsx("input",{value:o,onChange:y=>l(y.target.value),type:"email",placeholder:t("team:modals.addHuman.emailPlaceholder"),className:"input"})}),c.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:t("team:modals.addHuman.inviteFlowHint")}),h&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:h}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:m,disabled:u,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:t(u?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function B2({teamId:s,ungrouped:e,onClose:t,onAdd:r}){const{t:i}=Pt(["team","common"]);return c.jsx(Fa,{onClose:t,title:i("team:modals.addExisting.title"),children:c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:i("team:modals.addExisting.hint")}),e.length===0?c.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:i("team:modals.addExisting.allInTeam")}):c.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:e.map(n=>c.jsxs("button",{onClick:()=>r(n.id,n.type),className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:border-brand-500 hover:bg-brand-500/10 text-left transition-all",children:[c.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${n.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:n.name.charAt(0)}),c.jsxs("div",{className:"flex-1",children:[c.jsx("div",{className:"font-medium text-sm",children:n.name}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[n.role," · ",n.type==="agent"?i("team:modals.addExisting.typeAgent"):i("team:modals.addExisting.typeHuman")]})]}),n.status&&c.jsx("span",{className:`w-2 h-2 rounded-full ${n.status==="idle"?"bg-green-400":n.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},n.id))}),c.jsx("div",{className:"flex justify-end pt-2",children:c.jsx("button",{onClick:t,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:i("common:close")})})]})})}function W2({onClose:s,onConnected:e}){const{t}=Pt(["team","common"]),[r,i]=S.useState(""),[n,a]=S.useState(""),[o,l]=S.useState(!1),[h,d]=S.useState(null),[u,f]=S.useState(null),p=async()=>{if(!r.trim()){a(t("team:modals.openClaw.agentNameRequired"));return}const b=r.trim().toLowerCase().replace(/\s+/g,"-");l(!0),a("");try{const g=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:b,agentName:r.trim(),orgId:"default",capabilities:["general"]})});if(!g.ok){const m=await g.json().catch(()=>({}));throw new Error(m.error??`HTTP ${g.status}`)}const O=await g.json();d({externalAgentId:b,markusAgentId:O.registration?.markusAgentId,token:O.token,gatewayUrl:O.gatewayUrl})}catch(g){a(String(g))}l(!1)},v=(b,g)=>{navigator.clipboard.writeText(b),f(g),setTimeout(()=>f(null),2e3)};return c.jsx(Fa,{onClose:s,title:t("team:modals.openClaw.title"),width:"w-[560px]",children:h?(()=>{const b=h.gatewayUrl??`${window.location.origin}/api/gateway`,g=h.token?t("team:modals.openClaw.bearerTokenLine",{token:h.token}):"",O=t("team:modals.openClaw.connectionPromptBody",{gwUrl:b,externalAgentId:h.externalAgentId,tokenSection:g});return c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"text-center py-6",children:[c.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),c.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:t("team:modals.openClaw.agentRegistered")}),c.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:c.jsx("strong",{children:r})})]}),c.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:t("team:modals.openClaw.copyInstruction")}),c.jsx("button",{onClick:()=>v(O,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${u==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:t(u==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),c.jsx("div",{className:"flex justify-end pt-5",children:c.jsx("button",{onClick:()=>{e()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:t("team:modals.openClaw.done")})})]})})():c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:t("team:modals.openClaw.description")}),c.jsxs("div",{className:"space-y-4",children:[c.jsx(vo,{label:t("team:modals.openClaw.agentName"),children:c.jsx("input",{className:"input",placeholder:t("team:modals.openClaw.agentNamePlaceholder"),value:r,onChange:b=>i(b.target.value),autoFocus:!0})}),n&&c.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:n}),c.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[c.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:t("common:cancel")}),c.jsx("button",{onClick:p,disabled:o,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:t(o?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}function Hv(s){return`group:${s}`}function X2(s){const{chatMode:e,agentTeamId:t,channelTeamId:r,knownTeamIds:i}=s,n=e==="direct"?t:e==="channel"?r:null;return n&&(i instanceof Set?i.has(n):Array.from(i).includes(n))?`team/t/${n}`:"team"}function z2(s,e){return s&&typeof s.tokensUsedToday=="number"&&Number.isFinite(s.tokensUsedToday)?s.tokensUsedToday:typeof e=="number"&&Number.isFinite(e)?e:0}function q2(s){return s?s.filter(e=>e&&typeof e.size=="number"&&e.size>0).slice().sort((e,t)=>t.size-e.size||e.name.localeCompare(t.name)):[]}const Z2=new Set(["workspace","sessions","tool-outputs","daily-logs","role","subagent-logs","worktrees"]);function V2(s){return Z2.has(s)?`agent:profilePage.overview.storageBuckets.${s}`:null}const Cf={idle:{tone:"ok",dotClass:"bg-green-400",running:!0,chipClass:"bg-green-500/10 border border-green-500/20",textClass:"text-green-600",labelKey:"common:status.idle"},working:{tone:"busy",dotClass:"bg-blue-400 animate-pulse",running:!0,chipClass:"bg-blue-500/10 border border-blue-500/20",textClass:"text-blue-500",labelKey:"common:status.working"},error:{tone:"danger",dotClass:"bg-red-400 animate-pulse",running:!0,chipClass:"bg-red-500/10 border border-red-500/20",textClass:"text-red-500",labelKey:"common:status.error"},paused:{tone:"warn",dotClass:"bg-amber-400",running:!1,chipClass:"bg-amber-500/10 border border-amber-500/20",textClass:"text-amber-600",labelKey:"common:status.paused"},offline:{tone:"muted",dotClass:"bg-gray-400",running:!1,chipClass:"bg-gray-500/10 border border-border-default",textClass:"text-fg-tertiary",labelKey:"common:status.offline"}};function qh(s){const e=s?Cf[s]:void 0;return e||{...Cf.offline,labelKey:null}}const F2=Cf.working;function Ol(s,e){const t=qh(s);return!e||!t.running||t.tone==="danger"||t.tone==="busy"?t:F2}const U2=5;function s0(s,e=U2){const t=Array.isArray(s)?s:[];return{shown:t.slice().sort((i,n)=>Date.parse(n.startedAt)-Date.parse(i.startedAt)).slice(0,Math.max(0,e)),total:t.length}}const H2=100;function Y2(s){const e=Array.isArray(s)?s:[];return{heartbeats:e.filter(t=>t.type==="heartbeat"),comms:e.filter(t=>t.type==="a2a")}}const Um=["files","mind","recent","tools","memory","usage"],G2=Um[0];function r0(s,e){return e?"mind":Um.find(r=>r===s)??G2}function K2(s){return s?"right-panel":"page"}function J2(s){const e=s?.deferredItemIds?.length??0,t=s?.droppedItemIds?.length??0,r=s?.inlineCompletedIds?.length??0,i=1,n=i+e+t+r;return{processed:i,deferred:e,dropped:t,inlineCompleted:r,total:n,isBatch:n>1}}let hc=new Map;function eP({agents:s,humans:e,authUser:t,onClose:r,onCreate:i}){const{t:n}=Pt(["team","common"]),[a,o]=S.useState(""),[l,h]=S.useState(new Set),[d,u]=S.useState(""),[f,p]=S.useState(!1),v=S.useMemo(()=>{const m=[];for(const x of s)m.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of e)x.id!==t?.id&&m.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||"Human"});return m},[s,e,t]),b=S.useMemo(()=>{if(!d)return v;const m=d.toLowerCase();return v.filter(x=>x.name.toLowerCase().includes(m)||x.subtitle.toLowerCase().includes(m))},[v,d]),g=m=>{h(x=>{const y=new Set(x);return y.has(m)?y.delete(m):y.add(m),y})},O=async()=>{if(!a.trim()||l.size===0)return;p(!0);const m=[...l],x={},y={};for(const k of m){const C=v.find(P=>P.id===k);C&&(x[k]=C.type,y[k]=C.name)}await i(a.trim(),m,x,y),p(!1)};return c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[400px] max-w-[90vw] max-h-[80vh] flex flex-col",onClick:m=>m.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:n("modals.createGroupChat.title")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:n("modals.createGroupChat.subtitle")})]}),c.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:c.jsx("input",{value:a,onChange:m=>o(m.target.value),placeholder:n("modals.createGroupChat.groupNamePlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-2 text-sm text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50",autoFocus:!0})}),c.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:c.jsx("input",{value:d,onChange:m=>u(m.target.value),placeholder:n("modals.createGroupChat.searchPlaceholder"),className:"w-full bg-surface-primary border border-border-default rounded-lg px-3 py-1.5 text-xs text-fg-primary placeholder:text-fg-muted outline-none focus:ring-1 focus:ring-brand-500/50"})}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[b.length===0&&c.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:n("modals.createGroupChat.noMembersFound")}),b.map(m=>c.jsxs("button",{onClick:()=>g(m.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${l.has(m.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${l.has(m.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:l.has(m.id)&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})})}),c.jsx(Ns,{name:m.name,size:20,bgClass:m.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate text-[11px] font-medium block",children:m.name}),c.jsx("span",{className:"text-[9px] text-fg-tertiary",children:m.subtitle})]}),c.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${m.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:m.type==="agent"?n("modals.addExisting.typeAgent"):n("modals.addExisting.typeHuman")})]},m.id))]}),c.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("modals.createGroupChat.selected",{count:l.size})}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:r,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:n("common:cancel")}),c.jsx("button",{onClick:O,disabled:!a.trim()||l.size===0||f,className:"px-4 py-1.5 text-xs font-medium text-white bg-brand-600 hover:bg-brand-500 rounded-lg transition-colors disabled:opacity-50 disabled:pointer-events-none",children:n(f?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const tP=S.memo(function({authUser:e,agents:t,teams:r,humans:i,tasks:n,externalAgents:a,groupChats:o,chatMode:l,selectedAgent:h,activeChannel:d,activeDmUserId:u,onSelectAgent:f,onSelectChannel:p,onSelectDm:v,onSelectTeam:b,selectedTeamId:g,onRefreshTeams:O,onRefreshAgents:m,onRefreshHumans:x,onRefreshGroupChats:y,onViewProfile:k,onManageGroupMembers:C,unreadByAgent:P,unreadByChannel:_,width:T,onResizeStart:R,hidden:L,onCollapse:M,initialLoading:E,previewMode:B,focused:U,l2Available:F}){const{t:X}=Pt(["team","common"]),ae=qm(),j=Zm(Yt.TEAM),W=zh(),D=e?.role==="owner"||e?.role==="admin",V=S.useMemo(()=>new Set(a.map(q=>q.markusAgentId).filter(Boolean)),[a]);ah();const se=hs.streamingAgentIds(),[fe,z]=S.useState([]),[re,Z]=S.useState(new Set),[A,J]=S.useState(!1),[Y,oe]=S.useState(!1),[K,pe]=S.useState(null),[je,we]=S.useState(!1),[Ge,Qe]=S.useState(!1),[Ee,ye]=S.useState(null),[G,qe]=S.useState(null),[He,Ye]=S.useState(null),[pt,xt]=S.useState(!1),[bt,vt]=S.useState(""),[Pe,At]=S.useState(null),[Ft,Es]=S.useState(null),[rt,yt]=S.useState(null),[Bt,ut]=S.useState(!1),Ze=S.useRef(null),[Xt,ot]=S.useState(null),Mt=S.useRef(null),us=S.useRef(null),[he,ce]=S.useState(null),$e=(q,me="success")=>{ce({message:q,type:me}),setTimeout(()=>ce(null),3e3)},[Xe,de]=S.useState(null),[De,ve]=S.useState(!1),st=S.useRef(!1);S.useEffect(()=>{if(B)return;te.governance.getSystemStatus().then(be=>{st.current=!0,de(be.globalPaused)}).catch(()=>{st.current=!0,de(!1)});const q=St.on("system:pause-all",()=>{st.current&&de(!0)}),me=St.on("system:resume-all",()=>{st.current&&de(!1)});return()=>{q(),me()}},[]),S.useEffect(()=>{if(!B)return;const q=setTimeout(()=>{const me=us.current,be=Mt.current;me&&be&&be.scrollTo({top:me.offsetTop-be.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(q)},[B]);const ze=S.useCallback(()=>{Xe!==null&&ee({title:X(Xe?"modals.resumeAll.title":"modals.pauseAll.title"),message:X(Xe?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:X(Xe?"chat.resume":"chat.pause"),onConfirm:async()=>{ve(!0);try{Xe?(await te.governance.resumeAll(),de(!1)):(await te.governance.pauseAll(),de(!0))}catch{}ve(!1)}})},[Xe]),[Ve,ee]=S.useState(null),Te=(q,me,be,Ie,Ke)=>{ee({title:q,message:me,onConfirm:be,confirmLabel:Ie,checkboxes:Ke})},[Se,Oe]=S.useState(null),[_e,Fe]=S.useState(null),at=S.useRef(null),wt=S.useRef(null),[ht,dt]=S.useState(!1),[Qt,hi]=S.useState(null),[le,$t]=S.useState(""),ge=S.useCallback((q,me=176,be=220)=>{const Ie=window.innerWidth,Ke=window.innerHeight,Je=8;let lt=q.clientX,Rt=q.clientY;return lt+me>Ie-Je&&(lt=Math.max(Je,Ie-me-Je)),Rt+be>Ke-Je&&(Rt=Math.max(Je,Ke-be-Je)),lt=Math.max(Je,Math.min(lt,Ie-me-Je)),Rt=Math.max(Je,Math.min(Rt,Ke-be-Je)),{x:lt,y:Rt}},[]),[Us,gt]=S.useState(hc),Bs=S.useMemo(()=>t.map(q=>q.id).sort().join(","),[t]);S.useEffect(()=>{if(!t.length||!j)return;let q=!1;(async()=>{const lt=[];await Promise.allSettled(t.map(async Rt=>{if(!hc.has(Rt.id))try{const{sessions:Ot}=await te.sessions.listByAgent(Rt.id,1);if(!Ot.length)return;const{messages:cs}=await te.sessions.getMessages(Ot[0].id,1);if(cs.length){const bs=cs[0],ir=bs.metadata?.segments;let zt=bs.content;if(ir&&ir.length>0){const vs=[...ir].reverse().find(es=>es.type==="text");vs&&vs.type==="text"&&(zt=vs.content)}const ks=zt.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);ks&<.push([Rt.id,ks])}}catch{}})),!q&<.length&>(Rt=>{const Ot=new Map(Rt);for(const[cs,bs]of lt)Ot.set(cs,bs);return hc=Ot,Ot})})();const be=new Set(t.map(lt=>lt.id)),Ie=lt=>Fk(lt).replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),Ke=(lt,Rt)=>{if(!lt||!Rt||!be.has(lt))return;const Ot=Ie(Rt);Ot&>(cs=>{const bs=new Map(cs);return bs.set(lt,Ot),hc=bs,bs})},Je=St.on("chat:proactive_message",lt=>{const Rt=lt.payload;Ke(Rt.agentId??"",Rt.message??"")});return()=>{q=!0,Je()}},[Bs,j]);const _t=S.useCallback(()=>{B||te.teams.list().then(q=>z(q.ungrouped)).catch(()=>{})},[B]);S.useEffect(()=>{_t()},[_t]),S.useEffect(()=>{if(!j)return;const q=St.on("team:update",_t),me=St.on("agent:removed",_t);return()=>{q(),me()}},[_t,j]),S.useEffect(()=>{if(!G&&!He&&!Pe&&!Bt&&!rt)return;const q=()=>{qe(null),Ye(null),At(null),yt(null),ut(!1)},me=setTimeout(()=>document.addEventListener("click",q),0);return()=>{clearTimeout(me),document.removeEventListener("click",q)}},[G,He,Pe,Bt,rt]);const ln=(q,me)=>{Te(`${X("common:delete")} "${me}"?`,X("modals.deleteTeam.message"),async be=>{const Ie=be?.deleteMembers??!0,Ke=be?.purgeFiles??!1;await te.teams.delete(q,Ie,{purgeFiles:Ke}),O(),_t(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},X("contextMenu.deleteTeam"),[{id:"deleteMembers",label:X("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:X("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Fo=async(q,me)=>{try{const Ie=await(me==="start"?te.teams.startAll:te.teams.stopAll)(q),Ke=Ie.success?.length??0,Je=Ie.failed?.length??0;Je>0?$e(X("batchAction.failed",{action:X(`batchAction.operation.${me}`),ok:Ke,fail:Je}),"error"):Ke>0&&$e(X("batchAction.succeeded",{count:Ke,action:X(`batchAction.past.${me}`)}),"success"),m()}catch(be){$e(X("batchAction.failedToRun",{action:X(`batchAction.operation.${me}`),error:be instanceof Error?be.message:String(be)}),"error")}},cn=async(q,me,be)=>{await te.teams.update(q,{managerId:me,managerType:be}),O()},Tl=async q=>{if(!le.trim()){hi(null);return}await te.teams.update(q,{name:le.trim()}),hi(null),O()},Ql=async(q,me)=>{me==="offline"?await te.agents.start(q):await te.agents.stop(q),m()},Os=(q,me)=>{Te(X("modals.removeFromTeam.title"),X("modals.removeFromTeam.message"),async()=>{await te.teams.removeMember(q,me),O(),_t()},X("common:remove"))},rs=(q,me,be,Ie)=>{Te(`${X("common:remove")} "${me}"?`,X(be==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async Ke=>{if(be==="agent"&&Ie){const Je=o.find(lt=>lt.type==="team"&<.teamId===Ie);Je?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+Je.channelKey)}if(be==="agent"){const Je=Ke?.purgeFiles??!1;await te.agents.remove(q,{purgeFiles:Je})}else await te.users.remove(q);m(),O(),x?.(),_t(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},X("common:remove"),be==="agent"?[{id:"purgeFiles",label:X("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},_s=q=>{if(q.isOrgSecretary||q.protected)return!0;if(q.teamId)return!1;const me=(q.role??"").toLowerCase().trim(),be=(q.name??"").trim();return be==="Secretary"||be==="秘书"||me==="secretary"||me.startsWith("secretary")},xr=(q,me,be)=>{const Ie=t.find(Ke=>Ke.id===me);Ie&&_s(Ie)||(wt.current={x:q.clientX,y:q.clientY},at.current=setTimeout(()=>{Oe({agentId:me,fromTeamId:be}),dt(!0)},200))},Uo=q=>{if(!wt.current||!at.current)return;const me=Math.abs(q.clientX-wt.current.x),be=Math.abs(q.clientY-wt.current.y);(me>5||be>5)&&(ht||(clearTimeout(at.current),at.current=null))},$l=async()=>{if(at.current&&(clearTimeout(at.current),at.current=null),wt.current=null,ht&&Se&&_e){const q=_e==="_ungrouped"?void 0:_e;try{if(Se.fromTeamId&&Se.fromTeamId!==q&&await te.teams.removeMember(Se.fromTeamId,Se.agentId),q&&q!==Se.fromTeamId){const me=t.find(be=>be.id===Se.agentId);await te.teams.addMember(q,Se.agentId,"agent")}O(),m(),_t()}catch(me){$e(X("batchAction.moveFailed",{error:me instanceof Error?me.message:String(me)}),"error")}}Oe(null),Fe(null),dt(!1)},zr=S.useMemo(()=>new Map(r.map(q=>[q.id,q])),[r]),xs=S.useMemo(()=>{const q=new Map,me=[];for(const be of t)if(be.teamId&&zr.has(be.teamId)){const Ie=q.get(be.teamId)??[];Ie.push(be),q.set(be.teamId,Ie)}else me.push(be);return{byTeam:q,ungrouped:me}},[t,zr]),Vn=(q,me)=>{const be=l==="direct"&&h===q.id,Ie=V.has(q.id),Ke=q.status==="offline",Je=Ol(q.status,!Ke&&se.has(q.id)),lt=Je.tone==="busy",Rt=Je.dotClass,cs=(void 0)?.managerId===q.id,bs=q.role?.toLowerCase().replace(/[-_]/g," ").trim(),ir=q.name.toLowerCase().trim(),zt=bs&&bs!==ir,ks=Us.get(q.id)||q.currentActivity?.label?.slice(0,60)||"",vs=lt?X("common:status.working"):q.status==="error"?X("common:status.error"):X(Ke?"common:status.offline":"common:status.online");return c.jsx("div",{className:`relative mb-0.5 ${ht&&Se?.agentId===q.id?"opacity-40":""}`,onPointerDown:es=>xr(es,q.id,me),onPointerMove:Uo,onPointerUp:$l,children:c.jsxs("button",{"data-l1-nav-id":`agent:${q.id}`,onClick:()=>{ht||f(q.id)},onContextMenu:es=>{if(!D)return;es.preventDefault();const nr=ge(es);xt(!1),vt(""),Ye({agentId:q.id,teamId:me,...nr})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${ae?"":"touch-none"} ${Ke?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${$i(be)}`,children:[c.jsx(Ns,{name:q.name,avatarUrl:q.avatarUrl,size:28,bgClass:Ke?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:q.name}),zt&&c.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",q.role,")"]}),cs&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),Ie&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-brand-500/20 text-brand-400 font-medium shrink-0 leading-relaxed",children:"EXT"}),Ke&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:X("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:ks||" "})]}),c.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(P?.get(q.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:P.get(q.id)}),q.mailboxDepth!=null&&q.mailboxDepth>0&&c.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:q.mailboxDepth}),c.jsx("span",{title:vs,onClick:es=>{es.stopPropagation(),k(q.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${Rt}`}),ae&&D&&c.jsx("span",{role:"button",tabIndex:0,onClick:es=>{if(es.stopPropagation(),He?.agentId===q.id)Ye(null);else{const nr=ge(es);xt(!1),vt(""),Ye({agentId:q.id,teamId:me,...nr})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:X("chat.moreOptions"),children:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},q.id)},jl=(q,me,be,Ie)=>{const Ke=ht&&_e===q&&Se?.fromTeamId!==q,Je=Xt===q,lt=g===q,Rt=P?(xs.byTeam.get(q)??[]).reduce((qt,qr)=>qt+(P.get(qr.id)??0),0):0,cs=o.find(qt=>qt.type==="team"&&qt.teamId===q)?.channelKey??Hv(q),bs=_?_[cs]??0:0,ir=Rt+bs,zt=xs.byTeam.get(q)??[],ks=zt.filter(qt=>qt.status==="offline").length,vs=zt.length,es=vs>0&&ks===vs,nr=ks>0&&!es,dn=es?"bg-gray-500":nr?"bg-amber-500":"bg-green-500";return c.jsxs("div",{"data-team-id":q,className:`mb-0.5 rounded-lg transition-all duration-500 ${Ke?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${Je?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{ht&&Fe(q)},onPointerLeave:()=>{ht&&_e===q&&Fe(null)},children:[c.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[c.jsxs("button",{"data-l1-nav-id":`team:${q}`,onClick:()=>{b&&q!=="_ungrouped"&&b(q)},onContextMenu:qt=>{if(!D||!me)return;qt.preventDefault();const qr=ge(qt);qe({teamId:q,...qr})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${es?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${$i(lt)}`,children:[c.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${es?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[me?.avatarUrl?c.jsx("img",{src:me.avatarUrl,alt:Ie,className:"w-full h-full rounded-full object-cover",onError:qt=>{qt.target.style.display="none",qt.target.nextElementSibling?.classList.remove("hidden")}}):null,c.jsxs("svg",{className:`w-3 h-3 ${me?.avatarUrl?"hidden":""}`,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),vs>0&&c.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${dn}`})]}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[Qt===q?c.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:le,onChange:qt=>$t(qt.target.value),onBlur:()=>Tl(q),onKeyDown:qt=>{qt.key==="Enter"&&Tl(q),qt.key==="Escape"&&hi(null)},onClick:qt=>qt.stopPropagation(),autoFocus:!0}):c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:Ie}),c.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[X("chat.members_other",{count:be}),es&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:X("common:status.offline")}),nr&&c.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[ks,"/",vs]})]})]}),ir>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:ir}),c.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})})]}),D&&me&&c.jsx("button",{onClick:qt=>{if(qt.stopPropagation(),G?.teamId===q)qe(null);else{const qr=ge(qt);qe({teamId:q,...qr})}},className:"w-7 h-7 flex items-center justify-center text-fg-muted hover:text-fg-primary rounded-md hover:bg-white/[0.08] transition-colors shrink-0",title:X("chat.moreOptions"),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"1"}),c.jsx("circle",{cx:"12",cy:"5",r:"1"}),c.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),Ke&&ht&&c.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:X("chat.dropHere")})]},q)},is=S.useMemo(()=>{const q=new Map,me=[],be=[],Ie=[];for(const Ke of o)if(Ke.channelKey.startsWith("dm:a2a:"))Ie.push(Ke);else if(Ke.type==="custom")be.push(Ke);else if(Ke.teamId){const Je=q.get(Ke.teamId)??[];Je.push(Ke),q.set(Ke.teamId,Je)}else{const Je=r.find(lt=>Ke.name.toLowerCase().includes(lt.name.toLowerCase())||lt.name.toLowerCase().includes(Ke.name.toLowerCase()));if(Je){const lt=q.get(Je.id)??[];lt.push(Ke),q.set(Je.id,lt)}else me.push(Ke)}return{byTeam:q,unmatched:me,custom:be,dmChannels:Ie}},[o,r]),Qr=S.useMemo(()=>{const q=new Map;let me=0;for(const Ke of xs.ungrouped)q.set(Ke.id,me++);for(const Ke of r)for(const Je of xs.byTeam.get(Ke.id)??[])q.set(Je.id,me++);const be=Number.MAX_SAFE_INTEGER,Ie=Ke=>{const Je=Ke.split(":");return Je.length<4?[]:[Je[2],Je[3]].map(lt=>q.get(lt)??be).sort((lt,Rt)=>lt-Rt)};return[...is.dmChannels].sort((Ke,Je)=>{const lt=Ie(Ke.channelKey),Rt=Ie(Je.channelKey),Ot=lt[0]??be,cs=lt[1]??be,bs=Rt[0]??be,ir=Rt[1]??be;return Ot!==bs?Ot-bs:cs!==ir?cs-ir:Ke.channelKey.localeCompare(Je.channelKey)})},[is.dmChannels,xs,r]),[hn,jt]=S.useState(!1),br=l==="channel"&&is.dmChannels.some(q=>q.channelKey===d);S.useEffect(()=>{br&&jt(!0)},[br]);const Rl=S.useMemo(()=>{const q=[];e&&q.push({kind:"dm",id:`dm:${e.id}`,userId:e.id});for(const be of i)be.id!==e?.id&&q.push({kind:"dm",id:`dm:${be.id}`,userId:be.id});for(const be of is.custom)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});for(const be of is.unmatched)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});const me=xs.ungrouped.length>0?xs.ungrouped:r.length===0?t:[];for(const be of me)q.push({kind:"agent",id:`agent:${be.id}`,agentId:be.id});for(const be of r)q.push({kind:"team",id:`team:${be.id}`,teamId:be.id});if(hn)for(const be of Qr)q.push({kind:"channel",id:`channel:${be.channelKey}`,channelKey:be.channelKey});return q},[e,i,is,xs,r,t,hn]),El=S.useRef(Rl);El.current=Rl;const Al=S.useCallback(q=>{q.kind==="dm"?v(q.userId):q.kind==="channel"?p(q.channelKey):q.kind==="agent"?f(q.agentId):q.kind==="team"&&b?.(q.teamId),requestAnimationFrame(()=>{document.querySelector(`[data-l1-nav-id="${q.id}"]`)?.scrollIntoView({block:"nearest"})})},[v,p,f,b]);S.useEffect(()=>{if(B||ae||!j||L)return;const q=me=>{const be=W?.keyboardPane??"content";if(be==="l0"||be==="l2"||me.metaKey||me.ctrlKey||me.altKey||Vm(me.target))return;const Ie=me.key.length===1?me.key.toLowerCase():me.key;if(Ie==="h"||Ie==="ArrowLeft"){if(be!=="l1")return;me.preventDefault(),me.stopPropagation(),W?.setL0FocusPageId(Yt.TEAM),W?.setLeftCollapsed(!1),W?.setKeyboardPane("l0");return}if(Ie==="l"||Ie==="ArrowRight"){if(be!=="l1")return;me.preventDefault(),me.stopPropagation(),F&&W?.setKeyboardPane("l2");return}if(be!=="l1"&&!(U&&(Ie==="j"||Ie==="k"||Ie==="ArrowDown"||Ie==="ArrowUp")))return;const Ke=Ie==="j"||Ie==="ArrowDown"?1:Ie==="k"||Ie==="ArrowUp"?-1:0;if(!Ke)return;me.preventDefault(),me.stopPropagation(),W?.setKeyboardPane("l1");const Je=El.current;if(Je.length===0)return;let lt=-1;if(l==="dm"){const Ot=u||e?.id;Ot&&(lt=Je.findIndex(cs=>cs.kind==="dm"&&cs.userId===Ot))}else l==="direct"?lt=Je.findIndex(Ot=>Ot.kind==="agent"&&Ot.agentId===h):l==="channel"&&(lt=Je.findIndex(Ot=>Ot.kind==="channel"&&Ot.channelKey===d),lt<0&&g&&(lt=Je.findIndex(Ot=>Ot.kind==="team"&&Ot.teamId===g)));lt<0&&(lt=Ke>0?-1:0);const Rt=Math.max(0,Math.min(Je.length-1,lt+Ke));Al(Je[Rt])};return document.addEventListener("keydown",q,!0),()=>document.removeEventListener("keydown",q,!0)},[B,ae,j,L,W,U,F,l,u,e?.id,h,d,g,Al]);const $i=q=>q?U?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60";return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l1",className:`bg-surface-primary flex flex-col ${T!=null?"shrink-0":"flex-1 min-w-0"} ${U?"ring-1 ring-inset ring-brand-500/30":""}`,style:L?{display:"none"}:T!=null?{width:T}:void 0,children:[c.jsxs("div",{"data-electron-drag":!0,className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[ae&&c.jsx(Vk,{}),!ae&&M&&c.jsx("button",{onClick:M,className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 bg-brand-500/15 text-brand-500 hover:bg-brand-500/25",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsx("h2",{className:"text-lg font-semibold",children:X("chat.title")}),D&&c.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:Ze,children:[c.jsxs("button",{onClick:()=>ut(!Bt),className:"flex items-center gap-1 px-2.5 py-1 text-xs font-medium text-fg-secondary hover:text-fg-primary bg-surface-elevated/60 hover:bg-surface-elevated rounded-md transition-colors",children:[c.jsx("span",{className:"text-brand-500",children:"+"})," ",X("chat.manage"),c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${Bt?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M5.23 7.21a.75.75 0 011.06.02L10 11.168l3.71-3.938a.75.75 0 111.08 1.04l-4.25 4.5a.75.75 0 01-1.08 0l-4.25-4.5a.75.75 0 01.02-1.06z",clipRule:"evenodd"})})]}),Bt&&c.jsxs("div",{ref:q=>{if(!q)return;const me=q.getBoundingClientRect(),be=window.innerWidth,Ie=8;me.right>be-Ie&&(q.style.left="auto",q.style.right="0"),me.left<Ie&&(q.style.left="0",q.style.right="auto")},className:"absolute right-0 top-full mt-1 w-48 max-w-[calc(100vw-1rem)] bg-surface-elevated border border-border-default rounded-lg shadow-xl z-50 overflow-hidden",children:[c.jsxs("button",{onClick:()=>{ut(!1),ye("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),c.jsx("circle",{cx:"12",cy:"5",r:"2"}),c.jsx("path",{d:"M12 7v4"}),c.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),c.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),X("chat.addAgent")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.addAgentDesc")})]}),c.jsxs("button",{onClick:()=>{ut(!1),ye("team")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),c.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),X("chat.newTeam")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.newTeamDesc")})]}),c.jsxs("button",{onClick:()=>{ut(!1),oe(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-green-600 hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M20 8v6"}),c.jsx("path",{d:"M23 11h-6"})]}),X("chat.addHuman")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.addHumanDesc")})]}),c.jsxs("button",{onClick:()=>{ut(!1),Qe(!0)},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated border-t border-border-default transition-colors",children:[c.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z"}),c.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),X("chat.newGroupChat")]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X("chat.newGroupChatDesc")})]}),Xe!==null&&c.jsxs("button",{onClick:()=>{ut(!1),ze()},disabled:De,className:`w-full text-left px-4 py-2.5 text-xs hover:bg-surface-elevated border-t border-border-default transition-colors disabled:opacity-50 ${Xe?"text-green-600":"text-red-500"}`,children:[c.jsx("div",{className:"font-medium flex items-center gap-1.5",children:Xe?c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",X("chat.resume")]}):c.jsxs(c.Fragment,{children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",X("contextMenu.stopAll")]})}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:X(Xe?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),c.jsxs("div",{ref:Mt,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.people")}),e&&c.jsxs("button",{"data-l1-nav-id":`dm:${e.id}`,onClick:()=>v(e.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${$i(l==="dm"&&(u===e.id||!u))}`,children:[c.jsx(Ns,{name:e.name,avatarUrl:e.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:e.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:X("chat.myNotes")})]}),c.jsx("span",{className:"text-fg-secondary shrink-0",children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),i.filter(q=>q.id!==e?.id).map(q=>{const me=e?.id?`dm:${[e.id,q.id].sort().join(":")}`:"",be=me&&_?_[me]??0:0;return c.jsxs("button",{"data-l1-nav-id":`dm:${q.id}`,onClick:()=>v(q.id),onContextMenu:Ie=>{if(!D||q.id===e?.id)return;Ie.preventDefault();const Ke=ge(Ie);At({userId:q.id,...Ke})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${l==="dm"&&u===q.id?U?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[c.jsx(Ns,{name:q.name,avatarUrl:q.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:q.name}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:q.email||q.role})]}),be>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:be}):c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},q.id)})]}),is.custom.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:X("chat.groups")}),is.custom.map(q=>{const me=l==="channel"&&d===q.channelKey;return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),onContextMenu:be=>{be.preventDefault();const Ie=ge(be);yt({gcId:q.id,...Ie})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${$i(me)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:q.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:X("chat.members_other",{count:q.memberCount??0})})]})]},q.id)})]}),E?c.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((q,me)=>c.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[c.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),c.jsxs("div",{className:"flex-1 space-y-1.5",children:[c.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),c.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),c.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},me))}):t.length===0&&r.length===0?c.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:X("chat.noAgentsYet")}):null,is.unmatched.map(q=>{const me=_?.[q.channelKey]??0;return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${$i(l==="channel"&&d===q.channelKey)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:q.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:X("chat.groupChat")})]}),me>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none",children:me}):q.memberCount!==void 0&&q.memberCount>0?c.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:q.memberCount}):null]},q.id)}),xs.ungrouped.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.agents")}),xs.ungrouped.map(q=>Vn(q))]}),r.length>0&&c.jsxs("div",{className:"mb-2",ref:us,children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:X("chat.teams")}),r.map(q=>{const me=xs.byTeam.get(q.id)??[],be=q.members?.length||me.length;return jl(q.id,q,be,q.name)})]}),r.length===0&&xs.ungrouped.length===0&&t.length>0&&t.map(q=>Vn(q)),Qr.length>0&&c.jsxs("div",{className:"mb-2",children:[c.jsxs("button",{onClick:()=>jt(q=>!q),className:"w-full flex items-center gap-1.5 px-2.5 py-1 text-[10px] font-semibold text-fg-muted uppercase tracking-wider hover:text-fg-secondary transition-colors",children:[c.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${hn?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:c.jsx("path",{fillRule:"evenodd",d:"M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z",clipRule:"evenodd"})}),X("chat.agentDMs"),c.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:Qr.length})]}),hn&&Qr.map(q=>{const me=l==="channel"&&d===q.channelKey,be=_?.[q.channelKey]??0,Ie=q.name.replace(/^DM:\s*/,"");return c.jsxs("button",{"data-l1-nav-id":`channel:${q.channelKey}`,onClick:()=>p(q.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 pl-5 py-1.5 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${$i(me)}`,children:[c.jsx("div",{className:"w-5 h-5 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay/60 text-fg-tertiary text-[9px]",children:c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:Ie}),be>0&&c.jsx("span",{className:"min-w-[14px] h-[14px] flex items-center justify-center text-[8px] font-semibold text-white bg-red-500 rounded-full px-0.5 leading-none",children:be})]},q.id)})]})]})]}),R&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:R,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),G&&(()=>{const q=xs.byTeam.get(G.teamId)??[],me=q.some(Ie=>Ie.status==="offline"),be=q.some(Ie=>Ie.status!=="offline");return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:G.x,top:G.y},onClick:Ie=>Ie.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{const Ie=zr.get(G.teamId);Ie&&(hi(G.teamId),$t(Ie.name)),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),c.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),X("contextMenu.renameTeam")]}),me&&c.jsxs("button",{onClick:()=>{Fo(G.teamId,"start"),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),X("contextMenu.startAll")]}),be&&c.jsxs("button",{onClick:()=>{Fo(G.teamId,"stop"),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),X("contextMenu.stopAll")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{qe(null),Lr.navigate(Yt.STORE)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),X("chat.addAgent")]}),fe.length>0&&c.jsxs("button",{onClick:()=>{qe(null),pe(G.teamId)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),c.jsx("polyline",{points:"17 11 19 13 23 9"})]}),X("contextMenu.addExisting")]}),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{const Ie=zr.get(G.teamId);Ie&&ln(G.teamId,Ie.name),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.deleteTeam")]})]})})(),He&&(()=>{const q=t.find(Je=>Je.id===He.agentId);if(!q||!D)return null;const be=(He.teamId?zr.get(He.teamId):void 0)?.managerId===q.id,Ie=q.id===e?.id,Ke=_s(q);return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:He.x,top:He.y,maxHeight:Math.max(160,window.innerHeight-He.y-8)},onClick:Je=>Je.stopPropagation(),children:[Ke&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:X("contextMenu.orgSecretaryProtected")}),c.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),c.jsxs("button",{onClick:()=>{Ye(null),k(q.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),X("contextMenu.viewProfile")]}),q.status==="offline"?c.jsxs("button",{onClick:()=>{Ql(q.id,"offline"),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),X("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{Ql(q.id,q.status??"idle"),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),X("contextMenu.stop")]}),!Ke&&He.teamId&&!be&&c.jsxs("button",{onClick:()=>{cn(He.teamId,q.id,"agent"),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),X("contextMenu.setAsManager")]}),!Ke&&He.teamId&&c.jsxs("button",{onClick:()=>{Os(He.teamId,q.id),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),X("contextMenu.removeFromTeam")]}),!Ke&&(()=>{const Je=r.filter(Ot=>Ot.id!==He.teamId);if(Je.length===0)return null;const lt=bt.trim().toLowerCase(),Rt=lt?Je.filter(Ot=>Ot.name.toLowerCase().includes(lt)):Je;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>xt(Ot=>!Ot),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:X("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${pt?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),pt&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:Ot=>Ot.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:bt,onChange:Ot=>vt(Ot.target.value),onKeyDown:Ot=>Ot.stopPropagation(),placeholder:X("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:Rt.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:X("contextMenu.moveToEmpty")}):Rt.map(Ot=>c.jsx("button",{type:"button",onClick:async()=>{He.teamId&&await te.teams.removeMember(He.teamId,q.id),await te.teams.addMember(Ot.id,q.id,"agent"),O(),m(),_t(),Ye(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:Ot.name,children:Ot.name},Ot.id))})]})]})})(),!Ke&&!Ie&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{rs(q.id,q.name,"agent",He.teamId),Ye(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.removeFromOrg")]})]})]})})(),Pe&&(()=>{const q=i.find(me=>me.id===Pe.userId);return!q||!D?null:c.jsx("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:Pe.x,top:Pe.y},onClick:me=>me.stopPropagation(),children:c.jsxs("button",{onClick:()=>{rs(q.id,q.name,"human"),At(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("contextMenu.removeFromOrg")]})})})(),A&&c.jsx(D2,{onClose:()=>J(!1),onCreate:async(q,me)=>{try{const{team:be}=await te.teams.create(q,me);J(!1),O(),ot(be.id),setTimeout(()=>{document.querySelector(`[data-team-id="${be.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>ot(null),3e3)}catch(be){$e(X("chat.failedToCreateTeam",{message:be instanceof Error?be.message:String(be)}),"error")}}}),Y&&c.jsx(I2,{onClose:()=>{oe(!1),x?.()},onAdd:async(q,me,be)=>{const{inviteToken:Ie}=await te.users.create(q,me,void 0,be);return x?.(),{inviteToken:Ie}}}),K!==null&&c.jsx(B2,{teamId:K,ungrouped:fe,onClose:()=>pe(null),onAdd:async(q,me)=>{await te.teams.addMember(K,q,me),pe(null),O(),_t()}}),je&&c.jsx(W2,{onClose:()=>we(!1),onConnected:()=>{we(!1),m(),O()}}),rt&&(()=>{const q=o.find(me=>me.id===rt.gcId);return q?c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-44 max-w-[calc(100vw-1rem)] max-h-[calc(100vh-1rem)] overflow-y-auto",style:{left:rt.x,top:rt.y},onClick:me=>me.stopPropagation(),children:[q.type==="custom"&&c.jsxs("button",{onClick:()=>{yt(null),C?C(q.channelKey):p(q.channelKey)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),X("contextMenu.manageMembers")]}),c.jsxs("button",{onClick:async()=>{yt(null),Te(X("modals.deleteGroupChat.title"),X("modals.deleteGroupChat.message",{name:q.name}),async()=>{await te.groupChats.delete(q.id),y()},X("modals.deleteGroupChat.confirm"))},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),X("modals.deleteGroupChat.menuLabel")]})]}):null})(),Ge&&c.jsx(eP,{agents:t,humans:i,authUser:e,onClose:()=>Qe(!1),onCreate:async(q,me,be,Ie)=>{await te.groupChats.create({name:q,memberIds:me,memberTypes:be,memberNames:Ie,creatorId:e?.id,creatorName:e?.name}),Qe(!1),y()}}),Ee&&c.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>ye(null),children:c.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:q=>q.stopPropagation(),children:[c.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[c.jsx("h3",{className:"text-sm font-semibold",children:X(Ee==="agent"?"chat.addAgent":"chat.newTeam")}),c.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:X("chat.methodChoiceSubtitle")})]}),c.jsxs("div",{className:"p-3 space-y-2",children:[c.jsxs("button",{onClick:()=>{const q=Ee;ye(null);const me=t.find(be=>be.role==="secretary")??t.find(be=>be.name?.toLowerCase().includes("secretary"));me?(f(me.id),Lr.navigate(Yt.TEAM,{agentId:me.id,prefillMessage:X(q==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):q==="agent"?Lr.navigate(Yt.STORE):J(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-brand-500/30 bg-brand-500/5 hover:bg-brand-500/10 transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-brand-500",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"}),c.jsx("path",{d:"M20 3v4"}),c.jsx("path",{d:"M22 5h-4"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:X("chat.methodSecretary")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:X("chat.methodSecretaryDesc")})]}),c.jsx("span",{className:"text-[9px] px-1.5 py-0.5 rounded-full bg-brand-500/10 text-brand-500 font-medium shrink-0",children:X("chat.recommended")})]}),c.jsxs("button",{onClick:()=>{const q=Ee;ye(null),q==="agent"?Lr.navigate(Yt.STORE):J(!0)},className:"w-full flex items-center gap-3 px-4 py-3 rounded-lg border border-border-default hover:bg-surface-overlay transition-colors text-left",children:[c.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",className:"text-fg-secondary",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),c.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:X("chat.methodManual")}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:X(Ee==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),c.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:c.jsx("button",{onClick:()=>ye(null),className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:X("common:cancel")})})]})}),Ve&&c.jsx(Wo,{title:Ve.title,message:Ve.message,confirmLabel:Ve.confirmLabel,checkboxes:Ve.checkboxes,onConfirm:q=>{Ve.onConfirm(q),ee(null)},onCancel:()=>ee(null)}),he&&c.jsx("div",{className:`fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-4 py-2.5 rounded-lg shadow-xl text-sm font-medium ${he.type==="error"?"bg-red-500/10 text-red-500 border border-red-500/30":"bg-surface-elevated/95 text-fg-primary border border-border-default/50"}`,children:he.message})]})});function i0({team:s,agents:e,humans:t,authUser:r,groupChat:i,chatMode:n,selectedAgent:a,activeChannel:o,activeDmUserId:l,teams:h,onSelectAgent:d,onSelectChannel:u,onSelectDm:f,onBack:p,onViewProfile:v,onRefreshAgents:b,onRefreshTeams:g,unreadByAgent:O,width:m,onResizeStart:x,focused:y}){const{t:k}=Pt(["team","common"]),C=zh(),P=Zm(Yt.TEAM),_=r?.role==="owner"||r?.role==="admin";ah();const T=S.useMemo(()=>e.filter(Y=>Y.teamId===s.id),[e,s.id]),R=S.useMemo(()=>{const Y=new Set((s.members??[]).filter(oe=>oe.type==="human").map(oe=>oe.id));return t.filter(oe=>Y.has(oe.id))},[s.members,t]),L=i&&n==="channel"&&o===i.channelKey,M=S.useMemo(()=>{const Y=[];i&&Y.push({kind:"channel",id:`channel:${i.channelKey}`,channelKey:i.channelKey});for(const oe of T)Y.push({kind:"agent",id:`agent:${oe.id}`,agentId:oe.id});for(const oe of R)Y.push({kind:"dm",id:`dm:${oe.id}`,userId:oe.id});return Y},[i,T,R]),E=S.useRef(M);E.current=M;const B=S.useCallback(Y=>{Y.kind==="channel"?u(Y.channelKey):Y.kind==="agent"?d(Y.agentId):f(Y.userId),requestAnimationFrame(()=>{document.querySelector(`[data-l2-nav-id="${Y.id}"]`)?.scrollIntoView({block:"nearest"})})},[u,d,f]);S.useEffect(()=>{if(!P)return;const Y=oe=>{if((C?.keyboardPane??"content")!=="l2"||oe.metaKey||oe.ctrlKey||oe.altKey||Vm(oe.target))return;const pe=oe.key.length===1?oe.key.toLowerCase():oe.key;if(pe==="h"||pe==="ArrowLeft"){oe.preventDefault(),oe.stopPropagation(),C?.setKeyboardPane("l1");return}if(pe==="l"||pe==="ArrowRight"){oe.preventDefault(),oe.stopPropagation();return}const je=pe==="j"||pe==="ArrowDown"?1:pe==="k"||pe==="ArrowUp"?-1:0;if(!je)return;oe.preventDefault(),oe.stopPropagation();const we=E.current;if(we.length===0)return;let Ge=-1;n==="channel"?Ge=we.findIndex(Ee=>Ee.kind==="channel"&&Ee.channelKey===o):n==="direct"?Ge=we.findIndex(Ee=>Ee.kind==="agent"&&Ee.agentId===a):n==="dm"&&l&&(Ge=we.findIndex(Ee=>Ee.kind==="dm"&&Ee.userId===l)),Ge<0&&(Ge=je>0?-1:0);const Qe=Math.max(0,Math.min(we.length-1,Ge+je));B(we[Qe])};return document.addEventListener("keydown",Y,!0),()=>document.removeEventListener("keydown",Y,!0)},[P,C,n,o,a,l,B]);const U=Y=>Y?y?"bg-brand-500/25 ring-1 ring-inset ring-brand-500/40":"bg-surface-overlay":"hover:bg-surface-overlay/60",[F,X]=S.useState(null),[ae,j]=S.useState(!1),[W,D]=S.useState(""),[V,se]=S.useState(null),fe=(Y,oe,K,pe,je)=>{se({title:Y,message:oe,onConfirm:K,confirmLabel:pe,checkboxes:je})},z=S.useCallback((Y,oe=176,K=220)=>{const pe=window.innerWidth,je=window.innerHeight,we=8;let Ge=Y.clientX,Qe=Y.clientY;return Ge+oe>pe-we&&(Ge=Math.max(we,pe-oe-we)),Qe+K>je-we&&(Qe=Math.max(we,je-K-we)),Ge=Math.max(we,Math.min(Ge,pe-oe-we)),Qe=Math.max(we,Math.min(Qe,je-K-we)),{x:Ge,y:Qe}},[]);S.useEffect(()=>{if(!F)return;const Y=()=>X(null),oe=setTimeout(()=>document.addEventListener("click",Y),0);return()=>{clearTimeout(oe),document.removeEventListener("click",Y)}},[F]);const re=S.useCallback(async(Y,oe)=>{oe==="offline"?await te.agents.start(Y):await te.agents.stop(Y),b()},[b]),Z=S.useCallback(async Y=>{await te.teams.update(s.id,{managerId:Y,managerType:"agent"}),g()},[s.id,g]),A=S.useCallback(async Y=>{await te.teams.removeMember(s.id,Y),g(),b()},[s.id,g,b]),J=S.useCallback(async(Y,oe)=>{await te.teams.removeMember(s.id,Y),await te.teams.addMember(oe,Y,"agent"),g(),b()},[s.id,g,b]);return c.jsxs(c.Fragment,{children:[c.jsxs("div",{"data-keyboard-pane":"l2",className:`bg-surface-primary flex flex-col shrink-0 ${y?"ring-1 ring-inset ring-brand-500/30":""}`,style:m!=null?{width:m}:{width:260},children:[c.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[c.jsx("button",{onClick:p,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:k("common:back",{defaultValue:"Back"}),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"truncate font-semibold text-sm",children:s.name}),s.description&&c.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:s.description})]})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[i&&c.jsxs("div",{className:"mb-3",children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:k("chat.groupChat",{defaultValue:"Group Chat"})}),c.jsxs("button",{"data-l2-nav-id":`channel:${i.channelKey}`,onClick:()=>u(i.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${U(!!L)}`,children:[c.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:s.name}),c.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:k("chat.members_other",{count:i.memberCount||T.length+R.length})})]})]})]}),T.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[k("chat.agents",{defaultValue:"Agents"}),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:T.length})]}),T.map(Y=>{const oe=n==="direct"&&a===Y.id,K=s.managerId===Y.id,pe=Y.status==="offline",je=Ol(Y.status,hs.isAgentStreaming(Y.id)).dotClass;return c.jsxs("button",{"data-l2-nav-id":`agent:${Y.id}`,onClick:()=>d(Y.id),onContextMenu:we=>{if(!_)return;we.preventDefault();const Ge=z(we);j(!1),D(""),X({agentId:Y.id,...Ge})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${pe?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${U(oe)}`,children:[c.jsx(Ns,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:pe?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"flex items-center gap-1",children:[c.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:Y.name}),K&&c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),pe&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:k("common:status.offline")})]}),c.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:Y.role||" "})]}),(O?.get(Y.id)??0)>0&&c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:O.get(Y.id)}),c.jsx("span",{title:Y.status,onClick:we=>{we.stopPropagation(),v(Y.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${je}`})]},Y.id)})]}),R.length>0&&c.jsxs("div",{className:"mb-3",children:[c.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[k("chat.people"),c.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:R.length})]}),R.map(Y=>{const oe=Y.id===r?.id,K=n==="dm"&&l===Y.id;return c.jsxs("button",{"data-l2-nav-id":`dm:${Y.id}`,onClick:()=>f(Y.id),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${U(K)}`,children:[c.jsx(Ns,{name:Y.name,avatarUrl:Y.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[Y.name,oe?` (${k("chat.you",{defaultValue:"You"})})`:""]}),c.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:Y.email||Y.role})]}),c.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},Y.id)})]}),T.length===0&&R.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:k("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),x&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:x,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),F&&(()=>{const Y=T.find(K=>K.id===F.agentId);if(!Y||!_)return null;const oe=s.managerId===Y.id;return c.jsxs("div",{className:"fixed bg-surface-elevated border border-border-default rounded-lg shadow-xl py-1 z-50 w-48 max-w-[calc(100vw-1rem)] overflow-y-auto",style:{left:F.x,top:F.y,maxHeight:Math.max(160,window.innerHeight-F.y-8)},onClick:K=>K.stopPropagation(),children:[c.jsxs("button",{onClick:()=>{X(null),v(Y.id)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-brand-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),k("contextMenu.viewProfile")]}),Y.status==="offline"?c.jsxs("button",{onClick:()=>{re(Y.id,"offline"),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),k("contextMenu.start")]}):c.jsxs("button",{onClick:()=>{re(Y.id,Y.status??"idle"),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),k("contextMenu.stop")]}),!oe&&c.jsxs("button",{onClick:()=>{Z(Y.id),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-amber-600 flex items-center gap-2",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"})}),k("contextMenu.setAsManager")]}),c.jsxs("button",{onClick:()=>{A(Y.id),X(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"9 14 4 9 9 4"}),c.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),k("contextMenu.removeFromTeam")]}),(()=>{const K=h.filter(we=>we.id!==s.id);if(K.length===0)return null;const pe=W.trim().toLowerCase(),je=pe?K.filter(we=>we.name.toLowerCase().includes(pe)):K;return c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{type:"button",onClick:()=>j(we=>!we),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M5 12h14"}),c.jsx("path",{d:"M12 5l7 7-7 7"})]}),c.jsx("span",{className:"flex-1",children:k("contextMenu.moveTo")}),c.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:`shrink-0 text-fg-tertiary transition-transform ${ae?"rotate-180":""}`,children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),ae&&c.jsxs("div",{className:"px-2 pb-1.5",onClick:we=>we.stopPropagation(),children:[c.jsx("input",{autoFocus:!0,value:W,onChange:we=>D(we.target.value),onKeyDown:we=>we.stopPropagation(),placeholder:k("contextMenu.moveToSearch"),className:"w-full mb-1 px-2 py-1.5 text-xs rounded-md bg-surface-overlay border border-border-default text-fg-primary placeholder:text-fg-tertiary outline-none focus:border-brand-500/50"}),c.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:je.length===0?c.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:k("contextMenu.moveToEmpty")}):je.map(we=>c.jsx("button",{type:"button",onClick:()=>{J(Y.id,we.id),X(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:we.name,children:we.name},we.id))})]})]})})(),c.jsx("div",{className:"border-t border-border-default/50 my-1"}),c.jsxs("button",{onClick:()=>{fe(`${k("common:remove")} "${Y.name}"?`,k("modals.removeAgent.message"),async K=>{const pe=K?.purgeFiles??!1;i?.channelKey&&localStorage.setItem("markus_nav_after_remove","channel:"+i.channelKey),await te.agents.remove(Y.id,{purgeFiles:pe}),b(),X(null)},k("common:remove"),[{id:"purgeFiles",label:k("modals.removeAgent.purgeFiles"),defaultChecked:!1}])},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"3 6 5 6 21 6"}),c.jsx("path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"})]}),k("contextMenu.removeFromOrg")]})]})})(),V&&c.jsx(Wo,{title:V.title,message:V.message,confirmLabel:V.confirmLabel,checkboxes:V.checkboxes,onConfirm:Y=>{V.onConfirm(Y),se(null)},onCancel:()=>se(null)})]})}function Pf(){return Pf=Object.assign?Object.assign.bind():function(s){for(var e=1;e<arguments.length;e++){var t=arguments[e];for(var r in t)({}).hasOwnProperty.call(t,r)&&(s[r]=t[r])}return s},Pf.apply(null,arguments)}function sP(s,e){if(s==null)return{};var t={};for(var r in s)if({}.hasOwnProperty.call(s,r)){if(e.indexOf(r)!==-1)continue;t[r]=s[r]}return t}let Tf=[],Yv=[];(()=>{let s="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e<s.length;e++)(e%2?Yv:Tf).push(t=t+s[e])})();function rP(s){if(s<768)return!1;for(let e=0,t=Tf.length;;){let r=e+t>>1;if(s<Tf[r])t=r;else if(s>=Yv[r])e=r+1;else return!0;if(e==t)return!1}}function n0(s){return s>=127462&&s<=127487}const o0=8205;function iP(s,e,t=!0,r=!0){return(t?Gv:nP)(s,e,r)}function Gv(s,e,t){if(e==s.length)return e;e&&Kv(s.charCodeAt(e))&&Jv(s.charCodeAt(e-1))&&e--;let r=mu(s,e);for(e+=a0(r);e<s.length;){let i=mu(s,e);if(r==o0||i==o0||t&&rP(i))e+=a0(i),r=i;else if(n0(i)){let n=0,a=e-2;for(;a>=0&&n0(mu(s,a));)n++,a-=2;if(n%2==0)break;e+=2}else break}return e}function nP(s,e,t){for(;e>1;){let r=Gv(s,e-2,t);if(r<e)return r;e--}return 0}function mu(s,e){let t=s.charCodeAt(e);if(!Jv(t)||e+1==s.length)return t;let r=s.charCodeAt(e+1);return Kv(r)?(t-55296<<10)+(r-56320)+65536:t}function Kv(s){return s>=56320&&s<57344}function Jv(s){return s>=55296&&s<56320}function a0(s){return s<65536?1:2}let Lt=class ey{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,r){[e,t]=jo(this,e,t);let i=[];return this.decompose(0,e,i,2),r.length&&r.decompose(0,r.length,i,3),this.decompose(t,this.length,i,1),Jr.from(i,this.length-(t-e)+r.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=jo(this,e,t);let r=[];return this.decompose(e,t,r,0),Jr.from(r,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),r=this.length-this.scanIdentical(e,-1),i=new Da(this),n=new Da(e);for(let a=t,o=t;;){if(i.next(a),n.next(a),a=0,i.lineBreak!=n.lineBreak||i.done!=n.done||i.value!=n.value)return!1;if(o+=i.value.length,i.done||o>=r)return!0}}iter(e=1){return new Da(this,e)}iterRange(e,t=this.length){return new ty(this,e,t)}iterLines(e,t){let r;if(e==null)r=this.iter();else{t==null&&(t=this.lines+1);let i=this.line(e).from;r=this.iterRange(i,Math.max(i,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new sy(r)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?ey.empty:e.length<=32?new ls(e):Jr.from(ls.split(e,[]))}};class ls extends Lt{constructor(e,t=oP(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,r,i){for(let n=0;;n++){let a=this.text[n],o=i+a.length;if((t?r:o)>=e)return new aP(i,o,r,a);i=o+1,r++}}decompose(e,t,r,i){let n=e<=0&&t>=this.length?this:new ls(l0(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(i&1){let a=r.pop(),o=Xc(n.text,a.text.slice(),0,n.length);if(o.length<=32)r.push(new ls(o,a.length+n.length));else{let l=o.length>>1;r.push(new ls(o.slice(0,l)),new ls(o.slice(l)))}}else r.push(n)}replace(e,t,r){if(!(r instanceof ls))return super.replace(e,t,r);[e,t]=jo(this,e,t);let i=Xc(this.text,Xc(r.text,l0(this.text,0,e)),t),n=this.length+r.length-(t-e);return i.length<=32?new ls(i,n):Jr.from(ls.split(i,[]),n)}sliceString(e,t=this.length,r=`
|
|
6
6
|
`){[e,t]=jo(this,e,t);let i="";for(let n=0,a=0;n<=t&&a<this.text.length;a++){let o=this.text[a],l=n+o.length;n>e&&a&&(i+=r),e<l&&t>n&&(i+=o.slice(Math.max(0,e-n),t-n)),n=l+1}return i}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let r=[],i=-1;for(let n of e)r.push(n),i+=n.length+1,r.length==32&&(t.push(new ls(r,i)),r=[],i=-1);return i>-1&&t.push(new ls(r,i)),t}}class Jr extends Lt{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let r of e)this.lines+=r.lines}lineInner(e,t,r,i){for(let n=0;;n++){let a=this.children[n],o=i+a.length,l=r+a.lines-1;if((t?l:o)>=e)return a.lineInner(e,t,r,i);i=o+1,r=l+1}}decompose(e,t,r,i){for(let n=0,a=0;a<=t&&n<this.children.length;n++){let o=this.children[n],l=a+o.length;if(e<=l&&t>=a){let h=i&((a<=e?1:0)|(l>=t?2:0));a>=e&&l<=t&&!h?r.push(o):o.decompose(e-a,t-a,r,h)}a=l+1}}replace(e,t,r){if([e,t]=jo(this,e,t),r.lines<this.lines)for(let i=0,n=0;i<this.children.length;i++){let a=this.children[i],o=n+a.length;if(e>=n&&t<=o){let l=a.replace(e-n,t-n,r),h=this.lines-a.lines+l.lines;if(l.lines<h>>4&&l.lines>h>>6){let d=this.children.slice();return d[i]=l,new Jr(d,this.length-(t-e)+r.length)}return super.replace(n,o,l)}n=o+1}return super.replace(e,t,r)}sliceString(e,t=this.length,r=`
|
|
7
7
|
`){[e,t]=jo(this,e,t);let i="";for(let n=0,a=0;n<this.children.length&&a<=t;n++){let o=this.children[n],l=a+o.length;a>e&&n&&(i+=r),e<l&&t>a&&(i+=o.sliceString(e-a,t-a,r)),a=l+1}return i}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof Jr))return 0;let r=0,[i,n,a,o]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;i+=t,n+=t){if(i==a||n==o)return r;let l=this.children[i],h=e.children[n];if(l!=h)return r+l.scanIdentical(h,t);r+=l.length+1}}static from(e,t=e.reduce((r,i)=>r+i.length+1,-1)){let r=0;for(let p of e)r+=p.lines;if(r<32){let p=[];for(let v of e)v.flatten(p);return new ls(p,t)}let i=Math.max(32,r>>5),n=i<<1,a=i>>1,o=[],l=0,h=-1,d=[];function u(p){let v;if(p.lines>n&&p instanceof Jr)for(let b of p.children)u(b);else p.lines>a&&(l>a||!l)?(f(),o.push(p)):p instanceof ls&&l&&(v=d[d.length-1])instanceof ls&&p.lines+v.lines<=32?(l+=p.lines,h+=p.length+1,d[d.length-1]=new ls(v.text.concat(p.text),v.length+1+p.length)):(l+p.lines>i&&f(),l+=p.lines,h+=p.length+1,d.push(p))}function f(){l!=0&&(o.push(d.length==1?d[0]:Jr.from(d,h)),h=-1,l=d.length=0)}for(let p of e)u(p);return f(),o.length==1?o[0]:new Jr(o,t)}}Lt.empty=new ls([""],0);function oP(s){let e=-1;for(let t of s)e+=t.length+1;return e}function Xc(s,e,t=0,r=1e9){for(let i=0,n=0,a=!0;n<s.length&&i<=r;n++){let o=s[n],l=i+o.length;l>=t&&(l>r&&(o=o.slice(0,r-i)),i<t&&(o=o.slice(t-i)),a?(e[e.length-1]+=o,a=!1):e.push(o)),i=l+1}return e}function l0(s,e,t){return Xc(s,[""],e,t)}class Da{constructor(e,t=1){this.dir=t,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[e],this.offsets=[t>0?1:(e instanceof ls?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let r=this.nodes.length-1,i=this.nodes[r],n=this.offsets[r],a=n>>1,o=i instanceof ls?i.text.length:i.children.length;if(a==(t>0?o:0)){if(r==0)return this.done=!0,this.value="",this;t>0&&this.offsets[r-1]++,this.nodes.pop(),this.offsets.pop()}else if((n&1)==(t>0?0:1)){if(this.offsets[r]+=t,e==0)return this.lineBreak=!0,this.value=`
|
|
8
8
|
`,this;e--}else if(i instanceof ls){let l=i.text[a+(t<0?-1:0)];if(this.offsets[r]+=t,l.length>Math.max(0,e))return this.value=e==0?l:t>0?l.slice(e):l.slice(0,l.length-e),this;e-=l.length}else{let l=i.children[a+(t<0?-1:0)];e>l.length?(e-=l.length,this.offsets[r]+=t):(t<0&&this.offsets[r]--,this.nodes.push(l),this.offsets.push(t>0?1:(l instanceof ls?l.text.length:l.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class ty{constructor(e,t,r){this.value="",this.done=!1,this.cursor=new Da(e,t>r?-1:1),this.pos=t>r?e.length:0,this.from=Math.min(t,r),this.to=Math.max(t,r)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let r=t<0?this.pos-this.from:this.to-this.pos;e>r&&(e=r),r-=e;let{value:i}=this.cursor.next(e);return this.pos+=(i.length+e)*t,this.value=i.length<=r?i:t<0?i.slice(i.length-r):i.slice(0,r),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class sy{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:r,value:i}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):r?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=i,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(Lt.prototype[Symbol.iterator]=function(){return this.iter()},Da.prototype[Symbol.iterator]=ty.prototype[Symbol.iterator]=sy.prototype[Symbol.iterator]=function(){return this});let aP=class{constructor(e,t,r,i){this.from=e,this.to=t,this.number=r,this.text=i}get length(){return this.to-this.from}};function jo(s,e,t){return e=Math.max(0,Math.min(s.length,e)),[e,Math.max(e,Math.min(s.length,t))]}function ws(s,e,t=!0,r=!0){return iP(s,e,t,r)}function lP(s){return s>=56320&&s<57344}function cP(s){return s>=55296&&s<56320}function Js(s,e){let t=s.charCodeAt(e);if(!cP(t)||e+1==s.length)return t;let r=s.charCodeAt(e+1);return lP(r)?(t-55296<<10)+(r-56320)+65536:t}function Hm(s){return s<=65535?String.fromCharCode(s):(s-=65536,String.fromCharCode((s>>10)+55296,(s&1023)+56320))}function ei(s){return s<65536?1:2}const Qf=/\r\n?|\n/;var $s=(function(s){return s[s.Simple=0]="Simple",s[s.TrackDel=1]="TrackDel",s[s.TrackBefore=2]="TrackBefore",s[s.TrackAfter=3]="TrackAfter",s})($s||($s={}));class oi{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;t<this.sections.length;t+=2)e+=this.sections[t];return e}get newLength(){let e=0;for(let t=0;t<this.sections.length;t+=2){let r=this.sections[t+1];e+=r<0?this.sections[t]:r}return e}get empty(){return this.sections.length==0||this.sections.length==2&&this.sections[1]<0}iterGaps(e){for(let t=0,r=0,i=0;t<this.sections.length;){let n=this.sections[t++],a=this.sections[t++];a<0?(e(r,i,n),i+=n):i+=a,r+=n}}iterChangedRanges(e,t=!1){$f(this,e,t)}get invertedDesc(){let e=[];for(let t=0;t<this.sections.length;){let r=this.sections[t++],i=this.sections[t++];i<0?e.push(r,i):e.push(i,r)}return new oi(e)}composeDesc(e){return this.empty?e:e.empty?this:ry(this,e)}mapDesc(e,t=!1){return e.empty?this:jf(this,e,t)}mapPos(e,t=-1,r=$s.Simple){let i=0,n=0;for(let a=0;a<this.sections.length;){let o=this.sections[a++],l=this.sections[a++],h=i+o;if(l<0){if(h>e)return n+(e-i);n+=o}else{if(r!=$s.Simple&&h>=e&&(r==$s.TrackDel&&i<e&&h>e||r==$s.TrackBefore&&i<e||r==$s.TrackAfter&&h>e))return null;if(h>e||h==e&&t<0&&!o)return e==i||t<0?n:n+l;n+=l}i=h}if(e>i)throw new RangeError(`Position ${e} is out of range for changeset of length ${i}`);return n}touchesRange(e,t=e){for(let r=0,i=0;r<this.sections.length&&i<=t;){let n=this.sections[r++],a=this.sections[r++],o=i+n;if(a>=0&&i<=t&&o>=e)return i<e&&o>t?"cover":!0;i=o}return!1}toString(){let e="";for(let t=0;t<this.sections.length;){let r=this.sections[t++],i=this.sections[t++];e+=(e?" ":"")+r+(i>=0?":"+i:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new oi(e)}static create(e){return new oi(e)}}class fs extends oi{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return $f(this,(t,r,i,n,a)=>e=e.replace(i,i+(r-t),a),!1),e}mapDesc(e,t=!1){return jf(this,e,t,!0)}invert(e){let t=this.sections.slice(),r=[];for(let i=0,n=0;i<t.length;i+=2){let a=t[i],o=t[i+1];if(o>=0){t[i]=o,t[i+1]=a;let l=i>>1;for(;r.length<l;)r.push(Lt.empty);r.push(a?e.slice(n,n+a):Lt.empty)}n+=a}return new fs(t,r)}compose(e){return this.empty?e:e.empty?this:ry(this,e,!0)}map(e,t=!1){return e.empty?this:jf(this,e,t,!0)}iterChanges(e,t=!1){$f(this,e,t)}get desc(){return oi.create(this.sections)}filter(e){let t=[],r=[],i=[],n=new Ua(this);e:for(let a=0,o=0;;){let l=a==e.length?1e9:e[a++];for(;o<l||o==l&&n.len==0;){if(n.done)break e;let d=Math.min(n.len,l-o);Ls(i,d,-1);let u=n.ins==-1?-1:n.off==0?n.ins:0;Ls(t,d,u),u>0&&Hi(r,t,n.text),n.forward(d),o+=d}let h=e[a++];for(;o<h;){if(n.done)break e;let d=Math.min(n.len,h-o);Ls(t,d,-1),Ls(i,d,n.ins==-1?-1:n.off==0?n.ins:0),n.forward(d),o+=d}}return{changes:new fs(t,r),filtered:oi.create(i)}}toJSON(){let e=[];for(let t=0;t<this.sections.length;t+=2){let r=this.sections[t],i=this.sections[t+1];i<0?e.push(r):i==0?e.push([r]):e.push([r].concat(this.inserted[t>>1].toJSON()))}return e}static of(e,t,r){let i=[],n=[],a=0,o=null;function l(d=!1){if(!d&&!i.length)return;a<t&&Ls(i,t-a,-1);let u=new fs(i,n);o=o?o.compose(u.map(o)):u,i=[],n=[],a=0}function h(d){if(Array.isArray(d))for(let u of d)h(u);else if(d instanceof fs){if(d.length!=t)throw new RangeError(`Mismatched change set length (got ${d.length}, expected ${t})`);l(),o=o?o.compose(d.map(o)):d}else{let{from:u,to:f=u,insert:p}=d;if(u>f||u<0||f>t)throw new RangeError(`Invalid change range ${u} to ${f} (in doc of length ${t})`);let v=p?typeof p=="string"?Lt.of(p.split(r||Qf)):p:Lt.empty,b=v.length;if(u==f&&b==0)return;u<a&&l(),u>a&&Ls(i,u-a,-1),Ls(i,f-u,b),Hi(n,i,v),a=f}}return h(e),l(!o),o}static empty(e){return new fs(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],r=[];for(let i=0;i<e.length;i++){let n=e[i];if(typeof n=="number")t.push(n,-1);else{if(!Array.isArray(n)||typeof n[0]!="number"||n.some((a,o)=>o&&typeof a!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(n.length==1)t.push(n[0],0);else{for(;r.length<i;)r.push(Lt.empty);r[i]=Lt.of(n.slice(1)),t.push(n[0],r[i].length)}}}return new fs(t,r)}static createSet(e,t){return new fs(e,t)}}function Ls(s,e,t,r=!1){if(e==0&&t<=0)return;let i=s.length-2;i>=0&&t<=0&&t==s[i+1]?s[i]+=e:i>=0&&e==0&&s[i]==0?s[i+1]+=t:r?(s[i]+=e,s[i+1]+=t):s.push(e,t)}function Hi(s,e,t){if(t.length==0)return;let r=e.length-2>>1;if(r<s.length)s[s.length-1]=s[s.length-1].append(t);else{for(;s.length<r;)s.push(Lt.empty);s.push(t)}}function $f(s,e,t){let r=s.inserted;for(let i=0,n=0,a=0;a<s.sections.length;){let o=s.sections[a++],l=s.sections[a++];if(l<0)i+=o,n+=o;else{let h=i,d=n,u=Lt.empty;for(;h+=o,d+=l,l&&r&&(u=u.append(r[a-2>>1])),!(t||a==s.sections.length||s.sections[a+1]<0);)o=s.sections[a++],l=s.sections[a++];e(i,h,n,d,u),i=h,n=d}}}function jf(s,e,t,r=!1){let i=[],n=r?[]:null,a=new Ua(s),o=new Ua(e);for(let l=-1;;){if(a.done&&o.len||o.done&&a.len)throw new Error("Mismatched change set lengths");if(a.ins==-1&&o.ins==-1){let h=Math.min(a.len,o.len);Ls(i,h,-1),a.forward(h),o.forward(h)}else if(o.ins>=0&&(a.ins<0||l==a.i||a.off==0&&(o.len<a.len||o.len==a.len&&!t))){let h=o.len;for(Ls(i,o.ins,-1);h;){let d=Math.min(a.len,h);a.ins>=0&&l<a.i&&a.len<=d&&(Ls(i,0,a.ins),n&&Hi(n,i,a.text),l=a.i),a.forward(d),h-=d}o.next()}else if(a.ins>=0){let h=0,d=a.len;for(;d;)if(o.ins==-1){let u=Math.min(d,o.len);h+=u,d-=u,o.forward(u)}else if(o.ins==0&&o.len<d)d-=o.len,o.next();else break;Ls(i,h,l<a.i?a.ins:0),n&&l<a.i&&Hi(n,i,a.text),l=a.i,a.forward(a.len-d)}else{if(a.done&&o.done)return n?fs.createSet(i,n):oi.create(i);throw new Error("Mismatched change set lengths")}}}function ry(s,e,t=!1){let r=[],i=t?[]:null,n=new Ua(s),a=new Ua(e);for(let o=!1;;){if(n.done&&a.done)return i?fs.createSet(r,i):oi.create(r);if(n.ins==0)Ls(r,n.len,0,o),n.next();else if(a.len==0&&!a.done)Ls(r,0,a.ins,o),i&&Hi(i,r,a.text),a.next();else{if(n.done||a.done)throw new Error("Mismatched change set lengths");{let l=Math.min(n.len2,a.len),h=r.length;if(n.ins==-1){let d=a.ins==-1?-1:a.off?0:a.ins;Ls(r,l,d,o),i&&d&&Hi(i,r,a.text)}else a.ins==-1?(Ls(r,n.off?0:n.len,l,o),i&&Hi(i,r,n.textBit(l))):(Ls(r,n.off?0:n.len,a.off?0:a.ins,o),i&&!a.off&&Hi(i,r,a.text));o=(n.ins>l||a.ins>=0&&a.len>l)&&(o||r.length>h),n.forward2(l),a.forward(l)}}}}class Ua{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i<e.length?(this.len=e[this.i++],this.ins=e[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return this.ins==-2}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:e}=this.set,t=this.i-2>>1;return t>=e.length?Lt.empty:e[t]}textBit(e){let{inserted:t}=this.set,r=this.i-2>>1;return r>=t.length&&!e?Lt.empty:t[r].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class Fi{constructor(e,t,r,i){this.from=e,this.to=t,this.flags=r,this.goalColumn=i}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get undirectional(){return(this.flags&64)>0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}map(e,t=-1){let r,i;return this.empty?r=i=e.mapPos(this.from,t):(r=e.mapPos(this.from,1),i=e.mapPos(this.to,-1)),r==this.from&&i==this.to?this:new Fi(r,i,this.flags,this.goalColumn)}extend(e,t=e,r=0){if(e<=this.anchor&&t>=this.anchor)return ue.range(e,t,void 0,void 0,r);let i=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return ue.range(this.anchor,i,void 0,void 0,r)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return ue.range(e.anchor,e.head)}static create(e,t,r,i){return new Fi(e,t,r,i)}}class ue{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:ue.create(this.ranges.map(r=>r.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let r=0;r<this.ranges.length;r++)if(!this.ranges[r].eq(e.ranges[r],t))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return this.ranges.length==1?this:new ue([this.main],0)}addRange(e,t=!0){return ue.create([e].concat(this.ranges),t?0:this.mainIndex+1)}replaceRange(e,t=this.mainIndex){let r=this.ranges.slice();return r[t]=e,ue.create(r,this.mainIndex)}toJSON(){return{ranges:this.ranges.map(e=>e.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new ue(e.ranges.map(t=>Fi.fromJSON(t)),e.main)}static single(e,t=e){return new ue([ue.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let r=0,i=0;i<e.length;i++){let n=e[i];if(n.empty?n.from<=r:n.from<r)return ue.normalized(e.slice(),t);r=n.to}return new ue(e,t)}static cursor(e,t=0,r,i){return Fi.create(e,e,(t==0?0:t<0?8:16)|(r==null?7:Math.min(6,r)),i)}static range(e,t,r,i,n){let a=i==null?7:Math.min(6,i);return!n&&e!=t&&(n=t<e?1:-1),n&&(a|=n<0?8:16),t<e?Fi.create(t,e,a|32,r):Fi.create(e,t,a,r)}static undirectionalRange(e,t){return Fi.create(e,t,64,void 0)}static normalized(e,t=0){let r=e[t];e.sort((i,n)=>i.from-n.from),t=e.indexOf(r);for(let i=1;i<e.length;i++){let n=e[i],a=e[i-1];if(n.empty?n.from<=a.to:n.from<a.to){let o=a.from,l=Math.max(n.to,a.to);i<=t&&t--,e.splice(--i,2,n.anchor>n.head?ue.range(l,o):ue.range(o,l))}}return new ue(e,t)}}function iy(s,e){for(let t of s.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Ym=0;class We{constructor(e,t,r,i,n){this.combine=e,this.compareInput=t,this.compare=r,this.isStatic=i,this.id=Ym++,this.default=e([]),this.extensions=typeof n=="function"?n(this):n}get reader(){return this}static define(e={}){return new We(e.combine||(t=>t),e.compareInput||((t,r)=>t===r),e.compare||(e.combine?(t,r)=>t===r:Gm),!!e.static,e.enables)}of(e){return new zc([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new zc(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new zc(e,this,2,t)}from(e,t){return t||(t=r=>r),this.compute([e],r=>t(r.field(e)))}}function Gm(s,e){return s==e||s.length==e.length&&s.every((t,r)=>t===e[r])}class zc{constructor(e,t,r,i){this.dependencies=e,this.facet=t,this.type=r,this.value=i,this.id=Ym++}dynamicSlot(e){var t;let r=this.value,i=this.facet.compareInput,n=this.id,a=e[n]>>1,o=this.type==2,l=!1,h=!1,d=[];for(let u of this.dependencies)u=="doc"?l=!0:u=="selection"?h=!0:(((t=e[u.id])!==null&&t!==void 0?t:1)&1)==0&&d.push(e[u.id]);return{create(u){return u.values[a]=r(u),1},update(u,f){if(l&&f.docChanged||h&&(f.docChanged||f.selection)||Rf(u,d)){let p=r(u);if(o?!c0(p,u.values[a],i):!i(p,u.values[a]))return u.values[a]=p,1}return 0},reconfigure:(u,f)=>{let p,v=f.config.address[n];if(v!=null){let b=ch(f,v);if(this.dependencies.every(g=>g instanceof We?f.facet(g)===u.facet(g):g instanceof Rs?f.field(g,!1)==u.field(g,!1):!0)||(o?c0(p=r(u),b,i):i(p=r(u),b)))return u.values[a]=b,0}else p=r(u);return u.values[a]=p,1}}}get extension(){return this}}function c0(s,e,t){if(s.length!=e.length)return!1;for(let r=0;r<s.length;r++)if(!t(s[r],e[r]))return!1;return!0}function Rf(s,e){let t=!1;for(let r of e)Ia(s,r)&1&&(t=!0);return t}function hP(s,e,t){let r=t.map(l=>s[l.id]),i=t.map(l=>l.type),n=r.filter(l=>!(l&1)),a=s[e.id]>>1;function o(l){let h=[];for(let d=0;d<r.length;d++){let u=ch(l,r[d]);if(i[d]==2)for(let f of u)h.push(f);else h.push(u)}return e.combine(h)}return{create(l){for(let h of r)Ia(l,h);return l.values[a]=o(l),1},update(l,h){if(!Rf(l,n))return 0;let d=o(l);return e.compare(d,l.values[a])?0:(l.values[a]=d,1)},reconfigure(l,h){let d=Rf(l,r),u=h.config.facets[e.id],f=h.facet(e);if(u&&!d&&Gm(t,u))return l.values[a]=f,0;let p=o(l);return e.compare(p,f)?(l.values[a]=f,0):(l.values[a]=p,1)}}}const dc=We.define({static:!0});class Rs{constructor(e,t,r,i,n){this.id=e,this.createF=t,this.updateF=r,this.compareF=i,this.spec=n,this.provides=void 0}static define(e){let t=new Rs(Ym++,e.create,e.update,e.compare||((r,i)=>r===i),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(dc).find(r=>r.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:r=>(r.values[t]=this.create(r),1),update:(r,i)=>{let n=r.values[t],a=this.updateF(n,i);return this.compareF(n,a)?0:(r.values[t]=a,1)},reconfigure:(r,i)=>{let n=r.facet(dc),a=i.facet(dc),o;return(o=n.find(l=>l.field==this))&&o!=a.find(l=>l.field==this)?(r.values[t]=o.create(r),1):i.config.address[this.id]!=null?(r.values[t]=i.field(this),0):(r.values[t]=this.create(r),1)}}}init(e){return[this,dc.of({field:this,create:e})]}get extension(){return this}}const Rn={lowest:4,low:3,default:2,high:1,highest:0};function ka(s){return e=>new ny(e,s)}const Pi={highest:ka(Rn.highest),high:ka(Rn.high),default:ka(Rn.default),low:ka(Rn.low),lowest:ka(Rn.lowest)};class ny{constructor(e,t){this.inner=e,this.prec=t}get extension(){return this}}class Zh{of(e){return new Ef(this,e)}reconfigure(e){return Zh.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Ef{constructor(e,t){this.compartment=e,this.inner=t}get extension(){return this}}class lh{constructor(e,t,r,i,n,a){for(this.base=e,this.compartments=t,this.dynamicSlots=r,this.address=i,this.staticValues=n,this.facets=a,this.statusTemplate=[];this.statusTemplate.length<r.length;)this.statusTemplate.push(0)}staticFacet(e){let t=this.address[e.id];return t==null?e.default:this.staticValues[t>>1]}static resolve(e,t,r){let i=[],n=Object.create(null),a=new Map;for(let f of dP(e,t,a))f instanceof Rs?i.push(f):(n[f.facet.id]||(n[f.facet.id]=[])).push(f);let o=Object.create(null),l=[],h=[];for(let f of i)o[f.id]=h.length<<1,h.push(p=>f.slot(p));let d=r?.config.facets;for(let f in n){let p=n[f],v=p[0].facet,b=d&&d[f]||[];if(p.every(g=>g.type==0))if(o[v.id]=l.length<<1|1,Gm(b,p))l.push(r.facet(v));else{let g=v.combine(p.map(O=>O.value));l.push(r&&v.compare(g,r.facet(v))?r.facet(v):g)}else{for(let g of p)g.type==0?(o[g.id]=l.length<<1|1,l.push(g.value)):(o[g.id]=h.length<<1,h.push(O=>g.dynamicSlot(O)));o[v.id]=h.length<<1,h.push(g=>hP(g,v,p))}}let u=h.map(f=>f(o));return new lh(e,a,u,o,l,n)}}function dP(s,e,t){let r=[[],[],[],[],[]],i=new Map;function n(a,o){let l=i.get(a);if(l!=null){if(l<=o)return;let h=r[l].indexOf(a);h>-1&&r[l].splice(h,1),a instanceof Ef&&t.delete(a.compartment)}if(i.set(a,o),Array.isArray(a))for(let h of a)n(h,o);else if(a instanceof Ef){if(t.has(a.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(a.compartment)||a.inner;t.set(a.compartment,h),n(h,o)}else if(a instanceof ny)n(a.inner,a.prec);else if(a instanceof Rs)r[o].push(a),a.provides&&n(a.provides,o);else if(a instanceof zc)r[o].push(a),a.facet.extensions&&n(a.facet.extensions,Rn.default);else{let h=a.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${a}).`);if(h==a)throw new Error(`Unrecognized extension value in extension set (${a}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);n(h,o)}}return n(s,Rn.default),r.reduce((a,o)=>a.concat(o))}function Ia(s,e){if(e&1)return 2;let t=e>>1,r=s.status[t];if(r==4)throw new Error("Cyclic dependency between fields and/or facets");if(r&2)return r;s.status[t]=4;let i=s.computeSlot(s,s.config.dynamicSlots[t]);return s.status[t]=2|i}function ch(s,e){return e&1?s.config.staticValues[e>>1]:s.values[e>>1]}const oy=We.define(),Af=We.define({combine:s=>s.some(e=>e),static:!0}),ay=We.define({combine:s=>s.length?s[0]:void 0,static:!0}),ly=We.define(),cy=We.define(),hy=We.define(),dy=We.define({combine:s=>s.length?s[0]:!1});class li{constructor(e,t){this.type=e,this.value=t}static define(){return new uP}}class uP{of(e){return new li(this,e)}}class fP{constructor(e){this.map=e}of(e){return new ft(this,e)}}class ft{constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new ft(this.type,t)}is(e){return this.type==e}static define(e={}){return new fP(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let r=[];for(let i of e){let n=i.map(t);n&&r.push(n)}return r}}ft.reconfigure=ft.define();ft.appendConfig=ft.define();class ds{constructor(e,t,r,i,n,a){this.startState=e,this.changes=t,this.selection=r,this.effects=i,this.annotations=n,this.scrollIntoView=a,this._doc=null,this._state=null,r&&iy(r,t.newLength),n.some(o=>o.type==ds.time)||(this.annotations=n.concat(ds.time.of(Date.now())))}static create(e,t,r,i,n,a){return new ds(e,t,r,i,n,a)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(ds.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}ds.time=li.define();ds.userEvent=li.define();ds.addToHistory=li.define();ds.remote=li.define();function mP(s,e){let t=[];for(let r=0,i=0;;){let n,a;if(r<s.length&&(i==e.length||e[i]>=s[r]))n=s[r++],a=s[r++];else if(i<e.length)n=e[i++],a=e[i++];else return t;!t.length||t[t.length-1]<n?t.push(n,a):t[t.length-1]<a&&(t[t.length-1]=a)}}function uy(s,e,t){var r;let i,n,a;return t?(i=e.changes,n=fs.empty(e.changes.length),a=s.changes.compose(e.changes)):(i=e.changes.map(s.changes),n=s.changes.mapDesc(e.changes,!0),a=s.changes.compose(i)),{changes:a,selection:e.selection?e.selection.map(n):(r=s.selection)===null||r===void 0?void 0:r.map(i),effects:ft.mapEffects(s.effects,i).concat(ft.mapEffects(e.effects,n)),annotations:s.annotations.length?s.annotations.concat(e.annotations):e.annotations,scrollIntoView:s.scrollIntoView||e.scrollIntoView}}function Mf(s,e,t){let r=e.selection,i=yo(e.annotations);return e.userEvent&&(i=i.concat(ds.userEvent.of(e.userEvent))),{changes:e.changes instanceof fs?e.changes:fs.of(e.changes||[],t,s.facet(ay)),selection:r&&(r instanceof ue?r:ue.single(r.anchor,r.head)),effects:yo(e.effects),annotations:i,scrollIntoView:!!e.scrollIntoView}}function fy(s,e,t){let r=Mf(s,e.length?e[0]:{},s.doc.length);e.length&&e[0].filter===!1&&(t=!1);for(let n=1;n<e.length;n++){e[n].filter===!1&&(t=!1);let a=!!e[n].sequential;r=uy(r,Mf(s,e[n],a?r.changes.newLength:s.doc.length),a)}let i=ds.create(s,r.changes,r.selection,r.effects,r.annotations,r.scrollIntoView);return gP(t?pP(i):i)}function pP(s){let e=s.startState,t=!0;for(let i of e.facet(ly)){let n=i(s);if(n===!1){t=!1;break}Array.isArray(n)&&(t=t===!0?n:mP(t,n))}if(t!==!0){let i,n;if(t===!1)n=s.changes.invertedDesc,i=fs.empty(e.doc.length);else{let a=s.changes.filter(t);i=a.changes,n=a.filtered.mapDesc(a.changes).invertedDesc}s=ds.create(e,i,s.selection&&s.selection.map(n),ft.mapEffects(s.effects,n),s.annotations,s.scrollIntoView)}let r=e.facet(cy);for(let i=r.length-1;i>=0;i--){let n=r[i](s);n instanceof ds?s=n:Array.isArray(n)&&n.length==1&&n[0]instanceof ds?s=n[0]:s=fy(e,yo(n),!1)}return s}function gP(s){let e=s.startState,t=e.facet(hy),r=s;for(let i=t.length-1;i>=0;i--){let n=t[i](s);n&&Object.keys(n).length&&(r=uy(r,Mf(e,n,s.changes.newLength),!0))}return r==s?s:ds.create(e,s.changes,s.selection,r.effects,r.annotations,r.scrollIntoView)}const OP=[];function yo(s){return s==null?OP:Array.isArray(s)?s:[s]}var Gt=(function(s){return s[s.Word=0]="Word",s[s.Space=1]="Space",s[s.Other=2]="Other",s})(Gt||(Gt={}));const xP=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Lf;try{Lf=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function bP(s){if(Lf)return Lf.test(s);for(let e=0;e<s.length;e++){let t=s[e];if(/\w/.test(t)||t>""&&(t.toUpperCase()!=t.toLowerCase()||xP.test(t)))return!0}return!1}function vP(s){return e=>{if(!/\S/.test(e))return Gt.Space;if(bP(e))return Gt.Word;for(let t=0;t<s.length;t++)if(e.indexOf(s[t])>-1)return Gt.Word;return Gt.Other}}class Ct{constructor(e,t,r,i,n,a){this.config=e,this.doc=t,this.selection=r,this.values=i,this.status=e.statusTemplate.slice(),this.computeSlot=n,a&&(a._state=this);for(let o=0;o<this.config.dynamicSlots.length;o++)Ia(this,o<<1);this.computeSlot=null}field(e,t=!0){let r=this.config.address[e.id];if(r==null){if(t)throw new RangeError("Field is not present in this state");return}return Ia(this,r),ch(this,r)}update(...e){return fy(this,e,!0)}applyTransaction(e){let t=this.config,{base:r,compartments:i}=t;for(let o of e.effects)o.is(Zh.reconfigure)?(t&&(i=new Map,t.compartments.forEach((l,h)=>i.set(h,l)),t=null),i.set(o.value.compartment,o.value.extension)):o.is(ft.reconfigure)?(t=null,r=o.value):o.is(ft.appendConfig)&&(t=null,r=yo(r).concat(o.value));let n;t?n=e.startState.values.slice():(t=lh.resolve(r,i,this),n=new Ct(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(l,h)=>h.reconfigure(l,this),null).values);let a=e.startState.facet(Af)?e.newSelection:e.newSelection.asSingle();new Ct(t,e.newDoc,a,n,(o,l)=>l.update(o,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:ue.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,r=e(t.ranges[0]),i=this.changes(r.changes),n=[r.range],a=yo(r.effects);for(let o=1;o<t.ranges.length;o++){let l=e(t.ranges[o]),h=this.changes(l.changes),d=h.map(i);for(let f=0;f<o;f++)n[f]=n[f].map(d);let u=i.mapDesc(h,!0);n.push(l.range.map(u)),i=i.compose(d),a=ft.mapEffects(a,d).concat(ft.mapEffects(yo(l.effects),u))}return{changes:i,selection:ue.create(n,t.mainIndex),effects:a}}changes(e=[]){return e instanceof fs?e:fs.of(e,this.doc.length,this.facet(Ct.lineSeparator))}toText(e){return Lt.of(e.split(this.facet(Ct.lineSeparator)||Qf))}sliceDoc(e=0,t=this.doc.length){return this.doc.sliceString(e,t,this.lineBreak)}facet(e){let t=this.config.address[e.id];return t==null?e.default:(Ia(this,t),ch(this,t))}toJSON(e){let t={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(e)for(let r in e){let i=e[r];i instanceof Rs&&this.config.address[i.id]!=null&&(t[r]=i.spec.toJSON(this.field(e[r]),this))}return t}static fromJSON(e,t={},r){if(!e||typeof e.doc!="string")throw new RangeError("Invalid JSON representation for EditorState");let i=[];if(r){for(let n in r)if(Object.prototype.hasOwnProperty.call(e,n)){let a=r[n],o=e[n];i.push(a.init(l=>a.spec.fromJSON(o,l)))}}return Ct.create({doc:e.doc,selection:ue.fromJSON(e.selection),extensions:t.extensions?i.concat([t.extensions]):i})}static create(e={}){let t=lh.resolve(e.extensions||[],new Map),r=e.doc instanceof Lt?e.doc:Lt.of((e.doc||"").split(t.staticFacet(Ct.lineSeparator)||Qf)),i=e.selection?e.selection instanceof ue?e.selection:ue.single(e.selection.anchor,e.selection.head):ue.single(0);return iy(i,r.length),t.staticFacet(Af)||(i=i.asSingle()),new Ct(t,r,i,t.dynamicSlots.map(()=>null),(n,a)=>a.create(n),null)}get tabSize(){return this.facet(Ct.tabSize)}get lineBreak(){return this.facet(Ct.lineSeparator)||`
|
|
@@ -41,11 +41,11 @@ import{r as S,k as Wm,u as Pt,Y as Iv,j as c,q as $o,Z as Xm,$ as zm,w as St,l a
|
|
|
41
41
|
`)))),this.register(this._terminal.onA11yTab((C=>this._handleTab(C)))),this.register(this._terminal.onKey((C=>this._handleKey(C.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,g.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,p.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(m){for(let x=0;x<m;x++)this._handleChar(" ")}_handleChar(m){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==m&&(this._charsToAnnounce+=m):this._charsToAnnounce+=m,m===`
|
|
42
42
|
`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=u.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(m){this._clearLiveRegion(),new RegExp("\\p{Control}","u").test(m)||this._charsToConsume.push(m)}_refreshRows(m,x){this._liveRegionDebouncer.refresh(m,x,this._terminal.rows)}_renderRows(m,x){const y=this._terminal.buffer,k=y.lines.length.toString();for(let C=m;C<=x;C++){const P=y.lines.get(y.ydisp+C),_=[],T=P?.translateToString(!0,void 0,void 0,_)||"",R=(y.ydisp+C+1).toString(),L=this._rowElements[C];L&&(T.length===0?(L.innerText=" ",this._rowColumns.set(L,[0,1])):(L.textContent=T,this._rowColumns.set(L,_)),L.setAttribute("aria-posinset",R),L.setAttribute("aria-setsize",k))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(m,x){const y=m.target,k=this._rowElements[x===0?1:this._rowElements.length-2];if(y.getAttribute("aria-posinset")===(x===0?"1":`${this._terminal.buffer.lines.length}`)||m.relatedTarget!==k)return;let C,P;if(x===0?(C=y,P=this._rowElements.pop(),this._rowContainer.removeChild(P)):(C=this._rowElements.shift(),P=y,this._rowContainer.removeChild(C)),C.removeEventListener("focus",this._topBoundaryFocusListener),P.removeEventListener("focus",this._bottomBoundaryFocusListener),x===0){const _=this._createAccessibilityTreeNode();this._rowElements.unshift(_),this._rowContainer.insertAdjacentElement("afterbegin",_)}else{const _=this._createAccessibilityTreeNode();this._rowElements.push(_),this._rowContainer.appendChild(_)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(x===0?-1:1),this._rowElements[x===0?1:this._rowElements.length-2].focus(),m.preventDefault(),m.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;const m=document.getSelection();if(!m)return;if(m.isCollapsed)return void(this._rowContainer.contains(m.anchorNode)&&this._terminal.clearSelection());if(!m.anchorNode||!m.focusNode)return void console.error("anchorNode and/or focusNode are null");let x={node:m.anchorNode,offset:m.anchorOffset},y={node:m.focusNode,offset:m.focusOffset};if((x.node.compareDocumentPosition(y.node)&Node.DOCUMENT_POSITION_PRECEDING||x.node===y.node&&x.offset>y.offset)&&([x,y]=[y,x]),x.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(x={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(x.node))return;const k=this._rowElements.slice(-1)[0];if(y.node.compareDocumentPosition(k)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(y={node:k,offset:k.textContent?.length??0}),!this._rowContainer.contains(y.node))return;const C=({node:T,offset:R})=>{const L=T instanceof Text?T.parentNode:T;let M=parseInt(L?.getAttribute("aria-posinset"),10)-1;if(isNaN(M))return console.warn("row is invalid. Race condition?"),null;const E=this._rowColumns.get(L);if(!E)return console.warn("columns is null. Race condition?"),null;let B=R<E.length?E[R]:E.slice(-1)[0]+1;return B>=this._terminal.cols&&(++M,B=0),{row:M,column:B}},P=C(x),_=C(y);if(P&&_){if(P.row>_.row||P.row===_.row&&P.column>=_.column)throw new Error("invalid range");this._terminal.select(P.column,P.row,(_.row-P.row)*this._terminal.cols-P.column+_.column)}}_handleResize(m){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let x=this._rowContainer.children.length;x<this._terminal.rows;x++)this._rowElements[x]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[x]);for(;this._rowElements.length>m;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const m=this._coreBrowserService.mainDocument.createElement("div");return m.setAttribute("role","listitem"),m.tabIndex=-1,this._refreshRowDimensions(m),m}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=`${this._renderService.dimensions.css.canvas.width}px`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let m=0;m<this._terminal.rows;m++)this._refreshRowDimensions(this._rowElements[m])}}_refreshRowDimensions(m){m.style.height=`${this._renderService.dimensions.css.cell.height}px`}};o.AccessibilityManager=O=h([d(1,b.IInstantiationService),d(2,v.ICoreBrowserService),d(3,v.IRenderService)],O)},3614:(a,o)=>{function l(f){return f.replace(/\r?\n/g,"\r")}function h(f,p){return p?"\x1B[200~"+f+"\x1B[201~":f}function d(f,p,v,b){f=h(f=l(f),v.decPrivateModes.bracketedPasteMode&&b.rawOptions.ignoreBracketedPasteMode!==!0),v.triggerDataEvent(f,!0),p.value=""}function u(f,p,v){const b=v.getBoundingClientRect(),g=f.clientX-b.left-10,O=f.clientY-b.top-10;p.style.width="20px",p.style.height="20px",p.style.left=`${g}px`,p.style.top=`${O}px`,p.style.zIndex="1000",p.focus()}Object.defineProperty(o,"__esModule",{value:!0}),o.rightClickHandler=o.moveTextAreaUnderMouseCursor=o.paste=o.handlePasteEvent=o.copyHandler=o.bracketTextForPaste=o.prepareTextForTerminal=void 0,o.prepareTextForTerminal=l,o.bracketTextForPaste=h,o.copyHandler=function(f,p){f.clipboardData&&f.clipboardData.setData("text/plain",p.selectionText),f.preventDefault()},o.handlePasteEvent=function(f,p,v,b){f.stopPropagation(),f.clipboardData&&d(f.clipboardData.getData("text/plain"),p,v,b)},o.paste=d,o.moveTextAreaUnderMouseCursor=u,o.rightClickHandler=function(f,p,v,b,g){u(f,p,v),g&&b.rightClickSelect(f),p.value=b.selectionText,p.select()}},7239:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorContrastCache=void 0;const h=l(1505);o.ColorContrastCache=class{constructor(){this._color=new h.TwoKeyMap,this._css=new h.TwoKeyMap}setCss(d,u,f){this._css.set(d,u,f)}getCss(d,u){return this._css.get(d,u)}setColor(d,u,f){this._color.set(d,u,f)}getColor(d,u){return this._color.get(d,u)}clear(){this._color.clear(),this._css.clear()}}},3656:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.addDisposableDomListener=void 0,o.addDisposableDomListener=function(l,h,d,u){l.addEventListener(h,d,u);let f=!1;return{dispose:()=>{f||(f=!0,l.removeEventListener(h,d,u))}}}},3551:function(a,o,l){var h=this&&this.__decorate||function(O,m,x,y){var k,C=arguments.length,P=C<3?m:y===null?y=Object.getOwnPropertyDescriptor(m,x):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(O,m,x,y);else for(var _=O.length-1;_>=0;_--)(k=O[_])&&(P=(C<3?k(P):C>3?k(m,x,P):k(m,x))||P);return C>3&&P&&Object.defineProperty(m,x,P),P},d=this&&this.__param||function(O,m){return function(x,y){m(x,y,O)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Linkifier=void 0;const u=l(3656),f=l(8460),p=l(844),v=l(2585),b=l(4725);let g=o.Linkifier=class extends p.Disposable{get currentLink(){return this._currentLink}constructor(O,m,x,y,k){super(),this._element=O,this._mouseService=m,this._renderService=x,this._bufferService=y,this._linkProviderService=k,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this.register(new f.EventEmitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this.register(new f.EventEmitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this.register((0,p.getDisposeArrayDisposable)(this._linkCacheDisposables)),this.register((0,p.toDisposable)((()=>{this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()}))),this.register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this.register((0,u.addDisposableDomListener)(this._element,"mouseleave",(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this.register((0,u.addDisposableDomListener)(this._element,"mousemove",this._handleMouseMove.bind(this))),this.register((0,u.addDisposableDomListener)(this._element,"mousedown",this._handleMouseDown.bind(this))),this.register((0,u.addDisposableDomListener)(this._element,"mouseup",this._handleMouseUp.bind(this)))}_handleMouseMove(O){this._lastMouseEvent=O;const m=this._positionFromMouseEvent(O,this._element,this._mouseService);if(!m)return;this._isMouseOut=!1;const x=O.composedPath();for(let y=0;y<x.length;y++){const k=x[y];if(k.classList.contains("xterm"))break;if(k.classList.contains("xterm-hover"))return}this._lastBufferCell&&m.x===this._lastBufferCell.x&&m.y===this._lastBufferCell.y||(this._handleHover(m),this._lastBufferCell=m)}_handleHover(O){if(this._activeLine!==O.y||this._wasResized)return this._clearCurrentLink(),this._askForLink(O,!1),void(this._wasResized=!1);this._currentLink&&this._linkAtPosition(this._currentLink.link,O)||(this._clearCurrentLink(),this._askForLink(O,!0))}_askForLink(O,m){this._activeProviderReplies&&m||(this._activeProviderReplies?.forEach((y=>{y?.forEach((k=>{k.link.dispose&&k.link.dispose()}))})),this._activeProviderReplies=new Map,this._activeLine=O.y);let x=!1;for(const[y,k]of this._linkProviderService.linkProviders.entries())m?this._activeProviderReplies?.get(y)&&(x=this._checkLinkProviderResult(y,O,x)):k.provideLinks(O.y,(C=>{if(this._isMouseOut)return;const P=C?.map((_=>({link:_})));this._activeProviderReplies?.set(y,P),x=this._checkLinkProviderResult(y,O,x),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(O.y,this._activeProviderReplies)}))}_removeIntersectingLinks(O,m){const x=new Set;for(let y=0;y<m.size;y++){const k=m.get(y);if(k)for(let C=0;C<k.length;C++){const P=k[C],_=P.link.range.start.y<O?0:P.link.range.start.x,T=P.link.range.end.y>O?this._bufferService.cols:P.link.range.end.x;for(let R=_;R<=T;R++){if(x.has(R)){k.splice(C--,1);break}x.add(R)}}}}_checkLinkProviderResult(O,m,x){if(!this._activeProviderReplies)return x;const y=this._activeProviderReplies.get(O);let k=!1;for(let C=0;C<O;C++)this._activeProviderReplies.has(C)&&!this._activeProviderReplies.get(C)||(k=!0);if(!k&&y){const C=y.find((P=>this._linkAtPosition(P.link,m)));C&&(x=!0,this._handleNewLink(C))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!x)for(let C=0;C<this._activeProviderReplies.size;C++){const P=this._activeProviderReplies.get(C)?.find((_=>this._linkAtPosition(_.link,m)));if(P){x=!0,this._handleNewLink(P);break}}return x}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(O){if(!this._currentLink)return;const m=this._positionFromMouseEvent(O,this._element,this._mouseService);m&&this._mouseDownLink===this._currentLink&&this._linkAtPosition(this._currentLink.link,m)&&this._currentLink.link.activate(O,this._currentLink.link.text)}_clearCurrentLink(O,m){this._currentLink&&this._lastMouseEvent&&(!O||!m||this._currentLink.link.range.start.y>=O&&this._currentLink.link.range.end.y<=m)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,p.disposeArray)(this._linkCacheDisposables))}_handleNewLink(O){if(!this._lastMouseEvent)return;const m=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);m&&this._linkAtPosition(O.link,m)&&(this._currentLink=O,this._currentLink.state={decorations:{underline:O.link.decorations===void 0||O.link.decorations.underline,pointerCursor:O.link.decorations===void 0||O.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,O.link,this._lastMouseEvent),O.link.decorations={},Object.defineProperties(O.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:x=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==x&&(this._currentLink.state.decorations.pointerCursor=x,this._currentLink.state.isHovered&&this._element.classList.toggle("xterm-cursor-pointer",x))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:x=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==x&&(this._currentLink.state.decorations.underline=x,this._currentLink.state.isHovered&&this._fireUnderlineEvent(O.link,x))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((x=>{if(!this._currentLink)return;const y=x.start===0?0:x.start+1+this._bufferService.buffer.ydisp,k=this._bufferService.buffer.ydisp+1+x.end;if(this._currentLink.link.range.start.y>=y&&this._currentLink.link.range.end.y<=k&&(this._clearCurrentLink(y,k),this._lastMouseEvent)){const C=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);C&&this._askForLink(C,!1)}}))))}_linkHover(O,m,x){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(m,!0),this._currentLink.state.decorations.pointerCursor&&O.classList.add("xterm-cursor-pointer")),m.hover&&m.hover(x,m.text)}_fireUnderlineEvent(O,m){const x=O.range,y=this._bufferService.buffer.ydisp,k=this._createLinkUnderlineEvent(x.start.x-1,x.start.y-y-1,x.end.x,x.end.y-y-1,void 0);(m?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(k)}_linkLeave(O,m,x){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(m,!1),this._currentLink.state.decorations.pointerCursor&&O.classList.remove("xterm-cursor-pointer")),m.leave&&m.leave(x,m.text)}_linkAtPosition(O,m){const x=O.range.start.y*this._bufferService.cols+O.range.start.x,y=O.range.end.y*this._bufferService.cols+O.range.end.x,k=m.y*this._bufferService.cols+m.x;return x<=k&&k<=y}_positionFromMouseEvent(O,m,x){const y=x.getCoords(O,m,this._bufferService.cols,this._bufferService.rows);if(y)return{x:y[0],y:y[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(O,m,x,y,k){return{x1:O,y1:m,x2:x,y2:y,cols:this._bufferService.cols,fg:k}}};o.Linkifier=g=h([d(1,b.IMouseService),d(2,b.IRenderService),d(3,v.IBufferService),d(4,b.ILinkProviderService)],g)},9042:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.tooMuchOutput=o.promptLabel=void 0,o.promptLabel="Terminal input",o.tooMuchOutput="Too much output to announce, navigate to rows manually to read"},3730:function(a,o,l){var h=this&&this.__decorate||function(b,g,O,m){var x,y=arguments.length,k=y<3?g:m===null?m=Object.getOwnPropertyDescriptor(g,O):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(b,g,O,m);else for(var C=b.length-1;C>=0;C--)(x=b[C])&&(k=(y<3?x(k):y>3?x(g,O,k):x(g,O))||k);return y>3&&k&&Object.defineProperty(g,O,k),k},d=this&&this.__param||function(b,g){return function(O,m){g(O,m,b)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OscLinkProvider=void 0;const u=l(511),f=l(2585);let p=o.OscLinkProvider=class{constructor(b,g,O){this._bufferService=b,this._optionsService=g,this._oscLinkService=O}provideLinks(b,g){const O=this._bufferService.buffer.lines.get(b-1);if(!O)return void g(void 0);const m=[],x=this._optionsService.rawOptions.linkHandler,y=new u.CellData,k=O.getTrimmedLength();let C=-1,P=-1,_=!1;for(let T=0;T<k;T++)if(P!==-1||O.hasContent(T)){if(O.loadCell(T,y),y.hasExtendedAttrs()&&y.extended.urlId){if(P===-1){P=T,C=y.extended.urlId;continue}_=y.extended.urlId!==C}else P!==-1&&(_=!0);if(_||P!==-1&&T===k-1){const R=this._oscLinkService.getLinkData(C)?.uri;if(R){const L={start:{x:P+1,y:b},end:{x:T+(_||T!==k-1?0:1),y:b}};let M=!1;if(!x?.allowNonHttpProtocols)try{const E=new URL(R);["http:","https:"].includes(E.protocol)||(M=!0)}catch{M=!0}M||m.push({text:R,range:L,activate:(E,B)=>x?x.activate(E,B,L):v(0,B),hover:(E,B)=>x?.hover?.(E,B,L),leave:(E,B)=>x?.leave?.(E,B,L)})}_=!1,y.hasExtendedAttrs()&&y.extended.urlId?(P=T,C=y.extended.urlId):(P=-1,C=-1)}}g(m)}};function v(b,g){if(confirm(`Do you want to navigate to ${g}?
|
|
43
43
|
|
|
44
|
-
WARNING: This link could potentially be dangerous`)){const O=window.open();if(O){try{O.opener=null}catch{}O.location.href=g}else console.warn("Opening link blocked as opener could not be cleared")}}o.OscLinkProvider=p=h([d(0,f.IBufferService),d(1,f.IOptionsService),d(2,f.IOscLinkService)],p)},6193:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.RenderDebouncer=void 0,o.RenderDebouncer=class{constructor(l,h){this._renderCallback=l,this._coreBrowserService=h,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(l){return this._refreshCallbacks.push(l),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(l,h,d){this._rowCount=d,l=l!==void 0?l:0,h=h!==void 0?h:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,l):l,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,h):h,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const l=Math.max(this._rowStart,0),h=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(l,h),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const l of this._refreshCallbacks)l(0);this._refreshCallbacks=[]}}},3236:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Terminal=void 0;const h=l(3614),d=l(3656),u=l(3551),f=l(9042),p=l(3730),v=l(1680),b=l(3107),g=l(5744),O=l(2950),m=l(1296),x=l(428),y=l(4269),k=l(5114),C=l(8934),P=l(3230),_=l(9312),T=l(4725),R=l(6731),L=l(8055),M=l(8969),E=l(8460),B=l(844),U=l(6114),F=l(8437),X=l(2584),ae=l(7399),j=l(5941),W=l(9074),D=l(2585),V=l(5435),se=l(4567),fe=l(779);class z extends M.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(Z={}){super(Z),this.browser=U,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new B.MutableDisposable),this._onCursorMove=this.register(new E.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new E.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new E.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new E.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new E.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new E.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new E.EventEmitter),this._onBlur=this.register(new E.EventEmitter),this._onA11yCharEmitter=this.register(new E.EventEmitter),this._onA11yTabEmitter=this.register(new E.EventEmitter),this._onWillOpen=this.register(new E.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(W.DecorationService),this._instantiationService.setService(D.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(fe.LinkProviderService),this._instantiationService.setService(T.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(p.OscLinkProvider)),this.register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this.register(this._inputHandler.onRequestRefreshRows(((A,J)=>this.refresh(A,J)))),this.register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register(this._inputHandler.onRequestWindowsOptionsReport((A=>this._reportWindowsOptions(A)))),this.register(this._inputHandler.onColor((A=>this._handleColorEvent(A)))),this.register((0,E.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,E.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,E.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,E.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize((A=>this._afterResize(A.cols,A.rows)))),this.register((0,B.toDisposable)((()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)})))}_handleColorEvent(Z){if(this._themeService)for(const A of Z){let J,Y="";switch(A.index){case 256:J="foreground",Y="10";break;case 257:J="background",Y="11";break;case 258:J="cursor",Y="12";break;default:J="ansi",Y="4;"+A.index}switch(A.type){case 0:const oe=L.color.toColorRGB(J==="ansi"?this._themeService.colors.ansi[A.index]:this._themeService.colors[J]);this.coreService.triggerDataEvent(`${X.C0.ESC}]${Y};${(0,j.toRgbString)(oe)}${X.C1_ESCAPED.ST}`);break;case 1:if(J==="ansi")this._themeService.modifyColors((K=>K.ansi[A.index]=L.channels.toColor(...A.color)));else{const K=J;this._themeService.modifyColors((pe=>pe[K]=L.channels.toColor(...A.color)))}break;case 2:this._themeService.restoreColor(A.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(Z){Z?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(se.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(Z){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(X.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(X.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const Z=this.buffer.ybase+this.buffer.y,A=this.buffer.lines.get(Z);if(!A)return;const J=Math.min(this.buffer.x,this.cols-1),Y=this._renderService.dimensions.css.cell.height,oe=A.getWidth(J),K=this._renderService.dimensions.css.cell.width*oe,pe=this.buffer.y*this._renderService.dimensions.css.cell.height,je=J*this._renderService.dimensions.css.cell.width;this.textarea.style.left=je+"px",this.textarea.style.top=pe+"px",this.textarea.style.width=K+"px",this.textarea.style.height=Y+"px",this.textarea.style.lineHeight=Y+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,d.addDisposableDomListener)(this.element,"copy",(A=>{this.hasSelection()&&(0,h.copyHandler)(A,this._selectionService)})));const Z=A=>(0,h.handlePasteEvent)(A,this.textarea,this.coreService,this.optionsService);this.register((0,d.addDisposableDomListener)(this.textarea,"paste",Z)),this.register((0,d.addDisposableDomListener)(this.element,"paste",Z)),U.isFirefox?this.register((0,d.addDisposableDomListener)(this.element,"mousedown",(A=>{A.button===2&&(0,h.rightClickHandler)(A,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this.register((0,d.addDisposableDomListener)(this.element,"contextmenu",(A=>{(0,h.rightClickHandler)(A,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),U.isLinux&&this.register((0,d.addDisposableDomListener)(this.element,"auxclick",(A=>{A.button===1&&(0,h.moveTextAreaUnderMouseCursor)(A,this.textarea,this.screenElement)})))}_bindKeys(){this.register((0,d.addDisposableDomListener)(this.textarea,"keyup",(Z=>this._keyUp(Z)),!0)),this.register((0,d.addDisposableDomListener)(this.textarea,"keydown",(Z=>this._keyDown(Z)),!0)),this.register((0,d.addDisposableDomListener)(this.textarea,"keypress",(Z=>this._keyPress(Z)),!0)),this.register((0,d.addDisposableDomListener)(this.textarea,"compositionstart",(()=>this._compositionHelper.compositionstart()))),this.register((0,d.addDisposableDomListener)(this.textarea,"compositionupdate",(Z=>this._compositionHelper.compositionupdate(Z)))),this.register((0,d.addDisposableDomListener)(this.textarea,"compositionend",(()=>this._compositionHelper.compositionend()))),this.register((0,d.addDisposableDomListener)(this.textarea,"input",(Z=>this._inputEvent(Z)),!0)),this.register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(Z){if(!Z)throw new Error("Terminal requires a parent element.");if(Z.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=Z.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),Z.appendChild(this.element);const A=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),A.appendChild(this._viewportElement),this._viewportScrollArea=this._document.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this.register((0,d.addDisposableDomListener)(this.screenElement,"mousemove",(J=>this.updateCursorStyle(J)))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),A.appendChild(this.screenElement),this.textarea=this._document.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",f.promptLabel),U.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._coreBrowserService=this.register(this._instantiationService.createInstance(k.CoreBrowserService,this.textarea,Z.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(T.ICoreBrowserService,this._coreBrowserService),this.register((0,d.addDisposableDomListener)(this.textarea,"focus",(J=>this._handleTextAreaFocus(J)))),this.register((0,d.addDisposableDomListener)(this.textarea,"blur",(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(x.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(T.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(R.ThemeService),this._instantiationService.setService(T.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(y.CharacterJoinerService),this._instantiationService.setService(T.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(P.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(T.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange((J=>this._onRender.fire(J)))),this.onResize((J=>this._renderService.resize(J.cols,J.rows))),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(O.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(C.MouseService),this._instantiationService.setService(T.IMouseService,this._mouseService),this.linkifier=this.register(this._instantiationService.createInstance(u.Linkifier,this.screenElement)),this.element.appendChild(A);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this.viewport=this._instantiationService.createInstance(v.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines((J=>this.scrollLines(J.amount,J.suppressScrollEvent,1))),this.register(this._inputHandler.onRequestSyncScrollBar((()=>this.viewport.syncScrollArea()))),this.register(this.viewport),this.register(this.onCursorMove((()=>{this._renderService.handleCursorMove(),this._syncTextArea()}))),this.register(this.onResize((()=>this._renderService.handleResize(this.cols,this.rows)))),this.register(this.onBlur((()=>this._renderService.handleBlur()))),this.register(this.onFocus((()=>this._renderService.handleFocus()))),this.register(this._renderService.onDimensionsChange((()=>this.viewport.syncScrollArea()))),this._selectionService=this.register(this._instantiationService.createInstance(_.SelectionService,this.element,this.screenElement,this.linkifier)),this._instantiationService.setService(T.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines((J=>this.scrollLines(J.amount,J.suppressScrollEvent)))),this.register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this.register(this._selectionService.onRequestRedraw((J=>this._renderService.handleSelectionChanged(J.start,J.end,J.columnSelectMode)))),this.register(this._selectionService.onLinuxMouseSelection((J=>{this.textarea.value=J,this.textarea.focus(),this.textarea.select()}))),this.register(this._onScroll.event((J=>{this.viewport.syncScrollArea(),this._selectionService.refresh()}))),this.register((0,d.addDisposableDomListener)(this._viewportElement,"scroll",(()=>this._selectionService.refresh()))),this.register(this._instantiationService.createInstance(b.BufferDecorationRenderer,this.screenElement)),this.register((0,d.addDisposableDomListener)(this.element,"mousedown",(J=>this._selectionService.handleMouseDown(J)))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(se.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",(J=>this._handleScreenReaderModeOptionChange(J)))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(g.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",(J=>{!this._overviewRulerRenderer&&J&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(g.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(m.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const Z=this,A=this.element;function J(K){const pe=Z._mouseService.getMouseReportCoords(K,Z.screenElement);if(!pe)return!1;let je,we;switch(K.overrideType||K.type){case"mousemove":we=32,K.buttons===void 0?(je=3,K.button!==void 0&&(je=K.button<3?K.button:3)):je=1&K.buttons?0:4&K.buttons?1:2&K.buttons?2:3;break;case"mouseup":we=0,je=K.button<3?K.button:3;break;case"mousedown":we=1,je=K.button<3?K.button:3;break;case"wheel":if(Z._customWheelEventHandler&&Z._customWheelEventHandler(K)===!1||Z.viewport.getLinesScrolled(K)===0)return!1;we=K.deltaY<0?0:1,je=4;break;default:return!1}return!(we===void 0||je===void 0||je>4)&&Z.coreMouseService.triggerMouseEvent({col:pe.col,row:pe.row,x:pe.x,y:pe.y,button:je,action:we,ctrl:K.ctrlKey,alt:K.altKey,shift:K.shiftKey})}const Y={mouseup:null,wheel:null,mousedrag:null,mousemove:null},oe={mouseup:K=>(J(K),K.buttons||(this._document.removeEventListener("mouseup",Y.mouseup),Y.mousedrag&&this._document.removeEventListener("mousemove",Y.mousedrag)),this.cancel(K)),wheel:K=>(J(K),this.cancel(K,!0)),mousedrag:K=>{K.buttons&&J(K)},mousemove:K=>{K.buttons||J(K)}};this.register(this.coreMouseService.onProtocolChange((K=>{K?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(K)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&K?Y.mousemove||(A.addEventListener("mousemove",oe.mousemove),Y.mousemove=oe.mousemove):(A.removeEventListener("mousemove",Y.mousemove),Y.mousemove=null),16&K?Y.wheel||(A.addEventListener("wheel",oe.wheel,{passive:!1}),Y.wheel=oe.wheel):(A.removeEventListener("wheel",Y.wheel),Y.wheel=null),2&K?Y.mouseup||(Y.mouseup=oe.mouseup):(this._document.removeEventListener("mouseup",Y.mouseup),Y.mouseup=null),4&K?Y.mousedrag||(Y.mousedrag=oe.mousedrag):(this._document.removeEventListener("mousemove",Y.mousedrag),Y.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,d.addDisposableDomListener)(A,"mousedown",(K=>{if(K.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(K))return J(K),Y.mouseup&&this._document.addEventListener("mouseup",Y.mouseup),Y.mousedrag&&this._document.addEventListener("mousemove",Y.mousedrag),this.cancel(K)}))),this.register((0,d.addDisposableDomListener)(A,"wheel",(K=>{if(!Y.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(K)===!1)return!1;if(!this.buffer.hasScrollback){const pe=this.viewport.getLinesScrolled(K);if(pe===0)return;const je=X.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(K.deltaY<0?"A":"B");let we="";for(let Ge=0;Ge<Math.abs(pe);Ge++)we+=je;return this.coreService.triggerDataEvent(we,!0),this.cancel(K,!0)}return this.viewport.handleWheel(K)?this.cancel(K):void 0}}),{passive:!1})),this.register((0,d.addDisposableDomListener)(A,"touchstart",(K=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(K),this.cancel(K)}),{passive:!0})),this.register((0,d.addDisposableDomListener)(A,"touchmove",(K=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(K)?void 0:this.cancel(K)}),{passive:!1}))}refresh(Z,A){this._renderService?.refreshRows(Z,A)}updateCursorStyle(Z){this._selectionService?.shouldColumnSelect(Z)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(Z,A,J=0){J===1?(super.scrollLines(Z,A,J),this.refresh(0,this.rows-1)):this.viewport?.scrollLines(Z)}paste(Z){(0,h.paste)(Z,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(Z){this._customKeyEventHandler=Z}attachCustomWheelEventHandler(Z){this._customWheelEventHandler=Z}registerLinkProvider(Z){return this._linkProviderService.registerLinkProvider(Z)}registerCharacterJoiner(Z){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const A=this._characterJoinerService.register(Z);return this.refresh(0,this.rows-1),A}deregisterCharacterJoiner(Z){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(Z)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(Z){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+Z)}registerDecoration(Z){return this._decorationService.registerDecoration(Z)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(Z,A,J){this._selectionService.setSelection(Z,A,J)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(Z,A){this._selectionService?.selectLines(Z,A)}_keyDown(Z){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(Z)===!1)return!1;const A=this.browser.isMac&&this.options.macOptionIsMeta&&Z.altKey;if(!A&&!this._compositionHelper.keydown(Z))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;A||Z.key!=="Dead"&&Z.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const J=(0,ae.evaluateKeyboardEvent)(Z,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(Z),J.type===3||J.type===2){const Y=this.rows-1;return this.scrollLines(J.type===2?-Y:Y),this.cancel(Z,!0)}return J.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,Z)||(J.cancel&&this.cancel(Z,!0),!J.key||!!(Z.key&&!Z.ctrlKey&&!Z.altKey&&!Z.metaKey&&Z.key.length===1&&Z.key.charCodeAt(0)>=65&&Z.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(J.key!==X.C0.ETX&&J.key!==X.C0.CR||(this.textarea.value=""),this._onKey.fire({key:J.key,domEvent:Z}),this._showCursor(),this.coreService.triggerDataEvent(J.key,!0),!this.optionsService.rawOptions.screenReaderMode||Z.altKey||Z.ctrlKey?this.cancel(Z,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(Z,A){const J=Z.isMac&&!this.options.macOptionIsMeta&&A.altKey&&!A.ctrlKey&&!A.metaKey||Z.isWindows&&A.altKey&&A.ctrlKey&&!A.metaKey||Z.isWindows&&A.getModifierState("AltGraph");return A.type==="keypress"?J:J&&(!A.keyCode||A.keyCode>47)}_keyUp(Z){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(Z)===!1||((function(A){return A.keyCode===16||A.keyCode===17||A.keyCode===18})(Z)||this.focus(),this.updateCursorStyle(Z),this._keyPressHandled=!1)}_keyPress(Z){let A;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(Z)===!1)return!1;if(this.cancel(Z),Z.charCode)A=Z.charCode;else if(Z.which===null||Z.which===void 0)A=Z.keyCode;else{if(Z.which===0||Z.charCode===0)return!1;A=Z.which}return!(!A||(Z.altKey||Z.ctrlKey||Z.metaKey)&&!this._isThirdLevelShift(this.browser,Z)||(A=String.fromCharCode(A),this._onKey.fire({key:A,domEvent:Z}),this._showCursor(),this.coreService.triggerDataEvent(A,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(Z){if(Z.data&&Z.inputType==="insertText"&&(!Z.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const A=Z.data;return this.coreService.triggerDataEvent(A,!0),this.cancel(Z),!0}return!1}resize(Z,A){Z!==this.cols||A!==this.rows?super.resize(Z,A):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(Z,A){this._charSizeService?.measure(),this.viewport?.syncScrollArea(!0)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let Z=1;Z<this.rows;Z++)this.buffer.lines.push(this.buffer.getBlankLine(F.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0}),this.viewport?.reset(),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;const Z=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this.viewport?.reset(),this._customKeyEventHandler=Z,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(X.C0.ESC+"[I"):this.coreService.triggerDataEvent(X.C0.ESC+"[O")}_reportWindowsOptions(Z){if(this._renderService)switch(Z){case V.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:const A=this._renderService.dimensions.css.canvas.width.toFixed(0),J=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${X.C0.ESC}[4;${J};${A}t`);break;case V.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:const Y=this._renderService.dimensions.css.cell.width.toFixed(0),oe=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${X.C0.ESC}[6;${oe};${Y}t`)}}cancel(Z,A){if(this.options.cancelEvents||A)return Z.preventDefault(),Z.stopPropagation(),!1}}o.Terminal=z},9924:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.TimeBasedDebouncer=void 0,o.TimeBasedDebouncer=class{constructor(l,h=1e3){this._renderCallback=l,this._debounceThresholdMS=h,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(l,h,d){this._rowCount=d,l=l!==void 0?l:0,h=h!==void 0?h:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,l):l,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,h):h;const u=Date.now();if(u-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=u,this._innerRefresh();else if(!this._additionalRefreshRequested){const f=u-this._lastRefreshMs,p=this._debounceThresholdMS-f;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),p)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const l=Math.max(this._rowStart,0),h=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(l,h)}}},1680:function(a,o,l){var h=this&&this.__decorate||function(O,m,x,y){var k,C=arguments.length,P=C<3?m:y===null?y=Object.getOwnPropertyDescriptor(m,x):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(O,m,x,y);else for(var _=O.length-1;_>=0;_--)(k=O[_])&&(P=(C<3?k(P):C>3?k(m,x,P):k(m,x))||P);return C>3&&P&&Object.defineProperty(m,x,P),P},d=this&&this.__param||function(O,m){return function(x,y){m(x,y,O)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Viewport=void 0;const u=l(3656),f=l(4725),p=l(8460),v=l(844),b=l(2585);let g=o.Viewport=class extends v.Disposable{constructor(O,m,x,y,k,C,P,_){super(),this._viewportElement=O,this._scrollArea=m,this._bufferService=x,this._optionsService=y,this._charSizeService=k,this._renderService=C,this._coreBrowserService=P,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new p.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,u.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((T=>this._activeBuffer=T.activeBuffer))),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange((T=>this._renderDimensions=T))),this._handleThemeChange(_.colors),this.register(_.onChangeColors((T=>this._handleThemeChange(T)))),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.syncScrollArea()))),setTimeout((()=>this.syncScrollArea()))}_handleThemeChange(O){this._viewportElement.style.backgroundColor=O.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame((()=>this.syncScrollArea()))}_refresh(O){if(O)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderDimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderDimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const m=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderDimensions.css.canvas.height);this._lastRecordedBufferHeight!==m&&(this._lastRecordedBufferHeight=m,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const O=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==O&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=O),this._refreshAnimationFrame=null}syncScrollArea(O=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(O);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(O)}_handleScroll(O){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const m=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:m,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const O=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(O*(this._smoothScrollState.target-this._smoothScrollState.origin)),O<1?this._coreBrowserService.window.requestAnimationFrame((()=>this._smoothScroll())):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(O,m){const x=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(m<0&&this._viewportElement.scrollTop!==0||m>0&&x<this._lastRecordedBufferHeight)||(O.cancelable&&O.preventDefault(),!1)}handleWheel(O){const m=this._getPixelsScrolled(O);return m!==0&&(this._optionsService.rawOptions.smoothScrollDuration?(this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target===-1?this._smoothScrollState.target=this._viewportElement.scrollTop+m:this._smoothScrollState.target+=m,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()):this._viewportElement.scrollTop+=m,this._bubbleScroll(O,m))}scrollLines(O){if(O!==0)if(this._optionsService.rawOptions.smoothScrollDuration){const m=O*this._currentRowHeight;this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target=this._smoothScrollState.origin+m,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()}else this._onRequestScrollLines.fire({amount:O,suppressScrollEvent:!1})}_getPixelsScrolled(O){if(O.deltaY===0||O.shiftKey)return 0;let m=this._applyScrollModifier(O.deltaY,O);return O.deltaMode===WheelEvent.DOM_DELTA_LINE?m*=this._currentRowHeight:O.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(m*=this._currentRowHeight*this._bufferService.rows),m}getBufferElements(O,m){let x,y="";const k=[],C=m??this._bufferService.buffer.lines.length,P=this._bufferService.buffer.lines;for(let _=O;_<C;_++){const T=P.get(_);if(!T)continue;const R=P.get(_+1)?.isWrapped;if(y+=T.translateToString(!R),!R||_===P.length-1){const L=document.createElement("div");L.textContent=y,k.push(L),y.length>0&&(x=L),y=""}}return{bufferElements:k,cursorElement:x}}getLinesScrolled(O){if(O.deltaY===0||O.shiftKey)return 0;let m=this._applyScrollModifier(O.deltaY,O);return O.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(m/=this._currentRowHeight+0,this._wheelPartialScroll+=m,m=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):O.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(m*=this._bufferService.rows),m}_applyScrollModifier(O,m){const x=this._optionsService.rawOptions.fastScrollModifier;return x==="alt"&&m.altKey||x==="ctrl"&&m.ctrlKey||x==="shift"&&m.shiftKey?O*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:O*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(O){this._lastTouchY=O.touches[0].pageY}handleTouchMove(O){const m=this._lastTouchY-O.touches[0].pageY;return this._lastTouchY=O.touches[0].pageY,m!==0&&(this._viewportElement.scrollTop+=m,this._bubbleScroll(O,m))}};o.Viewport=g=h([d(2,b.IBufferService),d(3,b.IOptionsService),d(4,f.ICharSizeService),d(5,f.IRenderService),d(6,f.ICoreBrowserService),d(7,f.IThemeService)],g)},3107:function(a,o,l){var h=this&&this.__decorate||function(b,g,O,m){var x,y=arguments.length,k=y<3?g:m===null?m=Object.getOwnPropertyDescriptor(g,O):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(b,g,O,m);else for(var C=b.length-1;C>=0;C--)(x=b[C])&&(k=(y<3?x(k):y>3?x(g,O,k):x(g,O))||k);return y>3&&k&&Object.defineProperty(g,O,k),k},d=this&&this.__param||function(b,g){return function(O,m){g(O,m,b)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferDecorationRenderer=void 0;const u=l(4725),f=l(844),p=l(2585);let v=o.BufferDecorationRenderer=class extends f.Disposable{constructor(b,g,O,m,x){super(),this._screenElement=b,this._bufferService=g,this._coreBrowserService=O,this._decorationService=m,this._renderService=x,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange((()=>this._doRefreshDecorations()))),this.register(this._renderService.onDimensionsChange((()=>{this._dimensionsChanged=!0,this._queueRefresh()}))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt}))),this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh()))),this.register(this._decorationService.onDecorationRemoved((y=>this._removeDecoration(y)))),this.register((0,f.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(const b of this._decorationService.decorations)this._renderDecoration(b);this._dimensionsChanged=!1}_renderDecoration(b){this._refreshStyle(b),this._dimensionsChanged&&this._refreshXPosition(b)}_createElement(b){const g=this._coreBrowserService.mainDocument.createElement("div");g.classList.add("xterm-decoration"),g.classList.toggle("xterm-decoration-top-layer",b?.options?.layer==="top"),g.style.width=`${Math.round((b.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,g.style.height=(b.options.height||1)*this._renderService.dimensions.css.cell.height+"px",g.style.top=(b.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",g.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const O=b.options.x??0;return O&&O>this._bufferService.cols&&(g.style.display="none"),this._refreshXPosition(b,g),g}_refreshStyle(b){const g=b.marker.line-this._bufferService.buffers.active.ydisp;if(g<0||g>=this._bufferService.rows)b.element&&(b.element.style.display="none",b.onRenderEmitter.fire(b.element));else{let O=this._decorationElements.get(b);O||(O=this._createElement(b),b.element=O,this._decorationElements.set(b,O),this._container.appendChild(O),b.onDispose((()=>{this._decorationElements.delete(b),O.remove()}))),O.style.top=g*this._renderService.dimensions.css.cell.height+"px",O.style.display=this._altBufferIsActive?"none":"block",b.onRenderEmitter.fire(O)}}_refreshXPosition(b,g=b.element){if(!g)return;const O=b.options.x??0;(b.options.anchor||"left")==="right"?g.style.right=O?O*this._renderService.dimensions.css.cell.width+"px":"":g.style.left=O?O*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(b){this._decorationElements.get(b)?.remove(),this._decorationElements.delete(b),b.dispose()}};o.BufferDecorationRenderer=v=h([d(1,p.IBufferService),d(2,u.ICoreBrowserService),d(3,p.IDecorationService),d(4,u.IRenderService)],v)},5871:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorZoneStore=void 0,o.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(l){if(l.options.overviewRulerOptions){for(const h of this._zones)if(h.color===l.options.overviewRulerOptions.color&&h.position===l.options.overviewRulerOptions.position){if(this._lineIntersectsZone(h,l.marker.line))return;if(this._lineAdjacentToZone(h,l.marker.line,l.options.overviewRulerOptions.position))return void this._addLineToZone(h,l.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=l.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=l.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=l.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=l.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:l.options.overviewRulerOptions.color,position:l.options.overviewRulerOptions.position,startBufferLine:l.marker.line,endBufferLine:l.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(l){this._linePadding=l}_lineIntersectsZone(l,h){return h>=l.startBufferLine&&h<=l.endBufferLine}_lineAdjacentToZone(l,h,d){return h>=l.startBufferLine-this._linePadding[d||"full"]&&h<=l.endBufferLine+this._linePadding[d||"full"]}_addLineToZone(l,h){l.startBufferLine=Math.min(l.startBufferLine,h),l.endBufferLine=Math.max(l.endBufferLine,h)}}},5744:function(a,o,l){var h=this&&this.__decorate||function(x,y,k,C){var P,_=arguments.length,T=_<3?y:C===null?C=Object.getOwnPropertyDescriptor(y,k):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(x,y,k,C);else for(var R=x.length-1;R>=0;R--)(P=x[R])&&(T=(_<3?P(T):_>3?P(y,k,T):P(y,k))||T);return _>3&&T&&Object.defineProperty(y,k,T),T},d=this&&this.__param||function(x,y){return function(k,C){y(k,C,x)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OverviewRulerRenderer=void 0;const u=l(5871),f=l(4725),p=l(844),v=l(2585),b={full:0,left:0,center:0,right:0},g={full:0,left:0,center:0,right:0},O={full:0,left:0,center:0,right:0};let m=o.OverviewRulerRenderer=class extends p.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(x,y,k,C,P,_,T){super(),this._viewportElement=x,this._screenElement=y,this._bufferService=k,this._decorationService=C,this._renderService=P,this._optionsService=_,this._coreBrowserService=T,this._colorZoneStore=new u.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement);const R=this._canvas.getContext("2d");if(!R)throw new Error("Ctx cannot be null");this._ctx=R,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,p.toDisposable)((()=>{this._canvas?.remove()})))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this.register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0))))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"}))),this.register(this._bufferService.onScroll((()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",(()=>this._queueRefresh(!0)))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh(!0)))),this._queueRefresh(!0)}_refreshDrawConstants(){const x=Math.floor(this._canvas.width/3),y=Math.ceil(this._canvas.width/3);g.full=this._canvas.width,g.left=x,g.center=y,g.right=x,this._refreshDrawHeightConstants(),O.full=0,O.left=0,O.center=g.left,O.right=g.left+g.center}_refreshDrawHeightConstants(){b.full=Math.round(2*this._coreBrowserService.dpr);const x=this._canvas.height/this._bufferService.buffer.lines.length,y=Math.round(Math.max(Math.min(x,12),6)*this._coreBrowserService.dpr);b.left=y,b.center=y,b.right=y}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*b.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*b.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*b.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*b.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const y of this._decorationService.decorations)this._colorZoneStore.addDecoration(y);this._ctx.lineWidth=1;const x=this._colorZoneStore.zones;for(const y of x)y.position!=="full"&&this._renderColorZone(y);for(const y of x)y.position==="full"&&this._renderColorZone(y);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(x){this._ctx.fillStyle=x.color,this._ctx.fillRect(O[x.position||"full"],Math.round((this._canvas.height-1)*(x.startBufferLine/this._bufferService.buffers.active.lines.length)-b[x.position||"full"]/2),g[x.position||"full"],Math.round((this._canvas.height-1)*((x.endBufferLine-x.startBufferLine)/this._bufferService.buffers.active.lines.length)+b[x.position||"full"]))}_queueRefresh(x,y){this._shouldUpdateDimensions=x||this._shouldUpdateDimensions,this._shouldUpdateAnchor=y||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};o.OverviewRulerRenderer=m=h([d(2,v.IBufferService),d(3,v.IDecorationService),d(4,f.IRenderService),d(5,v.IOptionsService),d(6,f.ICoreBrowserService)],m)},2950:function(a,o,l){var h=this&&this.__decorate||function(b,g,O,m){var x,y=arguments.length,k=y<3?g:m===null?m=Object.getOwnPropertyDescriptor(g,O):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(b,g,O,m);else for(var C=b.length-1;C>=0;C--)(x=b[C])&&(k=(y<3?x(k):y>3?x(g,O,k):x(g,O))||k);return y>3&&k&&Object.defineProperty(g,O,k),k},d=this&&this.__param||function(b,g){return function(O,m){g(O,m,b)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CompositionHelper=void 0;const u=l(4725),f=l(2585),p=l(2584);let v=o.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(b,g,O,m,x,y){this._textarea=b,this._compositionView=g,this._bufferService=O,this._optionsService=m,this._coreService=x,this._renderService=y,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(b){this._compositionView.textContent=b.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(b){if(this._isComposing||this._isSendingComposition){if(b.keyCode===229||b.keyCode===16||b.keyCode===17||b.keyCode===18)return!1;this._finalizeComposition(!1)}return b.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(b){if(this._compositionView.classList.remove("active"),this._isComposing=!1,b){const g={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let O;this._isSendingComposition=!1,g.start+=this._dataAlreadySent.length,O=this._isComposing?this._textarea.value.substring(g.start,g.end):this._textarea.value.substring(g.start),O.length>0&&this._coreService.triggerDataEvent(O,!0)}}),0)}else{this._isSendingComposition=!1;const g=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(g,!0)}}_handleAnyTextareaChanges(){const b=this._textarea.value;setTimeout((()=>{if(!this._isComposing){const g=this._textarea.value,O=g.replace(b,"");this._dataAlreadySent=O,g.length>b.length?this._coreService.triggerDataEvent(O,!0):g.length<b.length?this._coreService.triggerDataEvent(`${p.C0.DEL}`,!0):g.length===b.length&&g!==b&&this._coreService.triggerDataEvent(g,!0)}}),0)}updateCompositionElements(b){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){const g=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),O=this._renderService.dimensions.css.cell.height,m=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,x=g*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=x+"px",this._compositionView.style.top=m+"px",this._compositionView.style.height=O+"px",this._compositionView.style.lineHeight=O+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";const y=this._compositionView.getBoundingClientRect();this._textarea.style.left=x+"px",this._textarea.style.top=m+"px",this._textarea.style.width=Math.max(y.width,1)+"px",this._textarea.style.height=Math.max(y.height,1)+"px",this._textarea.style.lineHeight=y.height+"px"}b||setTimeout((()=>this.updateCompositionElements(!0)),0)}}};o.CompositionHelper=v=h([d(2,f.IBufferService),d(3,f.IOptionsService),d(4,f.ICoreService),d(5,u.IRenderService)],v)},9806:(a,o)=>{function l(h,d,u){const f=u.getBoundingClientRect(),p=h.getComputedStyle(u),v=parseInt(p.getPropertyValue("padding-left")),b=parseInt(p.getPropertyValue("padding-top"));return[d.clientX-f.left-v,d.clientY-f.top-b]}Object.defineProperty(o,"__esModule",{value:!0}),o.getCoords=o.getCoordsRelativeToElement=void 0,o.getCoordsRelativeToElement=l,o.getCoords=function(h,d,u,f,p,v,b,g,O){if(!v)return;const m=l(h,d,u);return m?(m[0]=Math.ceil((m[0]+(O?b/2:0))/b),m[1]=Math.ceil(m[1]/g),m[0]=Math.min(Math.max(m[0],1),f+(O?1:0)),m[1]=Math.min(Math.max(m[1],1),p),m):void 0}},9504:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.moveToCellSequence=void 0;const h=l(2584);function d(g,O,m,x){const y=g-u(g,m),k=O-u(O,m),C=Math.abs(y-k)-(function(P,_,T){let R=0;const L=P-u(P,T),M=_-u(_,T);for(let E=0;E<Math.abs(L-M);E++){const B=f(P,_)==="A"?-1:1;T.buffer.lines.get(L+B*E)?.isWrapped&&R++}return R})(g,O,m);return b(C,v(f(g,O),x))}function u(g,O){let m=0,x=O.buffer.lines.get(g),y=x?.isWrapped;for(;y&&g>=0&&g<O.rows;)m++,x=O.buffer.lines.get(--g),y=x?.isWrapped;return m}function f(g,O){return g>O?"A":"B"}function p(g,O,m,x,y,k){let C=g,P=O,_="";for(;C!==m||P!==x;)C+=y?1:-1,y&&C>k.cols-1?(_+=k.buffer.translateBufferLineToString(P,!1,g,C),C=0,g=0,P++):!y&&C<0&&(_+=k.buffer.translateBufferLineToString(P,!1,0,g+1),C=k.cols-1,g=C,P--);return _+k.buffer.translateBufferLineToString(P,!1,g,C)}function v(g,O){const m=O?"O":"[";return h.C0.ESC+m+g}function b(g,O){g=Math.floor(g);let m="";for(let x=0;x<g;x++)m+=O;return m}o.moveToCellSequence=function(g,O,m,x){const y=m.buffer.x,k=m.buffer.y;if(!m.buffer.hasScrollback)return(function(_,T,R,L,M,E){return d(T,L,M,E).length===0?"":b(p(_,T,_,T-u(T,M),!1,M).length,v("D",E))})(y,k,0,O,m,x)+d(k,O,m,x)+(function(_,T,R,L,M,E){let B;B=d(T,L,M,E).length>0?L-u(L,M):T;const U=L,F=(function(X,ae,j,W,D,V){let se;return se=d(j,W,D,V).length>0?W-u(W,D):ae,X<j&&se<=W||X>=j&&se<W?"C":"D"})(_,T,R,L,M,E);return b(p(_,B,R,U,F==="C",M).length,v(F,E))})(y,k,g,O,m,x);let C;if(k===O)return C=y>g?"D":"C",b(Math.abs(y-g),v(C,x));C=k>O?"D":"C";const P=Math.abs(k-O);return b((function(_,T){return T.cols-_})(k>O?g:y,m)+(P-1)*m.cols+1+((k>O?y:g)-1),v(C,x))}},1296:function(a,o,l){var h=this&&this.__decorate||function(E,B,U,F){var X,ae=arguments.length,j=ae<3?B:F===null?F=Object.getOwnPropertyDescriptor(B,U):F;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(E,B,U,F);else for(var W=E.length-1;W>=0;W--)(X=E[W])&&(j=(ae<3?X(j):ae>3?X(B,U,j):X(B,U))||j);return ae>3&&j&&Object.defineProperty(B,U,j),j},d=this&&this.__param||function(E,B){return function(U,F){B(U,F,E)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRenderer=void 0;const u=l(3787),f=l(2550),p=l(2223),v=l(6171),b=l(6052),g=l(4725),O=l(8055),m=l(8460),x=l(844),y=l(2585),k="xterm-dom-renderer-owner-",C="xterm-rows",P="xterm-fg-",_="xterm-bg-",T="xterm-focus",R="xterm-selection";let L=1,M=o.DomRenderer=class extends x.Disposable{constructor(E,B,U,F,X,ae,j,W,D,V,se,fe,z){super(),this._terminal=E,this._document=B,this._element=U,this._screenElement=F,this._viewportElement=X,this._helperContainer=ae,this._linkifier2=j,this._charSizeService=D,this._optionsService=V,this._bufferService=se,this._coreBrowserService=fe,this._themeService=z,this._terminalClass=L++,this._rowElements=[],this._selectionRenderModel=(0,b.createSelectionRenderModel)(),this.onRequestRedraw=this.register(new m.EventEmitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(C),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(R),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,v.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._themeService.onChangeColors((re=>this._injectCss(re)))),this._injectCss(this._themeService.colors),this._rowFactory=W.createInstance(u.DomRendererRowFactory,document),this._element.classList.add(k+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline((re=>this._handleLinkHover(re)))),this.register(this._linkifier2.onHideLinkUnderline((re=>this._handleLinkLeave(re)))),this.register((0,x.toDisposable)((()=>{this._element.classList.remove(k+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new f.WidthCache(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const E=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*E,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*E),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/E),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/E),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const U of this._rowElements)U.style.width=`${this.dimensions.css.canvas.width}px`,U.style.height=`${this.dimensions.css.cell.height}px`,U.style.lineHeight=`${this.dimensions.css.cell.height}px`,U.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const B=`${this._terminalSelector} .${C} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=B,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(E){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let B=`${this._terminalSelector} .${C} { color: ${E.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;B+=`${this._terminalSelector} .${C} .xterm-dim { color: ${O.color.multiplyOpacity(E.foreground,.5).css};}`,B+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;const U=`blink_underline_${this._terminalClass}`,F=`blink_bar_${this._terminalClass}`,X=`blink_block_${this._terminalClass}`;B+=`@keyframes ${U} { 50% { border-bottom-style: hidden; }}`,B+=`@keyframes ${F} { 50% { box-shadow: none; }}`,B+=`@keyframes ${X} { 0% { background-color: ${E.cursor.css}; color: ${E.cursorAccent.css}; } 50% { background-color: inherit; color: ${E.cursor.css}; }}`,B+=`${this._terminalSelector} .${C}.${T} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${U} 1s step-end infinite;}${this._terminalSelector} .${C}.${T} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${F} 1s step-end infinite;}${this._terminalSelector} .${C}.${T} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${X} 1s step-end infinite;}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-block { background-color: ${E.cursor.css}; color: ${E.cursorAccent.css};}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${E.cursor.css} !important; color: ${E.cursorAccent.css} !important;}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${E.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${E.cursor.css} inset;}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${E.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,B+=`${this._terminalSelector} .${R} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${R} div { position: absolute; background-color: ${E.selectionBackgroundOpaque.css};}${this._terminalSelector} .${R} div { position: absolute; background-color: ${E.selectionInactiveBackgroundOpaque.css};}`;for(const[ae,j]of E.ansi.entries())B+=`${this._terminalSelector} .${P}${ae} { color: ${j.css}; }${this._terminalSelector} .${P}${ae}.xterm-dim { color: ${O.color.multiplyOpacity(j,.5).css}; }${this._terminalSelector} .${_}${ae} { background-color: ${j.css}; }`;B+=`${this._terminalSelector} .${P}${p.INVERTED_DEFAULT_COLOR} { color: ${O.color.opaque(E.background).css}; }${this._terminalSelector} .${P}${p.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${O.color.multiplyOpacity(O.color.opaque(E.background),.5).css}; }${this._terminalSelector} .${_}${p.INVERTED_DEFAULT_COLOR} { background-color: ${E.foreground.css}; }`,this._themeStyleElement.textContent=B}_setDefaultSpacing(){const E=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${E}px`,this._rowFactory.defaultSpacing=E}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(E,B){for(let U=this._rowElements.length;U<=B;U++){const F=this._document.createElement("div");this._rowContainer.appendChild(F),this._rowElements.push(F)}for(;this._rowElements.length>B;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(E,B){this._refreshRowElements(E,B),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(T),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(T),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(E,B,U){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(E,B,U),this.renderRows(0,this._bufferService.rows-1),!E||!B)return;this._selectionRenderModel.update(this._terminal,E,B,U);const F=this._selectionRenderModel.viewportStartRow,X=this._selectionRenderModel.viewportEndRow,ae=this._selectionRenderModel.viewportCappedStartRow,j=this._selectionRenderModel.viewportCappedEndRow;if(ae>=this._bufferService.rows||j<0)return;const W=this._document.createDocumentFragment();if(U){const D=E[0]>B[0];W.appendChild(this._createSelectionElement(ae,D?B[0]:E[0],D?E[0]:B[0],j-ae+1))}else{const D=F===ae?E[0]:0,V=ae===X?B[0]:this._bufferService.cols;W.appendChild(this._createSelectionElement(ae,D,V));const se=j-ae-1;if(W.appendChild(this._createSelectionElement(ae+1,0,this._bufferService.cols,se)),ae!==j){const fe=X===j?B[0]:this._bufferService.cols;W.appendChild(this._createSelectionElement(j,0,fe))}}this._selectionContainer.appendChild(W)}_createSelectionElement(E,B,U,F=1){const X=this._document.createElement("div"),ae=B*this.dimensions.css.cell.width;let j=this.dimensions.css.cell.width*(U-B);return ae+j>this.dimensions.css.canvas.width&&(j=this.dimensions.css.canvas.width-ae),X.style.height=F*this.dimensions.css.cell.height+"px",X.style.top=E*this.dimensions.css.cell.height+"px",X.style.left=`${ae}px`,X.style.width=`${j}px`,X}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const E of this._rowElements)E.replaceChildren()}renderRows(E,B){const U=this._bufferService.buffer,F=U.ybase+U.y,X=Math.min(U.x,this._bufferService.cols-1),ae=this._optionsService.rawOptions.cursorBlink,j=this._optionsService.rawOptions.cursorStyle,W=this._optionsService.rawOptions.cursorInactiveStyle;for(let D=E;D<=B;D++){const V=D+U.ydisp,se=this._rowElements[D],fe=U.lines.get(V);if(!se||!fe)break;se.replaceChildren(...this._rowFactory.createRow(fe,V,V===F,j,W,X,ae,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${k}${this._terminalClass}`}_handleLinkHover(E){this._setCellUnderline(E.x1,E.x2,E.y1,E.y2,E.cols,!0)}_handleLinkLeave(E){this._setCellUnderline(E.x1,E.x2,E.y1,E.y2,E.cols,!1)}_setCellUnderline(E,B,U,F,X,ae){U<0&&(E=0),F<0&&(B=0);const j=this._bufferService.rows-1;U=Math.max(Math.min(U,j),0),F=Math.max(Math.min(F,j),0),X=Math.min(X,this._bufferService.cols);const W=this._bufferService.buffer,D=W.ybase+W.y,V=Math.min(W.x,X-1),se=this._optionsService.rawOptions.cursorBlink,fe=this._optionsService.rawOptions.cursorStyle,z=this._optionsService.rawOptions.cursorInactiveStyle;for(let re=U;re<=F;++re){const Z=re+W.ydisp,A=this._rowElements[re],J=W.lines.get(Z);if(!A||!J)break;A.replaceChildren(...this._rowFactory.createRow(J,Z,Z===D,fe,z,V,se,this.dimensions.css.cell.width,this._widthCache,ae?re===U?E:0:-1,ae?(re===F?B:X)-1:-1))}}};o.DomRenderer=M=h([d(7,y.IInstantiationService),d(8,g.ICharSizeService),d(9,y.IOptionsService),d(10,y.IBufferService),d(11,g.ICoreBrowserService),d(12,g.IThemeService)],M)},3787:function(a,o,l){var h=this&&this.__decorate||function(C,P,_,T){var R,L=arguments.length,M=L<3?P:T===null?T=Object.getOwnPropertyDescriptor(P,_):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")M=Reflect.decorate(C,P,_,T);else for(var E=C.length-1;E>=0;E--)(R=C[E])&&(M=(L<3?R(M):L>3?R(P,_,M):R(P,_))||M);return L>3&&M&&Object.defineProperty(P,_,M),M},d=this&&this.__param||function(C,P){return function(_,T){P(_,T,C)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRendererRowFactory=void 0;const u=l(2223),f=l(643),p=l(511),v=l(2585),b=l(8055),g=l(4725),O=l(4269),m=l(6171),x=l(3734);let y=o.DomRendererRowFactory=class{constructor(C,P,_,T,R,L,M){this._document=C,this._characterJoinerService=P,this._optionsService=_,this._coreBrowserService=T,this._coreService=R,this._decorationService=L,this._themeService=M,this._workCell=new p.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(C,P,_){this._selectionStart=C,this._selectionEnd=P,this._columnSelectMode=_}createRow(C,P,_,T,R,L,M,E,B,U,F){const X=[],ae=this._characterJoinerService.getJoinedCharacters(P),j=this._themeService.colors;let W,D=C.getNoBgTrimmedLength();_&&D<L+1&&(D=L+1);let V=0,se="",fe=0,z=0,re=0,Z=!1,A=0,J=!1,Y=0;const oe=[],K=U!==-1&&F!==-1;for(let pe=0;pe<D;pe++){C.loadCell(pe,this._workCell);let je=this._workCell.getWidth();if(je===0)continue;let we=!1,Ge=pe,Qe=this._workCell;if(ae.length>0&&pe===ae[0][0]){we=!0;const rt=ae.shift();Qe=new O.JoinedCellData(this._workCell,C.translateToString(!0,rt[0],rt[1]),rt[1]-rt[0]),Ge=rt[1]-1,je=Qe.getWidth()}const Ee=this._isCellInSelection(pe,P),ye=_&&pe===L,G=K&&pe>=U&&pe<=F;let qe=!1;this._decorationService.forEachDecorationAtCell(pe,P,void 0,(rt=>{qe=!0}));let He=Qe.getChars()||f.WHITESPACE_CELL_CHAR;if(He===" "&&(Qe.isUnderline()||Qe.isOverline())&&(He=" "),Y=je*E-B.get(He,Qe.isBold(),Qe.isItalic()),W){if(V&&(Ee&&J||!Ee&&!J&&Qe.bg===fe)&&(Ee&&J&&j.selectionForeground||Qe.fg===z)&&Qe.extended.ext===re&&G===Z&&Y===A&&!ye&&!we&&!qe){Qe.isInvisible()?se+=f.WHITESPACE_CELL_CHAR:se+=He,V++;continue}V&&(W.textContent=se),W=this._document.createElement("span"),V=0,se=""}else W=this._document.createElement("span");if(fe=Qe.bg,z=Qe.fg,re=Qe.extended.ext,Z=G,A=Y,J=Ee,we&&L>=pe&&L<=Ge&&(L=pe),!this._coreService.isCursorHidden&&ye&&this._coreService.isCursorInitialized){if(oe.push("xterm-cursor"),this._coreBrowserService.isFocused)M&&oe.push("xterm-cursor-blink"),oe.push(T==="bar"?"xterm-cursor-bar":T==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(R)switch(R){case"outline":oe.push("xterm-cursor-outline");break;case"block":oe.push("xterm-cursor-block");break;case"bar":oe.push("xterm-cursor-bar");break;case"underline":oe.push("xterm-cursor-underline")}}if(Qe.isBold()&&oe.push("xterm-bold"),Qe.isItalic()&&oe.push("xterm-italic"),Qe.isDim()&&oe.push("xterm-dim"),se=Qe.isInvisible()?f.WHITESPACE_CELL_CHAR:Qe.getChars()||f.WHITESPACE_CELL_CHAR,Qe.isUnderline()&&(oe.push(`xterm-underline-${Qe.extended.underlineStyle}`),se===" "&&(se=" "),!Qe.isUnderlineColorDefault()))if(Qe.isUnderlineColorRGB())W.style.textDecorationColor=`rgb(${x.AttributeData.toColorRGB(Qe.getUnderlineColor()).join(",")})`;else{let rt=Qe.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&Qe.isBold()&&rt<8&&(rt+=8),W.style.textDecorationColor=j.ansi[rt].css}Qe.isOverline()&&(oe.push("xterm-overline"),se===" "&&(se=" ")),Qe.isStrikethrough()&&oe.push("xterm-strikethrough"),G&&(W.style.textDecoration="underline");let Ye=Qe.getFgColor(),pt=Qe.getFgColorMode(),xt=Qe.getBgColor(),bt=Qe.getBgColorMode();const vt=!!Qe.isInverse();if(vt){const rt=Ye;Ye=xt,xt=rt;const yt=pt;pt=bt,bt=yt}let Pe,Et,Ft,Es=!1;switch(this._decorationService.forEachDecorationAtCell(pe,P,void 0,(rt=>{rt.options.layer!=="top"&&Es||(rt.backgroundColorRGB&&(bt=50331648,xt=rt.backgroundColorRGB.rgba>>8&16777215,Pe=rt.backgroundColorRGB),rt.foregroundColorRGB&&(pt=50331648,Ye=rt.foregroundColorRGB.rgba>>8&16777215,Et=rt.foregroundColorRGB),Es=rt.options.layer==="top")})),!Es&&Ee&&(Pe=this._coreBrowserService.isFocused?j.selectionBackgroundOpaque:j.selectionInactiveBackgroundOpaque,xt=Pe.rgba>>8&16777215,bt=50331648,Es=!0,j.selectionForeground&&(pt=50331648,Ye=j.selectionForeground.rgba>>8&16777215,Et=j.selectionForeground)),Es&&oe.push("xterm-decoration-top"),bt){case 16777216:case 33554432:Ft=j.ansi[xt],oe.push(`xterm-bg-${xt}`);break;case 50331648:Ft=b.channels.toColor(xt>>16,xt>>8&255,255&xt),this._addStyle(W,`background-color:#${k((xt>>>0).toString(16),"0",6)}`);break;default:vt?(Ft=j.foreground,oe.push(`xterm-bg-${u.INVERTED_DEFAULT_COLOR}`)):Ft=j.background}switch(Pe||Qe.isDim()&&(Pe=b.color.multiplyOpacity(Ft,.5)),pt){case 16777216:case 33554432:Qe.isBold()&&Ye<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Ye+=8),this._applyMinimumContrast(W,Ft,j.ansi[Ye],Qe,Pe,void 0)||oe.push(`xterm-fg-${Ye}`);break;case 50331648:const rt=b.channels.toColor(Ye>>16&255,Ye>>8&255,255&Ye);this._applyMinimumContrast(W,Ft,rt,Qe,Pe,Et)||this._addStyle(W,`color:#${k(Ye.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(W,Ft,j.foreground,Qe,Pe,Et)||vt&&oe.push(`xterm-fg-${u.INVERTED_DEFAULT_COLOR}`)}oe.length&&(W.className=oe.join(" "),oe.length=0),ye||we||qe?W.textContent=se:V++,Y!==this.defaultSpacing&&(W.style.letterSpacing=`${Y}px`),X.push(W),pe=Ge}return W&&V&&(W.textContent=se),X}_applyMinimumContrast(C,P,_,T,R,L){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,m.treatGlyphAsBackgroundColor)(T.getCode()))return!1;const M=this._getContrastCache(T);let E;if(R||L||(E=M.getColor(P.rgba,_.rgba)),E===void 0){const B=this._optionsService.rawOptions.minimumContrastRatio/(T.isDim()?2:1);E=b.color.ensureContrastRatio(R||P,L||_,B),M.setColor((R||P).rgba,(L||_).rgba,E??null)}return!!E&&(this._addStyle(C,`color:${E.css}`),!0)}_getContrastCache(C){return C.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(C,P){C.setAttribute("style",`${C.getAttribute("style")||""}${P};`)}_isCellInSelection(C,P){const _=this._selectionStart,T=this._selectionEnd;return!(!_||!T)&&(this._columnSelectMode?_[0]<=T[0]?C>=_[0]&&P>=_[1]&&C<T[0]&&P<=T[1]:C<_[0]&&P>=_[1]&&C>=T[0]&&P<=T[1]:P>_[1]&&P<T[1]||_[1]===T[1]&&P===_[1]&&C>=_[0]&&C<T[0]||_[1]<T[1]&&P===T[1]&&C<T[0]||_[1]<T[1]&&P===_[1]&&C>=_[0])}};function k(C,P,_){for(;C.length<_;)C=P+C;return C}o.DomRendererRowFactory=y=h([d(1,g.ICharacterJoinerService),d(2,v.IOptionsService),d(3,g.ICoreBrowserService),d(4,v.ICoreService),d(5,v.IDecorationService),d(6,g.IThemeService)],y)},2550:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WidthCache=void 0,o.WidthCache=class{constructor(l,h){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=l.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const d=l.createElement("span");d.classList.add("xterm-char-measure-element");const u=l.createElement("span");u.classList.add("xterm-char-measure-element"),u.style.fontWeight="bold";const f=l.createElement("span");f.classList.add("xterm-char-measure-element"),f.style.fontStyle="italic";const p=l.createElement("span");p.classList.add("xterm-char-measure-element"),p.style.fontWeight="bold",p.style.fontStyle="italic",this._measureElements=[d,u,f,p],this._container.appendChild(d),this._container.appendChild(u),this._container.appendChild(f),this._container.appendChild(p),h.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(l,h,d,u){l===this._font&&h===this._fontSize&&d===this._weight&&u===this._weightBold||(this._font=l,this._fontSize=h,this._weight=d,this._weightBold=u,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${d}`,this._measureElements[1].style.fontWeight=`${u}`,this._measureElements[2].style.fontWeight=`${d}`,this._measureElements[3].style.fontWeight=`${u}`,this.clear())}get(l,h,d){let u=0;if(!h&&!d&&l.length===1&&(u=l.charCodeAt(0))<256){if(this._flat[u]!==-9999)return this._flat[u];const v=this._measure(l,0);return v>0&&(this._flat[u]=v),v}let f=l;h&&(f+="B"),d&&(f+="I");let p=this._holey.get(f);if(p===void 0){let v=0;h&&(v|=1),d&&(v|=2),p=this._measure(l,v),p>0&&this._holey.set(f,p)}return p}_measure(l,h){const d=this._measureElements[h];return d.textContent=l.repeat(32),d.offsetWidth/32}}},2223:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.TEXT_BASELINE=o.DIM_OPACITY=o.INVERTED_DEFAULT_COLOR=void 0;const h=l(6114);o.INVERTED_DEFAULT_COLOR=257,o.DIM_OPACITY=.5,o.TEXT_BASELINE=h.isFirefox||h.isLegacyEdge?"bottom":"ideographic"},6171:(a,o)=>{function l(d){return 57508<=d&&d<=57558}function h(d){return d>=128512&&d<=128591||d>=127744&&d<=128511||d>=128640&&d<=128767||d>=9728&&d<=9983||d>=9984&&d<=10175||d>=65024&&d<=65039||d>=129280&&d<=129535||d>=127462&&d<=127487}Object.defineProperty(o,"__esModule",{value:!0}),o.computeNextVariantOffset=o.createRenderDimensions=o.treatGlyphAsBackgroundColor=o.allowRescaling=o.isEmoji=o.isRestrictedPowerlineGlyph=o.isPowerlineGlyph=o.throwIfFalsy=void 0,o.throwIfFalsy=function(d){if(!d)throw new Error("value must not be falsy");return d},o.isPowerlineGlyph=l,o.isRestrictedPowerlineGlyph=function(d){return 57520<=d&&d<=57527},o.isEmoji=h,o.allowRescaling=function(d,u,f,p){return u===1&&f>Math.ceil(1.5*p)&&d!==void 0&&d>255&&!h(d)&&!l(d)&&!(function(v){return 57344<=v&&v<=63743})(d)},o.treatGlyphAsBackgroundColor=function(d){return l(d)||(function(u){return 9472<=u&&u<=9631})(d)},o.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},o.computeNextVariantOffset=function(d,u,f=0){return(d-(2*Math.round(u)-f))%(2*Math.round(u))}},6052:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createSelectionRenderModel=void 0;class l{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(d,u,f,p=!1){if(this.selectionStart=u,this.selectionEnd=f,!u||!f||u[0]===f[0]&&u[1]===f[1])return void this.clear();const v=d.buffers.active.ydisp,b=u[1]-v,g=f[1]-v,O=Math.max(b,0),m=Math.min(g,d.rows-1);O>=d.rows||m<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=p,this.viewportStartRow=b,this.viewportEndRow=g,this.viewportCappedStartRow=O,this.viewportCappedEndRow=m,this.startCol=u[0],this.endCol=f[0])}isCellSelected(d,u,f){return!!this.hasSelection&&(f-=d.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?u>=this.startCol&&f>=this.viewportCappedStartRow&&u<this.endCol&&f<=this.viewportCappedEndRow:u<this.startCol&&f>=this.viewportCappedStartRow&&u>=this.endCol&&f<=this.viewportCappedEndRow:f>this.viewportStartRow&&f<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&f===this.viewportStartRow&&u>=this.startCol&&u<this.endCol||this.viewportStartRow<this.viewportEndRow&&f===this.viewportEndRow&&u<this.endCol||this.viewportStartRow<this.viewportEndRow&&f===this.viewportStartRow&&u>=this.startCol)}}o.createSelectionRenderModel=function(){return new l}},456:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionModel=void 0,o.SelectionModel=class{constructor(l){this._bufferService=l,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const l=this.selectionStart[0]+this.selectionStartLength;return l>this._bufferService.cols?l%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)-1]:[l%this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)]:[l,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const l=this.selectionStart[0]+this.selectionStartLength;return l>this._bufferService.cols?[l%this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)]:[Math.max(l,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const l=this.selectionStart,h=this.selectionEnd;return!(!l||!h)&&(l[1]>h[1]||l[1]===h[1]&&l[0]>h[0])}handleTrim(l){return this.selectionStart&&(this.selectionStart[1]-=l),this.selectionEnd&&(this.selectionEnd[1]-=l),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(a,o,l){var h=this&&this.__decorate||function(m,x,y,k){var C,P=arguments.length,_=P<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,y):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(m,x,y,k);else for(var T=m.length-1;T>=0;T--)(C=m[T])&&(_=(P<3?C(_):P>3?C(x,y,_):C(x,y))||_);return P>3&&_&&Object.defineProperty(x,y,_),_},d=this&&this.__param||function(m,x){return function(y,k){x(y,k,m)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharSizeService=void 0;const u=l(2585),f=l(8460),p=l(844);let v=o.CharSizeService=class extends p.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(m,x,y){super(),this._optionsService=y,this.width=0,this.height=0,this._onCharSizeChange=this.register(new f.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this.register(new O(this._optionsService))}catch{this._measureStrategy=this.register(new g(m,x,this._optionsService))}this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],(()=>this.measure())))}measure(){const m=this._measureStrategy.measure();m.width===this.width&&m.height===this.height||(this.width=m.width,this.height=m.height,this._onCharSizeChange.fire())}};o.CharSizeService=v=h([d(2,u.IOptionsService)],v);class b extends p.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(x,y){x!==void 0&&x>0&&y!==void 0&&y>0&&(this._result.width=x,this._result.height=y)}}class g extends b{constructor(x,y,k){super(),this._document=x,this._parentElement=y,this._optionsService=k,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}}class O extends b{constructor(x){super(),this._optionsService=x,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const y=this._ctx.measureText("W");if(!("width"in y&&"fontBoundingBoxAscent"in y&&"fontBoundingBoxDescent"in y))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const x=this._ctx.measureText("W");return this._validateAndSet(x.width,x.fontBoundingBoxAscent+x.fontBoundingBoxDescent),this._result}}},4269:function(a,o,l){var h=this&&this.__decorate||function(O,m,x,y){var k,C=arguments.length,P=C<3?m:y===null?y=Object.getOwnPropertyDescriptor(m,x):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(O,m,x,y);else for(var _=O.length-1;_>=0;_--)(k=O[_])&&(P=(C<3?k(P):C>3?k(m,x,P):k(m,x))||P);return C>3&&P&&Object.defineProperty(m,x,P),P},d=this&&this.__param||function(O,m){return function(x,y){m(x,y,O)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharacterJoinerService=o.JoinedCellData=void 0;const u=l(3734),f=l(643),p=l(511),v=l(2585);class b extends u.AttributeData{constructor(m,x,y){super(),this.content=0,this.combinedData="",this.fg=m.fg,this.bg=m.bg,this.combinedData=x,this._width=y}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(m){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.JoinedCellData=b;let g=o.CharacterJoinerService=class T_{constructor(m){this._bufferService=m,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new p.CellData}register(m){const x={id:this._nextCharacterJoinerId++,handler:m};return this._characterJoiners.push(x),x.id}deregister(m){for(let x=0;x<this._characterJoiners.length;x++)if(this._characterJoiners[x].id===m)return this._characterJoiners.splice(x,1),!0;return!1}getJoinedCharacters(m){if(this._characterJoiners.length===0)return[];const x=this._bufferService.buffer.lines.get(m);if(!x||x.length===0)return[];const y=[],k=x.translateToString(!0);let C=0,P=0,_=0,T=x.getFg(0),R=x.getBg(0);for(let L=0;L<x.getTrimmedLength();L++)if(x.loadCell(L,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==T||this._workCell.bg!==R){if(L-C>1){const M=this._getJoinedRanges(k,_,P,x,C);for(let E=0;E<M.length;E++)y.push(M[E])}C=L,_=P,T=this._workCell.fg,R=this._workCell.bg}P+=this._workCell.getChars().length||f.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-C>1){const L=this._getJoinedRanges(k,_,P,x,C);for(let M=0;M<L.length;M++)y.push(L[M])}return y}_getJoinedRanges(m,x,y,k,C){const P=m.substring(x,y);let _=[];try{_=this._characterJoiners[0].handler(P)}catch(T){console.error(T)}for(let T=1;T<this._characterJoiners.length;T++)try{const R=this._characterJoiners[T].handler(P);for(let L=0;L<R.length;L++)T_._mergeRanges(_,R[L])}catch(R){console.error(R)}return this._stringRangesToCellRanges(_,k,C),_}_stringRangesToCellRanges(m,x,y){let k=0,C=!1,P=0,_=m[k];if(_){for(let T=y;T<this._bufferService.cols;T++){const R=x.getWidth(T),L=x.getString(T).length||f.WHITESPACE_CELL_CHAR.length;if(R!==0){if(!C&&_[0]<=P&&(_[0]=T,C=!0),_[1]<=P){if(_[1]=T,_=m[++k],!_)break;_[0]<=P?(_[0]=T,C=!0):C=!1}P+=L}}_&&(_[1]=this._bufferService.cols)}}static _mergeRanges(m,x){let y=!1;for(let k=0;k<m.length;k++){const C=m[k];if(y){if(x[1]<=C[0])return m[k-1][1]=x[1],m;if(x[1]<=C[1])return m[k-1][1]=Math.max(x[1],C[1]),m.splice(k,1),m;m.splice(k,1),k--}else{if(x[1]<=C[0])return m.splice(k,0,x),m;if(x[1]<=C[1])return C[0]=Math.min(x[0],C[0]),m;x[0]<C[1]&&(C[0]=Math.min(x[0],C[0]),y=!0)}}return y?m[m.length-1][1]=x[1]:m.push(x),m}};o.CharacterJoinerService=g=h([d(0,v.IBufferService)],g)},5114:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreBrowserService=void 0;const h=l(844),d=l(8460),u=l(3656);class f extends h.Disposable{constructor(b,g,O){super(),this._textarea=b,this._window=g,this.mainDocument=O,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=new p(this._window),this._onDprChange=this.register(new d.EventEmitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this.register(new d.EventEmitter),this.onWindowChange=this._onWindowChange.event,this.register(this.onWindowChange((m=>this._screenDprMonitor.setWindow(m)))),this.register((0,d.forwardEvent)(this._screenDprMonitor.onDprChange,this._onDprChange)),this._textarea.addEventListener("focus",(()=>this._isFocused=!0)),this._textarea.addEventListener("blur",(()=>this._isFocused=!1))}get window(){return this._window}set window(b){this._window!==b&&(this._window=b,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask((()=>this._cachedIsFocused=void 0))),this._cachedIsFocused}}o.CoreBrowserService=f;class p extends h.Disposable{constructor(b){super(),this._parentWindow=b,this._windowResizeListener=this.register(new h.MutableDisposable),this._onDprChange=this.register(new d.EventEmitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this.register((0,h.toDisposable)((()=>this.clearListener())))}setWindow(b){this._parentWindow=b,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,u.addDisposableDomListener)(this._parentWindow,"resize",(()=>this._setDprAndFireIfDiffers()))}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}}},779:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.LinkProviderService=void 0;const h=l(844);class d extends h.Disposable{constructor(){super(),this.linkProviders=[],this.register((0,h.toDisposable)((()=>this.linkProviders.length=0)))}registerLinkProvider(f){return this.linkProviders.push(f),{dispose:()=>{const p=this.linkProviders.indexOf(f);p!==-1&&this.linkProviders.splice(p,1)}}}}o.LinkProviderService=d},8934:function(a,o,l){var h=this&&this.__decorate||function(v,b,g,O){var m,x=arguments.length,y=x<3?b:O===null?O=Object.getOwnPropertyDescriptor(b,g):O;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")y=Reflect.decorate(v,b,g,O);else for(var k=v.length-1;k>=0;k--)(m=v[k])&&(y=(x<3?m(y):x>3?m(b,g,y):m(b,g))||y);return x>3&&y&&Object.defineProperty(b,g,y),y},d=this&&this.__param||function(v,b){return function(g,O){b(g,O,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.MouseService=void 0;const u=l(4725),f=l(9806);let p=o.MouseService=class{constructor(v,b){this._renderService=v,this._charSizeService=b}getCoords(v,b,g,O,m){return(0,f.getCoords)(window,v,b,g,O,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,m)}getMouseReportCoords(v,b){const g=(0,f.getCoordsRelativeToElement)(window,v,b);if(this._charSizeService.hasValidSize)return g[0]=Math.min(Math.max(g[0],0),this._renderService.dimensions.css.canvas.width-1),g[1]=Math.min(Math.max(g[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(g[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(g[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(g[0]),y:Math.floor(g[1])}}};o.MouseService=p=h([d(0,u.IRenderService),d(1,u.ICharSizeService)],p)},3230:function(a,o,l){var h=this&&this.__decorate||function(m,x,y,k){var C,P=arguments.length,_=P<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,y):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(m,x,y,k);else for(var T=m.length-1;T>=0;T--)(C=m[T])&&(_=(P<3?C(_):P>3?C(x,y,_):C(x,y))||_);return P>3&&_&&Object.defineProperty(x,y,_),_},d=this&&this.__param||function(m,x){return function(y,k){x(y,k,m)}};Object.defineProperty(o,"__esModule",{value:!0}),o.RenderService=void 0;const u=l(6193),f=l(4725),p=l(8460),v=l(844),b=l(7226),g=l(2585);let O=o.RenderService=class extends v.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(m,x,y,k,C,P,_,T){super(),this._rowCount=m,this._charSizeService=k,this._renderer=this.register(new v.MutableDisposable),this._pausedResizeTask=new b.DebouncedIdleTask,this._observerDisposable=this.register(new v.MutableDisposable),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new p.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new p.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new p.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new p.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new u.RenderDebouncer(((R,L)=>this._renderRows(R,L)),_),this.register(this._renderDebouncer),this.register(_.onDprChange((()=>this.handleDevicePixelRatioChange()))),this.register(P.onResize((()=>this._fullRefresh()))),this.register(P.buffers.onBufferActivate((()=>this._renderer.value?.clear()))),this.register(y.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this.register(C.onDecorationRegistered((()=>this._fullRefresh()))),this.register(C.onDecorationRemoved((()=>this._fullRefresh()))),this.register(y.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],(()=>{this.clear(),this.handleResize(P.cols,P.rows),this._fullRefresh()}))),this.register(y.onMultipleOptionChange(["cursorBlink","cursorStyle"],(()=>this.refreshRows(P.buffer.y,P.buffer.y,!0)))),this.register(T.onChangeColors((()=>this._fullRefresh()))),this._registerIntersectionObserver(_.window,x),this.register(_.onWindowChange((R=>this._registerIntersectionObserver(R,x))))}_registerIntersectionObserver(m,x){if("IntersectionObserver"in m){const y=new m.IntersectionObserver((k=>this._handleIntersectionChange(k[k.length-1])),{threshold:0});y.observe(x),this._observerDisposable.value=(0,v.toDisposable)((()=>y.disconnect()))}}_handleIntersectionChange(m){this._isPaused=m.isIntersecting===void 0?m.intersectionRatio===0:!m.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(m,x,y=!1){this._isPaused?this._needsFullRefresh=!0:(y||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(m,x,this._rowCount))}_renderRows(m,x){this._renderer.value&&(m=Math.min(m,this._rowCount-1),x=Math.min(x,this._rowCount-1),this._renderer.value.renderRows(m,x),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:m,end:x}),this._onRender.fire({start:m,end:x}),this._isNextRenderRedrawOnly=!0)}resize(m,x){this._rowCount=x,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(m){this._renderer.value=m,this._renderer.value&&(this._renderer.value.onRequestRedraw((x=>this.refreshRows(x.start,x.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(m){return this._renderDebouncer.addRefreshCallback(m)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(m,x){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>this._renderer.value?.handleResize(m,x))):this._renderer.value.handleResize(m,x),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(m,x,y){this._selectionState.start=m,this._selectionState.end=x,this._selectionState.columnSelectMode=y,this._renderer.value?.handleSelectionChanged(m,x,y)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};o.RenderService=O=h([d(2,g.IOptionsService),d(3,f.ICharSizeService),d(4,g.IDecorationService),d(5,g.IBufferService),d(6,f.ICoreBrowserService),d(7,f.IThemeService)],O)},9312:function(a,o,l){var h=this&&this.__decorate||function(_,T,R,L){var M,E=arguments.length,B=E<3?T:L===null?L=Object.getOwnPropertyDescriptor(T,R):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")B=Reflect.decorate(_,T,R,L);else for(var U=_.length-1;U>=0;U--)(M=_[U])&&(B=(E<3?M(B):E>3?M(T,R,B):M(T,R))||B);return E>3&&B&&Object.defineProperty(T,R,B),B},d=this&&this.__param||function(_,T){return function(R,L){T(R,L,_)}};Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionService=void 0;const u=l(9806),f=l(9504),p=l(456),v=l(4725),b=l(8460),g=l(844),O=l(6114),m=l(4841),x=l(511),y=l(2585),k=" ",C=new RegExp(k,"g");let P=o.SelectionService=class extends g.Disposable{constructor(_,T,R,L,M,E,B,U,F){super(),this._element=_,this._screenElement=T,this._linkifier=R,this._bufferService=L,this._coreService=M,this._mouseService=E,this._optionsService=B,this._renderService=U,this._coreBrowserService=F,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new x.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new b.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new b.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new b.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new b.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=X=>this._handleMouseMove(X),this._mouseUpListener=X=>this._handleMouseUp(X),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((X=>this._handleTrim(X))),this.register(this._bufferService.buffers.onBufferActivate((X=>this._handleBufferActivate(X)))),this.enable(),this._model=new p.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,g.toDisposable)((()=>{this._removeMouseDownListeners()})))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const _=this._model.finalSelectionStart,T=this._model.finalSelectionEnd;return!(!_||!T||_[0]===T[0]&&_[1]===T[1])}get selectionText(){const _=this._model.finalSelectionStart,T=this._model.finalSelectionEnd;if(!_||!T)return"";const R=this._bufferService.buffer,L=[];if(this._activeSelectionMode===3){if(_[0]===T[0])return"";const M=_[0]<T[0]?_[0]:T[0],E=_[0]<T[0]?T[0]:_[0];for(let B=_[1];B<=T[1];B++){const U=R.translateBufferLineToString(B,!0,M,E);L.push(U)}}else{const M=_[1]===T[1]?T[0]:void 0;L.push(R.translateBufferLineToString(_[1],!0,_[0],M));for(let E=_[1]+1;E<=T[1]-1;E++){const B=R.lines.get(E),U=R.translateBufferLineToString(E,!0);B?.isWrapped?L[L.length-1]+=U:L.push(U)}if(_[1]!==T[1]){const E=R.lines.get(T[1]),B=R.translateBufferLineToString(T[1],!0,0,T[0]);E&&E.isWrapped?L[L.length-1]+=B:L.push(B)}}return L.map((M=>M.replace(C," "))).join(O.isWindows?`\r
|
|
44
|
+
WARNING: This link could potentially be dangerous`)){const O=window.open();if(O){try{O.opener=null}catch{}O.location.href=g}else console.warn("Opening link blocked as opener could not be cleared")}}o.OscLinkProvider=p=h([d(0,f.IBufferService),d(1,f.IOptionsService),d(2,f.IOscLinkService)],p)},6193:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.RenderDebouncer=void 0,o.RenderDebouncer=class{constructor(l,h){this._renderCallback=l,this._coreBrowserService=h,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(l){return this._refreshCallbacks.push(l),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(l,h,d){this._rowCount=d,l=l!==void 0?l:0,h=h!==void 0?h:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,l):l,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,h):h,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const l=Math.max(this._rowStart,0),h=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(l,h),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const l of this._refreshCallbacks)l(0);this._refreshCallbacks=[]}}},3236:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Terminal=void 0;const h=l(3614),d=l(3656),u=l(3551),f=l(9042),p=l(3730),v=l(1680),b=l(3107),g=l(5744),O=l(2950),m=l(1296),x=l(428),y=l(4269),k=l(5114),C=l(8934),P=l(3230),_=l(9312),T=l(4725),R=l(6731),L=l(8055),M=l(8969),E=l(8460),B=l(844),U=l(6114),F=l(8437),X=l(2584),ae=l(7399),j=l(5941),W=l(9074),D=l(2585),V=l(5435),se=l(4567),fe=l(779);class z extends M.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(Z={}){super(Z),this.browser=U,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new B.MutableDisposable),this._onCursorMove=this.register(new E.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new E.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new E.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new E.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new E.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new E.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new E.EventEmitter),this._onBlur=this.register(new E.EventEmitter),this._onA11yCharEmitter=this.register(new E.EventEmitter),this._onA11yTabEmitter=this.register(new E.EventEmitter),this._onWillOpen=this.register(new E.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(W.DecorationService),this._instantiationService.setService(D.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(fe.LinkProviderService),this._instantiationService.setService(T.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(p.OscLinkProvider)),this.register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this.register(this._inputHandler.onRequestRefreshRows(((A,J)=>this.refresh(A,J)))),this.register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register(this._inputHandler.onRequestWindowsOptionsReport((A=>this._reportWindowsOptions(A)))),this.register(this._inputHandler.onColor((A=>this._handleColorEvent(A)))),this.register((0,E.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,E.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,E.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,E.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize((A=>this._afterResize(A.cols,A.rows)))),this.register((0,B.toDisposable)((()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)})))}_handleColorEvent(Z){if(this._themeService)for(const A of Z){let J,Y="";switch(A.index){case 256:J="foreground",Y="10";break;case 257:J="background",Y="11";break;case 258:J="cursor",Y="12";break;default:J="ansi",Y="4;"+A.index}switch(A.type){case 0:const oe=L.color.toColorRGB(J==="ansi"?this._themeService.colors.ansi[A.index]:this._themeService.colors[J]);this.coreService.triggerDataEvent(`${X.C0.ESC}]${Y};${(0,j.toRgbString)(oe)}${X.C1_ESCAPED.ST}`);break;case 1:if(J==="ansi")this._themeService.modifyColors((K=>K.ansi[A.index]=L.channels.toColor(...A.color)));else{const K=J;this._themeService.modifyColors((pe=>pe[K]=L.channels.toColor(...A.color)))}break;case 2:this._themeService.restoreColor(A.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(Z){Z?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(se.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(Z){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(X.C0.ESC+"[I"),this.element.classList.add("focus"),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value="",this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(X.C0.ESC+"[O"),this.element.classList.remove("focus"),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;const Z=this.buffer.ybase+this.buffer.y,A=this.buffer.lines.get(Z);if(!A)return;const J=Math.min(this.buffer.x,this.cols-1),Y=this._renderService.dimensions.css.cell.height,oe=A.getWidth(J),K=this._renderService.dimensions.css.cell.width*oe,pe=this.buffer.y*this._renderService.dimensions.css.cell.height,je=J*this._renderService.dimensions.css.cell.width;this.textarea.style.left=je+"px",this.textarea.style.top=pe+"px",this.textarea.style.width=K+"px",this.textarea.style.height=Y+"px",this.textarea.style.lineHeight=Y+"px",this.textarea.style.zIndex="-5"}_initGlobal(){this._bindKeys(),this.register((0,d.addDisposableDomListener)(this.element,"copy",(A=>{this.hasSelection()&&(0,h.copyHandler)(A,this._selectionService)})));const Z=A=>(0,h.handlePasteEvent)(A,this.textarea,this.coreService,this.optionsService);this.register((0,d.addDisposableDomListener)(this.textarea,"paste",Z)),this.register((0,d.addDisposableDomListener)(this.element,"paste",Z)),U.isFirefox?this.register((0,d.addDisposableDomListener)(this.element,"mousedown",(A=>{A.button===2&&(0,h.rightClickHandler)(A,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this.register((0,d.addDisposableDomListener)(this.element,"contextmenu",(A=>{(0,h.rightClickHandler)(A,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),U.isLinux&&this.register((0,d.addDisposableDomListener)(this.element,"auxclick",(A=>{A.button===1&&(0,h.moveTextAreaUnderMouseCursor)(A,this.textarea,this.screenElement)})))}_bindKeys(){this.register((0,d.addDisposableDomListener)(this.textarea,"keyup",(Z=>this._keyUp(Z)),!0)),this.register((0,d.addDisposableDomListener)(this.textarea,"keydown",(Z=>this._keyDown(Z)),!0)),this.register((0,d.addDisposableDomListener)(this.textarea,"keypress",(Z=>this._keyPress(Z)),!0)),this.register((0,d.addDisposableDomListener)(this.textarea,"compositionstart",(()=>this._compositionHelper.compositionstart()))),this.register((0,d.addDisposableDomListener)(this.textarea,"compositionupdate",(Z=>this._compositionHelper.compositionupdate(Z)))),this.register((0,d.addDisposableDomListener)(this.textarea,"compositionend",(()=>this._compositionHelper.compositionend()))),this.register((0,d.addDisposableDomListener)(this.textarea,"input",(Z=>this._inputEvent(Z)),!0)),this.register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(Z){if(!Z)throw new Error("Terminal requires a parent element.");if(Z.isConnected||this._logService.debug("Terminal.open was called on an element that was not attached to the DOM"),this.element?.ownerDocument.defaultView&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=Z.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement("div"),this.element.dir="ltr",this.element.classList.add("terminal"),this.element.classList.add("xterm"),Z.appendChild(this.element);const A=this._document.createDocumentFragment();this._viewportElement=this._document.createElement("div"),this._viewportElement.classList.add("xterm-viewport"),A.appendChild(this._viewportElement),this._viewportScrollArea=this._document.createElement("div"),this._viewportScrollArea.classList.add("xterm-scroll-area"),this._viewportElement.appendChild(this._viewportScrollArea),this.screenElement=this._document.createElement("div"),this.screenElement.classList.add("xterm-screen"),this.register((0,d.addDisposableDomListener)(this.screenElement,"mousemove",(J=>this.updateCursorStyle(J)))),this._helperContainer=this._document.createElement("div"),this._helperContainer.classList.add("xterm-helpers"),this.screenElement.appendChild(this._helperContainer),A.appendChild(this.screenElement),this.textarea=this._document.createElement("textarea"),this.textarea.classList.add("xterm-helper-textarea"),this.textarea.setAttribute("aria-label",f.promptLabel),U.isChromeOS||this.textarea.setAttribute("aria-multiline","false"),this.textarea.setAttribute("autocorrect","off"),this.textarea.setAttribute("autocapitalize","off"),this.textarea.setAttribute("spellcheck","false"),this.textarea.tabIndex=0,this._coreBrowserService=this.register(this._instantiationService.createInstance(k.CoreBrowserService,this.textarea,Z.ownerDocument.defaultView??window,this._document??typeof window<"u"?window.document:null)),this._instantiationService.setService(T.ICoreBrowserService,this._coreBrowserService),this.register((0,d.addDisposableDomListener)(this.textarea,"focus",(J=>this._handleTextAreaFocus(J)))),this.register((0,d.addDisposableDomListener)(this.textarea,"blur",(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(x.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(T.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(R.ThemeService),this._instantiationService.setService(T.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(y.CharacterJoinerService),this._instantiationService.setService(T.ICharacterJoinerService,this._characterJoinerService),this._renderService=this.register(this._instantiationService.createInstance(P.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(T.IRenderService,this._renderService),this.register(this._renderService.onRenderedViewportChange((J=>this._onRender.fire(J)))),this.onResize((J=>this._renderService.resize(J.cols,J.rows))),this._compositionView=this._document.createElement("div"),this._compositionView.classList.add("composition-view"),this._compositionHelper=this._instantiationService.createInstance(O.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(C.MouseService),this._instantiationService.setService(T.IMouseService,this._mouseService),this.linkifier=this.register(this._instantiationService.createInstance(u.Linkifier,this.screenElement)),this.element.appendChild(A);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this.viewport=this._instantiationService.createInstance(v.Viewport,this._viewportElement,this._viewportScrollArea),this.viewport.onRequestScrollLines((J=>this.scrollLines(J.amount,J.suppressScrollEvent,1))),this.register(this._inputHandler.onRequestSyncScrollBar((()=>this.viewport.syncScrollArea()))),this.register(this.viewport),this.register(this.onCursorMove((()=>{this._renderService.handleCursorMove(),this._syncTextArea()}))),this.register(this.onResize((()=>this._renderService.handleResize(this.cols,this.rows)))),this.register(this.onBlur((()=>this._renderService.handleBlur()))),this.register(this.onFocus((()=>this._renderService.handleFocus()))),this.register(this._renderService.onDimensionsChange((()=>this.viewport.syncScrollArea()))),this._selectionService=this.register(this._instantiationService.createInstance(_.SelectionService,this.element,this.screenElement,this.linkifier)),this._instantiationService.setService(T.ISelectionService,this._selectionService),this.register(this._selectionService.onRequestScrollLines((J=>this.scrollLines(J.amount,J.suppressScrollEvent)))),this.register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this.register(this._selectionService.onRequestRedraw((J=>this._renderService.handleSelectionChanged(J.start,J.end,J.columnSelectMode)))),this.register(this._selectionService.onLinuxMouseSelection((J=>{this.textarea.value=J,this.textarea.focus(),this.textarea.select()}))),this.register(this._onScroll.event((J=>{this.viewport.syncScrollArea(),this._selectionService.refresh()}))),this.register((0,d.addDisposableDomListener)(this._viewportElement,"scroll",(()=>this._selectionService.refresh()))),this.register(this._instantiationService.createInstance(b.BufferDecorationRenderer,this.screenElement)),this.register((0,d.addDisposableDomListener)(this.element,"mousedown",(J=>this._selectionService.handleMouseDown(J)))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add("enable-mouse-events")):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(se.AccessibilityManager,this)),this.register(this.optionsService.onSpecificOptionChange("screenReaderMode",(J=>this._handleScreenReaderModeOptionChange(J)))),this.options.overviewRulerWidth&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(g.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange("overviewRulerWidth",(J=>{!this._overviewRulerRenderer&&J&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this.register(this._instantiationService.createInstance(g.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(m.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){const Z=this,A=this.element;function J(K){const pe=Z._mouseService.getMouseReportCoords(K,Z.screenElement);if(!pe)return!1;let je,we;switch(K.overrideType||K.type){case"mousemove":we=32,K.buttons===void 0?(je=3,K.button!==void 0&&(je=K.button<3?K.button:3)):je=1&K.buttons?0:4&K.buttons?1:2&K.buttons?2:3;break;case"mouseup":we=0,je=K.button<3?K.button:3;break;case"mousedown":we=1,je=K.button<3?K.button:3;break;case"wheel":if(Z._customWheelEventHandler&&Z._customWheelEventHandler(K)===!1||Z.viewport.getLinesScrolled(K)===0)return!1;we=K.deltaY<0?0:1,je=4;break;default:return!1}return!(we===void 0||je===void 0||je>4)&&Z.coreMouseService.triggerMouseEvent({col:pe.col,row:pe.row,x:pe.x,y:pe.y,button:je,action:we,ctrl:K.ctrlKey,alt:K.altKey,shift:K.shiftKey})}const Y={mouseup:null,wheel:null,mousedrag:null,mousemove:null},oe={mouseup:K=>(J(K),K.buttons||(this._document.removeEventListener("mouseup",Y.mouseup),Y.mousedrag&&this._document.removeEventListener("mousemove",Y.mousedrag)),this.cancel(K)),wheel:K=>(J(K),this.cancel(K,!0)),mousedrag:K=>{K.buttons&&J(K)},mousemove:K=>{K.buttons||J(K)}};this.register(this.coreMouseService.onProtocolChange((K=>{K?(this.optionsService.rawOptions.logLevel==="debug"&&this._logService.debug("Binding to mouse events:",this.coreMouseService.explainEvents(K)),this.element.classList.add("enable-mouse-events"),this._selectionService.disable()):(this._logService.debug("Unbinding from mouse events."),this.element.classList.remove("enable-mouse-events"),this._selectionService.enable()),8&K?Y.mousemove||(A.addEventListener("mousemove",oe.mousemove),Y.mousemove=oe.mousemove):(A.removeEventListener("mousemove",Y.mousemove),Y.mousemove=null),16&K?Y.wheel||(A.addEventListener("wheel",oe.wheel,{passive:!1}),Y.wheel=oe.wheel):(A.removeEventListener("wheel",Y.wheel),Y.wheel=null),2&K?Y.mouseup||(Y.mouseup=oe.mouseup):(this._document.removeEventListener("mouseup",Y.mouseup),Y.mouseup=null),4&K?Y.mousedrag||(Y.mousedrag=oe.mousedrag):(this._document.removeEventListener("mousemove",Y.mousedrag),Y.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this.register((0,d.addDisposableDomListener)(A,"mousedown",(K=>{if(K.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(K))return J(K),Y.mouseup&&this._document.addEventListener("mouseup",Y.mouseup),Y.mousedrag&&this._document.addEventListener("mousemove",Y.mousedrag),this.cancel(K)}))),this.register((0,d.addDisposableDomListener)(A,"wheel",(K=>{if(!Y.wheel){if(this._customWheelEventHandler&&this._customWheelEventHandler(K)===!1)return!1;if(!this.buffer.hasScrollback){const pe=this.viewport.getLinesScrolled(K);if(pe===0)return;const je=X.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?"O":"[")+(K.deltaY<0?"A":"B");let we="";for(let Ge=0;Ge<Math.abs(pe);Ge++)we+=je;return this.coreService.triggerDataEvent(we,!0),this.cancel(K,!0)}return this.viewport.handleWheel(K)?this.cancel(K):void 0}}),{passive:!1})),this.register((0,d.addDisposableDomListener)(A,"touchstart",(K=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchStart(K),this.cancel(K)}),{passive:!0})),this.register((0,d.addDisposableDomListener)(A,"touchmove",(K=>{if(!this.coreMouseService.areMouseEventsActive)return this.viewport.handleTouchMove(K)?void 0:this.cancel(K)}),{passive:!1}))}refresh(Z,A){this._renderService?.refreshRows(Z,A)}updateCursorStyle(Z){this._selectionService?.shouldColumnSelect(Z)?this.element.classList.add("column-select"):this.element.classList.remove("column-select")}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(Z,A,J=0){J===1?(super.scrollLines(Z,A,J),this.refresh(0,this.rows-1)):this.viewport?.scrollLines(Z)}paste(Z){(0,h.paste)(Z,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(Z){this._customKeyEventHandler=Z}attachCustomWheelEventHandler(Z){this._customWheelEventHandler=Z}registerLinkProvider(Z){return this._linkProviderService.registerLinkProvider(Z)}registerCharacterJoiner(Z){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");const A=this._characterJoinerService.register(Z);return this.refresh(0,this.rows-1),A}deregisterCharacterJoiner(Z){if(!this._characterJoinerService)throw new Error("Terminal must be opened first");this._characterJoinerService.deregister(Z)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(Z){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+Z)}registerDecoration(Z){return this._decorationService.registerDecoration(Z)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(Z,A,J){this._selectionService.setSelection(Z,A,J)}getSelection(){return this._selectionService?this._selectionService.selectionText:""}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(Z,A){this._selectionService?.selectLines(Z,A)}_keyDown(Z){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&this._customKeyEventHandler(Z)===!1)return!1;const A=this.browser.isMac&&this.options.macOptionIsMeta&&Z.altKey;if(!A&&!this._compositionHelper.keydown(Z))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(),!1;A||Z.key!=="Dead"&&Z.key!=="AltGraph"||(this._unprocessedDeadKey=!0);const J=(0,ae.evaluateKeyboardEvent)(Z,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(Z),J.type===3||J.type===2){const Y=this.rows-1;return this.scrollLines(J.type===2?-Y:Y),this.cancel(Z,!0)}return J.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,Z)||(J.cancel&&this.cancel(Z,!0),!J.key||!!(Z.key&&!Z.ctrlKey&&!Z.altKey&&!Z.metaKey&&Z.key.length===1&&Z.key.charCodeAt(0)>=65&&Z.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(J.key!==X.C0.ETX&&J.key!==X.C0.CR||(this.textarea.value=""),this._onKey.fire({key:J.key,domEvent:Z}),this._showCursor(),this.coreService.triggerDataEvent(J.key,!0),!this.optionsService.rawOptions.screenReaderMode||Z.altKey||Z.ctrlKey?this.cancel(Z,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(Z,A){const J=Z.isMac&&!this.options.macOptionIsMeta&&A.altKey&&!A.ctrlKey&&!A.metaKey||Z.isWindows&&A.altKey&&A.ctrlKey&&!A.metaKey||Z.isWindows&&A.getModifierState("AltGraph");return A.type==="keypress"?J:J&&(!A.keyCode||A.keyCode>47)}_keyUp(Z){this._keyDownSeen=!1,this._customKeyEventHandler&&this._customKeyEventHandler(Z)===!1||((function(A){return A.keyCode===16||A.keyCode===17||A.keyCode===18})(Z)||this.focus(),this.updateCursorStyle(Z),this._keyPressHandled=!1)}_keyPress(Z){let A;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&this._customKeyEventHandler(Z)===!1)return!1;if(this.cancel(Z),Z.charCode)A=Z.charCode;else if(Z.which===null||Z.which===void 0)A=Z.keyCode;else{if(Z.which===0||Z.charCode===0)return!1;A=Z.which}return!(!A||(Z.altKey||Z.ctrlKey||Z.metaKey)&&!this._isThirdLevelShift(this.browser,Z)||(A=String.fromCharCode(A),this._onKey.fire({key:A,domEvent:Z}),this._showCursor(),this.coreService.triggerDataEvent(A,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(Z){if(Z.data&&Z.inputType==="insertText"&&(!Z.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;const A=Z.data;return this.coreService.triggerDataEvent(A,!0),this.cancel(Z),!0}return!1}resize(Z,A){Z!==this.cols||A!==this.rows?super.resize(Z,A):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(Z,A){this._charSizeService?.measure(),this.viewport?.syncScrollArea(!0)}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let Z=1;Z<this.rows;Z++)this.buffer.lines.push(this.buffer.getBlankLine(F.DEFAULT_ATTR_DATA));this._onScroll.fire({position:this.buffer.ydisp,source:0}),this.viewport?.reset(),this.refresh(0,this.rows-1)}}reset(){this.options.rows=this.rows,this.options.cols=this.cols;const Z=this._customKeyEventHandler;this._setup(),super.reset(),this._selectionService?.reset(),this._decorationService.reset(),this.viewport?.reset(),this._customKeyEventHandler=Z,this.refresh(0,this.rows-1)}clearTextureAtlas(){this._renderService?.clearTextureAtlas()}_reportFocus(){this.element?.classList.contains("focus")?this.coreService.triggerDataEvent(X.C0.ESC+"[I"):this.coreService.triggerDataEvent(X.C0.ESC+"[O")}_reportWindowsOptions(Z){if(this._renderService)switch(Z){case V.WindowsOptionsReportType.GET_WIN_SIZE_PIXELS:const A=this._renderService.dimensions.css.canvas.width.toFixed(0),J=this._renderService.dimensions.css.canvas.height.toFixed(0);this.coreService.triggerDataEvent(`${X.C0.ESC}[4;${J};${A}t`);break;case V.WindowsOptionsReportType.GET_CELL_SIZE_PIXELS:const Y=this._renderService.dimensions.css.cell.width.toFixed(0),oe=this._renderService.dimensions.css.cell.height.toFixed(0);this.coreService.triggerDataEvent(`${X.C0.ESC}[6;${oe};${Y}t`)}}cancel(Z,A){if(this.options.cancelEvents||A)return Z.preventDefault(),Z.stopPropagation(),!1}}o.Terminal=z},9924:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.TimeBasedDebouncer=void 0,o.TimeBasedDebouncer=class{constructor(l,h=1e3){this._renderCallback=l,this._debounceThresholdMS=h,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(l,h,d){this._rowCount=d,l=l!==void 0?l:0,h=h!==void 0?h:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,l):l,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,h):h;const u=Date.now();if(u-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=u,this._innerRefresh();else if(!this._additionalRefreshRequested){const f=u-this._lastRefreshMs,p=this._debounceThresholdMS-f;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=Date.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),p)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;const l=Math.max(this._rowStart,0),h=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(l,h)}}},1680:function(a,o,l){var h=this&&this.__decorate||function(O,m,x,y){var k,C=arguments.length,P=C<3?m:y===null?y=Object.getOwnPropertyDescriptor(m,x):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(O,m,x,y);else for(var _=O.length-1;_>=0;_--)(k=O[_])&&(P=(C<3?k(P):C>3?k(m,x,P):k(m,x))||P);return C>3&&P&&Object.defineProperty(m,x,P),P},d=this&&this.__param||function(O,m){return function(x,y){m(x,y,O)}};Object.defineProperty(o,"__esModule",{value:!0}),o.Viewport=void 0;const u=l(3656),f=l(4725),p=l(8460),v=l(844),b=l(2585);let g=o.Viewport=class extends v.Disposable{constructor(O,m,x,y,k,C,P,_){super(),this._viewportElement=O,this._scrollArea=m,this._bufferService=x,this._optionsService=y,this._charSizeService=k,this._renderService=C,this._coreBrowserService=P,this.scrollBarWidth=0,this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._wheelPartialScroll=0,this._refreshAnimationFrame=null,this._ignoreNextScrollEvent=!1,this._smoothScrollState={startTime:0,origin:-1,target:-1},this._onRequestScrollLines=this.register(new p.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this.scrollBarWidth=this._viewportElement.offsetWidth-this._scrollArea.offsetWidth||15,this.register((0,u.addDisposableDomListener)(this._viewportElement,"scroll",this._handleScroll.bind(this))),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((T=>this._activeBuffer=T.activeBuffer))),this._renderDimensions=this._renderService.dimensions,this.register(this._renderService.onDimensionsChange((T=>this._renderDimensions=T))),this._handleThemeChange(_.colors),this.register(_.onChangeColors((T=>this._handleThemeChange(T)))),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.syncScrollArea()))),setTimeout((()=>this.syncScrollArea()))}_handleThemeChange(O){this._viewportElement.style.backgroundColor=O.background.css}reset(){this._currentRowHeight=0,this._currentDeviceCellHeight=0,this._lastRecordedBufferLength=0,this._lastRecordedViewportHeight=0,this._lastRecordedBufferHeight=0,this._lastTouchY=0,this._lastScrollTop=0,this._coreBrowserService.window.requestAnimationFrame((()=>this.syncScrollArea()))}_refresh(O){if(O)return this._innerRefresh(),void(this._refreshAnimationFrame!==null&&this._coreBrowserService.window.cancelAnimationFrame(this._refreshAnimationFrame));this._refreshAnimationFrame===null&&(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._charSizeService.height>0){this._currentRowHeight=this._renderDimensions.device.cell.height/this._coreBrowserService.dpr,this._currentDeviceCellHeight=this._renderDimensions.device.cell.height,this._lastRecordedViewportHeight=this._viewportElement.offsetHeight;const m=Math.round(this._currentRowHeight*this._lastRecordedBufferLength)+(this._lastRecordedViewportHeight-this._renderDimensions.css.canvas.height);this._lastRecordedBufferHeight!==m&&(this._lastRecordedBufferHeight=m,this._scrollArea.style.height=this._lastRecordedBufferHeight+"px")}const O=this._bufferService.buffer.ydisp*this._currentRowHeight;this._viewportElement.scrollTop!==O&&(this._ignoreNextScrollEvent=!0,this._viewportElement.scrollTop=O),this._refreshAnimationFrame=null}syncScrollArea(O=!1){if(this._lastRecordedBufferLength!==this._bufferService.buffer.lines.length)return this._lastRecordedBufferLength=this._bufferService.buffer.lines.length,void this._refresh(O);this._lastRecordedViewportHeight===this._renderService.dimensions.css.canvas.height&&this._lastScrollTop===this._activeBuffer.ydisp*this._currentRowHeight&&this._renderDimensions.device.cell.height===this._currentDeviceCellHeight||this._refresh(O)}_handleScroll(O){if(this._lastScrollTop=this._viewportElement.scrollTop,!this._viewportElement.offsetParent)return;if(this._ignoreNextScrollEvent)return this._ignoreNextScrollEvent=!1,void this._onRequestScrollLines.fire({amount:0,suppressScrollEvent:!0});const m=Math.round(this._lastScrollTop/this._currentRowHeight)-this._bufferService.buffer.ydisp;this._onRequestScrollLines.fire({amount:m,suppressScrollEvent:!0})}_smoothScroll(){if(this._isDisposed||this._smoothScrollState.origin===-1||this._smoothScrollState.target===-1)return;const O=this._smoothScrollPercent();this._viewportElement.scrollTop=this._smoothScrollState.origin+Math.round(O*(this._smoothScrollState.target-this._smoothScrollState.origin)),O<1?this._coreBrowserService.window.requestAnimationFrame((()=>this._smoothScroll())):this._clearSmoothScrollState()}_smoothScrollPercent(){return this._optionsService.rawOptions.smoothScrollDuration&&this._smoothScrollState.startTime?Math.max(Math.min((Date.now()-this._smoothScrollState.startTime)/this._optionsService.rawOptions.smoothScrollDuration,1),0):1}_clearSmoothScrollState(){this._smoothScrollState.startTime=0,this._smoothScrollState.origin=-1,this._smoothScrollState.target=-1}_bubbleScroll(O,m){const x=this._viewportElement.scrollTop+this._lastRecordedViewportHeight;return!(m<0&&this._viewportElement.scrollTop!==0||m>0&&x<this._lastRecordedBufferHeight)||(O.cancelable&&O.preventDefault(),!1)}handleWheel(O){const m=this._getPixelsScrolled(O);return m!==0&&(this._optionsService.rawOptions.smoothScrollDuration?(this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target===-1?this._smoothScrollState.target=this._viewportElement.scrollTop+m:this._smoothScrollState.target+=m,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()):this._viewportElement.scrollTop+=m,this._bubbleScroll(O,m))}scrollLines(O){if(O!==0)if(this._optionsService.rawOptions.smoothScrollDuration){const m=O*this._currentRowHeight;this._smoothScrollState.startTime=Date.now(),this._smoothScrollPercent()<1?(this._smoothScrollState.origin=this._viewportElement.scrollTop,this._smoothScrollState.target=this._smoothScrollState.origin+m,this._smoothScrollState.target=Math.max(Math.min(this._smoothScrollState.target,this._viewportElement.scrollHeight),0),this._smoothScroll()):this._clearSmoothScrollState()}else this._onRequestScrollLines.fire({amount:O,suppressScrollEvent:!1})}_getPixelsScrolled(O){if(O.deltaY===0||O.shiftKey)return 0;let m=this._applyScrollModifier(O.deltaY,O);return O.deltaMode===WheelEvent.DOM_DELTA_LINE?m*=this._currentRowHeight:O.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(m*=this._currentRowHeight*this._bufferService.rows),m}getBufferElements(O,m){let x,y="";const k=[],C=m??this._bufferService.buffer.lines.length,P=this._bufferService.buffer.lines;for(let _=O;_<C;_++){const T=P.get(_);if(!T)continue;const R=P.get(_+1)?.isWrapped;if(y+=T.translateToString(!R),!R||_===P.length-1){const L=document.createElement("div");L.textContent=y,k.push(L),y.length>0&&(x=L),y=""}}return{bufferElements:k,cursorElement:x}}getLinesScrolled(O){if(O.deltaY===0||O.shiftKey)return 0;let m=this._applyScrollModifier(O.deltaY,O);return O.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(m/=this._currentRowHeight+0,this._wheelPartialScroll+=m,m=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):O.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(m*=this._bufferService.rows),m}_applyScrollModifier(O,m){const x=this._optionsService.rawOptions.fastScrollModifier;return x==="alt"&&m.altKey||x==="ctrl"&&m.ctrlKey||x==="shift"&&m.shiftKey?O*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:O*this._optionsService.rawOptions.scrollSensitivity}handleTouchStart(O){this._lastTouchY=O.touches[0].pageY}handleTouchMove(O){const m=this._lastTouchY-O.touches[0].pageY;return this._lastTouchY=O.touches[0].pageY,m!==0&&(this._viewportElement.scrollTop+=m,this._bubbleScroll(O,m))}};o.Viewport=g=h([d(2,b.IBufferService),d(3,b.IOptionsService),d(4,f.ICharSizeService),d(5,f.IRenderService),d(6,f.ICoreBrowserService),d(7,f.IThemeService)],g)},3107:function(a,o,l){var h=this&&this.__decorate||function(b,g,O,m){var x,y=arguments.length,k=y<3?g:m===null?m=Object.getOwnPropertyDescriptor(g,O):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(b,g,O,m);else for(var C=b.length-1;C>=0;C--)(x=b[C])&&(k=(y<3?x(k):y>3?x(g,O,k):x(g,O))||k);return y>3&&k&&Object.defineProperty(g,O,k),k},d=this&&this.__param||function(b,g){return function(O,m){g(O,m,b)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferDecorationRenderer=void 0;const u=l(4725),f=l(844),p=l(2585);let v=o.BufferDecorationRenderer=class extends f.Disposable{constructor(b,g,O,m,x){super(),this._screenElement=b,this._bufferService=g,this._coreBrowserService=O,this._decorationService=m,this._renderService=x,this._decorationElements=new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement("div"),this._container.classList.add("xterm-decoration-container"),this._screenElement.appendChild(this._container),this.register(this._renderService.onRenderedViewportChange((()=>this._doRefreshDecorations()))),this.register(this._renderService.onDimensionsChange((()=>{this._dimensionsChanged=!0,this._queueRefresh()}))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt}))),this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh()))),this.register(this._decorationService.onDecorationRemoved((y=>this._removeDecoration(y)))),this.register((0,f.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(const b of this._decorationService.decorations)this._renderDecoration(b);this._dimensionsChanged=!1}_renderDecoration(b){this._refreshStyle(b),this._dimensionsChanged&&this._refreshXPosition(b)}_createElement(b){const g=this._coreBrowserService.mainDocument.createElement("div");g.classList.add("xterm-decoration"),g.classList.toggle("xterm-decoration-top-layer",b?.options?.layer==="top"),g.style.width=`${Math.round((b.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,g.style.height=(b.options.height||1)*this._renderService.dimensions.css.cell.height+"px",g.style.top=(b.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+"px",g.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;const O=b.options.x??0;return O&&O>this._bufferService.cols&&(g.style.display="none"),this._refreshXPosition(b,g),g}_refreshStyle(b){const g=b.marker.line-this._bufferService.buffers.active.ydisp;if(g<0||g>=this._bufferService.rows)b.element&&(b.element.style.display="none",b.onRenderEmitter.fire(b.element));else{let O=this._decorationElements.get(b);O||(O=this._createElement(b),b.element=O,this._decorationElements.set(b,O),this._container.appendChild(O),b.onDispose((()=>{this._decorationElements.delete(b),O.remove()}))),O.style.top=g*this._renderService.dimensions.css.cell.height+"px",O.style.display=this._altBufferIsActive?"none":"block",b.onRenderEmitter.fire(O)}}_refreshXPosition(b,g=b.element){if(!g)return;const O=b.options.x??0;(b.options.anchor||"left")==="right"?g.style.right=O?O*this._renderService.dimensions.css.cell.width+"px":"":g.style.left=O?O*this._renderService.dimensions.css.cell.width+"px":""}_removeDecoration(b){this._decorationElements.get(b)?.remove(),this._decorationElements.delete(b),b.dispose()}};o.BufferDecorationRenderer=v=h([d(1,p.IBufferService),d(2,u.ICoreBrowserService),d(3,p.IDecorationService),d(4,u.IRenderService)],v)},5871:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ColorZoneStore=void 0,o.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(l){if(l.options.overviewRulerOptions){for(const h of this._zones)if(h.color===l.options.overviewRulerOptions.color&&h.position===l.options.overviewRulerOptions.position){if(this._lineIntersectsZone(h,l.marker.line))return;if(this._lineAdjacentToZone(h,l.marker.line,l.options.overviewRulerOptions.position))return void this._addLineToZone(h,l.marker.line)}if(this._zonePoolIndex<this._zonePool.length)return this._zonePool[this._zonePoolIndex].color=l.options.overviewRulerOptions.color,this._zonePool[this._zonePoolIndex].position=l.options.overviewRulerOptions.position,this._zonePool[this._zonePoolIndex].startBufferLine=l.marker.line,this._zonePool[this._zonePoolIndex].endBufferLine=l.marker.line,void this._zones.push(this._zonePool[this._zonePoolIndex++]);this._zones.push({color:l.options.overviewRulerOptions.color,position:l.options.overviewRulerOptions.position,startBufferLine:l.marker.line,endBufferLine:l.marker.line}),this._zonePool.push(this._zones[this._zones.length-1]),this._zonePoolIndex++}}setPadding(l){this._linePadding=l}_lineIntersectsZone(l,h){return h>=l.startBufferLine&&h<=l.endBufferLine}_lineAdjacentToZone(l,h,d){return h>=l.startBufferLine-this._linePadding[d||"full"]&&h<=l.endBufferLine+this._linePadding[d||"full"]}_addLineToZone(l,h){l.startBufferLine=Math.min(l.startBufferLine,h),l.endBufferLine=Math.max(l.endBufferLine,h)}}},5744:function(a,o,l){var h=this&&this.__decorate||function(x,y,k,C){var P,_=arguments.length,T=_<3?y:C===null?C=Object.getOwnPropertyDescriptor(y,k):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(x,y,k,C);else for(var R=x.length-1;R>=0;R--)(P=x[R])&&(T=(_<3?P(T):_>3?P(y,k,T):P(y,k))||T);return _>3&&T&&Object.defineProperty(y,k,T),T},d=this&&this.__param||function(x,y){return function(k,C){y(k,C,x)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OverviewRulerRenderer=void 0;const u=l(5871),f=l(4725),p=l(844),v=l(2585),b={full:0,left:0,center:0,right:0},g={full:0,left:0,center:0,right:0},O={full:0,left:0,center:0,right:0};let m=o.OverviewRulerRenderer=class extends p.Disposable{get _width(){return this._optionsService.options.overviewRulerWidth||0}constructor(x,y,k,C,P,_,T){super(),this._viewportElement=x,this._screenElement=y,this._bufferService=k,this._decorationService=C,this._renderService=P,this._optionsService=_,this._coreBrowserService=T,this._colorZoneStore=new u.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement("canvas"),this._canvas.classList.add("xterm-decoration-overview-ruler"),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement);const R=this._canvas.getContext("2d");if(!R)throw new Error("Ctx cannot be null");this._ctx=R,this._registerDecorationListeners(),this._registerBufferChangeListeners(),this._registerDimensionChangeListeners(),this.register((0,p.toDisposable)((()=>{this._canvas?.remove()})))}_registerDecorationListeners(){this.register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this.register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0))))}_registerBufferChangeListeners(){this.register(this._renderService.onRenderedViewportChange((()=>this._queueRefresh()))),this.register(this._bufferService.buffers.onBufferActivate((()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?"none":"block"}))),this.register(this._bufferService.onScroll((()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())})))}_registerDimensionChangeListeners(){this.register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this.register(this._optionsService.onSpecificOptionChange("overviewRulerWidth",(()=>this._queueRefresh(!0)))),this.register(this._coreBrowserService.onDprChange((()=>this._queueRefresh(!0)))),this._queueRefresh(!0)}_refreshDrawConstants(){const x=Math.floor(this._canvas.width/3),y=Math.ceil(this._canvas.width/3);g.full=this._canvas.width,g.left=x,g.center=y,g.right=x,this._refreshDrawHeightConstants(),O.full=0,O.left=0,O.center=g.left,O.right=g.left+g.center}_refreshDrawHeightConstants(){b.full=Math.round(2*this._coreBrowserService.dpr);const x=this._canvas.height/this._bufferService.buffer.lines.length,y=Math.round(Math.max(Math.min(x,12),6)*this._coreBrowserService.dpr);b.left=y,b.center=y,b.right=y}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*b.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*b.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*b.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*b.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(const y of this._decorationService.decorations)this._colorZoneStore.addDecoration(y);this._ctx.lineWidth=1;const x=this._colorZoneStore.zones;for(const y of x)y.position!=="full"&&this._renderColorZone(y);for(const y of x)y.position==="full"&&this._renderColorZone(y);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderColorZone(x){this._ctx.fillStyle=x.color,this._ctx.fillRect(O[x.position||"full"],Math.round((this._canvas.height-1)*(x.startBufferLine/this._bufferService.buffers.active.lines.length)-b[x.position||"full"]/2),g[x.position||"full"],Math.round((this._canvas.height-1)*((x.endBufferLine-x.startBufferLine)/this._bufferService.buffers.active.lines.length)+b[x.position||"full"]))}_queueRefresh(x,y){this._shouldUpdateDimensions=x||this._shouldUpdateDimensions,this._shouldUpdateAnchor=y||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};o.OverviewRulerRenderer=m=h([d(2,v.IBufferService),d(3,v.IDecorationService),d(4,f.IRenderService),d(5,v.IOptionsService),d(6,f.ICoreBrowserService)],m)},2950:function(a,o,l){var h=this&&this.__decorate||function(b,g,O,m){var x,y=arguments.length,k=y<3?g:m===null?m=Object.getOwnPropertyDescriptor(g,O):m;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")k=Reflect.decorate(b,g,O,m);else for(var C=b.length-1;C>=0;C--)(x=b[C])&&(k=(y<3?x(k):y>3?x(g,O,k):x(g,O))||k);return y>3&&k&&Object.defineProperty(g,O,k),k},d=this&&this.__param||function(b,g){return function(O,m){g(O,m,b)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CompositionHelper=void 0;const u=l(4725),f=l(2585),p=l(2584);let v=o.CompositionHelper=class{get isComposing(){return this._isComposing}constructor(b,g,O,m,x,y){this._textarea=b,this._compositionView=g,this._bufferService=O,this._optionsService=m,this._coreService=x,this._renderService=y,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent="",this._dataAlreadySent="",this._compositionView.classList.add("active")}compositionupdate(b){this._compositionView.textContent=b.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(b){if(this._isComposing||this._isSendingComposition){if(b.keyCode===229||b.keyCode===16||b.keyCode===17||b.keyCode===18)return!1;this._finalizeComposition(!1)}return b.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(b){if(this._compositionView.classList.remove("active"),this._isComposing=!1,b){const g={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let O;this._isSendingComposition=!1,g.start+=this._dataAlreadySent.length,O=this._isComposing?this._textarea.value.substring(g.start,g.end):this._textarea.value.substring(g.start),O.length>0&&this._coreService.triggerDataEvent(O,!0)}}),0)}else{this._isSendingComposition=!1;const g=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(g,!0)}}_handleAnyTextareaChanges(){const b=this._textarea.value;setTimeout((()=>{if(!this._isComposing){const g=this._textarea.value,O=g.replace(b,"");this._dataAlreadySent=O,g.length>b.length?this._coreService.triggerDataEvent(O,!0):g.length<b.length?this._coreService.triggerDataEvent(`${p.C0.DEL}`,!0):g.length===b.length&&g!==b&&this._coreService.triggerDataEvent(g,!0)}}),0)}updateCompositionElements(b){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){const g=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),O=this._renderService.dimensions.css.cell.height,m=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,x=g*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=x+"px",this._compositionView.style.top=m+"px",this._compositionView.style.height=O+"px",this._compositionView.style.lineHeight=O+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";const y=this._compositionView.getBoundingClientRect();this._textarea.style.left=x+"px",this._textarea.style.top=m+"px",this._textarea.style.width=Math.max(y.width,1)+"px",this._textarea.style.height=Math.max(y.height,1)+"px",this._textarea.style.lineHeight=y.height+"px"}b||setTimeout((()=>this.updateCompositionElements(!0)),0)}}};o.CompositionHelper=v=h([d(2,f.IBufferService),d(3,f.IOptionsService),d(4,f.ICoreService),d(5,u.IRenderService)],v)},9806:(a,o)=>{function l(h,d,u){const f=u.getBoundingClientRect(),p=h.getComputedStyle(u),v=parseInt(p.getPropertyValue("padding-left")),b=parseInt(p.getPropertyValue("padding-top"));return[d.clientX-f.left-v,d.clientY-f.top-b]}Object.defineProperty(o,"__esModule",{value:!0}),o.getCoords=o.getCoordsRelativeToElement=void 0,o.getCoordsRelativeToElement=l,o.getCoords=function(h,d,u,f,p,v,b,g,O){if(!v)return;const m=l(h,d,u);return m?(m[0]=Math.ceil((m[0]+(O?b/2:0))/b),m[1]=Math.ceil(m[1]/g),m[0]=Math.min(Math.max(m[0],1),f+(O?1:0)),m[1]=Math.min(Math.max(m[1],1),p),m):void 0}},9504:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.moveToCellSequence=void 0;const h=l(2584);function d(g,O,m,x){const y=g-u(g,m),k=O-u(O,m),C=Math.abs(y-k)-(function(P,_,T){let R=0;const L=P-u(P,T),M=_-u(_,T);for(let E=0;E<Math.abs(L-M);E++){const B=f(P,_)==="A"?-1:1;T.buffer.lines.get(L+B*E)?.isWrapped&&R++}return R})(g,O,m);return b(C,v(f(g,O),x))}function u(g,O){let m=0,x=O.buffer.lines.get(g),y=x?.isWrapped;for(;y&&g>=0&&g<O.rows;)m++,x=O.buffer.lines.get(--g),y=x?.isWrapped;return m}function f(g,O){return g>O?"A":"B"}function p(g,O,m,x,y,k){let C=g,P=O,_="";for(;C!==m||P!==x;)C+=y?1:-1,y&&C>k.cols-1?(_+=k.buffer.translateBufferLineToString(P,!1,g,C),C=0,g=0,P++):!y&&C<0&&(_+=k.buffer.translateBufferLineToString(P,!1,0,g+1),C=k.cols-1,g=C,P--);return _+k.buffer.translateBufferLineToString(P,!1,g,C)}function v(g,O){const m=O?"O":"[";return h.C0.ESC+m+g}function b(g,O){g=Math.floor(g);let m="";for(let x=0;x<g;x++)m+=O;return m}o.moveToCellSequence=function(g,O,m,x){const y=m.buffer.x,k=m.buffer.y;if(!m.buffer.hasScrollback)return(function(_,T,R,L,M,E){return d(T,L,M,E).length===0?"":b(p(_,T,_,T-u(T,M),!1,M).length,v("D",E))})(y,k,0,O,m,x)+d(k,O,m,x)+(function(_,T,R,L,M,E){let B;B=d(T,L,M,E).length>0?L-u(L,M):T;const U=L,F=(function(X,ae,j,W,D,V){let se;return se=d(j,W,D,V).length>0?W-u(W,D):ae,X<j&&se<=W||X>=j&&se<W?"C":"D"})(_,T,R,L,M,E);return b(p(_,B,R,U,F==="C",M).length,v(F,E))})(y,k,g,O,m,x);let C;if(k===O)return C=y>g?"D":"C",b(Math.abs(y-g),v(C,x));C=k>O?"D":"C";const P=Math.abs(k-O);return b((function(_,T){return T.cols-_})(k>O?g:y,m)+(P-1)*m.cols+1+((k>O?y:g)-1),v(C,x))}},1296:function(a,o,l){var h=this&&this.__decorate||function(E,B,U,F){var X,ae=arguments.length,j=ae<3?B:F===null?F=Object.getOwnPropertyDescriptor(B,U):F;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")j=Reflect.decorate(E,B,U,F);else for(var W=E.length-1;W>=0;W--)(X=E[W])&&(j=(ae<3?X(j):ae>3?X(B,U,j):X(B,U))||j);return ae>3&&j&&Object.defineProperty(B,U,j),j},d=this&&this.__param||function(E,B){return function(U,F){B(U,F,E)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRenderer=void 0;const u=l(3787),f=l(2550),p=l(2223),v=l(6171),b=l(6052),g=l(4725),O=l(8055),m=l(8460),x=l(844),y=l(2585),k="xterm-dom-renderer-owner-",C="xterm-rows",P="xterm-fg-",_="xterm-bg-",T="xterm-focus",R="xterm-selection";let L=1,M=o.DomRenderer=class extends x.Disposable{constructor(E,B,U,F,X,ae,j,W,D,V,se,fe,z){super(),this._terminal=E,this._document=B,this._element=U,this._screenElement=F,this._viewportElement=X,this._helperContainer=ae,this._linkifier2=j,this._charSizeService=D,this._optionsService=V,this._bufferService=se,this._coreBrowserService=fe,this._themeService=z,this._terminalClass=L++,this._rowElements=[],this._selectionRenderModel=(0,b.createSelectionRenderModel)(),this.onRequestRedraw=this.register(new m.EventEmitter).event,this._rowContainer=this._document.createElement("div"),this._rowContainer.classList.add(C),this._rowContainer.style.lineHeight="normal",this._rowContainer.setAttribute("aria-hidden","true"),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement("div"),this._selectionContainer.classList.add(R),this._selectionContainer.setAttribute("aria-hidden","true"),this.dimensions=(0,v.createRenderDimensions)(),this._updateDimensions(),this.register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._themeService.onChangeColors((re=>this._injectCss(re)))),this._injectCss(this._themeService.colors),this._rowFactory=W.createInstance(u.DomRendererRowFactory,document),this._element.classList.add(k+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this.register(this._linkifier2.onShowLinkUnderline((re=>this._handleLinkHover(re)))),this.register(this._linkifier2.onHideLinkUnderline((re=>this._handleLinkLeave(re)))),this.register((0,x.toDisposable)((()=>{this._element.classList.remove(k+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new f.WidthCache(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){const E=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*E,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*E),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/E),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/E),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(const U of this._rowElements)U.style.width=`${this.dimensions.css.canvas.width}px`,U.style.height=`${this.dimensions.css.cell.height}px`,U.style.lineHeight=`${this.dimensions.css.cell.height}px`,U.style.overflow="hidden";this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._dimensionsStyleElement));const B=`${this._terminalSelector} .${C} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=B,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(E){this._themeStyleElement||(this._themeStyleElement=this._document.createElement("style"),this._screenElement.appendChild(this._themeStyleElement));let B=`${this._terminalSelector} .${C} { color: ${E.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;B+=`${this._terminalSelector} .${C} .xterm-dim { color: ${O.color.multiplyOpacity(E.foreground,.5).css};}`,B+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;const U=`blink_underline_${this._terminalClass}`,F=`blink_bar_${this._terminalClass}`,X=`blink_block_${this._terminalClass}`;B+=`@keyframes ${U} { 50% { border-bottom-style: hidden; }}`,B+=`@keyframes ${F} { 50% { box-shadow: none; }}`,B+=`@keyframes ${X} { 0% { background-color: ${E.cursor.css}; color: ${E.cursorAccent.css}; } 50% { background-color: inherit; color: ${E.cursor.css}; }}`,B+=`${this._terminalSelector} .${C}.${T} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${U} 1s step-end infinite;}${this._terminalSelector} .${C}.${T} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${F} 1s step-end infinite;}${this._terminalSelector} .${C}.${T} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${X} 1s step-end infinite;}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-block { background-color: ${E.cursor.css}; color: ${E.cursorAccent.css};}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${E.cursor.css} !important; color: ${E.cursorAccent.css} !important;}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${E.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${E.cursor.css} inset;}${this._terminalSelector} .${C} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${E.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,B+=`${this._terminalSelector} .${R} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${R} div { position: absolute; background-color: ${E.selectionBackgroundOpaque.css};}${this._terminalSelector} .${R} div { position: absolute; background-color: ${E.selectionInactiveBackgroundOpaque.css};}`;for(const[ae,j]of E.ansi.entries())B+=`${this._terminalSelector} .${P}${ae} { color: ${j.css}; }${this._terminalSelector} .${P}${ae}.xterm-dim { color: ${O.color.multiplyOpacity(j,.5).css}; }${this._terminalSelector} .${_}${ae} { background-color: ${j.css}; }`;B+=`${this._terminalSelector} .${P}${p.INVERTED_DEFAULT_COLOR} { color: ${O.color.opaque(E.background).css}; }${this._terminalSelector} .${P}${p.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${O.color.multiplyOpacity(O.color.opaque(E.background),.5).css}; }${this._terminalSelector} .${_}${p.INVERTED_DEFAULT_COLOR} { background-color: ${E.foreground.css}; }`,this._themeStyleElement.textContent=B}_setDefaultSpacing(){const E=this.dimensions.css.cell.width-this._widthCache.get("W",!1,!1);this._rowContainer.style.letterSpacing=`${E}px`,this._rowFactory.defaultSpacing=E}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(E,B){for(let U=this._rowElements.length;U<=B;U++){const F=this._document.createElement("div");this._rowContainer.appendChild(F),this._rowElements.push(F)}for(;this._rowElements.length>B;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(E,B){this._refreshRowElements(E,B),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(T),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(T),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(E,B,U){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(E,B,U),this.renderRows(0,this._bufferService.rows-1),!E||!B)return;this._selectionRenderModel.update(this._terminal,E,B,U);const F=this._selectionRenderModel.viewportStartRow,X=this._selectionRenderModel.viewportEndRow,ae=this._selectionRenderModel.viewportCappedStartRow,j=this._selectionRenderModel.viewportCappedEndRow;if(ae>=this._bufferService.rows||j<0)return;const W=this._document.createDocumentFragment();if(U){const D=E[0]>B[0];W.appendChild(this._createSelectionElement(ae,D?B[0]:E[0],D?E[0]:B[0],j-ae+1))}else{const D=F===ae?E[0]:0,V=ae===X?B[0]:this._bufferService.cols;W.appendChild(this._createSelectionElement(ae,D,V));const se=j-ae-1;if(W.appendChild(this._createSelectionElement(ae+1,0,this._bufferService.cols,se)),ae!==j){const fe=X===j?B[0]:this._bufferService.cols;W.appendChild(this._createSelectionElement(j,0,fe))}}this._selectionContainer.appendChild(W)}_createSelectionElement(E,B,U,F=1){const X=this._document.createElement("div"),ae=B*this.dimensions.css.cell.width;let j=this.dimensions.css.cell.width*(U-B);return ae+j>this.dimensions.css.canvas.width&&(j=this.dimensions.css.canvas.width-ae),X.style.height=F*this.dimensions.css.cell.height+"px",X.style.top=E*this.dimensions.css.cell.height+"px",X.style.left=`${ae}px`,X.style.width=`${j}px`,X}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(const E of this._rowElements)E.replaceChildren()}renderRows(E,B){const U=this._bufferService.buffer,F=U.ybase+U.y,X=Math.min(U.x,this._bufferService.cols-1),ae=this._optionsService.rawOptions.cursorBlink,j=this._optionsService.rawOptions.cursorStyle,W=this._optionsService.rawOptions.cursorInactiveStyle;for(let D=E;D<=B;D++){const V=D+U.ydisp,se=this._rowElements[D],fe=U.lines.get(V);if(!se||!fe)break;se.replaceChildren(...this._rowFactory.createRow(fe,V,V===F,j,W,X,ae,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${k}${this._terminalClass}`}_handleLinkHover(E){this._setCellUnderline(E.x1,E.x2,E.y1,E.y2,E.cols,!0)}_handleLinkLeave(E){this._setCellUnderline(E.x1,E.x2,E.y1,E.y2,E.cols,!1)}_setCellUnderline(E,B,U,F,X,ae){U<0&&(E=0),F<0&&(B=0);const j=this._bufferService.rows-1;U=Math.max(Math.min(U,j),0),F=Math.max(Math.min(F,j),0),X=Math.min(X,this._bufferService.cols);const W=this._bufferService.buffer,D=W.ybase+W.y,V=Math.min(W.x,X-1),se=this._optionsService.rawOptions.cursorBlink,fe=this._optionsService.rawOptions.cursorStyle,z=this._optionsService.rawOptions.cursorInactiveStyle;for(let re=U;re<=F;++re){const Z=re+W.ydisp,A=this._rowElements[re],J=W.lines.get(Z);if(!A||!J)break;A.replaceChildren(...this._rowFactory.createRow(J,Z,Z===D,fe,z,V,se,this.dimensions.css.cell.width,this._widthCache,ae?re===U?E:0:-1,ae?(re===F?B:X)-1:-1))}}};o.DomRenderer=M=h([d(7,y.IInstantiationService),d(8,g.ICharSizeService),d(9,y.IOptionsService),d(10,y.IBufferService),d(11,g.ICoreBrowserService),d(12,g.IThemeService)],M)},3787:function(a,o,l){var h=this&&this.__decorate||function(C,P,_,T){var R,L=arguments.length,M=L<3?P:T===null?T=Object.getOwnPropertyDescriptor(P,_):T;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")M=Reflect.decorate(C,P,_,T);else for(var E=C.length-1;E>=0;E--)(R=C[E])&&(M=(L<3?R(M):L>3?R(P,_,M):R(P,_))||M);return L>3&&M&&Object.defineProperty(P,_,M),M},d=this&&this.__param||function(C,P){return function(_,T){P(_,T,C)}};Object.defineProperty(o,"__esModule",{value:!0}),o.DomRendererRowFactory=void 0;const u=l(2223),f=l(643),p=l(511),v=l(2585),b=l(8055),g=l(4725),O=l(4269),m=l(6171),x=l(3734);let y=o.DomRendererRowFactory=class{constructor(C,P,_,T,R,L,M){this._document=C,this._characterJoinerService=P,this._optionsService=_,this._coreBrowserService=T,this._coreService=R,this._decorationService=L,this._themeService=M,this._workCell=new p.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(C,P,_){this._selectionStart=C,this._selectionEnd=P,this._columnSelectMode=_}createRow(C,P,_,T,R,L,M,E,B,U,F){const X=[],ae=this._characterJoinerService.getJoinedCharacters(P),j=this._themeService.colors;let W,D=C.getNoBgTrimmedLength();_&&D<L+1&&(D=L+1);let V=0,se="",fe=0,z=0,re=0,Z=!1,A=0,J=!1,Y=0;const oe=[],K=U!==-1&&F!==-1;for(let pe=0;pe<D;pe++){C.loadCell(pe,this._workCell);let je=this._workCell.getWidth();if(je===0)continue;let we=!1,Ge=pe,Qe=this._workCell;if(ae.length>0&&pe===ae[0][0]){we=!0;const rt=ae.shift();Qe=new O.JoinedCellData(this._workCell,C.translateToString(!0,rt[0],rt[1]),rt[1]-rt[0]),Ge=rt[1]-1,je=Qe.getWidth()}const Ee=this._isCellInSelection(pe,P),ye=_&&pe===L,G=K&&pe>=U&&pe<=F;let qe=!1;this._decorationService.forEachDecorationAtCell(pe,P,void 0,(rt=>{qe=!0}));let He=Qe.getChars()||f.WHITESPACE_CELL_CHAR;if(He===" "&&(Qe.isUnderline()||Qe.isOverline())&&(He=" "),Y=je*E-B.get(He,Qe.isBold(),Qe.isItalic()),W){if(V&&(Ee&&J||!Ee&&!J&&Qe.bg===fe)&&(Ee&&J&&j.selectionForeground||Qe.fg===z)&&Qe.extended.ext===re&&G===Z&&Y===A&&!ye&&!we&&!qe){Qe.isInvisible()?se+=f.WHITESPACE_CELL_CHAR:se+=He,V++;continue}V&&(W.textContent=se),W=this._document.createElement("span"),V=0,se=""}else W=this._document.createElement("span");if(fe=Qe.bg,z=Qe.fg,re=Qe.extended.ext,Z=G,A=Y,J=Ee,we&&L>=pe&&L<=Ge&&(L=pe),!this._coreService.isCursorHidden&&ye&&this._coreService.isCursorInitialized){if(oe.push("xterm-cursor"),this._coreBrowserService.isFocused)M&&oe.push("xterm-cursor-blink"),oe.push(T==="bar"?"xterm-cursor-bar":T==="underline"?"xterm-cursor-underline":"xterm-cursor-block");else if(R)switch(R){case"outline":oe.push("xterm-cursor-outline");break;case"block":oe.push("xterm-cursor-block");break;case"bar":oe.push("xterm-cursor-bar");break;case"underline":oe.push("xterm-cursor-underline")}}if(Qe.isBold()&&oe.push("xterm-bold"),Qe.isItalic()&&oe.push("xterm-italic"),Qe.isDim()&&oe.push("xterm-dim"),se=Qe.isInvisible()?f.WHITESPACE_CELL_CHAR:Qe.getChars()||f.WHITESPACE_CELL_CHAR,Qe.isUnderline()&&(oe.push(`xterm-underline-${Qe.extended.underlineStyle}`),se===" "&&(se=" "),!Qe.isUnderlineColorDefault()))if(Qe.isUnderlineColorRGB())W.style.textDecorationColor=`rgb(${x.AttributeData.toColorRGB(Qe.getUnderlineColor()).join(",")})`;else{let rt=Qe.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&Qe.isBold()&&rt<8&&(rt+=8),W.style.textDecorationColor=j.ansi[rt].css}Qe.isOverline()&&(oe.push("xterm-overline"),se===" "&&(se=" ")),Qe.isStrikethrough()&&oe.push("xterm-strikethrough"),G&&(W.style.textDecoration="underline");let Ye=Qe.getFgColor(),pt=Qe.getFgColorMode(),xt=Qe.getBgColor(),bt=Qe.getBgColorMode();const vt=!!Qe.isInverse();if(vt){const rt=Ye;Ye=xt,xt=rt;const yt=pt;pt=bt,bt=yt}let Pe,At,Ft,Es=!1;switch(this._decorationService.forEachDecorationAtCell(pe,P,void 0,(rt=>{rt.options.layer!=="top"&&Es||(rt.backgroundColorRGB&&(bt=50331648,xt=rt.backgroundColorRGB.rgba>>8&16777215,Pe=rt.backgroundColorRGB),rt.foregroundColorRGB&&(pt=50331648,Ye=rt.foregroundColorRGB.rgba>>8&16777215,At=rt.foregroundColorRGB),Es=rt.options.layer==="top")})),!Es&&Ee&&(Pe=this._coreBrowserService.isFocused?j.selectionBackgroundOpaque:j.selectionInactiveBackgroundOpaque,xt=Pe.rgba>>8&16777215,bt=50331648,Es=!0,j.selectionForeground&&(pt=50331648,Ye=j.selectionForeground.rgba>>8&16777215,At=j.selectionForeground)),Es&&oe.push("xterm-decoration-top"),bt){case 16777216:case 33554432:Ft=j.ansi[xt],oe.push(`xterm-bg-${xt}`);break;case 50331648:Ft=b.channels.toColor(xt>>16,xt>>8&255,255&xt),this._addStyle(W,`background-color:#${k((xt>>>0).toString(16),"0",6)}`);break;default:vt?(Ft=j.foreground,oe.push(`xterm-bg-${u.INVERTED_DEFAULT_COLOR}`)):Ft=j.background}switch(Pe||Qe.isDim()&&(Pe=b.color.multiplyOpacity(Ft,.5)),pt){case 16777216:case 33554432:Qe.isBold()&&Ye<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(Ye+=8),this._applyMinimumContrast(W,Ft,j.ansi[Ye],Qe,Pe,void 0)||oe.push(`xterm-fg-${Ye}`);break;case 50331648:const rt=b.channels.toColor(Ye>>16&255,Ye>>8&255,255&Ye);this._applyMinimumContrast(W,Ft,rt,Qe,Pe,At)||this._addStyle(W,`color:#${k(Ye.toString(16),"0",6)}`);break;default:this._applyMinimumContrast(W,Ft,j.foreground,Qe,Pe,At)||vt&&oe.push(`xterm-fg-${u.INVERTED_DEFAULT_COLOR}`)}oe.length&&(W.className=oe.join(" "),oe.length=0),ye||we||qe?W.textContent=se:V++,Y!==this.defaultSpacing&&(W.style.letterSpacing=`${Y}px`),X.push(W),pe=Ge}return W&&V&&(W.textContent=se),X}_applyMinimumContrast(C,P,_,T,R,L){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,m.treatGlyphAsBackgroundColor)(T.getCode()))return!1;const M=this._getContrastCache(T);let E;if(R||L||(E=M.getColor(P.rgba,_.rgba)),E===void 0){const B=this._optionsService.rawOptions.minimumContrastRatio/(T.isDim()?2:1);E=b.color.ensureContrastRatio(R||P,L||_,B),M.setColor((R||P).rgba,(L||_).rgba,E??null)}return!!E&&(this._addStyle(C,`color:${E.css}`),!0)}_getContrastCache(C){return C.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(C,P){C.setAttribute("style",`${C.getAttribute("style")||""}${P};`)}_isCellInSelection(C,P){const _=this._selectionStart,T=this._selectionEnd;return!(!_||!T)&&(this._columnSelectMode?_[0]<=T[0]?C>=_[0]&&P>=_[1]&&C<T[0]&&P<=T[1]:C<_[0]&&P>=_[1]&&C>=T[0]&&P<=T[1]:P>_[1]&&P<T[1]||_[1]===T[1]&&P===_[1]&&C>=_[0]&&C<T[0]||_[1]<T[1]&&P===T[1]&&C<T[0]||_[1]<T[1]&&P===_[1]&&C>=_[0])}};function k(C,P,_){for(;C.length<_;)C=P+C;return C}o.DomRendererRowFactory=y=h([d(1,g.ICharacterJoinerService),d(2,v.IOptionsService),d(3,g.ICoreBrowserService),d(4,v.ICoreService),d(5,v.IDecorationService),d(6,g.IThemeService)],y)},2550:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WidthCache=void 0,o.WidthCache=class{constructor(l,h){this._flat=new Float32Array(256),this._font="",this._fontSize=0,this._weight="normal",this._weightBold="bold",this._measureElements=[],this._container=l.createElement("div"),this._container.classList.add("xterm-width-cache-measure-container"),this._container.setAttribute("aria-hidden","true"),this._container.style.whiteSpace="pre",this._container.style.fontKerning="none";const d=l.createElement("span");d.classList.add("xterm-char-measure-element");const u=l.createElement("span");u.classList.add("xterm-char-measure-element"),u.style.fontWeight="bold";const f=l.createElement("span");f.classList.add("xterm-char-measure-element"),f.style.fontStyle="italic";const p=l.createElement("span");p.classList.add("xterm-char-measure-element"),p.style.fontWeight="bold",p.style.fontStyle="italic",this._measureElements=[d,u,f,p],this._container.appendChild(d),this._container.appendChild(u),this._container.appendChild(f),this._container.appendChild(p),h.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=new Map}setFont(l,h,d,u){l===this._font&&h===this._fontSize&&d===this._weight&&u===this._weightBold||(this._font=l,this._fontSize=h,this._weight=d,this._weightBold=u,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${d}`,this._measureElements[1].style.fontWeight=`${u}`,this._measureElements[2].style.fontWeight=`${d}`,this._measureElements[3].style.fontWeight=`${u}`,this.clear())}get(l,h,d){let u=0;if(!h&&!d&&l.length===1&&(u=l.charCodeAt(0))<256){if(this._flat[u]!==-9999)return this._flat[u];const v=this._measure(l,0);return v>0&&(this._flat[u]=v),v}let f=l;h&&(f+="B"),d&&(f+="I");let p=this._holey.get(f);if(p===void 0){let v=0;h&&(v|=1),d&&(v|=2),p=this._measure(l,v),p>0&&this._holey.set(f,p)}return p}_measure(l,h){const d=this._measureElements[h];return d.textContent=l.repeat(32),d.offsetWidth/32}}},2223:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.TEXT_BASELINE=o.DIM_OPACITY=o.INVERTED_DEFAULT_COLOR=void 0;const h=l(6114);o.INVERTED_DEFAULT_COLOR=257,o.DIM_OPACITY=.5,o.TEXT_BASELINE=h.isFirefox||h.isLegacyEdge?"bottom":"ideographic"},6171:(a,o)=>{function l(d){return 57508<=d&&d<=57558}function h(d){return d>=128512&&d<=128591||d>=127744&&d<=128511||d>=128640&&d<=128767||d>=9728&&d<=9983||d>=9984&&d<=10175||d>=65024&&d<=65039||d>=129280&&d<=129535||d>=127462&&d<=127487}Object.defineProperty(o,"__esModule",{value:!0}),o.computeNextVariantOffset=o.createRenderDimensions=o.treatGlyphAsBackgroundColor=o.allowRescaling=o.isEmoji=o.isRestrictedPowerlineGlyph=o.isPowerlineGlyph=o.throwIfFalsy=void 0,o.throwIfFalsy=function(d){if(!d)throw new Error("value must not be falsy");return d},o.isPowerlineGlyph=l,o.isRestrictedPowerlineGlyph=function(d){return 57520<=d&&d<=57527},o.isEmoji=h,o.allowRescaling=function(d,u,f,p){return u===1&&f>Math.ceil(1.5*p)&&d!==void 0&&d>255&&!h(d)&&!l(d)&&!(function(v){return 57344<=v&&v<=63743})(d)},o.treatGlyphAsBackgroundColor=function(d){return l(d)||(function(u){return 9472<=u&&u<=9631})(d)},o.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},o.computeNextVariantOffset=function(d,u,f=0){return(d-(2*Math.round(u)-f))%(2*Math.round(u))}},6052:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createSelectionRenderModel=void 0;class l{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(d,u,f,p=!1){if(this.selectionStart=u,this.selectionEnd=f,!u||!f||u[0]===f[0]&&u[1]===f[1])return void this.clear();const v=d.buffers.active.ydisp,b=u[1]-v,g=f[1]-v,O=Math.max(b,0),m=Math.min(g,d.rows-1);O>=d.rows||m<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=p,this.viewportStartRow=b,this.viewportEndRow=g,this.viewportCappedStartRow=O,this.viewportCappedEndRow=m,this.startCol=u[0],this.endCol=f[0])}isCellSelected(d,u,f){return!!this.hasSelection&&(f-=d.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?u>=this.startCol&&f>=this.viewportCappedStartRow&&u<this.endCol&&f<=this.viewportCappedEndRow:u<this.startCol&&f>=this.viewportCappedStartRow&&u>=this.endCol&&f<=this.viewportCappedEndRow:f>this.viewportStartRow&&f<this.viewportEndRow||this.viewportStartRow===this.viewportEndRow&&f===this.viewportStartRow&&u>=this.startCol&&u<this.endCol||this.viewportStartRow<this.viewportEndRow&&f===this.viewportEndRow&&u<this.endCol||this.viewportStartRow<this.viewportEndRow&&f===this.viewportStartRow&&u>=this.startCol)}}o.createSelectionRenderModel=function(){return new l}},456:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionModel=void 0,o.SelectionModel=class{constructor(l){this._bufferService=l,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){const l=this.selectionStart[0]+this.selectionStartLength;return l>this._bufferService.cols?l%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)-1]:[l%this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)]:[l,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){const l=this.selectionStart[0]+this.selectionStartLength;return l>this._bufferService.cols?[l%this._bufferService.cols,this.selectionStart[1]+Math.floor(l/this._bufferService.cols)]:[Math.max(l,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){const l=this.selectionStart,h=this.selectionEnd;return!(!l||!h)&&(l[1]>h[1]||l[1]===h[1]&&l[0]>h[0])}handleTrim(l){return this.selectionStart&&(this.selectionStart[1]-=l),this.selectionEnd&&(this.selectionEnd[1]-=l),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},428:function(a,o,l){var h=this&&this.__decorate||function(m,x,y,k){var C,P=arguments.length,_=P<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,y):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(m,x,y,k);else for(var T=m.length-1;T>=0;T--)(C=m[T])&&(_=(P<3?C(_):P>3?C(x,y,_):C(x,y))||_);return P>3&&_&&Object.defineProperty(x,y,_),_},d=this&&this.__param||function(m,x){return function(y,k){x(y,k,m)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharSizeService=void 0;const u=l(2585),f=l(8460),p=l(844);let v=o.CharSizeService=class extends p.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(m,x,y){super(),this._optionsService=y,this.width=0,this.height=0,this._onCharSizeChange=this.register(new f.EventEmitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this.register(new O(this._optionsService))}catch{this._measureStrategy=this.register(new g(m,x,this._optionsService))}this.register(this._optionsService.onMultipleOptionChange(["fontFamily","fontSize"],(()=>this.measure())))}measure(){const m=this._measureStrategy.measure();m.width===this.width&&m.height===this.height||(this.width=m.width,this.height=m.height,this._onCharSizeChange.fire())}};o.CharSizeService=v=h([d(2,u.IOptionsService)],v);class b extends p.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(x,y){x!==void 0&&x>0&&y!==void 0&&y>0&&(this._result.width=x,this._result.height=y)}}class g extends b{constructor(x,y,k){super(),this._document=x,this._parentElement=y,this._optionsService=k,this._measureElement=this._document.createElement("span"),this._measureElement.classList.add("xterm-char-measure-element"),this._measureElement.textContent="W".repeat(32),this._measureElement.setAttribute("aria-hidden","true"),this._measureElement.style.whiteSpace="pre",this._measureElement.style.fontKerning="none",this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}}class O extends b{constructor(x){super(),this._optionsService=x,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext("2d");const y=this._ctx.measureText("W");if(!("width"in y&&"fontBoundingBoxAscent"in y&&"fontBoundingBoxDescent"in y))throw new Error("Required font metrics not supported")}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;const x=this._ctx.measureText("W");return this._validateAndSet(x.width,x.fontBoundingBoxAscent+x.fontBoundingBoxDescent),this._result}}},4269:function(a,o,l){var h=this&&this.__decorate||function(O,m,x,y){var k,C=arguments.length,P=C<3?m:y===null?y=Object.getOwnPropertyDescriptor(m,x):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")P=Reflect.decorate(O,m,x,y);else for(var _=O.length-1;_>=0;_--)(k=O[_])&&(P=(C<3?k(P):C>3?k(m,x,P):k(m,x))||P);return C>3&&P&&Object.defineProperty(m,x,P),P},d=this&&this.__param||function(O,m){return function(x,y){m(x,y,O)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CharacterJoinerService=o.JoinedCellData=void 0;const u=l(3734),f=l(643),p=l(511),v=l(2585);class b extends u.AttributeData{constructor(m,x,y){super(),this.content=0,this.combinedData="",this.fg=m.fg,this.bg=m.bg,this.combinedData=x,this._width=y}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(m){throw new Error("not implemented")}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.JoinedCellData=b;let g=o.CharacterJoinerService=class T_{constructor(m){this._bufferService=m,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new p.CellData}register(m){const x={id:this._nextCharacterJoinerId++,handler:m};return this._characterJoiners.push(x),x.id}deregister(m){for(let x=0;x<this._characterJoiners.length;x++)if(this._characterJoiners[x].id===m)return this._characterJoiners.splice(x,1),!0;return!1}getJoinedCharacters(m){if(this._characterJoiners.length===0)return[];const x=this._bufferService.buffer.lines.get(m);if(!x||x.length===0)return[];const y=[],k=x.translateToString(!0);let C=0,P=0,_=0,T=x.getFg(0),R=x.getBg(0);for(let L=0;L<x.getTrimmedLength();L++)if(x.loadCell(L,this._workCell),this._workCell.getWidth()!==0){if(this._workCell.fg!==T||this._workCell.bg!==R){if(L-C>1){const M=this._getJoinedRanges(k,_,P,x,C);for(let E=0;E<M.length;E++)y.push(M[E])}C=L,_=P,T=this._workCell.fg,R=this._workCell.bg}P+=this._workCell.getChars().length||f.WHITESPACE_CELL_CHAR.length}if(this._bufferService.cols-C>1){const L=this._getJoinedRanges(k,_,P,x,C);for(let M=0;M<L.length;M++)y.push(L[M])}return y}_getJoinedRanges(m,x,y,k,C){const P=m.substring(x,y);let _=[];try{_=this._characterJoiners[0].handler(P)}catch(T){console.error(T)}for(let T=1;T<this._characterJoiners.length;T++)try{const R=this._characterJoiners[T].handler(P);for(let L=0;L<R.length;L++)T_._mergeRanges(_,R[L])}catch(R){console.error(R)}return this._stringRangesToCellRanges(_,k,C),_}_stringRangesToCellRanges(m,x,y){let k=0,C=!1,P=0,_=m[k];if(_){for(let T=y;T<this._bufferService.cols;T++){const R=x.getWidth(T),L=x.getString(T).length||f.WHITESPACE_CELL_CHAR.length;if(R!==0){if(!C&&_[0]<=P&&(_[0]=T,C=!0),_[1]<=P){if(_[1]=T,_=m[++k],!_)break;_[0]<=P?(_[0]=T,C=!0):C=!1}P+=L}}_&&(_[1]=this._bufferService.cols)}}static _mergeRanges(m,x){let y=!1;for(let k=0;k<m.length;k++){const C=m[k];if(y){if(x[1]<=C[0])return m[k-1][1]=x[1],m;if(x[1]<=C[1])return m[k-1][1]=Math.max(x[1],C[1]),m.splice(k,1),m;m.splice(k,1),k--}else{if(x[1]<=C[0])return m.splice(k,0,x),m;if(x[1]<=C[1])return C[0]=Math.min(x[0],C[0]),m;x[0]<C[1]&&(C[0]=Math.min(x[0],C[0]),y=!0)}}return y?m[m.length-1][1]=x[1]:m.push(x),m}};o.CharacterJoinerService=g=h([d(0,v.IBufferService)],g)},5114:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreBrowserService=void 0;const h=l(844),d=l(8460),u=l(3656);class f extends h.Disposable{constructor(b,g,O){super(),this._textarea=b,this._window=g,this.mainDocument=O,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=new p(this._window),this._onDprChange=this.register(new d.EventEmitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this.register(new d.EventEmitter),this.onWindowChange=this._onWindowChange.event,this.register(this.onWindowChange((m=>this._screenDprMonitor.setWindow(m)))),this.register((0,d.forwardEvent)(this._screenDprMonitor.onDprChange,this._onDprChange)),this._textarea.addEventListener("focus",(()=>this._isFocused=!0)),this._textarea.addEventListener("blur",(()=>this._isFocused=!1))}get window(){return this._window}set window(b){this._window!==b&&(this._window=b,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask((()=>this._cachedIsFocused=void 0))),this._cachedIsFocused}}o.CoreBrowserService=f;class p extends h.Disposable{constructor(b){super(),this._parentWindow=b,this._windowResizeListener=this.register(new h.MutableDisposable),this._onDprChange=this.register(new d.EventEmitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this.register((0,h.toDisposable)((()=>this.clearListener())))}setWindow(b){this._parentWindow=b,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,u.addDisposableDomListener)(this._parentWindow,"resize",(()=>this._setDprAndFireIfDiffers()))}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}}},779:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.LinkProviderService=void 0;const h=l(844);class d extends h.Disposable{constructor(){super(),this.linkProviders=[],this.register((0,h.toDisposable)((()=>this.linkProviders.length=0)))}registerLinkProvider(f){return this.linkProviders.push(f),{dispose:()=>{const p=this.linkProviders.indexOf(f);p!==-1&&this.linkProviders.splice(p,1)}}}}o.LinkProviderService=d},8934:function(a,o,l){var h=this&&this.__decorate||function(v,b,g,O){var m,x=arguments.length,y=x<3?b:O===null?O=Object.getOwnPropertyDescriptor(b,g):O;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")y=Reflect.decorate(v,b,g,O);else for(var k=v.length-1;k>=0;k--)(m=v[k])&&(y=(x<3?m(y):x>3?m(b,g,y):m(b,g))||y);return x>3&&y&&Object.defineProperty(b,g,y),y},d=this&&this.__param||function(v,b){return function(g,O){b(g,O,v)}};Object.defineProperty(o,"__esModule",{value:!0}),o.MouseService=void 0;const u=l(4725),f=l(9806);let p=o.MouseService=class{constructor(v,b){this._renderService=v,this._charSizeService=b}getCoords(v,b,g,O,m){return(0,f.getCoords)(window,v,b,g,O,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,m)}getMouseReportCoords(v,b){const g=(0,f.getCoordsRelativeToElement)(window,v,b);if(this._charSizeService.hasValidSize)return g[0]=Math.min(Math.max(g[0],0),this._renderService.dimensions.css.canvas.width-1),g[1]=Math.min(Math.max(g[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(g[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(g[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(g[0]),y:Math.floor(g[1])}}};o.MouseService=p=h([d(0,u.IRenderService),d(1,u.ICharSizeService)],p)},3230:function(a,o,l){var h=this&&this.__decorate||function(m,x,y,k){var C,P=arguments.length,_=P<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,y):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(m,x,y,k);else for(var T=m.length-1;T>=0;T--)(C=m[T])&&(_=(P<3?C(_):P>3?C(x,y,_):C(x,y))||_);return P>3&&_&&Object.defineProperty(x,y,_),_},d=this&&this.__param||function(m,x){return function(y,k){x(y,k,m)}};Object.defineProperty(o,"__esModule",{value:!0}),o.RenderService=void 0;const u=l(6193),f=l(4725),p=l(8460),v=l(844),b=l(7226),g=l(2585);let O=o.RenderService=class extends v.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(m,x,y,k,C,P,_,T){super(),this._rowCount=m,this._charSizeService=k,this._renderer=this.register(new v.MutableDisposable),this._pausedResizeTask=new b.DebouncedIdleTask,this._observerDisposable=this.register(new v.MutableDisposable),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this.register(new p.EventEmitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this.register(new p.EventEmitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this.register(new p.EventEmitter),this.onRender=this._onRender.event,this._onRefreshRequest=this.register(new p.EventEmitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new u.RenderDebouncer(((R,L)=>this._renderRows(R,L)),_),this.register(this._renderDebouncer),this.register(_.onDprChange((()=>this.handleDevicePixelRatioChange()))),this.register(P.onResize((()=>this._fullRefresh()))),this.register(P.buffers.onBufferActivate((()=>this._renderer.value?.clear()))),this.register(y.onOptionChange((()=>this._handleOptionsChanged()))),this.register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this.register(C.onDecorationRegistered((()=>this._fullRefresh()))),this.register(C.onDecorationRemoved((()=>this._fullRefresh()))),this.register(y.onMultipleOptionChange(["customGlyphs","drawBoldTextInBrightColors","letterSpacing","lineHeight","fontFamily","fontSize","fontWeight","fontWeightBold","minimumContrastRatio","rescaleOverlappingGlyphs"],(()=>{this.clear(),this.handleResize(P.cols,P.rows),this._fullRefresh()}))),this.register(y.onMultipleOptionChange(["cursorBlink","cursorStyle"],(()=>this.refreshRows(P.buffer.y,P.buffer.y,!0)))),this.register(T.onChangeColors((()=>this._fullRefresh()))),this._registerIntersectionObserver(_.window,x),this.register(_.onWindowChange((R=>this._registerIntersectionObserver(R,x))))}_registerIntersectionObserver(m,x){if("IntersectionObserver"in m){const y=new m.IntersectionObserver((k=>this._handleIntersectionChange(k[k.length-1])),{threshold:0});y.observe(x),this._observerDisposable.value=(0,v.toDisposable)((()=>y.disconnect()))}}_handleIntersectionChange(m){this._isPaused=m.isIntersecting===void 0?m.intersectionRatio===0:!m.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(m,x,y=!1){this._isPaused?this._needsFullRefresh=!0:(y||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(m,x,this._rowCount))}_renderRows(m,x){this._renderer.value&&(m=Math.min(m,this._rowCount-1),x=Math.min(x,this._rowCount-1),this._renderer.value.renderRows(m,x),this._needsSelectionRefresh&&(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),this._needsSelectionRefresh=!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:m,end:x}),this._onRender.fire({start:m,end:x}),this._isNextRenderRedrawOnly=!0)}resize(m,x){this._rowCount=x,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(m){this._renderer.value=m,this._renderer.value&&(this._renderer.value.onRequestRedraw((x=>this.refreshRows(x.start,x.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(m){return this._renderDebouncer.addRefreshCallback(m)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(m,x){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>this._renderer.value?.handleResize(m,x))):this._renderer.value.handleResize(m,x),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(m,x,y){this._selectionState.start=m,this._selectionState.end=x,this._selectionState.columnSelectMode=y,this._renderer.value?.handleSelectionChanged(m,x,y)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};o.RenderService=O=h([d(2,g.IOptionsService),d(3,f.ICharSizeService),d(4,g.IDecorationService),d(5,g.IBufferService),d(6,f.ICoreBrowserService),d(7,f.IThemeService)],O)},9312:function(a,o,l){var h=this&&this.__decorate||function(_,T,R,L){var M,E=arguments.length,B=E<3?T:L===null?L=Object.getOwnPropertyDescriptor(T,R):L;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")B=Reflect.decorate(_,T,R,L);else for(var U=_.length-1;U>=0;U--)(M=_[U])&&(B=(E<3?M(B):E>3?M(T,R,B):M(T,R))||B);return E>3&&B&&Object.defineProperty(T,R,B),B},d=this&&this.__param||function(_,T){return function(R,L){T(R,L,_)}};Object.defineProperty(o,"__esModule",{value:!0}),o.SelectionService=void 0;const u=l(9806),f=l(9504),p=l(456),v=l(4725),b=l(8460),g=l(844),O=l(6114),m=l(4841),x=l(511),y=l(2585),k=" ",C=new RegExp(k,"g");let P=o.SelectionService=class extends g.Disposable{constructor(_,T,R,L,M,E,B,U,F){super(),this._element=_,this._screenElement=T,this._linkifier=R,this._bufferService=L,this._coreService=M,this._mouseService=E,this._optionsService=B,this._renderService=U,this._coreBrowserService=F,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new x.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this.register(new b.EventEmitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this.register(new b.EventEmitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this.register(new b.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this.register(new b.EventEmitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=X=>this._handleMouseMove(X),this._mouseUpListener=X=>this._handleMouseUp(X),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((X=>this._handleTrim(X))),this.register(this._bufferService.buffers.onBufferActivate((X=>this._handleBufferActivate(X)))),this.enable(),this._model=new p.SelectionModel(this._bufferService),this._activeSelectionMode=0,this.register((0,g.toDisposable)((()=>{this._removeMouseDownListeners()})))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){const _=this._model.finalSelectionStart,T=this._model.finalSelectionEnd;return!(!_||!T||_[0]===T[0]&&_[1]===T[1])}get selectionText(){const _=this._model.finalSelectionStart,T=this._model.finalSelectionEnd;if(!_||!T)return"";const R=this._bufferService.buffer,L=[];if(this._activeSelectionMode===3){if(_[0]===T[0])return"";const M=_[0]<T[0]?_[0]:T[0],E=_[0]<T[0]?T[0]:_[0];for(let B=_[1];B<=T[1];B++){const U=R.translateBufferLineToString(B,!0,M,E);L.push(U)}}else{const M=_[1]===T[1]?T[0]:void 0;L.push(R.translateBufferLineToString(_[1],!0,_[0],M));for(let E=_[1]+1;E<=T[1]-1;E++){const B=R.lines.get(E),U=R.translateBufferLineToString(E,!0);B?.isWrapped?L[L.length-1]+=U:L.push(U)}if(_[1]!==T[1]){const E=R.lines.get(T[1]),B=R.translateBufferLineToString(T[1],!0,0,T[0]);E&&E.isWrapped?L[L.length-1]+=B:L.push(B)}}return L.map((M=>M.replace(C," "))).join(O.isWindows?`\r
|
|
45
45
|
`:`
|
|
46
46
|
`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(_){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),O.isLinux&&_&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(_){const T=this._getMouseBufferCoords(_),R=this._model.finalSelectionStart,L=this._model.finalSelectionEnd;return!!(R&&L&&T)&&this._areCoordsInSelection(T,R,L)}isCellInSelection(_,T){const R=this._model.finalSelectionStart,L=this._model.finalSelectionEnd;return!(!R||!L)&&this._areCoordsInSelection([_,T],R,L)}_areCoordsInSelection(_,T,R){return _[1]>T[1]&&_[1]<R[1]||T[1]===R[1]&&_[1]===T[1]&&_[0]>=T[0]&&_[0]<R[0]||T[1]<R[1]&&_[1]===R[1]&&_[0]<R[0]||T[1]<R[1]&&_[1]===T[1]&&_[0]>=T[0]}_selectWordAtCursor(_,T){const R=this._linkifier.currentLink?.link?.range;if(R)return this._model.selectionStart=[R.start.x-1,R.start.y-1],this._model.selectionStartLength=(0,m.getRangeLength)(R,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const L=this._getMouseBufferCoords(_);return!!L&&(this._selectWordAt(L,T),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(_,T){this._model.clearSelection(),_=Math.max(_,0),T=Math.min(T,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,_],this._model.selectionEnd=[this._bufferService.cols,T],this.refresh(),this._onSelectionChange.fire()}_handleTrim(_){this._model.handleTrim(_)&&this.refresh()}_getMouseBufferCoords(_){const T=this._mouseService.getCoords(_,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(T)return T[0]--,T[1]--,T[1]+=this._bufferService.buffer.ydisp,T}_getMouseEventScrollAmount(_){let T=(0,u.getCoordsRelativeToElement)(this._coreBrowserService.window,_,this._screenElement)[1];const R=this._renderService.dimensions.css.canvas.height;return T>=0&&T<=R?0:(T>R&&(T-=R),T=Math.min(Math.max(T,-50),50),T/=50,T/Math.abs(T)+Math.round(14*T))}shouldForceSelection(_){return O.isMac?_.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:_.shiftKey}handleMouseDown(_){if(this._mouseDownTimeStamp=_.timeStamp,(_.button!==2||!this.hasSelection)&&_.button===0){if(!this._enabled){if(!this.shouldForceSelection(_))return;_.stopPropagation()}_.preventDefault(),this._dragScrollAmount=0,this._enabled&&_.shiftKey?this._handleIncrementalClick(_):_.detail===1?this._handleSingleClick(_):_.detail===2?this._handleDoubleClick(_):_.detail===3&&this._handleTripleClick(_),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(_){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(_))}_handleSingleClick(_){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(_)?3:0,this._model.selectionStart=this._getMouseBufferCoords(_),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const T=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);T&&T.length!==this._model.selectionStart[0]&&T.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(_){this._selectWordAtCursor(_,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(_){const T=this._getMouseBufferCoords(_);T&&(this._activeSelectionMode=2,this._selectLineAt(T[1]))}shouldColumnSelect(_){return _.altKey&&!(O.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(_){if(_.stopImmediatePropagation(),!this._model.selectionStart)return;const T=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(_),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWordAt(this._model.selectionEnd),this._dragScrollAmount=this._getMouseEventScrollAmount(_),this._activeSelectionMode!==3&&(this._dragScrollAmount>0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));const R=this._bufferService.buffer;if(this._model.selectionEnd[1]<R.lines.length){const L=R.lines.get(this._model.selectionEnd[1]);L&&L.hasWidth(this._model.selectionEnd[0])===0&&this._model.selectionEnd[0]<this._bufferService.cols&&this._model.selectionEnd[0]++}T&&T[0]===this._model.selectionEnd[0]&&T[1]===this._model.selectionEnd[1]||this.refresh(!0)}_dragScroll(){if(this._model.selectionEnd&&this._model.selectionStart&&this._dragScrollAmount){this._onRequestScrollLines.fire({amount:this._dragScrollAmount,suppressScrollEvent:!1});const _=this._bufferService.buffer;this._dragScrollAmount>0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(_.ydisp+this._bufferService.rows,_.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=_.ydisp),this.refresh()}}_handleMouseUp(_){const T=_.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&T<500&&_.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){const R=this._mouseService.getCoords(_,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(R&&R[0]!==void 0&&R[1]!==void 0){const L=(0,f.moveToCellSequence)(R[0]-1,R[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(L,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){const _=this._model.finalSelectionStart,T=this._model.finalSelectionEnd,R=!(!_||!T||_[0]===T[0]&&_[1]===T[1]);R?_&&T&&(this._oldSelectionStart&&this._oldSelectionEnd&&_[0]===this._oldSelectionStart[0]&&_[1]===this._oldSelectionStart[1]&&T[0]===this._oldSelectionEnd[0]&&T[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(_,T,R)):this._oldHasSelection&&this._fireOnSelectionChange(_,T,R)}_fireOnSelectionChange(_,T,R){this._oldSelectionStart=_,this._oldSelectionEnd=T,this._oldHasSelection=R,this._onSelectionChange.fire()}_handleBufferActivate(_){this.clearSelection(),this._trimListener.dispose(),this._trimListener=_.activeBuffer.lines.onTrim((T=>this._handleTrim(T)))}_convertViewportColToCharacterIndex(_,T){let R=T;for(let L=0;T>=L;L++){const M=_.loadCell(L,this._workCell).getChars().length;this._workCell.getWidth()===0?R--:M>1&&T!==L&&(R+=M-1)}return R}setSelection(_,T,R){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[_,T],this._model.selectionStartLength=R,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(_){this._isClickInSelection(_)||(this._selectWordAtCursor(_,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(_,T,R=!0,L=!0){if(_[0]>=this._bufferService.cols)return;const M=this._bufferService.buffer,E=M.lines.get(_[1]);if(!E)return;const B=M.translateBufferLineToString(_[1],!1);let U=this._convertViewportColToCharacterIndex(E,_[0]),F=U;const X=_[0]-U;let ae=0,j=0,W=0,D=0;if(B.charAt(U)===" "){for(;U>0&&B.charAt(U-1)===" ";)U--;for(;F<B.length&&B.charAt(F+1)===" ";)F++}else{let fe=_[0],z=_[0];E.getWidth(fe)===0&&(ae++,fe--),E.getWidth(z)===2&&(j++,z++);const re=E.getString(z).length;for(re>1&&(D+=re-1,F+=re-1);fe>0&&U>0&&!this._isCharWordSeparator(E.loadCell(fe-1,this._workCell));){E.loadCell(fe-1,this._workCell);const Z=this._workCell.getChars().length;this._workCell.getWidth()===0?(ae++,fe--):Z>1&&(W+=Z-1,U-=Z-1),U--,fe--}for(;z<E.length&&F+1<B.length&&!this._isCharWordSeparator(E.loadCell(z+1,this._workCell));){E.loadCell(z+1,this._workCell);const Z=this._workCell.getChars().length;this._workCell.getWidth()===2?(j++,z++):Z>1&&(D+=Z-1,F+=Z-1),F++,z++}}F++;let V=U+X-ae+W,se=Math.min(this._bufferService.cols,F-U+ae+j-W-D);if(T||B.slice(U,F).trim()!==""){if(R&&V===0&&E.getCodePoint(0)!==32){const fe=M.lines.get(_[1]-1);if(fe&&E.isWrapped&&fe.getCodePoint(this._bufferService.cols-1)!==32){const z=this._getWordAt([this._bufferService.cols-1,_[1]-1],!1,!0,!1);if(z){const re=this._bufferService.cols-z.start;V-=re,se+=re}}}if(L&&V+se===this._bufferService.cols&&E.getCodePoint(this._bufferService.cols-1)!==32){const fe=M.lines.get(_[1]+1);if(fe?.isWrapped&&fe.getCodePoint(0)!==32){const z=this._getWordAt([0,_[1]+1],!1,!1,!0);z&&(se+=z.length)}}return{start:V,length:se}}}_selectWordAt(_,T){const R=this._getWordAt(_,T);if(R){for(;R.start<0;)R.start+=this._bufferService.cols,_[1]--;this._model.selectionStart=[R.start,_[1]],this._model.selectionStartLength=R.length}}_selectToWordAt(_){const T=this._getWordAt(_,!0);if(T){let R=_[1];for(;T.start<0;)T.start+=this._bufferService.cols,R--;if(!this._model.areSelectionValuesReversed())for(;T.start+T.length>this._bufferService.cols;)T.length-=this._bufferService.cols,R++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?T.start:T.start+T.length,R]}}_isCharWordSeparator(_){return _.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(_.getChars())>=0}_selectLineAt(_){const T=this._bufferService.buffer.getWrappedRangeForLine(_),R={start:{x:0,y:T.first},end:{x:this._bufferService.cols-1,y:T.last}};this._model.selectionStart=[0,T.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,m.getRangeLength)(R,this._bufferService.cols)}};o.SelectionService=P=h([d(3,y.IBufferService),d(4,y.ICoreService),d(5,v.IMouseService),d(6,y.IOptionsService),d(7,v.IRenderService),d(8,v.ICoreBrowserService)],P)},4725:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ILinkProviderService=o.IThemeService=o.ICharacterJoinerService=o.ISelectionService=o.IRenderService=o.IMouseService=o.ICoreBrowserService=o.ICharSizeService=void 0;const h=l(8343);o.ICharSizeService=(0,h.createDecorator)("CharSizeService"),o.ICoreBrowserService=(0,h.createDecorator)("CoreBrowserService"),o.IMouseService=(0,h.createDecorator)("MouseService"),o.IRenderService=(0,h.createDecorator)("RenderService"),o.ISelectionService=(0,h.createDecorator)("SelectionService"),o.ICharacterJoinerService=(0,h.createDecorator)("CharacterJoinerService"),o.IThemeService=(0,h.createDecorator)("ThemeService"),o.ILinkProviderService=(0,h.createDecorator)("LinkProviderService")},6731:function(a,o,l){var h=this&&this.__decorate||function(P,_,T,R){var L,M=arguments.length,E=M<3?_:R===null?R=Object.getOwnPropertyDescriptor(_,T):R;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")E=Reflect.decorate(P,_,T,R);else for(var B=P.length-1;B>=0;B--)(L=P[B])&&(E=(M<3?L(E):M>3?L(_,T,E):L(_,T))||E);return M>3&&E&&Object.defineProperty(_,T,E),E},d=this&&this.__param||function(P,_){return function(T,R){_(T,R,P)}};Object.defineProperty(o,"__esModule",{value:!0}),o.ThemeService=o.DEFAULT_ANSI_COLORS=void 0;const u=l(7239),f=l(8055),p=l(8460),v=l(844),b=l(2585),g=f.css.toColor("#ffffff"),O=f.css.toColor("#000000"),m=f.css.toColor("#ffffff"),x=f.css.toColor("#000000"),y={css:"rgba(255, 255, 255, 0.3)",rgba:4294967117};o.DEFAULT_ANSI_COLORS=Object.freeze((()=>{const P=[f.css.toColor("#2e3436"),f.css.toColor("#cc0000"),f.css.toColor("#4e9a06"),f.css.toColor("#c4a000"),f.css.toColor("#3465a4"),f.css.toColor("#75507b"),f.css.toColor("#06989a"),f.css.toColor("#d3d7cf"),f.css.toColor("#555753"),f.css.toColor("#ef2929"),f.css.toColor("#8ae234"),f.css.toColor("#fce94f"),f.css.toColor("#729fcf"),f.css.toColor("#ad7fa8"),f.css.toColor("#34e2e2"),f.css.toColor("#eeeeec")],_=[0,95,135,175,215,255];for(let T=0;T<216;T++){const R=_[T/36%6|0],L=_[T/6%6|0],M=_[T%6];P.push({css:f.channels.toCss(R,L,M),rgba:f.channels.toRgba(R,L,M)})}for(let T=0;T<24;T++){const R=8+10*T;P.push({css:f.channels.toCss(R,R,R),rgba:f.channels.toRgba(R,R,R)})}return P})());let k=o.ThemeService=class extends v.Disposable{get colors(){return this._colors}constructor(P){super(),this._optionsService=P,this._contrastCache=new u.ColorContrastCache,this._halfContrastCache=new u.ColorContrastCache,this._onChangeColors=this.register(new p.EventEmitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:g,background:O,cursor:m,cursorAccent:x,selectionForeground:void 0,selectionBackgroundTransparent:y,selectionBackgroundOpaque:f.color.blend(O,y),selectionInactiveBackgroundTransparent:y,selectionInactiveBackgroundOpaque:f.color.blend(O,y),ansi:o.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this.register(this._optionsService.onSpecificOptionChange("minimumContrastRatio",(()=>this._contrastCache.clear()))),this.register(this._optionsService.onSpecificOptionChange("theme",(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(P={}){const _=this._colors;if(_.foreground=C(P.foreground,g),_.background=C(P.background,O),_.cursor=C(P.cursor,m),_.cursorAccent=C(P.cursorAccent,x),_.selectionBackgroundTransparent=C(P.selectionBackground,y),_.selectionBackgroundOpaque=f.color.blend(_.background,_.selectionBackgroundTransparent),_.selectionInactiveBackgroundTransparent=C(P.selectionInactiveBackground,_.selectionBackgroundTransparent),_.selectionInactiveBackgroundOpaque=f.color.blend(_.background,_.selectionInactiveBackgroundTransparent),_.selectionForeground=P.selectionForeground?C(P.selectionForeground,f.NULL_COLOR):void 0,_.selectionForeground===f.NULL_COLOR&&(_.selectionForeground=void 0),f.color.isOpaque(_.selectionBackgroundTransparent)&&(_.selectionBackgroundTransparent=f.color.opacity(_.selectionBackgroundTransparent,.3)),f.color.isOpaque(_.selectionInactiveBackgroundTransparent)&&(_.selectionInactiveBackgroundTransparent=f.color.opacity(_.selectionInactiveBackgroundTransparent,.3)),_.ansi=o.DEFAULT_ANSI_COLORS.slice(),_.ansi[0]=C(P.black,o.DEFAULT_ANSI_COLORS[0]),_.ansi[1]=C(P.red,o.DEFAULT_ANSI_COLORS[1]),_.ansi[2]=C(P.green,o.DEFAULT_ANSI_COLORS[2]),_.ansi[3]=C(P.yellow,o.DEFAULT_ANSI_COLORS[3]),_.ansi[4]=C(P.blue,o.DEFAULT_ANSI_COLORS[4]),_.ansi[5]=C(P.magenta,o.DEFAULT_ANSI_COLORS[5]),_.ansi[6]=C(P.cyan,o.DEFAULT_ANSI_COLORS[6]),_.ansi[7]=C(P.white,o.DEFAULT_ANSI_COLORS[7]),_.ansi[8]=C(P.brightBlack,o.DEFAULT_ANSI_COLORS[8]),_.ansi[9]=C(P.brightRed,o.DEFAULT_ANSI_COLORS[9]),_.ansi[10]=C(P.brightGreen,o.DEFAULT_ANSI_COLORS[10]),_.ansi[11]=C(P.brightYellow,o.DEFAULT_ANSI_COLORS[11]),_.ansi[12]=C(P.brightBlue,o.DEFAULT_ANSI_COLORS[12]),_.ansi[13]=C(P.brightMagenta,o.DEFAULT_ANSI_COLORS[13]),_.ansi[14]=C(P.brightCyan,o.DEFAULT_ANSI_COLORS[14]),_.ansi[15]=C(P.brightWhite,o.DEFAULT_ANSI_COLORS[15]),P.extendedAnsi){const T=Math.min(_.ansi.length-16,P.extendedAnsi.length);for(let R=0;R<T;R++)_.ansi[R+16]=C(P.extendedAnsi[R],o.DEFAULT_ANSI_COLORS[R+16])}this._contrastCache.clear(),this._halfContrastCache.clear(),this._updateRestoreColors(),this._onChangeColors.fire(this.colors)}restoreColor(P){this._restoreColor(P),this._onChangeColors.fire(this.colors)}_restoreColor(P){if(P!==void 0)switch(P){case 256:this._colors.foreground=this._restoreColors.foreground;break;case 257:this._colors.background=this._restoreColors.background;break;case 258:this._colors.cursor=this._restoreColors.cursor;break;default:this._colors.ansi[P]=this._restoreColors.ansi[P]}else for(let _=0;_<this._restoreColors.ansi.length;++_)this._colors.ansi[_]=this._restoreColors.ansi[_]}modifyColors(P){P(this._colors),this._onChangeColors.fire(this.colors)}_updateRestoreColors(){this._restoreColors={foreground:this._colors.foreground,background:this._colors.background,cursor:this._colors.cursor,ansi:this._colors.ansi.slice()}}};function C(P,_){if(P!==void 0)try{return f.css.toColor(P)}catch{}return _}o.ThemeService=k=h([d(0,b.IOptionsService)],k)},6349:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CircularList=void 0;const h=l(8460),d=l(844);class u extends d.Disposable{constructor(p){super(),this._maxLength=p,this.onDeleteEmitter=this.register(new h.EventEmitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this.register(new h.EventEmitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this.register(new h.EventEmitter),this.onTrim=this.onTrimEmitter.event,this._array=new Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(p){if(this._maxLength===p)return;const v=new Array(p);for(let b=0;b<Math.min(p,this.length);b++)v[b]=this._array[this._getCyclicIndex(b)];this._array=v,this._maxLength=p,this._startIndex=0}get length(){return this._length}set length(p){if(p>this._length)for(let v=this._length;v<p;v++)this._array[v]=void 0;this._length=p}get(p){return this._array[this._getCyclicIndex(p)]}set(p,v){this._array[this._getCyclicIndex(p)]=v}push(p){this._array[this._getCyclicIndex(this._length)]=p,this._length===this._maxLength?(this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1)):this._length++}recycle(){if(this._length!==this._maxLength)throw new Error("Can only recycle when the buffer is full");return this._startIndex=++this._startIndex%this._maxLength,this.onTrimEmitter.fire(1),this._array[this._getCyclicIndex(this._length-1)]}get isFull(){return this._length===this._maxLength}pop(){return this._array[this._getCyclicIndex(this._length---1)]}splice(p,v,...b){if(v){for(let g=p;g<this._length-v;g++)this._array[this._getCyclicIndex(g)]=this._array[this._getCyclicIndex(g+v)];this._length-=v,this.onDeleteEmitter.fire({index:p,amount:v})}for(let g=this._length-1;g>=p;g--)this._array[this._getCyclicIndex(g+b.length)]=this._array[this._getCyclicIndex(g)];for(let g=0;g<b.length;g++)this._array[this._getCyclicIndex(p+g)]=b[g];if(b.length&&this.onInsertEmitter.fire({index:p,amount:b.length}),this._length+b.length>this._maxLength){const g=this._length+b.length-this._maxLength;this._startIndex+=g,this._length=this._maxLength,this.onTrimEmitter.fire(g)}else this._length+=b.length}trimStart(p){p>this._length&&(p=this._length),this._startIndex+=p,this._length-=p,this.onTrimEmitter.fire(p)}shiftElements(p,v,b){if(!(v<=0)){if(p<0||p>=this._length)throw new Error("start argument out of range");if(p+b<0)throw new Error("Cannot shift elements in list beyond index 0");if(b>0){for(let O=v-1;O>=0;O--)this.set(p+O+b,this.get(p+O));const g=p+v+b-this._length;if(g>0)for(this._length+=g;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let g=0;g<v;g++)this.set(p+g+b,this.get(p+g))}}_getCyclicIndex(p){return(this._startIndex+p)%this._maxLength}}o.CircularList=u},1439:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.clone=void 0,o.clone=function l(h,d=5){if(typeof h!="object")return h;const u=Array.isArray(h)?[]:{};for(const f in h)u[f]=d<=1?h[f]:h[f]&&l(h[f],d-1);return u}},8055:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.contrastRatio=o.toPaddedHex=o.rgba=o.rgb=o.css=o.color=o.channels=o.NULL_COLOR=void 0;let l=0,h=0,d=0,u=0;var f,p,v,b,g;function O(x){const y=x.toString(16);return y.length<2?"0"+y:y}function m(x,y){return x<y?(y+.05)/(x+.05):(x+.05)/(y+.05)}o.NULL_COLOR={css:"#00000000",rgba:0},(function(x){x.toCss=function(y,k,C,P){return P!==void 0?`#${O(y)}${O(k)}${O(C)}${O(P)}`:`#${O(y)}${O(k)}${O(C)}`},x.toRgba=function(y,k,C,P=255){return(y<<24|k<<16|C<<8|P)>>>0},x.toColor=function(y,k,C,P){return{css:x.toCss(y,k,C,P),rgba:x.toRgba(y,k,C,P)}}})(f||(o.channels=f={})),(function(x){function y(k,C){return u=Math.round(255*C),[l,h,d]=g.toChannels(k.rgba),{css:f.toCss(l,h,d,u),rgba:f.toRgba(l,h,d,u)}}x.blend=function(k,C){if(u=(255&C.rgba)/255,u===1)return{css:C.css,rgba:C.rgba};const P=C.rgba>>24&255,_=C.rgba>>16&255,T=C.rgba>>8&255,R=k.rgba>>24&255,L=k.rgba>>16&255,M=k.rgba>>8&255;return l=R+Math.round((P-R)*u),h=L+Math.round((_-L)*u),d=M+Math.round((T-M)*u),{css:f.toCss(l,h,d),rgba:f.toRgba(l,h,d)}},x.isOpaque=function(k){return(255&k.rgba)==255},x.ensureContrastRatio=function(k,C,P){const _=g.ensureContrastRatio(k.rgba,C.rgba,P);if(_)return f.toColor(_>>24&255,_>>16&255,_>>8&255)},x.opaque=function(k){const C=(255|k.rgba)>>>0;return[l,h,d]=g.toChannels(C),{css:f.toCss(l,h,d),rgba:C}},x.opacity=y,x.multiplyOpacity=function(k,C){return u=255&k.rgba,y(k,u*C/255)},x.toColorRGB=function(k){return[k.rgba>>24&255,k.rgba>>16&255,k.rgba>>8&255]}})(p||(o.color=p={})),(function(x){let y,k;try{const C=document.createElement("canvas");C.width=1,C.height=1;const P=C.getContext("2d",{willReadFrequently:!0});P&&(y=P,y.globalCompositeOperation="copy",k=y.createLinearGradient(0,0,1,1))}catch{}x.toColor=function(C){if(C.match(/#[\da-f]{3,8}/i))switch(C.length){case 4:return l=parseInt(C.slice(1,2).repeat(2),16),h=parseInt(C.slice(2,3).repeat(2),16),d=parseInt(C.slice(3,4).repeat(2),16),f.toColor(l,h,d);case 5:return l=parseInt(C.slice(1,2).repeat(2),16),h=parseInt(C.slice(2,3).repeat(2),16),d=parseInt(C.slice(3,4).repeat(2),16),u=parseInt(C.slice(4,5).repeat(2),16),f.toColor(l,h,d,u);case 7:return{css:C,rgba:(parseInt(C.slice(1),16)<<8|255)>>>0};case 9:return{css:C,rgba:parseInt(C.slice(1),16)>>>0}}const P=C.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(P)return l=parseInt(P[1]),h=parseInt(P[2]),d=parseInt(P[3]),u=Math.round(255*(P[5]===void 0?1:parseFloat(P[5]))),f.toColor(l,h,d,u);if(!y||!k)throw new Error("css.toColor: Unsupported css format");if(y.fillStyle=k,y.fillStyle=C,typeof y.fillStyle!="string")throw new Error("css.toColor: Unsupported css format");if(y.fillRect(0,0,1,1),[l,h,d,u]=y.getImageData(0,0,1,1).data,u!==255)throw new Error("css.toColor: Unsupported css format");return{rgba:f.toRgba(l,h,d,u),css:C}}})(v||(o.css=v={})),(function(x){function y(k,C,P){const _=k/255,T=C/255,R=P/255;return .2126*(_<=.03928?_/12.92:Math.pow((_+.055)/1.055,2.4))+.7152*(T<=.03928?T/12.92:Math.pow((T+.055)/1.055,2.4))+.0722*(R<=.03928?R/12.92:Math.pow((R+.055)/1.055,2.4))}x.relativeLuminance=function(k){return y(k>>16&255,k>>8&255,255&k)},x.relativeLuminance2=y})(b||(o.rgb=b={})),(function(x){function y(C,P,_){const T=C>>24&255,R=C>>16&255,L=C>>8&255;let M=P>>24&255,E=P>>16&255,B=P>>8&255,U=m(b.relativeLuminance2(M,E,B),b.relativeLuminance2(T,R,L));for(;U<_&&(M>0||E>0||B>0);)M-=Math.max(0,Math.ceil(.1*M)),E-=Math.max(0,Math.ceil(.1*E)),B-=Math.max(0,Math.ceil(.1*B)),U=m(b.relativeLuminance2(M,E,B),b.relativeLuminance2(T,R,L));return(M<<24|E<<16|B<<8|255)>>>0}function k(C,P,_){const T=C>>24&255,R=C>>16&255,L=C>>8&255;let M=P>>24&255,E=P>>16&255,B=P>>8&255,U=m(b.relativeLuminance2(M,E,B),b.relativeLuminance2(T,R,L));for(;U<_&&(M<255||E<255||B<255);)M=Math.min(255,M+Math.ceil(.1*(255-M))),E=Math.min(255,E+Math.ceil(.1*(255-E))),B=Math.min(255,B+Math.ceil(.1*(255-B))),U=m(b.relativeLuminance2(M,E,B),b.relativeLuminance2(T,R,L));return(M<<24|E<<16|B<<8|255)>>>0}x.blend=function(C,P){if(u=(255&P)/255,u===1)return P;const _=P>>24&255,T=P>>16&255,R=P>>8&255,L=C>>24&255,M=C>>16&255,E=C>>8&255;return l=L+Math.round((_-L)*u),h=M+Math.round((T-M)*u),d=E+Math.round((R-E)*u),f.toRgba(l,h,d)},x.ensureContrastRatio=function(C,P,_){const T=b.relativeLuminance(C>>8),R=b.relativeLuminance(P>>8);if(m(T,R)<_){if(R<T){const E=y(C,P,_),B=m(T,b.relativeLuminance(E>>8));if(B<_){const U=k(C,P,_);return B>m(T,b.relativeLuminance(U>>8))?E:U}return E}const L=k(C,P,_),M=m(T,b.relativeLuminance(L>>8));if(M<_){const E=y(C,P,_);return M>m(T,b.relativeLuminance(E>>8))?L:E}return L}},x.reduceLuminance=y,x.increaseLuminance=k,x.toChannels=function(C){return[C>>24&255,C>>16&255,C>>8&255,255&C]}})(g||(o.rgba=g={})),o.toPaddedHex=O,o.contrastRatio=m},8969:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CoreTerminal=void 0;const h=l(844),d=l(2585),u=l(4348),f=l(7866),p=l(744),v=l(7302),b=l(6975),g=l(8460),O=l(1753),m=l(1480),x=l(7994),y=l(9282),k=l(5435),C=l(5981),P=l(2660);let _=!1;class T extends h.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this.register(new g.EventEmitter),this._onScroll.event((L=>{this._onScrollApi?.fire(L.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(L){for(const M in L)this.optionsService.options[M]=L[M]}constructor(L){super(),this._windowsWrappingHeuristics=this.register(new h.MutableDisposable),this._onBinary=this.register(new g.EventEmitter),this.onBinary=this._onBinary.event,this._onData=this.register(new g.EventEmitter),this.onData=this._onData.event,this._onLineFeed=this.register(new g.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this.register(new g.EventEmitter),this.onResize=this._onResize.event,this._onWriteParsed=this.register(new g.EventEmitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this.register(new g.EventEmitter),this._instantiationService=new u.InstantiationService,this.optionsService=this.register(new v.OptionsService(L)),this._instantiationService.setService(d.IOptionsService,this.optionsService),this._bufferService=this.register(this._instantiationService.createInstance(p.BufferService)),this._instantiationService.setService(d.IBufferService,this._bufferService),this._logService=this.register(this._instantiationService.createInstance(f.LogService)),this._instantiationService.setService(d.ILogService,this._logService),this.coreService=this.register(this._instantiationService.createInstance(b.CoreService)),this._instantiationService.setService(d.ICoreService,this.coreService),this.coreMouseService=this.register(this._instantiationService.createInstance(O.CoreMouseService)),this._instantiationService.setService(d.ICoreMouseService,this.coreMouseService),this.unicodeService=this.register(this._instantiationService.createInstance(m.UnicodeService)),this._instantiationService.setService(d.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(x.CharsetService),this._instantiationService.setService(d.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(P.OscLinkService),this._instantiationService.setService(d.IOscLinkService,this._oscLinkService),this._inputHandler=this.register(new k.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this.register((0,g.forwardEvent)(this._inputHandler.onLineFeed,this._onLineFeed)),this.register(this._inputHandler),this.register((0,g.forwardEvent)(this._bufferService.onResize,this._onResize)),this.register((0,g.forwardEvent)(this.coreService.onData,this._onData)),this.register((0,g.forwardEvent)(this.coreService.onBinary,this._onBinary)),this.register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom()))),this.register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this.register(this.optionsService.onMultipleOptionChange(["windowsMode","windowsPty"],(()=>this._handleWindowsPtyOptionChange()))),this.register(this._bufferService.onScroll((M=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this.register(this._inputHandler.onScroll((M=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp,source:0}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this.register(new C.WriteBuffer(((M,E)=>this._inputHandler.parse(M,E)))),this.register((0,g.forwardEvent)(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(L,M){this._writeBuffer.write(L,M)}writeSync(L,M){this._logService.logLevel<=d.LogLevelEnum.WARN&&!_&&(this._logService.warn("writeSync is unreliable and will be removed soon."),_=!0),this._writeBuffer.writeSync(L,M)}input(L,M=!0){this.coreService.triggerDataEvent(L,M)}resize(L,M){isNaN(L)||isNaN(M)||(L=Math.max(L,p.MINIMUM_COLS),M=Math.max(M,p.MINIMUM_ROWS),this._bufferService.resize(L,M))}scroll(L,M=!1){this._bufferService.scroll(L,M)}scrollLines(L,M,E){this._bufferService.scrollLines(L,M,E)}scrollPages(L){this.scrollLines(L*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(L){const M=L-this._bufferService.buffer.ydisp;M!==0&&this.scrollLines(M)}registerEscHandler(L,M){return this._inputHandler.registerEscHandler(L,M)}registerDcsHandler(L,M){return this._inputHandler.registerDcsHandler(L,M)}registerCsiHandler(L,M){return this._inputHandler.registerCsiHandler(L,M)}registerOscHandler(L,M){return this._inputHandler.registerOscHandler(L,M)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let L=!1;const M=this.optionsService.rawOptions.windowsPty;M&&M.buildNumber!==void 0&&M.buildNumber!==void 0?L=M.backend==="conpty"&&M.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(L=!0),L?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){const L=[];L.push(this.onLineFeed(y.updateWindowsModeWrappedState.bind(null,this._bufferService))),L.push(this.registerCsiHandler({final:"H"},(()=>((0,y.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,h.toDisposable)((()=>{for(const M of L)M.dispose()}))}}}o.CoreTerminal=T},8460:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.runAndSubscribe=o.forwardEvent=o.EventEmitter=void 0,o.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=l=>(this._listeners.push(l),{dispose:()=>{if(!this._disposed){for(let h=0;h<this._listeners.length;h++)if(this._listeners[h]===l)return void this._listeners.splice(h,1)}}})),this._event}fire(l,h){const d=[];for(let u=0;u<this._listeners.length;u++)d.push(this._listeners[u]);for(let u=0;u<d.length;u++)d[u].call(void 0,l,h)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},o.forwardEvent=function(l,h){return l((d=>h.fire(d)))},o.runAndSubscribe=function(l,h){return h(void 0),l((d=>h(d)))}},5435:function(a,o,l){var h=this&&this.__decorate||function(ae,j,W,D){var V,se=arguments.length,fe=se<3?j:D===null?D=Object.getOwnPropertyDescriptor(j,W):D;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")fe=Reflect.decorate(ae,j,W,D);else for(var z=ae.length-1;z>=0;z--)(V=ae[z])&&(fe=(se<3?V(fe):se>3?V(j,W,fe):V(j,W))||fe);return se>3&&fe&&Object.defineProperty(j,W,fe),fe},d=this&&this.__param||function(ae,j){return function(W,D){j(W,D,ae)}};Object.defineProperty(o,"__esModule",{value:!0}),o.InputHandler=o.WindowsOptionsReportType=void 0;const u=l(2584),f=l(7116),p=l(2015),v=l(844),b=l(482),g=l(8437),O=l(8460),m=l(643),x=l(511),y=l(3734),k=l(2585),C=l(1480),P=l(6242),_=l(6351),T=l(5941),R={"(":0,")":1,"*":2,"+":3,"-":1,".":2},L=131072;function M(ae,j){if(ae>24)return j.setWinLines||!1;switch(ae){case 1:return!!j.restoreWin;case 2:return!!j.minimizeWin;case 3:return!!j.setWinPosition;case 4:return!!j.setWinSizePixels;case 5:return!!j.raiseWin;case 6:return!!j.lowerWin;case 7:return!!j.refreshWin;case 8:return!!j.setWinSizeChars;case 9:return!!j.maximizeWin;case 10:return!!j.fullscreenWin;case 11:return!!j.getWinState;case 13:return!!j.getWinPosition;case 14:return!!j.getWinSizePixels;case 15:return!!j.getScreenSizePixels;case 16:return!!j.getCellSizePixels;case 18:return!!j.getWinSizeChars;case 19:return!!j.getScreenSizeChars;case 20:return!!j.getIconTitle;case 21:return!!j.getWinTitle;case 22:return!!j.pushTitle;case 23:return!!j.popTitle;case 24:return!!j.setWinLines}return!1}var E;(function(ae){ae[ae.GET_WIN_SIZE_PIXELS=0]="GET_WIN_SIZE_PIXELS",ae[ae.GET_CELL_SIZE_PIXELS=1]="GET_CELL_SIZE_PIXELS"})(E||(o.WindowsOptionsReportType=E={}));let B=0;class U extends v.Disposable{getAttrData(){return this._curAttrData}constructor(j,W,D,V,se,fe,z,re,Z=new p.EscapeSequenceParser){super(),this._bufferService=j,this._charsetService=W,this._coreService=D,this._logService=V,this._optionsService=se,this._oscLinkService=fe,this._coreMouseService=z,this._unicodeService=re,this._parser=Z,this._parseBuffer=new Uint32Array(4096),this._stringDecoder=new b.StringToUtf32,this._utf8Decoder=new b.Utf8ToUtf32,this._workCell=new x.CellData,this._windowTitle="",this._iconName="",this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=g.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this.register(new O.EventEmitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this.register(new O.EventEmitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this.register(new O.EventEmitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this.register(new O.EventEmitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this.register(new O.EventEmitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this.register(new O.EventEmitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this.register(new O.EventEmitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this.register(new O.EventEmitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this.register(new O.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this.register(new O.EventEmitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this.register(new O.EventEmitter),this.onScroll=this._onScroll.event,this._onTitleChange=this.register(new O.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this.register(new O.EventEmitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this.register(this._parser),this._dirtyRowTracker=new F(this._bufferService),this._activeBuffer=this._bufferService.buffer,this.register(this._bufferService.buffers.onBufferActivate((A=>this._activeBuffer=A.activeBuffer))),this._parser.setCsiHandlerFallback(((A,J)=>{this._logService.debug("Unknown CSI code: ",{identifier:this._parser.identToString(A),params:J.toArray()})})),this._parser.setEscHandlerFallback((A=>{this._logService.debug("Unknown ESC code: ",{identifier:this._parser.identToString(A)})})),this._parser.setExecuteHandlerFallback((A=>{this._logService.debug("Unknown EXECUTE code: ",{code:A})})),this._parser.setOscHandlerFallback(((A,J,Y)=>{this._logService.debug("Unknown OSC code: ",{identifier:A,action:J,data:Y})})),this._parser.setDcsHandlerFallback(((A,J,Y)=>{J==="HOOK"&&(Y=Y.toArray()),this._logService.debug("Unknown DCS code: ",{identifier:this._parser.identToString(A),action:J,payload:Y})})),this._parser.setPrintHandler(((A,J,Y)=>this.print(A,J,Y))),this._parser.registerCsiHandler({final:"@"},(A=>this.insertChars(A))),this._parser.registerCsiHandler({intermediates:" ",final:"@"},(A=>this.scrollLeft(A))),this._parser.registerCsiHandler({final:"A"},(A=>this.cursorUp(A))),this._parser.registerCsiHandler({intermediates:" ",final:"A"},(A=>this.scrollRight(A))),this._parser.registerCsiHandler({final:"B"},(A=>this.cursorDown(A))),this._parser.registerCsiHandler({final:"C"},(A=>this.cursorForward(A))),this._parser.registerCsiHandler({final:"D"},(A=>this.cursorBackward(A))),this._parser.registerCsiHandler({final:"E"},(A=>this.cursorNextLine(A))),this._parser.registerCsiHandler({final:"F"},(A=>this.cursorPrecedingLine(A))),this._parser.registerCsiHandler({final:"G"},(A=>this.cursorCharAbsolute(A))),this._parser.registerCsiHandler({final:"H"},(A=>this.cursorPosition(A))),this._parser.registerCsiHandler({final:"I"},(A=>this.cursorForwardTab(A))),this._parser.registerCsiHandler({final:"J"},(A=>this.eraseInDisplay(A,!1))),this._parser.registerCsiHandler({prefix:"?",final:"J"},(A=>this.eraseInDisplay(A,!0))),this._parser.registerCsiHandler({final:"K"},(A=>this.eraseInLine(A,!1))),this._parser.registerCsiHandler({prefix:"?",final:"K"},(A=>this.eraseInLine(A,!0))),this._parser.registerCsiHandler({final:"L"},(A=>this.insertLines(A))),this._parser.registerCsiHandler({final:"M"},(A=>this.deleteLines(A))),this._parser.registerCsiHandler({final:"P"},(A=>this.deleteChars(A))),this._parser.registerCsiHandler({final:"S"},(A=>this.scrollUp(A))),this._parser.registerCsiHandler({final:"T"},(A=>this.scrollDown(A))),this._parser.registerCsiHandler({final:"X"},(A=>this.eraseChars(A))),this._parser.registerCsiHandler({final:"Z"},(A=>this.cursorBackwardTab(A))),this._parser.registerCsiHandler({final:"`"},(A=>this.charPosAbsolute(A))),this._parser.registerCsiHandler({final:"a"},(A=>this.hPositionRelative(A))),this._parser.registerCsiHandler({final:"b"},(A=>this.repeatPrecedingCharacter(A))),this._parser.registerCsiHandler({final:"c"},(A=>this.sendDeviceAttributesPrimary(A))),this._parser.registerCsiHandler({prefix:">",final:"c"},(A=>this.sendDeviceAttributesSecondary(A))),this._parser.registerCsiHandler({final:"d"},(A=>this.linePosAbsolute(A))),this._parser.registerCsiHandler({final:"e"},(A=>this.vPositionRelative(A))),this._parser.registerCsiHandler({final:"f"},(A=>this.hVPosition(A))),this._parser.registerCsiHandler({final:"g"},(A=>this.tabClear(A))),this._parser.registerCsiHandler({final:"h"},(A=>this.setMode(A))),this._parser.registerCsiHandler({prefix:"?",final:"h"},(A=>this.setModePrivate(A))),this._parser.registerCsiHandler({final:"l"},(A=>this.resetMode(A))),this._parser.registerCsiHandler({prefix:"?",final:"l"},(A=>this.resetModePrivate(A))),this._parser.registerCsiHandler({final:"m"},(A=>this.charAttributes(A))),this._parser.registerCsiHandler({final:"n"},(A=>this.deviceStatus(A))),this._parser.registerCsiHandler({prefix:"?",final:"n"},(A=>this.deviceStatusPrivate(A))),this._parser.registerCsiHandler({intermediates:"!",final:"p"},(A=>this.softReset(A))),this._parser.registerCsiHandler({intermediates:" ",final:"q"},(A=>this.setCursorStyle(A))),this._parser.registerCsiHandler({final:"r"},(A=>this.setScrollRegion(A))),this._parser.registerCsiHandler({final:"s"},(A=>this.saveCursor(A))),this._parser.registerCsiHandler({final:"t"},(A=>this.windowOptions(A))),this._parser.registerCsiHandler({final:"u"},(A=>this.restoreCursor(A))),this._parser.registerCsiHandler({intermediates:"'",final:"}"},(A=>this.insertColumns(A))),this._parser.registerCsiHandler({intermediates:"'",final:"~"},(A=>this.deleteColumns(A))),this._parser.registerCsiHandler({intermediates:'"',final:"q"},(A=>this.selectProtected(A))),this._parser.registerCsiHandler({intermediates:"$",final:"p"},(A=>this.requestMode(A,!0))),this._parser.registerCsiHandler({prefix:"?",intermediates:"$",final:"p"},(A=>this.requestMode(A,!1))),this._parser.setExecuteHandler(u.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(u.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(u.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(u.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(u.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(u.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(u.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(u.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(u.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(u.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(u.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(u.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new P.OscHandler((A=>(this.setTitle(A),this.setIconName(A),!0)))),this._parser.registerOscHandler(1,new P.OscHandler((A=>this.setIconName(A)))),this._parser.registerOscHandler(2,new P.OscHandler((A=>this.setTitle(A)))),this._parser.registerOscHandler(4,new P.OscHandler((A=>this.setOrReportIndexedColor(A)))),this._parser.registerOscHandler(8,new P.OscHandler((A=>this.setHyperlink(A)))),this._parser.registerOscHandler(10,new P.OscHandler((A=>this.setOrReportFgColor(A)))),this._parser.registerOscHandler(11,new P.OscHandler((A=>this.setOrReportBgColor(A)))),this._parser.registerOscHandler(12,new P.OscHandler((A=>this.setOrReportCursorColor(A)))),this._parser.registerOscHandler(104,new P.OscHandler((A=>this.restoreIndexedColor(A)))),this._parser.registerOscHandler(110,new P.OscHandler((A=>this.restoreFgColor(A)))),this._parser.registerOscHandler(111,new P.OscHandler((A=>this.restoreBgColor(A)))),this._parser.registerOscHandler(112,new P.OscHandler((A=>this.restoreCursorColor(A)))),this._parser.registerEscHandler({final:"7"},(()=>this.saveCursor())),this._parser.registerEscHandler({final:"8"},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:"D"},(()=>this.index())),this._parser.registerEscHandler({final:"E"},(()=>this.nextLine())),this._parser.registerEscHandler({final:"H"},(()=>this.tabSet())),this._parser.registerEscHandler({final:"M"},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:"="},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:">"},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:"c"},(()=>this.fullReset())),this._parser.registerEscHandler({final:"n"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"o"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"|"},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:"}"},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:"~"},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:"%",final:"@"},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:"%",final:"G"},(()=>this.selectDefaultCharset()));for(const A in f.CHARSETS)this._parser.registerEscHandler({intermediates:"(",final:A},(()=>this.selectCharset("("+A))),this._parser.registerEscHandler({intermediates:")",final:A},(()=>this.selectCharset(")"+A))),this._parser.registerEscHandler({intermediates:"*",final:A},(()=>this.selectCharset("*"+A))),this._parser.registerEscHandler({intermediates:"+",final:A},(()=>this.selectCharset("+"+A))),this._parser.registerEscHandler({intermediates:"-",final:A},(()=>this.selectCharset("-"+A))),this._parser.registerEscHandler({intermediates:".",final:A},(()=>this.selectCharset("."+A))),this._parser.registerEscHandler({intermediates:"/",final:A},(()=>this.selectCharset("/"+A)));this._parser.registerEscHandler({intermediates:"#",final:"8"},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((A=>(this._logService.error("Parsing error: ",A),A))),this._parser.registerDcsHandler({intermediates:"$",final:"q"},new _.DcsHandler(((A,J)=>this.requestStatusString(A,J))))}_preserveStack(j,W,D,V){this._parseStack.paused=!0,this._parseStack.cursorStartX=j,this._parseStack.cursorStartY=W,this._parseStack.decodedLength=D,this._parseStack.position=V}_logSlowResolvingAsync(j){this._logService.logLevel<=k.LogLevelEnum.WARN&&Promise.race([j,new Promise(((W,D)=>setTimeout((()=>D("#SLOW_TIMEOUT")),5e3)))]).catch((W=>{if(W!=="#SLOW_TIMEOUT")throw W;console.warn("async parser handler taking longer than 5000 ms")}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(j,W){let D,V=this._activeBuffer.x,se=this._activeBuffer.y,fe=0;const z=this._parseStack.paused;if(z){if(D=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,W))return this._logSlowResolvingAsync(D),D;V=this._parseStack.cursorStartX,se=this._parseStack.cursorStartY,this._parseStack.paused=!1,j.length>L&&(fe=this._parseStack.position+L)}if(this._logService.logLevel<=k.LogLevelEnum.DEBUG&&this._logService.debug("parsing data"+(typeof j=="string"?` "${j}"`:` "${Array.prototype.map.call(j,(A=>String.fromCharCode(A))).join("")}"`),typeof j=="string"?j.split("").map((A=>A.charCodeAt(0))):j),this._parseBuffer.length<j.length&&this._parseBuffer.length<L&&(this._parseBuffer=new Uint32Array(Math.min(j.length,L))),z||this._dirtyRowTracker.clearRange(),j.length>L)for(let A=fe;A<j.length;A+=L){const J=A+L<j.length?A+L:j.length,Y=typeof j=="string"?this._stringDecoder.decode(j.substring(A,J),this._parseBuffer):this._utf8Decoder.decode(j.subarray(A,J),this._parseBuffer);if(D=this._parser.parse(this._parseBuffer,Y))return this._preserveStack(V,se,Y,A),this._logSlowResolvingAsync(D),D}else if(!z){const A=typeof j=="string"?this._stringDecoder.decode(j,this._parseBuffer):this._utf8Decoder.decode(j,this._parseBuffer);if(D=this._parser.parse(this._parseBuffer,A))return this._preserveStack(V,se,A,0),this._logSlowResolvingAsync(D),D}this._activeBuffer.x===V&&this._activeBuffer.y===se||this._onCursorMove.fire();const re=this._dirtyRowTracker.end+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp),Z=this._dirtyRowTracker.start+(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp);Z<this._bufferService.rows&&this._onRequestRefreshRows.fire(Math.min(Z,this._bufferService.rows-1),Math.min(re,this._bufferService.rows-1))}print(j,W,D){let V,se;const fe=this._charsetService.charset,z=this._optionsService.rawOptions.screenReaderMode,re=this._bufferService.cols,Z=this._coreService.decPrivateModes.wraparound,A=this._coreService.modes.insertMode,J=this._curAttrData;let Y=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._activeBuffer.x&&D-W>0&&Y.getWidth(this._activeBuffer.x-1)===2&&Y.setCellFromCodepoint(this._activeBuffer.x-1,0,1,J);let oe=this._parser.precedingJoinState;for(let K=W;K<D;++K){if(V=j[K],V<127&&fe){const Ge=fe[String.fromCharCode(V)];Ge&&(V=Ge.charCodeAt(0))}const pe=this._unicodeService.charProperties(V,oe);se=C.UnicodeService.extractWidth(pe);const je=C.UnicodeService.extractShouldJoin(pe),we=je?C.UnicodeService.extractWidth(oe):0;if(oe=pe,z&&this._onA11yChar.fire((0,b.stringFromCodePoint)(V)),this._getCurrentLinkId()&&this._oscLinkService.addLineToLink(this._getCurrentLinkId(),this._activeBuffer.ybase+this._activeBuffer.y),this._activeBuffer.x+se-we>re){if(Z){const Ge=Y;let Qe=this._activeBuffer.x-we;for(this._activeBuffer.x=we,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),Y=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),we>0&&Y instanceof g.BufferLine&&Y.copyCellsFrom(Ge,Qe,0,we,!1);Qe<re;)Ge.setCellFromCodepoint(Qe++,0,1,J)}else if(this._activeBuffer.x=re-1,se===2)continue}if(je&&this._activeBuffer.x){const Ge=Y.getWidth(this._activeBuffer.x-1)?1:2;Y.addCodepointToCell(this._activeBuffer.x-Ge,V,se);for(let Qe=se-we;--Qe>=0;)Y.setCellFromCodepoint(this._activeBuffer.x++,0,0,J)}else if(A&&(Y.insertCells(this._activeBuffer.x,se-we,this._activeBuffer.getNullCell(J)),Y.getWidth(re-1)===2&&Y.setCellFromCodepoint(re-1,m.NULL_CELL_CODE,m.NULL_CELL_WIDTH,J)),Y.setCellFromCodepoint(this._activeBuffer.x++,V,se,J),se>0)for(;--se;)Y.setCellFromCodepoint(this._activeBuffer.x++,0,0,J)}this._parser.precedingJoinState=oe,this._activeBuffer.x<re&&D-W>0&&Y.getWidth(this._activeBuffer.x)===0&&!Y.hasContent(this._activeBuffer.x)&&Y.setCellFromCodepoint(this._activeBuffer.x,0,1,J),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(j,W){return j.final!=="t"||j.prefix||j.intermediates?this._parser.registerCsiHandler(j,W):this._parser.registerCsiHandler(j,(D=>!M(D.params[0],this._optionsService.rawOptions.windowOptions)||W(D)))}registerDcsHandler(j,W){return this._parser.registerDcsHandler(j,new _.DcsHandler(W))}registerEscHandler(j,W){return this._parser.registerEscHandler(j,W)}registerOscHandler(j,W){return this._parser.registerOscHandler(j,new P.OscHandler(W))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;const j=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);j.hasWidth(this._activeBuffer.x)&&!j.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;const j=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-j),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(j=this._bufferService.cols-1){this._activeBuffer.x=Math.min(j,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(j,W){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=j,this._activeBuffer.y=this._activeBuffer.scrollTop+W):(this._activeBuffer.x=j,this._activeBuffer.y=W),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(j,W){this._restrictCursor(),this._setCursor(this._activeBuffer.x+j,this._activeBuffer.y+W)}cursorUp(j){const W=this._activeBuffer.y-this._activeBuffer.scrollTop;return W>=0?this._moveCursor(0,-Math.min(W,j.params[0]||1)):this._moveCursor(0,-(j.params[0]||1)),!0}cursorDown(j){const W=this._activeBuffer.scrollBottom-this._activeBuffer.y;return W>=0?this._moveCursor(0,Math.min(W,j.params[0]||1)):this._moveCursor(0,j.params[0]||1),!0}cursorForward(j){return this._moveCursor(j.params[0]||1,0),!0}cursorBackward(j){return this._moveCursor(-(j.params[0]||1),0),!0}cursorNextLine(j){return this.cursorDown(j),this._activeBuffer.x=0,!0}cursorPrecedingLine(j){return this.cursorUp(j),this._activeBuffer.x=0,!0}cursorCharAbsolute(j){return this._setCursor((j.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(j){return this._setCursor(j.length>=2?(j.params[1]||1)-1:0,(j.params[0]||1)-1),!0}charPosAbsolute(j){return this._setCursor((j.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(j){return this._moveCursor(j.params[0]||1,0),!0}linePosAbsolute(j){return this._setCursor(this._activeBuffer.x,(j.params[0]||1)-1),!0}vPositionRelative(j){return this._moveCursor(0,j.params[0]||1),!0}hVPosition(j){return this.cursorPosition(j),!0}tabClear(j){const W=j.params[0];return W===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:W===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(j){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let W=j.params[0]||1;for(;W--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(j){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let W=j.params[0]||1;for(;W--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(j){const W=j.params[0];return W===1&&(this._curAttrData.bg|=536870912),W!==2&&W!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(j,W,D,V=!1,se=!1){const fe=this._activeBuffer.lines.get(this._activeBuffer.ybase+j);fe.replaceCells(W,D,this._activeBuffer.getNullCell(this._eraseAttrData()),se),V&&(fe.isWrapped=!1)}_resetBufferLine(j,W=!1){const D=this._activeBuffer.lines.get(this._activeBuffer.ybase+j);D&&(D.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),W),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+j),D.isWrapped=!1)}eraseInDisplay(j,W=!1){let D;switch(this._restrictCursor(this._bufferService.cols),j.params[0]){case 0:for(D=this._activeBuffer.y,this._dirtyRowTracker.markDirty(D),this._eraseInBufferLine(D++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,W);D<this._bufferService.rows;D++)this._resetBufferLine(D,W);this._dirtyRowTracker.markDirty(D);break;case 1:for(D=this._activeBuffer.y,this._dirtyRowTracker.markDirty(D),this._eraseInBufferLine(D,0,this._activeBuffer.x+1,!0,W),this._activeBuffer.x+1>=this._bufferService.cols&&(this._activeBuffer.lines.get(D+1).isWrapped=!1);D--;)this._resetBufferLine(D,W);this._dirtyRowTracker.markDirty(0);break;case 2:for(D=this._bufferService.rows,this._dirtyRowTracker.markDirty(D-1);D--;)this._resetBufferLine(D,W);this._dirtyRowTracker.markDirty(0);break;case 3:const V=this._activeBuffer.lines.length-this._bufferService.rows;V>0&&(this._activeBuffer.lines.trimStart(V),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-V,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-V,0),this._onScroll.fire(0))}return!0}eraseInLine(j,W=!1){switch(this._restrictCursor(this._bufferService.cols),j.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,W);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,W);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,W)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(j){this._restrictCursor();let W=j.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const D=this._activeBuffer.ybase+this._activeBuffer.y,V=this._bufferService.rows-1-this._activeBuffer.scrollBottom,se=this._bufferService.rows-1+this._activeBuffer.ybase-V+1;for(;W--;)this._activeBuffer.lines.splice(se-1,1),this._activeBuffer.lines.splice(D,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}deleteLines(j){this._restrictCursor();let W=j.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const D=this._activeBuffer.ybase+this._activeBuffer.y;let V;for(V=this._bufferService.rows-1-this._activeBuffer.scrollBottom,V=this._bufferService.rows-1+this._activeBuffer.ybase-V;W--;)this._activeBuffer.lines.splice(D,1),this._activeBuffer.lines.splice(V,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.y,this._activeBuffer.scrollBottom),this._activeBuffer.x=0,!0}insertChars(j){this._restrictCursor();const W=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return W&&(W.insertCells(this._activeBuffer.x,j.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}deleteChars(j){this._restrictCursor();const W=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return W&&(W.deleteCells(this._activeBuffer.x,j.params[0]||1,this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}scrollUp(j){let W=j.params[0]||1;for(;W--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,0,this._activeBuffer.getBlankLine(this._eraseAttrData()));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollDown(j){let W=j.params[0]||1;for(;W--;)this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollBottom,1),this._activeBuffer.lines.splice(this._activeBuffer.ybase+this._activeBuffer.scrollTop,0,this._activeBuffer.getBlankLine(g.DEFAULT_ATTR_DATA));return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollLeft(j){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const W=j.params[0]||1;for(let D=this._activeBuffer.scrollTop;D<=this._activeBuffer.scrollBottom;++D){const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+D);V.deleteCells(0,W,this._activeBuffer.getNullCell(this._eraseAttrData())),V.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}scrollRight(j){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const W=j.params[0]||1;for(let D=this._activeBuffer.scrollTop;D<=this._activeBuffer.scrollBottom;++D){const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+D);V.insertCells(0,W,this._activeBuffer.getNullCell(this._eraseAttrData())),V.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}insertColumns(j){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const W=j.params[0]||1;for(let D=this._activeBuffer.scrollTop;D<=this._activeBuffer.scrollBottom;++D){const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+D);V.insertCells(this._activeBuffer.x,W,this._activeBuffer.getNullCell(this._eraseAttrData())),V.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}deleteColumns(j){if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.y<this._activeBuffer.scrollTop)return!0;const W=j.params[0]||1;for(let D=this._activeBuffer.scrollTop;D<=this._activeBuffer.scrollBottom;++D){const V=this._activeBuffer.lines.get(this._activeBuffer.ybase+D);V.deleteCells(this._activeBuffer.x,W,this._activeBuffer.getNullCell(this._eraseAttrData())),V.isWrapped=!1}return this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom),!0}eraseChars(j){this._restrictCursor();const W=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);return W&&(W.replaceCells(this._activeBuffer.x,this._activeBuffer.x+(j.params[0]||1),this._activeBuffer.getNullCell(this._eraseAttrData())),this._dirtyRowTracker.markDirty(this._activeBuffer.y)),!0}repeatPrecedingCharacter(j){const W=this._parser.precedingJoinState;if(!W)return!0;const D=j.params[0]||1,V=C.UnicodeService.extractWidth(W),se=this._activeBuffer.x-V,fe=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).getString(se),z=new Uint32Array(fe.length*D);let re=0;for(let A=0;A<fe.length;){const J=fe.codePointAt(A)||0;z[re++]=J,A+=J>65535?2:1}let Z=re;for(let A=1;A<D;++A)z.copyWithin(Z,0,re),Z+=re;return this.print(z,0,Z),!0}sendDeviceAttributesPrimary(j){return j.params[0]>0||(this._is("xterm")||this._is("rxvt-unicode")||this._is("screen")?this._coreService.triggerDataEvent(u.C0.ESC+"[?1;2c"):this._is("linux")&&this._coreService.triggerDataEvent(u.C0.ESC+"[?6c")),!0}sendDeviceAttributesSecondary(j){return j.params[0]>0||(this._is("xterm")?this._coreService.triggerDataEvent(u.C0.ESC+"[>0;276;0c"):this._is("rxvt-unicode")?this._coreService.triggerDataEvent(u.C0.ESC+"[>85;95;0c"):this._is("linux")?this._coreService.triggerDataEvent(j.params[0]+"c"):this._is("screen")&&this._coreService.triggerDataEvent(u.C0.ESC+"[>83;40003;0c")),!0}_is(j){return(this._optionsService.rawOptions.termName+"").indexOf(j)===0}setMode(j){for(let W=0;W<j.length;W++)switch(j.params[W]){case 4:this._coreService.modes.insertMode=!0;break;case 20:this._optionsService.options.convertEol=!0}return!0}setModePrivate(j){for(let W=0;W<j.length;W++)switch(j.params[W]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!0;break;case 2:this._charsetService.setgCharset(0,f.DEFAULT_CHARSET),this._charsetService.setgCharset(1,f.DEFAULT_CHARSET),this._charsetService.setgCharset(2,f.DEFAULT_CHARSET),this._charsetService.setgCharset(3,f.DEFAULT_CHARSET);break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(132,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!0,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!0;break;case 12:this._optionsService.options.cursorBlink=!0;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!0;break;case 66:this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire();break;case 9:this._coreMouseService.activeProtocol="X10";break;case 1e3:this._coreMouseService.activeProtocol="VT200";break;case 1002:this._coreMouseService.activeProtocol="DRAG";break;case 1003:this._coreMouseService.activeProtocol="ANY";break;case 1004:this._coreService.decPrivateModes.sendFocus=!0,this._onRequestSendFocus.fire();break;case 1005:this._logService.debug("DECSET 1005 not supported (see #2507)");break;case 1006:this._coreMouseService.activeEncoding="SGR";break;case 1015:this._logService.debug("DECSET 1015 not supported (see #2507)");break;case 1016:this._coreMouseService.activeEncoding="SGR_PIXELS";break;case 25:this._coreService.isCursorHidden=!1;break;case 1048:this.saveCursor();break;case 1049:this.saveCursor();case 47:case 1047:this._bufferService.buffers.activateAltBuffer(this._eraseAttrData()),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!0}return!0}resetMode(j){for(let W=0;W<j.length;W++)switch(j.params[W]){case 4:this._coreService.modes.insertMode=!1;break;case 20:this._optionsService.options.convertEol=!1}return!0}resetModePrivate(j){for(let W=0;W<j.length;W++)switch(j.params[W]){case 1:this._coreService.decPrivateModes.applicationCursorKeys=!1;break;case 3:this._optionsService.rawOptions.windowOptions.setWinLines&&(this._bufferService.resize(80,this._bufferService.rows),this._onRequestReset.fire());break;case 6:this._coreService.decPrivateModes.origin=!1,this._setCursor(0,0);break;case 7:this._coreService.decPrivateModes.wraparound=!1;break;case 12:this._optionsService.options.cursorBlink=!1;break;case 45:this._coreService.decPrivateModes.reverseWraparound=!1;break;case 66:this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire();break;case 9:case 1e3:case 1002:case 1003:this._coreMouseService.activeProtocol="NONE";break;case 1004:this._coreService.decPrivateModes.sendFocus=!1;break;case 1005:this._logService.debug("DECRST 1005 not supported (see #2507)");break;case 1006:case 1016:this._coreMouseService.activeEncoding="DEFAULT";break;case 1015:this._logService.debug("DECRST 1015 not supported (see #2507)");break;case 25:this._coreService.isCursorHidden=!0;break;case 1048:this.restoreCursor();break;case 1049:case 47:case 1047:this._bufferService.buffers.activateNormalBuffer(),j.params[W]===1049&&this.restoreCursor(),this._coreService.isCursorInitialized=!0,this._onRequestRefreshRows.fire(0,this._bufferService.rows-1),this._onRequestSyncScrollBar.fire();break;case 2004:this._coreService.decPrivateModes.bracketedPasteMode=!1}return!0}requestMode(j,W){const D=this._coreService.decPrivateModes,{activeProtocol:V,activeEncoding:se}=this._coreMouseService,fe=this._coreService,{buffers:z,cols:re}=this._bufferService,{active:Z,alt:A}=z,J=this._optionsService.rawOptions,Y=je=>je?1:2,oe=j.params[0];return K=oe,pe=W?oe===2?4:oe===4?Y(fe.modes.insertMode):oe===12?3:oe===20?Y(J.convertEol):0:oe===1?Y(D.applicationCursorKeys):oe===3?J.windowOptions.setWinLines?re===80?2:re===132?1:0:0:oe===6?Y(D.origin):oe===7?Y(D.wraparound):oe===8?3:oe===9?Y(V==="X10"):oe===12?Y(J.cursorBlink):oe===25?Y(!fe.isCursorHidden):oe===45?Y(D.reverseWraparound):oe===66?Y(D.applicationKeypad):oe===67?4:oe===1e3?Y(V==="VT200"):oe===1002?Y(V==="DRAG"):oe===1003?Y(V==="ANY"):oe===1004?Y(D.sendFocus):oe===1005?4:oe===1006?Y(se==="SGR"):oe===1015?4:oe===1016?Y(se==="SGR_PIXELS"):oe===1048?1:oe===47||oe===1047||oe===1049?Y(Z===A):oe===2004?Y(D.bracketedPasteMode):0,fe.triggerDataEvent(`${u.C0.ESC}[${W?"":"?"}${K};${pe}$y`),!0;var K,pe}_updateAttrColor(j,W,D,V,se){return W===2?(j|=50331648,j&=-16777216,j|=y.AttributeData.fromColorRGB([D,V,se])):W===5&&(j&=-50331904,j|=33554432|255&D),j}_extractColor(j,W,D){const V=[0,0,-1,0,0,0];let se=0,fe=0;do{if(V[fe+se]=j.params[W+fe],j.hasSubParams(W+fe)){const z=j.getSubParams(W+fe);let re=0;do V[1]===5&&(se=1),V[fe+re+1+se]=z[re];while(++re<z.length&&re+fe+1+se<V.length);break}if(V[1]===5&&fe+se>=2||V[1]===2&&fe+se>=5)break;V[1]&&(se=1)}while(++fe+W<j.length&&fe+se<V.length);for(let z=2;z<V.length;++z)V[z]===-1&&(V[z]=0);switch(V[0]){case 38:D.fg=this._updateAttrColor(D.fg,V[1],V[3],V[4],V[5]);break;case 48:D.bg=this._updateAttrColor(D.bg,V[1],V[3],V[4],V[5]);break;case 58:D.extended=D.extended.clone(),D.extended.underlineColor=this._updateAttrColor(D.extended.underlineColor,V[1],V[3],V[4],V[5])}return fe}_processUnderline(j,W){W.extended=W.extended.clone(),(!~j||j>5)&&(j=1),W.extended.underlineStyle=j,W.fg|=268435456,j===0&&(W.fg&=-268435457),W.updateExtended()}_processSGR0(j){j.fg=g.DEFAULT_ATTR_DATA.fg,j.bg=g.DEFAULT_ATTR_DATA.bg,j.extended=j.extended.clone(),j.extended.underlineStyle=0,j.extended.underlineColor&=-67108864,j.updateExtended()}charAttributes(j){if(j.length===1&&j.params[0]===0)return this._processSGR0(this._curAttrData),!0;const W=j.length;let D;const V=this._curAttrData;for(let se=0;se<W;se++)D=j.params[se],D>=30&&D<=37?(V.fg&=-50331904,V.fg|=16777216|D-30):D>=40&&D<=47?(V.bg&=-50331904,V.bg|=16777216|D-40):D>=90&&D<=97?(V.fg&=-50331904,V.fg|=16777224|D-90):D>=100&&D<=107?(V.bg&=-50331904,V.bg|=16777224|D-100):D===0?this._processSGR0(V):D===1?V.fg|=134217728:D===3?V.bg|=67108864:D===4?(V.fg|=268435456,this._processUnderline(j.hasSubParams(se)?j.getSubParams(se)[0]:1,V)):D===5?V.fg|=536870912:D===7?V.fg|=67108864:D===8?V.fg|=1073741824:D===9?V.fg|=2147483648:D===2?V.bg|=134217728:D===21?this._processUnderline(2,V):D===22?(V.fg&=-134217729,V.bg&=-134217729):D===23?V.bg&=-67108865:D===24?(V.fg&=-268435457,this._processUnderline(0,V)):D===25?V.fg&=-536870913:D===27?V.fg&=-67108865:D===28?V.fg&=-1073741825:D===29?V.fg&=2147483647:D===39?(V.fg&=-67108864,V.fg|=16777215&g.DEFAULT_ATTR_DATA.fg):D===49?(V.bg&=-67108864,V.bg|=16777215&g.DEFAULT_ATTR_DATA.bg):D===38||D===48||D===58?se+=this._extractColor(j,se,V):D===53?V.bg|=1073741824:D===55?V.bg&=-1073741825:D===59?(V.extended=V.extended.clone(),V.extended.underlineColor=-1,V.updateExtended()):D===100?(V.fg&=-67108864,V.fg|=16777215&g.DEFAULT_ATTR_DATA.fg,V.bg&=-67108864,V.bg|=16777215&g.DEFAULT_ATTR_DATA.bg):this._logService.debug("Unknown SGR attribute: %d.",D);return!0}deviceStatus(j){switch(j.params[0]){case 5:this._coreService.triggerDataEvent(`${u.C0.ESC}[0n`);break;case 6:const W=this._activeBuffer.y+1,D=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${u.C0.ESC}[${W};${D}R`)}return!0}deviceStatusPrivate(j){if(j.params[0]===6){const W=this._activeBuffer.y+1,D=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${u.C0.ESC}[?${W};${D}R`)}return!0}softReset(j){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(j){const W=j.params[0]||1;switch(W){case 1:case 2:this._optionsService.options.cursorStyle="block";break;case 3:case 4:this._optionsService.options.cursorStyle="underline";break;case 5:case 6:this._optionsService.options.cursorStyle="bar"}const D=W%2==1;return this._optionsService.options.cursorBlink=D,!0}setScrollRegion(j){const W=j.params[0]||1;let D;return(j.length<2||(D=j.params[1])>this._bufferService.rows||D===0)&&(D=this._bufferService.rows),D>W&&(this._activeBuffer.scrollTop=W-1,this._activeBuffer.scrollBottom=D-1,this._setCursor(0,0)),!0}windowOptions(j){if(!M(j.params[0],this._optionsService.rawOptions.windowOptions))return!0;const W=j.length>1?j.params[1]:0;switch(j.params[0]){case 14:W!==2&&this._onRequestWindowsOptionsReport.fire(E.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(E.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${u.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:W!==0&&W!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),W!==0&&W!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:W!==0&&W!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),W!==0&&W!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(j){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(j){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(j){return this._windowTitle=j,this._onTitleChange.fire(j),!0}setIconName(j){return this._iconName=j,!0}setOrReportIndexedColor(j){const W=[],D=j.split(";");for(;D.length>1;){const V=D.shift(),se=D.shift();if(/^\d+$/.exec(V)){const fe=parseInt(V);if(X(fe))if(se==="?")W.push({type:0,index:fe});else{const z=(0,T.parseColor)(se);z&&W.push({type:1,index:fe,color:z})}}}return W.length&&this._onColor.fire(W),!0}setHyperlink(j){const W=j.split(";");return!(W.length<2)&&(W[1]?this._createHyperlink(W[0],W[1]):!W[0]&&this._finishHyperlink())}_createHyperlink(j,W){this._getCurrentLinkId()&&this._finishHyperlink();const D=j.split(":");let V;const se=D.findIndex((fe=>fe.startsWith("id=")));return se!==-1&&(V=D[se].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:V,uri:W}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(j,W){const D=j.split(";");for(let V=0;V<D.length&&!(W>=this._specialColors.length);++V,++W)if(D[V]==="?")this._onColor.fire([{type:0,index:this._specialColors[W]}]);else{const se=(0,T.parseColor)(D[V]);se&&this._onColor.fire([{type:1,index:this._specialColors[W],color:se}])}return!0}setOrReportFgColor(j){return this._setOrReportSpecialColor(j,0)}setOrReportBgColor(j){return this._setOrReportSpecialColor(j,1)}setOrReportCursorColor(j){return this._setOrReportSpecialColor(j,2)}restoreIndexedColor(j){if(!j)return this._onColor.fire([{type:2}]),!0;const W=[],D=j.split(";");for(let V=0;V<D.length;++V)if(/^\d+$/.exec(D[V])){const se=parseInt(D[V]);X(se)&&W.push({type:2,index:se})}return W.length&&this._onColor.fire(W),!0}restoreFgColor(j){return this._onColor.fire([{type:2,index:256}]),!0}restoreBgColor(j){return this._onColor.fire([{type:2,index:257}]),!0}restoreCursorColor(j){return this._onColor.fire([{type:2,index:258}]),!0}nextLine(){return this._activeBuffer.x=0,this.index(),!0}keypadApplicationMode(){return this._logService.debug("Serial port requested application keypad."),this._coreService.decPrivateModes.applicationKeypad=!0,this._onRequestSyncScrollBar.fire(),!0}keypadNumericMode(){return this._logService.debug("Switching back to normal keypad."),this._coreService.decPrivateModes.applicationKeypad=!1,this._onRequestSyncScrollBar.fire(),!0}selectDefaultCharset(){return this._charsetService.setgLevel(0),this._charsetService.setgCharset(0,f.DEFAULT_CHARSET),!0}selectCharset(j){return j.length!==2?(this.selectDefaultCharset(),!0):(j[0]==="/"||this._charsetService.setgCharset(R[j[0]],f.CHARSETS[j[1]]||f.DEFAULT_CHARSET),!0)}index(){return this._restrictCursor(),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){const j=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,j,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=g.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=g.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(j){return this._charsetService.setgLevel(j),!0}screenAlignmentPattern(){const j=new x.CellData;j.content=4194373,j.fg=this._curAttrData.fg,j.bg=this._curAttrData.bg,this._setCursor(0,0);for(let W=0;W<this._bufferService.rows;++W){const D=this._activeBuffer.ybase+this._activeBuffer.y+W,V=this._activeBuffer.lines.get(D);V&&(V.fill(j),V.isWrapped=!1)}return this._dirtyRowTracker.markAllDirty(),this._setCursor(0,0),!0}requestStatusString(j,W){const D=this._bufferService.buffer,V=this._optionsService.rawOptions;return(se=>(this._coreService.triggerDataEvent(`${u.C0.ESC}${se}${u.C0.ESC}\\`),!0))(j==='"q'?`P1$r${this._curAttrData.isProtected()?1:0}"q`:j==='"p'?'P1$r61;1"p':j==="r"?`P1$r${D.scrollTop+1};${D.scrollBottom+1}r`:j==="m"?"P1$r0m":j===" q"?`P1$r${{block:2,underline:4,bar:6}[V.cursorStyle]-(V.cursorBlink?1:0)} q`:"P0$r")}markRangeDirty(j,W){this._dirtyRowTracker.markRangeDirty(j,W)}}o.InputHandler=U;let F=class{constructor(ae){this._bufferService=ae,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(ae){ae<this.start?this.start=ae:ae>this.end&&(this.end=ae)}markRangeDirty(ae,j){ae>j&&(B=ae,ae=j,j=B),ae<this.start&&(this.start=ae),j>this.end&&(this.end=j)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function X(ae){return 0<=ae&&ae<256}F=h([d(0,k.IBufferService)],F)},844:(a,o)=>{function l(h){for(const d of h)d.dispose();h.length=0}Object.defineProperty(o,"__esModule",{value:!0}),o.getDisposeArrayDisposable=o.disposeArray=o.toDisposable=o.MutableDisposable=o.Disposable=void 0,o.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const h of this._disposables)h.dispose();this._disposables.length=0}register(h){return this._disposables.push(h),h}unregister(h){const d=this._disposables.indexOf(h);d!==-1&&this._disposables.splice(d,1)}},o.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(h){this._isDisposed||h===this._value||(this._value?.dispose(),this._value=h)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},o.toDisposable=function(h){return{dispose:h}},o.disposeArray=l,o.getDisposeArrayDisposable=function(h){return{dispose:()=>l(h)}}},1505:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.FourKeyMap=o.TwoKeyMap=void 0;class l{constructor(){this._data={}}set(d,u,f){this._data[d]||(this._data[d]={}),this._data[d][u]=f}get(d,u){return this._data[d]?this._data[d][u]:void 0}clear(){this._data={}}}o.TwoKeyMap=l,o.FourKeyMap=class{constructor(){this._data=new l}set(h,d,u,f,p){this._data.get(h,d)||this._data.set(h,d,new l),this._data.get(h,d).set(u,f,p)}get(h,d,u,f){return this._data.get(h,d)?.get(u,f)}clear(){this._data.clear()}}},6114:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.isChromeOS=o.isLinux=o.isWindows=o.isIphone=o.isIpad=o.isMac=o.getSafariVersion=o.isSafari=o.isLegacyEdge=o.isFirefox=o.isNode=void 0,o.isNode=typeof process<"u"&&"title"in process;const l=o.isNode?"node":navigator.userAgent,h=o.isNode?"node":navigator.platform;o.isFirefox=l.includes("Firefox"),o.isLegacyEdge=l.includes("Edge"),o.isSafari=/^((?!chrome|android).)*safari/i.test(l),o.getSafariVersion=function(){if(!o.isSafari)return 0;const d=l.match(/Version\/(\d+)/);return d===null||d.length<2?0:parseInt(d[1])},o.isMac=["Macintosh","MacIntel","MacPPC","Mac68K"].includes(h),o.isIpad=h==="iPad",o.isIphone=h==="iPhone",o.isWindows=["Windows","Win16","Win32","WinCE"].includes(h),o.isLinux=h.indexOf("Linux")>=0,o.isChromeOS=/\bCrOS\b/.test(l)},6106:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.SortedList=void 0;let l=0;o.SortedList=class{constructor(h){this._getKey=h,this._array=[]}clear(){this._array.length=0}insert(h){this._array.length!==0?(l=this._search(this._getKey(h)),this._array.splice(l,0,h)):this._array.push(h)}delete(h){if(this._array.length===0)return!1;const d=this._getKey(h);if(d===void 0||(l=this._search(d),l===-1)||this._getKey(this._array[l])!==d)return!1;do if(this._array[l]===h)return this._array.splice(l,1),!0;while(++l<this._array.length&&this._getKey(this._array[l])===d);return!1}*getKeyIterator(h){if(this._array.length!==0&&(l=this._search(h),!(l<0||l>=this._array.length)&&this._getKey(this._array[l])===h))do yield this._array[l];while(++l<this._array.length&&this._getKey(this._array[l])===h)}forEachByKey(h,d){if(this._array.length!==0&&(l=this._search(h),!(l<0||l>=this._array.length)&&this._getKey(this._array[l])===h))do d(this._array[l]);while(++l<this._array.length&&this._getKey(this._array[l])===h)}values(){return[...this._array].values()}_search(h){let d=0,u=this._array.length-1;for(;u>=d;){let f=d+u>>1;const p=this._getKey(this._array[f]);if(p>h)u=f-1;else{if(!(p<h)){for(;f>0&&this._getKey(this._array[f-1])===h;)f--;return f}d=f+1}}return d}}},7226:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DebouncedIdleTask=o.IdleTaskQueue=o.PriorityTaskQueue=void 0;const h=l(6114);class d{constructor(){this._tasks=[],this._i=0}enqueue(p){this._tasks.push(p),this._start()}flush(){for(;this._i<this._tasks.length;)this._tasks[this._i]()||this._i++;this.clear()}clear(){this._idleCallback&&(this._cancelCallback(this._idleCallback),this._idleCallback=void 0),this._i=0,this._tasks.length=0}_start(){this._idleCallback||(this._idleCallback=this._requestCallback(this._process.bind(this)))}_process(p){this._idleCallback=void 0;let v=0,b=0,g=p.timeRemaining(),O=0;for(;this._i<this._tasks.length;){if(v=Date.now(),this._tasks[this._i]()||this._i++,v=Math.max(1,Date.now()-v),b=Math.max(v,b),O=p.timeRemaining(),1.5*b>O)return g-v<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(g-v))}ms`),void this._start();g=O}this.clear()}}class u extends d{_requestCallback(p){return setTimeout((()=>p(this._createDeadline(16))))}_cancelCallback(p){clearTimeout(p)}_createDeadline(p){const v=Date.now()+p;return{timeRemaining:()=>Math.max(0,v-Date.now())}}}o.PriorityTaskQueue=u,o.IdleTaskQueue=!h.isNode&&"requestIdleCallback"in window?class extends d{_requestCallback(f){return requestIdleCallback(f)}_cancelCallback(f){cancelIdleCallback(f)}}:u,o.DebouncedIdleTask=class{constructor(){this._queue=new o.IdleTaskQueue}set(f){this._queue.clear(),this._queue.enqueue(f)}flush(){this._queue.flush()}}},9282:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.updateWindowsModeWrappedState=void 0;const h=l(643);o.updateWindowsModeWrappedState=function(d){const u=d.buffer.lines.get(d.buffer.ybase+d.buffer.y-1),f=u?.get(d.cols-1),p=d.buffer.lines.get(d.buffer.ybase+d.buffer.y);p&&f&&(p.isWrapped=f[h.CHAR_DATA_CODE_INDEX]!==h.NULL_CELL_CODE&&f[h.CHAR_DATA_CODE_INDEX]!==h.WHITESPACE_CELL_CODE)}},3734:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ExtendedAttrs=o.AttributeData=void 0;class l{constructor(){this.fg=0,this.bg=0,this.extended=new h}static toColorRGB(u){return[u>>>16&255,u>>>8&255,255&u]}static fromColorRGB(u){return(255&u[0])<<16|(255&u[1])<<8|255&u[2]}clone(){const u=new l;return u.fg=this.fg,u.bg=this.bg,u.extended=this.extended.clone(),u}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return(50331648&this.fg)==50331648}isBgRGB(){return(50331648&this.bg)==50331648}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return(50331648&this.fg)==0}isBgDefault(){return(50331648&this.bg)==0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==50331648:this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==0:this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}o.AttributeData=l;class h{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(u){this._ext=u}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(u){this._ext&=-469762049,this._ext|=u<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(u){this._ext&=-67108864,this._ext|=67108863&u}get urlId(){return this._urlId}set urlId(u){this._urlId=u}get underlineVariantOffset(){const u=(3758096384&this._ext)>>29;return u<0?4294967288^u:u}set underlineVariantOffset(u){this._ext&=536870911,this._ext|=u<<29&3758096384}constructor(u=0,f=0){this._ext=0,this._urlId=0,this._ext=u,this._urlId=f}clone(){return new h(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}o.ExtendedAttrs=h},9092:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Buffer=o.MAX_BUFFER_SIZE=void 0;const h=l(6349),d=l(7226),u=l(3734),f=l(8437),p=l(4634),v=l(511),b=l(643),g=l(4863),O=l(7116);o.MAX_BUFFER_SIZE=4294967295,o.Buffer=class{constructor(m,x,y){this._hasScrollback=m,this._optionsService=x,this._bufferService=y,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=f.DEFAULT_ATTR_DATA.clone(),this.savedCharset=O.DEFAULT_CHARSET,this.markers=[],this._nullCell=v.CellData.fromCharData([0,b.NULL_CELL_CHAR,b.NULL_CELL_WIDTH,b.NULL_CELL_CODE]),this._whitespaceCell=v.CellData.fromCharData([0,b.WHITESPACE_CELL_CHAR,b.WHITESPACE_CELL_WIDTH,b.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new d.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new h.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(m){return m?(this._nullCell.fg=m.fg,this._nullCell.bg=m.bg,this._nullCell.extended=m.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new u.ExtendedAttrs),this._nullCell}getWhitespaceCell(m){return m?(this._whitespaceCell.fg=m.fg,this._whitespaceCell.bg=m.bg,this._whitespaceCell.extended=m.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new u.ExtendedAttrs),this._whitespaceCell}getBlankLine(m,x){return new f.BufferLine(this._bufferService.cols,this.getNullCell(m),x)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){const m=this.ybase+this.y-this.ydisp;return m>=0&&m<this._rows}_getCorrectBufferLength(m){if(!this._hasScrollback)return m;const x=m+this._optionsService.rawOptions.scrollback;return x>o.MAX_BUFFER_SIZE?o.MAX_BUFFER_SIZE:x}fillViewportRows(m){if(this.lines.length===0){m===void 0&&(m=f.DEFAULT_ATTR_DATA);let x=this._rows;for(;x--;)this.lines.push(this.getBlankLine(m))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new h.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(m,x){const y=this.getNullCell(f.DEFAULT_ATTR_DATA);let k=0;const C=this._getCorrectBufferLength(x);if(C>this.lines.maxLength&&(this.lines.maxLength=C),this.lines.length>0){if(this._cols<m)for(let _=0;_<this.lines.length;_++)k+=+this.lines.get(_).resize(m,y);let P=0;if(this._rows<x)for(let _=this._rows;_<x;_++)this.lines.length<x+this.ybase&&(this._optionsService.rawOptions.windowsMode||this._optionsService.rawOptions.windowsPty.backend!==void 0||this._optionsService.rawOptions.windowsPty.buildNumber!==void 0?this.lines.push(new f.BufferLine(m,y)):this.ybase>0&&this.lines.length<=this.ybase+this.y+P+1?(this.ybase--,P++,this.ydisp>0&&this.ydisp--):this.lines.push(new f.BufferLine(m,y)));else for(let _=this._rows;_>x;_--)this.lines.length>x+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(C<this.lines.maxLength){const _=this.lines.length-C;_>0&&(this.lines.trimStart(_),this.ybase=Math.max(this.ybase-_,0),this.ydisp=Math.max(this.ydisp-_,0),this.savedY=Math.max(this.savedY-_,0)),this.lines.maxLength=C}this.x=Math.min(this.x,m-1),this.y=Math.min(this.y,x-1),P&&(this.y+=P),this.savedX=Math.min(this.savedX,m-1),this.scrollTop=0}if(this.scrollBottom=x-1,this._isReflowEnabled&&(this._reflow(m,x),this._cols>m))for(let P=0;P<this.lines.length;P++)k+=+this.lines.get(P).resize(m,y);this._cols=m,this._rows=x,this._memoryCleanupQueue.clear(),k>.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let m=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,m=!1);let x=0;for(;this._memoryCleanupPosition<this.lines.length;)if(x+=this.lines.get(this._memoryCleanupPosition++).cleanupMemory(),x>100)return!0;return m}get _isReflowEnabled(){const m=this._optionsService.rawOptions.windowsPty;return m&&m.buildNumber?this._hasScrollback&&m.backend==="conpty"&&m.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(m,x){this._cols!==m&&(m>this._cols?this._reflowLarger(m,x):this._reflowSmaller(m,x))}_reflowLarger(m,x){const y=(0,p.reflowLargerGetLinesToRemove)(this.lines,this._cols,m,this.ybase+this.y,this.getNullCell(f.DEFAULT_ATTR_DATA));if(y.length>0){const k=(0,p.reflowLargerCreateNewLayout)(this.lines,y);(0,p.reflowLargerApplyNewLayout)(this.lines,k.layout),this._reflowLargerAdjustViewport(m,x,k.countRemoved)}}_reflowLargerAdjustViewport(m,x,y){const k=this.getNullCell(f.DEFAULT_ATTR_DATA);let C=y;for(;C-- >0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length<x&&this.lines.push(new f.BufferLine(m,k))):(this.ydisp===this.ybase&&this.ydisp--,this.ybase--);this.savedY=Math.max(this.savedY-y,0)}_reflowSmaller(m,x){const y=this.getNullCell(f.DEFAULT_ATTR_DATA),k=[];let C=0;for(let P=this.lines.length-1;P>=0;P--){let _=this.lines.get(P);if(!_||!_.isWrapped&&_.getTrimmedLength()<=m)continue;const T=[_];for(;_.isWrapped&&P>0;)_=this.lines.get(--P),T.unshift(_);const R=this.ybase+this.y;if(R>=P&&R<P+T.length)continue;const L=T[T.length-1].getTrimmedLength(),M=(0,p.reflowSmallerGetNewLineLengths)(T,this._cols,m),E=M.length-T.length;let B;B=this.ybase===0&&this.y!==this.lines.length-1?Math.max(0,this.y-this.lines.maxLength+E):Math.max(0,this.lines.length-this.lines.maxLength+E);const U=[];for(let D=0;D<E;D++){const V=this.getBlankLine(f.DEFAULT_ATTR_DATA,!0);U.push(V)}U.length>0&&(k.push({start:P+T.length+C,newLines:U}),C+=U.length),T.push(...U);let F=M.length-1,X=M[F];X===0&&(F--,X=M[F]);let ae=T.length-E-1,j=L;for(;ae>=0;){const D=Math.min(j,X);if(T[F]===void 0)break;if(T[F].copyCellsFrom(T[ae],j-D,X-D,D,!0),X-=D,X===0&&(F--,X=M[F]),j-=D,j===0){ae--;const V=Math.max(ae,0);j=(0,p.getWrappedLineTrimmedLength)(T,V,this._cols)}}for(let D=0;D<T.length;D++)M[D]<m&&T[D].setCell(M[D],y);let W=E-B;for(;W-- >0;)this.ybase===0?this.y<x-1?(this.y++,this.lines.pop()):(this.ybase++,this.ydisp++):this.ybase<Math.min(this.lines.maxLength,this.lines.length+C)-x&&(this.ybase===this.ydisp&&this.ydisp++,this.ybase++);this.savedY=Math.min(this.savedY+E,this.ybase+x-1)}if(k.length>0){const P=[],_=[];for(let F=0;F<this.lines.length;F++)_.push(this.lines.get(F));const T=this.lines.length;let R=T-1,L=0,M=k[L];this.lines.length=Math.min(this.lines.maxLength,this.lines.length+C);let E=0;for(let F=Math.min(this.lines.maxLength-1,T+C-1);F>=0;F--)if(M&&M.start>R+E){for(let X=M.newLines.length-1;X>=0;X--)this.lines.set(F--,M.newLines[X]);F++,P.push({index:R+1,amount:M.newLines.length}),E+=M.newLines.length,M=k[++L]}else this.lines.set(F,_[R--]);let B=0;for(let F=P.length-1;F>=0;F--)P[F].index+=B,this.lines.onInsertEmitter.fire(P[F]),B+=P[F].amount;const U=Math.max(0,T+C-this.lines.maxLength);U>0&&this.lines.onTrimEmitter.fire(U)}}translateBufferLineToString(m,x,y=0,k){const C=this.lines.get(m);return C?C.translateToString(x,y,k):""}getWrappedRangeForLine(m){let x=m,y=m;for(;x>0&&this.lines.get(x).isWrapped;)x--;for(;y+1<this.lines.length&&this.lines.get(y+1).isWrapped;)y++;return{first:x,last:y}}setupTabStops(m){for(m!=null?this.tabs[m]||(m=this.prevStop(m)):(this.tabs={},m=0);m<this._cols;m+=this._optionsService.rawOptions.tabStopWidth)this.tabs[m]=!0}prevStop(m){for(m==null&&(m=this.x);!this.tabs[--m]&&m>0;);return m>=this._cols?this._cols-1:m<0?0:m}nextStop(m){for(m==null&&(m=this.x);!this.tabs[++m]&&m<this._cols;);return m>=this._cols?this._cols-1:m<0?0:m}clearMarkers(m){this._isClearing=!0;for(let x=0;x<this.markers.length;x++)this.markers[x].line===m&&(this.markers[x].dispose(),this.markers.splice(x--,1));this._isClearing=!1}clearAllMarkers(){this._isClearing=!0;for(let m=0;m<this.markers.length;m++)this.markers[m].dispose(),this.markers.splice(m--,1);this._isClearing=!1}addMarker(m){const x=new g.Marker(m);return this.markers.push(x),x.register(this.lines.onTrim((y=>{x.line-=y,x.line<0&&x.dispose()}))),x.register(this.lines.onInsert((y=>{x.line>=y.index&&(x.line+=y.amount)}))),x.register(this.lines.onDelete((y=>{x.line>=y.index&&x.line<y.index+y.amount&&x.dispose(),x.line>y.index&&(x.line-=y.amount)}))),x.register(x.onDispose((()=>this._removeMarker(x)))),x}_removeMarker(m){this._isClearing||this.markers.splice(this.markers.indexOf(m),1)}}},8437:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferLine=o.DEFAULT_ATTR_DATA=void 0;const h=l(3734),d=l(511),u=l(643),f=l(482);o.DEFAULT_ATTR_DATA=Object.freeze(new h.AttributeData);let p=0;class v{constructor(g,O,m=!1){this.isWrapped=m,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*g);const x=O||d.CellData.fromCharData([0,u.NULL_CELL_CHAR,u.NULL_CELL_WIDTH,u.NULL_CELL_CODE]);for(let y=0;y<g;++y)this.setCell(y,x);this.length=g}get(g){const O=this._data[3*g+0],m=2097151&O;return[this._data[3*g+1],2097152&O?this._combined[g]:m?(0,f.stringFromCodePoint)(m):"",O>>22,2097152&O?this._combined[g].charCodeAt(this._combined[g].length-1):m]}set(g,O){this._data[3*g+1]=O[u.CHAR_DATA_ATTR_INDEX],O[u.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[g]=O[1],this._data[3*g+0]=2097152|g|O[u.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*g+0]=O[u.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|O[u.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(g){return this._data[3*g+0]>>22}hasWidth(g){return 12582912&this._data[3*g+0]}getFg(g){return this._data[3*g+1]}getBg(g){return this._data[3*g+2]}hasContent(g){return 4194303&this._data[3*g+0]}getCodePoint(g){const O=this._data[3*g+0];return 2097152&O?this._combined[g].charCodeAt(this._combined[g].length-1):2097151&O}isCombined(g){return 2097152&this._data[3*g+0]}getString(g){const O=this._data[3*g+0];return 2097152&O?this._combined[g]:2097151&O?(0,f.stringFromCodePoint)(2097151&O):""}isProtected(g){return 536870912&this._data[3*g+2]}loadCell(g,O){return p=3*g,O.content=this._data[p+0],O.fg=this._data[p+1],O.bg=this._data[p+2],2097152&O.content&&(O.combinedData=this._combined[g]),268435456&O.bg&&(O.extended=this._extendedAttrs[g]),O}setCell(g,O){2097152&O.content&&(this._combined[g]=O.combinedData),268435456&O.bg&&(this._extendedAttrs[g]=O.extended),this._data[3*g+0]=O.content,this._data[3*g+1]=O.fg,this._data[3*g+2]=O.bg}setCellFromCodepoint(g,O,m,x){268435456&x.bg&&(this._extendedAttrs[g]=x.extended),this._data[3*g+0]=O|m<<22,this._data[3*g+1]=x.fg,this._data[3*g+2]=x.bg}addCodepointToCell(g,O,m){let x=this._data[3*g+0];2097152&x?this._combined[g]+=(0,f.stringFromCodePoint)(O):2097151&x?(this._combined[g]=(0,f.stringFromCodePoint)(2097151&x)+(0,f.stringFromCodePoint)(O),x&=-2097152,x|=2097152):x=O|4194304,m&&(x&=-12582913,x|=m<<22),this._data[3*g+0]=x}insertCells(g,O,m){if((g%=this.length)&&this.getWidth(g-1)===2&&this.setCellFromCodepoint(g-1,0,1,m),O<this.length-g){const x=new d.CellData;for(let y=this.length-g-O-1;y>=0;--y)this.setCell(g+O+y,this.loadCell(g+y,x));for(let y=0;y<O;++y)this.setCell(g+y,m)}else for(let x=g;x<this.length;++x)this.setCell(x,m);this.getWidth(this.length-1)===2&&this.setCellFromCodepoint(this.length-1,0,1,m)}deleteCells(g,O,m){if(g%=this.length,O<this.length-g){const x=new d.CellData;for(let y=0;y<this.length-g-O;++y)this.setCell(g+y,this.loadCell(g+O+y,x));for(let y=this.length-O;y<this.length;++y)this.setCell(y,m)}else for(let x=g;x<this.length;++x)this.setCell(x,m);g&&this.getWidth(g-1)===2&&this.setCellFromCodepoint(g-1,0,1,m),this.getWidth(g)!==0||this.hasContent(g)||this.setCellFromCodepoint(g,0,1,m)}replaceCells(g,O,m,x=!1){if(x)for(g&&this.getWidth(g-1)===2&&!this.isProtected(g-1)&&this.setCellFromCodepoint(g-1,0,1,m),O<this.length&&this.getWidth(O-1)===2&&!this.isProtected(O)&&this.setCellFromCodepoint(O,0,1,m);g<O&&g<this.length;)this.isProtected(g)||this.setCell(g,m),g++;else for(g&&this.getWidth(g-1)===2&&this.setCellFromCodepoint(g-1,0,1,m),O<this.length&&this.getWidth(O-1)===2&&this.setCellFromCodepoint(O,0,1,m);g<O&&g<this.length;)this.setCell(g++,m)}resize(g,O){if(g===this.length)return 4*this._data.length*2<this._data.buffer.byteLength;const m=3*g;if(g>this.length){if(this._data.buffer.byteLength>=4*m)this._data=new Uint32Array(this._data.buffer,0,m);else{const x=new Uint32Array(m);x.set(this._data),this._data=x}for(let x=this.length;x<g;++x)this.setCell(x,O)}else{this._data=this._data.subarray(0,m);const x=Object.keys(this._combined);for(let k=0;k<x.length;k++){const C=parseInt(x[k],10);C>=g&&delete this._combined[C]}const y=Object.keys(this._extendedAttrs);for(let k=0;k<y.length;k++){const C=parseInt(y[k],10);C>=g&&delete this._extendedAttrs[C]}}return this.length=g,4*m*2<this._data.buffer.byteLength}cleanupMemory(){if(4*this._data.length*2<this._data.buffer.byteLength){const g=new Uint32Array(this._data.length);return g.set(this._data),this._data=g,1}return 0}fill(g,O=!1){if(O)for(let m=0;m<this.length;++m)this.isProtected(m)||this.setCell(m,g);else{this._combined={},this._extendedAttrs={};for(let m=0;m<this.length;++m)this.setCell(m,g)}}copyFrom(g){this.length!==g.length?this._data=new Uint32Array(g._data):this._data.set(g._data),this.length=g.length,this._combined={};for(const O in g._combined)this._combined[O]=g._combined[O];this._extendedAttrs={};for(const O in g._extendedAttrs)this._extendedAttrs[O]=g._extendedAttrs[O];this.isWrapped=g.isWrapped}clone(){const g=new v(0);g._data=new Uint32Array(this._data),g.length=this.length;for(const O in this._combined)g._combined[O]=this._combined[O];for(const O in this._extendedAttrs)g._extendedAttrs[O]=this._extendedAttrs[O];return g.isWrapped=this.isWrapped,g}getTrimmedLength(){for(let g=this.length-1;g>=0;--g)if(4194303&this._data[3*g+0])return g+(this._data[3*g+0]>>22);return 0}getNoBgTrimmedLength(){for(let g=this.length-1;g>=0;--g)if(4194303&this._data[3*g+0]||50331648&this._data[3*g+2])return g+(this._data[3*g+0]>>22);return 0}copyCellsFrom(g,O,m,x,y){const k=g._data;if(y)for(let P=x-1;P>=0;P--){for(let _=0;_<3;_++)this._data[3*(m+P)+_]=k[3*(O+P)+_];268435456&k[3*(O+P)+2]&&(this._extendedAttrs[m+P]=g._extendedAttrs[O+P])}else for(let P=0;P<x;P++){for(let _=0;_<3;_++)this._data[3*(m+P)+_]=k[3*(O+P)+_];268435456&k[3*(O+P)+2]&&(this._extendedAttrs[m+P]=g._extendedAttrs[O+P])}const C=Object.keys(g._combined);for(let P=0;P<C.length;P++){const _=parseInt(C[P],10);_>=O&&(this._combined[_-O+m]=g._combined[_])}}translateToString(g,O,m,x){O=O??0,m=m??this.length,g&&(m=Math.min(m,this.getTrimmedLength())),x&&(x.length=0);let y="";for(;O<m;){const k=this._data[3*O+0],C=2097151&k,P=2097152&k?this._combined[O]:C?(0,f.stringFromCodePoint)(C):u.WHITESPACE_CELL_CHAR;if(y+=P,x)for(let _=0;_<P.length;++_)x.push(O);O+=k>>22||1}return x&&x.push(O),y}}o.BufferLine=v},4841:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.getRangeLength=void 0,o.getRangeLength=function(l,h){if(l.start.y>l.end.y)throw new Error(`Buffer range end (${l.end.x}, ${l.end.y}) cannot be before start (${l.start.x}, ${l.start.y})`);return h*(l.end.y-l.start.y)+(l.end.x-l.start.x+1)}},4634:(a,o)=>{function l(h,d,u){if(d===h.length-1)return h[d].getTrimmedLength();const f=!h[d].hasContent(u-1)&&h[d].getWidth(u-1)===1,p=h[d+1].getWidth(0)===2;return f&&p?u-1:u}Object.defineProperty(o,"__esModule",{value:!0}),o.getWrappedLineTrimmedLength=o.reflowSmallerGetNewLineLengths=o.reflowLargerApplyNewLayout=o.reflowLargerCreateNewLayout=o.reflowLargerGetLinesToRemove=void 0,o.reflowLargerGetLinesToRemove=function(h,d,u,f,p){const v=[];for(let b=0;b<h.length-1;b++){let g=b,O=h.get(++g);if(!O.isWrapped)continue;const m=[h.get(b)];for(;g<h.length&&O.isWrapped;)m.push(O),O=h.get(++g);if(f>=b&&f<g){b+=m.length-1;continue}let x=0,y=l(m,x,d),k=1,C=0;for(;k<m.length;){const _=l(m,k,d),T=_-C,R=u-y,L=Math.min(T,R);m[x].copyCellsFrom(m[k],C,y,L,!1),y+=L,y===u&&(x++,y=0),C+=L,C===_&&(k++,C=0),y===0&&x!==0&&m[x-1].getWidth(u-1)===2&&(m[x].copyCellsFrom(m[x-1],u-1,y++,1,!1),m[x-1].setCell(u-1,p))}m[x].replaceCells(y,u,p);let P=0;for(let _=m.length-1;_>0&&(_>x||m[_].getTrimmedLength()===0);_--)P++;P>0&&(v.push(b+m.length-P),v.push(P)),b+=m.length-1}return v},o.reflowLargerCreateNewLayout=function(h,d){const u=[];let f=0,p=d[f],v=0;for(let b=0;b<h.length;b++)if(p===b){const g=d[++f];h.onDeleteEmitter.fire({index:b-v,amount:g}),b+=g-1,v+=g,p=d[++f]}else u.push(b);return{layout:u,countRemoved:v}},o.reflowLargerApplyNewLayout=function(h,d){const u=[];for(let f=0;f<d.length;f++)u.push(h.get(d[f]));for(let f=0;f<u.length;f++)h.set(f,u[f]);h.length=d.length},o.reflowSmallerGetNewLineLengths=function(h,d,u){const f=[],p=h.map(((O,m)=>l(h,m,d))).reduce(((O,m)=>O+m));let v=0,b=0,g=0;for(;g<p;){if(p-g<u){f.push(p-g);break}v+=u;const O=l(h,b,d);v>O&&(v-=O,b++);const m=h[b].getWidth(v-1)===2;m&&v--;const x=m?u-1:u;f.push(x),g+=x}return f},o.getWrappedLineTrimmedLength=l},5295:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferSet=void 0;const h=l(8460),d=l(844),u=l(9092);class f extends d.Disposable{constructor(v,b){super(),this._optionsService=v,this._bufferService=b,this._onBufferActivate=this.register(new h.EventEmitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this.register(this._optionsService.onSpecificOptionChange("scrollback",(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this.register(this._optionsService.onSpecificOptionChange("tabStopWidth",(()=>this.setupTabStops())))}reset(){this._normal=new u.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new u.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(v){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(v),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(v,b){this._normal.resize(v,b),this._alt.resize(v,b),this.setupTabStops(v)}setupTabStops(v){this._normal.setupTabStops(v),this._alt.setupTabStops(v)}}o.BufferSet=f},511:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CellData=void 0;const h=l(482),d=l(643),u=l(3734);class f extends u.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new u.ExtendedAttrs,this.combinedData=""}static fromCharData(v){const b=new f;return b.setFromCharData(v),b}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,h.stringFromCodePoint)(2097151&this.content):""}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(v){this.fg=v[d.CHAR_DATA_ATTR_INDEX],this.bg=0;let b=!1;if(v[d.CHAR_DATA_CHAR_INDEX].length>2)b=!0;else if(v[d.CHAR_DATA_CHAR_INDEX].length===2){const g=v[d.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=g&&g<=56319){const O=v[d.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=O&&O<=57343?this.content=1024*(g-55296)+O-56320+65536|v[d.CHAR_DATA_WIDTH_INDEX]<<22:b=!0}else b=!0}else this.content=v[d.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|v[d.CHAR_DATA_WIDTH_INDEX]<<22;b&&(this.combinedData=v[d.CHAR_DATA_CHAR_INDEX],this.content=2097152|v[d.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}o.CellData=f},643:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WHITESPACE_CELL_CODE=o.WHITESPACE_CELL_WIDTH=o.WHITESPACE_CELL_CHAR=o.NULL_CELL_CODE=o.NULL_CELL_WIDTH=o.NULL_CELL_CHAR=o.CHAR_DATA_CODE_INDEX=o.CHAR_DATA_WIDTH_INDEX=o.CHAR_DATA_CHAR_INDEX=o.CHAR_DATA_ATTR_INDEX=o.DEFAULT_EXT=o.DEFAULT_ATTR=o.DEFAULT_COLOR=void 0,o.DEFAULT_COLOR=0,o.DEFAULT_ATTR=256|o.DEFAULT_COLOR<<9,o.DEFAULT_EXT=0,o.CHAR_DATA_ATTR_INDEX=0,o.CHAR_DATA_CHAR_INDEX=1,o.CHAR_DATA_WIDTH_INDEX=2,o.CHAR_DATA_CODE_INDEX=3,o.NULL_CELL_CHAR="",o.NULL_CELL_WIDTH=1,o.NULL_CELL_CODE=0,o.WHITESPACE_CELL_CHAR=" ",o.WHITESPACE_CELL_WIDTH=1,o.WHITESPACE_CELL_CODE=32},4863:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Marker=void 0;const h=l(8460),d=l(844);class u{get id(){return this._id}constructor(p){this.line=p,this.isDisposed=!1,this._disposables=[],this._id=u._nextId++,this._onDispose=this.register(new h.EventEmitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,d.disposeArray)(this._disposables),this._disposables.length=0)}register(p){return this._disposables.push(p),p}}o.Marker=u,u._nextId=1},7116:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DEFAULT_CHARSET=o.CHARSETS=void 0,o.CHARSETS={},o.DEFAULT_CHARSET=o.CHARSETS.B,o.CHARSETS[0]={"`":"◆",a:"▒",b:"␉",c:"␌",d:"␍",e:"␊",f:"°",g:"±",h:"",i:"␋",j:"┘",k:"┐",l:"┌",m:"└",n:"┼",o:"⎺",p:"⎻",q:"─",r:"⎼",s:"⎽",t:"├",u:"┤",v:"┴",w:"┬",x:"│",y:"≤",z:"≥","{":"π","|":"≠","}":"£","~":"·"},o.CHARSETS.A={"#":"£"},o.CHARSETS.B=void 0,o.CHARSETS[4]={"#":"£","@":"¾","[":"ij","\\":"½","]":"|","{":"¨","|":"f","}":"¼","~":"´"},o.CHARSETS.C=o.CHARSETS[5]={"[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},o.CHARSETS.R={"#":"£","@":"à","[":"°","\\":"ç","]":"§","{":"é","|":"ù","}":"è","~":"¨"},o.CHARSETS.Q={"@":"à","[":"â","\\":"ç","]":"ê","^":"î","`":"ô","{":"é","|":"ù","}":"è","~":"û"},o.CHARSETS.K={"@":"§","[":"Ä","\\":"Ö","]":"Ü","{":"ä","|":"ö","}":"ü","~":"ß"},o.CHARSETS.Y={"#":"£","@":"§","[":"°","\\":"ç","]":"é","`":"ù","{":"à","|":"ò","}":"è","~":"ì"},o.CHARSETS.E=o.CHARSETS[6]={"@":"Ä","[":"Æ","\\":"Ø","]":"Å","^":"Ü","`":"ä","{":"æ","|":"ø","}":"å","~":"ü"},o.CHARSETS.Z={"#":"£","@":"§","[":"¡","\\":"Ñ","]":"¿","{":"°","|":"ñ","}":"ç"},o.CHARSETS.H=o.CHARSETS[7]={"@":"É","[":"Ä","\\":"Ö","]":"Å","^":"Ü","`":"é","{":"ä","|":"ö","}":"å","~":"ü"},o.CHARSETS["="]={"#":"ù","@":"à","[":"é","\\":"ç","]":"ê","^":"î",_:"è","`":"ô","{":"ä","|":"ö","}":"ü","~":"û"}},2584:(a,o)=>{var l,h,d;Object.defineProperty(o,"__esModule",{value:!0}),o.C1_ESCAPED=o.C1=o.C0=void 0,(function(u){u.NUL="\0",u.SOH="",u.STX="",u.ETX="",u.EOT="",u.ENQ="",u.ACK="",u.BEL="\x07",u.BS="\b",u.HT=" ",u.LF=`
|
|
47
47
|
`,u.VT="\v",u.FF="\f",u.CR="\r",u.SO="",u.SI="",u.DLE="",u.DC1="",u.DC2="",u.DC3="",u.DC4="",u.NAK="",u.SYN="",u.ETB="",u.CAN="",u.EM="",u.SUB="",u.ESC="\x1B",u.FS="",u.GS="",u.RS="",u.US="",u.SP=" ",u.DEL=""})(l||(o.C0=l={})),(function(u){u.PAD="",u.HOP="",u.BPH="",u.NBH="",u.IND="",u.NEL="
",u.SSA="",u.ESA="",u.HTS="",u.HTJ="",u.VTS="",u.PLD="",u.PLU="",u.RI="",u.SS2="",u.SS3="",u.DCS="",u.PU1="",u.PU2="",u.STS="",u.CCH="",u.MW="",u.SPA="",u.EPA="",u.SOS="",u.SGCI="",u.SCI="",u.CSI="",u.ST="",u.OSC="",u.PM="",u.APC=""})(h||(o.C1=h={})),(function(u){u.ST=`${l.ESC}\\`})(d||(o.C1_ESCAPED=d={}))},7399:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.evaluateKeyboardEvent=void 0;const h=l(2584),d={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["`","~"],219:["[","{"],220:["\\","|"],221:["]","}"],222:["'",'"']};o.evaluateKeyboardEvent=function(u,f,p,v){const b={type:0,cancel:!1,key:void 0},g=(u.shiftKey?1:0)|(u.altKey?2:0)|(u.ctrlKey?4:0)|(u.metaKey?8:0);switch(u.keyCode){case 0:u.key==="UIKeyInputUpArrow"?b.key=f?h.C0.ESC+"OA":h.C0.ESC+"[A":u.key==="UIKeyInputLeftArrow"?b.key=f?h.C0.ESC+"OD":h.C0.ESC+"[D":u.key==="UIKeyInputRightArrow"?b.key=f?h.C0.ESC+"OC":h.C0.ESC+"[C":u.key==="UIKeyInputDownArrow"&&(b.key=f?h.C0.ESC+"OB":h.C0.ESC+"[B");break;case 8:b.key=u.ctrlKey?"\b":h.C0.DEL,u.altKey&&(b.key=h.C0.ESC+b.key);break;case 9:if(u.shiftKey){b.key=h.C0.ESC+"[Z";break}b.key=h.C0.HT,b.cancel=!0;break;case 13:b.key=u.altKey?h.C0.ESC+h.C0.CR:h.C0.CR,b.cancel=!0;break;case 27:b.key=h.C0.ESC,u.altKey&&(b.key=h.C0.ESC+h.C0.ESC),b.cancel=!0;break;case 37:if(u.metaKey)break;g?(b.key=h.C0.ESC+"[1;"+(g+1)+"D",b.key===h.C0.ESC+"[1;3D"&&(b.key=h.C0.ESC+(p?"b":"[1;5D"))):b.key=f?h.C0.ESC+"OD":h.C0.ESC+"[D";break;case 39:if(u.metaKey)break;g?(b.key=h.C0.ESC+"[1;"+(g+1)+"C",b.key===h.C0.ESC+"[1;3C"&&(b.key=h.C0.ESC+(p?"f":"[1;5C"))):b.key=f?h.C0.ESC+"OC":h.C0.ESC+"[C";break;case 38:if(u.metaKey)break;g?(b.key=h.C0.ESC+"[1;"+(g+1)+"A",p||b.key!==h.C0.ESC+"[1;3A"||(b.key=h.C0.ESC+"[1;5A")):b.key=f?h.C0.ESC+"OA":h.C0.ESC+"[A";break;case 40:if(u.metaKey)break;g?(b.key=h.C0.ESC+"[1;"+(g+1)+"B",p||b.key!==h.C0.ESC+"[1;3B"||(b.key=h.C0.ESC+"[1;5B")):b.key=f?h.C0.ESC+"OB":h.C0.ESC+"[B";break;case 45:u.shiftKey||u.ctrlKey||(b.key=h.C0.ESC+"[2~");break;case 46:b.key=g?h.C0.ESC+"[3;"+(g+1)+"~":h.C0.ESC+"[3~";break;case 36:b.key=g?h.C0.ESC+"[1;"+(g+1)+"H":f?h.C0.ESC+"OH":h.C0.ESC+"[H";break;case 35:b.key=g?h.C0.ESC+"[1;"+(g+1)+"F":f?h.C0.ESC+"OF":h.C0.ESC+"[F";break;case 33:u.shiftKey?b.type=2:u.ctrlKey?b.key=h.C0.ESC+"[5;"+(g+1)+"~":b.key=h.C0.ESC+"[5~";break;case 34:u.shiftKey?b.type=3:u.ctrlKey?b.key=h.C0.ESC+"[6;"+(g+1)+"~":b.key=h.C0.ESC+"[6~";break;case 112:b.key=g?h.C0.ESC+"[1;"+(g+1)+"P":h.C0.ESC+"OP";break;case 113:b.key=g?h.C0.ESC+"[1;"+(g+1)+"Q":h.C0.ESC+"OQ";break;case 114:b.key=g?h.C0.ESC+"[1;"+(g+1)+"R":h.C0.ESC+"OR";break;case 115:b.key=g?h.C0.ESC+"[1;"+(g+1)+"S":h.C0.ESC+"OS";break;case 116:b.key=g?h.C0.ESC+"[15;"+(g+1)+"~":h.C0.ESC+"[15~";break;case 117:b.key=g?h.C0.ESC+"[17;"+(g+1)+"~":h.C0.ESC+"[17~";break;case 118:b.key=g?h.C0.ESC+"[18;"+(g+1)+"~":h.C0.ESC+"[18~";break;case 119:b.key=g?h.C0.ESC+"[19;"+(g+1)+"~":h.C0.ESC+"[19~";break;case 120:b.key=g?h.C0.ESC+"[20;"+(g+1)+"~":h.C0.ESC+"[20~";break;case 121:b.key=g?h.C0.ESC+"[21;"+(g+1)+"~":h.C0.ESC+"[21~";break;case 122:b.key=g?h.C0.ESC+"[23;"+(g+1)+"~":h.C0.ESC+"[23~";break;case 123:b.key=g?h.C0.ESC+"[24;"+(g+1)+"~":h.C0.ESC+"[24~";break;default:if(!u.ctrlKey||u.shiftKey||u.altKey||u.metaKey)if(p&&!v||!u.altKey||u.metaKey)!p||u.altKey||u.ctrlKey||u.shiftKey||!u.metaKey?u.key&&!u.ctrlKey&&!u.altKey&&!u.metaKey&&u.keyCode>=48&&u.key.length===1?b.key=u.key:u.key&&u.ctrlKey&&(u.key==="_"&&(b.key=h.C0.US),u.key==="@"&&(b.key=h.C0.NUL)):u.keyCode===65&&(b.type=1);else{const O=d[u.keyCode],m=O?.[u.shiftKey?1:0];if(m)b.key=h.C0.ESC+m;else if(u.keyCode>=65&&u.keyCode<=90){const x=u.ctrlKey?u.keyCode-64:u.keyCode+32;let y=String.fromCharCode(x);u.shiftKey&&(y=y.toUpperCase()),b.key=h.C0.ESC+y}else if(u.keyCode===32)b.key=h.C0.ESC+(u.ctrlKey?h.C0.NUL:" ");else if(u.key==="Dead"&&u.code.startsWith("Key")){let x=u.code.slice(3,4);u.shiftKey||(x=x.toLowerCase()),b.key=h.C0.ESC+x,b.cancel=!0}}else u.keyCode>=65&&u.keyCode<=90?b.key=String.fromCharCode(u.keyCode-64):u.keyCode===32?b.key=h.C0.NUL:u.keyCode>=51&&u.keyCode<=55?b.key=String.fromCharCode(u.keyCode-51+27):u.keyCode===56?b.key=h.C0.DEL:u.keyCode===219?b.key=h.C0.ESC:u.keyCode===220?b.key=h.C0.FS:u.keyCode===221&&(b.key=h.C0.GS)}return b}},482:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Utf8ToUtf32=o.StringToUtf32=o.utf32ToString=o.stringFromCodePoint=void 0,o.stringFromCodePoint=function(l){return l>65535?(l-=65536,String.fromCharCode(55296+(l>>10))+String.fromCharCode(l%1024+56320)):String.fromCharCode(l)},o.utf32ToString=function(l,h=0,d=l.length){let u="";for(let f=h;f<d;++f){let p=l[f];p>65535?(p-=65536,u+=String.fromCharCode(55296+(p>>10))+String.fromCharCode(p%1024+56320)):u+=String.fromCharCode(p)}return u},o.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(l,h){const d=l.length;if(!d)return 0;let u=0,f=0;if(this._interim){const p=l.charCodeAt(f++);56320<=p&&p<=57343?h[u++]=1024*(this._interim-55296)+p-56320+65536:(h[u++]=this._interim,h[u++]=p),this._interim=0}for(let p=f;p<d;++p){const v=l.charCodeAt(p);if(55296<=v&&v<=56319){if(++p>=d)return this._interim=v,u;const b=l.charCodeAt(p);56320<=b&&b<=57343?h[u++]=1024*(v-55296)+b-56320+65536:(h[u++]=v,h[u++]=b)}else v!==65279&&(h[u++]=v)}return u}},o.Utf8ToUtf32=class{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(l,h){const d=l.length;if(!d)return 0;let u,f,p,v,b=0,g=0,O=0;if(this.interim[0]){let y=!1,k=this.interim[0];k&=(224&k)==192?31:(240&k)==224?15:7;let C,P=0;for(;(C=63&this.interim[++P])&&P<4;)k<<=6,k|=C;const _=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,T=_-P;for(;O<T;){if(O>=d)return 0;if(C=l[O++],(192&C)!=128){O--,y=!0;break}this.interim[P++]=C,k<<=6,k|=63&C}y||(_===2?k<128?O--:h[b++]=k:_===3?k<2048||k>=55296&&k<=57343||k===65279||(h[b++]=k):k<65536||k>1114111||(h[b++]=k)),this.interim.fill(0)}const m=d-4;let x=O;for(;x<d;){for(;!(!(x<m)||128&(u=l[x])||128&(f=l[x+1])||128&(p=l[x+2])||128&(v=l[x+3]));)h[b++]=u,h[b++]=f,h[b++]=p,h[b++]=v,x+=4;if(u=l[x++],u<128)h[b++]=u;else if((224&u)==192){if(x>=d)return this.interim[0]=u,b;if(f=l[x++],(192&f)!=128){x--;continue}if(g=(31&u)<<6|63&f,g<128){x--;continue}h[b++]=g}else if((240&u)==224){if(x>=d)return this.interim[0]=u,b;if(f=l[x++],(192&f)!=128){x--;continue}if(x>=d)return this.interim[0]=u,this.interim[1]=f,b;if(p=l[x++],(192&p)!=128){x--;continue}if(g=(15&u)<<12|(63&f)<<6|63&p,g<2048||g>=55296&&g<=57343||g===65279)continue;h[b++]=g}else if((248&u)==240){if(x>=d)return this.interim[0]=u,b;if(f=l[x++],(192&f)!=128){x--;continue}if(x>=d)return this.interim[0]=u,this.interim[1]=f,b;if(p=l[x++],(192&p)!=128){x--;continue}if(x>=d)return this.interim[0]=u,this.interim[1]=f,this.interim[2]=p,b;if(v=l[x++],(192&v)!=128){x--;continue}if(g=(7&u)<<18|(63&f)<<12|(63&p)<<6|63&v,g<65536||g>1114111)continue;h[b++]=g}}return b}}},225:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeV6=void 0;const h=l(1480),d=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],u=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]];let f;o.UnicodeV6=class{constructor(){if(this.version="6",!f){f=new Uint8Array(65536),f.fill(1),f[0]=0,f.fill(0,1,32),f.fill(0,127,160),f.fill(2,4352,4448),f[9001]=2,f[9002]=2,f.fill(2,11904,42192),f[12351]=1,f.fill(2,44032,55204),f.fill(2,63744,64256),f.fill(2,65040,65050),f.fill(2,65072,65136),f.fill(2,65280,65377),f.fill(2,65504,65511);for(let p=0;p<d.length;++p)f.fill(0,d[p][0],d[p][1]+1)}}wcwidth(p){return p<32?0:p<127?1:p<65536?f[p]:(function(v,b){let g,O=0,m=b.length-1;if(v<b[0][0]||v>b[m][1])return!1;for(;m>=O;)if(g=O+m>>1,v>b[g][1])O=g+1;else{if(!(v<b[g][0]))return!0;m=g-1}return!1})(p,u)?0:p>=131072&&p<=196605||p>=196608&&p<=262141?2:1}charProperties(p,v){let b=this.wcwidth(p),g=b===0&&v!==0;if(g){const O=h.UnicodeService.extractWidth(v);O===0?g=!1:O>b&&(b=O)}return h.UnicodeService.createPropertyValue(0,b,g)}}},5981:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.WriteBuffer=void 0;const h=l(8460),d=l(844);class u extends d.Disposable{constructor(p){super(),this._action=p,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this.register(new h.EventEmitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(p,v){if(v!==void 0&&this._syncCalls>v)return void(this._syncCalls=0);if(this._pendingData+=p.length,this._writeBuffer.push(p),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let b;for(this._isSyncWriting=!0;b=this._writeBuffer.shift();){this._action(b);const g=this._callbacks.shift();g&&g()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(p,v){if(this._pendingData>5e7)throw new Error("write data discarded, use flow control to avoid losing data");if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=p.length,this._writeBuffer.push(p),this._callbacks.push(v),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=p.length,this._writeBuffer.push(p),this._callbacks.push(v)}_innerWrite(p=0,v=!0){const b=p||Date.now();for(;this._writeBuffer.length>this._bufferOffset;){const g=this._writeBuffer[this._bufferOffset],O=this._action(g,v);if(O){const x=y=>Date.now()-b>=12?setTimeout((()=>this._innerWrite(0,y))):this._innerWrite(b,y);return void O.catch((y=>(queueMicrotask((()=>{throw y})),Promise.resolve(!1)))).then(x)}const m=this._callbacks[this._bufferOffset];if(m&&m(),this._bufferOffset++,this._pendingData-=g.length,Date.now()-b>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}o.WriteBuffer=u},5941:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.toRgbString=o.parseColor=void 0;const l=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,h=/^[\da-f]+$/;function d(u,f){const p=u.toString(16),v=p.length<2?"0"+p:p;switch(f){case 4:return p[0];case 8:return v;case 12:return(v+v).slice(0,3);default:return v+v}}o.parseColor=function(u){if(!u)return;let f=u.toLowerCase();if(f.indexOf("rgb:")===0){f=f.slice(4);const p=l.exec(f);if(p){const v=p[1]?15:p[4]?255:p[7]?4095:65535;return[Math.round(parseInt(p[1]||p[4]||p[7]||p[10],16)/v*255),Math.round(parseInt(p[2]||p[5]||p[8]||p[11],16)/v*255),Math.round(parseInt(p[3]||p[6]||p[9]||p[12],16)/v*255)]}}else if(f.indexOf("#")===0&&(f=f.slice(1),h.exec(f)&&[3,6,9,12].includes(f.length))){const p=f.length/3,v=[0,0,0];for(let b=0;b<3;++b){const g=parseInt(f.slice(p*b,p*b+p),16);v[b]=p===1?g<<4:p===2?g:p===3?g>>4:g>>8}return v}},o.toRgbString=function(u,f=16){const[p,v,b]=u;return`rgb:${d(p,f)}/${d(v,f)}/${d(b,f)}`}},5770:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.PAYLOAD_LIMIT=void 0,o.PAYLOAD_LIMIT=1e7},6351:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DcsHandler=o.DcsParser=void 0;const h=l(482),d=l(8742),u=l(5770),f=[];o.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=f,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=f}registerHandler(v,b){this._handlers[v]===void 0&&(this._handlers[v]=[]);const g=this._handlers[v];return g.push(b),{dispose:()=>{const O=g.indexOf(b);O!==-1&&g.splice(O,1)}}}clearHandler(v){this._handlers[v]&&delete this._handlers[v]}setHandlerFallback(v){this._handlerFb=v}reset(){if(this._active.length)for(let v=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;v>=0;--v)this._active[v].unhook(!1);this._stack.paused=!1,this._active=f,this._ident=0}hook(v,b){if(this.reset(),this._ident=v,this._active=this._handlers[v]||f,this._active.length)for(let g=this._active.length-1;g>=0;g--)this._active[g].hook(b);else this._handlerFb(this._ident,"HOOK",b)}put(v,b,g){if(this._active.length)for(let O=this._active.length-1;O>=0;O--)this._active[O].put(v,b,g);else this._handlerFb(this._ident,"PUT",(0,h.utf32ToString)(v,b,g))}unhook(v,b=!0){if(this._active.length){let g=!1,O=this._active.length-1,m=!1;if(this._stack.paused&&(O=this._stack.loopPosition-1,g=b,m=this._stack.fallThrough,this._stack.paused=!1),!m&&g===!1){for(;O>=0&&(g=this._active[O].unhook(v),g!==!0);O--)if(g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=O,this._stack.fallThrough=!1,g;O--}for(;O>=0;O--)if(g=this._active[O].unhook(!1),g instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=O,this._stack.fallThrough=!0,g}else this._handlerFb(this._ident,"UNHOOK",v);this._active=f,this._ident=0}};const p=new d.Params;p.addParam(0),o.DcsHandler=class{constructor(v){this._handler=v,this._data="",this._params=p,this._hitLimit=!1}hook(v){this._params=v.length>1||v.params[0]?v.clone():p,this._data="",this._hitLimit=!1}put(v,b,g){this._hitLimit||(this._data+=(0,h.utf32ToString)(v,b,g),this._data.length>u.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}unhook(v){let b=!1;if(this._hitLimit)b=!1;else if(v&&(b=this._handler(this._data,this._params),b instanceof Promise))return b.then((g=>(this._params=p,this._data="",this._hitLimit=!1,g)));return this._params=p,this._data="",this._hitLimit=!1,b}}},2015:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.EscapeSequenceParser=o.VT500_TRANSITION_TABLE=o.TransitionTable=void 0;const h=l(844),d=l(8742),u=l(6242),f=l(6351);class p{constructor(O){this.table=new Uint8Array(O)}setDefault(O,m){this.table.fill(O<<4|m)}add(O,m,x,y){this.table[m<<8|O]=x<<4|y}addMany(O,m,x,y){for(let k=0;k<O.length;k++)this.table[m<<8|O[k]]=x<<4|y}}o.TransitionTable=p;const v=160;o.VT500_TRANSITION_TABLE=(function(){const g=new p(4095),O=Array.apply(null,Array(256)).map(((P,_)=>_)),m=(P,_)=>O.slice(P,_),x=m(32,127),y=m(0,24);y.push(25),y.push.apply(y,m(28,32));const k=m(0,14);let C;for(C in g.setDefault(1,0),g.addMany(x,0,2,0),k)g.addMany([24,26,153,154],C,3,0),g.addMany(m(128,144),C,3,0),g.addMany(m(144,152),C,3,0),g.add(156,C,0,0),g.add(27,C,11,1),g.add(157,C,4,8),g.addMany([152,158,159],C,0,7),g.add(155,C,11,3),g.add(144,C,11,9);return g.addMany(y,0,3,0),g.addMany(y,1,3,1),g.add(127,1,0,1),g.addMany(y,8,0,8),g.addMany(y,3,3,3),g.add(127,3,0,3),g.addMany(y,4,3,4),g.add(127,4,0,4),g.addMany(y,6,3,6),g.addMany(y,5,3,5),g.add(127,5,0,5),g.addMany(y,2,3,2),g.add(127,2,0,2),g.add(93,1,4,8),g.addMany(x,8,5,8),g.add(127,8,5,8),g.addMany([156,27,24,26,7],8,6,0),g.addMany(m(28,32),8,0,8),g.addMany([88,94,95],1,0,7),g.addMany(x,7,0,7),g.addMany(y,7,0,7),g.add(156,7,0,0),g.add(127,7,0,7),g.add(91,1,11,3),g.addMany(m(64,127),3,7,0),g.addMany(m(48,60),3,8,4),g.addMany([60,61,62,63],3,9,4),g.addMany(m(48,60),4,8,4),g.addMany(m(64,127),4,7,0),g.addMany([60,61,62,63],4,0,6),g.addMany(m(32,64),6,0,6),g.add(127,6,0,6),g.addMany(m(64,127),6,0,0),g.addMany(m(32,48),3,9,5),g.addMany(m(32,48),5,9,5),g.addMany(m(48,64),5,0,6),g.addMany(m(64,127),5,7,0),g.addMany(m(32,48),4,9,5),g.addMany(m(32,48),1,9,2),g.addMany(m(32,48),2,9,2),g.addMany(m(48,127),2,10,0),g.addMany(m(48,80),1,10,0),g.addMany(m(81,88),1,10,0),g.addMany([89,90,92],1,10,0),g.addMany(m(96,127),1,10,0),g.add(80,1,11,9),g.addMany(y,9,0,9),g.add(127,9,0,9),g.addMany(m(28,32),9,0,9),g.addMany(m(32,48),9,9,12),g.addMany(m(48,60),9,8,10),g.addMany([60,61,62,63],9,9,10),g.addMany(y,11,0,11),g.addMany(m(32,128),11,0,11),g.addMany(m(28,32),11,0,11),g.addMany(y,10,0,10),g.add(127,10,0,10),g.addMany(m(28,32),10,0,10),g.addMany(m(48,60),10,8,10),g.addMany([60,61,62,63],10,0,11),g.addMany(m(32,48),10,9,12),g.addMany(y,12,0,12),g.add(127,12,0,12),g.addMany(m(28,32),12,0,12),g.addMany(m(32,48),12,9,12),g.addMany(m(48,64),12,0,11),g.addMany(m(64,127),12,12,13),g.addMany(m(64,127),10,12,13),g.addMany(m(64,127),9,12,13),g.addMany(y,13,13,13),g.addMany(x,13,13,13),g.add(127,13,0,13),g.addMany([27,156,24,26],13,14,0),g.add(v,0,2,0),g.add(v,8,5,8),g.add(v,6,0,6),g.add(v,11,0,11),g.add(v,13,13,13),g})();class b extends h.Disposable{constructor(O=o.VT500_TRANSITION_TABLE){super(),this._transitions=O,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new d.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(m,x,y)=>{},this._executeHandlerFb=m=>{},this._csiHandlerFb=(m,x)=>{},this._escHandlerFb=m=>{},this._errorHandlerFb=m=>m,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this.register((0,h.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this.register(new u.OscParser),this._dcsParser=this.register(new f.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:"\\"},(()=>!0))}_identifier(O,m=[64,126]){let x=0;if(O.prefix){if(O.prefix.length>1)throw new Error("only one byte as prefix supported");if(x=O.prefix.charCodeAt(0),x&&60>x||x>63)throw new Error("prefix must be in range 0x3c .. 0x3f")}if(O.intermediates){if(O.intermediates.length>2)throw new Error("only two bytes as intermediates are supported");for(let k=0;k<O.intermediates.length;++k){const C=O.intermediates.charCodeAt(k);if(32>C||C>47)throw new Error("intermediate must be in range 0x20 .. 0x2f");x<<=8,x|=C}}if(O.final.length!==1)throw new Error("final must be a single byte");const y=O.final.charCodeAt(0);if(m[0]>y||y>m[1])throw new Error(`final must be in range ${m[0]} .. ${m[1]}`);return x<<=8,x|=y,x}identToString(O){const m=[];for(;O;)m.push(String.fromCharCode(255&O)),O>>=8;return m.reverse().join("")}setPrintHandler(O){this._printHandler=O}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(O,m){const x=this._identifier(O,[48,126]);this._escHandlers[x]===void 0&&(this._escHandlers[x]=[]);const y=this._escHandlers[x];return y.push(m),{dispose:()=>{const k=y.indexOf(m);k!==-1&&y.splice(k,1)}}}clearEscHandler(O){this._escHandlers[this._identifier(O,[48,126])]&&delete this._escHandlers[this._identifier(O,[48,126])]}setEscHandlerFallback(O){this._escHandlerFb=O}setExecuteHandler(O,m){this._executeHandlers[O.charCodeAt(0)]=m}clearExecuteHandler(O){this._executeHandlers[O.charCodeAt(0)]&&delete this._executeHandlers[O.charCodeAt(0)]}setExecuteHandlerFallback(O){this._executeHandlerFb=O}registerCsiHandler(O,m){const x=this._identifier(O);this._csiHandlers[x]===void 0&&(this._csiHandlers[x]=[]);const y=this._csiHandlers[x];return y.push(m),{dispose:()=>{const k=y.indexOf(m);k!==-1&&y.splice(k,1)}}}clearCsiHandler(O){this._csiHandlers[this._identifier(O)]&&delete this._csiHandlers[this._identifier(O)]}setCsiHandlerFallback(O){this._csiHandlerFb=O}registerDcsHandler(O,m){return this._dcsParser.registerHandler(this._identifier(O),m)}clearDcsHandler(O){this._dcsParser.clearHandler(this._identifier(O))}setDcsHandlerFallback(O){this._dcsParser.setHandlerFallback(O)}registerOscHandler(O,m){return this._oscParser.registerHandler(O,m)}clearOscHandler(O){this._oscParser.clearHandler(O)}setOscHandlerFallback(O){this._oscParser.setHandlerFallback(O)}setErrorHandler(O){this._errorHandler=O}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(O,m,x,y,k){this._parseStack.state=O,this._parseStack.handlers=m,this._parseStack.handlerPos=x,this._parseStack.transition=y,this._parseStack.chunkPos=k}parse(O,m,x){let y,k=0,C=0,P=0;if(this._parseStack.state)if(this._parseStack.state===2)this._parseStack.state=0,P=this._parseStack.chunkPos+1;else{if(x===void 0||this._parseStack.state===1)throw this._parseStack.state=1,new Error("improper continuation due to previous async handler, giving up parsing");const _=this._parseStack.handlers;let T=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(x===!1&&T>-1){for(;T>=0&&(y=_[T](this._params),y!==!0);T--)if(y instanceof Promise)return this._parseStack.handlerPos=T,y}this._parseStack.handlers=[];break;case 4:if(x===!1&&T>-1){for(;T>=0&&(y=_[T](),y!==!0);T--)if(y instanceof Promise)return this._parseStack.handlerPos=T,y}this._parseStack.handlers=[];break;case 6:if(k=O[this._parseStack.chunkPos],y=this._dcsParser.unhook(k!==24&&k!==26,x),y)return y;k===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(k=O[this._parseStack.chunkPos],y=this._oscParser.end(k!==24&&k!==26,x),y)return y;k===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,P=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}for(let _=P;_<m;++_){switch(k=O[_],C=this._transitions.table[this.currentState<<8|(k<160?k:v)],C>>4){case 2:for(let E=_+1;;++E){if(E>=m||(k=O[E])<32||k>126&&k<v){this._printHandler(O,_,E),_=E-1;break}if(++E>=m||(k=O[E])<32||k>126&&k<v){this._printHandler(O,_,E),_=E-1;break}if(++E>=m||(k=O[E])<32||k>126&&k<v){this._printHandler(O,_,E),_=E-1;break}if(++E>=m||(k=O[E])<32||k>126&&k<v){this._printHandler(O,_,E),_=E-1;break}}break;case 3:this._executeHandlers[k]?this._executeHandlers[k]():this._executeHandlerFb(k),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:_,code:k,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:const T=this._csiHandlers[this._collect<<8|k];let R=T?T.length-1:-1;for(;R>=0&&(y=T[R](this._params),y!==!0);R--)if(y instanceof Promise)return this._preserveStack(3,T,R,C,_),y;R<0&&this._csiHandlerFb(this._collect<<8|k,this._params),this.precedingJoinState=0;break;case 8:do switch(k){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(k-48)}while(++_<m&&(k=O[_])>47&&k<60);_--;break;case 9:this._collect<<=8,this._collect|=k;break;case 10:const L=this._escHandlers[this._collect<<8|k];let M=L?L.length-1:-1;for(;M>=0&&(y=L[M](),y!==!0);M--)if(y instanceof Promise)return this._preserveStack(4,L,M,C,_),y;M<0&&this._escHandlerFb(this._collect<<8|k),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|k,this._params);break;case 13:for(let E=_+1;;++E)if(E>=m||(k=O[E])===24||k===26||k===27||k>127&&k<v){this._dcsParser.put(O,_,E),_=E-1;break}break;case 14:if(y=this._dcsParser.unhook(k!==24&&k!==26),y)return this._preserveStack(6,[],0,C,_),y;k===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let E=_+1;;E++)if(E>=m||(k=O[E])<32||k>127&&k<v){this._oscParser.put(O,_,E),_=E-1;break}break;case 6:if(y=this._oscParser.end(k!==24&&k!==26),y)return this._preserveStack(5,[],0,C,_),y;k===27&&(C|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&C}}}o.EscapeSequenceParser=b},6242:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.OscHandler=o.OscParser=void 0;const h=l(5770),d=l(482),u=[];o.OscParser=class{constructor(){this._state=0,this._active=u,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(f,p){this._handlers[f]===void 0&&(this._handlers[f]=[]);const v=this._handlers[f];return v.push(p),{dispose:()=>{const b=v.indexOf(p);b!==-1&&v.splice(b,1)}}}clearHandler(f){this._handlers[f]&&delete this._handlers[f]}setHandlerFallback(f){this._handlerFb=f}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=u}reset(){if(this._state===2)for(let f=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;f>=0;--f)this._active[f].end(!1);this._stack.paused=!1,this._active=u,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||u,this._active.length)for(let f=this._active.length-1;f>=0;f--)this._active[f].start();else this._handlerFb(this._id,"START")}_put(f,p,v){if(this._active.length)for(let b=this._active.length-1;b>=0;b--)this._active[b].put(f,p,v);else this._handlerFb(this._id,"PUT",(0,d.utf32ToString)(f,p,v))}start(){this.reset(),this._state=1}put(f,p,v){if(this._state!==3){if(this._state===1)for(;p<v;){const b=f[p++];if(b===59){this._state=2,this._start();break}if(b<48||57<b)return void(this._state=3);this._id===-1&&(this._id=0),this._id=10*this._id+b-48}this._state===2&&v-p>0&&this._put(f,p,v)}}end(f,p=!0){if(this._state!==0){if(this._state!==3)if(this._state===1&&this._start(),this._active.length){let v=!1,b=this._active.length-1,g=!1;if(this._stack.paused&&(b=this._stack.loopPosition-1,v=p,g=this._stack.fallThrough,this._stack.paused=!1),!g&&v===!1){for(;b>=0&&(v=this._active[b].end(f),v!==!0);b--)if(v instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!1,v;b--}for(;b>=0;b--)if(v=this._active[b].end(!1),v instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=b,this._stack.fallThrough=!0,v}else this._handlerFb(this._id,"END",f);this._active=u,this._id=-1,this._state=0}}},o.OscHandler=class{constructor(f){this._handler=f,this._data="",this._hitLimit=!1}start(){this._data="",this._hitLimit=!1}put(f,p,v){this._hitLimit||(this._data+=(0,d.utf32ToString)(f,p,v),this._data.length>h.PAYLOAD_LIMIT&&(this._data="",this._hitLimit=!0))}end(f){let p=!1;if(this._hitLimit)p=!1;else if(f&&(p=this._handler(this._data),p instanceof Promise))return p.then((v=>(this._data="",this._hitLimit=!1,v)));return this._data="",this._hitLimit=!1,p}}},8742:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.Params=void 0;const l=2147483647;class h{static fromArray(u){const f=new h;if(!u.length)return f;for(let p=Array.isArray(u[0])?1:0;p<u.length;++p){const v=u[p];if(Array.isArray(v))for(let b=0;b<v.length;++b)f.addSubParam(v[b]);else f.addParam(v)}return f}constructor(u=32,f=32){if(this.maxLength=u,this.maxSubParamsLength=f,f>256)throw new Error("maxSubParamsLength must not be greater than 256");this.params=new Int32Array(u),this.length=0,this._subParams=new Int32Array(f),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(u),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){const u=new h(this.maxLength,this.maxSubParamsLength);return u.params.set(this.params),u.length=this.length,u._subParams.set(this._subParams),u._subParamsLength=this._subParamsLength,u._subParamsIdx.set(this._subParamsIdx),u._rejectDigits=this._rejectDigits,u._rejectSubDigits=this._rejectSubDigits,u._digitIsSub=this._digitIsSub,u}toArray(){const u=[];for(let f=0;f<this.length;++f){u.push(this.params[f]);const p=this._subParamsIdx[f]>>8,v=255&this._subParamsIdx[f];v-p>0&&u.push(Array.prototype.slice.call(this._subParams,p,v))}return u}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(u){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(u<-1)throw new Error("values lesser than -1 are not allowed");this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=u>l?l:u}}addSubParam(u){if(this._digitIsSub=!0,this.length)if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(u<-1)throw new Error("values lesser than -1 are not allowed");this._subParams[this._subParamsLength++]=u>l?l:u,this._subParamsIdx[this.length-1]++}}hasSubParams(u){return(255&this._subParamsIdx[u])-(this._subParamsIdx[u]>>8)>0}getSubParams(u){const f=this._subParamsIdx[u]>>8,p=255&this._subParamsIdx[u];return p-f>0?this._subParams.subarray(f,p):null}getSubParamsAll(){const u={};for(let f=0;f<this.length;++f){const p=this._subParamsIdx[f]>>8,v=255&this._subParamsIdx[f];v-p>0&&(u[f]=this._subParams.slice(p,v))}return u}addDigit(u){let f;if(this._rejectDigits||!(f=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;const p=this._digitIsSub?this._subParams:this.params,v=p[f-1];p[f-1]=~v?Math.min(10*v+u,l):u}}o.Params=h},5741:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.AddonManager=void 0,o.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let l=this._addons.length-1;l>=0;l--)this._addons[l].instance.dispose()}loadAddon(l,h){const d={instance:h,dispose:h.dispose,isDisposed:!1};this._addons.push(d),h.dispose=()=>this._wrappedAddonDispose(d),h.activate(l)}_wrappedAddonDispose(l){if(l.isDisposed)return;let h=-1;for(let d=0;d<this._addons.length;d++)if(this._addons[d]===l){h=d;break}if(h===-1)throw new Error("Could not dispose an addon that has not been loaded");l.isDisposed=!0,l.dispose.apply(l.instance),this._addons.splice(h,1)}}},8771:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferApiView=void 0;const h=l(3785),d=l(511);o.BufferApiView=class{constructor(u,f){this._buffer=u,this.type=f}init(u){return this._buffer=u,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(u){const f=this._buffer.lines.get(u);if(f)return new h.BufferLineApiView(f)}getNullCell(){return new d.CellData}}},3785:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferLineApiView=void 0;const h=l(511);o.BufferLineApiView=class{constructor(d){this._line=d}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(d,u){if(!(d<0||d>=this._line.length))return u?(this._line.loadCell(d,u),u):this._line.loadCell(d,new h.CellData)}translateToString(d,u,f){return this._line.translateToString(d,u,f)}}},8285:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.BufferNamespaceApi=void 0;const h=l(8771),d=l(8460),u=l(844);class f extends u.Disposable{constructor(v){super(),this._core=v,this._onBufferChange=this.register(new d.EventEmitter),this.onBufferChange=this._onBufferChange.event,this._normal=new h.BufferApiView(this._core.buffers.normal,"normal"),this._alternate=new h.BufferApiView(this._core.buffers.alt,"alternate"),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw new Error("Active buffer is neither normal nor alternate")}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}o.BufferNamespaceApi=f},7975:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.ParserApi=void 0,o.ParserApi=class{constructor(l){this._core=l}registerCsiHandler(l,h){return this._core.registerCsiHandler(l,(d=>h(d.toArray())))}addCsiHandler(l,h){return this.registerCsiHandler(l,h)}registerDcsHandler(l,h){return this._core.registerDcsHandler(l,((d,u)=>h(d,u.toArray())))}addDcsHandler(l,h){return this.registerDcsHandler(l,h)}registerEscHandler(l,h){return this._core.registerEscHandler(l,h)}addEscHandler(l,h){return this.registerEscHandler(l,h)}registerOscHandler(l,h){return this._core.registerOscHandler(l,h)}addOscHandler(l,h){return this.registerOscHandler(l,h)}}},7090:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeApi=void 0,o.UnicodeApi=class{constructor(l){this._core=l}register(l){this._core.unicodeService.register(l)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(l){this._core.unicodeService.activeVersion=l}}},744:function(a,o,l){var h=this&&this.__decorate||function(g,O,m,x){var y,k=arguments.length,C=k<3?O:x===null?x=Object.getOwnPropertyDescriptor(O,m):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,O,m,x);else for(var P=g.length-1;P>=0;P--)(y=g[P])&&(C=(k<3?y(C):k>3?y(O,m,C):y(O,m))||C);return k>3&&C&&Object.defineProperty(O,m,C),C},d=this&&this.__param||function(g,O){return function(m,x){O(m,x,g)}};Object.defineProperty(o,"__esModule",{value:!0}),o.BufferService=o.MINIMUM_ROWS=o.MINIMUM_COLS=void 0;const u=l(8460),f=l(844),p=l(5295),v=l(2585);o.MINIMUM_COLS=2,o.MINIMUM_ROWS=1;let b=o.BufferService=class extends f.Disposable{get buffer(){return this.buffers.active}constructor(g){super(),this.isUserScrolling=!1,this._onResize=this.register(new u.EventEmitter),this.onResize=this._onResize.event,this._onScroll=this.register(new u.EventEmitter),this.onScroll=this._onScroll.event,this.cols=Math.max(g.rawOptions.cols||0,o.MINIMUM_COLS),this.rows=Math.max(g.rawOptions.rows||0,o.MINIMUM_ROWS),this.buffers=this.register(new p.BufferSet(g,this))}resize(g,O){this.cols=g,this.rows=O,this.buffers.resize(g,O),this._onResize.fire({cols:g,rows:O})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(g,O=!1){const m=this.buffer;let x;x=this._cachedBlankLine,x&&x.length===this.cols&&x.getFg(0)===g.fg&&x.getBg(0)===g.bg||(x=m.getBlankLine(g,O),this._cachedBlankLine=x),x.isWrapped=O;const y=m.ybase+m.scrollTop,k=m.ybase+m.scrollBottom;if(m.scrollTop===0){const C=m.lines.isFull;k===m.lines.length-1?C?m.lines.recycle().copyFrom(x):m.lines.push(x.clone()):m.lines.splice(k+1,0,x.clone()),C?this.isUserScrolling&&(m.ydisp=Math.max(m.ydisp-1,0)):(m.ybase++,this.isUserScrolling||m.ydisp++)}else{const C=k-y+1;m.lines.shiftElements(y+1,C-1,-1),m.lines.set(k,x.clone())}this.isUserScrolling||(m.ydisp=m.ybase),this._onScroll.fire(m.ydisp)}scrollLines(g,O,m){const x=this.buffer;if(g<0){if(x.ydisp===0)return;this.isUserScrolling=!0}else g+x.ydisp>=x.ybase&&(this.isUserScrolling=!1);const y=x.ydisp;x.ydisp=Math.max(Math.min(x.ydisp+g,x.ybase),0),y!==x.ydisp&&(O||this._onScroll.fire(x.ydisp))}};o.BufferService=b=h([d(0,v.IOptionsService)],b)},7994:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.CharsetService=void 0,o.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(l){this.glevel=l,this.charset=this._charsets[l]}setgCharset(l,h){this._charsets[l]=h,this.glevel===l&&(this.charset=h)}}},1753:function(a,o,l){var h=this&&this.__decorate||function(x,y,k,C){var P,_=arguments.length,T=_<3?y:C===null?C=Object.getOwnPropertyDescriptor(y,k):C;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")T=Reflect.decorate(x,y,k,C);else for(var R=x.length-1;R>=0;R--)(P=x[R])&&(T=(_<3?P(T):_>3?P(y,k,T):P(y,k))||T);return _>3&&T&&Object.defineProperty(y,k,T),T},d=this&&this.__param||function(x,y){return function(k,C){y(k,C,x)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CoreMouseService=void 0;const u=l(2585),f=l(8460),p=l(844),v={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:x=>x.button!==4&&x.action===1&&(x.ctrl=!1,x.alt=!1,x.shift=!1,!0)},VT200:{events:19,restrict:x=>x.action!==32},DRAG:{events:23,restrict:x=>x.action!==32||x.button!==3},ANY:{events:31,restrict:x=>!0}};function b(x,y){let k=(x.ctrl?16:0)|(x.shift?4:0)|(x.alt?8:0);return x.button===4?(k|=64,k|=x.action):(k|=3&x.button,4&x.button&&(k|=64),8&x.button&&(k|=128),x.action===32?k|=32:x.action!==0||y||(k|=3)),k}const g=String.fromCharCode,O={DEFAULT:x=>{const y=[b(x,!1)+32,x.col+32,x.row+32];return y[0]>255||y[1]>255||y[2]>255?"":`\x1B[M${g(y[0])}${g(y[1])}${g(y[2])}`},SGR:x=>{const y=x.action===0&&x.button!==4?"m":"M";return`\x1B[<${b(x,!0)};${x.col};${x.row}${y}`},SGR_PIXELS:x=>{const y=x.action===0&&x.button!==4?"m":"M";return`\x1B[<${b(x,!0)};${x.x};${x.y}${y}`}};let m=o.CoreMouseService=class extends p.Disposable{constructor(x,y){super(),this._bufferService=x,this._coreService=y,this._protocols={},this._encodings={},this._activeProtocol="",this._activeEncoding="",this._lastEvent=null,this._onProtocolChange=this.register(new f.EventEmitter),this.onProtocolChange=this._onProtocolChange.event;for(const k of Object.keys(v))this.addProtocol(k,v[k]);for(const k of Object.keys(O))this.addEncoding(k,O[k]);this.reset()}addProtocol(x,y){this._protocols[x]=y}addEncoding(x,y){this._encodings[x]=y}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(x){if(!this._protocols[x])throw new Error(`unknown protocol "${x}"`);this._activeProtocol=x,this._onProtocolChange.fire(this._protocols[x].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(x){if(!this._encodings[x])throw new Error(`unknown encoding "${x}"`);this._activeEncoding=x}reset(){this.activeProtocol="NONE",this.activeEncoding="DEFAULT",this._lastEvent=null}triggerMouseEvent(x){if(x.col<0||x.col>=this._bufferService.cols||x.row<0||x.row>=this._bufferService.rows||x.button===4&&x.action===32||x.button===3&&x.action!==32||x.button!==4&&(x.action===2||x.action===3)||(x.col++,x.row++,x.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,x,this._activeEncoding==="SGR_PIXELS"))||!this._protocols[this._activeProtocol].restrict(x))return!1;const y=this._encodings[this._activeEncoding](x);return y&&(this._activeEncoding==="DEFAULT"?this._coreService.triggerBinaryEvent(y):this._coreService.triggerDataEvent(y,!0)),this._lastEvent=x,!0}explainEvents(x){return{down:!!(1&x),up:!!(2&x),drag:!!(4&x),move:!!(8&x),wheel:!!(16&x)}}_equalEvents(x,y,k){if(k){if(x.x!==y.x||x.y!==y.y)return!1}else if(x.col!==y.col||x.row!==y.row)return!1;return x.button===y.button&&x.action===y.action&&x.ctrl===y.ctrl&&x.alt===y.alt&&x.shift===y.shift}};o.CoreMouseService=m=h([d(0,u.IBufferService),d(1,u.ICoreService)],m)},6975:function(a,o,l){var h=this&&this.__decorate||function(m,x,y,k){var C,P=arguments.length,_=P<3?x:k===null?k=Object.getOwnPropertyDescriptor(x,y):k;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")_=Reflect.decorate(m,x,y,k);else for(var T=m.length-1;T>=0;T--)(C=m[T])&&(_=(P<3?C(_):P>3?C(x,y,_):C(x,y))||_);return P>3&&_&&Object.defineProperty(x,y,_),_},d=this&&this.__param||function(m,x){return function(y,k){x(y,k,m)}};Object.defineProperty(o,"__esModule",{value:!0}),o.CoreService=void 0;const u=l(1439),f=l(8460),p=l(844),v=l(2585),b=Object.freeze({insertMode:!1}),g=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,origin:!1,reverseWraparound:!1,sendFocus:!1,wraparound:!0});let O=o.CoreService=class extends p.Disposable{constructor(m,x,y){super(),this._bufferService=m,this._logService=x,this._optionsService=y,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this.register(new f.EventEmitter),this.onData=this._onData.event,this._onUserInput=this.register(new f.EventEmitter),this.onUserInput=this._onUserInput.event,this._onBinary=this.register(new f.EventEmitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this.register(new f.EventEmitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,u.clone)(b),this.decPrivateModes=(0,u.clone)(g)}reset(){this.modes=(0,u.clone)(b),this.decPrivateModes=(0,u.clone)(g)}triggerDataEvent(m,x=!1){if(this._optionsService.rawOptions.disableStdin)return;const y=this._bufferService.buffer;x&&this._optionsService.rawOptions.scrollOnUserInput&&y.ybase!==y.ydisp&&this._onRequestScrollToBottom.fire(),x&&this._onUserInput.fire(),this._logService.debug(`sending data "${m}"`,(()=>m.split("").map((k=>k.charCodeAt(0))))),this._onData.fire(m)}triggerBinaryEvent(m){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${m}"`,(()=>m.split("").map((x=>x.charCodeAt(0))))),this._onBinary.fire(m))}};o.CoreService=O=h([d(0,v.IBufferService),d(1,v.ILogService),d(2,v.IOptionsService)],O)},9074:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.DecorationService=void 0;const h=l(8055),d=l(8460),u=l(844),f=l(6106);let p=0,v=0;class b extends u.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new f.SortedList((m=>m?.marker.line)),this._onDecorationRegistered=this.register(new d.EventEmitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this.register(new d.EventEmitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this.register((0,u.toDisposable)((()=>this.reset())))}registerDecoration(m){if(m.marker.isDisposed)return;const x=new g(m);if(x){const y=x.marker.onDispose((()=>x.dispose()));x.onDispose((()=>{x&&(this._decorations.delete(x)&&this._onDecorationRemoved.fire(x),y.dispose())})),this._decorations.insert(x),this._onDecorationRegistered.fire(x)}return x}reset(){for(const m of this._decorations.values())m.dispose();this._decorations.clear()}*getDecorationsAtCell(m,x,y){let k=0,C=0;for(const P of this._decorations.getKeyIterator(x))k=P.options.x??0,C=k+(P.options.width??1),m>=k&&m<C&&(!y||(P.options.layer??"bottom")===y)&&(yield P)}forEachDecorationAtCell(m,x,y,k){this._decorations.forEachByKey(x,(C=>{p=C.options.x??0,v=p+(C.options.width??1),m>=p&&m<v&&(!y||(C.options.layer??"bottom")===y)&&k(C)}))}}o.DecorationService=b;class g extends u.Disposable{get isDisposed(){return this._isDisposed}get backgroundColorRGB(){return this._cachedBg===null&&(this.options.backgroundColor?this._cachedBg=h.css.toColor(this.options.backgroundColor):this._cachedBg=void 0),this._cachedBg}get foregroundColorRGB(){return this._cachedFg===null&&(this.options.foregroundColor?this._cachedFg=h.css.toColor(this.options.foregroundColor):this._cachedFg=void 0),this._cachedFg}constructor(m){super(),this.options=m,this.onRenderEmitter=this.register(new d.EventEmitter),this.onRender=this.onRenderEmitter.event,this._onDispose=this.register(new d.EventEmitter),this.onDispose=this._onDispose.event,this._cachedBg=null,this._cachedFg=null,this.marker=m.marker,this.options.overviewRulerOptions&&!this.options.overviewRulerOptions.position&&(this.options.overviewRulerOptions.position="full")}dispose(){this._onDispose.fire(),super.dispose()}}},4348:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.InstantiationService=o.ServiceCollection=void 0;const h=l(2585),d=l(8343);class u{constructor(...p){this._entries=new Map;for(const[v,b]of p)this.set(v,b)}set(p,v){const b=this._entries.get(p);return this._entries.set(p,v),b}forEach(p){for(const[v,b]of this._entries.entries())p(v,b)}has(p){return this._entries.has(p)}get(p){return this._entries.get(p)}}o.ServiceCollection=u,o.InstantiationService=class{constructor(){this._services=new u,this._services.set(h.IInstantiationService,this)}setService(f,p){this._services.set(f,p)}getService(f){return this._services.get(f)}createInstance(f,...p){const v=(0,d.getServiceDependencies)(f).sort(((O,m)=>O.index-m.index)),b=[];for(const O of v){const m=this._services.get(O.id);if(!m)throw new Error(`[createInstance] ${f.name} depends on UNKNOWN service ${O.id}.`);b.push(m)}const g=v.length>0?v[0].index:p.length;if(p.length!==g)throw new Error(`[createInstance] First service dependency of ${f.name} at position ${g+1} conflicts with ${p.length} static arguments`);return new f(...p,...b)}}},7866:function(a,o,l){var h=this&&this.__decorate||function(g,O,m,x){var y,k=arguments.length,C=k<3?O:x===null?x=Object.getOwnPropertyDescriptor(O,m):x;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")C=Reflect.decorate(g,O,m,x);else for(var P=g.length-1;P>=0;P--)(y=g[P])&&(C=(k<3?y(C):k>3?y(O,m,C):y(O,m))||C);return k>3&&C&&Object.defineProperty(O,m,C),C},d=this&&this.__param||function(g,O){return function(m,x){O(m,x,g)}};Object.defineProperty(o,"__esModule",{value:!0}),o.traceCall=o.setTraceLogger=o.LogService=void 0;const u=l(844),f=l(2585),p={trace:f.LogLevelEnum.TRACE,debug:f.LogLevelEnum.DEBUG,info:f.LogLevelEnum.INFO,warn:f.LogLevelEnum.WARN,error:f.LogLevelEnum.ERROR,off:f.LogLevelEnum.OFF};let v,b=o.LogService=class extends u.Disposable{get logLevel(){return this._logLevel}constructor(g){super(),this._optionsService=g,this._logLevel=f.LogLevelEnum.OFF,this._updateLogLevel(),this.register(this._optionsService.onSpecificOptionChange("logLevel",(()=>this._updateLogLevel()))),v=this}_updateLogLevel(){this._logLevel=p[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(g){for(let O=0;O<g.length;O++)typeof g[O]=="function"&&(g[O]=g[O]())}_log(g,O,m){this._evalLazyOptionalParams(m),g.call(console,(this._optionsService.options.logger?"":"xterm.js: ")+O,...m)}trace(g,...O){this._logLevel<=f.LogLevelEnum.TRACE&&this._log(this._optionsService.options.logger?.trace.bind(this._optionsService.options.logger)??console.log,g,O)}debug(g,...O){this._logLevel<=f.LogLevelEnum.DEBUG&&this._log(this._optionsService.options.logger?.debug.bind(this._optionsService.options.logger)??console.log,g,O)}info(g,...O){this._logLevel<=f.LogLevelEnum.INFO&&this._log(this._optionsService.options.logger?.info.bind(this._optionsService.options.logger)??console.info,g,O)}warn(g,...O){this._logLevel<=f.LogLevelEnum.WARN&&this._log(this._optionsService.options.logger?.warn.bind(this._optionsService.options.logger)??console.warn,g,O)}error(g,...O){this._logLevel<=f.LogLevelEnum.ERROR&&this._log(this._optionsService.options.logger?.error.bind(this._optionsService.options.logger)??console.error,g,O)}};o.LogService=b=h([d(0,f.IOptionsService)],b),o.setTraceLogger=function(g){v=g},o.traceCall=function(g,O,m){if(typeof m.value!="function")throw new Error("not supported");const x=m.value;m.value=function(...y){if(v.logLevel!==f.LogLevelEnum.TRACE)return x.apply(this,y);v.trace(`GlyphRenderer#${x.name}(${y.map((C=>JSON.stringify(C))).join(", ")})`);const k=x.apply(this,y);return v.trace(`GlyphRenderer#${x.name} return`,k),k}}},7302:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.OptionsService=o.DEFAULT_OPTIONS=void 0;const h=l(8460),d=l(844),u=l(6114);o.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:"block",cursorWidth:1,cursorInactiveStyle:"outline",customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:"alt",fastScrollSensitivity:5,fontFamily:"courier-new, courier, monospace",fontSize:15,fontWeight:"normal",fontWeightBold:"bold",ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:"info",logger:null,scrollback:1e3,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},rescaleOverlappingGlyphs:!1,rightClickSelectsWord:u.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:" ()[]{}',\"`",altClickMovesCursor:!0,convertEol:!1,termName:"xterm",cancelEvents:!1,overviewRulerWidth:0};const f=["normal","bold","100","200","300","400","500","600","700","800","900"];class p extends d.Disposable{constructor(b){super(),this._onOptionChange=this.register(new h.EventEmitter),this.onOptionChange=this._onOptionChange.event;const g={...o.DEFAULT_OPTIONS};for(const O in b)if(O in g)try{const m=b[O];g[O]=this._sanitizeAndValidateOption(O,m)}catch(m){console.error(m)}this.rawOptions=g,this.options={...g},this._setupOptions(),this.register((0,d.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(b,g){return this.onOptionChange((O=>{O===b&&g(this.rawOptions[b])}))}onMultipleOptionChange(b,g){return this.onOptionChange((O=>{b.indexOf(O)!==-1&&g()}))}_setupOptions(){const b=O=>{if(!(O in o.DEFAULT_OPTIONS))throw new Error(`No option with key "${O}"`);return this.rawOptions[O]},g=(O,m)=>{if(!(O in o.DEFAULT_OPTIONS))throw new Error(`No option with key "${O}"`);m=this._sanitizeAndValidateOption(O,m),this.rawOptions[O]!==m&&(this.rawOptions[O]=m,this._onOptionChange.fire(O))};for(const O in this.rawOptions){const m={get:b.bind(this,O),set:g.bind(this,O)};Object.defineProperty(this.options,O,m)}}_sanitizeAndValidateOption(b,g){switch(b){case"cursorStyle":if(g||(g=o.DEFAULT_OPTIONS[b]),!(function(O){return O==="block"||O==="underline"||O==="bar"})(g))throw new Error(`"${g}" is not a valid value for ${b}`);break;case"wordSeparator":g||(g=o.DEFAULT_OPTIONS[b]);break;case"fontWeight":case"fontWeightBold":if(typeof g=="number"&&1<=g&&g<=1e3)break;g=f.includes(g)?g:o.DEFAULT_OPTIONS[b];break;case"cursorWidth":g=Math.floor(g);case"lineHeight":case"tabStopWidth":if(g<1)throw new Error(`${b} cannot be less than 1, value: ${g}`);break;case"minimumContrastRatio":g=Math.max(1,Math.min(21,Math.round(10*g)/10));break;case"scrollback":if((g=Math.min(g,4294967295))<0)throw new Error(`${b} cannot be less than 0, value: ${g}`);break;case"fastScrollSensitivity":case"scrollSensitivity":if(g<=0)throw new Error(`${b} cannot be less than or equal to 0, value: ${g}`);break;case"rows":case"cols":if(!g&&g!==0)throw new Error(`${b} must be numeric, value: ${g}`);break;case"windowsPty":g=g??{}}return g}}o.OptionsService=p},2660:function(a,o,l){var h=this&&this.__decorate||function(p,v,b,g){var O,m=arguments.length,x=m<3?v:g===null?g=Object.getOwnPropertyDescriptor(v,b):g;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")x=Reflect.decorate(p,v,b,g);else for(var y=p.length-1;y>=0;y--)(O=p[y])&&(x=(m<3?O(x):m>3?O(v,b,x):O(v,b))||x);return m>3&&x&&Object.defineProperty(v,b,x),x},d=this&&this.__param||function(p,v){return function(b,g){v(b,g,p)}};Object.defineProperty(o,"__esModule",{value:!0}),o.OscLinkService=void 0;const u=l(2585);let f=o.OscLinkService=class{constructor(p){this._bufferService=p,this._nextId=1,this._entriesWithId=new Map,this._dataByLinkId=new Map}registerLink(p){const v=this._bufferService.buffer;if(p.id===void 0){const y=v.addMarker(v.ybase+v.y),k={data:p,id:this._nextId++,lines:[y]};return y.onDispose((()=>this._removeMarkerFromLink(k,y))),this._dataByLinkId.set(k.id,k),k.id}const b=p,g=this._getEntryIdKey(b),O=this._entriesWithId.get(g);if(O)return this.addLineToLink(O.id,v.ybase+v.y),O.id;const m=v.addMarker(v.ybase+v.y),x={id:this._nextId++,key:this._getEntryIdKey(b),data:b,lines:[m]};return m.onDispose((()=>this._removeMarkerFromLink(x,m))),this._entriesWithId.set(x.key,x),this._dataByLinkId.set(x.id,x),x.id}addLineToLink(p,v){const b=this._dataByLinkId.get(p);if(b&&b.lines.every((g=>g.line!==v))){const g=this._bufferService.buffer.addMarker(v);b.lines.push(g),g.onDispose((()=>this._removeMarkerFromLink(b,g)))}}getLinkData(p){return this._dataByLinkId.get(p)?.data}_getEntryIdKey(p){return`${p.id};;${p.uri}`}_removeMarkerFromLink(p,v){const b=p.lines.indexOf(v);b!==-1&&(p.lines.splice(b,1),p.lines.length===0&&(p.data.id!==void 0&&this._entriesWithId.delete(p.key),this._dataByLinkId.delete(p.id)))}};o.OscLinkService=f=h([d(0,u.IBufferService)],f)},8343:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.createDecorator=o.getServiceDependencies=o.serviceRegistry=void 0;const l="di$target",h="di$dependencies";o.serviceRegistry=new Map,o.getServiceDependencies=function(d){return d[h]||[]},o.createDecorator=function(d){if(o.serviceRegistry.has(d))return o.serviceRegistry.get(d);const u=function(f,p,v){if(arguments.length!==3)throw new Error("@IServiceName-decorator can only be used to decorate a parameter");(function(b,g,O){g[l]===g?g[h].push({id:b,index:O}):(g[h]=[{id:b,index:O}],g[l]=g)})(u,f,v)};return u.toString=()=>d,o.serviceRegistry.set(d,u),u}},2585:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.IDecorationService=o.IUnicodeService=o.IOscLinkService=o.IOptionsService=o.ILogService=o.LogLevelEnum=o.IInstantiationService=o.ICharsetService=o.ICoreService=o.ICoreMouseService=o.IBufferService=void 0;const h=l(8343);var d;o.IBufferService=(0,h.createDecorator)("BufferService"),o.ICoreMouseService=(0,h.createDecorator)("CoreMouseService"),o.ICoreService=(0,h.createDecorator)("CoreService"),o.ICharsetService=(0,h.createDecorator)("CharsetService"),o.IInstantiationService=(0,h.createDecorator)("InstantiationService"),(function(u){u[u.TRACE=0]="TRACE",u[u.DEBUG=1]="DEBUG",u[u.INFO=2]="INFO",u[u.WARN=3]="WARN",u[u.ERROR=4]="ERROR",u[u.OFF=5]="OFF"})(d||(o.LogLevelEnum=d={})),o.ILogService=(0,h.createDecorator)("LogService"),o.IOptionsService=(0,h.createDecorator)("OptionsService"),o.IOscLinkService=(0,h.createDecorator)("OscLinkService"),o.IUnicodeService=(0,h.createDecorator)("UnicodeService"),o.IDecorationService=(0,h.createDecorator)("DecorationService")},1480:(a,o,l)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.UnicodeService=void 0;const h=l(8460),d=l(225);class u{static extractShouldJoin(p){return(1&p)!=0}static extractWidth(p){return p>>1&3}static extractCharKind(p){return p>>3}static createPropertyValue(p,v,b=!1){return(16777215&p)<<3|(3&v)<<1|(b?1:0)}constructor(){this._providers=Object.create(null),this._active="",this._onChange=new h.EventEmitter,this.onChange=this._onChange.event;const p=new d.UnicodeV6;this.register(p),this._active=p.version,this._activeProvider=p}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(p){if(!this._providers[p])throw new Error(`unknown Unicode version "${p}"`);this._active=p,this._activeProvider=this._providers[p],this._onChange.fire(p)}register(p){this._providers[p.version]=p}wcwidth(p){return this._activeProvider.wcwidth(p)}getStringCellWidth(p){let v=0,b=0;const g=p.length;for(let O=0;O<g;++O){let m=p.charCodeAt(O);if(55296<=m&&m<=56319){if(++O>=g)return v+this.wcwidth(m);const k=p.charCodeAt(O);56320<=k&&k<=57343?m=1024*(m-55296)+k-56320+65536:v+=this.wcwidth(k)}const x=this.charProperties(m,b);let y=u.extractWidth(x);u.extractShouldJoin(x)&&(y-=u.extractWidth(b)),v+=y,b=x}return v}charProperties(p,v){return this._activeProvider.charProperties(p,v)}}o.UnicodeService=u}},r={};function i(a){var o=r[a];if(o!==void 0)return o.exports;var l=r[a]={exports:{}};return t[a].call(l.exports,l,l.exports,i),l.exports}var n={};return(()=>{var a=n;Object.defineProperty(a,"__esModule",{value:!0}),a.Terminal=void 0;const o=i(9042),l=i(3236),h=i(844),d=i(5741),u=i(8285),f=i(7975),p=i(7090),v=["cols","rows"];class b extends h.Disposable{constructor(O){super(),this._core=this.register(new l.Terminal(O)),this._addonManager=this.register(new d.AddonManager),this._publicOptions={...this._core.options};const m=y=>this._core.options[y],x=(y,k)=>{this._checkReadonlyOptions(y),this._core.options[y]=k};for(const y in this._core.options){const k={get:m.bind(this,y),set:x.bind(this,y)};Object.defineProperty(this._publicOptions,y,k)}}_checkReadonlyOptions(O){if(v.includes(O))throw new Error(`Option "${O}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw new Error("You must set the allowProposedApi option to true to use proposed API")}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||(this._parser=new f.ParserApi(this._core)),this._parser}get unicode(){return this._checkProposedApi(),new p.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||(this._buffer=this.register(new u.BufferNamespaceApi(this._core))),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){const O=this._core.coreService.decPrivateModes;let m="none";switch(this._core.coreMouseService.activeProtocol){case"X10":m="x10";break;case"VT200":m="vt200";break;case"DRAG":m="drag";break;case"ANY":m="any"}return{applicationCursorKeysMode:O.applicationCursorKeys,applicationKeypadMode:O.applicationKeypad,bracketedPasteMode:O.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:m,originMode:O.origin,reverseWraparoundMode:O.reverseWraparound,sendFocusMode:O.sendFocus,wraparoundMode:O.wraparound}}get options(){return this._publicOptions}set options(O){for(const m in O)this._publicOptions[m]=O[m]}blur(){this._core.blur()}focus(){this._core.focus()}input(O,m=!0){this._core.input(O,m)}resize(O,m){this._verifyIntegers(O,m),this._core.resize(O,m)}open(O){this._core.open(O)}attachCustomKeyEventHandler(O){this._core.attachCustomKeyEventHandler(O)}attachCustomWheelEventHandler(O){this._core.attachCustomWheelEventHandler(O)}registerLinkProvider(O){return this._core.registerLinkProvider(O)}registerCharacterJoiner(O){return this._checkProposedApi(),this._core.registerCharacterJoiner(O)}deregisterCharacterJoiner(O){this._checkProposedApi(),this._core.deregisterCharacterJoiner(O)}registerMarker(O=0){return this._verifyIntegers(O),this._core.registerMarker(O)}registerDecoration(O){return this._checkProposedApi(),this._verifyPositiveIntegers(O.x??0,O.width??0,O.height??0),this._core.registerDecoration(O)}hasSelection(){return this._core.hasSelection()}select(O,m,x){this._verifyIntegers(O,m,x),this._core.select(O,m,x)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(O,m){this._verifyIntegers(O,m),this._core.selectLines(O,m)}dispose(){super.dispose()}scrollLines(O){this._verifyIntegers(O),this._core.scrollLines(O)}scrollPages(O){this._verifyIntegers(O),this._core.scrollPages(O)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(O){this._verifyIntegers(O),this._core.scrollToLine(O)}clear(){this._core.clear()}write(O,m){this._core.write(O,m)}writeln(O,m){this._core.write(O),this._core.write(`\r
|
|
48
|
-
`,m)}paste(O){this._core.paste(O)}refresh(O,m){this._verifyIntegers(O,m),this._core.refresh(O,m)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(O){this._addonManager.loadAddon(this,O)}static get strings(){return o}_verifyIntegers(...O){for(const m of O)if(m===1/0||isNaN(m)||m%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...O){for(const m of O)if(m&&(m===1/0||isNaN(m)||m%1!=0||m<0))throw new Error("This API only accepts positive integers")}}a.Terminal=b})(),n})()))})(gf)),gf.exports}var cD=lD(),Of={exports:{}},av;function hD(){return av||(av=1,(function(s,e){(function(t,r){s.exports=r()})(self,(()=>(()=>{var t={};return(()=>{var r=t;Object.defineProperty(r,"__esModule",{value:!0}),r.FitAddon=void 0,r.FitAddon=class{activate(i){this._terminal=i}dispose(){}fit(){const i=this.proposeDimensions();if(!i||!this._terminal||isNaN(i.cols)||isNaN(i.rows))return;const n=this._terminal._core;this._terminal.rows===i.rows&&this._terminal.cols===i.cols||(n._renderService.clear(),this._terminal.resize(i.cols,i.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const i=this._terminal._core,n=i._renderService.dimensions;if(n.css.cell.width===0||n.css.cell.height===0)return;const a=this._terminal.options.scrollback===0?0:i.viewport.scrollBarWidth,o=window.getComputedStyle(this._terminal.element.parentElement),l=parseInt(o.getPropertyValue("height")),h=Math.max(0,parseInt(o.getPropertyValue("width"))),d=window.getComputedStyle(this._terminal.element),u=l-(parseInt(d.getPropertyValue("padding-top"))+parseInt(d.getPropertyValue("padding-bottom"))),f=h-(parseInt(d.getPropertyValue("padding-right"))+parseInt(d.getPropertyValue("padding-left")))-a;return{cols:Math.max(2,Math.floor(f/n.css.cell.width)),rows:Math.max(1,Math.floor(u/n.css.cell.height))}}}})(),t})()))})(Of)),Of.exports}var dD=hD(),xf={exports:{}},lv;function uD(){return lv||(lv=1,(function(s,e){(function(t,r){s.exports=r()})(self,(()=>(()=>{var t={345:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.runAndSubscribe=o.forwardEvent=o.EventEmitter=void 0,o.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=l=>(this._listeners.push(l),{dispose:()=>{if(!this._disposed){for(let h=0;h<this._listeners.length;h++)if(this._listeners[h]===l)return void this._listeners.splice(h,1)}}})),this._event}fire(l,h){const d=[];for(let u=0;u<this._listeners.length;u++)d.push(this._listeners[u]);for(let u=0;u<d.length;u++)d[u].call(void 0,l,h)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},o.forwardEvent=function(l,h){return l((d=>h.fire(d)))},o.runAndSubscribe=function(l,h){return h(void 0),l((d=>h(d)))}},859:(a,o)=>{function l(h){for(const d of h)d.dispose();h.length=0}Object.defineProperty(o,"__esModule",{value:!0}),o.getDisposeArrayDisposable=o.disposeArray=o.toDisposable=o.MutableDisposable=o.Disposable=void 0,o.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const h of this._disposables)h.dispose();this._disposables.length=0}register(h){return this._disposables.push(h),h}unregister(h){const d=this._disposables.indexOf(h);d!==-1&&this._disposables.splice(d,1)}},o.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(h){this._isDisposed||h===this._value||(this._value?.dispose(),this._value=h)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},o.toDisposable=function(h){return{dispose:h}},o.disposeArray=l,o.getDisposeArrayDisposable=function(h){return{dispose:()=>l(h)}}}},r={};function i(a){var o=r[a];if(o!==void 0)return o.exports;var l=r[a]={exports:{}};return t[a](l,l.exports,i),l.exports}var n={};return(()=>{var a=n;Object.defineProperty(a,"__esModule",{value:!0}),a.SearchAddon=void 0;const o=i(345),l=i(859),h=" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?";class d extends l.Disposable{constructor(f){super(),this._highlightedLines=new Set,this._highlightDecorations=[],this._selectedDecoration=this.register(new l.MutableDisposable),this._linesCacheTimeoutId=0,this._linesCacheDisposables=new l.MutableDisposable,this._onDidChangeResults=this.register(new o.EventEmitter),this.onDidChangeResults=this._onDidChangeResults.event,this._highlightLimit=f?.highlightLimit??1e3}activate(f){this._terminal=f,this.register(this._terminal.onWriteParsed((()=>this._updateMatches()))),this.register(this._terminal.onResize((()=>this._updateMatches()))),this.register((0,l.toDisposable)((()=>this.clearDecorations())))}_updateMatches(){this._highlightTimeout&&window.clearTimeout(this._highlightTimeout),this._cachedSearchTerm&&this._lastSearchOptions?.decorations&&(this._highlightTimeout=setTimeout((()=>{const f=this._cachedSearchTerm;this._cachedSearchTerm=void 0,this.findPrevious(f,{...this._lastSearchOptions,incremental:!0,noScroll:!0})}),200))}clearDecorations(f){this._selectedDecoration.clear(),(0,l.disposeArray)(this._highlightDecorations),this._highlightDecorations=[],this._highlightedLines.clear(),f||(this._cachedSearchTerm=void 0)}clearActiveDecoration(){this._selectedDecoration.clear()}findNext(f,p){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");const v=!this._lastSearchOptions||this._didOptionsChange(this._lastSearchOptions,p);this._lastSearchOptions=p,p?.decorations&&(this._cachedSearchTerm===void 0||f!==this._cachedSearchTerm||v)&&this._highlightAllMatches(f,p);const b=this._findNextAndSelect(f,p);return this._fireResults(p),this._cachedSearchTerm=f,b}_highlightAllMatches(f,p){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");if(!f||f.length===0)return void this.clearDecorations();p=p||{},this.clearDecorations(!0);const v=[];let b,g=this._find(f,0,0,p);for(;g&&(b?.row!==g.row||b?.col!==g.col)&&!(v.length>=this._highlightLimit);)b=g,v.push(b),g=this._find(f,b.col+b.term.length>=this._terminal.cols?b.row+1:b.row,b.col+b.term.length>=this._terminal.cols?0:b.col+1,p);for(const O of v){const m=this._createResultDecoration(O,p.decorations);m&&(this._highlightedLines.add(m.marker.line),this._highlightDecorations.push({decoration:m,match:O,dispose(){m.dispose()}}))}}_find(f,p,v,b){if(!this._terminal||!f||f.length===0)return this._terminal?.clearSelection(),void this.clearDecorations();if(v>this._terminal.cols)throw new Error(`Invalid col: ${v} to search in terminal of ${this._terminal.cols} cols`);let g;this._initLinesCache();const O={startRow:p,startCol:v};if(g=this._findInLine(f,O,b),!g)for(let m=p+1;m<this._terminal.buffer.active.baseY+this._terminal.rows&&(O.startRow=m,O.startCol=0,g=this._findInLine(f,O,b),!g);m++);return g}_findNextAndSelect(f,p){if(!this._terminal||!f||f.length===0)return this._terminal?.clearSelection(),this.clearDecorations(),!1;const v=this._terminal.getSelectionPosition();this._terminal.clearSelection();let b=0,g=0;v&&(this._cachedSearchTerm===f?(b=v.end.x,g=v.end.y):(b=v.start.x,g=v.start.y)),this._initLinesCache();const O={startRow:g,startCol:b};let m=this._findInLine(f,O,p);if(!m)for(let x=g+1;x<this._terminal.buffer.active.baseY+this._terminal.rows&&(O.startRow=x,O.startCol=0,m=this._findInLine(f,O,p),!m);x++);if(!m&&g!==0)for(let x=0;x<g&&(O.startRow=x,O.startCol=0,m=this._findInLine(f,O,p),!m);x++);return!m&&v&&(O.startRow=v.start.y,O.startCol=0,m=this._findInLine(f,O,p)),this._selectResult(m,p?.decorations,p?.noScroll)}findPrevious(f,p){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");const v=!this._lastSearchOptions||this._didOptionsChange(this._lastSearchOptions,p);this._lastSearchOptions=p,p?.decorations&&(this._cachedSearchTerm===void 0||f!==this._cachedSearchTerm||v)&&this._highlightAllMatches(f,p);const b=this._findPreviousAndSelect(f,p);return this._fireResults(p),this._cachedSearchTerm=f,b}_didOptionsChange(f,p){return!!p&&(f.caseSensitive!==p.caseSensitive||f.regex!==p.regex||f.wholeWord!==p.wholeWord)}_fireResults(f){if(f?.decorations){let p=-1;if(this._selectedDecoration.value){const v=this._selectedDecoration.value.match;for(let b=0;b<this._highlightDecorations.length;b++){const g=this._highlightDecorations[b].match;if(g.row===v.row&&g.col===v.col&&g.size===v.size){p=b;break}}}this._onDidChangeResults.fire({resultIndex:p,resultCount:this._highlightDecorations.length})}}_findPreviousAndSelect(f,p){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");if(!this._terminal||!f||f.length===0)return this._terminal?.clearSelection(),this.clearDecorations(),!1;const v=this._terminal.getSelectionPosition();this._terminal.clearSelection();let b=this._terminal.buffer.active.baseY+this._terminal.rows-1,g=this._terminal.cols;const O=!0;this._initLinesCache();const m={startRow:b,startCol:g};let x;if(v&&(m.startRow=b=v.start.y,m.startCol=g=v.start.x,this._cachedSearchTerm!==f&&(x=this._findInLine(f,m,p,!1),x||(m.startRow=b=v.end.y,m.startCol=g=v.end.x))),x||(x=this._findInLine(f,m,p,O)),!x){m.startCol=Math.max(m.startCol,this._terminal.cols);for(let y=b-1;y>=0&&(m.startRow=y,x=this._findInLine(f,m,p,O),!x);y--);}if(!x&&b!==this._terminal.buffer.active.baseY+this._terminal.rows-1)for(let y=this._terminal.buffer.active.baseY+this._terminal.rows-1;y>=b&&(m.startRow=y,x=this._findInLine(f,m,p,O),!x);y--);return this._selectResult(x,p?.decorations,p?.noScroll)}_initLinesCache(){const f=this._terminal;this._linesCache||(this._linesCache=new Array(f.buffer.active.length),this._linesCacheDisposables.value=(0,l.getDisposeArrayDisposable)([f.onLineFeed((()=>this._destroyLinesCache())),f.onCursorMove((()=>this._destroyLinesCache())),f.onResize((()=>this._destroyLinesCache()))])),window.clearTimeout(this._linesCacheTimeoutId),this._linesCacheTimeoutId=window.setTimeout((()=>this._destroyLinesCache()),15e3)}_destroyLinesCache(){this._linesCache=void 0,this._linesCacheDisposables.clear(),this._linesCacheTimeoutId&&(window.clearTimeout(this._linesCacheTimeoutId),this._linesCacheTimeoutId=0)}_isWholeWord(f,p,v){return(f===0||h.includes(p[f-1]))&&(f+v.length===p.length||h.includes(p[f+v.length]))}_findInLine(f,p,v={},b=!1){const g=this._terminal,O=p.startRow,m=p.startCol;if(g.buffer.active.getLine(O)?.isWrapped)return b?void(p.startCol+=g.cols):(p.startRow--,p.startCol+=g.cols,this._findInLine(f,p,v));let y=this._linesCache?.[O];y||(y=this._translateBufferLineToStringWithWrap(O,!0),this._linesCache&&(this._linesCache[O]=y));const[k,C]=y,P=this._bufferColsToStringOffset(O,m),_=v.caseSensitive?f:f.toLowerCase(),T=v.caseSensitive?k:k.toLowerCase();let R=-1;if(v.regex){const L=RegExp(_,"g");let M;if(b)for(;M=L.exec(T.slice(0,P));)R=L.lastIndex-M[0].length,f=M[0],L.lastIndex-=f.length-1;else M=L.exec(T.slice(P)),M&&M[0].length>0&&(R=P+(L.lastIndex-M[0].length),f=M[0])}else b?P-_.length>=0&&(R=T.lastIndexOf(_,P-_.length)):R=T.indexOf(_,P);if(R>=0){if(v.wholeWord&&!this._isWholeWord(R,T,f))return;let L=0;for(;L<C.length-1&&R>=C[L+1];)L++;let M=L;for(;M<C.length-1&&R+f.length>=C[M+1];)M++;const E=R-C[L],B=R+f.length-C[M],U=this._stringLengthToBufferSize(O+L,E);return{term:f,col:U,row:O+L,size:this._stringLengthToBufferSize(O+M,B)-U+g.cols*(M-L)}}}_stringLengthToBufferSize(f,p){const v=this._terminal.buffer.active.getLine(f);if(!v)return 0;for(let b=0;b<p;b++){const g=v.getCell(b);if(!g)break;const O=g.getChars();O.length>1&&(p-=O.length-1);const m=v.getCell(b+1);m&&m.getWidth()===0&&p++}return p}_bufferColsToStringOffset(f,p){const v=this._terminal;let b=f,g=0,O=v.buffer.active.getLine(b);for(;p>0&&O;){for(let m=0;m<p&&m<v.cols;m++){const x=O.getCell(m);if(!x)break;x.getWidth()&&(g+=x.getCode()===0?1:x.getChars().length)}if(b++,O=v.buffer.active.getLine(b),O&&!O.isWrapped)break;p-=v.cols}return g}_translateBufferLineToStringWithWrap(f,p){const v=this._terminal,b=[],g=[0];let O=v.buffer.active.getLine(f);for(;O;){const m=v.buffer.active.getLine(f+1),x=!!m&&m.isWrapped;let y=O.translateToString(!x&&p);if(x&&m){const k=O.getCell(O.length-1);k&&k.getCode()===0&&k.getWidth()===1&&m.getCell(0)?.getWidth()===2&&(y=y.slice(0,-1))}if(b.push(y),!x)break;g.push(g[g.length-1]+y.length),f++,O=m}return[b.join(""),g]}_selectResult(f,p,v){const b=this._terminal;if(this._selectedDecoration.clear(),!f)return b.clearSelection(),!1;if(b.select(f.col,f.row,f.size),p){const g=b.registerMarker(-b.buffer.active.baseY-b.buffer.active.cursorY+f.row);if(g){const O=b.registerDecoration({marker:g,x:f.col,width:f.size,backgroundColor:p.activeMatchBackground,layer:"top",overviewRulerOptions:{color:p.activeMatchColorOverviewRuler}});if(O){const m=[];m.push(g),m.push(O.onRender((x=>this._applyStyles(x,p.activeMatchBorder,!0)))),m.push(O.onDispose((()=>(0,l.disposeArray)(m)))),this._selectedDecoration.value={decoration:O,match:f,dispose(){O.dispose()}}}}}if(!v&&(f.row>=b.buffer.active.viewportY+b.rows||f.row<b.buffer.active.viewportY)){let g=f.row-b.buffer.active.viewportY;g-=Math.floor(b.rows/2),b.scrollLines(g)}return!0}_applyStyles(f,p,v){f.classList.contains("xterm-find-result-decoration")||(f.classList.add("xterm-find-result-decoration"),p&&(f.style.outline=`1px solid ${p}`)),v&&f.classList.add("xterm-find-active-result-decoration")}_createResultDecoration(f,p){const v=this._terminal,b=v.registerMarker(-v.buffer.active.baseY-v.buffer.active.cursorY+f.row);if(!b)return;const g=v.registerDecoration({marker:b,x:f.col,width:f.size,backgroundColor:p.matchBackground,overviewRulerOptions:this._highlightedLines.has(b.line)?void 0:{color:p.matchOverviewRuler,position:"center"}});if(g){const O=[];O.push(b),O.push(g.onRender((m=>this._applyStyles(m,p.matchBorder,!1)))),O.push(g.onDispose((()=>(0,l.disposeArray)(O))))}return g}}a.SearchAddon=d})(),n})()))})(xf)),xf.exports}var fD=uD(),bf={exports:{}},cv;function mD(){return cv||(cv=1,(function(s,e){(function(t,r){s.exports=r()})(self,(()=>(()=>{var t={6:(a,o)=>{function l(d){try{const u=new URL(d),f=u.password&&u.username?`${u.protocol}//${u.username}:${u.password}@${u.host}`:u.username?`${u.protocol}//${u.username}@${u.host}`:`${u.protocol}//${u.host}`;return d.toLocaleLowerCase().startsWith(f.toLocaleLowerCase())}catch{return!1}}Object.defineProperty(o,"__esModule",{value:!0}),o.LinkComputer=o.WebLinkProvider=void 0,o.WebLinkProvider=class{constructor(d,u,f,p={}){this._terminal=d,this._regex=u,this._handler=f,this._options=p}provideLinks(d,u){const f=h.computeLink(d,this._regex,this._terminal,this._handler);u(this._addCallbacks(f))}_addCallbacks(d){return d.map((u=>(u.leave=this._options.leave,u.hover=(f,p)=>{if(this._options.hover){const{range:v}=u;this._options.hover(f,p,v)}},u)))}};class h{static computeLink(u,f,p,v){const b=new RegExp(f.source,(f.flags||"")+"g"),[g,O]=h._getWindowedLineStrings(u-1,p),m=g.join("");let x;const y=[];for(;x=b.exec(m);){const k=x[0];if(!l(k))continue;const[C,P]=h._mapStrIdx(p,O,0,x.index),[_,T]=h._mapStrIdx(p,C,P,k.length);if(C===-1||P===-1||_===-1||T===-1)continue;const R={start:{x:P+1,y:C+1},end:{x:T,y:_+1}};y.push({range:R,text:k,activate:v})}return y}static _getWindowedLineStrings(u,f){let p,v=u,b=u,g=0,O="";const m=[];if(p=f.buffer.active.getLine(u)){const x=p.translateToString(!0);if(p.isWrapped&&x[0]!==" "){for(g=0;(p=f.buffer.active.getLine(--v))&&g<2048&&(O=p.translateToString(!0),g+=O.length,m.push(O),p.isWrapped&&O.indexOf(" ")===-1););m.reverse()}for(m.push(x),g=0;(p=f.buffer.active.getLine(++b))&&p.isWrapped&&g<2048&&(O=p.translateToString(!0),g+=O.length,m.push(O),O.indexOf(" ")===-1););}return[m,v]}static _mapStrIdx(u,f,p,v){const b=u.buffer.active,g=b.getNullCell();let O=p;for(;v;){const m=b.getLine(f);if(!m)return[-1,-1];for(let x=O;x<m.length;++x){m.getCell(x,g);const y=g.getChars();if(g.getWidth()&&(v-=y.length||1,x===m.length-1&&y==="")){const k=b.getLine(f+1);k&&k.isWrapped&&(k.getCell(0,g),g.getWidth()===2&&(v+=1))}if(v<0)return[f,x]}f++,O=0}return[f,O]}}o.LinkComputer=h}},r={};function i(a){var o=r[a];if(o!==void 0)return o.exports;var l=r[a]={exports:{}};return t[a](l,l.exports,i),l.exports}var n={};return(()=>{var a=n;Object.defineProperty(a,"__esModule",{value:!0}),a.WebLinksAddon=void 0;const o=i(6),l=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function h(d,u){const f=window.open();if(f){try{f.opener=null}catch{}f.location.href=u}else console.warn("Opening link blocked as opener could not be cleared")}a.WebLinksAddon=class{constructor(d=h,u={}){this._handler=d,this._options=u}activate(d){this._terminal=d;const u=this._options,f=u.urlRegex||l;this._linkProvider=this._terminal.registerLinkProvider(new o.WebLinkProvider(this._terminal,f,this._handler,u))}dispose(){this._linkProvider?.dispose()}}})(),n})()))})(bf)),bf.exports}var pD=mD();function vf(s,e){try{return getComputedStyle(document.documentElement).getPropertyValue(s).trim()||e}catch{return e}}function hv(s){return typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC")?s.metaKey:s.ctrlKey}function Q_(s){return!s||s.includes(" ")||/^https?:\/\//i.test(s)?!1:/^[a-zA-Z]:[\\/]/.test(s)||s.startsWith("/")||s.startsWith("~/")||s.startsWith("./")||s.startsWith("../")?!0:/^[\w./\\-]+\.[a-zA-Z0-9]{1,8}$/.test(s)}function dv(s,e){const t=s.trim().replace(/\\/g,"/");return!t||!Q_(t)?null:/^[a-zA-Z]:\//.test(t)||t.startsWith("~/")?t:t.startsWith("/")?/^\/packages\//.test(t)?!e||e==="/"?null:bO(t.slice(1),e):t:!e||e==="/"?null:bO(t,e)}function uv(s){return s.clientWidth>=16&&s.clientHeight>=16}async function gD(s,e){try{const r=(await te.files.check([s]))?.results?.[s];if(!r?.exists||!r?.isFile)return;e?.(s)}catch{e?.(s)}}function OD({terminalId:s,title:e,cwd:t,active:r=!0,onMeta:i,onSelection:n,onOpenUrl:a,onOpenPath:o,apiRef:l}){const{t:h}=Pt("common"),d=S.useRef(null),u=S.useRef(null),f=S.useRef(null),p=S.useRef(null),v=S.useRef(i),b=S.useRef(n),g=S.useRef(a),O=S.useRef(o),m=S.useRef(t);v.current=i,b.current=n,g.current=a,O.current=o,S.useEffect(()=>{t&&t!=="/"&&(m.current=t)},[t]);const[x,y]=S.useState(null),[k,C]=S.useState(!1),[P,_]=S.useState(""),[T,R]=S.useState(!1),L=S.useRef(!0),M=S.useCallback(()=>{const B=d.current,U=u.current,F=f.current;if(!B||!U||!F||!uv(B))return!1;try{return F.fit(),!0}catch{return!1}},[]),E=S.useCallback(()=>{const B=u.current;B&&(B.scrollToBottom(),L.current=!0,R(!1))},[]);return S.useEffect(()=>{Gk(s);const B=d.current,U=window.markusDesktop?.terminal;if(!B)return;if(!U){y("desktopOnly");return}let F=!1,X=null,ae=null,j,W,D,V=null,se=null,fe=null,z=null;const re=async()=>{if(F||!d.current)return;if(!uv(d.current)){z=window.setTimeout(()=>{re()},50);return}const Z=vf("--color-surface-primary","#0f1419"),A=vf("--color-fg-primary","#e7e9ea");X=new cD.Terminal({cursorBlink:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:13,lineHeight:1.25,allowProposedApi:!0,theme:{background:Z,foreground:A,cursor:vf("--color-brand-500","#3b82f6"),selectionBackground:"rgba(59, 130, 246, 0.35)"}});const J=new dD.FitAddon,Y=new fD.SearchAddon,oe=new pD.WebLinksAddon((K,pe)=>{hv(K)&&g.current?.(pe)});if(X.loadAddon(J),X.loadAddon(Y),X.loadAddon(oe),X.open(d.current),u.current=X,f.current=J,p.current=Y,!M())try{J.fit()}catch{}X.registerLinkProvider({provideLinks:(K,pe)=>{const je=X.buffer.active.getLine(K-1);if(!je){pe(void 0);return}const we=je.translateToString(!0),Ge=/(?:(?:[A-Za-z]:|\/|~\/)[\w./\\-]+|(?:\.\.?\/)?[\w./\\-]+\.[a-zA-Z0-9]{1,8})/g,Qe=[];let Ee;for(;Ee=Ge.exec(we);){const ye=Ee[0];Q_(ye)&&dv(ye,m.current)&&Qe.push({range:{start:{x:Ee.index+1,y:K},end:{x:Ee.index+ye.length,y:K}},text:ye,decorations:{pointerCursor:!0,underline:!0},activate:G=>{if(!hv(G))return;const qe=dv(ye,m.current);qe&&gD(qe,O.current)}})}pe(Qe.length?Qe:void 0)}});try{const K=Math.max(X.cols||80,2),pe=Math.max(X.rows||24,1);let je=t||m.current;if(!je||je==="/")try{je=await window.markusDesktop?.getDefaultCwd?.()}catch{}je==="/"&&(je=void 0),je&&(m.current=je);const we=await U.create(s,{cwd:je,title:e,cols:K,rows:pe});if(F)return;if(!we.ok){y(we.error||"createFailed");return}we.info&&(we.info.cwd&&(m.current=we.info.cwd),v.current?.(s,{title:we.info.title,cwd:we.info.cwd}));const Ge=await U.getBuffer(s,{maxChars:12e4});if(F)return;const Qe=Ge.ok?Ge.content:void 0;if(Qe&&(await new Promise(Ee=>{let ye=!1,G;const qe=()=>{ye||(ye=!0,G!==void 0&&window.clearTimeout(G),Ee())};G=window.setTimeout(qe,1500);try{X.write(Qe,qe)}catch{qe()}}),F))return;M(),U.resize(s,X.cols,X.rows),X.focus()}catch(K){F||y(K instanceof Error?K.message:String(K));return}j=U.onData?.(K=>{K.id!==s||!u.current||(u.current.write(K.data),L.current||R(!0))}),D=U.onEvent?.(K=>{K.id!==s||K.type!=="cwd"||!K.cwd||(m.current=K.cwd,v.current?.(s,{cwd:K.cwd}))}),W=U.onExit?.(()=>{}),V=X.onData(K=>{U.write(s,K)}),se=X.onScroll(()=>{const K=u.current;if(!K)return;const pe=K.buffer.active,je=pe.viewportY>=pe.baseY-1;L.current=je,je&&R(!1)}),fe=X.onSelectionChange(()=>{const K=u.current,pe=d.current;if(!K||!pe)return;if(!K.getSelection().trim()){b.current?.(null);return}requestAnimationFrame(()=>{const we=u.current,Ge=d.current;if(!we||!Ge)return;const Qe=we.getSelection().trim();if(!Qe){b.current?.(null);return}let Ee,ye;const G=Ge.querySelectorAll(".xterm-selection div");let qe=1/0,He=1/0,Ye=-1/0;if(G.forEach(pt=>{const xt=pt.getBoundingClientRect();xt.width<1&&xt.height<1||(qe=Math.min(qe,xt.top),He=Math.min(He,xt.left),Ye=Math.max(Ye,xt.right))}),qe<1/0)Ee=(He+Ye)/2,ye=qe;else{const pt=we.getSelectionPosition?.(),bt=(Ge.querySelector(".xterm-screen")??Ge).getBoundingClientRect(),vt=Math.max(we.cols,1),Pe=Math.max(we.rows,1),Et=bt.width/vt,Ft=bt.height/Pe;if(pt){const Es=we.buffer.active.viewportY,rt=Math.max(0,pt.start.y-Es);Ee=bt.left+(pt.start.x+.5)*Et,ye=bt.top+rt*Ft}else Ee=bt.left+bt.width/2,ye=bt.top+12}b.current?.({text:Qe,x:Ee,y:ye})})}),ae=new ResizeObserver(()=>{!M()||!u.current||U.resize(s,u.current.cols,u.current.rows)}),ae.observe(d.current),l&&(l.current={getSelection:()=>u.current?.getSelection()??"",getRecentOutput:async(K=80)=>{const pe=await U.getBuffer(s,{maxLines:K});return pe.ok&&pe.content||""},focus:()=>u.current?.focus(),findNext:K=>{p.current?.findNext(K)},clearSelection:()=>u.current?.clearSelection()})};return re(),()=>{F=!0,z!=null&&window.clearTimeout(z),j?.(),W?.(),D?.(),V?.dispose(),se?.dispose(),fe?.dispose(),ae?.disconnect(),l&&(l.current=null);try{X?.dispose()}catch{}u.current=null,f.current=null,p.current=null}},[s]),S.useEffect(()=>{if(!r)return;const B=window.requestAnimationFrame(()=>{M();const U=u.current;U&&(window.markusDesktop?.terminal?.resize(s,U.cols,U.rows),U.focus())});return()=>window.cancelAnimationFrame(B)},[r,s,M]),S.useEffect(()=>{const B=U=>{if(!r)return;if((navigator.platform.toUpperCase().includes("MAC")?U.metaKey&&!U.ctrlKey:U.ctrlKey&&!U.metaKey)&&!U.altKey&&!U.shiftKey&&U.key.toLowerCase()==="f"){const ae=U.target;ae instanceof HTMLElement&&(d.current?.contains(ae)||ae.closest(".xterm"))&&(U.preventDefault(),C(!0))}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[r]),c.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col rounded-lg overflow-hidden border border-border-default bg-surface-primary",children:[k&&c.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 px-2 py-1.5 border-b border-border-default bg-surface-elevated",children:[c.jsx("input",{autoFocus:!0,value:P,onChange:B=>_(B.target.value),onKeyDown:B=>{B.key==="Enter"?(B.preventDefault(),p.current?.findNext(P)):B.key==="Escape"&&C(!1)},placeholder:h("terminal.searchPlaceholder"),className:"flex-1 min-w-0 text-xs bg-transparent outline-none text-fg-primary placeholder:text-fg-muted"}),c.jsx("button",{type:"button",className:"text-[11px] px-2 py-0.5 rounded text-fg-secondary hover:bg-surface-overlay",onClick:()=>p.current?.findNext(P),children:h("terminal.searchNext")}),c.jsx("button",{type:"button",className:"text-[11px] px-2 py-0.5 rounded text-fg-tertiary hover:bg-surface-overlay",onClick:()=>C(!1),children:"Esc"})]}),x?c.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-2 p-6 text-center",children:[c.jsxs("svg",{className:"w-8 h-8 text-fg-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,"aria-hidden":"true",children:[c.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 9l3 3-3 3M13 15h4"})]}),x==="desktopOnly"?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"text-sm font-medium text-fg-secondary",children:h("terminal.desktopOnlyTitle")}),c.jsx("p",{className:"text-xs text-fg-muted max-w-xs",children:h("terminal.desktopOnlyDesc")})]}):c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"text-sm font-medium text-fg-secondary",children:h("terminal.createFailedTitle")}),c.jsx("p",{className:"text-xs text-fg-muted max-w-xs break-words",children:x==="createFailed"?h("terminal.createFailedDesc"):x})]})]}):c.jsx("div",{ref:d,className:"flex-1 min-h-0 w-full h-full [&_.xterm]:h-full [&_.xterm]:w-full [&_.xterm-viewport]:overflow-auto"}),T&&c.jsx("button",{type:"button",onClick:E,className:"absolute bottom-3 right-3 z-10 text-[11px] px-2.5 py-1 rounded-md bg-brand-600 text-white shadow-lg hover:bg-brand-500",children:h("terminal.jumpToBottom")})]})}const xD=8;function bD(s){const{left:e,width:t,viewport:r}=s,i=Math.max(0,t-r);if(i<=0||t<=0||r<=0)return{visible:!1,leftPct:0,widthPct:0,overflow:0};const n=Math.max(xD,r/t*100);return{visible:!0,leftPct:Math.max(0,Math.min(100-n,e/t*100)),widthPct:n,overflow:i}}const fv=(s,e,t)=>Math.max(e,Math.min(t,s));function vD({scrollRef:s,watch:e}){const[t,r]=S.useState({left:0,width:0,viewport:0}),i=S.useRef(null),n=S.useRef(null),a=S.useCallback(()=>{const u=s.current;if(!u)return;const f={left:u.scrollLeft,width:u.scrollWidth,viewport:u.clientWidth};r(p=>p.left===f.left&&p.width===f.width&&p.viewport===f.viewport?p:f)},[s]);S.useEffect(()=>{const u=s.current;if(!u)return;a(),u.addEventListener("scroll",a,{passive:!0});const f=new ResizeObserver(a);f.observe(u);for(const p of Array.from(u.children))f.observe(p);return()=>{u.removeEventListener("scroll",a),f.disconnect()}},[s,a,e]);const o=bD(t),l=u=>{const f=s.current,p=i.current;if(!f||!p||!o.visible||u.button!==0)return;const v=p.getBoundingClientRect();if(v.width<=0)return;const b=o.widthPct/100*v.width,g=o.leftPct/100*v.width,O=u.clientX-v.left;if(O<g||O>g+b){const m=f.scrollWidth/v.width;f.scrollLeft=fv((O-b/2)*m,0,o.overflow)}n.current={pointerId:u.pointerId,startX:u.clientX,startLeft:f.scrollLeft};try{p.setPointerCapture(u.pointerId)}catch{}u.preventDefault(),u.stopPropagation()},h=u=>{const f=n.current,p=s.current,v=i.current;if(!f||f.pointerId!==u.pointerId||!p||!v)return;const b=v.getBoundingClientRect();if(b.width<=0)return;const g=p.scrollWidth/b.width;p.scrollLeft=fv(f.startLeft+(u.clientX-f.startX)*g,0,o.overflow)},d=u=>{const f=n.current;if(!(!f||f.pointerId!==u.pointerId)){n.current=null;try{i.current?.releasePointerCapture(u.pointerId)}catch{}}};return o.visible?c.jsx("div",{ref:i,"aria-hidden":!0,"data-tab-scroll-rail":!0,className:"relative h-[3px] mt-[3px] mx-1 shrink-0 rounded-full bg-border-default/30 cursor-pointer select-none",onPointerDown:l,onPointerMove:h,onPointerUp:d,onPointerCancel:d,children:c.jsx("div",{className:"absolute top-0 h-full rounded-full bg-fg-muted/60 hover:bg-fg-secondary transition-colors",style:{left:`${o.leftPct}%`,width:`${o.widthPct}%`}})}):null}function mv(s){return/^(https?|file):\/\//i.test(s)?s:/^[a-zA-Z]:[\\/]/.test(s)?`file:///${s.replace(/\\/g,"/")}`:`file://${s.startsWith("/")?s:`/${s}`}`}function uo(s){return/^https?:\/\//i.test(s)}function yD(s){return s.kind==="deliverable"?s.deliverable.reference??"":s.kind==="url"?s.url:s.kind==="terminal"?s.terminalId:s.path}function SD(s){return s.kind==="deliverable"?s.deliverable.title||s.deliverable.reference||"":s.kind==="url"?s.title||s.url:s.kind==="terminal"?s.title||"Terminal":s.title||s.path.split(/[/\\]/).pop()||s.path}function wD(s,e){if(s.kind==="file")return`file:${s.path}:${e??""}`;if(s.kind==="url")return`url:${s.browserId||s.url}:${e??""}`;if(s.kind==="terminal")return`terminal:${s.terminalId}:${e??""}`;const t=s.deliverable;return`deliverable:${t.id||t.reference||t.title||"unknown"}:${e??""}`}function yf(s){return s==null||!Number.isFinite(s)?"":s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`}function _D(s){const e=s.includes("\\")?"\\":"/",t=s.lastIndexOf(e);return t<=0?e==="/"?"/":s.slice(0,2):s.slice(0,t)}function kD({payload:s,onClose:e,width:t,onResizeStart:r,onAddToChat:i,tabs:n,activeTabId:a,onSelectTab:o,onCloseTab:l,onNewTab:h,fullscreen:d,onToggleFullscreen:u,onBrowserMeta:f,panelMode:p="browser",onPanelModeChange:v,onTerminalMeta:b,onOpenUrlFromTerminal:g,onOpenPathFromTerminal:O}){const{t:m}=Pt(["deliverables","agent","common"]),[x,y]=S.useState({mode:"loading"}),[k,C]=S.useState(null),[P,_]=S.useState(!1),[T,R]=S.useState(!1),[L,M]=S.useState(null),[E,B]=S.useState(null),[U,F]=S.useState({}),[X,ae]=S.useState({}),[j,W]=S.useState(!1),[D,V]=S.useState(0),[se,fe]=S.useState(!0),z=S.useRef(null),re=S.useRef(null),Z=S.useRef(null),A=S.useRef(null),J=S.useRef(null),Y=S.useRef(!1);Y.current=j;const oe=S.useCallback(()=>b_(Y.current,m("common:fileEditor.discardConfirm",{defaultValue:"Discard unsaved changes?"})),[m]);S.useEffect(()=>{let he=!1;te.browser.tabOwnership().then($e=>{if(he)return;const Xe={};for(const de of $e.ownership??[])Xe[de.pageId]={agentId:de.agentId,agentName:de.agentName||de.agentId};F(Xe)}).catch(()=>{});const ce=St.on("ui:browser_ownership",$e=>{const Xe=$e.payload;typeof Xe.pageId=="number"&&F(de=>{if(Xe.action==="released"||!Xe.agentId){if(!(Xe.pageId in de))return de;const De={...de};return delete De[Xe.pageId],De}return{...de,[Xe.pageId]:{agentId:Xe.agentId,agentName:Xe.agentName||Xe.agentId}}})});return()=>{he=!0,ce()}},[]),S.useEffect(()=>{let he=!1;te.terminal?.sessionOwnership?.().then($e=>{if(he)return;const Xe={};for(const de of $e.ownership??[])Xe[de.terminalId]={agentId:de.agentId,agentName:de.agentName||de.agentId};ae(Xe)}).catch(()=>{});const ce=St.on("ui:terminal_ownership",$e=>{const Xe=$e.payload;typeof Xe.terminalId=="string"&&ae(de=>{if(Xe.action==="released"||!Xe.agentId){if(!(Xe.terminalId in de))return de;const De={...de};return delete De[Xe.terminalId],De}return{...de,[Xe.terminalId]:{agentId:Xe.agentId,agentName:Xe.agentName||Xe.agentId}}})});return()=>{he=!0,ce()}},[]);const K=yD(s),pe=SD(s),je=k??K,we=(n?.length??0)>=1,Ge=wD(s,a),Qe=(s.kind==="file"||s.kind==="deliverable")&&!!K&&!uo(K)&&!(s.kind==="deliverable"&&s.deliverable.artifactType),Ee=je||K,ye=S.useCallback(()=>{oe()&&(z.current=null,V(he=>he+1))},[oe]);S.useEffect(()=>{if(!Qe||!Ee||x.mode==="loading")return;let he=!1;return te.files.stat(Ee).then(ce=>{he||!ce.exists||(z.current={path:ce.path||Ee,mtimeMs:ce.mtimeMs??0,size:ce.size??0})}).catch(()=>{}),()=>{he=!0}},[Qe,Ee,x,D]),S.useEffect(()=>{if(!se||!Qe||!Ee||j)return;let he=!1;const ce=async()=>{const De=z.current;if(!(!De||De.path!==Ee))try{const ve=await te.files.stat(Ee);if(he||!ve.exists)return;((ve.mtimeMs??0)!==De.mtimeMs||(ve.size??0)!==De.size)&&V(st=>st+1)}catch{}},$e=window.setInterval(()=>{ce()},5e3),Xe=()=>{ce()},de=()=>{document.visibilityState==="visible"&&ce()};return window.addEventListener("focus",Xe),document.addEventListener("visibilitychange",de),()=>{he=!0,window.clearInterval($e),window.removeEventListener("focus",Xe),document.removeEventListener("visibilitychange",de)}},[se,Qe,Ee,j]),S.useEffect(()=>{if(!a)return;const he=A.current,ce=Z.current;if(!he||!ce)return;const $e=requestAnimationFrame(()=>{he.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame($e)},[a,n?.length]),S.useEffect(()=>{const he=ce=>{if(ce.key==="Escape"){if(!oe())return;d&&u?u():e()}};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e,d,u,oe]),S.useEffect(()=>{let he=!1;return B(null),W(!1),M(null),s.kind==="url"?(y({mode:"url",url:s.url,browserId:s.browserId}),()=>{he=!0}):s.kind==="terminal"?(y({mode:"terminal",terminalId:s.terminalId,title:s.title,cwd:s.cwd}),()=>{he=!0}):uo(K)?(y({mode:"url",url:K}),()=>{he=!0}):(y({mode:"loading"}),s.kind==="deliverable"&&s.deliverable.artifactType&&s.deliverable.artifactData?(y({mode:"artifact",summary:s.deliverable.summary||s.deliverable.title||""}),()=>{he=!0}):je?(te.files.preview(je).then(ce=>{if(he)return;if(ce.type==="directory"&&Array.isArray(ce.entries)){y({mode:"directory",path:ce.path,name:ce.name,entries:ce.entries});return}if(ce.type==="image"){const Xe=ce.content?`data:${ce.mimeType||"image/png"};base64,${ce.content}`:ce.streamUrl||(ce.path?te.files.streamUrl(ce.path):te.files.streamUrl(je));y({mode:"image",src:Xe,name:ce.name||pe});return}if(ce.type==="audio"){const Xe=ce.streamUrl||(ce.path?te.files.streamUrl(ce.path):te.files.streamUrl(je));y({mode:"audio",src:Xe,name:ce.name||pe,mimeType:ce.mimeType||"audio/mpeg",size:ce.size});return}if(ce.type==="video"){const Xe=ce.streamUrl||(ce.path?te.files.streamUrl(ce.path):te.files.streamUrl(je));y({mode:"video",src:Xe,name:ce.name||pe,mimeType:ce.mimeType||"video/mp4",size:ce.size});return}if(ce.type==="binary"){y({mode:"binary",name:ce.name||pe,reference:ce.path||je,size:ce.size,extension:ce.extension});return}if(ce.type==="office"){const Xe=ce.streamUrl||(ce.path?te.files.streamUrl(ce.path):te.files.streamUrl(je));y({mode:"office",format:ce.format||String(ce.extension||"").replace(/^\./,"")||"pdf",streamUrl:Xe,name:ce.name||pe,size:ce.size,reference:ce.path||je});return}if(typeof ce.content!="string"){y({mode:"unpreviewable",reference:je,isDirectory:!1});return}const $e=zC({format:s.kind==="deliverable"?s.deliverable.format:void 0,reference:K,content:ce.content});y({mode:"content",content:ce.content,format:$e})}).catch(()=>{he||y({mode:"unpreviewable",reference:je,isDirectory:!1})}),()=>{he=!0}):(y({mode:"unpreviewable",reference:"",isDirectory:!1}),()=>{he=!0}))},[Ge,s,je,K,pe,D]),S.useEffect(()=>{C(null)},[Ge]);const G=pe||je,qe=S.useCallback((he,ce)=>{const $e=he.length>40?`${he.slice(0,24)}…${he.slice(-12)}`:he;return ce?{label:`🌐 ${$e}`,content:["[html-selection]",`Text: "${he}"`,`CSS Selector: ${ce.cssSelector}`,`XPath: ${ce.xpath}`,K?`File: ${K}`:""].filter(Boolean).join(`
|
|
48
|
+
`,m)}paste(O){this._core.paste(O)}refresh(O,m){this._verifyIntegers(O,m),this._core.refresh(O,m)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(O){this._addonManager.loadAddon(this,O)}static get strings(){return o}_verifyIntegers(...O){for(const m of O)if(m===1/0||isNaN(m)||m%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...O){for(const m of O)if(m&&(m===1/0||isNaN(m)||m%1!=0||m<0))throw new Error("This API only accepts positive integers")}}a.Terminal=b})(),n})()))})(gf)),gf.exports}var cD=lD(),Of={exports:{}},av;function hD(){return av||(av=1,(function(s,e){(function(t,r){s.exports=r()})(self,(()=>(()=>{var t={};return(()=>{var r=t;Object.defineProperty(r,"__esModule",{value:!0}),r.FitAddon=void 0,r.FitAddon=class{activate(i){this._terminal=i}dispose(){}fit(){const i=this.proposeDimensions();if(!i||!this._terminal||isNaN(i.cols)||isNaN(i.rows))return;const n=this._terminal._core;this._terminal.rows===i.rows&&this._terminal.cols===i.cols||(n._renderService.clear(),this._terminal.resize(i.cols,i.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const i=this._terminal._core,n=i._renderService.dimensions;if(n.css.cell.width===0||n.css.cell.height===0)return;const a=this._terminal.options.scrollback===0?0:i.viewport.scrollBarWidth,o=window.getComputedStyle(this._terminal.element.parentElement),l=parseInt(o.getPropertyValue("height")),h=Math.max(0,parseInt(o.getPropertyValue("width"))),d=window.getComputedStyle(this._terminal.element),u=l-(parseInt(d.getPropertyValue("padding-top"))+parseInt(d.getPropertyValue("padding-bottom"))),f=h-(parseInt(d.getPropertyValue("padding-right"))+parseInt(d.getPropertyValue("padding-left")))-a;return{cols:Math.max(2,Math.floor(f/n.css.cell.width)),rows:Math.max(1,Math.floor(u/n.css.cell.height))}}}})(),t})()))})(Of)),Of.exports}var dD=hD(),xf={exports:{}},lv;function uD(){return lv||(lv=1,(function(s,e){(function(t,r){s.exports=r()})(self,(()=>(()=>{var t={345:(a,o)=>{Object.defineProperty(o,"__esModule",{value:!0}),o.runAndSubscribe=o.forwardEvent=o.EventEmitter=void 0,o.EventEmitter=class{constructor(){this._listeners=[],this._disposed=!1}get event(){return this._event||(this._event=l=>(this._listeners.push(l),{dispose:()=>{if(!this._disposed){for(let h=0;h<this._listeners.length;h++)if(this._listeners[h]===l)return void this._listeners.splice(h,1)}}})),this._event}fire(l,h){const d=[];for(let u=0;u<this._listeners.length;u++)d.push(this._listeners[u]);for(let u=0;u<d.length;u++)d[u].call(void 0,l,h)}dispose(){this.clearListeners(),this._disposed=!0}clearListeners(){this._listeners&&(this._listeners.length=0)}},o.forwardEvent=function(l,h){return l((d=>h.fire(d)))},o.runAndSubscribe=function(l,h){return h(void 0),l((d=>h(d)))}},859:(a,o)=>{function l(h){for(const d of h)d.dispose();h.length=0}Object.defineProperty(o,"__esModule",{value:!0}),o.getDisposeArrayDisposable=o.disposeArray=o.toDisposable=o.MutableDisposable=o.Disposable=void 0,o.Disposable=class{constructor(){this._disposables=[],this._isDisposed=!1}dispose(){this._isDisposed=!0;for(const h of this._disposables)h.dispose();this._disposables.length=0}register(h){return this._disposables.push(h),h}unregister(h){const d=this._disposables.indexOf(h);d!==-1&&this._disposables.splice(d,1)}},o.MutableDisposable=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(h){this._isDisposed||h===this._value||(this._value?.dispose(),this._value=h)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,this._value?.dispose(),this._value=void 0}},o.toDisposable=function(h){return{dispose:h}},o.disposeArray=l,o.getDisposeArrayDisposable=function(h){return{dispose:()=>l(h)}}}},r={};function i(a){var o=r[a];if(o!==void 0)return o.exports;var l=r[a]={exports:{}};return t[a](l,l.exports,i),l.exports}var n={};return(()=>{var a=n;Object.defineProperty(a,"__esModule",{value:!0}),a.SearchAddon=void 0;const o=i(345),l=i(859),h=" ~!@#$%^&*()+`-=[]{}|\\;:\"',./<>?";class d extends l.Disposable{constructor(f){super(),this._highlightedLines=new Set,this._highlightDecorations=[],this._selectedDecoration=this.register(new l.MutableDisposable),this._linesCacheTimeoutId=0,this._linesCacheDisposables=new l.MutableDisposable,this._onDidChangeResults=this.register(new o.EventEmitter),this.onDidChangeResults=this._onDidChangeResults.event,this._highlightLimit=f?.highlightLimit??1e3}activate(f){this._terminal=f,this.register(this._terminal.onWriteParsed((()=>this._updateMatches()))),this.register(this._terminal.onResize((()=>this._updateMatches()))),this.register((0,l.toDisposable)((()=>this.clearDecorations())))}_updateMatches(){this._highlightTimeout&&window.clearTimeout(this._highlightTimeout),this._cachedSearchTerm&&this._lastSearchOptions?.decorations&&(this._highlightTimeout=setTimeout((()=>{const f=this._cachedSearchTerm;this._cachedSearchTerm=void 0,this.findPrevious(f,{...this._lastSearchOptions,incremental:!0,noScroll:!0})}),200))}clearDecorations(f){this._selectedDecoration.clear(),(0,l.disposeArray)(this._highlightDecorations),this._highlightDecorations=[],this._highlightedLines.clear(),f||(this._cachedSearchTerm=void 0)}clearActiveDecoration(){this._selectedDecoration.clear()}findNext(f,p){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");const v=!this._lastSearchOptions||this._didOptionsChange(this._lastSearchOptions,p);this._lastSearchOptions=p,p?.decorations&&(this._cachedSearchTerm===void 0||f!==this._cachedSearchTerm||v)&&this._highlightAllMatches(f,p);const b=this._findNextAndSelect(f,p);return this._fireResults(p),this._cachedSearchTerm=f,b}_highlightAllMatches(f,p){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");if(!f||f.length===0)return void this.clearDecorations();p=p||{},this.clearDecorations(!0);const v=[];let b,g=this._find(f,0,0,p);for(;g&&(b?.row!==g.row||b?.col!==g.col)&&!(v.length>=this._highlightLimit);)b=g,v.push(b),g=this._find(f,b.col+b.term.length>=this._terminal.cols?b.row+1:b.row,b.col+b.term.length>=this._terminal.cols?0:b.col+1,p);for(const O of v){const m=this._createResultDecoration(O,p.decorations);m&&(this._highlightedLines.add(m.marker.line),this._highlightDecorations.push({decoration:m,match:O,dispose(){m.dispose()}}))}}_find(f,p,v,b){if(!this._terminal||!f||f.length===0)return this._terminal?.clearSelection(),void this.clearDecorations();if(v>this._terminal.cols)throw new Error(`Invalid col: ${v} to search in terminal of ${this._terminal.cols} cols`);let g;this._initLinesCache();const O={startRow:p,startCol:v};if(g=this._findInLine(f,O,b),!g)for(let m=p+1;m<this._terminal.buffer.active.baseY+this._terminal.rows&&(O.startRow=m,O.startCol=0,g=this._findInLine(f,O,b),!g);m++);return g}_findNextAndSelect(f,p){if(!this._terminal||!f||f.length===0)return this._terminal?.clearSelection(),this.clearDecorations(),!1;const v=this._terminal.getSelectionPosition();this._terminal.clearSelection();let b=0,g=0;v&&(this._cachedSearchTerm===f?(b=v.end.x,g=v.end.y):(b=v.start.x,g=v.start.y)),this._initLinesCache();const O={startRow:g,startCol:b};let m=this._findInLine(f,O,p);if(!m)for(let x=g+1;x<this._terminal.buffer.active.baseY+this._terminal.rows&&(O.startRow=x,O.startCol=0,m=this._findInLine(f,O,p),!m);x++);if(!m&&g!==0)for(let x=0;x<g&&(O.startRow=x,O.startCol=0,m=this._findInLine(f,O,p),!m);x++);return!m&&v&&(O.startRow=v.start.y,O.startCol=0,m=this._findInLine(f,O,p)),this._selectResult(m,p?.decorations,p?.noScroll)}findPrevious(f,p){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");const v=!this._lastSearchOptions||this._didOptionsChange(this._lastSearchOptions,p);this._lastSearchOptions=p,p?.decorations&&(this._cachedSearchTerm===void 0||f!==this._cachedSearchTerm||v)&&this._highlightAllMatches(f,p);const b=this._findPreviousAndSelect(f,p);return this._fireResults(p),this._cachedSearchTerm=f,b}_didOptionsChange(f,p){return!!p&&(f.caseSensitive!==p.caseSensitive||f.regex!==p.regex||f.wholeWord!==p.wholeWord)}_fireResults(f){if(f?.decorations){let p=-1;if(this._selectedDecoration.value){const v=this._selectedDecoration.value.match;for(let b=0;b<this._highlightDecorations.length;b++){const g=this._highlightDecorations[b].match;if(g.row===v.row&&g.col===v.col&&g.size===v.size){p=b;break}}}this._onDidChangeResults.fire({resultIndex:p,resultCount:this._highlightDecorations.length})}}_findPreviousAndSelect(f,p){if(!this._terminal)throw new Error("Cannot use addon until it has been loaded");if(!this._terminal||!f||f.length===0)return this._terminal?.clearSelection(),this.clearDecorations(),!1;const v=this._terminal.getSelectionPosition();this._terminal.clearSelection();let b=this._terminal.buffer.active.baseY+this._terminal.rows-1,g=this._terminal.cols;const O=!0;this._initLinesCache();const m={startRow:b,startCol:g};let x;if(v&&(m.startRow=b=v.start.y,m.startCol=g=v.start.x,this._cachedSearchTerm!==f&&(x=this._findInLine(f,m,p,!1),x||(m.startRow=b=v.end.y,m.startCol=g=v.end.x))),x||(x=this._findInLine(f,m,p,O)),!x){m.startCol=Math.max(m.startCol,this._terminal.cols);for(let y=b-1;y>=0&&(m.startRow=y,x=this._findInLine(f,m,p,O),!x);y--);}if(!x&&b!==this._terminal.buffer.active.baseY+this._terminal.rows-1)for(let y=this._terminal.buffer.active.baseY+this._terminal.rows-1;y>=b&&(m.startRow=y,x=this._findInLine(f,m,p,O),!x);y--);return this._selectResult(x,p?.decorations,p?.noScroll)}_initLinesCache(){const f=this._terminal;this._linesCache||(this._linesCache=new Array(f.buffer.active.length),this._linesCacheDisposables.value=(0,l.getDisposeArrayDisposable)([f.onLineFeed((()=>this._destroyLinesCache())),f.onCursorMove((()=>this._destroyLinesCache())),f.onResize((()=>this._destroyLinesCache()))])),window.clearTimeout(this._linesCacheTimeoutId),this._linesCacheTimeoutId=window.setTimeout((()=>this._destroyLinesCache()),15e3)}_destroyLinesCache(){this._linesCache=void 0,this._linesCacheDisposables.clear(),this._linesCacheTimeoutId&&(window.clearTimeout(this._linesCacheTimeoutId),this._linesCacheTimeoutId=0)}_isWholeWord(f,p,v){return(f===0||h.includes(p[f-1]))&&(f+v.length===p.length||h.includes(p[f+v.length]))}_findInLine(f,p,v={},b=!1){const g=this._terminal,O=p.startRow,m=p.startCol;if(g.buffer.active.getLine(O)?.isWrapped)return b?void(p.startCol+=g.cols):(p.startRow--,p.startCol+=g.cols,this._findInLine(f,p,v));let y=this._linesCache?.[O];y||(y=this._translateBufferLineToStringWithWrap(O,!0),this._linesCache&&(this._linesCache[O]=y));const[k,C]=y,P=this._bufferColsToStringOffset(O,m),_=v.caseSensitive?f:f.toLowerCase(),T=v.caseSensitive?k:k.toLowerCase();let R=-1;if(v.regex){const L=RegExp(_,"g");let M;if(b)for(;M=L.exec(T.slice(0,P));)R=L.lastIndex-M[0].length,f=M[0],L.lastIndex-=f.length-1;else M=L.exec(T.slice(P)),M&&M[0].length>0&&(R=P+(L.lastIndex-M[0].length),f=M[0])}else b?P-_.length>=0&&(R=T.lastIndexOf(_,P-_.length)):R=T.indexOf(_,P);if(R>=0){if(v.wholeWord&&!this._isWholeWord(R,T,f))return;let L=0;for(;L<C.length-1&&R>=C[L+1];)L++;let M=L;for(;M<C.length-1&&R+f.length>=C[M+1];)M++;const E=R-C[L],B=R+f.length-C[M],U=this._stringLengthToBufferSize(O+L,E);return{term:f,col:U,row:O+L,size:this._stringLengthToBufferSize(O+M,B)-U+g.cols*(M-L)}}}_stringLengthToBufferSize(f,p){const v=this._terminal.buffer.active.getLine(f);if(!v)return 0;for(let b=0;b<p;b++){const g=v.getCell(b);if(!g)break;const O=g.getChars();O.length>1&&(p-=O.length-1);const m=v.getCell(b+1);m&&m.getWidth()===0&&p++}return p}_bufferColsToStringOffset(f,p){const v=this._terminal;let b=f,g=0,O=v.buffer.active.getLine(b);for(;p>0&&O;){for(let m=0;m<p&&m<v.cols;m++){const x=O.getCell(m);if(!x)break;x.getWidth()&&(g+=x.getCode()===0?1:x.getChars().length)}if(b++,O=v.buffer.active.getLine(b),O&&!O.isWrapped)break;p-=v.cols}return g}_translateBufferLineToStringWithWrap(f,p){const v=this._terminal,b=[],g=[0];let O=v.buffer.active.getLine(f);for(;O;){const m=v.buffer.active.getLine(f+1),x=!!m&&m.isWrapped;let y=O.translateToString(!x&&p);if(x&&m){const k=O.getCell(O.length-1);k&&k.getCode()===0&&k.getWidth()===1&&m.getCell(0)?.getWidth()===2&&(y=y.slice(0,-1))}if(b.push(y),!x)break;g.push(g[g.length-1]+y.length),f++,O=m}return[b.join(""),g]}_selectResult(f,p,v){const b=this._terminal;if(this._selectedDecoration.clear(),!f)return b.clearSelection(),!1;if(b.select(f.col,f.row,f.size),p){const g=b.registerMarker(-b.buffer.active.baseY-b.buffer.active.cursorY+f.row);if(g){const O=b.registerDecoration({marker:g,x:f.col,width:f.size,backgroundColor:p.activeMatchBackground,layer:"top",overviewRulerOptions:{color:p.activeMatchColorOverviewRuler}});if(O){const m=[];m.push(g),m.push(O.onRender((x=>this._applyStyles(x,p.activeMatchBorder,!0)))),m.push(O.onDispose((()=>(0,l.disposeArray)(m)))),this._selectedDecoration.value={decoration:O,match:f,dispose(){O.dispose()}}}}}if(!v&&(f.row>=b.buffer.active.viewportY+b.rows||f.row<b.buffer.active.viewportY)){let g=f.row-b.buffer.active.viewportY;g-=Math.floor(b.rows/2),b.scrollLines(g)}return!0}_applyStyles(f,p,v){f.classList.contains("xterm-find-result-decoration")||(f.classList.add("xterm-find-result-decoration"),p&&(f.style.outline=`1px solid ${p}`)),v&&f.classList.add("xterm-find-active-result-decoration")}_createResultDecoration(f,p){const v=this._terminal,b=v.registerMarker(-v.buffer.active.baseY-v.buffer.active.cursorY+f.row);if(!b)return;const g=v.registerDecoration({marker:b,x:f.col,width:f.size,backgroundColor:p.matchBackground,overviewRulerOptions:this._highlightedLines.has(b.line)?void 0:{color:p.matchOverviewRuler,position:"center"}});if(g){const O=[];O.push(b),O.push(g.onRender((m=>this._applyStyles(m,p.matchBorder,!1)))),O.push(g.onDispose((()=>(0,l.disposeArray)(O))))}return g}}a.SearchAddon=d})(),n})()))})(xf)),xf.exports}var fD=uD(),bf={exports:{}},cv;function mD(){return cv||(cv=1,(function(s,e){(function(t,r){s.exports=r()})(self,(()=>(()=>{var t={6:(a,o)=>{function l(d){try{const u=new URL(d),f=u.password&&u.username?`${u.protocol}//${u.username}:${u.password}@${u.host}`:u.username?`${u.protocol}//${u.username}@${u.host}`:`${u.protocol}//${u.host}`;return d.toLocaleLowerCase().startsWith(f.toLocaleLowerCase())}catch{return!1}}Object.defineProperty(o,"__esModule",{value:!0}),o.LinkComputer=o.WebLinkProvider=void 0,o.WebLinkProvider=class{constructor(d,u,f,p={}){this._terminal=d,this._regex=u,this._handler=f,this._options=p}provideLinks(d,u){const f=h.computeLink(d,this._regex,this._terminal,this._handler);u(this._addCallbacks(f))}_addCallbacks(d){return d.map((u=>(u.leave=this._options.leave,u.hover=(f,p)=>{if(this._options.hover){const{range:v}=u;this._options.hover(f,p,v)}},u)))}};class h{static computeLink(u,f,p,v){const b=new RegExp(f.source,(f.flags||"")+"g"),[g,O]=h._getWindowedLineStrings(u-1,p),m=g.join("");let x;const y=[];for(;x=b.exec(m);){const k=x[0];if(!l(k))continue;const[C,P]=h._mapStrIdx(p,O,0,x.index),[_,T]=h._mapStrIdx(p,C,P,k.length);if(C===-1||P===-1||_===-1||T===-1)continue;const R={start:{x:P+1,y:C+1},end:{x:T,y:_+1}};y.push({range:R,text:k,activate:v})}return y}static _getWindowedLineStrings(u,f){let p,v=u,b=u,g=0,O="";const m=[];if(p=f.buffer.active.getLine(u)){const x=p.translateToString(!0);if(p.isWrapped&&x[0]!==" "){for(g=0;(p=f.buffer.active.getLine(--v))&&g<2048&&(O=p.translateToString(!0),g+=O.length,m.push(O),p.isWrapped&&O.indexOf(" ")===-1););m.reverse()}for(m.push(x),g=0;(p=f.buffer.active.getLine(++b))&&p.isWrapped&&g<2048&&(O=p.translateToString(!0),g+=O.length,m.push(O),O.indexOf(" ")===-1););}return[m,v]}static _mapStrIdx(u,f,p,v){const b=u.buffer.active,g=b.getNullCell();let O=p;for(;v;){const m=b.getLine(f);if(!m)return[-1,-1];for(let x=O;x<m.length;++x){m.getCell(x,g);const y=g.getChars();if(g.getWidth()&&(v-=y.length||1,x===m.length-1&&y==="")){const k=b.getLine(f+1);k&&k.isWrapped&&(k.getCell(0,g),g.getWidth()===2&&(v+=1))}if(v<0)return[f,x]}f++,O=0}return[f,O]}}o.LinkComputer=h}},r={};function i(a){var o=r[a];if(o!==void 0)return o.exports;var l=r[a]={exports:{}};return t[a](l,l.exports,i),l.exports}var n={};return(()=>{var a=n;Object.defineProperty(a,"__esModule",{value:!0}),a.WebLinksAddon=void 0;const o=i(6),l=/(https?|HTTPS?):[/]{2}[^\s"'!*(){}|\\\^<>`]*[^\s"':,.!?{}|\\\^~\[\]`()<>]/;function h(d,u){const f=window.open();if(f){try{f.opener=null}catch{}f.location.href=u}else console.warn("Opening link blocked as opener could not be cleared")}a.WebLinksAddon=class{constructor(d=h,u={}){this._handler=d,this._options=u}activate(d){this._terminal=d;const u=this._options,f=u.urlRegex||l;this._linkProvider=this._terminal.registerLinkProvider(new o.WebLinkProvider(this._terminal,f,this._handler,u))}dispose(){this._linkProvider?.dispose()}}})(),n})()))})(bf)),bf.exports}var pD=mD();function vf(s,e){try{return getComputedStyle(document.documentElement).getPropertyValue(s).trim()||e}catch{return e}}function hv(s){return typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC")?s.metaKey:s.ctrlKey}function Q_(s){return!s||s.includes(" ")||/^https?:\/\//i.test(s)?!1:/^[a-zA-Z]:[\\/]/.test(s)||s.startsWith("/")||s.startsWith("~/")||s.startsWith("./")||s.startsWith("../")?!0:/^[\w./\\-]+\.[a-zA-Z0-9]{1,8}$/.test(s)}function dv(s,e){const t=s.trim().replace(/\\/g,"/");return!t||!Q_(t)?null:/^[a-zA-Z]:\//.test(t)||t.startsWith("~/")?t:t.startsWith("/")?/^\/packages\//.test(t)?!e||e==="/"?null:bO(t.slice(1),e):t:!e||e==="/"?null:bO(t,e)}function uv(s){return s.clientWidth>=16&&s.clientHeight>=16}async function gD(s,e){try{const r=(await te.files.check([s]))?.results?.[s];if(!r?.exists||!r?.isFile)return;e?.(s)}catch{e?.(s)}}function OD({terminalId:s,title:e,cwd:t,active:r=!0,onMeta:i,onSelection:n,onOpenUrl:a,onOpenPath:o,apiRef:l}){const{t:h}=Pt("common"),d=S.useRef(null),u=S.useRef(null),f=S.useRef(null),p=S.useRef(null),v=S.useRef(i),b=S.useRef(n),g=S.useRef(a),O=S.useRef(o),m=S.useRef(t);v.current=i,b.current=n,g.current=a,O.current=o,S.useEffect(()=>{t&&t!=="/"&&(m.current=t)},[t]);const[x,y]=S.useState(null),[k,C]=S.useState(!1),[P,_]=S.useState(""),[T,R]=S.useState(!1),L=S.useRef(!0),M=S.useCallback(()=>{const B=d.current,U=u.current,F=f.current;if(!B||!U||!F||!uv(B))return!1;try{return F.fit(),!0}catch{return!1}},[]),E=S.useCallback(()=>{const B=u.current;B&&(B.scrollToBottom(),L.current=!0,R(!1))},[]);return S.useEffect(()=>{Gk(s);const B=d.current,U=window.markusDesktop?.terminal;if(!B)return;if(!U){y("desktopOnly");return}let F=!1,X=null,ae=null,j,W,D,V=null,se=null,fe=null,z=null;const re=async()=>{if(F||!d.current)return;if(!uv(d.current)){z=window.setTimeout(()=>{re()},50);return}const Z=vf("--color-surface-primary","#0f1419"),A=vf("--color-fg-primary","#e7e9ea");X=new cD.Terminal({cursorBlink:!0,fontFamily:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace",fontSize:13,lineHeight:1.25,allowProposedApi:!0,theme:{background:Z,foreground:A,cursor:vf("--color-brand-500","#3b82f6"),selectionBackground:"rgba(59, 130, 246, 0.35)"}});const J=new dD.FitAddon,Y=new fD.SearchAddon,oe=new pD.WebLinksAddon((K,pe)=>{hv(K)&&g.current?.(pe)});if(X.loadAddon(J),X.loadAddon(Y),X.loadAddon(oe),X.open(d.current),u.current=X,f.current=J,p.current=Y,!M())try{J.fit()}catch{}X.registerLinkProvider({provideLinks:(K,pe)=>{const je=X.buffer.active.getLine(K-1);if(!je){pe(void 0);return}const we=je.translateToString(!0),Ge=/(?:(?:[A-Za-z]:|\/|~\/)[\w./\\-]+|(?:\.\.?\/)?[\w./\\-]+\.[a-zA-Z0-9]{1,8})/g,Qe=[];let Ee;for(;Ee=Ge.exec(we);){const ye=Ee[0];Q_(ye)&&dv(ye,m.current)&&Qe.push({range:{start:{x:Ee.index+1,y:K},end:{x:Ee.index+ye.length,y:K}},text:ye,decorations:{pointerCursor:!0,underline:!0},activate:G=>{if(!hv(G))return;const qe=dv(ye,m.current);qe&&gD(qe,O.current)}})}pe(Qe.length?Qe:void 0)}});try{const K=Math.max(X.cols||80,2),pe=Math.max(X.rows||24,1);let je=t||m.current;if(!je||je==="/")try{je=await window.markusDesktop?.getDefaultCwd?.()}catch{}je==="/"&&(je=void 0),je&&(m.current=je);const we=await U.create(s,{cwd:je,title:e,cols:K,rows:pe});if(F)return;if(!we.ok){y(we.error||"createFailed");return}we.info&&(we.info.cwd&&(m.current=we.info.cwd),v.current?.(s,{title:we.info.title,cwd:we.info.cwd}));const Ge=await U.getBuffer(s,{maxChars:12e4});if(F)return;const Qe=Ge.ok?Ge.content:void 0;if(Qe&&(await new Promise(Ee=>{let ye=!1,G;const qe=()=>{ye||(ye=!0,G!==void 0&&window.clearTimeout(G),Ee())};G=window.setTimeout(qe,1500);try{X.write(Qe,qe)}catch{qe()}}),F))return;M(),U.resize(s,X.cols,X.rows),X.focus()}catch(K){F||y(K instanceof Error?K.message:String(K));return}j=U.onData?.(K=>{K.id!==s||!u.current||(u.current.write(K.data),L.current||R(!0))}),D=U.onEvent?.(K=>{K.id!==s||K.type!=="cwd"||!K.cwd||(m.current=K.cwd,v.current?.(s,{cwd:K.cwd}))}),W=U.onExit?.(()=>{}),V=X.onData(K=>{U.write(s,K)}),se=X.onScroll(()=>{const K=u.current;if(!K)return;const pe=K.buffer.active,je=pe.viewportY>=pe.baseY-1;L.current=je,je&&R(!1)}),fe=X.onSelectionChange(()=>{const K=u.current,pe=d.current;if(!K||!pe)return;if(!K.getSelection().trim()){b.current?.(null);return}requestAnimationFrame(()=>{const we=u.current,Ge=d.current;if(!we||!Ge)return;const Qe=we.getSelection().trim();if(!Qe){b.current?.(null);return}let Ee,ye;const G=Ge.querySelectorAll(".xterm-selection div");let qe=1/0,He=1/0,Ye=-1/0;if(G.forEach(pt=>{const xt=pt.getBoundingClientRect();xt.width<1&&xt.height<1||(qe=Math.min(qe,xt.top),He=Math.min(He,xt.left),Ye=Math.max(Ye,xt.right))}),qe<1/0)Ee=(He+Ye)/2,ye=qe;else{const pt=we.getSelectionPosition?.(),bt=(Ge.querySelector(".xterm-screen")??Ge).getBoundingClientRect(),vt=Math.max(we.cols,1),Pe=Math.max(we.rows,1),At=bt.width/vt,Ft=bt.height/Pe;if(pt){const Es=we.buffer.active.viewportY,rt=Math.max(0,pt.start.y-Es);Ee=bt.left+(pt.start.x+.5)*At,ye=bt.top+rt*Ft}else Ee=bt.left+bt.width/2,ye=bt.top+12}b.current?.({text:Qe,x:Ee,y:ye})})}),ae=new ResizeObserver(()=>{!M()||!u.current||U.resize(s,u.current.cols,u.current.rows)}),ae.observe(d.current),l&&(l.current={getSelection:()=>u.current?.getSelection()??"",getRecentOutput:async(K=80)=>{const pe=await U.getBuffer(s,{maxLines:K});return pe.ok&&pe.content||""},focus:()=>u.current?.focus(),findNext:K=>{p.current?.findNext(K)},clearSelection:()=>u.current?.clearSelection()})};return re(),()=>{F=!0,z!=null&&window.clearTimeout(z),j?.(),W?.(),D?.(),V?.dispose(),se?.dispose(),fe?.dispose(),ae?.disconnect(),l&&(l.current=null);try{X?.dispose()}catch{}u.current=null,f.current=null,p.current=null}},[s]),S.useEffect(()=>{if(!r)return;const B=window.requestAnimationFrame(()=>{M();const U=u.current;U&&(window.markusDesktop?.terminal?.resize(s,U.cols,U.rows),U.focus())});return()=>window.cancelAnimationFrame(B)},[r,s,M]),S.useEffect(()=>{const B=U=>{if(!r)return;if((navigator.platform.toUpperCase().includes("MAC")?U.metaKey&&!U.ctrlKey:U.ctrlKey&&!U.metaKey)&&!U.altKey&&!U.shiftKey&&U.key.toLowerCase()==="f"){const ae=U.target;ae instanceof HTMLElement&&(d.current?.contains(ae)||ae.closest(".xterm"))&&(U.preventDefault(),C(!0))}};return window.addEventListener("keydown",B),()=>window.removeEventListener("keydown",B)},[r]),c.jsxs("div",{className:"relative flex-1 min-h-0 flex flex-col rounded-lg overflow-hidden border border-border-default bg-surface-primary",children:[k&&c.jsxs("div",{className:"shrink-0 flex items-center gap-1.5 px-2 py-1.5 border-b border-border-default bg-surface-elevated",children:[c.jsx("input",{autoFocus:!0,value:P,onChange:B=>_(B.target.value),onKeyDown:B=>{B.key==="Enter"?(B.preventDefault(),p.current?.findNext(P)):B.key==="Escape"&&C(!1)},placeholder:h("terminal.searchPlaceholder"),className:"flex-1 min-w-0 text-xs bg-transparent outline-none text-fg-primary placeholder:text-fg-muted"}),c.jsx("button",{type:"button",className:"text-[11px] px-2 py-0.5 rounded text-fg-secondary hover:bg-surface-overlay",onClick:()=>p.current?.findNext(P),children:h("terminal.searchNext")}),c.jsx("button",{type:"button",className:"text-[11px] px-2 py-0.5 rounded text-fg-tertiary hover:bg-surface-overlay",onClick:()=>C(!1),children:"Esc"})]}),x?c.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-2 p-6 text-center",children:[c.jsxs("svg",{className:"w-8 h-8 text-fg-muted",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,"aria-hidden":"true",children:[c.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M7 9l3 3-3 3M13 15h4"})]}),x==="desktopOnly"?c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"text-sm font-medium text-fg-secondary",children:h("terminal.desktopOnlyTitle")}),c.jsx("p",{className:"text-xs text-fg-muted max-w-xs",children:h("terminal.desktopOnlyDesc")})]}):c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"text-sm font-medium text-fg-secondary",children:h("terminal.createFailedTitle")}),c.jsx("p",{className:"text-xs text-fg-muted max-w-xs break-words",children:x==="createFailed"?h("terminal.createFailedDesc"):x})]})]}):c.jsx("div",{ref:d,className:"flex-1 min-h-0 w-full h-full [&_.xterm]:h-full [&_.xterm]:w-full [&_.xterm-viewport]:overflow-auto"}),T&&c.jsx("button",{type:"button",onClick:E,className:"absolute bottom-3 right-3 z-10 text-[11px] px-2.5 py-1 rounded-md bg-brand-600 text-white shadow-lg hover:bg-brand-500",children:h("terminal.jumpToBottom")})]})}const xD=8;function bD(s){const{left:e,width:t,viewport:r}=s,i=Math.max(0,t-r);if(i<=0||t<=0||r<=0)return{visible:!1,leftPct:0,widthPct:0,overflow:0};const n=Math.max(xD,r/t*100);return{visible:!0,leftPct:Math.max(0,Math.min(100-n,e/t*100)),widthPct:n,overflow:i}}const fv=(s,e,t)=>Math.max(e,Math.min(t,s));function vD({scrollRef:s,watch:e}){const[t,r]=S.useState({left:0,width:0,viewport:0}),i=S.useRef(null),n=S.useRef(null),a=S.useCallback(()=>{const u=s.current;if(!u)return;const f={left:u.scrollLeft,width:u.scrollWidth,viewport:u.clientWidth};r(p=>p.left===f.left&&p.width===f.width&&p.viewport===f.viewport?p:f)},[s]);S.useEffect(()=>{const u=s.current;if(!u)return;a(),u.addEventListener("scroll",a,{passive:!0});const f=new ResizeObserver(a);f.observe(u);for(const p of Array.from(u.children))f.observe(p);return()=>{u.removeEventListener("scroll",a),f.disconnect()}},[s,a,e]);const o=bD(t),l=u=>{const f=s.current,p=i.current;if(!f||!p||!o.visible||u.button!==0)return;const v=p.getBoundingClientRect();if(v.width<=0)return;const b=o.widthPct/100*v.width,g=o.leftPct/100*v.width,O=u.clientX-v.left;if(O<g||O>g+b){const m=f.scrollWidth/v.width;f.scrollLeft=fv((O-b/2)*m,0,o.overflow)}n.current={pointerId:u.pointerId,startX:u.clientX,startLeft:f.scrollLeft};try{p.setPointerCapture(u.pointerId)}catch{}u.preventDefault(),u.stopPropagation()},h=u=>{const f=n.current,p=s.current,v=i.current;if(!f||f.pointerId!==u.pointerId||!p||!v)return;const b=v.getBoundingClientRect();if(b.width<=0)return;const g=p.scrollWidth/b.width;p.scrollLeft=fv(f.startLeft+(u.clientX-f.startX)*g,0,o.overflow)},d=u=>{const f=n.current;if(!(!f||f.pointerId!==u.pointerId)){n.current=null;try{i.current?.releasePointerCapture(u.pointerId)}catch{}}};return o.visible?c.jsx("div",{ref:i,"aria-hidden":!0,"data-tab-scroll-rail":!0,className:"relative h-[3px] mt-[3px] mx-1 shrink-0 rounded-full bg-border-default/30 cursor-pointer select-none",onPointerDown:l,onPointerMove:h,onPointerUp:d,onPointerCancel:d,children:c.jsx("div",{className:"absolute top-0 h-full rounded-full bg-fg-muted/60 hover:bg-fg-secondary transition-colors",style:{left:`${o.leftPct}%`,width:`${o.widthPct}%`}})}):null}function mv(s){return/^(https?|file):\/\//i.test(s)?s:/^[a-zA-Z]:[\\/]/.test(s)?`file:///${s.replace(/\\/g,"/")}`:`file://${s.startsWith("/")?s:`/${s}`}`}function uo(s){return/^https?:\/\//i.test(s)}function yD(s){return s.kind==="deliverable"?s.deliverable.reference??"":s.kind==="url"?s.url:s.kind==="terminal"?s.terminalId:s.path}function SD(s){return s.kind==="deliverable"?s.deliverable.title||s.deliverable.reference||"":s.kind==="url"?s.title||s.url:s.kind==="terminal"?s.title||"Terminal":s.title||s.path.split(/[/\\]/).pop()||s.path}function wD(s,e){if(s.kind==="file")return`file:${s.path}:${e??""}`;if(s.kind==="url")return`url:${s.browserId||s.url}:${e??""}`;if(s.kind==="terminal")return`terminal:${s.terminalId}:${e??""}`;const t=s.deliverable;return`deliverable:${t.id||t.reference||t.title||"unknown"}:${e??""}`}function yf(s){return s==null||!Number.isFinite(s)?"":s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`}function _D(s){const e=s.includes("\\")?"\\":"/",t=s.lastIndexOf(e);return t<=0?e==="/"?"/":s.slice(0,2):s.slice(0,t)}function kD({payload:s,onClose:e,width:t,onResizeStart:r,onAddToChat:i,tabs:n,activeTabId:a,onSelectTab:o,onCloseTab:l,onNewTab:h,fullscreen:d,onToggleFullscreen:u,onBrowserMeta:f,panelMode:p="browser",onPanelModeChange:v,onTerminalMeta:b,onOpenUrlFromTerminal:g,onOpenPathFromTerminal:O}){const{t:m}=Pt(["deliverables","agent","common"]),[x,y]=S.useState({mode:"loading"}),[k,C]=S.useState(null),[P,_]=S.useState(!1),[T,R]=S.useState(!1),[L,M]=S.useState(null),[E,B]=S.useState(null),[U,F]=S.useState({}),[X,ae]=S.useState({}),[j,W]=S.useState(!1),[D,V]=S.useState(0),[se,fe]=S.useState(!0),z=S.useRef(null),re=S.useRef(null),Z=S.useRef(null),A=S.useRef(null),J=S.useRef(null),Y=S.useRef(!1);Y.current=j;const oe=S.useCallback(()=>b_(Y.current,m("common:fileEditor.discardConfirm",{defaultValue:"Discard unsaved changes?"})),[m]);S.useEffect(()=>{let he=!1;te.browser.tabOwnership().then($e=>{if(he)return;const Xe={};for(const de of $e.ownership??[])Xe[de.pageId]={agentId:de.agentId,agentName:de.agentName||de.agentId};F(Xe)}).catch(()=>{});const ce=St.on("ui:browser_ownership",$e=>{const Xe=$e.payload;typeof Xe.pageId=="number"&&F(de=>{if(Xe.action==="released"||!Xe.agentId){if(!(Xe.pageId in de))return de;const De={...de};return delete De[Xe.pageId],De}return{...de,[Xe.pageId]:{agentId:Xe.agentId,agentName:Xe.agentName||Xe.agentId}}})});return()=>{he=!0,ce()}},[]),S.useEffect(()=>{let he=!1;te.terminal?.sessionOwnership?.().then($e=>{if(he)return;const Xe={};for(const de of $e.ownership??[])Xe[de.terminalId]={agentId:de.agentId,agentName:de.agentName||de.agentId};ae(Xe)}).catch(()=>{});const ce=St.on("ui:terminal_ownership",$e=>{const Xe=$e.payload;typeof Xe.terminalId=="string"&&ae(de=>{if(Xe.action==="released"||!Xe.agentId){if(!(Xe.terminalId in de))return de;const De={...de};return delete De[Xe.terminalId],De}return{...de,[Xe.terminalId]:{agentId:Xe.agentId,agentName:Xe.agentName||Xe.agentId}}})});return()=>{he=!0,ce()}},[]);const K=yD(s),pe=SD(s),je=k??K,we=(n?.length??0)>=1,Ge=wD(s,a),Qe=(s.kind==="file"||s.kind==="deliverable")&&!!K&&!uo(K)&&!(s.kind==="deliverable"&&s.deliverable.artifactType),Ee=je||K,ye=S.useCallback(()=>{oe()&&(z.current=null,V(he=>he+1))},[oe]);S.useEffect(()=>{if(!Qe||!Ee||x.mode==="loading")return;let he=!1;return te.files.stat(Ee).then(ce=>{he||!ce.exists||(z.current={path:ce.path||Ee,mtimeMs:ce.mtimeMs??0,size:ce.size??0})}).catch(()=>{}),()=>{he=!0}},[Qe,Ee,x,D]),S.useEffect(()=>{if(!se||!Qe||!Ee||j)return;let he=!1;const ce=async()=>{const De=z.current;if(!(!De||De.path!==Ee))try{const ve=await te.files.stat(Ee);if(he||!ve.exists)return;((ve.mtimeMs??0)!==De.mtimeMs||(ve.size??0)!==De.size)&&V(st=>st+1)}catch{}},$e=window.setInterval(()=>{ce()},5e3),Xe=()=>{ce()},de=()=>{document.visibilityState==="visible"&&ce()};return window.addEventListener("focus",Xe),document.addEventListener("visibilitychange",de),()=>{he=!0,window.clearInterval($e),window.removeEventListener("focus",Xe),document.removeEventListener("visibilitychange",de)}},[se,Qe,Ee,j]),S.useEffect(()=>{if(!a)return;const he=A.current,ce=Z.current;if(!he||!ce)return;const $e=requestAnimationFrame(()=>{he.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame($e)},[a,n?.length]),S.useEffect(()=>{const he=ce=>{if(ce.key==="Escape"){if(!oe())return;d&&u?u():e()}};return window.addEventListener("keydown",he),()=>window.removeEventListener("keydown",he)},[e,d,u,oe]),S.useEffect(()=>{let he=!1;return B(null),W(!1),M(null),s.kind==="url"?(y({mode:"url",url:s.url,browserId:s.browserId}),()=>{he=!0}):s.kind==="terminal"?(y({mode:"terminal",terminalId:s.terminalId,title:s.title,cwd:s.cwd}),()=>{he=!0}):uo(K)?(y({mode:"url",url:K}),()=>{he=!0}):(y({mode:"loading"}),s.kind==="deliverable"&&s.deliverable.artifactType&&s.deliverable.artifactData?(y({mode:"artifact",summary:s.deliverable.summary||s.deliverable.title||""}),()=>{he=!0}):je?(te.files.preview(je).then(ce=>{if(he)return;if(ce.type==="directory"&&Array.isArray(ce.entries)){y({mode:"directory",path:ce.path,name:ce.name,entries:ce.entries});return}if(ce.type==="image"){const Xe=ce.content?`data:${ce.mimeType||"image/png"};base64,${ce.content}`:ce.streamUrl||(ce.path?te.files.streamUrl(ce.path):te.files.streamUrl(je));y({mode:"image",src:Xe,name:ce.name||pe});return}if(ce.type==="audio"){const Xe=ce.streamUrl||(ce.path?te.files.streamUrl(ce.path):te.files.streamUrl(je));y({mode:"audio",src:Xe,name:ce.name||pe,mimeType:ce.mimeType||"audio/mpeg",size:ce.size});return}if(ce.type==="video"){const Xe=ce.streamUrl||(ce.path?te.files.streamUrl(ce.path):te.files.streamUrl(je));y({mode:"video",src:Xe,name:ce.name||pe,mimeType:ce.mimeType||"video/mp4",size:ce.size});return}if(ce.type==="binary"){y({mode:"binary",name:ce.name||pe,reference:ce.path||je,size:ce.size,extension:ce.extension});return}if(ce.type==="office"){const Xe=ce.streamUrl||(ce.path?te.files.streamUrl(ce.path):te.files.streamUrl(je));y({mode:"office",format:ce.format||String(ce.extension||"").replace(/^\./,"")||"pdf",streamUrl:Xe,name:ce.name||pe,size:ce.size,reference:ce.path||je});return}if(typeof ce.content!="string"){y({mode:"unpreviewable",reference:je,isDirectory:!1});return}const $e=zC({format:s.kind==="deliverable"?s.deliverable.format:void 0,reference:K,content:ce.content});y({mode:"content",content:ce.content,format:$e})}).catch(()=>{he||y({mode:"unpreviewable",reference:je,isDirectory:!1})}),()=>{he=!0}):(y({mode:"unpreviewable",reference:"",isDirectory:!1}),()=>{he=!0}))},[Ge,s,je,K,pe,D]),S.useEffect(()=>{C(null)},[Ge]);const G=pe||je,qe=S.useCallback((he,ce)=>{const $e=he.length>40?`${he.slice(0,24)}…${he.slice(-12)}`:he;return ce?{label:`🌐 ${$e}`,content:["[html-selection]",`Text: "${he}"`,`CSS Selector: ${ce.cssSelector}`,`XPath: ${ce.xpath}`,K?`File: ${K}`:""].filter(Boolean).join(`
|
|
49
49
|
`)}:s.kind==="terminal"?{label:`⌘ ${$e}`,content:["[terminal-selection]",`Terminal: ${s.title||"Terminal"} (${s.terminalId})`,s.cwd?`Cwd: ${s.cwd}`:"",'"""',he,'"""'].filter(Boolean).join(`
|
|
50
50
|
`)}:{label:`“${$e}”`,content:`${m("deliverables:chat.selectedFrom",{defaultValue:"Selected from"})} ${G}:
|
|
51
51
|
|
|
@@ -54,8 +54,8 @@ ${he}
|
|
|
54
54
|
"""`}},[K,G,m,s]),He=S.useCallback((he,ce)=>{!he.trim()||!i||(i(qe(he.trim(),ce)),B(null),window.getSelection()?.removeAllRanges(),J.current?.clearSelection())},[i,qe]),Ye=S.useCallback(async()=>{if(!i||s.kind!=="terminal")return;const he=(await J.current?.getRecentOutput(80))?.trim();if(!he)return;const ce=he.length>40?`${he.slice(0,24)}…${he.slice(-12)}`:he;i({label:`⌘ ${ce}`,content:["[terminal-output]",`Terminal: ${s.title||"Terminal"} (${s.terminalId})`,s.cwd?`Cwd: ${s.cwd}`:"",'"""',he,'"""'].filter(Boolean).join(`
|
|
55
55
|
`)})},[i,s]);S.useEffect(()=>{if(s.kind!=="terminal"||!i)return;const he=navigator.platform.toUpperCase().includes("MAC"),ce=$e=>{if(!(he?$e.metaKey&&!$e.ctrlKey:$e.ctrlKey&&!$e.metaKey)||!$e.shiftKey||$e.altKey||$e.key.toLowerCase()!=="a")return;const de=J.current?.getSelection()?.trim();de&&($e.preventDefault(),He(de))};return window.addEventListener("keydown",ce),()=>window.removeEventListener("keydown",ce)},[s.kind,i,He]);const pt=S.useCallback(he=>{if(!he.text.trim()||!i)return;const ce=re.current?.querySelector("iframe")?.getBoundingClientRect(),$e=(ce?.left??0)+he.rect.x+he.rect.width/2,Xe=(ce?.top??0)+he.rect.y;B({x:$e,y:Xe,text:he.text,htmlMeta:{xpath:he.xpath,cssSelector:he.cssSelector}})},[i]);S.useEffect(()=>{const he=re.current;if(!he||!i)return;const ce=()=>{requestAnimationFrame(()=>{const Xe=window.getSelection(),de=Xe?.toString().trim();if(!de||!Xe?.rangeCount){B(null);return}const De=Xe.getRangeAt(0);if(!he.contains(De.commonAncestorContainer)){B(null);return}const ve=De.getBoundingClientRect();B({x:ve.left+ve.width/2,y:ve.top,text:de})})},$e=Xe=>{const de=document.getElementById("right-panel-selection-toolbar");de&&de.contains(Xe.target)||B(null)};return he.addEventListener("mouseup",ce),document.addEventListener("mousedown",$e),()=>{he.removeEventListener("mouseup",ce),document.removeEventListener("mousedown",$e)}},[i,x.mode]);const xt=()=>{te.files.reveal(je||K).catch(()=>{})},bt=()=>{navigator.clipboard?.writeText(je||K).then(()=>{_(!0),setTimeout(()=>_(!1),1500)}).catch(()=>{})},vt=S.useMemo(()=>{if(!i)return null;const he=je||K;if(s.kind==="deliverable"){const ce=s.deliverable;if(!ce.id&&!ce.reference)return null;const $e=pe||ce.title||ce.reference||ce.id;return{label:`📄 ${$e.length>40?`${$e.slice(0,24)}…${$e.slice(-12)}`:$e}`,content:["[deliverable]",ce.id?`ID: ${ce.id}`:"",ce.title?`Title: ${ce.title}`:"",ce.reference?`Reference: ${ce.reference}`:"",ce.taskId?`Task: ${ce.taskId}`:"",ce.projectId?`Project: ${ce.projectId}`:""].filter(Boolean).join(`
|
|
56
56
|
`)}}if(s.kind==="file"){if(!he||uo(he))return null;const ce=pe||he.split(/[/\\]/).pop()||he;return{label:`📄 ${ce.length>40?`${ce.slice(0,24)}…${ce.slice(-12)}`:ce}`,content:["[file]",`Path: ${he}`,x.mode==="content"&&x.format?`Format: ${x.format}`:""].filter(Boolean).join(`
|
|
57
|
-
`)}}return null},[i,s,je,K,pe,x]),[Pe,Et]=S.useState(!1),Ft=S.useCallback(()=>{vt&&(i?.(vt),Et(!0),setTimeout(()=>Et(!1),1200))},[vt,i]),Es=S.useCallback(async()=>{if(s.kind==="deliverable"){Lr.navigate(Yt.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let ce=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const $e=await window.markusDesktop.browser.getState(s.browserId);if($e.ok){if($e.directoryPath){await te.system.openPath($e.directoryPath).catch(()=>te.files.reveal($e.directoryPath));return}$e.url&&$e.url!=="about:blank"&&(ce=$e.url)}}catch{}if(!ce||ce==="about:blank")return;if(/^https?:\/\//i.test(ce)||/^file:\/\//i.test(ce)){lc(ce);return}await te.system.openPath(ce).catch(()=>lc(mv(ce)));return}if(s.kind!=="file")return;const he=s.path;if(he){if(/^https?:\/\//i.test(he)||/^file:\/\//i.test(he)){lc(he);return}await te.system.openPath(he).catch(()=>lc(mv(he)))}},[s]),rt=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,yt=s.kind==="deliverable"?m("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):m("common:openInSystemBrowser"),Bt=!!K&&!uo(K)&&(s.kind==="file"||s.kind==="deliverable"),ut=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!K&&!uo(K)&&!s.deliverable.artifactType&&qC(s.deliverable.format),Ze=s.kind==="deliverable"?{...s.deliverable,hubShareId:L?.id??s.deliverable.hubShareId??null,shareStatus:L?.status??s.deliverable.shareStatus??null,shareUrl:L?.url??s.deliverable.shareUrl??null,shareVisibility:L?.visibility??s.deliverable.shareVisibility??null}:null,Xt=S.useCallback(he=>{M(he)},[]),ot=S.useMemo(()=>ZC(vO,Fm.getUrl()),[]),At=s.kind==="deliverable"?s.deliverable.id:null;S.useEffect(()=>{if(!At||!vO())return;let he=!1;const ce=async()=>{try{const Xe=await ot.listMine();if(he)return;const de=s.kind==="deliverable"?s.deliverable:null;if(!de)return;const De=de.hubShareId&&Xe.find(ze=>ze.id===de.hubShareId)||Xe.find(ze=>ze.localId===de.id);if(!De)return;M(ze=>ze&&ze.id===De.id&&ze.status===De.status?ze:De);const ve={hubShareId:de.hubShareId??De.id??null,shareStatus:De.status??null,shareUrl:De.url??null,shareVisibility:de.shareVisibility??De.visibility??null};(de.shareStatus!==ve.shareStatus||de.hubShareId!==ve.hubShareId||de.shareUrl!==ve.shareUrl||de.shareVisibility!==ve.shareVisibility)&&de.id&&te.deliverables.update(de.id,ve).catch(ze=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",ze)})}catch{}};ce();const $e=setInterval(ce,3e4);return()=>{he=!0,clearInterval($e)}},[ot,At,s]);const us=Ze?.shareStatus??null;return c.jsxs(c.Fragment,{children:[!d&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),c.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[c.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[c.jsx("button",{type:"button",onClick:()=>v("browser"),title:m("common:browserMode",{defaultValue:"Browser"}),"aria-label":m("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":p==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),c.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),c.jsx("button",{type:"button",onClick:()=>v("terminal"),title:m("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":m("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":p==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 17 10 11 4 5"}),c.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),we||h?c.jsxs("div",{"data-no-drag":!0,className:"flex-1 min-w-0 self-stretch flex flex-col justify-end",children:[c.jsxs("div",{ref:Z,role:"tablist",className:"flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hide",onWheel:he=>{const ce=he.currentTarget;ce.scrollWidth<=ce.clientWidth||Math.abs(he.deltaY)<=Math.abs(he.deltaX)||(ce.scrollLeft+=he.deltaY,he.preventDefault())},children:[n?.map(he=>{const ce=he.id===a,$e=he.payload.kind==="url"?he.payload.pageId:void 0,Xe=he.payload.kind==="terminal"?he.payload.terminalId:void 0,de=$e!=null?U[$e]:Xe?X[Xe]:void 0,De=de?`${he.title} — ${m("common:browserTabControlledBy",{name:de.agentName})}`:he.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${ce?de?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":de?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsxs("button",{type:"button",role:"tab","aria-selected":ce,ref:ce?A:void 0,className:"min-w-0 flex-1 truncate pl-2.5 pr-1 py-1 text-left cursor-pointer flex items-center gap-1",title:De,onPointerDown:ve=>{ve.button===0&&(he.id!==a&&!oe()||o?.(he.id))},onClick:()=>{he.id!==a&&!oe()||o?.(he.id)},children:[de&&c.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:m("common:browserTabControlledBy",{name:de.agentName}),children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),c.jsx("span",{className:"truncate",children:de.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:he.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:ve=>{ve.button===0&&(ve.preventDefault(),ve.stopPropagation(),!(he.id===a&&!oe())&&l(he.id))},onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),!(he.id===a&&!oe())&&l(he.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ce?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:m("common:closeTab",{defaultValue:"Close tab"}),"aria-label":m("common:closeTab",{defaultValue:"Close tab"}),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},he.id)}),h&&c.jsx("button",{type:"button",onClick:h,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:m("common:newTab",{defaultValue:"New Tab"}),"aria-label":m("common:newTab",{defaultValue:"New Tab"}),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),c.jsx(vD,{scrollRef:Z,watch:`${n?.length??0}:${a??""}`})]}):c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:K||pe,children:pe}),c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[Qe&&c.jsx("button",{type:"button",onClick:ye,title:m("common:refreshPreview",{defaultValue:"刷新"}),"aria-label":m("common:refreshPreview",{defaultValue:"刷新"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{className:x.mode==="loading"?"animate-spin":"",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}),Qe&&c.jsx("button",{type:"button",onClick:()=>fe(he=>!he),"aria-pressed":se,title:se?m("common:autoRefreshOn",{defaultValue:"自动刷新:已开启"}):m("common:autoRefreshOff",{defaultValue:"自动刷新:已关闭"}),"aria-label":se?m("common:autoRefreshOn",{defaultValue:"自动刷新:已开启"}):m("common:autoRefreshOff",{defaultValue:"自动刷新:已关闭"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${se?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"9"}),c.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})]})}),s.kind==="terminal"&&i&&c.jsx("button",{type:"button",onClick:()=>{Ye()},title:m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),vt&&c.jsx("button",{type:"button",onClick:Ft,title:Pe?m("common:addedToChat",{defaultValue:"Added to chat"}):s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),"aria-label":s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${Pe?"text-green-500 bg-green-500/10":"text-fg-tertiary hover:text-brand-500 hover:bg-brand-500/10"}`,children:Pe?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h6"}),c.jsx("line",{x1:"17",y1:"3",x2:"17",y2:"9"}),c.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"})]})}),ut&&c.jsxs("button",{type:"button",onClick:()=>R(!0),title:m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),"aria-label":m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),className:`relative w-7 h-7 flex items-center justify-center rounded-md transition-colors ${us==="published"?"text-green-500 hover:text-green-400":us==="pending_review"?"text-amber-500 hover:text-amber-400":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"18",cy:"5",r:"3"}),c.jsx("circle",{cx:"6",cy:"12",r:"3"}),c.jsx("circle",{cx:"18",cy:"19",r:"3"}),c.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),c.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]}),(us==="published"||us==="pending_review"||us==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${us==="published"?"bg-green-500":us==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),rt&&c.jsx("button",{type:"button",onClick:()=>{Es()},title:yt,"aria-label":yt,className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),Bt&&c.jsx("button",{onClick:bt,title:P?m("common:copied",{defaultValue:"Copied"}):m("common:copyPath",{defaultValue:"复制路径"}),"aria-label":m("common:copyPath",{defaultValue:"复制路径"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${P?"text-green-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:P?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),Bt&&c.jsx("button",{onClick:xt,title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&c.jsx("button",{onClick:u,title:d?m("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):m("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:d?c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 14 10 14 10 20"}),c.jsx("polyline",{points:"20 10 14 10 14 4"}),c.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("polyline",{points:"9 21 3 21 3 15"}),c.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),c.jsx("button",{onClick:()=>{oe()&&e()},title:m("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":m("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),c.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="office"||x.mode==="directory"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[k&&x.mode!=="directory"&&x.mode!=="loading"&&c.jsx("div",{className:"shrink-0 mb-2",children:c.jsxs("button",{className:"inline-flex items-center gap-1 text-xs text-fg-secondary hover:text-brand-500 transition-colors cursor-pointer",onClick:()=>C(_D(je)),children:[c.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 20 20",fill:"currentColor",children:c.jsx("path",{fillRule:"evenodd",d:"M17 10a.75.75 0 01-.75.75H5.612l4.158 3.96a.75.75 0 11-1.04 1.08l-5.5-5.25a.75.75 0 010-1.08l5.5-5.25a.75.75 0 111.04 1.08L5.612 9.25H16.25A.75.75 0 0117 10z",clipRule:"evenodd"})}),"返回上级目录"]})}),x.mode==="loading"&&c.jsxs("div",{className:"animate-pulse space-y-3",children:[c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),c.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9 18V5l12-2v13"}),c.jsx("circle",{cx:"6",cy:"18",r:"3"}),c.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${yf(x.size)}`:""]})]})]}),c.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[c.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),c.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${yf(x.size)}`:""]})]}),x.mode==="binary"&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[m("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${yf(x.size)}`:""]})]})]}),x.reference&&c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("button",{onClick:()=>{te.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="office"&&c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(Kk,{data:{format:x.format,streamUrl:x.streamUrl,name:x.name,size:x.size},reference:x.reference,onFallback:x.reference?()=>{te.files.reveal(x.reference)}:void 0})}),x.mode==="content"&&(()=>{const he=K?K.replace(/[/\\][^/\\]+$/,""):void 0,ce=K&&!uo(K)?K:"",$e=x.format;return ce&&($e==="code"||$e==="json"||$e==="text")?c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(x_,{path:ce,initialContent:x.content,language:tg(ce,$e),onDirtyChange:W})}):ce&&($e==="markdown"||$e==="html")?c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(z4,{path:ce,content:x.content,format:$e,basePath:he,onHtmlSelection:pt,onDirtyChange:W})}):c.jsx("div",{ref:re,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(kf,{content:x.content,format:$e,className:"text-fg-secondary text-sm",onHtmlSelection:pt,basePath:he})})})(),x.mode==="artifact"&&c.jsx("div",{ref:re,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(kf,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(aD,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?he=>f(x.browserId,he):void 0},x.browserId||x.url)}),x.mode==="terminal"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(OD,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:J,onMeta:b,onOpenUrl:g,onOpenPath:O,onSelection:he=>{if(!he||!i){B(null);return}B({x:he.x,y:he.y,text:he.text})}},x.terminalId)}),x.mode==="directory"&&c.jsx(Jk,{path:x.path,entries:x.entries,onNavigate:he=>C(he),onOpenFile:he=>C(he),onReveal:xt,onCopyPath:bt}),x.mode==="unpreviewable"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?m("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):m("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:xt,className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),c.jsx("button",{onClick:xt,className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:m("common:open",{defaultValue:"Open"})}),c.jsx("button",{onClick:bt,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${P?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:P?m("common:copied",{defaultValue:"Copied"}):m("common:copy",{defaultValue:"Copy"})})]})]})]},`${Ge}#${D}`)]}),E&&i&&c.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:E.x,top:E.y-8},children:c.jsxs("button",{onMouseDown:he=>{he.preventDefault(),he.stopPropagation(),He(E.text,E.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),m("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),T&&Ze&&c.jsx(VC,{item:Ze,onClose:()=>R(!1),onShared:Xt})]})}function CD({members:s,candidates:e,currentUserId:t,memberCount:r,onClose:i,onRemoveMember:n,onAddMember:a}){const{t:o}=Pt(["team","common"]);return c.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[o("page.members")," (",r,")"]}),c.jsx("button",{onClick:i,className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(l=>c.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${l.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[c.jsx(Ns,{name:l.name,size:16,bgClass:l.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),l.name,l.id!==t&&c.jsx("button",{onClick:()=>n(l.id),className:"ml-0.5 hover:text-red-500 transition-colors",title:o("common:remove"),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},l.id))}),e.length>0&&c.jsx("div",{className:"mt-1",children:c.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:l=>{l.target.value&&a(l.target.value)},children:[c.jsx("option",{value:"",children:o("page.addMemberPlaceholder")}),e.map(l=>c.jsxs("option",{value:l.id,children:["[",l.type==="agent"?"Agent":"Human","] ",l.name]},l.id))]})})]})}const PD={text:"page.findFieldText",thinking:"page.findFieldThinking",tool:"page.findFieldTool"},TD={text:"bg-brand-500/10 text-brand-500",thinking:"bg-amber-500/10 text-amber-600",tool:"bg-sky-500/10 text-sky-600"};function QD({match:s}){const e=s.snippet.slice(0,s.snippetMatchStart),t=s.snippet.slice(s.snippetMatchStart,s.snippetMatchStart+s.snippetMatchLength),r=s.snippet.slice(s.snippetMatchStart+s.snippetMatchLength);return c.jsxs("span",{className:"text-xs text-fg-secondary",children:[e,c.jsx("mark",{className:"bg-yellow-500/30 text-fg-primary rounded-[3px] px-0.5",children:t}),r]})}function $D({query:s,onQueryChange:e,matches:t,cursor:r,scanned:i,hasMore:n,loadingMore:a,truncated:o,onLoadEarlier:l,onJump:h,onClose:d,labelFor:u,serverResults:f,serverLoading:p,onServerResultClick:v}){const{t:b,i18n:g}=Pt(["team","common"]),O=S.useRef(null),m=S.useRef(null);S.useEffect(()=>{O.current?.focus()},[]),S.useEffect(()=>{if(r<0)return;m.current?.querySelector(`[data-find-idx="${r}"]`)?.scrollIntoView({block:"nearest"})},[r]);const x=k=>{if(t.length===0)return;const P=(((r<0?k>=0?-1:0:r)+k)%t.length+t.length)%t.length;h(P)},y=s.trim().length>0;return c.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/60 px-4 py-2 space-y-1.5 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsxs("div",{className:"flex-1 relative",children:[c.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),c.jsx("input",{ref:O,value:s,onChange:k=>e(k.target.value),onKeyDown:k=>{k.key==="Escape"?(k.preventDefault(),d()):k.key==="Enter"?(k.preventDefault(),x(k.shiftKey?-1:1)):k.key==="ArrowDown"?(k.preventDefault(),x(1)):k.key==="ArrowUp"&&(k.preventDefault(),x(-1))},placeholder:b("page.findPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),c.jsx("span",{className:"text-[11px] text-fg-tertiary tabular-nums shrink-0 min-w-[44px] text-center",children:y&&t.length>0?b("page.findMatchCount",{current:(r<0?0:r)+1,total:t.length}):y?"0/0":""}),c.jsx("button",{onClick:()=>x(-1),disabled:t.length===0,title:b("page.findPrev"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"18 15 12 9 6 15"})})}),c.jsx("button",{onClick:()=>x(1),disabled:t.length===0,title:b("page.findNext"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})}),c.jsx("button",{onClick:d,title:b("page.findClose"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated transition-colors",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y&&c.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:b("page.findScopeLoaded",{count:i})}),o&&c.jsx("span",{className:"text-amber-600",children:b("page.findTruncated",{count:t.length})}),t.length===0&&!n&&c.jsx("span",{className:"text-fg-secondary",children:b("page.findNoMatches")}),n&&c.jsx("button",{onClick:l,disabled:a,className:"ml-auto text-brand-500 hover:text-brand-500 disabled:opacity-50 underline decoration-dotted",children:b(a?"page.findLoadingEarlier":"page.findLoadEarlier")})]}),y&&t.length>0&&c.jsx("div",{ref:m,className:"max-h-52 overflow-y-auto scrollbar-thin space-y-0.5",children:t.map((k,C)=>c.jsxs("button",{"data-find-idx":C,onClick:()=>h(C),className:`w-full text-left px-2.5 py-1.5 rounded-lg transition-colors ${C===r?"bg-brand-500/15 ring-1 ring-brand-500/40":"hover:bg-surface-elevated"}`,children:[c.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${TD[k.field]}`,children:b(PD[k.field])}),u&&c.jsx("span",{className:"text-[10px] text-fg-tertiary truncate",children:u(k)})]}),c.jsx("div",{className:"line-clamp-2 break-words",children:c.jsx(QD,{match:k})})]},`${k.messageId}-${k.field}-${C}`))}),y&&(p||f&&f.length>0)&&c.jsxs("div",{className:"border-t border-border-default/60 mt-1 px-1",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-medium py-0.5",children:b("page.findServerResultsTitle")}),p&&c.jsx("div",{className:"text-xs text-fg-tertiary px-2.5 py-1",children:b("page.searching")}),f&&f.length>0&&c.jsx("div",{className:"max-h-40 overflow-y-auto scrollbar-thin space-y-0.5",children:f.map(k=>c.jsxs("button",{onClick:()=>v?.(k),className:"w-full text-left px-2.5 py-1.5 rounded-lg transition-colors hover:bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-fg-tertiary mb-0.5 min-w-0",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${k.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:k.source==="channel"?"#":"1:1"}),c.jsx("span",{className:"truncate max-w-[9rem] text-fg-secondary font-medium",children:k.source==="channel"?k.channel?`#${k.channel}`:b("page.findServerResultsTitle"):k.sessionTitle||b("page.untitledSession")}),k.senderName&&c.jsx("span",{className:"truncate max-w-[6rem] shrink-0",children:k.senderName}),c.jsx("span",{className:"shrink-0 ml-auto tabular-nums",title:zm(k.createdAt,g.language),children:Xm(k.createdAt,b)})]}),c.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 break-words",children:k.text.length>200?k.text.slice(0,200)+"…":k.text})]},k.id))})]})]})}const jD=300,RD=48;function ED(s){const e=[];if(s.segments&&s.segments.length>0){for(const t of s.segments)if(t.type==="text")t.thinking&&e.push({field:"thinking",value:t.thinking}),t.content&&e.push({field:"text",value:t.content});else if(t.type==="tool"){const r=[t.tool,t.result,t.error].filter(i=>!!i);r.length>0&&e.push({field:"tool",value:r.join(`
|
|
58
|
-
`)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function AD(s,e,t,r=RD){const i=Math.max(0,e-r),n=Math.min(s.length,e+t+r),a=i>0?"…":"",o=n<s.length?"…":"",l=s.slice(i,e).replace(/\s+/g," "),h=s.slice(e,e+t).replace(/\s+/g," "),d=s.slice(e+t,n).replace(/\s+/g," ");return{text:`${a}${l}${h}${d}${o}`,matchStart:a.length+l.length,matchLength:h.length}}function MD(s,e,t={}){const r=t.limit??jD,i=e.trim().toLocaleLowerCase();if(i.length===0)return{matches:[],scanned:s.length,truncated:!1};const n=[];for(let a=0;a<s.length;a+=1){const o=s[a];for(const{field:l,value:h}of ED(o)){const d=h.toLocaleLowerCase();let u=0;for(;;){const f=d.indexOf(i,u);if(f===-1)break;const p=AD(h,f,i.length);if(n.push({messageIndex:a,messageId:o.id,field:l,snippet:p.text,snippetMatchStart:p.matchStart,snippetMatchLength:p.matchLength}),n.length>=r)return{matches:n,scanned:s.length,truncated:!0};u=f+i.length}}}return{matches:n,scanned:s.length,truncated:!1}}function LD(s,e,t){if(s.length<=500)return s;const n=s.findIndex(o=>o.id===e);if(n<0)return s.slice(-500);const a=Math.max(0,Math.min(n-20,s.length-500));return s.slice(a,a+500)}async function ND(s){const{targetId:e,has:t,fetchPage:r,targetCreatedAt:i,maxPages:n=40}=s;if(t(e))return{found:!0,messages:[],hasMore:!0,oldestCursor:null,exhausted:!1};const a=i?Date.parse(i):Number.NaN;let o=[],l,h=!0,d=!1,u=!1;const f=()=>o.length>0?o[0].createdAt:null;for(let p=0;p<n;p++){let v;try{v=await r(l)}catch{return{found:!1,messages:o,hasMore:h,oldestCursor:f(),exhausted:!1}}const b=v?.messages??[];if(b.length===0){d=!0,h=!1;break}if(o=[...b,...o],h=!!v.hasMore,b.some(m=>m.id===e)){u=!0;break}if(!h){d=!0;break}const g=b[0],O=Date.parse(g.createdAt);if(Number.isFinite(a)&&Number.isFinite(O)&&O<a)break;l=g.createdAt}return{found:u,messages:o,hasMore:h,oldestCursor:f(),exhausted:d}}const DD="markus.scrollDebug";let Sf=null,pv=!1;function ID(){if(!pv){try{Sf=typeof localStorage<"u"&&localStorage.getItem(DD)==="1"}catch{Sf=!1}pv=!0}return Sf===!0}function zi(s,e){ID()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}function BD(s){if(!s||s.status&&s.status!=="pending"||s.type!=="action"||Array.isArray(s.questions)&&s.questions.length>0)return!1;const e=s.details?.toolName;return typeof e=="string"&&e.length>0}function WD(s){return s.details?.agentId??s.agentId}function XD(s){const e=s.details??{};return[e.chatSessionId,e.sessionId].filter(t=>typeof t=="string"&&t.length>0)}function zD(s,e){const t=s.filter(n=>BD(n)&&WD(n)===e.agentId);if(!e.sessionId)return t;const r=[],i=[];for(const n of t)(XD(n).includes(e.sessionId)?r:i).push(n);return[...r,...i]}const gv={urgent:0,high:1,normal:2,low:3};function Ov(s){return gv[s??"normal"]??gv.normal}function qD(s){return[...s].sort((e,t)=>{const r=Ov(e.priority)-Ov(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function ZD(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Mm(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}function VD(s,e){return e?qD(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&ZD(t)===e)):[]}const xv={sessionId:null,messageId:null};function FD(s){if(s.length===0)return xv;const e=new Set(s.map(Mm).filter(n=>!!n));if(e.size!==1||s.some(n=>!Mm(n)))return xv;const t=[...e][0],i=[...s].sort((n,a)=>new Date(n.createdAt).getTime()-new Date(a.createdAt).getTime()).map(n=>n.metadata?.messageId).find(n=>typeof n=="string"&&n.length>0)??null;return{sessionId:t,messageId:i}}const $_={system_event:{icon:"⚙",category:"system"},human_chat:{icon:"💬",category:"interaction"},task_comment:{icon:"💬",category:"task"},mention:{icon:"@",category:"interaction"},session_reply:{icon:"↩",category:"task"},task_status_update:{icon:"📋",category:"task"},a2a_message:{icon:"🔗",category:"interaction"},review_request:{icon:"👀",category:"task"},requirement_comment:{icon:"💬",category:"task"},requirement_update:{icon:"📝",category:"notification"},daily_report:{icon:"📊",category:"system"},heartbeat:{icon:"♡",category:"system"},memory_consolidation:{icon:"🧠",category:"system"},workflow_update:{icon:"🔄",category:"task"},callback_result:{icon:"↩",category:"system"}};function Nc(s){return s?$_[s]?.icon??"●":"●"}const UD=["interaction","task","notification","system"].reduce((s,e)=>(s[e]=Object.entries($_).filter(([,t])=>t.category===e).map(([t])=>t),s),{}),HD=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","task_request_approval","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update","office_generate"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_ask_agent","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_","recall_context","recall_activity","notebook_upsert","notebook_clear","notebook_read","session"]},{id:"knowledge",prefixes:["kb_search","kb_list","kb_read"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"reasoning",prefixes:["decide"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function YD(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of HD){const l=e(`agent:toolCategories.${a}`),h=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));h.length>0&&(t.set(l,h),h.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function GD(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function KD({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const JD=[/^Comment on task "(.+?)" from (.+)$/,/^Comment on requirement "(.+?)" from (.+)$/];function bv(s){if(!s)return null;for(const e of JD){const t=e.exec(s);if(t)return{subject:t[1],author:t[2]}}return null}const j_=16;function eI(s,e,t=j_){const r=s??[];return r.length<=t?{visible:[...r],hiddenCount:0,collapsible:!1}:e?{visible:[...r],hiddenCount:0,collapsible:!0}:{visible:r.slice(0,t),hiddenCount:r.length-t,collapsible:!0}}function tI(s,e=Date.now()){const t=Math.max(0,e-(Number.isFinite(s)?s:e));return t<6e4?{unit:"seconds",count:Math.round(t/1e3)}:t<36e5?{unit:"minutes",count:Math.round(t/6e4)}:{unit:"hours",count:Math.round(t/36e5*10)/10}}const sI=S.lazy(()=>Xv(()=>import("./index-BXWHxoXp.js").then(s=>s.bn),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),ih={mind:"mind",files:"files",tools:"tools",memory:"memory"},ag=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function Lm(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function rI(s,e){const{labelKey:t}=qh(s);return t?e(t):s}function Nm(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function vv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:d}=Pt(["agent","common"]),u=qm(),[f,p]=S.useState(null),[v,b]=S.useState(null),[g,O]=S.useState(r??"overview"),m=o&&l?l:g,[x,y]=S.useState(null),k=S.useMemo(()=>ag.map(F=>({...F,label:d(`agent:tabs.${F.key}`)})),[d]),C=S.useMemo(()=>k.map(F=>({id:F.key})),[k]),P=S.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=eC(C,g,O,P),T=S.useRef(null);S.useEffect(()=>{const F=T.current;if(!F)return;F.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[g]);const R=S.useCallback(()=>{te.agents.get(s).then(p).catch(()=>{})},[s]);if(S.useEffect(()=>(O(r??"overview"),y(null),R(),te.externalAgents.list().then(X=>{const ae=X.agents.find(j=>j.markusAgentId===s);y(ae??null)}).catch(()=>{}),St.on("agent:update",X=>{X.payload.agentId===s&&R()})),[s,R]),!f)return c.jsx(zv,{label:d("agent:profilePage.loadingAgent")});const L=qh(f.state.status).dotClass,M=a?.role==="owner"||a?.role==="admin",E=F=>h??ih[F],B=F=>x||ih[F]?"overview":F,U=ih[g];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[B(m)==="overview"&&c.jsx(Sv,{agent:f,onUpdate:R,externalInfo:x,t:d,canManageAgents:M,highlightMailboxId:n,initialSection:E(m)}),B(m)==="deliverables"&&c.jsx(Rv,{agentId:s})]})}):c.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Ns,{name:f.name,avatarUrl:f.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:f.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${L}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:rI(f.state.status,d)}),x&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:d("agent:profilePage.badges.external")}),f.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:d("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[f.role,f.roleDescription?` — ${f.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.jsxs("button",{onClick:()=>Lr.navigate(Yt.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[c.jsx("span",{children:"◈"})," ",d("agent:profilePage.chat")]}),M&&c.jsxs("button",{onClick:async()=>{if(f)try{const{filesMap:F}=await te.agents.getFilesMap(s),X={type:"agent",name:Bv(f.name,f.name),displayName:f.name,version:"1.0.0",description:f.roleDescription??f.role,author:"",category:"general",tags:[],agent:{roleName:f.role,agentRole:f.agentRole},dependencies:{skills:f.skills??[]}};await Fm.publishViaProxy({itemType:"agent",name:f.name,description:X.description,category:"general",config:X,files:F}),b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(F){b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishFailed",{error:String(F)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:d("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",d("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:T,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:k.filter(F=>!x||F.key==="overview").map(F=>c.jsxs("button",{onClick:()=>O(F.key),"data-active":g===F.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===F.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{className:"mr-1",children:F.icon}),F.label]},F.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:u?_.onTouchStart:void 0,onTouchEnd:u?_.onTouchEnd:void 0,children:[B(g)==="overview"&&c.jsx(Sv,{agent:f,onUpdate:R,externalInfo:x,t:d,canManageAgents:M,highlightMailboxId:n,initialSection:h??U}),B(g)==="deliverables"&&c.jsx(Rv,{agentId:s})]}),v&&c.jsx(Wo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function iI({section:s,onChange:e,t}){return c.jsx("div",{role:"tablist",className:"flex border-b border-border-default overflow-x-auto scrollbar-hide",onTouchStart:r=>r.stopPropagation(),onTouchEnd:r=>r.stopPropagation(),children:Um.map(r=>{const i=r===s,n=t(`agent:profilePage.overview.sections.${r}.hint`,{defaultValue:""});return c.jsx("button",{type:"button",role:"tab","aria-selected":i,title:n||void 0,onClick:()=>e(r),className:`px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors cursor-pointer ${i?"border-brand-500 text-fg-primary font-medium":"border-transparent text-fg-tertiary hover:text-fg-secondary"}`,children:t(`agent:profilePage.overview.sections.${r}.title`)},r)})})}function fo({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function yv({agentId:s,act:e,dotClass:t,expanded:r,onToggle:i}){return c.jsxs("div",{children:[c.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:e.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(e.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:r?"▲":"▼"})]}),r&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Wh,{agentId:s,activityId:e.id})})]})}function Sv({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i,highlightMailboxId:n,initialSection:a}){const[o,l]=S.useState(null),[h,d]=S.useState([]),[u,f]=S.useState(null),[p,v]=S.useState(null),[b,g]=S.useState(""),[O,m]=S.useState([]),[x,y]=S.useState(0),[k,C]=S.useState(!1),[P,_]=S.useState(!1),[T,R]=S.useState(()=>r0(a,n));S.useEffect(()=>{R(r0(a,n))},[a,n]);const L=(s.state.activeTaskIds??[]).join(",");S.useEffect(()=>{te.usage.agents().then(D=>{const V=D.agents.find(se=>se.agentId===s.id);V&&l(V)}).catch(()=>{}),s.state.activeTaskIds?.length&&te.tasks.list({assignedAgentId:s.id}).then(D=>{m(D.tasks.filter(V=>s.state.activeTaskIds?.includes(V.id)))}).catch(()=>{}),te.agents.getMailbox(s.id,{limit:1}).then(D=>{y(D.queued?.length??0)}).catch(()=>{})},[s.id,L,s.state.status]),S.useEffect(()=>{if(T!=="usage")return;let D=!1;return C(!0),te.system.storage().then(V=>{if(D)return;g(V.dataDir+"/agents/"+s.id);const se=V.agents.find(fe=>fe.id===s.id);se&&v(se)}).catch(()=>{}).finally(()=>{D||C(!1)}),()=>{D=!0}},[T,s.id]),S.useEffect(()=>{if(T!=="recent")return;let D=!1;return _(!0),te.agents.getActivities(s.id,{limit:H2}).then(V=>{D||d(V.activities)}).catch(()=>{}).finally(()=>{D||_(!1)}),()=>{D=!0}},[T,s.id]);const M=()=>{s.state.status==="offline"?te.agents.start(s.id).then(e):te.agents.stop(s.id).then(e)},E=S.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),B=S.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(ms,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(ms,{title:r("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(ms,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(ms,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:B.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:D.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:D.desc})]},D.field))})}),c.jsx(ms,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:E.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${D.method==="POST"?"text-amber-600":"text-green-600"}`,children:D.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:D.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:D.desc})]},D.path))})})]});const{heartbeats:U,comms:F}=Y2(h),X=s0(U),ae=s0(F),j=s.state.activeTaskIds?.length??0,W=[h.length>0?r("agent:profilePage.overview.recentWindow",{count:h.length}):null,X.total>0?r("agent:profilePage.overview.heartbeatRuns",{count:X.total}):null,ae.total>0?r("agent:profilePage.overview.a2aRuns",{count:ae.total}):null].filter(Boolean).join(" · ");return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.model"),children:s.effectiveModel?.model?c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx("span",{className:"font-mono",children:s.effectiveModel.model}),s.config?.llmConfig?.modelMode==="custom"&&s.effectiveModel.source!=="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeAgentModel")}):s.effectiveModel.source==="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:r("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Nm(z2(o,s.state.tokensUsedToday))}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(j),color:j>0?"blue":void 0}),i&&c.jsx("button",{onClick:M,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:nh(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(j>0||x>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),O.map(D=>c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:D.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Lm(D.status,r)})]},D.id)),x>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:x})})]})]})})]}),c.jsx(iI,{section:T,onChange:R,t:r}),T==="usage"&&c.jsx(fo,{children:o||p?c.jsxs("div",{className:"space-y-2",children:[o&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.lifetimeCaption")}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Nm(o.totalTokens)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.requests"),value:String(o.requestCount)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(o.toolCalls)})]})]}),p&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.storage"),value:Tv(p.size)}),q2(p.subItems).map(D=>{const V=V2(D.name);return c.jsx(Ks,{label:V?r(V):D.name,value:Tv(D.size)},D.name)}),c.jsxs("button",{onClick:()=>{te.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]}),p.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.storageDepthLimited")})]})]}):k?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.usage.empty")})}),T==="recent"&&c.jsxs(fo,{children:[W&&c.jsx("p",{className:"text-[10px] text-fg-tertiary mb-2",children:W}),X.total>0&&c.jsxs("div",{children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentHeartbeats")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:X.shown.map(D=>c.jsx(yv,{agentId:s.id,act:D,dotClass:"bg-green-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),ae.total>0&&c.jsxs("div",{className:"mt-3",children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentA2A")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:ae.shown.map(D=>c.jsx(yv,{agentId:s.id,act:D,dotClass:"bg-blue-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),X.total===0&&ae.total===0&&(P?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.recent.empty")}))]}),T==="mind"&&c.jsx(fo,{children:c.jsx(wI,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),T==="files"&&c.jsx(fo,{children:c.jsx(lI,{agentId:s.id})}),T==="tools"&&c.jsx(fo,{children:c.jsx(fI,{tools:s.tools??[],agent:s})}),T==="memory"&&c.jsxs(fo,{children:[c.jsx(pI,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(mI,{agentId:s.id})})]})]})}function nI(s,e){const t=s.split(`
|
|
57
|
+
`)}}return null},[i,s,je,K,pe,x]),[Pe,At]=S.useState(!1),Ft=S.useCallback(()=>{vt&&(i?.(vt),At(!0),setTimeout(()=>At(!1),1200))},[vt,i]),Es=S.useCallback(async()=>{if(s.kind==="deliverable"){Lr.navigate(Yt.DELIVERABLES,{openDeliverable:s.deliverable.id});return}if(s.kind==="url"){let ce=s.url;if(s.browserId&&window.markusDesktop?.browser)try{const $e=await window.markusDesktop.browser.getState(s.browserId);if($e.ok){if($e.directoryPath){await te.system.openPath($e.directoryPath).catch(()=>te.files.reveal($e.directoryPath));return}$e.url&&$e.url!=="about:blank"&&(ce=$e.url)}}catch{}if(!ce||ce==="about:blank")return;if(/^https?:\/\//i.test(ce)||/^file:\/\//i.test(ce)){lc(ce);return}await te.system.openPath(ce).catch(()=>lc(mv(ce)));return}if(s.kind!=="file")return;const he=s.path;if(he){if(/^https?:\/\//i.test(he)||/^file:\/\//i.test(he)){lc(he);return}await te.system.openPath(he).catch(()=>lc(mv(he)))}},[s]),rt=s.kind==="deliverable"?!!s.deliverable.id:s.kind==="url"?!!(s.url&&s.url!=="about:blank")||!!s.browserId:s.kind==="file"?!!s.path:!1,yt=s.kind==="deliverable"?m("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):m("common:openInSystemBrowser"),Bt=!!K&&!uo(K)&&(s.kind==="file"||s.kind==="deliverable"),ut=s.kind==="deliverable"&&s.deliverable.type==="file"&&!!K&&!uo(K)&&!s.deliverable.artifactType&&qC(s.deliverable.format),Ze=s.kind==="deliverable"?{...s.deliverable,hubShareId:L?.id??s.deliverable.hubShareId??null,shareStatus:L?.status??s.deliverable.shareStatus??null,shareUrl:L?.url??s.deliverable.shareUrl??null,shareVisibility:L?.visibility??s.deliverable.shareVisibility??null}:null,Xt=S.useCallback(he=>{M(he)},[]),ot=S.useMemo(()=>ZC(vO,Fm.getUrl()),[]),Mt=s.kind==="deliverable"?s.deliverable.id:null;S.useEffect(()=>{if(!Mt||!vO())return;let he=!1;const ce=async()=>{try{const Xe=await ot.listMine();if(he)return;const de=s.kind==="deliverable"?s.deliverable:null;if(!de)return;const De=de.hubShareId&&Xe.find(ze=>ze.id===de.hubShareId)||Xe.find(ze=>ze.localId===de.id);if(!De)return;M(ze=>ze&&ze.id===De.id&&ze.status===De.status?ze:De);const ve={hubShareId:de.hubShareId??De.id??null,shareStatus:De.status??null,shareUrl:De.url??null,shareVisibility:de.shareVisibility??De.visibility??null};(de.shareStatus!==ve.shareStatus||de.hubShareId!==ve.hubShareId||de.shareUrl!==ve.shareUrl||de.shareVisibility!==ve.shareVisibility)&&de.id&&te.deliverables.update(de.id,ve).catch(ze=>{console.warn("[right-panel] Hub 分享状态本地持久化失败:",ze)})}catch{}};ce();const $e=setInterval(ce,3e4);return()=>{he=!0,clearInterval($e)}},[ot,Mt,s]);const us=Ze?.shareStatus??null;return c.jsxs(c.Fragment,{children:[!d&&c.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:c.jsx("div",{className:"w-px h-2/3 border-l border-dashed border-transparent group-hover:border-border-default group-active:border-fg-tertiary transition-colors"})}),c.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${d?"flex-1 min-w-0":"shrink-0"}`,style:d?void 0:{width:t},"data-right-panel":!0,children:[c.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[v&&c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pr-1 border-r border-border-default/60",children:[c.jsx("button",{type:"button",onClick:()=>v("browser"),title:m("common:browserMode",{defaultValue:"Browser"}),"aria-label":m("common:browserMode",{defaultValue:"Browser"}),"aria-pressed":p==="browser",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="browser"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"10"}),c.jsx("line",{x1:"2",y1:"12",x2:"22",y2:"12"}),c.jsx("path",{d:"M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z"})]})}),c.jsx("button",{type:"button",onClick:()=>v("terminal"),title:m("common:terminalMode",{defaultValue:"Terminal"}),"aria-label":m("common:terminalMode",{defaultValue:"Terminal"}),"aria-pressed":p==="terminal",className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${p==="terminal"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 17 10 11 4 5"}),c.jsx("line",{x1:"12",y1:"19",x2:"20",y2:"19"})]})})]}),we||h?c.jsxs("div",{"data-no-drag":!0,className:"flex-1 min-w-0 self-stretch flex flex-col justify-end",children:[c.jsxs("div",{ref:Z,role:"tablist",className:"flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-hide",onWheel:he=>{const ce=he.currentTarget;ce.scrollWidth<=ce.clientWidth||Math.abs(he.deltaY)<=Math.abs(he.deltaX)||(ce.scrollLeft+=he.deltaY,he.preventDefault())},children:[n?.map(he=>{const ce=he.id===a,$e=he.payload.kind==="url"?he.payload.pageId:void 0,Xe=he.payload.kind==="terminal"?he.payload.terminalId:void 0,de=$e!=null?U[$e]:Xe?X[Xe]:void 0,De=de?`${he.title} — ${m("common:browserTabControlledBy",{name:de.agentName})}`:he.title;return c.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${ce?de?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":de?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsxs("button",{type:"button",role:"tab","aria-selected":ce,ref:ce?A:void 0,className:"min-w-0 flex-1 truncate pl-2.5 pr-1 py-1 text-left cursor-pointer flex items-center gap-1",title:De,onPointerDown:ve=>{ve.button===0&&(he.id!==a&&!oe()||o?.(he.id))},onClick:()=>{he.id!==a&&!oe()||o?.(he.id)},children:[de&&c.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:m("common:browserTabControlledBy",{name:de.agentName}),children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),c.jsx("span",{className:"truncate",children:de.agentName})]}),c.jsx("span",{className:"truncate min-w-0",children:he.title})]}),l&&c.jsx("button",{type:"button",onPointerDown:ve=>{ve.button===0&&(ve.preventDefault(),ve.stopPropagation(),!(he.id===a&&!oe())&&l(he.id))},onClick:ve=>{ve.preventDefault(),ve.stopPropagation(),!(he.id===a&&!oe())&&l(he.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ce?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:m("common:closeTab",{defaultValue:"Close tab"}),"aria-label":m("common:closeTab",{defaultValue:"Close tab"}),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},he.id)}),h&&c.jsx("button",{type:"button",onClick:h,className:"shrink-0 w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/60 transition-colors",title:m("common:newTab",{defaultValue:"New Tab"}),"aria-label":m("common:newTab",{defaultValue:"New Tab"}),children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),c.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}),c.jsx(vD,{scrollRef:Z,watch:`${n?.length??0}:${a??""}`})]}):c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:K||pe,children:pe}),c.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[Qe&&c.jsx("button",{type:"button",onClick:ye,title:m("common:refreshPreview",{defaultValue:"刷新"}),"aria-label":m("common:refreshPreview",{defaultValue:"刷新"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{className:x.mode==="loading"?"animate-spin":"",width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"23 4 23 10 17 10"}),c.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}),Qe&&c.jsx("button",{type:"button",onClick:()=>fe(he=>!he),"aria-pressed":se,title:se?m("common:autoRefreshOn",{defaultValue:"自动刷新:已开启"}):m("common:autoRefreshOff",{defaultValue:"自动刷新:已关闭"}),"aria-label":se?m("common:autoRefreshOn",{defaultValue:"自动刷新:已开启"}):m("common:autoRefreshOff",{defaultValue:"自动刷新:已关闭"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${se?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"12",r:"9"}),c.jsx("circle",{cx:"12",cy:"12",r:"3",fill:"currentColor",stroke:"none"})]})}),s.kind==="terminal"&&i&&c.jsx("button",{type:"button",onClick:()=>{Ye()},title:m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),"aria-label":m("common:addRecentOutput",{defaultValue:"Add recent output to chat"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),vt&&c.jsx("button",{type:"button",onClick:Ft,title:Pe?m("common:addedToChat",{defaultValue:"Added to chat"}):s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),"aria-label":s.kind==="deliverable"?m("common:addDeliverableToChat",{defaultValue:"Add deliverable to chat"}):m("common:addFilePathToChat",{defaultValue:"Add file path to chat"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${Pe?"text-green-500 bg-green-500/10":"text-fg-tertiary hover:text-brand-500 hover:bg-brand-500/10"}`,children:Pe?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h6"}),c.jsx("line",{x1:"17",y1:"3",x2:"17",y2:"9"}),c.jsx("line",{x1:"14",y1:"6",x2:"20",y2:"6"})]})}),ut&&c.jsxs("button",{type:"button",onClick:()=>R(!0),title:m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),"aria-label":m("deliverables:share.title",{defaultValue:"分享到 Markus Hub"}),className:`relative w-7 h-7 flex items-center justify-center rounded-md transition-colors ${us==="published"?"text-green-500 hover:text-green-400":us==="pending_review"?"text-amber-500 hover:text-amber-400":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"18",cy:"5",r:"3"}),c.jsx("circle",{cx:"6",cy:"12",r:"3"}),c.jsx("circle",{cx:"18",cy:"19",r:"3"}),c.jsx("line",{x1:"8.59",y1:"13.51",x2:"15.42",y2:"17.49"}),c.jsx("line",{x1:"15.41",y1:"6.51",x2:"8.59",y2:"10.49"})]}),(us==="published"||us==="pending_review"||us==="rejected")&&c.jsx("span",{className:`absolute -top-0.5 -right-0.5 w-2 h-2 rounded-full border border-surface-primary ${us==="published"?"bg-green-500":us==="pending_review"?"bg-amber-500":"bg-red-500"}`,"aria-hidden":!0})]}),rt&&c.jsx("button",{type:"button",onClick:()=>{Es()},title:yt,"aria-label":yt,className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),Bt&&c.jsx("button",{onClick:bt,title:P?m("common:copied",{defaultValue:"Copied"}):m("common:copyPath",{defaultValue:"复制路径"}),"aria-label":m("common:copyPath",{defaultValue:"复制路径"}),className:`w-7 h-7 flex items-center justify-center rounded-md transition-colors ${P?"text-green-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,children:P?c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"20 6 9 17 4 12"})}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),c.jsx("path",{d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})}),Bt&&c.jsx("button",{onClick:xt,title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M22 19a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h5l2 3h9a2 2 0 0 1 2 2z"})})}),u&&c.jsx("button",{onClick:u,title:d?m("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):m("common:fullscreen",{defaultValue:"Fullscreen"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:d?c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"4 14 10 14 10 20"}),c.jsx("polyline",{points:"20 10 14 10 14 4"}),c.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("polyline",{points:"15 3 21 3 21 9"}),c.jsx("polyline",{points:"9 21 3 21 3 15"}),c.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),c.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),c.jsx("button",{onClick:()=>{oe()&&e()},title:m("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":m("common:collapsePanel",{defaultValue:"Hide panel"}),className:"w-7 h-7 flex items-center justify-center rounded-md transition-colors text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),c.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${x.mode==="url"||x.mode==="terminal"||x.mode==="office"||x.mode==="directory"||x.mode==="content"&&["code","json","text","markdown","html"].includes(x.format)?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[k&&x.mode!=="directory"&&x.mode!=="loading"&&c.jsx("div",{className:"shrink-0 mb-2",children:c.jsxs("button",{className:"inline-flex items-center gap-1 text-xs text-fg-secondary hover:text-brand-500 transition-colors cursor-pointer",onClick:()=>C(_D(je)),children:[c.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 20 20",fill:"currentColor",children:c.jsx("path",{fillRule:"evenodd",d:"M17 10a.75.75 0 01-.75.75H5.612l4.158 3.96a.75.75 0 11-1.04 1.08l-5.5-5.25a.75.75 0 010-1.08l5.5-5.25a.75.75 0 111.04 1.08L5.612 9.25H16.25A.75.75 0 0117 10z",clipRule:"evenodd"})}),"返回上级目录"]})}),x.mode==="loading"&&c.jsxs("div",{className:"animate-pulse space-y-3",children:[c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),c.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),c.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),x.mode==="image"&&c.jsxs("div",{className:"flex flex-col items-center gap-2",children:[c.jsx("img",{src:x.src,alt:x.name,className:"max-w-full rounded-lg object-contain"}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:x.name})]}),x.mode==="audio"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M9 18V5l12-2v13"}),c.jsx("circle",{cx:"6",cy:"18",r:"3"}),c.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[x.mimeType,x.size!=null?` · ${yf(x.size)}`:""]})]})]}),c.jsx("audio",{controls:!0,preload:"metadata",src:x.src,className:"w-full"})]}),x.mode==="video"&&c.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[c.jsx("video",{controls:!0,preload:"metadata",src:x.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),c.jsxs("span",{className:"text-xs text-fg-tertiary",children:[x.name,x.size!=null?` · ${yf(x.size)}`:""]})]}),x.mode==="binary"&&c.jsxs("div",{className:"space-y-4 py-4",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-12 h-12 rounded-xl bg-surface-elevated text-fg-tertiary flex items-center justify-center shrink-0 text-xs font-mono uppercase",children:(x.extension||"file").replace(/^\./,"")||"file"}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:x.name}),c.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[m("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),x.size!=null?` · ${yf(x.size)}`:""]})]})]}),x.reference&&c.jsx("div",{className:"flex items-center gap-2",children:c.jsx("button",{onClick:()=>{te.files.reveal(x.reference)},className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),x.mode==="office"&&c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full",children:c.jsx(Kk,{data:{format:x.format,streamUrl:x.streamUrl,name:x.name,size:x.size},reference:x.reference,onFallback:x.reference?()=>{te.files.reveal(x.reference)}:void 0})}),x.mode==="content"&&(()=>{const he=K?K.replace(/[/\\][^/\\]+$/,""):void 0,ce=K&&!uo(K)?K:"",$e=x.format;return ce&&($e==="code"||$e==="json"||$e==="text")?c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(x_,{path:ce,initialContent:x.content,language:tg(ce,$e),onDirtyChange:W})}):ce&&($e==="markdown"||$e==="html")?c.jsx("div",{ref:re,className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(z4,{path:ce,content:x.content,format:$e,basePath:he,onHtmlSelection:pt,onDirtyChange:W})}):c.jsx("div",{ref:re,className:"min-w-0 max-w-full overflow-auto break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(kf,{content:x.content,format:$e,className:"text-fg-secondary text-sm",onHtmlSelection:pt,basePath:he})})})(),x.mode==="artifact"&&c.jsx("div",{ref:re,className:"min-w-0 max-w-full break-words [&_pre]:max-w-full [&_pre]:overflow-x-auto [&_table]:block [&_table]:max-w-full [&_table]:overflow-x-auto [&_img]:max-w-full",children:c.jsx(kf,{content:x.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),x.mode==="url"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(aD,{url:x.url,browserId:x.browserId,className:"flex-1 min-h-0",onMeta:x.browserId&&f?he=>f(x.browserId,he):void 0},x.browserId||x.url)}),x.mode==="terminal"&&c.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:c.jsx(OD,{terminalId:x.terminalId,title:x.title,cwd:x.cwd,active:!0,apiRef:J,onMeta:b,onOpenUrl:g,onOpenPath:O,onSelection:he=>{if(!he||!i){B(null);return}B({x:he.x,y:he.y,text:he.text})}},x.terminalId)}),x.mode==="directory"&&c.jsx(Jk,{path:x.path,entries:x.entries,onNavigate:he=>C(he),onOpenFile:he=>C(he),onReveal:xt,onCopyPath:bt}),x.mode==="unpreviewable"&&c.jsxs("div",{className:"space-y-3",children:[c.jsx("p",{className:"text-sm text-fg-secondary",children:x.isDirectory?m("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):m("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),x.reference&&c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:xt,className:"text-xs bg-surface-elevated px-3 py-2 rounded text-brand-500 hover:underline flex-1 truncate text-left cursor-pointer font-mono",title:m("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:x.reference}),c.jsx("button",{onClick:xt,className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors shrink-0",children:m("common:open",{defaultValue:"Open"})}),c.jsx("button",{onClick:bt,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${P?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:P?m("common:copied",{defaultValue:"Copied"}):m("common:copy",{defaultValue:"Copy"})})]})]})]},`${Ge}#${D}`)]}),E&&i&&c.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full rounded-lg shadow-xl overflow-hidden border border-brand-400/40 bg-brand-600",style:{left:E.x,top:E.y-8},children:c.jsxs("button",{onMouseDown:he=>{he.preventDefault(),he.stopPropagation(),He(E.text,E.htmlMeta)},className:"px-3 py-1.5 text-xs font-medium text-white hover:bg-brand-500 transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})}),m("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})}),T&&Ze&&c.jsx(VC,{item:Ze,onClose:()=>R(!1),onShared:Xt})]})}function CD({members:s,candidates:e,currentUserId:t,memberCount:r,onClose:i,onRemoveMember:n,onAddMember:a}){const{t:o}=Pt(["team","common"]);return c.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[c.jsxs("div",{className:"flex items-center justify-between",children:[c.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[o("page.members")," (",r,")"]}),c.jsx("button",{onClick:i,className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),c.jsx("div",{className:"flex flex-wrap gap-1.5",children:s.map(l=>c.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${l.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[c.jsx(Ns,{name:l.name,size:16,bgClass:l.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),l.name,l.id!==t&&c.jsx("button",{onClick:()=>n(l.id),className:"ml-0.5 hover:text-red-500 transition-colors",title:o("common:remove"),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},l.id))}),e.length>0&&c.jsx("div",{className:"mt-1",children:c.jsxs("select",{className:"w-full bg-surface-primary border border-border-default rounded-lg px-2.5 py-1.5 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50",value:"",onChange:l=>{l.target.value&&a(l.target.value)},children:[c.jsx("option",{value:"",children:o("page.addMemberPlaceholder")}),e.map(l=>c.jsxs("option",{value:l.id,children:["[",l.type==="agent"?"Agent":"Human","] ",l.name]},l.id))]})})]})}const PD={text:"page.findFieldText",thinking:"page.findFieldThinking",tool:"page.findFieldTool"},TD={text:"bg-brand-500/10 text-brand-500",thinking:"bg-amber-500/10 text-amber-600",tool:"bg-sky-500/10 text-sky-600"};function QD({match:s}){const e=s.snippet.slice(0,s.snippetMatchStart),t=s.snippet.slice(s.snippetMatchStart,s.snippetMatchStart+s.snippetMatchLength),r=s.snippet.slice(s.snippetMatchStart+s.snippetMatchLength);return c.jsxs("span",{className:"text-xs text-fg-secondary",children:[e,c.jsx("mark",{className:"bg-yellow-500/30 text-fg-primary rounded-[3px] px-0.5",children:t}),r]})}function $D({query:s,onQueryChange:e,matches:t,cursor:r,scanned:i,hasMore:n,loadingMore:a,truncated:o,onLoadEarlier:l,onJump:h,onClose:d,labelFor:u,serverResults:f,serverLoading:p,onServerResultClick:v}){const{t:b,i18n:g}=Pt(["team","common"]),O=S.useRef(null),m=S.useRef(null);S.useEffect(()=>{O.current?.focus()},[]),S.useEffect(()=>{if(r<0)return;m.current?.querySelector(`[data-find-idx="${r}"]`)?.scrollIntoView({block:"nearest"})},[r]);const x=k=>{if(t.length===0)return;const P=(((r<0?k>=0?-1:0:r)+k)%t.length+t.length)%t.length;h(P)},y=s.trim().length>0;return c.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/60 px-4 py-2 space-y-1.5 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsxs("div",{className:"flex-1 relative",children:[c.jsx("svg",{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-fg-tertiary",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),c.jsx("input",{ref:O,value:s,onChange:k=>e(k.target.value),onKeyDown:k=>{k.key==="Escape"?(k.preventDefault(),d()):k.key==="Enter"?(k.preventDefault(),x(k.shiftKey?-1:1)):k.key==="ArrowDown"?(k.preventDefault(),x(1)):k.key==="ArrowUp"&&(k.preventDefault(),x(-1))},placeholder:b("page.findPlaceholder"),className:"w-full pl-8 pr-3 py-1.5 text-xs bg-surface-primary border border-border-default rounded-lg outline-none focus:border-brand-500/50 transition-colors"})]}),c.jsx("span",{className:"text-[11px] text-fg-tertiary tabular-nums shrink-0 min-w-[44px] text-center",children:y&&t.length>0?b("page.findMatchCount",{current:(r<0?0:r)+1,total:t.length}):y?"0/0":""}),c.jsx("button",{onClick:()=>x(-1),disabled:t.length===0,title:b("page.findPrev"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"18 15 12 9 6 15"})})}),c.jsx("button",{onClick:()=>x(1),disabled:t.length===0,title:b("page.findNext"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated disabled:opacity-40 disabled:hover:bg-transparent transition-colors",children:c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})})}),c.jsx("button",{onClick:d,title:b("page.findClose"),className:"p-1 rounded-md text-fg-tertiary hover:text-fg-primary hover:bg-surface-elevated transition-colors",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),y&&c.jsxs("div",{className:"flex items-center gap-2 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:b("page.findScopeLoaded",{count:i})}),o&&c.jsx("span",{className:"text-amber-600",children:b("page.findTruncated",{count:t.length})}),t.length===0&&!n&&c.jsx("span",{className:"text-fg-secondary",children:b("page.findNoMatches")}),n&&c.jsx("button",{onClick:l,disabled:a,className:"ml-auto text-brand-500 hover:text-brand-500 disabled:opacity-50 underline decoration-dotted",children:b(a?"page.findLoadingEarlier":"page.findLoadEarlier")})]}),y&&t.length>0&&c.jsx("div",{ref:m,className:"max-h-52 overflow-y-auto scrollbar-thin space-y-0.5",children:t.map((k,C)=>c.jsxs("button",{"data-find-idx":C,onClick:()=>h(C),className:`w-full text-left px-2.5 py-1.5 rounded-lg transition-colors ${C===r?"bg-brand-500/15 ring-1 ring-brand-500/40":"hover:bg-surface-elevated"}`,children:[c.jsxs("div",{className:"flex items-center gap-1.5 mb-0.5",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${TD[k.field]}`,children:b(PD[k.field])}),u&&c.jsx("span",{className:"text-[10px] text-fg-tertiary truncate",children:u(k)})]}),c.jsx("div",{className:"line-clamp-2 break-words",children:c.jsx(QD,{match:k})})]},`${k.messageId}-${k.field}-${C}`))}),y&&(p||f&&f.length>0)&&c.jsxs("div",{className:"border-t border-border-default/60 mt-1 px-1",children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-medium py-0.5",children:b("page.findServerResultsTitle")}),p&&c.jsx("div",{className:"text-xs text-fg-tertiary px-2.5 py-1",children:b("page.searching")}),f&&f.length>0&&c.jsx("div",{className:"max-h-40 overflow-y-auto scrollbar-thin space-y-0.5",children:f.map(k=>c.jsxs("button",{onClick:()=>v?.(k),className:"w-full text-left px-2.5 py-1.5 rounded-lg transition-colors hover:bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-fg-tertiary mb-0.5 min-w-0",children:[c.jsx("span",{className:`px-1.5 py-0 rounded text-[9px] font-medium shrink-0 ${k.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:k.source==="channel"?"#":"1:1"}),c.jsx("span",{className:"truncate max-w-[9rem] text-fg-secondary font-medium",children:k.source==="channel"?k.channel?`#${k.channel}`:b("page.findServerResultsTitle"):k.sessionTitle||b("page.untitledSession")}),k.senderName&&c.jsx("span",{className:"truncate max-w-[6rem] shrink-0",children:k.senderName}),c.jsx("span",{className:"shrink-0 ml-auto tabular-nums",title:zm(k.createdAt,g.language),children:Xm(k.createdAt,b)})]}),c.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 break-words",children:k.text.length>200?k.text.slice(0,200)+"…":k.text})]},k.id))})]})]})}const jD=300,RD=48;function ED(s){const e=[];if(s.segments&&s.segments.length>0){for(const t of s.segments)if(t.type==="text")t.thinking&&e.push({field:"thinking",value:t.thinking}),t.content&&e.push({field:"text",value:t.content});else if(t.type==="tool"){const r=[t.tool,t.result,t.error].filter(i=>!!i);r.length>0&&e.push({field:"tool",value:r.join(`
|
|
58
|
+
`)})}if(e.length>0)return e}return s.text&&e.push({field:"text",value:s.text}),e}function AD(s,e,t,r=RD){const i=Math.max(0,e-r),n=Math.min(s.length,e+t+r),a=i>0?"…":"",o=n<s.length?"…":"",l=s.slice(i,e).replace(/\s+/g," "),h=s.slice(e,e+t).replace(/\s+/g," "),d=s.slice(e+t,n).replace(/\s+/g," ");return{text:`${a}${l}${h}${d}${o}`,matchStart:a.length+l.length,matchLength:h.length}}function MD(s,e,t={}){const r=t.limit??jD,i=e.trim().toLocaleLowerCase();if(i.length===0)return{matches:[],scanned:s.length,truncated:!1};const n=[];for(let a=0;a<s.length;a+=1){const o=s[a];for(const{field:l,value:h}of ED(o)){const d=h.toLocaleLowerCase();let u=0;for(;;){const f=d.indexOf(i,u);if(f===-1)break;const p=AD(h,f,i.length);if(n.push({messageIndex:a,messageId:o.id,field:l,snippet:p.text,snippetMatchStart:p.matchStart,snippetMatchLength:p.matchLength}),n.length>=r)return{matches:n,scanned:s.length,truncated:!0};u=f+i.length}}}return{matches:n,scanned:s.length,truncated:!1}}function LD(s,e,t){if(s.length<=500)return s;const n=s.findIndex(o=>o.id===e);if(n<0)return s.slice(-500);const a=Math.max(0,Math.min(n-20,s.length-500));return s.slice(a,a+500)}async function ND(s){const{targetId:e,has:t,fetchPage:r,targetCreatedAt:i,maxPages:n=40}=s;if(t(e))return{found:!0,messages:[],hasMore:!0,oldestCursor:null,exhausted:!1};const a=i?Date.parse(i):Number.NaN;let o=[],l,h=!0,d=!1,u=!1;const f=()=>o.length>0?o[0].createdAt:null;for(let p=0;p<n;p++){let v;try{v=await r(l)}catch{return{found:!1,messages:o,hasMore:h,oldestCursor:f(),exhausted:!1}}const b=v?.messages??[];if(b.length===0){d=!0,h=!1;break}if(o=[...b,...o],h=!!v.hasMore,b.some(m=>m.id===e)){u=!0;break}if(!h){d=!0;break}const g=b[0],O=Date.parse(g.createdAt);if(Number.isFinite(a)&&Number.isFinite(O)&&O<a)break;l=g.createdAt}return{found:u,messages:o,hasMore:h,oldestCursor:f(),exhausted:d}}const DD="markus.scrollDebug";let Sf=null,pv=!1;function ID(){if(!pv){try{Sf=typeof localStorage<"u"&&localStorage.getItem(DD)==="1"}catch{Sf=!1}pv=!0}return Sf===!0}function zi(s,e){ID()&&console.info(`[scroll] ${s}`,{t:Math.round(performance.now()),...e??{}})}function BD(s){if(!s||s.status&&s.status!=="pending"||s.type!=="action"||Array.isArray(s.questions)&&s.questions.length>0)return!1;const e=s.details?.toolName;return typeof e=="string"&&e.length>0}function WD(s){return s.details?.agentId??s.agentId}function XD(s){const e=s.details??{};return[e.chatSessionId,e.sessionId].filter(t=>typeof t=="string"&&t.length>0)}function zD(s,e){const t=s.filter(n=>BD(n)&&WD(n)===e.agentId);if(!e.sessionId)return t;const r=[],i=[];for(const n of t)(XD(n).includes(e.sessionId)?r:i).push(n);return[...r,...i]}const gv={urgent:0,high:1,normal:2,low:3};function Ov(s){return gv[s??"normal"]??gv.normal}function qD(s){return[...s].sort((e,t)=>{const r=Ov(e.priority)-Ov(t.priority);return r!==0?r:new Date(t.createdAt).getTime()-new Date(e.createdAt).getTime()})}function ZD(s){const e=s.metadata?.agentId;return typeof e=="string"&&e?e:void 0}function Mm(s){const e=s.metadata??{};if(typeof e.sessionId=="string"&&e.sessionId)return e.sessionId;if(s.actionType==="open_chat"&&s.actionTarget)try{const t=typeof s.actionTarget=="string"?JSON.parse(s.actionTarget):s.actionTarget;if(t&&typeof t=="object"&&typeof t.sessionId=="string")return t.sessionId}catch{}}function VD(s,e){return e?qD(s.filter(t=>!t.read&&t.type==="agent_report"&&!t.metadata?.creditExhausted&&ZD(t)===e)):[]}const xv={sessionId:null,messageId:null};function FD(s){if(s.length===0)return xv;const e=new Set(s.map(Mm).filter(n=>!!n));if(e.size!==1||s.some(n=>!Mm(n)))return xv;const t=[...e][0],i=[...s].sort((n,a)=>new Date(n.createdAt).getTime()-new Date(a.createdAt).getTime()).map(n=>n.metadata?.messageId).find(n=>typeof n=="string"&&n.length>0)??null;return{sessionId:t,messageId:i}}const $_={system_event:{icon:"⚙",category:"system"},human_chat:{icon:"💬",category:"interaction"},task_comment:{icon:"💬",category:"task"},mention:{icon:"@",category:"interaction"},session_reply:{icon:"↩",category:"task"},task_status_update:{icon:"📋",category:"task"},a2a_message:{icon:"🔗",category:"interaction"},review_request:{icon:"👀",category:"task"},requirement_comment:{icon:"💬",category:"task"},requirement_update:{icon:"📝",category:"notification"},daily_report:{icon:"📊",category:"system"},heartbeat:{icon:"♡",category:"system"},memory_consolidation:{icon:"🧠",category:"system"},workflow_update:{icon:"🔄",category:"task"},callback_result:{icon:"↩",category:"system"}};function Nc(s){return s?$_[s]?.icon??"●":"●"}const UD=["interaction","task","notification","system"].reduce((s,e)=>(s[e]=Object.entries($_).filter(([,t])=>t.category===e).map(([t])=>t),s),{}),HD=[{id:"files",prefixes:["file_read","file_write","file_edit","apply_patch"]},{id:"search",prefixes:["grep_search","glob_find","list_directory"]},{id:"runtime",prefixes:["shell_execute","background_exec","process"]},{id:"terminal",prefixes:["terminal__","list_terminals","new_terminal","select_terminal","close_terminal","read_terminal","write_terminal","exec_terminal"]},{id:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video","describe_image","upload_reference"]},{id:"browser",prefixes:["navigate_page","new_page","close_page","select_page","list_pages","open_page","resize_page","click","hover","fill","fill_form","type_text","press_key","take_screenshot","take_snapshot","evaluate_script","wait_for","list_console_messages","list_network_requests","get_console_message","get_network_request","lighthouse_audit","drag","upload_file","emulate","handle_dialog"]},{id:"tasks",prefixes:["task_create","task_list","task_update","task_get","task_assign","task_note","task_comment","task_submit_review","task_request_approval","subtask_create","subtask_complete","subtask_cancel","subtask_list","task_check_duplicates","task_cleanup_duplicates","task_board_health","create_task","update_task","add_task_note","create_subtask"]},{id:"requirements",prefixes:["requirement_propose","requirement_list","requirement_get","requirement_update","requirement_update_status","requirement_resubmit","requirement_comment"]},{id:"projects",prefixes:["list_projects","get_project","create_project","update_project","delete_project","project_stats","project_structure","code_stats","git_"]},{id:"deliverables",prefixes:["deliverable_create","deliverable_search","deliverable_list","deliverable_update","office_generate"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","agent_ask_agent","agent_list_colleagues","agent_send_group_message","agent_create_group_chat","agent_list_group_chats","agent_broadcast_status","agent_delegate_task","feishu_"]},{id:"memory",prefixes:["memory_","recall_context","recall_activity","notebook_upsert","notebook_clear","notebook_read","session"]},{id:"knowledge",prefixes:["kb_search","kb_list","kb_read"]},{id:"mailbox",prefixes:["check_mailbox","defer_mailbox_item","drop_mailbox_item","prioritize_mailbox_item","delegate_message"]},{id:"planning",prefixes:["goal_create","goal_update","goal_status","workflow_"]},{id:"reasoning",prefixes:["decide"]},{id:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop","list_teams"]},{id:"subagents",prefixes:["spawn_subagent","spawn_subagents","invoke_coding_tool","coding_tool_apply"]},{id:"system",prefixes:["discover_tools","notify_user","request_user_input","request_user_approval","schedule_wakeup","cancel_wakeup","set_heartbeat_interval"]},{id:"llm",prefixes:["llm_","agent_model_"]}];function YD(s,e){const t=new Map,r=new Set;for(const{id:a,prefixes:o}of HD){const l=e(`agent:toolCategories.${a}`),h=s.filter(d=>!r.has(d.name)&&o.some(u=>d.name.startsWith(u)));h.length>0&&(t.set(l,h),h.forEach(d=>r.add(d.name)))}const i=s.filter(a=>!r.has(a.name));for(const a of i){const o=a.name.indexOf("__");if(o>0){const l=a.name.slice(0,o),h=e("agent:toolCategories.mcp",{server:l});t.has(h)||t.set(h,[]),t.get(h).push(a),r.add(a.name)}}const n=s.filter(a=>!r.has(a.name));return n.length>0&&t.set(e("agent:toolCategories.other"),n),[...t.entries()].map(([a,o])=>({category:a,tools:o}))}function GD(s){return!s.agentRunning||s.itemStatus!=="processing"||!s.currentFocusId?!1:s.currentFocusId===s.itemId}function KD({itemStatus:s,agentRunning:e,currentFocusMailboxItemId:t,itemId:r}){return s!=="processing"?s:e&&t===r?"processing":"stale"}const JD=[/^Comment on task "(.+?)" from (.+)$/,/^Comment on requirement "(.+?)" from (.+)$/];function bv(s){if(!s)return null;for(const e of JD){const t=e.exec(s);if(t)return{subject:t[1],author:t[2]}}return null}const j_=16;function eI(s,e,t=j_){const r=s??[];return r.length<=t?{visible:[...r],hiddenCount:0,collapsible:!1}:e?{visible:[...r],hiddenCount:0,collapsible:!0}:{visible:r.slice(0,t),hiddenCount:r.length-t,collapsible:!0}}function tI(s,e=Date.now()){const t=Math.max(0,e-(Number.isFinite(s)?s:e));return t<6e4?{unit:"seconds",count:Math.round(t/1e3)}:t<36e5?{unit:"minutes",count:Math.round(t/6e4)}:{unit:"hours",count:Math.round(t/36e5*10)/10}}const sI=S.lazy(()=>Xv(()=>import("./index-CIrsLoqm.js").then(s=>s.bn),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),ih={mind:"mind",files:"files",tools:"tools",memory:"memory"},ag=[{key:"overview",icon:"▦"},{key:"deliverables",icon:"📦"}];function Lm(s,e){return e(`agent:profilePage.taskStatus.${s}`,{defaultValue:s.replace(/_/g," ")})}function rI(s,e){const{labelKey:t}=qh(s);return t?e(t):s}function Nm(s){return s>=1e6?`${(s/1e6).toFixed(1)}M`:s>=1e3?`${(s/1e3).toFixed(1)}K`:s.toLocaleString()}function vv({agentId:s,onBack:e,inline:t,defaultTab:r,onSwipeBack:i,highlightMailboxId:n,authUser:a,headless:o,activeTab:l,initialSection:h}){const{t:d}=Pt(["agent","common"]),u=qm(),[f,p]=S.useState(null),[v,b]=S.useState(null),[g,O]=S.useState(r??"overview"),m=o&&l?l:g,[x,y]=S.useState(null),k=S.useMemo(()=>ag.map(F=>({...F,label:d(`agent:tabs.${F.key}`)})),[d]),C=S.useMemo(()=>k.map(F=>({id:F.key})),[k]),P=S.useMemo(()=>({onSwipeOutLeft:i}),[i]),_=eC(C,g,O,P),T=S.useRef(null);S.useEffect(()=>{const F=T.current;if(!F)return;F.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[g]);const R=S.useCallback(()=>{te.agents.get(s).then(p).catch(()=>{})},[s]);if(S.useEffect(()=>(O(r??"overview"),y(null),R(),te.externalAgents.list().then(X=>{const ae=X.agents.find(j=>j.markusAgentId===s);y(ae??null)}).catch(()=>{}),St.on("agent:update",X=>{X.payload.agentId===s&&R()})),[s,R]),!f)return c.jsx(zv,{label:d("agent:profilePage.loadingAgent")});const L=qh(f.state.status).dotClass,M=a?.role==="owner"||a?.role==="admin",E=F=>h??ih[F],B=F=>x||ih[F]?"overview":F,U=ih[g];return o?c.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:c.jsxs("div",{className:"p-5",children:[B(m)==="overview"&&c.jsx(Sv,{agent:f,onUpdate:R,externalInfo:x,t:d,canManageAgents:M,highlightMailboxId:n,initialSection:E(m)}),B(m)==="deliverables"&&c.jsx(Rv,{agentId:s})]})}):c.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx(Ns,{name:f.name,avatarUrl:f.avatarUrl,size:40,className:"rounded-xl"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:f.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${L}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:rI(f.state.status,d)}),x&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:d("agent:profilePage.badges.external")}),f.agentRole==="manager"&&c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:d("agent:profilePage.badges.manager")})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[f.role,f.roleDescription?` — ${f.roleDescription}`:""]})]}),c.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!t&&c.jsxs("button",{onClick:()=>Lr.navigate(Yt.TEAM,{agentId:s}),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors flex items-center gap-1",children:[c.jsx("span",{children:"◈"})," ",d("agent:profilePage.chat")]}),M&&c.jsxs("button",{onClick:async()=>{if(f)try{const{filesMap:F}=await te.agents.getFilesMap(s),X={type:"agent",name:Bv(f.name,f.name),displayName:f.name,version:"1.0.0",description:f.roleDescription??f.role,author:"",category:"general",tags:[],agent:{roleName:f.role,agentRole:f.agentRole},dependencies:{skills:f.skills??[]}};await Fm.publishViaProxy({itemType:"agent",name:f.name,description:X.description,category:"general",config:X,files:F}),b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishSuccess",{name:f.name}),variant:"primary"})}catch(F){b({title:d("agent:profilePage.hub"),message:d("agent:profilePage.publishFailed",{error:String(F)}),variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:d("agent:profilePage.publishTitle"),children:[c.jsx("span",{children:"↑"})," ",d("agent:profilePage.hub")]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),c.jsx("div",{ref:T,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:k.filter(F=>!x||F.key==="overview").map(F=>c.jsxs("button",{onClick:()=>O(F.key),"data-active":g===F.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${g===F.key?"bg-surface-primary text-fg-primary border-border-default":"text-fg-tertiary border-transparent hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{className:"mr-1",children:F.icon}),F.label]},F.key))})]}),c.jsxs("div",{className:"p-5",onTouchStart:u?_.onTouchStart:void 0,onTouchEnd:u?_.onTouchEnd:void 0,children:[B(g)==="overview"&&c.jsx(Sv,{agent:f,onUpdate:R,externalInfo:x,t:d,canManageAgents:M,highlightMailboxId:n,initialSection:h??U}),B(g)==="deliverables"&&c.jsx(Rv,{agentId:s})]}),v&&c.jsx(Wo,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>b(null),onCancel:()=>b(null)})]})}function iI({section:s,onChange:e,t}){return c.jsx("div",{role:"tablist",className:"flex border-b border-border-default overflow-x-auto scrollbar-hide",onTouchStart:r=>r.stopPropagation(),onTouchEnd:r=>r.stopPropagation(),children:Um.map(r=>{const i=r===s,n=t(`agent:profilePage.overview.sections.${r}.hint`,{defaultValue:""});return c.jsx("button",{type:"button",role:"tab","aria-selected":i,title:n||void 0,onClick:()=>e(r),className:`px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors cursor-pointer ${i?"border-brand-500 text-fg-primary font-medium":"border-transparent text-fg-tertiary hover:text-fg-secondary"}`,children:t(`agent:profilePage.overview.sections.${r}.title`)},r)})})}function fo({children:s}){return c.jsx("div",{role:"tabpanel",className:"border border-border-default rounded-xl bg-surface-elevated/30 p-4",children:s})}function yv({agentId:s,act:e,dotClass:t,expanded:r,onToggle:i}){return c.jsxs("div",{children:[c.jsxs("button",{onClick:i,className:"w-full flex items-center gap-2.5 px-3 py-2 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${t}`}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:e.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(e.startedAt).toLocaleString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:r?"▲":"▼"})]}),r&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Wh,{agentId:s,activityId:e.id})})]})}function Sv({agent:s,onUpdate:e,externalInfo:t,t:r,canManageAgents:i,highlightMailboxId:n,initialSection:a}){const[o,l]=S.useState(null),[h,d]=S.useState([]),[u,f]=S.useState(null),[p,v]=S.useState(null),[b,g]=S.useState(""),[O,m]=S.useState([]),[x,y]=S.useState(0),[k,C]=S.useState(!1),[P,_]=S.useState(!1),[T,R]=S.useState(()=>r0(a,n));S.useEffect(()=>{R(r0(a,n))},[a,n]);const L=(s.state.activeTaskIds??[]).join(",");S.useEffect(()=>{te.usage.agents().then(D=>{const V=D.agents.find(se=>se.agentId===s.id);V&&l(V)}).catch(()=>{}),s.state.activeTaskIds?.length&&te.tasks.list({assignedAgentId:s.id}).then(D=>{m(D.tasks.filter(V=>s.state.activeTaskIds?.includes(V.id)))}).catch(()=>{}),te.agents.getMailbox(s.id,{limit:1}).then(D=>{y(D.queued?.length??0)}).catch(()=>{})},[s.id,L,s.state.status]),S.useEffect(()=>{if(T!=="usage")return;let D=!1;return C(!0),te.system.storage().then(V=>{if(D)return;g(V.dataDir+"/agents/"+s.id);const se=V.agents.find(fe=>fe.id===s.id);se&&v(se)}).catch(()=>{}).finally(()=>{D||C(!1)}),()=>{D=!0}},[T,s.id]),S.useEffect(()=>{if(T!=="recent")return;let D=!1;return _(!0),te.agents.getActivities(s.id,{limit:H2}).then(V=>{D||d(V.activities)}).catch(()=>{}).finally(()=>{D||_(!1)}),()=>{D=!0}},[T,s.id]);const M=()=>{s.state.status==="offline"?te.agents.start(s.id).then(e):te.agents.stop(s.id).then(e)},E=S.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:r("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:r("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:r("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:r("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:r("agent:profilePage.gateway.requirements")}],[r]),B=S.useMemo(()=>[{field:"assignedTasks",desc:r("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:r("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:r("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:r("agent:profilePage.syncContext.projectContext")}],[r]);if(t)return c.jsxs("div",{className:"space-y-4",children:[c.jsx(ms,{title:r("agent:profilePage.overview.identity"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.name"),children:s.name}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:s.id}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.organization"),children:s.config?.orgId??"default"}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),c.jsx(ms,{title:r("agent:profilePage.overview.connectionStatus"),children:c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.connection"),value:t.connected?r("common:status.online"):r("common:status.offline"),color:t.connected?"green":"gray"}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(s.state.activeTaskIds?.length??0)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.lastSync"),value:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),c.jsx(ms,{title:r("agent:profilePage.overview.externalAgentDetails"),children:c.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:t.externalAgentId}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(t.registeredAt).toLocaleString()}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.capabilities"),children:t.capabilities.length>0?t.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:t.lastHeartbeat?new Date(t.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),c.jsx(ms,{title:r("agent:profilePage.overview.syncContextTitle"),children:c.jsx("div",{className:"space-y-1.5",children:B.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:D.field}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:D.desc})]},D.field))})}),c.jsx(ms,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:c.jsx("div",{className:"space-y-1.5",children:E.map(D=>c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[c.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${D.method==="POST"?"text-amber-600":"text-green-600"}`,children:D.method}),c.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:D.path}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:D.desc})]},D.path))})})]});const{heartbeats:U,comms:F}=Y2(h),X=s0(U),ae=s0(F),j=s.state.activeTaskIds?.length??0,W=[h.length>0?r("agent:profilePage.overview.recentWindow",{count:h.length}):null,X.total>0?r("agent:profilePage.overview.heartbeatRuns",{count:X.total}):null,ae.total>0?r("agent:profilePage.overview.a2aRuns",{count:ae.total}):null].filter(Boolean).join(" · ");return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(qs,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:s.role}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentRole"),children:c.jsx("span",{className:s.agentRole==="manager"?"text-amber-600":"text-blue-600",children:s.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:s.id}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.model"),children:s.effectiveModel?.model?c.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[c.jsx("span",{className:"font-mono",children:s.effectiveModel.model}),s.config?.llmConfig?.modelMode==="custom"&&s.effectiveModel.source!=="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeAgentModel")}):s.effectiveModel.source==="override"?c.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:r("agent:profilePage.overview.labels.badgeSessionModel")}):null]}):c.jsx("span",{className:"text-fg-tertiary",children:r("agent:profilePage.overview.labels.followsGlobal")})}),c.jsx(qs,{label:r("agent:profilePage.overview.labels.created"),children:s.config?.createdAt?new Date(s.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),c.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.tokensToday"),value:Nm(z2(o,s.state.tokensUsedToday))}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(j),color:j>0?"blue":void 0}),i&&c.jsx("button",{onClick:M,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:s.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),s.state.status==="error"&&c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),s.state.lastErrorAt&&c.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(s.state.lastErrorAt).toLocaleString()})]}),c.jsx("pre",{className:"text-[11px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono bg-red-500/5 rounded p-2",children:nh(s.state.lastError,r)||s.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),s.state.status==="working"&&(j>0||x>0||s.runtime?.activityLabel)&&c.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:c.jsxs("div",{className:"space-y-1.5",children:[s.runtime?.activityLabel&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:s.runtime.activityLabel}),s.runtime.activityType&&c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:s.runtime.activityType})]}),O.map(D=>c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsx("span",{className:"text-fg-secondary truncate flex-1",children:D.title}),c.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:Lm(D.status,r)})]},D.id)),x>0&&c.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-amber-400 shrink-0"}),c.jsx("span",{className:"text-fg-secondary flex-1",children:r("agent:profilePage.overview.mailboxQueued",{count:x})})]})]})})]}),c.jsx(iI,{section:T,onChange:R,t:r}),T==="usage"&&c.jsx(fo,{children:o||p?c.jsxs("div",{className:"space-y-2",children:[o&&c.jsxs("div",{className:"space-y-1",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.lifetimeCaption")}),c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.labels.totalTokens"),value:Nm(o.totalTokens)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.requests"),value:String(o.requestCount)}),c.jsx(Ks,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(o.toolCalls)})]})]}),p&&c.jsxs("div",{className:"space-y-1",children:[c.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[c.jsx(Ks,{label:r("agent:profilePage.overview.storage"),value:Tv(p.size)}),q2(p.subItems).map(D=>{const V=V2(D.name);return c.jsx(Ks,{label:V?r(V):D.name,value:Tv(D.size)},D.name)}),c.jsxs("button",{onClick:()=>{te.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]}),p.depthLimited&&c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.storageDepthLimited")})]})]}):k?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.usage.empty")})}),T==="recent"&&c.jsxs(fo,{children:[W&&c.jsx("p",{className:"text-[10px] text-fg-tertiary mb-2",children:W}),X.total>0&&c.jsxs("div",{children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentHeartbeats")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:X.shown.map(D=>c.jsx(yv,{agentId:s.id,act:D,dotClass:"bg-green-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),ae.total>0&&c.jsxs("div",{className:"mt-3",children:[c.jsx("h4",{className:"text-[10px] text-fg-tertiary uppercase tracking-wider mb-1",children:r("agent:profilePage.overview.recentA2A")}),c.jsx("div",{className:"divide-y divide-gray-800/50",children:ae.shown.map(D=>c.jsx(yv,{agentId:s.id,act:D,dotClass:"bg-blue-400",expanded:u===D.id,onToggle:()=>f(u===D.id?null:D.id)},D.id))})]}),X.total===0&&ae.total===0&&(P?c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("common:loading")}):c.jsx("p",{className:"text-xs text-fg-tertiary",children:r("agent:profilePage.overview.sections.recent.empty")}))]}),T==="mind"&&c.jsx(fo,{children:c.jsx(wI,{agentId:s.id,highlightId:n,agentStatus:s.state.status,canManageAgents:i})}),T==="files"&&c.jsx(fo,{children:c.jsx(lI,{agentId:s.id})}),T==="tools"&&c.jsx(fo,{children:c.jsx(fI,{tools:s.tools??[],agent:s})}),T==="memory"&&c.jsxs(fo,{children:[c.jsx(pI,{agentId:s.id,initialData:s.heartbeat}),c.jsx("div",{className:"mt-6",children:c.jsx(mI,{agentId:s.id})})]})]})}function nI(s,e){const t=s.split(`
|
|
59
59
|
`),r=e.split(`
|
|
60
60
|
`),i=t.length,n=r.length,a=Array.from({length:i+1},()=>new Array(n+1).fill(0));for(let f=i-1;f>=0;f--)for(let p=n-1;p>=0;p--)a[f][p]=t[f]===r[p]?a[f+1][p+1]+1:Math.max(a[f+1][p],a[f][p+1]);const o=[];let l=0,h=0,d=1,u=1;for(;l<i||h<n;)l<i&&h<n&&t[l]===r[h]?(o.push({type:"equal",content:t[l],oldLineNum:d++,lineNum:u++}),l++,h++):h<n&&(l>=i||a[l][h+1]>=a[l+1][h])?(o.push({type:"add",content:r[h],lineNum:u++}),h++):(o.push({type:"remove",content:t[l],oldLineNum:d++}),l++);return o}function wv(s){return s.match(/\S+|\s+/g)??[""]}function _v({oldText:s,newText:e,mode:t}){const r=wv(s),i=wv(e),n=r.length,a=i.length,o=Array.from({length:n+1},()=>new Array(a+1).fill(0));for(let u=n-1;u>=0;u--)for(let f=a-1;f>=0;f--)o[u][f]=r[u]===i[f]?o[u+1][f+1]+1:Math.max(o[u+1][f],o[u][f+1]);const l=[];let h=0,d=0;for(;h<n||d<a;)h<n&&d<a&&r[h]===i[d]?(l.push({text:t==="remove"?r[h]:i[d],changed:!1}),h++,d++):d<a&&(h>=n||o[h][d+1]>=o[h+1][d])?(t==="add"&&l.push({text:i[d],changed:!0}),d++):(t==="remove"&&l.push({text:r[h],changed:!0}),h++);return c.jsx("span",{children:l.map((u,f)=>u.changed?c.jsx("span",{className:t==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:u.text},f):c.jsx("span",{children:u.text},f))})}function oI({agent:s,template:e,templateId:t}){const{t:r}=Pt(["agent","common"]),i=S.useMemo(()=>nI(s,e),[s,e]),[n,a]=S.useState(!0),o=3,l=S.useMemo(()=>{const p=i.map((O,m)=>O.type!=="equal"?m:-1).filter(O=>O>=0);if(p.length===0)return[];const v=[];let b=Math.max(0,p[0]-o),g=Math.min(i.length-1,p[0]+o);for(let O=1;O<p.length;O++){const m=Math.max(0,p[O]-o),x=Math.min(i.length-1,p[O]+o);m<=g+1||(v.push({start:b,end:g}),b=m),g=x}return v.push({start:b,end:g}),v},[i]),h=(p,v,b)=>{const g=p.type==="add"?"+":p.type==="remove"?"-":" ",O=p.type==="add"?"bg-green-500/8":p.type==="remove"?"bg-red-500/8":"",m=p.type==="add"?"text-green-600/90":p.type==="remove"?"text-red-500/80":"text-fg-tertiary",x=p.type==="add"?"text-green-500":p.type==="remove"?"text-red-500":"text-fg-muted",y=p.type==="remove"?p.oldLineNum:p.lineNum;let k=null;return p.type==="remove"&&v+1<b.length&&b[v+1].type==="add"?k=c.jsx(_v,{oldText:p.content,newText:b[v+1].content,mode:"remove"}):p.type==="add"&&v>0&&b[v-1].type==="remove"&&(k=c.jsx(_v,{oldText:b[v-1].content,newText:p.content,mode:"add"})),c.jsxs("div",{className:`flex ${O} hover:brightness-95 transition-colors`,children:[c.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:y??""}),c.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${x} select-none leading-[20px]`,children:g}),c.jsxs("span",{className:`flex-1 text-[11px] font-mono ${m} whitespace-pre-wrap break-words leading-[20px]`,children:[k??p.content,p.content===""&&" "]})]},v)},d=i.filter(p=>p.type==="add").length,u=i.filter(p=>p.type==="remove").length,f=n?l.flatMap(p=>{const v=[];for(let b=p.start;b<=p.end;b++)v.push({...i[b],_idx:b});return v}):i.map((p,v)=>({...p,_idx:v}));return c.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[c.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:r("agent:profilePage.diff.title",{templateId:t})}),c.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",d]}),c.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",u]})]}),c.jsx("button",{onClick:()=>a(p=>!p),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:r(n?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),c.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[n&&l.length>0&&l[0].start>0&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-b border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:l[0].start})}),f.map((p,v)=>{const b=v>0?f[v-1]:null,g=n&&b&&p._idx-b._idx>1;return c.jsxs("div",{children:[g&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-y border-border-default/30",children:"···"}),h(p,p._idx,i)]},v)}),n&&l.length>0&&l[l.length-1].end<i.length-1&&c.jsx("div",{className:"text-[10px] text-fg-muted/50 text-center py-0.5 bg-surface-elevated/40 border-t border-border-default/30",children:r("agent:profilePage.diff.linesHidden",{count:i.length-1-l[l.length-1].end})}),l.length===0&&c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:r("agent:profilePage.diff.identical")})]})]})}function aI(s,e){const t=s.split(`
|
|
61
61
|
`),r=e.split(`
|
|
@@ -72,13 +72,13 @@ ${he}
|
|
|
72
72
|
`+ae.join(`
|
|
73
73
|
---
|
|
74
74
|
|
|
75
|
-
`)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Lr.navigate(Yt.TEAM,{agentId:s,prefillMessage:j})},L=async F=>{if(y?.file===F){k(null);return}try{const X=await te.agents.roleDiff(s,F);X.agentContent!=null&&X.templateContent!=null&&k({file:F,agent:X.agentContent,template:X.templateContent})}catch{}};if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const M={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},E=F=>{const X=M[F];return X?e(`agent:profilePage.filesTab.fileLabels.${X}`):F},B=m?.hasTemplate&&!m.isUpToDate,U=a?T.some(F=>F.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[B&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:T.length,templateId:m.templateId})," ",T.map(F=>F.file).join(", ")]})]}),c.jsx("button",{onClick:()=>R(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(ms,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:m?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${m.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:m.templateId}),m.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(F=>{const X=T.some(ae=>ae.file===F.name);return c.jsxs("button",{onClick:()=>P(F.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===F.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[F.name,X&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},F.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:E(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[U&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>L(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>R(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&c.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[c.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),p(!0),setTimeout(()=>p(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-default rounded-md transition-colors",title:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),c.jsx("button",{onClick:()=>{te.system.openPath(d)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-default rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&c.jsx(oI,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(cI,{content:t.find(F=>F.name===a)?.content??"",editContent:l,setEditContent:F=>{h(F),O(!0)},dirty:g,onSave:_}),a==="ROLE.md"&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&c.jsx(Xh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function cI({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=S.useState(!1),o=S.useRef(null);return S.useEffect(()=>{n&&o.current?.focus()},[n]),S.useEffect(()=>{a(!1)},[s]),n||r?c.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):c.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[c.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(sI,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}function hI(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function dI({tools:s}){const{t:e}=Pt(["agent","common"]),t=YD(s,e);return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>c.jsx(ms,{title:`${r.category} (${r.tools.length})`,children:c.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=nC(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,h=hI(i.description||"");return c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[c.jsx(oC,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function uI({agent:s}){const{t:e}=Pt(["agent","common"]),t=s.proficiency??{},[r,i]=S.useState(null),[n,a]=S.useState(null),[o,l]=S.useState(!1),h=s.availableSkills??[],d=s.skillWarnings?.missing??[],u=new Map;for(const O of h){const m=O.category||"custom";u.has(m)||u.set(m,[]),u.get(m).push(O)}const f=async O=>{if(r===O){i(null),a(null);return}i(O),l(!0);try{const m=await fetch(`/api/skills/${encodeURIComponent(O)}`);if(m.ok){const x=await m.json();a(x.skill)}else a(null)}catch{a(null)}l(!1)},p={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=O=>{const m=t[O.name],x=m&&m.uses>0?Math.round(m.successes/m.uses*100):null,y=m&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:m.uses,successes:m.successes}),m.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(m.lastUsed).toLocaleDateString()})]}),k=r===O.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${k?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>f(O.name),children:[c.jsx("span",{className:`text-sm transition-transform ${k?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:O.name}),O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),O.builtIn&&!O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!O.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:O.description}),y]}),x!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${x>=80?"bg-green-400":x>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${x}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[x,"%"]})]})]}),k&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${p[n.category]??p.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(C=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:C},C))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(C=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",C]},C))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(C=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:C.name}),C.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:C.description})]},C.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},O.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],g=[...u.entries()].sort((O,m)=>{const x=b.indexOf(O[0]),y=b.indexOf(m[0]);return(x===-1?999:x)-(y===-1?999:y)});return c.jsxs("div",{className:"space-y-4",children:[d.length>0&&c.jsxs("div",{role:"alert",className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-600 space-y-1.5",children:[c.jsxs("div",{className:"font-semibold flex items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠️"}),e("agent:profilePage.skillsTab.missingSkillsTitle",{count:d.length})]}),c.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:d.map(O=>c.jsx("li",{children:c.jsx("span",{className:"font-medium",children:O})},O))}),c.jsx("div",{className:"text-amber-600/90",children:e("agent:profilePage.skillsTab.missingSkillsHint")})]}),c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),g.map(([O,m])=>c.jsx(ms,{title:c.jsxs("span",{className:"capitalize",children:[O," ",c.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",m.length,")"]})]}),children:c.jsx("div",{className:"space-y-2",children:m.map(x=>v(x))})},O)),h.length===0&&c.jsx(Xh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function fI({tools:s,agent:e}){const{t}=Pt(["agent","common"]),[r,i]=S.useState("tools");return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>c.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?c.jsx(dI,{tools:s}):c.jsx(uI,{agent:e})]})}function mI({agentId:s}){const{t:e}=Pt(["agent","common"]),[t,r]=S.useState(null),[i,n]=S.useState(!0),[a,o]=S.useState("longterm"),[l,h]=S.useState(""),[d,u]=S.useState(""),[f,p]=S.useState(!1),[v,b]=S.useState(null),[g,O]=S.useState(null),[m,x]=S.useState([]),[y,k]=S.useState(!1),C=S.useCallback(()=>{n(!0),te.agents.getMemory(s).then(M=>{r(M),h(M.recentDailyLogs??""),u(M.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);S.useEffect(()=>{C()},[C]);const P=async()=>{p(!0),await te.agents.updateDailyMemory(s,l).catch(()=>{}),p(!1),C()},_=async()=>{p(!0),await te.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),p(!1),C()},T=l!==(t?.recentDailyLogs??""),R=d!==(t?.longTermMemory??"");if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const L=[{key:"longterm",label:"knowledge.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return c.jsxs("div",{className:"space-y-4",children:[t.usedPercent!=null&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.healthTitle","记忆健康(knowledge.md)"),children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsxs("span",{className:"text-fg-secondary",children:[t.budgetChars??0," / ",t.budgetLimit??0," 字符"]}),c.jsxs("span",{className:t.usedPercent>=90?"text-red-500 font-medium":t.usedPercent>=70?"text-amber-600 font-medium":"text-fg-tertiary",children:[t.usedPercent,"%"]})]}),c.jsx("div",{className:"h-1.5 rounded-full bg-surface-overlay overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${t.usedPercent>=90?"bg-red-500":t.usedPercent>=70?"bg-amber-500":"bg-brand-500"}`,style:{width:`${Math.min(100,t.usedPercent)}%`}})}),c.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.memoryTab.observationsCount","观察")," ",t.observationCount??0]}),c.jsxs("span",{children:[e("agent:profilePage.memoryTab.curatedCount","知识段")," ",t.curatedCount??0]}),(t.archivedChars??0)>0&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.archivedChars","已归档")," ",t.archivedChars," 字符(可检索)"]}),t.lastConsolidatedAt&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.lastConsolidated","上次整理")," ",new Date(t.lastConsolidatedAt).toLocaleDateString()]})]}),t.usedPercent>=70&&c.jsx("div",{className:"text-[10px] text-amber-600",children:e("agent:profilePage.memoryTab.overBudgetHint","超预算的旧知识会被无损归档(不再注入)。可让 Agent 运行 memory_organize 整理。")})]})}),c.jsx("div",{className:"flex gap-2",children:L.map(M=>c.jsx("button",{onClick:()=>o(M.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===M.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:M.label},M.key))}),a==="entries"&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(Xh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map((M,E)=>{const B=v===E;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(B?null:E),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${M.type==="fact"?"bg-blue-500/15 text-blue-600":M.type==="task"?"bg-green-500/15 text-green-600":M.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:M.type}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${B?"":"line-clamp-2"}`,children:M.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M.importance!=null&&c.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${M.importance>=7?"bg-red-500/15 text-red-500":M.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",M.importance]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(M.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:B?"▲":"▼"})]})]}),B&&c.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[c.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:M.content}),c.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",M.type]}),M.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",M.importance]}),c.jsx("span",{children:new Date(M.timestamp).toLocaleString()})]})]})]},E)})})}),a==="sessions"&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(Xh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map(M=>{const E=g===M.id,B=async()=>{if(E){O(null),x([]);return}O(M.id),k(!0);try{const U=await te.agents.getMemorySession(s,M.id);x(U.messages)}catch{x([])}k(!1)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[c.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:M.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[M.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(M.updatedAt).toLocaleDateString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:E?"▲":"▼"})]}),E&&c.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):m.length===0?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const U=new Map;for(const F of m)F.role==="tool"&&F.toolCallId&&U.set(F.toolCallId,F.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:m.filter(F=>F.role!=="tool").map((F,X)=>c.jsxs("div",{className:"px-3 py-2",children:[(F.role==="user"||F.role==="system")&&c.jsxs("div",{children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${F.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${F.role}`,{defaultValue:F.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx($o,{content:F.content,className:"text-xs text-fg-secondary"})})]}),F.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[F.content&&c.jsxs("div",{children:[c.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx($o,{content:F.content,className:"text-xs text-fg-secondary"})})]}),F.toolCalls&&F.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:F.toolCalls.map(ae=>{let j;try{j=JSON.parse(ae.arguments)}catch{}const W={tool:ae.name,status:"done",args:j,result:U.get(ae.id)};return c.jsx(sC,{entry:{type:"tool",info:W}},ae.id)})})]})]},X))})})()})]},M.id)})})}),a==="daily"&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:T?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>h(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:P,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:M=>h(M.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:R?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:_,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:d,onChange:M=>u(M.target.value),placeholder:e("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function pI({agentId:s,initialData:e}){const{t}=Pt(["agent","common"]),[r,i]=S.useState(e??null),[n,a]=S.useState(!e),[o,l]=S.useState([]),[h,d]=S.useState(null),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(null),O=S.useRef(null);S.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const m=S.useCallback(()=>Promise.all([te.agents.getHeartbeat(s).then(i).catch(()=>{}),te.agents.getRecentActivities(s).then(P=>{l(P.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);S.useEffect(()=>{a(!0),m().finally(()=>a(!1))},[m]),S.useEffect(()=>St.on("agent:update",_=>{_.payload?.agentId===s&&m()}),[s,m]);const x=async()=>{f(!0),v(null);try{const P=await te.agents.triggerHeartbeat(s);v(P.message),setTimeout(()=>v(null),4e3),setTimeout(m,2e3)}catch(P){v(String(P).replace("Error: ",""))}f(!1)},y=async P=>{O.current!==null&&window.clearTimeout(O.current),g(null);try{await te.agents.cancelWakeup(s,P),g({kind:"ok",text:t("agent:profilePage.heartbeatTab.cancelWakeupOk")}),O.current=window.setTimeout(()=>g(null),4e3)}catch(_){const T=_ instanceof Error?_.message:String(_),R=!T||/no scheduled wakeup|404/i.test(T);g({kind:"error",text:R?t("agent:profilePage.heartbeatTab.cancelWakeupGone"):`${t("agent:profilePage.heartbeatTab.cancelWakeupFailed")}: ${T}`})}m()};if(n)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const k=P=>P?P<1e3?`${P}ms`:P<6e4?`${(P/1e3).toFixed(1)}s`:`${(P/6e4).toFixed(1)}m`:null,C=P=>{if(!P)return null;const _=Date.now()-new Date(P).getTime();if(_<0){const T=Math.abs(_);return T<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(T/1e3)}):T<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(T/6e4)}):t("agent:profilePage.relative.inHours",{hours:(T/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(ms,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:m,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:x,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(Ks,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),c.jsx(OI,{agentId:s,intervalMs:r.intervalMs,onChanged:m}),c.jsx(Ks,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(Ks,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),p&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),b&&c.jsx("div",{className:`text-[11px] rounded-lg px-3 py-2 border ${b.kind==="ok"?"text-green-600 bg-green-500/10 border-green-500/20":"text-red-500 bg-red-500/10 border-red-500/20"}`,children:b.text}),r.wakeups&&r.wakeups.length>0&&c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate",children:P.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[C(P.wakeAt)??new Date(P.wakeAt).toLocaleString(),P.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${P.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),c.jsx("button",{onClick:()=>y(P.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},P.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:P.type==="background_exec"?"⚙":"↔"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:P.label}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${P.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${C(P.timeoutAt)??new Date(P.timeoutAt).toLocaleString()}`]})]})]},P.id))})}),r.lastSummary&&c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:c.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:c.jsx($o,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(P=>{const _=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(_?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:P.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Wh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:k(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:x,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function gI({taskId:s,isLive:e}){const{t}=Pt("agent"),[r,i]=S.useState([]),[n,a]=S.useState(""),[o,l]=S.useState(!0);if(S.useEffect(()=>{l(!0),a(""),te.tasks.getLogs(s).then(d=>{i(d.logs),l(!1)}).catch(()=>l(!1))},[s]),S.useEffect(()=>{if(!e)return;const d=St.on("task:log",f=>{const p=f.payload;if(p.taskId!==s)return;const v={id:p.id,taskId:p.taskId,agentId:p.agentId,seq:p.seq,type:p.logType,content:p.content,metadata:p.metadata,createdAt:p.createdAt};i(b=>v.id&&b.some(g=>g.id===v.id)?b:[...b,v]),v.type==="text"&&a("")}),u=St.on("task:log:delta",f=>{const p=f.payload;p.taskId===s&&a(v=>v+p.text)});return()=>{d(),u()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const h=r.map(d=>iC(d));return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:h,isStreaming:e,streamingText:n})})}function Wh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=Pt("agent"),[i,n]=S.useState([]),[a,o]=S.useState(!0);if(S.useEffect(()=>{o(!0),te.agents.getActivityLogs(s,e).then(h=>{n(h.logs),o(!1)}).catch(()=>o(!1))},[s,e]),S.useEffect(()=>t?St.on("agent:activity_log",d=>{const u=d.payload;if(u.agentId!==s||u.activityId!==e)return;const f={seq:u.seq,type:u.type,content:u.content,metadata:u.metadata,createdAt:u.createdAt};n(p=>p.some(v=>v.seq===f.seq)?p:[...p,f])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const l=i.map(h=>rC(h,e,s)).filter(h=>h!==null);return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:l,isStreaming:t})})}function ms({title:s,action:e,children:t}){return c.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function qs({label:s,mono:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),c.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function Ks({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const kv=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Cv=5,Pv=1440;function OI({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=Pt(["agent","common"]),[i,n]=S.useState(!1),[a,o]=S.useState(null),[l,h]=S.useState(!1),[d,u]=S.useState(String(Math.round(e/6e4))),f=m=>m%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:m/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(m/6e4)}),p=async m=>{n(!0),o(null);try{await te.agents.updateConfig(s,{heartbeatIntervalMs:m}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=m=>{if(m.target.value==="custom"){h(!0);return}h(!1),p(Number(m.target.value))},b=()=>{const m=Math.round(Number(d));if(!Number.isFinite(m)||m<Cv||m>Pv){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(m*60*1e3)},g=kv.includes(e),O=l||!g?"custom":String(e);return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),c.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!g&&c.jsx("option",{value:String(e),children:f(e)}),kv.map(m=>c.jsx("option",{value:String(m),children:f(m)},m)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:Cv,max:Pv,value:d,onChange:m=>u(m.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function Xh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function Tv(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),r=s/Math.pow(1024,t);return`${r<10?r.toFixed(1):Math.round(r)} ${e[t]}`}const Qv={0:"0",1:"1",2:"2",3:"3",4:"4"},$v={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},xI={pick:"bg-brand-500/20 text-brand-500",continue:"bg-gray-500/20 text-gray-500",preempt:"bg-amber-500/20 text-amber-500",merge:"bg-blue-500/20 text-blue-500",defer:"bg-purple-500/20 text-purple-500",delegate:"bg-green-500/20 text-green-500",drop:"bg-red-500/20 text-red-500"},bI={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},vI=["all","interaction","task","notification","system"],yI={completed:"bg-green-500",processing:"bg-blue-400 animate-pulse",deferred:"bg-purple-400",merged:"bg-brand-400",queued:"bg-amber-400",dropped:"bg-red-500"},SI={pending:"text-gray-400",assigned:"text-blue-400",in_progress:"text-brand-400",completed:"text-green-400",failed:"text-red-400",cancelled:"text-gray-500",review:"text-amber-400",approved:"text-green-500",rejected:"text-red-500",draft:"text-gray-400"};function wf(s){const e=s.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(e?.[1]){const t=e[1].trim().replace(/\n/g," ");return t.length>80?t.slice(0,80)+"…":t}}function jv(s,e){const t=s.payload,r=t?.summary??"",i=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=r.match(/^Task "(.+?)" status:/),o=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??r;if(o){const d=o[1],u=o[2],f=Lm(d,e),p=Lm(u,e),v=SI[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=bv(r),o=wf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=bv(r),o=wf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=wf(i);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(i.length>120?"…":"")}}case"session_reply":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(i.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=r.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||s.sourceType}}}function wI({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=Pt(["agent","common","team"]),[n,a]=S.useState(null),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState("all"),[p,v]=S.useState("all"),[b,g]=S.useState(e??null),[O,m]=S.useState(e??null),[x,y]=S.useState(!1),[k,C]=S.useState(!1),[P,_]=S.useState(!0),[T,R]=S.useState(null),L=50,M=3,[E,B]=S.useState(null),U=S.useCallback(async(z=!0)=>{z&&d(!0);try{const re=u==="all"?void 0:u,Z=p==="all"?void 0:p,[A,J]=await Promise.all([te.agents.getMindState(s),te.agents.getMailbox(s,{limit:L,category:re,status:Z})]);a(A),l(J),_((J.history?.length??0)>=L)}catch{}d(!1)},[s,u,p]),F=S.useCallback(async z=>{B(z);try{await te.agents.dropMailboxItem(s,z,"operator"),await U()}catch{}finally{B(null)}},[s,U]),X=S.useCallback(async()=>{if(!o)return;const z=u==="all"?void 0:u,re=p==="all"?void 0:p;try{const Z=await te.agents.getMailbox(s,{limit:L,offset:o.history.length,category:z,status:re});l(A=>A?{...A,history:[...A.history,...Z.history]}:Z),_((Z.history?.length??0)>=L)}catch{}},[s,o,u,p]),ae=S.useCallback(async()=>{try{await te.agents.recoverStaleMailbox(s)}catch{}await U()},[s,U]);S.useEffect(()=>{g(e??null),m(e??null),U()},[U,e]);const j=S.useRef(!1);if(S.useEffect(()=>{if(!O||h)return;if(o?.history?.some(re=>re.id===O)){j.current=!1;const re=document.getElementById(`mbx-${O}`);if(re){setTimeout(()=>re.scrollIntoView({behavior:"smooth",block:"center"}),100);const Z=setTimeout(()=>m(null),3e3);return()=>clearTimeout(Z)}}else P&&!j.current&&(j.current=!0,(async()=>{let re=o?.history??[],Z=P;for(;Z;)try{const A=await te.agents.getMailbox(s,{limit:L,offset:re.length}),J=[...re,...A.history];re=J,Z=(A.history?.length??0)>=L;const Y=A.history.some(oe=>oe.id===O);if(l(oe=>oe?{...oe,history:J}:A),_(Z),Y||!Z)break}catch{break}j.current=!1})())},[O,h,o,P,s]),S.useEffect(()=>{let z=null;const re=A=>{A.payload?.agentId===s&&(z&&clearTimeout(z),z=setTimeout(()=>{z=null,U(!1)},500))},Z=[St.on("agent:mailbox",re),St.on("agent:decision",re),St.on("agent:attention",re),St.on("agent:focus",re),St.on("agent:update",re),St.on("agent:triage",re)];return()=>{z&&clearTimeout(z),Z.forEach(A=>A())}},[s,U]),h&&!n)return c.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:i("agent:profilePage.mind.loading")});const W=n?.mailboxDepth??n?.queuedItems?.length??0,D=qh(t).running,V=(()=>{const z=n?.attentionState??"idle";return z==="deciding"||z==="idle"&&W>0?"deciding":z!=="idle"&&!n?.currentFocus?"idle":z})(),se=V==="idle"&&o?.history?.some(z=>z.status==="processing"),fe=(n?.attentionState??"idle")==="idle"&&W>0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[D?c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${bI[V]??"bg-gray-500/20 text-gray-500"}`,children:i(`agent:profilePage.mind.attention.${V}`)}):c.jsx("span",{className:"px-2.5 py-1 text-xs font-medium rounded-full bg-gray-500/20 text-fg-tertiary",children:i("agent:profilePage.mind.agentStopped")}),D?n?.currentFocus?(()=>{const z=jv({id:n.currentFocus.mailboxItemId,sourceType:n.currentFocus.type,payload:{summary:n.currentFocus.label,taskId:n.currentFocus.taskId},metadata:{},queuedAt:n.currentFocus.startedAt},i);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[Nc(n.currentFocus.type)," ",c.jsx("span",{className:"text-fg-primary font-medium",children:z.title}),z.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:z.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:i("agent:profilePage.mind.since",{time:new Date(n.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>R(n.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]})})():fe?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.queuedButIdle",{count:W,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):V==="deciding"?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.decidingWaiting",{count:W})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.idleWaiting")}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.stoppedHint")}),c.jsx("div",{className:"ml-auto flex items-center gap-2",children:c.jsx("button",{onClick:()=>{U()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:i("agent:profilePage.mind.refresh")})})]}),D&&se&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600 flex-1",children:i("agent:profilePage.mind.staleProcessingWarning")}),r&&c.jsx("button",{onClick:()=>{ae()},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-amber-500/20 text-amber-700 hover:bg-amber-500/30 transition-colors shrink-0",children:i("agent:profilePage.mind.recoverStaleBtn")})]}),(n?.queuedItems?.length??0)>0&&(()=>{const z=n.queuedItems,re=z.length>M,Z=re&&!x?z.slice(0,M):z,A=z.reduce((J,Y)=>(J[Y.sourceType]=(J[Y.sourceType]??0)+1,J),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.queue",{count:z.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(A).map(([J,Y])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Nc(J)," ",Y]},J))})]}),c.jsxs("div",{className:"space-y-1",children:[Z.map((J,Y)=>c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[c.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:Y+1}),c.jsx("span",{className:"text-sm",children:Nc(J.sourceType)}),c.jsx("span",{className:`text-[10px] ${$v[J.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[J.priority]??J.priority}`,{defaultValue:`P${J.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:J.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(J.queuedAt).toLocaleTimeString()})]},J.id)),re&&c.jsx("button",{onClick:()=>y(!x),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:x?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandQueue",{count:z.length-M})})]})]})})()]}),(n?.notebook?.length??0)>0&&(()=>{const z=eI(n.notebook,k);return c.jsx("section",{className:"bg-surface-elevated rounded-lg border border-border-subtle p-3",children:c.jsxs("details",{children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"📓"}),c.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("agent:profilePage.mind.notebook")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:i("agent:profilePage.mind.notebookEntries",{count:n.notebook.length})})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-muted leading-relaxed",children:i("agent:profilePage.mind.notebookHint",{count:j_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[z.visible.map(re=>{const Z=tI(re.updatedAt),A=i(`agent:profilePage.relative.${Z.unit==="seconds"?"secondsAgo":Z.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:Z.count,hours:Z.count}),J=re.managed==="system"?"text-blue-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-overlay border border-border-subtle",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary",children:re.key}),c.jsxs("span",{className:`text-[10px] ${J}`,children:["[",re.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:A})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:re.text.length>500?re.text.slice(0,500)+"…":re.text})]},re.key)}),z.collapsible&&c.jsx("button",{onClick:()=>C(!k),className:"w-full text-center text-[11px] text-accent-primary hover:opacity-80 py-1 transition-colors",children:k?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandNotebook",{count:z.hiddenCount})})]})]})})})(),n?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-elevated rounded-lg border border-amber-500/20 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.deliberationInProgress")}),c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-300",children:i("agent:profilePage.mind.batchDeliberating")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:i("agent:profilePage.mind.since",{time:new Date(n.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(Wh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const re=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4,Z=J2(n.lastTriage);return c.jsx("section",{className:`bg-surface-elevated rounded-lg border p-3 transition-opacity ${re?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!re,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:i("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:new Date(n.lastTriage.timestamp).toLocaleTimeString()})]}),c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:n.lastTriage.reasoning}),c.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:i("agent:profilePage.mind.processingItem",{id:n.lastTriage.processedItemId.slice(0,12)})}),c.jsx("span",{className:`px-1.5 py-0.5 rounded ${Z.isBatch?"bg-indigo-500/15 text-indigo-300":"bg-surface-overlay text-fg-tertiary"}`,children:Z.isBatch?i("agent:profilePage.mind.batchSize",{count:Z.total}):i("agent:profilePage.mind.singleItem")}),n.lastTriage.deferredItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:i("agent:profilePage.mind.deferred",{count:n.lastTriage.deferredItemIds.length})}),n.lastTriage.droppedItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:i("agent:profilePage.mind.dropped",{count:n.lastTriage.droppedItemIds.length})}),(n.lastTriage.inlineCompletedIds?.length??0)>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:i("agent:profilePage.mind.inlineCompleted",{count:n.lastTriage.inlineCompletedIds.length})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:vI.map(z=>{const re=o?.sourceTypeCounts,Z=z==="all"?re?Object.values(re).reduce((A,J)=>A+J,0):void 0:re?(UD[z]??[]).reduce((A,J)=>A+(re[J]??0),0):void 0;return c.jsxs("button",{onClick:()=>f(z),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${u===z?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-elevated border-border-subtle text-fg-secondary hover:bg-surface-overlay"}`,children:[i(`agent:profilePage.mind.categoryFilters.${z}`),Z!=null&&Z>0&&c.jsx("span",{className:"ml-1 opacity-60",children:Z})]},z)})})]}),c.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(z=>{const re=o?.statusCounts,Z=z.key==="all"?re?Object.values(re).reduce((A,J)=>A+J,0):void 0:re?.[z.key];return c.jsxs("button",{onClick:()=>v(z.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===z.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-elevated border-border-subtle text-fg-secondary hover:bg-surface-overlay"}`,children:[z.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z.dot}`}),i(`agent:profilePage.mind.statusFilters.${z.key}`),Z!=null&&Z>0&&c.jsx("span",{className:"ml-1 opacity-60",children:Z})]},z.key)})}),(!o?.history||o.history.length===0)&&!h&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:i("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:o?.history?.map(z=>{const re=b===z.id,Z=Nc(z.sourceType),A=jv(z,i),J=KD({itemStatus:z.status,agentRunning:D,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:z.id}),Y=z.metadata?.senderName,oe=z.metadata?.senderRole,K=O===z.id;return c.jsxs("div",{id:`mbx-${z.id}`,className:`bg-surface-elevated rounded-lg border transition-colors duration-1000 ${K?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[c.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-overlay/50 transition-colors rounded-lg",onClick:()=>g(re?null:z.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:re?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${J==="stale"?"bg-amber-400/70":yI[z.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:Z}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`text-xs font-medium text-fg-primary ${re?"":"truncate"}`,children:A.title}),A.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${A.badge.color}`,children:A.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${$v[z.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[z.priority]??z.priority}`,{defaultValue:""})})]}),A.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${re?"":"truncate"}`,children:A.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(z.queuedAt).toLocaleString()}),z.completedAt&&c.jsxs("span",{children:["→ ",new Date(z.completedAt).toLocaleTimeString()]}),z.activity&&c.jsxs(c.Fragment,{children:[z.activity.totalTokens>0&&c.jsx("span",{children:i("agent:profilePage.mind.tokensCount",{count:Nm(z.activity.totalTokens)})}),z.activity.totalTools>0&&c.jsx("span",{children:i("agent:profilePage.mind.toolsCount",{count:z.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-overlay px-1.5 py-0.5 rounded shrink-0",children:z.sourceType}),r&&GD({agentRunning:D,itemId:z.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:z.status})&&c.jsxs("button",{onClick:pe=>{pe.stopPropagation(),R(z.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]}),re&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[Y&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:Y}),oe&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",oe,")"]})]}),z.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(z.sourceType)&&c.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:z.payload.content}),z.decisions&&z.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:i("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:z.decisions.map(pe=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${xI[pe.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:pe.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:pe.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(pe.createdAt).toLocaleTimeString()})]},pe.id))})]}),r&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.actions")}),c.jsx("div",{className:"flex gap-2",children:c.jsx("button",{disabled:E===z.id,onClick:()=>{F(z.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-400 hover:bg-red-500/25 disabled:opacity-40 transition-colors",children:i("agent:profilePage.mind.dropBtn")})})]}),z.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[i("agent:profilePage.mind.activityHeading",{label:z.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${z.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:z.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),z.activity.type==="task"&&z.payload?.taskId?c.jsx(gI,{taskId:z.payload.taskId,isLive:!z.activity.endedAt}):c.jsx(Wh,{agentId:s,activityId:z.activity.id,isLive:!z.activity.endedAt})]}):J==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):J==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):z.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},z.id)})}),P&&(o?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:X,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:i("agent:profilePage.mind.loadEarlier")})})]}),T&&c.jsx(Wo,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const z=T;R(null),te.agents.cancelProcessing(s,{itemId:z}).then(()=>{let re=0;const Z=()=>{re+=1,U(),re<8&&window.setTimeout(Z,750)};Z()}).catch(()=>{U()})},onCancel:()=>R(null)})]})}function Rv({agentId:s}){const{t:e}=Pt(["agent","common"]),t=zh(),[r,i]=S.useState([]),[n,a]=S.useState(!0),o=S.useCallback(h=>{if(K2(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:h});return}Lr.navigate(Yt.DELIVERABLES,{openDeliverable:h.id})},[t]),l=S.useCallback(async()=>{a(!0);try{const{results:h}=await te.deliverables.search({agentId:s,limit:200});i(h)}catch{i([])}a(!1)},[s]);return S.useEffect(()=>{l()},[l]),S.useEffect(()=>{const h=St.on("deliverable:created",()=>l()),d=St.on("deliverable:updated",()=>l()),u=St.on("deliverable:removed",()=>l());return()=>{h(),d(),u()}},[l]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(h=>c.jsxs("div",{className:"animate-pulse space-y-2",children:[c.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),c.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},h))}):r.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(h=>{const d=tC[h.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=yO[h.status]??yO.active;return c.jsxs("button",{onClick:()=>o(h),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[c.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${d.color}`,children:d.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:h.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:h.status})]}),h.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:h.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(h.createdAt).toLocaleDateString()}),h.tags.length>0&&c.jsx("span",{children:h.tags.slice(0,3).join(", ")})]})]}),c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},h.id)})]})})}const _I=S.lazy(()=>Xv(()=>import("./index-BXWHxoXp.js").then(s=>s.bn),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),lg=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Ev={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Av({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Pt("team"),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState(!0),[p,v]=S.useState(null),[b,g]=S.useState("overview"),O=r&&i?i:b,[m,x]=S.useState(""),[y,k]=S.useState(""),[C,P]=S.useState(!1),[_,T]=S.useState(!1),[R,L]=S.useState(""),[M,E]=S.useState(""),B=S.useRef(null),U=S.useRef(null),F=S.useRef(null),X=S.useRef(null),[ae,j]=S.useState(!1),[W,D]=S.useState(!1),[V,se]=S.useState(""),[fe,z]=S.useState(""),[re,Z]=S.useState(!1),[A,J]=S.useState([]),Y=S.useRef(null),oe=S.useCallback(async()=>{try{const qe=(await te.teams.list()).teams.find(Ye=>Ye.id===s);qe&&l(qe);const He=await te.teams.status(s);J(He.agents)}catch{}finally{d(!1)}},[s]),K=S.useCallback(async()=>{f(!0);try{const G=await te.teams.getFile(s,"ANNOUNCEMENT.md");x(G.content)}catch{x("")}try{const G=await te.teams.getFile(s,"NORMS.md");k(G.content)}catch{k("")}finally{f(!1)}},[s]);S.useEffect(()=>{g("overview"),oe(),K()},[s,oe,K]),S.useEffect(()=>{C&&U.current&&U.current.focus()},[C]),S.useEffect(()=>{_&&X.current&&X.current.focus()},[_]);const pe=async(G,qe)=>{j(!0);try{await te.teams.updateFile(s,G,qe),G==="ANNOUNCEMENT.md"?(x(qe),P(!1)):(k(qe),T(!1))}catch{}j(!1)},je=async()=>{V.trim()&&(await te.teams.update(s,{name:V.trim()}),D(!1),oe())},we=async()=>{await te.teams.update(s,{description:fe}),Z(!1),oe()};if(!o)return h?c.jsx(zv,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(BC,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const Ge=o.members.find(G=>G.agentRole==="manager"),Qe=A.filter(G=>G.status!=="offline").length,Ee=O==="announcements"&&C||O==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Ee?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Ee?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[O==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Ge?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(G=>{const qe=A.find(pt=>pt.id===G.id),He=Ev[qe?.status??"offline"]??"bg-gray-500",Ye=G.type==="agent";return c.jsxs("div",{onClick:()=>Ye&&n?.(G.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Ye&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ns,{name:G.name,avatarUrl:G.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:G.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),G.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[G.role," · ",G.type]})]}),Ye&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),O==="announcements"&&c.jsx(Dc,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ae,onSave:()=>pe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),O==="norms"&&c.jsx(Dc,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:F,saving:ae,onSave:()=>pe("NORMS.md",M),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:u}),O==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),W?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:V,onChange:G=>se(G.target.value),onKeyDown:G=>G.key==="Enter"&&je(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:je,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{se(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:fe,onChange:G=>z(G.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const ye=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${ye?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:o.name}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Qe," online"]})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:G}=await te.teams.getFilesMap(o.id),qe=o.members.filter(Ye=>Ye.type==="agent"),He={type:"team",name:Bv(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:qe.map(Ye=>({name:Ye.name,roleName:Ye.role,role:Ye.agentRole??"worker",count:1,skills:[]}))}};await Fm.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:He,files:G}),v({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(G){v({title:"Hub",message:`Failed to publish: ${G}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:lg.map(G=>c.jsxs("button",{onClick:()=>g(G.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===G.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[G.icon," ",a(G.labelKey)]},G.key))})]}),c.jsxs("div",{className:`${ye?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[b==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Ge?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(G=>{const qe=A.find(pt=>pt.id===G.id),He=Ev[qe?.status??"offline"]??"bg-gray-500",Ye=G.type==="agent";return c.jsxs("div",{onClick:()=>Ye&&n?.(G.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Ye&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ns,{name:G.name,avatarUrl:G.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:G.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),G.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[G.role," · ",G.type]})]}),Ye&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("teamProfile.noMembers",{defaultValue:"No members"})})]})]}),b==="announcements"&&c.jsx(Dc,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ae,onSave:()=>pe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),b==="norms"&&c.jsx(Dc,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:F,saving:ae,onSave:()=>pe("NORMS.md",M),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:u}),b==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),W?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:V,onChange:G=>se(G.target.value),onKeyDown:G=>G.key==="Enter"&&je(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:je,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{se(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:fe,onChange:G=>z(G.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]}),p&&c.jsx(Wo,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Dc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:d,loading:u}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:f=>t(f.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&(t(s),i(!0))},children:u&&!s.trim()?c.jsx(qv,{variant:"text",className:"px-1 py-2"}):s.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(_I,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function Mv({teamId:s,teamName:e,onDeleted:t}){const[r,i]=S.useState(!1),[n,a]=S.useState(!1),[o,l]=S.useState(!1),[h,d]=S.useState(!1);return c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[c.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:h,onClick:async()=>{d(!0);try{await te.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}const kI=["chat","overview","deliverables"],CI=["chat","overview","announcements","norms","settings"];function PI(s,e){if(s==="chat")return e("page.chatTitle");if(ag.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=lg.find(i=>i.key===s);return r?e(r.labelKey):s}function TI(s){if(s==="chat")return"💬";const e=ag.find(r=>r.key===s);if(e)return e.icon;const t=lg.find(r=>r.key===s);return t?t.icon:""}function qi(s){return s!=="chat"}function Ea(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const Dm=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Ar{currentConvKey="";loadingSession=null;buffers=new Map;view=new Map;viewReader={get:e=>this.view.get(e)};get activeSessions(){return this.viewReader}actBuffers=new Map;sessionTabs=new Map;windowBounds=new Map;getWindowBounds(e){return this.windowBounds.get(e)??{hasMore:!1,oldestCursor:null}}setWindowBounds(e,t){this.windowBounds.set(e,t)}phase=new Map;sendCount=new Map;streamingSessions=new Map;bufferOrder=[];static MAX_MESSAGES=500;static MAX_BUFFERS=30;static NEW_CHAT_ID="__new_chat__";getPhase(e){const t=this.phase.get(e)??"idle";return t==="streaming"?t:this.hasLiveStream(e)?"streaming":t}hasLiveStream(e){return(this.streamingSessions.get(e)?.size??0)>0}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e,t){this.phase.set(e,"idle");const r=this.view.get(e);r&&(this.buffers.delete(r),this.windowBounds.delete(r)),this.actBuffers.delete(r??e),this.actBuffers.delete(e),t?this.view.set(e,t):this.view.delete(e)}bufferIdFor(e,t){return t??this.view.get(e)??e}updateMessages(e,t,r){const i=this.bufferIdFor(e,r);let n=t(this.buffers.get(i)??[]);n.length>Ar.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const u of e)i.add(u.id),n.push(u);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let d=!1;for(const u of t)if(!i.has(u.id)){if(u.sender==="agent"&&!!!(u.isError||u.isStopped||u.emptyReply)){if(r&&u.isStreaming)if(h&&l&&!d){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),d=!0,a.push({...u,id:l.id}),i.add(l.id)}else a.push(u),i.add(u.id);continue}o.push(u)}for(const u of o){if(i.has(u.id))continue;const f=u.rawCreatedAt?Date.parse(u.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,u),i.add(u.id)}for(const u of a)n.push(u);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){if(!Dm(e))return;const r=this.view.get(e);if(r!==t&&(r===void 0||r===Ar.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Ar.NEW_CHAT_ID);if(!t||t.length===0)return;const r=this.buffers.get(e)??[],i=new Set(r.map(a=>a.id)),n=[...r,...t.filter(a=>!i.has(a.id))];this.buffers.set(e,n),this.touchBuffer(e),this.buffers.delete(Ar.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){Dm(e)&&this.view.set(e,t);const r=this.buffers.get(t);if(!r||r.length===0)return;if(this.isStreamLiveForSession(e,t))return r;const n=r.filter(a=>!(a.sender==="agent"&&a.isStreaming&&!a.isStopped));if(n.length===0){this.buffers.delete(t);return}return this.buffers.set(t,n),n}isStreamLiveForSession(e,t){if(this.getPhase(e)!=="streaming")return!1;const r=this.streamingSessions.get(e);return!r||r.size===0||r.has(t)?!0:this.placeholderTurnBelongsTo(e,t)}placeholderTurnBelongsTo(e,t){const r=this.streamingSessions.get(e);return!r||!r.has(Ar.NEW_CHAT_ID)?!1:this.view.get(e)===t}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const r=this.streamingSessions.get(e)??new Set;return r.has(t)?(this.streamingSessions.set(e,r),!1):(r.add(t),this.streamingSessions.set(e,r),!0)}removeStreamSession(e,t){if(t){const r=this.streamingSessions.get(e);return!r||!r.has(t)?!1:(r.delete(t),r.size===0&&this.streamingSessions.delete(e),!0)}return this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}abortStream(e,t){let r=!1;(this.sendCount.get(e)??0)>0&&(this.sendCount.set(e,0),r=!0);const i=t??e;if(this.actBuffers.delete(i)&&(r=!0),this.getPhase(e)==="streaming"&&(this.phase.set(e,"ready"),r=!0),t){const n=this.streamingSessions.get(e)?.has(t)??!1;this.removeStreamSession(e,t),n&&(r=!0)}else this.streamingSessions.delete(e)&&(r=!0);return r}getMessages(e){return this.buffers.get(this.view.get(e)??e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.buffers.delete(e),this.windowBounds.delete(e)}viewBufferId(){const e=this.currentConvKey;return this.view.get(e)??e}evictIfNeeded(e){if(this.buffers.size<=Ar.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Ar.MAX_BUFFERS)break;r===e||r===t||(this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r))}}touchBuffer(e){const t=this.bufferOrder.indexOf(e);for(t!==-1&&this.bufferOrder.splice(t,1),this.bufferOrder.push(e);this.bufferOrder.length>Ar.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(new Set([this.viewBufferId(),...this.view.values()]).has(r)){this.bufferOrder.push(r);break}this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r)}}}const it=Ar.NEW_CHAT_ID;function QI(s){const e=S.useRef(new Ar),[t,r]=S.useState(s??[]),[i,n]=S.useState(!1),[a,o]=S.useState([]),l=S.useRef(null),[,h]=S.useState(0),d=S.useCallback(()=>h(R=>R+1),[]),u=S.useCallback(R=>e.current.getStreamSessions(R),[]),f=S.useCallback((R,L)=>{e.current.addStreamSession(R,L)&&d()},[d]),p=S.useCallback((R,L)=>{e.current.removeStreamSession(R,L)&&d()},[d]),v=S.useCallback((R,L)=>e.current.setActiveSession(R,L),[]),b=S.useCallback(R=>e.current.clearActiveSession(R),[]);S.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const g=S.useCallback((R,L,M)=>{const E=e.current.updateMessages(R,L,M);E.displayChanged&&E.newMessages&&r(E.newMessages)},[]),O=S.useCallback((R,L,M)=>{e.current.updateMessages(R,L,M).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const B=e.current.getMessages(R);B&&e.current.currentConvKey===R&&r([...B])}))},[]),m=S.useCallback((R,L,M)=>{const E=e.current.appendActivity(R,L,M);E.displayChanged&&E.newActivities&&o(E.newActivities)},[]),x=S.useCallback(R=>e.current.getPhase(R),[]),y=S.useCallback(R=>e.current.beginLoad(R),[]),k=S.useCallback(R=>{e.current.beginStream(R)},[]),C=S.useCallback(R=>{e.current.endStream(R)},[]),P=S.useCallback((R,L)=>{e.current.abortStream(R,L)&&d(),e.current.currentConvKey===R&&(n(!1),o([]))},[d]),_=S.useCallback((R,L)=>{e.current.resetConv(R,L),e.current.deleteBuffer(R)},[]),T=S.useCallback(async(R,L,M)=>{e.current.loadingSession=R,e.current.beginLoad(L);try{const E=await M(),B=e.current.applyLoadResult(L,R,E.messages);return B.displayChanged&&B.newMessages&&r(B.newMessages),{count:E.messages.length,hasMore:E.hasMore,oldestCursor:E.oldestCursor}}catch{return e.current.currentConvKey===L&&e.current.getPhase(L)!=="streaming"&&(r([]),e.current.completeLoad(L)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get buffers(){return e.current.buffers},get viewBuffer(){return e.current.activeSessions},get activeSessionBuffer(){return e.current.activeSessions},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(R){e.current.currentConvKey=R}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(R){e.current.loadingSession=R}}},updateConvMsgs:g,updateConvMsgsRaf:O,appendConvActivity:m,getPhase:x,beginLoad:y,beginStream:k,endStream:C,resetConv:_,abortStream:P,loadAndDisplay:T,setActiveSession:v,clearActiveSession:b,incrementSending:R=>e.current.incrementSend(R),decrementSending:R=>e.current.decrementSend(R),resetSending:R=>e.current.resetSend(R),isSendingFor:R=>e.current.isSending(R),setStreamSession:f,clearStreamSession:p,getStreamSession:u,saveSessionToCache:(R,L)=>e.current.saveToCache(),restoreSessionFromCache:(R,L)=>{const M=e.current.restoreFromCache(R,L);return r(M??[]),M},readConvMsgs:R=>e.current.getMessages(R),writeConvMsgs:(R,L)=>{const M=e.current.updateMessages(R,()=>L);M.displayChanged&&M.newMessages&&r(M.newMessages)}}}function _f(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function $I(s){const e=S.useRef(new Map),t=S.useRef(new Map),r=Ee=>{if(Ee)for(const[ye,G]of e.current)G===Ee&&e.current.delete(ye)},i=Ee=>{if(Ee)for(const[ye,G]of t.current)G===Ee&&t.current.delete(ye)},n=Ee=>{const ye=e.current.get(Ee);ye&&(ye.abort(),e.current.delete(Ee));const G=t.current.get(Ee);G&&(G.abort(),t.current.delete(Ee))},a=Ee=>{const ye=e.current.get(it);ye&&e.current.size===1&&(e.current.delete(it),e.current.set(Ee,ye))},o=S.useRef(new Map),l=S.useRef(new Set),h=S.useRef(null),d=S.useRef(new Map),u=S.useRef(0),{stateRef:f}=s,{actBuffers:p,activeSessionBuffer:v,readConvMsgs:b,currentConvKeyRef:g,updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,beginStream:y,endStream:k,abortStream:C,clearStreamSession:P,setStreamSession:_,getStreamSession:T,setActiveSession:R,incrementSending:L,decrementSending:M,loadAndDisplay:E,sessionSwitchSeqRef:B,setSending:U,setActivities:F,setInput:X,setChatContext:ae,setPendingImages:j,setMentionDropdown:W,setChatReplyTo:D,setActiveSessionId:V,setStoredActiveSession:se,setOpenSessionTabs:fe,setSessions:z,setLoadingChat:re,setWindowBounds:Z,makeConvKey:A,makeDmChannel:J,addRecentMsgId:Y,resumeChatScrollFollow:oe,loadSessions:K}=s,{t:pe}=s,je=S.useCallback(async(Ee,ye)=>{const G=B.current,qe=g.current===ye&&(b(ye)?.length??0)===0;qe&&re(!0);try{const{count:He,hasMore:Ye,oldestCursor:pt}=await E(Ee,ye,async()=>{const xt=await te.sessions.getMessages(Ee,50);return{messages:aC(xt.messages.map(oh).filter(vt=>vt.sender!=="agent"||vt.text||vt.segments&&vt.segments.length>0||vt.isStreaming)),hasMore:xt.hasMore,oldestCursor:xt.messages[0]?new Date(xt.messages[0].createdAt).toISOString():null}});return Z(Ee,{hasMore:Ye,oldestCursor:pt}),He}finally{qe&&g.current===ye&&B.current===G&&re(!1)}},[E,b,B]),we=()=>{const Ee=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Ee){const ye=_f(f.current.activeSessionId,it);ye.kind==="cancel"&&te.agents.cancelProcessing(Ee,ye.target).catch(()=>{})}n(f.current.activeSessionId??it),Ee&&f.current.activeSessionId&&f.current.activeSessionId!==it&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Ge=S.useCallback(async(Ee,ye,G)=>{if(!Ee||!ye||ye===it||l.current.has(ye))return;let qe=null;try{const He=e.current.get(ye);if(He&&!He.signal.aborted&&T(G)?.has(ye)){g.current===G&&U(!0);return}const Ye=()=>{lC({liveSessions:T(G),sessionId:ye,placeholderId:it})&&(P(G,ye),g.current===G&&(U(!1),O(G,de=>ou(de),ye)))},pt=`${Ee}:${ye}`,xt=o.current.get(pt)??0;if(Date.now()-xt<1500)return;o.current.set(pt,Date.now());let bt;const vt=await te.sessions.streamStatus(Ee,ye);vt.messageId&&(bt=vt.messageId);const Pe=b(G)??[],Et=vt.status==="streaming",Ft=cC(Pe,{expectedMessageId:vt.messageId,allowCurrentTurnPartial:Et}),Es=!!vt.active&&(vt.status==="done"||vt.status==="error")&&!!Ft?.isStreaming;if(KO({aborted:!1,sawTerminal:Es,serverStatus:JO(vt.status)})==="finalize"){Ye();return}o.current.set(pt,Date.now());for(const de of t.current.values())de.abort();t.current.clear(),qe=new AbortController,t.current.set(ye,qe),y(G),U(!0),_(G,ye);const yt=Ft&&!Ft.isError&&Ft.sender==="agent"?Pe.findIndex(de=>de.id===Ft.id):-1,Bt=yt>=0?Pe[yt]:void 0,ut=hC(vt);if(!Bt&&!ut){Ye();return}const Ze=Bt?Bt.id:ut;if(!Bt)O(G,de=>[...de,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],ye);else{const de=(Bt.segments??[]).filter(De=>De.type==="tool").map(De=>De.status==="stopped"||De.status==="running"?{...De,status:"running"}:De);O(G,De=>De.map(ve=>ve.id===Ze?{...ve,text:"",isStreaming:!0,isStopped:!1,segments:de,committedSegments:void 0}:ve),ye)}const Xt=de=>{g.current===G&&(u.current=Date.now(),m(G,De=>{const ve=[...De],st=Ze?ve.findIndex(ee=>ee.id===Ze):-1,ze=st>=0?st:ve.map((ee,Te)=>({m:ee,j:Te})).reverse().find(ee=>ee.m.sender==="agent"&&ee.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];return ve[ze]={...Ve,text:(Ve.text??"")+de,segments:SO(Ve.segments??[],de),isStreaming:!0},ve},ye))},ot=de=>{g.current===G&&(u.current=Date.now(),m(G,De=>{const ve=[...De],st=Ze?ve.findIndex(ee=>ee.id===Ze):-1,ze=st>=0?st:ve.map((ee,Te)=>({m:ee,j:Te})).reverse().find(ee=>ee.m.sender==="agent"&&ee.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];return ve[ze]={...Ve,segments:wO(Ve.segments??[],de),isStreaming:!0},ve},ye))},At=de=>{if(g.current===G&&(u.current=Date.now(),de.phase!=="heartbeat")){if((de.phase==="start"||de.phase==="end")&&x(G,{...de,phase:de.phase,ts:Date.now()},ye),de.phase==="start"){const De=`${de.tool}_${Date.now()}`,ve=new Date().toISOString(),st=ze=>{const Ve=[...ze];for(let ee=Ve.length-1;ee>=0;ee--){const Te=Ve[ee];if(Te.type==="tool"&&Te.tool===de.tool&&(Te.status==="running"||Te.status==="stopped"))return Ve[ee]={...Te,status:"running",args:de.arguments??Te.args},Ve}return Ve.push({type:"tool",key:De,tool:de.tool,status:"running",args:de.arguments,createdAt:ve}),Ve};O(G,ze=>{const Ve=[...ze],ee=Ze?Ve.findIndex(_e=>_e.id===Ze):-1;if(ee<0)return ze;const Te=st(Ve[ee].segments??[]),Se=Ve[ee].committedSegments,Oe=Se&&st(Se);return Ve[ee]={...Ve[ee],segments:Te,committedSegments:Oe,isStreaming:!0},Ve},ye)}else if(de.phase==="end"){const De=new Date().toISOString(),ve=st=>{const ze=[...st];for(let Ve=ze.length-1;Ve>=0;Ve--){const ee=ze[Ve];if(ee.type==="tool"&&ee.tool===de.tool&&(ee.status==="running"||ee.status==="stopped")){ze[Ve]={...ee,status:de.success===!1?"error":"done",args:de.arguments??ee.args,result:de.result,error:de.error,durationMs:de.durationMs,liveOutput:void 0,createdAt:De};break}}return ze};O(G,st=>{const ze=[...st],Ve=Ze?ze.findIndex(Oe=>Oe.id===Ze):-1;if(Ve<0)return st;const ee=ve(ze[Ve].segments??[]),Te=ze[Ve].committedSegments,Se=Te&&ve(Te);return ze[Ve]={...ze[Ve],segments:ee,committedSegments:Se,isStreaming:!0},ze},ye)}else if(de.phase==="subagent_progress"&&de.subagentEvent){const De=ve=>{const st=[...ve];for(let ze=st.length-1;ze>=0;ze--){const Ve=st[ze];if(Ve.type==="tool"&&(Ve.tool==="spawn_subagent"||Ve.tool==="spawn_subagents")&&(Ve.status==="running"||Ve.status==="stopped")){st[ze]={...Ve,status:"running",subagentLogs:_O(Ve.subagentLogs,de.subagentEvent)};break}}return st};m(G,ve=>{const st=[...ve],ze=Ze?st.findIndex(Se=>Se.id===Ze):-1;if(ze<0)return ve;const Ve=De(st[ze].segments??[]),ee=st[ze].committedSegments,Te=ee&&De(ee);return st[ze]={...st[ze],segments:Ve,committedSegments:Te,isStreaming:!0},st},ye)}}},us=de=>{g.current===G&&(u.current=Date.now(),O(G,De=>{const ve=[...De],st=Ze?ve.findIndex(Ve=>Ve.id===Ze):-1;if(st<0)return De;const ze=[...ve[st].committedSegments??[]];if(de.type==="thinking_commit")ze.push({type:"text",content:"",thinking:de.content,createdAt:de.createdAt});else if(de.type==="text_commit")ze.push({type:"text",content:de.content,createdAt:de.createdAt});else return De;return ve[st]={...ve[st],committedSegments:ze,isStreaming:!0},ve},ye))},he=de=>{if(g.current!==G)return;u.current=Date.now();const De=(de.segments??[]).map((ve,st)=>ve.type==="tool"?{type:"tool",key:`${ve.tool}_${st}`,tool:ve.tool??"tool",status:ve.status==="error"?"error":ve.status==="running"||ve.status==="stopped"?"running":"done",args:ve.arguments,result:ve.result,error:ve.error,durationMs:ve.durationMs,createdAt:ve.createdAt,...ve.subagentLogs?.length?{subagentLogs:ve.subagentLogs}:{}}:{type:"text",content:ve.content??"",thinking:ve.thinking,createdAt:ve.createdAt});O(G,ve=>{const st=[...ve],ze=Ze?st.findIndex(Ve=>Ve.id===Ze):-1;return ze<0?ve:(st[ze]={...st[ze],text:de.content||st[ze].text,segments:De,committedSegments:De,isStreaming:!0,isStopped:!1},st)},ye);for(const ve of De)ve.type==="tool"&&x(G,{tool:ve.tool,phase:ve.status==="running"||ve.status==="stopped"?"start":"end",success:ve.status!=="error",arguments:ve.args,result:ve.result,error:ve.error,durationMs:ve.durationMs,ts:Date.now()},ye)},ce=8;let $e=null;const Xe=de=>{g.current===G&&O(G,De=>{const ve=De.map((ze,Ve)=>({m:ze,j:Ve})).reverse().find(ze=>ze.m.sender==="agent"&&ze.m.isStreaming)?.j??-1;if(ve<0||De[ve].reconnecting===de)return De;const st=[...De];return st[ve]={...st[ve],reconnecting:de},st},ye)};for(let de=1;de<=ce;de++){if(qe.signal.aborted)return;try{$e=await te.sessions.reattachStream(Ee,ye,{onChunk:Xt,onThinking:ot,onActivity:At,onCommit:us,onSnapshot:he},qe.signal,0)}catch(ve){if(qe.signal.aborted)throw ve;$e=null}if(!$e||!$e.attached){$e=null;break}if($e.terminal)break;Xe(!0);const De=await te.sessions.streamStatus(Ee,ye).catch(()=>null);if(De?.messageId&&(bt=De.messageId),!De||!De.active||De.status==="not_found"||De.status==="idle"){Xe(!1),$e=null;break}await new Promise(ve=>setTimeout(ve,Math.min(800*de,4e3))),Xe(!1)}if(!$e){k(G),P(G,ye),g.current===G&&(U(!1),bt&&Ze&&O(G,de=>wa(de,Ze,bt),ye),je(ye,G).catch(()=>{}).finally(()=>{O(G,de=>ou(de,"done"),ye)})),i(qe);return}if(g.current===G){let de;O(G,De=>{const ve=[...De],st=Ze?ve.findIndex(Te=>Te.id===Ze):-1,ze=st>=0?st:ve.map((Te,Se)=>({m:Te,j:Se})).reverse().find(Te=>Te.m.sender==="agent"&&Te.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];if(!Ve.isStreaming)return De;de=Ve.id;const ee=$e.segments?.length?kO($e.segments,Ve.segments):void 0;return ve[ze]={...Ve,text:$e.content||Ve.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...ee?{segments:ee,committedSegments:ee}:{}},ve},ye),de&&O(G,De=>wa(De,de,$e.messageId),ye),U(!1)}k(G),P(G,ye),i(qe)}catch(He){const Ye=qe?[...t.current.values()].includes(qe):!1;i(qe),k(G);const pt=l.current.has(ye);if(pt&&P(G,ye),g.current===G&&(U(!1),Ye&&pt&&O(G,xt=>ou(xt),ye)),He instanceof Error&&He.name==="AbortError")return}},[x,y,k,T,b,_,O,m]),Qe=S.useCallback(async(Ee,ye)=>{const G=f.current,qe=!Ee&&G.chatContext.length>0?G.chatContext.map(rt=>rt.content).join(`
|
|
75
|
+
`)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";Lr.navigate(Yt.TEAM,{agentId:s,prefillMessage:j})},L=async F=>{if(y?.file===F){k(null);return}try{const X=await te.agents.roleDiff(s,F);X.agentContent!=null&&X.templateContent!=null&&k({file:F,agent:X.agentContent,template:X.templateContent})}catch{}};if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.filesTab.loading")});const M={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},E=F=>{const X=M[F];return X?e(`agent:profilePage.filesTab.fileLabels.${X}`):F},B=m?.hasTemplate&&!m.isUpToDate,U=a?T.some(F=>F.file===a):!1;return c.jsxs("div",{className:"space-y-4",children:[B&&c.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[c.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-amber-600 font-medium",children:e("agent:profilePage.filesTab.templateUpdateAvailable")}),c.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[e("agent:profilePage.filesTab.filesDiffer",{count:T.length,templateId:m.templateId})," ",T.map(F=>F.file).join(", ")]})]}),c.jsx("button",{onClick:()=>R(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:e("agent:profilePage.filesTab.sendToAgent")})]}),c.jsxs(ms,{title:e("agent:profilePage.filesTab.agentConfigFiles"),action:m?.hasTemplate?c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${m.isUpToDate?"bg-green-400":"bg-amber-400"}`}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[e("agent:profilePage.filesTab.templateLabel")," ",c.jsx("span",{className:"text-fg-secondary",children:m.templateId}),m.isUpToDate?e("agent:profilePage.filesTab.upToDate"):e("agent:profilePage.filesTab.updatesAvailable")]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[c.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:t.map(F=>{const X=T.some(ae=>ae.file===F.name);return c.jsxs("button",{onClick:()=>P(F.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${a===F.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[F.name,X&&c.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},F.name)})}),a&&c.jsxs("div",{children:[c.jsxs("div",{className:"flex items-center justify-between mb-1",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:E(a)}),c.jsxs("div",{className:"flex gap-2 items-center",children:[U&&c.jsxs(c.Fragment,{children:[c.jsx("button",{onClick:()=>L(a),className:"px-2.5 py-1 text-[11px] text-amber-600 hover:text-amber-600 border border-amber-500/30 hover:border-amber-500/50 rounded-lg transition-colors",children:y?.file===a?e("agent:profilePage.filesTab.hideDiff"):e("agent:profilePage.filesTab.viewDiff")}),c.jsx("button",{onClick:()=>R(a),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:e("agent:profilePage.filesTab.sendToAgentTitle"),children:e("agent:profilePage.filesTab.sendToAgent")})]}),v&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("common:saving")})]})]}),d&&c.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[c.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${d}/${a}`,children:[d,"/",a]}),c.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${d}/${a}`),p(!0),setTimeout(()=>p(!1),2e3)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-default rounded-md transition-colors",title:e("agent:profilePage.filesTab.copyPath"),children:e(f?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),c.jsx("button",{onClick:()=>{te.system.openPath(d)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-default rounded-md transition-colors",title:e("agent:profilePage.filesTab.openInFinder"),children:e("agent:profilePage.filesTab.openInFinder")})]}),y?.file===a&&c.jsx(oI,{agent:y.agent,template:y.template,templateId:m?.templateId??""}),c.jsx(cI,{content:t.find(F=>F.name===a)?.content??"",editContent:l,setEditContent:F=>{h(F),O(!0)},dirty:g,onSave:_}),a==="ROLE.md"&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:e("agent:profilePage.filesTab.roleMdHint")})]}),t.length===0&&c.jsx(Xh,{text:e("agent:profilePage.filesTab.noConfigFiles")})]})]})}function cI({content:s,editContent:e,setEditContent:t,dirty:r,onSave:i}){const[n,a]=S.useState(!1),o=S.useRef(null);return S.useEffect(()=>{n&&o.current?.focus()},[n]),S.useEffect(()=>{a(!1)},[s]),n||r?c.jsx("textarea",{ref:o,value:e,onChange:l=>t(l.target.value),onBlur:()=>{e!==s&&i(),a(!1)},onKeyDown:l=>{l.key==="Escape"&&(l.preventDefault(),t(s),a(!1))},className:"w-full min-h-[60vh] bg-surface-elevated/60 border border-border-default rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y focus:border-brand-500 outline-none",spellCheck:!1}):c.jsxs("div",{className:"group relative cursor-pointer rounded-lg px-4 py-3 bg-surface-elevated hover:bg-surface-overlay transition-colors min-h-[200px]",onClick:()=>a(!0),role:"button",tabIndex:0,onKeyDown:l=>{l.key==="Enter"&&a(!0)},children:[c.jsx("div",{className:"absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity text-[10px] text-fg-tertiary bg-surface-secondary/80 px-2 py-0.5 rounded",children:"Click to edit"}),e.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(sI,{content:e,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}function hI(s){return s.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function dI({tools:s}){const{t:e}=Pt(["agent","common"]),t=YD(s,e);return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.toolsTab.registeredCount",{count:s.length})}),t.map(r=>c.jsx(ms,{title:`${r.category} (${r.tools.length})`,children:c.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(i=>{const n=nC(i.name),a=e(`common:execution.tools.${n.key}`,{defaultValue:n.label}),o=i.name.includes("__"),l=o?i.name.split("__").pop():i.name,h=hI(i.description||"");return c.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[c.jsx(oC,{name:n.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:a}),o&&c.jsx("span",{className:"text-[9px] px-1 py-px rounded bg-surface-secondary text-fg-tertiary border border-border-default/40 shrink-0",children:"MCP"})]}),l!==a&&c.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:l}),h&&c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:h,children:h})]})]},i.name)})})},r.category)),s.length===0&&c.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:e("agent:profilePage.toolsTab.noToolsRegistered")})]})}function uI({agent:s}){const{t:e}=Pt(["agent","common"]),t=s.proficiency??{},[r,i]=S.useState(null),[n,a]=S.useState(null),[o,l]=S.useState(!1),h=s.availableSkills??[],d=s.skillWarnings?.missing??[],u=new Map;for(const O of h){const m=O.category||"custom";u.has(m)||u.set(m,[]),u.get(m).push(O)}const f=async O=>{if(r===O){i(null),a(null);return}i(O),l(!0);try{const m=await fetch(`/api/skills/${encodeURIComponent(O)}`);if(m.ok){const x=await m.json();a(x.skill)}else a(null)}catch{a(null)}l(!1)},p={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=O=>{const m=t[O.name],x=m&&m.uses>0?Math.round(m.successes/m.uses*100):null,y=m&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[e("agent:profilePage.skillsTab.usesStats",{uses:m.uses,successes:m.successes}),m.lastUsed&&e("agent:profilePage.skillsTab.lastUsed",{date:new Date(m.lastUsed).toLocaleDateString()})]}),k=r===O.name;return c.jsxs("div",{children:[c.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${k?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>f(O.name),children:[c.jsx("span",{className:`text-sm transition-transform ${k?"rotate-90":""}`,children:"▶"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:O.name}),O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:e("agent:profilePage.skillsTab.alwaysOn")}),O.builtIn&&!O.alwaysOn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:e("agent:profilePage.skillsTab.builtIn")}),!O.builtIn&&c.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:e("agent:profilePage.skillsTab.installed")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:O.description}),y]}),x!==null&&c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[c.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${x>=80?"bg-green-400":x>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${x}%`}})}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[x,"%"]})]})]}),k&&c.jsx("div",{className:"ml-6 mt-1 mb-2 p-4 bg-surface-elevated/30 rounded-lg border border-border-default/20 space-y-3",children:o?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.loadingDetails")}):n?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${p[n.category]??p.custom}`,children:n.category}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",n.version]}),n.author&&c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:e("agent:profilePage.skillsTab.byAuthor",{author:n.author})}),n.requiredPermissions?.map(C=>c.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:C},C))]}),n.description&&c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:n.description}),n.tags&&n.tags.length>0&&c.jsx("div",{className:"flex gap-1 flex-wrap",children:n.tags.map(C=>c.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",C]},C))}),(n.toolDetails??n.tools??[]).length>0&&c.jsxs("div",{children:[c.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:e("agent:profilePage.skillsTab.toolsHeading",{count:(n.toolDetails??n.tools??[]).length})}),c.jsx("div",{className:"space-y-1.5",children:(n.toolDetails??n.tools??[]).map(C=>c.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[c.jsx("div",{className:"text-xs font-medium text-brand-500",children:C.name}),C.description&&c.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:C.description})]},C.name))})]})]}):c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.skillsTab.detailsUnavailable")})})]},O.name)},b=["development","productivity","browser","communication","devops","data","platform","custom"],g=[...u.entries()].sort((O,m)=>{const x=b.indexOf(O[0]),y=b.indexOf(m[0]);return(x===-1?999:x)-(y===-1?999:y)});return c.jsxs("div",{className:"space-y-4",children:[d.length>0&&c.jsxs("div",{role:"alert",className:"rounded-lg border border-amber-500/40 bg-amber-500/10 px-4 py-3 text-xs text-amber-600 space-y-1.5",children:[c.jsxs("div",{className:"font-semibold flex items-center gap-1.5",children:[c.jsx("span",{"aria-hidden":!0,children:"⚠️"}),e("agent:profilePage.skillsTab.missingSkillsTitle",{count:d.length})]}),c.jsx("ul",{className:"list-disc list-inside space-y-0.5",children:d.map(O=>c.jsx("li",{children:c.jsx("span",{className:"font-medium",children:O})},O))}),c.jsx("div",{className:"text-amber-600/90",children:e("agent:profilePage.skillsTab.missingSkillsHint")})]}),c.jsx("div",{className:"flex items-center justify-between",children:c.jsx("div",{className:"text-xs text-fg-tertiary",children:e("agent:profilePage.skillsTab.installedCount",{count:h.length})})}),g.map(([O,m])=>c.jsx(ms,{title:c.jsxs("span",{className:"capitalize",children:[O," ",c.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",m.length,")"]})]}),children:c.jsx("div",{className:"space-y-2",children:m.map(x=>v(x))})},O)),h.length===0&&c.jsx(Xh,{text:e("agent:profilePage.skillsTab.noSkills")})]})}function fI({tools:s,agent:e}){const{t}=Pt(["agent","common"]),[r,i]=S.useState("tools");return c.jsxs("div",{className:"space-y-4",children:[c.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(n=>c.jsx("button",{onClick:()=>i(n),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===n?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:n==="tools"?`${t("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${s.length})`:`${t("agent:tabs.skills")} (${e.availableSkills?.length??0})`},n))}),r==="tools"?c.jsx(dI,{tools:s}):c.jsx(uI,{agent:e})]})}function mI({agentId:s}){const{t:e}=Pt(["agent","common"]),[t,r]=S.useState(null),[i,n]=S.useState(!0),[a,o]=S.useState("longterm"),[l,h]=S.useState(""),[d,u]=S.useState(""),[f,p]=S.useState(!1),[v,b]=S.useState(null),[g,O]=S.useState(null),[m,x]=S.useState([]),[y,k]=S.useState(!1),C=S.useCallback(()=>{n(!0),te.agents.getMemory(s).then(M=>{r(M),h(M.recentDailyLogs??""),u(M.longTermMemory??"")}).catch(()=>{}).finally(()=>n(!1))},[s]);S.useEffect(()=>{C()},[C]);const P=async()=>{p(!0),await te.agents.updateDailyMemory(s,l).catch(()=>{}),p(!1),C()},_=async()=>{p(!0),await te.agents.updateLongTermMemory(s,e("agent:profilePage.memoryTab.userEditedSource"),d).catch(()=>{}),p(!1),C()},T=l!==(t?.recentDailyLogs??""),R=d!==(t?.longTermMemory??"");if(i)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loading")});if(!t)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:e("agent:profilePage.memoryTab.loadFailed")});const L=[{key:"longterm",label:"knowledge.md"},{key:"entries",label:`Observations (${t.entries.length})`},{key:"sessions",label:e("agent:profilePage.memoryTab.sessions",{count:t.sessions.length})},{key:"daily",label:e("agent:profilePage.memoryTab.dailyLogs")}];return c.jsxs("div",{className:"space-y-4",children:[t.usedPercent!=null&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.healthTitle","记忆健康(knowledge.md)"),children:c.jsxs("div",{className:"space-y-2",children:[c.jsxs("div",{className:"flex items-center justify-between text-xs",children:[c.jsxs("span",{className:"text-fg-secondary",children:[t.budgetChars??0," / ",t.budgetLimit??0," 字符"]}),c.jsxs("span",{className:t.usedPercent>=90?"text-red-500 font-medium":t.usedPercent>=70?"text-amber-600 font-medium":"text-fg-tertiary",children:[t.usedPercent,"%"]})]}),c.jsx("div",{className:"h-1.5 rounded-full bg-surface-overlay overflow-hidden",children:c.jsx("div",{className:`h-full rounded-full ${t.usedPercent>=90?"bg-red-500":t.usedPercent>=70?"bg-amber-500":"bg-brand-500"}`,style:{width:`${Math.min(100,t.usedPercent)}%`}})}),c.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.memoryTab.observationsCount","观察")," ",t.observationCount??0]}),c.jsxs("span",{children:[e("agent:profilePage.memoryTab.curatedCount","知识段")," ",t.curatedCount??0]}),(t.archivedChars??0)>0&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.archivedChars","已归档")," ",t.archivedChars," 字符(可检索)"]}),t.lastConsolidatedAt&&c.jsxs("span",{children:[e("agent:profilePage.memoryTab.lastConsolidated","上次整理")," ",new Date(t.lastConsolidatedAt).toLocaleDateString()]})]}),t.usedPercent>=70&&c.jsx("div",{className:"text-[10px] text-amber-600",children:e("agent:profilePage.memoryTab.overBudgetHint","超预算的旧知识会被无损归档(不再注入)。可让 Agent 运行 memory_organize 整理。")})]})}),c.jsx("div",{className:"flex gap-2",children:L.map(M=>c.jsx("button",{onClick:()=>o(M.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${a===M.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:M.label},M.key))}),a==="entries"&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.recentEntries"),children:t.entries.length===0?c.jsx(Xh,{text:e("agent:profilePage.memoryTab.noEntries")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.entries.map((M,E)=>{const B=v===E;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>b(B?null:E),className:"w-full flex gap-2 px-3 py-2 rounded-lg bg-surface-elevated/20 text-xs text-left hover:bg-surface-elevated/40 transition-colors cursor-pointer",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${M.type==="fact"?"bg-blue-500/15 text-blue-600":M.type==="task"?"bg-green-500/15 text-green-600":M.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:M.type}),c.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${B?"":"line-clamp-2"}`,children:M.content}),c.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[M.importance!=null&&c.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${M.importance>=7?"bg-red-500/15 text-red-500":M.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",M.importance]}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(M.timestamp).toLocaleTimeString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:B?"▲":"▼"})]})]}),B&&c.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[c.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:M.content}),c.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[c.jsxs("span",{children:[e("agent:profilePage.overview.labels.type"),": ",M.type]}),M.importance!=null&&c.jsxs("span",{children:[e("agent:profilePage.overview.labels.importance"),": ",M.importance]}),c.jsx("span",{children:new Date(M.timestamp).toLocaleString()})]})]})]},E)})})}),a==="sessions"&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.chatSessions"),children:t.sessions.length===0?c.jsx(Xh,{text:e("agent:profilePage.memoryTab.noSessions")}):c.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:t.sessions.map(M=>{const E=g===M.id,B=async()=>{if(E){O(null),x([]);return}O(M.id),k(!0);try{const U=await te.agents.getMemorySession(s,M.id);x(U.messages)}catch{x([])}k(!1)};return c.jsxs("div",{children:[c.jsxs("button",{onClick:B,className:"w-full flex items-center gap-3 px-3 py-2.5 rounded-lg bg-surface-elevated/20 hover:bg-surface-elevated/40 transition-colors cursor-pointer text-left",children:[c.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:M.id}),c.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[M.messageCount," ",e("agent:profilePage.memoryTab.msgs")]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(M.updatedAt).toLocaleDateString()}),c.jsx("span",{className:"text-fg-tertiary text-[10px]",children:E?"▲":"▼"})]}),E&&c.jsx("div",{className:"mx-3 mt-1 mb-2 bg-surface-elevated/30 rounded-lg border border-border-default/20 max-h-96 overflow-y-auto",children:y?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.loadingMessages")}):m.length===0?c.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:e("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const U=new Map;for(const F of m)F.role==="tool"&&F.toolCallId&&U.set(F.toolCallId,F.content);return c.jsx("div",{className:"divide-y divide-gray-700/30",children:m.filter(F=>F.role!=="tool").map((F,X)=>c.jsxs("div",{className:"px-3 py-2",children:[(F.role==="user"||F.role==="system")&&c.jsxs("div",{children:[c.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${F.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:e(`agent:profilePage.memoryTab.roles.${F.role}`,{defaultValue:F.role})}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx($o,{content:F.content,className:"text-xs text-fg-secondary"})})]}),F.role==="assistant"&&c.jsxs("div",{className:"space-y-1",children:[F.content&&c.jsxs("div",{children:[c.jsx("span",{className:"inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 bg-green-500/15 text-green-600",children:e("agent:profilePage.memoryTab.roles.assistant")}),c.jsx("div",{className:"text-xs text-fg-secondary",children:c.jsx($o,{content:F.content,className:"text-xs text-fg-secondary"})})]}),F.toolCalls&&F.toolCalls.length>0&&c.jsx("div",{className:"space-y-0.5",children:F.toolCalls.map(ae=>{let j;try{j=JSON.parse(ae.arguments)}catch{}const W={tool:ae.name,status:"done",args:j,result:U.get(ae.id)};return c.jsx(sC,{entry:{type:"tool",info:W}},ae.id)})})]})]},X))})})()})]},M.id)})})}),a==="daily"&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.dailyLogs"),action:T?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>h(t?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:P,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:l,onChange:M=>h(M.target.value),placeholder:e("agent:profilePage.memoryTab.noDailyLogs"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})}),a==="longterm"&&c.jsx(ms,{title:e("agent:profilePage.memoryTab.longTermTitle"),action:R?c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:()=>u(t?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:e("common:cancel")}),c.jsx("button",{onClick:_,disabled:f,className:"text-xs text-brand-500",children:e(f?"common:saving":"common:save")})]}):null,children:c.jsx("textarea",{value:d,onChange:M=>u(M.target.value),placeholder:e("agent:profilePage.memoryTab.noLongTerm"),className:"w-full min-h-[50vh] bg-surface-elevated/30 border border-border-default/50 hover:border-border-default focus:border-brand-500 rounded-lg p-4 text-xs font-mono text-fg-secondary leading-relaxed resize-y outline-none transition-colors"})})]})}function pI({agentId:s,initialData:e}){const{t}=Pt(["agent","common"]),[r,i]=S.useState(e??null),[n,a]=S.useState(!e),[o,l]=S.useState([]),[h,d]=S.useState(null),[u,f]=S.useState(!1),[p,v]=S.useState(null),[b,g]=S.useState(null),O=S.useRef(null);S.useEffect(()=>()=>{O.current!==null&&window.clearTimeout(O.current)},[]);const m=S.useCallback(()=>Promise.all([te.agents.getHeartbeat(s).then(i).catch(()=>{}),te.agents.getRecentActivities(s).then(P=>{l(P.activities.filter(_=>_.type==="heartbeat"))}).catch(()=>{})]),[s]);S.useEffect(()=>{a(!0),m().finally(()=>a(!1))},[m]),S.useEffect(()=>St.on("agent:update",_=>{_.payload?.agentId===s&&m()}),[s,m]);const x=async()=>{f(!0),v(null);try{const P=await te.agents.triggerHeartbeat(s);v(P.message),setTimeout(()=>v(null),4e3),setTimeout(m,2e3)}catch(P){v(String(P).replace("Error: ",""))}f(!1)},y=async P=>{O.current!==null&&window.clearTimeout(O.current),g(null);try{await te.agents.cancelWakeup(s,P),g({kind:"ok",text:t("agent:profilePage.heartbeatTab.cancelWakeupOk")}),O.current=window.setTimeout(()=>g(null),4e3)}catch(_){const T=_ instanceof Error?_.message:String(_),R=!T||/no scheduled wakeup|404/i.test(T);g({kind:"error",text:R?t("agent:profilePage.heartbeatTab.cancelWakeupGone"):`${t("agent:profilePage.heartbeatTab.cancelWakeupFailed")}: ${T}`})}m()};if(n)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.loading")});if(!r)return c.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:t("agent:profilePage.heartbeatTab.noData")});const k=P=>P?P<1e3?`${P}ms`:P<6e4?`${(P/1e3).toFixed(1)}s`:`${(P/6e4).toFixed(1)}m`:null,C=P=>{if(!P)return null;const _=Date.now()-new Date(P).getTime();if(_<0){const T=Math.abs(_);return T<6e4?t("agent:profilePage.relative.inSeconds",{count:Math.ceil(T/1e3)}):T<36e5?t("agent:profilePage.relative.inMinutes",{count:Math.ceil(T/6e4)}):t("agent:profilePage.relative.inHours",{hours:(T/36e5).toFixed(1)})}return _<6e4?t("agent:profilePage.relative.secondsAgo",{count:Math.floor(_/1e3)}):_<36e5?t("agent:profilePage.relative.minutesAgo",{count:Math.floor(_/6e4)}):t("agent:profilePage.relative.hoursAgo",{hours:(_/36e5).toFixed(1)})};return c.jsxs("div",{className:"space-y-4",children:[c.jsxs(ms,{title:t("agent:profilePage.heartbeatTab.scheduler"),action:c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("button",{onClick:m,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:t("common:refresh")}),c.jsx("button",{onClick:x,disabled:u||!r.running,className:"text-[10px] px-2.5 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[c.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[c.jsx(Ks,{label:t("agent:profilePage.overview.labels.status"),value:r.running?t("agent:profilePage.heartbeatTab.running"):t("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),c.jsx(OI,{agentId:s,intervalMs:r.intervalMs,onChanged:m}),c.jsx(Ks,{label:t("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??t("agent:profilePage.emDash"):t("agent:profilePage.never")}),c.jsx(Ks,{label:t("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??t("agent:profilePage.emDash"):r.running?t("agent:profilePage.heartbeatTab.pending"):t("agent:profilePage.emDash")})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:t("agent:profilePage.heartbeatTab.rhythmHint")}),p&&c.jsx("div",{className:"mt-3 text-[11px] text-blue-600 bg-blue-500/10 border border-blue-500/20 rounded-lg px-3 py-2",children:p})]}),b&&c.jsx("div",{className:`text-[11px] rounded-lg px-3 py-2 border ${b.kind==="ok"?"text-green-600 bg-green-500/10 border-green-500/20":"text-red-500 bg-red-500/10 border-red-500/20"}`,children:b.text}),r.wakeups&&r.wakeups.length>0&&c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.wakeupsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate",children:P.note||t("agent:profilePage.heartbeatTab.wakeupNoNote")}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[C(P.wakeAt)??new Date(P.wakeAt).toLocaleString(),P.recurringMs?` · ${t("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${P.deliveryMode==="in_session"?t("agent:profilePage.heartbeatTab.deliveryInSession"):t("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),c.jsx("button",{onClick:()=>y(P.id),className:"text-[10px] px-2 py-0.5 rounded text-fg-tertiary hover:text-red-500 hover:bg-red-500/10 transition-colors shrink-0",children:t("agent:profilePage.heartbeatTab.cancelWakeup")})]},P.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(P=>c.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[c.jsx("span",{className:"text-sm shrink-0 opacity-60",children:P.type==="background_exec"?"⚙":"↔"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:P.label}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[t(`agent:profilePage.heartbeatTab.callbackType.${P.type}`),` · ${t("agent:profilePage.heartbeatTab.timesOut")} ${C(P.timeoutAt)??new Date(P.timeoutAt).toLocaleString()}`]})]})]},P.id))})}),r.lastSummary&&c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:c.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:c.jsx($o,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),o.length>0?c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.recentRuns"),action:c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.runsThisSession",{count:o.length})}),children:c.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...o].reverse().map(P=>{const _=h===P.id;return c.jsxs("div",{children:[c.jsxs("button",{onClick:()=>d(_?null:P.id),className:"w-full flex items-center gap-2.5 px-5 py-2.5 text-left transition-colors hover:bg-surface-elevated/40 cursor-pointer",children:[c.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),c.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:P.label}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:t("agent:profilePage.heartbeatTab.actionsCount",{count:P.logCount})}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(P.startedAt).toLocaleString()}),c.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${_?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:c.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),_&&c.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:c.jsx(Wh,{agentId:s,activityId:P.id})})]},P.id)})})}):r.lastHeartbeat?null:c.jsx(ms,{title:t("agent:profilePage.heartbeatTab.recentRuns"),children:c.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[c.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),c.jsx("p",{className:"text-xs text-fg-tertiary",children:t("agent:profilePage.heartbeatTab.noRunsYet")}),c.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?t("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:k(r.intervalMs-r.uptimeMs%r.intervalMs)??t("agent:profilePage.heartbeatTab.soon")}):t("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&c.jsx("button",{onClick:x,disabled:u,className:"mt-3 text-[10px] px-3 py-1.5 rounded-md bg-blue-600/15 text-blue-600 hover:bg-blue-600/25 border border-blue-500/25 transition-colors disabled:opacity-40",children:t(u?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function gI({taskId:s,isLive:e}){const{t}=Pt("agent"),[r,i]=S.useState([]),[n,a]=S.useState(""),[o,l]=S.useState(!0);if(S.useEffect(()=>{l(!0),a(""),te.tasks.getLogs(s).then(d=>{i(d.logs),l(!1)}).catch(()=>l(!1))},[s]),S.useEffect(()=>{if(!e)return;const d=St.on("task:log",f=>{const p=f.payload;if(p.taskId!==s)return;const v={id:p.id,taskId:p.taskId,agentId:p.agentId,seq:p.seq,type:p.logType,content:p.content,metadata:p.metadata,createdAt:p.createdAt};i(b=>v.id&&b.some(g=>g.id===v.id)?b:[...b,v]),v.type==="text"&&a("")}),u=St.on("task:log:delta",f=>{const p=f.payload;p.taskId===s&&a(v=>v+p.text)});return()=>{d(),u()}},[s,e]),o)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.loading")});if(r.length===0&&!n)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:t("profilePage.taskLog.noLogs")});const h=r.map(d=>iC(d));return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:h,isStreaming:e,streamingText:n})})}function Wh({agentId:s,activityId:e,isLive:t=!1}){const{t:r}=Pt("agent"),[i,n]=S.useState([]),[a,o]=S.useState(!0);if(S.useEffect(()=>{o(!0),te.agents.getActivityLogs(s,e).then(h=>{n(h.logs),o(!1)}).catch(()=>o(!1))},[s,e]),S.useEffect(()=>t?St.on("agent:activity_log",d=>{const u=d.payload;if(u.agentId!==s||u.activityId!==e)return;const f={seq:u.seq,type:u.type,content:u.content,metadata:u.metadata,createdAt:u.createdAt};n(p=>p.some(v=>v.seq===f.seq)?p:[...p,f])}):void 0,[s,e,t]),a)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(i.length===0)return c.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const l=i.map(h=>rC(h,e,s)).filter(h=>h!==null);return c.jsx("div",{className:"px-3 py-2",children:c.jsx(Wv,{entries:l,isStreaming:t})})}function ms({title:s,action:e,children:t}){return c.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[c.jsxs("div",{className:"flex items-center justify-between mb-3",children:[c.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:s}),e]}),t]})}function qs({label:s,mono:e,children:t}){return c.jsxs("div",{className:"flex flex-col gap-0.5",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s}),c.jsx("span",{className:`text-xs text-fg-secondary ${e?"font-mono text-[10px]":""}`,children:t})]})}function Ks({label:s,value:e,color:t}){const r=t==="green"?"text-green-500":t==="blue"?"text-blue-400":t==="indigo"?"text-brand-500":t==="red"?"text-red-400":"text-fg-secondary";return c.jsxs("div",{className:"flex items-baseline gap-1.5",children:[c.jsx("span",{className:`text-sm font-semibold ${r}`,children:e}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s})]})}const kv=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Cv=5,Pv=1440;function OI({agentId:s,intervalMs:e,onChanged:t}){const{t:r}=Pt(["agent","common"]),[i,n]=S.useState(!1),[a,o]=S.useState(null),[l,h]=S.useState(!1),[d,u]=S.useState(String(Math.round(e/6e4))),f=m=>m%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:m/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(m/6e4)}),p=async m=>{n(!0),o(null);try{await te.agents.updateConfig(s,{heartbeatIntervalMs:m}),t()}catch(x){o(String(x).replace("Error: ",""))}n(!1)},v=m=>{if(m.target.value==="custom"){h(!0);return}h(!1),p(Number(m.target.value))},b=()=>{const m=Math.round(Number(d));if(!Number.isFinite(m)||m<Cv||m>Pv){o(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}p(m*60*1e3)},g=kv.includes(e),O=l||!g?"custom":String(e);return c.jsxs("div",{className:"flex flex-col gap-1",children:[c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),c.jsxs("select",{value:O,onChange:v,disabled:i,className:"text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40",children:[!g&&c.jsx("option",{value:String(e),children:f(e)}),kv.map(m=>c.jsx("option",{value:String(m),children:f(m)},m)),c.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(l||!g)&&c.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[c.jsx("input",{type:"number",min:Cv,max:Pv,value:d,onChange:m=>u(m.target.value),disabled:i,className:"w-16 text-xs bg-bg-secondary border border-gray-700/50 rounded-md px-1.5 py-1 text-fg-secondary focus:outline-none focus:border-blue-500/50 disabled:opacity-40"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),c.jsx("button",{onClick:b,disabled:i,className:"text-[10px] px-2 py-1 rounded-md bg-blue-600/20 text-blue-600 hover:bg-blue-600/30 border border-blue-500/30 transition-colors disabled:opacity-40",children:r(i?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),a&&c.jsx("span",{className:"text-[10px] text-red-400",children:a})]})}function Xh({text:s}){return c.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:s})}function Tv(s){if(s===0)return"0 B";const e=["B","KB","MB","GB"],t=Math.min(Math.floor(Math.log(s)/Math.log(1024)),e.length-1),r=s/Math.pow(1024,t);return`${r<10?r.toFixed(1):Math.round(r)} ${e[t]}`}const Qv={0:"0",1:"1",2:"2",3:"3",4:"4"},$v={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},xI={pick:"bg-brand-500/20 text-brand-500",continue:"bg-gray-500/20 text-gray-500",preempt:"bg-amber-500/20 text-amber-500",merge:"bg-blue-500/20 text-blue-500",defer:"bg-purple-500/20 text-purple-500",delegate:"bg-green-500/20 text-green-500",drop:"bg-red-500/20 text-red-500"},bI={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},vI=["all","interaction","task","notification","system"],yI={completed:"bg-green-500",processing:"bg-blue-400 animate-pulse",deferred:"bg-purple-400",merged:"bg-brand-400",queued:"bg-amber-400",dropped:"bg-red-500"},SI={pending:"text-gray-400",assigned:"text-blue-400",in_progress:"text-brand-400",completed:"text-green-400",failed:"text-red-400",cancelled:"text-gray-500",review:"text-amber-400",approved:"text-green-500",rejected:"text-red-500",draft:"text-gray-400"};function wf(s){const e=s.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(e?.[1]){const t=e[1].trim().replace(/\n/g," ");return t.length>80?t.slice(0,80)+"…":t}}function jv(s,e){const t=s.payload,r=t?.summary??"",i=t?.content??"",n=s.metadata?.senderName;switch(s.sourceType){case"task_status_update":{const a=r.match(/^Task "(.+?)" status:/),o=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),l=a?.[1]??r;if(o){const d=o[1],u=o[2],f=Lm(d,e),p=Lm(u,e),v=SI[u]??"text-fg-secondary";return{title:l,subtitle:e("agent:profilePage.mind.mailbox.statusArrow",{from:f,to:p}),badge:{label:p,color:v}}}const h=r.match(/^Task:\s*(.+)/);return h?{title:h[1]}:{title:l}}case"task_comment":{const a=bv(r),o=wf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"requirement_update":{const a=r.match(/^Requirement "(.+?)"\s+(.*)/);return a?{title:a[1],subtitle:a[2]}:{title:r}}case"requirement_comment":{const a=bv(r),o=wf(i);if(a){const l=o?e("agent:profilePage.mind.mailbox.commentFromAuthor",{author:a.author,text:o}):e("agent:profilePage.mind.mailbox.commentFrom",{name:a.author});return{title:a.subject,subtitle:l}}return{title:r}}case"human_chat":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.chatFrom",{sender:n}):e("agent:profilePage.mind.mailbox.humanChat"),subtitle:a+(i.length>120?"…":"")}}case"a2a_message":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.messageFrom",{sender:n}):e("agent:profilePage.mind.mailbox.agentMessage"),subtitle:a+(i.length>120?"…":"")}}case"mention":{const a=r.match(/from (.+)$/),o=wf(i);return{title:a?e("agent:profilePage.mind.mailbox.mentionedBy",{name:a[1]}):e("agent:profilePage.mind.mailbox.mention"),subtitle:o||void 0}}case"review_request":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:n}):e("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:a+(i.length>120?"…":"")}}case"session_reply":{const a=i.slice(0,120).replace(/\n/g," ");return{title:n?e("agent:profilePage.mind.mailbox.replyInSession",{sender:n}):e("agent:profilePage.mind.mailbox.sessionReply"),subtitle:a+(i.length>120?"…":"")}}case"heartbeat":return{title:e("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:e("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:e("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const a=r.match(/^\[Announcement]\s*(.+)/);return a?{title:a[1],subtitle:e("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||e("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||s.sourceType}}}function wI({agentId:s,highlightId:e,agentStatus:t,canManageAgents:r}){const{t:i}=Pt(["agent","common","team"]),[n,a]=S.useState(null),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState("all"),[p,v]=S.useState("all"),[b,g]=S.useState(e??null),[O,m]=S.useState(e??null),[x,y]=S.useState(!1),[k,C]=S.useState(!1),[P,_]=S.useState(!0),[T,R]=S.useState(null),L=50,M=3,[E,B]=S.useState(null),U=S.useCallback(async(z=!0)=>{z&&d(!0);try{const re=u==="all"?void 0:u,Z=p==="all"?void 0:p,[A,J]=await Promise.all([te.agents.getMindState(s),te.agents.getMailbox(s,{limit:L,category:re,status:Z})]);a(A),l(J),_((J.history?.length??0)>=L)}catch{}d(!1)},[s,u,p]),F=S.useCallback(async z=>{B(z);try{await te.agents.dropMailboxItem(s,z,"operator"),await U()}catch{}finally{B(null)}},[s,U]),X=S.useCallback(async()=>{if(!o)return;const z=u==="all"?void 0:u,re=p==="all"?void 0:p;try{const Z=await te.agents.getMailbox(s,{limit:L,offset:o.history.length,category:z,status:re});l(A=>A?{...A,history:[...A.history,...Z.history]}:Z),_((Z.history?.length??0)>=L)}catch{}},[s,o,u,p]),ae=S.useCallback(async()=>{try{await te.agents.recoverStaleMailbox(s)}catch{}await U()},[s,U]);S.useEffect(()=>{g(e??null),m(e??null),U()},[U,e]);const j=S.useRef(!1);if(S.useEffect(()=>{if(!O||h)return;if(o?.history?.some(re=>re.id===O)){j.current=!1;const re=document.getElementById(`mbx-${O}`);if(re){setTimeout(()=>re.scrollIntoView({behavior:"smooth",block:"center"}),100);const Z=setTimeout(()=>m(null),3e3);return()=>clearTimeout(Z)}}else P&&!j.current&&(j.current=!0,(async()=>{let re=o?.history??[],Z=P;for(;Z;)try{const A=await te.agents.getMailbox(s,{limit:L,offset:re.length}),J=[...re,...A.history];re=J,Z=(A.history?.length??0)>=L;const Y=A.history.some(oe=>oe.id===O);if(l(oe=>oe?{...oe,history:J}:A),_(Z),Y||!Z)break}catch{break}j.current=!1})())},[O,h,o,P,s]),S.useEffect(()=>{let z=null;const re=A=>{A.payload?.agentId===s&&(z&&clearTimeout(z),z=setTimeout(()=>{z=null,U(!1)},500))},Z=[St.on("agent:mailbox",re),St.on("agent:decision",re),St.on("agent:attention",re),St.on("agent:focus",re),St.on("agent:update",re),St.on("agent:triage",re)];return()=>{z&&clearTimeout(z),Z.forEach(A=>A())}},[s,U]),h&&!n)return c.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:i("agent:profilePage.mind.loading")});const W=n?.mailboxDepth??n?.queuedItems?.length??0,D=qh(t).running,V=(()=>{const z=n?.attentionState??"idle";return z==="deciding"||z==="idle"&&W>0?"deciding":z!=="idle"&&!n?.currentFocus?"idle":z})(),se=V==="idle"&&o?.history?.some(z=>z.status==="processing"),fe=(n?.attentionState??"idle")==="idle"&&W>0;return c.jsxs("div",{className:"space-y-4",children:[c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[D?c.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${bI[V]??"bg-gray-500/20 text-gray-500"}`,children:i(`agent:profilePage.mind.attention.${V}`)}):c.jsx("span",{className:"px-2.5 py-1 text-xs font-medium rounded-full bg-gray-500/20 text-fg-tertiary",children:i("agent:profilePage.mind.agentStopped")}),D?n?.currentFocus?(()=>{const z=jv({id:n.currentFocus.mailboxItemId,sourceType:n.currentFocus.type,payload:{summary:n.currentFocus.label,taskId:n.currentFocus.taskId},metadata:{},queuedAt:n.currentFocus.startedAt},i);return c.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[c.jsxs("span",{children:[Nc(n.currentFocus.type)," ",c.jsx("span",{className:"text-fg-primary font-medium",children:z.title}),z.subtitle&&c.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:z.subtitle}),c.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:i("agent:profilePage.mind.since",{time:new Date(n.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&c.jsxs("button",{onClick:()=>R(n.currentFocus.mailboxItemId),className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]})})():fe?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.queuedButIdle",{count:W,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):V==="deciding"?c.jsx("span",{className:"text-sm text-amber-500",children:i("agent:profilePage.mind.decidingWaiting",{count:W})}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.idleWaiting")}):c.jsx("span",{className:"text-sm text-fg-tertiary",children:i("agent:profilePage.mind.stoppedHint")}),c.jsx("div",{className:"ml-auto flex items-center gap-2",children:c.jsx("button",{onClick:()=>{U()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:i("agent:profilePage.mind.refresh")})})]}),D&&se&&c.jsxs("div",{className:"mb-3 px-3 py-2 rounded-lg bg-amber-500/10 border border-amber-500/30 flex items-center gap-2",children:[c.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),c.jsx("span",{className:"text-[11px] text-amber-600 flex-1",children:i("agent:profilePage.mind.staleProcessingWarning")}),r&&c.jsx("button",{onClick:()=>{ae()},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-amber-500/20 text-amber-700 hover:bg-amber-500/30 transition-colors shrink-0",children:i("agent:profilePage.mind.recoverStaleBtn")})]}),(n?.queuedItems?.length??0)>0&&(()=>{const z=n.queuedItems,re=z.length>M,Z=re&&!x?z.slice(0,M):z,A=z.reduce((J,Y)=>(J[Y.sourceType]=(J[Y.sourceType]??0)+1,J),{});return c.jsxs("div",{className:"mb-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.queue",{count:z.length})}),c.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(A).map(([J,Y])=>c.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[Nc(J)," ",Y]},J))})]}),c.jsxs("div",{className:"space-y-1",children:[Z.map((J,Y)=>c.jsxs("div",{className:"flex items-center gap-2 px-3 py-1.5 rounded bg-amber-500/5 border border-amber-500/20 text-sm",children:[c.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:Y+1}),c.jsx("span",{className:"text-sm",children:Nc(J.sourceType)}),c.jsx("span",{className:`text-[10px] ${$v[J.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[J.priority]??J.priority}`,{defaultValue:`P${J.priority}`})}),c.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:J.summary}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(J.queuedAt).toLocaleTimeString()})]},J.id)),re&&c.jsx("button",{onClick:()=>y(!x),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:x?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandQueue",{count:z.length-M})})]})]})})()]}),(n?.notebook?.length??0)>0&&(()=>{const z=eI(n.notebook,k);return c.jsx("section",{className:"bg-surface-elevated rounded-lg border border-border-subtle p-3",children:c.jsxs("details",{children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"📓"}),c.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:i("agent:profilePage.mind.notebook")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:i("agent:profilePage.mind.notebookEntries",{count:n.notebook.length})})]}),c.jsx("p",{className:"mt-2 text-[10px] text-fg-muted leading-relaxed",children:i("agent:profilePage.mind.notebookHint",{count:j_})}),c.jsxs("div",{className:"mt-2 space-y-2",children:[z.visible.map(re=>{const Z=tI(re.updatedAt),A=i(`agent:profilePage.relative.${Z.unit==="seconds"?"secondsAgo":Z.unit==="minutes"?"minutesAgo":"hoursAgo"}`,{count:Z.count,hours:Z.count}),J=re.managed==="system"?"text-blue-400":"text-emerald-400";return c.jsxs("div",{className:"px-3 py-2 rounded bg-surface-overlay border border-border-subtle",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[c.jsx("span",{className:"text-xs font-medium text-fg-primary",children:re.key}),c.jsxs("span",{className:`text-[10px] ${J}`,children:["[",re.managed,"]"]}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:A})]}),c.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:re.text.length>500?re.text.slice(0,500)+"…":re.text})]},re.key)}),z.collapsible&&c.jsx("button",{onClick:()=>C(!k),className:"w-full text-center text-[11px] text-accent-primary hover:opacity-80 py-1 transition-colors",children:k?i("agent:profilePage.mind.collapseQueue"):i("agent:profilePage.mind.expandNotebook",{count:z.hiddenCount})})]})]})})})(),n?.deliberationActivity&&c.jsxs("section",{className:"bg-surface-elevated rounded-lg border border-amber-500/20 p-3",children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:i("agent:profilePage.mind.deliberationInProgress")}),c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-indigo-500/15 text-indigo-300",children:i("agent:profilePage.mind.batchDeliberating")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:i("agent:profilePage.mind.since",{time:new Date(n.deliberationActivity.startedAt).toLocaleTimeString()})})]}),c.jsx(Wh,{agentId:s,activityId:n.deliberationActivity.activityId,isLive:!0})]}),n?.lastTriage&&(()=>{const re=Date.now()-new Date(n.lastTriage.timestamp).getTime()>6e4,Z=J2(n.lastTriage);return c.jsx("section",{className:`bg-surface-elevated rounded-lg border p-3 transition-opacity ${re?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:c.jsxs("details",{open:!re,children:[c.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[c.jsx("span",{className:"text-sm",children:"🧠"}),c.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:i("agent:profilePage.mind.triageDecision")}),c.jsx("span",{className:"text-[10px] text-fg-muted ml-auto",children:new Date(n.lastTriage.timestamp).toLocaleTimeString()})]}),c.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:n.lastTriage.reasoning}),c.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:i("agent:profilePage.mind.processingItem",{id:n.lastTriage.processedItemId.slice(0,12)})}),c.jsx("span",{className:`px-1.5 py-0.5 rounded ${Z.isBatch?"bg-indigo-500/15 text-indigo-300":"bg-surface-overlay text-fg-tertiary"}`,children:Z.isBatch?i("agent:profilePage.mind.batchSize",{count:Z.total}):i("agent:profilePage.mind.singleItem")}),n.lastTriage.deferredItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:i("agent:profilePage.mind.deferred",{count:n.lastTriage.deferredItemIds.length})}),n.lastTriage.droppedItemIds.length>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:i("agent:profilePage.mind.dropped",{count:n.lastTriage.droppedItemIds.length})}),(n.lastTriage.inlineCompletedIds?.length??0)>0&&c.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:i("agent:profilePage.mind.inlineCompleted",{count:n.lastTriage.inlineCompletedIds.length})})]})]})})})(),c.jsxs("section",{children:[c.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[c.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.mailboxHistory")}),c.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:vI.map(z=>{const re=o?.sourceTypeCounts,Z=z==="all"?re?Object.values(re).reduce((A,J)=>A+J,0):void 0:re?(UD[z]??[]).reduce((A,J)=>A+(re[J]??0),0):void 0;return c.jsxs("button",{onClick:()=>f(z),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${u===z?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-elevated border-border-subtle text-fg-secondary hover:bg-surface-overlay"}`,children:[i(`agent:profilePage.mind.categoryFilters.${z}`),Z!=null&&Z>0&&c.jsx("span",{className:"ml-1 opacity-60",children:Z})]},z)})})]}),c.jsx("div",{className:"flex gap-1 mb-2 flex-wrap",children:[{key:"all",dot:""},{key:"queued",dot:"bg-amber-400"},{key:"processing",dot:"bg-blue-400"},{key:"completed",dot:"bg-green-500"},{key:"merged",dot:"bg-brand-400"},{key:"deferred",dot:"bg-purple-400"},{key:"dropped",dot:"bg-red-500"}].map(z=>{const re=o?.statusCounts,Z=z.key==="all"?re?Object.values(re).reduce((A,J)=>A+J,0):void 0:re?.[z.key];return c.jsxs("button",{onClick:()=>v(z.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===z.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-elevated border-border-subtle text-fg-secondary hover:bg-surface-overlay"}`,children:[z.dot&&c.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${z.dot}`}),i(`agent:profilePage.mind.statusFilters.${z.key}`),Z!=null&&Z>0&&c.jsx("span",{className:"ml-1 opacity-60",children:Z})]},z.key)})}),(!o?.history||o.history.length===0)&&!h&&c.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:i("agent:profilePage.mind.noHistory")}),c.jsx("div",{className:"space-y-1",children:o?.history?.map(z=>{const re=b===z.id,Z=Nc(z.sourceType),A=jv(z,i),J=KD({itemStatus:z.status,agentRunning:D,currentFocusMailboxItemId:n?.currentFocus?.mailboxItemId??null,itemId:z.id}),Y=z.metadata?.senderName,oe=z.metadata?.senderRole,K=O===z.id;return c.jsxs("div",{id:`mbx-${z.id}`,className:`bg-surface-elevated rounded-lg border transition-colors duration-1000 ${K?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[c.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-overlay/50 transition-colors rounded-lg",onClick:()=>g(re?null:z.id),children:[c.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:re?"▾":"▸"}),c.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${J==="stale"?"bg-amber-400/70":yI[z.status]??"bg-gray-400"}`}),c.jsx("span",{className:"text-sm",children:Z}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:`text-xs font-medium text-fg-primary ${re?"":"truncate"}`,children:A.title}),A.badge&&c.jsx("span",{className:`text-[10px] font-medium shrink-0 ${A.badge.color}`,children:A.badge.label}),c.jsx("span",{className:`text-[10px] shrink-0 ${$v[z.priority]??"text-fg-tertiary"}`,children:i(`agent:profilePage.mind.priority.${Qv[z.priority]??z.priority}`,{defaultValue:""})})]}),A.subtitle&&c.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${re?"":"truncate"}`,children:A.subtitle}),c.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[c.jsx("span",{children:new Date(z.queuedAt).toLocaleString()}),z.completedAt&&c.jsxs("span",{children:["→ ",new Date(z.completedAt).toLocaleTimeString()]}),z.activity&&c.jsxs(c.Fragment,{children:[z.activity.totalTokens>0&&c.jsx("span",{children:i("agent:profilePage.mind.tokensCount",{count:Nm(z.activity.totalTokens)})}),z.activity.totalTools>0&&c.jsx("span",{children:i("agent:profilePage.mind.toolsCount",{count:z.activity.totalTools})})]})]})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-overlay px-1.5 py-0.5 rounded shrink-0",children:z.sourceType}),r&&GD({agentRunning:D,itemId:z.id,currentFocusId:n?.currentFocus?.mailboxItemId??null,itemStatus:z.status})&&c.jsxs("button",{onClick:pe=>{pe.stopPropagation(),R(z.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors shrink-0",children:["✕ ",i("agent:profilePage.mind.cancelCurrentBtn")]})]}),re&&c.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[Y&&c.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[i("agent:profilePage.mind.from")," ",c.jsx("span",{className:"text-fg-secondary",children:Y}),oe&&c.jsxs("span",{className:"text-fg-tertiary",children:[" (",oe,")"]})]}),z.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(z.sourceType)&&c.jsx("div",{className:"text-xs text-fg-secondary bg-surface-primary/50 rounded-md p-2.5 whitespace-pre-wrap break-words max-h-60 overflow-y-auto",children:z.payload.content}),z.decisions&&z.decisions.length>0&&c.jsxs("div",{children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:i("agent:profilePage.mind.decisions")}),c.jsx("div",{className:"space-y-1",children:z.decisions.map(pe=>c.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[c.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${xI[pe.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:pe.decisionType}),c.jsx("span",{className:"text-fg-secondary flex-1",children:pe.reasoning}),c.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(pe.createdAt).toLocaleTimeString()})]},pe.id))})]}),r&&c.jsxs("div",{className:"space-y-2",children:[c.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider",children:i("agent:profilePage.mind.actions")}),c.jsx("div",{className:"flex gap-2",children:c.jsx("button",{disabled:E===z.id,onClick:()=>{F(z.id)},className:"px-2 py-0.5 text-[10px] font-medium rounded-md bg-red-500/15 text-red-400 hover:bg-red-500/25 disabled:opacity-40 transition-colors",children:i("agent:profilePage.mind.dropBtn")})})]}),z.activity?c.jsxs("div",{children:[c.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[i("agent:profilePage.mind.activityHeading",{label:z.activity.label}),c.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${z.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:z.activity.success?i("agent:profilePage.mind.success"):i("agent:profilePage.mind.failed")})]}),z.activity.type==="task"&&z.payload?.taskId?c.jsx(gI,{taskId:z.payload.taskId,isLive:!z.activity.endedAt}):c.jsx(Wh,{agentId:s,activityId:z.activity.id,isLive:!z.activity.endedAt})]}):J==="processing"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:i("agent:profilePage.mind.processing")}):J==="stale"?c.jsx("div",{className:"text-xs text-amber-600 text-center py-2",children:i("agent:profilePage.mind.staleProcessingWarning")}):z.status==="completed"?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:i("agent:profilePage.mind.noActivityLog")}):null]})]},z.id)})}),P&&(o?.history?.length??0)>0&&c.jsx("div",{className:"text-center mt-3",children:c.jsx("button",{onClick:X,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:i("agent:profilePage.mind.loadEarlier")})})]}),T&&c.jsx(Wo,{title:i("agent:profilePage.mind.cancelConfirmTitle"),message:i("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:i("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{const z=T;R(null),te.agents.cancelProcessing(s,{itemId:z}).then(()=>{let re=0;const Z=()=>{re+=1,U(),re<8&&window.setTimeout(Z,750)};Z()}).catch(()=>{U()})},onCancel:()=>R(null)})]})}function Rv({agentId:s}){const{t:e}=Pt(["agent","common"]),t=zh(),[r,i]=S.useState([]),[n,a]=S.useState(!0),o=S.useCallback(h=>{if(K2(t?.hostAvailable)==="right-panel"){t?.openRightPanel({kind:"deliverable",deliverable:h});return}Lr.navigate(Yt.DELIVERABLES,{openDeliverable:h.id})},[t]),l=S.useCallback(async()=>{a(!0);try{const{results:h}=await te.deliverables.search({agentId:s,limit:200});i(h)}catch{i([])}a(!1)},[s]);return S.useEffect(()=>{l()},[l]),S.useEffect(()=>{const h=St.on("deliverable:created",()=>l()),d=St.on("deliverable:updated",()=>l()),u=St.on("deliverable:removed",()=>l());return()=>{h(),d(),u()}},[l]),n?c.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(h=>c.jsxs("div",{className:"animate-pulse space-y-2",children:[c.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),c.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},h))}):r.length===0?c.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[c.jsx("span",{className:"text-3xl mb-3",children:"📦"}),c.jsx("p",{className:"text-sm text-fg-secondary",children:e("agent:deliverables.empty")}),c.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:e("agent:deliverables.emptyHint")})]}):c.jsx(c.Fragment,{children:c.jsxs("div",{className:"space-y-2",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:e("agent:deliverables.count",{count:r.length})}),r.map(h=>{const d=tC[h.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},u=yO[h.status]??yO.active;return c.jsxs("button",{onClick:()=>o(h),className:"w-full text-left rounded-xl border border-border-default bg-surface-elevated/30 overflow-hidden transition-colors hover:border-brand-500/40 hover:bg-surface-elevated/50 px-4 py-3 flex items-start gap-3",children:[c.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${d.color}`,children:d.icon}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:h.title}),c.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${u.color}`,children:h.status})]}),h.summary&&c.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:h.summary}),c.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[c.jsx("span",{children:new Date(h.createdAt).toLocaleDateString()}),h.tags.length>0&&c.jsx("span",{children:h.tags.slice(0,3).join(", ")})]})]}),c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0 mt-1",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:2,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},h.id)})]})})}const _I=S.lazy(()=>Xv(()=>import("./index-CIrsLoqm.js").then(s=>s.bn),__vite__mapDeps([0,1])).then(s=>({default:s.MarkdownMessage}))),lg=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Ev={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Av({teamId:s,onBack:e,inline:t,headless:r,activeTab:i,onSelectAgent:n}){const{t:a}=Pt("team"),[o,l]=S.useState(null),[h,d]=S.useState(!0),[u,f]=S.useState(!0),[p,v]=S.useState(null),[b,g]=S.useState("overview"),O=r&&i?i:b,[m,x]=S.useState(""),[y,k]=S.useState(""),[C,P]=S.useState(!1),[_,T]=S.useState(!1),[R,L]=S.useState(""),[M,E]=S.useState(""),B=S.useRef(null),U=S.useRef(null),F=S.useRef(null),X=S.useRef(null),[ae,j]=S.useState(!1),[W,D]=S.useState(!1),[V,se]=S.useState(""),[fe,z]=S.useState(""),[re,Z]=S.useState(!1),[A,J]=S.useState([]),Y=S.useRef(null),oe=S.useCallback(async()=>{try{const qe=(await te.teams.list()).teams.find(Ye=>Ye.id===s);qe&&l(qe);const He=await te.teams.status(s);J(He.agents)}catch{}finally{d(!1)}},[s]),K=S.useCallback(async()=>{f(!0);try{const G=await te.teams.getFile(s,"ANNOUNCEMENT.md");x(G.content)}catch{x("")}try{const G=await te.teams.getFile(s,"NORMS.md");k(G.content)}catch{k("")}finally{f(!1)}},[s]);S.useEffect(()=>{g("overview"),oe(),K()},[s,oe,K]),S.useEffect(()=>{C&&U.current&&U.current.focus()},[C]),S.useEffect(()=>{_&&X.current&&X.current.focus()},[_]);const pe=async(G,qe)=>{j(!0);try{await te.teams.updateFile(s,G,qe),G==="ANNOUNCEMENT.md"?(x(qe),P(!1)):(k(qe),T(!1))}catch{}j(!1)},je=async()=>{V.trim()&&(await te.teams.update(s,{name:V.trim()}),D(!1),oe())},we=async()=>{await te.teams.update(s,{description:fe}),Z(!1),oe()};if(!o)return h?c.jsx(zv,{label:a("common:loading",{defaultValue:"Loading…"})}):c.jsx(BC,{icon:c.jsx("span",{className:"text-2xl",children:"🫥"}),title:a("teamProfile.teamMissing",{defaultValue:"Team not found"})});const Ge=o.members.find(G=>G.agentRole==="manager"),Qe=A.filter(G=>G.status!=="offline").length,Ee=O==="announcements"&&C||O==="norms"&&_;if(r)return c.jsx("div",{className:`flex-1 bg-surface-primary ${Ee?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:c.jsxs("div",{className:`${Ee?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[O==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Ge?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(G=>{const qe=A.find(pt=>pt.id===G.id),He=Ev[qe?.status??"offline"]??"bg-gray-500",Ye=G.type==="agent";return c.jsxs("div",{onClick:()=>Ye&&n?.(G.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Ye&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ns,{name:G.name,avatarUrl:G.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:G.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),G.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[G.role," · ",G.type]})]}),Ye&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),O==="announcements"&&c.jsx(Dc,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ae,onSave:()=>pe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),O==="norms"&&c.jsx(Dc,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:F,saving:ae,onSave:()=>pe("NORMS.md",M),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:u}),O==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),W?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:V,onChange:G=>se(G.target.value),onKeyDown:G=>G.key==="Enter"&&je(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:je,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{se(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:fe,onChange:G=>z(G.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]})});const ye=b==="announcements"&&C||b==="norms"&&_;return c.jsxs("div",{className:`flex-1 bg-surface-primary ${ye?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[c.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[c.jsxs("div",{className:"flex items-center gap-3",children:[c.jsx("div",{className:"w-10 h-10 rounded-xl bg-brand-600 text-white flex items-center justify-center text-lg font-bold shrink-0",children:c.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[c.jsx("h2",{className:"text-base font-semibold",children:o.name}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[o.members.length," members"]}),c.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Qe," online"]})]}),c.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:o.description||"No description"})]}),c.jsxs("button",{onClick:async()=>{if(o)try{const{files:G}=await te.teams.getFilesMap(o.id),qe=o.members.filter(Ye=>Ye.type==="agent"),He={type:"team",name:Bv(o.name,o.name),displayName:o.name,version:"1.0.0",description:o.description??"",author:"",category:"general",tags:[],team:{members:qe.map(Ye=>({name:Ye.name,roleName:Ye.role,role:Ye.agentRole??"worker",count:1,skills:[]}))}};await Fm.publishViaProxy({itemType:"team",name:o.name,description:o.description??"",category:"general",config:He,files:G}),v({title:"Hub",message:`Published "${o.name}" to Markus Hub`,variant:"primary"})}catch(G){v({title:"Hub",message:`Failed to publish: ${G}`,variant:"danger"})}},className:"px-3 py-1.5 text-xs bg-green-600 hover:bg-green-500 text-white rounded-lg transition-colors flex items-center gap-1",title:"Publish to Markus Hub",children:[c.jsx("span",{children:"↑"})," Hub"]}),t&&c.jsx("button",{onClick:e,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),c.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:lg.map(G=>c.jsxs("button",{onClick:()=>g(G.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${b===G.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[G.icon," ",a(G.labelKey)]},G.key))})]}),c.jsxs("div",{className:`${ye?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[b==="overview"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),c.jsx("div",{className:"text-sm font-medium",children:Ge?.name??o.managerName??"None"})]}),c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),c.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:o.id})]})]}),c.jsxs("div",{className:"space-y-3",children:[c.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),o.members.map(G=>{const qe=A.find(pt=>pt.id===G.id),He=Ev[qe?.status??"offline"]??"bg-gray-500",Ye=G.type==="agent";return c.jsxs("div",{onClick:()=>Ye&&n?.(G.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Ye&&n?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[c.jsx(Ns,{name:G.name,avatarUrl:G.avatarUrl,size:32,className:"rounded-lg"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm font-medium",children:G.name}),c.jsx("span",{className:`w-2 h-2 rounded-full ${He}`}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),G.agentRole==="manager"&&c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),c.jsxs("div",{className:"text-xs text-fg-tertiary",children:[G.role," · ",G.type]})]}),Ye&&n&&c.jsx("svg",{className:"w-4 h-4 text-fg-tertiary shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]},G.id)}),o.members.length===0&&c.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:a("teamProfile.noMembers",{defaultValue:"No members"})})]})]}),b==="announcements"&&c.jsx(Dc,{content:m,draft:R,setDraft:L,editing:C,setEditing:P,textareaRef:U,contentRef:B,saving:ae,onSave:()=>pe("ANNOUNCEMENT.md",R),placeholder:a("teamProfile.annPlaceholder"),emptyText:a("teamProfile.noAnnouncements"),loading:u}),b==="norms"&&c.jsx(Dc,{content:y,draft:M,setDraft:E,editing:_,setEditing:T,textareaRef:X,contentRef:F,saving:ae,onSave:()=>pe("NORMS.md",M),placeholder:a("teamProfile.normsPlaceholder"),emptyText:a("teamProfile.noNorms"),loading:u}),b==="settings"&&c.jsxs("div",{className:"space-y-5",children:[c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),W?c.jsxs("div",{className:"flex gap-2 items-center",children:[c.jsx("input",{ref:Y,value:V,onChange:G=>se(G.target.value),onKeyDown:G=>G.key==="Enter"&&je(),className:"flex-1 bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary focus:outline-none focus:border-brand-500",autoFocus:!0}),c.jsx("button",{onClick:je,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>D(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm",children:o.name}),c.jsx("button",{onClick:()=>{se(o.name),D(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),c.jsxs("div",{children:[c.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),re?c.jsxs("div",{className:"space-y-2",children:[c.jsx("textarea",{value:fe,onChange:G=>z(G.target.value),className:"w-full bg-surface-elevated border border-border-default rounded-lg px-3 py-1.5 text-sm text-fg-primary resize-y focus:outline-none focus:border-brand-500",rows:3,autoFocus:!0}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{onClick:we,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),c.jsx("button",{onClick:()=>Z(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):c.jsxs("div",{className:"flex items-center gap-2",children:[c.jsx("span",{className:"text-sm text-fg-secondary",children:o.description||"No description"}),c.jsx("button",{onClick:()=>{z(o.description??""),Z(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),c.jsx(Mv,{teamId:s,teamName:o.name,onDeleted:e})]})]}),p&&c.jsx(Wo,{alertOnly:!0,variant:p.variant??"primary",title:p.title,message:p.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function Dc({content:s,draft:e,setDraft:t,editing:r,setEditing:i,textareaRef:n,contentRef:a,saving:o,onSave:l,placeholder:h,emptyText:d,loading:u}){return r?c.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[c.jsx("textarea",{ref:n,value:e,onChange:f=>t(f.target.value),onBlur:()=>{e!==s?l():i(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),t(s),i(!1))},className:"flex-1 w-full bg-transparent border border-brand-500/30 rounded-lg text-sm text-fg-primary focus:border-brand-500 outline-none resize-none px-3 py-2 font-mono",placeholder:h}),o&&c.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):c.jsx("div",{ref:a,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{t(s),i(!0)},role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&(t(s),i(!0))},children:u&&!s.trim()?c.jsx(qv,{variant:"text",className:"px-1 py-2"}):s.trim()?c.jsx(S.Suspense,{fallback:c.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:c.jsx(_I,{content:s,className:"text-sm text-fg-secondary leading-relaxed"})}):c.jsx("div",{className:"text-sm text-fg-tertiary italic",children:d})})}function Mv({teamId:s,teamName:e,onDeleted:t}){const[r,i]=S.useState(!1),[n,a]=S.useState(!1),[o,l]=S.useState(!1),[h,d]=S.useState(!1);return c.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[c.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?c.jsxs("div",{className:"space-y-3",children:[c.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',e,'"? This removes the team record from the database.']}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:o,onChange:u=>l(u.target.checked),className:"rounded"}),"Also delete all members in this team"]}),c.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[c.jsx("input",{type:"checkbox",checked:n,onChange:u=>a(u.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),c.jsxs("div",{className:"flex gap-2",children:[c.jsx("button",{disabled:h,onClick:async()=>{d(!0);try{await te.teams.delete(s,o,{purgeFiles:n}),window.dispatchEvent(new CustomEvent("markus:data-changed")),t()}catch{d(!1)}},className:"px-4 py-1.5 text-xs bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors disabled:opacity-50",children:h?"Deleting...":"Confirm Delete"}),c.jsx("button",{onClick:()=>i(!1),className:"px-4 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay text-fg-secondary rounded-lg transition-colors border border-border-default",children:"Cancel"})]})]}):c.jsx("button",{onClick:()=>i(!0),className:"px-4 py-1.5 text-xs bg-red-600/20 hover:bg-red-600/30 text-red-500 rounded-lg transition-colors border border-red-500/30",children:"Delete Team"})]})}const kI=["chat","overview","deliverables"],CI=["chat","overview","announcements","norms","settings"];function PI(s,e){if(s==="chat")return e("page.chatTitle");if(ag.find(i=>i.key===s))return e(`agent:tabs.${s}`);const r=lg.find(i=>i.key===s);return r?e(r.labelKey):s}function TI(s){if(s==="chat")return"💬";const e=ag.find(r=>r.key===s);if(e)return e.icon;const t=lg.find(r=>r.key===s);return t?t.icon:""}function qi(s){return s!=="chat"}function Ea(s,e,t,r){return s==="channel"?`ch:${t}`:s==="dm"?`dm:${r??""}`:e||"_direct"}const Dm=s=>!!s&&!s.startsWith("ch:")&&!s.startsWith("dm:")&&s!=="_direct";class Ar{currentConvKey="";loadingSession=null;buffers=new Map;view=new Map;viewReader={get:e=>this.view.get(e)};get activeSessions(){return this.viewReader}actBuffers=new Map;sessionTabs=new Map;windowBounds=new Map;getWindowBounds(e){return this.windowBounds.get(e)??{hasMore:!1,oldestCursor:null}}setWindowBounds(e,t){this.windowBounds.set(e,t)}phase=new Map;sendCount=new Map;streamingSessions=new Map;bufferOrder=[];static MAX_MESSAGES=500;static MAX_BUFFERS=30;static NEW_CHAT_ID="__new_chat__";getPhase(e){const t=this.phase.get(e)??"idle";return t==="streaming"?t:this.hasLiveStream(e)?"streaming":t}hasLiveStream(e){return(this.streamingSessions.get(e)?.size??0)>0}beginLoad(e){this.getPhase(e)!=="streaming"&&this.phase.set(e,"loading")}completeLoad(e){this.getPhase(e)==="loading"&&this.phase.set(e,"ready")}beginStream(e){this.phase.set(e,"streaming")}endStream(e){this.getPhase(e)==="streaming"&&this.phase.set(e,"ready")}resetConv(e,t){this.phase.set(e,"idle");const r=this.view.get(e);r&&(this.buffers.delete(r),this.windowBounds.delete(r)),this.actBuffers.delete(r??e),this.actBuffers.delete(e),t?this.view.set(e,t):this.view.delete(e)}bufferIdFor(e,t){return t??this.view.get(e)??e}updateMessages(e,t,r){const i=this.bufferIdFor(e,r);let n=t(this.buffers.get(i)??[]);n.length>Ar.MAX_MESSAGES&&(n=n.slice(-500)),this.buffers.set(i,n),this.touchBuffer(i),this.evictIfNeeded(i);const a=this.currentConvKey===e&&(this.view.get(e)??e)===i;return{displayChanged:a,newMessages:a?n:void 0}}applyLoadResult(e,t,r){const i=this.buffers.get(t)??[],n=this.isStreamLiveForSession(e,t),a=this.mergeDbWithCache(r,i,n);this.buffers.set(t,a),this.touchBuffer(t),this.evictIfNeeded(t),this.loadingSession===t&&this.completeLoad(e);const o=this.currentConvKey===e&&(this.view.get(e)??e)===t;return{displayChanged:o,newMessages:o?a:void 0}}mergeDbWithCache(e,t,r=!1){if(!t||t.length===0)return[...e];const i=new Set,n=[];for(const u of e)i.add(u.id),n.push(u);const a=[],o=[],l=e.length>0?e[e.length-1]:void 0,h=!!l&&l.sender==="agent";let d=!1;for(const u of t)if(!i.has(u.id)){if(u.sender==="agent"&&!!!(u.isError||u.isStopped||u.emptyReply)){if(r&&u.isStreaming)if(h&&l&&!d){const p=n.findIndex(v=>v.id===l.id);p>=0&&n.splice(p,1),d=!0,a.push({...u,id:l.id}),i.add(l.id)}else a.push(u),i.add(u.id);continue}o.push(u)}for(const u of o){if(i.has(u.id))continue;const f=u.rawCreatedAt?Date.parse(u.rawCreatedAt):NaN;let p=n.length;for(;p>0&&n[p-1].rawCreatedAt&&Number.isFinite(f);){const v=Date.parse(n[p-1].rawCreatedAt);if(!Number.isFinite(v)||v<=f)break;p--}n.splice(p,0,u),i.add(u.id)}for(const u of a)n.push(u);return n}appendActivity(e,t,r){const i=r??e,n=[...this.actBuffers.get(i)??[],t];if(this.actBuffers.set(i,n),this.currentConvKey!==e)return{displayChanged:!1};const a=this.view.get(e);return!r||!a||a===r?{displayChanged:!0,newActivities:n}:{displayChanged:!1}}getActiveSession(e){return this.view.get(e)}setActiveSession(e,t){if(!Dm(e))return;const r=this.view.get(e);if(r!==t&&(r===void 0||r===Ar.NEW_CHAT_ID)){this.promotePlaceholder(t),this.view.set(e,t);return}}promotePlaceholder(e){const t=this.buffers.get(Ar.NEW_CHAT_ID);if(!t||t.length===0)return;const r=this.buffers.get(e)??[],i=new Set(r.map(a=>a.id)),n=[...r,...t.filter(a=>!i.has(a.id))];this.buffers.set(e,n),this.touchBuffer(e),this.buffers.delete(Ar.NEW_CHAT_ID)}clearActiveSession(e){this.view.delete(e)}saveToCache(){}restoreFromCache(e,t){Dm(e)&&this.view.set(e,t);const r=this.buffers.get(t);if(!r||r.length===0)return;if(this.isStreamLiveForSession(e,t))return r;const n=r.filter(a=>!(a.sender==="agent"&&a.isStreaming&&!a.isStopped));if(n.length===0){this.buffers.delete(t);return}return this.buffers.set(t,n),n}isStreamLiveForSession(e,t){if(this.getPhase(e)!=="streaming")return!1;const r=this.streamingSessions.get(e);return!r||r.size===0||r.has(t)?!0:this.placeholderTurnBelongsTo(e,t)}placeholderTurnBelongsTo(e,t){const r=this.streamingSessions.get(e);return!r||!r.has(Ar.NEW_CHAT_ID)?!1:this.view.get(e)===t}incrementSend(e){this.sendCount.set(e,(this.sendCount.get(e)??0)+1)}decrementSend(e){const t=Math.max(0,(this.sendCount.get(e)??1)-1);return this.sendCount.set(e,t),t}resetSend(e){this.sendCount.set(e,0)}isSending(e){return(this.sendCount.get(e)??0)>0}addStreamSession(e,t){const r=this.streamingSessions.get(e)??new Set;return r.has(t)?(this.streamingSessions.set(e,r),!1):(r.add(t),this.streamingSessions.set(e,r),!0)}removeStreamSession(e,t){if(t){const r=this.streamingSessions.get(e);return!r||!r.has(t)?!1:(r.delete(t),r.size===0&&this.streamingSessions.delete(e),!0)}return this.streamingSessions.delete(e)}getStreamSessions(e){return this.streamingSessions.get(e)}abortStream(e,t){let r=!1;(this.sendCount.get(e)??0)>0&&(this.sendCount.set(e,0),r=!0);const i=t??e;if(this.actBuffers.delete(i)&&(r=!0),this.getPhase(e)==="streaming"&&(this.phase.set(e,"ready"),r=!0),t){const n=this.streamingSessions.get(e)?.has(t)??!1;this.removeStreamSession(e,t),n&&(r=!0)}else this.streamingSessions.delete(e)&&(r=!0);return r}getMessages(e){return this.buffers.get(this.view.get(e)??e)}getActivities(e){return this.actBuffers.get(e)??[]}deleteBuffer(e){this.buffers.delete(e),this.windowBounds.delete(e)}viewBufferId(){const e=this.currentConvKey;return this.view.get(e)??e}evictIfNeeded(e){if(this.buffers.size<=Ar.MAX_BUFFERS)return;const t=this.viewBufferId();for(const r of[...this.buffers.keys()]){if(this.buffers.size<=Ar.MAX_BUFFERS)break;r===e||r===t||(this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r))}}touchBuffer(e){const t=this.bufferOrder.indexOf(e);for(t!==-1&&this.bufferOrder.splice(t,1),this.bufferOrder.push(e);this.bufferOrder.length>Ar.MAX_BUFFERS;){const r=this.bufferOrder.shift();if(new Set([this.viewBufferId(),...this.view.values()]).has(r)){this.bufferOrder.push(r);break}this.buffers.delete(r),this.actBuffers.delete(r),this.windowBounds.delete(r)}}}const it=Ar.NEW_CHAT_ID;function QI(s){const e=S.useRef(new Ar),[t,r]=S.useState(s??[]),[i,n]=S.useState(!1),[a,o]=S.useState([]),l=S.useRef(null),[,h]=S.useState(0),d=S.useCallback(()=>h(R=>R+1),[]),u=S.useCallback(R=>e.current.getStreamSessions(R),[]),f=S.useCallback((R,L)=>{e.current.addStreamSession(R,L)&&d()},[d]),p=S.useCallback((R,L)=>{e.current.removeStreamSession(R,L)&&d()},[d]),v=S.useCallback((R,L)=>e.current.setActiveSession(R,L),[]),b=S.useCallback(R=>e.current.clearActiveSession(R),[]);S.useEffect(()=>()=>{l.current!==null&&cancelAnimationFrame(l.current)},[]);const g=S.useCallback((R,L,M)=>{const E=e.current.updateMessages(R,L,M);E.displayChanged&&E.newMessages&&r(E.newMessages)},[]),O=S.useCallback((R,L,M)=>{e.current.updateMessages(R,L,M).displayChanged&&l.current===null&&(l.current=requestAnimationFrame(()=>{l.current=null;const B=e.current.getMessages(R);B&&e.current.currentConvKey===R&&r([...B])}))},[]),m=S.useCallback((R,L,M)=>{const E=e.current.appendActivity(R,L,M);E.displayChanged&&E.newActivities&&o(E.newActivities)},[]),x=S.useCallback(R=>e.current.getPhase(R),[]),y=S.useCallback(R=>e.current.beginLoad(R),[]),k=S.useCallback(R=>{e.current.beginStream(R)},[]),C=S.useCallback(R=>{e.current.endStream(R)},[]),P=S.useCallback((R,L)=>{e.current.abortStream(R,L)&&d(),e.current.currentConvKey===R&&(n(!1),o([]))},[d]),_=S.useCallback((R,L)=>{e.current.resetConv(R,L),e.current.deleteBuffer(R)},[]),T=S.useCallback(async(R,L,M)=>{e.current.loadingSession=R,e.current.beginLoad(L);try{const E=await M(),B=e.current.applyLoadResult(L,R,E.messages);return B.displayChanged&&B.newMessages&&r(B.newMessages),{count:E.messages.length,hasMore:E.hasMore,oldestCursor:E.oldestCursor}}catch{return e.current.currentConvKey===L&&e.current.getPhase(L)!=="streaming"&&(r([]),e.current.completeLoad(L)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:e.current,messages:t,setMessages:r,sending:i,setSending:n,activities:a,setActivities:o,get buffers(){return e.current.buffers},get viewBuffer(){return e.current.activeSessions},get activeSessionBuffer(){return e.current.activeSessions},get actBuffers(){return e.current.actBuffers},get sessionTabsBuffer(){return e.current.sessionTabs},get currentConvKeyRef(){return{get current(){return e.current.currentConvKey},set current(R){e.current.currentConvKey=R}}},get loadingSessionRef(){return{get current(){return e.current.loadingSession},set current(R){e.current.loadingSession=R}}},updateConvMsgs:g,updateConvMsgsRaf:O,appendConvActivity:m,getPhase:x,beginLoad:y,beginStream:k,endStream:C,resetConv:_,abortStream:P,loadAndDisplay:T,setActiveSession:v,clearActiveSession:b,incrementSending:R=>e.current.incrementSend(R),decrementSending:R=>e.current.decrementSend(R),resetSending:R=>e.current.resetSend(R),isSendingFor:R=>e.current.isSending(R),setStreamSession:f,clearStreamSession:p,getStreamSession:u,saveSessionToCache:(R,L)=>e.current.saveToCache(),restoreSessionFromCache:(R,L)=>{const M=e.current.restoreFromCache(R,L);return r(M??[]),M},readConvMsgs:R=>e.current.getMessages(R),writeConvMsgs:(R,L)=>{const M=e.current.updateMessages(R,()=>L);M.displayChanged&&M.newMessages&&r(M.newMessages)}}}function _f(s,e){return!s||s===e?{kind:"skip"}:{kind:"cancel",target:{sessionId:s}}}function $I(s){const e=S.useRef(new Map),t=S.useRef(new Map),r=Ee=>{if(Ee)for(const[ye,G]of e.current)G===Ee&&e.current.delete(ye)},i=Ee=>{if(Ee)for(const[ye,G]of t.current)G===Ee&&t.current.delete(ye)},n=Ee=>{const ye=e.current.get(Ee);ye&&(ye.abort(),e.current.delete(Ee));const G=t.current.get(Ee);G&&(G.abort(),t.current.delete(Ee))},a=Ee=>{const ye=e.current.get(it);ye&&e.current.size===1&&(e.current.delete(it),e.current.set(Ee,ye))},o=S.useRef(new Map),l=S.useRef(new Set),h=S.useRef(null),d=S.useRef(new Map),u=S.useRef(0),{stateRef:f}=s,{actBuffers:p,activeSessionBuffer:v,readConvMsgs:b,currentConvKeyRef:g,updateConvMsgs:O,updateConvMsgsRaf:m,appendConvActivity:x,beginStream:y,endStream:k,abortStream:C,clearStreamSession:P,setStreamSession:_,getStreamSession:T,setActiveSession:R,incrementSending:L,decrementSending:M,loadAndDisplay:E,sessionSwitchSeqRef:B,setSending:U,setActivities:F,setInput:X,setChatContext:ae,setPendingImages:j,setMentionDropdown:W,setChatReplyTo:D,setActiveSessionId:V,setStoredActiveSession:se,setOpenSessionTabs:fe,setSessions:z,setLoadingChat:re,setWindowBounds:Z,makeConvKey:A,makeDmChannel:J,addRecentMsgId:Y,resumeChatScrollFollow:oe,loadSessions:K}=s,{t:pe}=s,je=S.useCallback(async(Ee,ye)=>{const G=B.current,qe=g.current===ye&&(b(ye)?.length??0)===0;qe&&re(!0);try{const{count:He,hasMore:Ye,oldestCursor:pt}=await E(Ee,ye,async()=>{const xt=await te.sessions.getMessages(Ee,50);return{messages:aC(xt.messages.map(oh).filter(vt=>vt.sender!=="agent"||vt.text||vt.segments&&vt.segments.length>0||vt.isStreaming)),hasMore:xt.hasMore,oldestCursor:xt.messages[0]?new Date(xt.messages[0].createdAt).toISOString():null}});return Z(Ee,{hasMore:Ye,oldestCursor:pt}),He}finally{qe&&g.current===ye&&B.current===G&&re(!1)}},[E,b,B]),we=()=>{const Ee=f.current.chatMode==="direct"?f.current.selectedAgent:null;if(Ee){const ye=_f(f.current.activeSessionId,it);ye.kind==="cancel"&&te.agents.cancelProcessing(Ee,ye.target).catch(()=>{})}n(f.current.activeSessionId??it),Ee&&f.current.activeSessionId&&f.current.activeSessionId!==it&&l.current.add(f.current.activeSessionId),C(g.current,f.current.activeSessionId)},Ge=S.useCallback(async(Ee,ye,G)=>{if(!Ee||!ye||ye===it||l.current.has(ye))return;let qe=null;try{const He=e.current.get(ye);if(He&&!He.signal.aborted&&T(G)?.has(ye)){g.current===G&&U(!0);return}const Ye=()=>{lC({liveSessions:T(G),sessionId:ye,placeholderId:it})&&(P(G,ye),g.current===G&&(U(!1),O(G,de=>ou(de),ye)))},pt=`${Ee}:${ye}`,xt=o.current.get(pt)??0;if(Date.now()-xt<1500)return;o.current.set(pt,Date.now());let bt;const vt=await te.sessions.streamStatus(Ee,ye);vt.messageId&&(bt=vt.messageId);const Pe=b(G)??[],At=vt.status==="streaming",Ft=cC(Pe,{expectedMessageId:vt.messageId,allowCurrentTurnPartial:At}),Es=!!vt.active&&(vt.status==="done"||vt.status==="error")&&!!Ft?.isStreaming;if(KO({aborted:!1,sawTerminal:Es,serverStatus:JO(vt.status)})==="finalize"){Ye();return}o.current.set(pt,Date.now());for(const de of t.current.values())de.abort();t.current.clear(),qe=new AbortController,t.current.set(ye,qe),y(G),U(!0),_(G,ye);const yt=Ft&&!Ft.isError&&Ft.sender==="agent"?Pe.findIndex(de=>de.id===Ft.id):-1,Bt=yt>=0?Pe[yt]:void 0,ut=hC(vt);if(!Bt&&!ut){Ye();return}const Ze=Bt?Bt.id:ut;if(!Bt)O(G,de=>[...de,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],ye);else{const de=(Bt.segments??[]).filter(De=>De.type==="tool").map(De=>De.status==="stopped"||De.status==="running"?{...De,status:"running"}:De);O(G,De=>De.map(ve=>ve.id===Ze?{...ve,text:"",isStreaming:!0,isStopped:!1,segments:de,committedSegments:void 0}:ve),ye)}const Xt=de=>{g.current===G&&(u.current=Date.now(),m(G,De=>{const ve=[...De],st=Ze?ve.findIndex(ee=>ee.id===Ze):-1,ze=st>=0?st:ve.map((ee,Te)=>({m:ee,j:Te})).reverse().find(ee=>ee.m.sender==="agent"&&ee.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];return ve[ze]={...Ve,text:(Ve.text??"")+de,segments:SO(Ve.segments??[],de),isStreaming:!0},ve},ye))},ot=de=>{g.current===G&&(u.current=Date.now(),m(G,De=>{const ve=[...De],st=Ze?ve.findIndex(ee=>ee.id===Ze):-1,ze=st>=0?st:ve.map((ee,Te)=>({m:ee,j:Te})).reverse().find(ee=>ee.m.sender==="agent"&&ee.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];return ve[ze]={...Ve,segments:wO(Ve.segments??[],de),isStreaming:!0},ve},ye))},Mt=de=>{if(g.current===G&&(u.current=Date.now(),de.phase!=="heartbeat")){if((de.phase==="start"||de.phase==="end")&&x(G,{...de,phase:de.phase,ts:Date.now()},ye),de.phase==="start"){const De=`${de.tool}_${Date.now()}`,ve=new Date().toISOString(),st=ze=>{const Ve=[...ze];for(let ee=Ve.length-1;ee>=0;ee--){const Te=Ve[ee];if(Te.type==="tool"&&Te.tool===de.tool&&(Te.status==="running"||Te.status==="stopped"))return Ve[ee]={...Te,status:"running",args:de.arguments??Te.args},Ve}return Ve.push({type:"tool",key:De,tool:de.tool,status:"running",args:de.arguments,createdAt:ve}),Ve};O(G,ze=>{const Ve=[...ze],ee=Ze?Ve.findIndex(_e=>_e.id===Ze):-1;if(ee<0)return ze;const Te=st(Ve[ee].segments??[]),Se=Ve[ee].committedSegments,Oe=Se&&st(Se);return Ve[ee]={...Ve[ee],segments:Te,committedSegments:Oe,isStreaming:!0},Ve},ye)}else if(de.phase==="end"){const De=new Date().toISOString(),ve=st=>{const ze=[...st];for(let Ve=ze.length-1;Ve>=0;Ve--){const ee=ze[Ve];if(ee.type==="tool"&&ee.tool===de.tool&&(ee.status==="running"||ee.status==="stopped")){ze[Ve]={...ee,status:de.success===!1?"error":"done",args:de.arguments??ee.args,result:de.result,error:de.error,durationMs:de.durationMs,liveOutput:void 0,createdAt:De};break}}return ze};O(G,st=>{const ze=[...st],Ve=Ze?ze.findIndex(Oe=>Oe.id===Ze):-1;if(Ve<0)return st;const ee=ve(ze[Ve].segments??[]),Te=ze[Ve].committedSegments,Se=Te&&ve(Te);return ze[Ve]={...ze[Ve],segments:ee,committedSegments:Se,isStreaming:!0},ze},ye)}else if(de.phase==="subagent_progress"&&de.subagentEvent){const De=ve=>{const st=[...ve];for(let ze=st.length-1;ze>=0;ze--){const Ve=st[ze];if(Ve.type==="tool"&&(Ve.tool==="spawn_subagent"||Ve.tool==="spawn_subagents")&&(Ve.status==="running"||Ve.status==="stopped")){st[ze]={...Ve,status:"running",subagentLogs:_O(Ve.subagentLogs,de.subagentEvent)};break}}return st};m(G,ve=>{const st=[...ve],ze=Ze?st.findIndex(Se=>Se.id===Ze):-1;if(ze<0)return ve;const Ve=De(st[ze].segments??[]),ee=st[ze].committedSegments,Te=ee&&De(ee);return st[ze]={...st[ze],segments:Ve,committedSegments:Te,isStreaming:!0},st},ye)}}},us=de=>{g.current===G&&(u.current=Date.now(),O(G,De=>{const ve=[...De],st=Ze?ve.findIndex(Ve=>Ve.id===Ze):-1;if(st<0)return De;const ze=[...ve[st].committedSegments??[]];if(de.type==="thinking_commit")ze.push({type:"text",content:"",thinking:de.content,createdAt:de.createdAt});else if(de.type==="text_commit")ze.push({type:"text",content:de.content,createdAt:de.createdAt});else return De;return ve[st]={...ve[st],committedSegments:ze,isStreaming:!0},ve},ye))},he=de=>{if(g.current!==G)return;u.current=Date.now();const De=(de.segments??[]).map((ve,st)=>ve.type==="tool"?{type:"tool",key:`${ve.tool}_${st}`,tool:ve.tool??"tool",status:ve.status==="error"?"error":ve.status==="running"||ve.status==="stopped"?"running":"done",args:ve.arguments,result:ve.result,error:ve.error,durationMs:ve.durationMs,createdAt:ve.createdAt,...ve.subagentLogs?.length?{subagentLogs:ve.subagentLogs}:{}}:{type:"text",content:ve.content??"",thinking:ve.thinking,createdAt:ve.createdAt});O(G,ve=>{const st=[...ve],ze=Ze?st.findIndex(Ve=>Ve.id===Ze):-1;return ze<0?ve:(st[ze]={...st[ze],text:de.content||st[ze].text,segments:De,committedSegments:De,isStreaming:!0,isStopped:!1},st)},ye);for(const ve of De)ve.type==="tool"&&x(G,{tool:ve.tool,phase:ve.status==="running"||ve.status==="stopped"?"start":"end",success:ve.status!=="error",arguments:ve.args,result:ve.result,error:ve.error,durationMs:ve.durationMs,ts:Date.now()},ye)},ce=8;let $e=null;const Xe=de=>{g.current===G&&O(G,De=>{const ve=De.map((ze,Ve)=>({m:ze,j:Ve})).reverse().find(ze=>ze.m.sender==="agent"&&ze.m.isStreaming)?.j??-1;if(ve<0||De[ve].reconnecting===de)return De;const st=[...De];return st[ve]={...st[ve],reconnecting:de},st},ye)};for(let de=1;de<=ce;de++){if(qe.signal.aborted)return;try{$e=await te.sessions.reattachStream(Ee,ye,{onChunk:Xt,onThinking:ot,onActivity:Mt,onCommit:us,onSnapshot:he},qe.signal,0)}catch(ve){if(qe.signal.aborted)throw ve;$e=null}if(!$e||!$e.attached){$e=null;break}if($e.terminal)break;Xe(!0);const De=await te.sessions.streamStatus(Ee,ye).catch(()=>null);if(De?.messageId&&(bt=De.messageId),!De||!De.active||De.status==="not_found"||De.status==="idle"){Xe(!1),$e=null;break}await new Promise(ve=>setTimeout(ve,Math.min(800*de,4e3))),Xe(!1)}if(!$e){k(G),P(G,ye),g.current===G&&(U(!1),bt&&Ze&&O(G,de=>wa(de,Ze,bt),ye),je(ye,G).catch(()=>{}).finally(()=>{O(G,de=>ou(de,"done"),ye)})),i(qe);return}if(g.current===G){let de;O(G,De=>{const ve=[...De],st=Ze?ve.findIndex(Te=>Te.id===Ze):-1,ze=st>=0?st:ve.map((Te,Se)=>({m:Te,j:Se})).reverse().find(Te=>Te.m.sender==="agent"&&Te.m.isStreaming)?.j??-1;if(ze<0)return De;const Ve=ve[ze];if(!Ve.isStreaming)return De;de=Ve.id;const ee=$e.segments?.length?kO($e.segments,Ve.segments):void 0;return ve[ze]={...Ve,text:$e.content||Ve.text,isStreaming:!1,isStopped:!1,reconnecting:!1,...ee?{segments:ee,committedSegments:ee}:{}},ve},ye),de&&O(G,De=>wa(De,de,$e.messageId),ye),U(!1)}k(G),P(G,ye),i(qe)}catch(He){const Ye=qe?[...t.current.values()].includes(qe):!1;i(qe),k(G);const pt=l.current.has(ye);if(pt&&P(G,ye),g.current===G&&(U(!1),Ye&&pt&&O(G,xt=>ou(xt),ye)),He instanceof Error&&He.name==="AbortError")return}},[x,y,k,T,b,_,O,m]),Qe=S.useCallback(async(Ee,ye)=>{const G=f.current,qe=!Ee&&G.chatContext.length>0?G.chatContext.map(rt=>rt.content).join(`
|
|
76
76
|
|
|
77
77
|
`)+`
|
|
78
78
|
|
|
79
|
-
`:"",He=(Ee??qe+G.input).trim(),Ye=(Ee??G.input).trim();if(!He&&G.pendingImages.length===0||G.chatMode==="direct"&&!G.selectedAgent)return;oe();const pt=Date.now(),xt=h.current;if(!ye?.isRetry&&!ye?.isResume&&He&&xt&&xt.text===He&&pt-xt.at<1500)return;if(h.current={text:He,at:pt},ye?.isResume){const rt=ye.sessionIdOverride??G.activeSessionId??"";if(pt-(d.current.get(rt)??0)<2e3)return;d.current.set(rt,pt)}if(G.sending&&G.chatMode==="direct"){if(dC({liveSessions:T(g.current),sendSessionId:G.activeSessionId})){const yt=g.current;if([...b(yt)??[]].reverse().find(Xt=>Xt.sender==="user")?.text===He&&!ye?.isRetry&&!ye?.isResume){n(G.activeSessionId??it);const Xt=_f(G.activeSessionId,it);return Xt.kind==="cancel"&&te.agents.cancelProcessing(G.selectedAgent,Xt.target).catch(()=>{}),C(yt,G.activeSessionId),O(yt,ot=>{const At=[...ot];return At.length>0&&At[At.length-1].sender==="agent"&&At.pop(),At.length>0&&At[At.length-1].sender==="user"&&At[At.length-1].text===He&&At.pop(),At}),await new Promise(ot=>setTimeout(ot,50)),Qe(He,{isRetry:!0})}n(G.activeSessionId??it);const Ze=_f(G.activeSessionId,it);Ze.kind==="cancel"&&te.agents.cancelProcessing(G.selectedAgent,Ze.target).catch(()=>{}),C(yt,G.activeSessionId),O(yt,Xt=>CO(Xt)),await new Promise(Xt=>setTimeout(Xt,50))}}else if(G.sending&&G.chatMode!=="direct"){n(f.current.activeSessionId??g.current);const rt=g.current;C(rt),O(rt,yt=>CO(yt)),await new Promise(yt=>setTimeout(yt,50))}const bt=G.pendingImages.length>0?G.pendingImages.map(rt=>rt.dataUrl):void 0,vt=G.pendingImages.length>0?G.pendingImages.map(rt=>rt.name):void 0,Pe=A(G.chatMode,G.selectedAgent??"",G.activeChannel??"",G.activeDmUserId),Et=G.chatReplyTo;Ee||(X(""),ae([])),j([]),W(!1),D(null);const Ft=G.chatMode==="dm";L(Pe);const Es=G.activeSessionId??Pe;if(p.set(Es,[]),g.current===Pe&&!Ft&&(U(!0),F([])),G.chatMode==="dm"){const rt=J(G.authUser?.id??"",G.activeDmUserId),yt=`opt_${Date.now()}`,Bt={id:yt,sender:"user",text:He,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};bt?.length&&(Bt.images=bt),Et&&(Bt.replyToId=Et.id,Bt.replyToSender=Et.sender,Bt.replyToText=Et.text),O(Pe,ut=>[...ut,Bt]);try{const ut=await te.channels.sendMessage(rt,{text:He,senderName:G.authUser?.name??pe("page.fallbackYou"),senderId:G.authUser?.id,mentions:[],orgId:"default",humanOnly:!0,...bt?.length?{images:bt}:{},...vt?.length?{fileNames:vt}:{}});ut.userMessage&&Y(ut.userMessage.id),O(Pe,Ze=>{const Xt=Ze.filter(At=>At.id!==yt),ot=[];return ut.userMessage&&ot.push(Mn(ut.userMessage,G.authUser?.id)),ot.length>0?[...Xt,...ot]:Ze})}catch(ut){Ic(ut)&&Bc(),O(Pe,Ze=>[...Ze.filter(ot=>ot.id!==yt),{id:`err_${Date.now()}`,sender:"agent",text:pe("page.errorWithMessage",{message:String(ut)}),time:new Date().toLocaleTimeString(),agentName:pe("page.systemName"),isError:!0}])}M(Pe),g.current===Pe&&U(!1)}else if(G.chatMode==="channel"){const rt=`opt_${Date.now()}`,yt={id:rt,sender:"user",text:He,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};Et&&(yt.replyToId=Et.id,yt.replyToSender=Et.sender,yt.replyToText=Et.text),O(Pe,ut=>[...ut,yt]);const Bt=XC(He);G.groupChats.find(ut=>ut.channelKey===G.activeChannel);try{const ut=await te.channels.sendMessage(G.activeChannel,{text:He,senderName:G.authUser?.name??pe("page.fallbackYou"),mentions:Bt,senderId:G.authUser?.id,orgId:"default",replyToId:Et?.id,...bt?.length?{images:bt}:{},...vt?.length?{fileNames:vt}:{}});ut.userMessage&&Y(ut.userMessage.id),ut.agentMessage&&Y(ut.agentMessage.id),O(Pe,Ze=>{const Xt=Ze.filter(At=>At.id!==rt),ot=[];return ut.userMessage&&ot.push(Mn(ut.userMessage,G.authUser?.id)),ut.agentMessage&&ot.push(Mn(ut.agentMessage,G.authUser?.id)),ot.length>0?[...Xt,...ot]:Ze})}catch(ut){Ic(ut)&&Bc();const Ze=nh(ut,pe)||pe("page.errorWithMessage",{message:String(ut)});O(Pe,Xt=>[...Xt,{id:`err_${Date.now()}`,sender:"agent",text:Ze,time:new Date().toLocaleTimeString(),agentName:pe("page.systemName"),isError:!0}])}M(Pe),g.current===Pe&&U(!1)}else{y(Pe);const rt=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,yt=ye?.isResume?b(Pe)??[]:[],Bt=ye?.isResume?uC(yt):-1,ut=Bt>=0?yt[Bt].id:void 0,Ze=ut??`a_${rt}`,Xt=`u_${rt}`;let ot=ye?.sessionIdOverride??(G.activeSessionId===it?null:G.activeSessionId??null);if(ye?.isResume){const ee=new Date().toISOString();O(Pe,Te=>{if(ut){const Se=Te.findIndex(Oe=>Oe.id===ut);if(Se>=0)return Te.map((Oe,_e)=>_e===Se?{...Oe,isStreaming:!0,isStopped:!1,isError:!1}:Oe)}return[...Te,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:ee,segments:[],isStreaming:!0}]},ot)}else{const ee=new Date().toISOString(),Te={id:Xt,sender:"user",text:He,time:new Date().toLocaleTimeString(),rawCreatedAt:ee};bt?.length&&(Te.images=bt),Et&&(Te.replyToId=Et.id,Te.replyToSender=Et.sender,Te.replyToText=Et.text),O(Pe,Se=>[...Se,Te,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:ee,segments:[],isStreaming:!0}],ot)}const At=ee=>{u.current=Date.now(),m(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(Fe=>Fe.id===Ze);if(Oe<0)return Te;const _e=Se[Oe];return Se[Oe]={..._e,text:(_e.text??"")+ee,segments:SO(_e.segments??[],ee)},Se},ot)},us=ee=>{u.current=Date.now(),m(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(Fe=>Fe.id===Ze);if(Oe<0)return Te;const _e=Se[Oe];return Se[Oe]={..._e,segments:wO(_e.segments??[],ee)},Se},ot)},he=ee=>{if(u.current=Date.now(),ee.type==="session_start"&&ee.sessionId){const Te=ot;if(ot=ee.sessionId,l.current.delete(ee.sessionId),Te&&Te!==ee.sessionId&&(P(Pe,Te),G.selectedAgent&&Te===it&&(hs.applyLocalOptimistic(G.selectedAgent,Te,!1),hs.applyLocalOptimistic(G.selectedAgent,ee.sessionId,!0))),_(Pe,ee.sessionId),ee.userMessageId&&!ye?.isResume&&O(Pe,Se=>Se.map(Oe=>Oe.id===Xt?{...Oe,id:ee.userMessageId}:Oe),ee.sessionId),g.current===Pe){const Se=G.activeSessionId;(!Se||Se===it||Se===ee.sessionId)&&(V(ee.sessionId),R(Pe,ee.sessionId),a(ee.sessionId),G.selectedAgent&&se(G.selectedAgent,ee.sessionId),fe(Oe=>Oe.some(_e=>_e.id===it)?Oe.map(_e=>_e.id===it?{..._e,id:ee.sessionId}:_e):Oe.some(_e=>_e.id===ee.sessionId)?Oe:[...Oe,{id:ee.sessionId,agentId:G.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}O(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(Fe=>Fe.id===Ze);if(Oe<0)return Te;const _e=[...Se[Oe].committedSegments??[]];return ee.type==="thinking_commit"?_e.push({type:"text",content:"",thinking:ee.content,createdAt:ee.createdAt}):_e.push({type:"text",content:ee.content,createdAt:ee.createdAt}),Se[Oe]={...Se[Oe],committedSegments:_e},Se},ot)},ce=ee=>{u.current=Date.now(),ee.phase!=="heartbeat"&&((ee.phase==="start"||ee.phase==="end")&&x(Pe,{...ee,phase:ee.phase,ts:Date.now()},ot),ee.phase==="start"?O(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(dt=>dt.id===Ze);if(Oe<0)return Te;const _e=[...Se[Oe].segments??[]];let Fe=!1;if(ee.arguments)for(let dt=_e.length-1;dt>=0;dt--){const Qt=_e[dt];if(Qt.type==="tool"&&Qt.tool===ee.tool&&Qt.status==="running"){_e[dt]={...Qt,args:ee.arguments},Fe=!0;break}}const at=`${ee.tool}_${Date.now()}`,wt=new Date().toISOString();Fe||_e.push({type:"tool",key:at,tool:ee.tool,status:"running",args:ee.arguments,createdAt:wt});const ht=[...Se[Oe].committedSegments??[]];return ee.arguments!==void 0&&ht.push({type:"tool",key:at,tool:ee.tool,status:"running",args:ee.arguments,createdAt:wt}),Se[Oe]={...Se[Oe],segments:_e,committedSegments:ht},Se},ot):ee.phase==="output"?m(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(Fe=>Fe.id===Ze);if(Oe<0)return Te;const _e=[...Se[Oe].segments??[]];for(let Fe=_e.length-1;Fe>=0;Fe--){const at=_e[Fe];if(at.type==="tool"&&at.tool===ee.tool&&at.status==="running"){_e[Fe]={...at,liveOutput:pC(at.liveOutput,ee.output??"")};break}}return Se[Oe]={...Se[Oe],segments:_e},Se},ot):ee.phase==="subagent_progress"&&ee.subagentEvent?m(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(wt=>wt.id===Ze);if(Oe<0)return Te;const _e=wt=>{const ht=[...wt];for(let dt=ht.length-1;dt>=0;dt--){const Qt=ht[dt];if(Qt.type==="tool"&&(Qt.tool==="spawn_subagent"||Qt.tool==="spawn_subagents")&&Qt.status==="running"){ht[dt]={...Qt,subagentLogs:_O(Qt.subagentLogs,ee.subagentEvent)};break}}return ht},Fe=_e(Se[Oe].segments??[]),at=_e(Se[Oe].committedSegments??[]);return Se[Oe]={...Se[Oe],segments:Fe,committedSegments:at},Se},ot):O(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(ht=>ht.id===Ze);if(Oe<0)return Te;const _e=new Date().toISOString(),Fe=[...Se[Oe].segments??[]];let at;for(let ht=Fe.length-1;ht>=0;ht--){const dt=Fe[ht];if(dt.type==="tool"&&dt.tool===ee.tool&&dt.status==="running"){at=dt.subagentLogs,Fe[ht]={...dt,status:ee.success===!1?"error":"done",args:ee.arguments,result:ee.result,error:ee.error,durationMs:ee.durationMs,liveOutput:void 0,createdAt:_e};break}}const wt=[...Se[Oe].committedSegments??[]];for(let ht=wt.length-1;ht>=0;ht--){const dt=wt[ht];if(dt.type==="tool"&&dt.tool===ee.tool&&dt.status==="running"){wt[ht]={...dt,status:ee.success===!1?"error":"done",args:ee.arguments,result:ee.result,error:ee.error,durationMs:ee.durationMs,liveOutput:void 0,createdAt:_e,subagentLogs:at??dt.subagentLogs};break}}return Se[Oe]={...Se[Oe],segments:Fe,committedSegments:wt},Se},ot))},$e=new AbortController;e.current.set(f.current.activeSessionId??it,$e);const Xe=ot,de=Xe;de&&l.current.delete(de),de&&_(Pe,de),G.selectedAgent&&hs.applyLocalOptimistic(G.selectedAgent,de??it,!0);try{u.current=Date.now();const ee=await te.agents.messageStream(G.selectedAgent,He,{onChunk:At,onThinking:us,onActivity:ce,onCommit:he},{signal:$e.signal,images:bt,sessionId:Xe,isRetry:ye?.isRetry,isResume:ye?.isResume,fileNames:vt,replyTo:Et,titleSource:Ye});if(g.current===Pe){if(ee.merged&&O(Pe,Se=>Se.filter(Oe=>Oe.id!==Ze&&Oe.id!==Xt),ot),!ee.merged&&ee.segments?.length&&O(Pe,Se=>{const Oe=[...Se],_e=Oe.findIndex(ht=>ht.id===Ze);if(_e<0)return Se;const Fe=kO(ee.segments,Oe[_e].segments);let at=ee.content||Oe[_e].text;at||(at=Fe.filter(ht=>ht.type==="text").map(ht=>ht.content).join(""));const wt=ee.emptyReply===!0;return Oe[_e]={...Oe[_e],text:at,segments:Fe,committedSegments:Fe,isStopped:ee.cancelled||Oe[_e].isStopped,emptyReply:ee.emptyReply||wt||void 0,isError:ee.emptyReply||wt?!0:Oe[_e].isError},Oe},ot),!ee.merged&&!ee.segments?.length&&O(Pe,Se=>{const Oe=[...Se],_e=Oe.findIndex(Qt=>Qt.id===Ze);if(_e<0)return Se;const Fe=Oe[_e],at=Fe.committedSegments??[],ht=at.filter(Qt=>Qt.type==="text"&&!!Qt.content).map(Qt=>Qt.content).join("")||ee.content||Fe.text,dt=ee.emptyReply===!0;return(at.length>0||ht||ee.cancelled||ee.emptyReply||dt)&&(Oe[_e]={...Fe,text:ht,segments:at.length>0?at:Fe.segments,isStopped:ee.cancelled||Fe.isStopped,emptyReply:ee.emptyReply||dt||void 0,isError:ee.emptyReply||dt?!0:Fe.isError}),Oe},ot),ee.sessionId){V(Oe=>!Oe||Oe===it||Oe===ee.sessionId?ee.sessionId:Oe);const Se=v.get(Pe);(!Se||Se===it||Se===ee.sessionId)&&(R(Pe,ee.sessionId),a(ee.sessionId)),fe(Oe=>Oe.some(_e=>_e.id===it)?Oe.map(_e=>_e.id===it?{..._e,id:ee.sessionId}:_e):Oe.some(_e=>_e.id===ee.sessionId)?Oe:[...Oe,{id:ee.sessionId,agentId:G.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])}K(G.selectedAgent).then(Se=>{if(g.current===Pe&&(z(Se),ee.sessionId)){const Oe=Se.find(_e=>_e.id===ee.sessionId);Oe&&fe(_e=>_e.some(at=>at.id===Oe.id)?_e.map(at=>at.id===Oe.id?Oe:at):[Oe,..._e.filter(at=>at.id!==it)])}});const Te=ee.sessionId??(de&&de!==it?de:null);if(!$e.signal.aborted&&!ee.merged&&(ee.softDisconnected??ee.segments===void 0)&&G.chatMode==="direct"&&G.selectedAgent&&Te){const Se=G.selectedAgent;let Oe=!1,_e;for(let Fe=0;Fe<4&&!Oe&&(Fe>0&&await new Promise(at=>setTimeout(at,350*Fe)),!$e.signal.aborted);Fe+=1)try{const at=await te.sessions.streamStatus(Se,Te);if(at.messageId&&(_e=at.messageId),KO({aborted:$e.signal.aborted,sawTerminal:!1,serverStatus:JO(at.status)})==="reattach"){O(Pe,ht=>ht.map(dt=>dt.id===Ze?{...dt,isStreaming:!0,isStopped:!1,segments:(dt.segments??[]).map(Qt=>Qt.type==="tool"&&(Qt.status==="stopped"||Qt.status==="running")?{...Qt,status:"running"}:Qt)}:dt),Te),M(Pe),r($e),_(Pe,Te),k(Pe),Ge(Se,Te,Pe),Oe=!0;return}break}catch{}if(!Oe&&!$e.signal.aborted){_e&&Ze&&O(Pe,Fe=>wa(Fe,Ze,_e),Te);try{if(await je(Te,Pe)>0){M(Pe),r($e),k(Pe);return}}catch{}}}}!ee.merged&&(ot||g.current===Pe)&&O(Pe,Te=>wa(Te,Ze,ee.messageId),ot)}catch(ee){const Te=ee?.sessionId;Te&&G.chatMode==="direct"&&g.current===Pe&&(V(Te),R(Pe,Te),a(Te),fe(Oe=>Oe.map(_e=>_e.id===it?{..._e,id:Te}:_e)),K(G.selectedAgent).then(Oe=>{if(g.current!==Pe)return;z(Oe);const _e=Oe.find(Fe=>Fe.id===Te);_e&&fe(Fe=>Fe.some(wt=>wt.id===_e.id)?Fe.map(wt=>wt.id===_e.id?_e:wt):[_e,...Fe])})),Ic(ee)&&Bc();const Se=nh(ee,pe);Se?O(Pe,Oe=>{const _e=[...Oe],Fe=_e.findIndex(at=>at.id===Ze);return Fe>=0&&(_e[Fe]={..._e[Fe],text:Se,isError:!0}),_e},ot):O(Pe,Oe=>{const _e=[...Oe],Fe=_e.findIndex(at=>at.id===Ze);if(Fe>=0){const at=PO(_e[Fe],"stopped");if(at===null)return Oe.filter(wt=>wt.id!==Ze);_e[Fe]=at}return _e},ot)}O(Pe,ee=>fC(ee,Ze),ot),$e.signal.aborted&&O(Pe,ee=>{const Te=[...ee],Se=Te.findIndex(Oe=>Oe.id===Ze);if(Se>=0){const Oe=PO(Te[Se],"stopped");if(Oe===null)return ee.filter(_e=>_e.id!==Ze);Te[Se]=Oe}return Te},ot);const ve=(b(Pe)??[]).find(ee=>ee.id===Ze),st=G.activeSessionId&&G.activeSessionId!==it?G.activeSessionId:null,ze=ve?mC(ve):!1;ve&&!ze&&G.chatMode==="direct"&&st&&!$e.signal.aborted&&await(async(Te,Se)=>{for(let Oe=0;Oe<Te;Oe++){const _e=gC(Oe,{baseMs:Se,maxMs:8e3,maxAttempts:Te});await new Promise(Fe=>setTimeout(Fe,_e));try{const at=(await te.sessions.getMessages(st,2)).messages.find(wt=>wt.role==="assistant");if(at?.content){const wt=oh(at);O(Pe,ht=>{const dt=[...ht],Qt=dt.findIndex(hi=>hi.id===Ze);return Qt>=0&&(dt[Qt]={...dt[Qt],text:wt.text,segments:wt.segments}),dt},ot),O(Pe,ht=>wa(ht,Ze,wt.id),ot);return}}catch{}}})(5,2e3);const Ve=M(Pe);P(Pe,ot??it),G.selectedAgent&&hs.applyLocalOptimistic(G.selectedAgent,ot??it,!1),k(Pe),[...e.current.values()].includes($e)||e.current.size===0?(r($e),p.delete(ot??Pe),g.current===Pe&&(U(Ve>0),Ve===0&&F([]))):p.delete(ot??Pe)}},[x,y,P,g,M,k,L,K,b,U,_,f,O,m]);return{send:Qe,stopSending:we,tryReattachActiveStream:Ge,loadSessionMessages:je}}function jI({value:s,onSelect:e,agentId:t,disabled:r}){const{t:i}=Pt("team"),[n,a]=S.useState(!1),[o,l]=S.useState("agent"),[h,d]=S.useState(""),[u,f]=S.useState(!1),[p,v]=S.useState([]),[b,g]=S.useState(null),O=S.useRef(null),m=S.useCallback(async()=>{f(!0);try{const _=await fetch("/api/settings/llm",{credentials:"include"});if(!_.ok)throw new Error(`HTTP ${_.status}`);const T=await _.json(),R=T.providers?.markus;if(R?.configured&&R.enabled!==!1&&(!R.models||R.models.length===0))try{const B=await fetch("/api/models/live/markus",{credentials:"include"});if(B.ok){const U=await B.json();U.models?.length&&(R.models=U.models)}}catch{}const L=[];for(const[B,U]of Object.entries(T.providers??{})){if(!U.configured||U.enabled===!1)continue;const F=(U.models??[]).filter(FC).map(X=>({id:X.id,name:X.name}));F.length!==0&&L.push({provider:B,displayName:U.displayName??B,models:F})}L.sort((B,U)=>B.displayName.localeCompare(U.displayName)),v(L);const M=B=>!B?.provider||!B.model?!1:!!L.find(F=>F.provider===B.provider)?.models.some(F=>F.id===B.model);let E=null;if(T.routingDefaultModel?.provider&&T.routingDefaultModel?.model)E={provider:T.routingDefaultModel.provider,model:T.routingDefaultModel.model};else if(T.defaultProvider){const B=T.providers?.[T.defaultProvider];B?.model&&(E={provider:T.defaultProvider,model:B.model})}if(E&&!M(E)){const B=L.find(F=>F.provider==="markus"),U=B?.models[0]?{provider:"markus",model:B.models[0].id}:L[0]?.models[0]?{provider:L[0].provider,model:L[0].models[0].id}:null;U?(E=U,te.settings.updateRouting({defaultProvider:U.provider,routingDefaultModel:U}).catch(()=>{})):E=null}g(E)}catch{v([])}finally{f(!1)}},[]);S.useEffect(()=>{m()},[m]),S.useEffect(()=>{n&&(l("agent"),d(""),m())},[n,m]),S.useEffect(()=>{if(!n)return;const _=T=>{O.current?.contains(T.target)||a(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[n]);const x=S.useMemo(()=>{const _=h.trim().toLowerCase();return p.map(T=>({...T,models:_?T.models.filter(R=>R.id.toLowerCase().includes(_)||(R.name?.toLowerCase().includes(_)??!1)||T.displayName.toLowerCase().includes(_)||T.provider.toLowerCase().includes(_)):T.models})).filter(T=>T.models.length>0)},[p,h]),y=S.useCallback(_=>!_?.provider||!_.model?!1:p.length===0?!0:!!p.find(R=>R.provider===_.provider)?.models.some(R=>R.id===_.model),[p]);S.useEffect(()=>{if(!s||p.length===0||y(s))return;const _=b&&y(b)?b:(()=>{const T=p.find(R=>R.provider==="markus");return T?.models[0]?{provider:"markus",model:T.models[0].id}:p[0]?.models[0]?{provider:p[0].provider,model:p[0].models[0].id}:null})();_&&e(_,"global",{resetCurrentAgent:!0})},[s,p,b,y,e]);const k=s&&y(s)?s:b,P=(k?.model?k.model.includes("/")?k.model.split("/").pop():k.model:"")||i("chatModel.title",{defaultValue:"Model"});return c.jsxs("div",{ref:O,className:"relative shrink-0",children:[c.jsxs("button",{type:"button",disabled:r,onClick:()=>a(_=>!_),className:"max-w-[110px] md:max-w-[180px] px-1.5 py-1 text-[12px] text-fg-secondary hover:text-fg-primary disabled:opacity-40 rounded-md hover:bg-surface-elevated transition-colors flex items-center gap-1",title:k?`${k.provider}: ${k.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[c.jsx("span",{className:"truncate",children:P}),c.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n&&c.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-[300px] max-h-[360px] flex flex-col rounded-xl border border-border-default bg-surface-elevated shadow-xl z-50 overflow-hidden",children:[c.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[c.jsx("input",{autoFocus:!0,value:h,onChange:_=>d(_.target.value),placeholder:i("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-primary border border-border-default/50 outline-none focus:border-brand-500/50"}),c.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[c.jsx("span",{children:i("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),c.jsx(NO,{checked:o==="global",onChange:()=>l("global"),label:i("chatModel.applyGlobal",{defaultValue:"Apply to global"}),size:"sm",disabled:!t})]}),c.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[c.jsx("span",{children:i("chatModel.applyAgent",{defaultValue:"Apply to current agent"})}),c.jsx(NO,{checked:o==="agent",onChange:()=>l("agent"),label:i("chatModel.applyAgent",{defaultValue:"Apply to current agent"}),size:"sm",disabled:!t})]}),!t&&c.jsx("div",{className:"px-0.5 text-[10px] text-fg-tertiary",children:i("chatModel.noAgent",{defaultValue:"Select an agent to apply per-agent"})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[u&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!u&&x.length===0&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!u&&x.length>0&&c.jsx("div",{className:"px-3 pb-1 text-[10px] text-fg-tertiary",children:i("chatModel.chatOnlyHint",{defaultValue:"Only models with a chat interface are listed"})}),!u&&x.map(_=>c.jsxs("div",{className:"mb-1",children:[c.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:_.displayName}),_.models.slice(0,80).map(T=>{const R=k?.provider===_.provider&&k?.model===T.id;return c.jsxs("button",{type:"button",onClick:()=>{e({provider:_.provider,model:T.id},o),o==="global"&&g({provider:_.provider,model:T.id}),a(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-primary transition-colors ${R?"text-fg-primary":"text-fg-secondary"}`,children:[c.jsx("span",{className:"truncate flex-1",children:T.id}),R&&c.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:c.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${_.provider}:${T.id}`)})]},_.provider))]})]})]})}async function Lv(s,e,t,r){if(e==="agent"){if(!t)return;await te.agents.updateConfig(t,{llmConfig:{modelMode:"custom",primary:s.provider,defaultModel:s.model}});return}t&&r?.resetCurrentAgent!==!1&&await te.agents.updateConfig(t,{llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}).catch(()=>{}),await te.settings.updateRouting({defaultProvider:s.provider,routingDefaultModel:{provider:s.provider,model:s.model}})}const Nv="markus_team_sidebars_c";function Im(s,e){return s.id===it?e("page.newChat"):s.isMain?e("page.sessionMain"):s.title?.trim()||e("page.sessionConversation")}function Dv(s,e){const t=s.title?.trim(),r=!!t;return s.isMain?r?`${e("page.sessionMain")} · ${t}`:e("page.sessionMain"):Im(s,e)}const Bm=new Set;function RI(){return window.location.hash}function EI(s){return Bm.add(s),()=>{Bm.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>Bm.forEach(s=>s()));function KI({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=Pt(["team","common"]),a=S.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=Zm(Yt.TEAM),[l,h]=S.useState(r?.agents??[]),[d,u]=S.useState(r?.humans??[]),[f,p]=S.useState(!r),v=qm(),b=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC"),g=S.useSyncExternalStore(EI,RI),O=v&&(g.startsWith(`#${Yt.TEAM}/`)||g.startsWith("#chat/")),m=v&&g.match(/^#team\/t\/(.+)$/),x=v?m?"team":O?"chat":"roster":"roster",y=m?m[1]:null;S.useEffect(()=>(TO(v&&x==="chat"),()=>TO(!1)),[v,x]),S.useEffect(()=>(QO(Yt.TEAM,v&&x!=="roster"?1:0),()=>QO(Yt.TEAM,0)),[v,x]);const k=S.useCallback(()=>{window.location.hash=`${Yt.TEAM}/d`},[]),C=S.useCallback(w=>{window.location.hash=`${Yt.TEAM}/t/${w}`},[]);S.useEffect(()=>{if(!v)return;const w=()=>{qi(T.current)&&_("chat")};return window.addEventListener("popstate",w),()=>window.removeEventListener("popstate",w)},[v]);const[P,_]=S.useState("chat"),T=S.useRef("chat");T.current=P;const R=$O({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[L,M]=S.useState(()=>{try{return localStorage.getItem(Nv)==="1"}catch{return!1}}),E=S.useCallback(w=>{M(w);try{localStorage.setItem(Nv,w?"1":"0")}catch{}},[]),B=zh(),U=B?.leftCollapsed??!1,F=B?.rightPanel??null,X=B?.rightPanelTabs??[],ae=B?.activeRightPanelTabId??null,j=B?.rightPanelFullscreen??!1,W=F?"2xl:pr-8":"2xl:pr-[280px]",D=B?.setHostAvailable,V=B?.collapseRightPanelOnly??B?.toggleRightPanel,se=B?.openRightPanel,fe=400,z=320,re=6,[Z,A]=S.useState(typeof window<"u"?window.innerWidth:1440),[J,Y]=S.useState("auto"),oe=S.useRef(U);S.useEffect(()=>{oe.current!==U&&(oe.current=U,M(U))},[U]);const K=B?.keyboardPane??"content",pe=S.useRef(!1),je=S.useRef(K);S.useEffect(()=>{if(t||v||!o)return;const w=je.current;je.current=K,(K==="l1"||K==="l2")&&w!==K&&L&&(M(!1),B?.setLeftCollapsed(!1))},[K,t,v,o,L,B]),S.useEffect(()=>{if(t||v||!o)return;const w=Q=>{const $=B?.keyboardPane??"content";if($==="l0"||$==="l1"||$==="l2"||Q.metaKey||Q.ctrlKey||Q.altKey)return;if(Q.target instanceof HTMLElement){const H=Q.target.tagName;if(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||Q.target.isContentEditable||Q.target.closest(".xterm"))return}const I=Q.key.length===1?Q.key.toLowerCase():Q.key;I!=="h"&&I!=="ArrowLeft"||(Q.preventDefault(),L&&(E(!1),B?.setLeftCollapsed(!1)),B?.setKeyboardPane(pe.current?"l2":"l1"))};return document.addEventListener("keydown",w,!0),()=>document.removeEventListener("keydown",w,!0)},[t,v,o,B,L,E]),S.useEffect(()=>{if(D)return D(o&&!v),()=>D(!1)},[o,v,D]),S.useEffect(()=>t||v||!o?void 0:St.on("ui:right_panel",Q=>{const $=Q.payload;if($.action==="collapse"){V?.();return}if($.action!=="open"||!$.panel||!se)return;const I=$.panel;if(I.kind==="url"&&I.url){const H=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"url",url:I.url,title:I.title||I.url,browserId:H});return}if(I.kind==="file"&&I.path){se({kind:"file",path:I.path,title:I.title});return}if(I.kind==="terminal"){const H=I.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"terminal",terminalId:H,title:I.title||"Terminal",cwd:I.cwd});return}I.kind==="deliverable"&&I.deliverableId&&te.deliverables.get(I.deliverableId).then(H=>{H.deliverable&&se({kind:"deliverable",deliverable:H.deliverable})}).catch(()=>{})}),[t,v,o,V,se]);const we=S.useCallback(w=>{const Q=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;dn($=>[...$,{id:Q,...w}]),requestAnimationFrame(()=>Hs.current?.focus())},[]),Ge=S.useCallback(w=>{if(w)try{const Q=JSON.parse(w);if(!Array.isArray(Q)||Q.length===0)return;const $=Q.filter(H=>!!H&&typeof H.content=="string"&&H.content.trim().length>0);if($.length===0)return;const I=$.map(H=>({id:`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,label:H.label?.trim()||"Context",content:H.content}));dn(H=>[...H,...I]),requestAnimationFrame(()=>{const H=Hs.current;H&&(H.focus(),H.setSelectionRange(H.value.length,H.value.length))})}catch{}},[]),[Qe,Ee]=S.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),ye=$O({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),G=S.useRef(null),[qe,He]=S.useState(!1),[Ye,pt]=S.useState(!1),xt=S.useCallback(()=>{qe?pt(w=>!w):Ee(w=>{const Q=!w;try{localStorage.setItem("markus_team_panel_visible",String(Q))}catch{}return Q})},[qe]);S.useEffect(()=>{if(v)return;const w=G.current;if(!w)return;const Q=new ResizeObserver(([$])=>{if(!$)return;const I=$.contentRect.width;if(A(I),!t){const H=I-R.width-ye.width;He(H<400)}});return Q.observe(w),()=>Q.disconnect()},[v,t,R.width,ye.width]);const bt=Qe&&!qe&&!Ye,vt=L?0:R.width+re+(bt?ye.width+re:0),Pe=Math.max(0,Z-vt-re-8),Et=Math.min(fe,Math.floor(Pe*.4)),Ft=Math.max(0,Pe-Et),Es=Math.min(Math.round(Pe/2),Ft),yt=Math.max(0,Math.min(J==="auto"?Es:J,Ft)),Bt=S.useRef(!1);S.useEffect(()=>{const w=(B?.rightPanel??null)!==null;w&&!Bt.current&&(M(!0),Y("auto")),Bt.current=w},[B?.rightPanel]);const ut=S.useRef(yt);ut.current=yt;const Ze=S.useRef(Ft);Ze.current=Ft;const Xt=S.useCallback(w=>{w.preventDefault();const Q=w.clientX,$=ut.current,I=ie=>{const ne=$+(Q-ie.clientX),Ce=Ze.current,Le=Math.min(z,Ce);Y(Math.max(Le,Math.min(Ce,ne)))},H=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",H),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",I),document.addEventListener("mouseup",H),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);S.useEffect(()=>{if(!Ye)return;const w=Q=>{Q.target.closest("[data-l2-floating]")||pt(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[Ye]);const[ot,At]=S.useState(null),[us,he]=S.useState(!1),ce=S.useRef(null);S.useEffect(()=>{if(!us)return;const w=$=>{ce.current&&!ce.current.contains($.target)&&he(!1)},Q=$=>{$.key==="Escape"&&he(!1)};return document.addEventListener("mousedown",w),document.addEventListener("keydown",Q),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",Q)}},[us]);const[$e,Xe]=S.useState(),[de,De]=S.useState(),[ve,st]=S.useState(),[ze,Ve]=S.useState(!1),[ee,Te]=S.useState(""),[Se,Oe]=S.useState(!1),[_e,Fe]=S.useState(""),at=S.useRef(null),wt=S.useRef(null),ht=S.useCallback((w,Q)=>{const $=w?ih[w]:void 0,I=$?"overview":w;De($),Xe(I),st(Q),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(I??"overview")},[v]);S.useCallback(w=>{w==="profile"?ht():qi(T.current)?history.back():_("chat")},[ht]);const dt=S.useCallback((w,Q)=>{$t("direct"),Us(w),v&&k(),ht(Q?.tab,Q?.highlightMailboxId),At(null)},[v,k,ht]),Qt=S.useCallback((w,Q)=>{const $=l.find(I=>I.name.toLowerCase()===w.toLowerCase());if($){const I=Q.target.getBoundingClientRect();At({agentId:$.id,top:I.bottom,left:I.left})}},[l]),hi=S.useMemo(()=>l.map(w=>w.name),[l]),[le,$t]=S.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[ge,Us]=S.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[gt,Bs]=S.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[_t,ln]=S.useState(""),Fo=500,cn=S.useRef(new Set),Tl=w=>{if(cn.current.add(w),cn.current.size>Fo){const Q=Math.floor(Fo*.2),$=cn.current.values();for(let I=0;I<Q;I++){const H=$.next().value;H&&cn.current.delete(H)}}},Ql=S.useMemo(()=>{if(r?.channelMessages){const w=r.activeChannel??"custom:general";return r.channelMessages.filter(Q=>Q.channel===w).map(Q=>Mn(Q))}},[]),{manager:Os,messages:rs,setMessages:_s,sending:xr,setSending:Uo,activities:$l,setActivities:zr,activeSessionBuffer:xs,actBuffers:Vn,sessionTabsBuffer:jl,readConvMsgs:is,writeConvMsgs:Qr,setActiveSession:hn,currentConvKeyRef:jt,updateConvMsgs:br,updateConvMsgsRaf:Rl,appendConvActivity:El,beginLoad:Al,beginStream:$i,endStream:q,resetConv:me,abortStream:be,loadAndDisplay:Ie,incrementSending:Ke,decrementSending:Je,isSendingFor:lt,setStreamSession:Rt,clearStreamSession:Ot,getStreamSession:cs,saveSessionToCache:bs,restoreSessionFromCache:ir}=QI(Ql),[zt,ks]=S.useState(""),[vs,es]=S.useState(null),[nr,dn]=S.useState([]),[qt,qr]=S.useState(!!r?.streamLastMessage),un=S.useRef(null),R_=400;S.useEffect(()=>(xr?(un.current&&(clearTimeout(un.current),un.current=null),qr(!0)):qt&&(un.current=setTimeout(()=>{qr(!1),un.current=null},R_)),()=>{un.current&&clearTimeout(un.current)}),[xr]);const cd=S.useRef({fullText:"",timers:[]});S.useEffect(()=>{if(!t||!r?.streamLastMessage||rs.length===0)return;const w=rs[rs.length-1];if(!w||w.sender!=="agent")return;const Q=w.text;cd.current.fullText=Q;const $=cd.current.timers;function I(){let ie=0;_s(Ce=>Ce.map((Le,xe)=>xe===Ce.length-1?{...Le,text:""}:Le)),qr(!0);const ne=setInterval(()=>{if(ie+=1+Math.floor(Math.random()*2),ie>=Q.length){clearInterval(ne),_s(xe=>xe.map((ke,Ae)=>Ae===xe.length-1?{...ke,text:Q}:ke));const Ce=setTimeout(()=>qr(!1),800);$.push(Ce);const Le=setTimeout(I,6e3);$.push(Le)}else _s(Ce=>Ce.map((Le,xe)=>xe===Ce.length-1?{...Le,text:Q.slice(0,ie)}:Le))},30);$.push(ne)}const H=setTimeout(I,1500);return $.push(H),()=>{$.forEach(ie=>clearTimeout(ie)),cd.current.timers=[]}},[]);const[E_,cg]=S.useState(!1),[hd,hg]=S.useState(!1),[A_,dg]=S.useState(!1);S.useEffect(()=>{if(!hd){dg(!1);return}const w=setTimeout(()=>dg(!0),250);return()=>clearTimeout(w)},[hd]);const[fn,Zr]=S.useState(!0),[M_,dd]=S.useState(!0),ud=S.useRef(0),[or,Ml]=S.useState([]),[ug,fg]=S.useState(null),fd=S.useRef(null),Hs=S.useRef(null),[L_,ji]=S.useState(null);S.useEffect(()=>{if(!ge){ji(null);return}let w=!1;return te.agents.get(ge).then(Q=>{if(w)return;const $=Q.effectiveModel;ji($?.provider&&$?.model?{provider:$.provider,model:$.model}:null)}).catch(()=>{w||ji(null)}),()=>{w=!0}},[ge]);const md=S.useRef(!1),Ho=S.useCallback(()=>{const w=Hs.current;if(!w)return;const Q=md.current,$=Q?36:52,I=MO(Q);w.style.height="auto";const H=Math.max($,Math.min(w.scrollHeight,I));w.style.height=`${H}px`,w.style.overflowY=H>=I?"auto":"hidden"},[]);S.useEffect(()=>{const w=requestAnimationFrame(()=>Ho());return()=>cancelAnimationFrame(w)},[zt,or.length,Ho]);const pd=w=>{try{const Q=localStorage.getItem(`markus_closed_tabs_${w}`);return Q?new Set(JSON.parse(Q)):new Set}catch{return new Set}},N_=(w,Q)=>{const $=pd(w);$.add(Q);try{localStorage.setItem(`markus_closed_tabs_${w}`,JSON.stringify([...$]))}catch{}},D_=(w,Q)=>{const $=pd(w);if($.delete(Q))try{localStorage.setItem(`markus_closed_tabs_${w}`,JSON.stringify([...$]))}catch{}},mg=w=>{try{return localStorage.getItem(`markus_active_session_${w}`)}catch{return null}},Yo=(w,Q)=>{if(w)try{Q&&Q!==it?localStorage.setItem(`markus_active_session_${w}`,Q):localStorage.removeItem(`markus_active_session_${w}`)}catch{}},[$r,Ri]=S.useState([]),[I_,Ll]=S.useState(0),[pg,Nl]=S.useState(1),[Dl,Il]=S.useState(!1),[Bl,gg]=S.useState(!1),[et,Ei]=S.useState(null),[Go,mn]=S.useState(!1),[Og,pn]=S.useState(!1),[gd,xg]=S.useState(null),[Od,xd]=S.useState(""),[bg,bd]=S.useState([]),[gn,Wl]=S.useState(null),[B_,vg]=S.useState(null),[Ko,vd]=S.useState([]),[On,Jo]=S.useState(null),[W_,yg]=S.useState(null),Sg=S.useRef(new Set),[wg,yd]=S.useState([]),[jr,ea]=S.useState(null),Ai=jr?jr.items[jr.index]??null:null,[X_,_g]=S.useState(null),[kg,Sd]=S.useState([]),[Ws,z_]=S.useState([]),Ys=w=>{z_(Q=>{const $=typeof w=="function"?w(Q):w,I=new Set,H=$.filter(ie=>I.has(ie.id)?!1:(I.add(ie.id),!0));return H.some(ie=>ie.isMain)?[...H.filter(ie=>ie.isMain),...H.filter(ie=>!ie.isMain)]:H})},Cg=S.useRef(null);S.useEffect(()=>{if(!et)return;const w=Cg.current;if(!w)return;const Q=w.querySelector(`[data-session-tab-id="${CSS.escape(et)}"]`);if(!Q)return;const $=requestAnimationFrame(()=>{Q.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame($)},[et,Ws.length]);const Xl=S.useRef(null),wd=S.useRef(null),[Cs,ta]=S.useState(r?.groupChats??[]),_d=S.useRef(Cs);_d.current=Cs;const Pg=S.useRef(null),[kd,Ps]=S.useState(!1),[Cd,Fn]=S.useState(!1),[zl,Pd]=S.useState(""),[q_,sa]=S.useState(-1),[Z_,ql]=S.useState([]),[V_,Tg]=S.useState(!1),Td=S.useRef(void 0),[As,Qg]=S.useState(r?.teams??[]),[Qd,F_]=S.useState(!!r),[U_,H_]=S.useState([]),[$d,$g]=S.useState([]),[Y_,G_]=S.useState(null),[LI,NI]=S.useState(!1),[DI,II]=S.useState(""),[Un,ra]=S.useState(!1),[jg,K_]=S.useState(""),[ia,Hn]=S.useState(0),[Yn,Zl]=S.useState(!1),[Rg,J_]=S.useState(""),[jd,na]=S.useState(0),[Rd,ek]=S.useState([]),Eg=S.useRef(!1),Ed=S.useCallback(()=>{Eg.current||(Eg.current=!0,(async()=>{try{const{skills:w}=await te.skills.list();ek(w.map(Q=>({name:Q.name,description:Q.description??Q.name})))}catch{}})())},[]);S.useEffect(()=>{Ed()},[Ed]);const xn=Rg?Rd.filter(w=>w.name.toLowerCase().includes(Rg.toLowerCase())):Rd,[tk,sk]=S.useState([]),Ag=S.useRef(!1),rk=S.useCallback(()=>{Ag.current||(Ag.current=!0,(async()=>{const w=[];try{const[Q,$,I,H,ie]=await Promise.all([te.projects.list().catch(()=>({projects:[]})),te.requirements.list({lean:!0}).catch(()=>({requirements:[]})),te.tasks.list({pageSize:20,lean:!0}).catch(()=>({tasks:[]})),te.deliverables.search({limit:100}).catch(()=>({results:[]})),te.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const ne of Q.projects)w.push({id:ne.id,name:ne.name,entityType:"project",role:ne.status});for(const ne of $.requirements)w.push({id:ne.id,name:ne.title,entityType:"requirement",role:ne.priority});for(const ne of I.tasks)w.push({id:ne.id,name:ne.title,entityType:"task",role:ne.status});for(const ne of H.results)w.push({id:ne.id,name:ne.title,entityType:"deliverable",role:ne.type});for(const ne of ie.teams)try{const Ce=await te.workflows.list(ne.id);for(const Le of Ce.workflows)w.push({id:Le.name,name:Le.displayName||Le.name,entityType:"workflow",role:`v${Le.version}`})}catch{}}catch{}sk(w)})())},[]),ns=le==="channel"?Cs.find(w=>w.channelKey===gt)?.teamId:void 0,ik=S.useRef(null),Vr=S.useRef(null),Mg=S.useRef(void 0),oa=S.useCallback((w,Q)=>{Ei(Q),w&&(Q===null?Os.clearActiveSession(w):Os.setActiveSession(w,Q))},[Ei,Os]),Lg=S.useMemo(()=>Ea(le,ge,gt,_t),[le,ge,gt,_t]);ah();const aa=hs.isStreaming(et),bn=S.useMemo(()=>ho(Lg,et),[Lg,et]),Xs=S.useRef(bn);Xs.current=bn;const[la,nk]=S.useState(bn);if(S.useEffect(()=>{_a.save(la,{text:zt,images:or,context:nr,replyTo:vs})},[zt,la,or,nr,vs]),la!==bn){const w={text:zt,images:or,context:nr,replyTo:vs};if(zt!==_a.peek(la).text)_a.save(bn,w);else{_a.save(la,w);const Q=_a.get(bn);ks(Q.text),Ml(Q.images),dn(Q.context),es(Q.replyTo)}nk(bn)}const ys=S.useRef(null),Ad=S.useRef(null),Mi=S.useRef(null),Md=S.useRef(null),Vl=S.useRef(0),Fl=S.useRef([]),Gn=S.useRef(null),Ng=S.useRef([]),Ld=S.useRef(void 0),Ul=S.useRef(null),vn=S.useCallback(()=>Os.getActiveSession(jt.current)??jt.current,[Os]),Li=S.useCallback((w,Q)=>{w&&(Os.setWindowBounds(w,Q),w===vn()&&cg(Q.hasMore))},[Os,vn]);S.useEffect(()=>{cg(Os.getWindowBounds(vn()).hasMore)},[Os,vn,le,ge,gt,_t,et]),S.useEffect(()=>{if(!Go)return;const w=Q=>{wd.current&&!wd.current.contains(Q.target)&&Xl.current&&!Xl.current.contains(Q.target)&&mn(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[Go]);const Hl=(w,Q)=>{if(!Q||w===Q)return`notes:${w}`;const[$,I]=[w,Q].sort();return`dm:${$}:${I}`};S.useEffect(()=>{localStorage.setItem("markus_chat_mode",le)},[le]),S.useEffect(()=>{localStorage.setItem("markus_chat_agent",ge)},[ge]),S.useEffect(()=>{localStorage.setItem("markus_chat_channel",gt)},[gt]),S.useEffect(()=>{let w=!1;if(t||!ge||le!=="direct"){ji(null);return}return te.agents.get(ge).then(Q=>{if(w)return;const $=Q.config?.llmConfig;ji($?.modelMode==="custom"&&$.primary&&$.defaultModel?{provider:$.primary,model:$.defaultModel}:null)}).catch(()=>{w||ji(null)}),()=>{w=!0}},[ge,le,t]);const{counts:Nd,sessionAgentMap:ca,markRead:ha,setActiveKey:ok,clearActiveKey:ak}=OC({enabled:!t}),Yl=S.useMemo(()=>{const w={};for(const[Q,$]of Object.entries(Nd))Q.startsWith("channel:")&&(w[Q.slice(8)]=$);return w},[Nd]),Dd=xC(ca,Nd);S.useEffect(()=>{let w=0;for(const Q of Dd.values())w+=Q;for(const Q of Object.values(Yl))w+=Q;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:w}}))},[Dd,Yl]);const Gl=Dd,lk=S.useCallback(async w=>{for(const[Q,$]of Object.entries(ca))$===w&&ha(`session:${Q}`)},[ca,ha]);S.useEffect(()=>{if(t||!((!v||x==="chat")&&P==="chat"))return;if(le==="direct"&&ge&&lk(ge),le==="channel"&>)ha(`channel:${gt}`);else if(le==="direct"&&et)ha(`session:${et}`);else if(le==="dm"&&_t){const $=`dm:${[e?.id,_t].sort().join(":")}`;ha(`channel:${$}`)}const Q=[];if(le==="direct"&&et){Q.push(`session:${et}`);for(const[$,I]of Object.entries(ca))I===ge&&Q.push(`session:${$}`)}else le==="channel"&>?Q.push(`channel:${gt}`):le==="dm"&&_t&&e?.id&&Q.push(`channel:dm:${[e.id,_t].sort().join(":")}`);for(const $ of Q)ok($);return()=>{for(const $ of Q)ak($)}},[t,le,gt,et,_t,ge,x,P,ca]);const ar=S.useCallback(()=>te.agents.list().then(w=>h(w.agents)).catch(()=>{}),[]),ck=S.useCallback((w,Q)=>{w&&h($=>$.map(I=>I.id===w?{...I,avatarUrl:Q}:I))},[]),Gs=S.useCallback(()=>te.teams.list().then(w=>{Qg(w.teams),F_(!0)}).catch(()=>{}),[]),Kn=S.useCallback(()=>te.groupChats.list().then(w=>ta(w.chats)).catch(()=>{}),[]),hk=S.useMemo(()=>au(ar,3e3),[ar]),Kl=S.useMemo(()=>au(Gs,5e3),[Gs]),Id=S.useMemo(()=>au(Kn,3e3),[Kn]),da=S.useCallback(()=>{te.users.list(e?.orgId).then(w=>u(w.users)).catch(()=>{})},[e?.orgId]);S.useEffect(()=>{v&&(x!=="team"||!y||jO(y,As.map(w=>w.id),Qd)==="missing"&&(window.location.hash=Yt.TEAM))},[v,x,y,As,Qd]),S.useEffect(()=>{t||(Promise.all([ar(),Gs()]).finally(()=>p(!1)),da(),te.tasks.list().then(w=>$g(w.tasks)).catch(()=>{}),te.externalAgents.list().then(w=>H_(w.agents)).catch(()=>{}),Kn())},[t,da]),S.useEffect(()=>{if(!(!t||!r)&&(h(r.agents??[]),u(r.humans??[]),Qg(r.teams??[]),ta(r.groupChats??[]),r.channelMessages)){const w=r.activeChannel??"custom:general";_s(r.channelMessages.filter(Q=>Q.channel===w).map(Q=>Mn(Q)))}},[t,r]),S.useEffect(()=>{M2()},[]),S.useEffect(()=>{if(t||!o)return;const w=()=>{const ie=ge,ne=Ws.map(Ce=>Ce.id).filter(Ce=>Ce!==it);et&&et!==it&&!ne.includes(et)&&ne.push(et),ie&&ne.length>0&&L2(ie,ne)};let Q=null;const $=()=>{Q||(Q=setInterval(w,6e4))},I=()=>{Q&&clearInterval(Q),Q=null},H=()=>{document.hidden?I():(w(),$())};return document.addEventListener("visibilitychange",H),document.hidden||$(),w(),()=>{I(),document.removeEventListener("visibilitychange",H)}},[t,o,Ws,ge,et]),S.useEffect(()=>{if(t||!o)return;ar(),Gs();const w=setInterval(ar,3e4),Q=setInterval(Gs,6e4),$=St.on("agent:update",Ae=>{const Ue=Ae?.payload;if(Ue?.agentId){const ct=Ue.status,Kt=Ue.currentActivity;h(as=>as.map(Ht=>{if(Ht.id!==Ue.agentId)return Ht;const yr={...Ht};return ct&&(yr.status=ct),Kt!==void 0&&(yr.currentActivity=Kt),yr}))}hk(),Kl()}),I=St.on("team:update",()=>{Kl(),Id()}),H=St.on("agent:removed",Kl),ie=St.on("chat:group_created",()=>{Kn(),Gs(),ar()}),ne=St.on("chat:group_updated",Id),Ce=St.on("chat:group_deleted",()=>{Id(),Kl()}),Le=St.on("task:update",Ae=>{const Ue=Ae?.payload;Ue?.taskId&&$g(ct=>ct.map(Kt=>Kt.id===Ue.taskId?{...Kt,status:Ue.status??Kt.status}:Kt))}),xe=St.on("approval:resolved",Ae=>{const Ue=Ae?.payload?.approvalId;Ue&&(Wl(ct=>ct&&ct.id===Ue?null:ct),Jo(ct=>ct&&ct.id===Ue?null:ct))}),ke=()=>{ar(),Gs(),da()};return window.addEventListener("markus:data-changed",ke),()=>{clearInterval(w),clearInterval(Q),$(),I(),H(),ie(),ne(),Ce(),Le(),xe(),window.removeEventListener("markus:data-changed",ke)}},[t,o,da]),S.useEffect(()=>{if(t)return;const w=xe=>{const ke=xe.detail;if(MC(ke.page)===Yt.TEAM){if(ke.params?.agentId){if(ke.params.profileTab)dt(ke.params.agentId,{tab:ke.params.profileTab});else if($t("direct"),Us(ke.params.agentId),_("chat"),v&&k(),ke.params.sessionId){const Ae=ke.params.sessionId;setTimeout(async()=>{try{const{sessions:Ue}=await te.sessions.listByAgent(ke.params.agentId,20),ct=Ue.find(Kt=>Kt.id===Ae);ct&&Ii(ct)}catch{}},300)}}if(ke.params?.selectAgent&&($t("direct"),Us(ke.params.selectAgent),_("chat"),v&&k()),ke.params?.openDeliverable){const Ae=ke.params.openDeliverable;localStorage.removeItem("markus_nav_openDeliverable"),v?Lr.navigate(Yt.DELIVERABLES,{openDeliverable:Ae}):se&&te.deliverables.get(Ae).then(Ue=>{Ue.deliverable&&se({kind:"deliverable",deliverable:Ue.deliverable})}).catch(()=>{})}if(ke.params?.prefillMessage){const Ae=ke.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),ke.params?.autoSend==="true"?setTimeout(()=>Mg.current?.(Ae),300):(ks(Ae),setTimeout(()=>{const Ue=Hs.current;Ue&&(Ue.focus(),Ue.setSelectionRange(Ue.value.length,Ue.value.length))},100))}if(ke.params?.chatChips){const Ae=ke.params.chatChips;localStorage.removeItem("markus_nav_chatChips"),_("chat"),Ge(Ae)}if(ke.params?.dm&&($t("dm"),ln(ke.params.dm),_("chat"),v&&k()),ke.params?.channel&&($t("channel"),Bs(ke.params.channel),_("chat"),v&&k()),ke.params?.selectTeam){const Ae=ke.params.selectTeam;if(v)C(Ae);else{const Ue=_d.current.find(ct=>ct.type==="team"&&ct.teamId===Ae);$t("channel"),Bs(Ue?.channelKey??`group:${Ae}`),_("chat"),Ps(!1),Ee(!0)}}ke.params?.openHire}},Q=localStorage.getItem("markus_nav_agentId");if(Q){localStorage.removeItem("markus_nav_agentId");const xe=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),$t("direct"),Us(Q),xe?dt(Q,{tab:xe}):(_("chat"),v&&k())}const $=localStorage.getItem("markus_nav_dm");$&&(localStorage.removeItem("markus_nav_dm"),$t("dm"),ln($),_("chat"),v&&k());const I=localStorage.getItem("markus_nav_channel");I&&(localStorage.removeItem("markus_nav_channel"),$t("channel"),Bs(I),_("chat"),v&&k());const H=localStorage.getItem("markus_nav_prefillMessage");H&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),ks(H),setTimeout(()=>{const xe=Hs.current;xe&&(xe.focus(),xe.setSelectionRange(xe.value.length,xe.value.length))},150));const ie=localStorage.getItem("markus_nav_chatChips");ie&&(localStorage.removeItem("markus_nav_chatChips"),_("chat"),Ge(ie));const ne=localStorage.getItem("markus_nav_openDeliverable");ne&&(localStorage.removeItem("markus_nav_openDeliverable"),v?Lr.navigate(Yt.DELIVERABLES,{openDeliverable:ne}):se&&te.deliverables.get(ne).then(xe=>{xe.deliverable&&se({kind:"deliverable",deliverable:xe.deliverable})}).catch(()=>{}));const Ce=localStorage.getItem("markus_nav_selectAgent");Ce&&(localStorage.removeItem("markus_nav_selectAgent"),$t("direct"),Us(Ce),_("chat"),v&&k());const Le=localStorage.getItem("markus_nav_selectTeam");if(Le)if(localStorage.removeItem("markus_nav_selectTeam"),v)C(Le);else{const xe=_d.current.find(ke=>ke.type==="team"&&ke.teamId===Le);$t("channel"),Bs(xe?.channelKey??`group:${Le}`),_("chat"),Ps(!1),Ee(!0)}return window.addEventListener("markus:navigate",w),()=>window.removeEventListener("markus:navigate",w)},[t]),S.useEffect(()=>{const w=Pg.current;if(!w)return;const Q=Cs.find($=>$.type==="team"&&$.teamId===w);Pg.current=null,$t("channel"),Bs(Q?.channelKey??`group:${w}`),_("chat"),Ps(!1),Ee(!0)},[Cs,As]),S.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||ge&&l.some($=>$.id===ge))return;const w=localStorage.getItem("markus_nav_after_remove");if(w&&(localStorage.removeItem("markus_nav_after_remove"),w.startsWith("channel:"))){$t("channel"),Bs(w.slice(8)),_("chat");return}const Q=l.find($=>!$.teamId&&$.role?.toLowerCase()==="secretary")??l.find($=>$.role?.toLowerCase()==="secretary")??l.find($=>$.name?.toLowerCase().includes("secretary"));Q?($t("direct"),Us(Q.id),_("chat")):l.length>0&&($t("direct"),Us(l[0].id),_("chat"))},[l,ge]);const Jn=S.useRef(!1),yn=S.useRef(!1),ua=S.useRef(0),Bd=S.useRef("none"),Wd=S.useRef(0),Jl=S.useRef(0),di=S.useRef(null),Xd=S.useRef(null),Dg=S.useRef([]),zd=S.useRef(0),[dk,Sn]=S.useState(!1),eo=S.useRef(0),[Ig,fa]=S.useState(0),to=S.useCallback(()=>performance.now()<ua.current,[]),Ni=S.useCallback(()=>O2({takeover:yn.current,gestureActive:to()}),[to]),lr=S.useCallback(()=>{yn.current=!1,ua.current=0,Bd.current="none",zd.current=0,Jl.current+=1,Jn.current=!1,Sn(!1),eo.current=0,fa(0)},[]),Fr=S.useCallback(()=>{yn.current||(yn.current=!0,Jl.current+=1,Jn.current=!1,di.current!==null&&(cancelAnimationFrame(di.current),di.current=null),Sn(!0))},[]),ec=S.useCallback(w=>{ua.current=performance.now()+du,w!=="none"&&(Bd.current=w);const Q=Vr.current;x2(w,!!Q&&qO(Q))&&Fr()},[Fr]),tc=S.useCallback(w=>{const Q=Vr.current;if(!Q)return;const $=Q.scrollTop-Wd.current;Wd.current=Q.scrollTop;const I=g2({takeover:yn.current,gestureActive:to(),gestureDirection:Bd.current,scrollable:qO(Q),distance:Wc(Q),deltaScrollTop:$,programmatic:w?.programmatic??Jn.current,intentPending:ys.current!==null});I==="handover"?Fr():I==="resume"?lr():I==="follow"?(Sn(!1),eo.current=0,fa(0)):yn.current&&Sn(!0)},[to,Fr,lr]);S.useEffect(()=>{const w=Vr.current;if(!w)return;let Q=null;const $=ke=>{ec(d2(ke.deltaX,ke.deltaY))},I=ke=>{Q=ke.touches[0]?.clientY??null,ua.current=performance.now()+du},H=ke=>{const Ae=ke.touches[0]?.clientY;if(Ae==null)return;const Ue=p2(Q,Ae);Q=Ae,ec(Ue)},ie=()=>{Q=null},ne=ke=>{Vm(ke.target)||ec(m2(ke.key))},Ce=ke=>{const Ae=w.getBoundingClientRect();ke.clientX-Ae.left<w.clientWidth||(ua.current=performance.now()+du)},Le=()=>{tc()};w.addEventListener("wheel",$,{passive:!0}),w.addEventListener("touchstart",I,{passive:!0}),w.addEventListener("touchmove",H,{passive:!0}),w.addEventListener("touchend",ie,{passive:!0}),w.addEventListener("pointerdown",Ce,{passive:!0}),w.addEventListener("scroll",Le,{passive:!0}),document.addEventListener("keydown",ne);const xe=typeof ResizeObserver<"u"?new ResizeObserver(()=>tc()):null;return xe?.observe(w),Wd.current=w.scrollTop,tc(),()=>{w.removeEventListener("wheel",$),w.removeEventListener("touchstart",I),w.removeEventListener("touchmove",H),w.removeEventListener("touchend",ie),w.removeEventListener("pointerdown",Ce),w.removeEventListener("scroll",Le),document.removeEventListener("keydown",ne),xe?.disconnect()}},[x,tc,ec]);const qd=S.useMemo(()=>new Set(kg),[kg]),os=S.useMemo(()=>{const w=le==="channel"?rs:rs.filter(I=>!I.isActivityLog),Q=qd.size===0?w:w.filter(I=>!(I.isNotification&&qd.has(I.id))),$=t&&qt?Q.length-1:-1;return Q.filter((I,H)=>bC(I,H===$||!!I.isStreaming&&aa))},[rs,le,qd,aa,t,qt]);S.useEffect(()=>{md.current=P==="chat"&&os.length>0,Ho()},[P,os.length,Ho]);const so=n2({count:os.length,getScrollElement:()=>Vr.current,getItemKey:w=>os[w]?.id??w,estimateSize:w=>{const Q=os[w];return Q?Q.segments&&Q.segments.length>0?300:Q.text.length>500?200:120:120},overscan:8});so.shouldAdjustScrollPositionOnItemSizeChange=(w,Q,$)=>lu()||ys.current?.priority==="jump"?!1:w.start<($.scrollOffset??0);const cr=S.useCallback((w="instant")=>{if(!Ni()||performance.now()<zd.current)return;const Q=Vr.current;if(!Q)return;const $=++Jl.current,I=()=>$===Jl.current&&Ni();if(w==="smooth"){zd.current=performance.now()+c2,Q.scrollTo({top:Q.scrollHeight,behavior:"smooth"});return}di.current!==null&&(cancelAnimationFrame(di.current),di.current=null),Jn.current=!0;let H=0;const ie=()=>{if(di.current=null,!I()){Jn.current=!1;return}if(Q.scrollTop=Q.scrollHeight,H+=1,H<l2&&Wc(Q)>1){di.current=requestAnimationFrame(ie);return}Jn.current=!1};Q.scrollTop=Q.scrollHeight,di.current=requestAnimationFrame(ie)},[Ni]),wn=S.useCallback(w=>{const Q=Vr.current;!Q||!w||Q.scrollHeight<=Q.clientHeight||FO.save(w,v2(VO(Q),Q))},[]),_n=S.useCallback(()=>{Vl.current+=1;for(const w of Fl.current)clearTimeout(w);Fl.current=[]},[]),ro=S.useCallback(()=>{ys.current=null,_n()},[_n]),Bg=S.useCallback(()=>{lr(),ro(),Xd.current!==null&&cancelAnimationFrame(Xd.current);for(const w of Dg.current)clearTimeout(w);cr("instant"),Xd.current=requestAnimationFrame(()=>cr("instant")),Dg.current=[60,160,320].map(w=>setTimeout(()=>cr("instant"),w))},[lr,ro,cr]),Zd=S.useCallback(w=>{const Q=ys.current;if(!Q||Q.key!==w)return!0;if(Xs.current!==w||Q.priority!=="prepend"&&to())return ys.current=null,!0;const $=Vr.current;if(!$)return!0;if(lu())return!1;const{anchor:I}=Q;if(I.kind==="bottom"){uu(Q.priority)&&lr(),$.scrollTop=$.scrollHeight;const Ue=Wc($)<=1,ct=YO(Ue,Q.prevSettled);return Q.prevSettled=Ue,ct?(ys.current=null,!0):!1}const H=P2(Q.at,performance.now()),ie=w2(VO($),$,I.id,I.delta),ne=ie===null&&!H&&(is(Q.bufferId)??[]).some(Ue=>Ue.id===I.id),Ce=ie!==null&&Math.abs(ie)<=1,Le=YO(Ce,Q.prevSettled),xe=ie===null&&!ne,ke=Os.getWindowBounds(Q.bufferId).hasMore,Ae=T2({priority:Q.priority,rendered:ie!==null,stale:H,stable:Le,absent:xe,canLoadMore:ke});switch(Q.prevSettled=ie!==null?Ce:null,uu(Q.priority)&&Ae!=="release-bottom"&&Ae!=="release-hold"&&Fr(),Ae){case"apply":return zi("intent:apply",{id:I.id,priority:Q.priority,correction:ie}),ys.current=null,!0;case"refine":return ie!==null&&Math.abs(ie)>1&&($.scrollTop+=ie),ie!==null&&Math.abs(ie)>8&&zi("intent:refine",{id:I.id,priority:Q.priority,correction:ie}),!1;case"release-bottom":return zi("intent:release-bottom",{id:I.id,priority:Q.priority}),ys.current=null,uu(Q.priority)&&lr(),$.scrollTop=$.scrollHeight,!0;case"release-hold":return zi("intent:release-hold",{id:I.id,priority:Q.priority,stale:H,absent:xe,canLoadMore:ke,bufferId:Q.bufferId}),ys.current=null,console.warn("[scroll-intent] 目标行始终没能渲染出来,放弃定位(视口保持在原地)",{priority:Q.priority,anchor:I}),!0;default:{const Ue=Ng.current.findIndex(ct=>ct.id===I.id);if(Ue>=0){const ct=so.getOffsetForIndex(Ue,"start");ct&&($.scrollTop=ct[0]+I.delta)}else Ld.current?.();return!1}}},[so,to,Fr,lr,is]),sc=S.useCallback(()=>{const w=ys.current;if(!w)return;const Q=w.key;_n();const $=Vl.current,I=ie=>{Fl.current.push(setTimeout(()=>{$===Vl.current&&ys.current?.key===Q&&(Zd(Q)||I(HO))},ie))},H=[0,60,160,320,560,900];H.forEach((ie,ne)=>{const Ce=ne===H.length-1,Le=()=>{if($!==Vl.current)return;!Zd(Q)&&Ce&&I(HO)};ie===0?requestAnimationFrame(Le):Fl.current.push(setTimeout(Le,ie))})},[Zd,_n]),io=S.useCallback((w,Q,$="restore",I)=>{if(!w)return!1;const H=ys.current;return k2(H,{key:w,priority:$})?(ys.current={key:w,bufferId:I??vn(),anchor:Q,at:performance.now(),priority:$,prevSettled:null},sc(),!0):!1},[vn,sc]),ma=S.useCallback(w=>{w&&io(w,FO.get(w)??{kind:"bottom"})},[io]),uk=S.useCallback(()=>{ys.current||(Gn.current!==null&&clearTimeout(Gn.current),Gn.current=setTimeout(()=>{Gn.current=null,wn(Xs.current)},200))},[wn]);Ng.current=os,S.useLayoutEffect(()=>()=>{wn(Xs.current),_n(),Gn.current!==null&&clearTimeout(Gn.current)},[wn,_n]);const pa=S.useMemo(()=>MD(os,zl),[os,zl]);S.useEffect(()=>{sa(-1)},[zl]);const rc=S.useCallback(w=>{const Q=()=>{const H=document.getElementById(`msg-${w}`);return H?(H.classList.remove("chat-find-hit"),H.offsetWidth,H.classList.add("chat-find-hit"),window.setTimeout(()=>H.classList.remove("chat-find-hit"),1600),!0):!1};let $=0;const I=()=>{Q()||$++>=8||window.requestAnimationFrame(I)};I()},[]),Wg=S.useCallback(async(w,Q)=>{ro(),Fr();const $=Xs.current,I=jt.current,H=()=>(is(I)??[]).some(ne=>ne.id===w);let ie=H();if(!ie&&$){const ne=Os.getActiveSession(I)??I,Ce=await ND({targetId:w,has:H,targetCreatedAt:Q,fetchPage:async xe=>{if(!ne||ne===it)return{messages:[],hasMore:!1};const ke=await te.sessions.getMessages(ne,50,xe);return{messages:ke.messages,hasMore:ke.hasMore}}}),Le=LD(Ce.messages,w);Le.length>0&&(Qr(I,Le.map(oh)),Li(ne,{hasMore:Ce.hasMore,oldestCursor:Le[0]?new Date(Le[0].createdAt).toISOString():null})),ie=Ce.found||H(),zi("jump:collected",{messageId:w,found:Ce.found,kept:Le.length,exhausted:Ce.exhausted})}if(zi("jump:located",{messageId:w,loaded:ie,key:$,nowKey:Xs.current}),!($&&Xs.current!==$)){if(ie&&$){io($,ZO(w),"jump",vn()),zi("jump:scheduled",{messageId:w,key:$}),rc(w);return}$&&(zi("jump:fallback-bottom",{messageId:w,key:$}),console.warn("[jump] target message not loaded — falling back to the bottom",{messageId:w}),lr(),cr("instant"))}},[ro,Fr,io,rc,is,Os,Qr,Li,lr,cr]),fk=S.useCallback(w=>{const Q=pa.matches[w];Q&&(sa(w),ro(),Fr(),Xs.current&&io(Xs.current,ZO(Q.messageId),"jump"),rc(Q.messageId))},[pa.matches,ro,Fr,io,rc]);S.useEffect(()=>{if(P!=="chat"||t)return;const w=Q=>{Q.key.toLowerCase()!=="f"||Q.altKey||Q.shiftKey||!(b?Q.metaKey&&!Q.ctrlKey:Q.ctrlKey&&!Q.metaKey)||(Q.preventDefault(),Fn(!0))};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[P,t,b]);const Xg=S.useRef(o);S.useEffect(()=>{Xg.current=o},[o]),S.useLayoutEffect(()=>{const w=Ad.current;if(w&&(Ad.current=null,!ys.current&&w.key===Xs.current)){const Q=Vr.current,$=Q?Q.scrollHeight-w.scrollHeight:0;Q&&$>0&&(Q.scrollTop+=$,Q.dispatchEvent(new Event("scroll")))}if(ys.current){sc();return}Xg.current&&Ni()&&(lu()||cr())},[rs,cr,Ni,sc]);const zg=S.useRef(P);S.useEffect(()=>{const w=zg.current!=="chat";zg.current=P,P==="chat"&&w&&ma(Xs.current)},[P,xr,cr,Ni,ma]);const qg=S.useRef(W);S.useEffect(()=>{if(qg.current===W||(qg.current=W,P!=="chat")||os.length===0||xr||fn||!Ni())return;const w=[],Q=requestAnimationFrame(()=>cr("instant"));for(const $ of[60,160,320])w.push(setTimeout(()=>cr("instant"),$));return()=>{cancelAnimationFrame(Q);for(const $ of w)clearTimeout($)}},[W,P,os.length,xr,fn,cr,Ni]);const ic=S.useCallback(async(w,Q,$)=>{const I=Q??`ch:${w}`;!$?.quiet&&jt.current===I&&Zr(!0);try{const H=await te.channels.getMessages(w,50),ie=H.messages.map(ne=>Mn(ne,e?.id));Qr(I,ie),Li(I,{hasMore:H.hasMore,oldestCursor:H.messages[0]?new Date(H.messages[0].createdAt).toISOString():null}),jt.current===I&&_s(ie)}catch{jt.current===I&&_s([])}finally{!$?.quiet&&jt.current===I&&Zr(!1)}},[Li]),Vd=S.useCallback(async w=>{if(!w)return Ri([]),Ll(0),Nl(1),Il(!1),dd(!1),[];dd(!0);try{const Q=await te.sessions.listByAgent(w,20,1);return Ri(Q.sessions),Ll(Q.total??Q.sessions.length),Nl(Q.page??1),Il(!!Q.hasMore),Q.sessions}catch{return Ri([]),Ll(0),Nl(1),Il(!1),[]}finally{dd(!1)}},[]),Zg=S.useRef({chatContext:[],input:"",pendingImages:[],chatMode:le,selectedAgent:ge,activeSessionId:et,activeDmUserId:_t,authUser:e,activeChannel:gt,groupChats:Cs,agents:l,humans:d,sending:xr,chatReplyTo:null});Zg.current={chatContext:nr,input:zt,pendingImages:or,chatMode:le,selectedAgent:ge,activeSessionId:et,activeDmUserId:_t,authUser:e,activeChannel:gt,groupChats:Cs,agents:l,humans:d,sending:xr,chatReplyTo:vs};const mk=$I({stateRef:Zg,actBuffers:Vn,activeSessionBuffer:xs,readConvMsgs:is,currentConvKeyRef:jt,updateConvMsgs:br,updateConvMsgsRaf:Rl,appendConvActivity:El,beginStream:$i,endStream:q,abortStream:be,clearStreamSession:Ot,setStreamSession:Rt,getStreamSession:cs,setActiveSession:hn,incrementSending:Ke,decrementSending:Je,loadAndDisplay:Ie,sessionSwitchSeqRef:ud,setSending:Uo,setActivities:zr,setInput:ks,setChatContext:dn,setPendingImages:Ml,setMentionDropdown:ra,setChatReplyTo:es,setActiveSessionId:Ei,setStoredActiveSession:Yo,setOpenSessionTabs:Ys,setSessions:Ri,setLoadingChat:Zr,setWindowBounds:Li,makeConvKey:Ea,makeDmChannel:Hl,addRecentMsgId:Tl,resumeChatScrollFollow:lr,loadSessions:Vd,t:i}),{send:no,stopSending:pk,tryReattachActiveStream:oo,loadSessionMessages:Fd}=mk;Mg.current=no;const Vg=S.useCallback(()=>{Bg(),no()},[Bg,no]),Fg=S.useRef(oo);Fg.current=oo;const gk=ah();S.useEffect(()=>{if(!o||t||le!=="direct"||!ge)return;const w=et;!w||w===it||hs.isStreaming(w)&&Fg.current(ge,w,jt.current)},[o,t,le,ge,et,gk]);const Ok=S.useCallback(async()=>{if(Bl||!ge||!Dl)return;gg(!0);const w=pg+1,Q=ge;try{const $=await te.sessions.listByAgent(Q,20,w);Ri(I=>{const H=new Set(I.map(ne=>ne.id)),ie=[...I,...$.sessions.filter(ne=>!H.has(ne.id))];return Ll($.total??ie.length),ie}),Nl(w),Il(!!$.hasMore)}catch{}gg(!1)},[Bl,Dl,pg,ge]),Ug=S.useCallback(w=>{xg(w.id),xd((w.isMain?"":w.title)||"")},[]),ga=S.useCallback(()=>{xg(null),xd("")},[]),Hg=S.useCallback(async w=>{const Q=Od.trim();if(!Q){ga();return}try{const I=(await te.sessions.renameTitle(w.id,Q))?.session?.title??Q;Ri(H=>H.map(ie=>ie.id===w.id?{...ie,title:I}:ie)),Ys(H=>H.map(ie=>ie.id===w.id?{...ie,title:I}:ie))}catch{}ga()},[Od,ga]),Yg=S.useCallback(async()=>{if(Ul.current)return Ul.current;const w=jt.current,Q=Os.getActiveSession(w)??w,$=Os.getWindowBounds(Q),I=$.oldestCursor;if(!$.hasMore||!I)return 0;const H=Q&&Q!==it?Q:null,ne=(async()=>{hg(!0);try{const Ce=Xs.current;let Le=[],xe=!1,ke=null;if(le==="channel"||le==="dm"){const Ht=le==="dm"?Hl(e?.id??"",_t):gt,yr=await te.channels.getMessages(Ht,50,I);Le=yr.messages.map(hr=>Mn(hr,e?.id)),xe=yr.hasMore,ke=yr.messages[0]?new Date(yr.messages[0].createdAt).toISOString():null}else if(H){const Ht=await te.sessions.getMessages(H,50,I);Le=Ht.messages.map(oh),xe=Ht.hasMore,ke=Ht.messages[0]?new Date(Ht.messages[0].createdAt).toISOString():null}else return 0;if(Le.length===0)return Li(Q,{hasMore:xe,oldestCursor:I}),0;if(jt.current!==w||Xs.current!==Ce)return 0;const Ae=Vr.current,Ue=Ae?Ae.scrollHeight:null,ct=is(w)??[],Kt=new Set(Le.map(Ht=>Ht.id));let as=[...Le,...ct.filter(Ht=>!Kt.has(Ht.id))];return as.length>500&&(as=as.slice(-500)),Qr(w,as),Li(Q,{hasMore:xe,oldestCursor:ke}),Ue!==null&&(Ad.current={key:Xs.current,scrollHeight:Ue}),_s(as),Le.length}catch{return 0}finally{hg(!1)}})();Ul.current=ne;try{return await ne}finally{Ul.current=null}},[le,gt,e?.id,_t,is,Qr,Os,Li]);Ld.current=Yg;const Ud=S.useRef(!1),xk=S.useCallback(w=>{uk(),!Ud.current&&(Ud.current=!0,requestAnimationFrame(()=>{Ud.current=!1,w.target.scrollTop<100&&Ld.current?.()}))},[]);S.useEffect(()=>{if(t)return;const w=Ea(le,ge,gt,_t),Q=jt.current;jt.current=w,Q&&Q!==w&&(jl.set(Q,Ws),et&&Dm(Q)&&hn(Q,et),wn(ho(Q,et))),Q!==w&&(lr(),Sn(!1),eo.current=0,fa(0),Fn(!1),Pd(""),sa(-1));const $=is(w),I=jl.get(w),H=xs.get(w)??(ge?mg(ge)??void 0:void 0),ie=cs(w),ne=H??et,Ce=le!=="direct"?lt(w):e0(ie,ne),Le=ne??w,xe=Vn.get(Le)??[];zr(Ce?xe:[]),Uo(Ce),le==="direct"&&ge&&Vd(ge),I&&I.length>0&&Ys(I),mn(!1);const ke=N2(Mi.current,{chatMode:le,agentId:ge});if($!==void 0&&$.length>0)if(Ce||Os.completeLoad(w),Zr(!1),_s($),H!==void 0&&(oa(w,H),ma(ho(w,H))),(!I||I.length===0)&&Ys([]),le==="channel"||le==="dm"){const Ue=le==="dm"?Hl(e?.id??"",_t):gt;ic(Ue,w)}else le==="direct"&&ge&&H&&H!==it&&!ke&&(Ce?oo(ge,H,w):Fd(H,w).then(()=>{jt.current===w&&ge&&oo(ge,H,w)}));else if(Al(w),Zr(!0),_s([]),Qr(w,[]),le==="channel"||le==="dm"){const Ue=le==="dm"?Hl(e?.id??"",_t):gt;ic(Ue,w),(!I||I.length===0)&&Ys([])}else le==="direct"&&ge?Vd(ge).then(Ue=>{if(jt.current===w)if(Ue.length>0){const ct=Ue.find(zs=>zs.isMain),Kt=pd(ge),as=ct?[ct,...Ue.filter(zs=>!zs.isMain&&!Kt.has(zs.id)).slice(0,4)]:Ue.filter(zs=>!Kt.has(zs.id)).slice(0,5);let Ht=I&&I.length>0?I:as;const yr=mg(ge),hr=H!==void 0?H:yr??ct?.id??Ht[0].id;if(hr&&hr!==it&&!Ht.some(zs=>zs.id===hr)){const zs=Ue.find(Ur=>Ur.id===hr);zs&&(Ht=[...Ht,zs])}const ui=hr&&Ht.some(zs=>zs.id===hr)?hr:Ht[0].id,Bi=Mi.current;if(Bi&&Bi.mode==="direct"&&Bi.agentId===ge&&(Bi.sessionId||Bi.preferMain)){Ys(Ht);return}oa(w,ui),ma(ho(w,ui)),Yo(ge,ui),Ys(Ht),Fd(ui,w).then(()=>{jt.current===w&&ge&&oo(ge,ui,w)})}else oa(w,null),Zr(!1),(!I||I.length===0)&&Ys([])}).catch(()=>{jt.current===w&&Zr(!1)}):Zr(!1)},[t,le,ge,gt,_t,n.language,i]),S.useEffect(()=>t?void 0:St.on("chat:message",Q=>{const $=Q.payload,I=$.channel??"";if(!I)return;const H=$.senderType??"agent",ie=$.text??$.message??"",ne=$.senderId??$.agentId??"",Ce=$.senderName??$.agentId??i("page.fallbackAgent"),Le=$.metadata,xe=$.messageId??$.id??"";if(xe&&cn.current.has(xe))return;const ke=H==="human"&&ne===(e?.id??""),Ae={id:xe||`ws_${Date.now()}_${ne}`,sender:ke?"user":"agent",text:ie,time:new Date().toLocaleTimeString(),rawCreatedAt:Q.timestamp??new Date().toISOString(),agentName:ke?void 0:Ce,agentId:ke?void 0:ne,replyToId:$.replyToId??void 0,replyToSender:$.replyToSender??void 0,replyToText:$.replyToText??void 0};if(Le&&H==="agent"){const ct=[];if(Le.thinking?.length&&ct.push({type:"text",content:"",thinking:Le.thinking.join(`
|
|
79
|
+
`:"",He=(Ee??qe+G.input).trim(),Ye=(Ee??G.input).trim();if(!He&&G.pendingImages.length===0||G.chatMode==="direct"&&!G.selectedAgent)return;oe();const pt=Date.now(),xt=h.current;if(!ye?.isRetry&&!ye?.isResume&&He&&xt&&xt.text===He&&pt-xt.at<1500)return;if(h.current={text:He,at:pt},ye?.isResume){const rt=ye.sessionIdOverride??G.activeSessionId??"";if(pt-(d.current.get(rt)??0)<2e3)return;d.current.set(rt,pt)}if(G.sending&&G.chatMode==="direct"){if(dC({liveSessions:T(g.current),sendSessionId:G.activeSessionId})){const yt=g.current;if([...b(yt)??[]].reverse().find(Xt=>Xt.sender==="user")?.text===He&&!ye?.isRetry&&!ye?.isResume){n(G.activeSessionId??it);const Xt=_f(G.activeSessionId,it);return Xt.kind==="cancel"&&te.agents.cancelProcessing(G.selectedAgent,Xt.target).catch(()=>{}),C(yt,G.activeSessionId),O(yt,ot=>{const Mt=[...ot];return Mt.length>0&&Mt[Mt.length-1].sender==="agent"&&Mt.pop(),Mt.length>0&&Mt[Mt.length-1].sender==="user"&&Mt[Mt.length-1].text===He&&Mt.pop(),Mt}),await new Promise(ot=>setTimeout(ot,50)),Qe(He,{isRetry:!0})}n(G.activeSessionId??it);const Ze=_f(G.activeSessionId,it);Ze.kind==="cancel"&&te.agents.cancelProcessing(G.selectedAgent,Ze.target).catch(()=>{}),C(yt,G.activeSessionId),O(yt,Xt=>CO(Xt)),await new Promise(Xt=>setTimeout(Xt,50))}}else if(G.sending&&G.chatMode!=="direct"){n(f.current.activeSessionId??g.current);const rt=g.current;C(rt),O(rt,yt=>CO(yt)),await new Promise(yt=>setTimeout(yt,50))}const bt=G.pendingImages.length>0?G.pendingImages.map(rt=>rt.dataUrl):void 0,vt=G.pendingImages.length>0?G.pendingImages.map(rt=>rt.name):void 0,Pe=A(G.chatMode,G.selectedAgent??"",G.activeChannel??"",G.activeDmUserId),At=G.chatReplyTo;Ee||(X(""),ae([])),j([]),W(!1),D(null);const Ft=G.chatMode==="dm";L(Pe);const Es=G.activeSessionId??Pe;if(p.set(Es,[]),g.current===Pe&&!Ft&&(U(!0),F([])),G.chatMode==="dm"){const rt=J(G.authUser?.id??"",G.activeDmUserId),yt=`opt_${Date.now()}`,Bt={id:yt,sender:"user",text:He,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};bt?.length&&(Bt.images=bt),At&&(Bt.replyToId=At.id,Bt.replyToSender=At.sender,Bt.replyToText=At.text),O(Pe,ut=>[...ut,Bt]);try{const ut=await te.channels.sendMessage(rt,{text:He,senderName:G.authUser?.name??pe("page.fallbackYou"),senderId:G.authUser?.id,mentions:[],orgId:"default",humanOnly:!0,...bt?.length?{images:bt}:{},...vt?.length?{fileNames:vt}:{}});ut.userMessage&&Y(ut.userMessage.id),O(Pe,Ze=>{const Xt=Ze.filter(Mt=>Mt.id!==yt),ot=[];return ut.userMessage&&ot.push(Mn(ut.userMessage,G.authUser?.id)),ot.length>0?[...Xt,...ot]:Ze})}catch(ut){Ic(ut)&&Bc(),O(Pe,Ze=>[...Ze.filter(ot=>ot.id!==yt),{id:`err_${Date.now()}`,sender:"agent",text:pe("page.errorWithMessage",{message:String(ut)}),time:new Date().toLocaleTimeString(),agentName:pe("page.systemName"),isError:!0}])}M(Pe),g.current===Pe&&U(!1)}else if(G.chatMode==="channel"){const rt=`opt_${Date.now()}`,yt={id:rt,sender:"user",text:He,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};At&&(yt.replyToId=At.id,yt.replyToSender=At.sender,yt.replyToText=At.text),O(Pe,ut=>[...ut,yt]);const Bt=XC(He);G.groupChats.find(ut=>ut.channelKey===G.activeChannel);try{const ut=await te.channels.sendMessage(G.activeChannel,{text:He,senderName:G.authUser?.name??pe("page.fallbackYou"),mentions:Bt,senderId:G.authUser?.id,orgId:"default",replyToId:At?.id,...bt?.length?{images:bt}:{},...vt?.length?{fileNames:vt}:{}});ut.userMessage&&Y(ut.userMessage.id),ut.agentMessage&&Y(ut.agentMessage.id),O(Pe,Ze=>{const Xt=Ze.filter(Mt=>Mt.id!==rt),ot=[];return ut.userMessage&&ot.push(Mn(ut.userMessage,G.authUser?.id)),ut.agentMessage&&ot.push(Mn(ut.agentMessage,G.authUser?.id)),ot.length>0?[...Xt,...ot]:Ze})}catch(ut){Ic(ut)&&Bc();const Ze=nh(ut,pe)||pe("page.errorWithMessage",{message:String(ut)});O(Pe,Xt=>[...Xt,{id:`err_${Date.now()}`,sender:"agent",text:Ze,time:new Date().toLocaleTimeString(),agentName:pe("page.systemName"),isError:!0}])}M(Pe),g.current===Pe&&U(!1)}else{y(Pe);const rt=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,yt=ye?.isResume?b(Pe)??[]:[],Bt=ye?.isResume?uC(yt):-1,ut=Bt>=0?yt[Bt].id:void 0,Ze=ut??`a_${rt}`,Xt=`u_${rt}`;let ot=ye?.sessionIdOverride??(G.activeSessionId===it?null:G.activeSessionId??null);if(ye?.isResume){const ee=new Date().toISOString();O(Pe,Te=>{if(ut){const Se=Te.findIndex(Oe=>Oe.id===ut);if(Se>=0)return Te.map((Oe,_e)=>_e===Se?{...Oe,isStreaming:!0,isStopped:!1,isError:!1}:Oe)}return[...Te,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:ee,segments:[],isStreaming:!0}]},ot)}else{const ee=new Date().toISOString(),Te={id:Xt,sender:"user",text:He,time:new Date().toLocaleTimeString(),rawCreatedAt:ee};bt?.length&&(Te.images=bt),At&&(Te.replyToId=At.id,Te.replyToSender=At.sender,Te.replyToText=At.text),O(Pe,Se=>[...Se,Te,{id:Ze,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:ee,segments:[],isStreaming:!0}],ot)}const Mt=ee=>{u.current=Date.now(),m(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(Fe=>Fe.id===Ze);if(Oe<0)return Te;const _e=Se[Oe];return Se[Oe]={..._e,text:(_e.text??"")+ee,segments:SO(_e.segments??[],ee)},Se},ot)},us=ee=>{u.current=Date.now(),m(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(Fe=>Fe.id===Ze);if(Oe<0)return Te;const _e=Se[Oe];return Se[Oe]={..._e,segments:wO(_e.segments??[],ee)},Se},ot)},he=ee=>{if(u.current=Date.now(),ee.type==="session_start"&&ee.sessionId){const Te=ot;if(ot=ee.sessionId,l.current.delete(ee.sessionId),Te&&Te!==ee.sessionId&&(P(Pe,Te),G.selectedAgent&&Te===it&&(hs.applyLocalOptimistic(G.selectedAgent,Te,!1),hs.applyLocalOptimistic(G.selectedAgent,ee.sessionId,!0))),_(Pe,ee.sessionId),ee.userMessageId&&!ye?.isResume&&O(Pe,Se=>Se.map(Oe=>Oe.id===Xt?{...Oe,id:ee.userMessageId}:Oe),ee.sessionId),g.current===Pe){const Se=G.activeSessionId;(!Se||Se===it||Se===ee.sessionId)&&(V(ee.sessionId),R(Pe,ee.sessionId),a(ee.sessionId),G.selectedAgent&&se(G.selectedAgent,ee.sessionId),fe(Oe=>Oe.some(_e=>_e.id===it)?Oe.map(_e=>_e.id===it?{..._e,id:ee.sessionId}:_e):Oe.some(_e=>_e.id===ee.sessionId)?Oe:[...Oe,{id:ee.sessionId,agentId:G.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}O(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(Fe=>Fe.id===Ze);if(Oe<0)return Te;const _e=[...Se[Oe].committedSegments??[]];return ee.type==="thinking_commit"?_e.push({type:"text",content:"",thinking:ee.content,createdAt:ee.createdAt}):_e.push({type:"text",content:ee.content,createdAt:ee.createdAt}),Se[Oe]={...Se[Oe],committedSegments:_e},Se},ot)},ce=ee=>{u.current=Date.now(),ee.phase!=="heartbeat"&&((ee.phase==="start"||ee.phase==="end")&&x(Pe,{...ee,phase:ee.phase,ts:Date.now()},ot),ee.phase==="start"?O(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(dt=>dt.id===Ze);if(Oe<0)return Te;const _e=[...Se[Oe].segments??[]];let Fe=!1;if(ee.arguments)for(let dt=_e.length-1;dt>=0;dt--){const Qt=_e[dt];if(Qt.type==="tool"&&Qt.tool===ee.tool&&Qt.status==="running"){_e[dt]={...Qt,args:ee.arguments},Fe=!0;break}}const at=`${ee.tool}_${Date.now()}`,wt=new Date().toISOString();Fe||_e.push({type:"tool",key:at,tool:ee.tool,status:"running",args:ee.arguments,createdAt:wt});const ht=[...Se[Oe].committedSegments??[]];return ee.arguments!==void 0&&ht.push({type:"tool",key:at,tool:ee.tool,status:"running",args:ee.arguments,createdAt:wt}),Se[Oe]={...Se[Oe],segments:_e,committedSegments:ht},Se},ot):ee.phase==="output"?m(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(Fe=>Fe.id===Ze);if(Oe<0)return Te;const _e=[...Se[Oe].segments??[]];for(let Fe=_e.length-1;Fe>=0;Fe--){const at=_e[Fe];if(at.type==="tool"&&at.tool===ee.tool&&at.status==="running"){_e[Fe]={...at,liveOutput:pC(at.liveOutput,ee.output??"")};break}}return Se[Oe]={...Se[Oe],segments:_e},Se},ot):ee.phase==="subagent_progress"&&ee.subagentEvent?m(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(wt=>wt.id===Ze);if(Oe<0)return Te;const _e=wt=>{const ht=[...wt];for(let dt=ht.length-1;dt>=0;dt--){const Qt=ht[dt];if(Qt.type==="tool"&&(Qt.tool==="spawn_subagent"||Qt.tool==="spawn_subagents")&&Qt.status==="running"){ht[dt]={...Qt,subagentLogs:_O(Qt.subagentLogs,ee.subagentEvent)};break}}return ht},Fe=_e(Se[Oe].segments??[]),at=_e(Se[Oe].committedSegments??[]);return Se[Oe]={...Se[Oe],segments:Fe,committedSegments:at},Se},ot):O(Pe,Te=>{const Se=[...Te],Oe=Se.findIndex(ht=>ht.id===Ze);if(Oe<0)return Te;const _e=new Date().toISOString(),Fe=[...Se[Oe].segments??[]];let at;for(let ht=Fe.length-1;ht>=0;ht--){const dt=Fe[ht];if(dt.type==="tool"&&dt.tool===ee.tool&&dt.status==="running"){at=dt.subagentLogs,Fe[ht]={...dt,status:ee.success===!1?"error":"done",args:ee.arguments,result:ee.result,error:ee.error,durationMs:ee.durationMs,liveOutput:void 0,createdAt:_e};break}}const wt=[...Se[Oe].committedSegments??[]];for(let ht=wt.length-1;ht>=0;ht--){const dt=wt[ht];if(dt.type==="tool"&&dt.tool===ee.tool&&dt.status==="running"){wt[ht]={...dt,status:ee.success===!1?"error":"done",args:ee.arguments,result:ee.result,error:ee.error,durationMs:ee.durationMs,liveOutput:void 0,createdAt:_e,subagentLogs:at??dt.subagentLogs};break}}return Se[Oe]={...Se[Oe],segments:Fe,committedSegments:wt},Se},ot))},$e=new AbortController;e.current.set(f.current.activeSessionId??it,$e);const Xe=ot,de=Xe;de&&l.current.delete(de),de&&_(Pe,de),G.selectedAgent&&hs.applyLocalOptimistic(G.selectedAgent,de??it,!0);try{u.current=Date.now();const ee=await te.agents.messageStream(G.selectedAgent,He,{onChunk:Mt,onThinking:us,onActivity:ce,onCommit:he},{signal:$e.signal,images:bt,sessionId:Xe,isRetry:ye?.isRetry,isResume:ye?.isResume,fileNames:vt,replyTo:At,titleSource:Ye});if(g.current===Pe){if(ee.merged&&O(Pe,Se=>Se.filter(Oe=>Oe.id!==Ze&&Oe.id!==Xt),ot),!ee.merged&&ee.segments?.length&&O(Pe,Se=>{const Oe=[...Se],_e=Oe.findIndex(ht=>ht.id===Ze);if(_e<0)return Se;const Fe=kO(ee.segments,Oe[_e].segments);let at=ee.content||Oe[_e].text;at||(at=Fe.filter(ht=>ht.type==="text").map(ht=>ht.content).join(""));const wt=ee.emptyReply===!0;return Oe[_e]={...Oe[_e],text:at,segments:Fe,committedSegments:Fe,isStopped:ee.cancelled||Oe[_e].isStopped,emptyReply:ee.emptyReply||wt||void 0,isError:ee.emptyReply||wt?!0:Oe[_e].isError},Oe},ot),!ee.merged&&!ee.segments?.length&&O(Pe,Se=>{const Oe=[...Se],_e=Oe.findIndex(Qt=>Qt.id===Ze);if(_e<0)return Se;const Fe=Oe[_e],at=Fe.committedSegments??[],ht=at.filter(Qt=>Qt.type==="text"&&!!Qt.content).map(Qt=>Qt.content).join("")||ee.content||Fe.text,dt=ee.emptyReply===!0;return(at.length>0||ht||ee.cancelled||ee.emptyReply||dt)&&(Oe[_e]={...Fe,text:ht,segments:at.length>0?at:Fe.segments,isStopped:ee.cancelled||Fe.isStopped,emptyReply:ee.emptyReply||dt||void 0,isError:ee.emptyReply||dt?!0:Fe.isError}),Oe},ot),ee.sessionId){V(Oe=>!Oe||Oe===it||Oe===ee.sessionId?ee.sessionId:Oe);const Se=v.get(Pe);(!Se||Se===it||Se===ee.sessionId)&&(R(Pe,ee.sessionId),a(ee.sessionId)),fe(Oe=>Oe.some(_e=>_e.id===it)?Oe.map(_e=>_e.id===it?{..._e,id:ee.sessionId}:_e):Oe.some(_e=>_e.id===ee.sessionId)?Oe:[...Oe,{id:ee.sessionId,agentId:G.selectedAgent??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])}K(G.selectedAgent).then(Se=>{if(g.current===Pe&&(z(Se),ee.sessionId)){const Oe=Se.find(_e=>_e.id===ee.sessionId);Oe&&fe(_e=>_e.some(at=>at.id===Oe.id)?_e.map(at=>at.id===Oe.id?Oe:at):[Oe,..._e.filter(at=>at.id!==it)])}});const Te=ee.sessionId??(de&&de!==it?de:null);if(!$e.signal.aborted&&!ee.merged&&(ee.softDisconnected??ee.segments===void 0)&&G.chatMode==="direct"&&G.selectedAgent&&Te){const Se=G.selectedAgent;let Oe=!1,_e;for(let Fe=0;Fe<4&&!Oe&&(Fe>0&&await new Promise(at=>setTimeout(at,350*Fe)),!$e.signal.aborted);Fe+=1)try{const at=await te.sessions.streamStatus(Se,Te);if(at.messageId&&(_e=at.messageId),KO({aborted:$e.signal.aborted,sawTerminal:!1,serverStatus:JO(at.status)})==="reattach"){O(Pe,ht=>ht.map(dt=>dt.id===Ze?{...dt,isStreaming:!0,isStopped:!1,segments:(dt.segments??[]).map(Qt=>Qt.type==="tool"&&(Qt.status==="stopped"||Qt.status==="running")?{...Qt,status:"running"}:Qt)}:dt),Te),M(Pe),r($e),_(Pe,Te),k(Pe),Ge(Se,Te,Pe),Oe=!0;return}break}catch{}if(!Oe&&!$e.signal.aborted){_e&&Ze&&O(Pe,Fe=>wa(Fe,Ze,_e),Te);try{if(await je(Te,Pe)>0){M(Pe),r($e),k(Pe);return}}catch{}}}}!ee.merged&&(ot||g.current===Pe)&&O(Pe,Te=>wa(Te,Ze,ee.messageId),ot)}catch(ee){const Te=ee?.sessionId;Te&&G.chatMode==="direct"&&g.current===Pe&&(V(Te),R(Pe,Te),a(Te),fe(Oe=>Oe.map(_e=>_e.id===it?{..._e,id:Te}:_e)),K(G.selectedAgent).then(Oe=>{if(g.current!==Pe)return;z(Oe);const _e=Oe.find(Fe=>Fe.id===Te);_e&&fe(Fe=>Fe.some(wt=>wt.id===_e.id)?Fe.map(wt=>wt.id===_e.id?_e:wt):[_e,...Fe])})),Ic(ee)&&Bc();const Se=nh(ee,pe);Se?O(Pe,Oe=>{const _e=[...Oe],Fe=_e.findIndex(at=>at.id===Ze);return Fe>=0&&(_e[Fe]={..._e[Fe],text:Se,isError:!0}),_e},ot):O(Pe,Oe=>{const _e=[...Oe],Fe=_e.findIndex(at=>at.id===Ze);if(Fe>=0){const at=PO(_e[Fe],"stopped");if(at===null)return Oe.filter(wt=>wt.id!==Ze);_e[Fe]=at}return _e},ot)}O(Pe,ee=>fC(ee,Ze),ot),$e.signal.aborted&&O(Pe,ee=>{const Te=[...ee],Se=Te.findIndex(Oe=>Oe.id===Ze);if(Se>=0){const Oe=PO(Te[Se],"stopped");if(Oe===null)return ee.filter(_e=>_e.id!==Ze);Te[Se]=Oe}return Te},ot);const ve=(b(Pe)??[]).find(ee=>ee.id===Ze),st=G.activeSessionId&&G.activeSessionId!==it?G.activeSessionId:null,ze=ve?mC(ve):!1;ve&&!ze&&G.chatMode==="direct"&&st&&!$e.signal.aborted&&await(async(Te,Se)=>{for(let Oe=0;Oe<Te;Oe++){const _e=gC(Oe,{baseMs:Se,maxMs:8e3,maxAttempts:Te});await new Promise(Fe=>setTimeout(Fe,_e));try{const at=(await te.sessions.getMessages(st,2)).messages.find(wt=>wt.role==="assistant");if(at?.content){const wt=oh(at);O(Pe,ht=>{const dt=[...ht],Qt=dt.findIndex(hi=>hi.id===Ze);return Qt>=0&&(dt[Qt]={...dt[Qt],text:wt.text,segments:wt.segments}),dt},ot),O(Pe,ht=>wa(ht,Ze,wt.id),ot);return}}catch{}}})(5,2e3);const Ve=M(Pe);P(Pe,ot??it),G.selectedAgent&&hs.applyLocalOptimistic(G.selectedAgent,ot??it,!1),k(Pe),[...e.current.values()].includes($e)||e.current.size===0?(r($e),p.delete(ot??Pe),g.current===Pe&&(U(Ve>0),Ve===0&&F([]))):p.delete(ot??Pe)}},[x,y,P,g,M,k,L,K,b,U,_,f,O,m]);return{send:Qe,stopSending:we,tryReattachActiveStream:Ge,loadSessionMessages:je}}function jI({value:s,onSelect:e,agentId:t,disabled:r}){const{t:i}=Pt("team"),[n,a]=S.useState(!1),[o,l]=S.useState("agent"),[h,d]=S.useState(""),[u,f]=S.useState(!1),[p,v]=S.useState([]),[b,g]=S.useState(null),O=S.useRef(null),m=S.useCallback(async()=>{f(!0);try{const _=await fetch("/api/settings/llm",{credentials:"include"});if(!_.ok)throw new Error(`HTTP ${_.status}`);const T=await _.json(),R=T.providers?.markus;if(R?.configured&&R.enabled!==!1&&(!R.models||R.models.length===0))try{const B=await fetch("/api/models/live/markus",{credentials:"include"});if(B.ok){const U=await B.json();U.models?.length&&(R.models=U.models)}}catch{}const L=[];for(const[B,U]of Object.entries(T.providers??{})){if(!U.configured||U.enabled===!1)continue;const F=(U.models??[]).filter(FC).map(X=>({id:X.id,name:X.name}));F.length!==0&&L.push({provider:B,displayName:U.displayName??B,models:F})}L.sort((B,U)=>B.displayName.localeCompare(U.displayName)),v(L);const M=B=>!B?.provider||!B.model?!1:!!L.find(F=>F.provider===B.provider)?.models.some(F=>F.id===B.model);let E=null;if(T.routingDefaultModel?.provider&&T.routingDefaultModel?.model)E={provider:T.routingDefaultModel.provider,model:T.routingDefaultModel.model};else if(T.defaultProvider){const B=T.providers?.[T.defaultProvider];B?.model&&(E={provider:T.defaultProvider,model:B.model})}if(E&&!M(E)){const B=L.find(F=>F.provider==="markus"),U=B?.models[0]?{provider:"markus",model:B.models[0].id}:L[0]?.models[0]?{provider:L[0].provider,model:L[0].models[0].id}:null;U?(E=U,te.settings.updateRouting({defaultProvider:U.provider,routingDefaultModel:U}).catch(()=>{})):E=null}g(E)}catch{v([])}finally{f(!1)}},[]);S.useEffect(()=>{m()},[m]),S.useEffect(()=>{n&&(l("agent"),d(""),m())},[n,m]),S.useEffect(()=>{if(!n)return;const _=T=>{O.current?.contains(T.target)||a(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[n]);const x=S.useMemo(()=>{const _=h.trim().toLowerCase();return p.map(T=>({...T,models:_?T.models.filter(R=>R.id.toLowerCase().includes(_)||(R.name?.toLowerCase().includes(_)??!1)||T.displayName.toLowerCase().includes(_)||T.provider.toLowerCase().includes(_)):T.models})).filter(T=>T.models.length>0)},[p,h]),y=S.useCallback(_=>!_?.provider||!_.model?!1:p.length===0?!0:!!p.find(R=>R.provider===_.provider)?.models.some(R=>R.id===_.model),[p]);S.useEffect(()=>{if(!s||p.length===0||y(s))return;const _=b&&y(b)?b:(()=>{const T=p.find(R=>R.provider==="markus");return T?.models[0]?{provider:"markus",model:T.models[0].id}:p[0]?.models[0]?{provider:p[0].provider,model:p[0].models[0].id}:null})();_&&e(_,"global",{resetCurrentAgent:!0})},[s,p,b,y,e]);const k=s&&y(s)?s:b,P=(k?.model?k.model.includes("/")?k.model.split("/").pop():k.model:"")||i("chatModel.title",{defaultValue:"Model"});return c.jsxs("div",{ref:O,className:"relative shrink-0",children:[c.jsxs("button",{type:"button",disabled:r,onClick:()=>a(_=>!_),className:"max-w-[110px] md:max-w-[180px] px-1.5 py-1 text-[12px] text-fg-secondary hover:text-fg-primary disabled:opacity-40 rounded-md hover:bg-surface-elevated transition-colors flex items-center gap-1",title:k?`${k.provider}: ${k.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[c.jsx("span",{className:"truncate",children:P}),c.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),n&&c.jsxs("div",{className:"absolute bottom-full right-0 mb-2 w-[300px] max-h-[360px] flex flex-col rounded-xl border border-border-default bg-surface-elevated shadow-xl z-50 overflow-hidden",children:[c.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[c.jsx("input",{autoFocus:!0,value:h,onChange:_=>d(_.target.value),placeholder:i("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-primary border border-border-default/50 outline-none focus:border-brand-500/50"}),c.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[c.jsx("span",{children:i("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),c.jsx(NO,{checked:o==="global",onChange:()=>l("global"),label:i("chatModel.applyGlobal",{defaultValue:"Apply to global"}),size:"sm",disabled:!t})]}),c.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[c.jsx("span",{children:i("chatModel.applyAgent",{defaultValue:"Apply to current agent"})}),c.jsx(NO,{checked:o==="agent",onChange:()=>l("agent"),label:i("chatModel.applyAgent",{defaultValue:"Apply to current agent"}),size:"sm",disabled:!t})]}),!t&&c.jsx("div",{className:"px-0.5 text-[10px] text-fg-tertiary",children:i("chatModel.noAgent",{defaultValue:"Select an agent to apply per-agent"})})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[u&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!u&&x.length===0&&c.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!u&&x.length>0&&c.jsx("div",{className:"px-3 pb-1 text-[10px] text-fg-tertiary",children:i("chatModel.chatOnlyHint",{defaultValue:"Only models with a chat interface are listed"})}),!u&&x.map(_=>c.jsxs("div",{className:"mb-1",children:[c.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:_.displayName}),_.models.slice(0,80).map(T=>{const R=k?.provider===_.provider&&k?.model===T.id;return c.jsxs("button",{type:"button",onClick:()=>{e({provider:_.provider,model:T.id},o),o==="global"&&g({provider:_.provider,model:T.id}),a(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-primary transition-colors ${R?"text-fg-primary":"text-fg-secondary"}`,children:[c.jsx("span",{className:"truncate flex-1",children:T.id}),R&&c.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:c.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${_.provider}:${T.id}`)})]},_.provider))]})]})]})}async function Lv(s,e,t,r){if(e==="agent"){if(!t)return;await te.agents.updateConfig(t,{llmConfig:{modelMode:"custom",primary:s.provider,defaultModel:s.model}});return}t&&r?.resetCurrentAgent!==!1&&await te.agents.updateConfig(t,{llmConfig:{modelMode:"default",primary:"",defaultModel:void 0}}).catch(()=>{}),await te.settings.updateRouting({defaultProvider:s.provider,routingDefaultModel:{provider:s.provider,model:s.model}})}const Nv="markus_team_sidebars_c";function Im(s,e){return s.id===it?e("page.newChat"):s.isMain?e("page.sessionMain"):s.title?.trim()||e("page.sessionConversation")}function Dv(s,e){const t=s.title?.trim(),r=!!t;return s.isMain?r?`${e("page.sessionMain")} · ${t}`:e("page.sessionMain"):Im(s,e)}const Bm=new Set;function RI(){return window.location.hash}function EI(s){return Bm.add(s),()=>{Bm.delete(s)}}typeof window<"u"&&window.addEventListener("hashchange",()=>Bm.forEach(s=>s()));function KI({initialAgentId:s,authUser:e,previewMode:t,previewData:r}={}){const{t:i,i18n:n}=Pt(["team","common"]),a=S.useMemo(()=>({today:i("page.dateToday"),yesterday:i("page.dateYesterday")}),[i]),o=Zm(Yt.TEAM),[l,h]=S.useState(r?.agents??[]),[d,u]=S.useState(r?.humans??[]),[f,p]=S.useState(!r),v=qm(),b=typeof navigator<"u"&&navigator.platform.toUpperCase().includes("MAC"),g=S.useSyncExternalStore(EI,RI),O=v&&(g.startsWith(`#${Yt.TEAM}/`)||g.startsWith("#chat/")),m=v&&g.match(/^#team\/t\/(.+)$/),x=v?m?"team":O?"chat":"roster":"roster",y=m?m[1]:null;S.useEffect(()=>(TO(v&&x==="chat"),()=>TO(!1)),[v,x]),S.useEffect(()=>(QO(Yt.TEAM,v&&x!=="roster"?1:0),()=>QO(Yt.TEAM,0)),[v,x]);const k=S.useCallback(()=>{window.location.hash=`${Yt.TEAM}/d`},[]),C=S.useCallback(w=>{window.location.hash=`${Yt.TEAM}/t/${w}`},[]);S.useEffect(()=>{if(!v)return;const w=()=>{qi(T.current)&&_("chat")};return window.addEventListener("popstate",w),()=>window.removeEventListener("popstate",w)},[v]);const[P,_]=S.useState("chat"),T=S.useRef("chat");T.current=P;const R=$O({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[L,M]=S.useState(()=>{try{return localStorage.getItem(Nv)==="1"}catch{return!1}}),E=S.useCallback(w=>{M(w);try{localStorage.setItem(Nv,w?"1":"0")}catch{}},[]),B=zh(),U=B?.leftCollapsed??!1,F=B?.rightPanel??null,X=B?.rightPanelTabs??[],ae=B?.activeRightPanelTabId??null,j=B?.rightPanelFullscreen??!1,W=F?"2xl:pr-8":"2xl:pr-[280px]",D=B?.setHostAvailable,V=B?.collapseRightPanelOnly??B?.toggleRightPanel,se=B?.openRightPanel,fe=400,z=320,re=6,[Z,A]=S.useState(typeof window<"u"?window.innerWidth:1440),[J,Y]=S.useState("auto"),oe=S.useRef(U);S.useEffect(()=>{oe.current!==U&&(oe.current=U,M(U))},[U]);const K=B?.keyboardPane??"content",pe=S.useRef(!1),je=S.useRef(K);S.useEffect(()=>{if(t||v||!o)return;const w=je.current;je.current=K,(K==="l1"||K==="l2")&&w!==K&&L&&(M(!1),B?.setLeftCollapsed(!1))},[K,t,v,o,L,B]),S.useEffect(()=>{if(t||v||!o)return;const w=Q=>{const $=B?.keyboardPane??"content";if($==="l0"||$==="l1"||$==="l2"||Q.metaKey||Q.ctrlKey||Q.altKey)return;if(Q.target instanceof HTMLElement){const H=Q.target.tagName;if(H==="INPUT"||H==="TEXTAREA"||H==="SELECT"||Q.target.isContentEditable||Q.target.closest(".xterm"))return}const I=Q.key.length===1?Q.key.toLowerCase():Q.key;I!=="h"&&I!=="ArrowLeft"||(Q.preventDefault(),L&&(E(!1),B?.setLeftCollapsed(!1)),B?.setKeyboardPane(pe.current?"l2":"l1"))};return document.addEventListener("keydown",w,!0),()=>document.removeEventListener("keydown",w,!0)},[t,v,o,B,L,E]),S.useEffect(()=>{if(D)return D(o&&!v),()=>D(!1)},[o,v,D]),S.useEffect(()=>t||v||!o?void 0:St.on("ui:right_panel",Q=>{const $=Q.payload;if($.action==="collapse"){V?.();return}if($.action!=="open"||!$.panel||!se)return;const I=$.panel;if(I.kind==="url"&&I.url){const H=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"url",url:I.url,title:I.title||I.url,browserId:H});return}if(I.kind==="file"&&I.path){se({kind:"file",path:I.path,title:I.title});return}if(I.kind==="terminal"){const H=I.terminalId||`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"terminal",terminalId:H,title:I.title||"Terminal",cwd:I.cwd});return}I.kind==="deliverable"&&I.deliverableId&&te.deliverables.get(I.deliverableId).then(H=>{H.deliverable&&se({kind:"deliverable",deliverable:H.deliverable})}).catch(()=>{})}),[t,v,o,V,se]);const we=S.useCallback(w=>{const Q=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;dn($=>[...$,{id:Q,...w}]),requestAnimationFrame(()=>Hs.current?.focus())},[]),Ge=S.useCallback(w=>{if(w)try{const Q=JSON.parse(w);if(!Array.isArray(Q)||Q.length===0)return;const $=Q.filter(H=>!!H&&typeof H.content=="string"&&H.content.trim().length>0);if($.length===0)return;const I=$.map(H=>({id:`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`,label:H.label?.trim()||"Context",content:H.content}));dn(H=>[...H,...I]),requestAnimationFrame(()=>{const H=Hs.current;H&&(H.focus(),H.setSelectionRange(H.value.length,H.value.length))})}catch{}},[]),[Qe,Ee]=S.useState(()=>{if(t)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),ye=$O({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),G=S.useRef(null),[qe,He]=S.useState(!1),[Ye,pt]=S.useState(!1),xt=S.useCallback(()=>{qe?pt(w=>!w):Ee(w=>{const Q=!w;try{localStorage.setItem("markus_team_panel_visible",String(Q))}catch{}return Q})},[qe]);S.useEffect(()=>{if(v)return;const w=G.current;if(!w)return;const Q=new ResizeObserver(([$])=>{if(!$)return;const I=$.contentRect.width;if(A(I),!t){const H=I-R.width-ye.width;He(H<400)}});return Q.observe(w),()=>Q.disconnect()},[v,t,R.width,ye.width]);const bt=Qe&&!qe&&!Ye,vt=L?0:R.width+re+(bt?ye.width+re:0),Pe=Math.max(0,Z-vt-re-8),At=Math.min(fe,Math.floor(Pe*.4)),Ft=Math.max(0,Pe-At),Es=Math.min(Math.round(Pe/2),Ft),yt=Math.max(0,Math.min(J==="auto"?Es:J,Ft)),Bt=S.useRef(!1);S.useEffect(()=>{const w=(B?.rightPanel??null)!==null;w&&!Bt.current&&(M(!0),Y("auto")),Bt.current=w},[B?.rightPanel]);const ut=S.useRef(yt);ut.current=yt;const Ze=S.useRef(Ft);Ze.current=Ft;const Xt=S.useCallback(w=>{w.preventDefault();const Q=w.clientX,$=ut.current,I=ie=>{const ne=$+(Q-ie.clientX),Ce=Ze.current,Le=Math.min(z,Ce);Y(Math.max(Le,Math.min(Ce,ne)))},H=()=>{document.removeEventListener("mousemove",I),document.removeEventListener("mouseup",H),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",I),document.addEventListener("mouseup",H),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);S.useEffect(()=>{if(!Ye)return;const w=Q=>{Q.target.closest("[data-l2-floating]")||pt(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[Ye]);const[ot,Mt]=S.useState(null),[us,he]=S.useState(!1),ce=S.useRef(null);S.useEffect(()=>{if(!us)return;const w=$=>{ce.current&&!ce.current.contains($.target)&&he(!1)},Q=$=>{$.key==="Escape"&&he(!1)};return document.addEventListener("mousedown",w),document.addEventListener("keydown",Q),()=>{document.removeEventListener("mousedown",w),document.removeEventListener("keydown",Q)}},[us]);const[$e,Xe]=S.useState(),[de,De]=S.useState(),[ve,st]=S.useState(),[ze,Ve]=S.useState(!1),[ee,Te]=S.useState(""),[Se,Oe]=S.useState(!1),[_e,Fe]=S.useState(""),at=S.useRef(null),wt=S.useRef(null),ht=S.useCallback((w,Q)=>{const $=w?ih[w]:void 0,I=$?"overview":w;De($),Xe(I),st(Q),v?(_("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):_(I??"overview")},[v]);S.useCallback(w=>{w==="profile"?ht():qi(T.current)?history.back():_("chat")},[ht]);const dt=S.useCallback((w,Q)=>{$t("direct"),Us(w),v&&k(),ht(Q?.tab,Q?.highlightMailboxId),Mt(null)},[v,k,ht]),Qt=S.useCallback((w,Q)=>{const $=l.find(I=>I.name.toLowerCase()===w.toLowerCase());if($){const I=Q.target.getBoundingClientRect();Mt({agentId:$.id,top:I.bottom,left:I.left})}},[l]),hi=S.useMemo(()=>l.map(w=>w.name),[l]),[le,$t]=S.useState(()=>r?.chatMode??(s?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[ge,Us]=S.useState(()=>s??localStorage.getItem("markus_chat_agent")??""),[gt,Bs]=S.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[_t,ln]=S.useState(""),Fo=500,cn=S.useRef(new Set),Tl=w=>{if(cn.current.add(w),cn.current.size>Fo){const Q=Math.floor(Fo*.2),$=cn.current.values();for(let I=0;I<Q;I++){const H=$.next().value;H&&cn.current.delete(H)}}},Ql=S.useMemo(()=>{if(r?.channelMessages){const w=r.activeChannel??"custom:general";return r.channelMessages.filter(Q=>Q.channel===w).map(Q=>Mn(Q))}},[]),{manager:Os,messages:rs,setMessages:_s,sending:xr,setSending:Uo,activities:$l,setActivities:zr,activeSessionBuffer:xs,actBuffers:Vn,sessionTabsBuffer:jl,readConvMsgs:is,writeConvMsgs:Qr,setActiveSession:hn,currentConvKeyRef:jt,updateConvMsgs:br,updateConvMsgsRaf:Rl,appendConvActivity:El,beginLoad:Al,beginStream:$i,endStream:q,resetConv:me,abortStream:be,loadAndDisplay:Ie,incrementSending:Ke,decrementSending:Je,isSendingFor:lt,setStreamSession:Rt,clearStreamSession:Ot,getStreamSession:cs,saveSessionToCache:bs,restoreSessionFromCache:ir}=QI(Ql),[zt,ks]=S.useState(""),[vs,es]=S.useState(null),[nr,dn]=S.useState([]),[qt,qr]=S.useState(!!r?.streamLastMessage),un=S.useRef(null),R_=400;S.useEffect(()=>(xr?(un.current&&(clearTimeout(un.current),un.current=null),qr(!0)):qt&&(un.current=setTimeout(()=>{qr(!1),un.current=null},R_)),()=>{un.current&&clearTimeout(un.current)}),[xr]);const cd=S.useRef({fullText:"",timers:[]});S.useEffect(()=>{if(!t||!r?.streamLastMessage||rs.length===0)return;const w=rs[rs.length-1];if(!w||w.sender!=="agent")return;const Q=w.text;cd.current.fullText=Q;const $=cd.current.timers;function I(){let ie=0;_s(Ce=>Ce.map((Le,xe)=>xe===Ce.length-1?{...Le,text:""}:Le)),qr(!0);const ne=setInterval(()=>{if(ie+=1+Math.floor(Math.random()*2),ie>=Q.length){clearInterval(ne),_s(xe=>xe.map((ke,Ae)=>Ae===xe.length-1?{...ke,text:Q}:ke));const Ce=setTimeout(()=>qr(!1),800);$.push(Ce);const Le=setTimeout(I,6e3);$.push(Le)}else _s(Ce=>Ce.map((Le,xe)=>xe===Ce.length-1?{...Le,text:Q.slice(0,ie)}:Le))},30);$.push(ne)}const H=setTimeout(I,1500);return $.push(H),()=>{$.forEach(ie=>clearTimeout(ie)),cd.current.timers=[]}},[]);const[E_,cg]=S.useState(!1),[hd,hg]=S.useState(!1),[A_,dg]=S.useState(!1);S.useEffect(()=>{if(!hd){dg(!1);return}const w=setTimeout(()=>dg(!0),250);return()=>clearTimeout(w)},[hd]);const[fn,Zr]=S.useState(!0),[M_,dd]=S.useState(!0),ud=S.useRef(0),[or,Ml]=S.useState([]),[ug,fg]=S.useState(null),fd=S.useRef(null),Hs=S.useRef(null),[L_,ji]=S.useState(null);S.useEffect(()=>{if(!ge){ji(null);return}let w=!1;return te.agents.get(ge).then(Q=>{if(w)return;const $=Q.effectiveModel;ji($?.provider&&$?.model?{provider:$.provider,model:$.model}:null)}).catch(()=>{w||ji(null)}),()=>{w=!0}},[ge]);const md=S.useRef(!1),Ho=S.useCallback(()=>{const w=Hs.current;if(!w)return;const Q=md.current,$=Q?36:52,I=MO(Q);w.style.height="auto";const H=Math.max($,Math.min(w.scrollHeight,I));w.style.height=`${H}px`,w.style.overflowY=H>=I?"auto":"hidden"},[]);S.useEffect(()=>{const w=requestAnimationFrame(()=>Ho());return()=>cancelAnimationFrame(w)},[zt,or.length,Ho]);const pd=w=>{try{const Q=localStorage.getItem(`markus_closed_tabs_${w}`);return Q?new Set(JSON.parse(Q)):new Set}catch{return new Set}},N_=(w,Q)=>{const $=pd(w);$.add(Q);try{localStorage.setItem(`markus_closed_tabs_${w}`,JSON.stringify([...$]))}catch{}},D_=(w,Q)=>{const $=pd(w);if($.delete(Q))try{localStorage.setItem(`markus_closed_tabs_${w}`,JSON.stringify([...$]))}catch{}},mg=w=>{try{return localStorage.getItem(`markus_active_session_${w}`)}catch{return null}},Yo=(w,Q)=>{if(w)try{Q&&Q!==it?localStorage.setItem(`markus_active_session_${w}`,Q):localStorage.removeItem(`markus_active_session_${w}`)}catch{}},[$r,Ri]=S.useState([]),[I_,Ll]=S.useState(0),[pg,Nl]=S.useState(1),[Dl,Il]=S.useState(!1),[Bl,gg]=S.useState(!1),[et,Ei]=S.useState(null),[Go,mn]=S.useState(!1),[Og,pn]=S.useState(!1),[gd,xg]=S.useState(null),[Od,xd]=S.useState(""),[bg,bd]=S.useState([]),[gn,Wl]=S.useState(null),[B_,vg]=S.useState(null),[Ko,vd]=S.useState([]),[On,Jo]=S.useState(null),[W_,yg]=S.useState(null),Sg=S.useRef(new Set),[wg,yd]=S.useState([]),[jr,ea]=S.useState(null),Ai=jr?jr.items[jr.index]??null:null,[X_,_g]=S.useState(null),[kg,Sd]=S.useState([]),[Ws,z_]=S.useState([]),Ys=w=>{z_(Q=>{const $=typeof w=="function"?w(Q):w,I=new Set,H=$.filter(ie=>I.has(ie.id)?!1:(I.add(ie.id),!0));return H.some(ie=>ie.isMain)?[...H.filter(ie=>ie.isMain),...H.filter(ie=>!ie.isMain)]:H})},Cg=S.useRef(null);S.useEffect(()=>{if(!et)return;const w=Cg.current;if(!w)return;const Q=w.querySelector(`[data-session-tab-id="${CSS.escape(et)}"]`);if(!Q)return;const $=requestAnimationFrame(()=>{Q.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame($)},[et,Ws.length]);const Xl=S.useRef(null),wd=S.useRef(null),[Cs,ta]=S.useState(r?.groupChats??[]),_d=S.useRef(Cs);_d.current=Cs;const Pg=S.useRef(null),[kd,Ps]=S.useState(!1),[Cd,Fn]=S.useState(!1),[zl,Pd]=S.useState(""),[q_,sa]=S.useState(-1),[Z_,ql]=S.useState([]),[V_,Tg]=S.useState(!1),Td=S.useRef(void 0),[As,Qg]=S.useState(r?.teams??[]),[Qd,F_]=S.useState(!!r),[U_,H_]=S.useState([]),[$d,$g]=S.useState([]),[Y_,G_]=S.useState(null),[LI,NI]=S.useState(!1),[DI,II]=S.useState(""),[Un,ra]=S.useState(!1),[jg,K_]=S.useState(""),[ia,Hn]=S.useState(0),[Yn,Zl]=S.useState(!1),[Rg,J_]=S.useState(""),[jd,na]=S.useState(0),[Rd,ek]=S.useState([]),Eg=S.useRef(!1),Ed=S.useCallback(()=>{Eg.current||(Eg.current=!0,(async()=>{try{const{skills:w}=await te.skills.list();ek(w.map(Q=>({name:Q.name,description:Q.description??Q.name})))}catch{}})())},[]);S.useEffect(()=>{Ed()},[Ed]);const xn=Rg?Rd.filter(w=>w.name.toLowerCase().includes(Rg.toLowerCase())):Rd,[tk,sk]=S.useState([]),Ag=S.useRef(!1),rk=S.useCallback(()=>{Ag.current||(Ag.current=!0,(async()=>{const w=[];try{const[Q,$,I,H,ie]=await Promise.all([te.projects.list().catch(()=>({projects:[]})),te.requirements.list({lean:!0}).catch(()=>({requirements:[]})),te.tasks.list({pageSize:20,lean:!0}).catch(()=>({tasks:[]})),te.deliverables.search({limit:100}).catch(()=>({results:[]})),te.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const ne of Q.projects)w.push({id:ne.id,name:ne.name,entityType:"project",role:ne.status});for(const ne of $.requirements)w.push({id:ne.id,name:ne.title,entityType:"requirement",role:ne.priority});for(const ne of I.tasks)w.push({id:ne.id,name:ne.title,entityType:"task",role:ne.status});for(const ne of H.results)w.push({id:ne.id,name:ne.title,entityType:"deliverable",role:ne.type});for(const ne of ie.teams)try{const Ce=await te.workflows.list(ne.id);for(const Le of Ce.workflows)w.push({id:Le.name,name:Le.displayName||Le.name,entityType:"workflow",role:`v${Le.version}`})}catch{}}catch{}sk(w)})())},[]),ns=le==="channel"?Cs.find(w=>w.channelKey===gt)?.teamId:void 0,ik=S.useRef(null),Vr=S.useRef(null),Mg=S.useRef(void 0),oa=S.useCallback((w,Q)=>{Ei(Q),w&&(Q===null?Os.clearActiveSession(w):Os.setActiveSession(w,Q))},[Ei,Os]),Lg=S.useMemo(()=>Ea(le,ge,gt,_t),[le,ge,gt,_t]);ah();const aa=hs.isStreaming(et),bn=S.useMemo(()=>ho(Lg,et),[Lg,et]),Xs=S.useRef(bn);Xs.current=bn;const[la,nk]=S.useState(bn);if(S.useEffect(()=>{_a.save(la,{text:zt,images:or,context:nr,replyTo:vs})},[zt,la,or,nr,vs]),la!==bn){const w={text:zt,images:or,context:nr,replyTo:vs};if(zt!==_a.peek(la).text)_a.save(bn,w);else{_a.save(la,w);const Q=_a.get(bn);ks(Q.text),Ml(Q.images),dn(Q.context),es(Q.replyTo)}nk(bn)}const ys=S.useRef(null),Ad=S.useRef(null),Mi=S.useRef(null),Md=S.useRef(null),Vl=S.useRef(0),Fl=S.useRef([]),Gn=S.useRef(null),Ng=S.useRef([]),Ld=S.useRef(void 0),Ul=S.useRef(null),vn=S.useCallback(()=>Os.getActiveSession(jt.current)??jt.current,[Os]),Li=S.useCallback((w,Q)=>{w&&(Os.setWindowBounds(w,Q),w===vn()&&cg(Q.hasMore))},[Os,vn]);S.useEffect(()=>{cg(Os.getWindowBounds(vn()).hasMore)},[Os,vn,le,ge,gt,_t,et]),S.useEffect(()=>{if(!Go)return;const w=Q=>{wd.current&&!wd.current.contains(Q.target)&&Xl.current&&!Xl.current.contains(Q.target)&&mn(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[Go]);const Hl=(w,Q)=>{if(!Q||w===Q)return`notes:${w}`;const[$,I]=[w,Q].sort();return`dm:${$}:${I}`};S.useEffect(()=>{localStorage.setItem("markus_chat_mode",le)},[le]),S.useEffect(()=>{localStorage.setItem("markus_chat_agent",ge)},[ge]),S.useEffect(()=>{localStorage.setItem("markus_chat_channel",gt)},[gt]),S.useEffect(()=>{let w=!1;if(t||!ge||le!=="direct"){ji(null);return}return te.agents.get(ge).then(Q=>{if(w)return;const $=Q.config?.llmConfig;ji($?.modelMode==="custom"&&$.primary&&$.defaultModel?{provider:$.primary,model:$.defaultModel}:null)}).catch(()=>{w||ji(null)}),()=>{w=!0}},[ge,le,t]);const{counts:Nd,sessionAgentMap:ca,markRead:ha,setActiveKey:ok,clearActiveKey:ak}=OC({enabled:!t}),Yl=S.useMemo(()=>{const w={};for(const[Q,$]of Object.entries(Nd))Q.startsWith("channel:")&&(w[Q.slice(8)]=$);return w},[Nd]),Dd=xC(ca,Nd);S.useEffect(()=>{let w=0;for(const Q of Dd.values())w+=Q;for(const Q of Object.values(Yl))w+=Q;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:w}}))},[Dd,Yl]);const Gl=Dd,lk=S.useCallback(async w=>{for(const[Q,$]of Object.entries(ca))$===w&&ha(`session:${Q}`)},[ca,ha]);S.useEffect(()=>{if(t||!((!v||x==="chat")&&P==="chat"))return;if(le==="direct"&&ge&&lk(ge),le==="channel"&>)ha(`channel:${gt}`);else if(le==="direct"&&et)ha(`session:${et}`);else if(le==="dm"&&_t){const $=`dm:${[e?.id,_t].sort().join(":")}`;ha(`channel:${$}`)}const Q=[];if(le==="direct"&&et){Q.push(`session:${et}`);for(const[$,I]of Object.entries(ca))I===ge&&Q.push(`session:${$}`)}else le==="channel"&>?Q.push(`channel:${gt}`):le==="dm"&&_t&&e?.id&&Q.push(`channel:dm:${[e.id,_t].sort().join(":")}`);for(const $ of Q)ok($);return()=>{for(const $ of Q)ak($)}},[t,le,gt,et,_t,ge,x,P,ca]);const ar=S.useCallback(()=>te.agents.list().then(w=>h(w.agents)).catch(()=>{}),[]),ck=S.useCallback((w,Q)=>{w&&h($=>$.map(I=>I.id===w?{...I,avatarUrl:Q}:I))},[]),Gs=S.useCallback(()=>te.teams.list().then(w=>{Qg(w.teams),F_(!0)}).catch(()=>{}),[]),Kn=S.useCallback(()=>te.groupChats.list().then(w=>ta(w.chats)).catch(()=>{}),[]),hk=S.useMemo(()=>au(ar,3e3),[ar]),Kl=S.useMemo(()=>au(Gs,5e3),[Gs]),Id=S.useMemo(()=>au(Kn,3e3),[Kn]),da=S.useCallback(()=>{te.users.list(e?.orgId).then(w=>u(w.users)).catch(()=>{})},[e?.orgId]);S.useEffect(()=>{v&&(x!=="team"||!y||jO(y,As.map(w=>w.id),Qd)==="missing"&&(window.location.hash=Yt.TEAM))},[v,x,y,As,Qd]),S.useEffect(()=>{t||(Promise.all([ar(),Gs()]).finally(()=>p(!1)),da(),te.tasks.list().then(w=>$g(w.tasks)).catch(()=>{}),te.externalAgents.list().then(w=>H_(w.agents)).catch(()=>{}),Kn())},[t,da]),S.useEffect(()=>{if(!(!t||!r)&&(h(r.agents??[]),u(r.humans??[]),Qg(r.teams??[]),ta(r.groupChats??[]),r.channelMessages)){const w=r.activeChannel??"custom:general";_s(r.channelMessages.filter(Q=>Q.channel===w).map(Q=>Mn(Q)))}},[t,r]),S.useEffect(()=>{M2()},[]),S.useEffect(()=>{if(t||!o)return;const w=()=>{const ie=ge,ne=Ws.map(Ce=>Ce.id).filter(Ce=>Ce!==it);et&&et!==it&&!ne.includes(et)&&ne.push(et),ie&&ne.length>0&&L2(ie,ne)};let Q=null;const $=()=>{Q||(Q=setInterval(w,6e4))},I=()=>{Q&&clearInterval(Q),Q=null},H=()=>{document.hidden?I():(w(),$())};return document.addEventListener("visibilitychange",H),document.hidden||$(),w(),()=>{I(),document.removeEventListener("visibilitychange",H)}},[t,o,Ws,ge,et]),S.useEffect(()=>{if(t||!o)return;ar(),Gs();const w=setInterval(ar,3e4),Q=setInterval(Gs,6e4),$=St.on("agent:update",Ae=>{const Ue=Ae?.payload;if(Ue?.agentId){const ct=Ue.status,Kt=Ue.currentActivity;h(as=>as.map(Ht=>{if(Ht.id!==Ue.agentId)return Ht;const yr={...Ht};return ct&&(yr.status=ct),Kt!==void 0&&(yr.currentActivity=Kt),yr}))}hk(),Kl()}),I=St.on("team:update",()=>{Kl(),Id()}),H=St.on("agent:removed",Kl),ie=St.on("chat:group_created",()=>{Kn(),Gs(),ar()}),ne=St.on("chat:group_updated",Id),Ce=St.on("chat:group_deleted",()=>{Id(),Kl()}),Le=St.on("task:update",Ae=>{const Ue=Ae?.payload;Ue?.taskId&&$g(ct=>ct.map(Kt=>Kt.id===Ue.taskId?{...Kt,status:Ue.status??Kt.status}:Kt))}),xe=St.on("approval:resolved",Ae=>{const Ue=Ae?.payload?.approvalId;Ue&&(Wl(ct=>ct&&ct.id===Ue?null:ct),Jo(ct=>ct&&ct.id===Ue?null:ct))}),ke=()=>{ar(),Gs(),da()};return window.addEventListener("markus:data-changed",ke),()=>{clearInterval(w),clearInterval(Q),$(),I(),H(),ie(),ne(),Ce(),Le(),xe(),window.removeEventListener("markus:data-changed",ke)}},[t,o,da]),S.useEffect(()=>{if(t)return;const w=xe=>{const ke=xe.detail;if(MC(ke.page)===Yt.TEAM){if(ke.params?.agentId){if(ke.params.profileTab)dt(ke.params.agentId,{tab:ke.params.profileTab});else if($t("direct"),Us(ke.params.agentId),_("chat"),v&&k(),ke.params.sessionId){const Ae=ke.params.sessionId;setTimeout(async()=>{try{const{sessions:Ue}=await te.sessions.listByAgent(ke.params.agentId,20),ct=Ue.find(Kt=>Kt.id===Ae);ct&&Ii(ct)}catch{}},300)}}if(ke.params?.selectAgent&&($t("direct"),Us(ke.params.selectAgent),_("chat"),v&&k()),ke.params?.openDeliverable){const Ae=ke.params.openDeliverable;localStorage.removeItem("markus_nav_openDeliverable"),v?Lr.navigate(Yt.DELIVERABLES,{openDeliverable:Ae}):se&&te.deliverables.get(Ae).then(Ue=>{Ue.deliverable&&se({kind:"deliverable",deliverable:Ue.deliverable})}).catch(()=>{})}if(ke.params?.prefillMessage){const Ae=ke.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),ke.params?.autoSend==="true"?setTimeout(()=>Mg.current?.(Ae),300):(ks(Ae),setTimeout(()=>{const Ue=Hs.current;Ue&&(Ue.focus(),Ue.setSelectionRange(Ue.value.length,Ue.value.length))},100))}if(ke.params?.chatChips){const Ae=ke.params.chatChips;localStorage.removeItem("markus_nav_chatChips"),_("chat"),Ge(Ae)}if(ke.params?.dm&&($t("dm"),ln(ke.params.dm),_("chat"),v&&k()),ke.params?.channel&&($t("channel"),Bs(ke.params.channel),_("chat"),v&&k()),ke.params?.selectTeam){const Ae=ke.params.selectTeam;if(v)C(Ae);else{const Ue=_d.current.find(ct=>ct.type==="team"&&ct.teamId===Ae);$t("channel"),Bs(Ue?.channelKey??`group:${Ae}`),_("chat"),Ps(!1),Ee(!0)}}ke.params?.openHire}},Q=localStorage.getItem("markus_nav_agentId");if(Q){localStorage.removeItem("markus_nav_agentId");const xe=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),$t("direct"),Us(Q),xe?dt(Q,{tab:xe}):(_("chat"),v&&k())}const $=localStorage.getItem("markus_nav_dm");$&&(localStorage.removeItem("markus_nav_dm"),$t("dm"),ln($),_("chat"),v&&k());const I=localStorage.getItem("markus_nav_channel");I&&(localStorage.removeItem("markus_nav_channel"),$t("channel"),Bs(I),_("chat"),v&&k());const H=localStorage.getItem("markus_nav_prefillMessage");H&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),_("chat"),ks(H),setTimeout(()=>{const xe=Hs.current;xe&&(xe.focus(),xe.setSelectionRange(xe.value.length,xe.value.length))},150));const ie=localStorage.getItem("markus_nav_chatChips");ie&&(localStorage.removeItem("markus_nav_chatChips"),_("chat"),Ge(ie));const ne=localStorage.getItem("markus_nav_openDeliverable");ne&&(localStorage.removeItem("markus_nav_openDeliverable"),v?Lr.navigate(Yt.DELIVERABLES,{openDeliverable:ne}):se&&te.deliverables.get(ne).then(xe=>{xe.deliverable&&se({kind:"deliverable",deliverable:xe.deliverable})}).catch(()=>{}));const Ce=localStorage.getItem("markus_nav_selectAgent");Ce&&(localStorage.removeItem("markus_nav_selectAgent"),$t("direct"),Us(Ce),_("chat"),v&&k());const Le=localStorage.getItem("markus_nav_selectTeam");if(Le)if(localStorage.removeItem("markus_nav_selectTeam"),v)C(Le);else{const xe=_d.current.find(ke=>ke.type==="team"&&ke.teamId===Le);$t("channel"),Bs(xe?.channelKey??`group:${Le}`),_("chat"),Ps(!1),Ee(!0)}return window.addEventListener("markus:navigate",w),()=>window.removeEventListener("markus:navigate",w)},[t]),S.useEffect(()=>{const w=Pg.current;if(!w)return;const Q=Cs.find($=>$.type==="team"&&$.teamId===w);Pg.current=null,$t("channel"),Bs(Q?.channelKey??`group:${w}`),_("chat"),Ps(!1),Ee(!0)},[Cs,As]),S.useEffect(()=>{if(t&&r?.chatMode==="channel"||l.length===0||ge&&l.some($=>$.id===ge))return;const w=localStorage.getItem("markus_nav_after_remove");if(w&&(localStorage.removeItem("markus_nav_after_remove"),w.startsWith("channel:"))){$t("channel"),Bs(w.slice(8)),_("chat");return}const Q=l.find($=>!$.teamId&&$.role?.toLowerCase()==="secretary")??l.find($=>$.role?.toLowerCase()==="secretary")??l.find($=>$.name?.toLowerCase().includes("secretary"));Q?($t("direct"),Us(Q.id),_("chat")):l.length>0&&($t("direct"),Us(l[0].id),_("chat"))},[l,ge]);const Jn=S.useRef(!1),yn=S.useRef(!1),ua=S.useRef(0),Bd=S.useRef("none"),Wd=S.useRef(0),Jl=S.useRef(0),di=S.useRef(null),Xd=S.useRef(null),Dg=S.useRef([]),zd=S.useRef(0),[dk,Sn]=S.useState(!1),eo=S.useRef(0),[Ig,fa]=S.useState(0),to=S.useCallback(()=>performance.now()<ua.current,[]),Ni=S.useCallback(()=>O2({takeover:yn.current,gestureActive:to()}),[to]),lr=S.useCallback(()=>{yn.current=!1,ua.current=0,Bd.current="none",zd.current=0,Jl.current+=1,Jn.current=!1,Sn(!1),eo.current=0,fa(0)},[]),Fr=S.useCallback(()=>{yn.current||(yn.current=!0,Jl.current+=1,Jn.current=!1,di.current!==null&&(cancelAnimationFrame(di.current),di.current=null),Sn(!0))},[]),ec=S.useCallback(w=>{ua.current=performance.now()+du,w!=="none"&&(Bd.current=w);const Q=Vr.current;x2(w,!!Q&&qO(Q))&&Fr()},[Fr]),tc=S.useCallback(w=>{const Q=Vr.current;if(!Q)return;const $=Q.scrollTop-Wd.current;Wd.current=Q.scrollTop;const I=g2({takeover:yn.current,gestureActive:to(),gestureDirection:Bd.current,scrollable:qO(Q),distance:Wc(Q),deltaScrollTop:$,programmatic:w?.programmatic??Jn.current,intentPending:ys.current!==null});I==="handover"?Fr():I==="resume"?lr():I==="follow"?(Sn(!1),eo.current=0,fa(0)):yn.current&&Sn(!0)},[to,Fr,lr]);S.useEffect(()=>{const w=Vr.current;if(!w)return;let Q=null;const $=ke=>{ec(d2(ke.deltaX,ke.deltaY))},I=ke=>{Q=ke.touches[0]?.clientY??null,ua.current=performance.now()+du},H=ke=>{const Ae=ke.touches[0]?.clientY;if(Ae==null)return;const Ue=p2(Q,Ae);Q=Ae,ec(Ue)},ie=()=>{Q=null},ne=ke=>{Vm(ke.target)||ec(m2(ke.key))},Ce=ke=>{const Ae=w.getBoundingClientRect();ke.clientX-Ae.left<w.clientWidth||(ua.current=performance.now()+du)},Le=()=>{tc()};w.addEventListener("wheel",$,{passive:!0}),w.addEventListener("touchstart",I,{passive:!0}),w.addEventListener("touchmove",H,{passive:!0}),w.addEventListener("touchend",ie,{passive:!0}),w.addEventListener("pointerdown",Ce,{passive:!0}),w.addEventListener("scroll",Le,{passive:!0}),document.addEventListener("keydown",ne);const xe=typeof ResizeObserver<"u"?new ResizeObserver(()=>tc()):null;return xe?.observe(w),Wd.current=w.scrollTop,tc(),()=>{w.removeEventListener("wheel",$),w.removeEventListener("touchstart",I),w.removeEventListener("touchmove",H),w.removeEventListener("touchend",ie),w.removeEventListener("pointerdown",Ce),w.removeEventListener("scroll",Le),document.removeEventListener("keydown",ne),xe?.disconnect()}},[x,tc,ec]);const qd=S.useMemo(()=>new Set(kg),[kg]),os=S.useMemo(()=>{const w=le==="channel"?rs:rs.filter(I=>!I.isActivityLog),Q=qd.size===0?w:w.filter(I=>!(I.isNotification&&qd.has(I.id))),$=t&&qt?Q.length-1:-1;return Q.filter((I,H)=>bC(I,H===$||!!I.isStreaming&&aa))},[rs,le,qd,aa,t,qt]);S.useEffect(()=>{md.current=P==="chat"&&os.length>0,Ho()},[P,os.length,Ho]);const so=n2({count:os.length,getScrollElement:()=>Vr.current,getItemKey:w=>os[w]?.id??w,estimateSize:w=>{const Q=os[w];return Q?Q.segments&&Q.segments.length>0?300:Q.text.length>500?200:120:120},overscan:8});so.shouldAdjustScrollPositionOnItemSizeChange=(w,Q,$)=>lu()||ys.current?.priority==="jump"?!1:w.start<($.scrollOffset??0);const cr=S.useCallback((w="instant")=>{if(!Ni()||performance.now()<zd.current)return;const Q=Vr.current;if(!Q)return;const $=++Jl.current,I=()=>$===Jl.current&&Ni();if(w==="smooth"){zd.current=performance.now()+c2,Q.scrollTo({top:Q.scrollHeight,behavior:"smooth"});return}di.current!==null&&(cancelAnimationFrame(di.current),di.current=null),Jn.current=!0;let H=0;const ie=()=>{if(di.current=null,!I()){Jn.current=!1;return}if(Q.scrollTop=Q.scrollHeight,H+=1,H<l2&&Wc(Q)>1){di.current=requestAnimationFrame(ie);return}Jn.current=!1};Q.scrollTop=Q.scrollHeight,di.current=requestAnimationFrame(ie)},[Ni]),wn=S.useCallback(w=>{const Q=Vr.current;!Q||!w||Q.scrollHeight<=Q.clientHeight||FO.save(w,v2(VO(Q),Q))},[]),_n=S.useCallback(()=>{Vl.current+=1;for(const w of Fl.current)clearTimeout(w);Fl.current=[]},[]),ro=S.useCallback(()=>{ys.current=null,_n()},[_n]),Bg=S.useCallback(()=>{lr(),ro(),Xd.current!==null&&cancelAnimationFrame(Xd.current);for(const w of Dg.current)clearTimeout(w);cr("instant"),Xd.current=requestAnimationFrame(()=>cr("instant")),Dg.current=[60,160,320].map(w=>setTimeout(()=>cr("instant"),w))},[lr,ro,cr]),Zd=S.useCallback(w=>{const Q=ys.current;if(!Q||Q.key!==w)return!0;if(Xs.current!==w||Q.priority!=="prepend"&&to())return ys.current=null,!0;const $=Vr.current;if(!$)return!0;if(lu())return!1;const{anchor:I}=Q;if(I.kind==="bottom"){uu(Q.priority)&&lr(),$.scrollTop=$.scrollHeight;const Ue=Wc($)<=1,ct=YO(Ue,Q.prevSettled);return Q.prevSettled=Ue,ct?(ys.current=null,!0):!1}const H=P2(Q.at,performance.now()),ie=w2(VO($),$,I.id,I.delta),ne=ie===null&&!H&&(is(Q.bufferId)??[]).some(Ue=>Ue.id===I.id),Ce=ie!==null&&Math.abs(ie)<=1,Le=YO(Ce,Q.prevSettled),xe=ie===null&&!ne,ke=Os.getWindowBounds(Q.bufferId).hasMore,Ae=T2({priority:Q.priority,rendered:ie!==null,stale:H,stable:Le,absent:xe,canLoadMore:ke});switch(Q.prevSettled=ie!==null?Ce:null,uu(Q.priority)&&Ae!=="release-bottom"&&Ae!=="release-hold"&&Fr(),Ae){case"apply":return zi("intent:apply",{id:I.id,priority:Q.priority,correction:ie}),ys.current=null,!0;case"refine":return ie!==null&&Math.abs(ie)>1&&($.scrollTop+=ie),ie!==null&&Math.abs(ie)>8&&zi("intent:refine",{id:I.id,priority:Q.priority,correction:ie}),!1;case"release-bottom":return zi("intent:release-bottom",{id:I.id,priority:Q.priority}),ys.current=null,uu(Q.priority)&&lr(),$.scrollTop=$.scrollHeight,!0;case"release-hold":return zi("intent:release-hold",{id:I.id,priority:Q.priority,stale:H,absent:xe,canLoadMore:ke,bufferId:Q.bufferId}),ys.current=null,console.warn("[scroll-intent] 目标行始终没能渲染出来,放弃定位(视口保持在原地)",{priority:Q.priority,anchor:I}),!0;default:{const Ue=Ng.current.findIndex(ct=>ct.id===I.id);if(Ue>=0){const ct=so.getOffsetForIndex(Ue,"start");ct&&($.scrollTop=ct[0]+I.delta)}else Ld.current?.();return!1}}},[so,to,Fr,lr,is]),sc=S.useCallback(()=>{const w=ys.current;if(!w)return;const Q=w.key;_n();const $=Vl.current,I=ie=>{Fl.current.push(setTimeout(()=>{$===Vl.current&&ys.current?.key===Q&&(Zd(Q)||I(HO))},ie))},H=[0,60,160,320,560,900];H.forEach((ie,ne)=>{const Ce=ne===H.length-1,Le=()=>{if($!==Vl.current)return;!Zd(Q)&&Ce&&I(HO)};ie===0?requestAnimationFrame(Le):Fl.current.push(setTimeout(Le,ie))})},[Zd,_n]),io=S.useCallback((w,Q,$="restore",I)=>{if(!w)return!1;const H=ys.current;return k2(H,{key:w,priority:$})?(ys.current={key:w,bufferId:I??vn(),anchor:Q,at:performance.now(),priority:$,prevSettled:null},sc(),!0):!1},[vn,sc]),ma=S.useCallback(w=>{w&&io(w,FO.get(w)??{kind:"bottom"})},[io]),uk=S.useCallback(()=>{ys.current||(Gn.current!==null&&clearTimeout(Gn.current),Gn.current=setTimeout(()=>{Gn.current=null,wn(Xs.current)},200))},[wn]);Ng.current=os,S.useLayoutEffect(()=>()=>{wn(Xs.current),_n(),Gn.current!==null&&clearTimeout(Gn.current)},[wn,_n]);const pa=S.useMemo(()=>MD(os,zl),[os,zl]);S.useEffect(()=>{sa(-1)},[zl]);const rc=S.useCallback(w=>{const Q=()=>{const H=document.getElementById(`msg-${w}`);return H?(H.classList.remove("chat-find-hit"),H.offsetWidth,H.classList.add("chat-find-hit"),window.setTimeout(()=>H.classList.remove("chat-find-hit"),1600),!0):!1};let $=0;const I=()=>{Q()||$++>=8||window.requestAnimationFrame(I)};I()},[]),Wg=S.useCallback(async(w,Q)=>{ro(),Fr();const $=Xs.current,I=jt.current,H=()=>(is(I)??[]).some(ne=>ne.id===w);let ie=H();if(!ie&&$){const ne=Os.getActiveSession(I)??I,Ce=await ND({targetId:w,has:H,targetCreatedAt:Q,fetchPage:async xe=>{if(!ne||ne===it)return{messages:[],hasMore:!1};const ke=await te.sessions.getMessages(ne,50,xe);return{messages:ke.messages,hasMore:ke.hasMore}}}),Le=LD(Ce.messages,w);Le.length>0&&(Qr(I,Le.map(oh)),Li(ne,{hasMore:Ce.hasMore,oldestCursor:Le[0]?new Date(Le[0].createdAt).toISOString():null})),ie=Ce.found||H(),zi("jump:collected",{messageId:w,found:Ce.found,kept:Le.length,exhausted:Ce.exhausted})}if(zi("jump:located",{messageId:w,loaded:ie,key:$,nowKey:Xs.current}),!($&&Xs.current!==$)){if(ie&&$){io($,ZO(w),"jump",vn()),zi("jump:scheduled",{messageId:w,key:$}),rc(w);return}$&&(zi("jump:fallback-bottom",{messageId:w,key:$}),console.warn("[jump] target message not loaded — falling back to the bottom",{messageId:w}),lr(),cr("instant"))}},[ro,Fr,io,rc,is,Os,Qr,Li,lr,cr]),fk=S.useCallback(w=>{const Q=pa.matches[w];Q&&(sa(w),ro(),Fr(),Xs.current&&io(Xs.current,ZO(Q.messageId),"jump"),rc(Q.messageId))},[pa.matches,ro,Fr,io,rc]);S.useEffect(()=>{if(P!=="chat"||t)return;const w=Q=>{Q.key.toLowerCase()!=="f"||Q.altKey||Q.shiftKey||!(b?Q.metaKey&&!Q.ctrlKey:Q.ctrlKey&&!Q.metaKey)||(Q.preventDefault(),Fn(!0))};return document.addEventListener("keydown",w),()=>document.removeEventListener("keydown",w)},[P,t,b]);const Xg=S.useRef(o);S.useEffect(()=>{Xg.current=o},[o]),S.useLayoutEffect(()=>{const w=Ad.current;if(w&&(Ad.current=null,!ys.current&&w.key===Xs.current)){const Q=Vr.current,$=Q?Q.scrollHeight-w.scrollHeight:0;Q&&$>0&&(Q.scrollTop+=$,Q.dispatchEvent(new Event("scroll")))}if(ys.current){sc();return}Xg.current&&Ni()&&(lu()||cr())},[rs,cr,Ni,sc]);const zg=S.useRef(P);S.useEffect(()=>{const w=zg.current!=="chat";zg.current=P,P==="chat"&&w&&ma(Xs.current)},[P,xr,cr,Ni,ma]);const qg=S.useRef(W);S.useEffect(()=>{if(qg.current===W||(qg.current=W,P!=="chat")||os.length===0||xr||fn||!Ni())return;const w=[],Q=requestAnimationFrame(()=>cr("instant"));for(const $ of[60,160,320])w.push(setTimeout(()=>cr("instant"),$));return()=>{cancelAnimationFrame(Q);for(const $ of w)clearTimeout($)}},[W,P,os.length,xr,fn,cr,Ni]);const ic=S.useCallback(async(w,Q,$)=>{const I=Q??`ch:${w}`;!$?.quiet&&jt.current===I&&Zr(!0);try{const H=await te.channels.getMessages(w,50),ie=H.messages.map(ne=>Mn(ne,e?.id));Qr(I,ie),Li(I,{hasMore:H.hasMore,oldestCursor:H.messages[0]?new Date(H.messages[0].createdAt).toISOString():null}),jt.current===I&&_s(ie)}catch{jt.current===I&&_s([])}finally{!$?.quiet&&jt.current===I&&Zr(!1)}},[Li]),Vd=S.useCallback(async w=>{if(!w)return Ri([]),Ll(0),Nl(1),Il(!1),dd(!1),[];dd(!0);try{const Q=await te.sessions.listByAgent(w,20,1);return Ri(Q.sessions),Ll(Q.total??Q.sessions.length),Nl(Q.page??1),Il(!!Q.hasMore),Q.sessions}catch{return Ri([]),Ll(0),Nl(1),Il(!1),[]}finally{dd(!1)}},[]),Zg=S.useRef({chatContext:[],input:"",pendingImages:[],chatMode:le,selectedAgent:ge,activeSessionId:et,activeDmUserId:_t,authUser:e,activeChannel:gt,groupChats:Cs,agents:l,humans:d,sending:xr,chatReplyTo:null});Zg.current={chatContext:nr,input:zt,pendingImages:or,chatMode:le,selectedAgent:ge,activeSessionId:et,activeDmUserId:_t,authUser:e,activeChannel:gt,groupChats:Cs,agents:l,humans:d,sending:xr,chatReplyTo:vs};const mk=$I({stateRef:Zg,actBuffers:Vn,activeSessionBuffer:xs,readConvMsgs:is,currentConvKeyRef:jt,updateConvMsgs:br,updateConvMsgsRaf:Rl,appendConvActivity:El,beginStream:$i,endStream:q,abortStream:be,clearStreamSession:Ot,setStreamSession:Rt,getStreamSession:cs,setActiveSession:hn,incrementSending:Ke,decrementSending:Je,loadAndDisplay:Ie,sessionSwitchSeqRef:ud,setSending:Uo,setActivities:zr,setInput:ks,setChatContext:dn,setPendingImages:Ml,setMentionDropdown:ra,setChatReplyTo:es,setActiveSessionId:Ei,setStoredActiveSession:Yo,setOpenSessionTabs:Ys,setSessions:Ri,setLoadingChat:Zr,setWindowBounds:Li,makeConvKey:Ea,makeDmChannel:Hl,addRecentMsgId:Tl,resumeChatScrollFollow:lr,loadSessions:Vd,t:i}),{send:no,stopSending:pk,tryReattachActiveStream:oo,loadSessionMessages:Fd}=mk;Mg.current=no;const Vg=S.useCallback(()=>{Bg(),no()},[Bg,no]),Fg=S.useRef(oo);Fg.current=oo;const gk=ah();S.useEffect(()=>{if(!o||t||le!=="direct"||!ge)return;const w=et;!w||w===it||hs.isStreaming(w)&&Fg.current(ge,w,jt.current)},[o,t,le,ge,et,gk]);const Ok=S.useCallback(async()=>{if(Bl||!ge||!Dl)return;gg(!0);const w=pg+1,Q=ge;try{const $=await te.sessions.listByAgent(Q,20,w);Ri(I=>{const H=new Set(I.map(ne=>ne.id)),ie=[...I,...$.sessions.filter(ne=>!H.has(ne.id))];return Ll($.total??ie.length),ie}),Nl(w),Il(!!$.hasMore)}catch{}gg(!1)},[Bl,Dl,pg,ge]),Ug=S.useCallback(w=>{xg(w.id),xd((w.isMain?"":w.title)||"")},[]),ga=S.useCallback(()=>{xg(null),xd("")},[]),Hg=S.useCallback(async w=>{const Q=Od.trim();if(!Q){ga();return}try{const I=(await te.sessions.renameTitle(w.id,Q))?.session?.title??Q;Ri(H=>H.map(ie=>ie.id===w.id?{...ie,title:I}:ie)),Ys(H=>H.map(ie=>ie.id===w.id?{...ie,title:I}:ie))}catch{}ga()},[Od,ga]),Yg=S.useCallback(async()=>{if(Ul.current)return Ul.current;const w=jt.current,Q=Os.getActiveSession(w)??w,$=Os.getWindowBounds(Q),I=$.oldestCursor;if(!$.hasMore||!I)return 0;const H=Q&&Q!==it?Q:null,ne=(async()=>{hg(!0);try{const Ce=Xs.current;let Le=[],xe=!1,ke=null;if(le==="channel"||le==="dm"){const Ht=le==="dm"?Hl(e?.id??"",_t):gt,yr=await te.channels.getMessages(Ht,50,I);Le=yr.messages.map(hr=>Mn(hr,e?.id)),xe=yr.hasMore,ke=yr.messages[0]?new Date(yr.messages[0].createdAt).toISOString():null}else if(H){const Ht=await te.sessions.getMessages(H,50,I);Le=Ht.messages.map(oh),xe=Ht.hasMore,ke=Ht.messages[0]?new Date(Ht.messages[0].createdAt).toISOString():null}else return 0;if(Le.length===0)return Li(Q,{hasMore:xe,oldestCursor:I}),0;if(jt.current!==w||Xs.current!==Ce)return 0;const Ae=Vr.current,Ue=Ae?Ae.scrollHeight:null,ct=is(w)??[],Kt=new Set(Le.map(Ht=>Ht.id));let as=[...Le,...ct.filter(Ht=>!Kt.has(Ht.id))];return as.length>500&&(as=as.slice(-500)),Qr(w,as),Li(Q,{hasMore:xe,oldestCursor:ke}),Ue!==null&&(Ad.current={key:Xs.current,scrollHeight:Ue}),_s(as),Le.length}catch{return 0}finally{hg(!1)}})();Ul.current=ne;try{return await ne}finally{Ul.current=null}},[le,gt,e?.id,_t,is,Qr,Os,Li]);Ld.current=Yg;const Ud=S.useRef(!1),xk=S.useCallback(w=>{uk(),!Ud.current&&(Ud.current=!0,requestAnimationFrame(()=>{Ud.current=!1,w.target.scrollTop<100&&Ld.current?.()}))},[]);S.useEffect(()=>{if(t)return;const w=Ea(le,ge,gt,_t),Q=jt.current;jt.current=w,Q&&Q!==w&&(jl.set(Q,Ws),et&&Dm(Q)&&hn(Q,et),wn(ho(Q,et))),Q!==w&&(lr(),Sn(!1),eo.current=0,fa(0),Fn(!1),Pd(""),sa(-1));const $=is(w),I=jl.get(w),H=xs.get(w)??(ge?mg(ge)??void 0:void 0),ie=cs(w),ne=H??et,Ce=le!=="direct"?lt(w):e0(ie,ne),Le=ne??w,xe=Vn.get(Le)??[];zr(Ce?xe:[]),Uo(Ce),le==="direct"&&ge&&Vd(ge),I&&I.length>0&&Ys(I),mn(!1);const ke=N2(Mi.current,{chatMode:le,agentId:ge});if($!==void 0&&$.length>0)if(Ce||Os.completeLoad(w),Zr(!1),_s($),H!==void 0&&(oa(w,H),ma(ho(w,H))),(!I||I.length===0)&&Ys([]),le==="channel"||le==="dm"){const Ue=le==="dm"?Hl(e?.id??"",_t):gt;ic(Ue,w)}else le==="direct"&&ge&&H&&H!==it&&!ke&&(Ce?oo(ge,H,w):Fd(H,w).then(()=>{jt.current===w&&ge&&oo(ge,H,w)}));else if(Al(w),Zr(!0),_s([]),Qr(w,[]),le==="channel"||le==="dm"){const Ue=le==="dm"?Hl(e?.id??"",_t):gt;ic(Ue,w),(!I||I.length===0)&&Ys([])}else le==="direct"&&ge?Vd(ge).then(Ue=>{if(jt.current===w)if(Ue.length>0){const ct=Ue.find(zs=>zs.isMain),Kt=pd(ge),as=ct?[ct,...Ue.filter(zs=>!zs.isMain&&!Kt.has(zs.id)).slice(0,4)]:Ue.filter(zs=>!Kt.has(zs.id)).slice(0,5);let Ht=I&&I.length>0?I:as;const yr=mg(ge),hr=H!==void 0?H:yr??ct?.id??Ht[0].id;if(hr&&hr!==it&&!Ht.some(zs=>zs.id===hr)){const zs=Ue.find(Ur=>Ur.id===hr);zs&&(Ht=[...Ht,zs])}const ui=hr&&Ht.some(zs=>zs.id===hr)?hr:Ht[0].id,Bi=Mi.current;if(Bi&&Bi.mode==="direct"&&Bi.agentId===ge&&(Bi.sessionId||Bi.preferMain)){Ys(Ht);return}oa(w,ui),ma(ho(w,ui)),Yo(ge,ui),Ys(Ht),Fd(ui,w).then(()=>{jt.current===w&&ge&&oo(ge,ui,w)})}else oa(w,null),Zr(!1),(!I||I.length===0)&&Ys([])}).catch(()=>{jt.current===w&&Zr(!1)}):Zr(!1)},[t,le,ge,gt,_t,n.language,i]),S.useEffect(()=>t?void 0:St.on("chat:message",Q=>{const $=Q.payload,I=$.channel??"";if(!I)return;const H=$.senderType??"agent",ie=$.text??$.message??"",ne=$.senderId??$.agentId??"",Ce=$.senderName??$.agentId??i("page.fallbackAgent"),Le=$.metadata,xe=$.messageId??$.id??"";if(xe&&cn.current.has(xe))return;const ke=H==="human"&&ne===(e?.id??""),Ae={id:xe||`ws_${Date.now()}_${ne}`,sender:ke?"user":"agent",text:ie,time:new Date().toLocaleTimeString(),rawCreatedAt:Q.timestamp??new Date().toISOString(),agentName:ke?void 0:Ce,agentId:ke?void 0:ne,replyToId:$.replyToId??void 0,replyToSender:$.replyToSender??void 0,replyToText:$.replyToText??void 0};if(Le&&H==="agent"){const ct=[];if(Le.thinking?.length&&ct.push({type:"text",content:"",thinking:Le.thinking.join(`
|
|
80
80
|
|
|
81
81
|
`)}),Le.toolCalls?.length)for(let Kt=0;Kt<Le.toolCalls.length;Kt++){const as=Le.toolCalls[Kt];ct.push({type:"tool",key:`${as.tool}_${Kt}`,tool:as.tool,status:as.status==="error"?"error":"done",args:as.arguments,result:as.result,durationMs:as.durationMs})}ct.length>0&&(ct.push({type:"text",content:ie}),Ae.segments=ct)}let Ue;if(I.startsWith("notes:"))Ue=`dm:${I.slice(6)}`;else if(I.startsWith("dm:")){const ct=I.slice(3).split(":");Ue=`dm:${ct.find(as=>as!==(e?.id??""))??ct[0]??""}`}else Ue=`ch:${I}`;br(Ue,ct=>cu(ct,Ae)),Ue===jt.current&&yn.current&&(eo.current+=1,fa(eo.current),Sn(!0))}),[t,br,e?.id,gt]);const Gg=S.useRef(!1);S.useEffect(()=>t?void 0:St.on("connected",()=>{const Q=!Gg.current;Gg.current=!0,!Q&&le==="channel"&>&&ic(gt,void 0,{quiet:!0})}),[t,le,gt,ic]),S.useEffect(()=>t?void 0:St.on("session:title_updated",Q=>{const $=Q.payload;if(!$)return;const I=$.sessionId,H=$.title;!I||typeof H!="string"||(Ri(ie=>ie.map(ne=>ne.id===I?{...ne,title:H}:ne)),Ys(ie=>ie.map(ne=>ne.id===I?{...ne,title:H}:ne)))}),[t]),S.useEffect(()=>t?void 0:St.on("chat:proactive_message",Q=>{const $=Q.payload,I=$.targetUserId;if(I&&I!==e?.id)return;const H=$.agentId??"",ie=$.agentName??i("page.fallbackAgent"),ne=$.message??"",Ce=$.sessionId??"",Le=$.messageId??"",xe=$.metadata??{};if(!H||!ne||ne==="[cancelled]"||ne==="[Stream cancelled]")return;const ke=xe.role==="user",Ae=!ke&&(!!xe.activityLog||ne.startsWith("[ACTIVITY:")),{cleaned:Ue,priority:ct}=vC(ne),Kt=!ke&&(!!xe.notifyUser||Ue!==ne),as=Ea("direct",H,"","");if(Ce&&jt.current===as){const Er=et;if(Er&&Er!==it&&Er!==Ce)return}const Ht=!!xe.isMainSession&&!ke,yr=Ce||et,hr=typeof xe.userText=="string"?xe.userText:"",ui=typeof xe.userMessageId=="string"?xe.userMessageId:"",Bi=typeof xe.createdAt=="string"&&xe.createdAt||(typeof Q.timestamp=="string"?Q.timestamp:void 0)||new Date().toISOString(),zs=(()=>{try{return new Date(Bi).toLocaleTimeString()}catch{return new Date().toLocaleTimeString()}})(),Ur={id:Le||`proactive_${Date.now()}`,sender:ke?"user":"agent",text:Ue,time:zs,rawCreatedAt:Bi,...ke?{}:{agentName:ie,agentId:H,...Kt?{isNotification:!0,notifyPriority:xe.priority??ct}:{},...Ae?{isActivityLog:!0,activityType:xe.activityType,outcome:xe.outcome,mailboxItemId:xe.mailboxItemId,taskId:xe.taskId,requirementId:xe.requirementId}:{},...!Ae&&xe.taskId?{taskId:xe.taskId}:{},...!Ae&&xe.requirementId?{requirementId:xe.requirementId}:{}}};Kt&&Ur.id&&Sd(Er=>Er.includes(Ur.id)?Er:[...Er,Ur.id]),br(as,Er=>{if(Er.some(Qn=>Qn.id===Ur.id))return Er;let Tn=Er;if(!ke&&hr&&(Tn.some(Wi=>ui&&Wi.id===ui||Wi.sender==="user"&&Wi.text===hr)||(Tn=cu(Tn,{id:ui||`feishu_user_${Ur.id}`,sender:"user",text:hr,time:new Date().toLocaleTimeString(),rawCreatedAt:Ur.rawCreatedAt}))),Ht)for(let Qn=Tn.length-1;Qn>=0;Qn--){const Wi=Tn[Qn];if(Wi.sender==="agent"&&Wi.agentId===H&&Wi.isStopped){const xO=[...Tn];return xO[Qn]={...Ur,id:Wi.id},xO}}return cu(Tn,Ur)},yr||void 0)}),[t,br,i,et]),$d.find(w=>w.id===Y_),S.useEffect(()=>{G_(null)},[ge]);const[Rr,Hd]=S.useState(null),[Kg,Jg]=S.useState(!1),[bk,eO]=S.useState(null),[Di,Yd]=S.useState(null),vk=S.useMemo(()=>{for(let w=rs.length-1;w>=0;w--)if(rs[w]?.sender==="agent"&&!rs[w]?.isActivityLog)return rs[w].id;return null},[rs]),yk=S.useCallback(w=>{const Q=w.segments?w.segments.filter($=>$.type==="text").map($=>$.content).join(`
|
|
82
82
|
`):w.text;navigator.clipboard.writeText(Q),eO(w.id),setTimeout(()=>eO($=>$===w.id?null:$),2e3)},[]),Gd=S.useCallback((w,Q,$)=>{const I=jt.current,H=is(I)??rs,ie=H.findIndex(Ce=>Ce.id===w.id);if(ie<0)return;const ne=Q&&ie>0&&H[ie-1]?.id===Q.id;br(I,Ce=>{const Le=Ce.findIndex(xe=>xe.id===(ne?Q.id:w.id));return Le>=0?Ce.slice(0,Le):Ce}),no($,{isRetry:!0})},[rs,br]),Sk=S.useCallback(w=>{const Q=jt.current,$=is(Q)??rs,I=$.findIndex(Ce=>Ce.id===w.id);if(I<0)return;let H=null;for(let Ce=I-1;Ce>=0;Ce--)if($[Ce]?.sender==="user"){H=$[Ce];break}const ie=H?.text??"";if(!ie)return;if(I<$.length-1){const Ce=$.length-1-I;Yd({retryMsg:w,userMsg:H,retryText:ie,followCount:Ce});return}Gd(w,H,ie)},[rs,Gd]),wk=S.useCallback(w=>{const Q=jt.current;if((is(Q)??rs).findIndex(ie=>ie.id===w.id)<0)return;br(Q,ie=>{const ne=[...ie],Ce=ne.findIndex(ke=>ke.id===w.id);if(Ce<0)return ie;const Le=ne[Ce],xe=[...Le.segments??[]];for(;xe.length>0;){const ke=xe[xe.length-1];if(ke.type==="tool"&&(ke.status==="stopped"||ke.status==="running"))xe.pop();else if(ke.type==="text"&&!ke.content)xe.pop();else break}return ne[Ce]={...Le,segments:xe,isStopped:!1,isError:!1},ne});const H=xs.get(Q)??(et&&et!==it?et:null);if(!H){console.warn("[resume] no session bound to this conversation — resume aborted");return}no("[Continue from where you left off. Do not repeat content already generated.]",{isResume:!0,sessionIdOverride:H})},[rs,br,et]),_k=S.useCallback(w=>{const Q=w.sender==="user"?e?.name??i("page.fallbackYou"):w.agentName??i("page.fallbackAgent");if(es({id:w.id,sender:Q,text:w.text}),le==="channel"&&w.sender==="agent"&&w.agentName){const $=`@${w.agentName} `;ks(I=>I.startsWith($)?I:$+I)}Hs.current?.focus()},[e?.name,le,i]),kk=async w=>{if(!Rr||!ge||le!=="direct")return;const Q=et;if(!(!Q||Q===it)){Jg(!0);try{const $=await te.agents.evolveFromMessage(ge,{parentSessionId:Q,sourceMessageId:Rr.id.startsWith("a_")||Rr.id.startsWith("u_")?void 0:Rr.id,sourceText:(Rr.text||"").slice(0,500)||void 0,userNote:w.trim()||void 0}),I=new Date().toISOString(),H={id:$.sessionId,agentId:ge,userId:e?.id??null,title:"Remember / Evolution",isMain:!1,metadata:{kind:"evolution",parentSessionId:$.parentSessionId,sourceMessageId:Rr.id,sourceAgentId:ge,createdFrom:"remember_button"},createdAt:I,lastMessageAt:I};Hd(null),Ri(ne=>[H,...ne.filter(Ce=>Ce.id!==H.id)]),Ys(ne=>ne.some(Ce=>Ce.id===H.id)?ne:[...ne,H]),Ei(H.id);const ie=Ea("direct",ge,gt,_t);me(ie,H.id),Yo(ge,H.id),_s([]),await no($.seedPrompt,{sessionIdOverride:$.sessionId})}catch($){console.error("evolve-from-message failed",$)}finally{Jg(!1)}}},Ii=async w=>{const Q=++ud.current,$=et,I=jt.current;wn(ho(I,$)),oa(I,w.id),ma(ho(I,w.id)),mn(!1),lr(),Sn(!1),eo.current=0,fa(0);const H=cs(I),ne=e0(H,w.id);Uo(ne),zr(ne?Vn.get(w.id)??[]:[]),ge&&Yo(ge,w.id),$&&$!==it&&bs(I,$);const Ce=ir(I,w.id);(!Ce||Ce.length===0)&&w.id!==it&&Zr(!0),Ys(Le=>Le.some(xe=>xe.id===w.id)?Le:[...Le,w]),ge&&D_(ge,w.id),jt.current!==I&&(jt.current=I);try{await Fd(w.id,I)}finally{ud.current===Q&&Zr(!1)}ge&&oo(ge,w.id,I)},Ck=w=>{if(Ys(Q=>Q.filter($=>$.id!==w)),ge&&w!==it&&N_(ge,w),et===w){const Q=Ws.filter($=>$.id!==w);Q.length>0?Ii(Q[Q.length-1]):Oa()}},tO=S.useCallback(async w=>{if(w.trim().length<2){ql([]);return}Tg(!0);try{const Q=le==="channel"?"channel":le==="direct"?"direct":"all",$=le==="channel"?gt:void 0,{results:I}=await te.messages.search(w,{scope:Q,channel:$,limit:30});ql(I)}catch{ql([])}Tg(!1)},[le,gt]),Pk=S.useCallback(w=>{Pd(w),Td.current&&clearTimeout(Td.current),Td.current=setTimeout(()=>{tO(w)},300)},[tO]),nc=S.useRef(null),Tk=S.useCallback(w=>{if(Fn(!1),Pd(""),ql([]),w.source==="channel"&&w.channel){$t("channel"),Bs(w.channel),_("chat"),Mi.current={messageId:w.id,mode:"channel",channel:w.channel};return}w.source==="direct"&&w.agentId&&($t("direct"),_("chat"),w.agentId!==ge&&Us(w.agentId),Mi.current={messageId:w.id,mode:"direct",agentId:w.agentId,sessionId:w.sessionId??null,createdAt:w.createdAt})},[ge]);S.useEffect(()=>{const w=Mi.current;if(!w)return;const Q=()=>{Md.current=null,Mi.current===w&&(Mi.current=null,w.messageId&&Wg(w.messageId,w.createdAt))};if(w.mode==="channel"){if(le!=="channel"||gt!==w.channel||fn)return;Q();return}if(le!=="direct"||P!=="chat"||w.agentId&&w.agentId!==ge)return;const $=w.preferMain?($r.find(I=>I.isMain)??Ws.find(I=>I.isMain))?.id:w.sessionId;if(!(w.preferMain&&!$)){if($&&$!==et){if(Md.current===w)return;const I=$r.find(H=>H.id===$)??Ws.find(H=>H.id===$)??($r.length===0?null:void 0);if(I===null)return;Md.current=w,(async()=>{const H=new Date().toISOString();await Ii(I??{id:$,agentId:w.agentId??ge??"",userId:null,title:null,createdAt:H,lastMessageAt:H}),Q()})();return}fn||Q()}},[le,gt,ge,et,$r,Dl,Ws,fn,P,os,Wg,Ii]);const Oa=()=>{wn(Xs.current),_n(),ys.current=null,Ei(it);const w=jt.current;me(w,it),_s([]),mn(!1),Ys($=>{const I=$.filter(H=>H.id!==it);return[{id:it,agentId:ge??"",userId:null,title:i("page.newChat"),createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()},...I]});const Q=ge;Q&&te.sessions.create(Q).then($=>{const I=$?.session;if(!I?.id)return;const H=I.id;if(jt.current!==w)return;const ie=xs.get(w);ie!==void 0&&ie!==it||(oa(w,H),Yo(Q,H),Ys(ne=>ne.map(Ce=>Ce.id===it?{...Ce,id:H,title:I.title??Ce.title}:Ce)))}).catch(()=>{})},xa=S.useCallback(()=>{t||!o||P==="chat"&&(gd||ze||Se||Un||Yn||Di||Rr||requestAnimationFrame(()=>{const w=Hs.current;w&&!w.disabled&&(w.focus(),w.setSelectionRange(w.value.length,w.value.length))}))},[t,o,P,gd,ze,Se,Un,Yn,Di,Rr]),sO=S.useRef(o),rO=S.useRef(ge),iO=S.useRef(et);S.useEffect(()=>{const w=o&&!sO.current,Q=ge!==rO.current,$=et!==iO.current;sO.current=o,rO.current=ge,iO.current=et,!v&&(w||Q||$)&&xa()},[o,ge,et,v,xa]),S.useEffect(()=>{if(t||!o||v)return;const w=Q=>{if(Di||Rr||Un||Yn||LC(Q.target))return;const $=NC({key:Q.key,metaKey:Q.metaKey,ctrlKey:Q.ctrlKey,altKey:Q.altKey,shiftKey:Q.shiftKey},b);if($==="new-conversation"){if(le!=="direct"||!ge||P!=="chat")return;const I=Q.target;if(I&&I!==Hs.current&&(I.tagName==="INPUT"||I.tagName==="TEXTAREA"||I.isContentEditable))return;Q.preventDefault(),Oa(),xa();return}if($==="cycle-session-next"||$==="cycle-session-prev"){if(le!=="direct"||!ge||P!=="chat"||Ws.length<2)return;const I=$==="cycle-session-prev"?-1:1,H=DC(Ws.map(ne=>ne.id),et,I);if(!H)return;Q.preventDefault();const ie=Ws.find(ne=>ne.id===H);if(!ie)return;if(ie.id===it){Ei(it);const ne=jt.current;me(ne,it),_s([])}else Ii(ie);xa()}};return document.addEventListener("keydown",w,!0),()=>document.removeEventListener("keydown",w,!0)},[t,o,v,b,le,ge,P,Ws,et,Un,Yn,Di,Rr,Oa,Ii,xa,Ei,me,_s,jt]);const Qk=w=>{ks(w);const Q=Hs.current?.selectionStart??w.length,$=w.slice(0,Q),I=$.lastIndexOf("@");if(I>=0){const H=I===0?"":$[I-1];if(I===0||/[\s\n,,。!?!?;;::、()()\[\]【】]/.test(H)){const ne=$.slice(I+1);if(!ne.includes(" ")&&!ne.includes(`
|
|
83
83
|
`)){rk(),ra(!0),K_(ne.toLowerCase()),Hn(0);return}}}if(ra(!1),Rd.length>0){const H=$.lastIndexOf("/");if(H>=0){const ie=H===0?"":$[H-1];if(H===0||/[\s\n,,。!?!?;;::、()()\[\]【】]/.test(ie)){const Ce=$.slice(H+1);if(!Ce.includes(" ")&&!Ce.includes(`
|
|
84
|
-
`)){Ed(),Zl(!0),J_(Ce.toLowerCase()),na(0);return}}}}Zl(!1)},nO=S.useCallback(w=>{const Q=Hs.current?.selectionStart??zt.length,I=zt.slice(0,Q).lastIndexOf("/"),H=zt.slice(Q),ie=zt.slice(0,I)+"/"+w.name+" "+H;ks(ie),Zl(!1),na(0);const ne=I+w.name.length+2;requestAnimationFrame(()=>{const Ce=Hs.current;Ce&&(Ce.focus(),Ce.setSelectionRange(ne,ne))})},[zt]),oc=(w,Q,$)=>{const I=Hs.current?.selectionStart??zt.length,ie=zt.slice(0,I).lastIndexOf("@"),ne=zt.slice(I),Ce=zt.slice(0,ie)+ne;ks(Ce),ra(!1),Hn(0);const Le=Q&&$?`@[${w}](${Q}:${$})`:w.includes(" ")?`@[${w}]`:`@${w}`,xe=Q?fO[Q]??"📄":"🤖",ke=Q?i(`page.mentionType.${Q}`,{defaultValue:Q}):i("page.mentionType.agent");we({label:`[${xe}${ke}] ${w}`,content:`${Le} `}),requestAnimationFrame(()=>{const Ae=Hs.current;Ae&&(Ae.focus(),Ae.setSelectionRange(Ae.value.length,Ae.value.length))})},$k=10*1024*1024,oO=5,jk=new Set(["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/msword","text/csv","text/html","application/json","application/xml","text/xml","application/epub+zip"]),ao=S.useCallback(w=>w.type.startsWith("image/")||jk.has(w.type),[]),Kd=w=>w.dataUrl.startsWith("data:image/"),Rk=(w,Q)=>{if(Kd({dataUrl:Q}))return null;const $=w.split(".").pop()?.toLowerCase()??"";return{pdf:"📄",docx:"📝",doc:"📝",xlsx:"📊",xls:"📊",pptx:"📎",csv:"📊",json:"🔧",xml:"🔧",html:"🌐",epub:"📚"}[$]??"📁"},ba=S.useCallback(w=>{const Q=Array.from(w).filter(ao);if(Q.length!==0)for(const $ of Q){if($.size>$k)continue;const I=new FileReader;I.onload=()=>{const H=I.result;Ml(ie=>ie.length>=oO||ie.some(ne=>ne.dataUrl===H)?ie:[...ie,{id:`img_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,dataUrl:H,name:$.name}])},I.readAsDataURL($)}},[ao]),Ek=S.useCallback(w=>{Ml(Q=>Q.filter($=>$.id!==w))},[]),Ak=S.useCallback(w=>{const Q=w.clipboardData?.files;if(Q&&Q.length>0){const $=Array.from(Q).filter(ao);$.length>0&&(w.preventDefault(),ba($))}},[ba,ao]),Mk=S.useCallback(w=>{w.preventDefault();const Q=w.dataTransfer?.files;Q&&Q.length>0&&ba(Array.from(Q).filter(ao))},[ba,ao]),Lk=S.useCallback(w=>{w.preventDefault()},[]),Mt=l.find(w=>w.id===ge),kn=ns??(le==="direct"?Mt?.teamId:void 0),va=!!(!v&&!j&&kn&&As.some(w=>w.id===kn)),aO=!!(va&&!L&&(Qe&&!qe||Ye));pe.current=va,S.useEffect(()=>{if(K==="l2"){if(!va){B?.setKeyboardPane("l1");return}!L&&!Qe&&!Ye&&B?.setKeyboardPane("l1")}},[K,va,L,Qe,Ye,B]);const lO=S.useRef(K);S.useEffect(()=>{if(t||v||!o)return;const w=lO.current;if(lO.current=K,!(K!=="l2"||w==="l2")){if(!kn){B?.setKeyboardPane("l1");return}qe?pt(!0):Ee(!0)}},[K,t,v,o,kn,qe,B]);const ac=e?.name??i("page.fallbackYou"),cO=os[os.length-1];xr&&cO?.sender;const Nk=qt&&cO?.sender==="agent"&&(aa||!!r),hO=S.useMemo(()=>{if(le!=="channel")return null;if(gt.startsWith("group:custom:")){const Q=Cs.find($=>$.channelKey===gt);return Q?.members?new Set(Q.members.filter($=>$.type==="agent").map($=>$.id)):null}if(!ns)return null;const w=As.find(Q=>Q.id===ns);return w?new Set(w.members.filter(Q=>Q.type==="agent").map(Q=>Q.id)):null},[le,gt,ns,As,Cs]),dO=l.filter(w=>hO?hO.has(w.id):!0).filter(w=>w.name.toLowerCase().includes(jg)),uO=tk.filter(w=>w.name.toLowerCase().includes(jg)),fO={workflow:"⚙️",project:"📁",requirement:"📋",task:"✅",deliverable:"📦"},Cn=S.useMemo(()=>[...dO.map(w=>({kind:"agent",agent:w})),...uO.map(w=>({kind:"entity",entity:w}))],[dO,uO]),Pn=d.find(w=>w.id===_t),lo=_t===e?.id||!_t,Ms=Cs.find(w=>w.channelKey===gt);S.useEffect(()=>{if(t||!gt.startsWith("group:custom:"))return;const w=Cs.find(Q=>Q.channelKey===gt);!w||w.members||te.groupChats.getById(w.id).then(Q=>{Q.chat.members&&ta($=>$.map(I=>I.id===w.id?{...I,members:Q.chat.members}:I))}).catch(()=>{})},[t,gt,Cs]);const Jd=S.useCallback(async()=>{if(t||le!=="direct"||!ge){bd([]),vd([]);return}try{hu("/approvals");const{approvals:w}=await te.approvals.list("pending");bd(w.filter(Q=>Q.status==="pending"&&Array.isArray(Q.questions)&&Q.questions.length>0&&(Q.details?.agentId??Q.agentId)===ge)),vd(zD(w,{agentId:ge,sessionId:et&&et!==it?et:null}))}catch{}},[t,le,ge,et]),eu=S.useCallback(async()=>{if(t||le!=="direct"||!ge||!et||et===it){yd([]);return}try{hu("/notifications");const{notifications:w}=await te.notifications.list(e?.id,!0,{type:"agent_report",limit:30}),Q=w.filter($=>!$.read&&$.type==="agent_report"&&!$.metadata?.creditExhausted&&$.metadata?.agentId===ge&&Mm($)===et).sort(($,I)=>new Date(I.createdAt).getTime()-new Date($.createdAt).getTime()).slice(0,5);yd(Q),Sd(Q.map($=>$.metadata?.messageId).filter($=>typeof $=="string"&&$.length>0))}catch{}},[t,le,ge,et,e?.id]);S.useEffect(()=>{Jd(),eu();let w=null;const Q=()=>{w||(w=setTimeout(()=>{w=null,Jd(),eu()},400))},$=St.on("approval:requested",Q),I=St.on("approval:resolved",Q),H=St.on("notification",Q),ie=()=>Q();return window.addEventListener("markus:notifications-changed",ie),()=>{w&&clearTimeout(w),$(),I(),H(),window.removeEventListener("markus:notifications-changed",ie)}},[Jd,eu]),S.useEffect(()=>{if(!o||t||le!=="direct"||P!=="chat"||Ko.length===0||On||gn||Ai)return;const w=Ko.find(Q=>!Sg.current.has(Q.id));w&&(Sg.current.add(w.id),Jo(w))},[o,t,le,P,Ko,On,gn,Ai]);const Dk=S.useCallback(async(w,Q)=>{vg(w);try{await te.approvals.respond(w,Q.approved,e?.id,Q.comment,Q.selectedOption,Q.answers),bd($=>$.filter(I=>I.id!==w)),Wl(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}vg(null)},[e?.id]),Ik=S.useCallback(async(w,Q,$)=>{yg(w);try{await te.approvals.respond(w,Q,e?.id,$),vd(I=>I.filter(H=>H.id!==w)),Jo(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}yg(null)},[e?.id]),tu=S.useCallback(()=>{ea(null);const w=nc.current;nc.current=null,w&&(Mi.current={messageId:w.messageId,mode:"direct",agentId:w.agentId,sessionId:w.sessionId,preferMain:w.preferMain})},[]);S.useEffect(()=>{const w=jr?.agentId;!w||w===ge||(ea(null),nc.current=null)},[jr?.agentId,ge]);const mO=S.useCallback(async w=>{if(!(t||!e?.id||jr))try{hu("/notifications");const{notifications:Q}=await te.notifications.list(e.id,!0,{type:"agent_report",limit:30}),$=VD(Q,w);if($.length===0)return;const I=FD($);nc.current=I.sessionId?{agentId:w,sessionId:I.sessionId,messageId:I.messageId??void 0}:{agentId:w,sessionId:null,preferMain:!0},ea({items:$,index:0,agentId:w})}catch{}},[t,e?.id,jr]),su=S.useCallback(w=>{$t("direct"),Us(w),_("chat"),mO(w)},[mO]),Bk=S.useCallback(async w=>{_g(w);const Q=jr;try{const $=Q?.items.find(ie=>ie.id===w)??Ai,I=typeof $?.metadata?.messageId=="string"?$.metadata.messageId:null;await te.notifications.markRead(w),yd(ie=>ie.filter(ne=>ne.id!==w)),I&&Sd(ie=>ie.filter(ne=>ne!==I));const H=(Q?.index??0)+1;Q&&H<Q.items.length?ea({...Q,index:H}):tu(),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}_g(null)},[jr,Ai,tu]),pO=le==="channel"?Ms?.name??gt:le==="direct"?Mt?.name??i("page.selectAgent"):le==="dm"?lo?i("chat.myNotes"):Pn?.name??i("page.directMessage"):i("page.chatTitle"),gO=S.useMemo(()=>Math.floor(Math.random()*5),[ge,et]),ru=S.useMemo(()=>Math.floor(Math.random()*3),[_t,lo,et]),OO=S.useMemo(()=>{if(le==="dm"){if(lo)return i(`page.placeholder.dmSelfOptions.${ru}`);const w=Pn?.name??"";return w?i(`page.placeholder.dmOtherOptions.${ru}`,{name:w}):i("page.placeholder.dmOtherEmpty")}return le==="direct"&&ge?i(`page.placeholder.directOptions.${gO}`):""},[le,lo,Pn?.name,ru,ge,gO,i]),ya=le==="direct"&&!!Mt&&Mt.status==="offline",iu=le==="channel"?Ms?i("page.placeholder.channel",{name:Ms.name}):i("page.placeholder.channelWithMention",{name:gt}):le==="dm"?lo?i("page.placeholder.dmSelf"):i("page.placeholder.dmOther",{name:Pn?.name??""}):i(ya?"page.placeholder.agentOffline":ge?"page.placeholder.direct":"page.placeholder.noAgent"),Wk=v&&x==="chat",Xk=S.useMemo(()=>X2({chatMode:le,agentTeamId:Mt?.teamId,channelTeamId:Ms?.teamId,knownTeamIds:As.map(w=>w.id)}),[le,Mt?.teamId,Ms?.teamId,As]),zk=S.useMemo(()=>{if(le==="direct"){const w=$r.find(Q=>Q.id===et);if(w?.title)return w.title;if(Mt?.name)return Mt.name}return(le==="channel"?Ms?.name??gt:Pn?.name)||i("page.loadingChat",{defaultValue:"Loading conversation…"})},[le,$r,et,Mt?.name,gt,_t,Ms?.name,Pn?.name,i]),Sa=P==="chat"&&os.length===0&&!fn,vr=P==="chat"&&os.length>0;md.current=vr;const qk=!!(zt.trim()||or.length>0),nu=IC(v,qk);return c.jsxs("div",{ref:G,className:"flex-1 overflow-hidden flex relative",children:[!j&&c.jsx(tP,{authUser:e,agents:l,teams:As,humans:d,tasks:$d,externalAgents:U_,groupChats:Cs,chatMode:le,selectedAgent:ge,activeChannel:gt,activeDmUserId:_t,previewMode:t,onSelectAgent:w=>{su(w),Ps(!1),v&&k()},onSelectChannel:w=>{$t("channel"),Bs(w),_("chat"),Ps(!1),v&&k()},onSelectDm:w=>{$t("dm"),ln(w),_("chat"),Ps(!1),v&&k()},onSelectTeam:w=>{const Q=Cs.find(I=>I.type==="team"&&I.teamId===w),$=Q?.channelKey??`group:${w}`;v?C(w):($t("channel"),Bs($),_("chat"),Ps(!1),!Qe&&!qe&&Ee(!0),Q||(Kn(),Gs()))},selectedTeamId:ns??(le==="direct"&&Mt?.teamId?Mt.teamId:null),onRefreshTeams:Gs,onRefreshAgents:ar,onRefreshHumans:da,onRefreshGroupChats:Kn,onViewProfile:dt,onManageGroupMembers:w=>{$t("channel"),Bs(w),_("chat"),Ps(!0),v&&k()},unreadByAgent:Gl,unreadByChannel:Yl,width:v?void 0:R.width,onResizeStart:v?void 0:R.onResizeStart,hidden:v&&x!=="roster"||!v&&L,onCollapse:()=>E(!0),initialLoading:f,focused:!v&&!L&&K==="l1",l2Available:va}),v&&x==="team"&&y&&(()=>{const w=As.find(I=>I.id===y);if(!w){const H=jO(y,As.map(ie=>ie.id),Qd)==="missing";return c.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[c.jsx("button",{onClick:()=>{window.location.hash=Yt.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",title:i("common:back",{defaultValue:"Back"}),children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate",children:i(H?"page.teamMissingTitle":"page.loadingTeam")})]}),c.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-3 px-6 text-center",children:[c.jsx("p",{className:"text-xs text-fg-tertiary max-w-[280px]",children:i(H?"page.teamMissingBody":"page.loadingTeamBody")}),c.jsx("div",{className:"flex items-center gap-2",children:H?c.jsx("button",{onClick:()=>{window.location.hash=Yt.TEAM},className:"px-3 py-1.5 text-xs font-medium bg-brand-600 text-white rounded-md hover:bg-brand-700 transition-colors",children:i("page.backToList")}):c.jsx("button",{onClick:()=>{Gs()},className:"px-3 py-1.5 text-xs font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay transition-colors",children:i("common:retry",{defaultValue:"Retry"})})})]})]})}const Q=l.filter(I=>I.teamId===y),$=Cs.find(I=>I.type==="team"&&I.teamId===y);return c.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[c.jsx("button",{onClick:()=>{window.location.hash=Yt.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[c.jsx("div",{className:"w-8 h-8 rounded-lg bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("h3",{className:"text-sm font-semibold text-fg-primary truncate",children:w.name}),c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:i("chat.members_other",{count:w.members?.length||Q.length})})]})]})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-1",children:[(()=>{const I=$?.channelKey??Hv(y),H=Yl[I]??0;return c.jsxs("button",{onClick:()=>{$t("channel"),Bs(I),_("chat"),k()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[c.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:$?.name??w.name}),c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:i("chat.groupChat")})]}),H>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:H}):c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary shrink-0",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]})})(),Q.length>0&&c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider px-2.5 pt-2",children:i("chat.agents")}),Q.map(I=>{const H=Gl.get(I.id)??0,ie=I.status==="offline";return c.jsxs("button",{onClick:()=>{$t("direct"),Us(I.id),_("chat"),k()},className:`w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors ${ie?"opacity-50":""}`,children:[c.jsx(Ns,{name:I.name||"Agent",avatarUrl:I.avatarUrl,size:36}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"text-sm font-medium text-fg-primary truncate flex items-center gap-1.5",children:[I.name,ie&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:i("common:status.offline")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate",children:I.role||I.status})]}),H>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:H}):c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Ol(I.status,hs.isAgentStreaming(I.id)).dotClass}`})]},I.id)})]})]})]})})(),!j&&Qe&&!qe&&!v&&!L&&(()=>{const w=ns??(le==="direct"?Mt?.teamId:void 0);if(!w)return null;const Q=As.find(I=>I.id===w);if(!Q)return null;const $=Cs.find(I=>I.type==="team"&&I.teamId===w);return c.jsx(i0,{team:Q,agents:l,humans:d,authUser:e,groupChat:$,chatMode:le,selectedAgent:ge,activeChannel:gt,activeDmUserId:_t,teams:As,onSelectAgent:I=>{su(I),Ps(!1)},onSelectChannel:I=>{$t("channel"),Bs(I),_("chat"),Ps(!1)},onSelectDm:I=>{$t("dm"),ln(I),_("chat"),Ps(!1)},onBack:()=>Ee(!1),onViewProfile:dt,onRefreshAgents:ar,onRefreshTeams:Gs,unreadByAgent:Gl,width:ye.width,onResizeStart:ye.onResizeStart,focused:K==="l2"&&aO})})(),!j&&Ye&&!v&&!L&&(()=>{if(!kn)return null;const w=As.find($=>$.id===kn);if(!w)return null;const Q=Cs.find($=>$.type==="team"&&$.teamId===kn);return c.jsxs("div",{"data-l2-floating":!0,className:"absolute z-30 inset-0",style:{left:R.width+6},children:[c.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:()=>pt(!1)}),c.jsx("div",{className:"relative h-full",style:{width:ye.width+8},children:c.jsx(i0,{team:w,agents:l,humans:d,authUser:e,groupChat:Q,chatMode:le,selectedAgent:ge,activeChannel:gt,activeDmUserId:_t,teams:As,onSelectAgent:$=>{su($),Ps(!1),pt(!1)},onSelectChannel:$=>{$t("channel"),Bs($),_("chat"),Ps(!1),pt(!1)},onSelectDm:$=>{$t("dm"),ln($),_("chat"),Ps(!1),pt(!1)},onBack:()=>pt(!1),onViewProfile:$=>{dt($),pt(!1)},onRefreshAgents:ar,onRefreshTeams:Gs,unreadByAgent:Gl,width:ye.width,focused:K==="l2"&&aO})})]})})(),!j&&(!v||Wk)&&c.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col ${v||F?"min-w-0":"min-w-[400px]"}`,children:[c.jsxs("div",{className:"shrink-0 relative pb-2",children:[v?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center px-3 h-11 gap-2",children:[c.jsx("button",{onClick:()=>{window.location.hash=Xk},className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsxs("div",{className:"flex-1 min-w-0 flex items-center justify-center gap-1.5",children:[c.jsx("span",{className:"font-semibold text-sm truncate min-w-0",children:pO}),le==="direct"&&Mt&&c.jsx(AI,{agent:Mt})]}),c.jsx("button",{onClick:()=>pn(w=>!w),"aria-label":i("page.moreActions",{defaultValue:"更多操作"}),className:`p-1.5 rounded-md transition-colors shrink-0 ${Og?"bg-brand-500/15 text-brand-500":"text-fg-secondary"}`,children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor",children:[c.jsx("circle",{cx:"5",cy:"12",r:"1.7"}),c.jsx("circle",{cx:"12",cy:"12",r:"1.7"}),c.jsx("circle",{cx:"19",cy:"12",r:"1.7"})]})})]}),Og&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>pn(!1)}),c.jsxs("div",{className:"absolute right-2 top-full z-50 w-44 py-1 bg-surface-secondary border border-border-default rounded-xl shadow-2xl shadow-black/40",children:[c.jsxs("button",{onClick:()=>{pn(!1),qi(P)||ht()},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"8",r:"3.5"}),c.jsx("path",{d:"M5 20a7 7 0 1 1 14 0"})]}),i(le==="channel"?"page.teamTab":"page.profileTab")]}),c.jsxs("button",{onClick:()=>{pn(!1),Fn(!0)},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),i("page.findInConversation")]}),le==="direct"&&!qi(P)&&c.jsxs("button",{onClick:()=>{pn(!1),Oa()},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M12 5v14M5 12h14"})}),i("page.newChat")]}),le==="direct"&&!qi(P)&&c.jsxs("button",{ref:Xl,onClick:()=>{pn(!1),mn(!0)},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})}),i("page.historyTitle")]}),le==="channel"&&Ms?.type==="custom"&&c.jsxs("button",{onClick:()=>{pn(!1),Ps(!0)},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),i("page.membersTitle",{defaultValue:"成员"})," (",Ms.members?.length??Ms.memberCount??0,")"]})]})]})]}):(()=>{const w=ns?As.find(xe=>xe.id===ns):void 0,Q=le==="direct"&&ge?kI:le==="channel"&&ns?CI:["chat"],$=async()=>{const xe=ee.trim();if(!xe){Ve(!1);return}try{le==="direct"&&ge?(await te.agents.updateConfig(ge,{name:xe}),ar()):le==="channel"&&ns&&(await te.teams.update(ns,{name:xe}),Gs())}catch{}Ve(!1)},I=async()=>{try{le==="direct"&&ge?(await te.agents.updateConfig(ge,{title:_e}),ar()):le==="channel"&&ns&&(await te.teams.update(ns,{description:_e}),Gs())}catch{}Oe(!1)},H=le==="direct"?Mt?.name:le==="channel"?w?.name??Ms?.name:Pn?.name??"",ie=le==="direct"?Mt?.role||"":le==="channel"&&w?.description||"",ne=le==="direct"?Mt?.avatarUrl:void 0,Ce=H||"U",Le=le==="direct"&&ge||le==="channel"&&ns;return c.jsxs("div",{className:"flex flex-col",children:[c.jsxs("div",{"data-electron-drag":!0,className:"flex items-center px-4 h-14 gap-2.5",children:[L&&!v&&c.jsx("button",{onClick:()=>E(!1),className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",title:i("page.toggleSidebar"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),(!Qe||qe)&&(le==="channel"&&ns||le==="direct"&&Mt?.teamId)&&c.jsx("button",{onClick:xt,className:`w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 ${Ye?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:"Toggle team panel",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),Le&&c.jsx("div",{"data-no-drag":!0,className:"shrink-0",children:le==="channel"&&ns?c.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-600 text-white flex items-center justify-center text-sm font-bold",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}):c.jsxs("div",{className:"relative",ref:ce,children:[c.jsx("button",{type:"button",onClick:()=>he(xe=>!xe),className:"block rounded-xl shrink-0 transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500",title:i("page.editAgentAvatar"),"aria-label":i("page.editAgentAvatar"),"aria-expanded":us,children:c.jsx(Ns,{name:Ce,avatarUrl:ne,size:36,className:"rounded-xl shrink-0 pointer-events-none"})}),us&&c.jsx("div",{"data-no-drag":!0,className:"absolute z-50 top-full left-0 mt-1.5 p-3 rounded-xl bg-surface-secondary border border-border-default shadow-2xl",children:c.jsx(yC,{currentUrl:ne,name:Ce,size:64,targetType:"agent",targetId:Mt?.id,onUploaded:xe=>{he(!1),ck(Mt?.id,xe),ar()}})})]})}),Le?c.jsxs("div",{"data-no-drag":!0,className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[ze?c.jsx("input",{ref:at,value:ee,onChange:xe=>Te(xe.target.value),onBlur:$,onKeyDown:xe=>{xe.key==="Enter"&&$(),xe.key==="Escape"&&Ve(!1)},className:"text-sm font-semibold bg-transparent border-b border-brand-500 outline-none py-0 px-0 min-w-[80px] max-w-[240px]",autoFocus:!0}):c.jsx("span",{className:"text-sm font-semibold truncate cursor-pointer hover:text-brand-500 transition-colors",onClick:()=>{Te(H??""),Ve(!0)},title:"Click to edit name",children:H}),le==="direct"&&Mt&&c.jsx(MI,{agent:Mt,tasks:$d,onViewProfile:dt})]}),(le==="direct"||le==="channel"&&ns)&&(Se?c.jsx("input",{ref:wt,value:_e,onChange:xe=>Fe(xe.target.value),onBlur:I,onKeyDown:xe=>{xe.key==="Enter"&&I(),xe.key==="Escape"&&Oe(!1)},className:"text-[11px] text-fg-tertiary bg-transparent border-b border-brand-500/50 outline-none py-0 px-0 w-full max-w-[400px] mt-0.5",placeholder:"Add title...",autoFocus:!0}):c.jsx("div",{className:"text-[11px] text-fg-tertiary truncate cursor-pointer hover:text-fg-secondary transition-colors mt-0.5",onClick:()=>{Fe(ie),Oe(!0)},title:"Click to edit title",children:ie||"No title"}))]}):c.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[c.jsx("span",{className:"font-semibold text-sm truncate",children:pO}),le==="dm"&&c.jsx("span",{className:"text-xs text-fg-tertiary",children:lo?i("page.privateNotepad"):""})]}),c.jsxs("div",{"data-no-drag":!0,className:"ml-auto flex items-center gap-2 shrink-0",children:[c.jsx("button",{onClick:()=>{Fn(xe=>!xe),Cd&&sa(-1)},className:`p-1.5 rounded-md transition-colors ${Cd?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:`${i("page.findInConversationHint")} (${RO(["F"],b)})`,"data-testid":"find-in-conversation-btn",children:c.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:[c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8 6h11M8 12h11M8 18h6"}),c.jsx("circle",{cx:"17.5",cy:"17.5",r:"3.5"}),c.jsx("path",{strokeLinecap:"round",d:"M20.5 20.5L22 22"})]})}),le==="channel"&&Ms?.type==="custom"&&c.jsxs("button",{onClick:()=>Ps(!kd),className:`text-xs px-2.5 py-1 rounded-md border transition-colors flex items-center gap-1.5 ${kd?"bg-brand-500/15 text-brand-500 border-brand-500/30":"text-fg-secondary hover:text-fg-primary border-border-default hover:bg-surface-elevated"}`,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Ms.members?.length??Ms.memberCount??0]}),le==="direct"&&Mt&&P==="chat"&&c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("button",{onClick:Oa,title:i("page.newChatKbdHint",{kbd:RO(["N"],b)}),className:"text-xs text-brand-500 hover:text-brand-500 px-2.5 py-1 rounded-md hover:bg-brand-500/10 border border-brand-500/20 transition-colors flex items-center gap-1",children:i("page.newChatButton")}),c.jsx("button",{ref:Xl,onClick:()=>mn(!Go),className:`p-1.5 rounded-md transition-colors ${Go?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:i("page.historyTitle"),children:c.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]}),!v&&B&&c.jsx("button",{onClick:()=>B.toggleRightPanel(),className:`p-1.5 rounded-md transition-colors ${F?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:i("page.rightPanelToggle",{defaultValue:"Toggle side panel"}),children:c.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:[c.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),c.jsx("path",{d:"M15 4v16"})]})})]})]}),Q.length>1&&c.jsx("div",{className:"flex items-center gap-1 px-4 pb-1.5 overflow-x-auto scrollbar-hide",children:Q.map(xe=>c.jsxs("button",{onClick:()=>_(xe),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${P===xe?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{children:TI(xe)}),PI(xe,i)]},xe))})]})})(),le==="direct"&&ge&&P==="chat"&&Ws.length>1&&(()=>{const w=Q=>hs.isStreaming(Q.id);return c.jsx("div",{ref:Cg,className:"flex items-center gap-0 px-3 overflow-x-auto scrollbar-hide",children:Ws.map(Q=>{const $=Im(Q,i);return c.jsxs("div",{"data-session-tab-id":Q.id,title:Dv(Q,i),className:`group flex items-center gap-1.5 px-3 py-1.5 text-xs cursor-pointer rounded-md transition-colors shrink-0 max-w-[180px] ${Q.id===et?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>{if(Q.id===it){Ei(it);const I=jt.current;me(I,it),_s([])}else Ii(Q)},children:[Q.isMain&&c.jsx("span",{className:"text-[10px] opacity-50 shrink-0",children:"●"}),c.jsx("span",{className:"truncate",children:$}),w(Q)&&c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-500 animate-pulse shrink-0",title:i("common:status.working"),"aria-label":i("common:status.working"),"data-testid":"session-tab-streaming"}),!Q.isMain&&c.jsx("button",{onClick:I=>{I.stopPropagation(),Ck(Q.id)},className:"opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-fg-secondary transition-opacity shrink-0",children:"✕"})]},Q.id)})})})(),Cd&&P==="chat"&&c.jsx($D,{query:zl,onQueryChange:Pk,matches:pa.matches,cursor:q_,scanned:pa.scanned,truncated:pa.truncated,hasMore:E_,loadingMore:hd,onLoadEarlier:()=>{Yg()},onJump:fk,onClose:()=>{Fn(!1),sa(-1)},serverResults:Z_,serverLoading:V_,onServerResultClick:Tk,labelFor:w=>{const Q=os[w.messageIndex];if(!Q)return"";const $=Q.sender==="user"?i("page.you",{defaultValue:"你"}):Q.agentName??"",I=Q.rawCreatedAt?cc(Q.time,Q.rawCreatedAt,a):Q.time;return[$,I].filter(Boolean).join(" · ")}}),le==="direct"&&P==="chat"&&(Ws.find(w=>w.id===et)??$r.find(w=>w.id===et))?.metadata?.kind==="evolution"&&c.jsx("div",{className:"px-4 py-1.5 text-[11px] text-fg-tertiary border-b border-border-default bg-surface-secondary/40",children:i("page.messageActions.evolvedFrom")}),le==="channel"&&Ms?.type==="custom"&&kd&&(()=>{const w=Ms,Q=w.members??[],$=[];for(const I of l)Q.some(H=>H.id===I.id)||$.push({id:I.id,name:I.name,type:"agent",subtitle:I.role||"Agent"});for(const I of d)Q.some(H=>H.id===I.id)||$.push({id:I.id,name:I.name,type:"human",subtitle:I.email||I.role||""});return c.jsx(CD,{members:Q,candidates:$,currentUserId:e?.id,memberCount:Q.length,onClose:()=>Ps(!1),onRemoveMember:I=>{te.groupChats.removeMember(w.id,I).then(()=>{ta(H=>H.map(ie=>ie.id===w.id?{...ie,members:(ie.members??[]).filter(ne=>ne.id!==I),memberCount:(ie.memberCount??1)-1}:ie))}).catch(()=>{})},onAddMember:I=>{const H=$.find(ie=>ie.id===I);H&&te.groupChats.addMember(w.id,H.id,H.type,H.name).then(()=>{ta(ie=>ie.map(ne=>ne.id===w.id?{...ne,members:[...ne.members??[],{id:H.id,name:H.name,type:H.type}],memberCount:(ne.memberCount??0)+1}:ne))}).catch(()=>{})}})})(),le==="direct"&&ge&&Go&&c.jsxs("div",{ref:wd,className:"absolute right-4 top-full mt-1 w-72 max-h-[420px] bg-surface-secondary border border-border-default rounded-xl shadow-2xl shadow-black/40 z-50 flex flex-col overflow-hidden",children:[c.jsxs("div",{className:"px-4 py-3 border-b border-border-default flex items-center justify-between",children:[c.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:i("page.historyTitle")}),c.jsx("button",{onClick:()=>mn(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:"✕"})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[M_&&$r.length===0?c.jsx(qv,{rows:3,variant:"skeleton",className:"px-2 py-2"}):$r.length===0?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6",children:i("page.noConversationsYet")}):null,(()=>{const w=new Date,Q=new Date(w.getFullYear(),w.getMonth(),w.getDate()).getTime(),$=Q-864e5,I=Q-7*864e5,H=[],ie=[],ne=[],Ce=[],Le=[];for(const xe of $r){const ke=new Date(xe.lastMessageAt).getTime();ke>=Q?ie.push(xe):ke>=$?ne.push(xe):ke>=I?Ce.push(xe):Le.push(xe)}return ie.length>0&&H.push({label:i("page.dateToday"),items:ie}),ne.length>0&&H.push({label:i("page.dateYesterday"),items:ne}),Ce.length>0&&H.push({label:i("page.datePrevious7Days"),items:Ce}),Le.length>0&&H.push({label:i("page.dateOlder"),items:Le}),H.map(xe=>c.jsxs("div",{className:"mb-2",children:[c.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-3 py-1.5",children:xe.label}),xe.items.map(ke=>c.jsx("div",{className:`w-full text-left px-3 py-2 rounded-lg text-xs mb-0.5 transition-colors ${ke.id===et?"bg-brand-600/20 text-brand-500":"hover:bg-surface-elevated"}`,children:gd===ke.id?c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{autoFocus:!0,value:Od,onChange:Ae=>xd(Ae.target.value),onKeyDown:Ae=>{Ae.key==="Enter"&&(Ae.stopPropagation(),Hg(ke)),Ae.key==="Escape"&&ga()},onClick:Ae=>Ae.stopPropagation(),placeholder:ke.isMain?i("page.sessionMain"):ke.title||i("page.sessionConversation"),className:"w-full bg-surface-primary border border-brand-500/50 rounded-md px-2 py-1 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50"}),c.jsx("button",{onClick:Ae=>{Ae.stopPropagation(),Hg(ke)},className:"text-brand-400 hover:text-brand-300 shrink-0",title:i("common:save"),children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M20 6L9 17l-5-5"})})}),c.jsx("button",{onClick:Ae=>{Ae.stopPropagation(),ga()},className:"text-fg-tertiary hover:text-fg-secondary shrink-0",title:i("common:cancel"),children:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}):c.jsxs("button",{onClick:()=>{Ii(ke)},title:Dv(ke,i),className:"w-full text-left group/session",children:[c.jsxs("div",{className:"truncate font-medium flex items-center gap-1",children:[ke.isMain&&c.jsx("span",{className:"text-[10px] text-brand-500 opacity-80",children:"●"}),c.jsx("span",{className:"truncate",children:Im(ke,i)}),!ke.isMain&&c.jsx("span",{role:"button",tabIndex:0,onClick:Ae=>{Ae.stopPropagation(),Ug(ke)},onKeyDown:Ae=>{Ae.key==="Enter"&&(Ae.stopPropagation(),Ug(ke))},className:"opacity-0 group-hover/session:opacity-100 transition-opacity ml-auto text-fg-tertiary hover:text-brand-400 shrink-0",title:i("page.renameSession"),children:c.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})})]}),c.jsx("div",{className:"text-fg-tertiary text-[10px] mt-0.5",children:new Date(ke.lastMessageAt).toLocaleString()})]})},ke.id))]},xe.label))})(),Dl&&c.jsx("button",{onClick:()=>{Ok()},disabled:Bl,className:"w-full text-center text-[11px] text-fg-tertiary hover:text-brand-400 py-2 rounded-lg transition-colors disabled:opacity-50",children:Bl?i("page.loadingEarlierMessages"):`${i("page.loadMoreSessions")} (${$r.length}/${I_})`})]})]})]}),v&&P==="profile"&&le==="direct"&&ge&&c.jsx("div",{className:"flex-1 overflow-y-auto",children:c.jsx(vv,{agentId:ge,onBack:()=>_("chat"),inline:!0,defaultTab:$e,initialSection:de,highlightMailboxId:ve,onSwipeBack:()=>{qi(T.current)?history.back():_("chat")},authUser:e})}),v&&P==="profile"&&le==="channel"&&ns&&c.jsx("div",{className:"flex-1 overflow-y-auto",children:c.jsx(Av,{teamId:ns,onBack:()=>_("chat"),inline:!0,onSelectAgent:w=>{$t("direct"),Us(w),_("chat")}})}),!v&&qi(P)&&le==="direct"&&ge&&c.jsx("div",{className:"flex-1 overflow-y-auto",children:c.jsx(vv,{agentId:ge,onBack:()=>_("chat"),inline:!0,headless:!0,activeTab:P,initialSection:de,highlightMailboxId:ve,authUser:e})}),!v&&qi(P)&&le==="channel"&&ns&&c.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:c.jsx(Av,{teamId:ns,onBack:()=>_("chat"),inline:!0,headless:!0,activeTab:P,onSelectAgent:w=>{$t("direct"),Us(w),_("chat")}})}),c.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col relative ${Sa?"justify-center":""} ${P!=="chat"?"hidden":""}`,children:[fn&&os.length===0&&c.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-2.5",role:"status","aria-live":"polite",children:[c.jsx(WC,{className:"h-6 w-6 text-brand-400"}),c.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[c.jsx("span",{className:"text-xs text-fg-tertiary animate-pulse",children:i("page.loadingChat",{defaultValue:"Loading conversation…"})}),c.jsx("span",{className:"text-[11px] text-fg-muted max-w-[70%] truncate",children:zk})]})]}),A_&&c.jsx("div",{className:"absolute top-0 left-0 right-0 z-10 flex justify-center pointer-events-none pt-2",children:c.jsxs("span",{className:"flex items-center gap-2 px-3 py-1.5 rounded-full bg-surface-secondary/90 backdrop-blur-sm border border-border-default shadow",children:[c.jsxs("svg",{className:"animate-spin h-3.5 w-3.5 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:i("page.loadingEarlierMessages")})]})}),c.jsxs("div",{ref:Vr,"data-swipe-owner":!0,className:`${Sa?"hidden":"flex-1"} overflow-y-auto scrollbar-thin ${v?"px-4 py-2":`p-5 ${W}`}`,onScroll:xk,children:[os.length>0&&c.jsx("div",{style:{height:so.getTotalSize(),width:"100%",position:"relative"},children:so.getVirtualItems().map(w=>{const Q=w.index,$=os[Q],I=Q>0?os[Q-1]:null,H=EO($.rawCreatedAt),ie=I?EO(I.rawCreatedAt):"",ne=!!(H&&ie&&H!==ie),Ce=Q===os.length-1,Le=j2({msgIsStreaming:!!$.isStreaming,liveStreamForView:aa}),xe=Nk&&Ce||Le,ke=le==="channel"||!Le||$.isStopped;return c.jsx("div",{"data-index":Q,ref:so.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${w.start}px)`},children:c.jsxs("div",{className:"pb-3",children:[ne&&c.jsxs("div",{className:"flex items-center gap-3 py-2 my-1",children:[c.jsx("div",{className:"flex-1 h-px bg-border-default"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium uppercase tracking-wider shrink-0",children:SC($.rawCreatedAt,a)}),c.jsx("div",{className:"flex-1 h-px bg-border-default"})]}),c.jsxs("div",{id:`msg-${$.id}`,className:`group/msg flex transition-colors rounded-lg ${v?"gap-0":"gap-3"}`,children:[le==="channel"?c.jsx("div",{className:`shrink-0 cursor-pointer ${v?"hidden":""}`,onClick:Ae=>{if($.sender==="agent"&&$.agentId){const Ue=Ae.currentTarget.getBoundingClientRect();At({agentId:$.agentId,top:Ue.top,left:Ue.right+8})}},children:c.jsx(Ns,{name:$.sender==="user"?ac:$.agentName??i("page.fallbackAgent"),avatarUrl:$.sender==="user"?e?.avatarUrl:l.find(Ae=>Ae.id===$.agentId)?.avatarUrl,size:32,bgClass:$.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:$.sender==="agent"?"hover:ring-1 hover:ring-brand-500/40 rounded-lg":"rounded-lg"})}):c.jsx("div",{className:`shrink-0 ${v?"hidden":""}`,children:c.jsx(Ns,{name:$.sender==="user"?ac:$.agentName??(le==="direct"?Mt?.name??i("page.fallbackAgent"):i("page.fallbackAgent")),avatarUrl:$.sender==="user"?e?.avatarUrl:l.find(Ae=>Ae.id===($.agentId??(le==="direct"?Mt?.id:void 0)))?.avatarUrl,size:32,bgClass:$.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded-lg"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-baseline gap-2",children:[v&&c.jsx(Ns,{name:$.sender==="user"?ac:$.agentName??(le==="direct"?Mt?.name??i("page.fallbackAgent"):i("page.fallbackAgent")),avatarUrl:$.sender==="user"?e?.avatarUrl:l.find(Ae=>Ae.id===($.agentId??(le==="direct"?Mt?.id:void 0)))?.avatarUrl,size:22,bgClass:$.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded self-center"}),c.jsx("span",{className:"text-sm font-medium text-fg-primary",children:$.sender==="user"?ac:le==="channel"?$.agentName??i("page.fallbackAgent"):c.jsx(wC,{name:$.agentName??(le==="direct"?Mt?.name??i("page.fallbackAgent"):i("page.fallbackAgent")),agentId:$.agentId??(le==="direct"?Mt?.id:void 0),agents:l,onViewProfile:dt})}),c.jsx("span",{className:"text-xs text-fg-tertiary",title:$.rawCreatedAt?new Date($.rawCreatedAt).toLocaleString():"",children:cc($.time,$.rawCreatedAt,a)})]}),$.replyToId&&$.replyToSender&&c.jsxs("button",{onClick:()=>{const Ae=document.getElementById(`msg-${$.replyToId}`);Ae&&(Ae.scrollIntoView({behavior:"smooth",block:"center"}),Ae.classList.add("bg-brand-500/10"),setTimeout(()=>Ae.classList.remove("bg-brand-500/10"),1500))},className:"flex items-center gap-1.5 mt-0.5 mb-1 pl-2 py-0.5 border-l-2 border-brand-500/40 text-xs text-fg-tertiary hover:text-fg-secondary transition-colors cursor-pointer",children:[c.jsx("span",{className:"font-medium text-brand-500",children:$.replyToSender}),c.jsx("span",{className:"truncate max-w-[250px]",children:$.replyToText??"..."})]}),c.jsxs("div",{className:`mt-0.5 ${$.sender==="agent"?"py-1":"bg-surface-secondary rounded-2xl px-3.5 py-2.5 w-fit max-w-full"} ${xe&&$.sender==="agent"?"streaming-bubble":""}`,children:[$.sender==="user"?c.jsxs("div",{className:"text-sm text-fg-secondary whitespace-pre-wrap",children:[$.images&&$.images.length>0&&c.jsx("div",{className:"flex flex-wrap gap-1.5 mb-1",children:$.images.map((Ae,Ue)=>c.jsx("img",{src:Ae,alt:"",className:"max-w-[200px] max-h-[150px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>fg(Ae)},Ue))}),le==="channel"?LO($.text,l,(Ae,Ue)=>{const ct=Ue.currentTarget.getBoundingClientRect();At({agentId:Ae.id,top:ct.bottom,left:ct.left})}):$.text&&c.jsx("span",{className:"leading-relaxed",children:LO($.text,l,(Ae,Ue)=>{const ct=Ue.currentTarget.getBoundingClientRect();At({agentId:Ae.id,top:ct.bottom,left:ct.left})})})]}):$.sender==="agent"&&le==="channel"&&!($.segments&&$.segments.length>0)?Le&&!$.text?.trim()?c.jsx(_C,{activities:$l,isActive:!0}):c.jsx(AO,{resetKeys:[$.text],fallback:c.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:$.text}),children:c.jsx($o,{content:$.text,className:"text-sm text-fg-secondary",onMentionClick:Qt,knownNames:hi})}):c.jsx(AO,{resetKeys:[$.id,$.text,$.segments?.length,Le],fallback:c.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:$.text}),children:c.jsx(kC,{msg:$,isStreaming:Le,liveActivities:Le?$l:[],onMentionClick:Qt,knownNames:hi})}),$.isNotification&&c.jsx(CC,{priority:$.notifyPriority})]}),ke&&!t&&c.jsx("div",{className:`transition-opacity ${$.isStopped||$.isError||$.emptyReply||v?"opacity-100":"opacity-0 group-hover/msg:opacity-100"}`,children:c.jsx(PC,{msg:$,onCopy:yk,onRetry:Sk,onResume:wk,onReply:_k,onRemember:le==="direct"?Hd:void 0,showRemember:le==="direct",isCopied:bk===$.id,isLastAgentMsg:$.id===vk})})]})]})]})},$.id)})}),c.jsx("div",{ref:ik}),dk&&P==="chat"&&c.jsx("div",{className:"sticky bottom-0 z-20 h-0 pointer-events-none",children:c.jsx("div",{className:"absolute inset-x-0 bottom-2 flex justify-center",children:c.jsxs("button",{onClick:()=>{lr(),cr("smooth")},className:"pointer-events-auto flex items-center gap-1.5 px-3.5 py-2 bg-surface-secondary/90 backdrop-blur-sm border border-border-default rounded-full shadow-lg hover:bg-surface-elevated transition-colors text-xs text-fg-secondary",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})}),Ig>0?i("page.newMessages",{count:Ig}):i("page.scrollToBottom")]})})})]}),ot&&(()=>{const w=l.find(Q=>Q.id===ot.agentId);return w?c.jsx(TC,{agent:w,anchorRect:{top:ot.top,left:ot.left},onClose:()=>At(null),onViewProfile:dt}):null})(),Sa&&(OO||iu)&&c.jsx("div",{className:"text-center mb-4",children:c.jsx("h2",{className:"text-xl font-semibold text-fg-primary",children:OO||iu})}),le==="direct"&&(bg.length>0||Ko.length>0||wg.length>0)&&c.jsx("div",{className:`${v?"px-3":"px-5"} pb-1 shrink-0 ${Sa?"":W}`,children:c.jsxs("div",{className:`${v?"":"max-w-3xl mx-auto"} flex flex-col gap-1.5`,children:[bg.map(w=>c.jsxs("button",{onClick:()=>Wl(w),className:"w-full text-left px-3.5 py-2.5 rounded-xl border border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/15 transition-colors flex items-center gap-3",children:[c.jsx("span",{className:"w-8 h-8 rounded-lg bg-amber-500/20 text-amber-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z"}),c.jsx("path",{d:"M12 8v4"}),c.jsx("path",{d:"M12 16h.01"})]})}),c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsxs("span",{className:"flex items-baseline gap-1.5 min-w-0",children:[c.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary truncate",children:w.title}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0 whitespace-nowrap",children:cc(w.requestedAt,w.requestedAt,a)})]}),c.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:i("page.userInputPrompt",{count:w.questions?.length??1,defaultValue:`${w.questions?.length??1} question(s) awaiting your response`})})]}),c.jsxs("span",{className:"text-xs font-medium text-amber-500 shrink-0 inline-flex items-center gap-1",children:[i("page.userInputRespond",{defaultValue:"Respond"}),c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},w.id)),Ko.map(w=>c.jsxs("button",{onClick:()=>Jo(w),className:"w-full text-left px-3.5 py-2.5 rounded-xl border border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/15 transition-colors flex items-center gap-3",children:[c.jsx("span",{className:"w-8 h-8 rounded-lg bg-amber-500/20 text-amber-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}),c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsxs("span",{className:"flex items-baseline gap-1.5 min-w-0",children:[c.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary truncate",children:w.title}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0 whitespace-nowrap",children:cc(w.requestedAt,w.requestedAt,a)})]}),c.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:i("page.toolApprovalPrompt",{defaultValue:"Tool execution awaiting your approval"})})]}),c.jsxs("span",{className:"text-xs font-medium text-amber-500 shrink-0 inline-flex items-center gap-1",children:[i("page.toolApprovalReview",{defaultValue:"Review"}),c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},w.id)),wg.map(w=>{const Q=w.priority==="high"||w.priority==="urgent";return c.jsxs("button",{onClick:()=>ea({items:[w],index:0}),className:`w-full text-left px-3.5 py-2.5 rounded-xl border transition-colors flex items-center gap-3 ${Q?"border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/15":"border-blue-500/40 bg-blue-500/10 hover:bg-blue-500/15"}`,children:[c.jsx("span",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${Q?"bg-amber-500/20 text-amber-500":"bg-blue-500/20 text-blue-500"}`,children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),c.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsxs("span",{className:"flex items-baseline gap-1.5 min-w-0",children:[c.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary truncate",children:QC(w,i)}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0 whitespace-nowrap",title:zm(w.createdAt,n.language),children:Xm(w.createdAt,i)})]}),c.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:$C(w,i).replace(/\s+/g," ").trim()||i("page.notifyUserPrompt",{defaultValue:"Agent notification awaiting your attention"})})]}),c.jsxs("span",{className:`text-xs font-medium shrink-0 inline-flex items-center gap-1 ${Q?"text-amber-500":"text-blue-500"}`,children:[i("page.notifyUserView",{defaultValue:"View"}),c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},w.id)})]})}),gn&&c.jsx(jC,{approval:gn,submitting:B_===gn.id,readOnly:gn.status!=="pending",onClose:()=>Wl(null),onSubmit:w=>Dk(gn.id,w)}),On&&c.jsx(o2,{approval:On,submitting:W_===On.id,readOnly:On.status!=="pending",onClose:()=>Jo(null),onDecision:(w,Q)=>Ik(On.id,w,Q)}),Ai&&c.jsx(a2,{notification:Ai,agentName:Mt?.name,acknowledging:X_===Ai.id,index:jr?.index??0,total:jr?.items.length??1,onClose:tu,onAcknowledge:()=>Bk(Ai.id)}),Di&&c.jsx(Wo,{variant:"primary",title:i("page.retry",{defaultValue:"Retry"}),message:Di.followCount===1?i("page.retryConfirmSingular"):i("page.retryConfirmPlural",{count:Di.followCount}),confirmLabel:i("common:confirm"),onConfirm:()=>{const w=Di;Yd(null),Gd(w.retryMsg,w.userMsg,w.retryText)},onCancel:()=>Yd(null)}),Rr&&c.jsx(RC,{busy:Kg,onConfirm:w=>{kk(w)},onCancel:()=>{Kg||Hd(null)}}),c.jsxs("div",{"data-keep-edit-focus":!0,className:`${v?"px-3 py-2":"px-5 py-3"} relative shrink-0 ${Sa?"":W}`,onDrop:Mk,onDragOver:Lk,children:[c.jsxs("div",{className:`bg-surface-primary border border-border-default shadow-lg shadow-black/10 ${v?`${vr?"rounded-2xl p-2":"rounded-2xl p-3"}`:`${vr?"rounded-2xl p-2":"rounded-2xl p-3"} max-w-3xl mx-auto`}`,children:[Un&&Cn.length>0&&c.jsxs("div",{className:"absolute bottom-full left-4 mb-1 bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden z-10 max-h-64 max-w-xs w-72 overflow-y-auto",children:[c.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:i("page.mentionAgent")}),Cn.map((w,Q)=>w.kind==="agent"?c.jsxs("button",{ref:$=>{Q===ia&&$&&$.scrollIntoView({block:"nearest"})},onClick:()=>oc(w.agent.name),onMouseEnter:()=>Hn(Q),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${Q===ia?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx(Ns,{name:w.agent.name,avatarUrl:w.agent.avatarUrl,size:24,bgClass:"bg-brand-500/20 text-brand-500"}),c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-overlay text-fg-tertiary shrink-0",children:i("page.mentionType.agent")}),c.jsx("span",{className:"flex-1 min-w-0 truncate",children:w.agent.name}),c.jsx("span",{className:"text-xs text-fg-tertiary ml-auto shrink-0",children:w.agent.role})]},`agt-${w.agent.id}`):c.jsxs("button",{ref:$=>{Q===ia&&$&&$.scrollIntoView({block:"nearest"})},onClick:()=>oc(w.entity.name,w.entity.entityType,w.entity.id),onMouseEnter:()=>Hn(Q),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${Q===ia?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx("span",{className:"w-6 h-6 flex items-center justify-center text-sm shrink-0",children:fO[w.entity.entityType]??"📄"}),c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-overlay text-fg-tertiary shrink-0",children:i(`page.mentionType.${w.entity.entityType}`,{defaultValue:w.entity.entityType})}),c.jsx("span",{className:"flex-1 min-w-0 truncate",children:w.entity.name}),c.jsx("span",{className:"text-xs text-fg-tertiary ml-auto shrink-0",children:w.entity.role})]},`${w.entity.entityType}-${w.entity.id}`))]}),Yn&&xn.length>0&&c.jsxs("div",{className:"absolute bottom-full left-4 mb-1 bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden z-10 max-h-64 max-w-xs w-72 overflow-y-auto",children:[c.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:i("page.slashSkill")}),xn.map((w,Q)=>c.jsxs("button",{ref:$=>{Q===jd&&$&&$.scrollIntoView({block:"nearest"})},onClick:()=>nO(w),onMouseEnter:()=>na(Q),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${Q===jd?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx("span",{className:"text-xs w-5 h-5 flex items-center justify-center shrink-0",children:"🔧"}),c.jsxs("span",{className:"flex-1 min-w-0 truncate font-mono text-[13px]",children:["/",w.name]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto shrink-0 max-w-[100px] truncate",children:w.description})]},w.name))]}),nr.length>0&&c.jsx("div",{className:"flex items-center gap-1.5 mb-2 flex-wrap",children:nr.map(w=>c.jsxs("span",{className:"inline-flex items-center gap-1 max-w-[240px] pl-2 pr-1 py-1 rounded-lg bg-brand-500/10 text-brand-500 text-xs border border-brand-500/20",title:w.content,children:[c.jsx("span",{className:"truncate",children:w.label}),c.jsx("button",{onClick:()=>dn(Q=>Q.filter($=>$.id!==w.id)),className:"w-4 h-4 flex items-center justify-center rounded hover:bg-brand-500/20 shrink-0","aria-label":i("common:remove",{defaultValue:"Remove"}),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},w.id))}),or.length>0&&c.jsxs("div",{className:"flex items-center gap-2 mb-2 overflow-x-auto pb-1",children:[or.map(w=>c.jsxs("div",{className:"relative group/img shrink-0",children:[Kd(w)?c.jsx("img",{src:w.dataUrl,alt:w.name,className:"w-16 h-16 rounded-lg object-cover border border-border-default"}):c.jsxs("div",{className:"w-16 h-16 rounded-lg border border-border-default bg-surface-elevated flex flex-col items-center justify-center gap-0.5",title:w.name,children:[c.jsx("span",{className:"text-xl leading-none",children:Rk(w.name,w.dataUrl)}),c.jsx("span",{className:"text-[9px] text-fg-tertiary truncate max-w-[56px] px-0.5",children:w.name.split(".").pop()?.toUpperCase()})]}),c.jsx("button",{onClick:()=>Ek(w.id),className:"absolute -top-1.5 -right-1.5 w-5 h-5 bg-surface-secondary border border-gray-600 rounded-full flex items-center justify-center text-fg-secondary hover:text-red-500 hover:border-red-500 text-xs opacity-0 group-hover/img:opacity-100 transition-opacity",children:"×"})]},w.id)),or.length<oO&&c.jsx("button",{onClick:()=>fd.current?.click(),className:"w-16 h-16 rounded-lg border border-dashed border-gray-600 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary hover:border-gray-400 transition-colors shrink-0",title:i("page.addMoreFiles"),children:c.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),or.length>0&&or.some(w=>Kd(w))&&Mt&&Mt.modelSupportsVision===!1&&c.jsxs("div",{className:"text-[10px] text-amber-500/80 mb-1.5 flex items-center gap-1",children:[c.jsx("svg",{className:"w-3 h-3 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M12 9v4m0 4h.01M12 2L2 22h20L12 2z",strokeLinecap:"round",strokeLinejoin:"round"})}),i("page.visionWarning")]}),c.jsx("input",{ref:fd,type:"file",accept:"image/*,.pdf,.docx,.xlsx,.pptx,.xls,.doc,.csv,.json,.xml,.html,.epub",multiple:!0,className:"hidden",onChange:w=>{w.target.files&&ba(w.target.files),w.target.value=""}}),vs&&c.jsxs("div",{className:"flex items-center gap-2 mb-2 px-3 py-1.5 bg-surface-elevated rounded-lg border border-border-default/50",children:[c.jsxs("div",{className:"flex-1 min-w-0 pl-2 border-l-2 border-brand-500/50",children:[c.jsx("span",{className:"text-[11px] font-medium text-brand-500",children:vs.sender}),c.jsx("p",{className:"text-[11px] text-fg-tertiary truncate",children:vs.text})]}),c.jsx("button",{onClick:()=>es(null),className:"text-fg-tertiary hover:text-fg-secondary shrink-0 p-0.5",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),c.jsxs("div",{className:nu?"flex flex-col gap-2 min-w-0":"flex gap-2 items-end min-w-0",children:[c.jsxs("div",{className:nu?"flex gap-2 items-end min-w-0":"contents",children:[c.jsx("button",{onClick:()=>fd.current?.click(),disabled:le==="direct"&&(!ge||ya),className:`${vr?"p-1.5":"px-2.5 py-2.5"} text-fg-tertiary hover:text-fg-secondary disabled:opacity-40 transition-colors rounded-xl hover:bg-surface-elevated shrink-0 self-end mb-0.5`,title:i("page.attachFilesTitle"),children:c.jsx("svg",{className:vr?"w-[18px] h-[18px]":"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:c.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48",strokeLinecap:"round",strokeLinejoin:"round"})})}),c.jsx("textarea",{ref:Hs,value:zt,onChange:w=>{Qk(w.target.value),Ho()},onKeyDown:w=>{const Q=w.nativeEvent;if(!(Q.isComposing===!0||Q.keyCode===229)){if(Un&&Cn.length>0){const $=w.key==="ArrowUp"||w.ctrlKey&&w.key==="p",I=w.key==="ArrowDown"||w.ctrlKey&&w.key==="n",H=w.key==="Enter"||w.key==="Tab",ie=w.key==="Escape";if($){w.preventDefault(),Hn(ne=>(ne-1+Cn.length)%Cn.length);return}if(I){w.preventDefault(),Hn(ne=>(ne+1)%Cn.length);return}if(H){w.preventDefault();const ne=Cn[ia];ne&&(ne.kind==="agent"?oc(ne.agent.name):oc(ne.entity.name,ne.entity.entityType,ne.entity.id));return}if(ie){w.preventDefault(),ra(!1);return}}if(Yn&&xn.length>0){const $=w.key==="ArrowUp"||w.ctrlKey&&w.key==="p",I=w.key==="ArrowDown"||w.ctrlKey&&w.key==="n",H=w.key==="Enter"||w.key==="Tab",ie=w.key==="Escape";if($){w.preventDefault(),na(ne=>(ne-1+xn.length)%xn.length);return}if(I){w.preventDefault(),na(ne=>(ne+1)%xn.length);return}if(H){w.preventDefault();const ne=xn[jd];ne&&nO(ne);return}if(ie){w.preventDefault(),Zl(!1);return}}if(w.key==="Escape"){w.preventDefault(),w.currentTarget.blur();return}w.key==="Enter"&&!w.shiftKey&&(w.preventDefault(),Vg())}},onPaste:Ak,placeholder:iu,disabled:le==="direct"&&(!ge||ya),rows:vr?1:2,className:`flex-1 min-w-0 w-full bg-transparent rounded-xl text-sm outline-none disabled:opacity-40 transition-colors resize-none overflow-y-auto leading-relaxed placeholder:text-fg-secondary ${vr?"px-2 py-1.5":"px-4 py-3"}`,style:{minHeight:vr?"36px":"52px",maxHeight:`${MO(vr)}px`}})]}),c.jsxs("div",{className:`flex items-center gap-1.5 shrink-0 ${EC(nu)}`,children:[le==="direct"&&c.jsx(jI,{value:L_,agentId:ge,disabled:!ge||ya,onSelect:(w,Q)=>{if(Q==="agent"){ji(w),Lv(w,Q,ge).catch(()=>{});return}ji(null),Lv(w,Q,ge).catch(()=>{})}}),(le==="direct"?xr&&aa:xr)&&le!=="dm"?c.jsx("button",{onClick:pk,className:`${vr?"w-8 h-8 rounded-full flex items-center justify-center":"px-3 py-2.5 rounded-xl"} bg-red-600 hover:bg-red-500 text-white text-sm transition-colors`,title:i("page.stopAgent"),children:c.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}):c.jsx("button",{onClick:()=>Vg(),disabled:le==="direct"&&(!ge||ya)||!zt.trim()&&or.length===0,className:vr?"w-8 h-8 rounded-full flex items-center justify-center bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white transition-colors":"px-5 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",title:i("common:send"),children:vr?c.jsx("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:c.jsx("path",{d:"M12 19V5M5 12l7-7 7 7",strokeLinecap:"round",strokeLinejoin:"round"})}):i("common:send")})]})]})]}),(zt.trim()||or.length>0)&&c.jsx("div",{className:"mt-0.5 flex justify-end px-1 pointer-events-none select-none",children:c.jsx("span",{className:"text-[10px] text-fg-tertiary/80",children:i("common:shiftEnterHint")})})]})]})]}),!v&&F&&V&&c.jsx(kD,{payload:F,onClose:V,width:j?Z:yt,onResizeStart:Xt,onAddToChat:we,tabs:X,activeTabId:ae,onSelectTab:B?.setActiveRightPanelTab,onCloseTab:B?.closeRightPanelTab,onNewTab:()=>{if(!se)return;if(B?.rightPanelMode==="terminal"){const Q=`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"terminal",terminalId:Q,title:"Terminal"});return}const w=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"url",url:"about:blank",title:"New Tab",browserId:w})},fullscreen:j,onToggleFullscreen:B?.toggleRightPanelFullscreen,onBrowserMeta:B?.updateRightPanelBrowserTab?(w,Q)=>B.updateRightPanelBrowserTab(w,Q):void 0,panelMode:B?.rightPanelMode??"browser",onPanelModeChange:w=>B?.switchRightPanelMode(w),onTerminalMeta:B?.updateRightPanelTerminalTab?(w,Q)=>B.updateRightPanelTerminalTab(w,Q):void 0,onOpenUrlFromTerminal:w=>{if(!se)return;const Q=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"url",url:w,title:w,browserId:Q})},onOpenPathFromTerminal:w=>{se?.({kind:"file",path:w,title:w.split(/[/\\]/).pop()||w})}}),ug&&c.jsx(AC,{src:ug,onClose:()=>fg(null)})]})}function AI({agent:s}){const{t:e}=Pt(["common"]),t=Uv(s.id),r=Ol(s.status,t),i=r.labelKey?e(`common:${r.labelKey}`):"";return c.jsx("span",{className:`shrink-0 w-2 h-2 rounded-full ${r.dotClass} ${r.tone==="busy"?"animate-pulse":""}`,title:i,"aria-label":i})}function MI({agent:s,tasks:e,onViewProfile:t}){const{t:r}=Pt(["team","common"]),[i,n]=S.useState(!1),a=S.useRef(null),o=S.useRef(null),l=Uv(s.id),h=Ol(s.status,l),d=h.tone==="busy",u=h.tone==="danger",f=!h.running,p=d?e.find(O=>O.assignedAgentId===s.id&&O.status==="in_progress"):null,v=s.currentActivity;S.useEffect(()=>{u&&s.lastError&&Ic(s.lastError)&&Bc()},[u,s.lastError]),S.useEffect(()=>{if(!i)return;const O=m=>{a.current&&!a.current.contains(m.target)&&n(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[i]),S.useLayoutEffect(()=>{if(!i||!o.current)return;const O=o.current,m=O.getBoundingClientRect(),x=window.innerWidth;m.right>x-8&&(O.style.left="auto",O.style.right="0"),m.left<8&&(O.style.left="0",O.style.right="auto");const y=x-16;m.width>y&&(O.style.width=`${y}px`)},[i]);const b=h.labelKey?r(h.labelKey):s.status||"—",g=v?v.type==="heartbeat"?r("page.activityHeartbeat",{name:v.heartbeatName??v.label}):v.type==="chat"?v.label:v.type==="task"?r("page.activityTask",{label:v.label}):v.label:r("page.processing");return c.jsxs("div",{className:"relative",ref:a,children:[c.jsxs("button",{onClick:()=>n(O=>!O),className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full transition-colors hover:opacity-80 ${h.chipClass}`,children:[c.jsx("span",{className:`w-2 h-2 rounded-full ${h.dotClass}`}),c.jsx("span",{className:`text-xs ${h.textClass}`,children:b}),s.mailboxDepth!=null&&s.mailboxDepth>0&&c.jsx("span",{className:"text-[9px] bg-fg-tertiary/20 text-fg-tertiary rounded-full px-1.5",children:s.mailboxDepth})]}),i&&u&&c.jsxs("div",{ref:o,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-red-500/30 rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[c.jsx("p",{className:"text-[10px] text-red-500 uppercase font-semibold",children:r("page.errorDetails")}),c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2.5",children:[c.jsx("pre",{className:"text-[10px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:nh(s.lastError,r)||s.lastError||r("page.agentErrorFallback")}),s.lastErrorAt&&c.jsx("div",{className:"text-[9px] text-red-500/50 mt-1.5 border-t border-red-500/10 pt-1",children:new Date(s.lastErrorAt).toLocaleString()})]}),c.jsx("button",{onClick:()=>{n(!1),t?.(s.id)},className:"w-full text-center text-[10px] text-red-500 hover:text-red-500 border border-red-500/30 hover:border-red-500/50 rounded-lg py-1 transition-colors",children:r("page.viewAgentProfileArrow")})]}),i&&f&&c.jsxs("div",{ref:o,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:r("page.agentNotRunningTitle")}),c.jsx("p",{className:"text-[11px] text-fg-secondary",children:r("page.agentNotRunningHint")}),c.jsx("button",{onClick:()=>{n(!1),t?.(s.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1 transition-colors",children:r("page.viewAgentProfileArrow")})]}),i&&!d&&!u&&!f&&c.jsxs("div",{ref:o,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:r("page.agentIdleTitle")}),c.jsx("p",{className:"text-[11px] text-fg-secondary",children:r("page.agentIdleHint")}),c.jsx("button",{onClick:()=>{n(!1),t?.(s.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1 transition-colors",children:r("page.viewAgentProfileArrow")})]}),i&&d&&c.jsxs("div",{ref:o,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:r("page.currentActivity")}),p?c.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-brand-500/10 border border-brand-500/30 cursor-pointer hover:bg-brand-500/10 transition-colors",onClick:()=>{n(!1),Lr.navigate(Yt.WORK,{openTask:p.id})},children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-brand-500 truncate",children:p.title}),c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:r("page.workingOnTaskHint")})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"})]}):c.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-surface-elevated/50",children:[c.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${v?.type==="heartbeat"||v?.type==="chat","bg-blue-400 animate-pulse"}`}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:g}),c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:v?.type==="heartbeat"?r("page.activityDescHeartbeat"):v?.type==="chat"?r("page.activityDescChat"):r("page.activityDescFallback")})]})]}),c.jsx("button",{onClick:()=>{n(!1),t?.(s.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1.5 transition-colors",children:r("page.viewMindArrow")})]})]})}export{KI as TeamPage};
|
|
84
|
+
`)){Ed(),Zl(!0),J_(Ce.toLowerCase()),na(0);return}}}}Zl(!1)},nO=S.useCallback(w=>{const Q=Hs.current?.selectionStart??zt.length,I=zt.slice(0,Q).lastIndexOf("/"),H=zt.slice(Q),ie=zt.slice(0,I)+"/"+w.name+" "+H;ks(ie),Zl(!1),na(0);const ne=I+w.name.length+2;requestAnimationFrame(()=>{const Ce=Hs.current;Ce&&(Ce.focus(),Ce.setSelectionRange(ne,ne))})},[zt]),oc=(w,Q,$)=>{const I=Hs.current?.selectionStart??zt.length,ie=zt.slice(0,I).lastIndexOf("@"),ne=zt.slice(I),Ce=zt.slice(0,ie)+ne;ks(Ce),ra(!1),Hn(0);const Le=Q&&$?`@[${w}](${Q}:${$})`:w.includes(" ")?`@[${w}]`:`@${w}`,xe=Q?fO[Q]??"📄":"🤖",ke=Q?i(`page.mentionType.${Q}`,{defaultValue:Q}):i("page.mentionType.agent");we({label:`[${xe}${ke}] ${w}`,content:`${Le} `}),requestAnimationFrame(()=>{const Ae=Hs.current;Ae&&(Ae.focus(),Ae.setSelectionRange(Ae.value.length,Ae.value.length))})},$k=10*1024*1024,oO=5,jk=new Set(["application/pdf","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.ms-excel","application/msword","text/csv","text/html","application/json","application/xml","text/xml","application/epub+zip"]),ao=S.useCallback(w=>w.type.startsWith("image/")||jk.has(w.type),[]),Kd=w=>w.dataUrl.startsWith("data:image/"),Rk=(w,Q)=>{if(Kd({dataUrl:Q}))return null;const $=w.split(".").pop()?.toLowerCase()??"";return{pdf:"📄",docx:"📝",doc:"📝",xlsx:"📊",xls:"📊",pptx:"📎",csv:"📊",json:"🔧",xml:"🔧",html:"🌐",epub:"📚"}[$]??"📁"},ba=S.useCallback(w=>{const Q=Array.from(w).filter(ao);if(Q.length!==0)for(const $ of Q){if($.size>$k)continue;const I=new FileReader;I.onload=()=>{const H=I.result;Ml(ie=>ie.length>=oO||ie.some(ne=>ne.dataUrl===H)?ie:[...ie,{id:`img_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,dataUrl:H,name:$.name}])},I.readAsDataURL($)}},[ao]),Ek=S.useCallback(w=>{Ml(Q=>Q.filter($=>$.id!==w))},[]),Ak=S.useCallback(w=>{const Q=w.clipboardData?.files;if(Q&&Q.length>0){const $=Array.from(Q).filter(ao);$.length>0&&(w.preventDefault(),ba($))}},[ba,ao]),Mk=S.useCallback(w=>{w.preventDefault();const Q=w.dataTransfer?.files;Q&&Q.length>0&&ba(Array.from(Q).filter(ao))},[ba,ao]),Lk=S.useCallback(w=>{w.preventDefault()},[]),Et=l.find(w=>w.id===ge),kn=ns??(le==="direct"?Et?.teamId:void 0),va=!!(!v&&!j&&kn&&As.some(w=>w.id===kn)),aO=!!(va&&!L&&(Qe&&!qe||Ye));pe.current=va,S.useEffect(()=>{if(K==="l2"){if(!va){B?.setKeyboardPane("l1");return}!L&&!Qe&&!Ye&&B?.setKeyboardPane("l1")}},[K,va,L,Qe,Ye,B]);const lO=S.useRef(K);S.useEffect(()=>{if(t||v||!o)return;const w=lO.current;if(lO.current=K,!(K!=="l2"||w==="l2")){if(!kn){B?.setKeyboardPane("l1");return}qe?pt(!0):Ee(!0)}},[K,t,v,o,kn,qe,B]);const ac=e?.name??i("page.fallbackYou"),cO=os[os.length-1];xr&&cO?.sender;const Nk=qt&&cO?.sender==="agent"&&(aa||!!r),hO=S.useMemo(()=>{if(le!=="channel")return null;if(gt.startsWith("group:custom:")){const Q=Cs.find($=>$.channelKey===gt);return Q?.members?new Set(Q.members.filter($=>$.type==="agent").map($=>$.id)):null}if(!ns)return null;const w=As.find(Q=>Q.id===ns);return w?new Set(w.members.filter(Q=>Q.type==="agent").map(Q=>Q.id)):null},[le,gt,ns,As,Cs]),dO=l.filter(w=>hO?hO.has(w.id):!0).filter(w=>w.name.toLowerCase().includes(jg)),uO=tk.filter(w=>w.name.toLowerCase().includes(jg)),fO={workflow:"⚙️",project:"📁",requirement:"📋",task:"✅",deliverable:"📦"},Cn=S.useMemo(()=>[...dO.map(w=>({kind:"agent",agent:w})),...uO.map(w=>({kind:"entity",entity:w}))],[dO,uO]),Pn=d.find(w=>w.id===_t),lo=_t===e?.id||!_t,Ms=Cs.find(w=>w.channelKey===gt);S.useEffect(()=>{if(t||!gt.startsWith("group:custom:"))return;const w=Cs.find(Q=>Q.channelKey===gt);!w||w.members||te.groupChats.getById(w.id).then(Q=>{Q.chat.members&&ta($=>$.map(I=>I.id===w.id?{...I,members:Q.chat.members}:I))}).catch(()=>{})},[t,gt,Cs]);const Jd=S.useCallback(async()=>{if(t||le!=="direct"||!ge){bd([]),vd([]);return}try{hu("/approvals");const{approvals:w}=await te.approvals.list("pending");bd(w.filter(Q=>Q.status==="pending"&&Array.isArray(Q.questions)&&Q.questions.length>0&&(Q.details?.agentId??Q.agentId)===ge)),vd(zD(w,{agentId:ge,sessionId:et&&et!==it?et:null}))}catch{}},[t,le,ge,et]),eu=S.useCallback(async()=>{if(t||le!=="direct"||!ge||!et||et===it){yd([]);return}try{hu("/notifications");const{notifications:w}=await te.notifications.list(e?.id,!0,{type:"agent_report",limit:30}),Q=w.filter($=>!$.read&&$.type==="agent_report"&&!$.metadata?.creditExhausted&&$.metadata?.agentId===ge&&Mm($)===et).sort(($,I)=>new Date(I.createdAt).getTime()-new Date($.createdAt).getTime()).slice(0,5);yd(Q),Sd(Q.map($=>$.metadata?.messageId).filter($=>typeof $=="string"&&$.length>0))}catch{}},[t,le,ge,et,e?.id]);S.useEffect(()=>{Jd(),eu();let w=null;const Q=()=>{w||(w=setTimeout(()=>{w=null,Jd(),eu()},400))},$=St.on("approval:requested",Q),I=St.on("approval:resolved",Q),H=St.on("notification",Q),ie=()=>Q();return window.addEventListener("markus:notifications-changed",ie),()=>{w&&clearTimeout(w),$(),I(),H(),window.removeEventListener("markus:notifications-changed",ie)}},[Jd,eu]),S.useEffect(()=>{if(!o||t||le!=="direct"||P!=="chat"||Ko.length===0||On||gn||Ai)return;const w=Ko.find(Q=>!Sg.current.has(Q.id));w&&(Sg.current.add(w.id),Jo(w))},[o,t,le,P,Ko,On,gn,Ai]);const Dk=S.useCallback(async(w,Q)=>{vg(w);try{await te.approvals.respond(w,Q.approved,e?.id,Q.comment,Q.selectedOption,Q.answers),bd($=>$.filter(I=>I.id!==w)),Wl(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}vg(null)},[e?.id]),Ik=S.useCallback(async(w,Q,$)=>{yg(w);try{await te.approvals.respond(w,Q,e?.id,$),vd(I=>I.filter(H=>H.id!==w)),Jo(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}yg(null)},[e?.id]),tu=S.useCallback(()=>{ea(null);const w=nc.current;nc.current=null,w&&(Mi.current={messageId:w.messageId,mode:"direct",agentId:w.agentId,sessionId:w.sessionId,preferMain:w.preferMain})},[]);S.useEffect(()=>{const w=jr?.agentId;!w||w===ge||(ea(null),nc.current=null)},[jr?.agentId,ge]);const mO=S.useCallback(async w=>{if(!(t||!e?.id||jr))try{hu("/notifications");const{notifications:Q}=await te.notifications.list(e.id,!0,{type:"agent_report",limit:30}),$=VD(Q,w);if($.length===0)return;const I=FD($);nc.current=I.sessionId?{agentId:w,sessionId:I.sessionId,messageId:I.messageId??void 0}:{agentId:w,sessionId:null,preferMain:!0},ea({items:$,index:0,agentId:w})}catch{}},[t,e?.id,jr]),su=S.useCallback(w=>{$t("direct"),Us(w),_("chat"),mO(w)},[mO]),Bk=S.useCallback(async w=>{_g(w);const Q=jr;try{const $=Q?.items.find(ie=>ie.id===w)??Ai,I=typeof $?.metadata?.messageId=="string"?$.metadata.messageId:null;await te.notifications.markRead(w),yd(ie=>ie.filter(ne=>ne.id!==w)),I&&Sd(ie=>ie.filter(ne=>ne!==I));const H=(Q?.index??0)+1;Q&&H<Q.items.length?ea({...Q,index:H}):tu(),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}_g(null)},[jr,Ai,tu]),pO=le==="channel"?Ms?.name??gt:le==="direct"?Et?.name??i("page.selectAgent"):le==="dm"?lo?i("chat.myNotes"):Pn?.name??i("page.directMessage"):i("page.chatTitle"),gO=S.useMemo(()=>Math.floor(Math.random()*5),[ge,et]),ru=S.useMemo(()=>Math.floor(Math.random()*3),[_t,lo,et]),OO=S.useMemo(()=>{if(le==="dm"){if(lo)return i(`page.placeholder.dmSelfOptions.${ru}`);const w=Pn?.name??"";return w?i(`page.placeholder.dmOtherOptions.${ru}`,{name:w}):i("page.placeholder.dmOtherEmpty")}return le==="direct"&&ge?i(`page.placeholder.directOptions.${gO}`):""},[le,lo,Pn?.name,ru,ge,gO,i]),ya=le==="direct"&&!!Et&&Et.status==="offline",iu=le==="channel"?Ms?i("page.placeholder.channel",{name:Ms.name}):i("page.placeholder.channelWithMention",{name:gt}):le==="dm"?lo?i("page.placeholder.dmSelf"):i("page.placeholder.dmOther",{name:Pn?.name??""}):i(ya?"page.placeholder.agentOffline":ge?"page.placeholder.direct":"page.placeholder.noAgent"),Wk=v&&x==="chat",Xk=S.useMemo(()=>X2({chatMode:le,agentTeamId:Et?.teamId,channelTeamId:Ms?.teamId,knownTeamIds:As.map(w=>w.id)}),[le,Et?.teamId,Ms?.teamId,As]),zk=S.useMemo(()=>{if(le==="direct"){const w=$r.find(Q=>Q.id===et);if(w?.title)return w.title;if(Et?.name)return Et.name}return(le==="channel"?Ms?.name??gt:Pn?.name)||i("page.loadingChat",{defaultValue:"Loading conversation…"})},[le,$r,et,Et?.name,gt,_t,Ms?.name,Pn?.name,i]),Sa=P==="chat"&&os.length===0&&!fn,vr=P==="chat"&&os.length>0;md.current=vr;const qk=!!(zt.trim()||or.length>0),nu=IC(v,qk);return c.jsxs("div",{ref:G,className:"flex-1 overflow-hidden flex relative",children:[!j&&c.jsx(tP,{authUser:e,agents:l,teams:As,humans:d,tasks:$d,externalAgents:U_,groupChats:Cs,chatMode:le,selectedAgent:ge,activeChannel:gt,activeDmUserId:_t,previewMode:t,onSelectAgent:w=>{su(w),Ps(!1),v&&k()},onSelectChannel:w=>{$t("channel"),Bs(w),_("chat"),Ps(!1),v&&k()},onSelectDm:w=>{$t("dm"),ln(w),_("chat"),Ps(!1),v&&k()},onSelectTeam:w=>{const Q=Cs.find(I=>I.type==="team"&&I.teamId===w),$=Q?.channelKey??`group:${w}`;v?C(w):($t("channel"),Bs($),_("chat"),Ps(!1),!Qe&&!qe&&Ee(!0),Q||(Kn(),Gs()))},selectedTeamId:ns??(le==="direct"&&Et?.teamId?Et.teamId:null),onRefreshTeams:Gs,onRefreshAgents:ar,onRefreshHumans:da,onRefreshGroupChats:Kn,onViewProfile:dt,onManageGroupMembers:w=>{$t("channel"),Bs(w),_("chat"),Ps(!0),v&&k()},unreadByAgent:Gl,unreadByChannel:Yl,width:v?void 0:R.width,onResizeStart:v?void 0:R.onResizeStart,hidden:v&&x!=="roster"||!v&&L,onCollapse:()=>E(!0),initialLoading:f,focused:!v&&!L&&K==="l1",l2Available:va}),v&&x==="team"&&y&&(()=>{const w=As.find(I=>I.id===y);if(!w){const H=jO(y,As.map(ie=>ie.id),Qd)==="missing";return c.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[c.jsx("button",{onClick:()=>{window.location.hash=Yt.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",title:i("common:back",{defaultValue:"Back"}),children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate",children:i(H?"page.teamMissingTitle":"page.loadingTeam")})]}),c.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-3 px-6 text-center",children:[c.jsx("p",{className:"text-xs text-fg-tertiary max-w-[280px]",children:i(H?"page.teamMissingBody":"page.loadingTeamBody")}),c.jsx("div",{className:"flex items-center gap-2",children:H?c.jsx("button",{onClick:()=>{window.location.hash=Yt.TEAM},className:"px-3 py-1.5 text-xs font-medium bg-brand-600 text-white rounded-md hover:bg-brand-700 transition-colors",children:i("page.backToList")}):c.jsx("button",{onClick:()=>{Gs()},className:"px-3 py-1.5 text-xs font-medium border border-border-default text-fg-secondary rounded-md hover:bg-surface-overlay transition-colors",children:i("common:retry",{defaultValue:"Retry"})})})]})]})}const Q=l.filter(I=>I.teamId===y),$=Cs.find(I=>I.type==="team"&&I.teamId===y);return c.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[c.jsx("button",{onClick:()=>{window.location.hash=Yt.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",children:c.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[c.jsx("div",{className:"w-8 h-8 rounded-lg bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),c.jsxs("div",{className:"min-w-0",children:[c.jsx("h3",{className:"text-sm font-semibold text-fg-primary truncate",children:w.name}),c.jsx("p",{className:"text-[10px] text-fg-tertiary",children:i("chat.members_other",{count:w.members?.length||Q.length})})]})]})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-1",children:[(()=>{const I=$?.channelKey??Hv(y),H=Yl[I]??0;return c.jsxs("button",{onClick:()=>{$t("channel"),Bs(I),_("chat"),k()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[c.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-500/15 flex items-center justify-center shrink-0",children:c.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:c.jsx("path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"})})}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:$?.name??w.name}),c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:i("chat.groupChat")})]}),H>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:H}):c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"text-fg-tertiary shrink-0",children:c.jsx("polyline",{points:"9 18 15 12 9 6"})})]})})(),Q.length>0&&c.jsxs(c.Fragment,{children:[c.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider px-2.5 pt-2",children:i("chat.agents")}),Q.map(I=>{const H=Gl.get(I.id)??0,ie=I.status==="offline";return c.jsxs("button",{onClick:()=>{$t("direct"),Us(I.id),_("chat"),k()},className:`w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors ${ie?"opacity-50":""}`,children:[c.jsx(Ns,{name:I.name||"Agent",avatarUrl:I.avatarUrl,size:36}),c.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[c.jsxs("div",{className:"text-sm font-medium text-fg-primary truncate flex items-center gap-1.5",children:[I.name,ie&&c.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:i("common:status.offline")})]}),c.jsx("div",{className:"text-[10px] text-fg-tertiary truncate",children:I.role||I.status})]}),H>0?c.jsx("span",{className:"min-w-[16px] h-[16px] flex items-center justify-center text-[9px] font-semibold text-white bg-red-500 rounded-full px-1 leading-none shrink-0",children:H}):c.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Ol(I.status,hs.isAgentStreaming(I.id)).dotClass}`})]},I.id)})]})]})]})})(),!j&&Qe&&!qe&&!v&&!L&&(()=>{const w=ns??(le==="direct"?Et?.teamId:void 0);if(!w)return null;const Q=As.find(I=>I.id===w);if(!Q)return null;const $=Cs.find(I=>I.type==="team"&&I.teamId===w);return c.jsx(i0,{team:Q,agents:l,humans:d,authUser:e,groupChat:$,chatMode:le,selectedAgent:ge,activeChannel:gt,activeDmUserId:_t,teams:As,onSelectAgent:I=>{su(I),Ps(!1)},onSelectChannel:I=>{$t("channel"),Bs(I),_("chat"),Ps(!1)},onSelectDm:I=>{$t("dm"),ln(I),_("chat"),Ps(!1)},onBack:()=>Ee(!1),onViewProfile:dt,onRefreshAgents:ar,onRefreshTeams:Gs,unreadByAgent:Gl,width:ye.width,onResizeStart:ye.onResizeStart,focused:K==="l2"&&aO})})(),!j&&Ye&&!v&&!L&&(()=>{if(!kn)return null;const w=As.find($=>$.id===kn);if(!w)return null;const Q=Cs.find($=>$.type==="team"&&$.teamId===kn);return c.jsxs("div",{"data-l2-floating":!0,className:"absolute z-30 inset-0",style:{left:R.width+6},children:[c.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:()=>pt(!1)}),c.jsx("div",{className:"relative h-full",style:{width:ye.width+8},children:c.jsx(i0,{team:w,agents:l,humans:d,authUser:e,groupChat:Q,chatMode:le,selectedAgent:ge,activeChannel:gt,activeDmUserId:_t,teams:As,onSelectAgent:$=>{su($),Ps(!1),pt(!1)},onSelectChannel:$=>{$t("channel"),Bs($),_("chat"),Ps(!1),pt(!1)},onSelectDm:$=>{$t("dm"),ln($),_("chat"),Ps(!1),pt(!1)},onBack:()=>pt(!1),onViewProfile:$=>{dt($),pt(!1)},onRefreshAgents:ar,onRefreshTeams:Gs,unreadByAgent:Gl,width:ye.width,focused:K==="l2"&&aO})})]})})(),!j&&(!v||Wk)&&c.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col ${v||F?"min-w-0":"min-w-[400px]"}`,children:[c.jsxs("div",{className:"shrink-0 relative pb-2",children:[v?c.jsxs(c.Fragment,{children:[c.jsxs("div",{className:"flex items-center px-3 h-11 gap-2",children:[c.jsx("button",{onClick:()=>{window.location.hash=Xk},className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:c.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"15 18 9 12 15 6"})})}),c.jsxs("div",{className:"flex-1 min-w-0 flex items-center justify-center gap-1.5",children:[c.jsx("span",{className:"font-semibold text-sm truncate min-w-0",children:pO}),le==="direct"&&Et&&c.jsx(AI,{agent:Et})]}),c.jsx("button",{onClick:()=>pn(w=>!w),"aria-label":i("page.moreActions",{defaultValue:"更多操作"}),className:`p-1.5 rounded-md transition-colors shrink-0 ${Og?"bg-brand-500/15 text-brand-500":"text-fg-secondary"}`,children:c.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"currentColor",children:[c.jsx("circle",{cx:"5",cy:"12",r:"1.7"}),c.jsx("circle",{cx:"12",cy:"12",r:"1.7"}),c.jsx("circle",{cx:"19",cy:"12",r:"1.7"})]})})]}),Og&&c.jsxs(c.Fragment,{children:[c.jsx("div",{className:"fixed inset-0 z-40",onClick:()=>pn(!1)}),c.jsxs("div",{className:"absolute right-2 top-full z-50 w-44 py-1 bg-surface-secondary border border-border-default rounded-xl shadow-2xl shadow-black/40",children:[c.jsxs("button",{onClick:()=>{pn(!1),qi(P)||ht()},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("circle",{cx:"12",cy:"8",r:"3.5"}),c.jsx("path",{d:"M5 20a7 7 0 1 1 14 0"})]}),i(le==="channel"?"page.teamTab":"page.profileTab")]}),c.jsxs("button",{onClick:()=>{pn(!1),Fn(!0)},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z"})}),i("page.findInConversation")]}),le==="direct"&&!qi(P)&&c.jsxs("button",{onClick:()=>{pn(!1),Oa()},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M12 5v14M5 12h14"})}),i("page.newChat")]}),le==="direct"&&!qi(P)&&c.jsxs("button",{ref:Xl,onClick:()=>{pn(!1),mn(!0)},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})}),i("page.historyTitle")]}),le==="channel"&&Ms?.type==="custom"&&c.jsxs("button",{onClick:()=>{pn(!1),Ps(!0)},className:"w-full flex items-center gap-2 px-3 py-2 text-xs text-fg-secondary hover:bg-surface-overlay text-left",children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.7",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),i("page.membersTitle",{defaultValue:"成员"})," (",Ms.members?.length??Ms.memberCount??0,")"]})]})]})]}):(()=>{const w=ns?As.find(xe=>xe.id===ns):void 0,Q=le==="direct"&&ge?kI:le==="channel"&&ns?CI:["chat"],$=async()=>{const xe=ee.trim();if(!xe){Ve(!1);return}try{le==="direct"&&ge?(await te.agents.updateConfig(ge,{name:xe}),ar()):le==="channel"&&ns&&(await te.teams.update(ns,{name:xe}),Gs())}catch{}Ve(!1)},I=async()=>{try{le==="direct"&&ge?(await te.agents.updateConfig(ge,{title:_e}),ar()):le==="channel"&&ns&&(await te.teams.update(ns,{description:_e}),Gs())}catch{}Oe(!1)},H=le==="direct"?Et?.name:le==="channel"?w?.name??Ms?.name:Pn?.name??"",ie=le==="direct"?Et?.role||"":le==="channel"&&w?.description||"",ne=le==="direct"?Et?.avatarUrl:void 0,Ce=H||"U",Le=le==="direct"&&ge||le==="channel"&&ns;return c.jsxs("div",{className:"flex flex-col",children:[c.jsxs("div",{"data-electron-drag":!0,className:"flex items-center px-4 h-14 gap-2.5",children:[L&&!v&&c.jsx("button",{onClick:()=>E(!1),className:"w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated",title:i("page.toggleSidebar"),children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),(!Qe||qe)&&(le==="channel"&&ns||le==="direct"&&Et?.teamId)&&c.jsx("button",{onClick:xt,className:`w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 ${Ye?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:"Toggle team panel",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),c.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),Le&&c.jsx("div",{"data-no-drag":!0,className:"shrink-0",children:le==="channel"&&ns?c.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-600 text-white flex items-center justify-center text-sm font-bold",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}):c.jsxs("div",{className:"relative",ref:ce,children:[c.jsx("button",{type:"button",onClick:()=>he(xe=>!xe),className:"block rounded-xl shrink-0 transition-opacity hover:opacity-80 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand-500",title:i("page.editAgentAvatar"),"aria-label":i("page.editAgentAvatar"),"aria-expanded":us,children:c.jsx(Ns,{name:Ce,avatarUrl:ne,size:36,className:"rounded-xl shrink-0 pointer-events-none"})}),us&&c.jsx("div",{"data-no-drag":!0,className:"absolute z-50 top-full left-0 mt-1.5 p-3 rounded-xl bg-surface-secondary border border-border-default shadow-2xl",children:c.jsx(yC,{currentUrl:ne,name:Ce,size:64,targetType:"agent",targetId:Et?.id,onUploaded:xe=>{he(!1),ck(Et?.id,xe),ar()}})})]})}),Le?c.jsxs("div",{"data-no-drag":!0,className:"flex-1 min-w-0",children:[c.jsxs("div",{className:"flex items-center gap-2",children:[ze?c.jsx("input",{ref:at,value:ee,onChange:xe=>Te(xe.target.value),onBlur:$,onKeyDown:xe=>{xe.key==="Enter"&&$(),xe.key==="Escape"&&Ve(!1)},className:"text-sm font-semibold bg-transparent border-b border-brand-500 outline-none py-0 px-0 min-w-[80px] max-w-[240px]",autoFocus:!0}):c.jsx("span",{className:"text-sm font-semibold truncate cursor-pointer hover:text-brand-500 transition-colors",onClick:()=>{Te(H??""),Ve(!0)},title:"Click to edit name",children:H}),le==="direct"&&Et&&c.jsx(MI,{agent:Et,tasks:$d,onViewProfile:dt})]}),(le==="direct"||le==="channel"&&ns)&&(Se?c.jsx("input",{ref:wt,value:_e,onChange:xe=>Fe(xe.target.value),onBlur:I,onKeyDown:xe=>{xe.key==="Enter"&&I(),xe.key==="Escape"&&Oe(!1)},className:"text-[11px] text-fg-tertiary bg-transparent border-b border-brand-500/50 outline-none py-0 px-0 w-full max-w-[400px] mt-0.5",placeholder:"Add title...",autoFocus:!0}):c.jsx("div",{className:"text-[11px] text-fg-tertiary truncate cursor-pointer hover:text-fg-secondary transition-colors mt-0.5",onClick:()=>{Fe(ie),Oe(!0)},title:"Click to edit title",children:ie||"No title"}))]}):c.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[c.jsx("span",{className:"font-semibold text-sm truncate",children:pO}),le==="dm"&&c.jsx("span",{className:"text-xs text-fg-tertiary",children:lo?i("page.privateNotepad"):""})]}),c.jsxs("div",{"data-no-drag":!0,className:"ml-auto flex items-center gap-2 shrink-0",children:[le==="direct"&&Et&&P==="chat"&&c.jsx("button",{onClick:Oa,title:i("page.newChatKbdHint",{kbd:RO(["N"],b)}),className:"text-xs text-brand-500 hover:text-brand-500 px-2.5 py-1 rounded-md hover:bg-brand-500/10 border border-brand-500/20 transition-colors flex items-center gap-1",children:i("page.newChatButton")}),c.jsx("button",{onClick:()=>{Fn(xe=>!xe),Cd&&sa(-1)},className:`p-1.5 rounded-md transition-colors ${Cd?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:`${i("page.findInConversationHint")} (${RO(["F"],b)})`,"data-testid":"find-in-conversation-btn",children:c.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:[c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M8 6h11M8 12h11M8 18h6"}),c.jsx("circle",{cx:"17.5",cy:"17.5",r:"3.5"}),c.jsx("path",{strokeLinecap:"round",d:"M20.5 20.5L22 22"})]})}),le==="channel"&&Ms?.type==="custom"&&c.jsxs("button",{onClick:()=>Ps(!kd),className:`text-xs px-2.5 py-1 rounded-md border transition-colors flex items-center gap-1.5 ${kd?"bg-brand-500/15 text-brand-500 border-brand-500/30":"text-fg-secondary hover:text-fg-primary border-border-default hover:bg-surface-elevated"}`,children:[c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),c.jsx("circle",{cx:"9",cy:"7",r:"4"}),c.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),c.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),Ms.members?.length??Ms.memberCount??0]}),le==="direct"&&Et&&P==="chat"&&c.jsx("button",{ref:Xl,onClick:()=>mn(!Go),className:`p-1.5 rounded-md transition-colors ${Go?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:i("page.historyTitle"),children:c.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:c.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})}),!v&&B&&c.jsx("button",{onClick:()=>B.toggleRightPanel(),className:`p-1.5 rounded-md transition-colors ${F?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:i("page.rightPanelToggle",{defaultValue:"Toggle side panel"}),children:c.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:[c.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),c.jsx("path",{d:"M15 4v16"})]})})]})]}),Q.length>1&&c.jsx("div",{className:"flex items-center gap-1 px-4 pb-1.5 overflow-x-auto scrollbar-hide",children:Q.map(xe=>c.jsxs("button",{onClick:()=>_(xe),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${P===xe?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[c.jsx("span",{children:TI(xe)}),PI(xe,i)]},xe))})]})})(),le==="direct"&&ge&&P==="chat"&&Ws.length>1&&(()=>{const w=Q=>hs.isStreaming(Q.id);return c.jsx("div",{ref:Cg,className:"flex items-center gap-0 px-3 overflow-x-auto scrollbar-hide",children:Ws.map(Q=>{const $=Im(Q,i);return c.jsxs("div",{"data-session-tab-id":Q.id,title:Dv(Q,i),className:`group flex items-center gap-1.5 px-3 py-1.5 text-xs cursor-pointer rounded-md transition-colors shrink-0 max-w-[180px] ${Q.id===et?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>{if(Q.id===it){Ei(it);const I=jt.current;me(I,it),_s([])}else Ii(Q)},children:[Q.isMain&&c.jsx("span",{className:"text-[10px] opacity-50 shrink-0",children:"●"}),c.jsx("span",{className:"truncate",children:$}),w(Q)&&c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-blue-500 animate-pulse shrink-0",title:i("common:status.working"),"aria-label":i("common:status.working"),"data-testid":"session-tab-streaming"}),!Q.isMain&&c.jsx("button",{onClick:I=>{I.stopPropagation(),Ck(Q.id)},className:"opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-fg-secondary transition-opacity shrink-0",children:"✕"})]},Q.id)})})})(),Cd&&P==="chat"&&c.jsx($D,{query:zl,onQueryChange:Pk,matches:pa.matches,cursor:q_,scanned:pa.scanned,truncated:pa.truncated,hasMore:E_,loadingMore:hd,onLoadEarlier:()=>{Yg()},onJump:fk,onClose:()=>{Fn(!1),sa(-1)},serverResults:Z_,serverLoading:V_,onServerResultClick:Tk,labelFor:w=>{const Q=os[w.messageIndex];if(!Q)return"";const $=Q.sender==="user"?i("page.you",{defaultValue:"你"}):Q.agentName??"",I=Q.rawCreatedAt?cc(Q.time,Q.rawCreatedAt,a):Q.time;return[$,I].filter(Boolean).join(" · ")}}),le==="direct"&&P==="chat"&&(Ws.find(w=>w.id===et)??$r.find(w=>w.id===et))?.metadata?.kind==="evolution"&&c.jsx("div",{className:"px-4 py-1.5 text-[11px] text-fg-tertiary border-b border-border-default bg-surface-secondary/40",children:i("page.messageActions.evolvedFrom")}),le==="channel"&&Ms?.type==="custom"&&kd&&(()=>{const w=Ms,Q=w.members??[],$=[];for(const I of l)Q.some(H=>H.id===I.id)||$.push({id:I.id,name:I.name,type:"agent",subtitle:I.role||"Agent"});for(const I of d)Q.some(H=>H.id===I.id)||$.push({id:I.id,name:I.name,type:"human",subtitle:I.email||I.role||""});return c.jsx(CD,{members:Q,candidates:$,currentUserId:e?.id,memberCount:Q.length,onClose:()=>Ps(!1),onRemoveMember:I=>{te.groupChats.removeMember(w.id,I).then(()=>{ta(H=>H.map(ie=>ie.id===w.id?{...ie,members:(ie.members??[]).filter(ne=>ne.id!==I),memberCount:(ie.memberCount??1)-1}:ie))}).catch(()=>{})},onAddMember:I=>{const H=$.find(ie=>ie.id===I);H&&te.groupChats.addMember(w.id,H.id,H.type,H.name).then(()=>{ta(ie=>ie.map(ne=>ne.id===w.id?{...ne,members:[...ne.members??[],{id:H.id,name:H.name,type:H.type}],memberCount:(ne.memberCount??0)+1}:ne))}).catch(()=>{})}})})(),le==="direct"&&ge&&Go&&c.jsxs("div",{ref:wd,className:"absolute right-4 top-full mt-1 w-72 max-h-[420px] bg-surface-secondary border border-border-default rounded-xl shadow-2xl shadow-black/40 z-50 flex flex-col overflow-hidden",children:[c.jsxs("div",{className:"px-4 py-3 border-b border-border-default flex items-center justify-between",children:[c.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:i("page.historyTitle")}),c.jsx("button",{onClick:()=>mn(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:"✕"})]}),c.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[M_&&$r.length===0?c.jsx(qv,{rows:3,variant:"skeleton",className:"px-2 py-2"}):$r.length===0?c.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6",children:i("page.noConversationsYet")}):null,(()=>{const w=new Date,Q=new Date(w.getFullYear(),w.getMonth(),w.getDate()).getTime(),$=Q-864e5,I=Q-7*864e5,H=[],ie=[],ne=[],Ce=[],Le=[];for(const xe of $r){const ke=new Date(xe.lastMessageAt).getTime();ke>=Q?ie.push(xe):ke>=$?ne.push(xe):ke>=I?Ce.push(xe):Le.push(xe)}return ie.length>0&&H.push({label:i("page.dateToday"),items:ie}),ne.length>0&&H.push({label:i("page.dateYesterday"),items:ne}),Ce.length>0&&H.push({label:i("page.datePrevious7Days"),items:Ce}),Le.length>0&&H.push({label:i("page.dateOlder"),items:Le}),H.map(xe=>c.jsxs("div",{className:"mb-2",children:[c.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-3 py-1.5",children:xe.label}),xe.items.map(ke=>c.jsx("div",{className:`w-full text-left px-3 py-2 rounded-lg text-xs mb-0.5 transition-colors ${ke.id===et?"bg-brand-600/20 text-brand-500":"hover:bg-surface-elevated"}`,children:gd===ke.id?c.jsxs("div",{className:"flex items-center gap-1.5",children:[c.jsx("input",{autoFocus:!0,value:Od,onChange:Ae=>xd(Ae.target.value),onKeyDown:Ae=>{Ae.key==="Enter"&&(Ae.stopPropagation(),Hg(ke)),Ae.key==="Escape"&&ga()},onClick:Ae=>Ae.stopPropagation(),placeholder:ke.isMain?i("page.sessionMain"):ke.title||i("page.sessionConversation"),className:"w-full bg-surface-primary border border-brand-500/50 rounded-md px-2 py-1 text-xs text-fg-primary outline-none focus:ring-1 focus:ring-brand-500/50"}),c.jsx("button",{onClick:Ae=>{Ae.stopPropagation(),Hg(ke)},className:"text-brand-400 hover:text-brand-300 shrink-0",title:i("common:save"),children:c.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M20 6L9 17l-5-5"})})}),c.jsx("button",{onClick:Ae=>{Ae.stopPropagation(),ga()},className:"text-fg-tertiary hover:text-fg-secondary shrink-0",title:i("common:cancel"),children:c.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}):c.jsxs("button",{onClick:()=>{Ii(ke)},title:Dv(ke,i),className:"w-full text-left group/session",children:[c.jsxs("div",{className:"truncate font-medium flex items-center gap-1",children:[ke.isMain&&c.jsx("span",{className:"text-[10px] text-brand-500 opacity-80",children:"●"}),c.jsx("span",{className:"truncate",children:Im(ke,i)}),!ke.isMain&&c.jsx("span",{role:"button",tabIndex:0,onClick:Ae=>{Ae.stopPropagation(),Ug(ke)},onKeyDown:Ae=>{Ae.key==="Enter"&&(Ae.stopPropagation(),Ug(ke))},className:"opacity-0 group-hover/session:opacity-100 transition-opacity ml-auto text-fg-tertiary hover:text-brand-400 shrink-0",title:i("page.renameSession"),children:c.jsx("svg",{width:"11",height:"11",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M17 3a2.828 2.828 0 1 1 4 4L7.5 20.5 2 22l1.5-5.5L17 3z"})})})]}),c.jsx("div",{className:"text-fg-tertiary text-[10px] mt-0.5",children:new Date(ke.lastMessageAt).toLocaleString()})]})},ke.id))]},xe.label))})(),Dl&&c.jsx("button",{onClick:()=>{Ok()},disabled:Bl,className:"w-full text-center text-[11px] text-fg-tertiary hover:text-brand-400 py-2 rounded-lg transition-colors disabled:opacity-50",children:Bl?i("page.loadingEarlierMessages"):`${i("page.loadMoreSessions")} (${$r.length}/${I_})`})]})]})]}),v&&P==="profile"&&le==="direct"&&ge&&c.jsx("div",{className:"flex-1 overflow-y-auto",children:c.jsx(vv,{agentId:ge,onBack:()=>_("chat"),inline:!0,defaultTab:$e,initialSection:de,highlightMailboxId:ve,onSwipeBack:()=>{qi(T.current)?history.back():_("chat")},authUser:e})}),v&&P==="profile"&&le==="channel"&&ns&&c.jsx("div",{className:"flex-1 overflow-y-auto",children:c.jsx(Av,{teamId:ns,onBack:()=>_("chat"),inline:!0,onSelectAgent:w=>{$t("direct"),Us(w),_("chat")}})}),!v&&qi(P)&&le==="direct"&&ge&&c.jsx("div",{className:"flex-1 overflow-y-auto",children:c.jsx(vv,{agentId:ge,onBack:()=>_("chat"),inline:!0,headless:!0,activeTab:P,initialSection:de,highlightMailboxId:ve,authUser:e})}),!v&&qi(P)&&le==="channel"&&ns&&c.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:c.jsx(Av,{teamId:ns,onBack:()=>_("chat"),inline:!0,headless:!0,activeTab:P,onSelectAgent:w=>{$t("direct"),Us(w),_("chat")}})}),c.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col relative ${Sa?"justify-center":""} ${P!=="chat"?"hidden":""}`,children:[fn&&os.length===0&&c.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-2.5",role:"status","aria-live":"polite",children:[c.jsx(WC,{className:"h-6 w-6 text-brand-400"}),c.jsxs("div",{className:"flex flex-col items-center gap-0.5",children:[c.jsx("span",{className:"text-xs text-fg-tertiary animate-pulse",children:i("page.loadingChat",{defaultValue:"Loading conversation…"})}),c.jsx("span",{className:"text-[11px] text-fg-muted max-w-[70%] truncate",children:zk})]})]}),A_&&c.jsx("div",{className:"absolute top-0 left-0 right-0 z-10 flex justify-center pointer-events-none pt-2",children:c.jsxs("span",{className:"flex items-center gap-2 px-3 py-1.5 rounded-full bg-surface-secondary/90 backdrop-blur-sm border border-border-default shadow",children:[c.jsxs("svg",{className:"animate-spin h-3.5 w-3.5 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[c.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),c.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),c.jsx("span",{className:"text-xs text-fg-tertiary",children:i("page.loadingEarlierMessages")})]})}),c.jsxs("div",{ref:Vr,"data-swipe-owner":!0,className:`${Sa?"hidden":"flex-1"} overflow-y-auto scrollbar-thin ${v?"px-4 py-2":`p-5 ${W}`}`,onScroll:xk,children:[os.length>0&&c.jsx("div",{style:{height:so.getTotalSize(),width:"100%",position:"relative"},children:so.getVirtualItems().map(w=>{const Q=w.index,$=os[Q],I=Q>0?os[Q-1]:null,H=EO($.rawCreatedAt),ie=I?EO(I.rawCreatedAt):"",ne=!!(H&&ie&&H!==ie),Ce=Q===os.length-1,Le=j2({msgIsStreaming:!!$.isStreaming,liveStreamForView:aa}),xe=Nk&&Ce||Le,ke=le==="channel"||!Le||$.isStopped;return c.jsx("div",{"data-index":Q,ref:so.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${w.start}px)`},children:c.jsxs("div",{className:"pb-3",children:[ne&&c.jsxs("div",{className:"flex items-center gap-3 py-2 my-1",children:[c.jsx("div",{className:"flex-1 h-px bg-border-default"}),c.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium uppercase tracking-wider shrink-0",children:SC($.rawCreatedAt,a)}),c.jsx("div",{className:"flex-1 h-px bg-border-default"})]}),c.jsxs("div",{id:`msg-${$.id}`,className:`group/msg flex transition-colors rounded-lg ${v?"gap-0":"gap-3"}`,children:[le==="channel"?c.jsx("div",{className:`shrink-0 cursor-pointer ${v?"hidden":""}`,onClick:Ae=>{if($.sender==="agent"&&$.agentId){const Ue=Ae.currentTarget.getBoundingClientRect();Mt({agentId:$.agentId,top:Ue.top,left:Ue.right+8})}},children:c.jsx(Ns,{name:$.sender==="user"?ac:$.agentName??i("page.fallbackAgent"),avatarUrl:$.sender==="user"?e?.avatarUrl:l.find(Ae=>Ae.id===$.agentId)?.avatarUrl,size:32,bgClass:$.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:$.sender==="agent"?"hover:ring-1 hover:ring-brand-500/40 rounded-lg":"rounded-lg"})}):c.jsx("div",{className:`shrink-0 ${v?"hidden":""}`,children:c.jsx(Ns,{name:$.sender==="user"?ac:$.agentName??(le==="direct"?Et?.name??i("page.fallbackAgent"):i("page.fallbackAgent")),avatarUrl:$.sender==="user"?e?.avatarUrl:l.find(Ae=>Ae.id===($.agentId??(le==="direct"?Et?.id:void 0)))?.avatarUrl,size:32,bgClass:$.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded-lg"})}),c.jsxs("div",{className:"min-w-0 flex-1",children:[c.jsxs("div",{className:"flex items-baseline gap-2",children:[v&&c.jsx(Ns,{name:$.sender==="user"?ac:$.agentName??(le==="direct"?Et?.name??i("page.fallbackAgent"):i("page.fallbackAgent")),avatarUrl:$.sender==="user"?e?.avatarUrl:l.find(Ae=>Ae.id===($.agentId??(le==="direct"?Et?.id:void 0)))?.avatarUrl,size:22,bgClass:$.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded self-center"}),c.jsx("span",{className:"text-sm font-medium text-fg-primary",children:$.sender==="user"?ac:le==="channel"?$.agentName??i("page.fallbackAgent"):c.jsx(wC,{name:$.agentName??(le==="direct"?Et?.name??i("page.fallbackAgent"):i("page.fallbackAgent")),agentId:$.agentId??(le==="direct"?Et?.id:void 0),agents:l,onViewProfile:dt})}),c.jsx("span",{className:"text-xs text-fg-tertiary",title:$.rawCreatedAt?new Date($.rawCreatedAt).toLocaleString():"",children:cc($.time,$.rawCreatedAt,a)})]}),$.replyToId&&$.replyToSender&&c.jsxs("button",{onClick:()=>{const Ae=document.getElementById(`msg-${$.replyToId}`);Ae&&(Ae.scrollIntoView({behavior:"smooth",block:"center"}),Ae.classList.add("bg-brand-500/10"),setTimeout(()=>Ae.classList.remove("bg-brand-500/10"),1500))},className:"flex items-center gap-1.5 mt-0.5 mb-1 pl-2 py-0.5 border-l-2 border-brand-500/40 text-xs text-fg-tertiary hover:text-fg-secondary transition-colors cursor-pointer",children:[c.jsx("span",{className:"font-medium text-brand-500",children:$.replyToSender}),c.jsx("span",{className:"truncate max-w-[250px]",children:$.replyToText??"..."})]}),c.jsxs("div",{className:`mt-0.5 ${$.sender==="agent"?"py-1":"bg-surface-secondary rounded-2xl px-3.5 py-2.5 w-fit max-w-full"} ${xe&&$.sender==="agent"?"streaming-bubble":""}`,children:[$.sender==="user"?c.jsxs("div",{className:"text-sm text-fg-secondary whitespace-pre-wrap",children:[$.images&&$.images.length>0&&c.jsx("div",{className:"flex flex-wrap gap-1.5 mb-1",children:$.images.map((Ae,Ue)=>c.jsx("img",{src:Ae,alt:"",className:"max-w-[200px] max-h-[150px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>fg(Ae)},Ue))}),le==="channel"?LO($.text,l,(Ae,Ue)=>{const ct=Ue.currentTarget.getBoundingClientRect();Mt({agentId:Ae.id,top:ct.bottom,left:ct.left})}):$.text&&c.jsx("span",{className:"leading-relaxed",children:LO($.text,l,(Ae,Ue)=>{const ct=Ue.currentTarget.getBoundingClientRect();Mt({agentId:Ae.id,top:ct.bottom,left:ct.left})})})]}):$.sender==="agent"&&le==="channel"&&!($.segments&&$.segments.length>0)?Le&&!$.text?.trim()?c.jsx(_C,{activities:$l,isActive:!0}):c.jsx(AO,{resetKeys:[$.text],fallback:c.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:$.text}),children:c.jsx($o,{content:$.text,className:"text-sm text-fg-secondary",onMentionClick:Qt,knownNames:hi})}):c.jsx(AO,{resetKeys:[$.id,$.text,$.segments?.length,Le],fallback:c.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:$.text}),children:c.jsx(kC,{msg:$,isStreaming:Le,liveActivities:Le?$l:[],onMentionClick:Qt,knownNames:hi})}),$.isNotification&&c.jsx(CC,{priority:$.notifyPriority})]}),ke&&!t&&c.jsx("div",{className:`transition-opacity ${$.isStopped||$.isError||$.emptyReply||v?"opacity-100":"opacity-0 group-hover/msg:opacity-100"}`,children:c.jsx(PC,{msg:$,onCopy:yk,onRetry:Sk,onResume:wk,onReply:_k,onRemember:le==="direct"?Hd:void 0,showRemember:le==="direct",isCopied:bk===$.id,isLastAgentMsg:$.id===vk})})]})]})]})},$.id)})}),c.jsx("div",{ref:ik}),dk&&P==="chat"&&c.jsx("div",{className:"sticky bottom-0 z-20 h-0 pointer-events-none",children:c.jsx("div",{className:"absolute inset-x-0 bottom-2 flex justify-center",children:c.jsxs("button",{onClick:()=>{lr(),cr("smooth")},className:"pointer-events-auto flex items-center gap-1.5 px-3.5 py-2 bg-surface-secondary/90 backdrop-blur-sm border border-border-default rounded-full shadow-lg hover:bg-surface-elevated transition-colors text-xs text-fg-secondary",children:[c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("polyline",{points:"6 9 12 15 18 9"})}),Ig>0?i("page.newMessages",{count:Ig}):i("page.scrollToBottom")]})})})]}),ot&&(()=>{const w=l.find(Q=>Q.id===ot.agentId);return w?c.jsx(TC,{agent:w,anchorRect:{top:ot.top,left:ot.left},onClose:()=>Mt(null),onViewProfile:dt}):null})(),Sa&&(OO||iu)&&c.jsx("div",{className:"text-center mb-4",children:c.jsx("h2",{className:"text-xl font-semibold text-fg-primary",children:OO||iu})}),le==="direct"&&(bg.length>0||Ko.length>0||wg.length>0)&&c.jsx("div",{className:`${v?"px-3":"px-5"} pb-1 shrink-0 ${Sa?"":W}`,children:c.jsxs("div",{className:`${v?"":"max-w-3xl mx-auto"} flex flex-col gap-1.5`,children:[bg.map(w=>c.jsxs("button",{onClick:()=>Wl(w),className:"w-full text-left px-3.5 py-2.5 rounded-xl border border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/15 transition-colors flex items-center gap-3",children:[c.jsx("span",{className:"w-8 h-8 rounded-lg bg-amber-500/20 text-amber-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z"}),c.jsx("path",{d:"M12 8v4"}),c.jsx("path",{d:"M12 16h.01"})]})}),c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsxs("span",{className:"flex items-baseline gap-1.5 min-w-0",children:[c.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary truncate",children:w.title}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0 whitespace-nowrap",children:cc(w.requestedAt,w.requestedAt,a)})]}),c.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:i("page.userInputPrompt",{count:w.questions?.length??1,defaultValue:`${w.questions?.length??1} question(s) awaiting your response`})})]}),c.jsxs("span",{className:"text-xs font-medium text-amber-500 shrink-0 inline-flex items-center gap-1",children:[i("page.userInputRespond",{defaultValue:"Respond"}),c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},w.id)),Ko.map(w=>c.jsxs("button",{onClick:()=>Jo(w),className:"w-full text-left px-3.5 py-2.5 rounded-xl border border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/15 transition-colors flex items-center gap-3",children:[c.jsx("span",{className:"w-8 h-8 rounded-lg bg-amber-500/20 text-amber-500 flex items-center justify-center shrink-0",children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"}),c.jsx("path",{d:"M12 9v4"}),c.jsx("path",{d:"M12 17h.01"})]})}),c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsxs("span",{className:"flex items-baseline gap-1.5 min-w-0",children:[c.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary truncate",children:w.title}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0 whitespace-nowrap",children:cc(w.requestedAt,w.requestedAt,a)})]}),c.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:i("page.toolApprovalPrompt",{defaultValue:"Tool execution awaiting your approval"})})]}),c.jsxs("span",{className:"text-xs font-medium text-amber-500 shrink-0 inline-flex items-center gap-1",children:[i("page.toolApprovalReview",{defaultValue:"Review"}),c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},w.id)),wg.map(w=>{const Q=w.priority==="high"||w.priority==="urgent";return c.jsxs("button",{onClick:()=>ea({items:[w],index:0}),className:`w-full text-left px-3.5 py-2.5 rounded-xl border transition-colors flex items-center gap-3 ${Q?"border-amber-500/40 bg-amber-500/10 hover:bg-amber-500/15":"border-blue-500/40 bg-blue-500/10 hover:bg-blue-500/15"}`,children:[c.jsx("span",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${Q?"bg-amber-500/20 text-amber-500":"bg-blue-500/20 text-blue-500"}`,children:c.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),c.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),c.jsxs("span",{className:"flex-1 min-w-0",children:[c.jsxs("span",{className:"flex items-baseline gap-1.5 min-w-0",children:[c.jsx("span",{className:"flex-1 text-sm font-medium text-fg-primary truncate",children:QC(w,i)}),c.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0 whitespace-nowrap",title:zm(w.createdAt,n.language),children:Xm(w.createdAt,i)})]}),c.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:$C(w,i).replace(/\s+/g," ").trim()||i("page.notifyUserPrompt",{defaultValue:"Agent notification awaiting your attention"})})]}),c.jsxs("span",{className:`text-xs font-medium shrink-0 inline-flex items-center gap-1 ${Q?"text-amber-500":"text-blue-500"}`,children:[i("page.notifyUserView",{defaultValue:"View"}),c.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:c.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},w.id)})]})}),gn&&c.jsx(jC,{approval:gn,submitting:B_===gn.id,readOnly:gn.status!=="pending",onClose:()=>Wl(null),onSubmit:w=>Dk(gn.id,w)}),On&&c.jsx(o2,{approval:On,submitting:W_===On.id,readOnly:On.status!=="pending",onClose:()=>Jo(null),onDecision:(w,Q)=>Ik(On.id,w,Q)}),Ai&&c.jsx(a2,{notification:Ai,agentName:Et?.name,acknowledging:X_===Ai.id,index:jr?.index??0,total:jr?.items.length??1,onClose:tu,onAcknowledge:()=>Bk(Ai.id)}),Di&&c.jsx(Wo,{variant:"primary",title:i("page.retry",{defaultValue:"Retry"}),message:Di.followCount===1?i("page.retryConfirmSingular"):i("page.retryConfirmPlural",{count:Di.followCount}),confirmLabel:i("common:confirm"),onConfirm:()=>{const w=Di;Yd(null),Gd(w.retryMsg,w.userMsg,w.retryText)},onCancel:()=>Yd(null)}),Rr&&c.jsx(RC,{busy:Kg,onConfirm:w=>{kk(w)},onCancel:()=>{Kg||Hd(null)}}),c.jsxs("div",{"data-keep-edit-focus":!0,className:`${v?"px-3 py-2":"px-5 py-3"} relative shrink-0 ${Sa?"":W}`,onDrop:Mk,onDragOver:Lk,children:[c.jsxs("div",{className:`bg-surface-primary border border-border-default shadow-lg shadow-black/10 ${v?`${vr?"rounded-2xl p-2":"rounded-2xl p-3"}`:`${vr?"rounded-2xl p-2":"rounded-2xl p-3"} max-w-3xl mx-auto`}`,children:[Un&&Cn.length>0&&c.jsxs("div",{className:"absolute bottom-full left-4 mb-1 bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden z-10 max-h-64 max-w-xs w-72 overflow-y-auto",children:[c.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:i("page.mentionAgent")}),Cn.map((w,Q)=>w.kind==="agent"?c.jsxs("button",{ref:$=>{Q===ia&&$&&$.scrollIntoView({block:"nearest"})},onClick:()=>oc(w.agent.name),onMouseEnter:()=>Hn(Q),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${Q===ia?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx(Ns,{name:w.agent.name,avatarUrl:w.agent.avatarUrl,size:24,bgClass:"bg-brand-500/20 text-brand-500"}),c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-overlay text-fg-tertiary shrink-0",children:i("page.mentionType.agent")}),c.jsx("span",{className:"flex-1 min-w-0 truncate",children:w.agent.name}),c.jsx("span",{className:"text-xs text-fg-tertiary ml-auto shrink-0",children:w.agent.role})]},`agt-${w.agent.id}`):c.jsxs("button",{ref:$=>{Q===ia&&$&&$.scrollIntoView({block:"nearest"})},onClick:()=>oc(w.entity.name,w.entity.entityType,w.entity.id),onMouseEnter:()=>Hn(Q),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${Q===ia?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx("span",{className:"w-6 h-6 flex items-center justify-center text-sm shrink-0",children:fO[w.entity.entityType]??"📄"}),c.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded bg-surface-overlay text-fg-tertiary shrink-0",children:i(`page.mentionType.${w.entity.entityType}`,{defaultValue:w.entity.entityType})}),c.jsx("span",{className:"flex-1 min-w-0 truncate",children:w.entity.name}),c.jsx("span",{className:"text-xs text-fg-tertiary ml-auto shrink-0",children:w.entity.role})]},`${w.entity.entityType}-${w.entity.id}`))]}),Yn&&xn.length>0&&c.jsxs("div",{className:"absolute bottom-full left-4 mb-1 bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden z-10 max-h-64 max-w-xs w-72 overflow-y-auto",children:[c.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:i("page.slashSkill")}),xn.map((w,Q)=>c.jsxs("button",{ref:$=>{Q===jd&&$&&$.scrollIntoView({block:"nearest"})},onClick:()=>nO(w),onMouseEnter:()=>na(Q),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${Q===jd?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[c.jsx("span",{className:"text-xs w-5 h-5 flex items-center justify-center shrink-0",children:"🔧"}),c.jsxs("span",{className:"flex-1 min-w-0 truncate font-mono text-[13px]",children:["/",w.name]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto shrink-0 max-w-[100px] truncate",children:w.description})]},w.name))]}),nr.length>0&&c.jsx("div",{className:"flex items-center gap-1.5 mb-2 flex-wrap",children:nr.map(w=>c.jsxs("span",{className:"inline-flex items-center gap-1 max-w-[240px] pl-2 pr-1 py-1 rounded-lg bg-brand-500/10 text-brand-500 text-xs border border-brand-500/20",title:w.content,children:[c.jsx("span",{className:"truncate",children:w.label}),c.jsx("button",{onClick:()=>dn(Q=>Q.filter($=>$.id!==w.id)),className:"w-4 h-4 flex items-center justify-center rounded hover:bg-brand-500/20 shrink-0","aria-label":i("common:remove",{defaultValue:"Remove"}),children:c.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},w.id))}),or.length>0&&c.jsxs("div",{className:"flex items-center gap-2 mb-2 overflow-x-auto pb-1",children:[or.map(w=>c.jsxs("div",{className:"relative group/img shrink-0",children:[Kd(w)?c.jsx("img",{src:w.dataUrl,alt:w.name,className:"w-16 h-16 rounded-lg object-cover border border-border-default"}):c.jsxs("div",{className:"w-16 h-16 rounded-lg border border-border-default bg-surface-elevated flex flex-col items-center justify-center gap-0.5",title:w.name,children:[c.jsx("span",{className:"text-xl leading-none",children:Rk(w.name,w.dataUrl)}),c.jsx("span",{className:"text-[9px] text-fg-tertiary truncate max-w-[56px] px-0.5",children:w.name.split(".").pop()?.toUpperCase()})]}),c.jsx("button",{onClick:()=>Ek(w.id),className:"absolute -top-1.5 -right-1.5 w-5 h-5 bg-surface-secondary border border-gray-600 rounded-full flex items-center justify-center text-fg-secondary hover:text-red-500 hover:border-red-500 text-xs opacity-0 group-hover/img:opacity-100 transition-opacity",children:"×"})]},w.id)),or.length<oO&&c.jsx("button",{onClick:()=>fd.current?.click(),className:"w-16 h-16 rounded-lg border border-dashed border-gray-600 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary hover:border-gray-400 transition-colors shrink-0",title:i("page.addMoreFiles"),children:c.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),or.length>0&&or.some(w=>Kd(w))&&Et&&Et.modelSupportsVision===!1&&c.jsxs("div",{className:"text-[10px] text-amber-500/80 mb-1.5 flex items-center gap-1",children:[c.jsx("svg",{className:"w-3 h-3 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:c.jsx("path",{d:"M12 9v4m0 4h.01M12 2L2 22h20L12 2z",strokeLinecap:"round",strokeLinejoin:"round"})}),i("page.visionWarning")]}),c.jsx("input",{ref:fd,type:"file",accept:"image/*,.pdf,.docx,.xlsx,.pptx,.xls,.doc,.csv,.json,.xml,.html,.epub",multiple:!0,className:"hidden",onChange:w=>{w.target.files&&ba(w.target.files),w.target.value=""}}),vs&&c.jsxs("div",{className:"flex items-center gap-2 mb-2 px-3 py-1.5 bg-surface-elevated rounded-lg border border-border-default/50",children:[c.jsxs("div",{className:"flex-1 min-w-0 pl-2 border-l-2 border-brand-500/50",children:[c.jsx("span",{className:"text-[11px] font-medium text-brand-500",children:vs.sender}),c.jsx("p",{className:"text-[11px] text-fg-tertiary truncate",children:vs.text})]}),c.jsx("button",{onClick:()=>es(null),className:"text-fg-tertiary hover:text-fg-secondary shrink-0 p-0.5",children:c.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[c.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),c.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),c.jsxs("div",{className:nu?"flex flex-col gap-2 min-w-0":"flex gap-2 items-end min-w-0",children:[c.jsxs("div",{className:nu?"flex gap-2 items-end min-w-0":"contents",children:[c.jsx("button",{onClick:()=>fd.current?.click(),disabled:le==="direct"&&(!ge||ya),className:`${vr?"p-1.5":"px-2.5 py-2.5"} text-fg-tertiary hover:text-fg-secondary disabled:opacity-40 transition-colors rounded-xl hover:bg-surface-elevated shrink-0 self-end mb-0.5`,title:i("page.attachFilesTitle"),children:c.jsx("svg",{className:vr?"w-[18px] h-[18px]":"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:c.jsx("path",{d:"M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48",strokeLinecap:"round",strokeLinejoin:"round"})})}),c.jsx("textarea",{ref:Hs,value:zt,onChange:w=>{Qk(w.target.value),Ho()},onKeyDown:w=>{const Q=w.nativeEvent;if(!(Q.isComposing===!0||Q.keyCode===229)){if(Un&&Cn.length>0){const $=w.key==="ArrowUp"||w.ctrlKey&&w.key==="p",I=w.key==="ArrowDown"||w.ctrlKey&&w.key==="n",H=w.key==="Enter"||w.key==="Tab",ie=w.key==="Escape";if($){w.preventDefault(),Hn(ne=>(ne-1+Cn.length)%Cn.length);return}if(I){w.preventDefault(),Hn(ne=>(ne+1)%Cn.length);return}if(H){w.preventDefault();const ne=Cn[ia];ne&&(ne.kind==="agent"?oc(ne.agent.name):oc(ne.entity.name,ne.entity.entityType,ne.entity.id));return}if(ie){w.preventDefault(),ra(!1);return}}if(Yn&&xn.length>0){const $=w.key==="ArrowUp"||w.ctrlKey&&w.key==="p",I=w.key==="ArrowDown"||w.ctrlKey&&w.key==="n",H=w.key==="Enter"||w.key==="Tab",ie=w.key==="Escape";if($){w.preventDefault(),na(ne=>(ne-1+xn.length)%xn.length);return}if(I){w.preventDefault(),na(ne=>(ne+1)%xn.length);return}if(H){w.preventDefault();const ne=xn[jd];ne&&nO(ne);return}if(ie){w.preventDefault(),Zl(!1);return}}if(w.key==="Escape"){w.preventDefault(),w.currentTarget.blur();return}w.key==="Enter"&&!w.shiftKey&&(w.preventDefault(),Vg())}},onPaste:Ak,placeholder:iu,disabled:le==="direct"&&(!ge||ya),rows:vr?1:2,className:`flex-1 min-w-0 w-full bg-transparent rounded-xl text-sm outline-none disabled:opacity-40 transition-colors resize-none overflow-y-auto leading-relaxed placeholder:text-fg-secondary ${vr?"px-2 py-1.5":"px-4 py-3"}`,style:{minHeight:vr?"36px":"52px",maxHeight:`${MO(vr)}px`}})]}),c.jsxs("div",{className:`flex items-center gap-1.5 shrink-0 ${EC(nu)}`,children:[le==="direct"&&c.jsx(jI,{value:L_,agentId:ge,disabled:!ge||ya,onSelect:(w,Q)=>{if(Q==="agent"){ji(w),Lv(w,Q,ge).catch(()=>{});return}ji(null),Lv(w,Q,ge).catch(()=>{})}}),(le==="direct"?xr&&aa:xr)&&le!=="dm"?c.jsx("button",{onClick:pk,className:`${vr?"w-8 h-8 rounded-full flex items-center justify-center":"px-3 py-2.5 rounded-xl"} bg-red-600 hover:bg-red-500 text-white text-sm transition-colors`,title:i("page.stopAgent"),children:c.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:c.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}):c.jsx("button",{onClick:()=>Vg(),disabled:le==="direct"&&(!ge||ya)||!zt.trim()&&or.length===0,className:vr?"w-8 h-8 rounded-full flex items-center justify-center bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white transition-colors":"px-5 py-2.5 bg-brand-600 hover:bg-brand-500 disabled:opacity-40 text-white text-sm rounded-xl transition-colors",title:i("common:send"),children:vr?c.jsx("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:c.jsx("path",{d:"M12 19V5M5 12l7-7 7 7",strokeLinecap:"round",strokeLinejoin:"round"})}):i("common:send")})]})]})]}),(zt.trim()||or.length>0)&&c.jsx("div",{className:"mt-0.5 flex justify-end px-1 pointer-events-none select-none",children:c.jsx("span",{className:"text-[10px] text-fg-tertiary/80",children:i("common:shiftEnterHint")})})]})]})]}),!v&&F&&V&&c.jsx(kD,{payload:F,onClose:V,width:j?Z:yt,onResizeStart:Xt,onAddToChat:we,tabs:X,activeTabId:ae,onSelectTab:B?.setActiveRightPanelTab,onCloseTab:B?.closeRightPanelTab,onNewTab:()=>{if(!se)return;if(B?.rightPanelMode==="terminal"){const Q=`term_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"terminal",terminalId:Q,title:"Terminal"});return}const w=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"url",url:"about:blank",title:"New Tab",browserId:w})},fullscreen:j,onToggleFullscreen:B?.toggleRightPanelFullscreen,onBrowserMeta:B?.updateRightPanelBrowserTab?(w,Q)=>B.updateRightPanelBrowserTab(w,Q):void 0,panelMode:B?.rightPanelMode??"browser",onPanelModeChange:w=>B?.switchRightPanelMode(w),onTerminalMeta:B?.updateRightPanelTerminalTab?(w,Q)=>B.updateRightPanelTerminalTab(w,Q):void 0,onOpenUrlFromTerminal:w=>{if(!se)return;const Q=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;se({kind:"url",url:w,title:w,browserId:Q})},onOpenPathFromTerminal:w=>{se?.({kind:"file",path:w,title:w.split(/[/\\]/).pop()||w})}}),ug&&c.jsx(AC,{src:ug,onClose:()=>fg(null)})]})}function AI({agent:s}){const{t:e}=Pt(["common"]),t=Uv(s.id),r=Ol(s.status,t),i=r.labelKey?e(`common:${r.labelKey}`):"";return c.jsx("span",{className:`shrink-0 w-2 h-2 rounded-full ${r.dotClass} ${r.tone==="busy"?"animate-pulse":""}`,title:i,"aria-label":i})}function MI({agent:s,tasks:e,onViewProfile:t}){const{t:r}=Pt(["team","common"]),[i,n]=S.useState(!1),a=S.useRef(null),o=S.useRef(null),l=Uv(s.id),h=Ol(s.status,l),d=h.tone==="busy",u=h.tone==="danger",f=!h.running,p=d?e.find(O=>O.assignedAgentId===s.id&&O.status==="in_progress"):null,v=s.currentActivity;S.useEffect(()=>{u&&s.lastError&&Ic(s.lastError)&&Bc()},[u,s.lastError]),S.useEffect(()=>{if(!i)return;const O=m=>{a.current&&!a.current.contains(m.target)&&n(!1)};return document.addEventListener("mousedown",O),()=>document.removeEventListener("mousedown",O)},[i]),S.useLayoutEffect(()=>{if(!i||!o.current)return;const O=o.current,m=O.getBoundingClientRect(),x=window.innerWidth;m.right>x-8&&(O.style.left="auto",O.style.right="0"),m.left<8&&(O.style.left="0",O.style.right="auto");const y=x-16;m.width>y&&(O.style.width=`${y}px`)},[i]);const b=h.labelKey?r(h.labelKey):s.status||"—",g=v?v.type==="heartbeat"?r("page.activityHeartbeat",{name:v.heartbeatName??v.label}):v.type==="chat"?v.label:v.type==="task"?r("page.activityTask",{label:v.label}):v.label:r("page.processing");return c.jsxs("div",{className:"relative",ref:a,children:[c.jsxs("button",{onClick:()=>n(O=>!O),className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full transition-colors hover:opacity-80 ${h.chipClass}`,children:[c.jsx("span",{className:`w-2 h-2 rounded-full ${h.dotClass}`}),c.jsx("span",{className:`text-xs ${h.textClass}`,children:b}),s.mailboxDepth!=null&&s.mailboxDepth>0&&c.jsx("span",{className:"text-[9px] bg-fg-tertiary/20 text-fg-tertiary rounded-full px-1.5",children:s.mailboxDepth})]}),i&&u&&c.jsxs("div",{ref:o,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-red-500/30 rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[c.jsx("p",{className:"text-[10px] text-red-500 uppercase font-semibold",children:r("page.errorDetails")}),c.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2.5",children:[c.jsx("pre",{className:"text-[10px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:nh(s.lastError,r)||s.lastError||r("page.agentErrorFallback")}),s.lastErrorAt&&c.jsx("div",{className:"text-[9px] text-red-500/50 mt-1.5 border-t border-red-500/10 pt-1",children:new Date(s.lastErrorAt).toLocaleString()})]}),c.jsx("button",{onClick:()=>{n(!1),t?.(s.id)},className:"w-full text-center text-[10px] text-red-500 hover:text-red-500 border border-red-500/30 hover:border-red-500/50 rounded-lg py-1 transition-colors",children:r("page.viewAgentProfileArrow")})]}),i&&f&&c.jsxs("div",{ref:o,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:r("page.agentNotRunningTitle")}),c.jsx("p",{className:"text-[11px] text-fg-secondary",children:r("page.agentNotRunningHint")}),c.jsx("button",{onClick:()=>{n(!1),t?.(s.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1 transition-colors",children:r("page.viewAgentProfileArrow")})]}),i&&!d&&!u&&!f&&c.jsxs("div",{ref:o,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:r("page.agentIdleTitle")}),c.jsx("p",{className:"text-[11px] text-fg-secondary",children:r("page.agentIdleHint")}),c.jsx("button",{onClick:()=>{n(!1),t?.(s.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1 transition-colors",children:r("page.viewAgentProfileArrow")})]}),i&&d&&c.jsxs("div",{ref:o,className:"absolute top-full left-0 mt-1.5 bg-surface-secondary border border-border-default rounded-xl shadow-2xl z-30 w-80 max-w-[calc(100vw-1rem)] p-3 space-y-2",children:[c.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:r("page.currentActivity")}),p?c.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-brand-500/10 border border-brand-500/30 cursor-pointer hover:bg-brand-500/10 transition-colors",onClick:()=>{n(!1),Lr.navigate(Yt.WORK,{openTask:p.id})},children:[c.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-brand-500 truncate",children:p.title}),c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:r("page.workingOnTaskHint")})]}),c.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"})]}):c.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-surface-elevated/50",children:[c.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${v?.type==="heartbeat"||v?.type==="chat","bg-blue-400 animate-pulse"}`}),c.jsxs("div",{className:"flex-1 min-w-0",children:[c.jsx("div",{className:"text-xs text-fg-secondary",children:g}),c.jsx("div",{className:"text-[10px] text-fg-tertiary",children:v?.type==="heartbeat"?r("page.activityDescHeartbeat"):v?.type==="chat"?r("page.activityDescChat"):r("page.activityDescFallback")})]})]}),c.jsx("button",{onClick:()=>{n(!1),t?.(s.id,{tab:"overview"})},className:"w-full text-center text-[10px] text-brand-500 hover:text-brand-500 border border-border-default hover:border-gray-600 rounded-lg py-1.5 transition-colors",children:r("page.viewMindArrow")})]})]})}export{KI as TeamPage};
|