@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
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/index-CHkb08MZ.js","assets/index-CPULIfuW.css"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as s,e as zi,u as Xe,G as Zo,j as e,t as $n,H as Jo,a as xa,B as Wi,P as gt,f as T,w as We,M as el,A as wt,n as bs,J as Bn,K as tl,L as sl,O as mr,b as Hi,Q as Vi,h as qi,l as yr,U as nl,V as rl,W as ei,X as al,Y as il,Z as Ui,$ as Gi,a0 as ol,a1 as ll,a2 as cl,_ as Ki,C as ti,a3 as dl,a4 as Ks,a5 as ul,a6 as ml,a7 as ia,a8 as si,a9 as xl,x as oa,z as ni,k as ri,s as fl,g as gl,aa as ai,m as ii,o as hl,ab as pl,p as bl,ac as oi,q as yl,ad as vl,v as jl,ae as wl,af as kl,R as Nl,D as Sl,ag as pr,ah as br,y as Cl}from"./index-CHkb08MZ.js";import{r as li,p as Tl}from"./CommentInput-D3jx82c7.js";import{resolveFormat as Ml,ContentRenderer as ci}from"./ContentRenderer-CQ9uMng0.js";function cn(r,a,n){let i=n.initialDeps??[],o,u=!0;function d(){var m,f,y;let k;n.key&&((m=n.debug)!=null&&m.call(n))&&(k=Date.now());const j=r();if(!(j.length!==i.length||j.some((p,R)=>i[R]!==p)))return o;i=j;let v;if(n.key&&((f=n.debug)!=null&&f.call(n))&&(v=Date.now()),o=a(...j),n.key&&((y=n.debug)!=null&&y.call(n))){const p=Math.round((Date.now()-k)*100)/100,R=Math.round((Date.now()-v)*100)/100,P=R/16,I=(h,E)=>{for(h=String(h);h.length<E;)h=" "+h;return h};console.info(`%c⏱ ${I(R,5)} /${I(p,5)} ms`,`
|
|
3
|
+
font-size: .6rem;
|
|
4
|
+
font-weight: bold;
|
|
5
|
+
color: hsl(${Math.max(0,Math.min(120-120*P,120))}deg 100% 31%);`,n?.key)}return n?.onChange&&!(u&&n.skipInitialOnChange)&&n.onChange(o),u=!1,o}return d.updateDeps=m=>{i=m},d}function di(r,a){if(r===void 0)throw new Error("Unexpected undefined");return r}const Il=(r,a)=>Math.abs(r-a)<1.01,El=(r,a,n)=>{let i;return function(...o){r.clearTimeout(i),i=r.setTimeout(()=>a.apply(this,o),n)}},ui=r=>{const{offsetWidth:a,offsetHeight:n}=r;return{width:a,height:n}},Al=r=>r,Pl=r=>{const a=Math.max(r.startIndex-r.overscan,0),n=Math.min(r.endIndex+r.overscan,r.count-1),i=[];for(let o=a;o<=n;o++)i.push(o);return i},_l=(r,a)=>{const n=r.scrollElement;if(!n)return;const i=r.targetWindow;if(!i)return;const o=d=>{const{width:m,height:f}=d;a({width:Math.round(m),height:Math.round(f)})};if(o(ui(n)),!i.ResizeObserver)return()=>{};const u=new i.ResizeObserver(d=>{const m=()=>{const f=d[0];if(f?.borderBoxSize){const y=f.borderBoxSize[0];if(y){o({width:y.inlineSize,height:y.blockSize});return}}o(ui(n))};r.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(m):m()});return u.observe(n,{box:"border-box"}),()=>{u.unobserve(n)}},mi={passive:!0},xi=typeof window>"u"?!0:"onscrollend"in window,Ll=(r,a)=>{const n=r.scrollElement;if(!n)return;const i=r.targetWindow;if(!i)return;let o=0;const u=r.options.useScrollendEvent&&xi?()=>{}:El(i,()=>{a(o,!1)},r.options.isScrollingResetDelay),d=k=>()=>{const{horizontal:j,isRtl:$}=r.options;o=j?n.scrollLeft*($&&-1||1):n.scrollTop,u(),a(o,k)},m=d(!0),f=d(!1);n.addEventListener("scroll",m,mi);const y=r.options.useScrollendEvent&ξreturn y&&n.addEventListener("scrollend",f,mi),()=>{n.removeEventListener("scroll",m),y&&n.removeEventListener("scrollend",f)}},Rl=(r,a,n)=>{if(a?.borderBoxSize){const i=a.borderBoxSize[0];if(i)return Math.round(i[n.options.horizontal?"inlineSize":"blockSize"])}return r[n.options.horizontal?"offsetWidth":"offsetHeight"]},Dl=(r,{adjustments:a=0,behavior:n},i)=>{var o,u;const d=r+a;(u=(o=i.scrollElement)==null?void 0:o.scrollTo)==null||u.call(o,{[i.options.horizontal?"left":"top"]:d,behavior:n})};class $l{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 n,i,o;return((o=(i=(n=this.targetWindow)==null?void 0:n.performance)==null?void 0:i.now)==null?void 0:o.call(i))??Date.now()},this.observer=(()=>{let n=null;const i=()=>n||(!this.targetWindow||!this.targetWindow.ResizeObserver?null:n=new this.targetWindow.ResizeObserver(o=>{o.forEach(u=>{const d=()=>{const m=u.target,f=this.indexFromElement(m);if(!m.isConnected){this.observer.unobserve(m);return}this.shouldMeasureDuringScroll(f)&&this.resizeItem(f,this.options.measureElement(m,u,this))};this.options.useAnimationFrameWithResizeObserver?requestAnimationFrame(d):d()})}));return{disconnect:()=>{var o;(o=i())==null||o.disconnect(),n=null},observe:o=>{var u;return(u=i())==null?void 0:u.observe(o,{box:"border-box"})},unobserve:o=>{var u;return(u=i())==null?void 0:u.unobserve(o)}}})(),this.range=null,this.setOptions=n=>{Object.entries(n).forEach(([i,o])=>{typeof o>"u"&&delete n[i]}),this.options={debug:!1,initialOffset:0,overscan:1,paddingStart:0,paddingEnd:0,scrollPaddingStart:0,scrollPaddingEnd:0,horizontal:!1,getItemKey:Al,rangeExtractor:Pl,onChange:()=>{},measureElement:Rl,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",...n}},this.notify=n=>{var i,o;(o=(i=this.options).onChange)==null||o.call(i,this,n)},this.maybeNotify=cn(()=>(this.calculateRange(),[this.isScrolling,this.range?this.range.startIndex:null,this.range?this.range.endIndex:null]),n=>{this.notify(n)},{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(n=>n()),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 n;const i=this.options.enabled?this.options.getScrollElement():null;if(this.scrollElement!==i){if(this.cleanup(),!i){this.maybeNotify();return}this.scrollElement=i,this.scrollElement&&"ownerDocument"in this.scrollElement?this.targetWindow=this.scrollElement.ownerDocument.defaultView:this.targetWindow=((n=this.scrollElement)==null?void 0:n.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,u)=>{this.scrollAdjustments=0,this.scrollDirection=u?this.getScrollOffset()<o?"forward":"backward":null,this.scrollOffset=o,this.isScrolling=u,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=(n,i)=>{const o=new Map,u=new Map;for(let d=i-1;d>=0;d--){const m=n[d];if(o.has(m.lane))continue;const f=u.get(m.lane);if(f==null||m.end>f.end?u.set(m.lane,m):m.end<f.end&&o.set(m.lane,!0),o.size===this.options.lanes)break}return u.size===this.options.lanes?Array.from(u.values()).sort((d,m)=>d.end===m.end?d.index-m.index:d.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],(n,i,o,u,d,m,f)=>(this.prevLanes!==void 0&&this.prevLanes!==m&&(this.lanesChangedFlag=!0),this.prevLanes=m,this.pendingMeasuredCacheIndexes=[],{count:n,paddingStart:i,scrollMargin:o,getItemKey:u,enabled:d,lanes:m,laneAssignmentMode:f}),{key:!1}),this.getMeasurements=cn(()=>[this.getMeasurementOptions(),this.itemSizeCache],({count:n,paddingStart:i,scrollMargin:o,getItemKey:u,enabled:d,lanes:m,laneAssignmentMode:f},y)=>{if(!d)return this.measurementsCache=[],this.itemSizeCache.clear(),this.laneAssignments.clear(),[];if(this.laneAssignments.size>n)for(const v of this.laneAssignments.keys())v>=n&&this.laneAssignments.delete(v);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(v=>{this.itemSizeCache.set(v.key,v.size)}));const k=this.lanesSettling?0:this.pendingMeasuredCacheIndexes.length>0?Math.min(...this.pendingMeasuredCacheIndexes):0;this.pendingMeasuredCacheIndexes=[],this.lanesSettling&&this.measurementsCache.length===n&&(this.lanesSettling=!1);const j=this.measurementsCache.slice(0,k),$=new Array(m).fill(void 0);for(let v=0;v<k;v++){const p=j[v];p&&($[p.lane]=v)}for(let v=k;v<n;v++){const p=u(v),R=this.laneAssignments.get(v);let P,I;const h=f==="estimate"||y.has(p);if(R!==void 0&&this.options.lanes>1){P=R;const ie=$[P],N=ie!==void 0?j[ie]:void 0;I=N?N.end+this.options.gap:i+o}else{const ie=this.options.lanes===1?j[v-1]:this.getFurthestMeasurement(j,v);I=ie?ie.end+this.options.gap:i+o,P=ie?ie.lane:v%this.options.lanes,this.options.lanes>1&&h&&this.laneAssignments.set(v,P)}const E=y.get(p),M=typeof E=="number"?E:this.options.estimateSize(v),V=I+M;j[v]={index:v,start:I,size:M,end:V,key:p,lane:P},$[P]=v}return this.measurementsCache=j,j},{key:!1,debug:()=>this.options.debug}),this.calculateRange=cn(()=>[this.getMeasurements(),this.getSize(),this.getScrollOffset(),this.options.lanes],(n,i,o,u)=>this.range=n.length>0&&i>0?Ol({measurements:n,outerSize:i,scrollOffset:o,lanes:u}):null,{key:!1,debug:()=>this.options.debug}),this.getVirtualIndexes=cn(()=>{let n=null,i=null;const o=this.calculateRange();return o&&(n=o.startIndex,i=o.endIndex),this.maybeNotify.updateDeps([this.isScrolling,n,i]),[this.options.rangeExtractor,this.options.overscan,this.options.count,n,i]},(n,i,o,u,d)=>u===null||d===null?[]:n({startIndex:u,endIndex:d,overscan:i,count:o}),{key:!1,debug:()=>this.options.debug}),this.indexFromElement=n=>{const i=this.options.indexAttribute,o=n.getAttribute(i);return o?parseInt(o,10):(console.warn(`Missing attribute name '${i}={index}' on measured element.`),-1)},this.shouldMeasureDuringScroll=n=>{var i;if(!this.scrollState||this.scrollState.behavior!=="smooth")return!0;const o=this.scrollState.index??((i=this.getVirtualItemForOffset(this.scrollState.lastTargetOffset))==null?void 0:i.index);if(o!==void 0&&this.range){const u=Math.max(this.options.overscan,Math.ceil((this.range.endIndex-this.range.startIndex)/2)),d=Math.max(0,o-u),m=Math.min(this.options.count-1,o+u);return n>=d&&n<=m}return!0},this.measureElement=n=>{if(!n){this.elementsCache.forEach((d,m)=>{d.isConnected||(this.observer.unobserve(d),this.elementsCache.delete(m))});return}const i=this.indexFromElement(n),o=this.options.getItemKey(i),u=this.elementsCache.get(o);u!==n&&(u&&this.observer.unobserve(u),this.observer.observe(n),this.elementsCache.set(o,n)),(!this.isScrolling||this.scrollState)&&this.shouldMeasureDuringScroll(i)&&this.resizeItem(i,this.options.measureElement(n,void 0,this))},this.resizeItem=(n,i)=>{var o;const u=this.measurementsCache[n];if(!u)return;const d=this.itemSizeCache.get(u.key)??u.size,m=i-d;m!==0&&(((o=this.scrollState)==null?void 0:o.behavior)!=="smooth"&&(this.shouldAdjustScrollPositionOnItemSizeChange!==void 0?this.shouldAdjustScrollPositionOnItemSizeChange(u,m,this):u.start<this.getScrollOffset()+this.scrollAdjustments)&&this._scrollToOffset(this.getScrollOffset(),{adjustments:this.scrollAdjustments+=m,behavior:void 0}),this.pendingMeasuredCacheIndexes.push(u.index),this.itemSizeCache=new Map(this.itemSizeCache.set(u.key,i)),this.notify(!1))},this.getVirtualItems=cn(()=>[this.getVirtualIndexes(),this.getMeasurements()],(n,i)=>{const o=[];for(let u=0,d=n.length;u<d;u++){const m=n[u],f=i[m];o.push(f)}return o},{key:!1,debug:()=>this.options.debug}),this.getVirtualItemForOffset=n=>{const i=this.getMeasurements();if(i.length!==0)return di(i[Yi(0,i.length-1,o=>di(i[o]).start,n)])},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 n=this.scrollElement.document.documentElement;return this.options.horizontal?n.scrollWidth-this.scrollElement.innerWidth:n.scrollHeight-this.scrollElement.innerHeight}},this.getOffsetForAlignment=(n,i,o=0)=>{if(!this.scrollElement)return 0;const u=this.getSize(),d=this.getScrollOffset();i==="auto"&&(i=n>=d+u?"end":"start"),i==="center"?n+=(o-u)/2:i==="end"&&(n-=u);const m=this.getMaxScrollOffset();return Math.max(Math.min(m,n),0)},this.getOffsetForIndex=(n,i="auto")=>{n=Math.max(0,Math.min(n,this.options.count-1));const o=this.getSize(),u=this.getScrollOffset(),d=this.measurementsCache[n];if(!d)return;if(i==="auto")if(d.end>=u+o-this.options.scrollPaddingEnd)i="end";else if(d.start<=u+this.options.scrollPaddingStart)i="start";else return[u,i];if(i==="end"&&n===this.options.count-1)return[this.getMaxScrollOffset(),i];const m=i==="end"?d.end+this.options.scrollPaddingEnd:d.start-this.options.scrollPaddingStart;return[this.getOffsetForAlignment(m,i,d.size),i]},this.scrollToOffset=(n,{align:i="start",behavior:o="auto"}={})=>{const u=this.getOffsetForAlignment(n,i),d=this.now();this.scrollState={index:null,align:i,behavior:o,startedAt:d,lastTargetOffset:u,stableFrames:0},this._scrollToOffset(u,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollToIndex=(n,{align:i="auto",behavior:o="auto"}={})=>{n=Math.max(0,Math.min(n,this.options.count-1));const u=this.getOffsetForIndex(n,i);if(!u)return;const[d,m]=u,f=this.now();this.scrollState={index:n,align:m,behavior:o,startedAt:f,lastTargetOffset:d,stableFrames:0},this._scrollToOffset(d,{adjustments:void 0,behavior:o}),this.scheduleScrollReconcile()},this.scrollBy=(n,{behavior:i="auto"}={})=>{const o=this.getScrollOffset()+n,u=this.now();this.scrollState={index:null,align:"start",behavior:i,startedAt:u,lastTargetOffset:o,stableFrames:0},this._scrollToOffset(o,{adjustments:void 0,behavior:i}),this.scheduleScrollReconcile()},this.getTotalSize=()=>{var n;const i=this.getMeasurements();let o;if(i.length===0)o=this.options.paddingStart;else if(this.options.lanes===1)o=((n=i[i.length-1])==null?void 0:n.end)??0;else{const u=Array(this.options.lanes).fill(null);let d=i.length-1;for(;d>=0&&u.some(m=>m===null);){const m=i[d];u[m.lane]===null&&(u[m.lane]=m.end),d--}o=Math.max(...u.filter(m=>m!==null))}return Math.max(o-this.options.scrollMargin+this.options.paddingEnd,0)},this._scrollToOffset=(n,{adjustments:i,behavior:o})=>{this.options.scrollToFn(n,{behavior:o,adjustments:i},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 i=this.scrollState.index!=null?this.getOffsetForIndex(this.scrollState.index,this.scrollState.align):void 0,o=i?i[0]:this.scrollState.lastTargetOffset,u=1,d=o!==this.scrollState.lastTargetOffset;if(!d&&Il(o,this.getScrollOffset())){if(this.scrollState.stableFrames++,this.scrollState.stableFrames>=u){this.scrollState=null;return}}else this.scrollState.stableFrames=0,d&&(this.scrollState.lastTargetOffset=o,this.scrollState.behavior="auto",this._scrollToOffset(o,{adjustments:void 0,behavior:"auto"}));this.scheduleScrollReconcile()}}const Yi=(r,a,n,i)=>{for(;r<=a;){const o=(r+a)/2|0,u=n(o);if(u<i)r=o+1;else if(u>i)a=o-1;else return o}return r>0?r-1:0};function Ol({measurements:r,outerSize:a,scrollOffset:n,lanes:i}){const o=r.length-1,u=f=>r[f].start;if(r.length<=i)return{startIndex:0,endIndex:o};let d=Yi(0,o,u,n),m=d;if(i===1)for(;m<o&&r[m].end<n+a;)m++;else if(i>1){const f=Array(i).fill(0);for(;m<o&&f.some(k=>k<n+a);){const k=r[m];f[k.lane]=k.end,m++}const y=Array(i).fill(n+a);for(;d>=0&&y.some(k=>k>=n);){const k=r[d];y[k.lane]=k.start,d--}d=Math.max(0,d-d%i),m=Math.min(o,m+(i-1-m%i))}return{startIndex:d,endIndex:m}}const fi=typeof document<"u"?s.useLayoutEffect:s.useEffect;function Fl({useFlushSync:r=!0,...a}){const n=s.useReducer(()=>({}),{})[1],i={...a,onChange:(u,d)=>{var m;r&&d?zi.flushSync(n):n(),(m=a.onChange)==null||m.call(a,u,d)}},[o]=s.useState(()=>new $l(i));return o.setOptions(i),fi(()=>o._didMount(),[]),fi(()=>o._willUpdate()),o}function Bl(r){return Fl({observeElementRect:_l,observeElementOffset:Ll,scrollToFn:Dl,...r})}const gi={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 zl({notification:r,agentName:a,acknowledging:n,onClose:i,onAcknowledge:o}){const{t:u}=Xe(["team","common"]);Zo(!0);const d=r.priority||"normal",m=r.metadata??{},f=a||(typeof m.agentName=="string"?m.agentName:void 0);return zi.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&&i()},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:r.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}),d!=="normal"&&e.jsx("span",{className:`inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium ${gi[d]??gi.normal}`,children:d})]})]}),e.jsx("button",{onClick:i,className:"p-1.5 text-fg-tertiary hover:text-fg-primary rounded-md hover:bg-surface-overlay transition-colors shrink-0",title:u("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:r.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:i,className:"px-3.5 py-2 text-sm text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:u("common:close")}),e.jsx("button",{onClick:()=>{o()},disabled:n,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:n?u("common:loading"):u("page.notifyUserGotIt",{ns:"team",defaultValue:"Got it"})})]})]})}),document.body)}function On({children:r,onClose:a,title:n,width:i="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 ${i} shadow-2xl max-h-[90vh] overflow-y-auto`,onClick:o=>o.stopPropagation(),children:[e.jsx("h3",{className:"text-base font-semibold mb-5",children:n}),r]})})}function un({label:r,children:a}){return e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-fg-secondary mb-1.5 font-medium",children:r}),a]})}function Wl({onClose:r,onCreate:a}){const{t:n}=Xe(["team","common"]),[i,o]=s.useState(""),[u,d]=s.useState("");return e.jsx(On,{onClose:r,title:n("team:modals.createTeam.title"),children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(un,{label:n("team:modals.createTeam.teamName"),children:e.jsx("input",{value:i,onChange:m=>o(m.target.value),placeholder:n("team:modals.createTeam.teamNamePlaceholder"),className:"input",autoFocus:!0,onKeyDown:m=>{m.key==="Enter"&&i.trim()&&a(i.trim(),u.trim()||void 0)}})}),e.jsx(un,{label:n("team:modals.createTeam.description"),children:e.jsx("textarea",{value:u,onChange:m=>d(m.target.value),placeholder:n("team:modals.createTeam.descriptionPlaceholder"),className:"input",rows:2})}),e.jsx("div",{className:"text-xs text-fg-tertiary",children:n("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(Jo,{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:r,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:n("common:cancel")}),e.jsx("button",{onClick:()=>i.trim()&&a(i.trim(),u.trim()||void 0),disabled:!i.trim(),className:"px-4 py-2 text-sm bg-brand-600 hover:bg-brand-500 disabled:opacity-40 rounded-lg text-white",children:n("team:modals.createTeam.createTeam")})]})]})})}function Hl({onClose:r,onAdd:a}){const{t:n}=Xe(["team","common"]),[i,o]=s.useState(""),[u,d]=s.useState("member"),[m,f]=s.useState(""),[y,k]=s.useState(""),[j,$]=s.useState(!1),[v,p]=s.useState(null),[R,P]=s.useState(!1),I=v?.inviteToken?`${window.location.origin}/#invite?token=${v.inviteToken}`:null,h=async()=>{if(k(""),!i.trim()){k(n("team:modals.addHuman.nameRequired"));return}if(!m.trim()){k(n("team:modals.addHuman.emailRequired"));return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(m.trim())){k(n("team:modals.addHuman.invalidEmail"));return}$(!0);try{const M=await a(i.trim(),u,m.trim());p({...M,userName:i.trim()})}catch(M){k(M instanceof Error?M.message:String(M))}finally{$(!1)}},E=()=>{I&&(navigator.clipboard.writeText(I),P(!0),setTimeout(()=>P(!1),2e3))};return v?e.jsxs(On,{onClose:r,title:n("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:n("team:modals.addHuman.memberCreated",{name:v.userName})}),I?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-fg-secondary mt-1 mb-4",children:n("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:n("team:modals.addHuman.inviteLink")}),e.jsx("div",{className:"text-xs text-fg-primary break-all font-mono select-all",children:I})]}),e.jsx("button",{onClick:E,className:`w-full py-2.5 text-sm font-medium rounded-lg transition-colors ${R?"bg-green-600 text-white":"bg-brand-700 hover:bg-brand-600 text-white"}`,children:n(R?"common:copied":"team:modals.addHuman.copyInviteLink")})]}):e.jsx("div",{className:"text-xs text-fg-secondary mt-1",children:n("team:modals.addHuman.memberCreatedNoInvite")})]}),e.jsx("div",{className:"flex justify-end pt-3",children:e.jsx("button",{onClick:r,className:"px-5 py-2 text-sm bg-surface-elevated hover:bg-surface-overlay rounded-lg text-fg-secondary border border-border-default",children:n("common:done")})})]}):e.jsx(On,{onClose:r,title:n("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:n("team:modals.addHuman.sharedInstanceTitle")}),n("team:modals.addHuman.sharedInstanceDesc"),e.jsxs("div",{className:"mt-1.5 text-fg-tertiary",children:[n("team:modals.addHuman.orgHint")," ",e.jsx("a",{href:"#settings/organization",className:"text-brand-500 hover:text-brand-400 underline",children:n("team:modals.addHuman.orgLink")})]})]}),e.jsx(un,{label:n("team:modals.addHuman.name"),children:e.jsx("input",{value:i,onChange:M=>o(M.target.value),placeholder:n("team:modals.addHuman.namePlaceholder"),className:"input",autoFocus:!0})}),e.jsx(un,{label:n("team:modals.addHuman.role"),children:e.jsxs("select",{value:u,onChange:M=>d(M.target.value),className:"input",children:[e.jsx("option",{value:"owner",children:n("common:role.owner")}),e.jsx("option",{value:"admin",children:n("common:role.admin")}),e.jsx("option",{value:"member",children:n("common:role.member")}),e.jsx("option",{value:"guest",children:n("common:role.guest")})]})}),e.jsx(un,{label:n("team:modals.addHuman.emailRequired"),children:e.jsx("input",{value:m,onChange:M=>f(M.target.value),type:"email",placeholder:n("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:n("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:r,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:n("common:cancel")}),e.jsx("button",{onClick:h,disabled:j,className:"px-4 py-2 text-sm bg-green-700 hover:bg-green-600 disabled:opacity-50 rounded-lg text-white",children:n(j?"common:saving":"team:modals.addHuman.addMember")})]})]})})}function Vl({teamId:r,ungrouped:a,onClose:n,onAdd:i}){const{t:o}=Xe(["team","common"]);return e.jsx(On,{onClose:n,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(u=>e.jsxs("button",{onClick:()=>i(u.id,u.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 ${u.type==="agent"?"bg-brand-600":"bg-green-600"}`,children:u.name.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:u.name}),e.jsxs("div",{className:"text-xs text-fg-tertiary",children:[u.role," · ",u.type==="agent"?o("team:modals.addExisting.typeAgent"):o("team:modals.addExisting.typeHuman")]})]}),u.status&&e.jsx("span",{className:`w-2 h-2 rounded-full ${u.status==="idle"?"bg-green-400":u.status==="working"?"bg-blue-400":"bg-gray-600"}`})]},u.id))}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsx("button",{onClick:n,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:o("common:close")})})]})})}function ql({onClose:r,onConnected:a}){const{t:n}=Xe(["team","common"]),[i,o]=s.useState(""),[u,d]=s.useState(""),[m,f]=s.useState(!1),[y,k]=s.useState(null),[j,$]=s.useState(null),v=async()=>{if(!i.trim()){d(n("team:modals.openClaw.agentNameRequired"));return}const R=i.trim().toLowerCase().replace(/\s+/g,"-");f(!0),d("");try{const P=await fetch("/api/external-agents/register",{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({externalAgentId:R,agentName:i.trim(),orgId:"default",capabilities:["general"]})});if(!P.ok){const h=await P.json().catch(()=>({}));throw new Error(h.error??`HTTP ${P.status}`)}const I=await P.json();k({externalAgentId:R,markusAgentId:I.registration?.markusAgentId,token:I.token,gatewayUrl:I.gatewayUrl})}catch(P){d(String(P))}f(!1)},p=(R,P)=>{navigator.clipboard.writeText(R),$(P),setTimeout(()=>$(null),2e3)};return e.jsx(On,{onClose:r,title:n("team:modals.openClaw.title"),width:"w-[560px]",children:y?(()=>{const R=y.gatewayUrl??`${window.location.origin}/api/gateway`,P=y.token?n("team:modals.openClaw.bearerTokenLine",{token:y.token}):"",I=n("team:modals.openClaw.connectionPromptBody",{gwUrl:R,externalAgentId:y.externalAgentId,tokenSection:P});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:n("team:modals.openClaw.agentRegistered")}),e.jsx("div",{className:"text-sm text-fg-secondary mt-1",children:e.jsx("strong",{children:i})})]}),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:n("team:modals.openClaw.copyInstruction")}),e.jsx("button",{onClick:()=>p(I,"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:n(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:n("team:modals.openClaw.done")})})]})})():e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xs text-fg-secondary mb-4",children:n("team:modals.openClaw.description")}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(un,{label:n("team:modals.openClaw.agentName"),children:e.jsx("input",{className:"input",placeholder:n("team:modals.openClaw.agentNamePlaceholder"),value:i,onChange:R=>o(R.target.value),autoFocus:!0})}),u&&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:u}),e.jsxs("div",{className:"flex justify-end gap-3 pt-2",children:[e.jsx("button",{onClick:r,className:"px-4 py-2 text-sm border border-border-default rounded-lg hover:bg-surface-elevated",children:n("common:cancel")}),e.jsx("button",{onClick:v,disabled:m,className:"px-4 py-2 text-sm bg-brand-700 hover:bg-brand-600 rounded-lg text-white disabled:opacity-50",children:n(m?"team:modals.openClaw.connecting":"team:modals.openClaw.importAgent")})]})]})]})})}let xr=new Map;function Ul({agents:r,humans:a,authUser:n,onClose:i,onCreate:o}){const{t:u}=Xe(["team","common"]),[d,m]=s.useState(""),[f,y]=s.useState(new Set),[k,j]=s.useState(""),[$,v]=s.useState(!1),p=s.useMemo(()=>{const h=[];for(const E of r)h.push({id:E.id,name:E.name,type:"agent",subtitle:E.role||"Agent"});for(const E of a)E.id!==n?.id&&h.push({id:E.id,name:E.name,type:"human",subtitle:E.email||E.role||"Human"});return h},[r,a,n]),R=s.useMemo(()=>{if(!k)return p;const h=k.toLowerCase();return p.filter(E=>E.name.toLowerCase().includes(h)||E.subtitle.toLowerCase().includes(h))},[p,k]),P=h=>{y(E=>{const M=new Set(E);return M.has(h)?M.delete(h):M.add(h),M})},I=async()=>{if(!d.trim()||f.size===0)return;v(!0);const h=[...f],E={},M={};for(const V of h){const ie=p.find(N=>N.id===V);ie&&(E[V]=ie.type,M[V]=ie.name)}await o(d.trim(),h,E,M),v(!1)};return e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:i,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: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:u("modals.createGroupChat.title")}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:u("modals.createGroupChat.subtitle")})]}),e.jsx("div",{className:"px-5 py-3 border-b border-border-default",children:e.jsx("input",{value:d,onChange:h=>m(h.target.value),placeholder:u("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:k,onChange:h=>j(h.target.value),placeholder:u("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:[R.length===0&&e.jsx("p",{className:"text-xs text-fg-tertiary px-2 py-4 text-center",children:u("modals.createGroupChat.noMembersFound")}),R.map(h=>e.jsxs("button",{onClick:()=>P(h.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(h.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(h.id)?"bg-brand-500 border-brand-500":"border-border-default"}`,children:f.has(h.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(wt,{name:h.name,size:20,bgClass:h.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:h.name}),e.jsx("span",{className:"text-[9px] text-fg-tertiary",children:h.subtitle})]}),e.jsx("span",{className:`text-[8px] px-1.5 py-0.5 rounded-full font-medium ${h.type==="agent"?"bg-brand-500/10 text-brand-500":"bg-green-500/10 text-green-600"}`,children:h.type==="agent"?u("modals.addExisting.typeAgent"):u("modals.addExisting.typeHuman")})]},h.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:u("modals.createGroupChat.selected",{count:f.size})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:i,className:"px-3 py-1.5 text-xs text-fg-secondary hover:text-fg-primary rounded-lg hover:bg-surface-overlay transition-colors",children:u("common:cancel")}),e.jsx("button",{onClick:I,disabled:!d.trim()||f.size===0||$,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:u($?"modals.createGroupChat.creating":"modals.createGroupChat.create")})]})]})]})})}const Gl=s.memo(function({authUser:a,agents:n,teams:i,humans:o,tasks:u,externalAgents:d,groupChats:m,chatMode:f,selectedAgent:y,activeChannel:k,activeDmUserId:j,onSelectAgent:$,onSelectChannel:v,onSelectDm:p,onSelectTeam:R,selectedTeamId:P,onRefreshTeams:I,onRefreshAgents:h,onRefreshHumans:E,onRefreshGroupChats:M,onViewProfile:V,onManageGroupMembers:ie,unreadByAgent:N,unreadByChannel:L,width:F,onResizeStart:ke,hidden:Be,onCollapse:A,initialLoading:ce,previewMode:te}){const{t:S}=Xe(["team","common"]),J=xa(),Ee=Wi(gt.TEAM),$e=a?.role==="owner"||a?.role==="admin",b=s.useMemo(()=>new Set(d.map(g=>g.markusAgentId).filter(Boolean)),[d]),[U,fe]=s.useState([]),[be,_]=s.useState(new Set),[Q,ne]=s.useState(!1),[ye,ze]=s.useState(!1),[Je,kt]=s.useState(null),[is,ys]=s.useState(!1),[Ys,Qt]=s.useState(!1),[Nt,ht]=s.useState(null),[oe,qe]=s.useState(null),[Ke,He]=s.useState(null),[St,mn]=s.useState(!1),[zn,xn]=s.useState(""),[Zt,fn]=s.useState(null),[gn,ha]=s.useState(null),[Ms,vs]=s.useState(null),[js,Jt]=s.useState(!1),Wn=s.useRef(null),[jr,Is]=s.useState(null),os=s.useRef(null),Hn=s.useRef(null),[hn,pn]=s.useState(null),Es=(g,q="success")=>{pn({message:g,type:q}),setTimeout(()=>pn(null),3e3)},[Ot,Ut]=s.useState(null),[Vn,bn]=s.useState(!1),Xs=s.useRef(!1);s.useEffect(()=>{if(te)return;T.governance.getSystemStatus().then(G=>{Xs.current=!0,Ut(G.globalPaused)}).catch(()=>{Xs.current=!0,Ut(!1)});const g=We.on("system:pause-all",()=>{Xs.current&&Ut(!0)}),q=We.on("system:resume-all",()=>{Xs.current&&Ut(!1)});return()=>{g(),q()}},[]),s.useEffect(()=>{if(!te)return;const g=setTimeout(()=>{const q=Hn.current,G=os.current;q&&G&&G.scrollTo({top:q.offsetTop-G.offsetTop-8,behavior:"instant"})},100);return()=>clearTimeout(g)},[te]);const yn=s.useCallback(()=>{Ot!==null&&As({title:S(Ot?"modals.resumeAll.title":"modals.pauseAll.title"),message:S(Ot?"modals.resumeAll.message":"modals.pauseAll.message"),confirmLabel:S(Ot?"chat.resume":"chat.pause"),onConfirm:async()=>{bn(!0);try{Ot?(await T.governance.resumeAll(),Ut(!1)):(await T.governance.pauseAll(),Ut(!0))}catch{}bn(!1)}})},[Ot]),[es,As]=s.useState(null),Qs=(g,q,G,ge,Ce)=>{As({title:g,message:q,onConfirm:G,confirmLabel:ge,checkboxes:Ce})},[Ft,ws]=s.useState(null),[Ps,vn]=s.useState(null),Bt=s.useRef(null),Ct=s.useRef(null),[Gt,jn]=s.useState(!1),[O,Oe]=s.useState(null),[K,dt]=s.useState(""),Pe=s.useCallback((g,q=176,G=220)=>{const ge=window.innerWidth,Ce=window.innerHeight,Fe=8;let Ze=g.clientX,Ve=g.clientY;return Ze+q>ge-Fe&&(Ze=Math.max(Fe,ge-q-Fe)),Ve+G>Ce-Fe&&(Ve=Math.max(Fe,Ce-G-Fe)),Ze=Math.max(Fe,Math.min(Ze,ge-q-Fe)),Ve=Math.max(Fe,Math.min(Ve,Ce-G-Fe)),{x:Ze,y:Ve}},[]),[It,at]=s.useState(xr),_s=s.useMemo(()=>n.map(g=>g.id).sort().join(","),[n]);s.useEffect(()=>{if(!n.length||!Ee)return;let g=!1;(async()=>{const Ve=[];await Promise.allSettled(n.map(async De=>{if(!xr.has(De.id))try{const{sessions:it}=await T.sessions.listByAgent(De.id,1);if(!it.length)return;const{messages:bt}=await T.sessions.getMessages(it[0].id,1);if(bt.length){const mt=bt[0],Yt=mt.metadata?.segments;let ct=mt.content;if(Yt&&Yt.length>0){const Rt=[...Yt].reverse().find(ks=>ks.type==="text");Rt&&Rt.type==="text"&&(ct=Rt.content)}const nt=ct.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80);nt&&Ve.push([De.id,nt])}}catch{}})),!g&&Ve.length&&at(De=>{const it=new Map(De);for(const[bt,mt]of Ve)it.set(bt,mt);return xr=it,it})})();const G=new Set(n.map(Ve=>Ve.id)),ge=Ve=>Ve.replace(/<think>[\s\S]*?(<\/think>|$)/g,"").replace(/<(invoke|function_calls|antml:\w+)\b[\s\S]*?(<\/\1>|$)/g,"").replace(/\n+/g," ").trim().slice(0,80),Ce=(Ve,De)=>{if(!Ve||!De||!G.has(Ve))return;const it=ge(De);it&&at(bt=>{const mt=new Map(bt);return mt.set(Ve,it),xr=mt,mt})},Fe=We.on("chat:proactive_message",Ve=>{const De=Ve.payload;Ce(De.agentId??"",De.message??"")}),Ze=We.on("chat:message",Ve=>{const De=Ve.payload,it=De.senderId??De.agentId??"",bt=De.text??De.message??"";Ce(it,bt)});return()=>{g=!0,Fe(),Ze()}},[_s,Ee]);const Et=s.useCallback(()=>{te||T.teams.list().then(g=>fe(g.ungrouped)).catch(()=>{})},[te]);s.useEffect(()=>{Et()},[Et]),s.useEffect(()=>{if(!Ee)return;const g=We.on("team:update",Et),q=We.on("agent:removed",Et);return()=>{g(),q()}},[Et,Ee]),s.useEffect(()=>{if(!oe&&!Ke&&!Zt&&!js&&!Ms)return;const g=()=>{qe(null),He(null),fn(null),vs(null),Jt(!1)},q=setTimeout(()=>document.addEventListener("click",g),0);return()=>{clearTimeout(q),document.removeEventListener("click",g)}},[oe,Ke,Zt,js,Ms]);const Ls=(g,q)=>{Qs(`${S("common:delete")} "${q}"?`,S("modals.deleteTeam.message"),async G=>{const ge=G?.deleteMembers??!0,Ce=G?.purgeFiles??!1;await T.teams.delete(g,ge,{purgeFiles:Ce}),I(),Et(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},S("contextMenu.deleteTeam"),[{id:"deleteMembers",label:S("modals.deleteTeam.deleteMembers"),defaultChecked:!0},{id:"purgeFiles",label:S("modals.deleteTeam.purgeFiles"),defaultChecked:!1}])},Zs=async(g,q)=>{try{const ge=await(q==="start"?T.teams.startAll:T.teams.stopAll)(g),Ce=ge.success?.length??0,Fe=ge.failed?.length??0;Fe>0?Es(S("batchAction.failed",{action:S(`batchAction.operation.${q}`),ok:Ce,fail:Fe}),"error"):Ce>0&&Es(S("batchAction.succeeded",{count:Ce,action:S(`batchAction.past.${q}`)}),"success"),h()}catch(G){Es(S("batchAction.failedToRun",{action:S(`batchAction.operation.${q}`),error:G instanceof Error?G.message:String(G)}),"error")}},wr=async(g,q,G)=>{await T.teams.update(g,{managerId:q,managerType:G}),I()},qn=async g=>{if(!K.trim()){Oe(null);return}await T.teams.update(g,{name:K.trim()}),Oe(null),I()},Qe=async(g,q)=>{q==="offline"?await T.agents.start(g):await T.agents.stop(g),h()},Tt=(g,q)=>{Qs(S("modals.removeFromTeam.title"),S("modals.removeFromTeam.message"),async()=>{await T.teams.removeMember(g,q),I(),Et()},S("common:remove"))},Lt=(g,q,G)=>{Qs(`${S("common:remove")} "${q}"?`,S(G==="agent"?"modals.removeAgent.message":"modals.removeHuman.message"),async ge=>{if(G==="agent"){const Ce=ge?.purgeFiles??!1;await T.agents.remove(g,{purgeFiles:Ce})}else await T.users.remove(g);h(),I(),E?.(),Et(),window.dispatchEvent(new CustomEvent("markus:data-changed"))},S("common:remove"),G==="agent"?[{id:"purgeFiles",label:S("modals.removeAgent.purgeFiles"),defaultChecked:!1}]:void 0)},ut=g=>{if(g.isOrgSecretary||g.protected)return!0;if(g.teamId)return!1;const q=(g.role??"").toLowerCase().trim(),G=(g.name??"").trim();return G==="Secretary"||G==="秘书"||q==="secretary"||q.startsWith("secretary")},kr=(g,q,G)=>{const ge=n.find(Ce=>Ce.id===q);ge&&ut(ge)||(Ct.current={x:g.clientX,y:g.clientY},Bt.current=setTimeout(()=>{ws({agentId:q,fromTeamId:G}),jn(!0)},200))},Kt=g=>{if(!Ct.current||!Bt.current)return;const q=Math.abs(g.clientX-Ct.current.x),G=Math.abs(g.clientY-Ct.current.y);(q>5||G>5)&&(Gt||(clearTimeout(Bt.current),Bt.current=null))},pt=async()=>{if(Bt.current&&(clearTimeout(Bt.current),Bt.current=null),Ct.current=null,Gt&&Ft&&Ps){const g=Ps==="_ungrouped"?void 0:Ps;try{if(Ft.fromTeamId&&Ft.fromTeamId!==g&&await T.teams.removeMember(Ft.fromTeamId,Ft.agentId),g&&g!==Ft.fromTeamId){const q=n.find(G=>G.id===Ft.agentId);await T.teams.addMember(g,Ft.agentId,"agent")}I(),h(),Et()}catch(q){Es(S("batchAction.moveFailed",{error:q instanceof Error?q.message:String(q)}),"error")}}ws(null),vn(null),jn(!1)},Rs=s.useMemo(()=>new Map(i.map(g=>[g.id,g])),[i]),At=s.useMemo(()=>{const g=new Map,q=[];for(const G of n)if(G.teamId&&Rs.has(G.teamId)){const ge=g.get(G.teamId)??[];ge.push(G),g.set(G.teamId,ge)}else q.push(G);return{byTeam:g,ungrouped:q}},[n,Rs]),zt=(g,q)=>{const G=f==="direct"&&y===g.id,ge=b.has(g.id),Ce=g.status==="offline",Fe=g.status==="idle"?"bg-green-500":g.status==="working"?"bg-blue-500 animate-pulse":g.status==="error"?"bg-red-500":"bg-gray-600",Ve=(void 0)?.managerId===g.id,De=g.role?.toLowerCase().replace(/[-_]/g," ").trim(),it=g.name.toLowerCase().trim(),bt=De&&De!==it,mt=It.get(g.id)||g.currentActivity?.label?.slice(0,60)||"",Yt=g.status==="idle"?S("common:status.online"):g.status==="working"?S("common:status.working"):g.status==="error"?S("common:status.error"):S("common:status.offline");return e.jsx("div",{className:`relative mb-0.5 ${Gt&&Ft?.agentId===g.id?"opacity-40":""}`,onPointerDown:ct=>kr(ct,g.id,q),onPointerMove:Kt,onPointerUp:pt,children:e.jsxs("button",{onClick:()=>{Gt||$(g.id)},onContextMenu:ct=>{if(!$e)return;ct.preventDefault();const nt=Pe(ct);mn(!1),xn(""),He({agentId:g.id,teamId:q,...nt})},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"} ${Ce?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${G?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(wt,{name:g.name,avatarUrl:g.avatarUrl,size:28,bgClass:Ce?"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}),bt&&e.jsxs("span",{className:"text-[9px] text-fg-secondary shrink-0 truncate max-w-[80px]",children:["(",g.role,")"]}),Ve&&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"})}),ge&&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"}),Ce&&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:S("common:status.offline")})]}),e.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:mt||" "})]}),e.jsxs("span",{className:"flex items-center gap-1.5 shrink-0",children:[(N?.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",children:N.get(g.id)}),g.mailboxDepth!=null&&g.mailboxDepth>0&&e.jsx("span",{className:"text-[8px] text-fg-tertiary bg-surface-overlay rounded-full px-1 leading-relaxed",children:g.mailboxDepth}),e.jsx("span",{title:Yt,onClick:ct=>{ct.stopPropagation(),V(g.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] ${Fe}`}),J&&$e&&e.jsx("span",{role:"button",tabIndex:0,onClick:ct=>{if(ct.stopPropagation(),Ke?.agentId===g.id)He(null);else{const nt=Pe(ct);mn(!1),xn(""),He({agentId:g.id,teamId:q,...nt})}},className:"w-5 h-5 flex items-center justify-center text-fg-tertiary hover:text-fg-secondary rounded transition-colors",title:S("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"})]})})]})]})},g.id)},Un=(g,q,G,ge)=>{const Ce=Gt&&Ps===g&&Ft?.fromTeamId!==g,Fe=jr===g,Ze=P===g,Ve=N?(At.byTeam.get(g)??[]).reduce((et,ts)=>et+(N.get(ts.id)??0),0):0,De=m.find(et=>et.type==="team"&&et.teamId===g),it=De&&L?L[De.channelKey]??0:0,bt=Ve+it,mt=At.byTeam.get(g)??[],Yt=mt.filter(et=>et.status==="offline").length,ct=mt.length,nt=ct>0&&Yt===ct,Rt=Yt>0&&!nt,ks=nt?"bg-gray-500":Rt?"bg-amber-500":"bg-green-500";return e.jsxs("div",{"data-team-id":g,className:`mb-0.5 rounded-lg transition-all duration-500 ${Ce?"ring-1 ring-brand-500/50 bg-brand-500/5":""} ${Fe?"ring-2 ring-brand-500 bg-brand-500/10":""}`,onPointerEnter:()=>{Gt&&vn(g)},onPointerLeave:()=>{Gt&&Ps===g&&vn(null)},children:[e.jsxs("div",{className:"group/teamhdr flex items-center gap-0.5",children:[e.jsxs("button",{onClick:()=>{R&&g!=="_ungrouped"&&R(g)},onContextMenu:et=>{if(!$e||!q)return;et.preventDefault();const ts=Pe(et);qe({teamId:g,...ts})},className:`flex-1 flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs transition-colors min-w-0 ${nt?"opacity-50 text-fg-tertiary":"text-fg-primary"} ${Ze?"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 ${nt?"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"})]}),ct>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:[O===g?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:et=>dt(et.target.value),onBlur:()=>qn(g),onKeyDown:et=>{et.key==="Enter"&&qn(g),et.key==="Escape"&&Oe(null)},onClick:et=>et.stopPropagation(),autoFocus:!0}):e.jsx("span",{className:"truncate font-medium text-[12px] leading-tight block",children:ge}),e.jsxs("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5 flex items-center gap-1.5",children:[S("chat.members_other",{count:G}),nt&&e.jsx("span",{className:"text-[8px] px-1 py-0 rounded bg-gray-500/20 text-gray-400 font-medium leading-relaxed",children:S("common:status.offline")}),Rt&&e.jsxs("span",{className:"text-[8px] px-1 py-0 rounded bg-amber-500/20 text-amber-500 font-medium leading-relaxed",children:[Yt,"/",ct]})]})]}),bt>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:bt}),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"})})]}),$e&&q&&e.jsx("button",{onClick:et=>{if(et.stopPropagation(),oe?.teamId===g)qe(null);else{const ts=Pe(et);qe({teamId:g,...ts})}},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:S("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"})]})})]}),Ce&&Gt&&e.jsx("div",{className:"text-[9px] text-brand-500 px-4 py-0.5 animate-pulse",children:S("chat.dropHere")})]},g)},Ne=s.useMemo(()=>{const g=new Map,q=[],G=[],ge=[];for(const Ce of m)if(Ce.channelKey.startsWith("dm:a2a:"))ge.push(Ce);else if(Ce.type==="custom")G.push(Ce);else if(Ce.teamId){const Fe=g.get(Ce.teamId)??[];Fe.push(Ce),g.set(Ce.teamId,Fe)}else{const Fe=i.find(Ze=>Ce.name.toLowerCase().includes(Ze.name.toLowerCase())||Ze.name.toLowerCase().includes(Ce.name.toLowerCase()));if(Fe){const Ze=g.get(Fe.id)??[];Ze.push(Ce),g.set(Fe.id,Ze)}else q.push(Ce)}return{byTeam:g,unmatched:q,custom:G,dmChannels:ge}},[m,i]),[_e,ls]=s.useState(!1),Ds=f==="channel"&&Ne.dmChannels.some(g=>g.channelKey===k);return s.useEffect(()=>{Ds&&ls(!0)},[Ds]),e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:`bg-surface-primary flex flex-col ${F!=null?"shrink-0":"flex-1 min-w-0"}`,style:Be?{display:"none"}:F!=null?{width:F}: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(el,{}),!J&&A&&e.jsx("button",{onClick:A,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:S("chat.title")}),$e&&e.jsxs("div",{"data-no-drag":!0,className:"ml-auto relative",ref:Wn,children:[e.jsxs("button",{onClick:()=>Jt(!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:"+"})," ",S("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:g=>{if(!g)return;const q=g.getBoundingClientRect(),G=window.innerWidth,ge=8;q.right>G-ge&&(g.style.left="auto",g.style.right="0"),q.left<ge&&(g.style.left="0",g.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:()=>{Jt(!1),ht("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"})]}),S("chat.addAgent")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:S("chat.addAgentDesc")})]}),e.jsxs("button",{onClick:()=>{Jt(!1),ht("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"})]}),S("chat.newTeam")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:S("chat.newTeamDesc")})]}),e.jsxs("button",{onClick:()=>{Jt(!1),ze(!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"})]}),S("chat.addHuman")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:S("chat.addHumanDesc")})]}),e.jsxs("button",{onClick:()=>{Jt(!1),Qt(!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"})]}),S("chat.newGroupChat")]}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:S("chat.newGroupChatDesc")})]}),Ot!==null&&e.jsxs("button",{onClick:()=>{Jt(!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 ${Ot?"text-green-600":"text-red-500"}`,children:[e.jsx("div",{className:"font-medium flex items-center gap-1.5",children:Ot?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"})})," ",S("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"})})," ",S("contextMenu.stopAll")]})}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5 pl-[18px]",children:S(Ot?"modals.resumeAll.title":"modals.pauseAll.title")})]})]})]})]}),e.jsxs("div",{ref:os,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:S("chat.people")}),a&&e.jsxs("button",{onClick:()=>p(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(wt,{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:S("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(g=>g.id!==a?.id).map(g=>{const q=a?.id?`dm:${[a.id,g.id].sort().join(":")}`:"",G=q&&L?L[q]??0:0;return e.jsxs("button",{onClick:()=>p(g.id),onContextMenu:ge=>{if(!$e||g.id===a?.id)return;ge.preventDefault();const Ce=Pe(ge);fn({userId:g.id,...Ce})},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===g.id?"bg-green-500/15":"hover:bg-surface-overlay/60"}`,children:[e.jsx(wt,{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.jsx("div",{className:"truncate font-medium text-[12px] leading-tight",children:g.name}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:g.email||g.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"})]},g.id)})]}),Ne.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:S("chat.groups")}),Ne.custom.map(g=>{const q=f==="channel"&&k===g.channelKey;return e.jsxs("button",{onClick:()=>v(g.channelKey),onContextMenu:G=>{G.preventDefault();const ge=Pe(G);vs({gcId:g.id,...ge})},className:`w-full flex items-center gap-2.5 px-2.5 py-2 rounded-lg text-xs mb-0.5 transition-colors text-fg-primary ${q?"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:g.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:S("chat.members_other",{count:g.memberCount??0})})]})]},g.id)})]}),ce?e.jsx("div",{className:"space-y-3 px-1 mb-2",children:[...Array(6)].map((g,q)=>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"})]},q))}):n.length===0&&i.length===0?e.jsx("p",{className:"text-xs text-fg-tertiary px-1 mb-2",children:S("chat.noAgentsYet")}):null,Ne.unmatched.map(g=>{const q=L?.[g.channelKey]??0;return e.jsxs("button",{onClick:()=>v(g.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"&&k===g.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:g.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:S("chat.groupChat")})]}),q>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:q}):g.memberCount!==void 0&&g.memberCount>0?e.jsx("span",{className:"text-[9px] text-fg-secondary shrink-0",children:g.memberCount}):null]},g.id)}),At.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:S("chat.agents")}),At.ungrouped.map(g=>zt(g))]}),i.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:S("chat.teams")}),i.map(g=>{const q=At.byTeam.get(g.id)??[],G=g.members?.length||q.length;return Un(g.id,g,G,g.name)})]}),i.length===0&&At.ungrouped.length===0&&n.length>0&&n.map(g=>zt(g)),Ne.dmChannels.length>0&&e.jsxs("div",{className:"mb-2",children:[e.jsxs("button",{onClick:()=>ls(g=>!g),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 ${_e?"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"})}),S("chat.agentDMs"),e.jsx("span",{className:"ml-auto text-[9px] font-normal text-fg-tertiary",children:Ne.dmChannels.length})]}),_e&&Ne.dmChannels.map(g=>{const q=f==="channel"&&k===g.channelKey,G=L?.[g.channelKey]??0,ge=g.name.replace(/^DM:\s*/,"");return e.jsxs("button",{onClick:()=>v(g.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 ${q?"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:ge}),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})]},g.id)})]})]})]}),ke&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:ke,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"})}),oe&&(()=>{const g=At.byTeam.get(oe.teamId)??[],q=g.some(ge=>ge.status==="offline"),G=g.some(ge=>ge.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:oe.x,top:oe.y},onClick:ge=>ge.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{const ge=Rs.get(oe.teamId);ge&&(Oe(oe.teamId),dt(ge.name)),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-fg-secondary flex items-center gap-2",children:[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"})]}),S("contextMenu.renameTeam")]}),q&&e.jsxs("button",{onClick:()=>{Zs(oe.teamId,"start"),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-green-600 flex items-center gap-2",children:[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"})}),S("contextMenu.startAll")]}),G&&e.jsxs("button",{onClick:()=>{Zs(oe.teamId,"stop"),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[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"})}),S("contextMenu.stopAll")]}),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{qe(null),bs.navigate(gt.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"})]}),S("chat.addAgent")]}),U.length>0&&e.jsxs("button",{onClick:()=>{qe(null),kt(oe.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"})]}),S("contextMenu.addExisting")]}),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{const ge=Rs.get(oe.teamId);ge&&Ls(oe.teamId,ge.name),qe(null)},className:"w-full text-left px-3 py-2 text-xs hover:bg-surface-overlay text-red-500 flex items-center gap-2",children:[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"})]}),S("contextMenu.deleteTeam")]})]})})(),Ke&&(()=>{const g=n.find(Fe=>Fe.id===Ke.agentId);if(!g||!$e)return null;const G=(Ke.teamId?Rs.get(Ke.teamId):void 0)?.managerId===g.id,ge=g.id===a?.id,Ce=ut(g);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:Ke.x,top:Ke.y,maxHeight:Math.max(160,window.innerHeight-Ke.y-8)},onClick:Fe=>Fe.stopPropagation(),children:[Ce&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 py-2 text-[10px] leading-snug text-fg-secondary font-medium",children:S("contextMenu.orgSecretaryProtected")}),e.jsx("div",{className:"border-t border-border-default/50 my-1"})]}),e.jsxs("button",{onClick:()=>{He(null),V(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"})]}),S("contextMenu.viewProfile")]}),g.status==="offline"?e.jsxs("button",{onClick:()=>{Qe(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"})}),S("contextMenu.start")]}):e.jsxs("button",{onClick:()=>{Qe(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"})}),S("contextMenu.stop")]}),!Ce&&Ke.teamId&&!G&&e.jsxs("button",{onClick:()=>{wr(Ke.teamId,g.id,"agent"),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"})}),S("contextMenu.setAsManager")]}),!Ce&&Ke.teamId&&e.jsxs("button",{onClick:()=>{Tt(Ke.teamId,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"})]}),S("contextMenu.removeFromTeam")]}),!Ce&&(()=>{const Fe=i.filter(De=>De.id!==Ke.teamId);if(Fe.length===0)return null;const Ze=zn.trim().toLowerCase(),Ve=Ze?Fe.filter(De=>De.name.toLowerCase().includes(Ze)):Fe;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(De=>!De),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:S("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 ${St?"rotate-180":""}`,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),St&&e.jsxs("div",{className:"px-2 pb-1.5",onClick:De=>De.stopPropagation(),children:[e.jsx("input",{autoFocus:!0,value:zn,onChange:De=>xn(De.target.value),onKeyDown:De=>De.stopPropagation(),placeholder:S("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:Ve.length===0?e.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:S("contextMenu.moveToEmpty")}):Ve.map(De=>e.jsx("button",{type:"button",onClick:async()=>{Ke.teamId&&await T.teams.removeMember(Ke.teamId,g.id),await T.teams.addMember(De.id,g.id,"agent"),I(),h(),Et(),He(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:De.name,children:De.name},De.id))})]})]})})(),!Ce&&!ge&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:()=>{Lt(g.id,g.name,"agent"),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"})]}),S("contextMenu.removeFromOrg")]})]})]})})(),Zt&&(()=>{const g=o.find(q=>q.id===Zt.userId);return!g||!$e?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:Zt.x,top:Zt.y},onClick:q=>q.stopPropagation(),children:e.jsxs("button",{onClick:()=>{Lt(g.id,g.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"})]}),S("contextMenu.removeFromOrg")]})})})(),Q&&e.jsx(Wl,{onClose:()=>ne(!1),onCreate:async(g,q)=>{try{const{team:G}=await T.teams.create(g,q);ne(!1),I(),Is(G.id),setTimeout(()=>{document.querySelector(`[data-team-id="${G.id}"]`)?.scrollIntoView({behavior:"smooth",block:"center"})},300),setTimeout(()=>Is(null),3e3)}catch(G){Es(S("chat.failedToCreateTeam",{message:G instanceof Error?G.message:String(G)}),"error")}}}),ye&&e.jsx(Hl,{onClose:()=>{ze(!1),E?.()},onAdd:async(g,q,G)=>{const{inviteToken:ge}=await T.users.create(g,q,void 0,G);return E?.(),{inviteToken:ge}}}),Je!==null&&e.jsx(Vl,{teamId:Je,ungrouped:U,onClose:()=>kt(null),onAdd:async(g,q)=>{await T.teams.addMember(Je,g,q),kt(null),I(),Et()}}),is&&e.jsx(ql,{onClose:()=>ys(!1),onConnected:()=>{ys(!1),h(),I()}}),Ms&&(()=>{const g=m.find(q=>q.id===Ms.gcId);return g?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:q=>q.stopPropagation(),children:[g.type==="custom"&&e.jsxs("button",{onClick:()=>{vs(null),ie?ie(g.channelKey):v(g.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"})]}),S("contextMenu.manageMembers")]}),e.jsxs("button",{onClick:async()=>{vs(null),Qs(S("modals.deleteGroupChat.title"),S("modals.deleteGroupChat.message",{name:g.name}),async()=>{await T.groupChats.delete(g.id),M()},S("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"})]}),S("modals.deleteGroupChat.menuLabel")]})]}):null})(),Ys&&e.jsx(Ul,{agents:n,humans:o,authUser:a,onClose:()=>Qt(!1),onCreate:async(g,q,G,ge)=>{await T.groupChats.create({name:g,memberIds:q,memberTypes:G,memberNames:ge,creatorId:a?.id,creatorName:a?.name}),Qt(!1),M()}}),Nt&&e.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",onClick:()=>ht(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:g=>g.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:S(Nt==="agent"?"chat.addAgent":"chat.newTeam")}),e.jsx("p",{className:"text-[11px] text-fg-tertiary mt-0.5",children:S("chat.methodChoiceSubtitle")})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>{const g=Nt;ht(null);const q=n.find(G=>G.role==="secretary")??n.find(G=>G.name?.toLowerCase().includes("secretary"));q?($(q.id),bs.navigate(gt.TEAM,{agentId:q.id,prefillMessage:S(g==="agent"?"chat.addAgentPrefill":"chat.newTeamPrefill")})):g==="agent"?bs.navigate(gt.STORE):ne(!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:S("chat.methodSecretary")}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:S("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:S("chat.recommended")})]}),e.jsxs("button",{onClick:()=>{const g=Nt;ht(null),g==="agent"?bs.navigate(gt.STORE):ne(!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:S("chat.methodManual")}),e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:S(Nt==="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:()=>ht(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:S("common:cancel")})})]})}),es&&e.jsx(Bn,{title:es.title,message:es.message,confirmLabel:es.confirmLabel,checkboxes:es.checkboxes,onConfirm:g=>{es.onConfirm(g),As(null)},onCancel:()=>As(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 hi({team:r,agents:a,humans:n,authUser:i,groupChat:o,chatMode:u,selectedAgent:d,activeChannel:m,teams:f,onSelectAgent:y,onSelectChannel:k,onSelectDm:j,onBack:$,onViewProfile:v,onRefreshAgents:p,onRefreshTeams:R,unreadByAgent:P,width:I,onResizeStart:h}){const{t:E}=Xe(["team","common"]),M=i?.role==="owner"||i?.role==="admin",V=s.useMemo(()=>a.filter(b=>b.teamId===r.id),[a,r.id]),ie=s.useMemo(()=>{const b=new Set((r.members??[]).filter(U=>U.type==="human").map(U=>U.id));return n.filter(U=>b.has(U.id))},[r.members,n]),N=o&&u==="channel"&&m===o.channelKey,[L,F]=s.useState(null),[ke,Be]=s.useState(!1),[A,ce]=s.useState(""),te=s.useCallback((b,U=176,fe=220)=>{const be=window.innerWidth,_=window.innerHeight,Q=8;let ne=b.clientX,ye=b.clientY;return ne+U>be-Q&&(ne=Math.max(Q,be-U-Q)),ye+fe>_-Q&&(ye=Math.max(Q,_-fe-Q)),ne=Math.max(Q,Math.min(ne,be-U-Q)),ye=Math.max(Q,Math.min(ye,_-fe-Q)),{x:ne,y:ye}},[]);s.useEffect(()=>{if(!L)return;const b=()=>F(null),U=setTimeout(()=>document.addEventListener("click",b),0);return()=>{clearTimeout(U),document.removeEventListener("click",b)}},[L]);const S=s.useCallback(async(b,U)=>{U==="offline"?await T.agents.start(b):await T.agents.stop(b),p()},[p]),J=s.useCallback(async b=>{await T.teams.update(r.id,{managerId:b,managerType:"agent"}),R()},[r.id,R]),Ee=s.useCallback(async b=>{await T.teams.removeMember(r.id,b),R(),p()},[r.id,R,p]),$e=s.useCallback(async(b,U)=>{await T.teams.removeMember(r.id,b),await T.teams.addMember(U,b,"agent"),R(),p()},[r.id,R,p]);return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"bg-surface-primary flex flex-col shrink-0",style:I!=null?{width:I}:{width:260},children:[e.jsxs("div",{className:"px-3 h-14 flex items-center gap-2 shrink-0",children:[e.jsx("button",{onClick:$,className:"w-8 h-8 flex items-center justify-center rounded-lg bg-brand-500/15 text-brand-500 transition-colors shrink-0",title:E("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:r.name}),r.description&&e.jsx("div",{className:"truncate text-[10px] text-fg-tertiary",children:r.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:E("chat.groupChat",{defaultValue:"Group Chat"})}),e.jsxs("button",{onClick:()=>k(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 ${N?"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:r.name}),e.jsx("div",{className:"text-[10px] text-fg-secondary leading-tight mt-0.5",children:E("chat.members_other",{count:o.memberCount||V.length+ie.length})})]})]})]}),V.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:[E("chat.agents",{defaultValue:"Agents"}),e.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:V.length})]}),V.map(b=>{const U=u==="direct"&&d===b.id,fe=r.managerId===b.id,be=b.status==="offline",_=b.status==="idle"?"bg-green-500":b.status==="working"?"bg-blue-500 animate-pulse":b.status==="error"?"bg-red-500":"bg-gray-600";return e.jsxs("button",{onClick:()=>y(b.id),onContextMenu:Q=>{if(!M)return;Q.preventDefault();const ne=te(Q);Be(!1),ce(""),F({agentId:b.id,...ne})},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"} ${U?"bg-surface-overlay":"hover:bg-surface-overlay/60"}`,children:[e.jsx(wt,{name:b.name,avatarUrl:b.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:b.name}),fe&&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:E("common:status.offline")})]}),e.jsx("div",{className:"truncate text-[10px] leading-tight mt-0.5 text-fg-secondary",children:b.role||" "})]}),(P?.get(b.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:P.get(b.id)}),e.jsx("span",{title:b.status,onClick:Q=>{Q.stopPropagation(),v(b.id)},className:`w-2 h-2 rounded-full cursor-pointer transition-transform duration-150 hover:scale-[2] shrink-0 ${_}`})]},b.id)})]}),ie.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:[E("chat.people"),e.jsx("span",{className:"ml-1 text-fg-tertiary font-normal",children:ie.length})]}),ie.map(b=>{const U=b.id===i?.id;return e.jsxs("button",{onClick:()=>j(b.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(wt,{name:b.name,avatarUrl:b.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:[b.name,U?` (${E("chat.you",{defaultValue:"You"})})`:""]}),e.jsx("div",{className:"text-fg-secondary truncate text-[10px] leading-tight mt-0.5",children:b.email||b.role})]}),e.jsx("span",{className:"w-2 h-2 rounded-full bg-green-500 shrink-0"})]},b.id)})]}),V.length===0&&ie.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-6 px-2",children:E("chat.noMembers",{defaultValue:"No members in this team yet."})})]})]}),h&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative flex items-center justify-center",onMouseDown:h,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"})}),L&&(()=>{const b=V.find(fe=>fe.id===L.agentId);if(!b||!M)return null;const U=r.managerId===b.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:L.x,top:L.y,maxHeight:Math.max(160,window.innerHeight-L.y-8)},onClick:fe=>fe.stopPropagation(),children:[e.jsxs("button",{onClick:()=>{F(null),v(b.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"})]}),E("contextMenu.viewProfile")]}),b.status==="offline"?e.jsxs("button",{onClick:()=>{S(b.id,"offline"),F(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"})}),E("contextMenu.start")]}):e.jsxs("button",{onClick:()=>{S(b.id,b.status??"idle"),F(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"})}),E("contextMenu.stop")]}),!U&&e.jsxs("button",{onClick:()=>{J(b.id),F(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"})}),E("contextMenu.setAsManager")]}),e.jsxs("button",{onClick:()=>{Ee(b.id),F(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"})]}),E("contextMenu.removeFromTeam")]}),(()=>{const fe=f.filter(Q=>Q.id!==r.id);if(fe.length===0)return null;const be=A.trim().toLowerCase(),_=be?fe.filter(Q=>Q.name.toLowerCase().includes(be)):fe;return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{type:"button",onClick:()=>Be(Q=>!Q),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:E("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 ${ke?"rotate-180":""}`,children:e.jsx("polyline",{points:"6 9 12 15 18 9"})})]}),ke&&e.jsxs("div",{className:"px-2 pb-1.5",onClick:Q=>Q.stopPropagation(),children:[e.jsx("input",{autoFocus:!0,value:A,onChange:Q=>ce(Q.target.value),onKeyDown:Q=>Q.stopPropagation(),placeholder:E("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:_.length===0?e.jsx("div",{className:"px-2 py-2 text-[10px] text-fg-tertiary",children:E("contextMenu.moveToEmpty")}):_.map(Q=>e.jsx("button",{type:"button",onClick:()=>{$e(b.id,Q.id),F(null)},className:"w-full text-left px-2 py-1.5 text-xs hover:bg-surface-overlay text-fg-secondary rounded truncate",title:Q.name,children:Q.name},Q.id))})]})]})})(),e.jsx("div",{className:"border-t border-border-default/50 my-1"}),e.jsxs("button",{onClick:async()=>{await T.agents.remove(b.id),p(),F(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"})]}),E("contextMenu.removeFromOrg")]})]})})()]})}function Kl(r){const a=r.trim();return!a||a==="about:blank"?a:/^[a-z][a-z0-9+.-]*:/i.test(a)?/^file:/i.test(a)?Xl(a):a:Yl(a)?Xi(a):`https://${a}`}function Yl(r){return!!(r.startsWith("/")||/^[a-zA-Z]:[\\/]/.test(r)||r.startsWith("\\\\"))}function Xi(r){const a=r.replace(/\\/g,"/");return a.startsWith("//")?`file:${la(a)}`:/^[a-zA-Z]:\//.test(a)?`file:///${la(a)}`:`file://${la(a)}`}function Xl(r){try{return new URL(r).href}catch{let a=r.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}`),Xi(a)}}function la(r){return encodeURI(r).replace(/#/g,"%23")}function Ql({url:r,browserId:a,className:n,onMeta:i}){const{t:o}=Xe("common"),u=s.useId().replace(/:/g,""),d=a||`eb_${u}`,m=!a,f=s.useRef(null),y=s.useRef(null),k=s.useRef(null),[j,$]=s.useState(r==="about:blank"?"":r),[v,p]=s.useState(!1),[R,P]=s.useState(!1),[I,h]=s.useState(!1),[E,M]=s.useState(null),[V,ie]=s.useState(null),[N,L]=s.useState(!1),F=typeof window<"u"?window.markusDesktop?.browser:void 0,ke=typeof window<"u"?window.markusDesktop?.platform:void 0;k.current=V;const Be=o(ke==="darwin"?"browserFolderAppFinder":ke==="win32"?"browserFolderAppExplorer":"browserFolderAppGeneric");return s.useEffect(()=>{if(!F)return;let A=!1;return(async()=>{const ce=await F.getState(d);if(A||(ce.ok?r&&ce.url!==r&&!ce.directoryPath?(h(!0),await F.navigate(d,r)):r&&ce.directoryPath&&ce.url!==r&&await F.navigate(d,r):(h(!0),await F.create(d,r)),A))return;const te=await F.getState(d);A||!te.ok||(document.activeElement!==y.current&&$(te.url&&te.url!=="about:blank"?te.url:r==="about:blank"?"":r),h(!!te.isLoading),M(te.loadError??null),ie(te.directoryPath??null),(te.pageId!=null||te.url||te.title)&&i?.({pageId:te.pageId,url:te.url&&te.url!=="about:blank"?te.url:void 0,title:te.title||void 0}))})(),()=>{A=!0,m&&F.destroy(d)}},[F,d,r,m]),s.useEffect(()=>{if(r!=="about:blank")return;const A=window.setTimeout(()=>{y.current?.focus(),y.current?.select()},0);return()=>clearTimeout(A)},[r,d]),s.useEffect(()=>{if(F?.onPageEvent)return F.onPageEvent(A=>{if(A.browserId===d){if(A.type==="directory"){ie(A.directoryPath||null),h(!1),M(null),A.url&&document.activeElement!==y.current&&$(A.url);return}if(A.type==="loading"){h(!0),M(null),ie(null);return}if(A.type==="loaded"){if(h(!1),k.current)return;A.url&&document.activeElement!==y.current&&$(A.url==="about:blank"?"":A.url),window.dispatchEvent(new Event("markus:embedded-browser-resync"));return}if(A.type==="load-failed"){if(h(!1),k.current)return;M(A.error||"Load failed"),A.url&&document.activeElement!==y.current&&$(A.url==="about:blank"?"":A.url);return}A.type==="navigated"&&A.url&&document.activeElement!==y.current&&(k.current||$(A.url==="about:blank"?"":A.url))}})},[F,d]),s.useEffect(()=>{if(!F||!f.current)return;const A=f.current;let ce=!0;const te=()=>{let b=A;for(;b;){const U=getComputedStyle(b);if(U.visibility==="hidden"||U.display==="none")return!1;b=b.parentElement}return!0},S=()=>{if(!ce)return;if(!sl()||!te()||tl()||k.current){F.setBounds(d,{x:0,y:0,width:0,height:0},!1);return}const b=A.getBoundingClientRect();F.setBounds(d,{x:Math.round(b.left),y:Math.round(b.top),width:Math.round(b.width),height:Math.round(b.height)},b.width>2&&b.height>2)};S();const J=new ResizeObserver(S);J.observe(A),window.addEventListener("resize",S),window.addEventListener("scroll",S,!0),window.addEventListener("markus:embedded-browser-resync",S),window.addEventListener("markus:native-browser-overlay",S),window.addEventListener("markus:native-browser-page",S);const Ee=setInterval(()=>{ce&&F.getState(d).then(b=>{if(!ce||!b.ok)return;const U=b.directoryPath??null;ie(U),b.url&&document.activeElement!==y.current&&(U||b.url!=="about:blank")&&$(b.url==="about:blank"?"":b.url),p(!!b.canGoBack),P(!!b.canGoForward),h(!!b.isLoading),b.loadError!==void 0&&M(U?null:b.loadError??null)})},800),$e=()=>{F.setBounds(d,{x:0,y:0,width:0,height:0},!1)};return window.addEventListener("pagehide",$e),()=>{ce=!1,J.disconnect(),window.removeEventListener("resize",S),window.removeEventListener("scroll",S,!0),window.removeEventListener("markus:embedded-browser-resync",S),window.removeEventListener("markus:native-browser-overlay",S),window.removeEventListener("markus:native-browser-page",S),window.removeEventListener("pagehide",$e),clearInterval(Ee),F.setBounds(d,{x:0,y:0,width:0,height:0},!1)}},[F,d]),s.useEffect(()=>{window.dispatchEvent(new Event("markus:embedded-browser-resync"))},[V]),F?e.jsxs("div",{className:`flex flex-col h-full min-h-0 min-w-0 w-full ${n??""}`,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:!v,onClick:()=>{F.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:!R,onClick:()=>{F.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:()=>{I?F.action(d,"stop"):F.action(d,"reload")},className:"w-7 h-7 flex items-center justify-center rounded-md text-fg-tertiary hover:bg-surface-overlay",title:I?"Stop":"Reload",children:I?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:A=>{A.preventDefault();let ce=j.trim();ce&&(ce=Kl(ce),h(!0),M(null),ie(null),F.navigate(d,ce),$(ce))},children:e.jsx("input",{ref:y,value:j,onChange:A=>$(A.target.value),placeholder:o("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"})}),I&&e.jsx("span",{className:"shrink-0 text-[10px] text-fg-tertiary px-1 select-none",children:o("browserLoading")})]}),e.jsx("div",{className:`absolute left-2 right-2 bottom-0 h-0.5 overflow-hidden rounded-full transition-opacity ${I?"opacity-100":"opacity-0"}`,"aria-hidden":!I,children:e.jsx("div",{className:"h-full w-1/3 bg-brand-500 animate-[browser-load_1.1s_ease-in-out_infinite]"})})]}),E&&!I&&!V&&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:E}),e.jsx("div",{ref:f,className:"flex-1 min-h-0 min-w-0 w-full rounded-lg border border-border-default bg-surface-elevated/30 overflow-hidden",children:V&&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:o("browserFolderTitle")}),e.jsx("p",{className:"text-xs text-fg-tertiary break-all",children:V})]}),e.jsx("button",{type:"button",disabled:N,onClick:()=>{L(!0),T.system.openPath(V).catch(()=>T.files.reveal(V)).finally(()=>L(!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:N?o("browserFolderOpening"):o("browserFolderOpen",{app:Be})})]})}),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 ${n??""}`,children:[e.jsx("p",{className:"text-sm text-fg-secondary break-all",children:r}),e.jsx("button",{onClick:()=>window.open(r,"_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 pi(r){return/^(https?|file):\/\//i.test(r)?r:/^[a-zA-Z]:[\\/]/.test(r)?`file:///${r.replace(/\\/g,"/")}`:`file://${r.startsWith("/")?r:`/${r}`}`}function bi(r){return/^https?:\/\//i.test(r)}function Zl(r){return r.kind==="deliverable"?r.deliverable.reference??"":r.kind==="url"?r.url:r.path}function Jl(r){return r.kind==="deliverable"?r.deliverable.title||r.deliverable.reference||"":r.kind==="url"?r.title||r.url:r.title||r.path.split(/[/\\]/).pop()||r.path}function ec(r,a){if(r.kind==="file")return`file:${r.path}:${a??""}`;if(r.kind==="url")return`url:${r.browserId||r.url}:${a??""}`;const n=r.deliverable;return`deliverable:${n.id||n.reference||n.title||"unknown"}:${a??""}`}function ca(r){return r==null||!Number.isFinite(r)?"":r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}function tc({payload:r,onClose:a,width:n,onResizeStart:i,onAddToChat:o,tabs:u,activeTabId:d,onSelectTab:m,onCloseTab:f,onNewTab:y,fullscreen:k,onToggleFullscreen:j,onBrowserMeta:$}){const{t:v}=Xe(["deliverables","agent","common"]),[p,R]=s.useState({mode:"loading"}),[P,I]=s.useState(!1),[h,E]=s.useState(null),[M,V]=s.useState({}),ie=s.useRef(null),N=s.useRef(null),L=s.useRef(null);s.useEffect(()=>{let _=!1;T.browser.tabOwnership().then(ne=>{if(_)return;const ye={};for(const ze of ne.ownership??[])ye[ze.pageId]={agentId:ze.agentId,agentName:ze.agentName||ze.agentId};V(ye)}).catch(()=>{});const Q=We.on("ui:browser_ownership",ne=>{const ye=ne.payload;typeof ye.pageId=="number"&&V(ze=>{if(ye.action==="released"||!ye.agentId){if(!(ye.pageId in ze))return ze;const Je={...ze};return delete Je[ye.pageId],Je}return{...ze,[ye.pageId]:{agentId:ye.agentId,agentName:ye.agentName||ye.agentId}}})});return()=>{_=!0,Q()}},[]);const F=Zl(r),ke=Jl(r),Be=(u?.length??0)>=1,A=ec(r,d);s.useEffect(()=>{if(!d)return;const _=L.current,Q=N.current;if(!_||!Q)return;const ne=requestAnimationFrame(()=>{_.scrollIntoView({behavior:"smooth",inline:"nearest",block:"nearest"})});return()=>cancelAnimationFrame(ne)},[d,u?.length]),s.useEffect(()=>{const _=Q=>{Q.key==="Escape"&&(k&&j?j():a())};return window.addEventListener("keydown",_),()=>window.removeEventListener("keydown",_)},[a,k,j]),s.useEffect(()=>{let _=!1;return E(null),r.kind==="url"?(R({mode:"url",url:r.url,browserId:r.browserId}),()=>{_=!0}):bi(F)?(R({mode:"url",url:F}),()=>{_=!0}):(R({mode:"loading"}),r.kind==="deliverable"&&r.deliverable.artifactType&&r.deliverable.artifactData?(R({mode:"artifact",summary:r.deliverable.summary||r.deliverable.title||""}),()=>{_=!0}):F?r.kind==="deliverable"&&r.deliverable.type==="directory"?(R({mode:"unpreviewable",reference:F,isDirectory:!0}),()=>{_=!0}):(T.files.preview(F).then(ne=>{if(_)return;if(ne.type==="image"){const ze=ne.content?`data:${ne.mimeType||"image/png"};base64,${ne.content}`:ne.streamUrl||(ne.path?T.files.streamUrl(ne.path):T.files.streamUrl(F));R({mode:"image",src:ze,name:ne.name||ke});return}if(ne.type==="audio"){const ze=ne.streamUrl||(ne.path?T.files.streamUrl(ne.path):T.files.streamUrl(F));R({mode:"audio",src:ze,name:ne.name||ke,mimeType:ne.mimeType||"audio/mpeg",size:ne.size});return}if(ne.type==="video"){const ze=ne.streamUrl||(ne.path?T.files.streamUrl(ne.path):T.files.streamUrl(F));R({mode:"video",src:ze,name:ne.name||ke,mimeType:ne.mimeType||"video/mp4",size:ne.size});return}if(ne.type==="binary"){R({mode:"binary",name:ne.name||ke,reference:ne.path||F,size:ne.size,extension:ne.extension});return}if(typeof ne.content!="string"){R({mode:"unpreviewable",reference:F,isDirectory:!1});return}const ye=Ml({format:r.kind==="deliverable"?r.deliverable.format:void 0,reference:F,content:ne.content});R({mode:"content",content:ne.content,format:ye})}).catch(()=>{_||R({mode:"unpreviewable",reference:F,isDirectory:!1})}),()=>{_=!0}):(R({mode:"unpreviewable",reference:"",isDirectory:!1}),()=>{_=!0}))},[A,r,F,ke]);const ce=ke||F,te=s.useCallback((_,Q)=>{const ne=_.length>40?`${_.slice(0,24)}…${_.slice(-12)}`:_;return Q?{label:`🌐 ${ne}`,content:["[html-selection]",`Text: "${_}"`,`CSS Selector: ${Q.cssSelector}`,`XPath: ${Q.xpath}`,F?`File: ${F}`:""].filter(Boolean).join(`
|
|
11
|
+
`)}:{label:`“${ne}”`,content:`${v("deliverables:chat.selectedFrom",{defaultValue:"Selected from"})} ${ce}:
|
|
12
|
+
|
|
13
|
+
"""
|
|
14
|
+
${_}
|
|
15
|
+
"""`}},[F,ce,v]),S=s.useCallback((_,Q)=>{!_.trim()||!o||(o(te(_.trim(),Q)),E(null),window.getSelection()?.removeAllRanges())},[o,te]),J=s.useCallback(_=>{if(!_.text.trim()||!o)return;const Q=ie.current?.querySelector("iframe")?.getBoundingClientRect(),ne=(Q?.left??0)+_.rect.x+_.rect.width/2,ye=(Q?.top??0)+_.rect.y;E({x:ne,y:ye,text:_.text,htmlMeta:{xpath:_.xpath,cssSelector:_.cssSelector}})},[o]);s.useEffect(()=>{const _=ie.current;if(!_||!o)return;const Q=()=>{requestAnimationFrame(()=>{const ye=window.getSelection(),ze=ye?.toString().trim();if(!ze||!ye?.rangeCount){E(null);return}const Je=ye.getRangeAt(0);if(!_.contains(Je.commonAncestorContainer)){E(null);return}const kt=Je.getBoundingClientRect();E({x:kt.left+kt.width/2,y:kt.top,text:ze})})},ne=ye=>{const ze=document.getElementById("right-panel-selection-toolbar");ze&&ze.contains(ye.target)||E(null)};return _.addEventListener("mouseup",Q),document.addEventListener("mousedown",ne),()=>{_.removeEventListener("mouseup",Q),document.removeEventListener("mousedown",ne)}},[o,p.mode]);const Ee=()=>{T.files.reveal(F).catch(()=>{})},$e=()=>{navigator.clipboard?.writeText(F).then(()=>{I(!0),setTimeout(()=>I(!1),1500)}).catch(()=>{})},b=s.useCallback(async()=>{if(r.kind==="deliverable"){bs.navigate(gt.DELIVERABLES,{openDeliverable:r.deliverable.id});return}if(r.kind==="url"){let Q=r.url;if(r.browserId&&window.markusDesktop?.browser)try{const ne=await window.markusDesktop.browser.getState(r.browserId);if(ne.ok){if(ne.directoryPath){await T.system.openPath(ne.directoryPath).catch(()=>T.files.reveal(ne.directoryPath));return}ne.url&&ne.url!=="about:blank"&&(Q=ne.url)}}catch{}if(!Q||Q==="about:blank")return;if(/^https?:\/\//i.test(Q)||/^file:\/\//i.test(Q)){mr(Q);return}await T.system.openPath(Q).catch(()=>mr(pi(Q)));return}const _=r.path;if(_){if(/^https?:\/\//i.test(_)||/^file:\/\//i.test(_)){mr(_);return}await T.system.openPath(_).catch(()=>mr(pi(_)))}},[r]),U=r.kind==="deliverable"?!!r.deliverable.id:r.kind==="url"?!!(r.url&&r.url!=="about:blank")||!!r.browserId:!!r.path,fe=r.kind==="deliverable"?v("agent:deliverables.openInPage",{defaultValue:"Open in Output"}):v("common:openInSystemBrowser"),be=!!F&&!bi(F)&&(r.kind==="file"||r.kind==="deliverable");return e.jsxs(e.Fragment,{children:[!k&&e.jsx("div",{className:"w-1.5 cursor-col-resize shrink-0 group relative z-10 flex items-center justify-center",onMouseDown:i,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 ${k?"flex-1 min-w-0":"shrink-0"}`,style:k?void 0:{width:n},"data-right-panel":!0,children:[e.jsxs("header",{"data-electron-drag":!0,className:"relative z-20 h-10 shrink-0 flex items-center gap-1 pl-1.5 pr-1.5 border-b border-border-default bg-surface-primary",children:[Be||y?e.jsxs("div",{"data-no-drag":!0,ref:N,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:_=>{const Q=_.currentTarget;Q.scrollWidth<=Q.clientWidth||Math.abs(_.deltaY)<=Math.abs(_.deltaX)||(Q.scrollLeft+=_.deltaY,_.preventDefault())},children:[u?.map(_=>{const Q=_.id===d,ne=_.payload.kind==="url"?_.payload.pageId:void 0,ye=ne!=null?M[ne]:void 0,ze=ye?`${_.title} — ${v("common:browserTabControlledBy",{name:ye.agentName})}`:_.title;return e.jsxs("div",{className:`group shrink-0 flex items-center max-w-[200px] rounded-md text-[11px] border transition-colors ${Q?ye?"bg-brand-500/10 border-brand-500/35 text-fg-primary":"bg-surface-elevated border-border-default text-fg-primary":ye?"border-brand-500/25 text-fg-secondary hover:bg-brand-500/8":"border-transparent text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":Q,ref:Q?L:void 0,className:"min-w-0 flex-1 truncate pl-2.5 pr-1 py-1 text-left cursor-pointer flex items-center gap-1",title:ze,onPointerDown:Je=>{Je.button===0&&m?.(_.id)},onClick:()=>m?.(_.id),children:[ye&&e.jsxs("span",{className:"shrink-0 inline-flex items-center gap-0.5 max-w-[72px] px-1 py-px rounded text-[9px] font-semibold tracking-wide bg-brand-500/20 text-brand-500",title:v("common:browserTabControlledBy",{name:ye.agentName}),children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-brand-500 animate-pulse shrink-0","aria-hidden":!0}),e.jsx("span",{className:"truncate",children:ye.agentName})]}),e.jsx("span",{className:"truncate min-w-0",children:_.title})]}),f&&e.jsx("button",{type:"button",onPointerDown:Je=>{Je.button===0&&(Je.preventDefault(),Je.stopPropagation(),f(_.id))},onClick:Je=>{Je.preventDefault(),Je.stopPropagation(),f(_.id)},className:`shrink-0 mr-1 p-0.5 rounded hover:bg-surface-overlay transition-colors ${Q?"text-fg-tertiary hover:text-fg-secondary":"text-fg-muted hover:text-fg-secondary opacity-70 group-hover:opacity-100"}`,title:v("common:closeTab",{defaultValue:"Close tab"}),"aria-label":v("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"})]})})]},_.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:v("common:newTab",{defaultValue:"New Tab"}),"aria-label":v("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:F||ke,children:ke}),e.jsxs("div",{"data-no-drag":!0,className:"shrink-0 flex items-center gap-0.5 pl-1 border-l border-border-default/60",children:[U&&e.jsx("button",{type:"button",onClick:()=>{b()},title:fe,"aria-label":fe,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"})]})}),be&&e.jsx("button",{onClick:Ee,title:v("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),"aria-label":v("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:k?v("common:exitFullscreen",{defaultValue:"Exit fullscreen"}):v("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:k?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:v("common:collapsePanel",{defaultValue:"Hide panel"}),"aria-label":v("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 ${p.mode==="url"?"overflow-hidden p-2 flex flex-col":"overflow-auto p-4"}`,children:[p.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"})]}),p.mode==="image"&&e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("img",{src:p.src,alt:p.name,className:"max-w-full rounded-lg object-contain"}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:p.name})]}),p.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:p.name}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[p.mimeType,p.size!=null?` · ${ca(p.size)}`:""]})]})]}),e.jsx("audio",{controls:!0,preload:"metadata",src:p.src,className:"w-full"})]}),p.mode==="video"&&e.jsxs("div",{className:"flex flex-col items-stretch gap-3",children:[e.jsx("video",{controls:!0,preload:"metadata",src:p.src,className:"w-full max-h-[70vh] rounded-lg bg-black"}),e.jsxs("span",{className:"text-xs text-fg-tertiary",children:[p.name,p.size!=null?` · ${ca(p.size)}`:""]})]}),p.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:(p.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:p.name}),e.jsxs("div",{className:"text-[11px] text-fg-tertiary mt-0.5",children:[v("detail.cannotPreview",{type:"file",defaultValue:"This file type cannot be previewed."}),p.size!=null?` · ${ca(p.size)}`:""]})]})]}),p.reference&&e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("button",{onClick:()=>{T.files.reveal(p.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:v("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"})})})]}),p.mode==="content"&&e.jsx("div",{ref:ie,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(ci,{content:p.content,format:p.format,className:"text-fg-secondary text-sm",onHtmlSelection:J,basePath:F?F.replace(/[/\\][^/\\]+$/,""):void 0})}),p.mode==="artifact"&&e.jsx("div",{ref:ie,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(ci,{content:p.summary,format:"markdown",className:"text-fg-secondary text-sm"})}),p.mode==="url"&&e.jsx("div",{className:"flex-1 min-h-0 min-w-0 w-full flex flex-col",children:e.jsx(Ql,{url:p.url,browserId:p.browserId,className:"flex-1 min-h-0",onMeta:p.browserId&&$?_=>$(p.browserId,_):void 0},p.browserId||p.url)}),p.mode==="unpreviewable"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-fg-secondary",children:p.isDirectory?v("detail.cannotPreview",{type:"directory",defaultValue:"This item cannot be previewed here."}):v("detail.cannotPreview",{type:"file",defaultValue:"This file cannot be previewed here."})}),p.reference&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:Ee,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:v("detail.openInFileBrowser",{defaultValue:"Reveal in file browser"}),children:p.reference}),e.jsx("button",{onClick:Ee,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:v("common:open",{defaultValue:"Open"})}),e.jsx("button",{onClick:$e,className:`px-3 py-2 text-xs rounded-lg transition-colors shrink-0 ${P?"bg-green-500/20 text-green-600":"bg-surface-overlay/50 text-fg-secondary hover:bg-surface-overlay"}`,children:P?v("common:copied",{defaultValue:"Copied"}):v("common:copy",{defaultValue:"Copy"})})]})]})]},A)]}),h&&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:h.x,top:h.y-8},children:e.jsxs("button",{onMouseDown:_=>{_.preventDefault(),_.stopPropagation(),S(h.text,h.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"})}),v("deliverables:contextMenu.addToConversation",{defaultValue:"Add to conversation"})]})})]})}const sc=s.lazy(()=>Ki(()=>import("./index-CHkb08MZ.js").then(r=>r.aA),__vite__mapDeps([0,1])).then(r=>({default:r.MarkdownMessage}))),fa=[{key:"overview",icon:"▦"},{key:"files",icon:"📄"},{key:"tools",icon:"⚒"},{key:"memory",icon:"🧠"},{key:"deliverables",icon:"📦"}];function ua(r,a){return a(`agent:profilePage.taskStatus.${r}`,{defaultValue:r.replace(/_/g," ")})}function Qi(r,a){const i={idle:"common:status.idle",working:"common:status.working",offline:"common:status.offline",error:"common:status.error"}[r];return i?a(i):r}const Zi={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",paused:"bg-amber-400",offline:"bg-gray-500",error:"bg-red-400"};function dn(r){return r>=1e6?`${(r/1e6).toFixed(1)}M`:r>=1e3?`${(r/1e3).toFixed(1)}K`:r.toLocaleString()}function yi({agentId:r,onBack:a,inline:n,defaultTab:i,onSwipeBack:o,highlightMailboxId:u,authUser:d,headless:m,activeTab:f}){const{t:y}=Xe(["agent","common"]),k=xa(),[j,$]=s.useState(null),[v,p]=s.useState(null),[R,P]=s.useState(i??"overview"),I=m&&f?f:R,[h,E]=s.useState(null),M=s.useMemo(()=>fa.map(A=>({...A,label:y(`agent:tabs.${A.key}`)})),[y]),V=s.useMemo(()=>M.map(A=>({id:A.key})),[M]),ie=s.useMemo(()=>({onSwipeOutLeft:o}),[o]),N=Hi(V,R,P,ie),L=s.useRef(null);s.useEffect(()=>{const A=L.current;if(!A)return;A.querySelector('[data-active="true"]')?.scrollIntoView({behavior:"smooth",block:"nearest",inline:"center"})},[R]);const F=s.useCallback(()=>{T.agents.get(r).then($).catch(()=>{})},[r]);if(s.useEffect(()=>(P(i??"overview"),E(null),F(),T.externalAgents.list().then(ce=>{const te=ce.agents.find(S=>S.markusAgentId===r);E(te??null)}).catch(()=>{}),We.on("agent:update",ce=>{ce.payload.agentId===r&&F()})),[r,F]),!j)return e.jsx("div",{className:"flex-1 flex items-center justify-center text-fg-tertiary text-sm",children:y("agent:profilePage.loadingAgent")});const ke=Zi[j.state.status]??"bg-gray-500",Be=d?.role==="owner"||d?.role==="admin";return m?e.jsx("div",{className:"flex-1 overflow-y-auto bg-surface-primary",children:e.jsxs("div",{className:"p-5",children:[(I==="overview"||I==="mind")&&e.jsxs(e.Fragment,{children:[e.jsx(vi,{agent:j,onUpdate:F,externalInfo:h,t:y,canManageAgents:Be}),e.jsx("div",{className:"mt-6",children:e.jsx(Li,{agentId:r,highlightId:u,agentStatus:j.state.status,canManageAgents:Be,onAgentStateChange:F})})]}),I==="files"&&e.jsx(ki,{agentId:r}),I==="tools"&&e.jsx(Ni,{tools:j.tools??[],agent:j}),I==="memory"&&e.jsxs(e.Fragment,{children:[e.jsx(Ci,{agentId:r,initialData:j.heartbeat}),e.jsx("div",{className:"mt-6",children:e.jsx(Si,{agentId:r})})]}),I==="deliverables"&&e.jsx(Ri,{agentId:r})]})}):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(wt,{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 ${ke}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:Qi(j.state.status,y)}),h&&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:[!n&&e.jsxs("button",{onClick:()=>bs.navigate(gt.TEAM,{agentId:r}),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")]}),Be&&e.jsxs("button",{onClick:async()=>{if(j)try{const{filesMap:A}=await T.agents.getFilesMap(r),ce={type:"agent",name:Vi(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 qi.publishViaProxy({itemType:"agent",name:j.name,description:ce.description,category:"general",config:ce,files:A}),p({title:y("agent:profilePage.hub"),message:y("agent:profilePage.publishSuccess",{name:j.name}),variant:"primary"})}catch(A){p({title:y("agent:profilePage.hub"),message:y("agent:profilePage.publishFailed",{error:String(A)}),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")]}),n&&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:L,className:"flex gap-1 mt-3 -mb-[1px] overflow-x-auto scrollbar-hide",children:M.filter(A=>!h||["overview","mind"].includes(A.key)).map(A=>e.jsxs("button",{onClick:()=>P(A.key),"data-active":R===A.key,className:`px-3 py-1.5 text-xs rounded-t-lg border border-b-0 transition-colors whitespace-nowrap ${R===A.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:A.icon}),A.label]},A.key))})]}),e.jsxs("div",{className:"p-5",onTouchStart:k?N.onTouchStart:void 0,onTouchEnd:k?N.onTouchEnd:void 0,children:[(R==="overview"||R==="mind")&&e.jsxs(e.Fragment,{children:[e.jsx(vi,{agent:j,onUpdate:F,externalInfo:h,t:y,canManageAgents:Be}),e.jsx("div",{className:"mt-6",children:e.jsx(Li,{agentId:r,highlightId:u,agentStatus:j.state.status,canManageAgents:Be,onAgentStateChange:F})})]}),R==="files"&&e.jsx(ki,{agentId:r}),R==="tools"&&e.jsx(Ni,{tools:j.tools??[],agent:j}),R==="memory"&&e.jsxs(e.Fragment,{children:[e.jsx(Ci,{agentId:r,initialData:j.heartbeat}),e.jsx("div",{className:"mt-6",children:e.jsx(Si,{agentId:r})})]}),R==="deliverables"&&e.jsx(Ri,{agentId:r})]}),v&&e.jsx(Bn,{alertOnly:!0,variant:v.variant??"primary",title:v.title,message:v.message,onConfirm:()=>p(null),onCancel:()=>p(null)})]})}function vi({agent:r,onUpdate:a,externalInfo:n,t:i,canManageAgents:o}){const[u,d]=s.useState(null),[m,f]=s.useState([]),[y,k]=s.useState(null),[j,$]=s.useState(null),[v,p]=s.useState(""),[R,P]=s.useState([]);s.useEffect(()=>{T.usage.agents().then(N=>{const L=N.agents.find(F=>F.agentId===r.id);L&&d(L)}).catch(()=>{}),T.agents.getRecentActivities(r.id).then(N=>f(N.activities)).catch(()=>{}),T.system.storage().then(N=>{p(N.dataDir+"/agents/"+r.id);const L=N.agents.find(F=>F.id===r.id);L&&$(L)}).catch(()=>{}),r.state.activeTaskIds?.length&&T.tasks.list({assignedAgentId:r.id}).then(N=>{P(N.tasks.filter(L=>r.state.activeTaskIds?.includes(L.id)))}).catch(()=>{})},[r.id,r.state.activeTaskIds]);const I=()=>{r.state.status==="offline"?T.agents.start(r.id).then(a):T.agents.stop(r.id).then(a)},h=s.useMemo(()=>[{method:"POST",path:"/api/gateway/sync",desc:i("agent:profilePage.gateway.sync")},{method:"GET",path:"/api/gateway/manual",desc:i("agent:profilePage.gateway.manual")},{method:"GET",path:"/api/gateway/team",desc:i("agent:profilePage.gateway.team")},{method:"GET",path:"/api/gateway/projects",desc:i("agent:profilePage.gateway.projects")},{method:"GET",path:"/api/gateway/requirements",desc:i("agent:profilePage.gateway.requirements")}],[i]),E=s.useMemo(()=>[{field:"assignedTasks",desc:i("agent:profilePage.syncContext.assignedTasks")},{field:"inboxMessages",desc:i("agent:profilePage.syncContext.inboxMessages")},{field:"teamContext",desc:i("agent:profilePage.syncContext.teamContext")},{field:"projectContext",desc:i("agent:profilePage.syncContext.projectContext")}],[i]);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(lt,{title:i("agent:profilePage.overview.identity"),children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[e.jsx(_t,{label:i("agent:profilePage.overview.labels.name"),children:r.name}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.agentRole"),children:e.jsx("span",{className:r.agentRole==="manager"?"text-amber-600":"text-blue-600",children:r.agentRole==="manager"?i("agent:profilePage.roles.managerDisplay"):i("agent:profilePage.roles.workerDisplay")})}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.roleTemplate"),children:r.role}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.markusAgentId"),mono:!0,children:r.id}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.organization"),children:r.config?.orgId??"default"}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.created"),children:r.config?.createdAt?new Date(r.config.createdAt).toLocaleDateString():i("agent:profilePage.emDash")})]})}),e.jsx(lt,{title:i("agent:profilePage.overview.connectionStatus"),children:e.jsxs("div",{className:"flex flex-wrap items-center gap-x-5 gap-y-1.5",children:[e.jsx(ft,{label:i("agent:profilePage.overview.labels.connection"),value:n.connected?i("common:status.online"):i("common:status.offline"),color:n.connected?"green":"gray"}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.platform"),value:i("agent:profilePage.overview.openClaw")}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.activeTasks"),value:String(r.state.activeTaskIds?.length??0)}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.lastSync"),value:n.lastHeartbeat?new Date(n.lastHeartbeat).toLocaleTimeString():i("agent:profilePage.never")})]})}),e.jsx(lt,{title:i("agent:profilePage.overview.externalAgentDetails"),children:e.jsxs("div",{className:"grid grid-cols-2 gap-x-6 gap-y-3",children:[e.jsx(_t,{label:i("agent:profilePage.overview.labels.externalAgentId"),mono:!0,children:n.externalAgentId}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.registered"),children:new Date(n.registeredAt).toLocaleString()}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.capabilities"),children:n.capabilities.length>0?n.capabilities.join(", "):i("agent:profilePage.overview.noneDeclared")}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.lastHeartbeat"),children:n.lastHeartbeat?new Date(n.lastHeartbeat).toLocaleString():i("agent:profilePage.never")})]})}),e.jsx(lt,{title:i("agent:profilePage.overview.syncContextTitle"),children:e.jsx("div",{className:"space-y-1.5",children:E.map(N=>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:N.field}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:N.desc})]},N.field))})}),e.jsx(lt,{title:i("agent:profilePage.overview.gatewayEndpoints"),children:e.jsx("div",{className:"space-y-1.5",children:h.map(N=>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 ${N.method==="POST"?"text-amber-600":"text-green-600"}`,children:N.method}),e.jsx("span",{className:"font-mono text-[10px] text-fg-secondary shrink-0 pt-0.5",children:N.path}),e.jsx("span",{className:"text-[10px] text-fg-tertiary ml-auto",children:N.desc})]},N.path))})})]});const M=m.filter(N=>N.type==="heartbeat").length,V=m.filter(N=>N.type==="chat").length,ie=r.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(_t,{label:i("agent:profilePage.overview.labels.roleTemplate"),children:r.role}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.agentRole"),children:e.jsx("span",{className:r.agentRole==="manager"?"text-amber-600":"text-blue-600",children:r.agentRole==="manager"?i("agent:profilePage.roles.managerDisplay"):i("agent:profilePage.roles.workerDisplay")})}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.agentId"),mono:!0,children:r.id}),e.jsx(_t,{label:i("agent:profilePage.overview.labels.created"),children:r.config?.createdAt?new Date(r.config.createdAt).toLocaleDateString():i("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 ${Zi[r.state.status]||"bg-gray-500"}`}),e.jsx("span",{className:`text-sm font-semibold ${r.state.status==="idle"?"text-green-500":r.state.status==="working"?"text-blue-400":r.state.status==="error"?"text-red-400":"text-fg-secondary"}`,children:Qi(r.state.status,i)})]}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.tokensToday"),value:dn(r.state.tokensUsedToday)}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.activeTasks"),value:String(ie),color:ie>0?"blue":void 0}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.lastHeartbeat"),value:r.state.lastHeartbeat?new Date(r.state.lastHeartbeat).toLocaleTimeString():i("agent:profilePage.never")}),o&&e.jsx("button",{onClick:I,className:"ml-auto px-3 py-1 text-xs border border-border-default rounded-lg hover:border-brand-500 transition-colors shrink-0",children:r.state.status==="offline"?i("agent:profilePage.overview.startAgent"):i("agent:profilePage.overview.stopAgent")})]}),r.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:i("agent:profilePage.overview.errorDetails")}),r.state.lastErrorAt&&e.jsx("span",{className:"text-[10px] text-red-500/50 ml-auto",children:new Date(r.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:yr(r.state.lastError,i)||r.state.lastError||i("agent:profilePage.overview.errorFallback")})]}),r.state.status==="working"&&ie>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:R.map(N=>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:N.title}),e.jsx("span",{className:"text-fg-tertiary capitalize shrink-0",children:ua(N.status,i)})]},N.id))})}),u&&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(ft,{label:i("agent:profilePage.overview.labels.totalTokens"),value:dn(u.totalTokens)}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.requests"),value:String(u.requestCount)}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.toolCalls"),value:String(u.toolCalls)}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.promptTokens"),value:dn(u.promptTokens)}),e.jsx(ft,{label:i("agent:profilePage.overview.labels.completionTokens"),value:dn(u.completionTokens)}),e.jsx(ft,{label:"CU Used",value:dn(u.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(ft,{label:i("agent:profilePage.overview.storage"),value:Ei(j.size)}),j.subItems.filter(N=>N.size>0).map(N=>e.jsx(ft,{label:N.name,value:Ei(N.size)},N.name)),e.jsxs("button",{onClick:()=>{T.system.openPath(v)},className:"text-[10px] text-fg-tertiary hover:text-fg-secondary ml-auto",children:[i("agent:profilePage.overview.openFolder")," →"]})]})]})]}),M>0&&e.jsx(lt,{title:i("agent:profilePage.overview.recentHeartbeats"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.overview.heartbeatRuns",{count:M})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:m.filter(N=>N.type==="heartbeat").map(N=>{const L=y===N.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>k(L?null:N.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:N.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(N.startedAt).toLocaleString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:L?"▲":"▼"})]}),L&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(Fn,{agentId:r.id,activityId:N.id})})]},N.id)})})}),V>0&&e.jsx(lt,{title:i("agent:profilePage.overview.recentA2A"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.overview.conversations",{count:V})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:m.filter(N=>N.type==="chat").map(N=>{const L=y===N.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>k(L?null:N.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:N.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(N.startedAt).toLocaleString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:L?"▲":"▼"})]}),L&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(Fn,{agentId:r.id,activityId:N.id})})]},N.id)})})})]})}function nc(r,a){const n=r.split(`
|
|
16
|
+
`),i=a.split(`
|
|
17
|
+
`),o=n.length,u=i.length,d=Array.from({length:o+1},()=>new Array(u+1).fill(0));for(let $=o-1;$>=0;$--)for(let v=u-1;v>=0;v--)d[$][v]=n[$]===i[v]?d[$+1][v+1]+1:Math.max(d[$+1][v],d[$][v+1]);const m=[];let f=0,y=0,k=1,j=1;for(;f<o||y<u;)f<o&&y<u&&n[f]===i[y]?(m.push({type:"equal",content:n[f],oldLineNum:k++,lineNum:j++}),f++,y++):y<u&&(f>=o||d[f][y+1]>=d[f+1][y])?(m.push({type:"add",content:i[y],lineNum:j++}),y++):(m.push({type:"remove",content:n[f],oldLineNum:k++}),f++);return m}function ji(r){return r.match(/\S+|\s+/g)??[""]}function wi({oldText:r,newText:a,mode:n}){const i=ji(r),o=ji(a),u=i.length,d=o.length,m=Array.from({length:u+1},()=>new Array(d+1).fill(0));for(let j=u-1;j>=0;j--)for(let $=d-1;$>=0;$--)m[j][$]=i[j]===o[$]?m[j+1][$+1]+1:Math.max(m[j+1][$],m[j][$+1]);const f=[];let y=0,k=0;for(;y<u||k<d;)y<u&&k<d&&i[y]===o[k]?(f.push({text:n==="remove"?i[y]:o[k],changed:!1}),y++,k++):k<d&&(y>=u||m[y][k+1]>=m[y+1][k])?(n==="add"&&f.push({text:o[k],changed:!0}),k++):(n==="remove"&&f.push({text:i[y],changed:!0}),y++);return e.jsx("span",{children:f.map((j,$)=>j.changed?e.jsx("span",{className:n==="add"?"bg-green-500/30 rounded-sm":"bg-red-500/30 rounded-sm",children:j.text},$):e.jsx("span",{children:j.text},$))})}function rc({agent:r,template:a,templateId:n}){const{t:i}=Xe(["agent","common"]),o=s.useMemo(()=>nc(r,a),[r,a]),[u,d]=s.useState(!0),m=3,f=s.useMemo(()=>{const v=o.map((I,h)=>I.type!=="equal"?h:-1).filter(I=>I>=0);if(v.length===0)return[];const p=[];let R=Math.max(0,v[0]-m),P=Math.min(o.length-1,v[0]+m);for(let I=1;I<v.length;I++){const h=Math.max(0,v[I]-m),E=Math.min(o.length-1,v[I]+m);h<=P+1||(p.push({start:R,end:P}),R=h),P=E}return p.push({start:R,end:P}),p},[o]),y=(v,p,R)=>{const P=v.type==="add"?"+":v.type==="remove"?"-":" ",I=v.type==="add"?"bg-green-500/8":v.type==="remove"?"bg-red-500/8":"",h=v.type==="add"?"text-green-600/90":v.type==="remove"?"text-red-500/80":"text-fg-tertiary",E=v.type==="add"?"text-green-500":v.type==="remove"?"text-red-500":"text-fg-muted",M=v.type==="remove"?v.oldLineNum:v.lineNum;let V=null;return v.type==="remove"&&p+1<R.length&&R[p+1].type==="add"?V=e.jsx(wi,{oldText:v.content,newText:R[p+1].content,mode:"remove"}):v.type==="add"&&p>0&&R[p-1].type==="remove"&&(V=e.jsx(wi,{oldText:R[p-1].content,newText:v.content,mode:"add"})),e.jsxs("div",{className:`flex ${I} 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:M??""}),e.jsx("span",{className:`w-4 shrink-0 text-center text-[11px] font-mono ${E} select-none leading-[20px]`,children:P}),e.jsxs("span",{className:`flex-1 text-[11px] font-mono ${h} whitespace-pre-wrap break-words leading-[20px]`,children:[V??v.content,v.content===""&&" "]})]},p)},k=o.filter(v=>v.type==="add").length,j=o.filter(v=>v.type==="remove").length,$=u?f.flatMap(v=>{const p=[];for(let R=v.start;R<=v.end;R++)p.push({...o[R],_idx:R});return p}):o.map((v,p)=>({...v,_idx:p}));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:i("agent:profilePage.diff.title",{templateId:n})}),e.jsxs("span",{className:"text-[10px] text-green-500 font-mono",children:["+",k]}),e.jsxs("span",{className:"text-[10px] text-red-500 font-mono",children:["-",j]})]}),e.jsx("button",{onClick:()=>d(v=>!v),className:"text-[10px] text-brand-500 hover:text-brand-400 transition-colors",children:i(u?"agent:profilePage.diff.showFullFile":"agent:profilePage.diff.showChangesOnly")})]}),e.jsxs("div",{className:"max-h-72 overflow-y-auto bg-surface-primary/50",children:[u&&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:i("agent:profilePage.diff.linesHidden",{count:f[0].start})}),$.map((v,p)=>{const R=p>0?$[p-1]:null,P=u&&R&&v._idx-R._idx>1;return e.jsxs("div",{children:[P&&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(v,v._idx,o)]},p)}),u&&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:i("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:i("agent:profilePage.diff.identical")})]})]})}function ac(r,a){const n=r.split(`
|
|
18
|
+
`),i=a.split(`
|
|
19
|
+
`),o=[],u=Math.max(n.length,i.length);for(let d=0;d<u;d++){const m=n[d],f=i[d];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 d=o.filter(m=>m.startsWith("+ ")||m.startsWith("- "));if(d.length>0)return d.join(`
|
|
20
|
+
`)}return o.join(`
|
|
21
|
+
`)}function ki({agentId:r}){const{t:a}=Xe(["agent","common"]),[n,i]=s.useState([]),[o,u]=s.useState(!0),[d,m]=s.useState(null),[f,y]=s.useState(""),[k,j]=s.useState(""),[$,v]=s.useState(!1);s.useEffect(()=>{T.system.storage().then(J=>{j(J.dataDir+"/agents/"+r+"/role")}).catch(()=>{})},[r]);const[p,R]=s.useState(!1),[P,I]=s.useState(!1),[h,E]=s.useState(null),[M,V]=s.useState(null),ie=s.useCallback(()=>{u(!0),Promise.all([T.agents.getFiles(r),T.agents.roleStatus(r).catch(()=>null)]).then(([J,Ee])=>{i(J.files),E(Ee),J.files.length>0&&!d&&(m(J.files[0].name),y(J.files[0].content))}).catch(()=>{}).finally(()=>u(!1))},[r]);s.useEffect(()=>{ie()},[ie]);const N=J=>{const Ee=n.find($e=>$e.name===J);Ee&&(m(J),y(Ee.content),I(!1),V(null))},L=async()=>{if(d){R(!0);try{await T.agents.updateFile(r,d,f),i(J=>J.map(Ee=>Ee.name===d?{...Ee,content:f}:Ee)),I(!1),d==="ROLE.md"&&await T.agents.updateSystemPrompt(r,f)}catch{}R(!1)}},F=h?.files.filter(J=>J.status==="modified"||J.status==="added_in_template")??[],ke=async J=>{const Ee=J?F.filter(U=>U.file===J):F;if(Ee.length===0)return;const $e=[];for(const U of Ee)try{const fe=await T.agents.roleDiff(r,U.file);fe.agentContent!=null&&fe.templateContent!=null&&$e.push(`## ${U.file}
|
|
22
|
+
|
|
23
|
+
**Template file path:** built-in template \`${h?.templateId??"unknown"}\`
|
|
24
|
+
|
|
25
|
+
**Key changes in the new template version:**
|
|
26
|
+
\`\`\`diff
|
|
27
|
+
`+ac(fe.agentContent,fe.templateContent)+"\n```\n")}catch{}if($e.length===0)return;const b=`Your role configuration files have been updated in the latest template (\`${h?.templateId??""}\`). Please review the following changes and decide whether to update your files accordingly.
|
|
28
|
+
|
|
29
|
+
`+$e.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.";bs.navigate(gt.TEAM,{agentId:r,prefillMessage:b})},Be=async J=>{if(M?.file===J){V(null);return}try{const Ee=await T.agents.roleDiff(r,J);Ee.agentContent!=null&&Ee.templateContent!=null&&V({file:J,agent:Ee.agentContent,template:Ee.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 A={"ROLE.md":"roleMd","HEARTBEAT.md":"heartbeatMd","POLICIES.md":"policiesMd","CONTEXT.md":"contextMd"},ce=J=>{const Ee=A[J];return Ee?a(`agent:profilePage.filesTab.fileLabels.${Ee}`):J},te=h?.hasTemplate&&!h.isUpToDate,S=d?F.some(J=>J.file===d):!1;return e.jsxs("div",{className:"space-y-4",children:[te&&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:F.length,templateId:h.templateId})," ",F.map(J=>J.file).join(", ")]})]}),e.jsx("button",{onClick:()=>ke(),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(lt,{title:a("agent:profilePage.filesTab.agentConfigFiles"),action:h?.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 ${h.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:h.templateId}),h.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:n.map(J=>{const Ee=F.some($e=>$e.file===J.name);return e.jsxs("button",{onClick:()=>N(J.name),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors relative ${d===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,Ee&&e.jsx("span",{className:"absolute -top-1 -right-1 w-2 h-2 bg-amber-400 rounded-full"})]},J.name)})}),d&&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:ce(d)}),e.jsxs("div",{className:"flex gap-2 items-center",children:[S&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>Be(d),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:M?.file===d?a("agent:profilePage.filesTab.hideDiff"):a("agent:profilePage.filesTab.viewDiff")}),e.jsx("button",{onClick:()=>ke(d),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")})]}),p&&e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a("common:saving")})]})]}),k&&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:`${k}/${d}`,children:[k,"/",d]}),e.jsx("button",{onClick:()=>{navigator.clipboard.writeText(`${k}/${d}`),v(!0),setTimeout(()=>v(!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($?"agent:profilePage.filesTab.pathCopied":"agent:profilePage.filesTab.copyPath")}),e.jsx("button",{onClick:()=>{T.system.openPath(k)},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")})]}),M?.file===d&&e.jsx(rc,{agent:M.agent,template:M.template,templateId:h?.templateId??""}),e.jsx(ic,{content:n.find(J=>J.name===d)?.content??"",editContent:f,setEditContent:J=>{y(J),I(!0)},dirty:P,onSave:L}),d==="ROLE.md"&&e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-2",children:a("agent:profilePage.filesTab.roleMdHint")})]}),n.length===0&&e.jsx(vr,{text:a("agent:profilePage.filesTab.noConfigFiles")})]})]})}function ic({content:r,editContent:a,setEditContent:n,dirty:i,onSave:o}){const[u,d]=s.useState(!1),m=s.useRef(null);return s.useEffect(()=>{u&&m.current?.focus()},[u]),s.useEffect(()=>{d(!1)},[r]),u||i?e.jsx("textarea",{ref:m,value:a,onChange:f=>n(f.target.value),onBlur:()=>{a!==r&&o(),d(!1)},onKeyDown:f=>{f.key==="Escape"&&(f.preventDefault(),n(r),d(!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:()=>d(!0),role:"button",tabIndex:0,onKeyDown:f=>{f.key==="Enter"&&d(!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(s.Suspense,{fallback:e.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:e.jsx(sc,{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 oc=[{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 lc(r,a){const n=new Map,i=new Set;for(const{id:d,prefixes:m}of oc){const f=a(`agent:toolCategories.${d}`),y=r.filter(k=>!i.has(k.name)&&m.some(j=>k.name.startsWith(j)));y.length>0&&(n.set(f,y),y.forEach(k=>i.add(k.name)))}const o=r.filter(d=>!i.has(d.name));for(const d of o){const m=d.name.indexOf("__");if(m>0){const f=d.name.slice(0,m),y=a("agent:toolCategories.mcp",{server:f});n.has(y)||n.set(y,[]),n.get(y).push(d),i.add(d.name)}}const u=r.filter(d=>!i.has(d.name));return u.length>0&&n.set(a("agent:toolCategories.other"),u),[...n.entries()].map(([d,m])=>({category:d,tools:m}))}function cc(r){return r.replace(/^\[MCP:[^\]]*\]\s*/i,"")}function dc({tools:r}){const{t:a}=Xe(["agent","common"]),n=lc(r,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:r.length})}),n.map(i=>e.jsx(lt,{title:`${i.category} (${i.tools.length})`,children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:i.tools.map(o=>{const u=ll(o.name),d=a(`common:execution.tools.${u.key}`,{defaultValue:u.label}),m=o.name.includes("__"),f=m?o.name.split("__").pop():o.name,y=cc(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(cl,{name:u.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:d}),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!==d&&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)})})},i.category)),r.length===0&&e.jsx("div",{className:"text-center py-12 text-fg-tertiary text-sm",children:a("agent:profilePage.toolsTab.noToolsRegistered")})]})}function uc({agent:r}){const{t:a}=Xe(["agent","common"]),n=r.proficiency??{},[i,o]=s.useState(null),[u,d]=s.useState(null),[m,f]=s.useState(!1),y=r.availableSkills??[],k=new Map;for(const P of y){const I=P.category||"custom";k.has(I)||k.set(I,[]),k.get(I).push(P)}const j=async P=>{if(i===P){o(null),d(null);return}o(P),f(!0);try{const I=await fetch(`/api/skills/${encodeURIComponent(P)}`);if(I.ok){const h=await I.json();d(h.skill)}else d(null)}catch{d(null)}f(!1)},$={development:"bg-blue-500/15 text-blue-600",devops:"bg-amber-500/15 text-amber-600",communication:"bg-green-500/15 text-green-600",data:"bg-brand-500/15 text-brand-500",productivity:"bg-amber-500/15 text-amber-600",browser:"bg-blue-500/15 text-blue-600",custom:"bg-gray-500/15 text-fg-secondary",platform:"bg-purple-500/15 text-purple-500"},v=P=>{const I=n[P.name],h=I&&I.uses>0?Math.round(I.successes/I.uses*100):null,E=I&&e.jsxs("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:[a("agent:profilePage.skillsTab.usesStats",{uses:I.uses,successes:I.successes}),I.lastUsed&&a("agent:profilePage.skillsTab.lastUsed",{date:new Date(I.lastUsed).toLocaleDateString()})]}),M=i===P.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 ${M?"bg-brand-500/10 border-brand-500/40":"bg-surface-elevated/30 border-border-default/30 hover:border-gray-600/50"}`,onClick:()=>j(P.name),children:[e.jsx("span",{className:`text-sm transition-transform ${M?"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:P.name}),P.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")}),P.builtIn&&!P.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")}),!P.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:P.description}),E]}),h!==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 ${h>=80?"bg-green-400":h>=50?"bg-amber-400":"bg-red-400"}`,style:{width:`${h}%`}})}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary w-8 text-right",children:[h,"%"]})]})]}),M&&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")}):u?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 ${$[u.category]??$.custom}`,children:u.category}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:["v",u.version]}),u.author&&e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:a("agent:profilePage.skillsTab.byAuthor",{author:u.author})}),u.requiredPermissions?.map(V=>e.jsx("span",{className:"px-1.5 py-0.5 bg-amber-500/10 text-amber-600 text-[10px] rounded",children:V},V))]}),u.description&&e.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed",children:u.description}),u.tags&&u.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap",children:u.tags.map(V=>e.jsxs("span",{className:"px-1.5 py-0.5 bg-surface-overlay/40 text-fg-tertiary text-[10px] rounded",children:["#",V]},V))}),(u.toolDetails??u.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:(u.toolDetails??u.tools??[]).length})}),e.jsx("div",{className:"space-y-1.5",children:(u.toolDetails??u.tools??[]).map(V=>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:V.name}),V.description&&e.jsx("div",{className:"text-[10px] text-fg-tertiary mt-0.5",children:V.description})]},V.name))})]})]}):e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.skillsTab.detailsUnavailable")})})]},P.name)},p=["development","productivity","browser","communication","devops","data","platform","custom"],R=[...k.entries()].sort((P,I)=>{const h=p.indexOf(P[0]),E=p.indexOf(I[0]);return(h===-1?999:h)-(E===-1?999:E)});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})})}),R.map(([P,I])=>e.jsx(lt,{title:e.jsxs("span",{className:"capitalize",children:[P," ",e.jsxs("span",{className:"text-fg-tertiary font-normal",children:["(",I.length,")"]})]}),children:e.jsx("div",{className:"space-y-2",children:I.map(h=>v(h))})},P)),y.length===0&&e.jsx(vr,{text:a("agent:profilePage.skillsTab.noSkills")})]})}function Ni({tools:r,agent:a}){const{t:n}=Xe(["agent","common"]),[i,o]=s.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(u=>e.jsx("button",{onClick:()=>o(u),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${i===u?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:u==="tools"?`${n("agent:profilePage.toolsTab.title",{defaultValue:"Tools"})} (${r.length})`:`${n("agent:tabs.skills")} (${a.availableSkills?.length??0})`},u))}),i==="tools"?e.jsx(dc,{tools:r}):e.jsx(uc,{agent:a})]})}function Si({agentId:r}){const{t:a}=Xe(["agent","common"]),[n,i]=s.useState(null),[o,u]=s.useState(!0),[d,m]=s.useState("longterm"),[f,y]=s.useState(""),[k,j]=s.useState(""),[$,v]=s.useState(!1),[p,R]=s.useState(null),[P,I]=s.useState(null),[h,E]=s.useState([]),[M,V]=s.useState(!1),ie=s.useCallback(()=>{u(!0),T.agents.getMemory(r).then(A=>{i(A),y(A.recentDailyLogs??""),j(A.longTermMemory??"")}).catch(()=>{}).finally(()=>u(!1))},[r]);s.useEffect(()=>{ie()},[ie]);const N=async()=>{v(!0),await T.agents.updateDailyMemory(r,f).catch(()=>{}),v(!1),ie()},L=async()=>{v(!0),await T.agents.updateLongTermMemory(r,a("agent:profilePage.memoryTab.userEditedSource"),k).catch(()=>{}),v(!1),ie()},F=f!==(n?.recentDailyLogs??""),ke=k!==(n?.longTermMemory??"");if(o)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:a("agent:profilePage.memoryTab.loading")});if(!n)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:a("agent:profilePage.memoryTab.loadFailed")});const Be=[{key:"longterm",label:"MEMORY.md"},{key:"entries",label:`Observations (${n.entries.length})`},{key:"sessions",label:a("agent:profilePage.memoryTab.sessions",{count:n.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:Be.map(A=>e.jsx("button",{onClick:()=>m(A.key),className:`px-3 py-1.5 text-xs rounded-lg border transition-colors ${d===A.key?"bg-brand-600/15 border-brand-500/40 text-brand-500":"border-border-default text-fg-tertiary hover:text-fg-secondary"}`,children:A.label},A.key))}),d==="entries"&&e.jsx(lt,{title:a("agent:profilePage.memoryTab.recentEntries"),children:n.entries.length===0?e.jsx(vr,{text:a("agent:profilePage.memoryTab.noEntries")}):e.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:n.entries.map((A,ce)=>{const te=p===ce;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>R(te?null:ce),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 ${A.type==="fact"?"bg-blue-500/15 text-blue-600":A.type==="task"?"bg-green-500/15 text-green-600":A.type==="note"?"bg-brand-500/15 text-brand-500":"bg-surface-overlay text-fg-secondary"}`,children:A.type}),e.jsx("span",{className:`text-fg-secondary flex-1 min-w-0 ${te?"":"line-clamp-2"}`,children:A.content}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[A.importance!=null&&e.jsxs("span",{className:`px-1 py-0.5 rounded text-[9px] font-medium ${A.importance>=7?"bg-red-500/15 text-red-500":A.importance>=4?"bg-amber-500/15 text-amber-600":"bg-surface-overlay text-fg-tertiary"}`,children:["P",A.importance]}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:new Date(A.timestamp).toLocaleTimeString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:te?"▲":"▼"})]})]}),te&&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:A.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"),": ",A.type]}),A.importance!=null&&e.jsxs("span",{children:[a("agent:profilePage.overview.labels.importance"),": ",A.importance]}),e.jsx("span",{children:new Date(A.timestamp).toLocaleString()})]})]})]},ce)})})}),d==="sessions"&&e.jsx(lt,{title:a("agent:profilePage.memoryTab.chatSessions"),children:n.sessions.length===0?e.jsx(vr,{text:a("agent:profilePage.memoryTab.noSessions")}):e.jsx("div",{className:"space-y-1.5 max-h-[600px] overflow-y-auto",children:n.sessions.map(A=>{const ce=P===A.id,te=async()=>{if(ce){I(null),E([]);return}I(A.id),V(!0);try{const S=await T.agents.getMemorySession(r,A.id);E(S.messages)}catch{E([])}V(!1)};return e.jsxs("div",{children:[e.jsxs("button",{onClick:te,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:A.id}),e.jsxs("span",{className:"text-[10px] text-fg-tertiary",children:[A.messageCount," ",a("agent:profilePage.memoryTab.msgs")]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(A.updatedAt).toLocaleDateString()}),e.jsx("span",{className:"text-fg-tertiary text-[10px]",children:ce?"▲":"▼"})]}),ce&&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:M?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.memoryTab.loadingMessages")}):h.length===0?e.jsx("div",{className:"text-[10px] text-fg-tertiary py-3 text-center",children:a("agent:profilePage.memoryTab.noMessagesInSession")}):(()=>{const S=new Map;for(const J of h)J.role==="tool"&&J.toolCallId&&S.set(J.toolCallId,J.content);return e.jsx("div",{className:"divide-y divide-gray-700/30",children:h.filter(J=>J.role!=="tool").map((J,Ee)=>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($e=>{let b;try{b=JSON.parse($e.arguments)}catch{}const U={tool:$e.name,status:"done",args:b,result:S.get($e.id)};return e.jsx(nl,{entry:{type:"tool",info:U}},$e.id)})})]})]},Ee))})})()})]},A.id)})})}),d==="daily"&&e.jsx(lt,{title:a("agent:profilePage.memoryTab.dailyLogs"),action:F?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>y(n?.recentDailyLogs??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:cancel")}),e.jsx("button",{onClick:N,disabled:$,className:"text-xs text-brand-500",children:a($?"common:saving":"common:save")})]}):null,children:e.jsx("textarea",{value:f,onChange:A=>y(A.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"})}),d==="longterm"&&e.jsx(lt,{title:a("agent:profilePage.memoryTab.longTermTitle"),action:ke?e.jsxs("div",{className:"flex gap-2",children:[e.jsx("button",{onClick:()=>j(n?.longTermMemory??""),className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:a("common:cancel")}),e.jsx("button",{onClick:L,disabled:$,className:"text-xs text-brand-500",children:a($?"common:saving":"common:save")})]}):null,children:e.jsx("textarea",{value:k,onChange:A=>j(A.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 Ci({agentId:r,initialData:a}){const{t:n}=Xe(["agent","common"]),[i,o]=s.useState(a??null),[u,d]=s.useState(!a),[m,f]=s.useState([]),[y,k]=s.useState(null),[j,$]=s.useState(!1),[v,p]=s.useState(null),R=s.useCallback(()=>Promise.all([T.agents.getHeartbeat(r).then(o).catch(()=>{}),T.agents.getRecentActivities(r).then(M=>{f(M.activities.filter(V=>V.type==="heartbeat"))}).catch(()=>{})]),[r]);s.useEffect(()=>{d(!0),R().finally(()=>d(!1))},[R]),s.useEffect(()=>We.on("agent:update",V=>{V.payload?.agentId===r&&R()}),[r,R]);const P=async()=>{$(!0),p(null);try{const M=await T.agents.triggerHeartbeat(r);p(M.message),setTimeout(()=>p(null),4e3),setTimeout(R,2e3)}catch(M){p(String(M).replace("Error: ",""))}$(!1)},I=async M=>{try{await T.agents.cancelWakeup(r,M),R()}catch{}};if(u)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:n("agent:profilePage.heartbeatTab.loading")});if(!i)return e.jsx("div",{className:"text-xs text-fg-tertiary py-8 text-center",children:n("agent:profilePage.heartbeatTab.noData")});const h=M=>M?M<1e3?`${M}ms`:M<6e4?`${(M/1e3).toFixed(1)}s`:`${(M/6e4).toFixed(1)}m`:null,E=M=>{if(!M)return null;const V=Date.now()-new Date(M).getTime();if(V<0){const ie=Math.abs(V);return ie<6e4?n("agent:profilePage.relative.inSeconds",{count:Math.ceil(ie/1e3)}):ie<36e5?n("agent:profilePage.relative.inMinutes",{count:Math.ceil(ie/6e4)}):n("agent:profilePage.relative.inHours",{hours:(ie/36e5).toFixed(1)})}return V<6e4?n("agent:profilePage.relative.secondsAgo",{count:Math.floor(V/1e3)}):V<36e5?n("agent:profilePage.relative.minutesAgo",{count:Math.floor(V/6e4)}):n("agent:profilePage.relative.hoursAgo",{hours:(V/36e5).toFixed(1)})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(lt,{title:n("agent:profilePage.heartbeatTab.scheduler"),action:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("button",{onClick:R,className:"text-[10px] text-fg-tertiary hover:text-fg-secondary transition-colors",children:n("common:refresh")}),e.jsx("button",{onClick:P,disabled:j||!i.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:n(j?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.triggerNow")})]}),children:[e.jsxs("div",{className:"grid grid-cols-4 gap-4",children:[e.jsx(ft,{label:n("agent:profilePage.overview.labels.status"),value:i.running?n("agent:profilePage.heartbeatTab.running"):n("agent:profilePage.heartbeatTab.stopped"),color:i.running?"green":"gray"}),e.jsx(xc,{agentId:r,intervalMs:i.intervalMs,onChanged:R}),e.jsx(ft,{label:n("agent:profilePage.heartbeatTab.lastRun"),value:i.lastHeartbeat?E(i.lastHeartbeat)??n("agent:profilePage.emDash"):n("agent:profilePage.never")}),e.jsx(ft,{label:n("agent:profilePage.heartbeatTab.nextWake"),value:i.nextWakeAt?E(i.nextWakeAt)??n("agent:profilePage.emDash"):i.running?n("agent:profilePage.heartbeatTab.pending"):n("agent:profilePage.emDash")})]}),e.jsx("p",{className:"mt-2 text-[10px] text-fg-tertiary leading-relaxed",children:n("agent:profilePage.heartbeatTab.rhythmHint")}),v&&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:v})]}),i.wakeups&&i.wakeups.length>0&&e.jsx(lt,{title:n("agent:profilePage.heartbeatTab.wakeupsTitle"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("agent:profilePage.heartbeatTab.wakeupsCount",{count:i.wakeups.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:i.wakeups.map(M=>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:M.note||n("agent:profilePage.heartbeatTab.wakeupNoNote")}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[E(M.wakeAt)??new Date(M.wakeAt).toLocaleString(),M.recurringMs?` · ${n("agent:profilePage.heartbeatTab.recurring")}`:"",` · ${M.deliveryMode==="in_session"?n("agent:profilePage.heartbeatTab.deliveryInSession"):n("agent:profilePage.heartbeatTab.deliveryMailbox")}`]})]}),e.jsx("button",{onClick:()=>I(M.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:n("agent:profilePage.heartbeatTab.cancelWakeup")})]},M.id))})}),i.pendingCallbacks&&i.pendingCallbacks.length>0&&e.jsx(lt,{title:n("agent:profilePage.heartbeatTab.pendingOpsTitle"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("agent:profilePage.heartbeatTab.pendingOpsCount",{count:i.pendingCallbacks.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:i.pendingCallbacks.map(M=>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:M.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:M.label}),e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[n(`agent:profilePage.heartbeatTab.callbackType.${M.type}`),` · ${n("agent:profilePage.heartbeatTab.timesOut")} ${E(M.timeoutAt)??new Date(M.timeoutAt).toLocaleString()}`]})]})]},M.id))})}),i.lastSummary&&e.jsx(lt,{title:n("agent:profilePage.heartbeatTab.lastSummary"),action:i.lastSummaryAt?e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(i.lastSummaryAt).toLocaleString()}):void 0,children:e.jsx("div",{className:"bg-surface-primary/50 rounded-lg px-4 py-3",children:e.jsx($n,{content:i.lastSummary,className:"text-xs text-fg-secondary leading-relaxed"})})}),m.length>0?e.jsx(lt,{title:n("agent:profilePage.heartbeatTab.recentRuns"),action:e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:n("agent:profilePage.heartbeatTab.runsThisSession",{count:m.length})}),children:e.jsx("div",{className:"divide-y divide-gray-800/50 -mx-5",children:[...m].reverse().map(M=>{const V=y===M.id;return e.jsxs("div",{children:[e.jsxs("button",{onClick:()=>k(V?null:M.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:M.label}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:n("agent:profilePage.heartbeatTab.actionsCount",{count:M.logCount})}),e.jsx("span",{className:"text-[10px] text-fg-tertiary shrink-0",children:new Date(M.startedAt).toLocaleString()}),e.jsx("svg",{className:`w-3 h-3 text-fg-tertiary shrink-0 transition-transform ${V?"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"})})]}),V&&e.jsx("div",{className:"border-t border-border-default/60 bg-surface-primary/40",children:e.jsx(Fn,{agentId:r,activityId:M.id})})]},M.id)})})}):i.lastHeartbeat?null:e.jsx(lt,{title:n("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:n("agent:profilePage.heartbeatTab.noRunsYet")}),e.jsx("p",{className:"text-[10px] text-fg-tertiary mt-1",children:i.running?n("agent:profilePage.heartbeatTab.firstHeartbeatSoon",{when:h(i.intervalMs-i.uptimeMs%i.intervalMs)??n("agent:profilePage.heartbeatTab.soon")}):n("agent:profilePage.heartbeatTab.schedulerStopped")}),i.running&&e.jsx("button",{onClick:P,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:n(j?"agent:profilePage.heartbeatTab.triggering":"agent:profilePage.heartbeatTab.runFirstNow")})]})})]})}function mc({taskId:r,isLive:a}){const{t:n}=Xe("agent"),[i,o]=s.useState([]),[u,d]=s.useState(""),[m,f]=s.useState(!0),[y,k]=s.useState("compact");if(s.useEffect(()=>{f(!0),d(""),T.tasks.getLogs(r).then(v=>{o(v.logs),f(!1)}).catch(()=>f(!1))},[r]),s.useEffect(()=>{if(!a)return;const v=We.on("task:log",R=>{const P=R.payload;if(P.taskId!==r)return;const I={id:P.id,taskId:P.taskId,agentId:P.agentId,seq:P.seq,type:P.logType,content:P.content,metadata:P.metadata,createdAt:P.createdAt};o(h=>I.id&&h.some(E=>E.id===I.id)?h:[...h,I]),I.type==="text"&&d("")}),p=We.on("task:log:delta",R=>{const P=R.payload;P.taskId===r&&d(I=>I+P.text)});return()=>{v(),p()}},[r,a]),m)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:n("profilePage.taskLog.loading")});if(i.length===0&&!u)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:n("profilePage.taskLog.noLogs")});const j=i.map(v=>ol(v)),$=new Set(j.filter(v=>v.executionRound!=null).map(v=>v.executionRound)).size>1;return e.jsx("div",{className:"px-3 py-2",children:y==="compact"?e.jsx(Ui,{entries:j,streamingText:u,isActive:a,onExpand:()=>k("full"),showRounds:$}):e.jsx(Gi,{entries:j,streamingText:u,isActive:a,onCollapse:()=>k("compact"),showRounds:$})})}function Fn({agentId:r,activityId:a,isLive:n=!1}){const{t:i}=Xe("agent"),[o,u]=s.useState([]),[d,m]=s.useState(!0),[f,y]=s.useState("compact");if(s.useEffect(()=>{m(!0),T.agents.getActivityLogs(r,a).then(j=>{u(j.logs),m(!1)}).catch(()=>m(!1))},[r,a]),s.useEffect(()=>n?We.on("agent:activity_log",$=>{const v=$.payload;if(v.agentId!==r||v.activityId!==a)return;const p={seq:v.seq,type:v.type,content:v.content,metadata:v.metadata,createdAt:v.createdAt};u(R=>R.some(P=>P.seq===p.seq)?R:[...R,p])}):void 0,[r,a,n]),d)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:i("profilePage.activityLog.loading")});if(o.length===0)return e.jsx("div",{className:"px-4 py-3 text-xs text-fg-tertiary",children:i("profilePage.activityLog.noLogs")});const k=o.map(j=>il(j,a,r)).filter(j=>j!==null);return e.jsx("div",{className:"px-3 py-2",children:f==="compact"?e.jsx(Ui,{entries:k,isActive:n,onExpand:()=>y("full")}):e.jsx(Gi,{entries:k,isActive:n,onCollapse:()=>y("compact")})})}function lt({title:r,action:a,children:n}){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:r}),a]}),n]})}function _t({label:r,mono:a,children:n}){return e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r}),e.jsx("span",{className:`text-xs text-fg-secondary ${a?"font-mono text-[10px]":""}`,children:n})]})}function ft({label:r,value:a,color:n}){const i=n==="green"?"text-green-500":n==="blue"?"text-blue-400":n==="indigo"?"text-brand-500":n==="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 ${i}`,children:a}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:r})]})}const Ti=[1800*1e3,3600*1e3,10800*1e3,360*60*1e3,720*60*1e3,1440*60*1e3],Mi=5,Ii=1440;function xc({agentId:r,intervalMs:a,onChanged:n}){const{t:i}=Xe(["agent","common"]),[o,u]=s.useState(!1),[d,m]=s.useState(null),[f,y]=s.useState(!1),[k,j]=s.useState(String(Math.round(a/6e4))),$=h=>h%(3600*1e3)===0?i("agent:profilePage.heartbeatTab.intervalHours",{count:h/(3600*1e3)}):i("agent:profilePage.heartbeatTab.intervalMinutes",{count:Math.round(h/6e4)}),v=async h=>{u(!0),m(null);try{await T.agents.updateConfig(r,{heartbeatIntervalMs:h}),n()}catch(E){m(String(E).replace("Error: ",""))}u(!1)},p=h=>{if(h.target.value==="custom"){y(!0);return}y(!1),v(Number(h.target.value))},R=()=>{const h=Math.round(Number(k));if(!Number.isFinite(h)||h<Mi||h>Ii){m(i("agent:profilePage.heartbeatTab.intervalRangeHint"));return}v(h*60*1e3)},P=Ti.includes(a),I=f||!P?"custom":String(a);return e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:i("agent:profilePage.heartbeatTab.safetyNetInterval")}),e.jsxs("select",{value:I,onChange:p,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:[!P&&e.jsx("option",{value:String(a),children:$(a)}),Ti.map(h=>e.jsx("option",{value:String(h),children:$(h)},h)),e.jsx("option",{value:"custom",children:i("agent:profilePage.heartbeatTab.intervalCustom")})]}),(f||!P)&&e.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[e.jsx("input",{type:"number",min:Mi,max:Ii,value:k,onChange:h=>j(h.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:i("agent:profilePage.heartbeatTab.intervalCustomUnit")}),e.jsx("button",{onClick:R,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:i(o?"agent:profilePage.heartbeatTab.intervalSaving":"agent:profilePage.heartbeatTab.intervalSave")})]}),d&&e.jsx("span",{className:"text-[10px] text-red-400",children:d})]})}function vr({text:r}){return e.jsx("div",{className:"text-xs text-fg-tertiary py-6 text-center",children:r})}function Ei(r){if(r===0)return"0 B";const a=["B","KB","MB","GB"],n=Math.min(Math.floor(Math.log(r)/Math.log(1024)),a.length-1),i=r/Math.pow(1024,n);return`${i<10?i.toFixed(1):Math.round(i)} ${a[n]}`}const Ai={0:"0",1:"1",2:"2",3:"3",4:"4"},Pi={0:"text-red-500",1:"text-amber-500",2:"text-fg-secondary",3:"text-fg-tertiary",4:"text-fg-tertiary/60"},fc={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"},gc={idle:"bg-green-500/20 text-green-500",focused:"bg-brand-500/20 text-brand-500",deciding:"bg-amber-500/20 text-amber-500"},fr={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:"🧠"},hc=["all","interaction","task","notification","system"],pc={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"]},bc={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"},yc={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 da(r){const a=r.match(/Comment from .+?:\s*(.+?)(?:\n\n\*\*MANDATORY|\n\n---|\n\n\[|$)/s);if(a?.[1]){const n=a[1].trim().replace(/\n/g," ");return n.length>80?n.slice(0,80)+"…":n}}function _i(r,a){const n=r.payload,i=n?.summary??"",o=n?.content??"",u=r.metadata?.senderName;switch(r.sourceType){case"task_status_update":{const d=i.match(/^Task "(.+?)" status:/),m=i.match(/status:\s*(\S+)\s*→\s*(\S+)/),f=d?.[1]??i;if(m){const k=m[1],j=m[2],$=ua(k,a),v=ua(j,a),p=yc[j]??"text-fg-secondary";return{title:f,subtitle:a("agent:profilePage.mind.mailbox.statusArrow",{from:$,to:v}),badge:{label:v,color:p}}}const y=i.match(/^Task:\s*(.+)/);return y?{title:y[1]}:{title:f}}case"task_comment":{const d=i.match(/^Comment on task "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),m=da(o);if(d){const f=m?a("agent:profilePage.mind.mailbox.commentFromAuthor",{author:d[2],text:m}):a("agent:profilePage.mind.mailbox.commentFrom",{name:d[2]});return{title:d[1],subtitle:f}}return{title:i}}case"requirement_update":{const d=i.match(/^Requirement "(.+?)"\s+(.*)/);return d?{title:d[1],subtitle:d[2]}:{title:i}}case"requirement_comment":{const d=i.match(/^Comment on requirement "(.+?)" from (.+?)(\s*\(\+\d+\))?$/),m=da(o);if(d){const f=m?a("agent:profilePage.mind.mailbox.commentFromAuthor",{author:d[2],text:m}):a("agent:profilePage.mind.mailbox.commentFrom",{name:d[2]});return{title:d[1],subtitle:f}}return{title:i}}case"human_chat":{const d=o.slice(0,120).replace(/\n/g," ");return{title:u?a("agent:profilePage.mind.mailbox.chatFrom",{sender:u}):a("agent:profilePage.mind.mailbox.humanChat"),subtitle:d+(o.length>120?"…":"")}}case"a2a_message":{const d=o.slice(0,120).replace(/\n/g," ");return{title:u?a("agent:profilePage.mind.mailbox.messageFrom",{sender:u}):a("agent:profilePage.mind.mailbox.agentMessage"),subtitle:d+(o.length>120?"…":"")}}case"mention":{const d=i.match(/from (.+)$/),m=da(o);return{title:d?a("agent:profilePage.mind.mailbox.mentionedBy",{name:d[1]}):a("agent:profilePage.mind.mailbox.mention"),subtitle:m||void 0}}case"review_request":{const d=o.slice(0,120).replace(/\n/g," ");return{title:u?a("agent:profilePage.mind.mailbox.reviewRequestFrom",{sender:u}):a("agent:profilePage.mind.mailbox.reviewRequest"),subtitle:d+(o.length>120?"…":"")}}case"session_reply":{const d=o.slice(0,120).replace(/\n/g," ");return{title:u?a("agent:profilePage.mind.mailbox.replyInSession",{sender:u}):a("agent:profilePage.mind.mailbox.sessionReply"),subtitle:d+(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 d=i.match(/^\[Announcement]\s*(.+)/);return d?{title:d[1],subtitle:a("agent:profilePage.mind.mailbox.systemAnnouncement")}:{title:i||a("agent:profilePage.mind.mailbox.systemEvent")}}default:return{title:i||r.sourceType}}}function Li({agentId:r,highlightId:a,agentStatus:n,canManageAgents:i,onAgentStateChange:o}){const{t:u}=Xe(["agent","common","team"]),[d,m]=s.useState(null),[f,y]=s.useState(null),[k,j]=s.useState(!0),[$,v]=s.useState("all"),[p,R]=s.useState("all"),[P,I]=s.useState(a??null),[h,E]=s.useState(a??null),[M,V]=s.useState(!1),[ie,N]=s.useState(!0),[L,F]=s.useState(null),ke=50,Be=3,A=s.useCallback(async(b=!0)=>{b&&j(!0);try{const U=$==="all"?void 0:$,fe=p==="all"?void 0:p,[be,_]=await Promise.all([T.agents.getMindState(r),T.agents.getMailbox(r,{limit:ke,category:U,status:fe})]);m(be),y(_),N((_.history?.length??0)>=ke)}catch{}j(!1)},[r,$,p]),ce=s.useCallback(async()=>{if(!f)return;const b=$==="all"?void 0:$,U=p==="all"?void 0:p;try{const fe=await T.agents.getMailbox(r,{limit:ke,offset:f.history.length,category:b,status:U});y(be=>be?{...be,history:[...be.history,...fe.history]}:fe),N((fe.history?.length??0)>=ke)}catch{}},[r,f,$,p]);s.useEffect(()=>{I(a??null),E(a??null),A()},[A,a]);const te=s.useRef(!1);if(s.useEffect(()=>{if(!h||k)return;if(f?.history?.some(U=>U.id===h)){te.current=!1;const U=document.getElementById(`mbx-${h}`);if(U){setTimeout(()=>U.scrollIntoView({behavior:"smooth",block:"center"}),100);const fe=setTimeout(()=>E(null),3e3);return()=>clearTimeout(fe)}}else ie&&!te.current&&(te.current=!0,(async()=>{let U=f?.history??[],fe=ie;for(;fe;)try{const be=await T.agents.getMailbox(r,{limit:ke,offset:U.length}),_=[...U,...be.history];U=_,fe=(be.history?.length??0)>=ke;const Q=be.history.some(ne=>ne.id===h);if(y(ne=>ne?{...ne,history:_}:be),N(fe),Q||!fe)break}catch{break}te.current=!1})())},[h,k,f,ie,r]),s.useEffect(()=>{let b=null;const U=be=>{be.payload?.agentId===r&&(b&&clearTimeout(b),b=setTimeout(()=>{b=null,A(!1)},500))},fe=[We.on("agent:mailbox",U),We.on("agent:decision",U),We.on("agent:attention",U),We.on("agent:focus",U),We.on("agent:update",U),We.on("agent:triage",U)];return()=>{b&&clearTimeout(b),fe.forEach(be=>be())}},[r,A]),k&&!d)return e.jsx("div",{className:"text-fg-tertiary text-sm animate-pulse",children:u("agent:profilePage.mind.loading")});const S=d?.mailboxDepth??d?.queuedItems?.length??0,J=(()=>{const b=d?.attentionState??"idle";return b==="deciding"||b==="idle"&&S>0?"deciding":b!=="idle"&&!d?.currentFocus?"idle":b})(),Ee=J==="idle"&&f?.history?.some(b=>b.status==="processing"),$e=(d?.attentionState??"idle")==="idle"&&S>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 ${gc[J]??"bg-gray-500/20 text-gray-500"}`,children:u(`agent:profilePage.mind.attention.${J}`)}),d?.currentFocus?(()=>{const b=_i({id:d.currentFocus.mailboxItemId,sourceType:d.currentFocus.type,payload:{summary:d.currentFocus.label,taskId:d.currentFocus.taskId},metadata:{},queuedAt:d.currentFocus.startedAt},u);return e.jsxs("span",{className:"text-sm text-fg-secondary inline-flex items-center gap-2",children:[e.jsxs("span",{children:[fr[d.currentFocus.type]??"●"," ",e.jsx("span",{className:"text-fg-primary font-medium",children:b.title}),b.subtitle&&e.jsx("span",{className:"text-fg-tertiary ml-1.5 text-xs",children:b.subtitle}),e.jsx("span",{className:"text-fg-tertiary ml-2 text-xs",children:u("agent:profilePage.mind.since",{time:new Date(d.currentFocus.startedAt).toLocaleTimeString()})})]}),i&&e.jsxs("button",{onClick:()=>F(d.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:["✕ ",u("agent:profilePage.mind.cancelCurrentBtn")]})]})})():$e?e.jsx("span",{className:"text-sm text-amber-500",children:u("agent:profilePage.mind.queuedButIdle",{count:S,defaultValue:"Queue has {{count}} item(s) — attention loop should pick them up…"})}):J==="deciding"?e.jsx("span",{className:"text-sm text-amber-500",children:u("agent:profilePage.mind.decidingWaiting",{count:S})}):e.jsx("span",{className:"text-sm text-fg-tertiary",children:u("agent:profilePage.mind.idleWaiting")}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[i&&n==="offline"&&e.jsxs("button",{onClick:()=>{T.agents.start(r).then(()=>{o?.(),A()})},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:["▶ ",u("agent:profilePage.mind.continueBtn")]}),i&&(n==="working"||n==="idle")&&e.jsxs("button",{onClick:()=>{T.agents.stop(r).then(()=>{o?.(),A()})},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:["■ ",u("team:contextMenu.stop")]}),e.jsx("button",{onClick:()=>{A()},className:"text-xs text-fg-tertiary hover:text-fg-secondary active:text-fg-primary transition-colors",children:u("agent:profilePage.mind.refresh")})]})]}),Ee&&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:u("agent:profilePage.mind.staleProcessingWarning")})]}),(d?.queuedItems?.length??0)>0&&(()=>{const b=d.queuedItems,U=b.length>Be,fe=U&&!M?b.slice(0,Be):b,be=b.reduce((_,Q)=>(_[Q.sourceType]=(_[Q.sourceType]??0)+1,_),{});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:u("agent:profilePage.mind.queue",{count:b.length})}),e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Object.entries(be).map(([_,Q])=>e.jsxs("span",{className:"text-[10px] text-fg-tertiary bg-amber-500/10 px-1.5 py-0.5 rounded",children:[fr[_]??"●"," ",Q]},_))})]}),e.jsxs("div",{className:"space-y-1",children:[fe.map((_,Q)=>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:Q+1}),e.jsx("span",{className:"text-sm",children:fr[_.sourceType]??"●"}),e.jsx("span",{className:`text-[10px] ${Pi[_.priority]??"text-fg-tertiary"}`,children:u(`agent:profilePage.mind.priority.${Ai[_.priority]??_.priority}`,{defaultValue:`P${_.priority}`})}),e.jsx("span",{className:"text-fg-secondary truncate flex-1 text-xs",children:_.summary}),e.jsx("span",{className:"text-[10px] text-fg-tertiary",children:new Date(_.queuedAt).toLocaleTimeString()})]},_.id)),U&&e.jsx("button",{onClick:()=>V(!M),className:"w-full text-center text-[11px] text-amber-500 hover:text-amber-400 py-1 transition-colors",children:M?u("agent:profilePage.mind.collapseQueue"):u("agent:profilePage.mind.expandQueue",{count:b.length-Be})})]})]})})()]}),(d?.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:[d.notebook.length," ",d.notebook.length===1?"entry":"entries"]})]}),e.jsx("div",{className:"mt-2 space-y-2",children:d.notebook.map(b=>{const U=Date.now()-b.updatedAt,fe=U<6e4?`${Math.round(U/1e3)}s ago`:U<36e5?`${Math.round(U/6e4)}min ago`:`${(U/36e5).toFixed(1)}h ago`,be=b.managed==="system"?"text-blue-400":b.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:b.key}),e.jsxs("span",{className:`text-[10px] ${be}`,children:["[",b.managed,"]"]}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:fe})]}),e.jsx("pre",{className:"text-[11px] text-fg-secondary whitespace-pre-wrap break-words leading-relaxed max-h-32 overflow-y-auto",children:b.text.length>500?b.text.slice(0,500)+"…":b.text})]},b.key)})})]})}),d?.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:u("agent:profilePage.mind.deliberationInProgress")}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:u("agent:profilePage.mind.since",{time:new Date(d.deliberationActivity.startedAt).toLocaleTimeString()})})]}),e.jsx(Fn,{agentId:r,activityId:d.deliberationActivity.activityId,isLive:!0})]}),d?.lastTriage&&(()=>{const U=Date.now()-new Date(d.lastTriage.timestamp).getTime()>6e4;return e.jsx("section",{className:`bg-surface-2 rounded-lg border p-3 transition-opacity ${U?"border-border-subtle opacity-60":"border-indigo-500/20"}`,children:e.jsxs("details",{open:!U,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:u("agent:profilePage.mind.triageDecision")}),e.jsx("span",{className:"text-[10px] text-fg-quaternary ml-auto",children:new Date(d.lastTriage.timestamp).toLocaleTimeString()})]}),e.jsx("p",{className:"text-xs text-fg-secondary leading-relaxed mt-2",children:d.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:u("agent:profilePage.mind.processingItem",{id:d.lastTriage.processedItemId.slice(0,12)})}),d.lastTriage.deferredItemIds.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-amber-500/10 text-amber-400",children:u("agent:profilePage.mind.deferred",{count:d.lastTriage.deferredItemIds.length})}),d.lastTriage.droppedItemIds.length>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-red-500/10 text-red-400",children:u("agent:profilePage.mind.dropped",{count:d.lastTriage.droppedItemIds.length})}),(d.lastTriage.inlineCompletedIds?.length??0)>0&&e.jsx("span",{className:"px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-400",children:u("agent:profilePage.mind.inlineCompleted",{count:d.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:u("agent:profilePage.mind.mailboxHistory")}),e.jsx("div",{className:"flex gap-1 ml-auto flex-wrap",children:hc.map(b=>{const U=f?.sourceTypeCounts,fe=b==="all"?U?Object.values(U).reduce((be,_)=>be+_,0):void 0:U?(pc[b]??[]).reduce((be,_)=>be+(U[_]??0),0):void 0;return e.jsxs("button",{onClick:()=>v(b),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors ${$===b?"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:[u(`agent:profilePage.mind.categoryFilters.${b}`),fe!=null&&fe>0&&e.jsx("span",{className:"ml-1 opacity-60",children:fe})]},b)})})]}),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(b=>{const U=f?.statusCounts,fe=b.key==="all"?U?Object.values(U).reduce((be,_)=>be+_,0):void 0:U?.[b.key];return e.jsxs("button",{onClick:()=>R(b.key),className:`px-2 py-0.5 text-[10px] rounded-md border transition-colors flex items-center gap-1 ${p===b.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:[b.dot&&e.jsx("span",{className:`w-1.5 h-1.5 rounded-full ${b.dot}`}),u(`agent:profilePage.mind.statusFilters.${b.key}`),fe!=null&&fe>0&&e.jsx("span",{className:"ml-1 opacity-60",children:fe})]},b.key)})}),(!f?.history||f.history.length===0)&&!k&&e.jsx("div",{className:"text-center text-fg-tertiary text-sm py-8",children:u("agent:profilePage.mind.noHistory")}),e.jsx("div",{className:"space-y-1",children:f?.history?.map(b=>{const U=P===b.id,fe=fr[b.sourceType]??"●",be=_i(b,u),_=b.metadata?.senderName,Q=b.metadata?.senderRole,ne=h===b.id;return e.jsxs("div",{id:`mbx-${b.id}`,className:`bg-surface-2 rounded-lg border transition-colors duration-1000 ${ne?"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:()=>I(U?null:b.id),children:[e.jsx("span",{className:"text-xs mt-0.5 text-fg-tertiary",children:U?"▾":"▸"}),e.jsx("span",{className:`w-2 h-2 mt-1.5 rounded-full shrink-0 ${bc[b.status]??"bg-gray-400"}`}),e.jsx("span",{className:"text-sm",children:fe}),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 ${U?"":"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 ${Pi[b.priority]??"text-fg-tertiary"}`,children:u(`agent:profilePage.mind.priority.${Ai[b.priority]??b.priority}`,{defaultValue:""})})]}),be.subtitle&&e.jsx("div",{className:`text-[11px] text-fg-secondary mt-0.5 ${U?"":"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(b.queuedAt).toLocaleString()}),b.completedAt&&e.jsxs("span",{children:["→ ",new Date(b.completedAt).toLocaleTimeString()]}),b.activity&&e.jsxs(e.Fragment,{children:[b.activity.totalTokens>0&&e.jsx("span",{children:u("agent:profilePage.mind.tokensCount",{count:dn(b.activity.totalTokens)})}),b.activity.totalTools>0&&e.jsx("span",{children:u("agent:profilePage.mind.toolsCount",{count:b.activity.totalTools})})]})]})]}),e.jsx("span",{className:"text-[10px] text-fg-tertiary bg-surface-3 px-1.5 py-0.5 rounded shrink-0",children:b.sourceType}),i&&b.status==="processing"&&e.jsxs("button",{onClick:ye=>{ye.stopPropagation(),F(b.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:["✕ ",u("agent:profilePage.mind.cancelCurrentBtn")]})]}),U&&e.jsxs("div",{className:"border-t border-border-subtle px-3 py-3 space-y-3",children:[_&&e.jsxs("div",{className:"text-[10px] text-fg-tertiary",children:[u("agent:profilePage.mind.from")," ",e.jsx("span",{className:"text-fg-secondary",children:_}),Q&&e.jsxs("span",{className:"text-fg-tertiary",children:[" (",Q,")"]})]}),b.payload?.content&&["human_chat","a2a_message","task_comment","requirement_comment","review_request","session_reply","mention"].includes(b.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:b.payload.content}),b.decisions&&b.decisions.length>0&&e.jsxs("div",{children:[e.jsx("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:u("agent:profilePage.mind.decisions")}),e.jsx("div",{className:"space-y-1",children:b.decisions.map(ye=>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 ${fc[ye.decisionType]??"bg-gray-500/20 text-gray-500"}`,children:ye.decisionType}),e.jsx("span",{className:"text-fg-secondary flex-1",children:ye.reasoning}),e.jsx("span",{className:"text-fg-tertiary shrink-0",children:new Date(ye.createdAt).toLocaleTimeString()})]},ye.id))})]}),b.activity?e.jsxs("div",{children:[e.jsxs("h5",{className:"text-[10px] font-medium text-fg-tertiary uppercase tracking-wider mb-1",children:[u("agent:profilePage.mind.activityHeading",{label:b.activity.label}),e.jsx("span",{className:`ml-2 inline-block px-1 py-0 rounded text-[9px] ${b.activity.success?"bg-green-500/15 text-green-500":"bg-red-500/15 text-red-500"}`,children:b.activity.success?u("agent:profilePage.mind.success"):u("agent:profilePage.mind.failed")})]}),b.activity.type==="task"&&b.payload?.taskId?e.jsx(mc,{taskId:b.payload.taskId,isLive:!b.activity.endedAt}):e.jsx(Fn,{agentId:r,activityId:b.activity.id,isLive:!b.activity.endedAt})]}):b.status==="processing"?e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2 animate-pulse",children:u("agent:profilePage.mind.processing")}):b.status==="completed"?e.jsx("div",{className:"text-xs text-fg-tertiary text-center py-2",children:u("agent:profilePage.mind.noActivityLog")}):null]})]},b.id)})}),ie&&(f?.history?.length??0)>0&&e.jsx("div",{className:"text-center mt-3",children:e.jsx("button",{onClick:ce,className:"text-xs text-brand-400 hover:text-brand-300 transition-colors",children:u("agent:profilePage.mind.loadEarlier")})})]}),L&&e.jsx(Bn,{title:u("agent:profilePage.mind.cancelConfirmTitle"),message:u("agent:profilePage.mind.cancelConfirmMessage"),confirmLabel:u("agent:profilePage.mind.cancelCurrentBtn"),onConfirm:()=>{F(null),T.agents.cancelProcessing(r).then(()=>{let b=0;const U=()=>{b+=1,A(),b<8&&window.setTimeout(U,750)};U()}).catch(()=>{A()})},onCancel:()=>F(null)})]})}function Ri({agentId:r}){const{t:a}=Xe(["agent","common"]),[n,i]=s.useState([]),[o,u]=s.useState(!0),[d,m]=s.useState(null),f=s.useCallback(async()=>{u(!0);try{const{results:y}=await T.deliverables.search({agentId:r,limit:200});i(y)}catch{i([])}u(!1)},[r]);return s.useEffect(()=>{f()},[f]),s.useEffect(()=>{const y=We.on("deliverable:created",()=>f()),k=We.on("deliverable:updated",()=>f()),j=We.on("deliverable:removed",()=>f());return()=>{y(),k(),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))}):n.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:n.length})}),n.map(y=>{const k=rl[y.type]??{icon:"📎",color:"bg-surface-elevated text-fg-secondary"},j=ei[y.status]??ei.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 ${k.color}`,children:k.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)})]}),d&&e.jsx(al,{item:d,onClose:()=>m(null),onOpenInPage:y=>{m(null),bs.navigate(gt.DELIVERABLES,{openDeliverable:y})}})]})}const vc=s.lazy(()=>Ki(()=>import("./index-CHkb08MZ.js").then(r=>r.aA),__vite__mapDeps([0,1])).then(r=>({default:r.MarkdownMessage}))),ga=[{key:"overview",labelKey:"teamProfile.overview",icon:"▦"},{key:"announcements",labelKey:"teamProfile.announcements",icon:"◈"},{key:"norms",labelKey:"teamProfile.norms",icon:"☰"},{key:"settings",labelKey:"teamProfile.settings",icon:"⚙"}],Di={idle:"bg-green-400",working:"bg-blue-400 animate-pulse",offline:"bg-gray-500",error:"bg-red-400"};function $i({teamId:r,onBack:a,inline:n,headless:i,activeTab:o,onSelectAgent:u}){const{t:d}=Xe("team"),[m,f]=s.useState(null),[y,k]=s.useState(null),[j,$]=s.useState("overview"),v=i&&o?o:j,[p,R]=s.useState(""),[P,I]=s.useState(""),[h,E]=s.useState(!1),[M,V]=s.useState(!1),[ie,N]=s.useState(""),[L,F]=s.useState(""),ke=s.useRef(null),Be=s.useRef(null),A=s.useRef(null),ce=s.useRef(null),[te,S]=s.useState(!1),[J,Ee]=s.useState(!1),[$e,b]=s.useState(""),[U,fe]=s.useState(""),[be,_]=s.useState(!1),[Q,ne]=s.useState([]),ye=s.useRef(null),ze=s.useCallback(async()=>{try{const qe=(await T.teams.list()).teams.find(He=>He.id===r);qe&&f(qe);const Ke=await T.teams.status(r);ne(Ke.agents)}catch{}},[r]),Je=s.useCallback(async()=>{try{const oe=await T.teams.getFile(r,"ANNOUNCEMENT.md");R(oe.content)}catch{R("")}try{const oe=await T.teams.getFile(r,"NORMS.md");I(oe.content)}catch{I("")}},[r]);s.useEffect(()=>{$("overview"),ze(),Je()},[r,ze,Je]),s.useEffect(()=>{h&&Be.current&&Be.current.focus()},[h]),s.useEffect(()=>{M&&ce.current&&ce.current.focus()},[M]);const kt=async(oe,qe)=>{S(!0);try{await T.teams.updateFile(r,oe,qe),oe==="ANNOUNCEMENT.md"?(R(qe),E(!1)):(I(qe),V(!1))}catch{}S(!1)},is=async()=>{$e.trim()&&(await T.teams.update(r,{name:$e.trim()}),Ee(!1),ze())},ys=async()=>{await T.teams.update(r,{description:U}),_(!1),ze()};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(oe=>oe.agentRole==="manager"),Qt=Q.filter(oe=>oe.status!=="offline").length,Nt=v==="announcements"&&h||v==="norms"&&M;if(i)return e.jsx("div",{className:`flex-1 bg-surface-primary ${Nt?"flex flex-col overflow-hidden":"overflow-y-auto"}`,children:e.jsxs("div",{className:`${Nt?"flex-1 flex flex-col min-h-0 p-5":"p-5"}`,children:[v==="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(oe=>{const qe=Q.find(St=>St.id===oe.id),Ke=Di[qe?.status??"offline"]??"bg-gray-500",He=oe.type==="agent";return e.jsxs("div",{onClick:()=>He&&u?.(oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${He&&u?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[e.jsx(wt,{name:oe.name,avatarUrl:oe.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:oe.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${Ke}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),oe.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:[oe.role," · ",oe.type]})]}),He&&u&&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"})})]},oe.id)}),m.members.length===0&&e.jsx("div",{className:"text-sm text-fg-tertiary text-center py-8",children:"No members"})]})]}),v==="announcements"&&e.jsx(gr,{content:p,draft:ie,setDraft:N,editing:h,setEditing:E,textareaRef:Be,contentRef:ke,saving:te,onSave:()=>kt("ANNOUNCEMENT.md",ie),placeholder:d("teamProfile.annPlaceholder"),emptyText:d("teamProfile.noAnnouncements")}),v==="norms"&&e.jsx(gr,{content:P,draft:L,setDraft:F,editing:M,setEditing:V,textareaRef:ce,contentRef:A,saving:te,onSave:()=>kt("NORMS.md",L),placeholder:d("teamProfile.normsPlaceholder"),emptyText:d("teamProfile.noNorms")}),v==="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:ye,value:$e,onChange:oe=>b(oe.target.value),onKeyDown:oe=>oe.key==="Enter"&&is(),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:is,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:()=>Ee(!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:()=>{b(m.name),Ee(!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:U,onChange:oe=>fe(oe.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:()=>_(!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:()=>{fe(m.description??""),_(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),e.jsx(Oi,{teamId:r,teamName:m.name,onDeleted:a})]})]})});const ht=j==="announcements"&&h||j==="norms"&&M;return e.jsxs("div",{className:`flex-1 bg-surface-primary ${ht?"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:[Qt," 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:oe}=await T.teams.getFilesMap(m.id),qe=m.members.filter(He=>He.type==="agent"),Ke={type:"team",name:Vi(m.name,m.name),displayName:m.name,version:"1.0.0",description:m.description??"",author:"",category:"general",tags:[],team:{members:qe.map(He=>({name:He.name,roleName:He.role,role:He.agentRole??"worker",count:1,skills:[]}))}};await qi.publishViaProxy({itemType:"team",name:m.name,description:m.description??"",category:"general",config:Ke,files:oe}),k({title:"Hub",message:`Published "${m.name}" to Markus Hub`,variant:"primary"})}catch(oe){k({title:"Hub",message:`Failed to publish: ${oe}`,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"]}),n&&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:ga.map(oe=>e.jsxs("button",{onClick:()=>$(oe.key),className:`px-3 py-1.5 text-xs rounded-t-lg whitespace-nowrap transition-colors ${j===oe.key?"bg-surface-primary text-fg-primary border border-border-default border-b-gray-950":"text-fg-tertiary hover:text-fg-secondary"}`,children:[oe.icon," ",d(oe.labelKey)]},oe.key))})]}),e.jsxs("div",{className:`${ht?"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(oe=>{const qe=Q.find(St=>St.id===oe.id),Ke=Di[qe?.status??"offline"]??"bg-gray-500",He=oe.type==="agent";return e.jsxs("div",{onClick:()=>He&&u?.(oe.id),className:`p-3 bg-surface-secondary rounded-xl border border-border-default flex items-center gap-3${He&&u?" cursor-pointer hover:border-brand-500/40 transition-colors":""}`,children:[e.jsx(wt,{name:oe.name,avatarUrl:oe.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:oe.name}),e.jsx("span",{className:`w-2 h-2 rounded-full ${Ke}`}),e.jsx("span",{className:"text-xs text-fg-tertiary",children:qe?.status??"offline"}),oe.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:[oe.role," · ",oe.type]})]}),He&&u&&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"})})]},oe.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(gr,{content:p,draft:ie,setDraft:N,editing:h,setEditing:E,textareaRef:Be,contentRef:ke,saving:te,onSave:()=>kt("ANNOUNCEMENT.md",ie),placeholder:d("teamProfile.annPlaceholder"),emptyText:d("teamProfile.noAnnouncements")}),j==="norms"&&e.jsx(gr,{content:P,draft:L,setDraft:F,editing:M,setEditing:V,textareaRef:ce,contentRef:A,saving:te,onSave:()=>kt("NORMS.md",L),placeholder:d("teamProfile.normsPlaceholder"),emptyText:d("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:ye,value:$e,onChange:oe=>b(oe.target.value),onKeyDown:oe=>oe.key==="Enter"&&is(),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:is,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:()=>Ee(!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:()=>{b(m.name),Ee(!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:U,onChange:oe=>fe(oe.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:()=>_(!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:()=>{fe(m.description??""),_(!0)},className:"text-xs text-fg-tertiary hover:text-fg-secondary",children:"Edit"})]})]})]}),e.jsx(Oi,{teamId:r,teamName:m.name,onDeleted:a})]})]}),y&&e.jsx(Bn,{alertOnly:!0,variant:y.variant??"primary",title:y.title,message:y.message,onConfirm:()=>k(null),onCancel:()=>k(null)})]})}function gr({content:r,draft:a,setDraft:n,editing:i,setEditing:o,textareaRef:u,contentRef:d,saving:m,onSave:f,placeholder:y,emptyText:k}){return i?e.jsxs("div",{className:"flex flex-col h-full min-h-0",children:[e.jsx("textarea",{ref:u,value:a,onChange:j=>n(j.target.value),onBlur:()=>{a!==r?f():o(!1)},onKeyDown:j=>{j.key==="Escape"&&(j.preventDefault(),n(r),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:d,className:"group relative cursor-pointer rounded-lg px-1 py-1 hover:bg-surface-elevated/50 transition-colors min-h-[80px]",onClick:()=>{n(r),o(!0)},role:"button",tabIndex:0,onKeyDown:j=>{j.key==="Enter"&&(n(r),o(!0))},children:r.trim()?e.jsx(s.Suspense,{fallback:e.jsx("div",{className:"text-xs text-fg-tertiary",children:"Loading…"}),children:e.jsx(vc,{content:r,className:"text-sm text-fg-secondary leading-relaxed"})}):e.jsx("div",{className:"text-sm text-fg-tertiary italic",children:k})})}function Oi({teamId:r,teamName:a,onDeleted:n}){const[i,o]=s.useState(!1),[u,d]=s.useState(!1),[m,f]=s.useState(!1),[y,k]=s.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"}),i?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:u,onChange:j=>d(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()=>{k(!0);try{await T.teams.delete(r,m,{purgeFiles:u}),window.dispatchEvent(new CustomEvent("markus:data-changed")),n()}catch{k(!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 hr(r,a,n,i){return r==="channel"?`ch:${n}`:r==="dm"?`dm:${i??""}`:a||"_direct"}class ps{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,n,i){const o=this.activeSession.get(a),u=!i||o===i||o===void 0,d=u?this.msgBuffers.get(a)??[]:this.sessionMsgCache.get(i)??[];let m=n(d);m.length>ps.MAX_MESSAGES&&(m=m.slice(-500));let f=!1;return u&&(this.msgBuffers.set(a,m),this.evictIfNeeded(a),f=this.currentConvKey===a),i&&i!==ps.NEW_CHAT_ID&&(this.sessionMsgCache.set(i,m),this.touchSessionCache(i)),{displayChanged:f,newMessages:f?m:void 0}}applyLoadResult(a,n,i){const o=this.isCacheFresher(n,i);o||(this.sessionMsgCache.set(n,i),this.touchSessionCache(n));const u=this.getPhase(a),d=this.activeSession.get(a);if(this.currentConvKey===a&&(this.loadingSession===n||d===n)&&u!=="streaming"){const f=o?this.sessionMsgCache.get(n):i;return this.msgBuffers.set(a,f),this.loadingSession=n,this.completeLoad(a),{displayChanged:!0,newMessages:f}}return{displayChanged:!1}}appendActivity(a,n,i){const o=i??a,u=[...this.actBuffers.get(o)??[],n];if(this.actBuffers.set(o,u),this.currentConvKey!==a)return{displayChanged:!1};const d=this.activeSession.get(a);return!i||!d||d===i?{displayChanged:!0,newActivities:u}:{displayChanged:!1}}getActiveSession(a){return this.activeSession.get(a)}setActiveSession(a,n){this.activeSession.set(a,n)}saveToCache(a,n){if(!n||n===ps.NEW_CHAT_ID)return;const i=this.msgBuffers.get(a);i&&i.length>0&&(this.sessionMsgCache.set(n,i),this.touchSessionCache(n))}restoreFromCache(a,n){const i=this.sessionMsgCache.get(n);if(i&&i.length>0)return this.msgBuffers.set(a,i),i;this.msgBuffers.delete(a)}isCacheFresher(a,n){const i=this.sessionMsgCache.get(a);if(!i||i.length===0)return!1;if(i.length>n.length)return!0;const o=i.reduce((f,y)=>f+y.text.length,0),u=n.reduce((f,y)=>f+y.text.length,0);if(o>u)return!0;const d=i.reduce((f,y)=>f+(y.segments?.length??0),0),m=n.reduce((f,y)=>f+(y.segments?.length??0),0);return d>m}incrementSend(a){this.sendCount.set(a,(this.sendCount.get(a)??0)+1)}decrementSend(a){const n=Math.max(0,(this.sendCount.get(a)??1)-1);return this.sendCount.set(a,n),n}resetSend(a){this.sendCount.set(a,0)}isSending(a){return(this.sendCount.get(a)??0)>0}addStreamSession(a,n){const i=this.streamingSessions.get(a)??new Set;i.add(n),this.streamingSessions.set(a,i)}removeStreamSession(a,n){if(n){const i=this.streamingSessions.get(a);i&&(i.delete(n),i.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<=ps.MAX_CONVERSATIONS)return;const n=[...this.msgBuffers.keys()],i=n.filter(o=>o!==a&&o!==this.currentConvKey).slice(0,n.length-ps.MAX_CONVERSATIONS);for(const o of i)this.msgBuffers.delete(o),this.actBuffers.delete(o),this.sessionTabs.delete(o),this.activeSession.delete(o)}touchSessionCache(a){const n=this.sessionCacheOrder.indexOf(a);for(n!==-1&&this.sessionCacheOrder.splice(n,1),this.sessionCacheOrder.push(a);this.sessionCacheOrder.length>ps.MAX_SESSION_CACHE;){const i=this.sessionCacheOrder.shift();if(new Set(this.activeSession.values()).has(i)){this.sessionCacheOrder.push(i);break}this.sessionMsgCache.delete(i)}}}const Ue=ps.NEW_CHAT_ID;function jc(r){const a=s.useRef(new ps),[n,i]=s.useState(r??[]),[o,u]=s.useState(!1),[d,m]=s.useState([]),f=s.useRef(null);s.useEffect(()=>()=>{f.current!==null&&cancelAnimationFrame(f.current)},[]);const y=s.useCallback((h,E,M)=>{const V=a.current.updateMessages(h,E,M);V.displayChanged&&V.newMessages&&i(V.newMessages)},[]),k=s.useCallback((h,E,M)=>{a.current.updateMessages(h,E,M).displayChanged&&f.current===null&&(f.current=requestAnimationFrame(()=>{f.current=null;const ie=a.current.getMessages(h);ie&&a.current.currentConvKey===h&&i([...ie])}))},[]),j=s.useCallback((h,E,M)=>{const V=a.current.appendActivity(h,E,M);V.displayChanged&&V.newActivities&&m(V.newActivities)},[]),$=s.useCallback(h=>a.current.getPhase(h),[]),v=s.useCallback(h=>a.current.beginLoad(h),[]),p=s.useCallback(h=>a.current.beginStream(h),[]),R=s.useCallback(h=>a.current.endStream(h),[]),P=s.useCallback(h=>{a.current.resetConv(h),a.current.deleteBuffer(h)},[]),I=s.useCallback(async(h,E,M)=>{a.current.loadingSession=h,a.current.beginLoad(E);try{const V=await M(),ie=a.current.applyLoadResult(E,h,V.messages);return ie.displayChanged&&ie.newMessages&&i(ie.newMessages),{count:V.messages.length,hasMore:V.hasMore,oldestCursor:V.oldestCursor}}catch{return a.current.currentConvKey===E&&a.current.getPhase(E)!=="streaming"&&(i([]),a.current.completeLoad(E)),{count:0,hasMore:!1,oldestCursor:null}}},[]);return{manager:a.current,messages:n,setMessages:i,sending:o,setSending:u,activities:d,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(h){a.current.currentConvKey=h}}},get loadingSessionRef(){return{get current(){return a.current.loadingSession},set current(h){a.current.loadingSession=h}}},updateConvMsgs:y,updateConvMsgsRaf:k,appendConvActivity:j,getPhase:$,beginLoad:v,beginStream:p,endStream:R,resetConv:P,loadAndDisplay:I,incrementSending:h=>a.current.incrementSend(h),decrementSending:h=>a.current.decrementSend(h),resetSending:h=>a.current.resetSend(h),isSendingFor:h=>a.current.isSending(h),setStreamSession:(h,E)=>a.current.addStreamSession(h,E),clearStreamSession:(h,E)=>a.current.removeStreamSession(h,E),getStreamSession:h=>a.current.getStreamSessions(h),saveSessionToCache:(h,E)=>a.current.saveToCache(h,E),restoreSessionFromCache:(h,E)=>{const M=a.current.restoreFromCache(h,E);return i(M??[]),M},isSessionCacheFresherThanDb:(h,E)=>a.current.isCacheFresher(h,E)}}function wc({value:r,onSelect:a,disabled:n}){const{t:i}=Xe("team"),[o,u]=s.useState(!1),[d,m]=s.useState(!0),[f,y]=s.useState(""),[k,j]=s.useState(!1),[$,v]=s.useState([]),[p,R]=s.useState(null),P=s.useRef(null),I=s.useCallback(async()=>{j(!0);try{const N=await fetch("/api/settings/llm",{credentials:"include"});if(!N.ok)throw new Error(`HTTP ${N.status}`);const L=await N.json(),F=L.providers?.markus;if(F?.configured&&F.enabled!==!1&&(!F.models||F.models.length===0))try{const ce=await fetch("/api/models/live/markus",{credentials:"include"});if(ce.ok){const te=await ce.json();te.models?.length&&(F.models=te.models)}}catch{}const ke=[];for(const[ce,te]of Object.entries(L.providers??{})){if(!te.configured||te.enabled===!1)continue;const S=(te.models??[]).map(J=>({id:J.id,name:J.name}));S.length!==0&&ke.push({provider:ce,displayName:te.displayName??ce,models:S})}ke.sort((ce,te)=>ce.displayName.localeCompare(te.displayName)),v(ke);const Be=ce=>!ce?.provider||!ce.model?!1:!!ke.find(S=>S.provider===ce.provider)?.models.some(S=>S.id===ce.model);let A=null;if(L.routingDefaultModel?.provider&&L.routingDefaultModel?.model)A={provider:L.routingDefaultModel.provider,model:L.routingDefaultModel.model};else if(L.defaultProvider){const ce=L.providers?.[L.defaultProvider];ce?.model&&(A={provider:L.defaultProvider,model:ce.model})}if(A&&!Be(A)){const ce=ke.find(S=>S.provider==="markus"),te=ce?.models[0]?{provider:"markus",model:ce.models[0].id}:ke[0]?.models[0]?{provider:ke[0].provider,model:ke[0].models[0].id}:null;te?(A=te,T.settings.updateRouting({defaultProvider:te.provider,routingDefaultModel:te}).catch(()=>{})):A=null}R(A)}catch{v([])}finally{j(!1)}},[]);s.useEffect(()=>{I()},[I]),s.useEffect(()=>{o&&(m(!0),y(""),I())},[o,I]),s.useEffect(()=>{if(!o)return;const N=L=>{P.current?.contains(L.target)||u(!1)};return document.addEventListener("mousedown",N),()=>document.removeEventListener("mousedown",N)},[o]);const h=s.useMemo(()=>{const N=f.trim().toLowerCase();return $.map(L=>({...L,models:N?L.models.filter(F=>F.id.toLowerCase().includes(N)||(F.name?.toLowerCase().includes(N)??!1)||L.displayName.toLowerCase().includes(N)||L.provider.toLowerCase().includes(N)):L.models})).filter(L=>L.models.length>0)},[$,f]),E=s.useCallback(N=>!N?.provider||!N.model?!1:$.length===0?!0:!!$.find(F=>F.provider===N.provider)?.models.some(F=>F.id===N.model),[$]);s.useEffect(()=>{if(!r||$.length===0||E(r))return;const N=p&&E(p)?p:(()=>{const L=$.find(F=>F.provider==="markus");return L?.models[0]?{provider:"markus",model:L.models[0].id}:$[0]?.models[0]?{provider:$[0].provider,model:$[0].models[0].id}:null})();N&&a(N,!1)},[r,$,p,E,a]);const M=r&&E(r)?r:p,ie=(M?.model?M.model.includes("/")?M.model.split("/").pop():M.model:"")||i("chatModel.title",{defaultValue:"Model"});return e.jsxs("div",{ref:P,className:"relative shrink-0",children:[e.jsxs("button",{type:"button",disabled:n,onClick:()=>u(N=>!N),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:M?`${M.provider}: ${M.model}`:i("chatModel.title",{defaultValue:"Model"}),children:[e.jsx("span",{className:"truncate",children:ie}),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:N=>y(N.target.value),placeholder:i("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:i("chatModel.applyGlobal",{defaultValue:"Apply to global"})}),e.jsx("button",{type:"button",role:"switch","aria-checked":d,onClick:()=>m(N=>!N),className:`relative w-9 h-5 rounded-full transition-colors ${d?"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 ${d?"translate-x-4":""}`})})]})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto py-1",children:[k&&e.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("common:loading",{defaultValue:"Loading…"})}),!k&&h.length===0&&e.jsx("div",{className:"px-3 py-4 text-xs text-fg-tertiary",children:i("chatModel.empty",{defaultValue:"No enabled providers / models"})}),!k&&h.map(N=>e.jsxs("div",{className:"mb-1",children:[e.jsx("div",{className:"px-3 py-1 text-[10px] uppercase tracking-wide text-fg-tertiary",children:N.displayName}),N.models.slice(0,80).map(L=>{const F=M?.provider===N.provider&&M?.model===L.id;return e.jsxs("button",{type:"button",onClick:()=>{a({provider:N.provider,model:L.id},d),d&&R({provider:N.provider,model:L.id}),u(!1)},className:`w-full text-left px-3 py-1.5 text-xs flex items-center gap-2 hover:bg-surface-base transition-colors ${F?"text-fg-primary":"text-fg-secondary"}`,children:[e.jsx("span",{className:"truncate flex-1",children:L.id}),F&&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"})})]},`${N.provider}:${L.id}`)})]},N.provider))]})]})]})}async function kc(r,a,n){r&&!r.startsWith("new_")&&await T.sessions.setModelOverride(r,a),n&&await T.settings.updateRouting({defaultProvider:a.provider,routingDefaultModel:{provider:a.provider,model:a.model}})}const Fi="markus_team_sidebars_c";function Nc(r){const a=r.metadata??{};if(typeof a.sessionId=="string"&&a.sessionId)return a.sessionId;if(r.actionType==="open_chat"&&r.actionTarget)try{const n=typeof r.actionTarget=="string"?JSON.parse(r.actionTarget):r.actionTarget;if(n&&typeof n=="object"&&typeof n.sessionId=="string")return n.sessionId}catch{}}const Sc=["chat","overview","files","tools","memory","deliverables"],Cc=["chat","overview","announcements","norms","settings"];function Tc(r,a){if(r==="chat")return a("page.chatTitle");if(fa.find(o=>o.key===r))return a(`agent:tabs.${r}`);const i=ga.find(o=>o.key===r);return i?a(i.labelKey):r}function Mc(r){if(r==="chat")return"💬";const a=fa.find(i=>i.key===r);if(a)return a.icon;const n=ga.find(i=>i.key===r);return n?n.icon:""}function hs(r){return r!=="chat"}const ma=new Set;function Ic(){return window.location.hash}function Ec(r){return ma.add(r),()=>{ma.delete(r)}}typeof window<"u"&&window.addEventListener("hashchange",()=>ma.forEach(r=>r()));function Oc({initialAgentId:r,authUser:a,previewMode:n,previewData:i}={}){const{t:o,i18n:u}=Xe(["team","common"]),d=s.useMemo(()=>({today:o("page.dateToday"),yesterday:o("page.dateYesterday")}),[o]),m=Wi(gt.TEAM),[f,y]=s.useState(i?.agents??[]),[k,j]=s.useState(i?.humans??[]),[$,v]=s.useState(!i),p=xa(),R=s.useSyncExternalStore(Ec,Ic),P=p&&(R.startsWith(`#${gt.TEAM}/`)||R.startsWith("#chat/")),I=p&&R.match(/^#team\/t\/(.+)$/),h=p?I?"team":P?"chat":"roster":"roster",E=I?I[1]:null,M=s.useRef(gt.TEAM),V=s.useCallback(()=>{M.current=window.location.hash.slice(1)||gt.TEAM,window.location.hash=`${gt.TEAM}/d`},[]),ie=s.useCallback(t=>{window.location.hash=`${gt.TEAM}/t/${t}`},[]);s.useEffect(()=>{if(!p)return;const t=()=>{hs(F.current)&&L("chat")};return window.addEventListener("popstate",t),()=>window.removeEventListener("popstate",t)},[p]);const[N,L]=s.useState("chat"),F=s.useRef("chat");F.current=N;const ke=ti({side:"left",defaultWidth:280,minWidth:220,maxWidth:400,storageKey:"markus_chat_sidebar"}),[Be,A]=s.useState(()=>{try{return localStorage.getItem(Fi)==="1"}catch{return!1}}),ce=s.useCallback(t=>{A(t);try{localStorage.setItem(Fi,t?"1":"0")}catch{}},[]),te=dl(),S=te?.leftCollapsed??!1,J=te?.rightPanel??null,Ee=te?.rightPanelTabs??[],$e=te?.activeRightPanelTabId??null,b=te?.rightPanelFullscreen??!1,U=J?"2xl:pr-8":"2xl:pr-[280px]",fe=te?.setHostAvailable,be=te?.collapseRightPanelOnly??te?.toggleRightPanel,_=te?.openRightPanel,Q=400,ne=320,ye=6,[ze,Je]=s.useState(typeof window<"u"?window.innerWidth:1440),[kt,is]=s.useState("auto"),ys=s.useRef(S);s.useEffect(()=>{ys.current!==S&&(ys.current=S,A(S))},[S]),s.useEffect(()=>{if(fe)return fe(m&&!p),()=>fe(!1)},[m,p,fe]),s.useEffect(()=>n||p||!m?void 0:We.on("ui:right_panel",l=>{const c=l.payload;if(c.action==="collapse"){be?.();return}if(c.action!=="open"||!c.panel||!_)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)}`;_({kind:"url",url:x.url,title:x.title||x.url,browserId:w});return}if(x.kind==="file"&&x.path){_({kind:"file",path:x.path,title:x.title});return}x.kind==="deliverable"&&x.deliverableId&&T.deliverables.get(x.deliverableId).then(w=>{w.deliverable&&_({kind:"deliverable",deliverable:w.deliverable})}).catch(()=>{})}),[n,p,m,be,_]);const Ys=s.useCallback(t=>{const l=`ctx_${Date.now()}_${Math.random().toString(36).slice(2,7)}`;Nr(c=>[...c,{id:l,...t}]),requestAnimationFrame(()=>ds.current?.focus())},[]),[Qt,Nt]=s.useState(()=>{if(n)return!0;try{return localStorage.getItem("markus_team_panel_visible")==="true"}catch{return!1}}),ht=ti({side:"left",defaultWidth:260,minWidth:200,maxWidth:400,storageKey:"markus_team_detail_panel"}),oe=s.useRef(null),[qe,Ke]=s.useState(!1),[He,St]=s.useState(!1),mn=s.useCallback(()=>{qe?St(t=>!t):Nt(t=>{const l=!t;try{localStorage.setItem("markus_team_panel_visible",String(l))}catch{}return l})},[qe]);s.useEffect(()=>{if(p)return;const t=oe.current;if(!t)return;const l=new ResizeObserver(([c])=>{if(!c)return;const x=c.contentRect.width;if(Je(x),!n){const w=x-ke.width-ht.width;Ke(w<400)}});return l.observe(t),()=>l.disconnect()},[p,n,ke.width,ht.width]);const zn=Qt&&!qe&&!He,xn=Be?0:ke.width+ye+(zn?ht.width+ye:0),Zt=Math.max(0,ze-xn-ye-8),fn=Math.min(Q,Math.floor(Zt*.4)),gn=Math.max(0,Zt-fn),ha=Math.min(Math.round(Zt/2),gn),vs=Math.max(0,Math.min(kt==="auto"?ha:kt,gn)),js=s.useRef(!1);s.useEffect(()=>{const t=(te?.rightPanel??null)!==null;t&&!js.current&&(A(!0),is("auto")),js.current=t},[te?.rightPanel]);const Jt=s.useRef(vs);Jt.current=vs;const Wn=s.useRef(gn);Wn.current=gn;const jr=s.useCallback(t=>{t.preventDefault();const l=t.clientX,c=Jt.current,x=z=>{const H=c+(l-z.clientX),Z=Wn.current,C=Math.min(ne,Z);is(Math.max(C,Math.min(Z,H)))},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"},[]);s.useEffect(()=>{if(!He)return;const t=l=>{l.target.closest("[data-l2-floating]")||St(!1)};return document.addEventListener("mousedown",t),()=>document.removeEventListener("mousedown",t)},[He]);const[Is,os]=s.useState(null),[Hn,hn]=s.useState(),[pn,Es]=s.useState(),[Ot,Ut]=s.useState(!1),[Vn,bn]=s.useState(""),[Xs,yn]=s.useState(!1),[es,As]=s.useState(""),Qs=s.useRef(null),Ft=s.useRef(null),ws=s.useCallback((t,l)=>{hn(t),Es(l),p?(L("profile"),history.pushState({mobileProfile:!0},"",window.location.hash)):L(t??"overview")},[p]),Ps=[{id:"chat"},{id:"profile"}],vn=s.useCallback(t=>{t==="profile"?ws():hs(F.current)?history.back():L("chat")},[ws]),Bt=Hi(Ps,N,vn),Ct=s.useCallback((t,l)=>{Oe("direct"),dt(t),p&&V(),ws(l?.tab,l?.highlightMailboxId),os(null)},[p,V,ws]),Gt=s.useCallback((t,l)=>{const c=f.find(x=>x.name.toLowerCase()===t.toLowerCase());if(c){const x=l.target.getBoundingClientRect();os({agentId:c.id,top:x.bottom,left:x.left})}},[f]),jn=s.useMemo(()=>f.map(t=>t.name),[f]),[O,Oe]=s.useState(()=>i?.chatMode??(r?"direct":localStorage.getItem("markus_chat_mode")??"direct")),[K,dt]=s.useState(()=>r??localStorage.getItem("markus_chat_agent")??""),[Pe,It]=s.useState(()=>i?.activeChannel??localStorage.getItem("markus_chat_channel")??"#general"),[at,_s]=s.useState(""),Et=500,Ls=s.useRef(new Set),Zs=t=>{if(Ls.current.add(t),Ls.current.size>Et){const l=Math.floor(Et*.2),c=Ls.current.values();for(let x=0;x<l;x++){const w=c.next().value;w&&Ls.current.delete(w)}}},wr=s.useMemo(()=>{if(i?.channelMessages){const t=i.activeChannel??"custom:general";return i.channelMessages.filter(l=>l.channel===t).map(l=>Ks(l))}},[]),{manager:qn,messages:Qe,setMessages:Tt,sending:Lt,setSending:ut,activities:kr,setActivities:Kt,msgBuffers:pt,sessionMsgCache:Rs,activeSessionBuffer:At,actBuffers:zt,sessionTabsBuffer:Un,currentConvKeyRef:Ne,updateConvMsgs:_e,updateConvMsgsRaf:ls,appendConvActivity:Ds,beginLoad:g,beginStream:q,endStream:G,resetConv:ge,loadAndDisplay:Ce,incrementSending:Fe,decrementSending:Ze,resetSending:Ve,isSendingFor:De,setStreamSession:it,clearStreamSession:bt,getStreamSession:mt,saveSessionToCache:Yt,restoreSessionFromCache:ct}=jc(wr),[nt,Rt]=s.useState(""),[ks,et]=s.useState(null),[ts,Nr]=s.useState([]),[pa,wn]=s.useState([]),Wt=s.useRef(null),[Sr,Gn]=s.useState(!!i?.streamLastMessage),$s=s.useRef(null),Ji=400;s.useEffect(()=>(Lt?($s.current&&(clearTimeout($s.current),$s.current=null),Gn(!0)):Sr&&($s.current=setTimeout(()=>{Gn(!1),$s.current=null},Ji)),()=>{$s.current&&clearTimeout($s.current)}),[Lt]);const ba=Lt||Sr||(()=>{for(let t=Qe.length-1;t>=Math.max(0,Qe.length-8);t--){const l=Qe[t];if(l.isStreaming&&!l.isStopped)return!0}return!1})(),Cr=s.useRef({fullText:"",timers:[]});s.useEffect(()=>{if(!n||!i?.streamLastMessage||Qe.length===0)return;const t=Qe[Qe.length-1];if(!t||t.sender!=="agent")return;const l=t.text;Cr.current.fullText=l;const c=Cr.current.timers;function x(){let z=0;Tt(Z=>Z.map((C,B)=>B===Z.length-1?{...C,text:""}:C)),Gn(!0);const H=setInterval(()=>{if(z+=1+Math.floor(Math.random()*2),z>=l.length){clearInterval(H),Tt(B=>B.map((Le,ve)=>ve===B.length-1?{...Le,text:l}:Le));const Z=setTimeout(()=>Gn(!1),800);c.push(Z);const C=setTimeout(x,6e3);c.push(C)}else Tt(Z=>Z.map((C,B)=>B===Z.length-1?{...C,text:l.slice(0,z)}:C))},30);c.push(H)}const w=setTimeout(x,1500);return c.push(w),()=>{c.forEach(z=>clearTimeout(z)),Cr.current.timers=[]}},[]);const Ns=s.useRef(0),[ya,ss]=s.useState(!1),[Tr,va]=s.useState(!1),[ja,cs]=s.useState(!1),[Dt,Mr]=s.useState([]),Ir=s.useRef(null),ds=s.useRef(null),[Kn,Yn]=s.useState(null),Ss=s.useRef(null),Er=s.useRef(!1),kn=s.useCallback(()=>{const t=ds.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"},[]);s.useEffect(()=>{const t=requestAnimationFrame(()=>kn());return()=>cancelAnimationFrame(t)},[nt,Dt.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}},eo=(t,l)=>{const c=Ar(t);c.add(l);try{localStorage.setItem(`markus_closed_tabs_${t}`,JSON.stringify([...c]))}catch{}},to=(t,l)=>{const c=Ar(t);if(c.delete(l))try{localStorage.setItem(`markus_closed_tabs_${t}`,JSON.stringify([...c]))}catch{}},so=t=>{try{return localStorage.getItem(`markus_active_session_${t}`)}catch{return null}},Xn=(t,l)=>{if(t)try{l&&l!==Ue?localStorage.setItem(`markus_active_session_${t}`,l):localStorage.removeItem(`markus_active_session_${t}`)}catch{}},[Pr,Os]=s.useState([]),[Ie,ns]=s.useState(null),[Fs,Bs]=s.useState(!1),[wa,_r]=s.useState([]),[Nn,Lr]=s.useState(null),[no,ka]=s.useState(null),[Qn,Rr]=s.useState([]),[Js,Dr]=s.useState(null),[ro,Na]=s.useState(null),[Sa,$r]=s.useState([]),[Sn,ao]=s.useState([]),Pt=t=>{ao(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=s.useRef(null),Or=s.useRef(null),Xt=s.useRef(null),[vt,Cn]=s.useState(i?.groupChats??[]),Fr=s.useRef(vt);Fr.current=vt;const Ca=s.useRef(null),[Tn,yt]=s.useState(!1),[zs,Mn]=s.useState(!1),[Ta,en]=s.useState(""),[Br,Cs]=s.useState([]),[Ma,Ia]=s.useState(!1),zr=s.useRef(void 0),[rs,Ea]=s.useState(i?.teams??[]),[io,oo]=s.useState([]),[Jn,Aa]=s.useState([]),[lo,co]=s.useState(null),[Ac,Pc]=s.useState(!1),[_c,Lc]=s.useState(""),[Pa,In]=s.useState(!1),[_a,uo]=s.useState(""),[En,tn]=s.useState(0),[mo,xo]=s.useState([]),La=s.useRef(!1),fo=s.useCallback(()=>{La.current||(La.current=!0,(async()=>{const t=[];try{const[l,c,x,w,z]=await Promise.all([T.projects.list().catch(()=>({projects:[]})),T.requirements.list().catch(()=>({requirements:[]})),T.tasks.list({pageSize:100}).catch(()=>({tasks:[]})),T.deliverables.search({limit:100}).catch(()=>({results:[]})),T.teams.list().catch(()=>({teams:[],ungrouped:[]}))]);for(const H of l.projects)t.push({id:H.id,name:H.name,entityType:"project",role:H.status});for(const H of c.requirements)t.push({id:H.id,name:H.title,entityType:"requirement",role:H.priority});for(const H of x.tasks)t.push({id:H.id,name:H.title,entityType:"task",role:H.status});for(const H of w.results)t.push({id:H.id,name:H.title,entityType:"deliverable",role:H.type});for(const H of z.teams)try{const Z=await T.workflows.list(H.id);for(const C of Z.workflows)t.push({id:C.name,name:C.displayName||C.name,entityType:"workflow",role:`v${C.version}`})}catch{}}catch{}xo(t)})())},[]),ot=O==="channel"?vt.find(t=>t.channelKey===Pe)?.teamId:void 0,go=s.useRef(null),sn=s.useRef(null),jt=s.useRef(null),Ra=s.useRef(void 0),er=s.useRef(!1),us=s.useRef(!0),Da=s.useRef(void 0);s.useEffect(()=>{if(!Fs)return;const t=l=>{Or.current&&!Or.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}`};s.useEffect(()=>{localStorage.setItem("markus_chat_mode",O)},[O]),s.useEffect(()=>{localStorage.setItem("markus_chat_agent",K)},[K]),s.useEffect(()=>{localStorage.setItem("markus_chat_channel",Pe)},[Pe]);const{counts:Wr,sessionAgentMap:An,markRead:Pn,setActiveKey:ho,clearActiveKey:po}=ul({enabled:!n}),sr=s.useMemo(()=>{const t={};for(const[l,c]of Object.entries(Wr))l.startsWith("channel:")&&(t[l.slice(8)]=c);return t},[Wr]),Hr=ml(An,Wr);s.useEffect(()=>{let t=0;for(const l of Hr.values())t+=l;for(const l of Object.values(sr))t+=l;window.dispatchEvent(new CustomEvent("markus:team-unread-changed",{detail:{count:t}}))},[Hr,sr]);const nr=Hr,bo=s.useCallback(async t=>{for(const[l,c]of Object.entries(An))c===t&&Pn(`session:${l}`)},[An,Pn]);s.useEffect(()=>{if(n||!((!p||h==="chat")&&N==="chat"))return;if(O==="direct"&&K&&bo(K),O==="channel"&&Pe)Pn(`channel:${Pe}`);else if(O==="direct"&&Ie)Pn(`session:${Ie}`);else if(O==="dm"&&at){const c=`dm:${[a?.id,at].sort().join(":")}`;Pn(`channel:${c}`)}const l=[];if(O==="direct"&&Ie){l.push(`session:${Ie}`);for(const[c,x]of Object.entries(An))x===K&&l.push(`session:${c}`)}else O==="channel"&&Pe?l.push(`channel:${Pe}`):O==="dm"&&at&&a?.id&&l.push(`channel:dm:${[a.id,at].sort().join(":")}`);for(const c of l)ho(c);return()=>{for(const c of l)po(c)}},[n,O,Pe,Ie,at,K,h,N,An]);const Ht=s.useCallback(()=>T.agents.list().then(t=>y(t.agents)).catch(()=>{}),[]),$t=s.useCallback(()=>T.teams.list().then(t=>Ea(t.teams)).catch(()=>{}),[]),nn=s.useCallback(()=>T.groupChats.list().then(t=>Cn(t.chats)).catch(()=>{}),[]),yo=s.useMemo(()=>ia(Ht,3e3),[Ht]),rr=s.useMemo(()=>ia($t,5e3),[$t]),Vr=s.useMemo(()=>ia(nn,3e3),[nn]),_n=s.useCallback(()=>{T.users.list(a?.orgId).then(t=>j(t.users)).catch(()=>{})},[a?.orgId]);s.useEffect(()=>{n||(Promise.all([Ht(),$t()]).finally(()=>v(!1)),_n(),T.tasks.list().then(t=>Aa(t.tasks)).catch(()=>{}),T.externalAgents.list().then(t=>oo(t.agents)).catch(()=>{}),nn())},[n,_n]),s.useEffect(()=>{if(!(!n||!i)&&(y(i.agents??[]),j(i.humans??[]),Ea(i.teams??[]),Cn(i.groupChats??[]),i.channelMessages)){const t=i.activeChannel??"custom:general";Tt(i.channelMessages.filter(l=>l.channel===t).map(l=>Ks(l)))}},[n,i]),s.useEffect(()=>{if(n||!m)return;Ht(),$t();const t=setInterval(Ht,3e4),l=setInterval($t,6e4),c=We.on("agent:update",()=>{yo(),rr()}),x=We.on("team:update",()=>{rr(),Vr()}),w=We.on("agent:removed",rr),z=We.on("chat:group_created",()=>{nn(),$t(),Ht()}),H=We.on("chat:group_updated",Vr),Z=We.on("chat:group_deleted",()=>{Vr(),rr()}),C=We.on("task:update",Le=>{const ve=Le?.payload;ve?.taskId&&Aa(he=>he.map(re=>re.id===ve.taskId?{...re,status:ve.status??re.status}:re))}),B=()=>{Ht(),$t(),_n()};return window.addEventListener("markus:data-changed",B),()=>{clearInterval(t),clearInterval(l),c(),x(),w(),z(),H(),Z(),C(),window.removeEventListener("markus:data-changed",B)}},[n,m,_n]),s.useEffect(()=>{if(n)return;const t=Z=>{const C=Z.detail;if(Sl(C.page)===gt.TEAM){if(C.params?.agentId){if(C.params.profileTab)Ct(C.params.agentId,{tab:C.params.profileTab});else if(Oe("direct"),dt(C.params.agentId),L("chat"),p&&V(),C.params.sessionId){const B=C.params.sessionId;setTimeout(async()=>{try{const{sessions:Le}=await T.sessions.listByAgent(C.params.agentId,20),ve=Le.find(he=>he.id===B);ve&&dr(ve)}catch{}},300)}}if(C.params?.selectAgent&&(Oe("direct"),dt(C.params.selectAgent),L("chat"),p&&V()),C.params?.prefillMessage){const B=C.params.prefillMessage;localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),L("chat"),C.params?.autoSend==="true"?setTimeout(()=>Ra.current?.(B),300):(Rt(B),setTimeout(()=>{const Le=ds.current;Le&&(Le.focus(),Le.setSelectionRange(Le.value.length,Le.value.length))},100))}if(C.params?.dm&&(Oe("dm"),_s(C.params.dm),L("chat"),p&&V()),C.params?.channel&&(Oe("channel"),It(C.params.channel),L("chat"),p&&V()),C.params?.selectTeam){const B=C.params.selectTeam;if(p)ie(B);else{const Le=Fr.current.find(ve=>ve.type==="team"&&ve.teamId===B);Oe("channel"),It(Le?.channelKey??`group:${B}`),L("chat"),yt(!1),Nt(!0)}}C.params?.openHire}},l=localStorage.getItem("markus_nav_agentId");if(l){localStorage.removeItem("markus_nav_agentId");const Z=localStorage.getItem("markus_nav_profileTab");localStorage.removeItem("markus_nav_profileTab"),Oe("direct"),dt(l),Z?Ct(l,{tab:Z}):(L("chat"),p&&V())}const c=localStorage.getItem("markus_nav_dm");c&&(localStorage.removeItem("markus_nav_dm"),Oe("dm"),_s(c),L("chat"),p&&V());const x=localStorage.getItem("markus_nav_channel");x&&(localStorage.removeItem("markus_nav_channel"),Oe("channel"),It(x),L("chat"),p&&V());const w=localStorage.getItem("markus_nav_prefillMessage");w&&(localStorage.removeItem("markus_nav_prefillMessage"),localStorage.removeItem("markus_nav_autoSend"),L("chat"),Rt(w),setTimeout(()=>{const Z=ds.current;Z&&(Z.focus(),Z.setSelectionRange(Z.value.length,Z.value.length))},150));const z=localStorage.getItem("markus_nav_selectAgent");z&&(localStorage.removeItem("markus_nav_selectAgent"),Oe("direct"),dt(z),L("chat"),p&&V());const H=localStorage.getItem("markus_nav_selectTeam");if(H)if(localStorage.removeItem("markus_nav_selectTeam"),p)ie(H);else{const Z=Fr.current.find(C=>C.type==="team"&&C.teamId===H);Oe("channel"),It(Z?.channelKey??`group:${H}`),L("chat"),yt(!1),Nt(!0)}return window.addEventListener("markus:navigate",t),()=>window.removeEventListener("markus:navigate",t)},[n]),s.useEffect(()=>{const t=Ca.current;if(!t)return;const l=vt.find(c=>c.type==="team"&&c.teamId===t);Ca.current=null,Oe("channel"),It(l?.channelKey??`group:${t}`),L("chat"),yt(!1),Nt(!0)},[vt,rs]),s.useEffect(()=>{if(n&&i?.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?(Oe("direct"),dt(t.id),L("chat")):f.length>0&&(Oe("direct"),dt(f[0].id),L("chat"))},[f,K]);const rn=s.useRef(!1),as=s.useRef(!1),ar=s.useRef(!1),ir=s.useRef(0),an=s.useRef(0),[vo,ms]=s.useState(!1),Ts=s.useRef(0),[$a,Ws]=s.useState(0),xs=s.useCallback(()=>{as.current=!1,ar.current=!1,us.current=!0},[]),qr=s.useCallback(()=>{as.current=!0,us.current=!1,an.current+=1,rn.current=!1,ms(!0)},[]),Hs=s.useCallback(t=>{const l=sn.current;if(!l)return;const c=l.scrollHeight-l.scrollTop-l.clientHeight,x=c<160,w=c<48,z=ir.current,H=l.scrollTop<z-2;if(ir.current=l.scrollTop,H&&c>20){ar.current=!0,qr();return}if(ar.current){w?(xs(),ms(!1),Ts.current=0,Ws(0)):qr();return}if(x&&!as.current){xs(),ms(!1),Ts.current=0,Ws(0);return}t?.fromProgrammatic||rn.current||!as.current&&us.current||as.current&&(us.current=!1,ms(!0))},[qr,xs]);s.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()}},[h,Hs]);const Ur=s.useMemo(()=>new Set(Sa),[Sa]),xt=s.useMemo(()=>{const t=O==="channel"?Qe:Qe.filter(l=>!l.isActivityLog);return Ur.size===0?t:t.filter(l=>!(l.isNotification&&Ur.has(l.id)))},[Qe,O,Ur]);s.useEffect(()=>{Er.current=N==="chat"&&xt.length>0,kn()},[N,xt.length,kn]);const fs=Bl({count:xt.length,getScrollElement:()=>sn.current,getItemKey:t=>xt[t]?.id??t,estimateSize:t=>{const l=xt[t];return l?l.segments&&l.segments.length>0?300:l.text.length>500?200:120:120},overscan:8});fs.shouldAdjustScrollPositionOnItemSizeChange=(t,l,c)=>si()?!1:t.start<(c.scrollOffset??0);const on=s.useCallback((t="instant")=>{if(!us.current||as.current)return;const l=++an.current;rn.current=!0;const c=()=>l===an.current&&us.current&&!as.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&&!as.current&&(xs(),ms(!1),Ts.current=0,Ws(0))),requestAnimationFrame(()=>{l===an.current&&Hs({fromProgrammatic:!0})})};if(xt.length>0)fs.scrollToIndex(xt.length-1,{align:"end",behavior:t}),requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!c()){l===an.current&&(rn.current=!1);return}fs.scrollToIndex(xt.length-1,{align:"end",behavior:"instant"}),requestAnimationFrame(x)})});else{const w=sn.current;w&&w.scrollTo({top:w.scrollHeight,behavior:t}),requestAnimationFrame(x)}},[xt.length,fs,Hs,xs]),Oa=s.useRef(m);s.useEffect(()=>{Oa.current=m},[m]),s.useLayoutEffect(()=>{if(er.current){er.current=!1;const t=lr.current;t>0&&(lr.current=0,fs.scrollToIndex(t,{align:"start",behavior:"instant"}));return}Oa.current&&(!us.current||as.current||si()||on())},[Qe,on,fs]);const Fa=s.useRef(N);s.useEffect(()=>{const t=Fa.current!=="chat";if(Fa.current=N,N==="chat"&&t&&us.current&&!as.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)}}},[N,Lt,on]);const Ba=s.useCallback(async(t,l)=>{const c=l??`ch:${t}`;Ne.current===c&&cs(!0);try{const x=await T.channels.getMessages(t,50),w=x.messages.map(z=>Ks(z,a?.id));pt.set(c,w),Ne.current===c&&(Tt(w),ss(x.hasMore),Xt.current=x.messages[0]?new Date(x.messages[0].createdAt).toISOString():null)}catch{Ne.current===c&&(Tt([]),ss(!1))}finally{Ne.current===c&&cs(!1)}},[]),Gr=s.useCallback(async(t,l)=>{const c=Ne.current===l&&(pt.get(l)?.length??0)===0;c&&cs(!0);try{const{count:x,hasMore:w,oldestCursor:z}=await Ce(t,l,async()=>{const H=await T.sessions.getMessages(t,50);return{messages:xl(H.messages.map(oa).filter(C=>C.sender!=="agent"||C.text||C.segments&&C.segments.length>0||C.isStreaming)),hasMore:H.hasMore,oldestCursor:H.messages[0]?new Date(H.messages[0].createdAt).toISOString():null}});return ss(w),Xt.current=z,x}finally{c&&Ne.current===l&&cs(!1)}},[Ce,pt]),za=s.useRef(new Map),Vs=s.useCallback(async(t,l,c)=>{if(!t||!l||l===Ue)return;let x=null;try{if(jt.current&&!jt.current.signal.aborted&&mt(c)?.has(l)){q(c),Ne.current===c&&ut(!0);return}const w=`${t}:${l}`,z=za.current.get(w)??0;if(Date.now()-z<1500)return;const H=await T.sessions.streamStatus(t,l),C=[...pt.get(c)??[]].reverse().find(Y=>Y.sender==="agent"),B=H.status==="streaming",Le=!!H.active&&(H.status==="done"||H.status==="error")&&!!C?.isStreaming;if(!B&&!Le)return;za.current.set(w,Date.now()),Ss.current?.abort(),x=new AbortController,Ss.current=x,q(c),ut(!0),it(c,l);let ve=C?.id;if(!C||C.isError)ve=`reattach_${Date.now()}`,_e(c,Y=>[...Y,{id:ve,sender:"agent",text:"",time:new Date().toLocaleTimeString(),isStreaming:!0,segments:[]}],l);else{const Y=(C.segments??[]).filter(xe=>xe.type==="tool").map(xe=>xe.status==="stopped"||xe.status==="running"?{...xe,status:"running"}:xe);_e(c,xe=>xe.map(se=>se.id===C.id?{...se,text:"",isStreaming:!0,isStopped:!1,segments:Y,committedSegments:void 0}:se),l)}let he=!1;const re=Y=>{Ne.current===c&&(Ns.current=Date.now(),ls(c,xe=>{const se=[...xe],de=ve?se.findIndex(W=>W.id===ve):-1,le=de>=0?de:se.map((W,X)=>({m:W,j:X})).reverse().find(W=>W.m.sender==="agent")?.j??-1;if(le<0)return xe;const me=se[le].segments??[],Me=me[me.length-1],Ge=Me?.type==="text"?Me.thinking??"":"";let rt="",Mt="",D=Y;for(;D.length>0;)if(he){const W=D.indexOf("</think>");W>=0?(rt+=D.slice(0,W),D=D.slice(W+8),he=!1):(rt+=D,D="")}else{const W=D.indexOf("<think>");W>=0?(Mt+=D.slice(0,W),D=D.slice(W+7),he=!0):(Mt+=D,D="")}const pe=Ge+rt||void 0,ee=Me?.type==="text"?[...me.slice(0,-1),{type:"text",content:Me.content+Mt,thinking:pe,createdAt:Me.createdAt}]:[...me,{type:"text",content:Mt,thinking:pe,createdAt:new Date().toISOString()}];return se[le]={...se[le],text:(se[le].text??"")+Mt,segments:ee,isStreaming:!0},se},l))},Re=Y=>{if(Ne.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 xe=`${Y.tool}_${Date.now()}`,se=new Date().toISOString(),de=le=>{const me=[...le];for(let Me=me.length-1;Me>=0;Me--){const Ge=me[Me];if(Ge.type==="tool"&&Ge.tool===Y.tool&&(Ge.status==="running"||Ge.status==="stopped"))return me[Me]={...Ge,status:"running",args:Y.arguments??Ge.args},me}return me.push({type:"tool",key:xe,tool:Y.tool,status:"running",args:Y.arguments,createdAt:se}),me};_e(c,le=>{const me=[...le],Me=ve?me.findIndex(D=>D.id===ve):-1;if(Me<0)return le;const Ge=de(me[Me].segments??[]),rt=me[Me].committedSegments,Mt=rt&&de(rt);return me[Me]={...me[Me],segments:Ge,committedSegments:Mt,isStreaming:!0},me},l)}else if(Y.phase==="end"){const xe=new Date().toISOString(),se=de=>{const le=[...de];for(let me=le.length-1;me>=0;me--){const Me=le[me];if(Me.type==="tool"&&Me.tool===Y.tool&&(Me.status==="running"||Me.status==="stopped")){le[me]={...Me,status:Y.success===!1?"error":"done",args:Y.arguments??Me.args,result:Y.result,error:Y.error,durationMs:Y.durationMs,liveOutput:void 0,createdAt:xe};break}}return le};_e(c,de=>{const le=[...de],me=ve?le.findIndex(Mt=>Mt.id===ve):-1;if(me<0)return de;const Me=se(le[me].segments??[]),Ge=le[me].committedSegments,rt=Ge&&se(Ge);return le[me]={...le[me],segments:Me,committedSegments:rt,isStreaming:!0},le},l)}else if(Y.phase==="subagent_progress"&&Y.subagentEvent){const xe=se=>{const de=[...se];for(let le=de.length-1;le>=0;le--){const me=de[le];if(me.type==="tool"&&(me.tool==="spawn_subagent"||me.tool==="spawn_subagents")&&(me.status==="running"||me.status==="stopped")){de[le]={...me,status:"running",subagentLogs:ni(me.subagentLogs,Y.subagentEvent)};break}}return de};ls(c,se=>{const de=[...se],le=ve?de.findIndex(rt=>rt.id===ve):-1;if(le<0)return se;const me=xe(de[le].segments??[]),Me=de[le].committedSegments,Ge=Me&&xe(Me);return de[le]={...de[le],segments:me,committedSegments:Ge,isStreaming:!0},de},l)}}},ue=Y=>{Ne.current===c&&(Ns.current=Date.now(),_e(c,xe=>{const se=[...xe],de=ve?se.findIndex(me=>me.id===ve):-1;if(de<0)return xe;const le=[...se[de].committedSegments??[]];if(Y.type==="thinking_commit")le.push({type:"text",content:"",thinking:Y.content,createdAt:Y.createdAt});else if(Y.type==="text_commit")le.push({type:"text",content:Y.content,createdAt:Y.createdAt});else return xe;return se[de]={...se[de],committedSegments:le,isStreaming:!0},se},l))},Se=Y=>{if(Ne.current!==c)return;Ns.current=Date.now();const xe=(Y.segments??[]).map((se,de)=>se.type==="tool"?{type:"tool",key:`${se.tool}_${de}`,tool:se.tool??"tool",status:se.status==="error"?"error":se.status==="running"||se.status==="stopped"?"running":"done",args:se.arguments,result:se.result,error:se.error,durationMs:se.durationMs,createdAt:se.createdAt,...se.subagentLogs?.length?{subagentLogs:se.subagentLogs}:{}}:{type:"text",content:se.content??"",thinking:se.thinking,createdAt:se.createdAt});_e(c,se=>{const de=[...se],le=ve?de.findIndex(me=>me.id===ve):-1;return le<0?se:(de[le]={...de[le],text:Y.content||de[le].text,segments:xe,committedSegments:xe,isStreaming:!0,isStopped:!1},de)},l);for(const se of xe)se.type==="tool"&&Ds(c,{tool:se.tool,phase:se.status==="running"||se.status==="stopped"?"start":"end",success:se.status!=="error",arguments:se.args,result:se.result,error:se.error,durationMs:se.durationMs,ts:Date.now()},l)},Te=await T.sessions.reattachStream(t,l,{onChunk:re,onActivity:Re,onCommit:ue,onSnapshot:Se},x.signal,0);if(!Te.attached){G(c),Ne.current===c&&(_e(c,Y=>{const xe=[...Y],se=ve?xe.findIndex(me=>me.id===ve):-1,de=se>=0?se:xe.map((me,Me)=>({m:me,j:Me})).reverse().find(me=>me.m.sender==="agent"&&me.m.isStreaming)?.j??-1;if(de<0)return Y;const le=xe[de];return le.isStreaming?(xe[de]={...le,isStreaming:!1,isStopped:le.isError?le.isStopped:!0},xe):Y},l),ut(!1));return}Ne.current===c&&(_e(c,Y=>{const xe=[...Y],se=ve?xe.findIndex(Me=>Me.id===ve):-1,de=se>=0?se:xe.map((Me,Ge)=>({m:Me,j:Ge})).reverse().find(Me=>Me.m.sender==="agent")?.j??-1;if(de<0)return Y;const le=xe[de],me=Te.segments?.length?ri(Te.segments,le.segments):void 0;return xe[de]={...le,text:Te.content||le.text,isStreaming:!1,isStopped:!1,...me?{segments:me,committedSegments:me}:{}},xe},l),ut(!1)),G(c),Ss.current===x&&(Ss.current=null)}catch(w){if(Ss.current===x&&(Ss.current=null),G(c),Ne.current===c&&ut(!1),w instanceof Error&&w.name==="AbortError")return}},[Ds,q,G,mt,pt,it,_e,ls]);s.useEffect(()=>{if(!m||n||O!=="direct"||!K)return;const t=Ie;!t||t===Ue||Vs(K,t,Ne.current)},[m,n,O,K,Ie,Vs]);const or=s.useCallback(async t=>{if(!t)return Os([]),[];try{const{sessions:l}=await T.sessions.listByAgent(t,10);return Os(l),l}catch{return Os([]),[]}},[]),lr=s.useRef(0),jo=s.useCallback(async()=>{if(!(Tr||!ya||!Xt.current)){va(!0);try{const t=Ne.current;if(O==="channel"||O==="dm"){const l=O==="dm"?tr(a?.id??"",at):Pe,c=await T.channels.getMessages(l,50,Xt.current),x=c.messages.map(w=>Ks(w,a?.id));lr.current=x.length,er.current=!0,Tt(w=>{let z=[...x,...w];return z.length>500&&(z=z.slice(-500)),pt.set(t,z),z}),ss(c.hasMore),c.messages[0]&&(Xt.current=new Date(c.messages[0].createdAt).toISOString())}else if(Ie){const l=await T.sessions.getMessages(Ie,50,Xt.current),c=l.messages.map(oa);lr.current=c.length,er.current=!0,Tt(x=>{let w=[...c,...x];return w.length>500&&(w=w.slice(-500)),pt.set(t,w),w}),ss(l.hasMore),l.messages[0]&&(Xt.current=new Date(l.messages[0].createdAt).toISOString())}}catch{}finally{va(!1)}}},[Tr,ya,O,Pe,Ie,a?.id,at]);Da.current=jo;const Kr=s.useRef(!1),wo=s.useCallback(t=>{Kr.current||(Kr.current=!0,requestAnimationFrame(()=>{Kr.current=!1,t.target.scrollTop<100&&Da.current?.()}))},[]);s.useEffect(()=>{if(n)return;const t=hr(O,K,Pe,at),l=Ne.current;Ne.current=t,l&&l!==t&&(Un.set(l,Sn),Ie&&At.set(l,Ie)),l!==t&&(xs(),ms(!1),Ts.current=0,Ws(0));const c=pt.get(t),x=Un.get(t),w=At.get(t),z=mt(t),H=w??Ie,Z=De(t)&&(O!=="direct"||!z||!H||z.has(H)),C=H??t,B=zt.get(C)??[];if(Kt(Z?B:[]),ut(Z),O==="direct"&&K&&or(K),x&&x.length>0&&Pt(x),Bs(!1),c!==void 0&&c.length>0)if(Z||qn.completeLoad(t),cs(!1),Tt(c),ss(!1),w!==void 0&&ns(w),(!x||x.length===0)&&Pt([]),O==="channel"||O==="dm"){const ve=O==="dm"?tr(a?.id??"",at):Pe;Ba(ve,t)}else O==="direct"&&K&&w&&w!==Ue&&(Z?Vs(K,w,t):Gr(w,t).then(()=>{Ne.current===t&&K&&Vs(K,w,t)}));else if(g(t),cs(!0),Tt([]),ss(!1),Xt.current=null,pt.delete(t),O==="channel"||O==="dm"){const ve=O==="dm"?tr(a?.id??"",at):Pe;Ba(ve,t),(!x||x.length===0)&&Pt([])}else O==="direct"&&K?or(K).then(ve=>{if(Ne.current===t)if(ve.length>0){const he=ve.find(de=>de.isMain),re=Ar(K),Re=he?[he,...ve.filter(de=>!de.isMain&&!re.has(de.id)).slice(0,4)]:ve.filter(de=>!re.has(de.id)).slice(0,5);let ue=x&&x.length>0?x:Re;const Se=so(K),Te=w!==void 0?w:Se??he?.id??ue[0].id;if(Te&&Te!==Ue&&!ue.some(de=>de.id===Te)){const de=ve.find(le=>le.id===Te);de&&(ue=[...ue,de])}const Y=Te&&ue.some(de=>de.id===Te)?Te:ue[0].id;ns(Y),At.set(t,Y),Xn(K,Y),Pt(ue);const se=ve.find(de=>de.id===Y)?.metadata?.modelOverride;Yn(se?.provider&&se?.model?{provider:se.provider,model:se.model}:null),Gr(Y,t).then(()=>{Ne.current===t&&K&&Vs(K,Y,t)})}else ns(null),Yn(null),cs(!1),(!x||x.length===0)&&Pt([])}).catch(()=>{Ne.current===t&&cs(!1)}):cs(!1)},[n,O,K,Pe,at,u.language,o]),s.useEffect(()=>n?void 0:We.on("chat:message",l=>{const c=l.payload,x=c.channel??"";if(!x)return;const w=c.senderType??"agent",z=c.text??c.message??"",H=c.senderId??c.agentId??"",Z=c.senderName??c.agentId??o("page.fallbackAgent"),C=c.metadata,B=c.messageId??c.id??"";if(B&&Ls.current.has(B))return;const Le=w==="human"&&H===(a?.id??""),ve={id:B||`ws_${Date.now()}_${H}`,sender:Le?"user":"agent",text:z,time:new Date().toLocaleTimeString(),agentName:Le?void 0:Z,agentId:Le?void 0:H,replyToId:c.replyToId??void 0,replyToSender:c.replyToSender??void 0,replyToText:c.replyToText??void 0};if(C&&w==="agent"){const re=[];if(C.thinking?.length&&re.push({type:"text",content:"",thinking:C.thinking.join(`
|
|
33
|
+
|
|
34
|
+
`)}),C.toolCalls?.length)for(let Re=0;Re<C.toolCalls.length;Re++){const ue=C.toolCalls[Re];re.push({type:"tool",key:`${ue.tool}_${Re}`,tool:ue.tool,status:ue.status==="error"?"error":"done",args:ue.arguments,result:ue.result,durationMs:ue.durationMs})}re.length>0&&(re.push({type:"text",content:z}),ve.segments=re)}let he;if(x.startsWith("notes:"))he=`dm:${x.slice(6)}`;else if(x.startsWith("dm:")){const re=x.slice(3).split(":");he=`dm:${re.find(ue=>ue!==(a?.id??""))??re[0]??""}`}else he=`ch:${x}`;_e(he,re=>[...re,ve]),he===Ne.current&&!us.current&&(Ts.current+=1,Ws(Ts.current),ms(!0)),w==="agent"&&he===`ch:${Pe}`&&wn(re=>{const Re=re.filter(ue=>ue.id!==H);return Re.length===0&&Wt.current&&(clearTimeout(Wt.current),Wt.current=null),Re})}),[n,_e,a?.id,Pe]),s.useEffect(()=>n?void 0:We.on("chat:agent_no_response",l=>{const c=l.payload,x=c.channel??"",w=c.agentId??"";x&&w&&`ch:${Pe}`==`ch:${x}`&&wn(z=>{const H=z.filter(Z=>Z.id!==w);return H.length===0&&Wt.current&&(clearTimeout(Wt.current),Wt.current=null),H})}),[n,Pe]),s.useEffect(()=>n?void 0:We.on("chat:proactive_message",l=>{const c=l.payload,x=c.targetUserId;if(x&&x!==a?.id)return;const w=c.agentId??"",z=c.agentName??o("page.fallbackAgent"),H=c.message??"",Z=c.sessionId??"",C=c.messageId??"",B=c.metadata??{};if(!w||!H||H==="[cancelled]"||H==="[Stream cancelled]")return;const Le=B.role==="user",ve=!Le&&(!!B.activityLog||H.startsWith("[ACTIVITY:")),{cleaned:he,priority:re}=fl(H),Re=!Le&&(!!B.notifyUser||he!==H),ue=hr("direct",w,"","");if(Z&&Ne.current===ue){const me=Ie;if(me&&me!==Ue&&me!==Z)return}const Se=!!B.isMainSession&&!Le,Te=Z||Ie,Y=typeof B.userText=="string"?B.userText:"",xe=typeof B.userMessageId=="string"?B.userMessageId:"",se=typeof B.createdAt=="string"&&B.createdAt||(typeof l.timestamp=="string"?l.timestamp:void 0)||new Date().toISOString(),de=(()=>{try{return new Date(se).toLocaleTimeString()}catch{return new Date().toLocaleTimeString()}})(),le={id:C||`proactive_${Date.now()}`,sender:Le?"user":"agent",text:he,time:de,rawCreatedAt:se,...Le?{}:{agentName:z,agentId:w,...Re?{isNotification:!0,notifyPriority:B.priority??re}:{},...ve?{isActivityLog:!0,activityType:B.activityType,outcome:B.outcome,mailboxItemId:B.mailboxItemId,taskId:B.taskId,requirementId:B.requirementId}:{},...!ve&&B.taskId?{taskId:B.taskId}:{},...!ve&&B.requirementId?{requirementId:B.requirementId}:{}}};Re&&le.id&&$r(me=>me.includes(le.id)?me:[...me,le.id]),_e(ue,me=>{if(me.some(Ge=>Ge.id===le.id))return me;let Me=me;if(!Le&&Y&&(Me.some(rt=>xe&&rt.id===xe||rt.sender==="user"&&rt.text===Y)||(Me=[...Me,{id:xe||`feishu_user_${le.id}`,sender:"user",text:Y,time:new Date().toLocaleTimeString()}])),Se)for(let Ge=Me.length-1;Ge>=0;Ge--){const rt=Me[Ge];if(rt.sender==="agent"&&rt.agentId===w&&rt.isStopped){const Mt=[...Me];return Mt[Ge]={...le,id:rt.id},Mt}}return gl(Me,le)},Te||void 0)}),[n,_e,o,Ie]),Jn.find(t=>t.id===lo),s.useEffect(()=>{co(null)},[K]);const ko=t=>Tl(t),No=()=>{const t=O==="direct"?K:null;t&&T.agents.cancelProcessing(t).catch(()=>{}),jt.current?.abort(),jt.current=null,Ss.current?.abort(),Ss.current=null;const l=Ne.current;Ve(l),zt.delete(Ie??l),Ie&&bt(l,Ie),G(l),ut(!1),Kt([])},[qs,Yr]=s.useState(null),[Wa,Ha]=s.useState(!1),Va=s.useRef(null),Us=async(t,l)=>{const c=!t&&ts.length>0?ts.map(he=>he.content).join(`
|
|
35
|
+
|
|
36
|
+
`)+`
|
|
37
|
+
|
|
38
|
+
`:"",x=(t??c+nt).trim();if(!x&&Dt.length===0||O==="direct"&&!K)return;xs();const w=Date.now(),z=Va.current;if(!l?.isRetry&&!l?.isResume&&x&&z&&z.text===x&&w-z.at<1500)return;if(Va.current={text:x,at:w},Lt&&O==="direct"){if(Ie&&Ie!==Ue){const re=Ne.current;if([...pt.get(re)??[]].reverse().find(Se=>Se.sender==="user")?.text===x&&!l?.isRetry&&!l?.isResume)return jt.current?.abort(),jt.current=null,T.agents.cancelProcessing(K).catch(()=>{}),Ve(re),zt.delete(Ie??re),G(re),_e(re,Se=>{const Te=[...Se];return Te.length>0&&Te[Te.length-1].sender==="agent"&&Te.pop(),Te.length>0&&Te[Te.length-1].sender==="user"&&Te[Te.length-1].text===x&&Te.pop(),Te}),ut(!1),Kt([]),await new Promise(Se=>setTimeout(Se,50)),Us(x,{isRetry:!0});jt.current?.abort(),jt.current=null,T.agents.cancelProcessing(K).catch(()=>{}),Ve(re),zt.delete(Ie??re),G(re),_e(re,Se=>{const Te=[...Se];for(let Y=Te.length-1;Y>=0;Y--)if(Te[Y].sender==="agent"&&!Te[Y].isStopped&&!Te[Y].isError){const xe=Te[Y];if(!(xe.text?.trim()||(xe.segments??[]).some(de=>de.type==="text"&&(de.content||de.thinking)||de.type==="tool")))Te.splice(Y,1);else{const de=(xe.segments??[]).map(le=>le.type==="tool"&&le.status==="running"?{...le,status:"stopped"}:le);Te[Y]={...xe,isStopped:!0,segments:de}}break}return Te}),ut(!1),Kt([]),await new Promise(Se=>setTimeout(Se,50))}}else if(Lt&&O!=="direct"){jt.current?.abort(),jt.current=null;const he=Ne.current;Ve(he),zt.delete(he),G(he),_e(he,re=>{const Re=[...re];for(let ue=Re.length-1;ue>=0;ue--)if(Re[ue].sender==="agent"&&!Re[ue].isStopped&&!Re[ue].isError){const Se=Re[ue];if(!(Se.text?.trim()||(Se.segments??[]).some(Y=>Y.type==="text"&&(Y.content||Y.thinking)||Y.type==="tool")))Re.splice(ue,1);else{const Y=(Se.segments??[]).map(xe=>xe.type==="tool"&&xe.status==="running"?{...xe,status:"stopped"}:xe);Re[ue]={...Se,isStopped:!0,segments:Y}}break}return Re}),ut(!1),Kt([]),await new Promise(re=>setTimeout(re,50))}const H=Dt.length>0?Dt.map(he=>he.dataUrl):void 0,Z=Dt.length>0?Dt.map(he=>he.name):void 0,C=hr(O,K,Pe,at),B=ks;t||(Rt(""),Nr([])),Mr([]),In(!1),et(null);const Le=O==="dm";Fe(C);const ve=Ie??C;if(zt.set(ve,[]),Ne.current===C&&!Le&&(ut(!0),Kt([])),O==="dm"){const he=tr(a?.id??"",at),re=`opt_${Date.now()}`,Re={id:re,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};H?.length&&(Re.images=H),B&&(Re.replyToId=B.id,Re.replyToSender=B.sender,Re.replyToText=B.text),_e(C,ue=>[...ue,Re]);try{const ue=await T.channels.sendMessage(he,{text:x,senderName:a?.name??o("page.fallbackYou"),senderId:a?.id,mentions:[],orgId:"default",humanOnly:!0,...H?.length?{images:H}:{}});ue.userMessage&&Zs(ue.userMessage.id),_e(C,Se=>{const Te=Se.filter(xe=>xe.id!==re),Y=[];return ue.userMessage&&Y.push(Ks(ue.userMessage,a?.id)),Y.length>0?[...Te,...Y]:Se})}catch(ue){pr(ue)&&br(),_e(C,Se=>[...Se.filter(Y=>Y.id!==re),{id:`err_${Date.now()}`,sender:"agent",text:o("page.errorWithMessage",{message:String(ue)}),time:new Date().toLocaleTimeString(),agentName:o("page.systemName"),isError:!0}])}Ze(C),Ne.current===C&&ut(!1)}else if(O==="channel"){const he=`opt_${Date.now()}`,re={id:he,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:new Date().toISOString()};B&&(re.replyToId=B.id,re.replyToSender=B.sender,re.replyToText=B.text),_e(C,Se=>[...Se,re]);const Re=ko(x),ue=vt.find(Se=>Se.channelKey===Pe);if(Pe.startsWith("group:")){const Se=[];if(ue?.members){for(const Te of ue.members)if(Te.type==="agent"){const Y=f.find(xe=>xe.id===Te.id);Y&&Se.push({id:Y.id,name:Y.name,avatarUrl:Y.avatarUrl})}}Se.length>0&&(Wt.current&&clearTimeout(Wt.current),wn(Se),Wt.current=setTimeout(()=>wn([]),12e4))}try{const Se=await T.channels.sendMessage(Pe,{text:x,senderName:a?.name??o("page.fallbackYou"),mentions:Re,senderId:a?.id,orgId:"default",replyToId:B?.id});Se.userMessage&&Zs(Se.userMessage.id),Se.agentMessage&&Zs(Se.agentMessage.id),_e(C,Te=>{const Y=Te.filter(se=>se.id!==he),xe=[];return Se.userMessage&&xe.push(Ks(Se.userMessage,a?.id)),Se.agentMessage&&xe.push(Ks(Se.agentMessage,a?.id)),xe.length>0?[...Y,...xe]:Te})}catch(Se){pr(Se)&&br();const Te=yr(Se,o)||o("page.errorWithMessage",{message:String(Se)});_e(C,Y=>[...Y,{id:`err_${Date.now()}`,sender:"agent",text:Te,time:new Date().toLocaleTimeString(),agentName:o("page.systemName"),isError:!0}]),Wt.current&&(clearTimeout(Wt.current),Wt.current=null),wn([])}Ze(C),Ne.current===C&&ut(!1)}else{q(C);const he=`${Date.now().toString(36)}_${Math.random().toString(36).slice(2,8)}`,re=`a_${he}`,Re=`u_${he}`;let ue=l?.sessionIdOverride??(Ie===Ue?null:Ie);if(l?.isResume){const D=new Date().toISOString();_e(C,pe=>[...pe,{id:re,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:D,segments:[]}],ue)}else{const D=new Date().toISOString(),pe={id:Re,sender:"user",text:x,time:new Date().toLocaleTimeString(),rawCreatedAt:D};H?.length&&(pe.images=H),B&&(pe.replyToId=B.id,pe.replyToSender=B.sender,pe.replyToText=B.text),_e(C,ee=>[...ee,pe,{id:re,sender:"agent",text:"",time:new Date().toLocaleTimeString(),rawCreatedAt:D,segments:[]}],ue)}let Se=!1;const Te=D=>{Ns.current=Date.now(),ls(C,pe=>{const ee=[...pe],W=ee.findIndex(gs=>gs.id===re);if(W<0)return pe;const X=ee[W].segments??[],ae=X[X.length-1],we=ae?.type==="text"?ae.thinking??"":"";let Ye="",je="",Ae=D;for(;Ae.length>0;)if(Se){const gs=Ae.indexOf("</think>");gs>=0?(Ye+=Ae.slice(0,gs),Ae=Ae.slice(gs+8),Se=!1):(Ye+=Ae,Ae="")}else{const gs=Ae.indexOf("<think>");gs>=0?(je+=Ae.slice(0,gs),Ae=Ae.slice(gs+7),Se=!0):(je+=Ae,Ae="")}const st=we+Ye||void 0,Qo=ae?.type==="text"?[...X.slice(0,-1),{type:"text",content:ae.content+je,thinking:st,createdAt:ae.createdAt}]:[...X,{type:"text",content:je,thinking:st,createdAt:new Date().toISOString()}];return ee[W]={...ee[W],text:ee[W].text+je,segments:Qo},ee},ue)},Y=D=>{if(Ns.current=Date.now(),D.type==="session_start"&&D.sessionId){const pe=ue;ue=D.sessionId,pe&&pe!==D.sessionId&&bt(C,pe),it(C,D.sessionId),Kn&&T.sessions.setModelOverride(D.sessionId,Kn).catch(()=>{}),D.userMessageId&&!l?.isResume&&_e(C,W=>W.map(X=>X.id===Re?{...X,id:D.userMessageId}:X),D.sessionId);const ee=pt.get(C);if(ee&&ee.length>0&&Rs.set(D.sessionId,ee),Ne.current===C){const W=Ie;(!W||W===Ue||W===D.sessionId)&&(ns(D.sessionId),At.set(C,D.sessionId),K&&Xn(K,D.sessionId),Pt(X=>X.some(ae=>ae.id===Ue)?X.map(ae=>ae.id===Ue?{...ae,id:D.sessionId}:ae):X.some(ae=>ae.id===D.sessionId)?X:[...X,{id:D.sessionId,agentId:K??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}]))}return}_e(C,pe=>{const ee=[...pe],W=ee.findIndex(ae=>ae.id===re);if(W<0)return pe;const X=[...ee[W].committedSegments??[]];return D.type==="thinking_commit"?X.push({type:"text",content:"",thinking:D.content,createdAt:D.createdAt}):X.push({type:"text",content:D.content,createdAt:D.createdAt}),ee[W]={...ee[W],committedSegments:X},ee},ue)},xe=D=>{Ns.current=Date.now(),D.phase!=="heartbeat"&&((D.phase==="start"||D.phase==="end")&&Ds(C,{...D,phase:D.phase,ts:Date.now()},ue),D.phase==="start"?_e(C,pe=>{const ee=[...pe],W=ee.findIndex(Ae=>Ae.id===re);if(W<0)return pe;const X=[...ee[W].segments??[]];let ae=!1;if(D.arguments)for(let Ae=X.length-1;Ae>=0;Ae--){const st=X[Ae];if(st.type==="tool"&&st.tool===D.tool&&st.status==="running"){X[Ae]={...st,args:D.arguments},ae=!0;break}}const we=`${D.tool}_${Date.now()}`,Ye=new Date().toISOString();ae||X.push({type:"tool",key:we,tool:D.tool,status:"running",args:D.arguments,createdAt:Ye});const je=[...ee[W].committedSegments??[]];return D.arguments!==void 0&&je.push({type:"tool",key:we,tool:D.tool,status:"running",args:D.arguments,createdAt:Ye}),ee[W]={...ee[W],segments:X,committedSegments:je},ee},ue):D.phase==="output"?ls(C,pe=>{const ee=[...pe],W=ee.findIndex(ae=>ae.id===re);if(W<0)return pe;const X=[...ee[W].segments??[]];for(let ae=X.length-1;ae>=0;ae--){const we=X[ae];if(we.type==="tool"&&we.tool===D.tool&&we.status==="running"){X[ae]={...we,liveOutput:Cl(we.liveOutput,D.output??"")};break}}return ee[W]={...ee[W],segments:X},ee},ue):D.phase==="subagent_progress"&&D.subagentEvent?ls(C,pe=>{const ee=[...pe],W=ee.findIndex(Ye=>Ye.id===re);if(W<0)return pe;const X=Ye=>{const je=[...Ye];for(let Ae=je.length-1;Ae>=0;Ae--){const st=je[Ae];if(st.type==="tool"&&(st.tool==="spawn_subagent"||st.tool==="spawn_subagents")&&st.status==="running"){je[Ae]={...st,subagentLogs:ni(st.subagentLogs,D.subagentEvent)};break}}return je},ae=X(ee[W].segments??[]),we=X(ee[W].committedSegments??[]);return ee[W]={...ee[W],segments:ae,committedSegments:we},ee},ue):_e(C,pe=>{const ee=[...pe],W=ee.findIndex(je=>je.id===re);if(W<0)return pe;const X=new Date().toISOString(),ae=[...ee[W].segments??[]];let we;for(let je=ae.length-1;je>=0;je--){const Ae=ae[je];if(Ae.type==="tool"&&Ae.tool===D.tool&&Ae.status==="running"){we=Ae.subagentLogs,ae[je]={...Ae,status:D.success===!1?"error":"done",args:D.arguments,result:D.result,error:D.error,durationMs:D.durationMs,liveOutput:void 0,createdAt:X};break}}const Ye=[...ee[W].committedSegments??[]];for(let je=Ye.length-1;je>=0;je--){const Ae=Ye[je];if(Ae.type==="tool"&&Ae.tool===D.tool&&Ae.status==="running"){Ye[je]={...Ae,status:D.success===!1?"error":"done",args:D.arguments,result:D.result,error:D.error,durationMs:D.durationMs,liveOutput:void 0,createdAt:X,subagentLogs:we??Ae.subagentLogs};break}}return ee[W]={...ee[W],segments:ae,committedSegments:Ye},ee},ue))},se=new AbortController;jt.current=se;const de=l?.sessionIdOverride??(Ie===Ue?null:Ie),le=de;le&&it(C,le);try{Ns.current=Date.now();const D=await T.agents.messageStream(K,x,Te,xe,se.signal,H,de,l?.isRetry,l?.isResume,Y,Z,B,Kn);if(Ne.current===C){D.merged&&_e(C,ee=>ee.filter(W=>W.id!==re&&W.id!==Re),ue),!D.merged&&D.segments?.length&&_e(C,ee=>{const W=[...ee],X=W.findIndex(je=>je.id===re);if(X<0)return ee;const ae=ri(D.segments,W[X].segments);let we=D.content||W[X].text;we||(we=ae.filter(je=>je.type==="text").map(je=>je.content).join(""));const Ye=!we?.trim()&&!ae.some(je=>je.type==="text"&&(je.content||je.thinking)||je.type==="tool");return W[X]={...W[X],text:we,segments:ae,committedSegments:ae,isStopped:D.cancelled||W[X].isStopped,emptyReply:D.emptyReply||Ye||void 0,isError:D.emptyReply||Ye?!0:W[X].isError},W},ue),!D.merged&&!D.segments?.length&&_e(C,ee=>{const W=[...ee],X=W.findIndex(st=>st.id===re);if(X<0)return ee;const ae=W[X],we=ae.committedSegments??[],je=we.filter(st=>st.type==="text"&&!!st.content).map(st=>st.content).join("")||D.content||ae.text,Ae=!je?.trim()&&we.length===0;return(we.length>0||je||D.cancelled||D.emptyReply||Ae)&&(W[X]={...ae,text:je,segments:we.length>0?we:ae.segments,isStopped:D.cancelled||ae.isStopped,emptyReply:D.emptyReply||Ae||void 0,isError:D.emptyReply||Ae?!0:ae.isError}),W},ue),D.sessionId&&(ns(ee=>!ee||ee===Ue||ee===D.sessionId?D.sessionId:ee),Pt(ee=>ee.some(W=>W.id===Ue)?ee.map(W=>W.id===Ue?{...W,id:D.sessionId}:W):ee.some(W=>W.id===D.sessionId)?ee:[...ee,{id:D.sessionId,agentId:K??"",userId:null,title:"",createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()}])),or(K).then(ee=>{if(Ne.current===C&&(Os(ee),D.sessionId)){const W=ee.find(X=>X.id===D.sessionId);W&&Pt(X=>X.some(we=>we.id===W.id)?X.map(we=>we.id===W.id?W:we):[W,...X.filter(we=>we.id!==Ue)])}});const pe=D.sessionId??(le&&le!==Ue?le:null);if(!se.signal.aborted&&!D.merged&&D.segments===void 0&&O==="direct"&&K&&pe)try{if((await T.sessions.streamStatus(K,pe)).status==="streaming"){_e(C,W=>W.map(X=>X.id===re?{...X,isStreaming:!0,isStopped:!1,segments:(X.segments??[]).map(ae=>ae.type==="tool"&&(ae.status==="stopped"||ae.status==="running")?{...ae,status:"running"}:ae)}:X),pe),Ze(C),jt.current===se&&(jt.current=null),it(C,pe),Vs(K,pe,C);return}}catch{}}}catch(D){const pe=D?.sessionId;pe&&O==="direct"&&Ne.current===C&&(ns(pe),Pt(W=>W.map(X=>X.id===Ue?{...X,id:pe}:X)),or(K).then(W=>{if(Ne.current!==C)return;Os(W);const X=W.find(ae=>ae.id===pe);X&&Pt(ae=>ae.some(Ye=>Ye.id===X.id)?ae.map(Ye=>Ye.id===X.id?X:Ye):[X,...ae])})),pr(D)&&br();const ee=yr(D,o);ee?_e(C,W=>{const X=[...W],ae=X.findIndex(we=>we.id===re);if(ae>=0){const we=X[ae].segments??[];X[ae]={...X[ae],text:ee,isError:!0,segments:[...we,{type:"text",content:ee}]}}return X},ue):_e(C,W=>{const X=[...W],ae=X.findIndex(we=>we.id===re);if(ae>=0){const we=X[ae];if(!(we.text||we.segments&&we.segments.length>0&&we.segments.some(je=>je.type==="text"&&(je.content||je.thinking)||je.type==="tool")))return W.filter(je=>je.id!==re);X[ae]={...we,isStopped:!0}}return X},ue)}_e(C,D=>{const pe=[...D],ee=pe.findIndex(W=>W.id===re);if(ee>=0){const W=(pe[ee].segments??[]).map(X=>X.type==="tool"&&X.status==="running"?{...X,status:"stopped"}:X);pe[ee]={...pe[ee],segments:W}}return pe},ue),se.signal.aborted&&_e(C,D=>{const pe=[...D],ee=pe.findIndex(W=>W.id===re);if(ee>=0){const W=pe[ee];if(!(W.text||W.segments&&W.segments.length>0&&W.segments.some(ae=>ae.type==="text"&&(ae.content||ae.thinking)||ae.type==="tool")))return D.filter(ae=>ae.id!==re);pe[ee]={...W,isStopped:!0}}return pe},ue);const Me=(pt.get(C)??[]).find(D=>D.id===re),Ge=Ie&&Ie!==Ue?Ie:null,rt=Me?.text||Me?.segments?.some(D=>D.type==="text"&&D.content||D.type==="tool");Me&&!rt&&O==="direct"&&Ge&&!se.signal.aborted&&await(async(pe,ee)=>{for(let W=0;W<pe;W++){await new Promise(X=>setTimeout(X,ee));try{const ae=(await T.sessions.getMessages(Ge,2)).messages.find(we=>we.role==="assistant");if(ae?.content){const we=oa(ae);_e(C,Ye=>{const je=[...Ye],Ae=je.findIndex(st=>st.id===re);return Ae>=0&&(je[Ae]={...je[Ae],text:we.text,segments:we.segments}),je},ue);return}}catch{}}})(5,3e3);const Mt=Ze(C);ue&&bt(C,ue),G(C),jt.current===se||jt.current===null?(jt.current=null,zt.delete(ue??C),Ne.current===C&&(ut(Mt>0),Mt===0&&Kt([]))):zt.delete(ue??C)}};Ra.current=Us;const[So,qa]=s.useState(null),[cr,Xr]=s.useState(null),Co=s.useMemo(()=>{for(let t=Qe.length-1;t>=0;t--)if(Qe[t]?.sender==="agent"&&!Qe[t]?.isActivityLog)return Qe[t].id;return null},[Qe]),To=s.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),qa(t.id),setTimeout(()=>qa(c=>c===t.id?null:c),2e3)},[]),Qr=s.useCallback((t,l,c)=>{const x=Ne.current,w=pt.get(x)??Qe,z=w.findIndex(Z=>Z.id===t.id);if(z<0)return;const H=l&&z>0&&w[z-1]?.id===l.id;_e(x,Z=>{const C=Z.findIndex(B=>B.id===(H?l.id:t.id));return C>=0?Z.slice(0,C):Z}),Us(c,{isRetry:!0})},[Qe,_e]),Mo=s.useCallback(t=>{const l=Ne.current,c=pt.get(l)??Qe,x=c.findIndex(Z=>Z.id===t.id);if(x<0)return;let w=null;for(let Z=x-1;Z>=0;Z--)if(c[Z]?.sender==="user"){w=c[Z];break}const z=w?.text??"";if(!z)return;if(x<c.length-1){const Z=c.length-1-x;Xr({retryMsg:t,userMsg:w,retryText:z,followCount:Z});return}Qr(t,w,z)},[Qe,Qr]),Io=s.useCallback(t=>{const l=Ne.current;(pt.get(l)??Qe).findIndex(w=>w.id===t.id)<0||(_e(l,w=>{const z=[...w],H=z.findIndex(B=>B.id===t.id);if(H<0)return w;const Z=z[H],C=[...Z.segments??[]];for(;C.length>0;){const B=C[C.length-1];if(B.type==="tool"&&(B.status==="stopped"||B.status==="running"))C.pop();else if(B.type==="text"&&!B.content)C.pop();else break}return z[H]={...Z,segments:C,isStopped:!1,isError:!1},z}),Us("[Continue from where you left off. Do not repeat content already generated.]",{isResume:!0}))},[Qe,_e]),Eo=s.useCallback(t=>{const l=t.sender==="user"?a?.name??o("page.fallbackYou"):t.agentName??o("page.fallbackAgent");if(et({id:t.id,sender:l,text:t.text}),O==="channel"&&t.sender==="agent"&&t.agentName){const c=`@${t.agentName} `;Rt(x=>x.startsWith(c)?x:c+x)}ds.current?.focus()},[a?.name,O,o]),Ao=async t=>{if(!qs||!K||O!=="direct")return;const l=Ie;if(!(!l||l===Ue)){Ha(!0);try{const c=await T.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};Yr(null),Os(H=>[w,...H.filter(Z=>Z.id!==w.id)]),Pt(H=>H.some(Z=>Z.id===w.id)?H:[...H,w]),ns(w.id);const z=hr("direct",K,Pe,at);At.set(z,w.id),Xn(K,w.id),ge(z),Tt([]),ss(!1),Xt.current=null,await Us(c.seedPrompt,{sessionIdOverride:c.sessionId})}catch(c){console.error("evolve-from-message failed",c)}finally{Ha(!1)}}},dr=async t=>{const l=Ie;ns(t.id),Bs(!1),ss(!1),Xt.current=null,xs(),ms(!1),Ts.current=0,Ws(0);const c=Ne.current,x=mt(c),w=!!x&&(x.has(t.id)||x.has(Ue)),z=De(c)&&w;ut(z),Kt(z?zt.get(t.id)??[]:[]),At.set(c,t.id),K&&Xn(K,t.id),l&&l!==Ue&&Yt(c,l),ct(c,t.id),Pt(Z=>Z.some(C=>C.id===t.id)?Z:[...Z,t]),K&&to(K,t.id),await Gr(t.id,c);const H=t.metadata?.modelOverride;Yn(H?.provider&&H?.model?{provider:H.provider,model:H.model}:null),K&&!z&&Vs(K,t.id,c)},Po=t=>{if(Pt(l=>l.filter(c=>c.id!==t)),K&&t!==Ue&&eo(K,t),Ie===t){const l=Sn.filter(c=>c.id!==t);l.length>0?dr(l[l.length-1]):Zr()}},Ua=s.useCallback(async t=>{if(t.length<2){Cs([]);return}Ia(!0);try{const l=O==="channel"?"channel":O==="direct"?"direct":"all",c=O==="channel"?Pe:void 0,{results:x}=await T.messages.search(t,{scope:l,channel:c,limit:30});Cs(x)}catch{Cs([])}Ia(!1)},[O,Pe]),_o=s.useCallback(t=>{en(t),zr.current&&clearTimeout(zr.current),zr.current=setTimeout(()=>Ua(t),300)},[Ua]),Lo=s.useCallback(t=>{Mn(!1),en(""),Cs([]),t.source==="channel"&&t.channel?(Oe("channel"),It(t.channel)):t.source==="direct"&&t.agentId&&(Oe("direct"),dt(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)},[]),Zr=()=>{ns(Ue);const t=Ne.current;ge(t),Tt([]),ss(!1),Xt.current=null,Bs(!1),Pt(l=>{const c=l.filter(x=>x.id!==Ue);return[{id:Ue,agentId:K??"",userId:null,title:o("page.newChat"),createdAt:new Date().toISOString(),lastMessageAt:new Date().toISOString()},...c]})},Ro=t=>{Rt(t);const l=ds.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 H=c.slice(x+1);if(!H.includes(" ")&&!H.includes(`
|
|
40
|
+
`)){fo(),In(!0),uo(H.toLowerCase()),tn(0);return}}}In(!1)},ur=(t,l,c)=>{const x=ds.current?.selectionStart??nt.length,z=nt.slice(0,x).lastIndexOf("@"),H=nt.slice(x),Z=l&&c?`@[${t}](${l}:${c})`:t.includes(" ")?`@[${t}]`:`@${t}`,C=nt.slice(0,z)+Z+" "+H;Rt(C),In(!1),tn(0);const B=z+Z.length+1;requestAnimationFrame(()=>{ds.current?.setSelectionRange(B,B)})},Do=10*1024*1024,Ga=5,$o=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=s.useCallback(t=>t.type.startsWith("image/")||$o.has(t.type),[]),Jr=t=>t.dataUrl.startsWith("data:image/"),Oo=(t,l)=>{if(Jr({dataUrl:l}))return null;const c=t.split(".").pop()?.toLowerCase()??"";return{pdf:"📄",docx:"📝",doc:"📝",xlsx:"📊",xls:"📊",pptx:"📎",csv:"📊",json:"🔧",xml:"🔧",html:"🌐",epub:"📚"}[c]??"📁"},Ln=s.useCallback(t=>{const l=Array.from(t).filter(ln);if(l.length!==0)for(const c of l){if(c.size>Do)continue;const x=new FileReader;x.onload=()=>{const w=x.result;Mr(z=>z.length>=Ga||z.some(H=>H.dataUrl===w)?z:[...z,{id:`img_${Date.now()}_${Math.random().toString(36).slice(2,6)}`,dataUrl:w,name:c.name}])},x.readAsDataURL(c)}},[ln]),Fo=s.useCallback(t=>{Mr(l=>l.filter(c=>c.id!==t))},[]),Bo=s.useCallback(t=>{const l=t.clipboardData?.files;if(l&&l.length>0){const c=Array.from(l).filter(ln);c.length>0&&(t.preventDefault(),Ln(c))}},[Ln,ln]),zo=s.useCallback(t=>{t.preventDefault();const l=t.dataTransfer?.files;l&&l.length>0&&Ln(Array.from(l).filter(ln))},[Ln,ln]),Wo=s.useCallback(t=>{t.preventDefault()},[]),tt=f.find(t=>t.id===K),ea=a?.name??o("page.fallbackYou"),Ka=xt[xt.length-1],Ho=Lt&&Ka?.sender==="agent",Vo=Sr&&Ka?.sender==="agent",Ya=s.useMemo(()=>{if(O!=="channel")return null;if(Pe.startsWith("group:custom:")){const l=vt.find(c=>c.channelKey===Pe);return l?.members?new Set(l.members.filter(c=>c.type==="agent").map(c=>c.id)):null}if(!ot)return null;const t=rs.find(l=>l.id===ot);return t?new Set(t.members.filter(l=>l.type==="agent").map(l=>l.id)):null},[O,Pe,ot,rs,vt]),Xa=f.filter(t=>Ya?Ya.has(t.id):!0).filter(t=>t.name.toLowerCase().includes(_a)),Qa=mo.filter(t=>t.name.toLowerCase().includes(_a)),qo={workflow:"⚙️",project:"📁",requirement:"📋",task:"✅",deliverable:"📦"},Gs=s.useMemo(()=>[...Xa.map(t=>({kind:"agent",agent:t})),...Qa.map(t=>({kind:"entity",entity:t}))],[Xa,Qa]),ta=k.find(t=>t.id===at),sa=at===a?.id||!at,Vt=vt.find(t=>t.channelKey===Pe);s.useEffect(()=>{if(n||!Pe.startsWith("group:custom:"))return;const t=vt.find(l=>l.channelKey===Pe);!t||t.members||T.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(()=>{})},[n,Pe,vt]);const na=s.useCallback(async()=>{if(n||O!=="direct"||!K){_r([]);return}try{ai("/approvals");const{approvals:t}=await T.approvals.list("pending");_r(t.filter(l=>l.status==="pending"&&Array.isArray(l.questions)&&l.questions.length>0&&(l.details?.agentId??l.agentId)===K))}catch{}},[n,O,K]),ra=s.useCallback(async()=>{if(n||O!=="direct"||!K||!Ie||Ie===Ue){Rr([]);return}try{ai("/notifications");const{notifications:t}=await T.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&&Nc(c)===Ie).sort((c,x)=>new Date(x.createdAt).getTime()-new Date(c.createdAt).getTime()).slice(0,5);Rr(l),$r(l.map(c=>c.metadata?.messageId).filter(c=>typeof c=="string"&&c.length>0))}catch{}},[n,O,K,Ie,a?.id]);s.useEffect(()=>{na(),ra();let t=null;const l=()=>{t||(t=setTimeout(()=>{t=null,na(),ra()},400))},c=We.on("approval:requested",l),x=We.on("notification",l),w=()=>l();return window.addEventListener("markus:notifications-changed",w),()=>{t&&clearTimeout(t),c(),x(),window.removeEventListener("markus:notifications-changed",w)}},[na,ra]);const Uo=s.useCallback(async(t,l)=>{ka(t);try{await T.approvals.respond(t,l.approved,a?.id,l.comment,l.selectedOption,l.answers),_r(c=>c.filter(x=>x.id!==t)),Lr(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}ka(null)},[a?.id]),Go=s.useCallback(async t=>{Na(t);try{const l=Qn.find(x=>x.id===t)??Js,c=typeof l?.metadata?.messageId=="string"?l.metadata.messageId:null;await T.notifications.markRead(t),Rr(x=>x.filter(w=>w.id!==t)),c&&$r(x=>x.filter(w=>w!==c)),Dr(null),window.dispatchEvent(new CustomEvent("markus:notifications-changed"))}catch{}Na(null)},[Qn,Js]),Za=O==="channel"?Vt?.name??Pe:O==="direct"?tt?.name??o("page.selectAgent"):O==="dm"?sa?o("chat.myNotes"):ta?.name??o("page.directMessage"):o("page.chatTitle"),Ko=s.useMemo(()=>Math.floor(Math.random()*5),[K,Ie]),Ja=K?o(`page.placeholder.directOptions.${Ko}`):"",Rn=O==="direct"&&!!tt&&tt.status==="offline",Yo=O==="channel"?Vt?o("page.placeholder.channel",{name:Vt.name}):o("page.placeholder.channelWithMention",{name:Pe}):O==="dm"?sa?o("page.placeholder.dmSelf"):o("page.placeholder.dmOther",{name:ta?.name??""}):o(Rn?"page.placeholder.agentOffline":K?"page.placeholder.direct":"page.placeholder.noAgent"),Xo=p&&h==="chat",Dn=N==="chat"&&xt.length===0&&!Lt&&!ja,qt=N==="chat"&&xt.length>0;Er.current=qt;const aa=!!(nt.trim()||Dt.length>0);return e.jsxs("div",{ref:oe,className:"flex-1 overflow-hidden flex relative",children:[!b&&e.jsx(Gl,{authUser:a,agents:f,teams:rs,humans:k,tasks:Jn,externalAgents:io,groupChats:vt,chatMode:O,selectedAgent:K,activeChannel:Pe,activeDmUserId:at,previewMode:n,onSelectAgent:t=>{Oe("direct"),dt(t),L("chat"),yt(!1),p&&V()},onSelectChannel:t=>{Oe("channel"),It(t),L("chat"),yt(!1),p&&V()},onSelectDm:t=>{Oe("dm"),_s(t),L("chat"),yt(!1),p&&V()},onSelectTeam:t=>{const l=vt.find(x=>x.type==="team"&&x.teamId===t),c=l?.channelKey??`group:${t}`;p?ie(t):(Oe("channel"),It(c),L("chat"),yt(!1),!Qt&&!qe&&Nt(!0),l||(nn(),$t()))},selectedTeamId:ot??(O==="direct"&&tt?.teamId?tt.teamId:null),onRefreshTeams:$t,onRefreshAgents:Ht,onRefreshHumans:_n,onRefreshGroupChats:nn,onViewProfile:Ct,onManageGroupMembers:t=>{Oe("channel"),It(t),L("chat"),yt(!0),p&&V()},unreadByAgent:nr,unreadByChannel:sr,width:p?void 0:ke.width,onResizeStart:p?void 0:ke.onResizeStart,hidden:p&&h!=="roster"||!p&&Be,onCollapse:()=>ce(!0),initialLoading:$}),p&&h==="team"&&E&&(()=>{const t=rs.find(x=>x.id===E);if(!t)return null;const l=f.filter(x=>x.teamId===E),c=vt.find(x=>x.type==="team"&&x.teamId===E);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=gt.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:()=>{Oe("channel"),It(c.channelKey),L("chat"),V()},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,z=x.status==="offline";return e.jsxs("button",{onClick:()=>{Oe("direct"),dt(x.id),L("chat"),V()},className:`w-full flex items-center gap-2.5 px-2.5 py-2.5 rounded-xl hover:bg-surface-overlay transition-colors ${z?"opacity-50":""}`,children:[e.jsx(wt,{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,z&&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)})]})]})]})})(),!b&&Qt&&!qe&&!p&&!Be&&(()=>{const t=ot??(O==="direct"?tt?.teamId:void 0);if(!t)return null;const l=rs.find(x=>x.id===t);if(!l)return null;const c=vt.find(x=>x.type==="team"&&x.teamId===t);return e.jsx(hi,{team:l,agents:f,humans:k,authUser:a,groupChat:c,chatMode:O,selectedAgent:K,activeChannel:Pe,teams:rs,onSelectAgent:x=>{Oe("direct"),dt(x),L("chat"),yt(!1)},onSelectChannel:x=>{Oe("channel"),It(x),L("chat"),yt(!1)},onSelectDm:x=>{Oe("dm"),_s(x),L("chat"),yt(!1)},onBack:()=>Nt(!1),onViewProfile:Ct,onRefreshAgents:Ht,onRefreshTeams:$t,unreadByAgent:nr,width:ht.width,onResizeStart:ht.onResizeStart})})(),!b&&He&&!p&&!Be&&(()=>{const t=ot??(O==="direct"?tt?.teamId:void 0);if(!t)return null;const l=rs.find(x=>x.id===t);if(!l)return null;const c=vt.find(x=>x.type==="team"&&x.teamId===t);return e.jsxs("div",{"data-l2-floating":!0,className:"absolute z-30 inset-0",style:{left:ke.width+6},children:[e.jsx("div",{className:"absolute inset-0 bg-black/20",onClick:()=>St(!1)}),e.jsx("div",{className:"relative h-full",style:{width:ht.width+8},children:e.jsx(hi,{team:l,agents:f,humans:k,authUser:a,groupChat:c,chatMode:O,selectedAgent:K,activeChannel:Pe,teams:rs,onSelectAgent:x=>{Oe("direct"),dt(x),L("chat"),yt(!1),St(!1)},onSelectChannel:x=>{Oe("channel"),It(x),L("chat"),yt(!1),St(!1)},onSelectDm:x=>{Oe("dm"),_s(x),L("chat"),yt(!1),St(!1)},onBack:()=>St(!1),onViewProfile:x=>{Ct(x),St(!1)},onRefreshAgents:Ht,onRefreshTeams:$t,unreadByAgent:nr,width:ht.width})})]})})(),!b&&(!p||Xo)&&e.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col ${p||J?"min-w-0":"min-w-[400px]"}`,children:[e.jsxs("div",{className:"shrink-0 relative pb-2",children:[p?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=M.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:Za}),O==="direct"&&tt&&e.jsx(Bi,{agent:tt,tasks:Jn,onViewProfile:Ct,streamActive:ba})]}),e.jsxs("div",{className:"flex items-center px-3 h-9 gap-1 border-t border-border-default/40",children:[e.jsx("button",{onClick:()=>{hs(N)?history.back():L("chat")},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${N==="chat"?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:o("page.chatTitle")}),e.jsx("button",{onClick:()=>{hs(N)||ws()},className:`px-2.5 py-1 text-xs font-medium rounded-md transition-colors ${hs(N)?"bg-brand-500/15 text-brand-500":"text-fg-tertiary"}`,children:o(O==="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"})})}),O==="channel"&&Vt?.type==="custom"&&e.jsxs("button",{onClick:()=>yt(!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"})]}),Vt.members?.length??Vt.memberCount??0]}),O==="direct"&&!hs(N)&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Zr,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=ot?rs.find(B=>B.id===ot):void 0,l=O==="direct"&&K?Sc:O==="channel"&&ot?Cc:["chat"],c=async()=>{const B=Vn.trim();if(!B){Ut(!1);return}try{O==="direct"&&K?(await T.agents.updateConfig(K,{name:B}),Ht()):O==="channel"&&ot&&(await T.teams.update(ot,{name:B}),$t())}catch{}Ut(!1)},x=async()=>{try{O==="direct"&&K?(await T.agents.updateConfig(K,{roleDescription:es}),Ht()):O==="channel"&&ot&&(await T.teams.update(ot,{description:es}),$t())}catch{}yn(!1)},w=O==="direct"?tt?.name:O==="channel"?t?.name??Vt?.name:ta?.name??"",z=O==="direct"?tt?.role||"":O==="channel"&&t?.description||"",H=O==="direct"?tt?.avatarUrl:void 0,Z=w||"U",C=O==="direct"&&K||O==="channel"&&ot;return e.jsxs("div",{className:"flex flex-col",children:[e.jsxs("div",{"data-electron-drag":!0,className:"flex items-center px-4 h-14 gap-2.5",children:[Be&&!p&&e.jsx("button",{onClick:()=>ce(!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"})]})}),(!Qt||qe)&&(O==="channel"&&ot||O==="direct"&&tt?.teamId)&&e.jsx("button",{onClick:mn,className:`w-8 h-8 flex items-center justify-center rounded-lg transition-colors shrink-0 ${He?"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"})]})}),C&&e.jsx("div",{"data-no-drag":!0,className:"shrink-0",children:O==="channel"&&ot?e.jsx("div",{className:"w-9 h-9 rounded-xl bg-brand-600 text-white flex items-center justify-center text-sm font-bold",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(wt,{name:Z,avatarUrl:H,size:36,className:"rounded-xl shrink-0"})}),C?e.jsxs("div",{"data-no-drag":!0,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[Ot?e.jsx("input",{ref:Qs,value:Vn,onChange:B=>bn(B.target.value),onBlur:c,onKeyDown:B=>{B.key==="Enter"&&c(),B.key==="Escape"&&Ut(!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??""),Ut(!0)},title:"Click to edit name",children:w}),O==="direct"&&tt&&e.jsx(Bi,{agent:tt,tasks:Jn,onViewProfile:Ct,streamActive:ba})]}),(O==="direct"||O==="channel"&&ot)&&(Xs?e.jsx("input",{ref:Ft,value:es,onChange:B=>As(B.target.value),onBlur:x,onKeyDown:B=>{B.key==="Enter"&&x(),B.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:()=>{As(z),yn(!0)},title:"Click to edit description",children:z||"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:Za}),O==="dm"&&e.jsx("span",{className:"text-xs text-fg-tertiary",children:sa?o("page.privateNotepad"):""})]}),e.jsxs("div",{"data-no-drag":!0,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"})})}),O==="channel"&&Vt?.type==="custom"&&e.jsxs("button",{onClick:()=>yt(!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"})]}),Vt.members?.length??Vt.memberCount??0]}),O==="direct"&&tt&&N==="chat"&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("button",{onClick:Zr,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"})})})]}),!p&&te&&e.jsx("button",{onClick:()=>te.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(B=>e.jsxs("button",{onClick:()=>L(B),className:`px-3 py-1.5 text-xs font-medium rounded-md transition-colors whitespace-nowrap flex items-center gap-1 ${N===B?"bg-brand-500/15 text-brand-500":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,children:[e.jsx("span",{children:Mc(B)}),Tc(B,o)]},B))})]})})(),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:Ta,onChange:t=>_o(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:"✕"})]}),Ma&&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")]}),!Ma&&Ta.length>=2&&Br.length===0&&e.jsx("div",{className:"text-xs text-fg-tertiary py-1",children:o("page.noSearchResults")}),Br.length>0&&e.jsx("div",{className:"max-h-60 overflow-y-auto space-y-0.5",children:Br.map(t=>e.jsxs("button",{onClick:()=>Lo(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))})]}),O==="direct"&&K&&N==="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===Ie?"text-brand-500 bg-brand-500/10":"text-fg-tertiary hover:text-fg-secondary hover:bg-surface-elevated/50"}`,onClick:()=>{if(t.id===Ue){ns(Ue);const l=Ne.current;ge(l),Tt([])}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===Ue?o("page.newChat"):t.isMain?o("page.sessionMain"):t.title||o("page.sessionConversation")}),!t.isMain&&e.jsx("button",{onClick:l=>{l.stopPropagation(),Po(t.id)},className:"opacity-0 group-hover:opacity-100 text-fg-tertiary hover:text-fg-secondary transition-opacity shrink-0",children:"✕"})]},t.id))}),O==="direct"&&N==="chat"&&(Sn.find(t=>t.id===Ie)??Pr.find(t=>t.id===Ie))?.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")}),O==="channel"&&Vt?.type==="custom"&&Tn&&(()=>{const t=Vt,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 k)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:()=>yt(!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(wt,{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 T.groupChats.removeMember(t.id,x.id),Cn(w=>w.map(z=>z.id===t.id?{...z,members:(z.members??[]).filter(H=>H.id!==x.id),memberCount:(z.memberCount??1)-1}:z))}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 z=c.find(H=>H.id===w);if(z)try{await T.groupChats.addMember(t.id,z.id,z.type,z.name),Cn(H=>H.map(Z=>Z.id===t.id?{...Z,members:[...Z.members??[],{id:z.id,name:z.name,type:z.type}],memberCount:(Z.memberCount??0)+1}:Z))}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))]})})]})})(),O==="direct"&&K&&Fs&&e.jsxs("div",{ref:Or,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:[Pr.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=[],z=[],H=[],Z=[],C=[];for(const B of Pr){const Le=new Date(B.lastMessageAt).getTime();Le>=l?z.push(B):Le>=c?H.push(B):Le>=x?Z.push(B):C.push(B)}return z.length>0&&w.push({label:o("page.dateToday"),items:z}),H.length>0&&w.push({label:o("page.dateYesterday"),items:H}),Z.length>0&&w.push({label:o("page.datePrevious7Days"),items:Z}),C.length>0&&w.push({label:o("page.dateOlder"),items:C}),w.map(B=>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:B.label}),B.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===Ie?"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))]},B.label))})()]})]})]}),p&&N==="profile"&&O==="direct"&&K&&e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(yi,{agentId:K,onBack:()=>L("chat"),inline:!0,defaultTab:Hn,highlightMailboxId:pn,onSwipeBack:()=>{hs(F.current)?history.back():L("chat")},authUser:a})}),p&&N==="profile"&&O==="channel"&&ot&&e.jsx("div",{className:"flex-1 overflow-y-auto",onTouchStart:p?Bt.onTouchStart:void 0,onTouchEnd:p?Bt.onTouchEnd:void 0,children:e.jsx($i,{teamId:ot,onBack:()=>L("chat"),inline:!0,onSelectAgent:t=>{Oe("direct"),dt(t),L("chat")}})}),!p&&hs(N)&&O==="direct"&&K&&e.jsx("div",{className:"flex-1 overflow-y-auto",children:e.jsx(yi,{agentId:K,onBack:()=>L("chat"),inline:!0,headless:!0,activeTab:N,highlightMailboxId:pn,authUser:a})}),!p&&hs(N)&&O==="channel"&&ot&&e.jsx("div",{className:"flex-1 flex flex-col min-h-0",children:e.jsx($i,{teamId:ot,onBack:()=>L("chat"),inline:!0,headless:!0,activeTab:N,onSelectAgent:t=>{Oe("direct"),dt(t),L("chat")}})}),e.jsxs("div",{className:`flex-1 overflow-hidden flex flex-col relative ${Dn?"justify-center":""} ${N!=="chat"?"hidden":""}`,children:[ja&&xt.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…"})})]}),Tr&&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 ${p?"p-2.5":`p-5 ${U}`}`,onScroll:wo,onTouchStart:p?Bt.onTouchStart:void 0,onTouchEnd:p?Bt.onTouchEnd:void 0,children:[xt.length>0&&e.jsx("div",{style:{height:fs.getTotalSize(),width:"100%",position:"relative"},children:fs.getVirtualItems().map(t=>{const l=t.index,c=xt[l],x=l>0?xt[l-1]:null,w=ii(c.rawCreatedAt),z=x?ii(x.rawCreatedAt):"",H=!!(w&&z&&w!==z),Z=l===xt.length-1,B=Ho&&Z&&Lt||!!c.isStreaming,Le=Vo&&Z||B,ve=O==="channel"||!B||c.isStopped;return e.jsx("div",{"data-index":l,ref:fs.measureElement,style:{position:"absolute",top:0,left:0,width:"100%",transform:`translateY(${t.start}px)`},children:e.jsxs("div",{className:"pb-3",children:[H&&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:hl(c.rawCreatedAt,d)}),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:[O==="channel"?e.jsx("div",{className:"shrink-0 cursor-pointer",onClick:he=>{if(c.sender==="agent"&&c.agentId){const re=he.currentTarget.getBoundingClientRect();os({agentId:c.agentId,top:re.top,left:re.right+8})}},children:e.jsx(wt,{name:c.sender==="user"?ea:c.agentName??o("page.fallbackAgent"),avatarUrl:c.sender==="user"?a?.avatarUrl:f.find(he=>he.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(wt,{name:c.sender==="user"?ea:c.agentName??(O==="direct"?tt?.name??o("page.fallbackAgent"):o("page.fallbackAgent")),avatarUrl:c.sender==="user"?a?.avatarUrl:f.find(he=>he.id===(c.agentId??(O==="direct"?tt?.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"?ea:O==="channel"?c.agentName??o("page.fallbackAgent"):e.jsx(pl,{name:c.agentName??(O==="direct"?tt?.name??o("page.fallbackAgent"):o("page.fallbackAgent")),agentId:c.agentId??(O==="direct"?tt?.id:void 0),agents:f,onViewProfile:Ct})}),e.jsx("span",{className:"text-xs text-fg-tertiary",title:c.rawCreatedAt?new Date(c.rawCreatedAt).toLocaleString():"",children:bl(c.time,c.rawCreatedAt,d)})]}),c.replyToId&&c.replyToSender&&e.jsxs("button",{onClick:()=>{const he=document.getElementById(`msg-${c.replyToId}`);he&&(he.scrollIntoView({behavior:"smooth",block:"center"}),he.classList.add("bg-brand-500/10"),setTimeout(()=>he.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((he,re)=>e.jsx("img",{src:he,alt:"",className:"max-w-[200px] max-h-[150px] rounded-lg object-cover cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>window.open(he,"_blank")},re))}),O==="channel"?li(c.text,f,(he,re)=>{const Re=re.currentTarget.getBoundingClientRect();os({agentId:he.id,top:Re.bottom,left:Re.left})}):c.text&&e.jsx("span",{className:"leading-relaxed",children:li(c.text,f,(he,re)=>{const Re=re.currentTarget.getBoundingClientRect();os({agentId:he.id,top:Re.bottom,left:Re.left})})})]}):c.sender==="agent"&&O==="channel"&&!(c.segments&&c.segments.length>0)?e.jsx(oi,{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:Gt,knownNames:jn})}):e.jsx(oi,{resetKeys:[c.id,c.text,c.segments?.length,B],fallback:e.jsx("div",{className:"whitespace-pre-wrap break-words text-sm text-fg-secondary",children:c.text}),children:e.jsx(yl,{msg:c,isStreaming:B,liveActivities:B?kr:[],onMentionClick:Gt,knownNames:jn})}),c.isNotification&&e.jsx(vl,{priority:c.notifyPriority})]}),ve&&!n&&e.jsx("div",{className:`transition-opacity ${c.isStopped||c.isError||c.emptyReply||p?"opacity-100":"opacity-0 group-hover/msg:opacity-100"}`,children:e.jsx(jl,{msg:c,onCopy:To,onRetry:Mo,onResume:Io,onReply:Eo,onRemember:O==="direct"?Yr:void 0,showRemember:O==="direct",isCopied:So===c.id,isLastAgentMsg:c.id===Co})})]})]})]})},c.id)})}),O==="channel"&&pa.length>0&&e.jsx("div",{className:"flex flex-col gap-1.5 py-2",children:pa.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:()=>{Oe("direct"),dt(t.id),L("chat")},children:[e.jsxs("div",{className:"relative shrink-0",children:[e.jsx(wt,{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:go})]}),vo&&N==="chat"&&e.jsx("div",{className:`absolute ${p?"bottom-4":"bottom-28"} inset-x-0 z-10 pointer-events-none ${p?"px-3":`px-5 ${U}`}`,children:e.jsx("div",{className:`${p?"":"max-w-3xl mx-auto"} flex justify-center`,children:e.jsxs("button",{onClick:()=>{xs(),on("smooth"),ms(!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"})}),$a>0?o("page.newMessages",{count:$a}):o("page.scrollToBottom")]})})}),Is&&(()=>{const t=f.find(l=>l.id===Is.agentId);return t?e.jsx(wl,{agent:t,anchorRect:{top:Is.top,left:Is.left},onClose:()=>os(null),onViewProfile:Ct}):null})(),Dn&&Ja&&e.jsx("div",{className:"text-center mb-4",children:e.jsx("h2",{className:"text-xl font-semibold text-fg-primary",children:Ja})}),O==="direct"&&(wa.length>0||Qn.length>0)&&e.jsx("div",{className:`${p?"px-3":"px-5"} pb-1 shrink-0 ${Dn?"":U}`,children:e.jsxs("div",{className:`${p?"":"max-w-3xl mx-auto"} flex flex-col gap-1.5`,children:[wa.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:()=>Dr(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(kl,{approval:Nn,submitting:no===Nn.id,readOnly:Nn.status!=="pending",onClose:()=>Lr(null),onSubmit:t=>Uo(Nn.id,t)}),Js&&e.jsx(zl,{notification:Js,agentName:tt?.name,acknowledging:ro===Js.id,onClose:()=>Dr(null),onAcknowledge:()=>Go(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;Xr(null),Qr(t.retryMsg,t.userMsg,t.retryText)},onCancel:()=>Xr(null)}),qs&&e.jsx(Nl,{busy:Wa,onConfirm:t=>{Ao(t)},onCancel:()=>{Wa||Yr(null)}}),e.jsx("div",{className:`${p?"px-3 py-2":"px-5 py-3"} relative shrink-0 ${Dn?"":U}`,onDrop:zo,onDragOver:Wo,children:e.jsxs("div",{className:`bg-surface-primary border border-border-default shadow-lg shadow-black/10 ${p?`${qt?"rounded-2xl p-2":"rounded-2xl p-3"}`:`${qt?"rounded-2xl p-2":"rounded-2xl p-3"} max-w-3xl mx-auto`}`,children:[Pa&&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===En&&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===En?"bg-brand-500/15 text-brand-500":"text-fg-secondary hover:bg-surface-overlay"}`,children:[e.jsx(wt,{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===En&&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===En?"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:qo[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}`))]}),ts.length>0&&e.jsx("div",{className:"flex items-center gap-1.5 mb-2 flex-wrap",children:ts.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:()=>Nr(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))}),Dt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 overflow-x-auto pb-1",children:[Dt.map(t=>e.jsxs("div",{className:"relative group/img shrink-0",children:[Jr(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:Oo(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:()=>Fo(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)),Dt.length<Ga&&e.jsx("button",{onClick:()=>Ir.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"})})})]}),Dt.length>0&&Dt.some(t=>Jr(t))&&tt&&tt.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:Ir,type:"file",accept:"image/*,.pdf,.docx,.xlsx,.pptx,.xls,.doc,.csv,.json,.xml,.html,.epub",multiple:!0,className:"hidden",onChange:t=>{t.target.files&&Ln(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:()=>et(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:aa?"flex flex-col gap-2 min-w-0":"flex gap-2 items-end min-w-0",children:[e.jsxs("div",{className:aa?"flex gap-2 items-end min-w-0":"contents",children:[e.jsx("button",{onClick:()=>Ir.current?.click(),disabled:O==="direct"&&(!K||Rn),className:`${qt?"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:qt?"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:ds,value:nt,onChange:t=>{Ro(t.target.value),kn()},onKeyDown:t=>{if(Pa&&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(z=>(z-1+Gs.length)%Gs.length);return}if(c){t.preventDefault(),tn(z=>(z+1)%Gs.length);return}if(x){t.preventDefault();const z=Gs[En];z&&(z.kind==="agent"?ur(z.agent.name):ur(z.entity.name,z.entity.entityType,z.entity.id));return}if(w){t.preventDefault(),In(!1);return}}t.key==="Enter"&&!t.shiftKey&&(t.preventDefault(),Us())},onPaste:Bo,placeholder:Yo,disabled:O==="direct"&&(!K||Rn),rows:qt?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 ${qt?"px-2 py-1.5":"px-4 py-3"}`,style:{minHeight:qt?"36px":"52px",maxHeight:qt?"160px":"120px"}})]}),e.jsxs("div",{className:`flex items-center gap-1.5 shrink-0 ${aa?"justify-end":""}`,children:[O==="direct"&&e.jsx(wc,{value:Kn,disabled:!K||Rn,onSelect:(t,l)=>{Yn(t);const c=Ie&&Ie!==Ue?Ie:null;kc(c,t,l).catch(()=>{}),c&&Os(x=>x.map(w=>w.id===c?{...w,metadata:{...w.metadata??{},modelOverride:t}}:w))}}),Lt&&O!=="dm"?e.jsx("button",{onClick:No,className:`${qt?"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:O==="direct"&&(!K||Rn)||!nt.trim()&&Dt.length===0,className:qt?"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:qt?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")})]})]})]})})]})]}),!p&&J&&be&&e.jsx(tc,{payload:J,onClose:be,width:b?ze:vs,onResizeStart:jr,onAddToChat:Ys,tabs:Ee,activeTabId:$e,onSelectTab:te?.setActiveRightPanelTab,onCloseTab:te?.closeRightPanelTab,onNewTab:()=>{if(!_)return;const t=`eb_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,7)}`;_({kind:"url",url:"about:blank",title:"New Tab",browserId:t})},fullscreen:b,onToggleFullscreen:te?.toggleRightPanelFullscreen,onBrowserMeta:te?.updateRightPanelBrowserTab?(t,l)=>te.updateRightPanelBrowserTab(t,l):void 0})]})}function Bi({agent:r,tasks:a,onViewProfile:n,streamActive:i}){const{t:o}=Xe(["team","common"]),[u,d]=s.useState(!1),m=s.useRef(null),f=s.useRef(null),y=r.status==="working"||!!i,k=r.status==="error",j=y?a.find(P=>P.assignedAgentId===r.id&&P.status==="in_progress"):null,$=r.currentActivity;s.useEffect(()=>{k&&r.lastError&&pr(r.lastError)&&br()},[k,r.lastError]),s.useEffect(()=>{if(!u)return;const P=I=>{m.current&&!m.current.contains(I.target)&&d(!1)};return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[u]),s.useLayoutEffect(()=>{if(!u||!f.current)return;const P=f.current,I=P.getBoundingClientRect(),h=window.innerWidth;I.right>h-8&&(P.style.left="auto",P.style.right="0"),I.left<8&&(P.style.left="0",P.style.right="auto");const E=h-16;I.width>E&&(P.style.width=`${E}px`)},[u]);const v=k?"bg-red-400 animate-pulse":y?"bg-blue-400 animate-pulse":"bg-green-400",p=o(k?"common:status.error":y?"common:status.working":"common:status.idle"),R=$?$.type==="heartbeat"?o("page.activityHeartbeat",{name:$.heartbeatName??$.label}):$.type==="chat"?$.label:$.type==="task"?o("page.activityTask",{label:$.label}):$.label:o("page.processing");return e.jsxs("div",{className:"relative",ref:m,children:[e.jsxs("button",{onClick:()=>d(P=>!P),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":k?"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 ${v}`}),e.jsx("span",{className:`text-xs ${k?"text-red-500":y?"text-blue-500":"text-green-600"}`,children:p}),r.mailboxDepth!=null&&r.mailboxDepth>0&&e.jsx("span",{className:"text-[9px] bg-fg-tertiary/20 text-fg-tertiary rounded-full px-1.5",children:r.mailboxDepth})]}),u&&k&&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:yr(r.lastError,o)||r.lastError||o("page.agentErrorFallback")}),r.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(r.lastErrorAt).toLocaleString()})]}),e.jsx("button",{onClick:()=>{d(!1),n?.(r.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")})]}),u&&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:()=>{d(!1),bs.navigate(gt.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 ${$?.type==="heartbeat"||$?.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:R}),e.jsx("div",{className:"text-[10px] text-fg-tertiary",children:$?.type==="heartbeat"?o("page.activityDescHeartbeat"):$?.type==="chat"?o("page.activityDescChat"):o("page.activityDescFallback")})]})]}),e.jsx("button",{onClick:()=>{d(!1),n?.(r.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{Oc as TeamPage};
|