@markus-global/cli 0.9.0 → 0.9.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/commands/start.js +25 -0
- package/dist/commands/start.js.map +1 -1
- package/dist/markus.mjs +211 -24
- package/dist/web-ui/assets/{CommentInput-Ccv0KCzc.js → CommentInput-D3jx82c7.js} +1 -1
- package/dist/web-ui/assets/{ContentRenderer-BbN7QT3E.js → ContentRenderer-CQ9uMng0.js} +2 -2
- package/dist/web-ui/assets/{Deliverables-Dzfujlqv.js → Deliverables-DKy2_HPY.js} +1 -1
- package/dist/web-ui/assets/Notifications-1YKMlJ91.js +1 -0
- package/dist/web-ui/assets/{Search-Va12fH-V.js → Search-D5P2V5tM.js} +1 -1
- package/dist/web-ui/assets/{Settings-D_0MEUGb.js → Settings-C86a_mG8.js} +6 -6
- package/dist/web-ui/assets/{Store-dRlOlppM.js → Store-Ca8mvyTT.js} +1 -1
- package/dist/web-ui/assets/Team-DHmWU23x.js +40 -0
- package/dist/web-ui/assets/{Work-C6pfFbRU.js → Work-zJLJ6A3I.js} +5 -5
- package/dist/web-ui/assets/{arc-w52qYN0j.js → arc-s5quZ9MF.js} +1 -1
- package/dist/web-ui/assets/{architectureDiagram-3BPJPVTR-Dq5t04Vy.js → architectureDiagram-3BPJPVTR-iZhZ9wDV.js} +1 -1
- package/dist/web-ui/assets/{blockDiagram-GPEHLZMM-dMSQ7RYP.js → blockDiagram-GPEHLZMM-lYMBEpQb.js} +1 -1
- package/dist/web-ui/assets/{c4Diagram-AAUBKEIU-yG4K-xPW.js → c4Diagram-AAUBKEIU-C8vbScKq.js} +1 -1
- package/dist/web-ui/assets/channel-D2RoSw08.js +1 -0
- package/dist/web-ui/assets/{chunk-2J33WTMH-BMCCyFP7.js → chunk-2J33WTMH-DhvC5Teh.js} +1 -1
- package/dist/web-ui/assets/{chunk-4BX2VUAB-DrZE__0f.js → chunk-4BX2VUAB-Do4f1QNX.js} +1 -1
- package/dist/web-ui/assets/{chunk-55IACEB6-BHAPJ9Eo.js → chunk-55IACEB6-BCDgVda5.js} +1 -1
- package/dist/web-ui/assets/{chunk-727SXJPM-Ctfjl9vK.js → chunk-727SXJPM-n9W-gHJL.js} +1 -1
- package/dist/web-ui/assets/{chunk-AQP2D5EJ-SVZPGzSA.js → chunk-AQP2D5EJ-joCNa2WM.js} +1 -1
- package/dist/web-ui/assets/{chunk-FMBD7UC4-DeTpOrnv.js → chunk-FMBD7UC4-Cp9QtfEA.js} +1 -1
- package/dist/web-ui/assets/{chunk-ND2GUHAM-CudW1r3G.js → chunk-ND2GUHAM-Dt_ZkR0s.js} +1 -1
- package/dist/web-ui/assets/{chunk-QZHKN3VN-CJSQIoVy.js → chunk-QZHKN3VN-CVGCkc4k.js} +1 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-DGebyJZN.js +1 -0
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-DGebyJZN.js +1 -0
- package/dist/web-ui/assets/{cose-bilkent-S5V4N54A-CcCOSPt7.js → cose-bilkent-S5V4N54A-B4Q2AELl.js} +1 -1
- package/dist/web-ui/assets/{dagre-BM42HDAG-F3l9565T.js → dagre-BM42HDAG-DoazhTnM.js} +1 -1
- package/dist/web-ui/assets/{diagram-2AECGRRQ-B5Ep5hBX.js → diagram-2AECGRRQ-C7KY67Fn.js} +1 -1
- package/dist/web-ui/assets/{diagram-5GNKFQAL-Ba-Xi40Z.js → diagram-5GNKFQAL-dPjx6DBc.js} +1 -1
- package/dist/web-ui/assets/{diagram-KO2AKTUF-nq3nvV52.js → diagram-KO2AKTUF-D4BEU7N2.js} +1 -1
- package/dist/web-ui/assets/{diagram-LMA3HP47-BLQG5suI.js → diagram-LMA3HP47-D9PLmyge.js} +1 -1
- package/dist/web-ui/assets/{diagram-OG6HWLK6-BZwEfL_A.js → diagram-OG6HWLK6-Dg6SRSYN.js} +1 -1
- package/dist/web-ui/assets/{erDiagram-TEJ5UH35-x0d6Urzc.js → erDiagram-TEJ5UH35-D97ueERw.js} +1 -1
- package/dist/web-ui/assets/{flowDiagram-I6XJVG4X-Bps4iInm.js → flowDiagram-I6XJVG4X-Cm-sRIL_.js} +1 -1
- package/dist/web-ui/assets/{ganttDiagram-6RSMTGT7-BQhqabZG.js → ganttDiagram-6RSMTGT7-CXq6jqCz.js} +1 -1
- package/dist/web-ui/assets/{gitGraphDiagram-PVQCEYII-CZsFUtiG.js → gitGraphDiagram-PVQCEYII-CJ50_J0p.js} +1 -1
- package/dist/web-ui/assets/{index-BVZKeNvh.js → index-CHkb08MZ.js} +55 -55
- package/dist/web-ui/assets/index-CPULIfuW.css +1 -0
- package/dist/web-ui/assets/{infoDiagram-5YYISTIA-bUkRpixn.js → infoDiagram-5YYISTIA-CbTpYpwF.js} +1 -1
- package/dist/web-ui/assets/{ishikawaDiagram-YF4QCWOH-C71uSHjN.js → ishikawaDiagram-YF4QCWOH-CUt9Btxt.js} +1 -1
- package/dist/web-ui/assets/{journeyDiagram-JHISSGLW-CH4cq7H3.js → journeyDiagram-JHISSGLW-F9zmJizG.js} +1 -1
- package/dist/web-ui/assets/{kanban-definition-UN3LZRKU-B1plHCmn.js → kanban-definition-UN3LZRKU-jNs9ezLz.js} +1 -1
- package/dist/web-ui/assets/{mermaid.core-BtKFJxef.js → mermaid.core-Cxm0p7KD.js} +5 -5
- package/dist/web-ui/assets/{mindmap-definition-RKZ34NQL-BRinAMnx.js → mindmap-definition-RKZ34NQL-BuW2AA71.js} +1 -1
- package/dist/web-ui/assets/{pieDiagram-4H26LBE5-B8r7cm8D.js → pieDiagram-4H26LBE5-BKrViKGj.js} +1 -1
- package/dist/web-ui/assets/{quadrantDiagram-W4KKPZXB-BlYE_3Bv.js → quadrantDiagram-W4KKPZXB-Hh0Kzhcb.js} +1 -1
- package/dist/web-ui/assets/{requirementDiagram-4Y6WPE33-XHqns5Oh.js → requirementDiagram-4Y6WPE33-B1ga-7j9.js} +1 -1
- package/dist/web-ui/assets/{sankeyDiagram-5OEKKPKP--WceN9u7.js → sankeyDiagram-5OEKKPKP-2uQ075vI.js} +1 -1
- package/dist/web-ui/assets/{sequenceDiagram-3UESZ5HK-NXQDJA2d.js → sequenceDiagram-3UESZ5HK-97k-cDlv.js} +1 -1
- package/dist/web-ui/assets/{stateDiagram-AJRCARHV-Cs8Vl8wX.js → stateDiagram-AJRCARHV-PTiMHe-8.js} +1 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-CNP7uL0K.js +1 -0
- package/dist/web-ui/assets/{timeline-definition-PNZ67QCA-V9TBhcGA.js → timeline-definition-PNZ67QCA-Gji5tIlk.js} +1 -1
- package/dist/web-ui/assets/{vennDiagram-CIIHVFJN-BkrjAkwE.js → vennDiagram-CIIHVFJN-B91fyhQC.js} +1 -1
- package/dist/web-ui/assets/{wardley-L42UT6IY-DnYl7xFk.js → wardley-L42UT6IY-C9MIuW9C.js} +1 -1
- package/dist/web-ui/assets/{wardleyDiagram-YWT4CUSO-Bgjk8gUy.js → wardleyDiagram-YWT4CUSO-CtXjrE4d.js} +1 -1
- package/dist/web-ui/assets/{xychartDiagram-2RQKCTM6-DVv-I1Er.js → xychartDiagram-2RQKCTM6-BgVdUlxT.js} +1 -1
- package/dist/web-ui/index.html +2 -2
- package/package.json +1 -1
- package/dist/web-ui/assets/Notifications-DMI9cmK5.js +0 -1
- package/dist/web-ui/assets/Team-D8m98W3b.js +0 -40
- package/dist/web-ui/assets/channel-0x_SxlyN.js +0 -1
- package/dist/web-ui/assets/classDiagram-4FO5ZUOK-D4o-x8Tr.js +0 -1
- package/dist/web-ui/assets/classDiagram-v2-Q7XG4LA2-D4o-x8Tr.js +0 -1
- package/dist/web-ui/assets/index-BDWvYwl1.css +0 -1
- package/dist/web-ui/assets/stateDiagram-v2-BHNVJYJU-Cmof_fUq.js +0 -1
|
@@ -1,40 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-BVZKeNvh.js","assets/index-BDWvYwl1.css"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as n,e as Fi,u as Ge,G as Xo,j as e,t as $n,H as Qo,a as ma,B as Bi,P as xt,f as M,w as ze,M as Zo,A as vt,n as ps,J as Bn,K as Jo,L as el,b as zi,O as Wi,h as Hi,l as br,Q as tl,U as sl,V as Ja,W as nl,X as rl,Y as Vi,Z as qi,$ as al,a0 as il,a1 as ol,_ as Ui,C as ei,a2 as ll,a3 as Ks,a4 as cl,a5 as dl,a6 as aa,a7 as ti,a8 as ul,x as ia,z as si,k as ni,s as ml,g as xl,a9 as ri,m as ai,o as fl,aa as gl,p as hl,ab as ii,q as pl,ac as bl,v as yl,ad as vl,ae as jl,R as wl,D as kl,af as hr,ag as pr,y as Nl}from"./index-BVZKeNvh.js";import{r as oi,p as Sl}from"./CommentInput-Ccv0KCzc.js";import{resolveFormat as Cl,ContentRenderer as li}from"./ContentRenderer-BbN7QT3E.js";function cn(i,a,s){let r=s.initialDeps??[],o,d=!0;function u(){var m,f,y;let N;s.key&&((m=s.debug)!=null&&m.call(s))&&(N=Date.now());const j=i();if(!(j.length!==r.length||j.some((v,O)=>r[O]!==v)))return o;r=j;let b;if(s.key&&((f=s.debug)!=null&&f.call(s))&&(b=Date.now()),o=a(...j),s.key&&((y=s.debug)!=null&&y.call(s))){const v=Math.round((Date.now()-N)*100)/100,O=Math.round((Date.now()-b)*100)/100,E=O/16,T=(p,C)=>{for(p=String(p);p.length<C;)p=" "+p;return p};console.info(`%c⏱ ${T(O,5)} /${T(v,5)} ms`,`
|
|
3
|
-
font-size: .6rem;
|
|
4
|
-
font-weight: bold;
|
|
5
|
-
color: hsl(${Math.max(0,Math.min(120-120*E,120))}deg 100% 31%);`,s?.key)}return s?.onChange&&!(d&&s.skipInitialOnChange)&&s.onChange(o),d=!1,o}return u.updateDeps=m=>{r=m},u}function ci(i,a){if(i===void 0)throw new Error("Unexpected undefined");return i}const Tl=(i,a)=>Math.abs(i-a)<1.01,Ml=(i,a,s)=>{let r;return function(...o){i.clearTimeout(r),r=i.setTimeout(()=>a.apply(this,o),s)}},di=i=>{const{offsetWidth:a,offsetHeight:s}=i;return{width:a,height:s}},El=i=>i,Al=i=>{const a=Math.max(i.startIndex-i.overscan,0),s=Math.min(i.endIndex+i.overscan,i.count-1),r=[];for(let o=a;o<=s;o++)r.push(o);return r},Il=(i,a)=>{const s=i.scrollElement;if(!s)return;const r=i.targetWindow;if(!r)return;const o=u=>{const{width:m,height:f}=u;a({width:Math.round(m),height:Math.round(f)})};if(o(di(s)),!r.ResizeObserver)return()=>{};const d=new r.ResizeObserver(u=>{const m=()=>{const f=u[0];if(f?.borderBoxSize){const y=f.borderBoxSize[0];if(y){o({width:y.inlineSize,height:y.blockSize});return}}o(di(s))};i.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(m):m()});return d.observe(s,{box:"border-box"}),()=>{d.unobserve(s)}},ui={passive:!0},mi=typeof window>"u"?!0:"onscrollend"in window,Pl=(i,a)=>{const s=i.scrollElement;if(!s)return;const r=i.targetWindow;if(!r)return;let o=0;const d=i.options.useScrollendEvent&&mi?()=>{}:Ml(r,()=>{a(o,!1)},i.options.isScrollingResetDelay),u=N=>()=>{const{horizontal:j,isRtl:I}=i.options;o=j?s.scrollLeft*(I&&-1||1):s.scrollTop,d(),a(o,N)},m=u(!0),f=u(!1);s.addEventListener("scroll",m,ui);const y=i.options.useScrollendEvent&&mi;return y&&s.addEventListener("scrollend",f,ui),()=>{s.removeEventListener("scroll",m),y&&s.removeEventListener("scrollend",f)}},Ll=(i,a,s)=>{if(a?.borderBoxSize){const r=a.borderBoxSize[0];if(r)return Math.round(r[s.options.horizontal?"inlineSize":"blockSize"])}return i[s.options.horizontal?"offsetWidth":"offsetHeight"]},_l=(i,{adjustments:a=0,behavior:s},r)=>{var o,d;const u=i+a;(d=(o=r.scrollElement)==null?void 0:o.scrollTo)==null||d.call(o,{[r.options.horizontal?"left":"top"]:u,behavior:s})};class Rl{constructor(a){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 s,r,o;return((o=(r=(s=this.targetWindow)==null?void 0:s.performance)==null?void 0:r.now)==null?void 0:o.call(r))??Date.now()},this.observer=(()=>{let s=null;const r=()=>s||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:s=new this.targetWindow.ResizeObserver(o=>{o.forEach(d=>{const u=()=>{const m=d.target,f=this.indexFromElement(m);if(!m.isConnected){this.observer.unobserve(m);return}this.shouldMeasureDuringScroll(f)&&this.resizeItem(f,this.options.measureElement(m,d,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(u):u()})}));return{disconnect:()=>{var o;(o=r())==null||o.disconnect(),s=null},observe:o=>{var d;return(d=r())==null?void 0:d.observe(o,{box:"border-box"})},unobserve:o=>{var d;return(d=r())==null?void 0:d.unobserve(o)}}})(),this.range=null,this.setOptions=s=>{Object.entries(s).forEach(([r,o])=>{typeof o>"u"&&delete s[r]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:El,rangeExtractor:Al,onChange:()=>{},measureElement:Ll,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",...s}},this.notify=s=>{var r,o;(o=(r=this.options).onChange)==null||o.call(r,this,s)},this.maybeNotify=cn(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),s=>{this.notify(s)},{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(s=>s()),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 s;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=((s=this.scrollElement)==null?void 0:s.window)??null,this.elementsCache.forEach(o=>{this.observer.observe(o)}),this.unsubs.push(this.options.observeElementRect(this,o=>{this.scrollRect=o,this.maybeNotify()})),this.unsubs.push(this.options.observeElementOffset(this,(o,d)=>{this.scrollAdjustments=0,this.scrollDirection=d?this.getScrollOffset()<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=d,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=(s,r)=>{const o=new Map,d=new Map;for(let u=r-1;u>=0;u--){const m=s[u];if(o.has(m.lane))continue;const f=d.get(m.lane);if(f==null||m.end>f.end?d.set(m.lane,m):m.end<f.end&&o.set(m.lane,!0),o.size===this.options.lanes)break}return d.size===this.options.lanes?Array.from(d.values()).sort((u,m)=>u.end===m.end?u.index-m.index:u.end-m.end)[0]:void 0},this.getMeasurementOptions=cn(()=>[this.options.count,this.options.paddingStart,this.options.scrollMargin,this.options.getItemKey,this.options.enabled,this.options.lanes,this.options.laneAssignmentMode],(s,r,o,d,u,m,f)=>(this.prevLanes!==void 0&&this.prevLanes!==m&&(this.lanesChangedFlag=!0),this.prevLanes=m,this.pendingMeasuredCacheIndexes=[],{count:s,paddingStart:r,scrollMargin:o,getItemKey:d,enabled:u,lanes:m,laneAssignmentMode:f}),{key:!1}),this.getMeasurements=cn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:s,paddingStart:r,scrollMargin:o,getItemKey:d,enabled:u,lanes:m,laneAssignmentMode:f},y)=>{if(!u)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>s)for(const b of this.laneAssignments.keys())b>=s&&this.laneAssignments.delete(b);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(b=>{this.itemSizeCache.set(b.key,b.size)}));const N=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===s&&(this.lanesSettling=!1);const j=this.measurementsCache.slice(0,N),I=new Array(m).fill(void 0);for(let b=0;b<N;b++){const v=j[b];v&&(I[v.lane]=b)}for(let b=N;b<s;b++){const v=d(b),O=this.laneAssignments.get(b);let E,T;const p=f==="estimate"||y.has(v);if(O!==void 0&&this.options.lanes>1){E=O;const D=I[E],k=D!==void 0?j[D]:void 0;T=k?k.end+this.options.gap:r+o}else{const D=this.options.lanes===1?j[b-1]:this.getFurthestMeasurement(j,b);T=D?D.end+this.options.gap:r+o,E=D?D.lane:b%this.options.lanes,this.options.lanes>1&&p&&this.laneAssignments.set(b,E)}const C=y.get(v),A=typeof C=="number"?C:this.options.estimateSize(b),H=T+A;j[b]={index:b,start:T,size:A,end:H,key:v,lane:E},I[E]=b}return this.measurementsCache=j,j},{key:!1,debug:()=>this.options.debug}),this.calculateRange=cn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(s,r,o,d)=>this.range=s.length>0&&r>0?Dl({measurements:s,outerSize:r,scrollOffset:o,lanes:d}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=cn(()=>{let s=null,r=null;const o=this.calculateRange();return o&&(s=o.startIndex,r=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,s,r]),[this.options.rangeExtractor,this.options.overscan,this.options.count,s,r]},(s,r,o,d,u)=>d===null||u===null?[]:s({startIndex:d,endIndex:u,overscan:r,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=s=>{const r=this.options.indexAttribute,o=s.getAttribute(r);return o?parseInt(o,10):(console.warn(`Missing attribute name '${r}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=s=>{var r;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const o=this.scrollState.index??((r=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:r.index);if(o!==void 0&&this.range){const d=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),u=Math.max(0,o-d),m=Math.min(this.options.count-1,o+d);return s>=u&&s<=m}return!0},this.measureElement=s=>{if(!s){this.elementsCache.forEach((u,m)=>{u.isConnected||(this.observer.unobserve(u),this.elementsCache.delete(m))});return}const r=this.indexFromElement(s),o=this.options.getItemKey(r),d=this.elementsCache.get(o);d!==s&&(d&&this.observer.unobserve(d),this.observer.observe(s),this.elementsCache.set(o,s)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(r)&&this.resizeItem(r,this.options.measureElement(s,void 0,this))},this.resizeItem=(s,r)=>{var o;const d=this.measurementsCache[s];if(!d)return;const u=this.itemSizeCache.get(d.key)??d.size,m=r-u;m!==0&&(((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(d,m,this):d.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=m,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(d.index),this.itemSizeCache=new Map(this.itemSizeCache.set(d.key,r)),this.notify(!1))},this.getVirtualItems=cn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(s,r)=>{const o=[];for(let d=0,u=s.length;d<u;d++){const m=s[d],f=r[m];o.push(f)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=s=>{const r=this.getMeasurements();if(r.length!==0)return ci(r[Gi(0,r.length-1,o=>ci(r[o]).start,s)])},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 s=this.scrollElement.document.documentElement;return this.options.horizontal?s.scrollWidth-this.scrollElement.innerWidth:s.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(s,r,o=0)=>{if(!this.scrollElement)return 0;const d=this.getSize(),u=this.getScrollOffset();r==="auto"&&(r=s>=u+d?"end":"start"),r==="center"?s+=(o-d)/2:r==="end"&&(s-=d);const m=this.getMaxScrollOffset();return Math.max(Math.min(m,s),0)},this.getOffsetForIndex=(s,r="auto")=>{s=Math.max(0,Math.min(s,this.options.count-1));const o=this.getSize(),d=this.getScrollOffset(),u=this.measurementsCache[s];if(!u)return;if(r==="auto")if(u.end>=d+o-this.options.scrollPaddingEnd)r="end";else if(u.start<=d+this.options.scrollPaddingStart)r="start";else return[d,r];if(r==="end"&&s===this.options.count-1)return[this.getMaxScrollOffset(),r];const m=r==="end"?u.end+this.options.scrollPaddingEnd:u.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(m,r,u.size),r]},this.scrollToOffset=(s,{align:r="start",behavior:o="auto"}={})=>{const d=this.getOffsetForAlignment(s,r),u=this.now();this.scrollState={index:null,align:r,behavior:o,startedAt:u,lastTargetOffset:d,stableFrames:0},this._scrollToOffset(d,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollToIndex=(s,{align:r="auto",behavior:o="auto"}={})=>{s=Math.max(0,Math.min(s,this.options.count-1));const d=this.getOffsetForIndex(s,r);if(!d)return;const[u,m]=d,f=this.now();this.scrollState={index:s,align:m,behavior:o,startedAt:f,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollBy=(s,{behavior:r="auto"}={})=>{const o=this.getScrollOffset()+s,d=this.now();this.scrollState={index:null,align:"start",behavior:r,startedAt:d,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:r}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var s;const r=this.getMeasurements();let o;if(r.length===0)o=this.options.paddingStart;else if(this.options.lanes===1)o=((s=r[r.length-1])==null?void 0:s.end)??0;else{const d=Array(this.options.lanes).fill(null);let u=r.length-1;for(;u>=0&&d.some(m=>m===null);){const m=r[u];d[m.lane]===null&&(d[m.lane]=m.end),u--}o=Math.max(...d.filter(m=>m!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(s,{adjustments:r,behavior:o})=>{this.options.scrollToFn(s,{behavior:o,adjustments:r},this)},this.measure=()=>{this.itemSizeCache=new Map,this.laneAssignments=new Map,this.notify(!1)},this.setOptions(a)}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,o=r?r[0]:this.scrollState.lastTargetOffset,d=1,u=o!==this.scrollState.lastTargetOffset;if(!u&&Tl(o,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=d){this.scrollState=null;return}}else this.scrollState.stableFrames=0,u&&(this.scrollState.lastTargetOffset=o,this.scrollState.behavior="auto",this._scrollToOffset(o,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Gi=(i,a,s,r)=>{for(;i<=a;){const o=(i+a)/2|0,d=s(o);if(d<r)i=o+1;else if(d>r)a=o-1;else return o}return i>0?i-1:0};function Dl({measurements:i,outerSize:a,scrollOffset:s,lanes:r}){const o=i.length-1,d=f=>i[f].start;if(i.length<=r)return{startIndex:0,endIndex:o};let u=Gi(0,o,d,s),m=u;if(r===1)for(;m<o&&i[m].end<s+a;)m++;else if(r>1){const f=Array(r).fill(0);for(;m<o&&f.some(N=>N<s+a);){const N=i[m];f[N.lane]=N.end,m++}const y=Array(r).fill(s+a);for(;u>=0&&y.some(N=>N>=s);){const N=i[u];y[N.lane]=N.start,u--}u=Math.max(0,u-u%r),m=Math.min(o,m+(r-1-m%r))}return{startIndex:u,endIndex:m}}const xi=typeof document<"u"?n.useLayoutEffect:n.useEffect;function $l({useFlushSync:i=!0,...a}){const s=n.useReducer(()=>({}),{})[1],r={...a,onChange:(d,u)=>{var m;i&&u?Fi.flushSync(s):s(),(m=a.onChange)==null||m.call(a,d,u)}},[o]=n.useState(()=>new Rl(r));return o.setOptions(r),xi(()=>o._didMount(),[]),xi(()=>o._willUpdate()),o}function Ol(i){return $l({observeElementRect:Il,observeElementOffset:Pl,scrollToFn:_l,...i})}const fi={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 Fl({notification:i,agentName:a,acknowledging:s,onClose:r,onAcknowledge:o}){const{t:d}=Ge(["team","common"]);Xo(!0);const u=i.priority||"normal",m=i.metadata??{},f=a||(typeof m.agentName=="string"?m.agentName:void 0);return Fi.createPortal(e.jsx("div",{className:"fixed inset-0 z-[10000] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm",onMouseDown:y=>{y.target===y.currentTarget&&r()},children:e.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:[e.jsxs("div",{className:"flex items-start gap-3 px-6 py-4 border-b border-border-default shrink-0",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-blue-500/15 text-blue-500 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),e.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h2",{className:"text-base font-semibold text-fg-primary leading-snug",children:i.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[f&&e.jsx("p",{className:"text-xs text-fg-tertiary",children:f}),u!=="normal"&&e.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${fi[u]??fi.normal}`,children:u})]})]}),e.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:d("common:close"),children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M18 6L6 18"}),e.jsx("path",{d:"M6 6l12 12"})]})})]}),e.jsx("div",{className:"flex-1 overflow-y-auto px-6 py-5",children:e.jsx("div",{className:"text-sm text-fg-primary leading-relaxed",children:e.jsx($n,{content:i.body||""})})}),e.jsxs("div",{className:"flex items-center justify-end gap-2 px-6 py-4 border-t border-border-default shrink-0",children:[e.jsx("button",{onClick:r,className:"px-3.5 py-2 text-sm text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:d("common:close")}),e.jsx("button",{onClick:()=>{o()},disabled:s,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:s?d("common:loading"):d("page.notifyUserGotIt",{ns:"team",defaultValue:"Got it"})})]})]})}),document.body)}function On({children:i,onClose:a,title:s,width:r="w-[440px]"}){return e.jsx("div",{className:"fixed inset-0 bg-black/60 flex items-center justify-center z-50",onClick:a,children:e.jsxs("div",{className:`bg-surface-secondary border border-border-default rounded-xl p-6 ${r} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:o=>o.stopPropagation(),children:[e.jsx("h3",{className:"text-base font-semibold mb-5",children:s}),i]})})}function un({label:i,children:a}){return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:i}),a]})}function Bl({onClose:i,onCreate:a}){const{t:s}=Ge(["team","common"]),[r,o]=n.useState(""),[d,u]=n.useState("");return e.jsx(On,{onClose:i,title:s("team:modals.createTeam.title"),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(un,{label:s("team:modals.createTeam.teamName"),children:e.jsx("input",{value:r,onChange:m=>o(m.target.value),placeholder:s("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:m=>{m.key==="Enter"&&r.trim()&&a(r.trim(),d.trim()||void 0)}})}),e.jsx(un,{label:s("team:modals.createTeam.description"),children:e.jsx("textarea",{value:d,onChange:m=>u(m.target.value),placeholder:s("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),e.jsx("div",{className:"text-xs text-fg-tertiary",children:s("team:modals.createTeam.hint")}),e.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:e.jsx(Qo,{i18nKey:"modals.createTeam.tipTrans",ns:"team",components:{0:e.jsx("span",{className:"text-brand-400 font-medium"}),1:e.jsx("span",{className:"text-brand-400"})}})}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:()=>r.trim()&&a(r.trim(),d.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:s("team:modals.createTeam.createTeam")})]})]})})}function zl({onClose:i,onAdd:a}){const{t:s}=Ge(["team","common"]),[r,o]=n.useState(""),[d,u]=n.useState("member"),[m,f]=n.useState(""),[y,N]=n.useState(""),[j,I]=n.useState(!1),[b,v]=n.useState(null),[O,E]=n.useState(!1),T=b?.inviteToken?`${window.location.origin}/#invite?token=${b.inviteToken}`:null,p=async()=>{if(N(""),!r.trim()){N(s("team:modals.addHuman.nameRequired"));return}if(!m.trim()){N(s("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m.trim())){N(s("team:modals.addHuman.invalidEmail"));return}I(!0);try{const A=await a(r.trim(),d,m.trim());v({...A,userName:r.trim()})}catch(A){N(A instanceof Error?A.message:String(A))}finally{I(!1)}},C=()=>{T&&(navigator.clipboard.writeText(T),E(!0),setTimeout(()=>E(!1),2e3))};return b?e.jsxs(On,{onClose:i,title:s("team:modals.addHuman.title"),width:"w-[460px]",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-green-600/20 flex items-center justify-center mx-auto mb-3",children:e.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:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsx("div",{className:"text-base font-medium mb-1",children:s("team:modals.addHuman.memberCreated",{name:b.userName})}),T?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:s("team:modals.addHuman.inviteHint")}),e.jsxs("div",{className:"bg-surface-primary border border-border-default rounded-lg p-3 text-left mb-3",children:[e.jsx("div",{className:"text-[10px] text-fg-tertiary uppercase mb-1.5",children:s("team:modals.addHuman.inviteLink")}),e.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:T})]}),e.jsx("button",{onClick:C,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${O?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:s(O?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):e.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:s("team:modals.addHuman.memberCreatedNoInvite")})]}),e.jsx("div",{className:"flex justify-end pt-3",children:e.jsx("button",{onClick:i,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:s("common:done")})})]}):e.jsx(On,{onClose:i,title:s("team:modals.addHuman.title"),width:"w-[460px]",children:e.jsxs("div",{className:"space-y-4",children:[e.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:[e.jsx("div",{className:"font-semibold text-fg-primary mb-1",children:s("team:modals.addHuman.sharedInstanceTitle")}),s("team:modals.addHuman.sharedInstanceDesc"),e.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[s("team:modals.addHuman.orgHint")," ",e.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:s("team:modals.addHuman.orgLink")})]})]}),e.jsx(un,{label:s("team:modals.addHuman.name"),children:e.jsx("input",{value:r,onChange:A=>o(A.target.value),placeholder:s("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),e.jsx(un,{label:s("team:modals.addHuman.role"),children:e.jsxs("select",{value:d,onChange:A=>u(A.target.value),className:"input",children:[e.jsx("option",{value:"owner",children:s("common:role.owner")}),e.jsx("option",{value:"admin",children:s("common:role.admin")}),e.jsx("option",{value:"member",children:s("common:role.member")}),e.jsx("option",{value:"guest",children:s("common:role.guest")})]})}),e.jsx(un,{label:s("team:modals.addHuman.emailRequired"),children:e.jsx("input",{value:m,onChange:A=>f(A.target.value),type:"email",placeholder:s("team:modals.addHuman.emailPlaceholder"),className:"input"})}),e.jsx("div",{className:"text-xs text-fg-tertiary bg-brand-500/5 border border-brand-500/20 rounded-lg px-3 py-2",children:s("team:modals.addHuman.inviteFlowHint")}),y&&e.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:y}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:p,disabled:j,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:s(j?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function Wl({teamId:i,ungrouped:a,onClose:s,onAdd:r}){const{t:o}=Ge(["team","common"]);return e.jsx(On,{onClose:s,title:o("team:modals.addExisting.title"),children:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:o("team:modals.addExisting.hint")}),a.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-fg-tertiary",children:o("team:modals.addExisting.allInTeam")}):e.jsx("div",{className:"space-y-2 max-h-72 overflow-y-auto",children:a.map(d=>e.jsxs("button",{onClick:()=>r(d.id,d.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:[e.jsx("div",{className:`w-8 h-8 rounded-lg flex items-center justify-center text-xs font-bold text-white ${d.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:d.name.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:d.name}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[d.role," · ",d.type==="agent"?o("team:modals.addExisting.typeAgent"):o("team:modals.addExisting.typeHuman")]})]}),d.status&&e.jsx("span",{className:`w-2 h-2 rounded-full ${d.status==="idle"?"bg-green-400":d.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},d.id))}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsx("button",{onClick:s,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:o("common:close")})})]})})}function Hl({onClose:i,onConnected:a}){const{t:s}=Ge(["team","common"]),[r,o]=n.useState(""),[d,u]=n.useState(""),[m,f]=n.useState(!1),[y,N]=n.useState(null),[j,I]=n.useState(null),b=async()=>{if(!r.trim()){u(s("team:modals.openClaw.agentNameRequired"));return}const O=r.trim().toLowerCase().replace(/\s+/g,"-");f(!0),u("");try{const E=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:O,agentName:r.trim(),orgId:"default",capabilities:["general"]})});if(!E.ok){const p=await E.json().catch(()=>({}));throw new Error(p.error??`HTTP ${E.status}`)}const T=await E.json();N({externalAgentId:O,markusAgentId:T.registration?.markusAgentId,token:T.token,gatewayUrl:T.gatewayUrl})}catch(E){u(String(E))}f(!1)},v=(O,E)=>{navigator.clipboard.writeText(O),I(E),setTimeout(()=>I(null),2e3)};return e.jsx(On,{onClose:i,title:s("team:modals.openClaw.title"),width:"w-[560px]",children:y?(()=>{const O=y.gatewayUrl??`${window.location.origin}/api/gateway`,E=y.token?s("team:modals.openClaw.bearerTokenLine",{token:y.token}):"",T=s("team:modals.openClaw.connectionPromptBody",{gwUrl:O,externalAgentId:y.externalAgentId,tokenSection:E});return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"text-3xl mb-3 text-green-600",children:"✓"}),e.jsx("div",{className:"text-base text-green-600 font-medium mb-1",children:s("team:modals.openClaw.agentRegistered")}),e.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:e.jsx("strong",{children:r})})]}),e.jsxs("div",{className:"bg-brand-500/10 border border-brand-500/30 rounded-xl p-4",children:[e.jsx("div",{className:"text-xs text-fg-secondary mb-3",children:s("team:modals.openClaw.copyInstruction")}),e.jsx("button",{onClick:()=>v(T,"prompt"),className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${j==="prompt"?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:s(j==="prompt"?"common:copied":"team:modals.openClaw.copyPrompt")})]}),e.jsx("div",{className:"flex justify-end pt-5",children:e.jsx("button",{onClick:()=>{a()},className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:s("team:modals.openClaw.done")})})]})})():e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:s("team:modals.openClaw.description")}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(un,{label:s("team:modals.openClaw.agentName"),children:e.jsx("input",{className:"input",placeholder:s("team:modals.openClaw.agentNamePlaceholder"),value:r,onChange:O=>o(O.target.value),autoFocus:!0})}),d&&e.jsx("div",{className:"text-xs text-red-500 bg-red-500/10 border border-red-500/30 rounded-lg px-3 py-2",children:d}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:i,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:s("common:cancel")}),e.jsx("button",{onClick:b,disabled:m,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:s(m?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}let mr=new Map;function Vl({agents:i,humans:a,authUser:s,onClose:r,onCreate:o}){const{t:d}=Ge(["team","common"]),[u,m]=n.useState(""),[f,y]=n.useState(new Set),[N,j]=n.useState(""),[I,b]=n.useState(!1),v=n.useMemo(()=>{const p=[];for(const C of i)p.push({id:C.id,name:C.name,type:"agent",subtitle:C.role||"Agent"});for(const C of a)C.id!==s?.id&&p.push({id:C.id,name:C.name,type:"human",subtitle:C.email||C.role||"Human"});return p},[i,a,s]),O=n.useMemo(()=>{if(!N)return v;const p=N.toLowerCase();return v.filter(C=>C.name.toLowerCase().includes(p)||C.subtitle.toLowerCase().includes(p))},[v,N]),E=p=>{y(C=>{const A=new Set(C);return A.has(p)?A.delete(p):A.add(p),A})},T=async()=>{if(!u.trim()||f.size===0)return;b(!0);const p=[...f],C={},A={};for(const H of p){const D=v.find(k=>k.id===H);D&&(C[H]=D.type,A[H]=D.name)}await o(u.trim(),p,C,A),b(!1)};return e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:r,children:e.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:p=>p.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[e.jsx("h3",{className:"text-sm font-semibold",children:d("modals.createGroupChat.title")}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:d("modals.createGroupChat.subtitle")})]}),e.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:e.jsx("input",{value:u,onChange:p=>m(p.target.value),placeholder:d("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})}),e.jsx("div",{className:"px-5 py-2 border-b border-border-default",children:e.jsx("input",{value:N,onChange:p=>j(p.target.value),placeholder:d("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"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 min-h-0 max-h-[300px]",children:[O.length===0&&e.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:d("modals.createGroupChat.noMembersFound")}),O.map(p=>e.jsxs("button",{onClick:()=>E(p.id),className:`w-full flex items-center gap-2.5 px-2 py-1.5 rounded-lg text-xs mb-0.5 transition-colors ${f.has(p.id)?"bg-brand-500/10 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx("div",{className:`w-4 h-4 rounded border flex items-center justify-center shrink-0 transition-colors ${f.has(p.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:f.has(p.id)&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"white",strokeWidth:"3",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"20 6 9 17 4 12"})})}),e.jsx(vt,{name:p.name,size:20,bgClass:p.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate text-[11px] font-medium block",children:p.name}),e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:p.subtitle})]}),e.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${p.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:p.type==="agent"?d("modals.addExisting.typeAgent"):d("modals.addExisting.typeHuman")})]},p.id))]}),e.jsxs("div",{className:"px-5 py-3 border-t border-border-default flex items-center justify-between",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:d("modals.createGroupChat.selected",{count:f.size})}),e.jsxs("div",{className:"flex gap-2",children:[e.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:d("common:cancel")}),e.jsx("button",{onClick:T,disabled:!u.trim()||f.size===0||I,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:d(I?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const ql=n.memo(function({authUser:a,agents:s,teams:r,humans:o,tasks:d,externalAgents:u,groupChats:m,chatMode:f,selectedAgent:y,activeChannel:N,activeDmUserId:j,onSelectAgent:I,onSelectChannel:b,onSelectDm:v,onSelectTeam:O,selectedTeamId:E,onRefreshTeams:T,onRefreshAgents:p,onRefreshHumans:C,onRefreshGroupChats:A,onViewProfile:H,onManageGroupMembers:D,unreadByAgent:k,unreadByChannel:P,width:he,onResizeStart:De,hidden:se,onCollapse:F,initialLoading:Me,previewMode:ue}){const{t:L}=Ge(["team","common"]),J=ma(),U=Bi(xt.TEAM),ee=a?.role==="owner"||a?.role==="admin",g=n.useMemo(()=>new Set(u.map(h=>h.markusAgentId).filter(Boolean)),[u]),[q,oe]=n.useState([]),[be,ge]=n.useState(new Set),[ye,Xe]=n.useState(!1),[et,Yt]=n.useState(!1),[bs,Ht]=n.useState(null),[as,ys]=n.useState(!1),[Ys,Xt]=n.useState(!1),[jt,ft]=n.useState(null),[ae,We]=n.useState(null),[qe,Fe]=n.useState(null),[wt,mn]=n.useState(!1),[zn,xn]=n.useState(""),[Qt,fn]=n.useState(null),[gn,ga]=n.useState(null),[Ms,vs]=n.useState(null),[js,Zt]=n.useState(!1),Wn=n.useRef(null),[vr,Es]=n.useState(null),is=n.useRef(null),Hn=n.useRef(null),[hn,pn]=n.useState(null),As=(h,V="success")=>{pn({message:h,type:V}),setTimeout(()=>pn(null),3e3)},[Rt,Vt]=n.useState(null),[Vn,bn]=n.useState(!1),Xs=n.useRef(!1);n.useEffect(()=>{if(ue)return;M.governance.getSystemStatus().then(G=>{Xs.current=!0,Vt(G.globalPaused)}).catch(()=>{Xs.current=!0,Vt(!1)});const h=ze.on("system:pause-all",()=>{Xs.current&&Vt(!0)}),V=ze.on("system:resume-all",()=>{Xs.current&&Vt(!1)});return()=>{h(),V()}},[]),n.useEffect(()=>{if(!ue)return;const h=setTimeout(()=>{const V=Hn.current,G=is.current;V&&G&&G.scrollTo({top:V.offsetTop-G.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(h)},[ue]);const yn=n.useCallback(()=>{Rt!==null&&Is({title:L(Rt?"modals.resumeAll.title":"modals.pauseAll.title"),message:L(Rt?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:L(Rt?"chat.resume":"chat.pause"),onConfirm:async()=>{bn(!0);try{Rt?(await M.governance.resumeAll(),Vt(!1)):(await M.governance.pauseAll(),Vt(!0))}catch{}bn(!1)}})},[Rt]),[Jt,Is]=n.useState(null),Qs=(h,V,G,xe,Se)=>{Is({title:h,message:V,onConfirm:G,confirmLabel:xe,checkboxes:Se})},[Dt,ws]=n.useState(null),[Ps,vn]=n.useState(null),$t=n.useRef(null),kt=n.useRef(null),[qt,jn]=n.useState(!1),[R,$e]=n.useState(null),[K,lt]=n.useState(""),Ie=n.useCallback((h,V=176,G=220)=>{const xe=window.innerWidth,Se=window.innerHeight,Oe=8;let Ye=h.clientX,Be=h.clientY;return Ye+V>xe-Oe&&(Ye=Math.max(Oe,xe-V-Oe)),Be+G>Se-Oe&&(Be=Math.max(Oe,Se-G-Oe)),Ye=Math.max(Oe,Math.min(Ye,xe-V-Oe)),Be=Math.max(Oe,Math.min(Be,Se-G-Oe)),{x:Ye,y:Be}},[]),[Ct,nt]=n.useState(mr),Ls=n.useMemo(()=>s.map(h=>h.id).sort().join(","),[s]);n.useEffect(()=>{if(!s.length||!U)return;let h=!1;(async()=>{const Be=[];await Promise.allSettled(s.map(async Re=>{if(!mr.has(Re.id))try{const{sessions:rt}=await M.sessions.listByAgent(Re.id,1);if(!rt.length)return;const{messages:ht}=await M.sessions.getMessages(rt[0].id,1);if(ht.length){const dt=ht[0],Gt=dt.metadata?.segments;let ot=dt.content;if(Gt&&Gt.length>0){const Pt=[...Gt].reverse().find(ks=>ks.type==="text");Pt&&Pt.type==="text"&&(ot=Pt.content)}const tt=ot.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);tt&&Be.push([Re.id,tt])}}catch{}})),!h&&Be.length&&nt(Re=>{const rt=new Map(Re);for(const[ht,dt]of Be)rt.set(ht,dt);return mr=rt,rt})})();const G=new Set(s.map(Be=>Be.id)),xe=Be=>Be.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),Se=(Be,Re)=>{if(!Be||!Re||!G.has(Be))return;const rt=xe(Re);rt&&nt(ht=>{const dt=new Map(ht);return dt.set(Be,rt),mr=dt,dt})},Oe=ze.on("chat:proactive_message",Be=>{const Re=Be.payload;Se(Re.agentId??"",Re.message??"")}),Ye=ze.on("chat:message",Be=>{const Re=Be.payload,rt=Re.senderId??Re.agentId??"",ht=Re.text??Re.message??"";Se(rt,ht)});return()=>{h=!0,Oe(),Ye()}},[Ls,U]);const Tt=n.useCallback(()=>{ue||M.teams.list().then(h=>oe(h.ungrouped)).catch(()=>{})},[ue]);n.useEffect(()=>{Tt()},[Tt]),n.useEffect(()=>{if(!U)return;const h=ze.on("team:update",Tt),V=ze.on("agent:removed",Tt);return()=>{h(),V()}},[Tt,U]),n.useEffect(()=>{if(!ae&&!qe&&!Qt&&!js&&!Ms)return;const h=()=>{We(null),Fe(null),fn(null),vs(null),Zt(!1)},V=setTimeout(()=>document.addEventListener("click",h),0);return()=>{clearTimeout(V),document.removeEventListener("click",h)}},[ae,qe,Qt,js,Ms]);const _s=(h,V)=>{Qs(`${L("common:delete")} "${V}"?`,L("modals.deleteTeam.message"),async G=>{const xe=G?.deleteMembers??!0,Se=G?.purgeFiles??!1;await M.teams.delete(h,xe,{purgeFiles:Se}),T(),Tt(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},L("contextMenu.deleteTeam"),[{id:"deleteMembers",label:L("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:L("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Zs=async(h,V)=>{try{const xe=await(V==="start"?M.teams.startAll:M.teams.stopAll)(h),Se=xe.success?.length??0,Oe=xe.failed?.length??0;Oe>0?As(L("batchAction.failed",{action:L(`batchAction.operation.${V}`),ok:Se,fail:Oe}),"error"):Se>0&&As(L("batchAction.succeeded",{count:Se,action:L(`batchAction.past.${V}`)}),"success"),p()}catch(G){As(L("batchAction.failedToRun",{action:L(`batchAction.operation.${V}`),error:G instanceof Error?G.message:String(G)}),"error")}},jr=async(h,V,G)=>{await M.teams.update(h,{managerId:V,managerType:G}),T()},qn=async h=>{if(!K.trim()){$e(null);return}await M.teams.update(h,{name:K.trim()}),$e(null),T()},Ke=async(h,V)=>{V==="offline"?await M.agents.start(h):await M.agents.stop(h),p()},Nt=(h,V)=>{Qs(L("modals.removeFromTeam.title"),L("modals.removeFromTeam.message"),async()=>{await M.teams.removeMember(h,V),T(),Tt()},L("common:remove"))},It=(h,V,G)=>{Qs(`${L("common:remove")} "${V}"?`,L(G==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async xe=>{if(G==="agent"){const Se=xe?.purgeFiles??!1;await M.agents.remove(h,{purgeFiles:Se})}else await M.users.remove(h);p(),T(),C?.(),Tt(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},L("common:remove"),G==="agent"?[{id:"purgeFiles",label:L("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},ct=h=>{if(h.isOrgSecretary||h.protected)return!0;if(h.teamId)return!1;const V=(h.role??"").toLowerCase().trim(),G=(h.name??"").trim();return G==="Secretary"||G==="秘书"||V==="secretary"||V.startsWith("secretary")},wr=(h,V,G)=>{const xe=s.find(Se=>Se.id===V);xe&&ct(xe)||(kt.current={x:h.clientX,y:h.clientY},$t.current=setTimeout(()=>{ws({agentId:V,fromTeamId:G}),jn(!0)},200))},Ut=h=>{if(!kt.current||!$t.current)return;const V=Math.abs(h.clientX-kt.current.x),G=Math.abs(h.clientY-kt.current.y);(V>5||G>5)&&(qt||(clearTimeout($t.current),$t.current=null))},gt=async()=>{if($t.current&&(clearTimeout($t.current),$t.current=null),kt.current=null,qt&&Dt&&Ps){const h=Ps==="_ungrouped"?void 0:Ps;try{if(Dt.fromTeamId&&Dt.fromTeamId!==h&&await M.teams.removeMember(Dt.fromTeamId,Dt.agentId),h&&h!==Dt.fromTeamId){const V=s.find(G=>G.id===Dt.agentId);await M.teams.addMember(h,Dt.agentId,"agent")}T(),p(),Tt()}catch(V){As(L("batchAction.moveFailed",{error:V instanceof Error?V.message:String(V)}),"error")}}ws(null),vn(null),jn(!1)},Rs=n.useMemo(()=>new Map(r.map(h=>[h.id,h])),[r]),Mt=n.useMemo(()=>{const h=new Map,V=[];for(const G of s)if(G.teamId&&Rs.has(G.teamId)){const xe=h.get(G.teamId)??[];xe.push(G),h.set(G.teamId,xe)}else V.push(G);return{byTeam:h,ungrouped:V}},[s,Rs]),Ot=(h,V)=>{const G=f==="direct"&&y===h.id,xe=g.has(h.id),Se=h.status==="offline",Oe=h.status==="idle"?"bg-green-500":h.status==="working"?"bg-blue-500 animate-pulse":h.status==="error"?"bg-red-500":"bg-gray-600",Be=(void 0)?.managerId===h.id,Re=h.role?.toLowerCase().replace(/[-_]/g," ").trim(),rt=h.name.toLowerCase().trim(),ht=Re&&Re!==rt,dt=Ct.get(h.id)||h.currentActivity?.label?.slice(0,60)||"",Gt=h.status==="idle"?L("common:status.online"):h.status==="working"?L("common:status.working"):h.status==="error"?L("common:status.error"):L("common:status.offline");return e.jsx("div",{className:`relative mb-0.5 ${qt&&Dt?.agentId===h.id?"opacity-40":""}`,onPointerDown:ot=>wr(ot,h.id,V),onPointerMove:Ut,onPointerUp:gt,children:e.jsxs("button",{onClick:()=>{qt||I(h.id)},onContextMenu:ot=>{if(!ee)return;ot.preventDefault();const tt=Ie(ot);mn(!1),xn(""),Fe({agentId:h.id,teamId:V,...tt})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors select-none ${J?"":"touch-none"} ${Se?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${G?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(vt,{name:h.name,avatarUrl:h.avatarUrl,size:28,bgClass:Se?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:h.name}),ht&&e.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",h.role,")"]}),Be&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:e.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"})}),xe&&e.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"}),Se&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:L("common:status.offline")})]}),e.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:dt||" "})]}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(k?.get(h.id)??0)>0&&e.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:k.get(h.id)}),h.mailboxDepth!=null&&h.mailboxDepth>0&&e.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:h.mailboxDepth}),e.jsx("span",{title:Gt,onClick:ot=>{ot.stopPropagation(),H(h.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${Oe}`}),J&&ee&&e.jsx("span",{role:"button",tabIndex:0,onClick:ot=>{if(ot.stopPropagation(),qe?.agentId===h.id)Fe(null);else{const tt=Ie(ot);mn(!1),xn(""),Fe({agentId:h.id,teamId:V,...tt})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:L("chat.moreOptions"),children:e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]})]})},h.id)},Un=(h,V,G,xe)=>{const Se=qt&&Ps===h&&Dt?.fromTeamId!==h,Oe=vr===h,Ye=E===h,Be=k?(Mt.byTeam.get(h)??[]).reduce((Qe,es)=>Qe+(k.get(es.id)??0),0):0,Re=m.find(Qe=>Qe.type==="team"&&Qe.teamId===h),rt=Re&&P?P[Re.channelKey]??0:0,ht=Be+rt,dt=Mt.byTeam.get(h)??[],Gt=dt.filter(Qe=>Qe.status==="offline").length,ot=dt.length,tt=ot>0&&Gt===ot,Pt=Gt>0&&!tt,ks=tt?"bg-gray-500":Pt?"bg-amber-500":"bg-green-500";return e.jsxs("div",{"data-team-id":h,className:`mb-0.5 rounded-lg transition-all duration-500 ${Se?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${Oe?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{qt&&vn(h)},onPointerLeave:()=>{qt&&Ps===h&&vn(null)},children:[e.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[e.jsxs("button",{onClick:()=>{O&&h!=="_ungrouped"&&O(h)},onContextMenu:Qe=>{if(!ee||!V)return;Qe.preventDefault();const es=Ie(Qe);We({teamId:h,...es})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${tt?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ye?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsxs("div",{className:`w-7 h-7 rounded-full flex items-center justify-center shrink-0 relative ${tt?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}`,children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),ot>0&&e.jsx("span",{className:`absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full border-2 border-surface-primary ${ks}`})]}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[R===h?e.jsx("input",{className:"bg-transparent border-b border-brand-500 text-fg-primary text-[12px] font-medium outline-none w-full",value:K,onChange:Qe=>lt(Qe.target.value),onBlur:()=>qn(h),onKeyDown:Qe=>{Qe.key==="Enter"&&qn(h),Qe.key==="Escape"&&$e(null)},onClick:Qe=>Qe.stopPropagation(),autoFocus:!0}):e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:xe}),e.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[L("chat.members_other",{count:G}),tt&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:L("common:status.offline")}),Pt&&e.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[Gt,"/",ot]})]})]}),ht>0&&e.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:ht}),e.jsx("svg",{className:"w-3.5 h-3.5 text-fg-muted shrink-0",fill:"currentColor",viewBox:"0 0 20 20",children:e.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"})})]}),ee&&V&&e.jsx("button",{onClick:Qe=>{if(Qe.stopPropagation(),ae?.teamId===h)We(null);else{const es=Ie(Qe);We({teamId:h,...es})}},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:L("chat.moreOptions"),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("circle",{cx:"12",cy:"12",r:"1"}),e.jsx("circle",{cx:"12",cy:"5",r:"1"}),e.jsx("circle",{cx:"12",cy:"19",r:"1"})]})})]}),Se&&qt&&e.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:L("chat.dropHere")})]},h)},ke=n.useMemo(()=>{const h=new Map,V=[],G=[],xe=[];for(const Se of m)if(Se.channelKey.startsWith("dm:a2a:"))xe.push(Se);else if(Se.type==="custom")G.push(Se);else if(Se.teamId){const Oe=h.get(Se.teamId)??[];Oe.push(Se),h.set(Se.teamId,Oe)}else{const Oe=r.find(Ye=>Se.name.toLowerCase().includes(Ye.name.toLowerCase())||Ye.name.toLowerCase().includes(Se.name.toLowerCase()));if(Oe){const Ye=h.get(Oe.id)??[];Ye.push(Se),h.set(Oe.id,Ye)}else V.push(Se)}return{byTeam:h,unmatched:V,custom:G,dmChannels:xe}},[m,r]),[Pe,os]=n.useState(!1),Ds=f==="channel"&&ke.dmChannels.some(h=>h.channelKey===N);return n.useEffect(()=>{Ds&&os(!0)},[Ds]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`bg-surface-primary flex flex-col ${he!=null?"shrink-0":"flex-1 min-w-0"}`,style:se?{display:"none"}:he!=null?{width:he}:void 0,children:[e.jsxs("div",{"data-electron-drag":!0,className:"px-4 h-14 flex items-center shrink-0 gap-2",children:[J&&e.jsx(Zo,{}),!J&&F&&e.jsx("button",{onClick:F,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:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),e.jsx("h2",{className:"text-lg font-semibold",children:L("chat.title")}),ee&&e.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:Wn,children:[e.jsxs("button",{onClick:()=>Zt(!js),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:[e.jsx("span",{className:"text-brand-500",children:"+"})," ",L("chat.manage"),e.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${js?"rotate-180":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:e.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"})})]}),js&&e.jsxs("div",{ref:h=>{if(!h)return;const V=h.getBoundingClientRect(),G=window.innerWidth,xe=8;V.right>G-xe&&(h.style.left="auto",h.style.right="0"),V.left<xe&&(h.style.left="0",h.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:[e.jsxs("button",{onClick:()=>{Zt(!1),ft("agent")},className:"w-full text-left px-4 py-2.5 text-xs text-fg-secondary hover:bg-surface-elevated transition-colors",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"11",width:"18",height:"10",rx:"2"}),e.jsx("circle",{cx:"12",cy:"5",r:"2"}),e.jsx("path",{d:"M12 7v4"}),e.jsx("circle",{cx:"9",cy:"16",r:"1",fill:"currentColor",stroke:"none"}),e.jsx("circle",{cx:"15",cy:"16",r:"1",fill:"currentColor",stroke:"none"})]}),L("chat.addAgent")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:L("chat.addAgentDesc")})]}),e.jsxs("button",{onClick:()=>{Zt(!1),ft("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:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("line",{x1:"19",y1:"8",x2:"19",y2:"14"}),e.jsx("line",{x1:"22",y1:"11",x2:"16",y2:"11"})]}),L("chat.newTeam")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:L("chat.newTeamDesc")})]}),e.jsxs("button",{onClick:()=>{Zt(!1),Yt(!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:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M20 8v6"}),e.jsx("path",{d:"M23 11h-6"})]}),L("chat.addHuman")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:L("chat.addHumanDesc")})]}),e.jsxs("button",{onClick:()=>{Zt(!1),Xt(!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:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.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"}),e.jsx("path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1"})]}),L("chat.newGroupChat")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:L("chat.newGroupChatDesc")})]}),Rt!==null&&e.jsxs("button",{onClick:()=>{Zt(!1),yn()},disabled:Vn,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 ${Rt?"text-green-600":"text-red-500"}`,children:[e.jsx("div",{className:"font-medium flex items-center gap-1.5",children:Rt?e.jsxs(e.Fragment,{children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})})," ",L("chat.resume")]}):e.jsxs(e.Fragment,{children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})," ",L("contextMenu.stopAll")]})}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:L(Rt?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),e.jsxs("div",{ref:is,className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:L("chat.people")}),a&&e.jsxs("button",{onClick:()=>v(a.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 ${f==="dm"&&(j===a.id||!j)?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(vt,{name:a.name,avatarUrl:a.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-400"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:a.name}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:L("chat.myNotes")})]}),e.jsx("span",{className:"text-fg-secondary shrink-0",children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]})})]}),o.filter(h=>h.id!==a?.id).map(h=>{const V=a?.id?`dm:${[a.id,h.id].sort().join(":")}`:"",G=V&&P?P[V]??0:0;return e.jsxs("button",{onClick:()=>v(h.id),onContextMenu:xe=>{if(!ee||h.id===a?.id)return;xe.preventDefault();const Se=Ie(xe);fn({userId:h.id,...Se})},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 ${f==="dm"&&j===h.id?"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[e.jsx(vt,{name:h.name,avatarUrl:h.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:h.name}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:h.email||h.role})]}),G>0?e.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:G}):e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},h.id)})]}),ke.custom.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1 px-2.5",children:L("chat.groups")}),ke.custom.map(h=>{const V=f==="channel"&&N===h.channelKey;return e.jsxs("button",{onClick:()=>b(h.channelKey),onContextMenu:G=>{G.preventDefault();const xe=Ie(G);vs({gcId:h.id,...xe})},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 ${V?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.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"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:h.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:L("chat.members_other",{count:h.memberCount??0})})]})]},h.id)})]}),Me?e.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((h,V)=>e.jsxs("div",{className:"flex items-center gap-2.5 animate-pulse",children:[e.jsx("div",{className:"w-6 h-6 rounded-lg bg-surface-overlay shrink-0"}),e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx("div",{className:"h-2.5 bg-surface-overlay rounded w-24"}),e.jsx("div",{className:"h-2 bg-surface-overlay rounded w-36"})]}),e.jsx("div",{className:"w-2 h-2 rounded-full bg-surface-overlay shrink-0"})]},V))}):s.length===0&&r.length===0?e.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:L("chat.noAgentsYet")}):null,ke.unmatched.map(h=>{const V=P?.[h.channelKey]??0;return e.jsxs("button",{onClick:()=>b(h.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 ${f==="channel"&&N===h.channelKey?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-full flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.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"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:h.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:L("chat.groupChat")})]}),V>0?e.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:V}):h.memberCount!==void 0&&h.memberCount>0?e.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:h.memberCount}):null]},h.id)}),Mt.ungrouped.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:L("chat.agents")}),Mt.ungrouped.map(h=>Ot(h))]}),r.length>0&&e.jsxs("div",{className:"mb-2",ref:Hn,children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:L("chat.teams")}),r.map(h=>{const V=Mt.byTeam.get(h.id)??[],G=h.members?.length||V.length;return Un(h.id,h,G,h.name)})]}),r.length===0&&Mt.ungrouped.length===0&&s.length>0&&s.map(h=>Ot(h)),ke.dmChannels.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsxs("button",{onClick:()=>os(h=>!h),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:[e.jsx("svg",{className:`w-2.5 h-2.5 transition-transform ${Pe?"rotate-90":""}`,fill:"currentColor",viewBox:"0 0 20 20",children:e.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"})}),L("chat.agentDMs"),e.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:ke.dmChannels.length})]}),Pe&&ke.dmChannels.map(h=>{const V=f==="channel"&&N===h.channelKey,G=P?.[h.channelKey]??0,xe=h.name.replace(/^DM:\s*/,"");return e.jsxs("button",{onClick:()=>b(h.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 ${V?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.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:e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.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"})})}),e.jsx("span",{className:"flex-1 min-w-0 text-left truncate text-[11px] text-fg-secondary",children:xe}),G>0&&e.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:G})]},h.id)})]})]})]}),De&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:De,children:e.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"})}),ae&&(()=>{const h=Mt.byTeam.get(ae.teamId)??[],V=h.some(xe=>xe.status==="offline"),G=h.some(xe=>xe.status!=="offline");return e.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:ae.x,top:ae.y},onClick:xe=>xe.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{const xe=Rs.get(ae.teamId);xe&&($e(ae.teamId),lt(xe.name)),We(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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),e.jsx("path",{d:"M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"})]}),L("contextMenu.renameTeam")]}),V&&e.jsxs("button",{onClick:()=>{Zs(ae.teamId,"start"),We(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:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),L("contextMenu.startAll")]}),G&&e.jsxs("button",{onClick:()=>{Zs(ae.teamId,"stop"),We(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:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),L("contextMenu.stopAll")]}),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{We(null),ps.navigate(xt.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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),L("chat.addAgent")]}),q.length>0&&e.jsxs("button",{onClick:()=>{We(null),Ht(ae.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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"8.5",cy:"7",r:"4"}),e.jsx("polyline",{points:"17 11 19 13 23 9"})]}),L("contextMenu.addExisting")]}),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{const xe=Rs.get(ae.teamId);xe&&_s(ae.teamId,xe.name),We(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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.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"})]}),L("contextMenu.deleteTeam")]})]})})(),qe&&(()=>{const h=s.find(Oe=>Oe.id===qe.agentId);if(!h||!ee)return null;const G=(qe.teamId?Rs.get(qe.teamId):void 0)?.managerId===h.id,xe=h.id===a?.id,Se=ct(h);return e.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:qe.x,top:qe.y,maxHeight:Math.max(160,window.innerHeight-qe.y-8)},onClick:Oe=>Oe.stopPropagation(),children:[Se&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:L("contextMenu.orgSecretaryProtected")}),e.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),e.jsxs("button",{onClick:()=>{Fe(null),H(h.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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),L("contextMenu.viewProfile")]}),h.status==="offline"?e.jsxs("button",{onClick:()=>{Ke(h.id,"offline"),Fe(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:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),L("contextMenu.start")]}):e.jsxs("button",{onClick:()=>{Ke(h.id,h.status??"idle"),Fe(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:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),L("contextMenu.stop")]}),!Se&&qe.teamId&&!G&&e.jsxs("button",{onClick:()=>{jr(qe.teamId,h.id,"agent"),Fe(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:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.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"})}),L("contextMenu.setAsManager")]}),!Se&&qe.teamId&&e.jsxs("button",{onClick:()=>{Nt(qe.teamId,h.id),Fe(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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"9 14 4 9 9 4"}),e.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),L("contextMenu.removeFromTeam")]}),!Se&&(()=>{const Oe=r.filter(Re=>Re.id!==qe.teamId);if(Oe.length===0)return null;const Ye=zn.trim().toLowerCase(),Be=Ye?Oe.filter(Re=>Re.name.toLowerCase().includes(Ye)):Oe;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{type:"button",onClick:()=>mn(Re=>!Re),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M5 12h14"}),e.jsx("path",{d:"M12 5l7 7-7 7"})]}),e.jsx("span",{className:"flex-1",children:L("contextMenu.moveTo")}),e.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 ${wt?"rotate-180":""}`,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),wt&&e.jsxs("div",{className:"px-2 pb-1.5",onClick:Re=>Re.stopPropagation(),children:[e.jsx("input",{autoFocus:!0,value:zn,onChange:Re=>xn(Re.target.value),onKeyDown:Re=>Re.stopPropagation(),placeholder:L("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"}),e.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:Be.length===0?e.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:L("contextMenu.moveToEmpty")}):Be.map(Re=>e.jsx("button",{type:"button",onClick:async()=>{qe.teamId&&await M.teams.removeMember(qe.teamId,h.id),await M.teams.addMember(Re.id,h.id,"agent"),T(),p(),Tt(),Fe(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:Re.name,children:Re.name},Re.id))})]})]})})(),!Se&&!xe&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{It(h.id,h.name,"agent"),Fe(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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.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"})]}),L("contextMenu.removeFromOrg")]})]})]})})(),Qt&&(()=>{const h=o.find(V=>V.id===Qt.userId);return!h||!ee?null:e.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:Qt.x,top:Qt.y},onClick:V=>V.stopPropagation(),children:e.jsxs("button",{onClick:()=>{It(h.id,h.name,"human"),fn(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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.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"})]}),L("contextMenu.removeFromOrg")]})})})(),ye&&e.jsx(Bl,{onClose:()=>Xe(!1),onCreate:async(h,V)=>{try{const{team:G}=await M.teams.create(h,V);Xe(!1),T(),Es(G.id),setTimeout(()=>{document.querySelector(`[data-team-id="${G.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>Es(null),3e3)}catch(G){As(L("chat.failedToCreateTeam",{message:G instanceof Error?G.message:String(G)}),"error")}}}),et&&e.jsx(zl,{onClose:()=>{Yt(!1),C?.()},onAdd:async(h,V,G)=>{const{inviteToken:xe}=await M.users.create(h,V,void 0,G);return C?.(),{inviteToken:xe}}}),bs!==null&&e.jsx(Wl,{teamId:bs,ungrouped:q,onClose:()=>Ht(null),onAdd:async(h,V)=>{await M.teams.addMember(bs,h,V),Ht(null),T(),Tt()}}),as&&e.jsx(Hl,{onClose:()=>ys(!1),onConnected:()=>{ys(!1),p(),T()}}),Ms&&(()=>{const h=m.find(V=>V.id===Ms.gcId);return h?e.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:Ms.x,top:Ms.y},onClick:V=>V.stopPropagation(),children:[h.type==="custom"&&e.jsxs("button",{onClick:()=>{vs(null),D?D(h.channelKey):b(h.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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),L("contextMenu.manageMembers")]}),e.jsxs("button",{onClick:async()=>{vs(null),Qs(L("modals.deleteGroupChat.title"),L("modals.deleteGroupChat.message",{name:h.name}),async()=>{await M.groupChats.delete(h.id),A()},L("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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.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"})]}),L("modals.deleteGroupChat.menuLabel")]})]}):null})(),Ys&&e.jsx(Vl,{agents:s,humans:o,authUser:a,onClose:()=>Xt(!1),onCreate:async(h,V,G,xe)=>{await M.groupChats.create({name:h,memberIds:V,memberTypes:G,memberNames:xe,creatorId:a?.id,creatorName:a?.name}),Xt(!1),A()}}),jt&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>ft(null),children:e.jsxs("div",{className:"bg-surface-elevated rounded-xl border border-border-default shadow-2xl w-[340px] max-w-[90vw] overflow-hidden",onClick:h=>h.stopPropagation(),children:[e.jsxs("div",{className:"px-5 py-4 border-b border-border-default",children:[e.jsx("h3",{className:"text-sm font-semibold",children:L(jt==="agent"?"chat.addAgent":"chat.newTeam")}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:L("chat.methodChoiceSubtitle")})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>{const h=jt;ft(null);const V=s.find(G=>G.role==="secretary")??s.find(G=>G.name?.toLowerCase().includes("secretary"));V?(I(V.id),ps.navigate(xt.TEAM,{agentId:V.id,prefillMessage:L(h==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):h==="agent"?ps.navigate(xt.STORE):Xe(!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:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-brand-500/15 flex items-center justify-center shrink-0",children:e.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:[e.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"}),e.jsx("path",{d:"M20 3v4"}),e.jsx("path",{d:"M22 5h-4"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium text-brand-500",children:L("chat.methodSecretary")}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:L("chat.methodSecretaryDesc")})]}),e.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:L("chat.recommended")})]}),e.jsxs("button",{onClick:()=>{const h=jt;ft(null),h==="agent"?ps.navigate(xt.STORE):Xe(!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:[e.jsx("div",{className:"w-8 h-8 rounded-full bg-surface-overlay flex items-center justify-center shrink-0",children:e.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:[e.jsx("path",{d:"M2 12s3-7 10-7 10 7 10 7-3 7-10 7-10-7-10-7z"}),e.jsx("circle",{cx:"12",cy:"12",r:"3"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs font-medium text-fg-secondary",children:L("chat.methodManual")}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:L(jt==="agent"?"chat.methodManualAgentDesc":"chat.methodManualTeamDesc")})]})]})]}),e.jsx("div",{className:"px-5 py-3 border-t border-border-default flex justify-end",children:e.jsx("button",{onClick:()=>ft(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:L("common:cancel")})})]})}),Jt&&e.jsx(Bn,{title:Jt.title,message:Jt.message,confirmLabel:Jt.confirmLabel,checkboxes:Jt.checkboxes,onConfirm:h=>{Jt.onConfirm(h),Is(null)},onCancel:()=>Is(null)}),hn&&e.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 ${hn.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:hn.message})]})});function gi({team:i,agents:a,humans:s,authUser:r,groupChat:o,chatMode:d,selectedAgent:u,activeChannel:m,teams:f,onSelectAgent:y,onSelectChannel:N,onSelectDm:j,onBack:I,onViewProfile:b,onRefreshAgents:v,onRefreshTeams:O,unreadByAgent:E,width:T,onResizeStart:p}){const{t:C}=Ge(["team","common"]),A=r?.role==="owner"||r?.role==="admin",H=n.useMemo(()=>a.filter(g=>g.teamId===i.id),[a,i.id]),D=n.useMemo(()=>{const g=new Set((i.members??[]).filter(q=>q.type==="human").map(q=>q.id));return s.filter(q=>g.has(q.id))},[i.members,s]),k=o&&d==="channel"&&m===o.channelKey,[P,he]=n.useState(null),[De,se]=n.useState(!1),[F,Me]=n.useState(""),ue=n.useCallback((g,q=176,oe=220)=>{const be=window.innerWidth,ge=window.innerHeight,ye=8;let Xe=g.clientX,et=g.clientY;return Xe+q>be-ye&&(Xe=Math.max(ye,be-q-ye)),et+oe>ge-ye&&(et=Math.max(ye,ge-oe-ye)),Xe=Math.max(ye,Math.min(Xe,be-q-ye)),et=Math.max(ye,Math.min(et,ge-oe-ye)),{x:Xe,y:et}},[]);n.useEffect(()=>{if(!P)return;const g=()=>he(null),q=setTimeout(()=>document.addEventListener("click",g),0);return()=>{clearTimeout(q),document.removeEventListener("click",g)}},[P]);const L=n.useCallback(async(g,q)=>{q==="offline"?await M.agents.start(g):await M.agents.stop(g),v()},[v]),J=n.useCallback(async g=>{await M.teams.update(i.id,{managerId:g,managerType:"agent"}),O()},[i.id,O]),U=n.useCallback(async g=>{await M.teams.removeMember(i.id,g),O(),v()},[i.id,O,v]),ee=n.useCallback(async(g,q)=>{await M.teams.removeMember(i.id,g),await M.teams.addMember(q,g,"agent"),O(),v()},[i.id,O,v]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-surface-primary flex flex-col shrink-0",style:T!=null?{width:T}:{width:260},children:[e.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[e.jsx("button",{onClick:I,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:C("common:back",{defaultValue:"Back"}),children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"truncate font-semibold text-sm",children:i.name}),i.description&&e.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:i.description})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-2 flex flex-col",children:[o&&e.jsxs("div",{className:"mb-3",children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:C("chat.groupChat",{defaultValue:"Group Chat"})}),e.jsxs("button",{onClick:()=>N(o.channelKey),className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors text-fg-primary ${k?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center shrink-0 bg-surface-overlay text-fg-primary",children:e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:e.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"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:i.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:C("chat.members_other",{count:o.memberCount||H.length+D.length})})]})]})]}),H.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[C("chat.agents",{defaultValue:"Agents"}),e.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:H.length})]}),H.map(g=>{const q=d==="direct"&&u===g.id,oe=i.managerId===g.id,be=g.status==="offline",ge=g.status==="idle"?"bg-green-500":g.status==="working"?"bg-blue-500 animate-pulse":g.status==="error"?"bg-red-500":"bg-gray-600";return e.jsxs("button",{onClick:()=>y(g.id),onContextMenu:ye=>{if(!A)return;ye.preventDefault();const Xe=ue(ye);se(!1),Me(""),he({agentId:g.id,...Xe})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors ${be?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${q?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(vt,{name:g.name,avatarUrl:g.avatarUrl,size:28,bgClass:be?"bg-surface-overlay/60 text-fg-tertiary":"bg-surface-overlay text-fg-primary"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight",children:g.name}),oe&&e.jsx("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"currentColor",className:"text-amber-500 shrink-0",children:e.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"})}),be&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium shrink-0 leading-relaxed",children:C("common:status.offline")})]}),e.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:g.role||" "})]}),(E?.get(g.id)??0)>0&&e.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:E.get(g.id)}),e.jsx("span",{title:g.status,onClick:ye=>{ye.stopPropagation(),b(g.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${ge}`})]},g.id)})]}),D.length>0&&e.jsxs("div",{className:"mb-3",children:[e.jsxs("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider mb-1.5 px-2.5",children:[C("chat.people"),e.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:D.length})]}),D.map(g=>{const q=g.id===r?.id;return e.jsxs("button",{onClick:()=>j(g.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 hover:bg-white/[0.08]",children:[e.jsx(vt,{name:g.name,avatarUrl:g.avatarUrl,size:28,bgClass:"bg-green-500/10 text-green-500"}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"truncate font-medium text-[12px] leading-tight",children:[g.name,q?` (${C("chat.you",{defaultValue:"You"})})`:""]}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:g.email||g.role})]}),e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},g.id)})]}),H.length===0&&D.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:C("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),p&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:p,children:e.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"})}),P&&(()=>{const g=H.find(oe=>oe.id===P.agentId);if(!g||!A)return null;const q=i.managerId===g.id;return e.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:P.x,top:P.y,maxHeight:Math.max(160,window.innerHeight-P.y-8)},onClick:oe=>oe.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{he(null),b(g.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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"12",cy:"7",r:"4"})]}),C("contextMenu.viewProfile")]}),g.status==="offline"?e.jsxs("button",{onClick:()=>{L(g.id,"offline"),he(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:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("polygon",{points:"5 3 19 12 5 21 5 3"})}),C("contextMenu.start")]}):e.jsxs("button",{onClick:()=>{L(g.id,g.status??"idle"),he(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:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})}),C("contextMenu.stop")]}),!q&&e.jsxs("button",{onClick:()=>{J(g.id),he(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:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"currentColor",children:e.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"})}),C("contextMenu.setAsManager")]}),e.jsxs("button",{onClick:()=>{U(g.id),he(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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"9 14 4 9 9 4"}),e.jsx("path",{d:"M20 20v-7a4 4 0 0 0-4-4H4"})]}),C("contextMenu.removeFromTeam")]}),(()=>{const oe=f.filter(ye=>ye.id!==i.id);if(oe.length===0)return null;const be=F.trim().toLowerCase(),ge=be?oe.filter(ye=>ye.name.toLowerCase().includes(be)):oe;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{type:"button",onClick:()=>se(ye=>!ye),className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M5 12h14"}),e.jsx("path",{d:"M12 5l7 7-7 7"})]}),e.jsx("span",{className:"flex-1",children:C("contextMenu.moveTo")}),e.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 ${De?"rotate-180":""}`,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),De&&e.jsxs("div",{className:"px-2 pb-1.5",onClick:ye=>ye.stopPropagation(),children:[e.jsx("input",{autoFocus:!0,value:F,onChange:ye=>Me(ye.target.value),onKeyDown:ye=>ye.stopPropagation(),placeholder:C("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"}),e.jsx("div",{className:"max-h-36 overflow-y-auto rounded-md",children:ge.length===0?e.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:C("contextMenu.moveToEmpty")}):ge.map(ye=>e.jsx("button",{type:"button",onClick:()=>{ee(g.id,ye.id),he(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:ye.name,children:ye.name},ye.id))})]})]})})(),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:async()=>{await M.agents.remove(g.id),v(),he(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:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"3 6 5 6 21 6"}),e.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"})]}),C("contextMenu.removeFromOrg")]})]})})()]})}function Ul(i){const a=i.trim();return!a||a==="about:blank"?a:/^[a-z][a-z0-9+.-]*:/i.test(a)?/^file:/i.test(a)?Kl(a):a:Gl(a)?Ki(a):`https://${a}`}function Gl(i){return!!(i.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(i)||i.startsWith("\\\\"))}function Ki(i){const a=i.replace(/\\/g,"/");return a.startsWith("//")?`file:${oa(a)}`:/^[a-zA-Z]:\//.test(a)?`file:///${oa(a)}`:`file://${oa(a)}`}function Kl(i){try{return new URL(i).href}catch{let a=i.replace(/^file:/i,"").replace(/\\/g,"/");return a.startsWith("//")&&(a=a.replace(/^\/\/(localhost)?/i,""),!a.startsWith("/")&&!/^[a-zA-Z]:\//.test(a)&&(a=`/${a}`)),/^\/[a-zA-Z]:\//.test(a)&&(a=a.slice(1)),!a.startsWith("/")&&!/^[a-zA-Z]:\//.test(a)&&(a=`/${a}`),Ki(a)}}function oa(i){return encodeURI(i).replace(/#/g,"%23")}function Yl({url:i,browserId:a,className:s}){const{t:r}=Ge("common"),o=n.useId().replace(/:/g,""),d=a||`eb_${o}`,u=!a,m=n.useRef(null),f=n.useRef(null),y=n.useRef(null),[N,j]=n.useState(i==="about:blank"?"":i),[I,b]=n.useState(!1),[v,O]=n.useState(!1),[E,T]=n.useState(!1),[p,C]=n.useState(null),[A,H]=n.useState(null),[D,k]=n.useState(!1),P=typeof window<"u"?window.markusDesktop?.browser:void 0,he=typeof window<"u"?window.markusDesktop?.platform:void 0;y.current=A;const De=r(he==="darwin"?"browserFolderAppFinder":he==="win32"?"browserFolderAppExplorer":"browserFolderAppGeneric");return n.useEffect(()=>{if(!P)return;let se=!1;return(async()=>{const F=await P.getState(d);if(se||(F.ok?i&&F.url!==i&&!F.directoryPath?(T(!0),await P.navigate(d,i)):i&&F.directoryPath&&F.url!==i&&await P.navigate(d,i):(T(!0),await P.create(d,i)),se))return;const Me=await P.getState(d);se||!Me.ok||(document.activeElement!==f.current&&j(Me.url&&Me.url!=="about:blank"?Me.url:i==="about:blank"?"":i),T(!!Me.isLoading),C(Me.loadError??null),H(Me.directoryPath??null))})(),()=>{se=!0,u&&P.destroy(d)}},[P,d,i,u]),n.useEffect(()=>{if(i!=="about:blank")return;const se=window.setTimeout(()=>{f.current?.focus(),f.current?.select()},0);return()=>clearTimeout(se)},[i,d]),n.useEffect(()=>{if(P?.onPageEvent)return P.onPageEvent(se=>{if(se.browserId===d){if(se.type==="directory"){H(se.directoryPath||null),T(!1),C(null),se.url&&document.activeElement!==f.current&&j(se.url);return}if(se.type==="loading"){T(!0),C(null),H(null);return}if(se.type==="loaded"){if(T(!1),y.current)return;se.url&&document.activeElement!==f.current&&j(se.url==="about:blank"?"":se.url),window.dispatchEvent(new Event("markus:embedded-browser-resync"));return}if(se.type==="load-failed"){if(T(!1),y.current)return;C(se.error||"Load failed"),se.url&&document.activeElement!==f.current&&j(se.url==="about:blank"?"":se.url);return}se.type==="navigated"&&se.url&&document.activeElement!==f.current&&(y.current||j(se.url==="about:blank"?"":se.url))}})},[P,d]),n.useEffect(()=>{if(!P||!m.current)return;const se=m.current;let F=!0;const Me=()=>{let ee=se;for(;ee;){const g=getComputedStyle(ee);if(g.visibility==="hidden"||g.display==="none")return!1;ee=ee.parentElement}return!0},ue=()=>{if(!F)return;if(!el()||!Me()||Jo()||y.current){P.setBounds(d,{x:0,y:0,width:0,height:0},!1);return}const ee=se.getBoundingClientRect();P.setBounds(d,{x:Math.round(ee.left),y:Math.round(ee.top),width:Math.round(ee.width),height:Math.round(ee.height)},ee.width>2&&ee.height>2)};ue();const L=new ResizeObserver(ue);L.observe(se),window.addEventListener("resize",ue),window.addEventListener("scroll",ue,!0),window.addEventListener("markus:embedded-browser-resync",ue),window.addEventListener("markus:native-browser-overlay",ue),window.addEventListener("markus:native-browser-page",ue);const J=setInterval(()=>{F&&P.getState(d).then(ee=>{if(!F||!ee.ok)return;const g=ee.directoryPath??null;H(g),ee.url&&document.activeElement!==f.current&&(g||ee.url!=="about:blank")&&j(ee.url==="about:blank"?"":ee.url),b(!!ee.canGoBack),O(!!ee.canGoForward),T(!!ee.isLoading),ee.loadError!==void 0&&C(g?null:ee.loadError??null)})},800),U=()=>{P.setBounds(d,{x:0,y:0,width:0,height:0},!1)};return window.addEventListener("pagehide",U),()=>{F=!1,L.disconnect(),window.removeEventListener("resize",ue),window.removeEventListener("scroll",ue,!0),window.removeEventListener("markus:embedded-browser-resync",ue),window.removeEventListener("markus:native-browser-overlay",ue),window.removeEventListener("markus:native-browser-page",ue),window.removeEventListener("pagehide",U),clearInterval(J),P.setBounds(d,{x:0,y:0,width:0,height:0},!1)}},[P,d]),n.useEffect(()=>{window.dispatchEvent(new Event("markus:embedded-browser-resync"))},[A]),P?e.jsxs("div",{className:`flex flex-col h-full min-h-0 min-w-0 w-full ${s??""}`,children:[e.jsxs("div",{className:"shrink-0 relative mb-2",children:[e.jsxs("div",{className:"flex items-center gap-1 px-2 py-1.5 border border-border-default rounded-lg bg-surface-elevated",children:[e.jsx("button",{disabled:!I,onClick:()=>{P.action(d,"back")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay disabled:opacity-30",title:"Back",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsx("button",{disabled:!v,onClick:()=>{P.action(d,"forward")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay disabled:opacity-30",title:"Forward",children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("polyline",{points:"9 18 15 12 9 6"})})}),e.jsx("button",{onClick:()=>{E?P.action(d,"stop"):P.action(d,"reload")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay",title:E?"Stop":"Reload",children:E?e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"animate-spin",children:e.jsx("path",{d:"M12 2a10 10 0 0 1 10 10",strokeLinecap:"round"})}):e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[e.jsx("polyline",{points:"23 4 23 10 17 10"}),e.jsx("path",{d:"M20.49 15a9 9 0 1 1-2.12-9.36L23 10"})]})}),e.jsx("form",{className:"flex-1 min-w-0",onSubmit:se=>{se.preventDefault();let F=N.trim();F&&(F=Ul(F),T(!0),C(null),H(null),P.navigate(d,F),j(F))},children:e.jsx("input",{ref:f,value:N,onChange:se=>j(se.target.value),placeholder:r("browserUrlPlaceholder"),spellCheck:!1,autoCorrect:"off",autoCapitalize:"off",className:"w-full px-2 py-1 text-xs bg-surface-primary border border-border-default rounded-md text-fg-primary outline-none focus:border-brand-500"})}),E&&e.jsx("span",{className:"shrink-0 text-[10px] text-fg-tertiary px-1 select-none",children:r("browserLoading")})]}),e.jsx("div",{className:`absolute left-2 right-2 bottom-0 h-0.5 overflow-hidden rounded-full transition-opacity ${E?"opacity-100":"opacity-0"}`,"aria-hidden":!E,children:e.jsx("div",{className:"h-full w-1/3 bg-brand-500 animate-[browser-load_1.1s_ease-in-out_infinite]"})})]}),p&&!E&&!A&&e.jsx("div",{className:"shrink-0 mb-2 px-2.5 py-1.5 text-[11px] text-amber-600 dark:text-amber-400 bg-amber-500/10 border border-amber-500/20 rounded-lg",children:p}),e.jsx("div",{ref:m,className:"flex-1 min-h-0 min-w-0 w-full rounded-lg border border-border-default bg-surface-elevated/30 overflow-hidden",children:A&&e.jsxs("div",{className:"h-full w-full flex flex-col items-center justify-center gap-4 px-6 text-center",children:[e.jsx("div",{className:"w-12 h-12 rounded-2xl bg-surface-elevated border border-border-default flex items-center justify-center text-fg-secondary",children:e.jsx("svg",{width:"24",height:"24",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:e.jsx("path",{d:"M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z",strokeLinejoin:"round"})})}),e.jsxs("div",{className:"space-y-1.5 max-w-md",children:[e.jsx("p",{className:"text-sm font-medium text-fg-primary",children:r("browserFolderTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary break-all",children:A})]}),e.jsx("button",{type:"button",disabled:D,onClick:()=>{k(!0),M.system.openPath(A).catch(()=>M.files.reveal(A)).finally(()=>k(!1))},className:"px-3.5 py-2 text-xs rounded-lg bg-brand-600 hover:bg-brand-500 disabled:opacity-50 text-white transition-colors",children:D?r("browserFolderOpening"):r("browserFolderOpen",{app:De})})]})}),e.jsx("style",{children:`
|
|
6
|
-
@keyframes browser-load {
|
|
7
|
-
0% { transform: translateX(-120%); }
|
|
8
|
-
100% { transform: translateX(360%); }
|
|
9
|
-
}
|
|
10
|
-
`})]}):e.jsxs("div",{className:`space-y-3 ${s??""}`,children:[e.jsx("p",{className:"text-sm text-fg-secondary break-all",children:i}),e.jsx("button",{onClick:()=>window.open(i,"_blank","noopener,noreferrer"),className:"px-3 py-2 text-xs rounded-lg bg-brand-600/20 text-brand-500 hover:bg-brand-600/30 transition-colors",children:"Open in browser"})]})}function hi(i){return/^https?:\/\//i.test(i)}function Xl(i){return i.kind==="deliverable"?i.deliverable.reference??"":i.kind==="url"?i.url:i.path}function Ql(i){return i.kind==="deliverable"?i.deliverable.title||i.deliverable.reference||"":i.kind==="url"?i.title||i.url:i.title||i.path.split(/[/\\]/).pop()||i.path}function Zl(i,a){if(i.kind==="file")return`file:${i.path}:${a??""}`;if(i.kind==="url")return`url:${i.browserId||i.url}:${a??""}`;const s=i.deliverable;return`deliverable:${s.id||s.reference||s.title||"unknown"}:${a??""}`}function la(i){return i==null||!Number.isFinite(i)?"":i<1024?`${i} B`:i<1024*1024?`${(i/1024).toFixed(1)} KB`:`${(i/(1024*1024)).toFixed(1)} MB`}function Jl({payload:i,onClose:a,width:s,onResizeStart:r,onAddToChat:o,tabs:d,activeTabId:u,onSelectTab:m,onCloseTab:f,onNewTab:y,fullscreen:N,onToggleFullscreen:j}){const{t:I}=Ge(["deliverables","agent","common"]),[b,v]=n.useState({mode:"loading"}),[O,E]=n.useState(!1),[T,p]=n.useState(null),C=n.useRef(null),A=n.useRef(null),H=n.useRef(null),D=Xl(i),k=Ql(i),P=(d?.length??0)>=1,he=Zl(i,u);n.useEffect(()=>{if(!u)return;const U=H.current,ee=A.current;if(!U||!ee)return;const g=requestAnimationFrame(()=>{U.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame(g)},[u,d?.length]),n.useEffect(()=>{const U=ee=>{ee.key==="Escape"&&(N&&j?j():a())};return window.addEventListener("keydown",U),()=>window.removeEventListener("keydown",U)},[a,N,j]),n.useEffect(()=>{let U=!1;return p(null),i.kind==="url"?(v({mode:"url",url:i.url,browserId:i.browserId}),()=>{U=!0}):hi(D)?(v({mode:"url",url:D}),()=>{U=!0}):(v({mode:"loading"}),i.kind==="deliverable"&&i.deliverable.artifactType&&i.deliverable.artifactData?(v({mode:"artifact",summary:i.deliverable.summary||i.deliverable.title||""}),()=>{U=!0}):D?i.kind==="deliverable"&&i.deliverable.type==="directory"?(v({mode:"unpreviewable",reference:D,isDirectory:!0}),()=>{U=!0}):(M.files.preview(D).then(g=>{if(U)return;if(g.type==="image"){const oe=g.content?`data:${g.mimeType||"image/png"};base64,${g.content}`:g.streamUrl||(g.path?M.files.streamUrl(g.path):M.files.streamUrl(D));v({mode:"image",src:oe,name:g.name||k});return}if(g.type==="audio"){const oe=g.streamUrl||(g.path?M.files.streamUrl(g.path):M.files.streamUrl(D));v({mode:"audio",src:oe,name:g.name||k,mimeType:g.mimeType||"audio/mpeg",size:g.size});return}if(g.type==="video"){const oe=g.streamUrl||(g.path?M.files.streamUrl(g.path):M.files.streamUrl(D));v({mode:"video",src:oe,name:g.name||k,mimeType:g.mimeType||"video/mp4",size:g.size});return}if(g.type==="binary"){v({mode:"binary",name:g.name||k,reference:g.path||D,size:g.size,extension:g.extension});return}if(typeof g.content!="string"){v({mode:"unpreviewable",reference:D,isDirectory:!1});return}const q=Cl({format:i.kind==="deliverable"?i.deliverable.format:void 0,reference:D,content:g.content});v({mode:"content",content:g.content,format:q})}).catch(()=>{U||v({mode:"unpreviewable",reference:D,isDirectory:!1})}),()=>{U=!0}):(v({mode:"unpreviewable",reference:"",isDirectory:!1}),()=>{U=!0}))},[he,i,D,k]);const De=k||D,se=n.useCallback((U,ee)=>{const g=U.length>40?`${U.slice(0,24)}…${U.slice(-12)}`:U;return ee?{label:`🌐 ${g}`,content:["[html-selection]",`Text: "${U}"`,`CSS Selector: ${ee.cssSelector}`,`XPath: ${ee.xpath}`,D?`File: ${D}`:""].filter(Boolean).join(`
|
|
11
|
-
`)}:{label:`“${g}”`,content:`${I("deliverables:chat.selectedFrom",{defaultValue:"Selected from"})} ${De}:
|
|
12
|
-
|
|
13
|
-
"""
|
|
14
|
-
${U}
|
|
15
|
-
"""`}},[D,De,I]),F=n.useCallback((U,ee)=>{!U.trim()||!o||(o(se(U.trim(),ee)),p(null),window.getSelection()?.removeAllRanges())},[o,se]),Me=n.useCallback(U=>{if(!U.text.trim()||!o)return;const ee=C.current?.querySelector("iframe")?.getBoundingClientRect(),g=(ee?.left??0)+U.rect.x+U.rect.width/2,q=(ee?.top??0)+U.rect.y;p({x:g,y:q,text:U.text,htmlMeta:{xpath:U.xpath,cssSelector:U.cssSelector}})},[o]);n.useEffect(()=>{const U=C.current;if(!U||!o)return;const ee=()=>{requestAnimationFrame(()=>{const q=window.getSelection(),oe=q?.toString().trim();if(!oe||!q?.rangeCount){p(null);return}const be=q.getRangeAt(0);if(!U.contains(be.commonAncestorContainer)){p(null);return}const ge=be.getBoundingClientRect();p({x:ge.left+ge.width/2,y:ge.top,text:oe})})},g=q=>{const oe=document.getElementById("right-panel-selection-toolbar");oe&&oe.contains(q.target)||p(null)};return U.addEventListener("mouseup",ee),document.addEventListener("mousedown",g),()=>{U.removeEventListener("mouseup",ee),document.removeEventListener("mousedown",g)}},[o,b.mode]);const ue=()=>{M.files.reveal(D).catch(()=>{})},L=()=>{navigator.clipboard?.writeText(D).then(()=>{E(!0),setTimeout(()=>E(!1),1500)}).catch(()=>{})},J=!!D&&!hi(D)&&(i.kind==="file"||i.kind==="deliverable");return e.jsxs(e.Fragment,{children:[!N&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:r,children:e.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"})}),e.jsxs("div",{className:`bg-surface-primary flex flex-col overflow-hidden ${N?"flex-1 min-w-0":"shrink-0"}`,style:N?void 0:{width:s},"data-right-panel":!0,children:[e.jsxs("header",{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:[P||y?e.jsxs("div",{ref:A,role:"tablist",className:"flex-1 min-w-0 flex flex-nowrap items-center gap-0.5 overflow-x-auto overflow-y-hidden overscroll-x-contain scrollbar-thin",onWheel:U=>{const ee=U.currentTarget;ee.scrollWidth<=ee.clientWidth||Math.abs(U.deltaY)<=Math.abs(U.deltaX)||(ee.scrollLeft+=U.deltaY,U.preventDefault())},children:[d?.map(U=>{const ee=U.id===u;return e.jsxs("div",{className:`group shrink-0 flex items-center max-w-[160px] rounded-md text-[11px] border transition-colors ${ee?"bg-surface-elevated border-border-default text-fg-primary":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[e.jsx("button",{type:"button",role:"tab","aria-selected":ee,ref:ee?H:void 0,className:"min-w-0 flex-1 truncate pl-2.5 pr-1 py-1 text-left cursor-pointer",title:U.title,onPointerDown:g=>{g.button===0&&m?.(U.id)},onClick:()=>m?.(U.id),children:U.title}),f&&e.jsx("button",{type:"button",onPointerDown:g=>{g.button===0&&(g.preventDefault(),g.stopPropagation(),f(U.id))},onClick:g=>{g.preventDefault(),g.stopPropagation(),f(U.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${ee?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:I("common:closeTab",{defaultValue:"Close tab"}),"aria-label":I("common:closeTab",{defaultValue:"Close tab"}),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},U.id)}),y&&e.jsx("button",{type:"button",onClick:y,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:I("common:newTab",{defaultValue:"New Tab"}),"aria-label":I("common:newTab",{defaultValue:"New Tab"}),children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),e.jsx("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]})})]}):e.jsx("span",{className:"text-sm font-semibold text-fg-primary truncate flex-1 min-w-0 px-1.5",title:D||k,children:k}),e.jsxs("div",{className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[i.kind==="deliverable"&&e.jsx("button",{onClick:()=>ps.navigate(xt.DELIVERABLES,{openDeliverable:i.deliverable.id}),title:I("agent:deliverables.openInPage",{defaultValue:"Open in page"}),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:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}),e.jsx("polyline",{points:"15 3 21 3 21 9"}),e.jsx("line",{x1:"10",y1:"14",x2:"21",y2:"3"})]})}),J&&e.jsx("button",{onClick:ue,title:I("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":I("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:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.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"})})}),j&&e.jsx("button",{onClick:j,title:N?I("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):I("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:N?e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"4 14 10 14 10 20"}),e.jsx("polyline",{points:"20 10 14 10 14 4"}),e.jsx("line",{x1:"14",y1:"10",x2:"21",y2:"3"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]}):e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("polyline",{points:"15 3 21 3 21 9"}),e.jsx("polyline",{points:"9 21 3 21 3 15"}),e.jsx("line",{x1:"21",y1:"3",x2:"14",y2:"10"}),e.jsx("line",{x1:"3",y1:"21",x2:"10",y2:"14"})]})}),e.jsx("button",{onClick:a,title:I("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":I("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:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]})]}),e.jsxs("div",{className:`flex-1 min-w-0 min-h-0 ${b.mode==="url"?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[b.mode==="loading"&&e.jsxs("div",{className:"animate-pulse space-y-3",children:[e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-full"}),e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-5/6"}),e.jsx("div",{className:"h-32 bg-surface-overlay/40 rounded-lg w-full mt-2"}),e.jsx("div",{className:"h-4 bg-surface-overlay/60 rounded w-3/4"})]}),b.mode==="image"&&e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("img",{src:b.src,alt:b.name,className:"max-w-full rounded-lg object-contain"}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:b.name})]}),b.mode==="audio"&&e.jsxs("div",{className:"flex flex-col items-stretch gap-3 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-brand-500/15 text-brand-500 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"22",height:"22",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M9 18V5l12-2v13"}),e.jsx("circle",{cx:"6",cy:"18",r:"3"}),e.jsx("circle",{cx:"18",cy:"16",r:"3"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:b.name}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[b.mimeType,b.size!=null?` · ${la(b.size)}`:""]})]})]}),e.jsx("audio",{controls:!0,preload:"metadata",src:b.src,className:"w-full"})]}),b.mode==="video"&&e.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[e.jsx("video",{controls:!0,preload:"metadata",src:b.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),e.jsxs("span",{className:"text-xs text-fg-tertiary",children:[b.name,b.size!=null?` · ${la(b.size)}`:""]})]}),b.mode==="binary"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.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:(b.extension||"file").replace(/^\./,"")||"file"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:b.name}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[I("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),b.size!=null?` · ${la(b.size)}`:""]})]})]}),b.reference&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{onClick:()=>{M.files.reveal(b.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:I("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),b.mode==="content"&&e.jsx("div",{ref:C,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:e.jsx(li,{content:b.content,format:b.format,className:"text-fg-secondary text-sm",onHtmlSelection:Me,basePath:D?D.replace(/[/\\][^/\\]+$/,""):void 0})}),b.mode==="artifact"&&e.jsx("div",{ref:C,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:e.jsx(li,{content:b.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),b.mode==="url"&&e.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:e.jsx(Yl,{url:b.url,browserId:b.browserId,className:"flex-1 min-h-0"},b.browserId||b.url)}),b.mode==="unpreviewable"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-fg-secondary",children:b.isDirectory?I("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):I("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),b.reference&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:ue,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:I("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:b.reference}),e.jsx("button",{onClick:ue,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:I("common:open",{defaultValue:"Open"})}),e.jsx("button",{onClick:L,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${O?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:O?I("common:copied",{defaultValue:"Copied"}):I("common:copy",{defaultValue:"Copy"})})]})]})]},he)]}),T&&o&&e.jsx("div",{id:"right-panel-selection-toolbar",className:"fixed z-50 -translate-x-1/2 -translate-y-full bg-surface-elevated border border-border-default rounded-lg shadow-xl overflow-hidden",style:{left:T.x,top:T.y-8},children:e.jsxs("button",{onMouseDown:U=>{U.preventDefault(),U.stopPropagation(),F(T.text,T.htmlMeta)},className:"px-3 py-1.5 text-xs text-fg-secondary hover:bg-surface-overlay hover:text-fg-primary transition-colors flex items-center gap-1.5 whitespace-nowrap",children:[e.jsx("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.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"})}),I("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})})]})}const ec=n.lazy(()=>Ui(()=>import("./index-BVZKeNvh.js").then(i=>i.az),__vite__mapDeps([0,1])).then(i=>({default:i.MarkdownMessage}))),xa=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function da(i,a){return a(`agent:profilePage.taskStatus.${i}`,{defaultValue:i.replace(/_/g," ")})}function Yi(i,a){const r={idle:"common:status.idle",working:"common:status.working",offline:"common:status.offline",error:"common:status.error"}[i];return r?a(r):i}const Xi={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function dn(i){return i>=1e6?`${(i/1e6).toFixed(1)}M`:i>=1e3?`${(i/1e3).toFixed(1)}K`:i.toLocaleString()}function pi({agentId:i,onBack:a,inline:s,defaultTab:r,onSwipeBack:o,highlightMailboxId:d,authUser:u,headless:m,activeTab:f}){const{t:y}=Ge(["agent","common"]),N=ma(),[j,I]=n.useState(null),[b,v]=n.useState(null),[O,E]=n.useState(r??"overview"),T=m&&f?f:O,[p,C]=n.useState(null),A=n.useMemo(()=>xa.map(F=>({...F,label:y(`agent:tabs.${F.key}`)})),[y]),H=n.useMemo(()=>A.map(F=>({id:F.key})),[A]),D=n.useMemo(()=>({onSwipeOutLeft:o}),[o]),k=zi(H,O,E,D),P=n.useRef(null);n.useEffect(()=>{const F=P.current;if(!F)return;F.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[O]);const he=n.useCallback(()=>{M.agents.get(i).then(I).catch(()=>{})},[i]);if(n.useEffect(()=>(E(r??"overview"),C(null),he(),M.externalAgents.list().then(Me=>{const ue=Me.agents.find(L=>L.markusAgentId===i);C(ue??null)}).catch(()=>{}),ze.on("agent:update",Me=>{Me.payload.agentId===i&&he()})),[i,he]),!j)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:y("agent:profilePage.loadingAgent")});const De=Xi[j.state.status]??"bg-gray-500",se=u?.role==="owner"||u?.role==="admin";return m?e.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:e.jsxs("div",{className:"p-5",children:[(T==="overview"||T==="mind")&&e.jsxs(e.Fragment,{children:[e.jsx(bi,{agent:j,onUpdate:he,externalInfo:p,t:y,canManageAgents:se}),e.jsx("div",{className:"mt-6",children:e.jsx(Pi,{agentId:i,highlightId:d,agentStatus:j.state.status,canManageAgents:se,onAgentStateChange:he})})]}),T==="files"&&e.jsx(ji,{agentId:i}),T==="tools"&&e.jsx(wi,{tools:j.tools??[],agent:j}),T==="memory"&&e.jsxs(e.Fragment,{children:[e.jsx(Ni,{agentId:i,initialData:j.heartbeat}),e.jsx("div",{className:"mt-6",children:e.jsx(ki,{agentId:i})})]}),T==="deliverables"&&e.jsx(Li,{agentId:i})]})}):e.jsxs("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:[e.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(vt,{name:j.name,avatarUrl:j.avatarUrl,size:40,className:"rounded-xl"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h2",{className:"text-base font-semibold",children:j.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${De}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:Yi(j.state.status,y)}),p&&e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:y("agent:profilePage.badges.external")}),j.agentRole==="manager"&&e.jsx("span",{className:"px-1.5 py-0.5 text-[10px] bg-amber-500/15 text-amber-600 rounded font-medium",children:y("agent:profilePage.badges.manager")})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary truncate",children:[j.role,j.roleDescription?` — ${j.roleDescription}`:""]})]}),e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[!s&&e.jsxs("button",{onClick:()=>ps.navigate(xt.TEAM,{agentId:i}),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:[e.jsx("span",{children:"◈"})," ",y("agent:profilePage.chat")]}),se&&e.jsxs("button",{onClick:async()=>{if(j)try{const{filesMap:F}=await M.agents.getFilesMap(i),Me={type:"agent",name:Wi(j.name,j.name),displayName:j.name,version:"1.0.0",description:j.roleDescription??j.role,author:"",category:"general",tags:[],agent:{roleName:j.role,agentRole:j.agentRole},dependencies:{skills:j.skills??[]}};await Hi.publishViaProxy({itemType:"agent",name:j.name,description:Me.description,category:"general",config:Me,files:F}),v({title:y("agent:profilePage.hub"),message:y("agent:profilePage.publishSuccess",{name:j.name}),variant:"primary"})}catch(F){v({title:y("agent:profilePage.hub"),message:y("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:y("agent:profilePage.publishTitle"),children:[e.jsx("span",{children:"↑"})," ",y("agent:profilePage.hub")]}),s&&e.jsx("button",{onClick:a,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]})]}),e.jsx("div",{ref:P,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:A.filter(F=>!p||["overview","mind"].includes(F.key)).map(F=>e.jsxs("button",{onClick:()=>E(F.key),"data-active":O===F.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${O===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:[e.jsx("span",{className:"mr-1",children:F.icon}),F.label]},F.key))})]}),e.jsxs("div",{className:"p-5",onTouchStart:N?k.onTouchStart:void 0,onTouchEnd:N?k.onTouchEnd:void 0,children:[(O==="overview"||O==="mind")&&e.jsxs(e.Fragment,{children:[e.jsx(bi,{agent:j,onUpdate:he,externalInfo:p,t:y,canManageAgents:se}),e.jsx("div",{className:"mt-6",children:e.jsx(Pi,{agentId:i,highlightId:d,agentStatus:j.state.status,canManageAgents:se,onAgentStateChange:he})})]}),O==="files"&&e.jsx(ji,{agentId:i}),O==="tools"&&e.jsx(wi,{tools:j.tools??[],agent:j}),O==="memory"&&e.jsxs(e.Fragment,{children:[e.jsx(Ni,{agentId:i,initialData:j.heartbeat}),e.jsx("div",{className:"mt-6",children:e.jsx(ki,{agentId:i})})]}),O==="deliverables"&&e.jsx(Li,{agentId:i})]}),b&&e.jsx(Bn,{alertOnly:!0,variant:b.variant??"primary",title:b.title,message:b.message,onConfirm:()=>v(null),onCancel:()=>v(null)})]})}function bi({agent:i,onUpdate:a,externalInfo:s,t:r,canManageAgents:o}){const[d,u]=n.useState(null),[m,f]=n.useState([]),[y,N]=n.useState(null),[j,I]=n.useState(null),[b,v]=n.useState(""),[O,E]=n.useState([]);n.useEffect(()=>{M.usage.agents().then(k=>{const P=k.agents.find(he=>he.agentId===i.id);P&&u(P)}).catch(()=>{}),M.agents.getRecentActivities(i.id).then(k=>f(k.activities)).catch(()=>{}),M.system.storage().then(k=>{v(k.dataDir+"/agents/"+i.id);const P=k.agents.find(he=>he.id===i.id);P&&I(P)}).catch(()=>{}),i.state.activeTaskIds?.length&&M.tasks.list({assignedAgentId:i.id}).then(k=>{E(k.tasks.filter(P=>i.state.activeTaskIds?.includes(P.id)))}).catch(()=>{})},[i.id,i.state.activeTaskIds]);const T=()=>{i.state.status==="offline"?M.agents.start(i.id).then(a):M.agents.stop(i.id).then(a)},p=n.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]),C=n.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(s)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(it,{title:r("agent:profilePage.overview.identity"),children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[e.jsx(At,{label:r("agent:profilePage.overview.labels.name"),children:i.name}),e.jsx(At,{label:r("agent:profilePage.overview.labels.agentRole"),children:e.jsx("span",{className:i.agentRole==="manager"?"text-amber-600":"text-blue-600",children:i.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),e.jsx(At,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:i.role}),e.jsx(At,{label:r("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:i.id}),e.jsx(At,{label:r("agent:profilePage.overview.labels.organization"),children:i.config?.orgId??"default"}),e.jsx(At,{label:r("agent:profilePage.overview.labels.created"),children:i.config?.createdAt?new Date(i.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]})}),e.jsx(it,{title:r("agent:profilePage.overview.connectionStatus"),children:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(mt,{label:r("agent:profilePage.overview.labels.connection"),value:s.connected?r("common:status.online"):r("common:status.offline"),color:s.connected?"green":"gray"}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.platform"),value:r("agent:profilePage.overview.openClaw")}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(i.state.activeTaskIds?.length??0)}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.lastSync"),value:s.lastHeartbeat?new Date(s.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")})]})}),e.jsx(it,{title:r("agent:profilePage.overview.externalAgentDetails"),children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[e.jsx(At,{label:r("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:s.externalAgentId}),e.jsx(At,{label:r("agent:profilePage.overview.labels.registered"),children:new Date(s.registeredAt).toLocaleString()}),e.jsx(At,{label:r("agent:profilePage.overview.labels.capabilities"),children:s.capabilities.length>0?s.capabilities.join(", "):r("agent:profilePage.overview.noneDeclared")}),e.jsx(At,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),children:s.lastHeartbeat?new Date(s.lastHeartbeat).toLocaleString():r("agent:profilePage.never")})]})}),e.jsx(it,{title:r("agent:profilePage.overview.syncContextTitle"),children:e.jsx("div",{className:"space-y-1.5",children:C.map(k=>e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[e.jsx("span",{className:"font-mono text-[10px] text-brand-500 shrink-0 pt-0.5",children:k.field}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:k.desc})]},k.field))})}),e.jsx(it,{title:r("agent:profilePage.overview.gatewayEndpoints"),children:e.jsx("div",{className:"space-y-1.5",children:p.map(k=>e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2 rounded-lg bg-surface-elevated",children:[e.jsx("span",{className:`text-[10px] font-semibold shrink-0 pt-0.5 ${k.method==="POST"?"text-amber-600":"text-green-600"}`,children:k.method}),e.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:k.path}),e.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:k.desc})]},k.path))})})]});const A=m.filter(k=>k.type==="heartbeat").length,H=m.filter(k=>k.type==="chat").length,D=i.state.activeTaskIds?.length??0;return e.jsxs("div",{className:"space-y-4",children:[e.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:[e.jsx(At,{label:r("agent:profilePage.overview.labels.roleTemplate"),children:i.role}),e.jsx(At,{label:r("agent:profilePage.overview.labels.agentRole"),children:e.jsx("span",{className:i.agentRole==="manager"?"text-amber-600":"text-blue-600",children:i.agentRole==="manager"?r("agent:profilePage.roles.managerDisplay"):r("agent:profilePage.roles.workerDisplay")})}),e.jsx(At,{label:r("agent:profilePage.overview.labels.agentId"),mono:!0,children:i.id}),e.jsx(At,{label:r("agent:profilePage.overview.labels.created"),children:i.config?.createdAt?new Date(i.config.createdAt).toLocaleDateString():r("agent:profilePage.emDash")})]}),e.jsxs("div",{className:"bg-surface-elevated rounded-xl px-4 py-3 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${Xi[i.state.status]||"bg-gray-500"}`}),e.jsx("span",{className:`text-sm font-semibold ${i.state.status==="idle"?"text-green-500":i.state.status==="working"?"text-blue-400":i.state.status==="error"?"text-red-400":"text-fg-secondary"}`,children:Yi(i.state.status,r)})]}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.tokensToday"),value:dn(i.state.tokensUsedToday)}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.activeTasks"),value:String(D),color:D>0?"blue":void 0}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.lastHeartbeat"),value:i.state.lastHeartbeat?new Date(i.state.lastHeartbeat).toLocaleTimeString():r("agent:profilePage.never")}),o&&e.jsx("button",{onClick:T,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:i.state.status==="offline"?r("agent:profilePage.overview.startAgent"):r("agent:profilePage.overview.stopAgent")})]}),i.state.status==="error"&&e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-medium text-red-500",children:r("agent:profilePage.overview.errorDetails")}),i.state.lastErrorAt&&e.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(i.state.lastErrorAt).toLocaleString()})]}),e.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:br(i.state.lastError,r)||i.state.lastError||r("agent:profilePage.overview.errorFallback")})]}),i.state.status==="working"&&D>0&&e.jsx("div",{className:"bg-brand-500/10 border border-brand-500/20 rounded-lg p-2.5",children:e.jsx("div",{className:"space-y-1",children:O.map(k=>e.jsxs("div",{className:"flex items-center gap-2 text-[11px]",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),e.jsx("span",{className:"text-fg-secondary truncate flex-1",children:k.title}),e.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:da(k.status,r)})]},k.id))})}),d&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/40"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(mt,{label:r("agent:profilePage.overview.labels.totalTokens"),value:dn(d.totalTokens)}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.requests"),value:String(d.requestCount)}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.toolCalls"),value:String(d.toolCalls)}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.promptTokens"),value:dn(d.promptTokens)}),e.jsx(mt,{label:r("agent:profilePage.overview.labels.completionTokens"),value:dn(d.completionTokens)}),e.jsx(mt,{label:"CU Used",value:dn(d.cuUsed??0)})]})]}),j&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/40"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(mt,{label:r("agent:profilePage.overview.storage"),value:Mi(j.size)}),j.subItems.filter(k=>k.size>0).map(k=>e.jsx(mt,{label:k.name,value:Mi(k.size)},k.name)),e.jsxs("button",{onClick:()=>{M.system.openPath(b)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[r("agent:profilePage.overview.openFolder")," →"]})]})]})]}),A>0&&e.jsx(it,{title:r("agent:profilePage.overview.recentHeartbeats"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.heartbeatRuns",{count:A})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:m.filter(k=>k.type==="heartbeat").map(k=>{const P=y===k.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>N(P?null:k.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:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-green-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:k.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(k.startedAt).toLocaleString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:P?"▲":"▼"})]}),P&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(Fn,{agentId:i.id,activityId:k.id})})]},k.id)})})}),H>0&&e.jsx(it,{title:r("agent:profilePage.overview.recentA2A"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.overview.conversations",{count:H})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:m.filter(k=>k.type==="chat").map(k=>{const P=y===k.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>N(P?null:k.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:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:k.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(k.startedAt).toLocaleString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:P?"▲":"▼"})]}),P&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(Fn,{agentId:i.id,activityId:k.id})})]},k.id)})})})]})}function tc(i,a){const s=i.split(`
|
|
16
|
-
`),r=a.split(`
|
|
17
|
-
`),o=s.length,d=r.length,u=Array.from({length:o+1},()=>new Array(d+1).fill(0));for(let I=o-1;I>=0;I--)for(let b=d-1;b>=0;b--)u[I][b]=s[I]===r[b]?u[I+1][b+1]+1:Math.max(u[I+1][b],u[I][b+1]);const m=[];let f=0,y=0,N=1,j=1;for(;f<o||y<d;)f<o&&y<d&&s[f]===r[y]?(m.push({type:"equal",content:s[f],oldLineNum:N++,lineNum:j++}),f++,y++):y<d&&(f>=o||u[f][y+1]>=u[f+1][y])?(m.push({type:"add",content:r[y],lineNum:j++}),y++):(m.push({type:"remove",content:s[f],oldLineNum:N++}),f++);return m}function yi(i){return i.match(/\S+|\s+/g)??[""]}function vi({oldText:i,newText:a,mode:s}){const r=yi(i),o=yi(a),d=r.length,u=o.length,m=Array.from({length:d+1},()=>new Array(u+1).fill(0));for(let j=d-1;j>=0;j--)for(let I=u-1;I>=0;I--)m[j][I]=r[j]===o[I]?m[j+1][I+1]+1:Math.max(m[j+1][I],m[j][I+1]);const f=[];let y=0,N=0;for(;y<d||N<u;)y<d&&N<u&&r[y]===o[N]?(f.push({text:s==="remove"?r[y]:o[N],changed:!1}),y++,N++):N<u&&(y>=d||m[y][N+1]>=m[y+1][N])?(s==="add"&&f.push({text:o[N],changed:!0}),N++):(s==="remove"&&f.push({text:r[y],changed:!0}),y++);return e.jsx("span",{children:f.map((j,I)=>j.changed?e.jsx("span",{className:s==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:j.text},I):e.jsx("span",{children:j.text},I))})}function sc({agent:i,template:a,templateId:s}){const{t:r}=Ge(["agent","common"]),o=n.useMemo(()=>tc(i,a),[i,a]),[d,u]=n.useState(!0),m=3,f=n.useMemo(()=>{const b=o.map((T,p)=>T.type!=="equal"?p:-1).filter(T=>T>=0);if(b.length===0)return[];const v=[];let O=Math.max(0,b[0]-m),E=Math.min(o.length-1,b[0]+m);for(let T=1;T<b.length;T++){const p=Math.max(0,b[T]-m),C=Math.min(o.length-1,b[T]+m);p<=E+1||(v.push({start:O,end:E}),O=p),E=C}return v.push({start:O,end:E}),v},[o]),y=(b,v,O)=>{const E=b.type==="add"?"+":b.type==="remove"?"-":" ",T=b.type==="add"?"bg-green-500/8":b.type==="remove"?"bg-red-500/8":"",p=b.type==="add"?"text-green-600/90":b.type==="remove"?"text-red-500/80":"text-fg-tertiary",C=b.type==="add"?"text-green-500":b.type==="remove"?"text-red-500":"text-fg-muted",A=b.type==="remove"?b.oldLineNum:b.lineNum;let H=null;return b.type==="remove"&&v+1<O.length&&O[v+1].type==="add"?H=e.jsx(vi,{oldText:b.content,newText:O[v+1].content,mode:"remove"}):b.type==="add"&&v>0&&O[v-1].type==="remove"&&(H=e.jsx(vi,{oldText:O[v-1].content,newText:b.content,mode:"add"})),e.jsxs("div",{className:`flex ${T} hover:brightness-95 transition-colors`,children:[e.jsx("span",{className:"w-10 shrink-0 text-right pr-2 text-[10px] text-fg-muted/50 select-none leading-[20px]",children:A??""}),e.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${C} select-none leading-[20px]`,children:E}),e.jsxs("span",{className:`flex-1 text-[11px] font-mono ${p} whitespace-pre-wrap break-words leading-[20px]`,children:[H??b.content,b.content===""&&" "]})]},v)},N=o.filter(b=>b.type==="add").length,j=o.filter(b=>b.type==="remove").length,I=d?f.flatMap(b=>{const v=[];for(let O=b.start;O<=b.end;O++)v.push({...o[O],_idx:O});return v}):o.map((b,v)=>({...b,_idx:v}));return e.jsxs("div",{className:"mb-3 bg-surface-elevated rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-1.5 bg-surface-elevated",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:r("agent:profilePage.diff.title",{templateId:s})}),e.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",N]}),e.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",j]})]}),e.jsx("button",{onClick:()=>u(b=>!b),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:r(d?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),e.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[d&&f.length>0&&f[0].start>0&&e.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:f[0].start})}),I.map((b,v)=>{const O=v>0?I[v-1]:null,E=d&&O&&b._idx-O._idx>1;return e.jsxs("div",{children:[E&&e.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:"···"}),y(b,b._idx,o)]},v)}),d&&f.length>0&&f[f.length-1].end<o.length-1&&e.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:o.length-1-f[f.length-1].end})}),f.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-4",children:r("agent:profilePage.diff.identical")})]})]})}function nc(i,a){const s=i.split(`
|
|
18
|
-
`),r=a.split(`
|
|
19
|
-
`),o=[],d=Math.max(s.length,r.length);for(let u=0;u<d;u++){const m=s[u],f=r[u];if(m===f){o.push(` ${m??""}`);continue}m!==void 0&&(f===void 0||m!==f)&&o.push(`- ${m}`),f!==void 0&&(m===void 0||m!==f)&&o.push(`+ ${f}`)}if(o.length>80){const u=o.filter(m=>m.startsWith("+ ")||m.startsWith("- "));if(u.length>0)return u.join(`
|
|
20
|
-
`)}return o.join(`
|
|
21
|
-
`)}function ji({agentId:i}){const{t:a}=Ge(["agent","common"]),[s,r]=n.useState([]),[o,d]=n.useState(!0),[u,m]=n.useState(null),[f,y]=n.useState(""),[N,j]=n.useState(""),[I,b]=n.useState(!1);n.useEffect(()=>{M.system.storage().then(J=>{j(J.dataDir+"/agents/"+i+"/role")}).catch(()=>{})},[i]);const[v,O]=n.useState(!1),[E,T]=n.useState(!1),[p,C]=n.useState(null),[A,H]=n.useState(null),D=n.useCallback(()=>{d(!0),Promise.all([M.agents.getFiles(i),M.agents.roleStatus(i).catch(()=>null)]).then(([J,U])=>{r(J.files),C(U),J.files.length>0&&!u&&(m(J.files[0].name),y(J.files[0].content))}).catch(()=>{}).finally(()=>d(!1))},[i]);n.useEffect(()=>{D()},[D]);const k=J=>{const U=s.find(ee=>ee.name===J);U&&(m(J),y(U.content),T(!1),H(null))},P=async()=>{if(u){O(!0);try{await M.agents.updateFile(i,u,f),r(J=>J.map(U=>U.name===u?{...U,content:f}:U)),T(!1),u==="ROLE.md"&&await M.agents.updateSystemPrompt(i,f)}catch{}O(!1)}},he=p?.files.filter(J=>J.status==="modified"||J.status==="added_in_template")??[],De=async J=>{const U=J?he.filter(q=>q.file===J):he;if(U.length===0)return;const ee=[];for(const q of U)try{const oe=await M.agents.roleDiff(i,q.file);oe.agentContent!=null&&oe.templateContent!=null&&ee.push(`## ${q.file}
|
|
22
|
-
|
|
23
|
-
**Template file path:** built-in template \`${p?.templateId??"unknown"}\`
|
|
24
|
-
|
|
25
|
-
**Key changes in the new template version:**
|
|
26
|
-
\`\`\`diff
|
|
27
|
-
`+nc(oe.agentContent,oe.templateContent)+"\n```\n")}catch{}if(ee.length===0)return;const g=`Your role configuration files have been updated in the latest template (\`${p?.templateId??""}\`). Please review the following changes and decide whether to update your files accordingly.
|
|
28
|
-
|
|
29
|
-
`+ee.join(`
|
|
30
|
-
---
|
|
31
|
-
|
|
32
|
-
`)+"\nPlease review each change and update your files if appropriate. You can use the `update_file` tool or ask me to apply the changes.";ps.navigate(xt.TEAM,{agentId:i,prefillMessage:g})},se=async J=>{if(A?.file===J){H(null);return}try{const U=await M.agents.roleDiff(i,J);U.agentContent!=null&&U.templateContent!=null&&H({file:J,agent:U.agentContent,template:U.templateContent})}catch{}};if(o)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:a("agent:profilePage.filesTab.loading")});const F={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},Me=J=>{const U=F[J];return U?a(`agent:profilePage.filesTab.fileLabels.${U}`):J},ue=p?.hasTemplate&&!p.isUpToDate,L=u?he.some(J=>J.file===u):!1;return e.jsxs("div",{className:"space-y-4",children:[ue&&e.jsxs("div",{className:"bg-amber-500/8 border border-amber-500/25 rounded-xl p-4 flex items-start gap-3",children:[e.jsx("span",{className:"text-amber-600 text-sm mt-0.5",children:"↻"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-amber-600 font-medium",children:a("agent:profilePage.filesTab.templateUpdateAvailable")}),e.jsxs("div",{className:"text-[11px] text-amber-600/70 mt-0.5",children:[a("agent:profilePage.filesTab.filesDiffer",{count:he.length,templateId:p.templateId})," ",he.map(J=>J.file).join(", ")]})]}),e.jsx("button",{onClick:()=>De(),className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors shrink-0",children:a("agent:profilePage.filesTab.sendToAgent")})]}),e.jsxs(it,{title:a("agent:profilePage.filesTab.agentConfigFiles"),action:p?.hasTemplate?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`inline-block w-1.5 h-1.5 rounded-full ${p.isUpToDate?"bg-green-400":"bg-amber-400"}`}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[a("agent:profilePage.filesTab.templateLabel")," ",e.jsx("span",{className:"text-fg-secondary",children:p.templateId}),p.isUpToDate?a("agent:profilePage.filesTab.upToDate"):a("agent:profilePage.filesTab.updatesAvailable")]})]}):e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:a("agent:profilePage.filesTab.customAgentNoTemplate")}),children:[e.jsx("div",{className:"flex gap-2 mb-4 flex-wrap",children:s.map(J=>{const U=he.some(ee=>ee.file===J.name);return e.jsxs("button",{onClick:()=>k(J.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${u===J.name?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:[J.name,U&&e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},J.name)})}),u&&e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-xs text-fg-secondary",children:Me(u)}),e.jsxs("div",{className:"flex gap-2 items-center",children:[L&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>se(u),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:A?.file===u?a("agent:profilePage.filesTab.hideDiff"):a("agent:profilePage.filesTab.viewDiff")}),e.jsx("button",{onClick:()=>De(u),className:"px-2.5 py-1 text-[11px] bg-brand-600 hover:bg-brand-500 text-white rounded-lg transition-colors",title:a("agent:profilePage.filesTab.sendToAgentTitle"),children:a("agent:profilePage.filesTab.sendToAgent")})]}),v&&e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a("common:saving")})]})]}),N&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 bg-surface-elevated/40 rounded-lg px-3 py-2",children:[e.jsxs("code",{className:"text-[10px] text-fg-tertiary font-mono flex-1 truncate select-all",title:`${N}/${u}`,children:[N,"/",u]}),e.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${N}/${u}`),b(!0),setTimeout(()=>b(!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-hover rounded-md transition-colors",title:a("agent:profilePage.filesTab.copyPath"),children:a(I?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),e.jsx("button",{onClick:()=>{M.system.openPath(N)},className:"shrink-0 px-2 py-1 text-[10px] text-fg-tertiary hover:text-fg-secondary border border-border-default hover:border-border-hover rounded-md transition-colors",title:a("agent:profilePage.filesTab.openInFinder"),children:a("agent:profilePage.filesTab.openInFinder")})]}),A?.file===u&&e.jsx(sc,{agent:A.agent,template:A.template,templateId:p?.templateId??""}),e.jsx(rc,{content:s.find(J=>J.name===u)?.content??"",editContent:f,setEditContent:J=>{y(J),T(!0)},dirty:E,onSave:P}),u==="ROLE.md"&&e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:a("agent:profilePage.filesTab.roleMdHint")})]}),s.length===0&&e.jsx(yr,{text:a("agent:profilePage.filesTab.noConfigFiles")})]})]})}function rc({content:i,editContent:a,setEditContent:s,dirty:r,onSave:o}){const[d,u]=n.useState(!1),m=n.useRef(null);return n.useEffect(()=>{d&&m.current?.focus()},[d]),n.useEffect(()=>{u(!1)},[i]),d||r?e.jsx("textarea",{ref:m,value:a,onChange:f=>s(f.target.value),onBlur:()=>{a!==i&&o(),u(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),s(i),u(!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}):e.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:()=>u(!0),role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&u(!0)},children:[e.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"}),a.trim()?e.jsx(n.Suspense,{fallback:e.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:e.jsx(ec,{content:a,className:"text-sm text-fg-secondary leading-relaxed"})}):e.jsx("div",{className:"text-sm text-fg-tertiary italic py-4 text-center",children:"Empty"})]})}const ac=[{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:"web",prefixes:["web_search","web_fetch","web_extract"]},{id:"multimodal",prefixes:["generate_image","text_to_speech","speech_to_text","generate_video"]},{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","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"]},{id:"packages",prefixes:["package_list","package_install","hub_search","hub_install","builder_list","builder_install","markus-hub__"]},{id:"communication",prefixes:["agent_send_message","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_save","memory_search","memory_list","memory_update","memory_update_longterm","memory_delete","recall_context","recall_activity","update_working_memory","clear_working_memory","update_notebook","clear_notebook"]},{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:"teamManager",prefixes:["team_list","team_status","team_update","team_start","team_stop","agent_update","agent_start","agent_stop"]},{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_"]}];function ic(i,a){const s=new Map,r=new Set;for(const{id:u,prefixes:m}of ac){const f=a(`agent:toolCategories.${u}`),y=i.filter(N=>!r.has(N.name)&&m.some(j=>N.name.startsWith(j)));y.length>0&&(s.set(f,y),y.forEach(N=>r.add(N.name)))}const o=i.filter(u=>!r.has(u.name));for(const u of o){const m=u.name.indexOf("__");if(m>0){const f=u.name.slice(0,m),y=a("agent:toolCategories.mcp",{server:f});s.has(y)||s.set(y,[]),s.get(y).push(u),r.add(u.name)}}const d=i.filter(u=>!r.has(u.name));return d.length>0&&s.set(a("agent:toolCategories.other"),d),[...s.entries()].map(([u,m])=>({category:u,tools:m}))}function oc(i){return i.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function lc({tools:i}){const{t:a}=Ge(["agent","common"]),s=ic(i,a);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"text-xs text-fg-tertiary",children:a("agent:profilePage.toolsTab.registeredCount",{count:i.length})}),s.map(r=>e.jsx(it,{title:`${r.category} (${r.tools.length})`,children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:r.tools.map(o=>{const d=il(o.name),u=a(`common:execution.tools.${d.key}`,{defaultValue:d.label}),m=o.name.includes("__"),f=m?o.name.split("__").pop():o.name,y=oc(o.description||"");return e.jsxs("div",{className:"flex items-start gap-2.5 px-3 py-2.5 rounded-lg bg-surface-elevated min-w-0",children:[e.jsx(ol,{name:d.iconName,size:15,className:"shrink-0 mt-0.5 text-fg-secondary"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-xs font-medium text-fg-primary truncate",children:u}),m&&e.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"})]}),f!==u&&e.jsx("div",{className:"text-[10px] font-mono text-fg-tertiary/70 truncate",children:f}),y&&e.jsx("div",{className:"text-[10px] text-fg-tertiary truncate mt-0.5",title:y,children:y})]})]},o.name)})})},r.category)),i.length===0&&e.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:a("agent:profilePage.toolsTab.noToolsRegistered")})]})}function cc({agent:i}){const{t:a}=Ge(["agent","common"]),s=i.proficiency??{},[r,o]=n.useState(null),[d,u]=n.useState(null),[m,f]=n.useState(!1),y=i.availableSkills??[],N=new Map;for(const E of y){const T=E.category||"custom";N.has(T)||N.set(T,[]),N.get(T).push(E)}const j=async E=>{if(r===E){o(null),u(null);return}o(E),f(!0);try{const T=await fetch(`/api/skills/${encodeURIComponent(E)}`);if(T.ok){const p=await T.json();u(p.skill)}else u(null)}catch{u(null)}f(!1)},I={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"},b=E=>{const T=s[E.name],p=T&&T.uses>0?Math.round(T.successes/T.uses*100):null,C=T&&e.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[a("agent:profilePage.skillsTab.usesStats",{uses:T.uses,successes:T.successes}),T.lastUsed&&a("agent:profilePage.skillsTab.lastUsed",{date:new Date(T.lastUsed).toLocaleDateString()})]}),A=r===E.name;return e.jsxs("div",{children:[e.jsxs("div",{className:`flex items-center gap-3 px-4 py-2.5 rounded-lg border cursor-pointer transition-all ${A?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>j(E.name),children:[e.jsx("span",{className:`text-sm transition-transform ${A?"rotate-90":""}`,children:"▶"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:E.name}),E.alwaysOn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-green-500/15 text-green-500",children:a("agent:profilePage.skillsTab.alwaysOn")}),E.builtIn&&!E.alwaysOn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-surface-overlay/40 text-fg-tertiary",children:a("agent:profilePage.skillsTab.builtIn")}),!E.builtIn&&e.jsx("span",{className:"px-1.5 py-0.5 rounded text-[9px] font-medium bg-brand-500/15 text-brand-400",children:a("agent:profilePage.skillsTab.installed")})]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 truncate",children:E.description}),C]}),p!==null&&e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx("div",{className:"w-16 h-1.5 bg-surface-overlay rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full rounded-full ${p>=80?"bg-green-400":p>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${p}%`}})}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[p,"%"]})]})]}),A&&e.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:m?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.skillsTab.loadingDetails")}):d?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:`px-2 py-0.5 rounded text-[10px] font-medium ${I[d.category]??I.custom}`,children:d.category}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",d.version]}),d.author&&e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a("agent:profilePage.skillsTab.byAuthor",{author:d.author})}),d.requiredPermissions?.map(H=>e.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:H},H))]}),d.description&&e.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:d.description}),d.tags&&d.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap",children:d.tags.map(H=>e.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",H]},H))}),(d.toolDetails??d.tools??[]).length>0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] text-fg-tertiary font-semibold uppercase tracking-wider mb-2",children:a("agent:profilePage.skillsTab.toolsHeading",{count:(d.toolDetails??d.tools??[]).length})}),e.jsx("div",{className:"space-y-1.5",children:(d.toolDetails??d.tools??[]).map(H=>e.jsxs("div",{className:"px-3 py-2 bg-surface-secondary/50 rounded border border-border-default/20",children:[e.jsx("div",{className:"text-xs font-medium text-brand-500",children:H.name}),H.description&&e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:H.description})]},H.name))})]})]}):e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.skillsTab.detailsUnavailable")})})]},E.name)},v=["development","productivity","browser","communication","devops","data","platform","custom"],O=[...N.entries()].sort((E,T)=>{const p=v.indexOf(E[0]),C=v.indexOf(T[0]);return(p===-1?999:p)-(C===-1?999:C)});return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsx("div",{className:"text-xs text-fg-tertiary",children:a("agent:profilePage.skillsTab.installedCount",{count:y.length})})}),O.map(([E,T])=>e.jsx(it,{title:e.jsxs("span",{className:"capitalize",children:[E," ",e.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",T.length,")"]})]}),children:e.jsx("div",{className:"space-y-2",children:T.map(p=>b(p))})},E)),y.length===0&&e.jsx(yr,{text:a("agent:profilePage.skillsTab.noSkills")})]})}function wi({tools:i,agent:a}){const{t:s}=Ge(["agent","common"]),[r,o]=n.useState("tools");return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex items-center gap-2 mb-2",children:["tools","skills"].map(d=>e.jsx("button",{onClick:()=>o(d),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${r===d?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:d==="tools"?`${s("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${i.length})`:`${s("agent:tabs.skills")} (${a.availableSkills?.length??0})`},d))}),r==="tools"?e.jsx(lc,{tools:i}):e.jsx(cc,{agent:a})]})}function ki({agentId:i}){const{t:a}=Ge(["agent","common"]),[s,r]=n.useState(null),[o,d]=n.useState(!0),[u,m]=n.useState("longterm"),[f,y]=n.useState(""),[N,j]=n.useState(""),[I,b]=n.useState(!1),[v,O]=n.useState(null),[E,T]=n.useState(null),[p,C]=n.useState([]),[A,H]=n.useState(!1),D=n.useCallback(()=>{d(!0),M.agents.getMemory(i).then(F=>{r(F),y(F.recentDailyLogs??""),j(F.longTermMemory??"")}).catch(()=>{}).finally(()=>d(!1))},[i]);n.useEffect(()=>{D()},[D]);const k=async()=>{b(!0),await M.agents.updateDailyMemory(i,f).catch(()=>{}),b(!1),D()},P=async()=>{b(!0),await M.agents.updateLongTermMemory(i,a("agent:profilePage.memoryTab.userEditedSource"),N).catch(()=>{}),b(!1),D()},he=f!==(s?.recentDailyLogs??""),De=N!==(s?.longTermMemory??"");if(o)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:a("agent:profilePage.memoryTab.loading")});if(!s)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:a("agent:profilePage.memoryTab.loadFailed")});const se=[{key:"longterm",label:"MEMORY.md"},{key:"entries",label:`Observations (${s.entries.length})`},{key:"sessions",label:a("agent:profilePage.memoryTab.sessions",{count:s.sessions.length})},{key:"daily",label:a("agent:profilePage.memoryTab.dailyLogs")}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"flex gap-2",children:se.map(F=>e.jsx("button",{onClick:()=>m(F.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${u===F.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:F.label},F.key))}),u==="entries"&&e.jsx(it,{title:a("agent:profilePage.memoryTab.recentEntries"),children:s.entries.length===0?e.jsx(yr,{text:a("agent:profilePage.memoryTab.noEntries")}):e.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:s.entries.map((F,Me)=>{const ue=v===Me;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>O(ue?null:Me),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:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium shrink-0 ${F.type==="fact"?"bg-blue-500/15 text-blue-600":F.type==="task"?"bg-green-500/15 text-green-600":F.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:F.type}),e.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${ue?"":"line-clamp-2"}`,children:F.content}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[F.importance!=null&&e.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${F.importance>=7?"bg-red-500/15 text-red-500":F.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",F.importance]}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(F.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:ue?"▲":"▼"})]})]}),ue&&e.jsxs("div",{className:"mx-3 mt-1 mb-2 p-3 bg-surface-elevated/30 rounded-lg border border-border-default/20",children:[e.jsx("pre",{className:"text-xs text-fg-secondary whitespace-pre-wrap font-mono leading-relaxed break-words",children:F.content}),e.jsxs("div",{className:"flex gap-3 mt-2 pt-2 border-t border-border-default/30 text-[10px] text-fg-tertiary",children:[e.jsxs("span",{children:[a("agent:profilePage.overview.labels.type"),": ",F.type]}),F.importance!=null&&e.jsxs("span",{children:[a("agent:profilePage.overview.labels.importance"),": ",F.importance]}),e.jsx("span",{children:new Date(F.timestamp).toLocaleString()})]})]})]},Me)})})}),u==="sessions"&&e.jsx(it,{title:a("agent:profilePage.memoryTab.chatSessions"),children:s.sessions.length===0?e.jsx(yr,{text:a("agent:profilePage.memoryTab.noSessions")}):e.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:s.sessions.map(F=>{const Me=E===F.id,ue=async()=>{if(Me){T(null),C([]);return}T(F.id),H(!0);try{const L=await M.agents.getMemorySession(i,F.id);C(L.messages)}catch{C([])}H(!1)};return e.jsxs("div",{children:[e.jsxs("button",{onClick:ue,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:[e.jsx("div",{className:"text-xs text-fg-secondary font-mono flex-1 truncate",children:F.id}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[F.messageCount," ",a("agent:profilePage.memoryTab.msgs")]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(F.updatedAt).toLocaleDateString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:Me?"▲":"▼"})]}),Me&&e.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:A?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.memoryTab.loadingMessages")}):p.length===0?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const L=new Map;for(const J of p)J.role==="tool"&&J.toolCallId&&L.set(J.toolCallId,J.content);return e.jsx("div",{className:"divide-y divide-gray-700/30",children:p.filter(J=>J.role!=="tool").map((J,U)=>e.jsxs("div",{className:"px-3 py-2",children:[(J.role==="user"||J.role==="system")&&e.jsxs("div",{children:[e.jsx("span",{className:`inline-block px-1.5 py-0.5 rounded text-[10px] font-medium mb-1 ${J.role==="user"?"bg-blue-500/15 text-blue-600":"bg-surface-overlay text-fg-secondary"}`,children:a(`agent:profilePage.memoryTab.roles.${J.role}`,{defaultValue:J.role})}),e.jsx("div",{className:"text-xs text-fg-secondary",children:e.jsx($n,{content:J.content,className:"text-xs text-fg-secondary"})})]}),J.role==="assistant"&&e.jsxs("div",{className:"space-y-1",children:[J.content&&e.jsxs("div",{children:[e.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:a("agent:profilePage.memoryTab.roles.assistant")}),e.jsx("div",{className:"text-xs text-fg-secondary",children:e.jsx($n,{content:J.content,className:"text-xs text-fg-secondary"})})]}),J.toolCalls&&J.toolCalls.length>0&&e.jsx("div",{className:"space-y-0.5",children:J.toolCalls.map(ee=>{let g;try{g=JSON.parse(ee.arguments)}catch{}const q={tool:ee.name,status:"done",args:g,result:L.get(ee.id)};return e.jsx(tl,{entry:{type:"tool",info:q}},ee.id)})})]})]},U))})})()})]},F.id)})})}),u==="daily"&&e.jsx(it,{title:a("agent:profilePage.memoryTab.dailyLogs"),action:he?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>y(s?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:cancel")}),e.jsx("button",{onClick:k,disabled:I,className:"text-xs text-brand-500",children:a(I?"common:saving":"common:save")})]}):null,children:e.jsx("textarea",{value:f,onChange:F=>y(F.target.value),placeholder:a("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"})}),u==="longterm"&&e.jsx(it,{title:a("agent:profilePage.memoryTab.longTermTitle"),action:De?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>j(s?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:cancel")}),e.jsx("button",{onClick:P,disabled:I,className:"text-xs text-brand-500",children:a(I?"common:saving":"common:save")})]}):null,children:e.jsx("textarea",{value:N,onChange:F=>j(F.target.value),placeholder:a("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 Ni({agentId:i,initialData:a}){const{t:s}=Ge(["agent","common"]),[r,o]=n.useState(a??null),[d,u]=n.useState(!a),[m,f]=n.useState([]),[y,N]=n.useState(null),[j,I]=n.useState(!1),[b,v]=n.useState(null),O=n.useCallback(()=>Promise.all([M.agents.getHeartbeat(i).then(o).catch(()=>{}),M.agents.getRecentActivities(i).then(A=>{f(A.activities.filter(H=>H.type==="heartbeat"))}).catch(()=>{})]),[i]);n.useEffect(()=>{u(!0),O().finally(()=>u(!1))},[O]),n.useEffect(()=>ze.on("agent:update",H=>{H.payload?.agentId===i&&O()}),[i,O]);const E=async()=>{I(!0),v(null);try{const A=await M.agents.triggerHeartbeat(i);v(A.message),setTimeout(()=>v(null),4e3),setTimeout(O,2e3)}catch(A){v(String(A).replace("Error: ",""))}I(!1)},T=async A=>{try{await M.agents.cancelWakeup(i,A),O()}catch{}};if(d)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:s("agent:profilePage.heartbeatTab.loading")});if(!r)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:s("agent:profilePage.heartbeatTab.noData")});const p=A=>A?A<1e3?`${A}ms`:A<6e4?`${(A/1e3).toFixed(1)}s`:`${(A/6e4).toFixed(1)}m`:null,C=A=>{if(!A)return null;const H=Date.now()-new Date(A).getTime();if(H<0){const D=Math.abs(H);return D<6e4?s("agent:profilePage.relative.inSeconds",{count:Math.ceil(D/1e3)}):D<36e5?s("agent:profilePage.relative.inMinutes",{count:Math.ceil(D/6e4)}):s("agent:profilePage.relative.inHours",{hours:(D/36e5).toFixed(1)})}return H<6e4?s("agent:profilePage.relative.secondsAgo",{count:Math.floor(H/1e3)}):H<36e5?s("agent:profilePage.relative.minutesAgo",{count:Math.floor(H/6e4)}):s("agent:profilePage.relative.hoursAgo",{hours:(H/36e5).toFixed(1)})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(it,{title:s("agent:profilePage.heartbeatTab.scheduler"),action:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:O,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:s("common:refresh")}),e.jsx("button",{onClick:E,disabled:j||!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:s(j?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsx(mt,{label:s("agent:profilePage.overview.labels.status"),value:r.running?s("agent:profilePage.heartbeatTab.running"):s("agent:profilePage.heartbeatTab.stopped"),color:r.running?"green":"gray"}),e.jsx(uc,{agentId:i,intervalMs:r.intervalMs,onChanged:O}),e.jsx(mt,{label:s("agent:profilePage.heartbeatTab.lastRun"),value:r.lastHeartbeat?C(r.lastHeartbeat)??s("agent:profilePage.emDash"):s("agent:profilePage.never")}),e.jsx(mt,{label:s("agent:profilePage.heartbeatTab.nextWake"),value:r.nextWakeAt?C(r.nextWakeAt)??s("agent:profilePage.emDash"):r.running?s("agent:profilePage.heartbeatTab.pending"):s("agent:profilePage.emDash")})]}),e.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:s("agent:profilePage.heartbeatTab.rhythmHint")}),b&&e.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:b})]}),r.wakeups&&r.wakeups.length>0&&e.jsx(it,{title:s("agent:profilePage.heartbeatTab.wakeupsTitle"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.wakeupsCount",{count:r.wakeups.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.wakeups.map(A=>e.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[e.jsx("span",{className:"text-sm shrink-0 opacity-60",children:"⏰"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary truncate",children:A.note||s("agent:profilePage.heartbeatTab.wakeupNoNote")}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[C(A.wakeAt)??new Date(A.wakeAt).toLocaleString(),A.recurringMs?` · ${s("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${A.deliveryMode==="in_session"?s("agent:profilePage.heartbeatTab.deliveryInSession"):s("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),e.jsx("button",{onClick:()=>T(A.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:s("agent:profilePage.heartbeatTab.cancelWakeup")})]},A.id))})}),r.pendingCallbacks&&r.pendingCallbacks.length>0&&e.jsx(it,{title:s("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.pendingOpsCount",{count:r.pendingCallbacks.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:r.pendingCallbacks.map(A=>e.jsxs("div",{className:"flex items-center gap-2.5 px-5 py-2.5",children:[e.jsx("span",{className:"text-sm shrink-0 opacity-60",children:A.type==="background_exec"?"⚙":"↔"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary truncate font-mono",children:A.label}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[s(`agent:profilePage.heartbeatTab.callbackType.${A.type}`),` · ${s("agent:profilePage.heartbeatTab.timesOut")} ${C(A.timeoutAt)??new Date(A.timeoutAt).toLocaleString()}`]})]})]},A.id))})}),r.lastSummary&&e.jsx(it,{title:s("agent:profilePage.heartbeatTab.lastSummary"),action:r.lastSummaryAt?e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(r.lastSummaryAt).toLocaleString()}):void 0,children:e.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:e.jsx($n,{content:r.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),m.length>0?e.jsx(it,{title:s("agent:profilePage.heartbeatTab.recentRuns"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.runsThisSession",{count:m.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...m].reverse().map(A=>{const H=y===A.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>N(H?null:A.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:[e.jsx("span",{className:"w-2 h-2 rounded-full shrink-0 bg-blue-400"}),e.jsx("span",{className:"text-xs text-fg-secondary flex-1 truncate",children:A.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:s("agent:profilePage.heartbeatTab.actionsCount",{count:A.logCount})}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(A.startedAt).toLocaleString()}),e.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${H?"rotate-180":""}`,viewBox:"0 0 12 12",fill:"currentColor",children:e.jsx("path",{d:"M3 4.5l3 3 3-3",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})})]}),H&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(Fn,{agentId:i,activityId:A.id})})]},A.id)})})}):r.lastHeartbeat?null:e.jsx(it,{title:s("agent:profilePage.heartbeatTab.recentRuns"),children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx("div",{className:"text-xl mb-2 opacity-40",children:"♡"}),e.jsx("p",{className:"text-xs text-fg-tertiary",children:s("agent:profilePage.heartbeatTab.noRunsYet")}),e.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:r.running?s("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:p(r.intervalMs-r.uptimeMs%r.intervalMs)??s("agent:profilePage.heartbeatTab.soon")}):s("agent:profilePage.heartbeatTab.schedulerStopped")}),r.running&&e.jsx("button",{onClick:E,disabled:j,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:s(j?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function dc({taskId:i,isLive:a}){const{t:s}=Ge("agent"),[r,o]=n.useState([]),[d,u]=n.useState(""),[m,f]=n.useState(!0),[y,N]=n.useState("compact");if(n.useEffect(()=>{f(!0),u(""),M.tasks.getLogs(i).then(b=>{o(b.logs),f(!1)}).catch(()=>f(!1))},[i]),n.useEffect(()=>{if(!a)return;const b=ze.on("task:log",O=>{const E=O.payload;if(E.taskId!==i)return;const T={id:E.id,taskId:E.taskId,agentId:E.agentId,seq:E.seq,type:E.logType,content:E.content,metadata:E.metadata,createdAt:E.createdAt};o(p=>T.id&&p.some(C=>C.id===T.id)?p:[...p,T]),T.type==="text"&&u("")}),v=ze.on("task:log:delta",O=>{const E=O.payload;E.taskId===i&&u(T=>T+E.text)});return()=>{b(),v()}},[i,a]),m)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:s("profilePage.taskLog.loading")});if(r.length===0&&!d)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:s("profilePage.taskLog.noLogs")});const j=r.map(b=>al(b)),I=new Set(j.filter(b=>b.executionRound!=null).map(b=>b.executionRound)).size>1;return e.jsx("div",{className:"px-3 py-2",children:y==="compact"?e.jsx(Vi,{entries:j,streamingText:d,isActive:a,onExpand:()=>N("full"),showRounds:I}):e.jsx(qi,{entries:j,streamingText:d,isActive:a,onCollapse:()=>N("compact"),showRounds:I})})}function Fn({agentId:i,activityId:a,isLive:s=!1}){const{t:r}=Ge("agent"),[o,d]=n.useState([]),[u,m]=n.useState(!0),[f,y]=n.useState("compact");if(n.useEffect(()=>{m(!0),M.agents.getActivityLogs(i,a).then(j=>{d(j.logs),m(!1)}).catch(()=>m(!1))},[i,a]),n.useEffect(()=>s?ze.on("agent:activity_log",I=>{const b=I.payload;if(b.agentId!==i||b.activityId!==a)return;const v={seq:b.seq,type:b.type,content:b.content,metadata:b.metadata,createdAt:b.createdAt};d(O=>O.some(E=>E.seq===v.seq)?O:[...O,v])}):void 0,[i,a,s]),u)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.loading")});if(o.length===0)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:r("profilePage.activityLog.noLogs")});const N=o.map(j=>rl(j,a,i)).filter(j=>j!==null);return e.jsx("div",{className:"px-3 py-2",children:f==="compact"?e.jsx(Vi,{entries:N,isActive:s,onExpand:()=>y("full")}):e.jsx(qi,{entries:N,isActive:s,onCollapse:()=>y("compact")})})}function it({title:i,action:a,children:s}){return e.jsxs("div",{className:"bg-surface-elevated rounded-xl p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider",children:i}),a]}),s]})}function At({label:i,mono:a,children:s}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i}),e.jsx("span",{className:`text-xs text-fg-secondary ${a?"font-mono text-[10px]":""}`,children:s})]})}function mt({label:i,value:a,color:s}){const r=s==="green"?"text-green-500":s==="blue"?"text-blue-400":s==="indigo"?"text-brand-500":s==="red"?"text-red-400":"text-fg-secondary";return e.jsxs("div",{className:"flex items-baseline gap-1.5",children:[e.jsx("span",{className:`text-sm font-semibold ${r}`,children:a}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i})]})}const Si=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Ci=5,Ti=1440;function uc({agentId:i,intervalMs:a,onChanged:s}){const{t:r}=Ge(["agent","common"]),[o,d]=n.useState(!1),[u,m]=n.useState(null),[f,y]=n.useState(!1),[N,j]=n.useState(String(Math.round(a/6e4))),I=p=>p%(3600*1e3)===0?r("agent:profilePage.heartbeatTab.intervalHours",{count:p/(3600*1e3)}):r("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(p/6e4)}),b=async p=>{d(!0),m(null);try{await M.agents.updateConfig(i,{heartbeatIntervalMs:p}),s()}catch(C){m(String(C).replace("Error: ",""))}d(!1)},v=p=>{if(p.target.value==="custom"){y(!0);return}y(!1),b(Number(p.target.value))},O=()=>{const p=Math.round(Number(N));if(!Number.isFinite(p)||p<Ci||p>Ti){m(r("agent:profilePage.heartbeatTab.intervalRangeHint"));return}b(p*60*1e3)},E=Si.includes(a),T=f||!E?"custom":String(a);return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.safetyNetInterval")}),e.jsxs("select",{value:T,onChange:v,disabled:o,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:[!E&&e.jsx("option",{value:String(a),children:I(a)}),Si.map(p=>e.jsx("option",{value:String(p),children:I(p)},p)),e.jsx("option",{value:"custom",children:r("agent:profilePage.heartbeatTab.intervalCustom")})]}),(f||!E)&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx("input",{type:"number",min:Ci,max:Ti,value:N,onChange:p=>j(p.target.value),disabled:o,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"}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r("agent:profilePage.heartbeatTab.intervalCustomUnit")}),e.jsx("button",{onClick:O,disabled:o,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(o?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),u&&e.jsx("span",{className:"text-[10px] text-red-400",children:u})]})}function yr({text:i}){return e.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:i})}function Mi(i){if(i===0)return"0 B";const a=["B","KB","MB","GB"],s=Math.min(Math.floor(Math.log(i)/Math.log(1024)),a.length-1),r=i/Math.pow(1024,s);return`${r<10?r.toFixed(1):Math.round(r)} ${a[s]}`}const Ei={0:"0",1:"1",2:"2",3:"3",4:"4"},Ai={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},mc={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"},xc={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},xr={system_event:"⚙",human_chat:"💬",task_comment:"💬",mention:"@",session_reply:"↩",task_status_update:"📋",a2a_message:"🔗",review_request:"👀",requirement_update:"📝",requirement_comment:"💬",daily_report:"📊",heartbeat:"♡",memory_consolidation:"🧠"},fc=["all","interaction","task","notification","system"],gc={interaction:["human_chat","a2a_message","mention"],task:["task_status_update","task_comment","requirement_comment","review_request","session_reply"],notification:["requirement_update"],system:["system_event","heartbeat","daily_report","memory_consolidation"]},hc={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"},pc={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 ca(i){const a=i.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(a?.[1]){const s=a[1].trim().replace(/\n/g," ");return s.length>80?s.slice(0,80)+"…":s}}function Ii(i,a){const s=i.payload,r=s?.summary??"",o=s?.content??"",d=i.metadata?.senderName;switch(i.sourceType){case"task_status_update":{const u=r.match(/^Task "(.+?)" status:/),m=r.match(/status:\s*(\S+)\s*→\s*(\S+)/),f=u?.[1]??r;if(m){const N=m[1],j=m[2],I=da(N,a),b=da(j,a),v=pc[j]??"text-fg-secondary";return{title:f,subtitle:a("agent:profilePage.mind.mailbox.statusArrow",{from:I,to:b}),badge:{label:b,color:v}}}const y=r.match(/^Task:\s*(.+)/);return y?{title:y[1]}:{title:f}}case"task_comment":{const u=r.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),m=ca(o);if(u){const f=m?a("agent:profilePage.mind.mailbox.commentFromAuthor",{author:u[2],text:m}):a("agent:profilePage.mind.mailbox.commentFrom",{name:u[2]});return{title:u[1],subtitle:f}}return{title:r}}case"requirement_update":{const u=r.match(/^Requirement "(.+?)"\s+(.*)/);return u?{title:u[1],subtitle:u[2]}:{title:r}}case"requirement_comment":{const u=r.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),m=ca(o);if(u){const f=m?a("agent:profilePage.mind.mailbox.commentFromAuthor",{author:u[2],text:m}):a("agent:profilePage.mind.mailbox.commentFrom",{name:u[2]});return{title:u[1],subtitle:f}}return{title:r}}case"human_chat":{const u=o.slice(0,120).replace(/\n/g," ");return{title:d?a("agent:profilePage.mind.mailbox.chatFrom",{sender:d}):a("agent:profilePage.mind.mailbox.humanChat"),subtitle:u+(o.length>120?"…":"")}}case"a2a_message":{const u=o.slice(0,120).replace(/\n/g," ");return{title:d?a("agent:profilePage.mind.mailbox.messageFrom",{sender:d}):a("agent:profilePage.mind.mailbox.agentMessage"),subtitle:u+(o.length>120?"…":"")}}case"mention":{const u=r.match(/from (.+)$/),m=ca(o);return{title:u?a("agent:profilePage.mind.mailbox.mentionedBy",{name:u[1]}):a("agent:profilePage.mind.mailbox.mention"),subtitle:m||void 0}}case"review_request":{const u=o.slice(0,120).replace(/\n/g," ");return{title:d?a("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:d}):a("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:u+(o.length>120?"…":"")}}case"session_reply":{const u=o.slice(0,120).replace(/\n/g," ");return{title:d?a("agent:profilePage.mind.mailbox.replyInSession",{sender:d}):a("agent:profilePage.mind.mailbox.sessionReply"),subtitle:u+(o.length>120?"…":"")}}case"heartbeat":return{title:a("agent:profilePage.mind.mailbox.scheduledHeartbeat")};case"daily_report":return{title:a("agent:profilePage.mind.mailbox.dailyReport")};case"memory_consolidation":return{title:a("agent:profilePage.mind.mailbox.memoryConsolidation")};case"system_event":{const u=r.match(/^\[Announcement]\s*(.+)/);return u?{title:u[1],subtitle:a("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:r||a("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:r||i.sourceType}}}function Pi({agentId:i,highlightId:a,agentStatus:s,canManageAgents:r,onAgentStateChange:o}){const{t:d}=Ge(["agent","common","team"]),[u,m]=n.useState(null),[f,y]=n.useState(null),[N,j]=n.useState(!0),[I,b]=n.useState("all"),[v,O]=n.useState("all"),[E,T]=n.useState(a??null),[p,C]=n.useState(a??null),[A,H]=n.useState(!1),[D,k]=n.useState(!0),[P,he]=n.useState(null),De=50,se=3,F=n.useCallback(async(g=!0)=>{g&&j(!0);try{const q=I==="all"?void 0:I,oe=v==="all"?void 0:v,[be,ge]=await Promise.all([M.agents.getMindState(i),M.agents.getMailbox(i,{limit:De,category:q,status:oe})]);m(be),y(ge),k((ge.history?.length??0)>=De)}catch{}j(!1)},[i,I,v]),Me=n.useCallback(async()=>{if(!f)return;const g=I==="all"?void 0:I,q=v==="all"?void 0:v;try{const oe=await M.agents.getMailbox(i,{limit:De,offset:f.history.length,category:g,status:q});y(be=>be?{...be,history:[...be.history,...oe.history]}:oe),k((oe.history?.length??0)>=De)}catch{}},[i,f,I,v]);n.useEffect(()=>{T(a??null),C(a??null),F()},[F,a]);const ue=n.useRef(!1);if(n.useEffect(()=>{if(!p||N)return;if(f?.history?.some(q=>q.id===p)){ue.current=!1;const q=document.getElementById(`mbx-${p}`);if(q){setTimeout(()=>q.scrollIntoView({behavior:"smooth",block:"center"}),100);const oe=setTimeout(()=>C(null),3e3);return()=>clearTimeout(oe)}}else D&&!ue.current&&(ue.current=!0,(async()=>{let q=f?.history??[],oe=D;for(;oe;)try{const be=await M.agents.getMailbox(i,{limit:De,offset:q.length}),ge=[...q,...be.history];q=ge,oe=(be.history?.length??0)>=De;const ye=be.history.some(Xe=>Xe.id===p);if(y(Xe=>Xe?{...Xe,history:ge}:be),k(oe),ye||!oe)break}catch{break}ue.current=!1})())},[p,N,f,D,i]),n.useEffect(()=>{let g=null;const q=be=>{be.payload?.agentId===i&&(g&&clearTimeout(g),g=setTimeout(()=>{g=null,F(!1)},500))},oe=[ze.on("agent:mailbox",q),ze.on("agent:decision",q),ze.on("agent:attention",q),ze.on("agent:focus",q),ze.on("agent:update",q),ze.on("agent:triage",q)];return()=>{g&&clearTimeout(g),oe.forEach(be=>be())}},[i,F]),N&&!u)return e.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:d("agent:profilePage.mind.loading")});const L=u?.mailboxDepth??u?.queuedItems?.length??0,J=(()=>{const g=u?.attentionState??"idle";return g==="deciding"||g==="idle"&&L>0?"deciding":g!=="idle"&&!u?.currentFocus?"idle":g})(),U=J==="idle"&&f?.history?.some(g=>g.status==="processing"),ee=(u?.attentionState??"idle")==="idle"&&L>0;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("span",{className:`px-2.5 py-1 text-xs font-medium rounded-full ${xc[J]??"bg-gray-500/20 text-gray-500"}`,children:d(`agent:profilePage.mind.attention.${J}`)}),u?.currentFocus?(()=>{const g=Ii({id:u.currentFocus.mailboxItemId,sourceType:u.currentFocus.type,payload:{summary:u.currentFocus.label,taskId:u.currentFocus.taskId},metadata:{},queuedAt:u.currentFocus.startedAt},d);return e.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[e.jsxs("span",{children:[xr[u.currentFocus.type]??"●"," ",e.jsx("span",{className:"text-fg-primary font-medium",children:g.title}),g.subtitle&&e.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:g.subtitle}),e.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:d("agent:profilePage.mind.since",{time:new Date(u.currentFocus.startedAt).toLocaleTimeString()})})]}),r&&e.jsxs("button",{onClick:()=>he(u.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:["✕ ",d("agent:profilePage.mind.cancelCurrentBtn")]})]})})():ee?e.jsx("span",{className:"text-sm text-amber-500",children:d("agent:profilePage.mind.queuedButIdle",{count:L,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):J==="deciding"?e.jsx("span",{className:"text-sm text-amber-500",children:d("agent:profilePage.mind.decidingWaiting",{count:L})}):e.jsx("span",{className:"text-sm text-fg-tertiary",children:d("agent:profilePage.mind.idleWaiting")}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[r&&s==="offline"&&e.jsxs("button",{onClick:()=>{M.agents.start(i).then(()=>{o?.(),F()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-green-500/15 text-green-500 hover:bg-green-500/25 transition-colors",children:["▶ ",d("agent:profilePage.mind.continueBtn")]}),r&&(s==="working"||s==="idle")&&e.jsxs("button",{onClick:()=>{M.agents.stop(i).then(()=>{o?.(),F()})},className:"px-2.5 py-1 text-[11px] font-medium rounded-lg bg-red-500/15 text-red-500 hover:bg-red-500/25 transition-colors",children:["■ ",d("team:contextMenu.stop")]}),e.jsx("button",{onClick:()=>{F()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:d("agent:profilePage.mind.refresh")})]})]}),U&&e.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:[e.jsx("span",{className:"text-amber-500 text-sm",children:"⚠"}),e.jsx("span",{className:"text-[11px] text-amber-600",children:d("agent:profilePage.mind.staleProcessingWarning")})]}),(u?.queuedItems?.length??0)>0&&(()=>{const g=u.queuedItems,q=g.length>se,oe=q&&!A?g.slice(0,se):g,be=g.reduce((ge,ye)=>(ge[ye.sourceType]=(ge[ye.sourceType]??0)+1,ge),{});return e.jsxs("div",{className:"mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5",children:[e.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:d("agent:profilePage.mind.queue",{count:g.length})}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(be).map(([ge,ye])=>e.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[xr[ge]??"●"," ",ye]},ge))})]}),e.jsxs("div",{className:"space-y-1",children:[oe.map((ge,ye)=>e.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:[e.jsx("span",{className:"text-fg-tertiary w-4 text-right text-xs",children:ye+1}),e.jsx("span",{className:"text-sm",children:xr[ge.sourceType]??"●"}),e.jsx("span",{className:`text-[10px] ${Ai[ge.priority]??"text-fg-tertiary"}`,children:d(`agent:profilePage.mind.priority.${Ei[ge.priority]??ge.priority}`,{defaultValue:`P${ge.priority}`})}),e.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:ge.summary}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(ge.queuedAt).toLocaleTimeString()})]},ge.id)),q&&e.jsx("button",{onClick:()=>H(!A),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:A?d("agent:profilePage.mind.collapseQueue"):d("agent:profilePage.mind.expandQueue",{count:g.length-se})})]})]})})()]}),(u?.notebook?.length??0)>0&&e.jsx("section",{className:"bg-surface-2 rounded-lg border border-border-subtle p-3",children:e.jsxs("details",{open:!0,children:[e.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[e.jsx("span",{className:"text-sm",children:"📓"}),e.jsx("h4",{className:"text-xs font-medium text-fg-secondary uppercase tracking-wider",children:"Notebook"}),e.jsxs("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:[u.notebook.length," ",u.notebook.length===1?"entry":"entries"]})]}),e.jsx("div",{className:"mt-2 space-y-2",children:u.notebook.map(g=>{const q=Date.now()-g.updatedAt,oe=q<6e4?`${Math.round(q/1e3)}s ago`:q<36e5?`${Math.round(q/6e4)}min ago`:`${(q/36e5).toFixed(1)}h ago`,be=g.managed==="system"?"text-blue-400":g.managed==="cpp"?"text-purple-400":"text-emerald-400";return e.jsxs("div",{className:"px-3 py-2 rounded bg-surface-3 border border-border-subtle",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"text-xs font-medium text-fg-primary",children:g.key}),e.jsxs("span",{className:`text-[10px] ${be}`,children:["[",g.managed,"]"]}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:oe})]}),e.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:g.text.length>500?g.text.slice(0,500)+"…":g.text})]},g.key)})})]})}),u?.deliberationActivity&&e.jsxs("section",{className:"bg-surface-2 rounded-lg border border-amber-500/20 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-sm",children:"🧠"}),e.jsx("h4",{className:"text-xs font-medium text-amber-500 uppercase tracking-wider",children:d("agent:profilePage.mind.deliberationInProgress")}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:d("agent:profilePage.mind.since",{time:new Date(u.deliberationActivity.startedAt).toLocaleTimeString()})})]}),e.jsx(Fn,{agentId:i,activityId:u.deliberationActivity.activityId,isLive:!0})]}),u?.lastTriage&&(()=>{const q=Date.now()-new Date(u.lastTriage.timestamp).getTime()>6e4;return e.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${q?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:e.jsxs("details",{open:!q,children:[e.jsxs("summary",{className:"flex items-center gap-2 cursor-pointer list-none",children:[e.jsx("span",{className:"text-sm",children:"🧠"}),e.jsx("h4",{className:"text-xs font-medium text-indigo-400 uppercase tracking-wider",children:d("agent:profilePage.mind.triageDecision")}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(u.lastTriage.timestamp).toLocaleTimeString()})]}),e.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:u.lastTriage.reasoning}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-2 text-[10px]",children:[e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-green-500/10 text-green-400",children:d("agent:profilePage.mind.processingItem",{id:u.lastTriage.processedItemId.slice(0,12)})}),u.lastTriage.deferredItemIds.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:d("agent:profilePage.mind.deferred",{count:u.lastTriage.deferredItemIds.length})}),u.lastTriage.droppedItemIds.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:d("agent:profilePage.mind.dropped",{count:u.lastTriage.droppedItemIds.length})}),(u.lastTriage.inlineCompletedIds?.length??0)>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:d("agent:profilePage.mind.inlineCompleted",{count:u.lastTriage.inlineCompletedIds.length})})]})]})})})(),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("h3",{className:"text-xs font-medium text-fg-tertiary uppercase tracking-wider",children:d("agent:profilePage.mind.mailboxHistory")}),e.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:fc.map(g=>{const q=f?.sourceTypeCounts,oe=g==="all"?q?Object.values(q).reduce((be,ge)=>be+ge,0):void 0:q?(gc[g]??[]).reduce((be,ge)=>be+(q[ge]??0),0):void 0;return e.jsxs("button",{onClick:()=>b(g),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${I===g?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[d(`agent:profilePage.mind.categoryFilters.${g}`),oe!=null&&oe>0&&e.jsx("span",{className:"ml-1 opacity-60",children:oe})]},g)})})]}),e.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(g=>{const q=f?.statusCounts,oe=g.key==="all"?q?Object.values(q).reduce((be,ge)=>be+ge,0):void 0:q?.[g.key];return e.jsxs("button",{onClick:()=>O(g.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${v===g.key?"bg-brand-500/20 border-brand-500/40 text-brand-300":"bg-surface-2 border-border-subtle text-fg-secondary hover:bg-surface-3"}`,children:[g.dot&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${g.dot}`}),d(`agent:profilePage.mind.statusFilters.${g.key}`),oe!=null&&oe>0&&e.jsx("span",{className:"ml-1 opacity-60",children:oe})]},g.key)})}),(!f?.history||f.history.length===0)&&!N&&e.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:d("agent:profilePage.mind.noHistory")}),e.jsx("div",{className:"space-y-1",children:f?.history?.map(g=>{const q=E===g.id,oe=xr[g.sourceType]??"●",be=Ii(g,d),ge=g.metadata?.senderName,ye=g.metadata?.senderRole,Xe=p===g.id;return e.jsxs("div",{id:`mbx-${g.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${Xe?"border-brand-500 ring-1 ring-brand-500/40":"border-border-subtle"}`,children:[e.jsxs("button",{className:"w-full px-3 py-2.5 flex items-start gap-2 text-left hover:bg-surface-3/50 transition-colors rounded-lg",onClick:()=>T(q?null:g.id),children:[e.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:q?"▾":"▸"}),e.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${hc[g.status]??"bg-gray-400"}`}),e.jsx("span",{className:"text-sm",children:oe}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-xs font-medium text-fg-primary ${q?"":"truncate"}`,children:be.title}),be.badge&&e.jsx("span",{className:`text-[10px] font-medium shrink-0 ${be.badge.color}`,children:be.badge.label}),e.jsx("span",{className:`text-[10px] shrink-0 ${Ai[g.priority]??"text-fg-tertiary"}`,children:d(`agent:profilePage.mind.priority.${Ei[g.priority]??g.priority}`,{defaultValue:""})})]}),be.subtitle&&e.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${q?"":"truncate"}`,children:be.subtitle}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5 flex gap-2 flex-wrap",children:[e.jsx("span",{children:new Date(g.queuedAt).toLocaleString()}),g.completedAt&&e.jsxs("span",{children:["→ ",new Date(g.completedAt).toLocaleTimeString()]}),g.activity&&e.jsxs(e.Fragment,{children:[g.activity.totalTokens>0&&e.jsx("span",{children:d("agent:profilePage.mind.tokensCount",{count:dn(g.activity.totalTokens)})}),g.activity.totalTools>0&&e.jsx("span",{children:d("agent:profilePage.mind.toolsCount",{count:g.activity.totalTools})})]})]})]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:g.sourceType}),r&&g.status==="processing"&&e.jsxs("button",{onClick:et=>{et.stopPropagation(),he(g.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:["✕ ",d("agent:profilePage.mind.cancelCurrentBtn")]})]}),q&&e.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[ge&&e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[d("agent:profilePage.mind.from")," ",e.jsx("span",{className:"text-fg-secondary",children:ge}),ye&&e.jsxs("span",{className:"text-fg-tertiary",children:[" (",ye,")"]})]}),g.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(g.sourceType)&&e.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:g.payload.content}),g.decisions&&g.decisions.length>0&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:d("agent:profilePage.mind.decisions")}),e.jsx("div",{className:"space-y-1",children:g.decisions.map(et=>e.jsxs("div",{className:"flex items-start gap-2 text-xs",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded shrink-0 ${mc[et.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:et.decisionType}),e.jsx("span",{className:"text-fg-secondary flex-1",children:et.reasoning}),e.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(et.createdAt).toLocaleTimeString()})]},et.id))})]}),g.activity?e.jsxs("div",{children:[e.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[d("agent:profilePage.mind.activityHeading",{label:g.activity.label}),e.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${g.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:g.activity.success?d("agent:profilePage.mind.success"):d("agent:profilePage.mind.failed")})]}),g.activity.type==="task"&&g.payload?.taskId?e.jsx(dc,{taskId:g.payload.taskId,isLive:!g.activity.endedAt}):e.jsx(Fn,{agentId:i,activityId:g.activity.id,isLive:!g.activity.endedAt})]}):g.status==="processing"?e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:d("agent:profilePage.mind.processing")}):g.status==="completed"?e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:d("agent:profilePage.mind.noActivityLog")}):null]})]},g.id)})}),D&&(f?.history?.length??0)>0&&e.jsx("div",{className:"text-center mt-3",children:e.jsx("button",{onClick:Me,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:d("agent:profilePage.mind.loadEarlier")})})]}),P&&e.jsx(Bn,{title:d("agent:profilePage.mind.cancelConfirmTitle"),message:d("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:d("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{he(null),M.agents.cancelProcessing(i).then(()=>{let g=0;const q=()=>{g+=1,F(),g<8&&window.setTimeout(q,750)};q()}).catch(()=>{F()})},onCancel:()=>he(null)})]})}function Li({agentId:i}){const{t:a}=Ge(["agent","common"]),[s,r]=n.useState([]),[o,d]=n.useState(!0),[u,m]=n.useState(null),f=n.useCallback(async()=>{d(!0);try{const{results:y}=await M.deliverables.search({agentId:i,limit:200});r(y)}catch{r([])}d(!1)},[i]);return n.useEffect(()=>{f()},[f]),n.useEffect(()=>{const y=ze.on("deliverable:created",()=>f()),N=ze.on("deliverable:updated",()=>f()),j=ze.on("deliverable:removed",()=>f());return()=>{y(),N(),j()}},[f]),o?e.jsx("div",{className:"space-y-3 py-4",children:[1,2,3].map(y=>e.jsxs("div",{className:"animate-pulse space-y-2",children:[e.jsx("div",{className:"h-4 bg-surface-elevated rounded w-3/4"}),e.jsx("div",{className:"h-3 bg-surface-elevated rounded w-1/2"})]},y))}):s.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("span",{className:"text-3xl mb-3",children:"📦"}),e.jsx("p",{className:"text-sm text-fg-secondary",children:a("agent:deliverables.empty")}),e.jsx("p",{className:"text-xs text-fg-tertiary mt-1",children:a("agent:deliverables.emptyHint")})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-3",children:a("agent:deliverables.count",{count:s.length})}),s.map(y=>{const N=sl[y.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},j=Ja[y.status]??Ja.active;return e.jsxs("button",{onClick:()=>m(y),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:[e.jsx("span",{className:`inline-flex items-center justify-center w-8 h-8 rounded-lg text-sm shrink-0 ${N.color}`,children:N.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary truncate",children:y.title}),e.jsx("span",{className:`px-1.5 py-0.5 text-[10px] rounded font-medium ${j.color}`,children:y.status})]}),y.summary&&e.jsx("p",{className:"text-xs text-fg-tertiary mt-0.5 line-clamp-1",children:y.summary}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-[10px] text-fg-tertiary",children:[e.jsx("span",{children:new Date(y.createdAt).toLocaleDateString()}),y.tags.length>0&&e.jsx("span",{children:y.tags.slice(0,3).join(", ")})]})]}),e.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:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})})]},y.id)})]}),u&&e.jsx(nl,{item:u,onClose:()=>m(null),onOpenInPage:y=>{m(null),ps.navigate(xt.DELIVERABLES,{openDeliverable:y})}})]})}const bc=n.lazy(()=>Ui(()=>import("./index-BVZKeNvh.js").then(i=>i.az),__vite__mapDeps([0,1])).then(i=>({default:i.MarkdownMessage}))),fa=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],_i={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function Ri({teamId:i,onBack:a,inline:s,headless:r,activeTab:o,onSelectAgent:d}){const{t:u}=Ge("team"),[m,f]=n.useState(null),[y,N]=n.useState(null),[j,I]=n.useState("overview"),b=r&&o?o:j,[v,O]=n.useState(""),[E,T]=n.useState(""),[p,C]=n.useState(!1),[A,H]=n.useState(!1),[D,k]=n.useState(""),[P,he]=n.useState(""),De=n.useRef(null),se=n.useRef(null),F=n.useRef(null),Me=n.useRef(null),[ue,L]=n.useState(!1),[J,U]=n.useState(!1),[ee,g]=n.useState(""),[q,oe]=n.useState(""),[be,ge]=n.useState(!1),[ye,Xe]=n.useState([]),et=n.useRef(null),Yt=n.useCallback(async()=>{try{const We=(await M.teams.list()).teams.find(Fe=>Fe.id===i);We&&f(We);const qe=await M.teams.status(i);Xe(qe.agents)}catch{}},[i]),bs=n.useCallback(async()=>{try{const ae=await M.teams.getFile(i,"ANNOUNCEMENT.md");O(ae.content)}catch{O("")}try{const ae=await M.teams.getFile(i,"NORMS.md");T(ae.content)}catch{T("")}},[i]);n.useEffect(()=>{I("overview"),Yt(),bs()},[i,Yt,bs]),n.useEffect(()=>{p&&se.current&&se.current.focus()},[p]),n.useEffect(()=>{A&&Me.current&&Me.current.focus()},[A]);const Ht=async(ae,We)=>{L(!0);try{await M.teams.updateFile(i,ae,We),ae==="ANNOUNCEMENT.md"?(O(We),C(!1)):(T(We),H(!1))}catch{}L(!1)},as=async()=>{ee.trim()&&(await M.teams.update(i,{name:ee.trim()}),U(!1),Yt())},ys=async()=>{await M.teams.update(i,{description:q}),ge(!1),Yt()};if(!m)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:"Loading team..."});const Ys=m.members.find(ae=>ae.agentRole==="manager"),Xt=ye.filter(ae=>ae.status!=="offline").length,jt=b==="announcements"&&p||b==="norms"&&A;if(r)return e.jsx("div",{className:`flex-1 bg-surface-primary ${jt?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:e.jsxs("div",{className:`${jt?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[b==="overview"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),e.jsx("div",{className:"text-sm font-medium",children:Ys?.name??m.managerName??"None"})]}),e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),e.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:m.id})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),m.members.map(ae=>{const We=ye.find(wt=>wt.id===ae.id),qe=_i[We?.status??"offline"]??"bg-gray-500",Fe=ae.type==="agent";return e.jsxs("div",{onClick:()=>Fe&&d?.(ae.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Fe&&d?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[e.jsx(vt,{name:ae.name,avatarUrl:ae.avatarUrl,size:32,className:"rounded-lg"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:ae.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${qe}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:We?.status??"offline"}),ae.agentRole==="manager"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[ae.role," · ",ae.type]})]}),Fe&&d&&e.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:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]},ae.id)}),m.members.length===0&&e.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),b==="announcements"&&e.jsx(fr,{content:v,draft:D,setDraft:k,editing:p,setEditing:C,textareaRef:se,contentRef:De,saving:ue,onSave:()=>Ht("ANNOUNCEMENT.md",D),placeholder:u("teamProfile.annPlaceholder"),emptyText:u("teamProfile.noAnnouncements")}),b==="norms"&&e.jsx(fr,{content:E,draft:P,setDraft:he,editing:A,setEditing:H,textareaRef:Me,contentRef:F,saving:ue,onSave:()=>Ht("NORMS.md",P),placeholder:u("teamProfile.normsPlaceholder"),emptyText:u("teamProfile.noNorms")}),b==="settings"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),J?e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{ref:et,value:ee,onChange:ae=>g(ae.target.value),onKeyDown:ae=>ae.key==="Enter"&&as(),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}),e.jsx("button",{onClick:as,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:m.name}),e.jsx("button",{onClick:()=>{g(m.name),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),be?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:q,onChange:ae=>oe(ae.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}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:ys,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>ge(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-fg-secondary",children:m.description||"No description"}),e.jsx("button",{onClick:()=>{oe(m.description??""),ge(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),e.jsx(Di,{teamId:i,teamName:m.name,onDeleted:a})]})]})});const ft=j==="announcements"&&p||j==="norms"&&A;return e.jsxs("div",{className:`flex-1 bg-surface-primary ${ft?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:[e.jsxs("div",{className:"px-5 py-3.5 bg-surface-secondary sticky top-0 z-10 shrink-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.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:e.jsxs("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h2",{className:"text-base font-semibold",children:m.name}),e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-brand-500/15 text-brand-500 rounded font-medium",children:[m.members.length," members"]}),e.jsxs("span",{className:"px-1.5 py-0.5 text-[10px] bg-green-500/15 text-green-600 rounded font-medium",children:[Xt," online"]})]}),e.jsx("div",{className:"text-xs text-fg-tertiary truncate",children:m.description||"No description"})]}),e.jsxs("button",{onClick:async()=>{if(m)try{const{files:ae}=await M.teams.getFilesMap(m.id),We=m.members.filter(Fe=>Fe.type==="agent"),qe={type:"team",name:Wi(m.name,m.name),displayName:m.name,version:"1.0.0",description:m.description??"",author:"",category:"general",tags:[],team:{members:We.map(Fe=>({name:Fe.name,roleName:Fe.role,role:Fe.agentRole??"worker",count:1,skills:[]}))}};await Hi.publishViaProxy({itemType:"team",name:m.name,description:m.description??"",category:"general",config:qe,files:ae}),N({title:"Hub",message:`Published "${m.name}" to Markus Hub`,variant:"primary"})}catch(ae){N({title:"Hub",message:`Failed to publish: ${ae}`,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:[e.jsx("span",{children:"↑"})," Hub"]}),s&&e.jsx("button",{onClick:a,className:"p-1.5 text-fg-tertiary hover:text-fg-secondary text-lg leading-none",children:"×"})]}),e.jsx("div",{className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto",children:fa.map(ae=>e.jsxs("button",{onClick:()=>I(ae.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${j===ae.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[ae.icon," ",u(ae.labelKey)]},ae.key))})]}),e.jsxs("div",{className:`${ft?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[j==="overview"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Manager"}),e.jsx("div",{className:"text-sm font-medium",children:Ys?.name??m.managerName??"None"})]}),e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default",children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team ID"}),e.jsx("div",{className:"text-sm font-mono text-fg-secondary truncate",children:m.id})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-xs text-fg-tertiary font-medium px-1",children:"Members"}),m.members.map(ae=>{const We=ye.find(wt=>wt.id===ae.id),qe=_i[We?.status??"offline"]??"bg-gray-500",Fe=ae.type==="agent";return e.jsxs("div",{onClick:()=>Fe&&d?.(ae.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${Fe&&d?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[e.jsx(vt,{name:ae.name,avatarUrl:ae.avatarUrl,size:32,className:"rounded-lg"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:ae.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${qe}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:We?.status??"offline"}),ae.agentRole==="manager"&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 bg-amber-500/15 text-amber-600 rounded font-medium",children:"Manager"})]}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[ae.role," · ",ae.type]})]}),Fe&&d&&e.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:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]},ae.id)}),m.members.length===0&&e.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),j==="announcements"&&e.jsx(fr,{content:v,draft:D,setDraft:k,editing:p,setEditing:C,textareaRef:se,contentRef:De,saving:ue,onSave:()=>Ht("ANNOUNCEMENT.md",D),placeholder:u("teamProfile.annPlaceholder"),emptyText:u("teamProfile.noAnnouncements")}),j==="norms"&&e.jsx(fr,{content:E,draft:P,setDraft:he,editing:A,setEditing:H,textareaRef:Me,contentRef:F,saving:ue,onSave:()=>Ht("NORMS.md",P),placeholder:u("teamProfile.normsPlaceholder"),emptyText:u("teamProfile.noNorms")}),j==="settings"&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-border-default space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Team Name"}),J?e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{ref:et,value:ee,onChange:ae=>g(ae.target.value),onKeyDown:ae=>ae.key==="Enter"&&as(),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}),e.jsx("button",{onClick:as,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>U(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:m.name}),e.jsx("button",{onClick:()=>{g(m.name),U(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-fg-tertiary mb-1",children:"Description"}),be?e.jsxs("div",{className:"space-y-2",children:[e.jsx("textarea",{value:q,onChange:ae=>oe(ae.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}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:ys,className:"px-3 py-1.5 text-xs bg-brand-600 hover:bg-brand-500 rounded-lg text-white",children:"Save"}),e.jsx("button",{onClick:()=>ge(!1),className:"px-3 py-1.5 text-xs bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary",children:"Cancel"})]})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-fg-secondary",children:m.description||"No description"}),e.jsx("button",{onClick:()=>{oe(m.description??""),ge(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),e.jsx(Di,{teamId:i,teamName:m.name,onDeleted:a})]})]}),y&&e.jsx(Bn,{alertOnly:!0,variant:y.variant??"primary",title:y.title,message:y.message,onConfirm:()=>N(null),onCancel:()=>N(null)})]})}function fr({content:i,draft:a,setDraft:s,editing:r,setEditing:o,textareaRef:d,contentRef:u,saving:m,onSave:f,placeholder:y,emptyText:N}){return r?e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx("textarea",{ref:d,value:a,onChange:j=>s(j.target.value),onBlur:()=>{a!==i?f():o(!1)},onKeyDown:j=>{j.key==="Escape"&&(j.preventDefault(),s(i),o(!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:y}),m&&e.jsx("div",{className:"text-xs text-fg-tertiary mt-1 shrink-0",children:"Saving..."})]}):e.jsx("div",{ref:u,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{s(i),o(!0)},role:"button",tabIndex:0,onKeyDown:j=>{j.key==="Enter"&&(s(i),o(!0))},children:i.trim()?e.jsx(n.Suspense,{fallback:e.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:e.jsx(bc,{content:i,className:"text-sm text-fg-secondary leading-relaxed"})}):e.jsx("div",{className:"text-sm text-fg-tertiary italic",children:N})})}function Di({teamId:i,teamName:a,onDeleted:s}){const[r,o]=n.useState(!1),[d,u]=n.useState(!1),[m,f]=n.useState(!1),[y,N]=n.useState(!1);return e.jsxs("div",{className:"p-4 bg-surface-secondary rounded-xl border border-red-900/30 space-y-3",children:[e.jsx("div",{className:"text-sm font-medium text-red-500",children:"Danger Zone"}),r?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-xs text-fg-secondary",children:['Delete team "',a,'"? This removes the team record from the database.']}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:m,onChange:j=>f(j.target.checked),className:"rounded"}),"Also delete all members in this team"]}),e.jsxs("label",{className:"flex items-center gap-2 text-xs text-fg-secondary cursor-pointer",children:[e.jsx("input",{type:"checkbox",checked:d,onChange:j=>u(j.target.checked),className:"rounded"}),"Also delete disk files (workspace, memory, logs)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{disabled:y,onClick:async()=>{N(!0);try{await M.teams.delete(i,m,{purgeFiles:d}),window.dispatchEvent(new CustomEvent("markus:data-changed")),s()}catch{N(!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:y?"Deleting...":"Confirm Delete"}),e.jsx("button",{onClick:()=>o(!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"})]})]}):e.jsx("button",{onClick:()=>o(!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"})]})}function gr(i,a,s,r){return i==="channel"?`ch:${s}`:i==="dm"?`dm:${r??""}`:a||"_direct"}class hs{currentConvKey="";loadingSession=null;msgBuffers=new Map;sessionMsgCache=new Map;activeSession=new Map;actBuffers=new Map;sessionTabs=new Map;phase=new Map;sendCount=new Map;streamingSessions=new Map;sessionCacheOrder=[];static MAX_MESSAGES=500;static MAX_CONVERSATIONS=20;static MAX_SESSION_CACHE=30;static NEW_CHAT_ID="__new_chat__";getPhase(a){return this.phase.get(a)??"idle"}beginLoad(a){this.getPhase(a)!=="streaming"&&this.phase.set(a,"loading")}completeLoad(a){this.getPhase(a)==="loading"&&this.phase.set(a,"ready")}beginStream(a){this.phase.set(a,"streaming")}endStream(a){this.getPhase(a)==="streaming"&&this.phase.set(a,"ready")}resetConv(a){this.phase.set(a,"idle"),this.activeSession.delete(a)}updateMessages(a,s,r){const o=this.activeSession.get(a),d=!r||o===r||o===void 0,u=d?this.msgBuffers.get(a)??[]:this.sessionMsgCache.get(r)??[];let m=s(u);m.length>hs.MAX_MESSAGES&&(m=m.slice(-500));let f=!1;return d&&(this.msgBuffers.set(a,m),this.evictIfNeeded(a),f=this.currentConvKey===a),r&&r!==hs.NEW_CHAT_ID&&(this.sessionMsgCache.set(r,m),this.touchSessionCache(r)),{displayChanged:f,newMessages:f?m:void 0}}applyLoadResult(a,s,r){const o=this.isCacheFresher(s,r);o||(this.sessionMsgCache.set(s,r),this.touchSessionCache(s));const d=this.getPhase(a),u=this.activeSession.get(a);if(this.currentConvKey===a&&(this.loadingSession===s||u===s)&&d!=="streaming"){const f=o?this.sessionMsgCache.get(s):r;return this.msgBuffers.set(a,f),this.loadingSession=s,this.completeLoad(a),{displayChanged:!0,newMessages:f}}return{displayChanged:!1}}appendActivity(a,s,r){const o=r??a,d=[...this.actBuffers.get(o)??[],s];if(this.actBuffers.set(o,d),this.currentConvKey!==a)return{displayChanged:!1};const u=this.activeSession.get(a);return!r||!u||u===r?{displayChanged:!0,newActivities:d}:{displayChanged:!1}}getActiveSession(a){return this.activeSession.get(a)}setActiveSession(a,s){this.activeSession.set(a,s)}saveToCache(a,s){if(!s||s===hs.NEW_CHAT_ID)return;const r=this.msgBuffers.get(a);r&&r.length>0&&(this.sessionMsgCache.set(s,r),this.touchSessionCache(s))}restoreFromCache(a,s){const r=this.sessionMsgCache.get(s);if(r&&r.length>0)return this.msgBuffers.set(a,r),r;this.msgBuffers.delete(a)}isCacheFresher(a,s){const r=this.sessionMsgCache.get(a);if(!r||r.length===0)return!1;if(r.length>s.length)return!0;const o=r.reduce((f,y)=>f+y.text.length,0),d=s.reduce((f,y)=>f+y.text.length,0);if(o>d)return!0;const u=r.reduce((f,y)=>f+(y.segments?.length??0),0),m=s.reduce((f,y)=>f+(y.segments?.length??0),0);return u>m}incrementSend(a){this.sendCount.set(a,(this.sendCount.get(a)??0)+1)}decrementSend(a){const s=Math.max(0,(this.sendCount.get(a)??1)-1);return this.sendCount.set(a,s),s}resetSend(a){this.sendCount.set(a,0)}isSending(a){return(this.sendCount.get(a)??0)>0}addStreamSession(a,s){const r=this.streamingSessions.get(a)??new Set;r.add(s),this.streamingSessions.set(a,r)}removeStreamSession(a,s){if(s){const r=this.streamingSessions.get(a);r&&(r.delete(s),r.size===0&&this.streamingSessions.delete(a))}else this.streamingSessions.delete(a)}getStreamSessions(a){return this.streamingSessions.get(a)}getMessages(a){return this.msgBuffers.get(a)}getActivities(a){return this.actBuffers.get(a)??[]}deleteBuffer(a){this.msgBuffers.delete(a)}evictIfNeeded(a){if(this.msgBuffers.size<=hs.MAX_CONVERSATIONS)return;const s=[...this.msgBuffers.keys()],r=s.filter(o=>o!==a&&o!==this.currentConvKey).slice(0,s.length-hs.MAX_CONVERSATIONS);for(const o of r)this.msgBuffers.delete(o),this.actBuffers.delete(o),this.sessionTabs.delete(o),this.activeSession.delete(o)}touchSessionCache(a){const s=this.sessionCacheOrder.indexOf(a);for(s!==-1&&this.sessionCacheOrder.splice(s,1),this.sessionCacheOrder.push(a);this.sessionCacheOrder.length>hs.MAX_SESSION_CACHE;){const r=this.sessionCacheOrder.shift();if(new Set(this.activeSession.values()).has(r)){this.sessionCacheOrder.push(r);break}this.sessionMsgCache.delete(r)}}}const He=hs.NEW_CHAT_ID;function yc(i){const a=n.useRef(new hs),[s,r]=n.useState(i??[]),[o,d]=n.useState(!1),[u,m]=n.useState([]),f=n.useRef(null);n.useEffect(()=>()=>{f.current!==null&&cancelAnimationFrame(f.current)},[]);const y=n.useCallback((p,C,A)=>{const H=a.current.updateMessages(p,C,A);H.displayChanged&&H.newMessages&&r(H.newMessages)},[]),N=n.useCallback((p,C,A)=>{a.current.updateMessages(p,C,A).displayChanged&&f.current===null&&(f.current=requestAnimationFrame(()=>{f.current=null;const D=a.current.getMessages(p);D&&a.current.currentConvKey===p&&r([...D])}))},[]),j=n.useCallback((p,C,A)=>{const H=a.current.appendActivity(p,C,A);H.displayChanged&&H.newActivities&&m(H.newActivities)},[]),I=n.useCallback(p=>a.current.getPhase(p),[]),b=n.useCallback(p=>a.current.beginLoad(p),[]),v=n.useCallback(p=>a.current.beginStream(p),[]),O=n.useCallback(p=>a.current.endStream(p),[]),E=n.useCallback(p=>{a.current.resetConv(p),a.current.deleteBuffer(p)},[]),T=n.useCallback(async(p,C,A)=>{a.current.loadingSession=p,a.current.beginLoad(C);try{const H=await A(),D=a.current.applyLoadResult(C,p,H.messages);return D.displayChanged&&D.newMessages&&r(D.newMessages),{count:H.messages.length,hasMore:H.hasMore,oldestCursor:H.oldestCursor}}catch{return a.current.currentConvKey===C&&a.current.getPhase(C)!=="streaming"&&(r([]),a.current.completeLoad(C)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:a.current,messages:s,setMessages:r,sending:o,setSending:d,activities:u,setActivities:m,get msgBuffers(){return a.current.msgBuffers},get sessionMsgCache(){return a.current.sessionMsgCache},get activeSessionBuffer(){return a.current.activeSession},get actBuffers(){return a.current.actBuffers},get sessionTabsBuffer(){return a.current.sessionTabs},get currentConvKeyRef(){return{get current(){return a.current.currentConvKey},set current(p){a.current.currentConvKey=p}}},get loadingSessionRef(){return{get current(){return a.current.loadingSession},set current(p){a.current.loadingSession=p}}},updateConvMsgs:y,updateConvMsgsRaf:N,appendConvActivity:j,getPhase:I,beginLoad:b,beginStream:v,endStream:O,resetConv:E,loadAndDisplay:T,incrementSending:p=>a.current.incrementSend(p),decrementSending:p=>a.current.decrementSend(p),resetSending:p=>a.current.resetSend(p),isSendingFor:p=>a.current.isSending(p),setStreamSession:(p,C)=>a.current.addStreamSession(p,C),clearStreamSession:(p,C)=>a.current.removeStreamSession(p,C),getStreamSession:p=>a.current.getStreamSessions(p),saveSessionToCache:(p,C)=>a.current.saveToCache(p,C),restoreSessionFromCache:(p,C)=>{const A=a.current.restoreFromCache(p,C);return r(A??[]),A},isSessionCacheFresherThanDb:(p,C)=>a.current.isCacheFresher(p,C)}}function vc({value:i,onSelect:a,disabled:s}){const{t:r}=Ge("team"),[o,d]=n.useState(!1),[u,m]=n.useState(!0),[f,y]=n.useState(""),[N,j]=n.useState(!1),[I,b]=n.useState([]),[v,O]=n.useState(null),E=n.useRef(null),T=n.useCallback(async()=>{j(!0);try{const D=await fetch("/api/settings/llm",{credentials:"include"});if(!D.ok)throw new Error(`HTTP ${D.status}`);const k=await D.json(),P=k.providers?.markus;if(P?.configured&&P.enabled!==!1&&(!P.models||P.models.length===0))try{const se=await fetch("/api/models/live/markus",{credentials:"include"});if(se.ok){const F=await se.json();F.models?.length&&(P.models=F.models)}}catch{}const he=[];for(const[se,F]of Object.entries(k.providers??{})){if(!F.configured||F.enabled===!1)continue;const Me=(F.models??[]).map(ue=>({id:ue.id,name:ue.name}));Me.length!==0&&he.push({provider:se,displayName:F.displayName??se,models:Me})}he.sort((se,F)=>se.displayName.localeCompare(F.displayName)),b(he);let De=null;if(k.routingDefaultModel?.provider&&k.routingDefaultModel?.model)De={provider:k.routingDefaultModel.provider,model:k.routingDefaultModel.model};else if(k.defaultProvider){const se=k.providers?.[k.defaultProvider];se?.model&&(De={provider:k.defaultProvider,model:se.model})}O(De)}catch{b([])}finally{j(!1)}},[]);n.useEffect(()=>{T()},[T]),n.useEffect(()=>{o&&(m(!0),y(""),T())},[o,T]),n.useEffect(()=>{if(!o)return;const D=k=>{E.current?.contains(k.target)||d(!1)};return document.addEventListener("mousedown",D),()=>document.removeEventListener("mousedown",D)},[o]);const p=n.useMemo(()=>{const D=f.trim().toLowerCase();return I.map(k=>({...k,models:D?k.models.filter(P=>P.id.toLowerCase().includes(D)||(P.name?.toLowerCase().includes(D)??!1)||k.displayName.toLowerCase().includes(D)||k.provider.toLowerCase().includes(D)):k.models})).filter(k=>k.models.length>0)},[I,f]),C=i??v,H=(C?.model?C.model.includes("/")?C.model.split("/").pop():C.model:"")||r("chatModel.title",{defaultValue:"Model"});return e.jsxs("div",{ref:E,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",disabled:s,onClick:()=>d(D=>!D),className:"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:C?`${C.provider}: ${C.model}`:r("chatModel.title",{defaultValue:"Model"}),children:[e.jsx("span",{className:"truncate",children:H}),e.jsx("svg",{className:"w-3 h-3 shrink-0 opacity-60",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M6 9l6 6 6-6",strokeLinecap:"round",strokeLinejoin:"round"})})]}),o&&e.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:[e.jsxs("div",{className:"p-2 border-b border-border-default/60 space-y-2",children:[e.jsx("input",{autoFocus:!0,value:f,onChange:D=>y(D.target.value),placeholder:r("chatModel.search",{defaultValue:"Search models"}),className:"w-full px-2.5 py-1.5 text-xs rounded-lg bg-surface-base border border-border-default/50 outline-none focus:border-brand-500/50"}),e.jsxs("label",{className:"flex items-center justify-between gap-2 px-0.5 text-xs text-fg-secondary cursor-pointer select-none",children:[e.jsx("span",{children:r("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),e.jsx("button",{type:"button",role:"switch","aria-checked":u,onClick:()=>m(D=>!D),className:`relative w-9 h-5 rounded-full transition-colors ${u?"bg-brand-600":"bg-fg-tertiary/30"}`,children:e.jsx("span",{className:`absolute top-0.5 left-0.5 w-4 h-4 rounded-full bg-white transition-transform ${u?"translate-x-4":""}`})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[N&&e.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:r("common:loading",{defaultValue:"Loading…"})}),!N&&p.length===0&&e.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:r("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!N&&p.map(D=>e.jsxs("div",{className:"mb-1",children:[e.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:D.displayName}),D.models.slice(0,80).map(k=>{const P=C?.provider===D.provider&&C?.model===k.id;return e.jsxs("button",{type:"button",onClick:()=>{a({provider:D.provider,model:k.id},u),u&&O({provider:D.provider,model:k.id}),d(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${P?"text-fg-primary":"text-fg-secondary"}`,children:[e.jsx("span",{className:"truncate flex-1",children:k.id}),P&&e.jsx("svg",{className:"w-3.5 h-3.5 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:e.jsx("path",{d:"M5 12l5 5L20 7",strokeLinecap:"round",strokeLinejoin:"round"})})]},`${D.provider}:${k.id}`)})]},D.provider))]})]})]})}async function jc(i,a,s){i&&!i.startsWith("new_")&&await M.sessions.setModelOverride(i,a),s&&await M.settings.updateRouting({defaultProvider:a.provider,routingDefaultModel:{provider:a.provider,model:a.model}})}const $i="markus_team_sidebars_c";function wc(i){const a=i.metadata??{};if(typeof a.sessionId=="string"&&a.sessionId)return a.sessionId;if(i.actionType==="open_chat"&&i.actionTarget)try{const s=typeof i.actionTarget=="string"?JSON.parse(i.actionTarget):i.actionTarget;if(s&&typeof s=="object"&&typeof s.sessionId=="string")return s.sessionId}catch{}}const kc=["chat","overview","files","tools","memory","deliverables"],Nc=["chat","overview","announcements","norms","settings"];function Sc(i,a){if(i==="chat")return a("page.chatTitle");if(xa.find(o=>o.key===i))return a(`agent:tabs.${i}`);const r=fa.find(o=>o.key===i);return r?a(r.labelKey):i}function Cc(i){if(i==="chat")return"💬";const a=xa.find(r=>r.key===i);if(a)return a.icon;const s=fa.find(r=>r.key===i);return s?s.icon:""}function gs(i){return i!=="chat"}const ua=new Set;function Tc(){return window.location.hash}function Mc(i){return ua.add(i),()=>{ua.delete(i)}}typeof window<"u"&&window.addEventListener("hashchange",()=>ua.forEach(i=>i()));function Dc({initialAgentId:i,authUser:a,previewMode:s,previewData:r}={}){const{t:o,i18n:d}=Ge(["team","common"]),u=n.useMemo(()=>({today:o("page.dateToday"),yesterday:o("page.dateYesterday")}),[o]),m=Bi(xt.TEAM),[f,y]=n.useState(r?.agents??[]),[N,j]=n.useState(r?.humans??[]),[I,b]=n.useState(!r),v=ma(),O=n.useSyncExternalStore(Mc,Tc),E=v&&(O.startsWith(`#${xt.TEAM}/`)||O.startsWith("#chat/")),T=v&&O.match(/^#team\/t\/(.+)$/),p=v?T?"team":E?"chat":"roster":"roster",C=T?T[1]:null,A=n.useRef(xt.TEAM),H=n.useCallback(()=>{A.current=window.location.hash.slice(1)||xt.TEAM,window.location.hash=`${xt.TEAM}/d`},[]),D=n.useCallback(t=>{window.location.hash=`${xt.TEAM}/t/${t}`},[]);n.useEffect(()=>{if(!v)return;const t=()=>{gs(he.current)&&P("chat")};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[v]);const[k,P]=n.useState("chat"),he=n.useRef("chat");he.current=k;const De=ei({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[se,F]=n.useState(()=>{try{return localStorage.getItem($i)==="1"}catch{return!1}}),Me=n.useCallback(t=>{F(t);try{localStorage.setItem($i,t?"1":"0")}catch{}},[]),ue=ll(),L=ue?.leftCollapsed??!1,J=ue?.rightPanel??null,U=ue?.rightPanelTabs??[],ee=ue?.activeRightPanelTabId??null,g=ue?.rightPanelFullscreen??!1,q=J?"2xl:pr-8":"2xl:pr-[280px]",oe=ue?.setHostAvailable,be=ue?.collapseRightPanelOnly??ue?.toggleRightPanel,ge=ue?.openRightPanel,ye=400,Xe=320,et=6,[Yt,bs]=n.useState(typeof window<"u"?window.innerWidth:1440),[Ht,as]=n.useState("auto"),ys=n.useRef(L);n.useEffect(()=>{ys.current!==L&&(ys.current=L,F(L))},[L]),n.useEffect(()=>{if(oe)return oe(m&&!v),()=>oe(!1)},[m,v,oe]),n.useEffect(()=>s||v||!m?void 0:ze.on("ui:right_panel",l=>{const c=l.payload;if(c.action==="collapse"){be?.();return}if(c.action!=="open"||!c.panel||!ge)return;const x=c.panel;if(x.kind==="url"&&x.url){const w=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;ge({kind:"url",url:x.url,title:x.title||x.url,browserId:w});return}if(x.kind==="file"&&x.path){ge({kind:"file",path:x.path,title:x.title});return}x.kind==="deliverable"&&x.deliverableId&&M.deliverables.get(x.deliverableId).then(w=>{w.deliverable&&ge({kind:"deliverable",deliverable:w.deliverable})}).catch(()=>{})}),[s,v,m,be,ge]);const Ys=n.useCallback(t=>{const l=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;kr(c=>[...c,{id:l,...t}]),requestAnimationFrame(()=>cs.current?.focus())},[]),[Xt,jt]=n.useState(()=>{if(s)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),ft=ei({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),ae=n.useRef(null),[We,qe]=n.useState(!1),[Fe,wt]=n.useState(!1),mn=n.useCallback(()=>{We?wt(t=>!t):jt(t=>{const l=!t;try{localStorage.setItem("markus_team_panel_visible",String(l))}catch{}return l})},[We]);n.useEffect(()=>{if(v)return;const t=ae.current;if(!t)return;const l=new ResizeObserver(([c])=>{if(!c)return;const x=c.contentRect.width;if(bs(x),!s){const w=x-De.width-ft.width;qe(w<400)}});return l.observe(t),()=>l.disconnect()},[v,s,De.width,ft.width]);const zn=Xt&&!We&&!Fe,xn=se?0:De.width+et+(zn?ft.width+et:0),Qt=Math.max(0,Yt-xn-et-8),fn=Math.min(ye,Math.floor(Qt*.4)),gn=Math.max(0,Qt-fn),ga=Math.min(Math.round(Qt/2),gn),vs=Math.max(0,Math.min(Ht==="auto"?ga:Ht,gn)),js=n.useRef(!1);n.useEffect(()=>{const t=(ue?.rightPanel??null)!==null;t&&!js.current&&(F(!0),as("auto")),js.current=t},[ue?.rightPanel]);const Zt=n.useRef(vs);Zt.current=vs;const Wn=n.useRef(gn);Wn.current=gn;const vr=n.useCallback(t=>{t.preventDefault();const l=t.clientX,c=Zt.current,x=B=>{const W=c+(l-B.clientX),Q=Wn.current,S=Math.min(Xe,Q);as(Math.max(S,Math.min(Q,W)))},w=()=>{document.removeEventListener("mousemove",x),document.removeEventListener("mouseup",w),document.body.style.cursor="",document.body.style.userSelect=""};document.addEventListener("mousemove",x),document.addEventListener("mouseup",w),document.body.style.cursor="col-resize",document.body.style.userSelect="none"},[]);n.useEffect(()=>{if(!Fe)return;const t=l=>{l.target.closest("[data-l2-floating]")||wt(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Fe]);const[Es,is]=n.useState(null),[Hn,hn]=n.useState(),[pn,As]=n.useState(),[Rt,Vt]=n.useState(!1),[Vn,bn]=n.useState(""),[Xs,yn]=n.useState(!1),[Jt,Is]=n.useState(""),Qs=n.useRef(null),Dt=n.useRef(null),ws=n.useCallback((t,l)=>{hn(t),As(l),v?(P("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):P(t??"overview")},[v]),Ps=[{id:"chat"},{id:"profile"}],vn=n.useCallback(t=>{t==="profile"?ws():gs(he.current)?history.back():P("chat")},[ws]),$t=zi(Ps,k,vn),kt=n.useCallback((t,l)=>{$e("direct"),lt(t),v&&H(),ws(l?.tab,l?.highlightMailboxId),is(null)},[v,H,ws]),qt=n.useCallback((t,l)=>{const c=f.find(x=>x.name.toLowerCase()===t.toLowerCase());if(c){const x=l.target.getBoundingClientRect();is({agentId:c.id,top:x.bottom,left:x.left})}},[f]),jn=n.useMemo(()=>f.map(t=>t.name),[f]),[R,$e]=n.useState(()=>r?.chatMode??(i?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[K,lt]=n.useState(()=>i??localStorage.getItem("markus_chat_agent")??""),[Ie,Ct]=n.useState(()=>r?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[nt,Ls]=n.useState(""),Tt=500,_s=n.useRef(new Set),Zs=t=>{if(_s.current.add(t),_s.current.size>Tt){const l=Math.floor(Tt*.2),c=_s.current.values();for(let x=0;x<l;x++){const w=c.next().value;w&&_s.current.delete(w)}}},jr=n.useMemo(()=>{if(r?.channelMessages){const t=r.activeChannel??"custom:general";return r.channelMessages.filter(l=>l.channel===t).map(l=>Ks(l))}},[]),{manager:qn,messages:Ke,setMessages:Nt,sending:It,setSending:ct,activities:wr,setActivities:Ut,msgBuffers:gt,sessionMsgCache:Rs,activeSessionBuffer:Mt,actBuffers:Ot,sessionTabsBuffer:Un,currentConvKeyRef:ke,updateConvMsgs:Pe,updateConvMsgsRaf:os,appendConvActivity:Ds,beginLoad:h,beginStream:V,endStream:G,resetConv:xe,loadAndDisplay:Se,incrementSending:Oe,decrementSending:Ye,resetSending:Be,isSendingFor:Re,setStreamSession:rt,clearStreamSession:ht,getStreamSession:dt,saveSessionToCache:Gt,restoreSessionFromCache:ot}=yc(jr),[tt,Pt]=n.useState(""),[ks,Qe]=n.useState(null),[es,kr]=n.useState([]),[ha,wn]=n.useState([]),Ft=n.useRef(null),[Nr,Gn]=n.useState(!!r?.streamLastMessage),$s=n.useRef(null),Qi=400;n.useEffect(()=>(It?($s.current&&(clearTimeout($s.current),$s.current=null),Gn(!0)):Nr&&($s.current=setTimeout(()=>{Gn(!1),$s.current=null},Qi)),()=>{$s.current&&clearTimeout($s.current)}),[It]);const pa=It||Nr||(()=>{for(let t=Ke.length-1;t>=Math.max(0,Ke.length-8);t--){const l=Ke[t];if(l.isStreaming&&!l.isStopped)return!0}return!1})(),Sr=n.useRef({fullText:"",timers:[]});n.useEffect(()=>{if(!s||!r?.streamLastMessage||Ke.length===0)return;const t=Ke[Ke.length-1];if(!t||t.sender!=="agent")return;const l=t.text;Sr.current.fullText=l;const c=Sr.current.timers;function x(){let B=0;Nt(Q=>Q.map((S,$)=>$===Q.length-1?{...S,text:""}:S)),Gn(!0);const W=setInterval(()=>{if(B+=1+Math.floor(Math.random()*2),B>=l.length){clearInterval(W),Nt($=>$.map((Le,ve)=>ve===$.length-1?{...Le,text:l}:Le));const Q=setTimeout(()=>Gn(!1),800);c.push(Q);const S=setTimeout(x,6e3);c.push(S)}else Nt(Q=>Q.map((S,$)=>$===Q.length-1?{...S,text:l.slice(0,B)}:S))},30);c.push(W)}const w=setTimeout(x,1500);return c.push(w),()=>{c.forEach(B=>clearTimeout(B)),Sr.current.timers=[]}},[]);const Ns=n.useRef(0),[ba,ts]=n.useState(!1),[Cr,ya]=n.useState(!1),[va,ls]=n.useState(!1),[Lt,Tr]=n.useState([]),Mr=n.useRef(null),cs=n.useRef(null),[Kn,Yn]=n.useState(null),Ss=n.useRef(null),Er=n.useRef(!1),kn=n.useCallback(()=>{const t=cs.current;if(!t)return;const l=Er.current,c=l?36:52,x=l?160:120;t.style.height="auto";const w=Math.max(c,Math.min(t.scrollHeight,x));t.style.height=`${w}px`,t.style.overflowY=w>=x?"auto":"hidden"},[]);n.useEffect(()=>{const t=requestAnimationFrame(()=>kn());return()=>cancelAnimationFrame(t)},[tt,Lt.length,kn]);const Ar=t=>{try{const l=localStorage.getItem(`markus_closed_tabs_${t}`);return l?new Set(JSON.parse(l)):new Set}catch{return new Set}},Zi=(t,l)=>{const c=Ar(t);c.add(l);try{localStorage.setItem(`markus_closed_tabs_${t}`,JSON.stringify([...c]))}catch{}},Ji=(t,l)=>{const c=Ar(t);if(c.delete(l))try{localStorage.setItem(`markus_closed_tabs_${t}`,JSON.stringify([...c]))}catch{}},eo=t=>{try{return localStorage.getItem(`markus_active_session_${t}`)}catch{return null}},Xn=(t,l)=>{if(t)try{l&&l!==He?localStorage.setItem(`markus_active_session_${t}`,l):localStorage.removeItem(`markus_active_session_${t}`)}catch{}},[Ir,Os]=n.useState([]),[Ee,ss]=n.useState(null),[Fs,Bs]=n.useState(!1),[ja,Pr]=n.useState([]),[Nn,Lr]=n.useState(null),[to,wa]=n.useState(null),[Qn,_r]=n.useState([]),[Js,Rr]=n.useState(null),[so,ka]=n.useState(null),[Na,Dr]=n.useState([]),[Sn,no]=n.useState([]),Et=t=>{no(l=>{const c=typeof t=="function"?t(l):t,x=new Set;return c.filter(w=>x.has(w.id)?!1:(x.add(w.id),!0))})},Zn=n.useRef(null),$r=n.useRef(null),Kt=n.useRef(null),[bt,Cn]=n.useState(r?.groupChats??[]),Or=n.useRef(bt);Or.current=bt;const Sa=n.useRef(null),[Tn,pt]=n.useState(!1),[zs,Mn]=n.useState(!1),[Ca,en]=n.useState(""),[Fr,Cs]=n.useState([]),[Ta,Ma]=n.useState(!1),Br=n.useRef(void 0),[ns,Ea]=n.useState(r?.teams??[]),[ro,ao]=n.useState([]),[Jn,Aa]=n.useState([]),[io,oo]=n.useState(null),[Ec,Ac]=n.useState(!1),[Ic,Pc]=n.useState(""),[Ia,En]=n.useState(!1),[Pa,lo]=n.useState(""),[An,tn]=n.useState(0),[co,uo]=n.useState([]),La=n.useRef(!1),mo=n.useCallback(()=>{La.current||(La.current=!0,(async()=>{const t=[];try{const[l,c,x,w,B]=await Promise.all([M.projects.list().catch(()=>({projects:[]})),M.requirements.list().catch(()=>({requirements:[]})),M.tasks.list({pageSize:100}).catch(()=>({tasks:[]})),M.deliverables.search({limit:100}).catch(()=>({results:[]})),M.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const W of l.projects)t.push({id:W.id,name:W.name,entityType:"project",role:W.status});for(const W of c.requirements)t.push({id:W.id,name:W.title,entityType:"requirement",role:W.priority});for(const W of x.tasks)t.push({id:W.id,name:W.title,entityType:"task",role:W.status});for(const W of w.results)t.push({id:W.id,name:W.title,entityType:"deliverable",role:W.type});for(const W of B.teams)try{const Q=await M.workflows.list(W.id);for(const S of Q.workflows)t.push({id:S.name,name:S.displayName||S.name,entityType:"workflow",role:`v${S.version}`})}catch{}}catch{}uo(t)})())},[]),at=R==="channel"?bt.find(t=>t.channelKey===Ie)?.teamId:void 0,xo=n.useRef(null),sn=n.useRef(null),yt=n.useRef(null),_a=n.useRef(void 0),er=n.useRef(!1),ds=n.useRef(!0),Ra=n.useRef(void 0);n.useEffect(()=>{if(!Fs)return;const t=l=>{$r.current&&!$r.current.contains(l.target)&&Zn.current&&!Zn.current.contains(l.target)&&Bs(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[Fs]);const tr=(t,l)=>{if(!l||t===l)return`notes:${t}`;const[c,x]=[t,l].sort();return`dm:${c}:${x}`};n.useEffect(()=>{localStorage.setItem("markus_chat_mode",R)},[R]),n.useEffect(()=>{localStorage.setItem("markus_chat_agent",K)},[K]),n.useEffect(()=>{localStorage.setItem("markus_chat_channel",Ie)},[Ie]);const{counts:zr,sessionAgentMap:In,markRead:Pn,setActiveKey:fo,clearActiveKey:go}=cl({enabled:!s}),sr=n.useMemo(()=>{const t={};for(const[l,c]of Object.entries(zr))l.startsWith("channel:")&&(t[l.slice(8)]=c);return t},[zr]),Wr=dl(In,zr);n.useEffect(()=>{let t=0;for(const l of Wr.values())t+=l;for(const l of Object.values(sr))t+=l;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:t}}))},[Wr,sr]);const nr=Wr,ho=n.useCallback(async t=>{for(const[l,c]of Object.entries(In))c===t&&Pn(`session:${l}`)},[In,Pn]);n.useEffect(()=>{if(s||!((!v||p==="chat")&&k==="chat"))return;if(R==="direct"&&K&&ho(K),R==="channel"&&Ie)Pn(`channel:${Ie}`);else if(R==="direct"&&Ee)Pn(`session:${Ee}`);else if(R==="dm"&&nt){const c=`dm:${[a?.id,nt].sort().join(":")}`;Pn(`channel:${c}`)}const l=[];if(R==="direct"&&Ee){l.push(`session:${Ee}`);for(const[c,x]of Object.entries(In))x===K&&l.push(`session:${c}`)}else R==="channel"&&Ie?l.push(`channel:${Ie}`):R==="dm"&&nt&&a?.id&&l.push(`channel:dm:${[a.id,nt].sort().join(":")}`);for(const c of l)fo(c);return()=>{for(const c of l)go(c)}},[s,R,Ie,Ee,nt,K,p,k,In]);const Bt=n.useCallback(()=>M.agents.list().then(t=>y(t.agents)).catch(()=>{}),[]),_t=n.useCallback(()=>M.teams.list().then(t=>Ea(t.teams)).catch(()=>{}),[]),nn=n.useCallback(()=>M.groupChats.list().then(t=>Cn(t.chats)).catch(()=>{}),[]),po=n.useMemo(()=>aa(Bt,3e3),[Bt]),rr=n.useMemo(()=>aa(_t,5e3),[_t]),Hr=n.useMemo(()=>aa(nn,3e3),[nn]),Ln=n.useCallback(()=>{M.users.list(a?.orgId).then(t=>j(t.users)).catch(()=>{})},[a?.orgId]);n.useEffect(()=>{s||(Promise.all([Bt(),_t()]).finally(()=>b(!1)),Ln(),M.tasks.list().then(t=>Aa(t.tasks)).catch(()=>{}),M.externalAgents.list().then(t=>ao(t.agents)).catch(()=>{}),nn())},[s,Ln]),n.useEffect(()=>{if(!(!s||!r)&&(y(r.agents??[]),j(r.humans??[]),Ea(r.teams??[]),Cn(r.groupChats??[]),r.channelMessages)){const t=r.activeChannel??"custom:general";Nt(r.channelMessages.filter(l=>l.channel===t).map(l=>Ks(l)))}},[s,r]),n.useEffect(()=>{if(s||!m)return;Bt(),_t();const t=setInterval(Bt,3e4),l=setInterval(_t,6e4),c=ze.on("agent:update",()=>{po(),rr()}),x=ze.on("team:update",()=>{rr(),Hr()}),w=ze.on("agent:removed",rr),B=ze.on("chat:group_created",()=>{nn(),_t(),Bt()}),W=ze.on("chat:group_updated",Hr),Q=ze.on("chat:group_deleted",()=>{Hr(),rr()}),S=ze.on("task:update",Le=>{const ve=Le?.payload;ve?.taskId&&Aa(fe=>fe.map(ne=>ne.id===ve.taskId?{...ne,status:ve.status??ne.status}:ne))}),$=()=>{Bt(),_t(),Ln()};return window.addEventListener("markus:data-changed",$),()=>{clearInterval(t),clearInterval(l),c(),x(),w(),B(),W(),Q(),S(),window.removeEventListener("markus:data-changed",$)}},[s,m,Ln]),n.useEffect(()=>{if(s)return;const t=Q=>{const S=Q.detail;if(kl(S.page)===xt.TEAM){if(S.params?.agentId){if(S.params.profileTab)kt(S.params.agentId,{tab:S.params.profileTab});else if($e("direct"),lt(S.params.agentId),P("chat"),v&&H(),S.params.sessionId){const $=S.params.sessionId;setTimeout(async()=>{try{const{sessions:Le}=await M.sessions.listByAgent(S.params.agentId,20),ve=Le.find(fe=>fe.id===$);ve&&dr(ve)}catch{}},300)}}if(S.params?.selectAgent&&($e("direct"),lt(S.params.selectAgent),P("chat"),v&&H()),S.params?.prefillMessage){const $=S.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),P("chat"),S.params?.autoSend==="true"?setTimeout(()=>_a.current?.($),300):(Pt($),setTimeout(()=>{const Le=cs.current;Le&&(Le.focus(),Le.setSelectionRange(Le.value.length,Le.value.length))},100))}if(S.params?.dm&&($e("dm"),Ls(S.params.dm),P("chat"),v&&H()),S.params?.channel&&($e("channel"),Ct(S.params.channel),P("chat"),v&&H()),S.params?.selectTeam){const $=S.params.selectTeam;if(v)D($);else{const Le=Or.current.find(ve=>ve.type==="team"&&ve.teamId===$);$e("channel"),Ct(Le?.channelKey??`group:${$}`),P("chat"),pt(!1),jt(!0)}}S.params?.openHire}},l=localStorage.getItem("markus_nav_agentId");if(l){localStorage.removeItem("markus_nav_agentId");const Q=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),$e("direct"),lt(l),Q?kt(l,{tab:Q}):(P("chat"),v&&H())}const c=localStorage.getItem("markus_nav_dm");c&&(localStorage.removeItem("markus_nav_dm"),$e("dm"),Ls(c),P("chat"),v&&H());const x=localStorage.getItem("markus_nav_channel");x&&(localStorage.removeItem("markus_nav_channel"),$e("channel"),Ct(x),P("chat"),v&&H());const w=localStorage.getItem("markus_nav_prefillMessage");w&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),P("chat"),Pt(w),setTimeout(()=>{const Q=cs.current;Q&&(Q.focus(),Q.setSelectionRange(Q.value.length,Q.value.length))},150));const B=localStorage.getItem("markus_nav_selectAgent");B&&(localStorage.removeItem("markus_nav_selectAgent"),$e("direct"),lt(B),P("chat"),v&&H());const W=localStorage.getItem("markus_nav_selectTeam");if(W)if(localStorage.removeItem("markus_nav_selectTeam"),v)D(W);else{const Q=Or.current.find(S=>S.type==="team"&&S.teamId===W);$e("channel"),Ct(Q?.channelKey??`group:${W}`),P("chat"),pt(!1),jt(!0)}return window.addEventListener("markus:navigate",t),()=>window.removeEventListener("markus:navigate",t)},[s]),n.useEffect(()=>{const t=Sa.current;if(!t)return;const l=bt.find(c=>c.type==="team"&&c.teamId===t);Sa.current=null,$e("channel"),Ct(l?.channelKey??`group:${t}`),P("chat"),pt(!1),jt(!0)},[bt,ns]),n.useEffect(()=>{if(s&&r?.chatMode==="channel"||f.length===0||K&&f.some(l=>l.id===K))return;const t=f.find(l=>!l.teamId&&l.role?.toLowerCase()==="secretary")??f.find(l=>l.role?.toLowerCase()==="secretary")??f.find(l=>l.name?.toLowerCase().includes("secretary"));t?($e("direct"),lt(t.id),P("chat")):f.length>0&&($e("direct"),lt(f[0].id),P("chat"))},[f,K]);const rn=n.useRef(!1),rs=n.useRef(!1),ar=n.useRef(!1),ir=n.useRef(0),an=n.useRef(0),[bo,us]=n.useState(!1),Ts=n.useRef(0),[Da,Ws]=n.useState(0),ms=n.useCallback(()=>{rs.current=!1,ar.current=!1,ds.current=!0},[]),Vr=n.useCallback(()=>{rs.current=!0,ds.current=!1,an.current+=1,rn.current=!1,us(!0)},[]),Hs=n.useCallback(t=>{const l=sn.current;if(!l)return;const c=l.scrollHeight-l.scrollTop-l.clientHeight,x=c<160,w=c<48,B=ir.current,W=l.scrollTop<B-2;if(ir.current=l.scrollTop,W&&c>20){ar.current=!0,Vr();return}if(ar.current){w?(ms(),us(!1),Ts.current=0,Ws(0)):Vr();return}if(x&&!rs.current){ms(),us(!1),Ts.current=0,Ws(0);return}t?.fromProgrammatic||rn.current||!rs.current&&ds.current||rs.current&&(ds.current=!1,us(!0))},[Vr,ms]);n.useEffect(()=>{const t=sn.current;if(!t)return;const l=()=>{ar.current=!0},c=()=>{Hs({fromProgrammatic:rn.current})};t.addEventListener("wheel",l,{passive:!0}),t.addEventListener("touchmove",l,{passive:!0}),t.addEventListener("scroll",c,{passive:!0});const x=typeof ResizeObserver<"u"?new ResizeObserver(()=>Hs()):null;return x?.observe(t),ir.current=t.scrollTop,Hs(),()=>{t.removeEventListener("wheel",l),t.removeEventListener("touchmove",l),t.removeEventListener("scroll",c),x?.disconnect()}},[p,Hs]);const qr=n.useMemo(()=>new Set(Na),[Na]),ut=n.useMemo(()=>{const t=R==="channel"?Ke:Ke.filter(l=>!l.isActivityLog);return qr.size===0?t:t.filter(l=>!(l.isNotification&&qr.has(l.id)))},[Ke,R,qr]);n.useEffect(()=>{Er.current=k==="chat"&&ut.length>0,kn()},[k,ut.length,kn]);const xs=Ol({count:ut.length,getScrollElement:()=>sn.current,getItemKey:t=>ut[t]?.id??t,estimateSize:t=>{const l=ut[t];return l?l.segments&&l.segments.length>0?300:l.text.length>500?200:120:120},overscan:8});xs.shouldAdjustScrollPositionOnItemSizeChange=(t,l,c)=>ti()?!1:t.start<(c.scrollOffset??0);const on=n.useCallback((t="instant")=>{if(!ds.current||rs.current)return;const l=++an.current;rn.current=!0;const c=()=>l===an.current&&ds.current&&!rs.current,x=()=>{if(l!==an.current)return;if(rn.current=!1,!c()){Hs();return}const w=sn.current;w&&(ir.current=w.scrollTop,w.scrollHeight-w.scrollTop-w.clientHeight<160&&!rs.current&&(ms(),us(!1),Ts.current=0,Ws(0))),requestAnimationFrame(()=>{l===an.current&&Hs({fromProgrammatic:!0})})};if(ut.length>0)xs.scrollToIndex(ut.length-1,{align:"end",behavior:t}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!c()){l===an.current&&(rn.current=!1);return}xs.scrollToIndex(ut.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(x)})});else{const w=sn.current;w&&w.scrollTo({top:w.scrollHeight,behavior:t}),requestAnimationFrame(x)}},[ut.length,xs,Hs,ms]),$a=n.useRef(m);n.useEffect(()=>{$a.current=m},[m]),n.useLayoutEffect(()=>{if(er.current){er.current=!1;const t=lr.current;t>0&&(lr.current=0,xs.scrollToIndex(t,{align:"start",behavior:"instant"}));return}$a.current&&(!ds.current||rs.current||ti()||on())},[Ke,on,xs]);const Oa=n.useRef(k);n.useEffect(()=>{const t=Oa.current!=="chat";if(Oa.current=k,k==="chat"&&t&&ds.current&&!rs.current){const l=[],c=requestAnimationFrame(()=>on("instant"));for(const x of[60,160,320])l.push(setTimeout(()=>on("instant"),x));return()=>{cancelAnimationFrame(c);for(const x of l)clearTimeout(x)}}},[k,It,on]);const Fa=n.useCallback(async(t,l)=>{const c=l??`ch:${t}`;ke.current===c&&ls(!0);try{const x=await M.channels.getMessages(t,50),w=x.messages.map(B=>Ks(B,a?.id));gt.set(c,w),ke.current===c&&(Nt(w),ts(x.hasMore),Kt.current=x.messages[0]?new Date(x.messages[0].createdAt).toISOString():null)}catch{ke.current===c&&(Nt([]),ts(!1))}finally{ke.current===c&&ls(!1)}},[]),Ur=n.useCallback(async(t,l)=>{const c=ke.current===l&&(gt.get(l)?.length??0)===0;c&&ls(!0);try{const{count:x,hasMore:w,oldestCursor:B}=await Se(t,l,async()=>{const W=await M.sessions.getMessages(t,50);return{messages:ul(W.messages.map(ia).filter(S=>S.sender!=="agent"||S.text||S.segments&&S.segments.length>0||S.isStreaming)),hasMore:W.hasMore,oldestCursor:W.messages[0]?new Date(W.messages[0].createdAt).toISOString():null}});return ts(w),Kt.current=B,x}finally{c&&ke.current===l&&ls(!1)}},[Se,gt]),Ba=n.useRef(new Map),Vs=n.useCallback(async(t,l,c)=>{if(!t||!l||l===He)return;let x=null;try{if(yt.current&&!yt.current.signal.aborted&&dt(c)?.has(l)){V(c),ke.current===c&&ct(!0);return}const w=`${t}:${l}`,B=Ba.current.get(w)??0;if(Date.now()-B<1500)return;const W=await M.sessions.streamStatus(t,l),S=[...gt.get(c)??[]].reverse().find(Y=>Y.sender==="agent"),$=W.status==="streaming",Le=!!W.active&&(W.status==="done"||W.status==="error")&&!!S?.isStreaming;if(!$&&!Le)return;Ba.current.set(w,Date.now()),Ss.current?.abort(),x=new AbortController,Ss.current=x,V(c),ct(!0),rt(c,l);let ve=S?.id;if(!S||S.isError)ve=`reattach_${Date.now()}`,Pe(c,Y=>[...Y,{id:ve,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],l);else{const Y=(S.segments??[]).filter(me=>me.type==="tool").map(me=>me.status==="stopped"||me.status==="running"?{...me,status:"running"}:me);Pe(c,me=>me.map(te=>te.id===S.id?{...te,text:"",isStreaming:!0,isStopped:!1,segments:Y,committedSegments:void 0}:te),l)}let fe=!1;const ne=Y=>{ke.current===c&&(Ns.current=Date.now(),os(c,me=>{const te=[...me],le=ve?te.findIndex(z=>z.id===ve):-1,ie=le>=0?le:te.map((z,X)=>({m:z,j:X})).reverse().find(z=>z.m.sender==="agent")?.j??-1;if(ie<0)return me;const de=te[ie].segments??[],Te=de[de.length-1],Ve=Te?.type==="text"?Te.thinking??"":"";let st="",St="",_=Y;for(;_.length>0;)if(fe){const z=_.indexOf("</think>");z>=0?(st+=_.slice(0,z),_=_.slice(z+8),fe=!1):(st+=_,_="")}else{const z=_.indexOf("<think>");z>=0?(St+=_.slice(0,z),_=_.slice(z+7),fe=!0):(St+=_,_="")}const pe=Ve+st||void 0,Z=Te?.type==="text"?[...de.slice(0,-1),{type:"text",content:Te.content+St,thinking:pe,createdAt:Te.createdAt}]:[...de,{type:"text",content:St,thinking:pe,createdAt:new Date().toISOString()}];return te[ie]={...te[ie],text:(te[ie].text??"")+St,segments:Z,isStreaming:!0},te},l))},_e=Y=>{if(ke.current===c&&(Ns.current=Date.now(),Y.phase!=="heartbeat")){if((Y.phase==="start"||Y.phase==="end")&&Ds(c,{...Y,phase:Y.phase,ts:Date.now()},l),Y.phase==="start"){const me=`${Y.tool}_${Date.now()}`,te=new Date().toISOString(),le=ie=>{const de=[...ie];for(let Te=de.length-1;Te>=0;Te--){const Ve=de[Te];if(Ve.type==="tool"&&Ve.tool===Y.tool&&(Ve.status==="running"||Ve.status==="stopped"))return de[Te]={...Ve,status:"running",args:Y.arguments??Ve.args},de}return de.push({type:"tool",key:me,tool:Y.tool,status:"running",args:Y.arguments,createdAt:te}),de};Pe(c,ie=>{const de=[...ie],Te=ve?de.findIndex(_=>_.id===ve):-1;if(Te<0)return ie;const Ve=le(de[Te].segments??[]),st=de[Te].committedSegments,St=st&&le(st);return de[Te]={...de[Te],segments:Ve,committedSegments:St,isStreaming:!0},de},l)}else if(Y.phase==="end"){const me=new Date().toISOString(),te=le=>{const ie=[...le];for(let de=ie.length-1;de>=0;de--){const Te=ie[de];if(Te.type==="tool"&&Te.tool===Y.tool&&(Te.status==="running"||Te.status==="stopped")){ie[de]={...Te,status:Y.success===!1?"error":"done",args:Y.arguments??Te.args,result:Y.result,error:Y.error,durationMs:Y.durationMs,liveOutput:void 0,createdAt:me};break}}return ie};Pe(c,le=>{const ie=[...le],de=ve?ie.findIndex(St=>St.id===ve):-1;if(de<0)return le;const Te=te(ie[de].segments??[]),Ve=ie[de].committedSegments,st=Ve&&te(Ve);return ie[de]={...ie[de],segments:Te,committedSegments:st,isStreaming:!0},ie},l)}else if(Y.phase==="subagent_progress"&&Y.subagentEvent){const me=te=>{const le=[...te];for(let ie=le.length-1;ie>=0;ie--){const de=le[ie];if(de.type==="tool"&&(de.tool==="spawn_subagent"||de.tool==="spawn_subagents")&&(de.status==="running"||de.status==="stopped")){le[ie]={...de,status:"running",subagentLogs:si(de.subagentLogs,Y.subagentEvent)};break}}return le};os(c,te=>{const le=[...te],ie=ve?le.findIndex(st=>st.id===ve):-1;if(ie<0)return te;const de=me(le[ie].segments??[]),Te=le[ie].committedSegments,Ve=Te&&me(Te);return le[ie]={...le[ie],segments:de,committedSegments:Ve,isStreaming:!0},le},l)}}},ce=Y=>{ke.current===c&&(Ns.current=Date.now(),Pe(c,me=>{const te=[...me],le=ve?te.findIndex(de=>de.id===ve):-1;if(le<0)return me;const ie=[...te[le].committedSegments??[]];if(Y.type==="thinking_commit")ie.push({type:"text",content:"",thinking:Y.content,createdAt:Y.createdAt});else if(Y.type==="text_commit")ie.push({type:"text",content:Y.content,createdAt:Y.createdAt});else return me;return te[le]={...te[le],committedSegments:ie,isStreaming:!0},te},l))},Ne=Y=>{if(ke.current!==c)return;Ns.current=Date.now();const me=(Y.segments??[]).map((te,le)=>te.type==="tool"?{type:"tool",key:`${te.tool}_${le}`,tool:te.tool??"tool",status:te.status==="error"?"error":te.status==="running"||te.status==="stopped"?"running":"done",args:te.arguments,result:te.result,error:te.error,durationMs:te.durationMs,createdAt:te.createdAt,...te.subagentLogs?.length?{subagentLogs:te.subagentLogs}:{}}:{type:"text",content:te.content??"",thinking:te.thinking,createdAt:te.createdAt});Pe(c,te=>{const le=[...te],ie=ve?le.findIndex(de=>de.id===ve):-1;return ie<0?te:(le[ie]={...le[ie],text:Y.content||le[ie].text,segments:me,committedSegments:me,isStreaming:!0,isStopped:!1},le)},l);for(const te of me)te.type==="tool"&&Ds(c,{tool:te.tool,phase:te.status==="running"||te.status==="stopped"?"start":"end",success:te.status!=="error",arguments:te.args,result:te.result,error:te.error,durationMs:te.durationMs,ts:Date.now()},l)},Ce=await M.sessions.reattachStream(t,l,{onChunk:ne,onActivity:_e,onCommit:ce,onSnapshot:Ne},x.signal,0);if(!Ce.attached){G(c),ke.current===c&&(Pe(c,Y=>{const me=[...Y],te=ve?me.findIndex(de=>de.id===ve):-1,le=te>=0?te:me.map((de,Te)=>({m:de,j:Te})).reverse().find(de=>de.m.sender==="agent"&&de.m.isStreaming)?.j??-1;if(le<0)return Y;const ie=me[le];return ie.isStreaming?(me[le]={...ie,isStreaming:!1,isStopped:ie.isError?ie.isStopped:!0},me):Y},l),ct(!1));return}ke.current===c&&(Pe(c,Y=>{const me=[...Y],te=ve?me.findIndex(Te=>Te.id===ve):-1,le=te>=0?te:me.map((Te,Ve)=>({m:Te,j:Ve})).reverse().find(Te=>Te.m.sender==="agent")?.j??-1;if(le<0)return Y;const ie=me[le],de=Ce.segments?.length?ni(Ce.segments,ie.segments):void 0;return me[le]={...ie,text:Ce.content||ie.text,isStreaming:!1,isStopped:!1,...de?{segments:de,committedSegments:de}:{}},me},l),ct(!1)),G(c),Ss.current===x&&(Ss.current=null)}catch(w){if(Ss.current===x&&(Ss.current=null),G(c),ke.current===c&&ct(!1),w instanceof Error&&w.name==="AbortError")return}},[Ds,V,G,dt,gt,rt,Pe,os]);n.useEffect(()=>{if(!m||s||R!=="direct"||!K)return;const t=Ee;!t||t===He||Vs(K,t,ke.current)},[m,s,R,K,Ee,Vs]);const or=n.useCallback(async t=>{if(!t)return Os([]),[];try{const{sessions:l}=await M.sessions.listByAgent(t,10);return Os(l),l}catch{return Os([]),[]}},[]),lr=n.useRef(0),yo=n.useCallback(async()=>{if(!(Cr||!ba||!Kt.current)){ya(!0);try{const t=ke.current;if(R==="channel"||R==="dm"){const l=R==="dm"?tr(a?.id??"",nt):Ie,c=await M.channels.getMessages(l,50,Kt.current),x=c.messages.map(w=>Ks(w,a?.id));lr.current=x.length,er.current=!0,Nt(w=>{let B=[...x,...w];return B.length>500&&(B=B.slice(-500)),gt.set(t,B),B}),ts(c.hasMore),c.messages[0]&&(Kt.current=new Date(c.messages[0].createdAt).toISOString())}else if(Ee){const l=await M.sessions.getMessages(Ee,50,Kt.current),c=l.messages.map(ia);lr.current=c.length,er.current=!0,Nt(x=>{let w=[...c,...x];return w.length>500&&(w=w.slice(-500)),gt.set(t,w),w}),ts(l.hasMore),l.messages[0]&&(Kt.current=new Date(l.messages[0].createdAt).toISOString())}}catch{}finally{ya(!1)}}},[Cr,ba,R,Ie,Ee,a?.id,nt]);Ra.current=yo;const Gr=n.useRef(!1),vo=n.useCallback(t=>{Gr.current||(Gr.current=!0,requestAnimationFrame(()=>{Gr.current=!1,t.target.scrollTop<100&&Ra.current?.()}))},[]);n.useEffect(()=>{if(s)return;const t=gr(R,K,Ie,nt),l=ke.current;ke.current=t,l&&l!==t&&(Un.set(l,Sn),Ee&&Mt.set(l,Ee)),l!==t&&(ms(),us(!1),Ts.current=0,Ws(0));const c=gt.get(t),x=Un.get(t),w=Mt.get(t),B=dt(t),W=w??Ee,Q=Re(t)&&(R!=="direct"||!B||!W||B.has(W)),S=W??t,$=Ot.get(S)??[];if(Ut(Q?$:[]),ct(Q),R==="direct"&&K&&or(K),x&&x.length>0&&Et(x),Bs(!1),c!==void 0&&c.length>0)if(Q||qn.completeLoad(t),ls(!1),Nt(c),ts(!1),w!==void 0&&ss(w),(!x||x.length===0)&&Et([]),R==="channel"||R==="dm"){const ve=R==="dm"?tr(a?.id??"",nt):Ie;Fa(ve,t)}else R==="direct"&&K&&w&&w!==He&&(Q?Vs(K,w,t):Ur(w,t).then(()=>{ke.current===t&&K&&Vs(K,w,t)}));else if(h(t),ls(!0),Nt([]),ts(!1),Kt.current=null,gt.delete(t),R==="channel"||R==="dm"){const ve=R==="dm"?tr(a?.id??"",nt):Ie;Fa(ve,t),(!x||x.length===0)&&Et([])}else R==="direct"&&K?or(K).then(ve=>{if(ke.current===t)if(ve.length>0){const fe=ve.find(le=>le.isMain),ne=Ar(K),_e=fe?[fe,...ve.filter(le=>!le.isMain&&!ne.has(le.id)).slice(0,4)]:ve.filter(le=>!ne.has(le.id)).slice(0,5);let ce=x&&x.length>0?x:_e;const Ne=eo(K),Ce=w!==void 0?w:Ne??fe?.id??ce[0].id;if(Ce&&Ce!==He&&!ce.some(le=>le.id===Ce)){const le=ve.find(ie=>ie.id===Ce);le&&(ce=[...ce,le])}const Y=Ce&&ce.some(le=>le.id===Ce)?Ce:ce[0].id;ss(Y),Mt.set(t,Y),Xn(K,Y),Et(ce);const te=ve.find(le=>le.id===Y)?.metadata?.modelOverride;Yn(te?.provider&&te?.model?{provider:te.provider,model:te.model}:null),Ur(Y,t).then(()=>{ke.current===t&&K&&Vs(K,Y,t)})}else ss(null),Yn(null),ls(!1),(!x||x.length===0)&&Et([])}).catch(()=>{ke.current===t&&ls(!1)}):ls(!1)},[s,R,K,Ie,nt,d.language,o]),n.useEffect(()=>s?void 0:ze.on("chat:message",l=>{const c=l.payload,x=c.channel??"";if(!x)return;const w=c.senderType??"agent",B=c.text??c.message??"",W=c.senderId??c.agentId??"",Q=c.senderName??c.agentId??o("page.fallbackAgent"),S=c.metadata,$=c.messageId??c.id??"";if($&&_s.current.has($))return;const Le=w==="human"&&W===(a?.id??""),ve={id:$||`ws_${Date.now()}_${W}`,sender:Le?"user":"agent",text:B,time:new Date().toLocaleTimeString(),agentName:Le?void 0:Q,agentId:Le?void 0:W,replyToId:c.replyToId??void 0,replyToSender:c.replyToSender??void 0,replyToText:c.replyToText??void 0};if(S&&w==="agent"){const ne=[];if(S.thinking?.length&&ne.push({type:"text",content:"",thinking:S.thinking.join(`
|
|
33
|
-
|
|
34
|
-
`)}),S.toolCalls?.length)for(let _e=0;_e<S.toolCalls.length;_e++){const ce=S.toolCalls[_e];ne.push({type:"tool",key:`${ce.tool}_${_e}`,tool:ce.tool,status:ce.status==="error"?"error":"done",args:ce.arguments,result:ce.result,durationMs:ce.durationMs})}ne.length>0&&(ne.push({type:"text",content:B}),ve.segments=ne)}let fe;if(x.startsWith("notes:"))fe=`dm:${x.slice(6)}`;else if(x.startsWith("dm:")){const ne=x.slice(3).split(":");fe=`dm:${ne.find(ce=>ce!==(a?.id??""))??ne[0]??""}`}else fe=`ch:${x}`;Pe(fe,ne=>[...ne,ve]),fe===ke.current&&!ds.current&&(Ts.current+=1,Ws(Ts.current),us(!0)),w==="agent"&&fe===`ch:${Ie}`&&wn(ne=>{const _e=ne.filter(ce=>ce.id!==W);return _e.length===0&&Ft.current&&(clearTimeout(Ft.current),Ft.current=null),_e})}),[s,Pe,a?.id,Ie]),n.useEffect(()=>s?void 0:ze.on("chat:agent_no_response",l=>{const c=l.payload,x=c.channel??"",w=c.agentId??"";x&&w&&`ch:${Ie}`==`ch:${x}`&&wn(B=>{const W=B.filter(Q=>Q.id!==w);return W.length===0&&Ft.current&&(clearTimeout(Ft.current),Ft.current=null),W})}),[s,Ie]),n.useEffect(()=>s?void 0:ze.on("chat:proactive_message",l=>{const c=l.payload,x=c.targetUserId;if(x&&x!==a?.id)return;const w=c.agentId??"",B=c.agentName??o("page.fallbackAgent"),W=c.message??"",Q=c.sessionId??"",S=c.messageId??"",$=c.metadata??{};if(!w||!W||W==="[cancelled]"||W==="[Stream cancelled]")return;const Le=$.role==="user",ve=!Le&&(!!$.activityLog||W.startsWith("[ACTIVITY:")),{cleaned:fe,priority:ne}=ml(W),_e=!Le&&(!!$.notifyUser||fe!==W),ce=gr("direct",w,"","");if(Q&&ke.current===ce){const de=Ee;if(de&&de!==He&&de!==Q)return}const Ne=!!$.isMainSession&&!Le,Ce=Q||Ee,Y=typeof $.userText=="string"?$.userText:"",me=typeof $.userMessageId=="string"?$.userMessageId:"",te=typeof $.createdAt=="string"&&$.createdAt||(typeof l.timestamp=="string"?l.timestamp:void 0)||new Date().toISOString(),le=(()=>{try{return new Date(te).toLocaleTimeString()}catch{return new Date().toLocaleTimeString()}})(),ie={id:S||`proactive_${Date.now()}`,sender:Le?"user":"agent",text:fe,time:le,rawCreatedAt:te,...Le?{}:{agentName:B,agentId:w,..._e?{isNotification:!0,notifyPriority:$.priority??ne}:{},...ve?{isActivityLog:!0,activityType:$.activityType,outcome:$.outcome,mailboxItemId:$.mailboxItemId,taskId:$.taskId,requirementId:$.requirementId}:{},...!ve&&$.taskId?{taskId:$.taskId}:{},...!ve&&$.requirementId?{requirementId:$.requirementId}:{}}};_e&&ie.id&&Dr(de=>de.includes(ie.id)?de:[...de,ie.id]),Pe(ce,de=>{if(de.some(Ve=>Ve.id===ie.id))return de;let Te=de;if(!Le&&Y&&(Te.some(st=>me&&st.id===me||st.sender==="user"&&st.text===Y)||(Te=[...Te,{id:me||`feishu_user_${ie.id}`,sender:"user",text:Y,time:new Date().toLocaleTimeString()}])),Ne)for(let Ve=Te.length-1;Ve>=0;Ve--){const st=Te[Ve];if(st.sender==="agent"&&st.agentId===w&&st.isStopped){const St=[...Te];return St[Ve]={...ie,id:st.id},St}}return xl(Te,ie)},Ce||void 0)}),[s,Pe,o,Ee]),Jn.find(t=>t.id===io),n.useEffect(()=>{oo(null)},[K]);const jo=t=>Sl(t),wo=()=>{const t=R==="direct"?K:null;t&&M.agents.cancelProcessing(t).catch(()=>{}),yt.current?.abort(),yt.current=null,Ss.current?.abort(),Ss.current=null;const l=ke.current;Be(l),Ot.delete(Ee??l),Ee&&ht(l,Ee),G(l),ct(!1),Ut([])},[qs,Kr]=n.useState(null),[za,Wa]=n.useState(!1),Ha=n.useRef(null),Us=async(t,l)=>{const c=!t&&es.length>0?es.map(fe=>fe.content).join(`
|
|
35
|
-
|
|
36
|
-
`)+`
|
|
37
|
-
|
|
38
|
-
`:"",x=(t??c+tt).trim();if(!x&&Lt.length===0||R==="direct"&&!K)return;ms();const w=Date.now(),B=Ha.current;if(!l?.isRetry&&!l?.isResume&&x&&B&&B.text===x&&w-B.at<1500)return;if(Ha.current={text:x,at:w},It&&R==="direct"){if(Ee&&Ee!==He){const ne=ke.current;if([...gt.get(ne)??[]].reverse().find(Ne=>Ne.sender==="user")?.text===x&&!l?.isRetry&&!l?.isResume)return yt.current?.abort(),yt.current=null,M.agents.cancelProcessing(K).catch(()=>{}),Be(ne),Ot.delete(Ee??ne),G(ne),Pe(ne,Ne=>{const Ce=[...Ne];return Ce.length>0&&Ce[Ce.length-1].sender==="agent"&&Ce.pop(),Ce.length>0&&Ce[Ce.length-1].sender==="user"&&Ce[Ce.length-1].text===x&&Ce.pop(),Ce}),ct(!1),Ut([]),await new Promise(Ne=>setTimeout(Ne,50)),Us(x,{isRetry:!0});yt.current?.abort(),yt.current=null,M.agents.cancelProcessing(K).catch(()=>{}),Be(ne),Ot.delete(Ee??ne),G(ne),Pe(ne,Ne=>{const Ce=[...Ne];for(let Y=Ce.length-1;Y>=0;Y--)if(Ce[Y].sender==="agent"&&!Ce[Y].isStopped&&!Ce[Y].isError){const me=Ce[Y];if(!(me.text?.trim()||(me.segments??[]).some(le=>le.type==="text"&&(le.content||le.thinking)||le.type==="tool")))Ce.splice(Y,1);else{const le=(me.segments??[]).map(ie=>ie.type==="tool"&&ie.status==="running"?{...ie,status:"stopped"}:ie);Ce[Y]={...me,isStopped:!0,segments:le}}break}return Ce}),ct(!1),Ut([]),await new Promise(Ne=>setTimeout(Ne,50))}}else if(It&&R!=="direct"){yt.current?.abort(),yt.current=null;const fe=ke.current;Be(fe),Ot.delete(fe),G(fe),Pe(fe,ne=>{const _e=[...ne];for(let ce=_e.length-1;ce>=0;ce--)if(_e[ce].sender==="agent"&&!_e[ce].isStopped&&!_e[ce].isError){const Ne=_e[ce];if(!(Ne.text?.trim()||(Ne.segments??[]).some(Y=>Y.type==="text"&&(Y.content||Y.thinking)||Y.type==="tool")))_e.splice(ce,1);else{const Y=(Ne.segments??[]).map(me=>me.type==="tool"&&me.status==="running"?{...me,status:"stopped"}:me);_e[ce]={...Ne,isStopped:!0,segments:Y}}break}return _e}),ct(!1),Ut([]),await new Promise(ne=>setTimeout(ne,50))}const W=Lt.length>0?Lt.map(fe=>fe.dataUrl):void 0,Q=Lt.length>0?Lt.map(fe=>fe.name):void 0,S=gr(R,K,Ie,nt),$=ks;t||(Pt(""),kr([])),Tr([]),En(!1),Qe(null);const Le=R==="dm";Oe(S);const ve=Ee??S;if(Ot.set(ve,[]),ke.current===S&&!Le&&(ct(!0),Ut([])),R==="dm"){const fe=tr(a?.id??"",nt),ne=`opt_${Date.now()}`,_e={id:ne,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};W?.length&&(_e.images=W),$&&(_e.replyToId=$.id,_e.replyToSender=$.sender,_e.replyToText=$.text),Pe(S,ce=>[...ce,_e]);try{const ce=await M.channels.sendMessage(fe,{text:x,senderName:a?.name??o("page.fallbackYou"),senderId:a?.id,mentions:[],orgId:"default",humanOnly:!0,...W?.length?{images:W}:{}});ce.userMessage&&Zs(ce.userMessage.id),Pe(S,Ne=>{const Ce=Ne.filter(me=>me.id!==ne),Y=[];return ce.userMessage&&Y.push(Ks(ce.userMessage,a?.id)),Y.length>0?[...Ce,...Y]:Ne})}catch(ce){hr(ce)&&pr(),Pe(S,Ne=>[...Ne.filter(Y=>Y.id!==ne),{id:`err_${Date.now()}`,sender:"agent",text:o("page.errorWithMessage",{message:String(ce)}),time:new Date().toLocaleTimeString(),agentName:o("page.systemName"),isError:!0}])}Ye(S),ke.current===S&&ct(!1)}else if(R==="channel"){const fe=`opt_${Date.now()}`,ne={id:fe,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};$&&(ne.replyToId=$.id,ne.replyToSender=$.sender,ne.replyToText=$.text),Pe(S,Ne=>[...Ne,ne]);const _e=jo(x),ce=bt.find(Ne=>Ne.channelKey===Ie);if(Ie.startsWith("group:")){const Ne=[];if(ce?.members){for(const Ce of ce.members)if(Ce.type==="agent"){const Y=f.find(me=>me.id===Ce.id);Y&&Ne.push({id:Y.id,name:Y.name,avatarUrl:Y.avatarUrl})}}Ne.length>0&&(Ft.current&&clearTimeout(Ft.current),wn(Ne),Ft.current=setTimeout(()=>wn([]),12e4))}try{const Ne=await M.channels.sendMessage(Ie,{text:x,senderName:a?.name??o("page.fallbackYou"),mentions:_e,senderId:a?.id,orgId:"default",replyToId:$?.id});Ne.userMessage&&Zs(Ne.userMessage.id),Ne.agentMessage&&Zs(Ne.agentMessage.id),Pe(S,Ce=>{const Y=Ce.filter(te=>te.id!==fe),me=[];return Ne.userMessage&&me.push(Ks(Ne.userMessage,a?.id)),Ne.agentMessage&&me.push(Ks(Ne.agentMessage,a?.id)),me.length>0?[...Y,...me]:Ce})}catch(Ne){hr(Ne)&&pr();const Ce=br(Ne,o)||o("page.errorWithMessage",{message:String(Ne)});Pe(S,Y=>[...Y,{id:`err_${Date.now()}`,sender:"agent",text:Ce,time:new Date().toLocaleTimeString(),agentName:o("page.systemName"),isError:!0}]),Ft.current&&(clearTimeout(Ft.current),Ft.current=null),wn([])}Ye(S),ke.current===S&&ct(!1)}else{V(S);const fe=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,ne=`a_${fe}`,_e=`u_${fe}`;let ce=l?.sessionIdOverride??(Ee===He?null:Ee);if(l?.isResume){const _=new Date().toISOString();Pe(S,pe=>[...pe,{id:ne,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:_,segments:[]}],ce)}else{const _=new Date().toISOString(),pe={id:_e,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:_};W?.length&&(pe.images=W),$&&(pe.replyToId=$.id,pe.replyToSender=$.sender,pe.replyToText=$.text),Pe(S,Z=>[...Z,pe,{id:ne,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:_,segments:[]}],ce)}let Ne=!1;const Ce=_=>{Ns.current=Date.now(),os(S,pe=>{const Z=[...pe],z=Z.findIndex(fs=>fs.id===ne);if(z<0)return pe;const X=Z[z].segments??[],re=X[X.length-1],we=re?.type==="text"?re.thinking??"":"";let Ue="",je="",Ae=_;for(;Ae.length>0;)if(Ne){const fs=Ae.indexOf("</think>");fs>=0?(Ue+=Ae.slice(0,fs),Ae=Ae.slice(fs+8),Ne=!1):(Ue+=Ae,Ae="")}else{const fs=Ae.indexOf("<think>");fs>=0?(je+=Ae.slice(0,fs),Ae=Ae.slice(fs+7),Ne=!0):(je+=Ae,Ae="")}const Je=we+Ue||void 0,Yo=re?.type==="text"?[...X.slice(0,-1),{type:"text",content:re.content+je,thinking:Je,createdAt:re.createdAt}]:[...X,{type:"text",content:je,thinking:Je,createdAt:new Date().toISOString()}];return Z[z]={...Z[z],text:Z[z].text+je,segments:Yo},Z},ce)},Y=_=>{if(Ns.current=Date.now(),_.type==="session_start"&&_.sessionId){const pe=ce;ce=_.sessionId,pe&&pe!==_.sessionId&&ht(S,pe),rt(S,_.sessionId),Kn&&M.sessions.setModelOverride(_.sessionId,Kn).catch(()=>{}),_.userMessageId&&!l?.isResume&&Pe(S,z=>z.map(X=>X.id===_e?{...X,id:_.userMessageId}:X),_.sessionId);const Z=gt.get(S);if(Z&&Z.length>0&&Rs.set(_.sessionId,Z),ke.current===S){const z=Ee;(!z||z===He||z===_.sessionId)&&(ss(_.sessionId),Mt.set(S,_.sessionId),K&&Xn(K,_.sessionId),Et(X=>X.some(re=>re.id===He)?X.map(re=>re.id===He?{...re,id:_.sessionId}:re):X.some(re=>re.id===_.sessionId)?X:[...X,{id:_.sessionId,agentId:K??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}Pe(S,pe=>{const Z=[...pe],z=Z.findIndex(re=>re.id===ne);if(z<0)return pe;const X=[...Z[z].committedSegments??[]];return _.type==="thinking_commit"?X.push({type:"text",content:"",thinking:_.content,createdAt:_.createdAt}):X.push({type:"text",content:_.content,createdAt:_.createdAt}),Z[z]={...Z[z],committedSegments:X},Z},ce)},me=_=>{Ns.current=Date.now(),_.phase!=="heartbeat"&&((_.phase==="start"||_.phase==="end")&&Ds(S,{..._,phase:_.phase,ts:Date.now()},ce),_.phase==="start"?Pe(S,pe=>{const Z=[...pe],z=Z.findIndex(Ae=>Ae.id===ne);if(z<0)return pe;const X=[...Z[z].segments??[]];let re=!1;if(_.arguments)for(let Ae=X.length-1;Ae>=0;Ae--){const Je=X[Ae];if(Je.type==="tool"&&Je.tool===_.tool&&Je.status==="running"){X[Ae]={...Je,args:_.arguments},re=!0;break}}const we=`${_.tool}_${Date.now()}`,Ue=new Date().toISOString();re||X.push({type:"tool",key:we,tool:_.tool,status:"running",args:_.arguments,createdAt:Ue});const je=[...Z[z].committedSegments??[]];return _.arguments!==void 0&&je.push({type:"tool",key:we,tool:_.tool,status:"running",args:_.arguments,createdAt:Ue}),Z[z]={...Z[z],segments:X,committedSegments:je},Z},ce):_.phase==="output"?os(S,pe=>{const Z=[...pe],z=Z.findIndex(re=>re.id===ne);if(z<0)return pe;const X=[...Z[z].segments??[]];for(let re=X.length-1;re>=0;re--){const we=X[re];if(we.type==="tool"&&we.tool===_.tool&&we.status==="running"){X[re]={...we,liveOutput:Nl(we.liveOutput,_.output??"")};break}}return Z[z]={...Z[z],segments:X},Z},ce):_.phase==="subagent_progress"&&_.subagentEvent?os(S,pe=>{const Z=[...pe],z=Z.findIndex(Ue=>Ue.id===ne);if(z<0)return pe;const X=Ue=>{const je=[...Ue];for(let Ae=je.length-1;Ae>=0;Ae--){const Je=je[Ae];if(Je.type==="tool"&&(Je.tool==="spawn_subagent"||Je.tool==="spawn_subagents")&&Je.status==="running"){je[Ae]={...Je,subagentLogs:si(Je.subagentLogs,_.subagentEvent)};break}}return je},re=X(Z[z].segments??[]),we=X(Z[z].committedSegments??[]);return Z[z]={...Z[z],segments:re,committedSegments:we},Z},ce):Pe(S,pe=>{const Z=[...pe],z=Z.findIndex(je=>je.id===ne);if(z<0)return pe;const X=new Date().toISOString(),re=[...Z[z].segments??[]];let we;for(let je=re.length-1;je>=0;je--){const Ae=re[je];if(Ae.type==="tool"&&Ae.tool===_.tool&&Ae.status==="running"){we=Ae.subagentLogs,re[je]={...Ae,status:_.success===!1?"error":"done",args:_.arguments,result:_.result,error:_.error,durationMs:_.durationMs,liveOutput:void 0,createdAt:X};break}}const Ue=[...Z[z].committedSegments??[]];for(let je=Ue.length-1;je>=0;je--){const Ae=Ue[je];if(Ae.type==="tool"&&Ae.tool===_.tool&&Ae.status==="running"){Ue[je]={...Ae,status:_.success===!1?"error":"done",args:_.arguments,result:_.result,error:_.error,durationMs:_.durationMs,liveOutput:void 0,createdAt:X,subagentLogs:we??Ae.subagentLogs};break}}return Z[z]={...Z[z],segments:re,committedSegments:Ue},Z},ce))},te=new AbortController;yt.current=te;const le=l?.sessionIdOverride??(Ee===He?null:Ee),ie=le;ie&&rt(S,ie);try{Ns.current=Date.now();const _=await M.agents.messageStream(K,x,Ce,me,te.signal,W,le,l?.isRetry,l?.isResume,Y,Q,$,Kn);if(ke.current===S){_.merged&&Pe(S,Z=>Z.filter(z=>z.id!==ne&&z.id!==_e),ce),!_.merged&&_.segments?.length&&Pe(S,Z=>{const z=[...Z],X=z.findIndex(je=>je.id===ne);if(X<0)return Z;const re=ni(_.segments,z[X].segments);let we=_.content||z[X].text;we||(we=re.filter(je=>je.type==="text").map(je=>je.content).join(""));const Ue=!we?.trim()&&!re.some(je=>je.type==="text"&&(je.content||je.thinking)||je.type==="tool");return z[X]={...z[X],text:we,segments:re,committedSegments:re,isStopped:_.cancelled||z[X].isStopped,emptyReply:_.emptyReply||Ue||void 0,isError:_.emptyReply||Ue?!0:z[X].isError},z},ce),!_.merged&&!_.segments?.length&&Pe(S,Z=>{const z=[...Z],X=z.findIndex(Je=>Je.id===ne);if(X<0)return Z;const re=z[X],we=re.committedSegments??[],je=we.filter(Je=>Je.type==="text"&&!!Je.content).map(Je=>Je.content).join("")||_.content||re.text,Ae=!je?.trim()&&we.length===0;return(we.length>0||je||_.cancelled||_.emptyReply||Ae)&&(z[X]={...re,text:je,segments:we.length>0?we:re.segments,isStopped:_.cancelled||re.isStopped,emptyReply:_.emptyReply||Ae||void 0,isError:_.emptyReply||Ae?!0:re.isError}),z},ce),_.sessionId&&(ss(Z=>!Z||Z===He||Z===_.sessionId?_.sessionId:Z),Et(Z=>Z.some(z=>z.id===He)?Z.map(z=>z.id===He?{...z,id:_.sessionId}:z):Z.some(z=>z.id===_.sessionId)?Z:[...Z,{id:_.sessionId,agentId:K??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])),or(K).then(Z=>{if(ke.current===S&&(Os(Z),_.sessionId)){const z=Z.find(X=>X.id===_.sessionId);z&&Et(X=>X.some(we=>we.id===z.id)?X.map(we=>we.id===z.id?z:we):[z,...X.filter(we=>we.id!==He)])}});const pe=_.sessionId??(ie&&ie!==He?ie:null);if(!te.signal.aborted&&!_.merged&&_.segments===void 0&&R==="direct"&&K&&pe)try{if((await M.sessions.streamStatus(K,pe)).status==="streaming"){Pe(S,z=>z.map(X=>X.id===ne?{...X,isStreaming:!0,isStopped:!1,segments:(X.segments??[]).map(re=>re.type==="tool"&&(re.status==="stopped"||re.status==="running")?{...re,status:"running"}:re)}:X),pe),Ye(S),yt.current===te&&(yt.current=null),rt(S,pe),Vs(K,pe,S);return}}catch{}}}catch(_){const pe=_?.sessionId;pe&&R==="direct"&&ke.current===S&&(ss(pe),Et(z=>z.map(X=>X.id===He?{...X,id:pe}:X)),or(K).then(z=>{if(ke.current!==S)return;Os(z);const X=z.find(re=>re.id===pe);X&&Et(re=>re.some(Ue=>Ue.id===X.id)?re.map(Ue=>Ue.id===X.id?X:Ue):[X,...re])})),hr(_)&&pr();const Z=br(_,o);Z?Pe(S,z=>{const X=[...z],re=X.findIndex(we=>we.id===ne);if(re>=0){const we=X[re].segments??[];X[re]={...X[re],text:Z,isError:!0,segments:[...we,{type:"text",content:Z}]}}return X},ce):Pe(S,z=>{const X=[...z],re=X.findIndex(we=>we.id===ne);if(re>=0){const we=X[re];if(!(we.text||we.segments&&we.segments.length>0&&we.segments.some(je=>je.type==="text"&&(je.content||je.thinking)||je.type==="tool")))return z.filter(je=>je.id!==ne);X[re]={...we,isStopped:!0}}return X},ce)}Pe(S,_=>{const pe=[..._],Z=pe.findIndex(z=>z.id===ne);if(Z>=0){const z=(pe[Z].segments??[]).map(X=>X.type==="tool"&&X.status==="running"?{...X,status:"stopped"}:X);pe[Z]={...pe[Z],segments:z}}return pe},ce),te.signal.aborted&&Pe(S,_=>{const pe=[..._],Z=pe.findIndex(z=>z.id===ne);if(Z>=0){const z=pe[Z];if(!(z.text||z.segments&&z.segments.length>0&&z.segments.some(re=>re.type==="text"&&(re.content||re.thinking)||re.type==="tool")))return _.filter(re=>re.id!==ne);pe[Z]={...z,isStopped:!0}}return pe},ce);const Te=(gt.get(S)??[]).find(_=>_.id===ne),Ve=Ee&&Ee!==He?Ee:null,st=Te?.text||Te?.segments?.some(_=>_.type==="text"&&_.content||_.type==="tool");Te&&!st&&R==="direct"&&Ve&&!te.signal.aborted&&await(async(pe,Z)=>{for(let z=0;z<pe;z++){await new Promise(X=>setTimeout(X,Z));try{const re=(await M.sessions.getMessages(Ve,2)).messages.find(we=>we.role==="assistant");if(re?.content){const we=ia(re);Pe(S,Ue=>{const je=[...Ue],Ae=je.findIndex(Je=>Je.id===ne);return Ae>=0&&(je[Ae]={...je[Ae],text:we.text,segments:we.segments}),je},ce);return}}catch{}}})(5,3e3);const St=Ye(S);ce&&ht(S,ce),G(S),yt.current===te||yt.current===null?(yt.current=null,Ot.delete(ce??S),ke.current===S&&(ct(St>0),St===0&&Ut([]))):Ot.delete(ce??S)}};_a.current=Us;const[ko,Va]=n.useState(null),[cr,Yr]=n.useState(null),No=n.useMemo(()=>{for(let t=Ke.length-1;t>=0;t--)if(Ke[t]?.sender==="agent"&&!Ke[t]?.isActivityLog)return Ke[t].id;return null},[Ke]),So=n.useCallback(t=>{const l=t.segments?t.segments.filter(c=>c.type==="text").map(c=>c.content).join(`
|
|
39
|
-
`):t.text;navigator.clipboard.writeText(l),Va(t.id),setTimeout(()=>Va(c=>c===t.id?null:c),2e3)},[]),Xr=n.useCallback((t,l,c)=>{const x=ke.current,w=gt.get(x)??Ke,B=w.findIndex(Q=>Q.id===t.id);if(B<0)return;const W=l&&B>0&&w[B-1]?.id===l.id;Pe(x,Q=>{const S=Q.findIndex($=>$.id===(W?l.id:t.id));return S>=0?Q.slice(0,S):Q}),Us(c,{isRetry:!0})},[Ke,Pe]),Co=n.useCallback(t=>{const l=ke.current,c=gt.get(l)??Ke,x=c.findIndex(Q=>Q.id===t.id);if(x<0)return;let w=null;for(let Q=x-1;Q>=0;Q--)if(c[Q]?.sender==="user"){w=c[Q];break}const B=w?.text??"";if(!B)return;if(x<c.length-1){const Q=c.length-1-x;Yr({retryMsg:t,userMsg:w,retryText:B,followCount:Q});return}Xr(t,w,B)},[Ke,Xr]),To=n.useCallback(t=>{const l=ke.current;(gt.get(l)??Ke).findIndex(w=>w.id===t.id)<0||(Pe(l,w=>{const B=[...w],W=B.findIndex($=>$.id===t.id);if(W<0)return w;const Q=B[W],S=[...Q.segments??[]];for(;S.length>0;){const $=S[S.length-1];if($.type==="tool"&&($.status==="stopped"||$.status==="running"))S.pop();else if($.type==="text"&&!$.content)S.pop();else break}return B[W]={...Q,segments:S,isStopped:!1,isError:!1},B}),Us("[Continue from where you left off. Do not repeat content already generated.]",{isResume:!0}))},[Ke,Pe]),Mo=n.useCallback(t=>{const l=t.sender==="user"?a?.name??o("page.fallbackYou"):t.agentName??o("page.fallbackAgent");if(Qe({id:t.id,sender:l,text:t.text}),R==="channel"&&t.sender==="agent"&&t.agentName){const c=`@${t.agentName} `;Pt(x=>x.startsWith(c)?x:c+x)}cs.current?.focus()},[a?.name,R,o]),Eo=async t=>{if(!qs||!K||R!=="direct")return;const l=Ee;if(!(!l||l===He)){Wa(!0);try{const c=await M.agents.evolveFromMessage(K,{parentSessionId:l,sourceMessageId:qs.id.startsWith("a_")||qs.id.startsWith("u_")?void 0:qs.id,sourceText:(qs.text||"").slice(0,500)||void 0,userNote:t.trim()||void 0}),x=new Date().toISOString(),w={id:c.sessionId,agentId:K,userId:a?.id??null,title:"Remember / Evolution",isMain:!1,metadata:{kind:"evolution",parentSessionId:c.parentSessionId,sourceMessageId:qs.id,sourceAgentId:K,createdFrom:"remember_button"},createdAt:x,lastMessageAt:x};Kr(null),Os(W=>[w,...W.filter(Q=>Q.id!==w.id)]),Et(W=>W.some(Q=>Q.id===w.id)?W:[...W,w]),ss(w.id);const B=gr("direct",K,Ie,nt);Mt.set(B,w.id),Xn(K,w.id),xe(B),Nt([]),ts(!1),Kt.current=null,await Us(c.seedPrompt,{sessionIdOverride:c.sessionId})}catch(c){console.error("evolve-from-message failed",c)}finally{Wa(!1)}}},dr=async t=>{const l=Ee;ss(t.id),Bs(!1),ts(!1),Kt.current=null,ms(),us(!1),Ts.current=0,Ws(0);const c=ke.current,x=dt(c),w=!!x&&(x.has(t.id)||x.has(He)),B=Re(c)&&w;ct(B),Ut(B?Ot.get(t.id)??[]:[]),Mt.set(c,t.id),K&&Xn(K,t.id),l&&l!==He&&Gt(c,l),ot(c,t.id),Et(Q=>Q.some(S=>S.id===t.id)?Q:[...Q,t]),K&&Ji(K,t.id),await Ur(t.id,c);const W=t.metadata?.modelOverride;Yn(W?.provider&&W?.model?{provider:W.provider,model:W.model}:null),K&&!B&&Vs(K,t.id,c)},Ao=t=>{if(Et(l=>l.filter(c=>c.id!==t)),K&&t!==He&&Zi(K,t),Ee===t){const l=Sn.filter(c=>c.id!==t);l.length>0?dr(l[l.length-1]):Qr()}},qa=n.useCallback(async t=>{if(t.length<2){Cs([]);return}Ma(!0);try{const l=R==="channel"?"channel":R==="direct"?"direct":"all",c=R==="channel"?Ie:void 0,{results:x}=await M.messages.search(t,{scope:l,channel:c,limit:30});Cs(x)}catch{Cs([])}Ma(!1)},[R,Ie]),Io=n.useCallback(t=>{en(t),Br.current&&clearTimeout(Br.current),Br.current=setTimeout(()=>qa(t),300)},[qa]),Po=n.useCallback(t=>{Mn(!1),en(""),Cs([]),t.source==="channel"&&t.channel?($e("channel"),Ct(t.channel)):t.source==="direct"&&t.agentId&&($e("direct"),lt(t.agentId)),setTimeout(()=>{const l=document.getElementById(`msg-${t.id}`);l&&(l.scrollIntoView({behavior:"smooth",block:"center"}),l.classList.add("bg-brand-500/10"),setTimeout(()=>l.classList.remove("bg-brand-500/10"),2e3))},500)},[]),Qr=()=>{ss(He);const t=ke.current;xe(t),Nt([]),ts(!1),Kt.current=null,Bs(!1),Et(l=>{const c=l.filter(x=>x.id!==He);return[{id:He,agentId:K??"",userId:null,title:o("page.newChat"),createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()},...c]})},Lo=t=>{Pt(t);const l=cs.current?.selectionStart??t.length,c=t.slice(0,l),x=c.lastIndexOf("@");if(x>=0){const w=x===0?"":c[x-1];if(x===0||/[\s\n,,。!?!?;;::、()()\[\]【】]/.test(w)){const W=c.slice(x+1);if(!W.includes(" ")&&!W.includes(`
|
|
40
|
-
`)){mo(),En(!0),lo(W.toLowerCase()),tn(0);return}}}En(!1)},ur=(t,l,c)=>{const x=cs.current?.selectionStart??tt.length,B=tt.slice(0,x).lastIndexOf("@"),W=tt.slice(x),Q=l&&c?`@[${t}](${l}:${c})`:t.includes(" ")?`@[${t}]`:`@${t}`,S=tt.slice(0,B)+Q+" "+W;Pt(S),En(!1),tn(0);const $=B+Q.length+1;requestAnimationFrame(()=>{cs.current?.setSelectionRange($,$)})},_o=10*1024*1024,Ua=5,Ro=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"]),ln=n.useCallback(t=>t.type.startsWith("image/")||Ro.has(t.type),[]),Zr=t=>t.dataUrl.startsWith("data:image/"),Do=(t,l)=>{if(Zr({dataUrl:l}))return null;const c=t.split(".").pop()?.toLowerCase()??"";return{pdf:"📄",docx:"📝",doc:"📝",xlsx:"📊",xls:"📊",pptx:"📎",csv:"📊",json:"🔧",xml:"🔧",html:"🌐",epub:"📚"}[c]??"📁"},_n=n.useCallback(t=>{const l=Array.from(t).filter(ln);if(l.length!==0)for(const c of l){if(c.size>_o)continue;const x=new FileReader;x.onload=()=>{const w=x.result;Tr(B=>B.length>=Ua||B.some(W=>W.dataUrl===w)?B:[...B,{id:`img_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,dataUrl:w,name:c.name}])},x.readAsDataURL(c)}},[ln]),$o=n.useCallback(t=>{Tr(l=>l.filter(c=>c.id!==t))},[]),Oo=n.useCallback(t=>{const l=t.clipboardData?.files;if(l&&l.length>0){const c=Array.from(l).filter(ln);c.length>0&&(t.preventDefault(),_n(c))}},[_n,ln]),Fo=n.useCallback(t=>{t.preventDefault();const l=t.dataTransfer?.files;l&&l.length>0&&_n(Array.from(l).filter(ln))},[_n,ln]),Bo=n.useCallback(t=>{t.preventDefault()},[]),Ze=f.find(t=>t.id===K),Jr=a?.name??o("page.fallbackYou"),Ga=ut[ut.length-1],zo=It&&Ga?.sender==="agent",Wo=Nr&&Ga?.sender==="agent",Ka=n.useMemo(()=>{if(R!=="channel")return null;if(Ie.startsWith("group:custom:")){const l=bt.find(c=>c.channelKey===Ie);return l?.members?new Set(l.members.filter(c=>c.type==="agent").map(c=>c.id)):null}if(!at)return null;const t=ns.find(l=>l.id===at);return t?new Set(t.members.filter(l=>l.type==="agent").map(l=>l.id)):null},[R,Ie,at,ns,bt]),Ya=f.filter(t=>Ka?Ka.has(t.id):!0).filter(t=>t.name.toLowerCase().includes(Pa)),Xa=co.filter(t=>t.name.toLowerCase().includes(Pa)),Ho={workflow:"⚙️",project:"📁",requirement:"📋",task:"✅",deliverable:"📦"},Gs=n.useMemo(()=>[...Ya.map(t=>({kind:"agent",agent:t})),...Xa.map(t=>({kind:"entity",entity:t}))],[Ya,Xa]),ea=N.find(t=>t.id===nt),ta=nt===a?.id||!nt,zt=bt.find(t=>t.channelKey===Ie);n.useEffect(()=>{if(s||!Ie.startsWith("group:custom:"))return;const t=bt.find(l=>l.channelKey===Ie);!t||t.members||M.groupChats.getById(t.id).then(l=>{l.chat.members&&Cn(c=>c.map(x=>x.id===t.id?{...x,members:l.chat.members}:x))}).catch(()=>{})},[s,Ie,bt]);const sa=n.useCallback(async()=>{if(s||R!=="direct"||!K){Pr([]);return}try{ri("/approvals");const{approvals:t}=await M.approvals.list("pending");Pr(t.filter(l=>l.status==="pending"&&Array.isArray(l.questions)&&l.questions.length>0&&(l.details?.agentId??l.agentId)===K))}catch{}},[s,R,K]),na=n.useCallback(async()=>{if(s||R!=="direct"||!K||!Ee||Ee===He){_r([]);return}try{ri("/notifications");const{notifications:t}=await M.notifications.list(a?.id,!0,{type:"agent_report",limit:30}),l=t.filter(c=>!c.read&&c.type==="agent_report"&&!c.metadata?.creditExhausted&&c.metadata?.agentId===K&&wc(c)===Ee).sort((c,x)=>new Date(x.createdAt).getTime()-new Date(c.createdAt).getTime()).slice(0,5);_r(l),Dr(l.map(c=>c.metadata?.messageId).filter(c=>typeof c=="string"&&c.length>0))}catch{}},[s,R,K,Ee,a?.id]);n.useEffect(()=>{sa(),na();let t=null;const l=()=>{t||(t=setTimeout(()=>{t=null,sa(),na()},400))},c=ze.on("approval:requested",l),x=ze.on("notification",l),w=()=>l();return window.addEventListener("markus:notifications-changed",w),()=>{t&&clearTimeout(t),c(),x(),window.removeEventListener("markus:notifications-changed",w)}},[sa,na]);const Vo=n.useCallback(async(t,l)=>{wa(t);try{await M.approvals.respond(t,l.approved,a?.id,l.comment,l.selectedOption,l.answers),Pr(c=>c.filter(x=>x.id!==t)),Lr(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}wa(null)},[a?.id]),qo=n.useCallback(async t=>{ka(t);try{const l=Qn.find(x=>x.id===t)??Js,c=typeof l?.metadata?.messageId=="string"?l.metadata.messageId:null;await M.notifications.markRead(t),_r(x=>x.filter(w=>w.id!==t)),c&&Dr(x=>x.filter(w=>w!==c)),Rr(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}ka(null)},[Qn,Js]),Qa=R==="channel"?zt?.name??Ie:R==="direct"?Ze?.name??o("page.selectAgent"):R==="dm"?ta?o("chat.myNotes"):ea?.name??o("page.directMessage"):o("page.chatTitle"),Uo=n.useMemo(()=>Math.floor(Math.random()*5),[K,Ee]),Za=K?o(`page.placeholder.directOptions.${Uo}`):"",Rn=R==="direct"&&!!Ze&&Ze.status==="offline",Go=R==="channel"?zt?o("page.placeholder.channel",{name:zt.name}):o("page.placeholder.channelWithMention",{name:Ie}):R==="dm"?ta?o("page.placeholder.dmSelf"):o("page.placeholder.dmOther",{name:ea?.name??""}):o(Rn?"page.placeholder.agentOffline":K?"page.placeholder.direct":"page.placeholder.noAgent"),Ko=v&&p==="chat",Dn=k==="chat"&&ut.length===0&&!It&&!va,Wt=k==="chat"&&ut.length>0;Er.current=Wt;const ra=!!(tt.trim()||Lt.length>0);return e.jsxs("div",{ref:ae,className:"flex-1 overflow-hidden flex relative",children:[!g&&e.jsx(ql,{authUser:a,agents:f,teams:ns,humans:N,tasks:Jn,externalAgents:ro,groupChats:bt,chatMode:R,selectedAgent:K,activeChannel:Ie,activeDmUserId:nt,previewMode:s,onSelectAgent:t=>{$e("direct"),lt(t),P("chat"),pt(!1),v&&H()},onSelectChannel:t=>{$e("channel"),Ct(t),P("chat"),pt(!1),v&&H()},onSelectDm:t=>{$e("dm"),Ls(t),P("chat"),pt(!1),v&&H()},onSelectTeam:t=>{const l=bt.find(x=>x.type==="team"&&x.teamId===t),c=l?.channelKey??`group:${t}`;v?D(t):($e("channel"),Ct(c),P("chat"),pt(!1),!Xt&&!We&&jt(!0),l||(nn(),_t()))},selectedTeamId:at??(R==="direct"&&Ze?.teamId?Ze.teamId:null),onRefreshTeams:_t,onRefreshAgents:Bt,onRefreshHumans:Ln,onRefreshGroupChats:nn,onViewProfile:kt,onManageGroupMembers:t=>{$e("channel"),Ct(t),P("chat"),pt(!0),v&&H()},unreadByAgent:nr,unreadByChannel:sr,width:v?void 0:De.width,onResizeStart:v?void 0:De.onResizeStart,hidden:v&&p!=="roster"||!v&&se,onCollapse:()=>Me(!0),initialLoading:I}),v&&p==="team"&&C&&(()=>{const t=ns.find(x=>x.id===C);if(!t)return null;const l=f.filter(x=>x.teamId===C),c=bt.find(x=>x.type==="team"&&x.teamId===C);return e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 h-12 shrink-0 border-b border-border-default",children:[e.jsx("button",{onClick:()=>{window.location.hash=xt.TEAM},className:"p-1.5 -ml-1 rounded-lg hover:bg-surface-overlay transition-colors shrink-0 text-fg-secondary",children:e.jsx("svg",{width:"18",height:"18",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg bg-brand-500/15 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"text-sm font-semibold text-fg-primary truncate",children:t.name}),e.jsx("p",{className:"text-[10px] text-fg-tertiary",children:o("chat.members_other",{count:t.members?.length||l.length})})]})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-3 py-3 space-y-1",children:[c&&(()=>{const x=sr[c.channelKey]??0;return e.jsxs("button",{onClick:()=>{$e("channel"),Ct(c.channelKey),P("chat"),H()},className:"w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors",children:[e.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-500/15 flex items-center justify-center shrink-0",children:e.jsx("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",className:"text-brand-500",children:e.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"})})}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsx("div",{className:"text-sm font-medium text-fg-primary truncate",children:c.name}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:o("chat.groupChat")})]}),x>0?e.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:x}):e.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:e.jsx("polyline",{points:"9 18 15 12 9 6"})})]})})(),l.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-[10px] font-semibold text-fg-muted uppercase tracking-wider px-2.5 pt-2",children:o("chat.agents")}),l.map(x=>{const w=nr.get(x.id)??0,B=x.status==="offline";return e.jsxs("button",{onClick:()=>{$e("direct"),lt(x.id),P("chat"),H()},className:`w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors ${B?"opacity-50":""}`,children:[e.jsx(vt,{name:x.name||"Agent",avatarUrl:x.avatarUrl,size:36}),e.jsxs("div",{className:"flex-1 min-w-0 text-left",children:[e.jsxs("div",{className:"text-sm font-medium text-fg-primary truncate flex items-center gap-1.5",children:[x.name,B&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:o("common:status.offline")})]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary truncate",children:x.role||x.status})]}),w>0?e.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:w}):e.jsx("span",{className:`w-2 h-2 rounded-full shrink-0 ${x.status==="idle"?"bg-green-500":x.status==="working"?"bg-blue-500":"bg-gray-400"}`})]},x.id)})]})]})]})})(),!g&&Xt&&!We&&!v&&!se&&(()=>{const t=at??(R==="direct"?Ze?.teamId:void 0);if(!t)return null;const l=ns.find(x=>x.id===t);if(!l)return null;const c=bt.find(x=>x.type==="team"&&x.teamId===t);return e.jsx(gi,{team:l,agents:f,humans:N,authUser:a,groupChat:c,chatMode:R,selectedAgent:K,activeChannel:Ie,teams:ns,onSelectAgent:x=>{$e("direct"),lt(x),P("chat"),pt(!1)},onSelectChannel:x=>{$e("channel"),Ct(x),P("chat"),pt(!1)},onSelectDm:x=>{$e("dm"),Ls(x),P("chat"),pt(!1)},onBack:()=>jt(!1),onViewProfile:kt,onRefreshAgents:Bt,onRefreshTeams:_t,unreadByAgent:nr,width:ft.width,onResizeStart:ft.onResizeStart})})(),!g&&Fe&&!v&&!se&&(()=>{const t=at??(R==="direct"?Ze?.teamId:void 0);if(!t)return null;const l=ns.find(x=>x.id===t);if(!l)return null;const c=bt.find(x=>x.type==="team"&&x.teamId===t);return e.jsxs("div",{"data-l2-floating":!0,className:"absolute z-30 inset-0",style:{left:De.width+6},children:[e.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:()=>wt(!1)}),e.jsx("div",{className:"relative h-full",style:{width:ft.width+8},children:e.jsx(gi,{team:l,agents:f,humans:N,authUser:a,groupChat:c,chatMode:R,selectedAgent:K,activeChannel:Ie,teams:ns,onSelectAgent:x=>{$e("direct"),lt(x),P("chat"),pt(!1),wt(!1)},onSelectChannel:x=>{$e("channel"),Ct(x),P("chat"),pt(!1),wt(!1)},onSelectDm:x=>{$e("dm"),Ls(x),P("chat"),pt(!1),wt(!1)},onBack:()=>wt(!1),onViewProfile:x=>{kt(x),wt(!1)},onRefreshAgents:Bt,onRefreshTeams:_t,unreadByAgent:nr,width:ft.width})})]})})(),!g&&(!v||Ko)&&e.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col ${v||J?"min-w-0":"min-w-[400px]"}`,children:[e.jsxs("div",{className:"shrink-0 relative pb-2",children:[v?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center px-3 h-11 gap-2",children:[e.jsx("button",{onClick:()=>{window.location.hash=A.current},className:"text-fg-secondary hover:text-fg-primary transition-colors p-1 -ml-1 shrink-0",children:e.jsx("svg",{width:"20",height:"20",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"15 18 9 12 15 6"})})}),e.jsx("span",{className:"font-semibold text-sm truncate min-w-0 flex-1",children:Qa}),R==="direct"&&Ze&&e.jsx(Oi,{agent:Ze,tasks:Jn,onViewProfile:kt,streamActive:pa})]}),e.jsxs("div",{className:"flex items-center px-3 h-9 gap-1 border-t border-border-default/40",children:[e.jsx("button",{onClick:()=>{gs(k)?history.back():P("chat")},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${k==="chat"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:o("page.chatTitle")}),e.jsx("button",{onClick:()=>{gs(k)||ws()},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${gs(k)?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:o(R==="channel"?"page.teamTab":"page.profileTab")}),e.jsx("div",{className:"flex-1"}),e.jsx("button",{onClick:()=>{Mn(!zs),zs||(en(""),Cs([]))},className:`p-1 rounded-md transition-colors shrink-0 ${zs?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,children:e.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"})})}),R==="channel"&&zt?.type==="custom"&&e.jsxs("button",{onClick:()=>pt(!Tn),className:`text-[11px] px-2 py-1 rounded-md font-medium shrink-0 flex items-center gap-1 ${Tn?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:[e.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),zt.members?.length??zt.memberCount??0]}),R==="direct"&&!gs(k)&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Qr,className:"text-[11px] text-brand-500 px-2 py-1 rounded-md bg-brand-500/10 font-medium shrink-0",children:o("page.newChatPlus")}),e.jsx("button",{ref:Zn,onClick:()=>Bs(!Fs),className:`p-1 rounded-md transition-colors shrink-0 ${Fs?"bg-surface-overlay text-fg-primary":"text-fg-tertiary"}`,title:o("page.historyTitle"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]})]})]}):(()=>{const t=at?ns.find($=>$.id===at):void 0,l=R==="direct"&&K?kc:R==="channel"&&at?Nc:["chat"],c=async()=>{const $=Vn.trim();if(!$){Vt(!1);return}try{R==="direct"&&K?(await M.agents.updateConfig(K,{name:$}),Bt()):R==="channel"&&at&&(await M.teams.update(at,{name:$}),_t())}catch{}Vt(!1)},x=async()=>{try{R==="direct"&&K?(await M.agents.updateConfig(K,{roleDescription:Jt}),Bt()):R==="channel"&&at&&(await M.teams.update(at,{description:Jt}),_t())}catch{}yn(!1)},w=R==="direct"?Ze?.name:R==="channel"?t?.name??zt?.name:ea?.name??"",B=R==="direct"?Ze?.role||"":R==="channel"&&t?.description||"",W=R==="direct"?Ze?.avatarUrl:void 0,Q=w||"U",S=R==="direct"&&K||R==="channel"&&at;return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{className:"flex items-center px-4 h-14 gap-2.5",children:[se&&!v&&e.jsx("button",{onClick:()=>Me(!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:o("page.toggleSidebar"),children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),(!Xt||We)&&(R==="channel"&&at||R==="direct"&&Ze?.teamId)&&e.jsx("button",{onClick:mn,className:`w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 ${Fe?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:"Toggle team panel",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",ry:"2"}),e.jsx("line",{x1:"9",y1:"3",x2:"9",y2:"21"})]})}),S&&(R==="channel"&&at?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-600 text-white flex items-center justify-center text-sm font-bold shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]})}):e.jsx(vt,{name:Q,avatarUrl:W,size:36,className:"rounded-xl shrink-0"})),S?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Rt?e.jsx("input",{ref:Qs,value:Vn,onChange:$=>bn($.target.value),onBlur:c,onKeyDown:$=>{$.key==="Enter"&&c(),$.key==="Escape"&&Vt(!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}):e.jsx("span",{className:"text-sm font-semibold truncate cursor-pointer hover:text-brand-500 transition-colors",onClick:()=>{bn(w??""),Vt(!0)},title:"Click to edit name",children:w}),R==="direct"&&Ze&&e.jsx(Oi,{agent:Ze,tasks:Jn,onViewProfile:kt,streamActive:pa})]}),(R==="direct"||R==="channel"&&at)&&(Xs?e.jsx("input",{ref:Dt,value:Jt,onChange:$=>Is($.target.value),onBlur:x,onKeyDown:$=>{$.key==="Enter"&&x(),$.key==="Escape"&&yn(!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 description...",autoFocus:!0}):e.jsx("div",{className:"text-[11px] text-fg-tertiary truncate cursor-pointer hover:text-fg-secondary transition-colors mt-0.5",onClick:()=>{Is(B),yn(!0)},title:"Click to edit description",children:B||"No description"}))]}):e.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:Qa}),R==="dm"&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:ta?o("page.privateNotepad"):""})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2 shrink-0",children:[e.jsx("button",{onClick:()=>{Mn(!zs),zs||(en(""),Cs([]))},className:`p-1.5 rounded-md transition-colors ${zs?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.searchMessages"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.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"})})}),R==="channel"&&zt?.type==="custom"&&e.jsxs("button",{onClick:()=>pt(!Tn),className:`text-xs px-2.5 py-1 rounded-md border transition-colors flex items-center gap-1.5 ${Tn?"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:[e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M17 21v-2a4 4 0 0 0-4-4H5a4 4 0 0 0-4 4v2"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M23 21v-2a4 4 0 0 0-3-3.87"}),e.jsx("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"})]}),zt.members?.length??zt.memberCount??0]}),R==="direct"&&Ze&&k==="chat"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:Qr,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:o("page.newChatButton")}),e.jsx("button",{ref:Zn,onClick:()=>Bs(!Fs),className:`p-1.5 rounded-md transition-colors ${Fs?"bg-surface-overlay text-fg-primary":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.historyTitle"),children:e.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v6h4.5m4.5 0a9 9 0 11-18 0 9 9 0 0118 0z"})})})]}),!v&&ue&&e.jsx("button",{onClick:()=>ue.toggleRightPanel(),className:`p-1.5 rounded-md transition-colors ${J?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated"}`,title:o("page.rightPanelToggle",{defaultValue:"Toggle side panel"}),children:e.jsxs("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:1.5,children:[e.jsx("rect",{x:"3",y:"4",width:"18",height:"16",rx:"2"}),e.jsx("path",{d:"M15 4v16"})]})})]})]}),l.length>1&&e.jsx("div",{className:"flex items-center gap-1 px-4 pb-1.5 overflow-x-auto scrollbar-hide",children:l.map($=>e.jsxs("button",{onClick:()=>P($),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${k===$?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[e.jsx("span",{children:Cc($)}),Sc($,o)]},$))})]})})(),zs&&e.jsxs("div",{className:"border-b border-border-default bg-surface-secondary/50 px-4 py-2 space-y-2 animate-in slide-in-from-top-2 duration-200",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 relative",children:[e.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:e.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"})}),e.jsx("input",{autoFocus:!0,value:Ca,onChange:t=>Io(t.target.value),onKeyDown:t=>{t.key==="Escape"&&(Mn(!1),en(""),Cs([]))},placeholder:o("page.searchPlaceholder"),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"})]}),e.jsx("button",{onClick:()=>{Mn(!1),en(""),Cs([])},className:"text-fg-tertiary hover:text-fg-secondary text-xs px-1",children:"✕"})]}),Ta&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-fg-tertiary py-1",children:[e.jsxs("svg",{className:"animate-spin h-3 w-3",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),o("page.searching")]}),!Ta&&Ca.length>=2&&Fr.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary py-1",children:o("page.noSearchResults")}),Fr.length>0&&e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-0.5",children:Fr.map(t=>e.jsxs("button",{onClick:()=>Po(t),className:"w-full text-left px-3 py-2 rounded-lg hover:bg-surface-elevated transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-fg-tertiary mb-0.5",children:[e.jsx("span",{className:`px-1.5 py-0.5 rounded text-[10px] font-medium ${t.source==="channel"?"bg-blue-500/10 text-blue-500":"bg-emerald-500/10 text-emerald-500"}`,children:t.source==="channel"?"#":"1:1"}),t.senderName&&e.jsx("span",{children:t.senderName}),e.jsx("span",{children:new Date(t.createdAt).toLocaleDateString(void 0,{month:"short",day:"numeric"})})]}),e.jsx("div",{className:"text-xs text-fg-secondary line-clamp-2 group-hover:text-fg-primary transition-colors",children:t.text.length>200?t.text.slice(0,200)+"…":t.text})]},t.id))})]}),R==="direct"&&K&&k==="chat"&&Sn.length>1&&e.jsx("div",{className:"flex items-center gap-0 px-3 overflow-x-auto scrollbar-hide",children:Sn.map(t=>e.jsxs("div",{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] ${t.id===Ee?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>{if(t.id===He){ss(He);const l=ke.current;xe(l),Nt([])}else dr(t)},children:[t.isMain&&e.jsx("span",{className:"text-[10px] opacity-50 shrink-0",children:"●"}),e.jsx("span",{className:"truncate",children:t.id===He?o("page.newChat"):t.isMain?o("page.sessionMain"):t.title||o("page.sessionConversation")}),!t.isMain&&e.jsx("button",{onClick:l=>{l.stopPropagation(),Ao(t.id)},className:"opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-fg-secondary transition-opacity shrink-0",children:"✕"})]},t.id))}),R==="direct"&&k==="chat"&&(Sn.find(t=>t.id===Ee)??Ir.find(t=>t.id===Ee))?.metadata?.kind==="evolution"&&e.jsx("div",{className:"px-4 py-1.5 text-[11px] text-fg-tertiary border-b border-border-default bg-surface-secondary/40",children:o("page.messageActions.evolvedFrom")}),R==="channel"&&zt?.type==="custom"&&Tn&&(()=>{const t=zt,l=t.members??[],c=[];for(const x of f)l.some(w=>w.id===x.id)||c.push({id:x.id,name:x.name,type:"agent",subtitle:x.role||"Agent"});for(const x of N)l.some(w=>w.id===x.id)||c.push({id:x.id,name:x.name,type:"human",subtitle:x.email||x.role||""});return e.jsxs("div",{className:"bg-surface-secondary/80 px-4 py-3 flex flex-col gap-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"text-xs font-semibold text-fg-secondary",children:[o("page.members")," (",l.length,")"]}),e.jsx("button",{onClick:()=>pt(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(x=>e.jsxs("span",{className:`inline-flex items-center gap-1.5 px-2 py-1 rounded-full text-[11px] font-medium ${x.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:[e.jsx(vt,{name:x.name,size:16,bgClass:x.type==="agent"?"bg-brand-500/15 text-brand-500":"bg-green-500/15 text-green-600"}),x.name,x.id!==a?.id&&e.jsx("button",{onClick:async()=>{try{await M.groupChats.removeMember(t.id,x.id),Cn(w=>w.map(B=>B.id===t.id?{...B,members:(B.members??[]).filter(W=>W.id!==x.id),memberCount:(B.memberCount??1)-1}:B))}catch{}},className:"ml-0.5 hover:text-red-500 transition-colors",title:o("common:remove"),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},x.id))}),c.length>0&&e.jsx("div",{className:"mt-1",children:e.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:async x=>{const w=x.target.value;if(!w)return;const B=c.find(W=>W.id===w);if(B)try{await M.groupChats.addMember(t.id,B.id,B.type,B.name),Cn(W=>W.map(Q=>Q.id===t.id?{...Q,members:[...Q.members??[],{id:B.id,name:B.name,type:B.type}],memberCount:(Q.memberCount??0)+1}:Q))}catch{}},children:[e.jsx("option",{value:"",children:o("page.addMemberPlaceholder")}),c.map(x=>e.jsxs("option",{value:x.id,children:["[",x.type==="agent"?"Agent":"Human","] ",x.name]},x.id))]})})]})})(),R==="direct"&&K&&Fs&&e.jsxs("div",{ref:$r,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:[e.jsxs("div",{className:"px-4 py-3 border-b border-border-default flex items-center justify-between",children:[e.jsx("span",{className:"text-xs font-semibold text-fg-secondary uppercase tracking-wider",children:o("page.historyTitle")}),e.jsx("button",{onClick:()=>Bs(!1),className:"text-fg-tertiary hover:text-fg-secondary text-xs",children:"✕"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto p-2",children:[Ir.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6",children:o("page.noConversationsYet")}),(()=>{const t=new Date,l=new Date(t.getFullYear(),t.getMonth(),t.getDate()).getTime(),c=l-864e5,x=l-7*864e5,w=[],B=[],W=[],Q=[],S=[];for(const $ of Ir){const Le=new Date($.lastMessageAt).getTime();Le>=l?B.push($):Le>=c?W.push($):Le>=x?Q.push($):S.push($)}return B.length>0&&w.push({label:o("page.dateToday"),items:B}),W.length>0&&w.push({label:o("page.dateYesterday"),items:W}),Q.length>0&&w.push({label:o("page.datePrevious7Days"),items:Q}),S.length>0&&w.push({label:o("page.dateOlder"),items:S}),w.map($=>e.jsxs("div",{className:"mb-2",children:[e.jsx("div",{className:"text-[10px] font-semibold text-fg-tertiary uppercase tracking-wider px-3 py-1.5",children:$.label}),$.items.map(Le=>e.jsxs("button",{onClick:()=>{dr(Le)},className:`w-full text-left px-3 py-2.5 rounded-lg text-xs mb-0.5 transition-colors ${Le.id===Ee?"bg-brand-600/20 text-brand-500":"text-fg-secondary hover:bg-surface-elevated"}`,children:[e.jsxs("div",{className:"truncate font-medium flex items-center gap-1",children:[Le.isMain&&e.jsx("span",{className:"text-[10px] text-brand-500 opacity-80",children:"●"}),Le.isMain?o("page.sessionMain"):Le.title||o("page.sessionConversation")]}),e.jsx("div",{className:"text-fg-tertiary text-[10px] mt-0.5",children:new Date(Le.lastMessageAt).toLocaleString()})]},Le.id))]},$.label))})()]})]})]}),v&&k==="profile"&&R==="direct"&&K&&e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(pi,{agentId:K,onBack:()=>P("chat"),inline:!0,defaultTab:Hn,highlightMailboxId:pn,onSwipeBack:()=>{gs(he.current)?history.back():P("chat")},authUser:a})}),v&&k==="profile"&&R==="channel"&&at&&e.jsx("div",{className:"flex-1 overflow-y-auto",onTouchStart:v?$t.onTouchStart:void 0,onTouchEnd:v?$t.onTouchEnd:void 0,children:e.jsx(Ri,{teamId:at,onBack:()=>P("chat"),inline:!0,onSelectAgent:t=>{$e("direct"),lt(t),P("chat")}})}),!v&&gs(k)&&R==="direct"&&K&&e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(pi,{agentId:K,onBack:()=>P("chat"),inline:!0,headless:!0,activeTab:k,highlightMailboxId:pn,authUser:a})}),!v&&gs(k)&&R==="channel"&&at&&e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:e.jsx(Ri,{teamId:at,onBack:()=>P("chat"),inline:!0,headless:!0,activeTab:k,onSelectAgent:t=>{$e("direct"),lt(t),P("chat")}})}),e.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col relative ${Dn?"justify-center":""} ${k!=="chat"?"hidden":""}`,children:[va&&ut.length===0&&e.jsxs("div",{className:"flex-1 flex flex-col items-center justify-center gap-3",children:[e.jsxs("svg",{className:"animate-spin h-6 w-6 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),e.jsx("span",{className:"text-xs text-fg-tertiary animate-pulse",children:o("page.loadingChat",{defaultValue:"Loading conversation…"})})]}),Cr&&e.jsxs("div",{className:"absolute top-0 left-0 right-0 z-10 flex justify-center items-center gap-2 py-2 bg-gradient-to-b from-surface-primary/90 to-transparent pointer-events-none",children:[e.jsxs("svg",{className:"animate-spin h-3.5 w-3.5 text-brand-400",viewBox:"0 0 24 24",fill:"none",children:[e.jsx("circle",{className:"opacity-25",cx:"12",cy:"12",r:"10",stroke:"currentColor",strokeWidth:"4"}),e.jsx("path",{className:"opacity-75",fill:"currentColor",d:"M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"})]}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:o("page.loadingEarlierMessages")})]}),e.jsxs("div",{ref:sn,className:`${Dn?"hidden":"flex-1"} overflow-y-auto ${v?"p-2.5":`p-5 ${q}`}`,onScroll:vo,onTouchStart:v?$t.onTouchStart:void 0,onTouchEnd:v?$t.onTouchEnd:void 0,children:[ut.length>0&&e.jsx("div",{style:{height:xs.getTotalSize(),width:"100%",position:"relative"},children:xs.getVirtualItems().map(t=>{const l=t.index,c=ut[l],x=l>0?ut[l-1]:null,w=ai(c.rawCreatedAt),B=x?ai(x.rawCreatedAt):"",W=!!(w&&B&&w!==B),Q=l===ut.length-1,$=zo&&Q&&It||!!c.isStreaming,Le=Wo&&Q||$,ve=R==="channel"||!$||c.isStopped;return e.jsx("div",{"data-index":l,ref:xs.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${t.start}px)`},children:e.jsxs("div",{className:"pb-3",children:[W&&e.jsxs("div",{className:"flex items-center gap-3 py-2 my-1",children:[e.jsx("div",{className:"flex-1 h-px bg-border-default"}),e.jsx("span",{className:"text-[10px] text-fg-tertiary font-medium uppercase tracking-wider shrink-0",children:fl(c.rawCreatedAt,u)}),e.jsx("div",{className:"flex-1 h-px bg-border-default"})]}),e.jsxs("div",{id:`msg-${c.id}`,className:"group/msg flex gap-3 transition-colors rounded-lg",children:[R==="channel"?e.jsx("div",{className:"shrink-0 cursor-pointer",onClick:fe=>{if(c.sender==="agent"&&c.agentId){const ne=fe.currentTarget.getBoundingClientRect();is({agentId:c.agentId,top:ne.top,left:ne.right+8})}},children:e.jsx(vt,{name:c.sender==="user"?Jr:c.agentName??o("page.fallbackAgent"),avatarUrl:c.sender==="user"?a?.avatarUrl:f.find(fe=>fe.id===c.agentId)?.avatarUrl,size:32,bgClass:c.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:c.sender==="agent"?"hover:ring-1 hover:ring-brand-500/40 rounded-lg":"rounded-lg"})}):e.jsx("div",{className:"shrink-0",children:e.jsx(vt,{name:c.sender==="user"?Jr:c.agentName??(R==="direct"?Ze?.name??o("page.fallbackAgent"):o("page.fallbackAgent")),avatarUrl:c.sender==="user"?a?.avatarUrl:f.find(fe=>fe.id===(c.agentId??(R==="direct"?Ze?.id:void 0)))?.avatarUrl,size:32,bgClass:c.sender==="user"?"bg-brand-600":"bg-brand-500/15 text-brand-600",className:"rounded-lg"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsx("span",{className:"text-sm font-medium text-fg-primary",children:c.sender==="user"?Jr:R==="channel"?c.agentName??o("page.fallbackAgent"):e.jsx(gl,{name:c.agentName??(R==="direct"?Ze?.name??o("page.fallbackAgent"):o("page.fallbackAgent")),agentId:c.agentId??(R==="direct"?Ze?.id:void 0),agents:f,onViewProfile:kt})}),e.jsx("span",{className:"text-xs text-fg-tertiary",title:c.rawCreatedAt?new Date(c.rawCreatedAt).toLocaleString():"",children:hl(c.time,c.rawCreatedAt,u)})]}),c.replyToId&&c.replyToSender&&e.jsxs("button",{onClick:()=>{const fe=document.getElementById(`msg-${c.replyToId}`);fe&&(fe.scrollIntoView({behavior:"smooth",block:"center"}),fe.classList.add("bg-brand-500/10"),setTimeout(()=>fe.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:[e.jsx("span",{className:"font-medium text-brand-500",children:c.replyToSender}),e.jsx("span",{className:"truncate max-w-[250px]",children:c.replyToText??"..."})]}),e.jsxs("div",{className:`mt-0.5 ${c.sender==="agent"?"py-1":"bg-surface-secondary rounded-2xl px-3.5 py-2.5 w-fit max-w-full"} ${Le&&c.sender==="agent"?"streaming-bubble":""}`,children:[c.sender==="user"?e.jsxs("div",{className:"text-sm text-fg-secondary whitespace-pre-wrap",children:[c.images&&c.images.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-1",children:c.images.map((fe,ne)=>e.jsx("img",{src:fe,alt:"",className:"max-w-[200px] max-h-[150px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>window.open(fe,"_blank")},ne))}),R==="channel"?oi(c.text,f,(fe,ne)=>{const _e=ne.currentTarget.getBoundingClientRect();is({agentId:fe.id,top:_e.bottom,left:_e.left})}):c.text&&e.jsx("span",{className:"leading-relaxed",children:oi(c.text,f,(fe,ne)=>{const _e=ne.currentTarget.getBoundingClientRect();is({agentId:fe.id,top:_e.bottom,left:_e.left})})})]}):c.sender==="agent"&&R==="channel"&&!(c.segments&&c.segments.length>0)?e.jsx(ii,{resetKeys:[c.text],fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:c.text}),children:e.jsx($n,{content:c.text,className:"text-sm text-fg-secondary",onMentionClick:qt,knownNames:jn})}):e.jsx(ii,{resetKeys:[c.id,c.text,c.segments?.length,$],fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:c.text}),children:e.jsx(pl,{msg:c,isStreaming:$,liveActivities:$?wr:[],onMentionClick:qt,knownNames:jn})}),c.isNotification&&e.jsx(bl,{priority:c.notifyPriority})]}),ve&&!s&&e.jsx("div",{className:`transition-opacity ${c.isStopped||c.isError||c.emptyReply||v?"opacity-100":"opacity-0 group-hover/msg:opacity-100"}`,children:e.jsx(yl,{msg:c,onCopy:So,onRetry:Co,onResume:To,onReply:Mo,onRemember:R==="direct"?Kr:void 0,showRemember:R==="direct",isCopied:ko===c.id,isLastAgentMsg:c.id===No})})]})]})]})},c.id)})}),R==="channel"&&ha.length>0&&e.jsx("div",{className:"flex flex-col gap-1.5 py-2",children:ha.map(t=>e.jsxs("div",{className:"flex items-center gap-2.5 px-3 py-1.5 rounded-lg cursor-pointer hover:bg-surface-elevated/60 transition-colors group/think",onClick:()=>{$e("direct"),lt(t.id),P("chat")},children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(vt,{name:t.name,avatarUrl:t.avatarUrl,size:28,bgClass:"bg-brand-500/15 text-brand-600"}),e.jsx("span",{className:"absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 rounded-full bg-blue-500 animate-pulse ring-2 ring-surface-primary"})]}),e.jsxs("div",{className:"flex items-center gap-1.5 min-w-0",children:[e.jsx("span",{className:"text-sm font-medium text-fg-secondary truncate",children:t.name}),e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce"}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.15s"}}),e.jsx("span",{className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0.3s"}})]}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:o("page.agentThinking")})]}),e.jsx("span",{className:"ml-auto text-[10px] text-fg-tertiary opacity-0 group-hover/think:opacity-100 transition-opacity",children:"→"})]},t.id))}),e.jsx("div",{ref:xo})]}),bo&&k==="chat"&&e.jsx("div",{className:`absolute ${v?"bottom-4":"bottom-28"} inset-x-0 z-10 pointer-events-none ${v?"px-3":`px-5 ${q}`}`,children:e.jsx("div",{className:`${v?"":"max-w-3xl mx-auto"} flex justify-center`,children:e.jsxs("button",{onClick:()=>{ms(),on("smooth"),us(!1),Ts.current=0,Ws(0)},className:"pointer-events-auto flex items-center gap-1.5 px-3.5 py-2 bg-surface-secondary/95 backdrop-blur-sm border border-border-default rounded-full shadow-lg hover:bg-surface-elevated transition-colors text-xs text-fg-secondary",children:[e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("polyline",{points:"6 9 12 15 18 9"})}),Da>0?o("page.newMessages",{count:Da}):o("page.scrollToBottom")]})})}),Es&&(()=>{const t=f.find(l=>l.id===Es.agentId);return t?e.jsx(vl,{agent:t,anchorRect:{top:Es.top,left:Es.left},onClose:()=>is(null),onViewProfile:kt}):null})(),Dn&&Za&&e.jsx("div",{className:"text-center mb-4",children:e.jsx("h2",{className:"text-xl font-semibold text-fg-primary",children:Za})}),R==="direct"&&(ja.length>0||Qn.length>0)&&e.jsx("div",{className:`${v?"px-3":"px-5"} pb-1 shrink-0 ${Dn?"":q}`,children:e.jsxs("div",{className:`${v?"":"max-w-3xl mx-auto"} flex flex-col gap-1.5`,children:[ja.map(t=>e.jsxs("button",{onClick:()=>Lr(t),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:[e.jsx("span",{className:"w-8 h-8 rounded-lg bg-amber-500/20 text-amber-500 flex items-center justify-center shrink-0",children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20z"}),e.jsx("path",{d:"M12 8v4"}),e.jsx("path",{d:"M12 16h.01"})]})}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-fg-primary truncate",children:t.title}),e.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:o("page.userInputPrompt",{count:t.questions?.length??1,defaultValue:`${t.questions?.length??1} question(s) awaiting your response`})})]}),e.jsxs("span",{className:"text-xs font-medium text-amber-500 shrink-0 inline-flex items-center gap-1",children:[o("page.userInputRespond",{defaultValue:"Respond"}),e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},t.id)),Qn.map(t=>{const l=t.priority==="high"||t.priority==="urgent";return e.jsxs("button",{onClick:()=>Rr(t),className:`w-full text-left px-3.5 py-2.5 rounded-xl border transition-colors flex items-center gap-3 ${l?"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:[e.jsx("span",{className:`w-8 h-8 rounded-lg flex items-center justify-center shrink-0 ${l?"bg-amber-500/20 text-amber-500":"bg-blue-500/20 text-blue-500"}`,children:e.jsxs("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("path",{d:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"}),e.jsx("path",{d:"M13.73 21a2 2 0 0 1-3.46 0"})]})}),e.jsxs("span",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"block text-sm font-medium text-fg-primary truncate",children:t.title}),e.jsx("span",{className:"block text-xs text-fg-tertiary truncate",children:t.body?.replace(/\s+/g," ").trim()||o("page.notifyUserPrompt",{defaultValue:"Agent notification awaiting your attention"})})]}),e.jsxs("span",{className:`text-xs font-medium shrink-0 inline-flex items-center gap-1 ${l?"text-amber-500":"text-blue-500"}`,children:[o("page.notifyUserView",{defaultValue:"View"}),e.jsx("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:e.jsx("path",{d:"M9 18l6-6-6-6"})})]})]},t.id)})]})}),Nn&&e.jsx(jl,{approval:Nn,submitting:to===Nn.id,readOnly:Nn.status!=="pending",onClose:()=>Lr(null),onSubmit:t=>Vo(Nn.id,t)}),Js&&e.jsx(Fl,{notification:Js,agentName:Ze?.name,acknowledging:so===Js.id,onClose:()=>Rr(null),onAcknowledge:()=>qo(Js.id)}),cr&&e.jsx(Bn,{variant:"primary",title:o("page.retry",{defaultValue:"Retry"}),message:cr.followCount===1?o("page.retryConfirmSingular"):o("page.retryConfirmPlural",{count:cr.followCount}),confirmLabel:o("common:confirm"),onConfirm:()=>{const t=cr;Yr(null),Xr(t.retryMsg,t.userMsg,t.retryText)},onCancel:()=>Yr(null)}),qs&&e.jsx(wl,{busy:za,onConfirm:t=>{Eo(t)},onCancel:()=>{za||Kr(null)}}),e.jsx("div",{className:`${v?"px-3 py-2":"px-5 py-3"} relative shrink-0 ${Dn?"":q}`,onDrop:Fo,onDragOver:Bo,children:e.jsxs("div",{className:`bg-surface-primary border border-border-default shadow-lg shadow-black/10 ${v?`${Wt?"rounded-2xl p-2":"rounded-2xl p-3"}`:`${Wt?"rounded-2xl p-2":"rounded-2xl p-3"} max-w-3xl mx-auto`}`,children:[Ia&&Gs.length>0&&e.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:[e.jsx("div",{className:"px-3 py-1.5 text-[10px] text-fg-tertiary font-medium uppercase tracking-wider border-b border-border-default",children:o("page.mentionAgent")}),Gs.map((t,l)=>t.kind==="agent"?e.jsxs("button",{ref:c=>{l===An&&c&&c.scrollIntoView({block:"nearest"})},onClick:()=>ur(t.agent.name),onMouseEnter:()=>tn(l),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${l===An?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx(vt,{name:t.agent.name,avatarUrl:t.agent.avatarUrl,size:24,bgClass:"bg-brand-500/20 text-brand-500"}),e.jsx("span",{className:"flex-1 min-w-0 truncate",children:t.agent.name}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-auto",children:t.agent.role})]},`agt-${t.agent.id}`):e.jsxs("button",{ref:c=>{l===An&&c&&c.scrollIntoView({block:"nearest"})},onClick:()=>ur(t.entity.name,t.entity.entityType,t.entity.id),onMouseEnter:()=>tn(l),className:`w-full text-left px-4 py-2 text-sm flex items-center gap-2 transition-colors ${l===An?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx("span",{className:"w-6 h-6 flex items-center justify-center text-sm shrink-0",children:Ho[t.entity.entityType]??"📄"}),e.jsx("span",{className:"flex-1 min-w-0 truncate",children:t.entity.name}),e.jsx("span",{className:"text-xs text-fg-tertiary ml-auto",children:t.entity.role})]},`${t.entity.entityType}-${t.entity.id}`))]}),es.length>0&&e.jsx("div",{className:"flex items-center gap-1.5 mb-2 flex-wrap",children:es.map(t=>e.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:t.content,children:[e.jsx("span",{className:"truncate",children:t.label}),e.jsx("button",{onClick:()=>kr(l=>l.filter(c=>c.id!==t.id)),className:"w-4 h-4 flex items-center justify-center rounded hover:bg-brand-500/20 shrink-0","aria-label":o("common:remove",{defaultValue:"Remove"}),children:e.jsxs("svg",{width:"10",height:"10",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]},t.id))}),Lt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 overflow-x-auto pb-1",children:[Lt.map(t=>e.jsxs("div",{className:"relative group/img shrink-0",children:[Zr(t)?e.jsx("img",{src:t.dataUrl,alt:t.name,className:"w-16 h-16 rounded-lg object-cover border border-border-default"}):e.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:t.name,children:[e.jsx("span",{className:"text-xl leading-none",children:Do(t.name,t.dataUrl)}),e.jsx("span",{className:"text-[9px] text-fg-tertiary truncate max-w-[56px] px-0.5",children:t.name.split(".").pop()?.toUpperCase()})]}),e.jsx("button",{onClick:()=>$o(t.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:"×"})]},t.id)),Lt.length<Ua&&e.jsx("button",{onClick:()=>Mr.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:o("page.addMoreFiles"),children:e.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 5v14M5 12h14"})})})]}),Lt.length>0&&Lt.some(t=>Zr(t))&&Ze&&Ze.modelSupportsVision===!1&&e.jsxs("div",{className:"text-[10px] text-amber-500/80 mb-1.5 flex items-center gap-1",children:[e.jsx("svg",{className:"w-3 h-3 shrink-0",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:e.jsx("path",{d:"M12 9v4m0 4h.01M12 2L2 22h20L12 2z",strokeLinecap:"round",strokeLinejoin:"round"})}),o("page.visionWarning")]}),e.jsx("input",{ref:Mr,type:"file",accept:"image/*,.pdf,.docx,.xlsx,.pptx,.xls,.doc,.csv,.json,.xml,.html,.epub",multiple:!0,className:"hidden",onChange:t=>{t.target.files&&_n(t.target.files),t.target.value=""}}),ks&&e.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:[e.jsxs("div",{className:"flex-1 min-w-0 pl-2 border-l-2 border-brand-500/50",children:[e.jsx("span",{className:"text-[11px] font-medium text-brand-500",children:ks.sender}),e.jsx("p",{className:"text-[11px] text-fg-tertiary truncate",children:ks.text})]}),e.jsx("button",{onClick:()=>Qe(null),className:"text-fg-tertiary hover:text-fg-secondary shrink-0 p-0.5",children:e.jsxs("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[e.jsx("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),e.jsx("line",{x1:"6",y1:"6",x2:"18",y2:"18"})]})})]}),e.jsxs("div",{className:ra?"flex flex-col gap-2 min-w-0":"flex gap-2 items-end min-w-0",children:[e.jsxs("div",{className:ra?"flex gap-2 items-end min-w-0":"contents",children:[e.jsx("button",{onClick:()=>Mr.current?.click(),disabled:R==="direct"&&(!K||Rn),className:`${Wt?"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:o("page.attachFilesTitle"),children:e.jsx("svg",{className:Wt?"w-[18px] h-[18px]":"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",children:e.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"})})}),e.jsx("textarea",{ref:cs,value:tt,onChange:t=>{Lo(t.target.value),kn()},onKeyDown:t=>{if(Ia&&Gs.length>0){const l=t.key==="ArrowUp"||t.ctrlKey&&t.key==="p",c=t.key==="ArrowDown"||t.ctrlKey&&t.key==="n",x=t.key==="Enter"||t.key==="Tab",w=t.key==="Escape";if(l){t.preventDefault(),tn(B=>(B-1+Gs.length)%Gs.length);return}if(c){t.preventDefault(),tn(B=>(B+1)%Gs.length);return}if(x){t.preventDefault();const B=Gs[An];B&&(B.kind==="agent"?ur(B.agent.name):ur(B.entity.name,B.entity.entityType,B.entity.id));return}if(w){t.preventDefault(),En(!1);return}}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Us())},onPaste:Oo,placeholder:Go,disabled:R==="direct"&&(!K||Rn),rows:Wt?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 ${Wt?"px-2 py-1.5":"px-4 py-3"}`,style:{minHeight:Wt?"36px":"52px",maxHeight:Wt?"160px":"120px"}})]}),e.jsxs("div",{className:`flex items-center gap-1.5 shrink-0 ${ra?"justify-end":""}`,children:[R==="direct"&&e.jsx(vc,{value:Kn,disabled:!K||Rn,onSelect:(t,l)=>{Yn(t);const c=Ee&&Ee!==He?Ee:null;jc(c,t,l).catch(()=>{}),c&&Os(x=>x.map(w=>w.id===c?{...w,metadata:{...w.metadata??{},modelOverride:t}}:w))}}),It&&R!=="dm"?e.jsx("button",{onClick:wo,className:`${Wt?"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:o("page.stopAgent"),children:e.jsx("svg",{className:"w-3.5 h-3.5",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})})}):e.jsx("button",{onClick:()=>{Us()},disabled:R==="direct"&&(!K||Rn)||!tt.trim()&&Lt.length===0,className:Wt?"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:o("common:send"),children:Wt?e.jsx("svg",{className:"w-4 h-4",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:e.jsx("path",{d:"M12 19V5M5 12l7-7 7 7",strokeLinecap:"round",strokeLinejoin:"round"})}):o("common:send")})]})]})]})})]})]}),!v&&J&&be&&e.jsx(Jl,{payload:J,onClose:be,width:g?Yt:vs,onResizeStart:vr,onAddToChat:Ys,tabs:U,activeTabId:ee,onSelectTab:ue?.setActiveRightPanelTab,onCloseTab:ue?.closeRightPanelTab,onNewTab:()=>{if(!ge)return;const t=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;ge({kind:"url",url:"about:blank",title:"New Tab",browserId:t})},fullscreen:g,onToggleFullscreen:ue?.toggleRightPanelFullscreen})]})}function Oi({agent:i,tasks:a,onViewProfile:s,streamActive:r}){const{t:o}=Ge(["team","common"]),[d,u]=n.useState(!1),m=n.useRef(null),f=n.useRef(null),y=i.status==="working"||!!r,N=i.status==="error",j=y?a.find(E=>E.assignedAgentId===i.id&&E.status==="in_progress"):null,I=i.currentActivity;n.useEffect(()=>{N&&i.lastError&&hr(i.lastError)&&pr()},[N,i.lastError]),n.useEffect(()=>{if(!d)return;const E=T=>{m.current&&!m.current.contains(T.target)&&u(!1)};return document.addEventListener("mousedown",E),()=>document.removeEventListener("mousedown",E)},[d]),n.useLayoutEffect(()=>{if(!d||!f.current)return;const E=f.current,T=E.getBoundingClientRect(),p=window.innerWidth;T.right>p-8&&(E.style.left="auto",E.style.right="0"),T.left<8&&(E.style.left="0",E.style.right="auto");const C=p-16;T.width>C&&(E.style.width=`${C}px`)},[d]);const b=N?"bg-red-400 animate-pulse":y?"bg-blue-400 animate-pulse":"bg-green-400",v=o(N?"common:status.error":y?"common:status.working":"common:status.idle"),O=I?I.type==="heartbeat"?o("page.activityHeartbeat",{name:I.heartbeatName??I.label}):I.type==="chat"?I.label:I.type==="task"?o("page.activityTask",{label:I.label}):I.label:o("page.processing");return e.jsxs("div",{className:"relative",ref:m,children:[e.jsxs("button",{onClick:()=>u(E=>!E),className:`flex items-center gap-1.5 px-2 py-0.5 rounded-full transition-colors ${y?"bg-blue-500/10 border border-blue-500/20 hover:bg-blue-500/20":N?"bg-red-500/10 border border-red-500/20 hover:bg-red-500/20":"bg-green-500/10 border border-green-500/20 hover:bg-green-500/20"}`,children:[e.jsx("span",{className:`w-2 h-2 rounded-full ${b}`}),e.jsx("span",{className:`text-xs ${N?"text-red-500":y?"text-blue-500":"text-green-600"}`,children:v}),i.mailboxDepth!=null&&i.mailboxDepth>0&&e.jsx("span",{className:"text-[9px] bg-fg-tertiary/20 text-fg-tertiary rounded-full px-1.5",children:i.mailboxDepth})]}),d&&N&&e.jsxs("div",{ref:f,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:[e.jsx("p",{className:"text-[10px] text-red-500 uppercase font-semibold",children:o("page.errorDetails")}),e.jsxs("div",{className:"bg-red-500/10 border border-red-500/20 rounded-lg p-2.5",children:[e.jsx("pre",{className:"text-[10px] text-red-500/80 leading-relaxed whitespace-pre-wrap break-all font-mono line-clamp-6",children:br(i.lastError,o)||i.lastError||o("page.agentErrorFallback")}),i.lastErrorAt&&e.jsx("div",{className:"text-[9px] text-red-500/50 mt-1.5 border-t border-red-500/10 pt-1",children:new Date(i.lastErrorAt).toLocaleString()})]}),e.jsx("button",{onClick:()=>{u(!1),s?.(i.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:o("page.viewAgentProfileArrow")})]}),d&&y&&e.jsxs("div",{ref:f,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:[e.jsx("p",{className:"text-[10px] text-fg-tertiary uppercase font-semibold",children:o("page.currentActivity")}),j?e.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:()=>{u(!1),ps.navigate(xt.WORK,{openTask:j.id})},children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-400 animate-pulse shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-brand-500 truncate",children:j.title}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:o("page.workingOnTaskHint")})]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:"→"})]}):e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-surface-elevated/50",children:[e.jsx("span",{className:`w-1.5 h-1.5 rounded-full shrink-0 ${I?.type==="heartbeat"||I?.type==="chat","bg-blue-400 animate-pulse"}`}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-xs text-fg-secondary",children:O}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:I?.type==="heartbeat"?o("page.activityDescHeartbeat"):I?.type==="chat"?o("page.activityDescChat"):o("page.activityDescFallback")})]})]}),e.jsx("button",{onClick:()=>{u(!1),s?.(i.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:o("page.viewMindArrow")})]})]})}export{Dc as TeamPage};
|